advanced_help.module 38.2 KB
Newer Older
1 2
<?php
/**
3
 * @file
4 5 6
 * Pluggable system to provide advanced help facilities for Drupal and modules.
 *
 * Modules utilizing this help system should create a 'help' directory in their
7 8
 * module. Inside that directory place MODULENAME.help.ini which will be
 * formatted like this:
9 10 11 12 13 14 15 16 17
 *
 * @code
 * [buses]
 * title = "How buses are tied into the system"
 * file = buses
 *
 * [TOPIC_ID]
 * title = "Title of topic"
 * file = filename of topic, without the .html extension
18
 * weight = the importance of the topic on the index page
19 20
 * parent = the optional topic parent to use in the breadcrumb.
 * Can be either topic or module%topic
21 22 23
 * @endcode
 *
 * 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 29
 * @endcode
 *
30 31 32
 * Link to other topics using <a href="topic:module/topic">. (Using
 * this format ensures the popup status remains consistent for all
 * links.)
33 34
 */

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

52
/**
53
 * Implements hook_menu().
54
 *
55
 * Strings in hook_menu() should not be run through t().
56 57
 */
function advanced_help_menu() {
58 59 60 61 62 63 64 65 66 67 68
  $help_exists = module_exists('help') ? TRUE : FALSE;
  if ($help_exists) {
    // Add tabs to core Help page to access Advanced Help.
    $items['admin/help/tab1'] = array(
      'title' => 'Help',
      'type' => MENU_DEFAULT_LOCAL_TASK,
      'weight' => 0,
    );

    $items['admin/help/ah'] = array(
      'title' => 'Advanced Help',
69 70
      'page callback' => 'advanced_help_index_page',
      'access arguments' => array('view advanced help index'),
71 72
      'type' => MENU_LOCAL_TASK,
      'weight' => 2,
73 74 75
    );
  }
  else {
76 77
    // Make Advanced Help the normal help.
    $items['admin/help/ah'] = array(
78 79 80
      'title' => 'Help',
      'page callback' => 'advanced_help_index_page',
      'access arguments' => array('view advanced help index'),
81
      'type' => MENU_NORMAL_ITEM,
82 83 84
      'weight' => 9,
    );
  }
85
  $items['help/ah/search/%'] = array(
86 87 88
    'title' => 'Search help',
    'page callback' => 'advanced_help_search_view',
    'page arguments' => array('advanced_help'),
merlinofchaos's avatar
merlinofchaos committed
89
    'access arguments' => array('view advanced help index'),
90 91
  );

92
  // View help topic.
93 94 95 96 97 98 99 100 101 102
  $items['help/%/%'] = array(
    'page callback' => 'advanced_help_topic_page',
    'page arguments' => array(1, 2),
    'access arguments' => array('view advanced help topic'),
    'type' => MENU_CALLBACK,
  );

  return $items;
}

103
/**
104 105
 * Implements hook_menu_alter().
 */
106 107 108 109 110 111
function advanced_help_menu_alter(&$callbacks) {
  // We need to fix the menu item provided by search module to restrict access.
  $callbacks['search/advanced_help/%menu_tail']['access callback'] = 'user_access';
  $callbacks['search/advanced_help/%menu_tail']['access arguments'] = array('view advanced help index');
}

112
/**
113
 * Implements hook_theme().
114 115 116
 */
function advanced_help_theme() {
  $hooks['advanced_help_topic'] = array(
117 118 119 120 121
    'variables' => array(
      'module' => NULL,
      'topic'  => NULL,
      'type'   => 'icon',
    ),
122 123 124
  );

  $hooks['advanced_help_popup'] = array(
fgm's avatar
fgm committed
125
    'render element' => 'content',
126 127 128 129 130 131
    'template' => 'advanced-help-popup',
  );

  return $hooks;
}

132 133 134
/**
 * Helper function to sort topics.
 */
