Projet

Général

Profil

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

root / htmltest / sites / all / modules / print / print.module @ dc45a079

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

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

    
287
          if (function_exists($func)) {
288
            $links = $func(NULL, $node);
289
            if (!empty($links)) {
290
              $block['content'] .= $links;
291
            }
292
          }
293
        }
294
      }
295
      break;
296
    case 'print-top':
297
      $block['subject'] = t('Most printed');
298
      $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)
299
                  ->fetchAll();
300
      if (count($result)) {
301
        $block['content'] = '<div class="item-list"><ul>';
302
        foreach ($result as $obj) {
303
          $block['content'] .= '<li>' . l(_print_get_title($obj->path), $obj->path) . '</li>';
304
        }
305
        $block['content'] .= '</ul></div>';
306
      }
307
      break;
308
  }
309
  return $block;
310
}
311

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

    
319
    if ($print_html_book_link) {
320
      $print_html_link_pos = variable_get('print_html_link_pos', drupal_json_decode(PRINT_HTML_LINK_POS_DEFAULT));
321

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

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

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

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

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

    
363
    if ($output === FALSE) {
364
      $output = TRUE;
365

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

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

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

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

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

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

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

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

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

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

    
443
  foreach ($nodes as $node) {
444
    $node->print_display = isset($result[$node->nid]) ? intval($result[$node->nid]->link) : variable_get('print_display_' . $node->type, PRINT_TYPE_SHOW_LINK_DEFAULT);
445
    $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);
446
    $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);
447
  }
448
}
449

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

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

    
463
/**
464
 * Implements hook_node_update().
465
 */
466
function print_node_update($node) {
467
  if (user_access('administer print') || user_access('node-specific print configuration')) {
468
    if (!isset($node->print_display)) $node->print_display = variable_get('print_display_' . $node->type, PRINT_TYPE_SHOW_LINK_DEFAULT);
469
    if (!isset($node->print_display_comment)) $node->print_display_comment = variable_get('print_display_comment_' . $node->type, PRINT_TYPE_COMMENT_LINK_DEFAULT);
470
    if (!isset($node->print_display_urllist)) $node->print_display_urllist = variable_get('print_display_urllist_' . $node->type, PRINT_TYPE_URLLIST_DEFAULT);
471

    
472
    _print_node_conf_modify($node->nid, $node->print_display, $node->print_display_comment, $node->print_display_urllist);
473
  }
474
}
475

    
476
/**
477
 * Implements hook_node_delete().
478
 */
479
function print_node_delete($node) {
480
  db_delete('print_node_conf')
481
    ->condition('nid', $node->nid)
482
    ->execute();
483
  db_delete('print_page_counter')
484
    ->condition('path', 'node/' . $node->nid)
485
    ->execute();
486
}
487

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

    
504
    $form['print']['label'] = array(
505
      '#type' => 'markup',
506
      '#markup' => '<p><strong>' . t('Printer-friendly version') . '</strong></p>',
507
    );
508

    
509
    $form['print']['print_display'] = array(
510
      '#type' => 'checkbox',
511
      '#title' => t('Show link'),
512
    );
513
    $form['print']['print_display_comment'] = array(
514
      '#type' => 'checkbox',
515
      '#title' => t('Show link in individual comments'),
516
    );
517
    $form['print']['print_display_urllist'] = array(
518
      '#type' => 'checkbox',
519
      '#title' => t('Show Printer-friendly URLs list'),
520
    );
521

    
522
    if ($form_id == 'node_type_form') {
523
      $form['print']['print_display']['#default_value'] = variable_get('print_display_' . $form['#node_type']->type, PRINT_TYPE_SHOW_LINK_DEFAULT);
524
      $form['print']['print_display_comment']['#default_value'] = variable_get('print_display_comment_' . $form['#node_type']->type, PRINT_TYPE_COMMENT_LINK_DEFAULT);
525
      $form['print']['print_display_urllist']['#default_value'] = variable_get('print_display_urllist_' . $form['#node_type']->type, PRINT_TYPE_URLLIST_DEFAULT);
526
    }
527
    else {
528
      $node = $form['#node'];
529
      $form['print']['print_display']['#default_value'] = isset($node->print_display) ? $node->print_display : variable_get('print_display_' . $node->type, PRINT_TYPE_SHOW_LINK_DEFAULT);
530
      $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);
531
      $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);
532
    }
533
  }
534
}
535

    
536
/**
537
 * Implements hook_entity_info_alter().
538
 */
