Projet

Général

Profil

Paste
Télécharger (39 ko) Statistiques
| Branche: | Révision:

root / drupal7 / sites / all / modules / advanced_help / advanced_help.module @ d51f9c7d

1
<?php
2
/**
3
 * @file
4
 * Pluggable system to provide advanced help facilities for Drupal and modules.
5
 *
6
 * Modules utilizing this help system should create a 'help' directory in their
7
 * module. Inside that directory place MODULENAME.help.ini which will be
8
 * formatted like this:
9
 *
10
 * @code
11
 * [buses]
12
 * title = "How buses are tied into the system"
13
 * file = buses
14
 *
15
 * [TOPIC_ID]
16
 * title = "Title of topic"
17
 * file = filename of topic, without the .html extension
18
 * weight = the importance of the topic on the index page
19
 * parent = the optional topic parent to use in the breadcrumb.
20
 * Can be either topic or module%topic
21
 * @endcode
22
 *
23
 * All topics are addressed by the module that provides the topic, and the topic
24
 * id. Links may be embedded as in the following example:
25
 *
26
 * @code
27
 * $output .= theme('advanced_help_topic', array('module' => $module, 'topic' => $topic));
28
 * @endcode
29
 *
30
 * Link to other topics using <a href="topic:module/topic">. (Using
31
 * this format ensures the popup status remains consistent for all
32
 * links.)
33
 */
34

    
35
/**
36
 * Implements hook_help().
37
 */
38
function advanced_help_help($path, $arg) {
39
  if ($path == 'admin/help#advanced_help') {
40
    $output = '<p>' . t('This module provides extended help and documentation.') . '</p>';
41
    if (function_exists('advanced_help_hint_docs')) {
42
      $output .= '<p>' . advanced_help_hint_docs('advanced_help', 'https://www.drupal.org/docs/7/modules/advanced-help', TRUE) . '</p>';
43
    }
44
    else {
45
      $output .= t('If you install and enable the module <strong>!url</strong>, you will get more help for <strong>Advanced help</strong>.',
46
        array('!url' => l('Advanced help hint', 'https://www.drupal.org/project/advanced_help_hint')));
47
    }
48
    return $output;
49
  }
50
}
51

    
52
/**
53
 * Implements hook_admin_paths_alter().
54
 *
55
 * Force help pages for this module to be rendered in admin theme.
56
 */
57
function advanced_help_admin_paths_alter(&$paths) {
58
  $paths['help/advanced_help/*'] = TRUE;
59
}
60

    
61
/**
62
 * Implements hook_menu().
63
 *
64
 * Strings in hook_menu() should not be run through t().
65
 */
66
function advanced_help_menu() {
67
  $help_exists = module_exists('help') ? TRUE : FALSE;
68
  if ($help_exists) {
69
    // Add tabs to core Help page to access Advanced Help.
70
    $items['admin/help/tab1'] = array(
71
      'title' => 'Help',
72
      'type' => MENU_DEFAULT_LOCAL_TASK,
73
      'weight' => 0,
74
    );
75

    
76
    $items['admin/help/ah'] = array(
77
      'title' => 'Advanced Help',
78
      'page callback' => 'advanced_help_index_page',
79
      'access arguments' => array('view advanced help index'),
80
      'type' => MENU_LOCAL_TASK,
81
      'weight' => 2,
82
    );
83
  }
84
  else {
85
    // Make Advanced Help the normal help.
86
    $items['admin/help/ah'] = array(
87
      'title' => 'Help',
88
      'page callback' => 'advanced_help_index_page',
89
      'access arguments' => array('view advanced help index'),
90
      'type' => MENU_NORMAL_ITEM,
91
      'weight' => 9,
92
    );
93
  }
94
  $items['help/ah/search/%'] = array(
95
    'title' => 'Search help',
96
    'page callback' => 'advanced_help_search_view',
97
    'page arguments' => array('advanced_help'),
98
    'access arguments' => array('view advanced help index'),
99
  );
100

    
101
  // View help topic.
102
  $items['help/%/%'] = array(
103
    'page callback' => 'advanced_help_topic_page',
104
    'page arguments' => array(1, 2),
105
    'access arguments' => array('view advanced help topic'),
106
    'type' => MENU_CALLBACK,
107
  );
108

    
109
  return $items;
110
}
111

    
112
/**
113
 * Implements hook_menu_alter().
114
 */
115
function advanced_help_menu_alter(&$callbacks) {
116
  // We need to fix the menu item provided by search module to restrict access.
117
  $callbacks['search/advanced_help/%menu_tail']['access callback'] = 'user_access';
118
  $callbacks['search/advanced_help/%menu_tail']['access arguments'] = array('view advanced help index');
119
}
120

    
121
/**
122
 * Implements hook_theme().
123
 */
124
function advanced_help_theme() {
125
  $hooks['advanced_help_topic'] = array(
126
    'variables' => array(
127
      'module' => NULL,
128
      'topic'  => NULL,
129
      'type'   => 'icon',
130
    ),
131
  );
132

    
133
  $hooks['advanced_help_popup'] = array(
134
    'render element' => 'content',
135
    'template' => 'advanced-help-popup',
136
  );
137

    
138
  return $hooks;
139
}
140

    
141
/**
142
 * Helper function to sort topics.
143
 */
144
function advanced_help_uasort($id_a, $id_b) {
145
  $topics = advanced_help_get_topics();
146
  list($module_a, $topic_a) = $id_a;
147
  $a = $topics[$module_a][$topic_a];
148
  list($module_b, $topic_b) = $id_b;
149
  $b = $topics[$module_b][$topic_b];
150

    
151
  $a_weight = isset($a['weight']) ? $a['weight'] : 0;
152
  $b_weight = isset($b['weight']) ? $b['weight'] : 0;
153
  if ($a_weight != $b_weight) {
154
    return ($a_weight < $b_weight) ? -1 : 1;
155
  }
156

    
157
  if ($a['title'] != $b['title']) {
158
    return ($a['title'] < $b['title']) ? -1 : 1;
159
  }
160
  return 0;
161
}
162

    
163
/**
164
 * Helper function for grabbing search keys. Function is missing in D7.
165
 *
166
 * http://api.drupal.org/api/function/search_get_keys/6
167
 */