135 136
function advanced_help_uasort($id_a, $id_b) {
  $topics = advanced_help_get_topics();
137 138 139 140
  list($module_a, $topic_a) = $id_a;
  $a = $topics[$module_a][$topic_a];
  list($module_b, $topic_b) = $id_b;
  $b = $topics[$module_b][$topic_b];
141 142 143 144 145 146 147 148 149 150 151 152 153

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

  if ($a['title'] != $b['title']) {
    return ($a['title'] < $b['title']) ? -1 : 1;
  }
  return 0;
}

154 155
/**
 * Helper function for grabbing search keys. Function is missing in D7.
156 157 158 159 160 161 162 163
 *
 * http://api.drupal.org/api/function/search_get_keys/6
 */
function advanced_help_search_get_keys() {
  static $return;
  if (!isset($return)) {
    // Extract keys as remainder of path
    // Note: support old GET format of searches for existing links.
164
    $path = explode('/', $_GET['q'], 4);
165
    $keys = empty($_REQUEST['keys']) ? '' : $_REQUEST['keys'];
166
    $return = count($path) == 4 ? $path[3] : $keys;
167 168 169 170
  }
  return $return;
}

171
/**
172
 * Page callback for advanced help search.
173 174 175
 */
function advanced_help_search_view() {
  if (!module_exists('search')) {
fgm's avatar
fgm committed
176
    return drupal_not_found();
177 178
  }

179
  $breadcrumb[] = advanced_help_l(t('Advanced help'), 'admin/help/ah');
180 181

  if (!isset($_POST['form_id'])) {
182
    $keys = advanced_help_search_get_keys();
183 184 185
    // Only perform search if there is non-whitespace search term:
    $results = '';
    if (trim($keys)) {
186 187
      $search_results = search_data($keys, 'advanced_help');
      $search_results = drupal_render($search_results);
188
      // Collect the search results:
fgm's avatar
fgm committed
189 190
      $results = array(
        '#type' => 'markup',
191
        '#markup' => $search_results,
fgm's avatar
fgm committed
192
      );
193 194 195
    }

    // Construct the search form.
fgm's avatar
fgm committed
196 197
    $output['advanced_help_search_form'] = drupal_get_form('advanced_help_search_form', $keys);
    $output['results'] = $results;
198 199 200 201 202 203 204 205

  }
  else {
    $output = drupal_get_form('advanced_help_search_form', empty($keys) ? '' : $keys);
  }

  $popup = !empty($_GET['popup']) && user_access('view advanced help popup');
  if ($popup) {
206 207 208 209
    // Prevent devel module from spewing.
    $GLOBALS['devel_shutdown'] = FALSE;
    // Suppress admin_menu.
    module_invoke('admin_menu', 'suppress');
210
    drupal_set_breadcrumb(array_reverse($breadcrumb));
fgm's avatar
fgm committed
211
    print theme('advanced_help_popup', array('content' => $output));
212 213 214 215
    return;
  }

  $breadcrumb = array_merge(drupal_get_breadcrumb(), array_reverse($breadcrumb));
216
  drupal_set_breadcrumb($breadcrumb);
217 218 219 220 221
  return $output;
}

/**
 * Page callback to view the advanced help topic index.
fgm's avatar
fgm committed
222 223
 *
 * @param string $module
224 225
 *   Name of the module.
 *
fgm's avatar
fgm committed
226
 * @return array
227
 *   Returns module index.
228 229 230
 */