539
function print_entity_info_alter(&$info) {
540
  // Add the 'Print' view mode for nodes.
541
  $info['node']['view modes'] += array(
542
    'print' => array(
543
      'label' => t('Print'),
544
      'custom settings' => FALSE,
545
    ),
546
  );
547
}
548

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

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

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

    
623
  $attributes = array();
624
  $attributes['title'] = $title;
625
  if (!empty($class)) {
626
    $attributes['class'] = array($class);
627
  }
628

    
629
  if ($new_window) {
630
    switch ($print_newwindow) {
631
    case 0:
632
      $attributes['target'] = '_blank';
633
      break;
634
    case 1:
635
      $attributes['onclick'] = 'window.open(this.href); return false';
636
      break;
637
    }
638
  }
639
  if (!empty($print_robots_noindex)) {
640
    $attributes['rel'] = 'nofollow';
641
  }
642
  return $attributes;
643
}
644

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

    
674
  return array('text' => $text,
675
               'html' => $html,
676
              );
677
}
678

    
679
/**
680
 * Format the Printer-friendly link
681
 *
682
 * @return
683
 *   array of formatted attributes
684
 * @ingroup themeable
685
 */
686
function theme_print_format_link() {
687
  $print_html_link_class = variable_get('print_html_link_class', PRINT_HTML_LINK_CLASS_DEFAULT);
688
  $print_html_new_window = variable_get('print_html_new_window', PRINT_HTML_NEW_WINDOW_DEFAULT);
689
  $print_html_show_link = variable_get('print_html_show_link', PRINT_HTML_SHOW_LINK_DEFAULT);
690
  $print_html_link_text = filter_xss(variable_get('print_html_link_text', t('Printer-friendly version')));
691

    
692
  $img = drupal_get_path('module', 'print') . '/icons/print_icon.gif';
693
  $title = t('Display a printer-friendly version of this page.');
694
  $class = strip_tags($print_html_link_class);
695
  $new_window = $print_html_new_window;
696
  $format = _print_format_link_aux($print_html_show_link, $print_html_link_text, $img);
697

    
698
  return array('text' => $format['text'],
699
               'html' => $format['html'],
700
               'attributes' => print_fill_attributes($title, $class, $new_window),
701
              );
702
}
703

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

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

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

    
792
    return !($visibility xor $page_match);
793
  }
794
  else {
795
    return !$visibility;
796
  }
797
}
798

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

    
826
    $node = $args['node'];
827
    if (isset($node->type)) {
828
      $node_type = $node->type;
829
    }
830
    // Node
831
    $print_html_node_link_visibility = variable_get('print_html_node_link_visibility', PRINT_HTML_NODE_LINK_VISIBILITY_DEFAULT);
832
    $print_html_node_link_pages = variable_get('print_html_node_link_pages', PRINT_HTML_NODE_LINK_PAGES_DEFAULT);
833

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

    
879
    return _print_page_match($print_html_sys_link_visibility, $_GET['q'], $print_html_sys_link_pages);
880
  }
881
  return FALSE;
882
}
883

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

    
904
    if (is_array($value)) {
905
      $params[$key] = print_query_string_encode($value, $exclude, $key);
906
    }
907
    else {
908
      $params[$key] = $value;
909
    }
910
  }
911

    
912
  return empty($params) ? NULL : $params;
913
}
914

    
915
/**
916
 * Implements hook_contextual_links_view_alter().
917
 */
918
function print_contextual_links_view_alter(&$element, $items) {
919
  // Hide all contextual links
920
  if (preg_match('!^print!', $_GET['q'])) {
921
    unset($element['#links']);
922
  }
923
}
924

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

    
944
  $size = count($attribs);
945
  for ($i=1; $i < $size; $i++) {
946
    // If the attribute is href or src, we may need to rewrite the URL in the value
947
    if (preg_match('!^(?:href|src)\s*?=(.*)!i', $attribs[$i], $urls) > 0) {
948
      $url = trim($urls[1], " \t\n\r\0\x0B\"'");
949
      $new_url = str_replace(' ', '%20', $url);
950
      $matches[1] = str_replace($url, $new_url, $matches[1]);
951
    }
952
  }
953

    
954
  $ret = '<' . $matches[1] . '>';
955
  if (count($matches) == 4) {
956
    $ret .= $matches[2] . $matches[3];
957
  }
958

    
959
  return $ret;
960
}
961

    
962
/**
963
 * Implements hook_views_api().
964
 */
965
function print_views_api() {
966
  return array(
967
    'api' => 2.0,
968
    'path' => drupal_get_path('module', 'print'),
969
  );
970
}