168
function advanced_help_search_get_keys() {
169
  static $return;
170
  if (!isset($return)) {
171
    // Extract keys as remainder of path
172
    // Note: support old GET format of searches for existing links.
173
    $path = explode('/', $_GET['q'], 4);
174
    $keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
175
    $return = count($path) == 4 ? $path[3] : $keys;
176
  }
177
  return $return;
178
}
179

    
180
/**
181
 * Page callback for advanced help search.
182
 */
183
function advanced_help_search_view() {
184
  if (!module_exists('search')) {
185
    return drupal_not_found();
186
  }
187

    
188
  $breadcrumb[] = advanced_help_l(t('Advanced help'), 'admin/help/ah');
189

    
190
  if (!isset($_POST['form_id'])) {
191
    $keys = advanced_help_search_get_keys();
192
    // Only perform search if there is non-whitespace search term:
193
    $results = '';
194
    if (trim($keys)) {
195
      $search_results = search_data($keys, 'advanced_help');
196
      $search_results = drupal_render($search_results);
197
      // Collect the search results:
198
      $results = array(
199
        '#type' => 'markup',
200
        '#markup' => $search_results,
201
      );
202
    }
203

    
204
    // Construct the search form.
205
    $output['advanced_help_search_form'] = drupal_get_form('advanced_help_search_form', $keys);
206
    $output['results'] = $results;
207

    
208
  }
209
  else {
210
    $output = drupal_get_form('advanced_help_search_form', empty($keys) ? '' : $keys);
211
  }
212

    
213
  $popup = !empty($_GET['popup']) && user_access('view advanced help popup');
214
  if ($popup) {
215
    // Prevent devel module from spewing.
216
    $GLOBALS['devel_shutdown'] = FALSE;
217
    // Suppress admin_menu.
218
    module_invoke('admin_menu', 'suppress');
219
    drupal_set_breadcrumb(array_reverse($breadcrumb));
220
    print theme('advanced_help_popup', array('content' => $output));
221
    return;
222
  }
223

    
224
  $breadcrumb = array_merge(drupal_get_breadcrumb(), array_reverse($breadcrumb));
225
  drupal_set_breadcrumb($breadcrumb);
226
  return $output;
227
}
228

    
229
/**
230
 * Page callback to view the advanced help topic index.
231
 *
232
 * @param string $module
233
 *   Name of the module.
234
 *
235
 * @return array
236
 *   Returns module index.
237
 */
238
function advanced_help_index_page($module = '') {
239
  $topics = advanced_help_get_topics();
240
  $settings = advanced_help_get_settings();
241

    
242
  $output = array();
243
  // Print a search widget.
244
  $output['advanced_help_search'] = module_exists('search') ? drupal_get_form('advanced_help_search_form') : array('#markup' => t('Enable the search module to search help.'));
245

    
246
  $breadcrumb = array();
247
  if ($module) {
248
    if (empty($topics[$module])) {
249
      return drupal_not_found();
250
    }
251

    
252
    advanced_help_get_topic_hierarchy($topics);
253
    $items = advanced_help_get_tree($topics, $topics[$module]['']['children']);
254

    
255
    $breadcrumb[] = advanced_help_l(t('Advanced help'), 'admin/help/ah');
256

    
257
    drupal_set_title(t('@module help index', array('@module' => advanced_help_get_module_name($module))));
258
    $output['items-module'] = array(
259
      '#theme' => 'item_list',
260
      '#items' => $items,
261
    );
262
  }
263
  else {
264
    // Print a module index.
265
    $modules = array();
266
    $result = db_query('SELECT * FROM {system}');
267
    foreach ($result as $info) {
268
      $module_info = unserialize($info->info);
269
      $modules[$info->name] = isset($module_info['name']) ? $module_info['name'] : $info->name;
270
    }
271

    
272
    asort($modules);
273

    
274
    $items = array();
275
    foreach ($modules as $module => $module_name) {
276
      if (!empty($topics[$module]) && empty($settings[$module]['hide'])) {
277
        if (isset($settings[$module]['index name'])) {
278
          $name = $settings[$module]['index name'];
279
        }
280
        elseif (isset($settings[$module]['name'])) {
281
          $name = $settings[$module]['name'];
282
        }
283
        else {
284
          $name = t($module_name);
285
        }
286
        $items[] = advanced_help_l($name, "admin/help/ah/$module");
287
      }
288
    }
289

    
290
    drupal_set_title(t('Advanced help'));
291
    $output['items-nomodule'] = array(
292
      '#theme' => 'item_list',
293
      '#items' => $items,
294
    );
295
  }
296

    
297
  $popup = !empty($_GET['popup']) && user_access('view advanced help popup');
298
  if ($popup) {
299
    // Prevent devel module from spewing.
300
    $GLOBALS['devel_shutdown'] = FALSE;
301
    // Suppress admin_menu.
302
    module_invoke('admin_menu', 'suppress');
303
    drupal_set_breadcrumb(array_reverse($breadcrumb));
304
    print theme('advanced_help_popup', array('content' => $output));
305
    return;
306
  }
307

    
308
  $breadcrumb = array_merge(drupal_get_breadcrumb(), array_reverse($breadcrumb));
309
  drupal_set_breadcrumb($breadcrumb);
310
  return $output;
311
}
312

    
313
/**
314
 * Build a tree of advanced help topics.
315
 *
316
 * @param array $topics
317
 *   Topics.
318
 * @param array $topic_ids
319
 *   Topic Ids.
320
 * @param int $max_depth
321
 *   Maximum depth for subtopics.
322
 * @param int $depth
323
 *   Default depth for subtopics.
324
 *
325
 * @return array
326
 *   Returns list of topics/subtopics.
327
 */