function advanced_help_index_page($module = '') {
  $topics = advanced_help_get_topics();
231
  $settings = advanced_help_get_settings();
232

fgm's avatar
fgm committed
233
  $output = array();
234
  // Print a search widget.
235
  $output['advanced_help_search'] = module_exists('search') ? drupal_get_form('advanced_help_search_form') : array('#markup' => t('Enable the search module to search help.'));
236 237 238 239 240 241 242

  $breadcrumb = array();
  if ($module) {
    if (empty($topics[$module])) {
      return drupal_not_found();
    }

243 244
    advanced_help_get_topic_hierarchy($topics);
    $items = advanced_help_get_tree($topics, $topics[$module]['']['children']);
245

246
    $breadcrumb[] = advanced_help_l(t('Advanced help'), 'admin/help/ah');
247 248

    drupal_set_title(t('@module help index', array('@module' => advanced_help_get_module_name($module))));
fgm's avatar
fgm committed
249 250 251 252
    $output['items-module'] = array(
      '#theme' => 'item_list',
      '#items' => $items,
    );
253 254
  }
  else {
255
    // Print a module index.
256
    $modules = array();
fgm's avatar
fgm committed
257 258
    $result = db_query('SELECT * FROM {system}');
    foreach ($result as $info) {
259
      $module_info = unserialize($info->info);
260
      $modules[$info->name] = isset($module_info['name']) ? $module_info['name'] : $info->name;
261 262 263 264 265 266
    }

    asort($modules);

    $items = array();
    foreach ($modules as $module => $module_name) {
267
      if (!empty($topics[$module]) && empty($settings[$module]['hide'])) {
268 269 270 271 272 273 274
        if (isset($settings[$module]['index name'])) {
          $name = $settings[$module]['index name'];
        }
        elseif (isset($settings[$module]['name'])) {
          $name = $settings[$module]['name'];
        }
        else {
275
          $name = t($module_name);
276
        }
277
        $items[] = advanced_help_l($name, "admin/help/ah/$module");
278 279 280
      }
    }

281
    drupal_set_title(t('Advanced help'));
fgm's avatar
fgm committed
282 283 284 285
    $output['items-nomodule'] = array(
      '#theme' => 'item_list',
      '#items' => $items,
    );
286 287 288 289
  }

  $popup = !empty($_GET['popup']) && user_access('view advanced help popup');
  if ($popup) {
290 291 292 293
    // Prevent devel module from spewing.
    $GLOBALS['devel_shutdown'] = FALSE;
    // Suppress admin_menu.
    module_invoke('admin_menu', 'suppress');
294
    drupal_set_breadcrumb(array_reverse($breadcrumb));
fgm's avatar
fgm committed
295
    print theme('advanced_help_popup', array('content' => $output));
296 297 298 299 300 301 302 303
    return;
  }

  $breadcrumb = array_merge(drupal_get_breadcrumb(), array_reverse($breadcrumb));
  drupal_set_breadcrumb($breadcrumb);
  return $output;
}

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

    $items[] = $item;
  }

  return $items;
}
336

337
/**
338
 * Build a hierarchy for a single module's topics.
339 340
 */
function advanced_help_get_topic_hierarchy(&$topics) {
341 342 343
  foreach ($topics as $module => $module_topics) {
    foreach ($module_topics as $topic => $info) {
      $parent_module = $module;
fgm's avatar
fgm committed
344
      // We have a blank topic that we don't want parented to itself.
345 346 347
      if (!$topic) {
        continue;
      }
348

349
      if (empty($info['parent'])) {
350 351
        $parent = '';
      }
fgm's avatar
fgm committed
352
      elseif (strpos($info['parent'], '%')) {
353
        list($parent_module, $parent) = explode('%', $info['parent']);
354 355 356 357 358 359 360 361 362 363 364 365
        if (empty($topics[$parent_module][$parent])) {
          // If it doesn't exist, top level.
          $parent = '';
        }
      }
      else {
        $parent = $info['parent'];
        if (empty($module_topics[$parent])) {
          // If it doesn't exist, top level.
          $parent = '';
        }
      }
366

367 368 369 370 371
      if (!isset($topics[$parent_module][$parent]['children'])) {
        $topics[$parent_module][$parent]['children'] = array();
      }
      $topics[$parent_module][$parent]['children'][] = array($module, $topic);
      $topics[$module][$topic]['_parent'] = array($parent_module, $parent);
372 373 374 375
    }
  }
}

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

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

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

  return $form;
}

/**
 * Process a search form submission.
 */
function advanced_help_search_form_submit($form, &$form_state) {
425
  $keys = empty($form_state['values']['processed_keys']) ? $form_state['values']['keys'] : $form_state['values']['processed_keys'];
426 427 428 429 430 431 432 433
  if ($keys == '') {
    form_set_error('keys', t('Please enter some keywords.'));
    return;
  }

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

  if ($popup) {
434
    $form_state['redirect'] = array('help/ah/search/' . $keys, array('query' => array('popup' => 'true')));
435 436
  }
  else {
437
    $form_state['redirect'] = 'help/ah/search/' . $keys;
438 439 440 441 442
  }
}

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

