print.pages.inc 24.4 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
/**
 * @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.
11 12
 *
 * @ingroup print
jcnventura's avatar
jcnventura committed
13
 */
jcnventura's avatar
jcnventura committed
14

15 16
$_print_urls = PRINT_URLS_DEFAULT;

jcnventura's avatar
jcnventura committed
17 18 19 20 21 22
/**
 * Generate an HTML version of the printer-friendly page
 *
 * @see print_controller()
 * @see _print_get_template()
 */
jcnventura's avatar
jcnventura committed
23
function print_controller_html() {
24 25
  $args = func_get_args();
  $path = implode('/', $args);
26
  $cid = isset($_GET['comment']) ? (int)$_GET['comment'] : NULL;
27

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

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

/**
46
 * Select the print generator function based on the page type
jcnventura's avatar
jcnventura committed
47 48 49 50
 *
 * Depending on the type of node, this functions chooses the appropriate
 * generator function.
 *
51 52 53 54
 * @param $path
 *   path of the original page
 * @param $cid
 *   comment ID of the individual comment to be rendered
55 56
 * @param $format
 *   format of the page being generated
57 58
 * @param $teaser
 *   if set to TRUE, outputs only the node's teaser
59 60
 * @param $message
 *   optional sender's message (used by the send e-mail module)
jcnventura's avatar
jcnventura committed
61 62 63 64 65
 * @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
66
 */
67
function print_controller($path, $cid = NULL, $format = PRINT_HTML_FORMAT, $teaser = FALSE, $message = NULL) {
68 69 70 71 72 73 74 75 76 77
  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 = '';
    }
  }
78
  if (!is_numeric($path)) {
jcnventura's avatar
jcnventura committed
79 80
    // Indirect call with print/alias
    // If there is a path alias with these arguments, generate a printer-friendly version for it
81
    $path = drupal_get_normal_path($path);
82
    $ret = preg_match('!^node/(.*)!i', $path, $matches);
jcnventura's avatar
jcnventura committed
83
    if ($ret == 1) {
84
      $path = $matches[1];
jcnventura's avatar
jcnventura committed
85 86
    }
  }
87
  $parts = explode('/', $path);
88
  if (is_numeric($parts[0]) && (count($parts) == 1)) {
89
    $print = _print_generate_node($path, $cid, $format, $teaser, $message);
jcnventura's avatar
jcnventura committed
90 91
  }
  else {
92
    $ret = preg_match('!^book/export/html/(.*)!i', $path, $matches);
jcnventura's avatar
jcnventura committed
93 94
    if ($ret == 1) {
      // This is a book PF page link, handle trough the book handling functions
95
      $print = _print_generate_book($matches[1], $format, $teaser, $message);
jcnventura's avatar
jcnventura committed
96 97 98
    }
    else {
      // If no content node was found, handle the page printing with the 'printable' engine
99
      $print = _print_generate_path($path, $format, $teaser, $message);
jcnventura's avatar
jcnventura committed
100 101 102 103 104 105 106
    }
  }

  return $print;
}

/**
jcnventura's avatar
jcnventura committed
107
 * Generates a robots meta tag to tell them what they may index
jcnventura's avatar
jcnventura committed
108
 *
jcnventura's avatar
jcnventura committed
109
 * @return
jcnventura's avatar
jcnventura committed
110
 *   string with the meta robots tag
jcnventura's avatar
jcnventura committed
111 112
 */
function _print_robots_meta_generator() {
113 114 115
  $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
116 117
  $robots_meta = array();

118
  if (!empty($print_robots_noindex)) {
jcnventura's avatar
jcnventura committed
119 120
    $robots_meta[] = 'noindex';
  }
121
  if (!empty($print_robots_nofollow)) {
jcnventura's avatar
jcnventura committed
122 123
    $robots_meta[] = 'nofollow';
  }
124
  if (!empty($print_robots_noarchive)) {
jcnventura's avatar
jcnventura committed
125 126 127
    $robots_meta[] = 'noarchive';
  }

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

  return $robots_meta;
}

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

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

  // print module settings
158
  $print_css = variable_get('print_css', PRINT_CSS_DEFAULT);
159
  $print_logo_options = variable_get('print_logo_options', PRINT_LOGO_OPTIONS_DEFAULT);
160
  $print_logo_url = variable_get('print_logo_url', PRINT_LOGO_URL_DEFAULT);
161
  $print_html_new_window = variable_get('print_html_new_window', PRINT_HTML_NEW_WINDOW_DEFAULT);
162
  $print_html_sendtoprinter = variable_get('print_html_sendtoprinter', PRINT_HTML_SENDTOPRINTER_DEFAULT);
163
  $print_html_windowclose = variable_get('print_html_windowclose', PRINT_HTML_WINDOWCLOSE_DEFAULT);
164 165 166
  $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);
167 168
  $print_footer_options = variable_get('print_footer_options', PRINT_FOOTER_OPTIONS_DEFAULT);
  $print_footer_user = variable_get('print_footer_user', PRINT_FOOTER_USER_DEFAULT);