328
function advanced_help_get_tree($topics, $topic_ids, $max_depth = -1, $depth = 0) {
329
  uasort($topic_ids, 'advanced_help_uasort');
330
  $items = array();
331
  foreach ($topic_ids as $info) {
332
    list($module, $topic) = $info;
333
    $item = advanced_help_l($topics[$module][$topic]['title'], "help/$module/$topic");
334
    if (!empty($topics[$module][$topic]['children']) && ($max_depth == -1 || $depth < $max_depth)) {
335
      $item .= theme('item_list', array(
336
        'items' => advanced_help_get_tree($topics, $topics[$module][$topic]['children'], $max_depth, $depth + 1),
337
      ));
338
    }
339

    
340
    $items[] = $item;
341
  }
342

    
343
  return $items;
344
}
345

    
346
/**
347
 * Build a hierarchy for a single module's topics.
348
 */
349
function advanced_help_get_topic_hierarchy(&$topics) {
350
  foreach ($topics as $module => $module_topics) {
351
    foreach ($module_topics as $topic => $info) {
352
      $parent_module = $module;
353
      // We have a blank topic that we don't want parented to itself.
354
      if (!$topic) {
355
        continue;
356
      }
357

    
358
      if (empty($info['parent'])) {
359
        $parent = '';
360
      }
361
      elseif (strpos($info['parent'], '%')) {
362
        list($parent_module, $parent) = explode('%', $info['parent']);
363
        if (empty($topics[$parent_module][$parent])) {
364
          // If it doesn't exist, top level.
365
          $parent = '';
366
        }
367
      }
368
      else {
369
        $parent = $info['parent'];
370
        if (empty($module_topics[$parent])) {
371
          // If it doesn't exist, top level.
372
          $parent = '';
373
        }
374
      }
375

    
376
      if (!isset($topics[$parent_module][$parent]['children'])) {
377
        $topics[$parent_module][$parent]['children'] = array();
378
      }
379
      $topics[$parent_module][$parent]['children'][] = array($module, $topic);
380
      $topics[$module][$topic]['_parent'] = array($parent_module, $parent);
381
    }
382
  }
383
}
384

    
385
/**
386
 * Implements hook_form_system_modules_alter().
387
 *
388
 * Add advanced help links to the modules page.
389
 */
390
function advanced_help_form_system_modules_alter(&$form, &$form_state) {
391
  if (!isset($form['modules'])) {
392
    return;
393
  }
394
  $advanced_help_modules = drupal_map_assoc(array_keys(advanced_help_get_topics()));
395
  foreach (element_children($form['modules']) as $group) {
396
    foreach (element_children($form['modules'][$group]) as $module) {
397
      if (isset($advanced_help_modules[$module])) {
398
        $form['modules'][$group][$module]['links']['help'] = array(
399
          '#type' => 'link',
400
          '#title' => t('Help'),
401
          '#href' => "admin/help/ah/$module",
402
          '#options' => array(
403
            'attributes' => array(
404
              'class' => array('module-link', 'module-link-help'),
405
              'title' => t('Help'),
406
            ),
407
          ),
408
        );
409
      }
410
    }
411
  }
412
}
413

    
414
/**
415
 * Form builder callback to build the search form.
416
 *
417
 * Load search/search.pages so that its template preprocess functions are
418
 * visible and can be invoked.
419
 */
420
function advanced_help_search_form($form, &$form_state, $keys = '') {
421
  module_load_include('inc', 'search', 'search.pages');
422
  $form = search_form($form, $form_state, 'admin/help/ah', $keys, 'advanced_help', t('Search help'));
423

    
424
  $form['basic']['inline']['submit']['#validate'] = array('search_form_validate');
425
  $form['basic']['inline']['submit']['#submit'] = array('advanced_help_search_form_submit');
426

    
427
  return $form;
428
}
429

    
430
/**
431
 * Process a search form submission.
432
 */
433
function advanced_help_search_form_submit($form, &$form_state) {
434
  $keys = empty($form_state['values']['processed_keys']) ? $form_state['values']['keys'] : $form_state['values']['processed_keys'];
435
  if ($keys == '') {
436
    form_set_error('keys', t('Please enter some keywords.'));
437
    return;
438
  }
439

    
440
  $popup = !empty($_GET['popup']) && user_access('view advanced help popup');
441

    
442
  if ($popup) {
443
    $form_state['redirect'] = array('help/ah/search/' . $keys, array('query' => array('popup' => 'true')));
444
  }
445
  else {
446
    $form_state['redirect'] = 'help/ah/search/' . $keys;
447
  }
448
}
449

    
450
/**
451
 * Small helper function to get a module's proper name.
452
 *
453
 * @param string $module
454
 *   Name of the module.
455
 *
456
 * @return string
457
 *   Returns module's descriptive name.
458
 */
459
function advanced_help_get_module_name($module) {
460
  $settings = advanced_help_get_settings();
461
  if (isset($settings[$module]['name'])) {
462
    $name = $settings[$module]['name'];
463
  }
464
  else {
465
    $info = db_query("SELECT s.info FROM {system} s WHERE s.name = :name",
466
      array(':name' => $module))
467
      ->fetchField();
468
    $info = unserialize($info);
469
    $name = t($info['name']);
470
  }
471
  return $name;
472
}
473

    
474
/**
475
 * Page callback to view a help topic.
476
 */