/**
 * Page callback to view a help topic.
 */
function advanced_help_topic_page($module, $topic) {
  $info = advanced_help_get_topic($module, $topic);
  if (!$info) {
    return drupal_not_found();
  }

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

  drupal_set_title($info['title']);

478
  // Set up breadcrumb.
479 480 481 482 483
  $breadcrumb = array();

  $parent = $info;
  $pmodule = $module;

484
  // Loop checker.
485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506
  $checked = array();
  while (!empty($parent['parent'])) {
    if (strpos($parent['parent'], '%')) {
      list($pmodule, $ptopic) = explode('%', $parent['parent']);
    }
    else {
      $ptopic = $parent['parent'];
    }

    if (!empty($checked[$pmodule][$ptopic])) {
      break;
    }
    $checked[$pmodule][$ptopic] = TRUE;

    $parent = advanced_help_get_topic($pmodule, $ptopic);
    if (!$parent) {
      break;
    }

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

507 508
  $breadcrumb[] = advanced_help_l(advanced_help_get_module_name($pmodule), "admin/help/ah/$pmodule");
  $breadcrumb[] = advanced_help_l(t('Help'), "admin/help/ah");
509 510 511 512 513 514 515

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

  if ($popup) {
516 517 518 519
    // Prevent devel module from spewing.
    $GLOBALS['devel_shutdown'] = FALSE;
    // Suppress admin_menu.
    module_invoke('admin_menu', 'suppress');
520
    drupal_set_breadcrumb(array_reverse($breadcrumb));
fgm's avatar
fgm committed
521
    print theme('advanced_help_popup', array('content' => $output));
522 523 524
    return;
  }

525
  drupal_add_css(drupal_get_path('module', 'advanced_help') . '/help.css');
526
  $breadcrumb[] = l(t('Home'), '');
527 528 529 530 531
  drupal_set_breadcrumb(array_reverse($breadcrumb));
  return $output;
}

/**
532
 * Implements hook_permission().
533
 */
fgm's avatar
fgm committed
534 535 536 537 538 539
function advanced_help_permission() {
  return array(
    'view advanced help topic' => array('title' => t('View help topics')),
    'view advanced help popup' => array('title' => t('View help popups')),
    'view advanced help index' => array('title' => t('View help index')),
  );
540 541 542
}

/**
543
 * Display a help icon with a link to view the topic in a popup.
544
 *
545
 * @param array $variables
546 547 548 549 550 551 552
 *   An associative array containing:
 *   - module: The module that owns this help topic.
 *   - topic: The identifier for the topic
 *   - type
 *     - 'icon' to display the question mark icon
 *     - 'title' to display the topic's title
 *     - any other text to display the text. Be sure to t() it!
553
 */
554 555 556 557 558
function theme_advanced_help_topic($variables) {
  $module = $variables['module'];
  $topic  = $variables['topic'];
  $type   = $variables['type'];

559 560 561 562 563
  $info = advanced_help_get_topic($module, $topic);
  if (!$info) {
    return;
  }

564 565 566 567 568
  switch ($type) {
    case 'icon':
      $text = '<span>' . t('Help') . '</span>';
      $class = 'advanced-help-link';
      break;
fgm's avatar
fgm committed
569

570 571 572 573
    case 'title':
      $text = $info['title'];
      $class = 'advanced-help-title';
      break;
fgm's avatar
fgm committed
574

575 576 577 578 579 580
    default:
      $class = 'advanced-help-title';
      $text = $type;
      break;
  }

581
  if (user_access('view advanced help popup')) {
merlinofchaos's avatar
merlinofchaos committed
582
    drupal_add_css(drupal_get_path('module', 'advanced_help') . '/help-icon.css');
583
    return l($text, "help/$module/$topic", array(
584
      'attributes' => array(
585
        'class' => $class,
586
        'onclick' => "var w=window.open(this.href, 'advanced_help_window', 'width=" . $info['popup width'] . ",height=" . $info['popup height'] . ",scrollbars,resizable'); w.focus(); return false;",
587
        'title' => $info['title'],
588 589 590 591 592
      ),
      'query' => array('popup' => TRUE),
      'html' => TRUE)
    );
  }
593
  elseif (user_access('view advanced help topic')) {
594
    return l($text, "help/$module/$topic", array(
595
      'attributes' => array(
596
        'class' => $class,
597
        'title' => $info['title'],
598 599 600 601 602 603 604
      ),
      'html' => TRUE)
    );
  }
}

/**
605
 * Load and render a help topic.
606 607
 */
function advanced_help_get_topic_filename($module, $topic) {
608 609
  $info = advanced_help_get_topic_file_info($module, $topic);
  if ($info) {
610
    return "$info[path]/$info[file]";
611 612
  }
}
613 614 615 616 617 618 619 620 621 622

/**
 * Get the module type (theme or module).
 */
function _advanced_help_get_module_type($module) {
  $theme_list = array_keys(list_themes());
  $is_theme = in_array($module, $theme_list);
  return $is_theme ? 'theme' : 'module';
}

623 624
/**
 * Load and render a help topic.
625 626 627
 *
 * The strategy is first to see if a translated file for the current
 * active language exists.  If not found, look for the default.
628 629
 */
function advanced_help_get_topic_file_info($module, $topic) {
630 631 632 633 634 635 636
  global $language;

  $info = advanced_help_get_topic($module, $topic);
  if (empty($info)) {
    return;
  }

637
  // Search paths:
638
  $module_type = _advanced_help_get_module_type($module);
639
  $paths = array(
640
    // First see if a translation exists.
641
    drupal_get_path($module_type, $module) . "/translations/help/$language->language",
642 643
    // In same directory as .inc file.
    $info['path'],
644 645 646
  );

  foreach ($paths as $path) {
647
    if (file_exists("$path/$info[file]")) {
648
      return array('path' => $path, 'file' => $info['file']);
649 650 651 652 653
    }
  }
}

/**
654
 * Load and render a help topic.
fgm's avatar
fgm committed
655 656
 *
 * @param string $module
657
 *   Name of the module.
fgm's avatar
fgm committed
658
 * @param string $topic
659
 *   Name of the topic.
660
 * @param bool $popup
661 662 663 664
 *   Whether to show in popup or not.
 *
 * @return string
 *   Returns formatted topic.
665 666
 */
function advanced_help_view_topic($module, $topic, $popup = FALSE) {
667 668 669 670 671
  $file_info = advanced_help_get_topic_file_info($module, $topic);
  if ($file_info) {
    $info = advanced_help_get_topic($module, $topic);
    $file = "./$file_info[path]/$file_info[file]";

672
    // Fix invalid byte sequences (Issue #1330056).
673
    $output = file_get_contents($file);
674 675 676
    mb_substitute_character(0xfffd);
    $output = mb_convert_encoding($output, 'UTF-8', 'UTF-8');

677
    if (isset($info['readme file']) && $info['readme file']) {
678 679 680 681 682 683 684 685 686 687 688 689 690
      $ext = pathinfo($file, PATHINFO_EXTENSION);
      if ('md' == $ext && module_exists('markdown')) {
        $filters = module_invoke('markdown', 'filter_info');
        $md_info = $filters['filter_markdown'];
        if (function_exists($md_info['process callback'])) {
          $function = $md_info['process callback'];
          $output = '<div class="advanced-help-topic">' . filter_xss_admin($function($output, NULL)) . '</div>';
        }
        else {
          $output = '<div class="advanced-help-topic"><pre class="readme">' . check_plain($output) . '</pre></div>';
        }
      }
      else {
691 692 693 694
        $readme = '';
        if ('md' == $ext) {
          $readme .=
            '<p>' .
695 696 697 698 699 700 701
            t('If you install the !module module, the text below will be filtered by the module, producing rich text.',
              array(
                '!module' => l(t('Markdown filter'),
                  'https://www.drupal.org/project/markdown',
                  array('attributes' => array('title' => t('Link to project.'))))
              )) . '</p>';
        }
702 703
        $readme .=
          '<div class="advanced-help-topic"><pre class="readme">' . check_plain($output) . '</pre></div>';
704
        $output = $readme;
705
      }
gisle's avatar
gisle committed
706
      return $output;
707 708
    }

709 710
    // Make some exchanges. The strtr is because url() translates $ into %24
    // but we need to change it back for the regex replacement.
711
    //
merlinofchaos's avatar
merlinofchaos committed
712
    // Change 'topic:' to the URL for another help topic.
713
    if ($popup) {
fgm's avatar
fgm committed
714
      $output = preg_replace('/href="topic:([^"]+)"/', 'href="' . strtr(url('help/$1', array('query' => array('popup' => 'true'))), array('%24' => '$')) . '"', $output);
715
      $output = preg_replace('/src="topic:([^"]+)"/', 'src="' . strtr(url('help/$1', array('query' => array('popup' => 'true'))), array('%24' => '$')) . '"', $output);
716
      $output = preg_replace('/&topic:([^"]+)&/', strtr(url('help/$1', array('query' => array('popup' => 'true'))), array('%24' => '$')), $output);
717 718
    }
    else {
719
      $output = preg_replace('/href="topic:([^"]+)"/', 'href="' . strtr(url('help/$1'), array('%24' => '$')) . '"', $output);
720
      $output = preg_replace('/src="topic:([^"]+)"/', 'src="' . strtr(url('help/$1'), array('%24' => '$')) . '"', $output);
721
      $output = preg_replace('/&topic:([^"]+)&/', strtr(url('help/$1'), array('%24' => '$')), $output);
722 723
    }

724 725
    global $base_path;

merlinofchaos's avatar
merlinofchaos committed
726
    // Change 'path:' to the URL to the base help directory.
727
    $output = preg_replace('/href="path:([^"]+)"/', 'href="' . $base_path . $info['path'] . '/$1"', $output);
728 729
    $output = preg_replace('/src="path:([^"]+)"/', 'src="' . $base_path . $info['path'] . '/$1"', $output);
    $output = str_replace('&path&', $base_path . $info['path'] . '/', $output);
730

731 732
    // Change 'trans_path:' to the URL to the actual help directory.
    $output = preg_replace('/href="trans_path:([^"]+)"/', 'href="' . $base_path . $file_info['path'] . '/$1"', $output);
733 734
    $output = preg_replace('/src="trans_path:([^"]+)"/', 'src="' . $base_path . $file_info['path'] . '/$1"', $output);
    $output = str_replace('&trans_path&', $base_path . $file_info['path'] . '/', $output);
735

merlinofchaos's avatar
merlinofchaos committed
736
    // Change 'base_url:' to the URL to the site.
737
    $output = preg_replace('/href="base_url:([^"]+)"/', 'href="' . strtr(url('$1'), array('%24' => '$')) . '"', $output);
738
    $output = preg_replace('/src="base_url:([^"]+)"/', 'src="' . strtr(url('$1'), array('%24' => '$')) . '"', $output);
739
    $output = preg_replace('/&base_url&([^"]+)"/', strtr(url('$1'), array('%24' => '$')) . '"', $output);
merlinofchaos's avatar
merlinofchaos committed
740

741
    // Run the line break filter if requested.
742 743 744 745 746 747 748
    if (!empty($info['line break'])) {
      // Remove the header since it adds an extra <br /> to the filter.
      $output = preg_replace('/^<!--[^\n]*-->\n/', '', $output);

      $output = _filter_autop($output);
    }

749 750 751 752 753
    if (!empty($info['navigation'])) {
      $topics = advanced_help_get_topics();
      advanced_help_get_topic_hierarchy($topics);
      if (!empty($topics[$module][$topic]['children'])) {
        $items = advanced_help_get_tree($topics, $topics[$module][$topic]['children']);
fgm's avatar
fgm committed
754
        $output .= theme('item_list', array('items' => $items));
755 756 757
      }

      list($parent_module, $parent_topic) = $topics[$module][$topic]['_parent'];
758 759 760 761 762
      if ($parent_topic) {
        $parent = $topics[$module][$topic]['_parent'];
        $up = "help/$parent[0]/$parent[1]";
      }
      else {
763
        $up = "admin/help/ah/$module";
764 765
      }

766
      $siblings = $topics[$parent_module][$parent_topic]['children'];
767
      uasort($siblings, 'advanced_help_uasort');
768 769 770 771 772 773 774 775 776 777 778 779 780 781 782
      $prev = $next = NULL;
      $found = FALSE;
      foreach ($siblings as $sibling) {
        list($sibling_module, $sibling_topic) = $sibling;
        if ($found) {
          $next = $sibling;
          break;
        }
        if ($sibling_module == $module && $sibling_topic == $topic) {
          $found = TRUE;
          continue;
        }
        $prev = $sibling;
      }

783
      if ($prev || $up || $next) {
784 785 786
        $navigation = '<div class="help-navigation clear-block">';

        if ($prev) {
787
          $navigation .= advanced_help_l('«« ' . $topics[$prev[0]][$prev[1]]['title'], "help/$prev[0]/$prev[1]", array('attributes' => array('class' => 'help-left')));
788 789 790
        }
        if ($up) {
          $navigation .= advanced_help_l(t('Up'), $up, array('attributes' => array('class' => $prev ? 'help-up' : 'help-up-noleft')));
791 792
        }
        if ($next) {
793
          $navigation .= advanced_help_l($topics[$next[0]][$next[1]]['title'] . ' »»', "help/$next[0]/$next[1]", array('attributes' => array('class' => 'help-right')));
794 795 796 797 798 799 800 801
        }

        $navigation .= '</div>';

        $output .= $navigation;
      }
    }

802 803 804 805
    if (!empty($info['css'])) {
      drupal_add_css($info['path'] . '/' . $info['css']);
    }

806 807
    $output = '<div class="advanced-help-topic">' . $output . '</div>';
    drupal_alter('advanced_help_topic', $output, $popup);
gisle's avatar
gisle committed
808
    
809
    return $output;
810 811 812 813 814 815 816 817 818 819 820 821 822 823
  }
}

/**
 * Get the information for a single help topic.
 */
function advanced_help_get_topic($module, $topic) {
  $topics = advanced_help_get_topics();
  if (!empty($topics[$module][$topic])) {
    return $topics[$module][$topic];
  }
}

/**
824
 * Search the system for all available help topics.
825 826
 */
function advanced_help_get_topics() {
827 828
  $ini = _advanced_help_parse_ini();
  return $ini['topics'];
829 830
}

831 832 833
/**
 * Returns advanced help settings.
 */
834
function advanced_help_get_settings() {
835 836
  $ini = _advanced_help_parse_ini();
  return $ini['settings'];
837 838
}

839
/**
840
 * Function to parse ini / txt files.
841
 */
842
function _advanced_help_parse_ini() {
843 844 845 846 847 848 849 850 851
  global $language;
  static $ini = NULL;
  if (!isset($ini)) {
    $cache = cache_get('advanced_help_ini:' . $language->language);
    if ($cache) {
      $ini = $cache->data;
    }
  }
  if (!isset($ini)) {
852
    // No cached list of topics - create it.
853
    $ini = array('topics' => array(), 'settings' => array());
854

855 856 857
    foreach (array_merge(module_list(), list_themes()) as $plugin) {
      $module = is_string($plugin) ? $plugin : $plugin->name;
      $module_path = drupal_get_path(is_string($plugin) ? 'module' : 'theme', $module);
858 859

      // Parse ini-file if it exists
860
      if (file_exists("$module_path/help/$module.help.ini")) {
861
        $path_html = "$module_path/help";
862
        $info = parse_ini_file("./$module_path/help/$module.help.ini", TRUE);
863 864 865 866 867 868
        if (!$info) {
          drupal_set_message(t('There is a syntax error in the default .ini-file.  Unable to display topics.'), 'error');
        }
      }
      else {
        $info = array();
869
      }
870
      if (empty($info) || !empty($info['advanced help settings']['show readme'])) {
871
        // Look for one or more README files.
fgm's avatar
fgm committed
872
        $files = file_scan_directory("./$module_path",
873
          '/^(readme).*\.(txt|md)$/i', array('recurse' => FALSE));
874
        $path_readme = "$module_path";
875
        foreach ($files as $name => $fileinfo) {
fgm's avatar
fgm committed
876 877 878 879 880
          $info[$fileinfo->filename] = array(
            'line break' => TRUE,
            'readme file' => TRUE,
            'file' => $fileinfo->filename,
            'title' => $fileinfo->name,
881
            'weight' => -99,
fgm's avatar
fgm committed
882
          );
883 884
        }
      }
885

886
      if (!empty($info)) {
887
        // Get translated titles:
888
        $translation = array();
889 890
        if (file_exists("$module_path/translations/help/$language->language/$module.help.ini")) {
          $translation = parse_ini_file("$module_path/translations/help/$language->language/$module.help.ini", TRUE);
891 892 893
          if (!$translation) {
            drupal_set_message(t('There is a syntax error in the translated .ini-file.'), 'error');
          }
894
        }
895

896
        $ini['settings'][$module] = array();
897
        if (!empty($info['advanced help settings'])) {
898
          $ini['settings'][$module] = $info['advanced help settings'];
899
          unset($info['advanced help settings']);
900 901 902

          // Check translated strings for translatable global settings.
          if (isset($translation['advanced help settings']['name'])) {
903
            $ini['settings']['name'] = $translation['advanced help settings']['name'];
904 905
          }
          if (isset($translation['advanced help settings']['index name'])) {
906
            $ini['settings']['index name'] = $translation['advanced help settings']['index name'];
907 908
          }

909 910
        }

911
        foreach ($info as $name => $topic) {
912
          // Each topic should have a name, a title, a file and path.
913
          $file = !empty($topic['file']) ? $topic['file'] : $name;
914
          $ini['topics'][$module][$name] = array(
915
            'name' => $name,
916 917
            'module' => $module,
            'ini' => $topic,
918
            'title' => !empty($translation[$name]['title']) ? $translation[$name]['title'] : $topic['title'],
919 920
            'weight' => isset($topic['weight']) ? $topic['weight'] : 0,
            'parent' => isset($topic['parent']) ? $topic['parent'] : 0,
921 922
            'popup width' => isset($topic['popup width']) ? $topic['popup width'] : 500,
            'popup height' => isset($topic['popup height']) ? $topic['popup height'] : 500,
923 924 925
            // Require extension.
            'file' => isset($topic['readme file']) ? $file : $file . '.html',
            // Not in .ini file.
926
            'path' => isset($topic['readme file']) ? $path_readme : $path_html,
927 928
            'line break' => isset($topic['line break']) ? $topic['line break'] : (isset($ini['settings'][$module]['line break']) ? $ini['settings'][$module]['line break'] : FALSE),
            'navigation' => isset($topic['navigation']) ? $topic['navigation'] : (isset($ini['settings'][$module]['navigation']) ? $ini['settings'][$module]['navigation'] : TRUE),
929
            'show readme' => isset($topic['show readme']) ? $topic['show readme'] : (isset($ini['settings'][$module]['show readme']) ? $ini['settings'][$module]['show readme'] : FALSE),
930
            'css' => isset($topic['css']) ? $topic['css'] : (isset($ini['settings'][$module]['css']) ? $ini['settings'][$module]['css'] : NULL),
931
            'readme file' => isset($topic['readme file']) ? $topic['readme file'] : FALSE,
932 933 934 935
          );
        }
      }
    }
936 937 938
    drupal_alter('advanced_help_topic_info', $ini);

    cache_set('advanced_help_ini:' . $language->language, $ini);
939
  }
940
  return $ini;
941 942 943
}

/**