print.pages.inc 23.6 KB
Newer Older
jcnventura's avatar
jcnventura committed
1
<?php
jcnventura's avatar
jcnventura committed
2
// $Id$
jcnventura's avatar
jcnventura committed
3

jcnventura's avatar
jcnventura committed
4 5 6 7 8 9 10 11
/**
 * @file
 * Contains the functions to generate Printer-friendly pages.
 *
 * This file is included by the core PF module, and includes all the
 * functions necessary to generate a PF version of the original page
 * in HTML format.
 */
jcnventura's avatar
jcnventura committed
12

jcnventura's avatar
jcnventura committed
13 14
$_print_urls = PRINT_URLS_DEFAULT;

jcnventura's avatar
jcnventura committed
15 16 17 18 19 20
/**
 * Generate an HTML version of the printer-friendly page
 *
 * @see print_controller()
 * @see _print_get_template()
 */
jcnventura's avatar
jcnventura committed
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;
26

jcnventura's avatar
jcnventura committed
27
  $print = print_controller($path, $cid, PRINT_HTML_FORMAT);
28 29
  if ($print !== FALSE) {
    $node = $print['node'];
jcnventura's avatar
jcnventura committed
30
    include_once(DRUPAL_ROOT . '/' . _print_get_template(PRINT_HTML_FORMAT, $print['type']));
jcnventura's avatar
jcnventura committed
31

jcnventura's avatar
jcnventura committed
32 33 34 35 36 37
    if (is_numeric($path)) {
      $nodepath = 'node/' . $path;
    }
    else {
      $nodepath = drupal_get_normal_path($path);
    }
jcnventura's avatar
jcnventura committed
38 39 40 41 42 43 44 45
    db_merge('print_page_counter')
      ->key(array('path' => $nodepath))
      ->fields(array(
          'totalcount' => 1,
          'timestamp' => REQUEST_TIME,
      ))
      ->expression('totalcount', 'totalcount + :inc', array(':inc' => 1))
      ->execute();
46
  }
jcnventura's avatar
jcnventura committed
47 48 49
}

/**
50
 * Select the print generator function based on the page type
jcnventura's avatar
jcnventura committed
51 52 53 54
 *
 * Depending on the type of node, this functions chooses the appropriate
 * generator function.
 *
55 56 57 58
 * @param $path
 *   path of the original page
 * @param $cid
 *   comment ID of the individual comment to be rendered
jcnventura's avatar
jcnventura committed
59 60
 * @param $format
 *   format of the page being generated
61 62
 * @param $teaser
 *   if set to TRUE, outputs only the node's teaser
63 64
 * @param $message
 *   optional sender's message (used by the send e-mail module)
jcnventura's avatar
jcnventura committed
65 66 67 68 69
 * @return
 *   array with the fields to be used in the template
 * @see _print_generate_node()
 * @see _print_generate_path()
 * @see _print_generate_book()
jcnventura's avatar
jcnventura committed
70
 */
jcnventura's avatar
jcnventura committed
71
function print_controller($path, $cid = NULL, $format = PRINT_HTML_FORMAT, $teaser = FALSE, $message = NULL) {
72 73 74 75 76 77 78 79 80 81
  if (empty($path)) {
    // If no path was provided, let's try to generate a page for the referer
    global $base_url;

    $ref = $_SERVER['HTTP_REFERER'];
    $path = preg_replace("!^$base_url/!", '', $ref);
    if ($path === $ref) {
      $path = '';
    }
  }
82
  if (!is_numeric($path)) {
jcnventura's avatar
jcnventura committed
83 84
    // Indirect call with print/alias
    // If there is a path alias with these arguments, generate a printer-friendly version for it
85
    $path = drupal_get_normal_path($path);
86
    $ret = preg_match('!^node/(.*)!i', $path, $matches);
jcnventura's avatar
jcnventura committed
87
    if ($ret == 1) {
88
      $path = $matches[1];
jcnventura's avatar
jcnventura committed
89 90
    }
  }
91
  $parts = explode('/', $path);
92
  if (is_numeric($parts[0])) {
jcnventura's avatar
jcnventura committed
93
    $print = _print_generate_node($path, $cid, $format, $teaser, $message);
jcnventura's avatar
jcnventura committed
94 95
  }
  else {
96
    $ret = preg_match('!^book/export/html/(.*)!i', $path, $matches);
jcnventura's avatar
jcnventura committed
97 98
    if ($ret == 1) {
      // This is a book PF page link, handle trough the book handling functions
jcnventura's avatar
jcnventura committed
99
      $print = _print_generate_book($matches[1], $format, $teaser, $message);
jcnventura's avatar
jcnventura committed
100 101 102
    }
    else {
      // If no content node was found, handle the page printing with the 'printable' engine
jcnventura's avatar
jcnventura committed
103
      $print = _print_generate_path($path, $format, $teaser, $message);
jcnventura's avatar
jcnventura committed
104 105 106 107 108 109 110
    }
  }

  return $print;
}