477
function advanced_help_topic_page($module, $topic) {
478
  if ('toc' == $topic) {
479
    return advanced_help_index_page($module);
480
  }
481
  $info = advanced_help_get_topic($module, $topic);
482
  if (!$info) {
483
    return drupal_not_found();
484
  }
485
  $popup = !empty($_GET['popup']) && user_access('view advanced help popup');
486

    
487
  drupal_set_title($info['title']);
488

    
489
  // Set up breadcrumb.
490
  $breadcrumb = array();
491

    
492
  $parent = $info;
493
  $pmodule = $module;
494

    
495
  // Loop checker.
496
  $checked = array();
497
  while (!empty($parent['parent'])) {
498
    if (strpos($parent['parent'], '%')) {
499
      list($pmodule, $ptopic) = explode('%', $parent['parent']);
500
    }
501
    else {
502
      $ptopic = $parent['parent'];
503
    }
504

    
505
    if (!empty($checked[$pmodule][$ptopic])) {
506
      break;
507
    }
508
    $checked[$pmodule][$ptopic] = TRUE;
509

    
510
    $parent = advanced_help_get_topic($pmodule, $ptopic);
511
    if (!$parent) {
512
      break;
513
    }
514

    
515
    $breadcrumb[] = advanced_help_l($parent['title'], "help/$pmodule/$ptopic");
516
  }
517

    
518
  $breadcrumb[] = advanced_help_l(advanced_help_get_module_name($pmodule), "admin/help/ah/$pmodule");
519
  $breadcrumb[] = advanced_help_l(t('Help'), "admin/help/ah");
520

    
521
  $output = advanced_help_view_topic($module, $topic, $popup);
522
  if (empty($output)) {
523
    $output = t('Missing help topic.');
524
  }
525

    
526
  if ($popup) {
527
    // Prevent devel module from spewing.
528
    $GLOBALS['devel_shutdown'] = FALSE;
529
    // Suppress admin_menu.
530
    module_invoke('admin_menu', 'suppress');
531
    drupal_set_breadcrumb(array_reverse($breadcrumb));
532
    print theme('advanced_help_popup', array('content' => $output));
533
    return;
534
  }
535

    
536
  drupal_add_css(drupal_get_path('module', 'advanced_help') . '/help.css');
537
  $breadcrumb[] = l(t('Home'), '');
538
  drupal_set_breadcrumb(array_reverse($breadcrumb));
539
  return $output;
540
}
541

    
542
/**
543
 * Implements hook_permission().
544
 */
545
function advanced_help_permission() {
546
  return array(
547
    'view advanced help topic' => array('title' => t('View help topics')),
548
    'view advanced help popup' => array('title' => t('View help popups')),
549
    'view advanced help index' => array('title' => t('View help index')),
550
  );
551
}
552

    
553
/**
554
 * Display a help icon with a link to view the topic in a popup.
555
 *
556
 * @param array $variables
557
 *   An associative array containing:
558
 *   - module: The module that owns this help topic.
559
 *   - topic: The identifier for the topic
560
 *   - type
561
 *     - 'icon' to display the question mark icon
562
 *     - 'title' to display the topic's title
563
 *     - any other text to display the text. Be sure to t() it!
564
 */
565
function theme_advanced_help_topic($variables) {
566
  $module = $variables['module'];
567
  $topic  = $variables['topic'];
568
  $type   = $variables['type'];
569

    
570
  if ('toc'  == $topic) {
571
    $info = array(
572
      'title' => 'Index page',
573
      'popup width' => 500,
574
      'popup height' => 500,
575
    );
576
  }
577
  else {
578
    $info = advanced_help_get_topic($module, $topic);
579
    if (!$info) {
580
      return;
581
    }
582
  }
583

    
584
  switch ($type) {
585
    case 'icon':
586
      $text = '<span>' . t('Help') . '</span>';
587
      $class = 'advanced-help-link';
588
      break;
589

    
590
    case 'title':
591
      $text = $info['title'];
592
      $class = 'advanced-help-title';
593
      break;
594

    
595
    default:
596
      $class = 'advanced-help-title';
597
      $text = $type;
598
      break;
599
  }
600

    
601
  if (user_access('view advanced help popup')) {
602
    drupal_add_css(drupal_get_path('module', 'advanced_help') . '/help-icon.css');
603
    return l($text, "help/$module/$topic", array(
604
      'attributes' => array(
605
        'class' => $class,
606
        'onclick' => "var w=window.open(this.href, 'advanced_help_window', 'width=" . $info['popup width'] . ",height=" . $info['popup height'] . ",scrollbars,resizable'); w.focus(); return false;",
607
        'title' => $info['title'],
608
      ),
609
      'query' => array('popup' => TRUE),
610
      'html' => TRUE)
611
    );
612
  }
613
  elseif (user_access('view advanced help topic')) {
614
    return l($text, "help/$module/$topic", array(
615
      'attributes' => array(
616
        'class' => $class,
617
        'title' => $info['title'],
618
      ),
619
      'html' => TRUE)
620
    );
621
  }
622
}
623

    
624
/**
625
 * Load and render a help topic.
626
 */
627
function advanced_help_get_topic_filename($module, $topic) {
628
  $info = advanced_help_get_topic_file_info($module, $topic);
629
  if ($info) {
630
    return "$info[path]/$info[file]";
631
  }
632
}
633

    
634
/**
635
 * Get the module type (theme or module).
636
 */
637
function _advanced_help_get_module_type($module) {
638
  $theme_list = array_keys(list_themes());
639
  $is_theme = in_array($module, $theme_list);
640
  return $is_theme ? 'theme' : 'module';
641
}
642

    
643
/**
644
 * Load and render a help topic.
645
 *
646
 * The strategy is first to see if a translated file for the current
647
 * active language exists.  If not found, look for the default.
648
 */
649
function advanced_help_get_topic_file_info($module, $topic) {
650
  global $language;
651

    
652
  $info = advanced_help_get_topic($module, $topic);
653
  if (empty($info)) {
654
    return;
655
  }
656

    
657
  // Search paths:
658
  $module_type = _advanced_help_get_module_type($module);
659
  $paths = array(
660
    // First see if a translation exists.
661
    drupal_get_path($module_type, $module) . "/translations/help/$language->language",
662
    // In same directory as .inc file.
663
    $info['path'],
664
  );
665

    
666
  foreach ($paths as $path) {
667
    if (file_exists("$path/$info[file]")) {
668
      return array('path' => $path, 'file' => $info['file']);
669
    }
670
  }
671
}
672

    
673
/**
674
 * Load and render a help topic.
675
 *
676
 * @param string $module
677
 *   Name of the module.
678
 * @param string $topic
679
 *   Name of the topic.
680
 * @param bool $popup
681
 *   Whether to show in popup or not.
682
 *
683
 * @return string
684
 *   Returns formatted topic.
685
 */
