Projet

Général

Profil

Paste
Télécharger (32,8 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / print / print.module @ ba09eb79

1
<?php
2

    
3
/**
4
 * @defgroup print Printer, email and PDF versions
5
 *
6
 * Welcome to the print module developer's documentation. The interesting
7
 * functions for themers are those that start with 'theme_'.
8
 *
9
 * - Printer-friendly pages
10
 *   - @link print.module Module main file @endlink
11
 *   - @link print.admin.inc Settings form @endlink
12
 *   - @link print.pages.inc HTML generation @endlink
13
 *   - @link print.install (Un)Install routines @endlink
14
 *   - @link print.tpl.php Page generation template @endlink
15
 * - Send by email
16
 *   - @link print_mail.module Module main file @endlink
17
 *   - @link print_mail.admin.inc Settings form @endlink
18
 *   - @link print_mail.inc Mail form and send mail routine @endlink
19
 *   - @link print_mail.install (Un)Install routines @endlink
20
 * - PDF version
21
 *   - @link print_pdf.module Module main file @endlink
22
 *   - @link print_pdf.admin.inc Settings form @endlink
23
 *   - @link print_pdf.pages.inc PDF generation @endlink
24
 *   - @link print_pdf.class.inc Auxiliary PHP5 class @endlink
25
 *   - @link print_pdf.class_php4.inc Auxiliary PHP4 class @endlink
26
 *   - @link print_pdf.install (Un)Install routines @endlink
27
 */
28

    
29
/**
30
 * @file
31
 * Displays Printer-friendly versions of Drupal pages.
32
 *
33
 * This is the core module of the PF package, with the Drupal hooks
34
 * and other administrative functions.
35
 *
36
 * @ingroup print
37
 */
38

    
39
define('PRINT_PATH', 'print');
40

    
41
define('PRINT_HTML_FORMAT', 'html');
42
define('PRINT_MAIL_FORMAT', 'mail');
43
define('PRINT_PDF_FORMAT', 'pdf');
44
define('PRINT_LOGO_OPTIONS_DEFAULT', 1);
45
define('PRINT_LOGO_URL_DEFAULT', '');
46
define('PRINT_FOOTER_OPTIONS_DEFAULT', 1);
47
define('PRINT_FOOTER_USER_DEFAULT', '');
48
define('PRINT_CSS_DEFAULT', '');
49
define('PRINT_KEEP_THEME_CSS_DEFAULT', 0);
50
define('PRINT_URLS_DEFAULT', 1);
51
define('PRINT_URLS_ANCHORS_DEFAULT', 0);
52
define('PRINT_COMMENTS_DEFAULT', 0);
53
define('PRINT_NEWWINDOW_DEFAULT', 1);
54

    
55
define('PRINT_HTML_LINK_POS_DEFAULT', '{ "link": "link", "block": "block", "help": "help" }');
56
define('PRINT_HTML_LINK_TEASER_DEFAULT', 0);
57
define('PRINT_HTML_SHOW_LINK_DEFAULT', 1);
58
define('PRINT_HTML_NODE_LINK_VISIBILITY_DEFAULT', 0);
59
define('PRINT_HTML_NODE_LINK_PAGES_DEFAULT', '');
60
define('PRINT_HTML_LINK_CLASS_DEFAULT', 'print-page');
61
define('PRINT_HTML_SYS_LINK_VISIBILITY_DEFAULT', 1);
62
define('PRINT_HTML_SYS_LINK_PAGES_DEFAULT', '');
63
define('PRINT_HTML_LINK_USE_ALIAS_DEFAULT', 0);
64
define('PRINT_HTML_BOOK_LINK_DEFAULT', 1);
65
define('PRINT_HTML_NEW_WINDOW_DEFAULT', 0);
66
define('PRINT_HTML_SENDTOPRINTER_DEFAULT', 0);
67
define('PRINT_HTML_WINDOWCLOSE_DEFAULT', 1);
68

    
69
define('PRINT_SOURCEURL_ENABLED_DEFAULT', 1);
70
define('PRINT_SOURCEURL_DATE_DEFAULT', 0);
71
define('PRINT_SOURCEURL_FORCENODE_DEFAULT', 0);
72

    
73
define('PRINT_ROBOTS_NOINDEX_DEFAULT', 1);
74
define('PRINT_ROBOTS_NOFOLLOW_DEFAULT', 1);
75
define('PRINT_ROBOTS_NOARCHIVE_DEFAULT', 0);
76

    
77
define('PRINT_TYPE_SHOW_LINK_DEFAULT', 1);
78
define('PRINT_TYPE_COMMENT_LINK_DEFAULT', 0);
79
define('PRINT_TYPE_URLLIST_DEFAULT', 1);
80
define('PRINT_TYPE_SYS_URLLIST_DEFAULT', 0);
81

    
82
define('PRINT_ALLOW_NORMAL_LINK', 1);
83
define('PRINT_ALLOW_BOOK_LINK', 2);
84
define('PRINT_TYPE_FIELDS_WEIGHT', 30);
85

    
86
/**
87
 * Implements hook_permission().
88
 */
89
function print_permission() {
90
  return array(
91
    'administer print' => array(
92
      'title' => t('Administer the module'),
93
      'description' => t('Perform maintenance tasks for the print module.'),
94
    ),
95
    'node-specific print configuration' => array(
96
      'title' => t('Node-specific configuration'),
97
      'description' => t('Enable access to the per-node settings.'),
98
    ),
99
    'access print' => array(
100
      'title' => t('Access the printer-friendly page'),
101
      'description' => t('View the printer-friendly pages and the links to them in the original pages.'),
102
    ),
103
  );
104
}
105

    
106
/**
107
 * Implements hook_theme().
108
 */
109
function print_theme() {
110
  return array(
111
    'print_format_link' => array(
112
      'variables' => array(),
113
    ),
114
    'print' => array(
115
      'variables' => array('print' => array(), 'type' => PRINT_HTML_FORMAT, 'node' => NULL),
116
      'template' => 'print',
117
    ),
118
  );
119
}
120

    
121
/**
122
 * Implements hook_preprocess_HOOK().
123
 */
124
function print_preprocess_node(&$variables) {
125
  if (($variables['elements']['#view_mode'] == 'print') && isset($variables['elements']['#print_format'])) {
126
    $type = $variables['elements']['#node']->type;
127
    $format = $variables['elements']['#print_format'];
128
    $nid = $variables['elements']['#node']->nid;
129

    
130
    $variables['theme_hook_suggestions'][] = "node__print";
131
    $variables['theme_hook_suggestions'][] = "node__print__{$format}";
132
    $variables['theme_hook_suggestions'][] = "node__print__{$format}__node__{$type}";
133
    $variables['theme_hook_suggestions'][] = "node__print__{$format}__node__{$nid}";
134
  }
135
}
136

    
137
/**
138
 * Implements hook_preprocess_HOOK().
139
 */
140
function print_preprocess_print(&$variables) {
141
  static $hooks = NULL;
142
  if (!isset($hooks)) {
143
    drupal_theme_initialize();
144
    $hooks = theme_get_registry();
145
  }
146

    
147
  $variables['page']['#show_messages'] = FALSE;
148

    
149
  // Stolen from theme() so that ALL preprocess functions are called
150
  $hook = 'page';
151
  $info = $hooks[$hook];
152
  if (isset($info['preprocess functions']) || isset($info['process functions'])) {
153
    foreach (array('preprocess functions', 'process functions') as $phase) {
154
      if (!empty($info[$phase])) {
155
        foreach ($info[$phase] as $processor_function) {
156
          if (function_exists($processor_function)) {
157
            // We don't want a poorly behaved process function changing $hook.
158
            $hook_clone = $hook;
159
            $processor_function($variables, $hook_clone);
160
          }
161
        }
162
      }
163
    }
164
  }
165

    
166
  $format = $variables['type'];
167
  $type = (isset($variables['node']->type)) ? $variables['node']->type : '';
168
  $nid = (isset($variables['node']->nid)) ? $variables['node']->nid : '';
169

    
170
  $variables['theme_hook_suggestions'] = array();
171
  $variables['theme_hook_suggestions'][] = "print__node__{$type}";
172
  $variables['theme_hook_suggestions'][] = "print__node__{$type}__{$nid}";
173
  $variables['theme_hook_suggestions'][] = "print__{$format}";
174
  $variables['theme_hook_suggestions'][] = "print__{$format}__node__{$type}";
175
  $variables['theme_hook_suggestions'][] = "print__{$format}__node__{$type}__{$nid}";
176
}
177

    
178
/**
179
 * Implements hook_menu().
180
 */
181
function print_menu() {
182
  $items = array();
183

    
184
  $items[PRINT_PATH] = array(
185
    'title' => 'Printer-friendly',
186
    'page callback' => 'print_controller_html',
187
    'access arguments' => array('access print'),
188
    'type' => MENU_CALLBACK,
189
    'file' => 'print.pages.inc',
190
  );
191
  $items[PRINT_PATH . '/' . PRINT_PATH] = array(
192
    'access callback' => FALSE,
193
  );
194
  $items['admin/config/user-interface/print'] = array(
195
    'title' => 'Printer, email and PDF versions',
196
    'description' => 'Adds a printer-friendly version link to content and administrative pages.',
197
    'page callback' => 'drupal_get_form',
198
    'page arguments' => array('print_html_settings'),
199
    'access arguments'  => array('administer print'),
200
    'file' => 'print.admin.inc',
201
  );
202
  $items['admin/config/user-interface/print/html'] = array(
203
    'title' => 'Web page',
204
    'weight' => 1,
205
    'type' => MENU_DEFAULT_LOCAL_TASK,
206
  );
207
  $items['admin/config/user-interface/print/html/options'] = array(
208
    'title' => 'Options',
209
    'weight' => 1,
210
    'type' => MENU_DEFAULT_LOCAL_TASK,
211
  );
212
  $items['admin/config/user-interface/print/html/strings'] = array(
213
    'title' => 'Text strings',
214
    'description' => 'Override the user-facing strings used in the printer-friendly version.',
215
    'page callback' => 'drupal_get_form',
216
    'page arguments' => array('print_html_strings_settings'),
217
    'access arguments'  => array('administer print'),
218
    'weight' => 2,
219
    'type' => MENU_LOCAL_TASK,
220
    'file' => 'print.admin.inc',
221
  );
222
  $items['admin/config/user-interface/print/common'] = array(
223
    'title' => 'Settings',
224
    'description' => 'Settings for the common functionalities for all the print sub-modules.',
225
    'page callback' => 'drupal_get_form',
226
    'page arguments' => array('print_main_settings'),
227
    'access arguments'  => array('administer print'),
228
    'weight' => 10,
229
    'type' => MENU_LOCAL_TASK,
230
    'file' => 'print.admin.inc',
231
  );
232
  $items['admin/config/user-interface/print/common/options'] = array(
233
    'title' => 'Options',
234
    'weight' => 1,
235
    'type' => MENU_DEFAULT_LOCAL_TASK,
236
  );
237
  $items['admin/config/user-interface/print/common/strings'] = array(
238
    'title' => 'Text strings',
239
    'description' => 'Override the user-facing strings used by the print module.',
240
    'page callback' => 'drupal_get_form',
241
    'page arguments' => array('print_main_strings_settings'),
242
    'access arguments'  => array('administer print'),
243
    'weight' => 2,
244
    'type' => MENU_LOCAL_TASK,
245
    'file' => 'print.admin.inc',
246
  );
247

    
248
  return $items;
249
}
250

    
251
/**
252
 * Implements hook_block_info().
253
 */
254
function print_block_info() {
255
      $block['print-links']['info'] = t('Printer, email and PDF versions');
256
      $block['print-links']['cache'] = DRUPAL_CACHE_PER_PAGE;
257
      $block['print-top']['info'] = t('Most printed');
258
      $block['print-top']['cache'] = DRUPAL_CACHE_GLOBAL;
259
      return $block;
260
}
261

    
262
/**
263
 * Implements hook_block_view().
264
 */
265
function print_block_view($delta = '') {
266
  $block = array();
267

    
268
  switch ($delta) {
269
    case 'print-links':
270
      $nid = preg_replace('!^node/!', '', $_GET['q']);
271
      if (ctype_digit($nid)) {
272
        $node = node_load($nid);
273
        if (!node_access('view', $node)) {
274
          // If the user doesn't have access to the node, don't show any links
275
          $block['content'] = '';
276
          return;
277
        }
278
      }
279
      else {
280
        $node = NULL;
281
      }
282
      $block['content'] = '';
283
      foreach (array('html' => 'print', 'mail' => 'print_mail', 'pdf' => 'print_pdf') as $format => $module) {
284
        $link_pos = variable_get('print_' . $format . '_link_pos', drupal_json_decode(PRINT_HTML_LINK_POS_DEFAULT));
285

    
286
        if (!(empty($link_pos['block']))) {
287
          $func = $module . '_insert_link';
288

    
289
          if (function_exists($func)) {
290
            $links = $func(NULL, $node);
291
            if (!empty($links)) {
292
              $block['content'] .= $links;
293
            }
294
          }
295
        }
296
      }
297
      break;
298
    case 'print-top':
299
      $block['subject'] = t('Most printed');
300
      $result = db_query_range("SELECT path FROM {print_page_counter} LEFT JOIN {node} n ON path = CONCAT('node/', n.nid) WHERE status <> 0 OR status IS NULL ORDER BY totalcount DESC", 0, 3)
301
                  ->fetchAll();
302
      if (count($result)) {
303
        $block['content'] = '<div class="item-list"><ul>';
304
        foreach ($result as $obj) {
305
          $block['content'] .= '<li>' . l(_print_get_title($obj->path), $obj->path) . '</li>';
306
        }
307
        $block['content'] .= '</ul></div>';
308
      }
309
      break;
310
  }
311
  return $block;
312
}
313

    
314
/**
315
 * Implements hook_node_view_alter().
316
 */
317
function print_node_view_alter(&$build) {
318
  if (isset($build['links']['book']['#links']['book_printer'])) {
319
    $print_html_book_link = variable_get('print_html_book_link', PRINT_HTML_BOOK_LINK_DEFAULT);
320

    
321
    if ($print_html_book_link) {
322
      $print_html_link_pos = variable_get('print_html_link_pos', drupal_json_decode(PRINT_HTML_LINK_POS_DEFAULT));
323

    
324
      if (!empty($print_html_link_pos['link'])) {
325
        $format = theme('print_format_link');
326

    
327
        switch ($print_html_book_link) {
328
          case 1:
329
            $path = $build['links']['book']['#links']['book_printer']['href'];
330
            break;
331
          case 2:
332
            $print_html_link_use_alias = variable_get('print_html_link_use_alias', PRINT_HTML_LINK_USE_ALIAS_DEFAULT);
333
            $path = ($print_html_link_use_alias && ($alias = drupal_lookup_path('alias', 'node/' . $build['#node']->nid))) ? $alias : $build['#node']->nid;
334
            break;
335
        }
336

    
337
        $build['links']['book']['#links']['book_printer'] = array(
338
          'href' => PRINT_PATH . '/' . $path,
339
          'title' => $format['text'],
340
          'attributes' => $format['attributes'],
341
          'html' => $format['html'],
342
        );
343
      }
344
      else {
345
        unset($build['links']['book']['#links']['book_printer']);
346
      }
347
    }
348
  }
349
}
350

    
351
/**
352
 * Implements hook_help().
353
 */
354
function print_help($path, $arg) {
355
  switch ($path) {
356
    case 'admin/help#print':
357
      // Return a line-break version of the module README
358
      return _filter_autop(file_get_contents(drupal_get_path('module', 'print') . '/README.txt'));
359
  }
360

    
361
  $print_html_link_pos = variable_get('print_html_link_pos', drupal_json_decode(PRINT_HTML_LINK_POS_DEFAULT));
362
  if (($path !== 'node/%') && !(empty($print_html_link_pos['help']))) {
363
    static $output = FALSE;
364

    
365
    if ($output === FALSE) {
366
      $output = TRUE;
367

    
368
      $link = print_insert_link();
369
      if ($link) {
370
        return "<span class='print-syslink'>$link</span>";
371
      }
372
    }
373
  }
374
}
375

    
376
/**
377
 * Implements hook_node_view().
378
 */
379
function print_node_view($node, $view_mode) {
380
  $print_html_link_pos = variable_get('print_html_link_pos', drupal_json_decode(PRINT_HTML_LINK_POS_DEFAULT));
381
  $print_html_link_use_alias = variable_get('print_html_link_use_alias', PRINT_HTML_LINK_USE_ALIAS_DEFAULT);
382

    
383
  foreach (array('node', 'comment') as $type) {
384
    $allowed_type = print_link_allowed(array('type' => $type, 'node' => $node, 'view_mode' => $view_mode));
385
    if (($allowed_type === PRINT_ALLOW_NORMAL_LINK) && !isset($node->book) && !empty($print_html_link_pos['link'])) {
386
      drupal_add_css(drupal_get_path('module', 'print') . '/css/printlinks.css');
387
      $links = array();
388
      $format = theme('print_format_link');
389

    
390
      $path = (($print_html_link_use_alias) && ($alias = drupal_lookup_path('alias', 'node/' . $node->nid))) ? $alias : $node->nid;
391

    
392
      $links['print_html'] = array(
393
        'href' => PRINT_PATH . '/' . $path,
394
        'title' => $format['text'],
395
        'attributes' => $format['attributes'],
396
        'html' => $format['html'],
397
        'query' => print_query_string_encode($_GET, array('q')),
398
      );
399

    
400
      $link_content = array(
401
        '#theme' => 'links',
402
        '#links' => $links,
403
        '#attributes' => array('class' => array('links', 'inline')),
404
      );
405

    
406
      if ($type == 'node') {
407
        $node->content['links']['print_html'] = $link_content;
408
      }
409
      elseif (($type == 'comment') && isset($node->content['comments']['comments'])) {
410
        foreach ($node->content['comments']['comments'] as $cid => $comment) {
411
          if (is_numeric($cid)) {
412
            $link_content['#links']['print_html']['query']['comment'] = $cid;
413
            $node->content['comments']['comments'][$cid]['links']['print_html'] = $link_content;
414
          }
415
        }
416
      }
417
    }
418
  }
419

    
420
  if ($view_mode == 'full') {
421
      // Insert content corner links
422
      $node->content['print_links'] = array(
423
        '#prefix' => '<span class="print-link">',
424
        '#markup' => '',
425
        '#suffix' => '</span>',
426
        '#weight' => -101,
427
      );
428
      if (!empty($print_html_link_pos['corner'])) {
429
        $node->content['print_links']['#markup'] .= print_insert_link(NULL, $node);
430
      }
431
  }
432
}
433

    
434
/**
435
 * Implements hook_node_load().
436
 */
437
function print_node_load($nodes, $types) {
438
  $ids = array();
439
  foreach ($nodes as $node) {
440
    $ids[] = $node->nid;
441
  }
442

    
443
  $result = db_query('SELECT nid, link, comments, url_list FROM {print_node_conf} WHERE nid IN (:nids)', array(':nids' => $ids))->fetchAllAssoc('nid');
444

    
445
  foreach ($nodes as $node) {
446
    $node->print_display = isset($result[$node->nid]) ? intval($result[$node->nid]->link) : variable_get('print_display_' . $node->type, PRINT_TYPE_SHOW_LINK_DEFAULT);
447
    $node->print_display_comment = isset($result[$node->nid]) ? intval($result[$node->nid]->comments) : variable_get('print_display_comment_' . $node->type, PRINT_TYPE_COMMENT_LINK_DEFAULT);
448
    $node->print_display_urllist = isset($result[$node->nid]) ? intval($result[$node->nid]->url_list) : variable_get('print_display_urllist_' . $node->type, PRINT_TYPE_URLLIST_DEFAULT);
449
  }
450
}
451

    
452
/**
453
 * Implements hook_node_insert().
454
 */
455
function print_node_insert($node) {
456
  if (user_access('administer print') || user_access('node-specific print configuration')) {
457
    if (!isset($node->print_display)) $node->print_display = variable_get('print_display_' . $node->type, PRINT_TYPE_SHOW_LINK_DEFAULT);
458
    if (!isset($node->print_display_comment)) $node->print_display_comment = variable_get('print_display_comment_' . $node->type, PRINT_TYPE_COMMENT_LINK_DEFAULT);
459
    if (!isset($node->print_display_urllist)) $node->print_display_urllist = variable_get('print_display_urllist_' . $node->type, PRINT_TYPE_URLLIST_DEFAULT);
460

    
461
    _print_node_conf_modify($node->nid, $node->print_display, $node->print_display_comment, $node->print_display_urllist);
462
  }
463
}
464

    
465
/**
466
 * Implements hook_node_update().
467
 */
468
function print_node_update($node) {
469
  if (user_access('administer print') || user_access('node-specific print configuration')) {
470
    if (!isset($node->print_display) || $node->print_display === NULL) {
471
      $node->print_display = variable_get('print_display_' . $node->type, PRINT_TYPE_SHOW_LINK_DEFAULT);
472
    }
473
    if (!isset($node->print_display_comment) || $node->print_display_comment === NULL) {
474
      $node->print_display_comment = variable_get('print_display_comment_' . $node->type, PRINT_TYPE_COMMENT_LINK_DEFAULT);
475
    }
476
    if (!isset($node->print_display_urllist) || $node->print_display_urllist === NULL) {
477
      $node->print_display_urllist = variable_get('print_display_urllist_' . $node->type, PRINT_TYPE_URLLIST_DEFAULT);
478
    }
479

    
480
    _print_node_conf_modify($node->nid, $node->print_display, $node->print_display_comment, $node->print_display_urllist);
481
  }
482
}
483

    
484
/**
485
 * Implements hook_node_delete().
486
 */
487
function print_node_delete($node) {
488
  db_delete('print_node_conf')
489
    ->condition('nid', $node->nid)
490
    ->execute();
491
  db_delete('print_page_counter')
492
    ->condition('path', 'node/' . $node->nid)
493
    ->execute();
494
}
495

    
496
/**
497
 * Implements hook_form_alter().
498
 */
499
function print_form_alter(&$form, &$form_state, $form_id) {
500
  // Add the node-type settings option to activate the printer-friendly version link
501
  if ((user_access('administer print') || user_access('node-specific print configuration')) &&
502
      (($form_id == 'node_type_form') || !empty($form['#node_edit_form']))) {
503
    $form['print'] = array(
504
      '#type' => 'fieldset',
505
      '#title' => t('Printer, email and PDF versions'),
506
      '#collapsible' => TRUE,
507
      '#collapsed' => TRUE,
508
      '#weight' => PRINT_TYPE_FIELDS_WEIGHT,
509
      '#group' => 'additional_settings',
510
    );
511

    
512
    $form['print']['label'] = array(
513
      '#type' => 'markup',
514
      '#markup' => '<p><strong>' . t('Printer-friendly version') . '</strong></p>',
515
    );
516

    
517
    $form['print']['print_display'] = array(
518
      '#type' => 'checkbox',
519
      '#title' => t('Show link'),
520
    );
521
    $form['print']['print_display_comment'] = array(
522
      '#type' => 'checkbox',
523
      '#title' => t('Show link in individual comments'),
524
    );
525
    $form['print']['print_display_urllist'] = array(
526
      '#type' => 'checkbox',
527
      '#title' => t('Show Printer-friendly URLs list'),
528
    );
529

    
530
    if ($form_id == 'node_type_form') {
531
      $form['print']['print_display']['#default_value'] = variable_get('print_display_' . $form['#node_type']->type, PRINT_TYPE_SHOW_LINK_DEFAULT);
532
      $form['print']['print_display_comment']['#default_value'] = variable_get('print_display_comment_' . $form['#node_type']->type, PRINT_TYPE_COMMENT_LINK_DEFAULT);
533
      $form['print']['print_display_urllist']['#default_value'] = variable_get('print_display_urllist_' . $form['#node_type']->type, PRINT_TYPE_URLLIST_DEFAULT);
534
    }
535
    else {
536
      $node = $form['#node'];
537
      $form['print']['print_display']['#default_value'] = isset($node->print_display) ? $node->print_display : variable_get('print_display_' . $node->type, PRINT_TYPE_SHOW_LINK_DEFAULT);
538
      $form['print']['print_display_comment']['#default_value'] = isset($node->print_display_comment) ? $node->print_display_comment : variable_get('print_display_comment_' . $node->type, PRINT_TYPE_COMMENT_LINK_DEFAULT);
539
      $form['print']['print_display_urllist']['#default_value'] = isset($node->print_display_urllist) ? $node->print_display_urllist : variable_get('print_display_urllist_' . $node->type, PRINT_TYPE_URLLIST_DEFAULT);
540
    }
541
  }
542
}
543

    
544
/**
545
 * Implements hook_entity_info_alter().
546
 */
547
function print_entity_info_alter(&$info) {
548
  // Add the 'Print' view mode for nodes.
549
  $info['node']['view modes'] += array(
550
    'print' => array(
551
      'label' => t('Print'),
552
      'custom settings' => FALSE,
553
    ),
554
  );
555
}
556

    
557
/**
558
 * Auxiliary function to discover a given page's title
559
 *
560
 * @param $path
561
 *   path of the page being identified
562
 * @return
563
 *   string with the page's title
564
 */
565
function _print_get_title($path) {
566
  $path = drupal_get_normal_path($path);
567
  $nid = preg_replace('!^node/!', '', $path);
568
  if (ctype_digit($nid)) {
569
    return db_query("SELECT title FROM {node} WHERE nid = :nid", array(':nid' => $nid))
570
              ->fetchField();
571
  }
572
  else {
573
    // Not a node, try to get title from the menu system
574
    $menu_item = menu_get_item($path);
575
    if (!empty($menu_item['title'])) {
576
      return $menu_item['title'];
577
    }
578
    elseif (drupal_substr($menu_item['page_callback'], 0, 6) == 'views_') {
579
      // It's a view, load the view to have access to the title
580
      $view = views_get_view($menu_item['page_arguments']['0']);
581
      return $view->get_title();
582
    }
583
    else {
584
      return NULL;
585
    }
586
  }
587
}
588

    
589
/**
590
 * Modify the print_node_conf_table
591
 *
592
 * Update the print_node_conf table to reflect the given attributes.
593
 * If updating to the default values, delete the record.
594
 *
595
 * @param $nid
596
 *   value of the nid field (primary key)
597
 * @param $link
598
 *   value of the link field (0 or 1)
599
 * @param $comments
600
 *   value of the comments field (0 or 1)
601
 * @param $url_list
602
 *   value of the url_list field (0 or 1)
603
 */
604
function _print_node_conf_modify($nid, $link, $comments, $url_list) {
605
    db_merge('print_node_conf')
606
      ->key(array('nid' => $nid))
607
      ->fields(array(
608
        'link' => $link,
609
        'comments' => $comments,
610
        'url_list' => $url_list,
611
      ))
612
      ->execute();
613
}
614

    
615
/**
616
 * Auxiliary function to fill the Printer-friendly link attributes
617
 *
618
 * @param $title
619
 *   text to displayed by the link when hovering over it with the mouse
620
 * @param $class
621
 *   class attribute to be used in the link
622
 * @param $new_window
623
 *   if TRUE opens the target page in a new window
624
 * @return
625
 *   array of formatted attributes
626
 */
627
function print_fill_attributes($title = '', $class = '', $new_window = FALSE) {
628
  $print_newwindow = variable_get('print_newwindow', PRINT_NEWWINDOW_DEFAULT);
629
  $print_robots_noindex = variable_get('print_robots_noindex', PRINT_ROBOTS_NOINDEX_DEFAULT);
630

    
631
  $attributes = array();
632
  $attributes['title'] = $title;
633
  if (!empty($class)) {
634
    $attributes['class'] = array($class);
635
  }
636

    
637
  if ($new_window) {
638
    switch ($print_newwindow) {
639
    case 0:
640
      $attributes['target'] = '_blank';
641
      break;
642
    case 1:
643
      $attributes['onclick'] = 'window.open(this.href); return false';
644
      break;
645
    }
646
  }
647
  if (!empty($print_robots_noindex)) {
648
    $attributes['rel'] = 'nofollow';
649
  }
650
  return $attributes;
651
}
652

    
653
/**
654
 * Auxiliary function to set the link text and html flag
655
 *
656
 * @param $type
657
 *   type of link: 0 or 1 for a text-only link, 2 for icon-only and 3 for
658
 *   both text and icon
659
 * @param $text
660
 *   text to be displayed on the link to the printer-friendly page
661
 * @param $img
662
 *   path to the icon file
663
 * @return
664
 *   array with the link text and html flag
665
 */
666
function _print_format_link_aux($type = 0, $text = '', $img = '') {
667
  if ($type >= 2) {
668
    $html = TRUE;
669
    switch ($type) {
670
    case 2:
671
      $text = theme('image', array('path' => $img, 'alt' => $text, 'title' => $text, 'attributes' => array('class' => array('print-icon'))));
672
      break;
673
    case 3:
674
      $text = theme('image', array('path' => $img, 'alt' => $text, 'title' => $text, 'attributes' => array('class' => array('print-icon', 'print-icon-margin')))) . $text;
675
      break;
676
    }
677
  }
678
  else {
679
    $html = FALSE;
680
  }
681

    
682
  return array('text' => $text,
683
               'html' => $html,
684
              );
685
}
686

    
687
/**
688
 * Format the Printer-friendly link
689
 *
690
 * @return
691
 *   array of formatted attributes
692
 * @ingroup themeable
693
 */
694
function theme_print_format_link() {
695
  $print_html_link_class = variable_get('print_html_link_class', PRINT_HTML_LINK_CLASS_DEFAULT);
696
  $print_html_new_window = variable_get('print_html_new_window', PRINT_HTML_NEW_WINDOW_DEFAULT);
697
  $print_html_show_link = variable_get('print_html_show_link', PRINT_HTML_SHOW_LINK_DEFAULT);
698
  $print_html_link_text = filter_xss(variable_get('print_html_link_text', t('Printer-friendly version')));
699

    
700
  $img = drupal_get_path('module', 'print') . '/icons/print_icon.gif';
701
  $title = t('Display a printer-friendly version of this page.');
702
  $class = strip_tags($print_html_link_class);
703
  $new_window = $print_html_new_window;
704
  $format = _print_format_link_aux($print_html_show_link, $print_html_link_text, $img);
705

    
706
  return array('text' => $format['text'],
707
               'html' => $format['html'],
708
               'attributes' => print_fill_attributes($title, $class, $new_window),
709
              );
710
}
711

    
712
/**
713
 * Auxiliary function to display a formatted Printer-friendly link
714
 *
715
 * Function made available so that developers may call this function from
716
 * their defined pages/blocks.
717
 *
718
 * @param $path
719
 *   path of the original page (optional). If not specified, the current URL
720
 *   is used
721
 * @param $node
722
 *   an optional node object, to be used in defining the path, if used, the
723
 *   path argument is irrelevant
724
 * @return
725
 *   string with the HTML link to the printer-friendly page
726
 */
727
function print_insert_link($path = NULL, $node = NULL) {
728
  if ($node !== NULL) {
729
    $nid = $node->nid;
730
    $path = 'node/' . $nid;
731
    $allowed_type = print_link_allowed(array('node' => $node));
732
  }
733
  else {
734
    if ($path === NULL) {
735
      $nid = preg_replace('!^node/([\d]+)!', '$1', $_GET['q']);
736
      $path = $_GET['q'];
737
    }
738
    else {
739
      $nid = NULL;
740
    }
741
    $allowed_type = print_link_allowed(array('path' => $path));
742
  }
743

    
744
  if ($allowed_type) {
745
    if ($nid !== NULL) {
746
      if ($allowed_type === PRINT_ALLOW_BOOK_LINK) {
747
        $path = 'book/export/html/' . $nid;
748
      }
749
      else {
750
        if (variable_get('print_html_link_use_alias', PRINT_HTML_LINK_USE_ALIAS_DEFAULT) && ($alias = drupal_lookup_path('alias', $path))) {
751
          $path = $alias;
752
        }
753
        else {
754
          $path = $nid;
755
        }
756
      }
757
      $path = PRINT_PATH . '/' . $path;
758
      $query = print_query_string_encode($_GET, array('q'));
759
    }
760
    else {
761
      $query = NULL;
762
    }
763
    drupal_add_css(drupal_get_path('module', 'print') . '/css/printlinks.css');
764
    $format = theme('print_format_link');
765
    return '<span class="print_html">' . l($format['text'], $path, array('attributes' => $format['attributes'], 'query' => $query, 'absolute' => TRUE, 'html' => $format['html'])) . '</span>';
766
  }
767
  else {
768
    return FALSE;
769
  }
770
}
771

    
772
/**
773
 * Check if the provided page is enabled according to the visibility settings
774
 *
775
 * @param $visibility
776
 *   current visibility settings:
777
 *    0 for show on every page except the listed pages
778
 *    1 for show on only the listed pages
779
 * @param $pages
780
 *   list of pages
781
 * @return
782
 *   TRUE if it is enabled, FALSE otherwise
783
 */
784
function _print_page_match($visibility, $path, $pages) {
785
  if ($pages) {
786
    if ($visibility == 2) {
787
      if (module_exists('php')) {
788
        return php_eval($pages);
789
      }
790
      else {
791
        return FALSE;
792
      }
793
    }
794
    $alias = drupal_get_path_alias($path);
795
    $page_match = drupal_match_path($path, $pages);
796
    if ($alias != $path) {
797
      $page_match = $page_match || drupal_match_path($alias, $pages);
798
    }
799

    
800
    return !($visibility xor $page_match);
801
  }
802
  else {
803
    return !$visibility;
804
  }
805
}
806

    
807
/**
808
 * Check if the link to the PF version is allowed depending on the settings
809
 *
810
 * @param $args
811
 *   array containing the possible parameters:
812
 *    teaser, node, type, path
813
 * @return
814
 *   FALSE if not allowed
815
 *   PRINT_ALLOW_NORMAL_LINK if a normal link is allowed
816
 *   PRINT_ALLOW_BOOK_LINK if a link is allowed in a book node
817
 */
818
function print_link_allowed($args) {
819
  $view_mode = isset($args['view_mode']) ? $args['view_mode'] : '';
820
  if ((($view_mode == 'teaser') && !variable_get('print_html_link_teaser', PRINT_HTML_LINK_TEASER_DEFAULT))
821
      || !in_array($view_mode, array('full', 'teaser', '')) || !user_access('access print')) {
822
    // If the teaser link is disabled or the user is not allowed
823
    return FALSE;
824
  }
825
  if (!empty($args['path'])) {
826
    $nid = preg_replace('!^node/!', '', drupal_get_normal_path($args['path']));
827
    if (ctype_digit($nid)) {
828
      $args['node'] = node_load($nid);
829
    }
830
  }
831
  if (!empty($args['node'])) {
832
    static $node_type = '';
833

    
834
    $node = $args['node'];
835
    if (isset($node->type)) {
836
      $node_type = $node->type;
837
    }
838
    // Node
839
    $print_html_node_link_visibility = variable_get('print_html_node_link_visibility', PRINT_HTML_NODE_LINK_VISIBILITY_DEFAULT);
840
    $print_html_node_link_pages = variable_get('print_html_node_link_pages', PRINT_HTML_NODE_LINK_PAGES_DEFAULT);
841

    
842
    if (!_print_page_match($print_html_node_link_visibility, "node/" . $node->nid, $print_html_node_link_pages)) {
843
      // Page not in visibility list
844
      return FALSE;
845
    }
846
    elseif (isset($args['type']) && ($args['type'] == 'comment') && isset($node_type)) {
847
      // Link is for a comment, return the configured setting
848
      // Cache this statically to avoid duplicate queries for every comment.
849
      static $res = array();
850
      if (!isset($res[$node->nid])) {
851
        $res[$node->nid] = db_query("SELECT comments FROM {print_node_conf} WHERE nid = :nid", array(':nid' => $node->nid))->fetchField();
852
      }
853
      $print_display_comment = ($res && ($res[$node->nid] !== FALSE)) ? $res[$node->nid] : variable_get('print_display_comment_' . $node_type, PRINT_TYPE_COMMENT_LINK_DEFAULT);
854
      if ($print_display_comment) {
855
        return PRINT_ALLOW_NORMAL_LINK;
856
      }
857
    }
858
    else {
859
      // Node link
860
      if (isset($node->print_display) && !$node->print_display) {
861
        // Link for this node is disabled
862
        return FALSE;
863
      }
864
      elseif (isset($node->book)) {
865
        // Node is a book;
866
        $print_html_book_link = variable_get('print_html_book_link', PRINT_HTML_BOOK_LINK_DEFAULT);
867
        switch ($print_html_book_link) {
868
          case 1:
869
            if (user_access('access printer-friendly version')) {
870
              return PRINT_ALLOW_BOOK_LINK;
871
            }
872
            break;
873
          case 2:
874
            return PRINT_ALLOW_NORMAL_LINK;
875
        }
876
      }
877
      else {
878
        return PRINT_ALLOW_NORMAL_LINK;
879
      }
880
    }
881
  }
882
  else {
883
    // 'System' page
884
    $print_html_sys_link_visibility = variable_get('print_html_sys_link_visibility', PRINT_HTML_SYS_LINK_VISIBILITY_DEFAULT);
885
    $print_html_sys_link_pages = variable_get('print_html_sys_link_pages', PRINT_HTML_SYS_LINK_PAGES_DEFAULT);
886

    
887
    return _print_page_match($print_html_sys_link_visibility, $_GET['q'], $print_html_sys_link_pages);
888
  }
889
  return FALSE;
890
}
891

    
892
/**
893
 * Parse an array into a valid urlencoded query string.
894
 *
895
 * Modified from drupal_query_string_encode to prevent re-encoding of
896
 * encoded original. (see #301192)
897
 *
898
 * @param $query
899
 *   The array to be processed e.g. $_GET
900
 * @param $exclude
901
 *   The array filled with keys to be excluded.
902
 * @return
903
 *   urlencoded string which can be appended to/as the URL query string
904
 */
905
function print_query_string_encode($query, $exclude = array(), $parent = '') {
906
  $params = array();
907
  foreach ($query as $key => $value) {
908
    if (in_array($key, $exclude, TRUE)) {
909
      continue;
910
    }
911

    
912
    if (is_array($value)) {
913
      $params[$key] = print_query_string_encode($value, $exclude, $key);
914
    }
915
    else {
916
      $params[$key] = $value;
917
    }
918
  }
919

    
920
  return empty($params) ? NULL : $params;
921
}
922

    
923
/**
924
 * Implements hook_contextual_links_view_alter().
925
 */
926
function print_contextual_links_view_alter(&$element, $items) {
927
  // Hide all contextual links
928
  if (preg_match('!^print!', $_GET['q'])) {
929
    unset($element['#links']);
930
  }
931
}
932

    
933
/**
934
 * Callback function for the preg_replace_callback replacing spaces with %20
935
 *
936
 * Replace spaces in URLs with %20
937
 *
938
 * @param array $matches
939
 *   array with the matched tag patterns, usually <a...>+text+</a>
940
 *
941
 * @return string
942
 *   tag with re-written URL
943
 */
944
function _print_replace_spaces($matches) {
945
  // first, split the html into the different tag attributes
946
  $pattern = '!\s*(\w+\s*=\s*"(?:\\\"|[^"])*")\s*|\s*(\w+\s*=\s*\'(?:\\\\\'|[^\'])*\')\s*|\s*(\w+\s*=\s*\w+)\s*|\s+!';
947
  $attribs = preg_split($pattern, $matches[1], -1, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE);
948
  foreach ($attribs as $key => $value) {
949
    $attribs[$key] = preg_replace('!(\w)\s*=\s*(.*)!', '$1=$2', $value);
950
  }
951

    
952
  $size = count($attribs);
953
  for ($i=1; $i < $size; $i++) {
954
    // If the attribute is href or src, we may need to rewrite the URL in the value
955
    if (preg_match('!^(?:href|src)\s*?=(.*)!i', $attribs[$i], $urls) > 0) {
956
      $url = trim($urls[1], " \t\n\r\0\x0B\"'");
957
      $new_url = str_replace(' ', '%20', $url);
958
      $matches[1] = str_replace($url, $new_url, $matches[1]);
959
    }
960
  }
961

    
962
  $ret = '<' . $matches[1] . '>';
963
  if (count($matches) == 4) {
964
    $ret .= $matches[2] . $matches[3];
965
  }
966

    
967
  return $ret;
968
}
969

    
970
/**
971
 * Implements hook_views_api().
972
 */
973
function print_views_api() {
974
  return array(
975
    'api' => 2.0,
976
    'path' => drupal_get_path('module', 'print'),
977
  );
978
}