/**
jcnventura's avatar
jcnventura committed
111
 * Generates a robots meta tag to tell them what they may index
jcnventura's avatar
jcnventura committed
112
 *
jcnventura's avatar
jcnventura committed
113
 * @return
jcnventura's avatar
jcnventura committed
114
 *   string with the meta robots tag
jcnventura's avatar
jcnventura committed
115 116
 */
function _print_robots_meta_generator() {
117 118 119
  $print_robots_noindex = variable_get('print_robots_noindex', PRINT_ROBOTS_NOINDEX_DEFAULT);
  $print_robots_nofollow = variable_get('print_robots_nofollow', PRINT_ROBOTS_NOFOLLOW_DEFAULT);
  $print_robots_noarchive = variable_get('print_robots_noarchive', PRINT_ROBOTS_NOARCHIVE_DEFAULT);
jcnventura's avatar
jcnventura committed
120 121
  $robots_meta = array();

122
  if (!empty($print_robots_noindex)) {
jcnventura's avatar
jcnventura committed
123 124
    $robots_meta[] = 'noindex';
  }
125
  if (!empty($print_robots_nofollow)) {
jcnventura's avatar
jcnventura committed
126 127
    $robots_meta[] = 'nofollow';
  }
128
  if (!empty($print_robots_noarchive)) {
jcnventura's avatar
jcnventura committed
129 130 131
    $robots_meta[] = 'noarchive';
  }

132 133
  if (count($robots_meta) > 0) {
    $robots_meta = implode(', ', $robots_meta);
134
    $robots_meta = "<meta name='robots' content='$robots_meta' />\n";
jcnventura's avatar
jcnventura committed
135 136 137 138 139 140 141 142 143
  }
  else {
    $robots_meta = '';
  }

  return $robots_meta;
}

/**
jcnventura's avatar
jcnventura committed
144
 * Post-processor that fills the array for the template with common details
jcnventura's avatar
jcnventura committed
145
 *
jcnventura's avatar
jcnventura committed
146 147
 * @param $node
 *   generated node with a printer-friendly node body
148 149
 * @param $message
 *   optional sender's message (used by the send e-mail module)
jcnventura's avatar
jcnventura committed
150
 * @param $cid
jcnventura's avatar
jcnventura committed
151
 *   id of current comment being generated (NULL when not generating
jcnventura's avatar
jcnventura committed
152 153 154
 *   an individual comment)
 * @return
 *   array with the fields to be used in the template
jcnventura's avatar
jcnventura committed
155
 */
