6 * Contains the functions to generate Printer-friendly pages.
8 * This file is included by the core PF module, and includes all the
9 * functions necessary to generate a PF version of the original page
13 $_print_urls = PRINT_URLS_DEFAULT
;
16 * Generate an HTML version of the printer-friendly page
18 * @see print_controller()
19 * @see _print_get_template()
21 function print_controller_html() {
22 $args = func_get_args();
23 // Remove the print/ prefix
24 $path = implode('/', $args);
25 $cid = isset($_GET['comment']) ?
(int)$_GET['comment'] : NULL
;
27 $print = print_controller($path, $cid, PRINT_HTML_FORMAT
);
28 if ($print !== FALSE
) {
29 $node = $print['node'];
30 include_once(_print_get_template(PRINT_HTML_FORMAT
, $print['type']));
32 $nodepath = drupal_get_normal_path($node->path
);
33 db_query("UPDATE {print_page_counter} SET totalcount = totalcount + 1, timestamp = %d WHERE path = '%s'", time(), $nodepath);
34 // If we affected 0 rows, this is the first time viewing the node.
35 if (!db_affected_rows()) {
36 // We must create a new row to store counters for the new node.
37 db_query("INSERT INTO {print_page_counter} (path, totalcount, timestamp) VALUES ('%s', 1, %d)", $nodepath, time());
43 * Select the print generator function based on the page type
45 * Depending on the type of node, this functions chooses the appropriate
49 * path of the original page
51 * comment ID of the individual comment to be rendered
53 * format of the page being generated
55 * if set to TRUE, outputs only the node's teaser
57 * optional sender's message (used by the send e-mail module)
59 * array with the fields to be used in the template
60 * @see _print_generate_node()
61 * @see _print_generate_path()
62 * @see _print_generate_book()
64 function print_controller($path, $cid = NULL
, $format = PRINT_HTML_FORMAT
, $teaser = FALSE
, $message = NULL
) {
66 // If no path was provided, let's try to generate a page for the referer
70 $path = preg_replace("!^$base_url/!", '', $ref);
75 if (!is_numeric($path)) {
76 // Indirect call with print/alias
77 // If there is a path alias with these arguments, generate a printer-friendly version for it
78 $path = drupal_get_normal_path($path);
79 $ret = preg_match('!^node/(.*)!i', $path, $matches);
84 $parts = explode('/', $path);
85 if (is_numeric($parts[0])) {
86 $print = _print_generate_node($path, $cid, $format, $teaser, $message);
89 $ret = preg_match('!^book/export/html/(.*)!i', $path, $matches);
91 // This is a book PF page link, handle trough the book handling functions
92 $print = _print_generate_book($matches[1], $format, $teaser, $message);
95 // If no content node was found, handle the page printing with the 'printable' engine
96 $print = _print_generate_path($path, $format, $teaser, $message);
104 * Generates a robots meta tag to tell them what they may index
107 * string with the meta robots tag
109 function _print_robots_meta_generator() {
110 $print_robots_noindex = variable_get('print_robots_noindex', PRINT_ROBOTS_NOINDEX_DEFAULT
);
111 $print_robots_nofollow = variable_get('print_robots_nofollow', PRINT_ROBOTS_NOFOLLOW_DEFAULT
);
112 $print_robots_noarchive = variable_get('print_robots_noarchive', PRINT_ROBOTS_NOARCHIVE_DEFAULT
);
113 $robots_meta = array();
115 if (!empty($print_robots_noindex)) {
116 $robots_meta[] = 'noindex';
118 if (!empty($print_robots_nofollow)) {
119 $robots_meta[] = 'nofollow';
121 if (!empty($print_robots_noarchive)) {
122 $robots_meta[] = 'noarchive';
125 if (count($robots_meta) > 0) {
126 $robots_meta = implode(', ', $robots_meta);
127 $robots_meta = "<meta name='robots' content='$robots_meta' />\n";
137 * Post-processor that fills the array for the template with common details
140 * generated node with a printer-friendly node body
142 * optional sender's message (used by the send e-mail module)
144 * id of current comment being generated (NULL when not generating
145 * an individual comment)
147 * array with the fields to be used in the template
149 function _print_var_generator($node, $message = NULL
, $cid = NULL
) {
150 global $base_url, $_print_urls;
152 $path = empty($node->nid
) ?
$node->path
: "node/$node->nid";
154 // print module settings
155 $print_css = variable_get('print_css', PRINT_CSS_DEFAULT
);
156 $print_logo_options = variable_get('print_logo_options', PRINT_LOGO_OPTIONS_DEFAULT
);
157 $print_logo_url = variable_get('print_logo_url', PRINT_LOGO_URL_DEFAULT
);
158 $print_html_sendtoprinter = variable_get('print_html_sendtoprinter', PRINT_HTML_SENDTOPRINTER_DEFAULT
);
159 $print_sourceurl_enabled = variable_get('print_sourceurl_enabled', PRINT_SOURCEURL_ENABLED_DEFAULT
);
160 $print_sourceurl_forcenode = variable_get('print_sourceurl_forcenode', PRINT_SOURCEURL_FORCENODE_DEFAULT
);
161 $print_sourceurl_date = variable_get('print_sourceurl_date', PRINT_SOURCEURL_DATE_DEFAULT
);
162 $print_footer_options = variable_get('print_footer_options', PRINT_FOOTER_OPTIONS_DEFAULT
);
163 $print_footer_user = variable_get('print_footer_user', PRINT_FOOTER_USER_DEFAULT
);
165 $print['language'] = $GLOBALS['locale'];
166 $print['title'] = $node->title
;
167 $print['head'] = drupal_get_html_head();
168 $print['scripts'] = drupal_get_js();
169 $print['robots_meta'] = _print_robots_meta_generator();
170 $print['url'] = url($path, NULL
, NULL
, TRUE
);
171 $print['base_href'] = "<base href='".
$print['url'] .
"' />\n";
172 $print['favicon'] = theme_get_setting('toggle_favicon') ?
"<link rel='shortcut icon' href='".
theme_get_setting('favicon') .
"' type='image/x-icon' />\n" : '';
174 if (!empty($print_css)) {
175 $replace_pairs = array('%b' => base_path(), '%t' => path_to_theme());
176 $user_css = strip_tags(strtr($print_css, $replace_pairs));
179 drupal_add_css(drupal_get_path('module', 'print') .
'/css/print.css');
181 $drupal_css = drupal_add_css();
182 foreach ($drupal_css as
$key => $types) {
183 // Unset the theme's CSS
184 $drupal_css[$key]['theme'] = array();
187 // If we are sending a message via e-mail, the CSS must be embedded
188 if (!empty($message)) {
190 $css_files = array();
191 foreach ($drupal_css as
$types) {
192 foreach ($types as
$values) {
193 $css_files = array_merge($css_files, array_keys($values));
196 if (!empty($print_css)) {
197 // Convert to a local path, by removing the base_path
198 $pattern = '!^'.
base_path() .
'!';
199 $css_files[] = preg_replace($pattern, '', $user_css);
201 foreach ($css_files as
$filename) {
202 $res = file_get_contents($filename, TRUE
);
207 $print['css'] = "<style type='text/css' media='all'>$style</style>\n";
210 $print['css'] = drupal_get_css($drupal_css);
211 if (!empty($print_css)) {
212 $print['css'] .
= "<link type='text/css' rel='stylesheet' media='all' href='$user_css' />\n";
216 $print['sendtoprinter'] = $print_html_sendtoprinter ?
' onload="window.print();"' : '';
218 switch ($print_logo_options) {
223 $logo_url = theme_get_setting('logo');
225 case
2: // user-specifed
226 $logo_url = strip_tags($print_logo_url);
229 $print['logo'] = $logo_url ?
"<img class='print-logo' src='$logo_url' alt='' />\n" : '';
231 switch ($print_footer_options) {
236 $footer = filter_xss_admin(variable_get('site_footer', FALSE
)) .
"\n".
theme('blocks', 'footer');
237 $logo_url = theme_get_setting('logo');
239 case
2: // user-specifed
240 $footer = $print_footer_user;
243 $print['footer_message'] = $footer;
245 $published_site = variable_get('site_name', 0);
246 if ($published_site) {
247 $print_text_published = variable_get('print_text_published', t('Published on %site_name'));
248 $published = t($print_text_published, array('%site_name' => $published_site));
249 $print['site_name'] = $published .
' ('.
l($base_url, $base_url) .
')';
252 $print['site_name'] = '';
255 if ($print_sourceurl_enabled == 1) {
256 /* Grab and format the src URL */
257 if (empty($print_sourceurl_forcenode)) {
258 $url = $print['url'];
261 $url = $base_url .
'/'.
(((bool
)variable_get('clean_url', '0')) ?
'' : '?q=') .
$path;
264 $url .
= '#comment-$cid';
266 $retrieved_date = format_date(time(), 'small');
267 $print_text_retrieved = variable_get('print_text_retrieved', t('retrieved on %date'));
268 $retrieved = t($print_text_retrieved, array('%date' => $retrieved_date));
269 $print['printdate'] = $print_sourceurl_date ?
" ($retrieved)" : '';
271 $source_url = variable_get('print_text_source_url', t('Source URL'));
272 $print['source_url'] = '<strong>'.
$source_url .
$print['printdate'] .
':</strong> '.
l($url, $url);
275 $print['source_url'] = '';
278 if (isset($node->type
)) {
279 $node_type = $node->type
;
281 if (theme_get_setting("toggle_node_info_$node_type")) {
282 $print_text_by = variable_get('print_text_by', t('By %author'));
283 $by_author = ($node->name ?
$node->name
: variable_get('anonymous', t('Anonymous')));
284 $print['submitted'] = t($print_text_by, array('%author' => $by_author));
286 $print_text_created = variable_get('print_text_created', t('Created %date'));
287 $created_datetime = format_date($node->created
, 'small');
288 $print['created'] = t($print_text_created, array('%date' => $created_datetime));
291 $print['submitted'] = '';
292 $print['created'] = '';
295 $print['type'] = $node->type
;
298 $print['submitted'] = '';
299 $print['created'] = '';
303 menu_set_active_item($path);
304 $breadcrumb = drupal_get_breadcrumb();
305 if (!empty($breadcrumb)) {
306 $breadcrumb[] = menu_get_active_title();
307 $print['breadcrumb'] = implode(' > ', $breadcrumb);
310 $print['breadcrumb'] = '';
313 // Display the collected links at the bottom of the page. Code once taken from Kjartan Mannes' project.module
314 $print['pfp_links'] = '';
315 if (!empty($_print_urls)) {
316 $urls = _print_friendly_urls();
320 for ($i = 0; $i < $max; $i++) {
321 $pfp_links .
= '['.
($i + 1) .
'] '.
$urls[$i] .
"<br />\n";
323 $links = variable_get('print_text_links', t('Links'));
324 $print['pfp_links'] = "<p><strong>$links:</strong><br />$pfp_links</p>";
328 if (module_exists('taxonomy')) {
329 $terms = taxonomy_link('taxonomy terms', $node);
330 $print['taxonomy'] = theme('links', $terms);
333 $print['content'] = $node->body
;
334 $print['node'] = $node;
335 $print['message'] = $message;
341 * Callback function for the preg_replace_callback for URL-capable patterns
343 * Manipulate URLs to make them absolute in the URLs list, and to add a
344 * [n] footnote marker.
347 * array with the matched tag patterns, usually <a...>+text+</a>
349 * tag with re-written URL and when appropriate the [n] index to the
352 function _print_rewrite_urls($matches) {
353 global $base_url, $base_root, $_print_urls;
355 // first, split the html into the different tag attributes
356 $pattern = '!\s*(\w+\s*=\s*"(?:\\\"|[^"])*")\s*|\s*(\w+\s*=\s*\'(?:\\\\\'|[^\'])*\')\s*|\s*(\w+\s*=\s*\w+)\s*|\s+!';
357 $attribs = preg_split($pattern, $matches[1], -1, PREG_SPLIT_NO_EMPTY
| PREG_SPLIT_DELIM_CAPTURE
);
358 foreach ($attribs as
$key => $value) {
359 $attribs[$key] = preg_replace('!(\w)\s*=\s*(.*)!', '$1=$2', $value);
362 $size = count($attribs);
363 for ($i=1; $i < $size; $i++) {
364 // If the attribute is href or src, we may need to rewrite the URL in the value
365 if (preg_match('!^(?:href|src)\s*?=(.*)!i', $attribs[$i], $urls) > 0) {
366 $url = trim($urls[1], " \t\n\r\0\x0B\"'");
368 if (strpos($url, '://') || preg_match('!^mailto:.*?@.*?\..*?$!iu', $url)) {
369 // URL is absolute, do nothing
370 $newurl = urldecode($url);
373 if ($url[0] == '#') {
374 // URL is an anchor tag
375 if (!empty($_print_urls)) {
376 $path = explode('/', $_GET['q']);
378 $path = implode('/', $path);
379 if (is_numeric($path)) {
380 $path = "node/$path";
382 // Printer-friendly URLs is on, so we need to make it absolute
383 $newurl = url($path, NULL
, substr(urldecode($url), 1), TRUE
);
385 // Because base href is the original page, change the link to
386 // still be usable inside the print page
387 $matches[1] = str_replace($url, $_GET['q'] .
$url, $matches[1]);
390 // URL is relative, convert it into absolute URL
391 if ($url[0] == '/') {
392 // If it starts with '/' just append it to the server name
393 $newurl = $base_root .
'/'.
trim(urldecode($url), '/');
395 elseif (preg_match('!^(?:index.php)?\?q=!i', $url)) {
396 // If it starts with ?q=, just prepend with the base URL
397 $newurl = $base_url .
'/'.
trim(urldecode($url), '/');
400 $newurl = url(trim(urldecode($url), '/'), NULL
, NULL
, TRUE
);
402 $matches[1] = str_replace($url, $newurl, $matches[1]);
408 $ret = '<'.
$matches[1] .
'>';
409 if (count($matches) == 4) {
410 $ret .
= $matches[2] .
$matches[3];
411 if ((!empty($_print_urls)) && (isset($newurl))) {
412 $ret .
= ' <span class="print-footnote">['.
_print_friendly_urls(trim(stripslashes($newurl))) .
']</span>';
420 * Auxiliary function to store the Printer-friendly URLs list as static.
423 * absolute URL to be inserted in the list
425 * list of URLs previously stored if $url is 0, or the current count
428 function _print_friendly_urls($url = 0) {
429 static
$urls = array();
431 $url_idx = array_search($url, $urls);
432 if ($url_idx !== FALSE
) {
433 return ($url_idx + 1);
446 * Choose most appropriate template
448 * Auxiliary function to resolve the most appropriate template trying to find
449 * a content specific template in the theme or module dir before falling back
450 * on a generic template also in those dirs.
453 * format of the PF page being rendered (html, pdf, etc.)
455 * name of the node type being rendered in a PF page
457 * filename of the most suitable template
459 function _print_get_template($format = NULL
, $type = NULL
) {
460 $filenames = array();
461 // First try to find a template defined both for the format and then the type
462 if (!empty($format) && !empty($type)) {
463 $filenames[] = "print_$format.node-$type.tpl.php";
465 // Then only for the format
466 if (!empty($format)) {
467 $filenames[] = "print_$format.tpl.php";
469 // If the node type is known, then try to find that type's template file
471 $filenames[] = "print.node-$type.tpl.php";
472 $filenames[] = "print.$type.tpl.php";
474 // Finally search for a generic template file
475 $filenames[] = 'print.tpl.php';
477 foreach ($filenames as
$value) {
478 // First in the theme directory
479 $file = drupal_get_path('theme', $GLOBALS['theme_key']) .
'/'.
$value;
480 if (file_exists($file)) {
483 // Then in the module directory
484 $file = drupal_get_path('module', 'print') .
'/'.
$value;
485 if (file_exists($file)) {
492 * Check URL list settings for this node
497 * format of the page being generated
499 * TRUE if URL list should be displayed, FALSE otherwise
501 function _print_url_list_enabled($node, $format = PRINT_HTML_FORMAT
) {
503 case PRINT_HTML_FORMAT
:
504 $node_urllist = isset($node->print_display_urllist
) ?
$node->print_display_urllist
: TRUE
;
507 case PRINT_MAIL_FORMAT
:
508 $node_urllist = isset($node->print_mail_display_urllist
) ?
$node->print_mail_display_urllist
: TRUE
;
511 case PRINT_PDF_FORMAT
:
512 $node_urllist = isset($node->print_pdf_display_urllist
) ?
$node->print_pdf_display_urllist
: TRUE
;
516 if (!isset($node_urllist)) $node_urllist = TRUE
;
518 // Get value of Printer-friendly URLs setting
519 return (variable_get('print_urls', PRINT_URLS_DEFAULT
) && ($node_urllist) &&
520 variable_get('print_'.
$fmt .
'display_urllist_'.
$node->type
, PRINT_TYPE_URLLIST_DEFAULT
));
524 * Prepare a Printer-friendly-ready node body for content nodes
527 * node ID of the node to be rendered into a printer-friendly page
529 * comment ID of the individual comment to be rendered
531 * format of the page being generated
533 * if set to TRUE, outputs only the node's teaser
535 * optional sender's message (used by the send e-mail module)
537 * filled array ready to be used in the template
539 function _print_generate_node($nid, $cid = NULL
, $format = PRINT_HTML_FORMAT
, $teaser = FALSE
, $message = NULL
) {
542 // We can take a node id
543 $node = node_load(array('nid' => $nid));
549 elseif (!node_access('view', $node)) {
551 drupal_access_denied();
554 drupal_set_title($node->title
);
556 //alert other modules that we are generating a printer-friendly page, so they can choose to show/hide info
557 $node->printing
= TRUE
;
558 // Turn off Pagination by the Paging module
560 unset($node->pages_count
);
561 unset($node->page_count
);
564 // Adapted (simplified) version of node_view
565 //Render the node content
566 $node = node_build_content($node, $teaser, TRUE
);
567 // Disable fivestar widget output
568 unset($node->content
['fivestar_widget']);
569 // Disable service links module output
570 unset($node->content
['service_links']);
572 $content = drupal_render($node->content
);
574 $node->teaser
= $content;
578 $node->body
= $content;
579 unset($node->teaser
);
583 $print_comments = variable_get('print_comments', PRINT_COMMENTS_DEFAULT
);
585 if (function_exists('comment_render') && (($cid != NULL
) || ($print_comments))) {
586 //Print only the requested comment (or if $cid is NULL, all of them)
587 $comments = comment_render($node, $cid);
589 //Remove the comment forms
590 $comments = preg_replace('!<form.*?id="comment-.*?">.*?</form>!sim', '', $comments);
591 //Remove the 'Post new comment' title
592 $comments = preg_replace('!<h2.*?>Post new comment</h2>!', '', $comments);
593 //Remove the comment title hyperlink
594 $comments = preg_replace('!(<h3.*?>)(<a.*?>)(.*?)</a>(</h3>)!', '$1$3$4', $comments);
595 //Remove the comment author link
596 $pattern = '!(<span class="submitted">)(.*?)<a.*?>(.*?)</a>(</span>)!sim';
597 if (preg_match($pattern, $comments)) {
598 $comments = preg_replace($pattern , '$1$2$3$4', $comments);
600 //Remove the comment links
601 $comments = preg_replace('!\s*<ul class="links">.*?</ul>!sim', '', $comments);
603 // Single comment requested, output only the comment
606 $node->body .
= $comments;
609 node_invoke_nodeapi($node, 'alter', $teaser, TRUE
);
612 $node->body
= $node->teaser
;
613 unset($node->teaser
);
616 //Check URL list settings
617 $_print_urls = _print_url_list_enabled($node, $format);
619 // Convert the a href elements
620 $pattern = '!<(a\s[^>]*?)>(.*?)(</a>)!is';
621 $node->body
= preg_replace_callback($pattern, '_print_rewrite_urls', $node->body
);
625 $print = _print_var_generator($node, $message, $cid);
631 * Prepare a Printer-friendly-ready node body for non-content pages
634 * path of the node to be rendered into a printer-friendly page
636 * format of the page being generated
638 * if set to TRUE, outputs only the node's teaser
640 * optional sender's message (used by the send e-mail module)
642 * filled array ready to be used in the template
644 function _print_generate_path($path, $format = PRINT_HTML_FORMAT
, $teaser = FALSE
, $message = NULL
) {
647 $path = drupal_get_normal_path($path);
649 _menu_append_contextual_items();
651 menu_set_active_item($path);
652 // Adapted from index.php.
653 $node = new
stdClass();
654 $node->body
= menu_execute_active_handler();
655 $node->title
= drupal_get_title();
658 // It may happen that a drupal_not_found is called in the above call
659 if (preg_match('/404 Not Found/', drupal_get_headers()) == 1) {
663 if (is_int($node->body
)) {
664 switch ($node->body
) {
669 case MENU_ACCESS_DENIED
:
670 drupal_access_denied();
676 // Delete any links area
677 $node->body
= preg_replace('!\s*<div class="links">.*?</div>!sim', '', $node->body
);
679 //Check URL list settings
680 $_print_urls = _print_url_list_enabled($node, $format);
682 // Convert the a href elements
683 $pattern = '!<(a\s[^>]*?)>(.*?)(</a>)!is';
684 $node->body
= preg_replace_callback($pattern, '_print_rewrite_urls', $node->body
);
688 $print = _print_var_generator($node, $message);
695 * Prepare a Printer-friendly-ready node body for book pages
698 * node ID of the node to be rendered into a printer-friendly page
700 * format of the page being generated
702 * if set to TRUE, outputs only the node's teaser
704 * optional sender's message (used by the send e-mail module)
706 * filled array ready to be used in the template
708 function _print_generate_book($nid, $format = PRINT_HTML_FORMAT
, $teaser = FALSE
, $message = NULL
) {
711 $node = node_load(array('nid' => $nid));
717 elseif (!node_access('view', $node) || (!user_access('see printer-friendly version'))) {
719 drupal_access_denied();
723 $depth = count(book_location($node)) + 1;
724 $node->body
= book_recurse($nid, $depth, '_print_node_visitor_html_pre', 'book_node_visitor_html_post');
726 //Check URL list settings
727 $_print_urls = _print_url_list_enabled($node, $format);
729 // Convert the a href elements
730 $pattern = '!<(a\s[^>]*?)>(.*?)(</a>)!is';
731 $node->body
= preg_replace_callback($pattern, '_print_rewrite_urls', $node->body
);
735 $print = _print_var_generator($node, $message);
736 // The title is already displayed by the book_recurse, so avoid duplication
737 $print['title'] = '';
743 * Generates printer-friendly HTML for a node. This function is a 'pre-node' visitor function for book_recurse()
745 * My own version of book_node_visitor_html_pre so that CCK pages in book nodes
749 * the node to generate output for.
751 * the depth of the given node in the hierarchy. This is used only for
754 * the node id (nid) of the given node. This is used only for generating
757 * the HTML generated for the given node.
759 function _print_node_visitor_html_pre($node, $depth, $nid) {
760 $node = node_build_content($node, FALSE
, TRUE
);
762 unset($node->content
['book_navigation']);
764 $output .
= "<div id='node-$node->nid' class='section-$depth'>\n";
765 $output .
= "<h1 class='book-heading'>".
check_plain($node->title
) .
"</h1>\n";
766 $output .
= drupal_render($node->content
);