169 170

  $print['language'] = $language->language;
171
  $print['title'] = check_plain($node->title);
172 173 174 175
  $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
176 177
  $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
178

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

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

221 222
  $window_close = ($print_html_new_window && $print_html_windowclose) ? 'window.close();' : '';
  $print['sendtoprinter'] = $print_html_sendtoprinter ? " onload='window.print();$window_close'" : '';
jcnventura's avatar
jcnventura committed
223

224 225 226 227 228 229 230 231 232 233 234
  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;
  }
235
  $print['logo'] = $logo_url ? "<img class='print-logo' src='" . check_url($logo_url) . "' alt='' />\n" : '';
236

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

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

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

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

283 284
  if (isset($node->type)) {
    $node_type = $node->type;
285

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

291
      $print_text_created = filter_xss(variable_get('print_text_created', t('Created %date')));
292
      $created_datetime = format_date($node->created, 'small');
293
      $print['created'] = t($print_text_created, array('%date' => $created_datetime));
294 295
    }
    else {
296 297
      $print['submitted'] = '';
      $print['created'] = '';
298
    }
299

300
    $print['type'] = $node->type;
301 302
  }
  else {
303 304 305
    $print['submitted'] = '';
    $print['created'] = '';
    $print['type'] = '';
306
  }
307

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

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

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

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

  return $print;
}

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

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

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

375
      if (strpos($url, '://') || preg_match('!^mailto:.*?@.*?\..*?$!iu', $url)) {
jcnventura's avatar
jcnventura committed
376 377 378 379
        // URL is absolute, do nothing
        $newurl = urldecode($url);
      }
      else {
380
        if ($url[0] == '#') {
jcnventura's avatar
jcnventura committed
381
          // URL is an anchor tag
382
          if (!empty($_print_urls)) {
383 384 385
            $path = explode('/', $_GET['q']);
            unset($path[0]);
            $path = implode('/', $path);
jcnventura's avatar
jcnventura committed
386 387 388 389 390 391 392 393 394 395 396 397
            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
398
          if ($url[0] == '/') {
jcnventura's avatar
jcnventura committed
399
            // If it starts with '/' just append it to the server name
jcnventura's avatar
jcnventura committed
400
            $newurl = $base_root . '/' . trim(urldecode($url), '/');
jcnventura's avatar
jcnventura committed
401
          }
402 403
          elseif (preg_match('!^(?:index.php)?\?q=!i', $url)) {
            // If it starts with ?q=, just prepend with the base URL
jcnventura's avatar
jcnventura committed
404
            $newurl = $base_url . '/' . trim(urldecode($url), '/');
jcnventura's avatar
jcnventura committed
405 406
          }
          else {
407
            $newurl = url(trim(urldecode($url), '/'), array('absolute' => TRUE));
jcnventura's avatar
jcnventura committed
408
          }
409
          $matches[1] = str_replace($url, $newurl, $matches[1]);
jcnventura's avatar
jcnventura committed
410 411 412 413 414
        }
      }
    }
  }

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

  return $ret;
}

/**
 * Auxiliary function to store the Printer-friendly URLs list as static.
 *
jcnventura's avatar
jcnventura committed
429 430
 * @param $url
 *   absolute URL to be inserted in the list
jcnventura's avatar
jcnventura committed
431 432
 * @return
 *   list of URLs previously stored if $url is 0, or the current count
jcnventura's avatar
jcnventura committed
433
 *   otherwise.
jcnventura's avatar
jcnventura committed
434 435 436 437 438 439 440 441 442 443 444 445 446
 */
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
447 448 449
  $ret = $urls;
  $urls = array();
  return $ret;
jcnventura's avatar
jcnventura committed
450 451 452
}

/**
jcnventura's avatar
jcnventura committed
453
 * Choose most appropriate template
jcnventura's avatar
jcnventura committed
454
 *
jcnventura's avatar
jcnventura committed
455 456 457 458
 * 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.
 *
459 460
 * @param format
 *   format of the PF page being rendered (html, pdf, etc.)
jcnventura's avatar
jcnventura committed
461 462 463 464
 * @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
465
 */
466 467 468 469 470 471 472 473 474 475 476 477 478 479 480
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
481
  $filenames[] = 'print.tpl.php';
482 483

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