686
function advanced_help_view_topic($module, $topic, $popup = FALSE) {
687
  $file_info = advanced_help_get_topic_file_info($module, $topic);
688
  if ($file_info) {
689
    $info = advanced_help_get_topic($module, $topic);
690
    $file = "./$file_info[path]/$file_info[file]";
691

    
692
    // Fix invalid byte sequences (https://www.drupal.org/node/2659746).
693
    $output = file_get_contents($file);
694
    mb_substitute_character(0xfffd);
695
    $output = mb_convert_encoding($output, 'UTF-8', 'UTF-8');
696

    
697
    if (isset($info['readme file']) && $info['readme file']) {
698
      $ext = pathinfo($file, PATHINFO_EXTENSION);
699
      if ('md' == $ext && module_exists('markdown')) {
700
        $filters = module_invoke('markdown', 'filter_info');
701
        $md_info = $filters['filter_markdown'];
702
        if (function_exists($md_info['process callback'])) {
703
          $function = $md_info['process callback'];
704
          $output = '<div class="advanced-help-topic">' . filter_xss_admin($function($output, NULL)) . '</div>';
705
        }
706
        else {
707
          $output = '<div class="advanced-help-topic"><pre class="readme">' . check_plain($output) . '</pre></div>';
708
        }
709
      }
710
      else {
711
        $readme = '';
712
        if ('md' == $ext) {
713
          $readme .=
714
            '<p>' .
715
            t('If you install the !module module, the text below will be filtered by the module, producing rich text.',
716
              array(
717
                '!module' => l(t('Markdown filter'),
718
                  'https://www.drupal.org/project/markdown',
719
                  array('attributes' => array('title' => t('Link to project.'))))
720
              )) . '</p>';
721
        }
722
        $readme .=
723
          '<div class="advanced-help-topic"><pre class="readme">' . check_plain($output) . '</pre></div>';
724
        $output = $readme;
725
      }
726
      return $output;
727
    }
728

    
729
    // Make some exchanges. The strtr is because url() translates $ into %24
730
    // but we need to change it back for the regex replacement.
731
    //
732
    // Change 'topic:' to the URL for another help topic.
733
    if ($popup) {
734
      $output = preg_replace('/href="topic:([^"]+)"/', 'href="' . strtr(url('help/$1', array('query' => array('popup' => 'true'))), array('%24' => '$')) . '"', $output);
735
      $output = preg_replace('/src="topic:([^"]+)"/', 'src="' . strtr(url('help/$1', array('query' => array('popup' => 'true'))), array('%24' => '$')) . '"', $output);
736
      $output = preg_replace('/&topic:([^"]+)&/', strtr(url('help/$1', array('query' => array('popup' => 'true'))), array('%24' => '$')), $output);
737
    }
738
    else {
739
      $output = preg_replace('/href="topic:([^"]+)"/', 'href="' . strtr(url('help/$1'), array('%24' => '$')) . '"', $output);
740
      $output = preg_replace('/src="topic:([^"]+)"/', 'src="' . strtr(url('help/$1'), array('%24' => '$')) . '"', $output);
741
      $output = preg_replace('/&topic:([^"]+)&/', strtr(url('help/$1'), array('%24' => '$')), $output);
742
    }
743

    
744
    global $base_path;
745

    
746
    // Change 'path:' to the URL to the base help directory.
747
    $output = preg_replace('/href="path:([^"]+)"/', 'href="' . $base_path . $info['path'] . '/$1"', $output);
748
    $output = preg_replace('/src="path:([^"]+)"/', 'src="' . $base_path . $info['path'] . '/$1"', $output);
749
    $output = str_replace('&path&', $base_path . $info['path'] . '/', $output);
750

    
751
    // Change 'trans_path:' to the URL to the actual help directory.
752
    $output = preg_replace('/href="trans_path:([^"]+)"/', 'href="' . $base_path . $file_info['path'] . '/$1"', $output);
753
    $output = preg_replace('/src="trans_path:([^"]+)"/', 'src="' . $base_path . $file_info['path'] . '/$1"', $output);
754
    $output = str_replace('&trans_path&', $base_path . $file_info['path'] . '/', $output);
755

    
756
    // Change 'base_url:' to the URL to the site.
757
    $output = preg_replace('/href="base_url:([^"]+)"/', 'href="' . strtr(url('$1'), array('%24' => '$')) . '"', $output);
758
    $output = preg_replace('/src="base_url:([^"]+)"/', 'src="' . strtr(url('$1'), array('%24' => '$')) . '"', $output);
759
    $output = preg_replace('/&base_url&([^"]+)"/', strtr(url('$1'), array('%24' => '$')) . '"', $output);
760

    
761
    // Run the line break filter if requested.
762
    if (!empty($info['line break'])) {
763
      // Remove the header since it adds an extra <br /> to the filter.
764
      $output = preg_replace('/^<!--[^\n]*-->\n/', '', $output);
765

    
766
      $output = _filter_autop($output);
767
    }
768
    if (!empty($info['ini']['format'])) {
769
      $filter = $info['ini']['format'];
770
      if (filter_format_exists($filter)) {
771
        $output = check_markup($output, $filter);
772
      }
773
      else {
774
        drupal_set_message(t('Ini-file request non-existing format: “!format”.', array('!format' => $filter)), 'error');
775
      }
776
    }
777

    
778
    if (!empty($info['navigation'])) {
779
      $topics = advanced_help_get_topics();
780
      advanced_help_get_topic_hierarchy($topics);
781
      if (!empty($topics[$module][$topic]['children'])) {
782
        $items = advanced_help_get_tree($topics, $topics[$module][$topic]['children']);
783
        $output .= theme('item_list', array('items' => $items));
784
      }
785

    
786
      list($parent_module, $parent_topic) = $topics[$module][$topic]['_parent'];
787
      if ($parent_topic) {
788
        $parent = $topics[$module][$topic]['_parent'];
789
        $up = "help/$parent[0]/$parent[1]";
790
      }
791
      else {
792
        $up = "admin/help/ah/$module";
793
      }
794

    
795
      $siblings = $topics[$parent_module][$parent_topic]['children'];
796
      uasort($siblings, 'advanced_help_uasort');
797
      $prev = $next = NULL;
798
      $found = FALSE;
799
      foreach ($siblings as $sibling) {
800
        list($sibling_module, $sibling_topic) = $sibling;
801
        if ($found) {
802
          $next = $sibling;
803
          break;
804
        }
805
        if ($sibling_module == $module && $sibling_topic == $topic) {
806
          $found = TRUE;
807
          continue;
808
        }
809
        $prev = $sibling;
810
      }
811

    
812
      if ($prev || $up || $next) {
813
        $navigation = '<div class="help-navigation clear-block">';
814

    
815
        if ($prev) {
816
          $navigation .= advanced_help_l('«« ' . $topics[$prev[0]][$prev[1]]['title'], "help/$prev[0]/$prev[1]", array('attributes' => array('class' => 'help-left')));
817
        }
818
        if ($up) {
819
          $navigation .= advanced_help_l(t('Up'), $up, array('attributes' => array('class' => $prev ? 'help-up' : 'help-up-noleft')));
820
        }
821
        if ($next) {
822
          $navigation .= advanced_help_l($topics[$next[0]][$next[1]]['title'] . ' »»', "help/$next[0]/$next[1]", array('attributes' => array('class' => 'help-right')));
823
        }
824

    
825
        $navigation .= '</div>';
826

    
827
        $output .= $navigation;
828
      }
829
    }
830

    
831
    if (!empty($info['css'])) {
832
      drupal_add_css($info['path'] . '/' . $info['css']);
833
    }
834

    
835
    $output = '<div class="advanced-help-topic">' . $output . '</div>';
836
    drupal_alter('advanced_help_topic', $output, $popup);
837
    
838
    return $output;
839
  }
840
}
841

    
842
/**
843
 * Get the information for a single help topic.
844
 */