156
function _print_var_generator($node, $message = NULL, $cid = NULL) {
jcnventura's avatar
jcnventura committed
157
  global $base_url, $language, $_print_urls;
jcnventura's avatar
jcnventura committed
158 159 160 161

  $path = empty($node->nid) ? $node->path : "node/$node->nid";

  // print module settings
162
  $print_css = variable_get('print_css', PRINT_CSS_DEFAULT);
163
  $print_logo_options = variable_get('print_logo_options', PRINT_LOGO_OPTIONS_DEFAULT);
164 165 166 167 168
  $print_logo_url = variable_get('print_logo_url', PRINT_LOGO_URL_DEFAULT);
  $print_html_sendtoprinter = variable_get('print_html_sendtoprinter', PRINT_HTML_SENDTOPRINTER_DEFAULT);
  $print_sourceurl_enabled = variable_get('print_sourceurl_enabled', PRINT_SOURCEURL_ENABLED_DEFAULT);
  $print_sourceurl_forcenode = variable_get('print_sourceurl_forcenode', PRINT_SOURCEURL_FORCENODE_DEFAULT);
  $print_sourceurl_date = variable_get('print_sourceurl_date', PRINT_SOURCEURL_DATE_DEFAULT);
169 170
  $print_footer_options = variable_get('print_footer_options', PRINT_FOOTER_OPTIONS_DEFAULT);
  $print_footer_user = variable_get('print_footer_user', PRINT_FOOTER_USER_DEFAULT);
171 172

  $print['language'] = $language->language;
173
  $print['title'] = check_plain($node->title);
174 175 176 177
  $print['head'] = drupal_get_html_head();
  $print['scripts'] = drupal_get_js();
  $print['robots_meta'] = _print_robots_meta_generator();
  $print['url'] = url($path, array('absolute' => TRUE));
jcnventura's avatar
jcnventura committed
178 179
  $print['base_href'] = "<base href='" . $print['url'] . "' />\n";
  $print['favicon'] = theme_get_setting('toggle_favicon') ? "<link rel='shortcut icon' href='" . theme_get_setting('favicon') . "' type='image/x-icon' />\n" : '';
jcnventura's avatar
jcnventura committed
180

181
  if (!empty($print_css)) {
182
    $replace_pairs = array('%b' => base_path(), '%t' => path_to_theme());
jcnventura's avatar
jcnventura committed
183
    $user_css = strip_tags(strtr($print_css, $replace_pairs));
jcnventura's avatar
jcnventura committed
184 185
  }
  else {
jcnventura's avatar
jcnventura committed
186
    drupal_add_css(drupal_get_path('module', 'print') . '/css/print.css');
jcnventura's avatar
jcnventura committed
187
  }
jcnventura's avatar
jcnventura committed
188 189 190 191
  $drupal_css = drupal_add_css();
  foreach ($drupal_css as $key => $types) {
    // Unset the theme's CSS
    $drupal_css[$key]['theme'] = array();
192 193 194 195
  }

  // If we are sending a message via e-mail, the CSS must be embedded
  if (!empty($message)) {
196
    $style = '';
jcnventura's avatar
jcnventura committed
197 198 199 200 201 202 203
    $css_files = array();
    foreach ($drupal_css as $types) {
      foreach ($types as $values) {
        $css_files = array_merge($css_files, array_keys($values));
      }
    }
    if (!empty($print_css)) {
204
      // Convert to a local path, by removing the base_path
jcnventura's avatar
jcnventura committed
205
      $pattern = '!^' . base_path() . '!';
jcnventura's avatar
jcnventura committed
206 207 208
      $css_files[] = preg_replace($pattern, '', $user_css);
    }
    foreach ($css_files as $filename) {
jcnventura's avatar
jcnventura committed
209
      $res = file_exists($filename) ? file_get_contents($filename, TRUE) : FALSE;
210 211 212
      if ($res != FALSE) {
        $style .= $res;
      }
213
    }
214
    $print['css'] = "<style type='text/css' media='all'>$style</style>\n";
215 216
  }
  else {
jcnventura's avatar
jcnventura committed
217 218 219
    $print['css'] = drupal_get_css($drupal_css);
    if (!empty($print_css)) {
      $print['css'] .= "<link type='text/css' rel='stylesheet' media='all' href='$user_css' />\n";
220
    }
221
  }
jcnventura's avatar
jcnventura committed
222

223
  $print['sendtoprinter'] = $print_html_sendtoprinter ? ' onload="window.print();"' : '';
jcnventura's avatar
jcnventura committed
224

225 226 227 228 229 230 231 232 233 234 235
  switch ($print_logo_options) {
    case 0: // none
      $logo_url = 0;
      break;
    case 1: // theme's
      $logo_url = theme_get_setting('logo');
      break;
    case 2: // user-specifed
      $logo_url = strip_tags($print_logo_url);
      break;
  }
236
  $print['logo'] = $logo_url ? "<img class='print-logo' src='$logo_url' alt='' />\n" : '';
237

238 239 240 241 242
  switch ($print_footer_options) {
    case 0: // none
      $footer = '';
      break;
    case 1: // theme's
jcnventura's avatar
jcnventura committed
243
      $footer = filter_xss_admin(variable_get('site_footer', FALSE)) . "\n" . theme('blocks', 'footer');
244 245 246 247 248 249 250 251
      $logo_url = theme_get_setting('logo');
      break;
    case 2: // user-specifed
      $footer = $print_footer_user;
      break;
  }
  $print['footer_message'] = $footer;

252
  $published_site = variable_get('site_name', 0);
253
  if ($published_site) {
jcnventura's avatar
jcnventura committed
254 255
    $print_text_published = variable_get('print_text_published', t('Published on %site_name'));
    $published = t($print_text_published, array('%site_name' => $published_site));
jcnventura's avatar
jcnventura committed
256
    $print['site_name'] = $published . ' (' . l($base_url, $base_url) . ')';
257 258
  }
  else {
259
    $print['site_name'] = '';
260
  }
jcnventura's avatar
jcnventura committed
261

262
  if ($print_sourceurl_enabled == 1) {
263
    /* Grab and format the src URL */
264 265
    if (empty($print_sourceurl_forcenode)) {
      $url = $print['url'];
266 267
    }
    else {
jcnventura's avatar
jcnventura committed
268
      $url = $base_url . '/' . (((bool)variable_get('clean_url', '0')) ? '' : '?q=') . $path;
269
    }
270
    if (is_int($cid)) {
271
      $url .= '#comment-$cid';
272
    }
jcnventura's avatar
jcnventura committed
273
    $retrieved_date = format_date(REQUEST_TIME, 'small');
jcnventura's avatar
jcnventura committed
274 275
    $print_text_retrieved = variable_get('print_text_retrieved', t('retrieved on %date'));
    $retrieved = t($print_text_retrieved, array('%date' => $retrieved_date));
276
    $print['printdate'] = $print_sourceurl_date ? " ($retrieved)" : '';
277

jcnventura's avatar
jcnventura committed
278
    $source_url = variable_get('print_text_source_url', t('Source URL'));
jcnventura's avatar
jcnventura committed
279
    $print['source_url'] = '<strong>' . $source_url . $print['printdate'] . ':</strong> ' . l($url, $url);
jcnventura's avatar
jcnventura committed
280 281
  }
  else {
282
    $print['source_url'] = '';
jcnventura's avatar
jcnventura committed
283 284
  }

285 286
  if (isset($node->type)) {
    $node_type = $node->type;
287

288
    if (theme_get_setting("toggle_node_info_$node_type")) {
jcnventura's avatar
jcnventura committed
289
      $print_text_by = variable_get('print_text_by', t('By %author'));
290
      $by_author = ($node->name ? $node->name : variable_get('anonymous', t('Anonymous')));
jcnventura's avatar
jcnventura committed
291
      $print['submitted'] = t($print_text_by, array('%author' => $by_author));
292

jcnventura's avatar
jcnventura committed
293
      $print_text_created = variable_get('print_text_created', t('Created %date'));
294
      $created_datetime = format_date($node->created, 'small');
jcnventura's avatar
jcnventura committed
295
      $print['created'] = t($print_text_created, array('%date' => $created_datetime));
296 297
    }
    else {
298 299
      $print['submitted'] = '';
      $print['created'] = '';
300
    }
301

302
    $print['type'] = $node->type;
303 304
  }
  else {
305 306 307
    $print['submitted'] = '';
    $print['created'] = '';
    $print['type'] = '';
308
  }
jcnventura's avatar
jcnventura committed
309

jcnventura's avatar
jcnventura committed
310 311 312 313
  menu_set_active_item($path);
  $breadcrumb = drupal_get_breadcrumb();
  if (!empty($breadcrumb)) {
    $breadcrumb[] = menu_get_active_title();
314
    $print['breadcrumb'] = implode(' > ', $breadcrumb);
jcnventura's avatar
jcnventura committed
315 316
  }
  else {
317
    $print['breadcrumb'] = '';
jcnventura's avatar
jcnventura committed
318 319 320
  }

  // Display the collected links at the bottom of the page. Code once taken from Kjartan Mannes' project.module
jcnventura's avatar
jcnventura committed
321
  $print['pfp_links'] = '';
jcnventura's avatar
jcnventura committed
322
  if (!empty($_print_urls)) {
jcnventura's avatar
jcnventura committed
323 324
    $urls = _print_friendly_urls();
    $max = count($urls);
325
    $pfp_links = '';
jcnventura's avatar
jcnventura committed
326 327
    if ($max) {
      for ($i = 0; $i < $max; $i++) {
jcnventura's avatar
jcnventura committed
328
        $pfp_links .= '[' . ($i + 1) . '] ' . $urls[$i] . "<br />\n";
jcnventura's avatar
jcnventura committed
329
      }
jcnventura's avatar
jcnventura committed
330
      $links = variable_get('print_text_links', t('Links'));
331
      $print['pfp_links'] = "<p><strong>$links:</strong><br />$pfp_links</p>";
jcnventura's avatar
jcnventura committed
332 333 334 335
    }
  }

  if (module_exists('taxonomy')) {
jcnventura's avatar
jcnventura committed
336 337 338
// TODO make this work when taxonomy works again
//    $terms = taxonomy_link('taxonomy terms', $node);
    $terms = taxonomy_preview_terms($node);
339
    $print['taxonomy'] = theme('links', $terms);
jcnventura's avatar
jcnventura committed
340 341
  }

342 343 344
  $print['content'] = $node->body;
  $print['node'] = $node;
  $print['message'] = $message;
jcnventura's avatar
jcnventura committed
345 346 347 348 349

  return $print;
}