497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514
/**
 * 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
515
      $fmt = $format . '_';
516 517 518
      break;
    case PRINT_PDF_FORMAT:
      $node_urllist = isset($node->print_pdf_display_urllist) ? $node->print_pdf_display_urllist : TRUE;
jcnventura's avatar
jcnventura committed
519
      $fmt = $format . '_';
520 521 522 523 524 525
      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) &&
526
          (isset($node->type) ? variable_get('print_' . $fmt . 'display_urllist_' . $node->type, PRINT_TYPE_URLLIST_DEFAULT) : PRINT_TYPE_URLLIST_DEFAULT));
527 528
}

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

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

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

565
  //use the proper build_mode
566
  $node->build_mode = 'print';
567

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

572 573 574 575 576
  // Make this page a member of the original page's organic group
  if (function_exists('og_set_group_context') && isset($node->og_groups)) {
    og_set_group_context($node->og_groups);
  }

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

588
    $content = drupal_render($node->content);
589 590 591 592

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

593 594 595 596 597 598 599 600
    if ($teaser) {
      $node->teaser = $content;
      unset($node->body);
    }
    else {
      $node->body = $content;
      unset($node->teaser);
    }
jcnventura's avatar
jcnventura committed
601 602
  }

603
  $print_comments = variable_get('print_comments', PRINT_COMMENTS_DEFAULT);
jcnventura's avatar
jcnventura committed
604

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

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

629
  module_invoke_all('node_alter', $node, $teaser, TRUE);
jcnventura's avatar
jcnventura committed
630

631 632 633 634 635 636 637 638
  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
639
  // Convert the a href elements
640 641
  $pattern = '!<(a\s[^>]*?)>(.*?)(</a>)!is';
  $node->body = preg_replace_callback($pattern, '_print_rewrite_urls', $node->body);
jcnventura's avatar
jcnventura committed
642 643 644

  init_theme();

645
  $print = _print_var_generator($node, $message, $cid);
jcnventura's avatar
jcnventura committed
646 647 648 649 650

  return $print;
}

/**
jcnventura's avatar
jcnventura committed
651
 * Prepare a Printer-friendly-ready node body for non-content pages
jcnventura's avatar
jcnventura committed
652
 *
jcnventura's avatar
jcnventura committed
653 654
 * @param $path
 *   path of the node to be rendered into a printer-friendly page
655 656
 * @param $format
 *   format of the page being generated
657 658 659 660
 * @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
661 662
 * @return
 *   filled array ready to be used in the template
jcnventura's avatar
jcnventura committed
663
 */
664 665 666
function _print_generate_path($path, $format = PRINT_HTML_FORMAT, $teaser = FALSE, $message = NULL) {
  global $_print_urls;

667 668 669 670 671 672
  // Handle node tabs
  $parts = explode('/', $path);
  if (is_numeric($parts[0]) && (count($parts) > 1)) {
    $path = 'node/' . $path;
  }

jcnventura's avatar
jcnventura committed
673 674 675 676 677 678 679 680 681
  $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);

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

685 686 687
  if (is_int($node->body)) {
    switch ($node->body) {
      case MENU_NOT_FOUND:
688
        drupal_not_found();
689
        return FALSE;
690 691
        break;
      case MENU_ACCESS_DENIED:
692
        drupal_access_denied();
693
        return FALSE;
694 695
        break;
    }
jcnventura's avatar
jcnventura committed
696 697
  }

698 699 700
  $node->title = drupal_get_title();
  $node->path = $path;

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

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

jcnventura's avatar
jcnventura committed
707
  // Convert the a href elements
708 709
  $pattern = '!<(a\s[^>]*?)>(.*?)(</a>)!is';
  $node->body = preg_replace_callback($pattern, '_print_rewrite_urls', $node->body);
jcnventura's avatar
jcnventura committed
710 711 712

  init_theme();

713
  $print = _print_var_generator($node, $message);
jcnventura's avatar
jcnventura committed
714 715 716 717 718 719

  return $print;
}


/**
jcnventura's avatar
jcnventura committed
720
 * Prepare a Printer-friendly-ready node body for book pages
jcnventura's avatar
jcnventura committed
721
 *
jcnventura's avatar
jcnventura committed
722 723
 * @param $nid
 *   node ID of the node to be rendered into a printer-friendly page
724 725
 * @param $format
 *   format of the page being generated
726 727 728 729
 * @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
730 731
 * @return
 *   filled array ready to be used in the template
jcnventura's avatar
jcnventura committed
732
 */
733 734 735
function _print_generate_book($nid, $format = PRINT_HTML_FORMAT, $teaser = FALSE, $message = NULL) {
  global $_print_urls;

736
  $node = node_load($nid);
737 738 739
  if (!$node) {
    // Node not found
    drupal_not_found();
740
    return FALSE;
741 742
  }
  elseif (!node_access('view', $node) || (!user_access('access printer-friendly version'))) {
jcnventura's avatar
jcnventura committed
743
    // Access is denied
744
    drupal_access_denied();
745
    return FALSE;
jcnventura's avatar
jcnventura committed
746 747 748 749 750
  }

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

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

jcnventura's avatar
jcnventura committed
754
  // Convert the a href elements
755 756
  $pattern = '!<(a\s[^>]*?)>(.*?)(</a>)!is';
  $node->body = preg_replace_callback($pattern, '_print_rewrite_urls', $node->body);
jcnventura's avatar
jcnventura committed
757 758 759

  init_theme();

760
  $print = _print_var_generator($node, $message);
jcnventura's avatar
jcnventura committed
761
  // The title is already displayed by the book_recurse, so avoid duplication
762
  $print['title'] = '';
jcnventura's avatar
jcnventura committed
763 764 765

  return $print;
}