845
function advanced_help_get_topic($module, $topic) {
846
  $topics = advanced_help_get_topics();
847
  if (!empty($topics[$module][$topic])) {
848
    return $topics[$module][$topic];
849
  }
850
}
851

    
852
/**
853
 * Search the system for all available help topics.
854
 */
855
function advanced_help_get_topics() {
856
  $ini = _advanced_help_parse_ini();
857
  return $ini['topics'];
858
}
859

    
860
/**
861
 * Returns advanced help settings.
862
 */
863
function advanced_help_get_settings() {
864
  $ini = _advanced_help_parse_ini();
865
  return $ini['settings'];
866
}
867

    
868
/**
869
 * Function to parse ini / txt files.
870
 */
871
function _advanced_help_parse_ini() {
872
  global $language;
873
  static $ini = NULL;
874
  if (!isset($ini)) {
875
    $cache = cache_get('advanced_help_ini:' . $language->language);
876
    if ($cache) {
877
      $ini = $cache->data;
878
    }
879
  }
880
  if (!isset($ini)) {
881
    // No cached list of topics - create it.
882
    $ini = array('topics' => array(), 'settings' => array());
883

    
884
    foreach (array_merge(module_list(), list_themes()) as $plugin) {
885
      $module = is_string($plugin) ? $plugin : $plugin->name;
886
      $module_path = drupal_get_path(is_string($plugin) ? 'module' : 'theme', $module);
887

    
888
      // Parse ini-file if it exists
889
      if (file_exists("$module_path/help/$module.help.ini")) {
890
        $path_html = "$module_path/help";
891
        $info = parse_ini_file("./$module_path/help/$module.help.ini", TRUE);
892
        if (!$info) {
893
          drupal_set_message(t('There is a syntax error in the default .ini-file.  Unable to display topics.'), 'error');
894
        }
895
      }
896
      else {
897
        $info = array();
898
      }
899
      if (empty($info) || !empty($info['advanced help settings']['show readme'])) {
900
        // Look for one or more README files.
901
        $files = file_scan_directory("./$module_path",
902
          '/^(readme).*\.(txt|md)$/i', array('recurse' => FALSE));
903
        $path_readme = "$module_path";
904
        foreach ($files as $name => $fileinfo) {
905
          $info[$fileinfo->filename] = array(
906
            'line break' => TRUE,
907
            'readme file' => TRUE,
908
            'file' => $fileinfo->filename,
909
            'title' => $fileinfo->name,
910
            'weight' => -99,
911
          );
912
        }
913
      }
914

    
915
      if (!empty($info)) {
916
        // Get translated titles:
917
        $translation = array();
918
        if (file_exists("$module_path/translations/help/$language->language/$module.help.ini")) {
919
          $translation = parse_ini_file("$module_path/translations/help/$language->language/$module.help.ini", TRUE);
920
          if (!$translation) {
921
            drupal_set_message(t('There is a syntax error in the translated .ini-file.'), 'error');
922
          }
923
        }
924

    
925
        $ini['settings'][$module] = array();
926
        if (!empty($info['advanced help settings'])) {
927
          $ini['settings'][$module] = $info['advanced help settings'];
928
          unset($info['advanced help settings']);
929

    
930
          // Check translated strings for translatable global settings.
931
          if (isset($translation['advanced help settings']['name'])) {
932
            $ini['settings']['name'] = $translation['advanced help settings']['name'];
933
          }
934
          if (isset($translation['advanced help settings']['index name'])) {
935
            $ini['settings']['index name'] = $translation['advanced help settings']['index name'];
936
          }
937

    
938
        }
939

    
940
        foreach ($info as $name => $topic) {
941
          // Each topic should have a name, a title, a file and path.
942
          $file = !empty($topic['file']) ? $topic['file'] : $name;
943
          $ini['topics'][$module][$name] = array(
944
            'name' => $name,
945
            'module' => $module,
946
            'ini' => $topic,
947
            'title' => !empty($translation[$name]['title']) ? $translation[$name]['title'] : $topic['title'],
948
            'weight' => isset($topic['weight']) ? $topic['weight'] : 0,
949
            'parent' => isset($topic['parent']) ? $topic['parent'] : 0,
950
            'popup width' => isset($topic['popup width']) ? $topic['popup width'] : 500,
951
            'popup height' => isset($topic['popup height']) ? $topic['popup height'] : 500,
952
            // Require extension.
953
            'file' => isset($topic['readme file']) ? $file : $file . '.html',
954
            // Not in .ini file.
955
            'path' => isset($topic['readme file']) ? $path_readme : $path_html,
956
            'line break' => isset($topic['line break']) ? $topic['line break'] : (isset($ini['settings'][$module]['line break']) ? $ini['settings'][$module]['line break'] : FALSE),
957
            'navigation' => isset($topic['navigation']) ? $topic['navigation'] : (isset($ini['settings'][$module]['navigation']) ? $ini['settings'][$module]['navigation'] : TRUE),
958
            'show readme' => isset($topic['show readme']) ? $topic['show readme'] : (isset($ini['settings'][$module]['show readme']) ? $ini['settings'][$module]['show readme'] : FALSE),
959
            'css' => isset($topic['css']) ? $topic['css'] : (isset($ini['settings'][$module]['css']) ? $ini['settings'][$module]['css'] : NULL),
960
            'readme file' => isset($topic['readme file']) ? $topic['readme file'] : FALSE,
961
          );
962
        }
963
      }
964
    }
965
    drupal_alter('advanced_help_topic_info', $ini);
966

    
967
    cache_set('advanced_help_ini:' . $language->language, $ini);
968
  }
969
  return $ini;
970
}
971

    
972
/**
973
 * Implements hook_search_info().
974
 *
975
 * Returns title for the tab on search page & path component after 'search/'.
976
 */