/**
jcnventura's avatar
jcnventura committed
350
 * Callback function for the preg_replace_callback for URL-capable patterns
jcnventura's avatar
jcnventura committed
351
 *
jcnventura's avatar
jcnventura committed
352
 * Manipulate URLs to make them absolute in the URLs list, and to add a
jcnventura's avatar
jcnventura committed
353
 * [n] footnote marker.
jcnventura's avatar
jcnventura committed
354
 *
jcnventura's avatar
jcnventura committed
355 356 357
 * @param $matches
 *   array with the matched tag patterns, usually <a...>+text+</a>
 * @return
jcnventura's avatar
jcnventura committed
358
 *   tag with re-written URL and when appropriate the [n] index to the
jcnventura's avatar
jcnventura committed
359
 *   URL list
jcnventura's avatar
jcnventura committed
360 361
 */
function _print_rewrite_urls($matches) {
jcnventura's avatar
jcnventura committed
362
  global $base_url, $base_root, $_print_urls;
jcnventura's avatar
jcnventura committed
363 364

  // first, split the html into the different tag attributes
365
  $pattern = '!\s*(\w+\s*=\s*"(?:\\\"|[^"])*")\s*|\s*(\w+\s*=\s*\'(?:\\\\\'|[^\'])*\')\s*|\s*(\w+\s*=\s*\w+)\s*|\s+!';
366 367
  $attribs = preg_split($pattern, $matches[1], -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
  foreach ($attribs as $key => $value) {
368
    $attribs[$key] = preg_replace('!(\w)\s*=\s*(.*)!', '$1=$2', $value);
369
  }
jcnventura's avatar
jcnventura committed
370

371 372
  $size = count($attribs);
  for ($i=1; $i < $size; $i++) {
jcnventura's avatar
jcnventura committed
373
    // If the attribute is href or src, we may need to rewrite the URL in the value
374
    if (preg_match('!^(?:href|src)\s*?=(.*)!i', $attribs[$i], $urls) > 0) {
375
      $url = trim($urls[1], " \t\n\r\0\x0B\"'");
jcnventura's avatar
jcnventura committed
376

377
      if (strpos($url, '://') || preg_match('!^mailto:.*?@.*?\..*?$!iu', $url)) {
jcnventura's avatar
jcnventura committed
378 379 380 381
        // URL is absolute, do nothing
        $newurl = urldecode($url);
      }
      else {
382
        if ($url[0] == '#') {
jcnventura's avatar
jcnventura committed
383
          // URL is an anchor tag
jcnventura's avatar
jcnventura committed
384
          if (!empty($_print_urls)) {
385 386 387
            $path = explode('/', $_GET['q']);
            unset($path[0]);
            $path = implode('/', $path);
jcnventura's avatar
jcnventura committed
388 389 390 391 392 393 394 395 396 397 398 399
            if (is_numeric($path)) {
              $path = "node/$path";
            }
            // Printer-friendly URLs is on, so we need to make it absolute
            $newurl = url($path, array('fragment' => substr(urldecode($url), 1), 'absolute' => TRUE));
          }
          // Because base href is the original page, change the link to
          // still be usable inside the print page
          $matches[1] = str_replace($url, $_GET['q'] . $url, $matches[1]);
        }
        else {
          // URL is relative, convert it into absolute URL
400
          if ($url[0] == '/') {
jcnventura's avatar
jcnventura committed
401
            // If it starts with '/' just append it to the server name
jcnventura's avatar
jcnventura committed
402
            $newurl = $base_root . '/' . trim(urldecode($url), '/');
jcnventura's avatar
jcnventura committed
403
          }
404 405
          elseif (preg_match('!^(?:index.php)?\?q=!i', $url)) {
            // If it starts with ?q=, just prepend with the base URL
jcnventura's avatar
jcnventura committed
406
            $newurl = $base_url . '/' . trim(urldecode($url), '/');
jcnventura's avatar
jcnventura committed
407 408
          }
          else {
409
            $newurl = url(trim(urldecode($url), '/'), array('absolute' => TRUE));
jcnventura's avatar
jcnventura committed
410
          }
411
          $matches[1] = str_replace($url, $newurl, $matches[1]);
jcnventura's avatar
jcnventura committed
412 413 414 415 416
        }
      }
    }
  }

jcnventura's avatar
jcnventura committed
417
  $ret = '<' . $matches[1] . '>';
jcnventura's avatar
jcnventura committed
418 419
  if (count($matches) == 4) {
    $ret .= $matches[2] . $matches[3];
jcnventura's avatar
jcnventura committed
420
    if ((!empty($_print_urls)) && (isset($newurl))) {
jcnventura's avatar
jcnventura committed
421
      $ret .= ' <span class="print-footnote">[' . _print_friendly_urls(trim(stripslashes($newurl))) . ']</span>';
jcnventura's avatar
jcnventura committed
422 423 424 425 426 427 428 429 430
    }
  }

  return $ret;
}

/**
 * Auxiliary function to store the Printer-friendly URLs list as static.
 *
jcnventura's avatar
jcnventura committed
431 432
 * @param $url
 *   absolute URL to be inserted in the list
jcnventura's avatar
jcnventura committed
433 434
 * @return
 *   list of URLs previously stored if $url is 0, or the current count
jcnventura's avatar
jcnventura committed
435
 *   otherwise.
jcnventura's avatar
jcnventura committed
436 437 438 439 440 441 442 443 444 445 446 447 448
 */
function _print_friendly_urls($url = 0) {
  static $urls = array();
  if ($url) {
    $url_idx = array_search($url, $urls);
    if ($url_idx !== FALSE) {
      return ($url_idx + 1);
    }
    else {
      $urls[] = $url;
      return count($urls);
    }
  }
jcnventura's avatar
jcnventura committed
449 450 451
  $ret = $urls;
  $urls = array();
  return $ret;
jcnventura's avatar
jcnventura committed
452 453 454
}

/**
jcnventura's avatar
jcnventura committed
455
 * Choose most appropriate template
jcnventura's avatar
jcnventura committed
456
 *
jcnventura's avatar
jcnventura committed
457 458 459 460
 * Auxiliary function to resolve the most appropriate template trying to find
 * a content specific template in the theme or module dir before falling back
 * on a generic template also in those dirs.
 *
461 462
 * @param format
 *   format of the PF page being rendered (html, pdf, etc.)
jcnventura's avatar
jcnventura committed
463 464 465 466
 * @param $type
 *   name of the node type being rendered in a PF page
 * @return
 *   filename of the most suitable template
jcnventura's avatar
jcnventura committed
467
 */
468 469 470 471 472 473 474 475 476 477 478 479 480 481 482
function _print_get_template($format = NULL, $type = NULL) {
  $filenames = array();
  // First try to find a template defined both for the format and then the type
  if (!empty($format) && !empty($type)) {
    $filenames[] = "print_$format.node-$type.tpl.php";
  }
  // Then only for the format
  if (!empty($format)) {
    $filenames[] = "print_$format.tpl.php";
  }
  // If the node type is known, then try to find that type's template file
  if (!empty($type)) {
    $filenames[] = "print.node-$type.tpl.php";
  }
  // Finally search for a generic template file
483
  $filenames[] = 'print.tpl.php';
484 485

  foreach ($filenames as $value) {
jcnventura's avatar
jcnventura committed
486
    // First in the theme directory
jcnventura's avatar
jcnventura committed
487
    $file = drupal_get_path('theme', $GLOBALS['theme_key']) . '/' . $value;
488 489
    if (file_exists($file)) {
      return $file;
jcnventura's avatar
jcnventura committed
490 491
    }
    // Then in the module directory
jcnventura's avatar
jcnventura committed
492
    $file = drupal_get_path('module', 'print') . '/' . $value;
493 494
    if (file_exists($file)) {
      return $file;
jcnventura's avatar
jcnventura committed
495 496 497 498
    }
  }
}

jcnventura's avatar
jcnventura committed
499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516
/**
 * Check URL list settings for this node
 *
 * @param node
 *   node object
 * @param $format
 *   format of the page being generated
 * @return
 *   TRUE if URL list should be displayed, FALSE otherwise
 */
function _print_url_list_enabled($node, $format = PRINT_HTML_FORMAT) {
  switch ($format) {
    case PRINT_HTML_FORMAT:
      $node_urllist = isset($node->print_display_urllist) ? $node->print_display_urllist : TRUE;
      $fmt = '';
      break;
    case PRINT_MAIL_FORMAT:
      $node_urllist = isset($node->print_mail_display_urllist) ? $node->print_mail_display_urllist : TRUE;
jcnventura's avatar
jcnventura committed
517
      $fmt = $format . '_';
jcnventura's avatar
jcnventura committed
518 519 520
      break;
    case PRINT_PDF_FORMAT:
      $node_urllist = isset($node->print_pdf_display_urllist) ? $node->print_pdf_display_urllist : TRUE;
jcnventura's avatar
jcnventura committed
521
      $fmt = $format . '_';
jcnventura's avatar
jcnventura committed
522 523 524 525 526 527
      break;
  }
  if (!isset($node_urllist)) $node_urllist = TRUE;

  // Get value of Printer-friendly URLs setting
  return (variable_get('print_urls', PRINT_URLS_DEFAULT) && ($node_urllist) &&
528
          (isset($node->type) ? variable_get('print_' . $fmt . 'display_urllist_' . $node->type, PRINT_TYPE_URLLIST_DEFAULT) : PRINT_TYPE_URLLIST_DEFAULT));
jcnventura's avatar
jcnventura committed
529 530
}

jcnventura's avatar
jcnventura committed
531
/**
jcnventura's avatar
jcnventura committed
532
 * Prepare a Printer-friendly-ready node body for content nodes
jcnventura's avatar
jcnventura committed
533
 *
jcnventura's avatar
jcnventura committed
534 535 536 537
 * @param $nid
 *   node ID of the node to be rendered into a printer-friendly page
 * @param $cid
 *   comment ID of the individual comment to be rendered
jcnventura's avatar
jcnventura committed
538 539
 * @param $format
 *   format of the page being generated
540 541
 * @param $teaser
 *   if set to TRUE, outputs only the node's teaser
542 543
 * @param $message
 *   optional sender's message (used by the send e-mail module)
jcnventura's avatar
jcnventura committed
544 545
 * @return
 *   filled array ready to be used in the template
jcnventura's avatar
jcnventura committed
546
 */
jcnventura's avatar
jcnventura committed
547 548 549
function _print_generate_node($nid, $cid = NULL, $format = PRINT_HTML_FORMAT, $teaser = FALSE, $message = NULL) {
  global $_print_urls;

jcnventura's avatar
jcnventura committed
550
  // We can take a node id
551
  $node = node_load($nid);
552 553 554
  if (!$node) {
    // Node not found
    drupal_not_found();
555
    return FALSE;
556 557
  }
  elseif (!node_access('view', $node)) {
jcnventura's avatar
jcnventura committed
558
    // Access is denied
559
    drupal_access_denied();
560
    return FALSE;
jcnventura's avatar
jcnventura committed
561
  }
562
  drupal_set_title($node->title);
jcnventura's avatar
jcnventura committed
563 564

  //alert other modules that we are generating a printer-friendly page, so they can choose to show/hide info
565
  $node->printing = TRUE;
jcnventura's avatar
jcnventura committed
566

567
  //use the proper build_mode
jcnventura's avatar
jcnventura committed
568
  $node->build_mode = NODE_BUILD_PRINT;
569

jcnventura's avatar
jcnventura committed
570 571 572 573 574
  // Turn off Pagination by the Paging module
  unset($node->pages);
  unset($node->page_count);

  if ($cid === NULL) {
575
    // Adapted (simplified) version of node_view
jcnventura's avatar
jcnventura committed
576
    //Render the node content
577
    $node = node_build_content($node, $teaser, TRUE);
jcnventura's avatar
jcnventura committed
578
    // Disable fivestar widget output
579
    unset($node->content['fivestar_widget']);
jcnventura's avatar
jcnventura committed
580
    // Disable service links module output
581
    unset($node->content['service_links']);
jcnventura's avatar
jcnventura committed
582

583
    $content = drupal_render($node->content);
584 585 586 587

    // Disable the AdSense module ads
    $content = preg_replace('!<div class=[\'"]adsense[\'"].*?</div>!sim', '', $content);

588 589 590 591 592 593 594 595
    if ($teaser) {
      $node->teaser = $content;
      unset($node->body);
    }
    else {
      $node->body = $content;
      unset($node->teaser);
    }
jcnventura's avatar
jcnventura committed
596 597
  }

598
  $print_comments = variable_get('print_comments', PRINT_COMMENTS_DEFAULT);
jcnventura's avatar
jcnventura committed
599

600
  if (function_exists('comment_render') && (($cid != NULL) || ($print_comments))) {
jcnventura's avatar
jcnventura committed
601 602
    //Print only the requested comment (or if $cid is NULL, all of them)
    $comments = comment_render($node, $cid);
jcnventura's avatar
jcnventura committed
603

jcnventura's avatar
jcnventura committed
604
    //Remove the comment forms
605
    $comments = preg_replace('!<form.*?id="comment-.*?">.*?</form>!sim', '', $comments);
jcnventura's avatar
jcnventura committed
606
    //Remove the 'Post new comment' title
jcnventura's avatar
jcnventura committed
607
    $comments = preg_replace('!<h2.*?>' . t('Post new comment') . '</h2>!', '', $comments);
jcnventura's avatar
jcnventura committed
608
    //Remove the comment title hyperlink
609
    $comments = preg_replace('!(<h3.*?>.*?)<a.*?>(.*?)</a>(.*?</h3>)!i', '$1$2$3', $comments);
610
    //Remove the comment author link
611
    $pattern = '!(<(?:span|div) class="submitted">.*?)<a.*?>(.*?)</a>(.*?</(?:span|div)>)!sim';
612
    if (preg_match($pattern, $comments)) {
613
      $comments = preg_replace($pattern , '$1$2$3', $comments);
614
    }
jcnventura's avatar
jcnventura committed
615
    //Remove the comment links
616
    $comments = preg_replace('!\s*<ul class="links">.*?</ul>!sim', '', $comments);
jcnventura's avatar
jcnventura committed
617 618 619 620 621 622
    if ($cid != NULL) {
      // Single comment requested, output only the comment
      unset($node->body);
    }
    $node->body .= $comments;
  }
623
  node_invoke_node($node, 'alter', $teaser, TRUE);
jcnventura's avatar
jcnventura committed
624

jcnventura's avatar
jcnventura committed
625 626 627 628 629 630 631 632
  if ($teaser) {
    $node->body = $node->teaser;
    unset($node->teaser);
  }

  //Check URL list settings
  $_print_urls = _print_url_list_enabled($node, $format);

jcnventura's avatar
jcnventura committed
633
  // Convert the a href elements
634 635
  $pattern = '!<(a\s[^>]*?)>(.*?)(</a>)!is';
  $node->body = preg_replace_callback($pattern, '_print_rewrite_urls', $node->body);
jcnventura's avatar
jcnventura committed
636 637 638

  init_theme();

639
  $print = _print_var_generator($node, $message, $cid);
jcnventura's avatar
jcnventura committed
640 641 642 643 644

  return $print;
}

/**
jcnventura's avatar
jcnventura committed
645
 * Prepare a Printer-friendly-ready node body for non-content pages
jcnventura's avatar
jcnventura committed
646
 *
jcnventura's avatar
jcnventura committed
647 648
 * @param $path
 *   path of the node to be rendered into a printer-friendly page
jcnventura's avatar
jcnventura committed
649 650
 * @param $format
 *   format of the page being generated
651 652 653 654
 * @param $teaser
 *   if set to TRUE, outputs only the node's teaser
 * @param $message
 *   optional sender's message (used by the send e-mail module)
jcnventura's avatar
jcnventura committed
655 656
 * @return
 *   filled array ready to be used in the template
jcnventura's avatar
jcnventura committed
657
 */
jcnventura's avatar
jcnventura committed
658 659 660
function _print_generate_path($path, $format = PRINT_HTML_FORMAT, $teaser = FALSE, $message = NULL) {
  global $_print_urls;

jcnventura's avatar
jcnventura committed
661 662 663 664 665 666
  $path = drupal_get_normal_path($path);

  menu_set_active_item($path);
  // Adapted from index.php.
  $node = new stdClass();
  $node->body = menu_execute_active_handler($path);
667
  $node->title = drupal_get_title();
jcnventura's avatar
jcnventura committed
668 669 670 671
  $node->path = $path;

  // It may happen that a drupal_not_found is called in the above call
  if (preg_match('/404 Not Found/', drupal_get_headers()) == 1) {
672
    return FALSE;
jcnventura's avatar
jcnventura committed
673 674
  }

675 676 677
  if (is_int($node->body)) {
    switch ($node->body) {
      case MENU_NOT_FOUND:
678
        drupal_not_found();
679
        return FALSE;
680 681
        break;
      case MENU_ACCESS_DENIED:
682
        drupal_access_denied();
683
        return FALSE;
684 685
        break;
    }
jcnventura's avatar
jcnventura committed
686 687 688
  }

  // Delete any links area
689
  $node->body = preg_replace('!\s*<div class="links">.*?</div>!sim', '', $node->body);
jcnventura's avatar
jcnventura committed
690

jcnventura's avatar
jcnventura committed
691 692 693
  //Check URL list settings
  $_print_urls = _print_url_list_enabled($node, $format);

jcnventura's avatar
jcnventura committed
694
  // Convert the a href elements
695 696
  $pattern = '!<(a\s[^>]*?)>(.*?)(</a>)!is';
  $node->body = preg_replace_callback($pattern, '_print_rewrite_urls', $node->body);
jcnventura's avatar
jcnventura committed
697 698 699

  init_theme();

700
  $print = _print_var_generator($node, $message);
jcnventura's avatar
jcnventura committed
701 702 703 704 705 706

  return $print;
}


/**
jcnventura's avatar
jcnventura committed
707
 * Prepare a Printer-friendly-ready node body for book pages
jcnventura's avatar
jcnventura committed
708
 *
jcnventura's avatar
jcnventura committed
709 710
 * @param $nid
 *   node ID of the node to be rendered into a printer-friendly page
jcnventura's avatar
jcnventura committed
711 712
 * @param $format
 *   format of the page being generated
713 714 715 716
 * @param $teaser
 *   if set to TRUE, outputs only the node's teaser
 * @param $message
 *   optional sender's message (used by the send e-mail module)
jcnventura's avatar
jcnventura committed
717 718
 * @return
 *   filled array ready to be used in the template
jcnventura's avatar
jcnventura committed
719
 */
jcnventura's avatar
jcnventura committed
720 721 722
function _print_generate_book($nid, $format = PRINT_HTML_FORMAT, $teaser = FALSE, $message = NULL) {
  global $_print_urls;

723
  $node = node_load($nid);
724 725 726
  if (!$node) {
    // Node not found
    drupal_not_found();
727
    return FALSE;
728 729
  }
  elseif (!node_access('view', $node) || (!user_access('access printer-friendly version'))) {
jcnventura's avatar
jcnventura committed
730
    // Access is denied
731
    drupal_access_denied();
732
    return FALSE;
jcnventura's avatar
jcnventura committed
733 734 735 736 737
  }

  $tree = book_menu_subtree_data($node->book);
  $node->body = book_export_traverse($tree, 'book_node_export');

jcnventura's avatar
jcnventura committed
738 739 740
  //Check URL list settings
  $_print_urls = _print_url_list_enabled($node, $format);

jcnventura's avatar
jcnventura committed
741
  // Convert the a href elements
742 743
  $pattern = '!<(a\s[^>]*?)>(.*?)(</a>)!is';
  $node->body = preg_replace_callback($pattern, '_print_rewrite_urls', $node->body);
jcnventura's avatar
jcnventura committed
744 745 746

  init_theme();

747
  $print = _print_var_generator($node, $message);
jcnventura's avatar
jcnventura committed
748
  // The title is already displayed by the book_recurse, so avoid duplication
749
  $print['title'] = '';
jcnventura's avatar
jcnventura committed
750 751 752

  return $print;
}