977
function advanced_help_search_info() {
978
  return array(
979
    'title' => t('Help'),
980
    'path' => 'advanced_help',
981
  );
982
}
983

    
984
/**
985
 * Implements hook_search_execute().
986
 */
987
function advanced_help_search_execute($keys = NULL) {
988
  $topics = advanced_help_get_topics();
989

    
990
  $query = db_select('search_index', 'i', array('target' => 'slave'))
991
    ->extend('SearchQuery')
992
    ->extend('PagerDefault');
993
  $query->join('advanced_help_index', 'ahi', 'i.sid = ahi.sid');
994
  $query->searchExpression($keys, 'help');
995

    
996
  // Only continue if the first pass query matches.
997
  if (!$query->executeFirstPass()) {
998
    return array();
999
  }
1000

    
1001
  $results = array();
1002

    
1003
  $find = $query->execute();
1004
  foreach ($find as $item) {
1005
    $sids[] = $item->sid;
1006
  }
1007

    
1008
  $query = db_select('advanced_help_index', 'ahi');
1009
  $result = $query
1010
    ->fields('ahi')
1011
    ->condition('sid', $sids, 'IN')
1012
    ->execute();
1013

    
1014
  foreach ($result as $sid) {
1015
    // Guard against removed help topics that are still indexed.
1016
    if (empty($topics[$sid->module][$sid->topic])) {
1017
      continue;
1018
    }
1019
    $info = $topics[$sid->module][$sid->topic];
1020
    $text = advanced_help_view_topic($sid->module, $sid->topic);
1021
    $results[] = array(
1022
      'link' => advanced_help_url("help/$sid->module/$sid->topic"),
1023
      'title' => $info['title'],
1024
      'snippet' => search_excerpt($keys, $text),
1025
    );
1026
  }
1027
  return $results;
1028
}
1029

    
1030
/**
1031
 * Implements hook_search_reset().
1032
 */
1033
function advanced_help_search_reset() {
1034
  variable_del('advanced_help_last_cron');
1035
}
1036

    
1037
/**
1038
 * Implements hook_search_status().
1039
 */
1040
function advanced_help_search_status() {
1041
  $topics = advanced_help_get_topics();
1042
  $total = 0;
1043
  foreach ($topics as $module => $module_topics) {
1044
    foreach ($module_topics as $topic => $info) {
1045
      $file = advanced_help_get_topic_filename($module, $topic);
1046
      if ($file) {
1047
        $total++;
1048
      }
1049
    }
1050
  }
1051

    
1052
  $last_cron = variable_get('advanced_help_last_cron', array('time' => 0));
1053
  $indexed = 0;
1054
  if ($last_cron['time'] != 0) {
1055
    $indexed = db_query("SELECT COUNT(*) FROM {search_dataset} sd WHERE sd.type = 'help' AND sd.sid IS NOT NULL AND sd.reindex = 0")->fetchField();
1056
  }
1057
  return array('remaining' => $total - $indexed, 'total' => $total);
1058
}
1059

    
1060
/**
1061
 * Gets search id for each topic.
1062
 *
1063
 * Get or create an sid (search id) that correlates to each topic for
1064
 * the search system.
1065
 */
1066
function advanced_help_get_sids(&$topics) {
1067
  global $language;
1068
  $result = db_query("SELECT * FROM {advanced_help_index} WHERE language = :language",
1069
    array(':language' => $language->language));
1070
  foreach ($result as $sid) {
1071
    if (empty($topics[$sid->module][$sid->topic])) {
1072
      db_query("DELETE FROM {advanced_help_index} WHERE sid = :sid",
1073
        array(':sid' => $sid->sid));
1074
    }
1075
    else {
1076
      $topics[$sid->module][$sid->topic]['sid'] = $sid->sid;
1077
    }
1078
  }
1079
}
1080

    
1081
/**
1082
 * Implements hook_update_index().
1083
 */
1084
function advanced_help_update_index() {
1085
  global $language;
1086

    
1087
  // If we got interrupted by limit, this will contain the last module
1088
  // and topic we looked at.
1089
  $last = variable_get('advanced_help_last_cron', array('time' => 0));
1090
  $limit = intval(variable_get('search_cron_limit', 100));
1091
  $topics = advanced_help_get_topics();
1092
  advanced_help_get_sids($topics);
1093

    
1094
  $count = 0;
1095

    
1096
  foreach ($topics as $module => $module_topics) {
1097
    // Fast forward if necessary.
1098
    if (!empty($last['module']) && $last['module'] != $module) {
1099
      continue;
1100
    }
1101

    
1102
    foreach ($module_topics as $topic => $info) {
1103
      // Fast forward if necessary.
1104
      if (!empty($last['topic']) && $last['topic'] != $topic) {
1105
        continue;
1106
      }
1107

    
1108
      // If we've been looking to catch up, and we have, reset so we
1109
      // stop fast forwarding.
1110
      if (!empty($last['module'])) {
1111
        unset($last['topic']);
1112
        unset($last['module']);
1113
      }
1114

    
1115
      $file = advanced_help_get_topic_filename($module, $topic);
1116
      if ($file && (empty($info['sid']) || filemtime($file) > $last['time'])) {
1117
        if (empty($info['sid'])) {
1118
          $info['sid'] = db_insert('advanced_help_index')
1119
            ->fields(array(
1120
              'module' => $module,
1121
              'topic'  => $topic,
1122
              'language' => $language->language,
1123
            ))
1124
            ->execute();
1125
        }
1126

    
1127
        search_index($info['sid'], 'help', '<h1>' . $info['title'] . '</h1>' . file_get_contents($file));
1128
        $count++;
1129
        if ($count >= $limit) {
1130
          $last['topic'] = $topic;
1131
          $last['module'] = $module;
1132
          // Don't change time if we stop.
1133
          variable_set('advanced_help_last_cron', $last);
1134
          return;
1135
        }
1136
      }
1137
    }
1138
  }
1139

    
1140
  variable_set('advanced_help_last_cron', array('time' => time()));
1141
}
1142

    
1143
/**
1144
 * Fill in a bunch of page variables for our specialized popup page.
1145
 */
1146
function template_preprocess_advanced_help_popup(&$variables) {
1147
  // Add favicon.
1148
  if (theme_get_setting('toggle_favicon')) {
1149
    drupal_add_html_head('<link rel="shortcut icon" href="' . check_url(theme_get_setting('favicon')) . '" type="image/x-icon" />');
1150
  }
1151

    
1152
  global $theme;
1153
  // Construct page title.
1154
  if (drupal_get_title()) {
1155
    $head_title = array(
1156
      strip_tags(drupal_get_title()),
1157
      variable_get('site_name', 'Drupal'),
1158
    );
1159
  }
1160
  else {
1161
    $head_title = array(variable_get('site_name', 'Drupal'));
1162
    if (variable_get('site_slogan', '')) {
1163
      $head_title[] = variable_get('site_slogan', '');
1164
    }
1165
  }
1166

    
1167
  drupal_add_css(drupal_get_path('module', 'advanced_help') . '/help-popup.css');
1168
  drupal_add_css(drupal_get_path('module', 'advanced_help') . '/help.css');
1169

    
1170
  $variables['head_title']        = implode(' | ', $head_title);
1171
  $variables['base_path']         = base_path();
1172
  $variables['front_page']        = url();
1173
  $variables['breadcrumb']        = theme('breadcrumb', array('breadcrumb' => drupal_get_breadcrumb()));
1174
  $variables['feed_icons']        = drupal_get_feeds();
1175
  $variables['head']              = drupal_get_html_head();
1176
  $variables['language']          = $GLOBALS['language'];
1177
  $variables['language']->dir     = $GLOBALS['language']->direction ? 'rtl' : 'ltr';
1178
  $variables['logo']              = theme_get_setting('logo');
1179
  $variables['messages']          = theme('status_messages');
1180
  $variables['site_name']         = (theme_get_setting('toggle_name') ? variable_get('site_name', 'Drupal') : '');
1181
  $variables['css']               = drupal_add_css();
1182
  $css = drupal_add_css();
1183

    
1184
  // Remove theme css.
1185
  foreach ($css as $key => $value) {
1186
    if ($value['group'] == CSS_THEME) {
1187
      $exclude[$key] = FALSE;
1188
    }
1189
  }
1190
  $css = array_diff_key($css, $exclude);
1191

    
1192
  $variables['styles']            = drupal_get_css($css);
1193
  $variables['scripts']           = drupal_get_js();
1194
  $variables['title']             = drupal_get_title();
1195

    
1196
  // This function can be called either with a render array or
1197
  // an already rendered string.
1198
  if (is_array($variables['content'])) {
1199
    $variables['content'] = drupal_render($variables['content']);
1200
  }
1201
  // Closure should be filled last.
1202
  // There has never been a theme hook for closure (going back to
1203
  // first release 2008-04-17), so it is always 0 bytes.
1204
  // Unable to figure out its purpose - commenting out.
1205
  // $variables['closure'] = theme('closure');
1206
}
1207

    
1208
/**
1209
 * Format a link but preserve popup identity.
1210
 */
1211
function advanced_help_l($text, $dest, $options = array()) {
1212
  $popup = !empty($_GET['popup']) && user_access('view advanced help popup');
1213
  if ($popup) {
1214
    if (empty($options['query'])) {
1215
      $options['query'] = array();
1216
    }
1217

    
1218
    if (is_array($options['query'])) {
1219
      $options['query'] += array('popup' => TRUE);
1220
    }
1221
    else {
1222
      $options['query'] += '&popup=TRUE';
1223
    }
1224
  }
1225

    
1226
  return l($text, $dest, $options);
1227
}
1228

    
1229
/**
1230
 * Format a URL but preserve popup identity.
1231
 */
1232
function advanced_help_url($dest, $options = array()) {
1233
  $popup = !empty($_GET['popup']) && user_access('view advanced help popup');
1234
  if ($popup) {
1235
    if (empty($options['query'])) {
1236
      $options['query'] = array();
1237
    }
1238

    
1239
    $options['query'] += array('popup' => TRUE);
1240
  }
1241

    
1242
  return url($dest, $options);
1243
}