Drupal PHP Cross Reference Content Management Systems

Source: /modules/filter/filter.module - 1692 lines - 65646 bytes - Summary - Text - Print

   1  <?php
   2  
   3  /**
   4   * @file
   5   * Framework for handling filtering of content.
   6   */
   7  
   8  /**
   9   * Implements hook_help().
  10   */
  11  function filter_help($path, $arg) {
  12    switch ($path) {
  13      case 'admin/help#filter':
  14        $output = '';
  15        $output .= '<h3>' . t('About') . '</h3>';
  16        $output .= '<p>' . t('The Filter module allows administrators to configure text formats. A text format defines the HTML tags, codes, and other input allowed in content and comments, and is a key feature in guarding against potentially damaging input from malicious users. For more information, see the online handbook entry for <a href="@filter">Filter module</a>.', array('@filter' => 'http://drupal.org/documentation/modules/filter/')) . '</p>';
  17        $output .= '<h3>' . t('Uses') . '</h3>';
  18        $output .= '<dl>';
  19        $output .= '<dt>' . t('Configuring text formats') . '</dt>';
  20        $output .= '<dd>' . t('Configure text formats on the <a href="@formats">Text formats page</a>. <strong>Improper text format configuration is a security risk</strong>. To ensure security, untrusted users should only have access to text formats that restrict them to either plain text or a safe set of HTML tags, since certain HTML tags can allow embedding malicious links or scripts in text. More trusted registered users may be granted permission to use less restrictive text formats in order to create rich content.', array('@formats' => url('admin/config/content/formats'))) . '</dd>';
  21        $output .= '<dt>' . t('Applying filters to text') . '</dt>';
  22        $output .= '<dd>' . t('Each text format uses filters to manipulate text, and most formats apply several different filters to text in a specific order. Each filter is designed for a specific purpose, and generally either adds, removes, or transforms elements within user-entered text before it is displayed. A filter does not change the actual content, but instead, modifies it temporarily before it is displayed. One filter may remove unapproved HTML tags, while another automatically adds HTML to make URLs display as clickable links.') . '</dd>';
  23        $output .= '<dt>' . t('Defining text formats') . '</dt>';
  24        $output .= '<dd>' . t('One format is included by default: <em>Plain text</em> (which removes all HTML tags). Additional formats may be created by your installation profile when you install Drupal, and more can be created by an administrator on the <a href="@text-formats">Text formats page</a>.', array('@text-formats' => url('admin/config/content/formats'))) . '</dd>';
  25        $output .= '<dt>' . t('Choosing a text format') . '</dt>';
  26        $output .= '<dd>' . t('Users with access to more than one text format can use the <em>Text format</em> fieldset to choose between available text formats when creating or editing multi-line content. Administrators can define the text formats available to each user role, and control the order of formats listed in the <em>Text format</em> fieldset on the <a href="@text-formats">Text formats page</a>.', array('@text-formats' => url('admin/config/content/formats'))) . '</dd>';
  27        $output .= '</dl>';
  28        return $output;
  29  
  30      case 'admin/config/content/formats':
  31        $output = '<p>' . t('Text formats define the HTML tags, code, and other formatting that can be used when entering text. <strong>Improper text format configuration is a security risk</strong>. Learn more on the <a href="@filterhelp">Filter module help page</a>.', array('@filterhelp' => url('admin/help/filter'))) . '</p>';
  32        $output .= '<p>' . t('Text formats are presented on content editing pages in the order defined on this page. The first format available to a user will be selected by default.') . '</p>';
  33        return $output;
  34  
  35      case 'admin/config/content/formats/%':
  36        $output = '<p>' . t('A text format contains filters that change the user input, for example stripping out malicious HTML or making URLs clickable. Filters are executed from top to bottom and the order is important, since one filter may prevent another filter from doing its job. For example, when URLs are converted into links before disallowed HTML tags are removed, all links may be removed. When this happens, the order of filters may need to be re-arranged.') . '</p>';
  37        return $output;
  38    }
  39  }
  40  
  41  /**
  42   * Implements hook_theme().
  43   */
  44  function filter_theme() {
  45    return array(
  46      'filter_admin_overview' => array(
  47        'render element' => 'form',
  48        'file' => 'filter.admin.inc',
  49      ),
  50      'filter_admin_format_filter_order' => array(
  51        'render element' => 'element',
  52        'file' => 'filter.admin.inc',
  53      ),
  54      'filter_tips' => array(
  55        'variables' => array('tips' => NULL, 'long' => FALSE),
  56        'file' => 'filter.pages.inc',
  57      ),
  58      'text_format_wrapper' => array(
  59        'render element' => 'element',
  60      ),
  61      'filter_tips_more_info' => array(
  62        'variables' => array(),
  63      ),
  64      'filter_guidelines' => array(
  65        'variables' => array('format' => NULL),
  66      ),
  67    );
  68  }
  69  
  70  /**
  71   * Implements hook_element_info().
  72   *
  73   * @see filter_process_format()
  74   */
  75  function filter_element_info() {
  76    $type['text_format'] = array(
  77      '#process' => array('filter_process_format'),
  78      '#base_type' => 'textarea',
  79      '#theme_wrappers' => array('text_format_wrapper'),
  80    );
  81    return $type;
  82  }
  83  
  84  /**
  85   * Implements hook_menu().
  86   */
  87  function filter_menu() {
  88    $items['filter/tips'] = array(
  89      'title' => 'Compose tips',
  90      'page callback' => 'filter_tips_long',
  91      'access callback' => TRUE,
  92      'type' => MENU_SUGGESTED_ITEM,
  93      'file' => 'filter.pages.inc',
  94    );
  95    $items['admin/config/content/formats'] = array(
  96      'title' => 'Text formats',
  97      'description' => 'Configure how content input by users is filtered, including allowed HTML tags. Also allows enabling of module-provided filters.',
  98      'page callback' => 'drupal_get_form',
  99      'page arguments' => array('filter_admin_overview'),
 100      'access arguments' => array('administer filters'),
 101      'file' => 'filter.admin.inc',
 102    );
 103    $items['admin/config/content/formats/list'] = array(
 104      'title' => 'List',
 105      'type' => MENU_DEFAULT_LOCAL_TASK,
 106    );
 107    $items['admin/config/content/formats/add'] = array(
 108      'title' => 'Add text format',
 109      'page callback' => 'filter_admin_format_page',
 110      'access arguments' => array('administer filters'),
 111      'type' => MENU_LOCAL_ACTION,
 112      'weight' => 1,
 113      'file' => 'filter.admin.inc',
 114    );
 115    $items['admin/config/content/formats/%filter_format'] = array(
 116      'title callback' => 'filter_admin_format_title',
 117      'title arguments' => array(4),
 118      'page callback' => 'filter_admin_format_page',
 119      'page arguments' => array(4),
 120      'access arguments' => array('administer filters'),
 121      'file' => 'filter.admin.inc',
 122    );
 123    $items['admin/config/content/formats/%filter_format/disable'] = array(
 124      'title' => 'Disable text format',
 125      'page callback' => 'drupal_get_form',
 126      'page arguments' => array('filter_admin_disable', 4),
 127      'access callback' => '_filter_disable_format_access',
 128      'access arguments' => array(4),
 129      'file' => 'filter.admin.inc',
 130    );
 131    return $items;
 132  }
 133  
 134  /**
 135   * Access callback for deleting text formats.
 136   *
 137   * @param $format
 138   *   A text format object.
 139   * @return
 140   *   TRUE if the text format can be disabled by the current user, FALSE
 141   *   otherwise.
 142   */
 143  function _filter_disable_format_access($format) {
 144    // The fallback format can never be disabled.
 145    return user_access('administer filters') && ($format->format != filter_fallback_format());
 146  }
 147  
 148  /**
 149   * Load a text format object from the database.
 150   *
 151   * @param $format_id
 152   *   The format ID.
 153   *
 154   * @return
 155   *   A fully-populated text format object, if the requested format exists and
 156   *   is enabled. If the format does not exist, or exists in the database but
 157   *   has been marked as disabled, FALSE is returned.
 158   *
 159   * @see filter_format_exists()
 160   */
 161  function filter_format_load($format_id) {
 162    $formats = filter_formats();
 163    return isset($formats[$format_id]) ? $formats[$format_id] : FALSE;
 164  }
 165  
 166  /**
 167   * Save a text format object to the database.
 168   *
 169   * @param $format
 170   *   A format object using the properties:
 171   *   - 'format': A machine-readable name representing the ID of the text format
 172   *     to save. If this corresponds to an existing text format, that format
 173   *     will be updated; otherwise, a new format will be created.
 174   *   - 'name': The title of the text format.
 175   *   - 'status': (optional) An integer indicating whether the text format is
 176   *     enabled (1) or not (0). Defaults to 1.
 177   *   - 'weight': (optional) The weight of the text format, which controls its
 178   *     placement in text format lists. If omitted, the weight is set to 0.
 179   *   - 'filters': (optional) An associative, multi-dimensional array of filters
 180   *     assigned to the text format, keyed by the name of each filter and using
 181   *     the properties:
 182   *     - 'weight': (optional) The weight of the filter in the text format. If
 183   *       omitted, either the currently stored weight is retained (if there is
 184   *       one), or the filter is assigned a weight of 10, which will usually
 185   *       put it at the bottom of the list.
 186   *     - 'status': (optional) A boolean indicating whether the filter is
 187   *       enabled in the text format. If omitted, the filter will be disabled.
 188   *     - 'settings': (optional) An array of configured settings for the filter.
 189   *       See hook_filter_info() for details.
 190   */
 191  function filter_format_save($format) {
 192    $format->name = trim($format->name);
 193    $format->cache = _filter_format_is_cacheable($format);
 194    if (!isset($format->status)) {
 195      $format->status = 1;
 196    }
 197    if (!isset($format->weight)) {
 198      $format->weight = 0;
 199    }
 200  
 201    // Insert or update the text format.
 202    $return = db_merge('filter_format')
 203      ->key(array('format' => $format->format))
 204      ->fields(array(
 205        'name' => $format->name,
 206        'cache' => (int) $format->cache,
 207        'status' => (int) $format->status,
 208        'weight' => (int) $format->weight,
 209      ))
 210      ->execute();
 211  
 212    // Programmatic saves may not contain any filters.
 213    if (!isset($format->filters)) {
 214      $format->filters = array();
 215    }
 216    $filter_info = filter_get_filters();
 217    foreach ($filter_info as $name => $filter) {
 218      // If the format does not specify an explicit weight for a filter, assign
 219      // a default weight, either defined in hook_filter_info(), or the default of
 220      // 0 by filter_get_filters()
 221      if (!isset($format->filters[$name]['weight'])) {
 222        $format->filters[$name]['weight'] = $filter['weight'];
 223      }
 224      $format->filters[$name]['status'] = isset($format->filters[$name]['status']) ? $format->filters[$name]['status'] : 0;
 225      $format->filters[$name]['module'] = $filter['module'];
 226  
 227      // If settings were passed, only ensure default settings.
 228      if (isset($format->filters[$name]['settings'])) {
 229        if (isset($filter['default settings'])) {
 230          $format->filters[$name]['settings'] = array_merge($filter['default settings'], $format->filters[$name]['settings']);
 231        }
 232      }
 233      // Otherwise, use default settings or fall back to an empty array.
 234      else {
 235        $format->filters[$name]['settings'] = isset($filter['default settings']) ? $filter['default settings'] : array();
 236      }
 237  
 238      $fields = array();
 239      $fields['weight'] = $format->filters[$name]['weight'];
 240      $fields['status'] = $format->filters[$name]['status'];
 241      $fields['module'] = $format->filters[$name]['module'];
 242      $fields['settings'] = serialize($format->filters[$name]['settings']);
 243  
 244      db_merge('filter')
 245        ->key(array(
 246          'format' => $format->format,
 247          'name' => $name,
 248        ))
 249        ->fields($fields)
 250        ->execute();
 251    }
 252  
 253    if ($return == SAVED_NEW) {
 254      module_invoke_all('filter_format_insert', $format);
 255    }
 256    else {
 257      module_invoke_all('filter_format_update', $format);
 258      // Explicitly indicate that the format was updated. We need to do this
 259      // since if the filters were updated but the format object itself was not,
 260      // the merge query above would not return an indication that anything had
 261      // changed.
 262      $return = SAVED_UPDATED;
 263  
 264      // Clear the filter cache whenever a text format is updated.
 265      cache_clear_all($format->format . ':', 'cache_filter', TRUE);
 266    }
 267  
 268    filter_formats_reset();
 269  
 270    return $return;
 271  }
 272  
 273  /**
 274   * Disable a text format.
 275   *
 276   * There is no core facility to re-enable a disabled format. It is not deleted
 277   * to keep information for contrib and to make sure the format ID is never
 278   * reused. As there might be content using the disabled format, this would lead
 279   * to data corruption.
 280   *
 281   * @param $format
 282   *   The text format object to be disabled.
 283   */
 284  function filter_format_disable($format) {
 285    db_update('filter_format')
 286      ->fields(array('status' => 0))
 287      ->condition('format', $format->format)
 288      ->execute();
 289  
 290    // Allow modules to react on text format deletion.
 291    module_invoke_all('filter_format_disable', $format);
 292  
 293    // Clear the filter cache whenever a text format is disabled.
 294    filter_formats_reset();
 295    cache_clear_all($format->format . ':', 'cache_filter', TRUE);
 296  }
 297  
 298  /**
 299   * Determines if a text format exists.
 300   *
 301   * @param $format_id
 302   *   The ID of the text format to check.
 303   *
 304   * @return
 305   *   TRUE if the text format exists, FALSE otherwise. Note that for disabled
 306   *   formats filter_format_exists() will return TRUE while filter_format_load()
 307   *   will return FALSE.
 308   *
 309   * @see filter_format_load()
 310   */
 311  function filter_format_exists($format_id) {
 312    return (bool) db_query_range('SELECT 1 FROM {filter_format} WHERE format = :format', 0, 1, array(':format' => $format_id))->fetchField();
 313  }
 314  
 315  /**
 316   * Display a text format form title.
 317   */
 318  function filter_admin_format_title($format) {
 319    return $format->name;
 320  }
 321  
 322  /**
 323   * Implements hook_permission().
 324   */
 325  function filter_permission() {
 326    $perms['administer filters'] = array(
 327      'title' => t('Administer text formats and filters'),
 328      'restrict access' => TRUE,
 329    );
 330  
 331    // Generate permissions for each text format. Warn the administrator that any
 332    // of them are potentially unsafe.
 333    foreach (filter_formats() as $format) {
 334      $permission = filter_permission_name($format);
 335      if (!empty($permission)) {
 336        // Only link to the text format configuration page if the user who is
 337        // viewing this will have access to that page.
 338        $format_name_replacement = user_access('administer filters') ? l($format->name, 'admin/config/content/formats/' . $format->format) : drupal_placeholder($format->name);
 339        $perms[$permission] = array(
 340          'title' => t("Use the !text_format text format", array('!text_format' => $format_name_replacement,)),
 341          'description' => drupal_placeholder(t('Warning: This permission may have security implications depending on how the text format is configured.')),
 342        );
 343      }
 344    }
 345    return $perms;
 346  }
 347  
 348  /**
 349   * Returns the machine-readable permission name for a provided text format.
 350   *
 351   * @param $format
 352   *   An object representing a text format.
 353   * @return
 354   *   The machine-readable permission name, or FALSE if the provided text format
 355   *   is malformed or is the fallback format (which is available to all users).
 356   */
 357  function filter_permission_name($format) {
 358    if (isset($format->format) && $format->format != filter_fallback_format()) {
 359      return 'use text format ' . $format->format;
 360    }
 361    return FALSE;
 362  }
 363  
 364  /**
 365   * Implements hook_modules_enabled().
 366   */
 367  function filter_modules_enabled($modules) {
 368    // Reset the static cache of module-provided filters, in case any of the
 369    // newly enabled modules defines a new filter or alters existing ones.
 370    drupal_static_reset('filter_get_filters');
 371  }
 372  
 373  /**
 374   * Implements hook_modules_disabled().
 375   */
 376  function filter_modules_disabled($modules) {
 377    // Reset the static cache of module-provided filters, in case any of the
 378    // newly disabled modules defined or altered any filters.
 379    drupal_static_reset('filter_get_filters');
 380  }
 381  
 382  /**
 383   * Retrieve a list of text formats, ordered by weight.
 384   *
 385   * @param $account
 386   *   (optional) If provided, only those formats that are allowed for this user
 387   *   account will be returned. All formats will be returned otherwise.
 388   * @return
 389   *   An array of text format objects, keyed by the format ID and ordered by
 390   *   weight.
 391   *
 392   * @see filter_formats_reset()
 393   */
 394  function filter_formats($account = NULL) {
 395    global $language;
 396    $formats = &drupal_static(__FUNCTION__, array());
 397  
 398    // All available formats are cached for performance.
 399    if (!isset($formats['all'])) {
 400      if ($cache = cache_get("filter_formats:{$language->language}")) {
 401        $formats['all'] = $cache->data;
 402      }
 403      else {
 404        $formats['all'] = db_select('filter_format', 'ff')
 405          ->addTag('translatable')
 406          ->fields('ff')
 407          ->condition('status', 1)
 408          ->orderBy('weight')
 409          ->execute()
 410          ->fetchAllAssoc('format');
 411  
 412        cache_set("filter_formats:{$language->language}", $formats['all']);
 413      }
 414    }
 415  
 416    // Build a list of user-specific formats.
 417    if (isset($account) && !isset($formats['user'][$account->uid])) {
 418      $formats['user'][$account->uid] = array();
 419      foreach ($formats['all'] as $format) {
 420        if (filter_access($format, $account)) {
 421          $formats['user'][$account->uid][$format->format] = $format;
 422        }
 423      }
 424    }
 425  
 426    return isset($account) ? $formats['user'][$account->uid] : $formats['all'];
 427  }
 428  
 429  /**
 430   * Resets text format caches.
 431   *
 432   * @see filter_formats()
 433   */
 434  function filter_formats_reset() {
 435    cache_clear_all('filter_formats', 'cache', TRUE);
 436    cache_clear_all('filter_list_format', 'cache', TRUE);
 437    drupal_static_reset('filter_list_format');
 438    drupal_static_reset('filter_formats');
 439  }
 440  
 441  /**
 442   * Retrieves a list of roles that are allowed to use a given text format.
 443   *
 444   * @param $format
 445   *   An object representing the text format.
 446   * @return
 447   *   An array of role names, keyed by role ID.
 448   */
 449  function filter_get_roles_by_format($format) {
 450    // Handle the fallback format upfront (all roles have access to this format).
 451    if ($format->format == filter_fallback_format()) {
 452      return user_roles();
 453    }
 454    // Do not list any roles if the permission does not exist.
 455    $permission = filter_permission_name($format);
 456    return !empty($permission) ? user_roles(FALSE, $permission) : array();
 457  }
 458  
 459  /**
 460   * Retrieves a list of text formats that are allowed for a given role.
 461   *
 462   * @param $rid
 463   *   The user role ID to retrieve text formats for.
 464   * @return
 465   *   An array of text format objects that are allowed for the role, keyed by
 466   *   the text format ID and ordered by weight.
 467   */
 468  function filter_get_formats_by_role($rid) {
 469    $formats = array();
 470    foreach (filter_formats() as $format) {
 471      $roles = filter_get_roles_by_format($format);
 472      if (isset($roles[$rid])) {
 473        $formats[$format->format] = $format;
 474      }
 475    }
 476    return $formats;
 477  }
 478  
 479  /**
 480   * Returns the ID of the default text format for a particular user.
 481   *
 482   * The default text format is the first available format that the user is
 483   * allowed to access, when the formats are ordered by weight. It should
 484   * generally be used as a default choice when presenting the user with a list
 485   * of possible text formats (for example, in a node creation form).
 486   *
 487   * Conversely, when existing content that does not have an assigned text format
 488   * needs to be filtered for display, the default text format is the wrong
 489   * choice, because it is not guaranteed to be consistent from user to user, and
 490   * some trusted users may have an unsafe text format set by default, which
 491   * should not be used on text of unknown origin. Instead, the fallback format
 492   * returned by filter_fallback_format() should be used, since that is intended
 493   * to be a safe, consistent format that is always available to all users.
 494   *
 495   * @param $account
 496   *   (optional) The user account to check. Defaults to the currently logged-in
 497   *   user.
 498   * @return
 499   *   The ID of the user's default text format.
 500   *
 501   * @see filter_fallback_format()
 502   */
 503  function filter_default_format($account = NULL) {
 504    global $user;
 505    if (!isset($account)) {
 506      $account = $user;
 507    }
 508    // Get a list of formats for this user, ordered by weight. The first one
 509    // available is the user's default format.
 510    $formats = filter_formats($account);
 511    $format = reset($formats);
 512    return $format->format;
 513  }
 514  
 515  /**
 516   * Returns the ID of the fallback text format that all users have access to.
 517   *
 518   * The fallback text format is a regular text format in every respect, except
 519   * it does not participate in the filter permission system and cannot be
 520   * disabled. It needs to exist because any user who has permission to create
 521   * formatted content must always have at least one text format they can use.
 522   *
 523   * Because the fallback format is available to all users, it should always be
 524   * configured securely. For example, when the Filter module is installed, this
 525   * format is initialized to output plain text. Installation profiles and site
 526   * administrators have the freedom to configure it further.
 527   *
 528   * Note that the fallback format is completely distinct from the default
 529   * format, which differs per user and is simply the first format which that
 530   * user has access to. The default and fallback formats are only guaranteed to
 531   * be the same for users who do not have access to any other format; otherwise,
 532   * the fallback format's weight determines its placement with respect to the
 533   * user's other formats.
 534   *
 535   * Any modules implementing a format deletion functionality must not delete
 536   * this format.
 537   *
 538   * @see hook_filter_format_disable()
 539   * @see filter_default_format()
 540   */
 541  function filter_fallback_format() {
 542    // This variable is automatically set in the database for all installations
 543    // of Drupal. In the event that it gets disabled or deleted somehow, there
 544    // is no safe default to return, since we do not want to risk making an
 545    // existing (and potentially unsafe) text format on the site automatically
 546    // available to all users. Returning NULL at least guarantees that this
 547    // cannot happen.
 548    return variable_get('filter_fallback_format');
 549  }
 550  
 551  /**
 552   * Returns the title of the fallback text format.
 553   */
 554  function filter_fallback_format_title() {
 555    $fallback_format = filter_format_load(filter_fallback_format());
 556    return filter_admin_format_title($fallback_format);
 557  }
 558  
 559  /**
 560   * Return a list of all filters provided by modules.
 561   */
 562  function filter_get_filters() {
 563    $filters = &drupal_static(__FUNCTION__, array());
 564  
 565    if (empty($filters)) {
 566      foreach (module_implements('filter_info') as $module) {
 567        $info = module_invoke($module, 'filter_info');
 568        if (isset($info) && is_array($info)) {
 569          // Assign the name of the module implementing the filters and ensure
 570          // default values.
 571          foreach (array_keys($info) as $name) {
 572            $info[$name]['module'] = $module;
 573            $info[$name] += array(
 574              'description' => '',
 575              'weight' => 0,
 576            );
 577          }
 578          $filters = array_merge($filters, $info);
 579        }
 580      }
 581      // Allow modules to alter filter definitions.
 582      drupal_alter('filter_info', $filters);
 583  
 584      uasort($filters, '_filter_list_cmp');
 585    }
 586  
 587    return $filters;
 588  }
 589  
 590  /**
 591   * Helper function for sorting the filter list by filter name.
 592   */
 593  function _filter_list_cmp($a, $b) {
 594    return strcmp($a['title'], $b['title']);
 595  }
 596  
 597  /**
 598   * Check if text in a certain text format is allowed to be cached.
 599   *
 600   * This function can be used to check whether the result of the filtering
 601   * process can be cached. A text format may allow caching depending on the
 602   * filters enabled.
 603   *
 604   * @param $format_id
 605   *   The text format ID to check.
 606   * @return
 607   *   TRUE if the given text format allows caching, FALSE otherwise.
 608   */
 609  function filter_format_allowcache($format_id) {
 610    $format = filter_format_load($format_id);
 611    return !empty($format->cache);
 612  }
 613  
 614  /**
 615   * Helper function to determine whether the output of a given text format can be cached.
 616   *
 617   * The output of a given text format can be cached when all enabled filters in
 618   * the text format allow caching.
 619   *
 620   * @param $format
 621   *   The text format object to check.
 622   * @return
 623   *   TRUE if all the filters enabled in the given text format allow caching,
 624   *   FALSE otherwise.
 625   *
 626   * @see filter_format_save()
 627   */
 628  function _filter_format_is_cacheable($format) {
 629    if (empty($format->filters)) {
 630      return TRUE;
 631    }
 632    $filter_info = filter_get_filters();
 633    foreach ($format->filters as $name => $filter) {
 634      // By default, 'cache' is TRUE for all filters unless specified otherwise.
 635      if (!empty($filter['status']) && isset($filter_info[$name]['cache']) && !$filter_info[$name]['cache']) {
 636        return FALSE;
 637      }
 638    }
 639    return TRUE;
 640  }
 641  
 642  /**
 643   * Retrieve a list of filters for a given text format.
 644   *
 645   * Note that this function returns all associated filters regardless of whether
 646   * they are enabled or disabled. All functions working with the filter
 647   * information outside of filter administration should test for $filter->status
 648   * before performing actions with the filter.
 649   *
 650   * @param $format_id
 651   *   The format ID to retrieve filters for.
 652   *
 653   * @return
 654   *   An array of filter objects associated to the given text format, keyed by
 655   *   filter name.
 656   */
 657  function filter_list_format($format_id) {
 658    $filters = &drupal_static(__FUNCTION__, array());
 659    $filter_info = filter_get_filters();
 660  
 661    if (!isset($filters['all'])) {
 662      if ($cache = cache_get('filter_list_format')) {
 663        $filters['all'] = $cache->data;
 664      }
 665      else {
 666        $result = db_query('SELECT * FROM {filter} ORDER BY weight, module, name');
 667        foreach ($result as $record) {
 668          $filters['all'][$record->format][$record->name] = $record;
 669        }
 670        cache_set('filter_list_format', $filters['all']);
 671      }
 672    }
 673  
 674    if (!isset($filters[$format_id])) {
 675      $format_filters = array();
 676      $filter_map = isset($filters['all'][$format_id]) ? $filters['all'][$format_id] : array();
 677      foreach ($filter_map as $name => $filter) {
 678        if (isset($filter_info[$name])) {
 679          $filter->title = $filter_info[$name]['title'];
 680          // Unpack stored filter settings.
 681          $filter->settings = (isset($filter->settings) ? unserialize($filter->settings) : array());
 682          // Merge in default settings.
 683          if (isset($filter_info[$name]['default settings'])) {
 684            $filter->settings += $filter_info[$name]['default settings'];
 685          }
 686  
 687          $format_filters[$name] = $filter;
 688        }
 689      }
 690      $filters[$format_id] = $format_filters;
 691    }
 692  
 693    return isset($filters[$format_id]) ? $filters[$format_id] : array();
 694  }
 695  
 696  /**
 697   * Run all the enabled filters on a piece of text.
 698   *
 699   * Note: Because filters can inject JavaScript or execute PHP code, security is
 700   * vital here. When a user supplies a text format, you should validate it using
 701   * filter_access() before accepting/using it. This is normally done in the
 702   * validation stage of the Form API. You should for example never make a preview
 703   * of content in a disallowed format.
 704   *
 705   * @param $text
 706   *   The text to be filtered.
 707   * @param $format_id
 708   *   The format id of the text to be filtered. If no format is assigned, the
 709   *   fallback format will be used.
 710   * @param $langcode
 711   *   Optional: the language code of the text to be filtered, e.g. 'en' for
 712   *   English. This allows filters to be language aware so language specific
 713   *   text replacement can be implemented.
 714   * @param $cache
 715   *   Boolean whether to cache the filtered output in the {cache_filter} table.
 716   *   The caller may set this to FALSE when the output is already cached
 717   *   elsewhere to avoid duplicate cache lookups and storage.
 718   *
 719   * @ingroup sanitization
 720   */
 721  function check_markup($text, $format_id = NULL, $langcode = '', $cache = FALSE) {
 722    if (!isset($format_id)) {
 723      $format_id = filter_fallback_format();
 724    }
 725    // If the requested text format does not exist, the text cannot be filtered.
 726    if (!$format = filter_format_load($format_id)) {
 727      watchdog('filter', 'Missing text format: %format.', array('%format' => $format_id), WATCHDOG_ALERT);
 728      return '';
 729    }
 730  
 731    // Check for a cached version of this piece of text.
 732    $cache = $cache && !empty($format->cache);
 733    $cache_id = '';
 734    if ($cache) {
 735      $cache_id = $format->format . ':' . $langcode . ':' . hash('sha256', $text);
 736      if ($cached = cache_get($cache_id, 'cache_filter')) {
 737        return $cached->data;
 738      }
 739    }
 740  
 741    // Convert all Windows and Mac newlines to a single newline, so filters only
 742    // need to deal with one possibility.
 743    $text = str_replace(array("\r\n", "\r"), "\n", $text);
 744  
 745    // Get a complete list of filters, ordered properly.
 746    $filters = filter_list_format($format->format);
 747    $filter_info = filter_get_filters();
 748  
 749    // Give filters the chance to escape HTML-like data such as code or formulas.
 750    foreach ($filters as $name => $filter) {
 751      if ($filter->status && isset($filter_info[$name]['prepare callback']) && function_exists($filter_info[$name]['prepare callback'])) {
 752        $function = $filter_info[$name]['prepare callback'];
 753        $text = $function($text, $filter, $format, $langcode, $cache, $cache_id);
 754      }
 755    }
 756  
 757    // Perform filtering.
 758    foreach ($filters as $name => $filter) {
 759      if ($filter->status && isset($filter_info[$name]['process callback']) && function_exists($filter_info[$name]['process callback'])) {
 760        $function = $filter_info[$name]['process callback'];
 761        $text = $function($text, $filter, $format, $langcode, $cache, $cache_id);
 762      }
 763    }
 764  
 765    // Cache the filtered text. This cache is infinitely valid. It becomes
 766    // obsolete when $text changes (which leads to a new $cache_id). It is
 767    // automatically flushed when the text format is updated.
 768    // @see filter_format_save()
 769    if ($cache) {
 770      cache_set($cache_id, $text, 'cache_filter');
 771    }
 772  
 773    return $text;
 774  }
 775  
 776  /**
 777   * Expands an element into a base element with text format selector attached.
 778   *
 779   * The form element will be expanded into two separate form elements, one
 780   * holding the original element, and the other holding the text format selector:
 781   * - value: Holds the original element, having its #type changed to the value of
 782   *   #base_type or 'textarea' by default.
 783   * - format: Holds the text format fieldset and the text format selection, using
 784   *   the text format id specified in #format or the user's default format by
 785   *   default, if NULL.
 786   *
 787   * The resulting value for the element will be an array holding the value and the
 788   * format.  For example, the value for the body element will be:
 789   * @code
 790   *   $form_state['values']['body']['value'] = 'foo';
 791   *   $form_state['values']['body']['format'] = 'foo';
 792   * @endcode
 793   *
 794   * @param $element
 795   *   The form element to process. Properties used:
 796   *   - #base_type: The form element #type to use for the 'value' element.
 797   *     'textarea' by default.
 798   *   - #format: (optional) The text format id to preselect. If NULL or not set,
 799   *     the default format for the current user will be used.
 800   *
 801   * @return
 802   *   The expanded element.
 803   */
 804  function filter_process_format($element) {
 805    global $user;
 806  
 807    // Ensure that children appear as subkeys of this element.
 808    $element['#tree'] = TRUE;
 809    $blacklist = array(
 810      // Make form_builder() regenerate child properties.
 811      '#parents',
 812      '#id',
 813      '#name',
 814      // Do not copy this #process function to prevent form_builder() from
 815      // recursing infinitely.
 816      '#process',
 817      // Description is handled by theme_text_format_wrapper().
 818      '#description',
 819      // Ensure proper ordering of children.
 820      '#weight',
 821      // Properties already processed for the parent element.
 822      '#prefix',
 823      '#suffix',
 824      '#attached',
 825      '#processed',
 826      '#theme_wrappers',
 827    );
 828    // Move this element into sub-element 'value'.
 829    unset($element['value']);
 830    foreach (element_properties($element) as $key) {
 831      if (!in_array($key, $blacklist)) {
 832        $element['value'][$key] = $element[$key];
 833      }
 834    }
 835  
 836    $element['value']['#type'] = $element['#base_type'];
 837    $element['value'] += element_info($element['#base_type']);
 838  
 839    // Turn original element into a text format wrapper.
 840    $path = drupal_get_path('module', 'filter');
 841    $element['#attached']['js'][] = $path . '/filter.js';
 842    $element['#attached']['css'][] = $path . '/filter.css';
 843  
 844    // Setup child container for the text format widget.
 845    $element['format'] = array(
 846      '#type' => 'fieldset',
 847      '#attributes' => array('class' => array('filter-wrapper')),
 848    );
 849  
 850    // Prepare text format guidelines.
 851    $element['format']['guidelines'] = array(
 852      '#type' => 'container',
 853      '#attributes' => array('class' => array('filter-guidelines')),
 854      '#weight' => 20,
 855    );
 856    // Get a list of formats that the current user has access to.
 857    $formats = filter_formats($user);
 858    foreach ($formats as $format) {
 859      $options[$format->format] = $format->name;
 860      $element['format']['guidelines'][$format->format] = array(
 861        '#theme' => 'filter_guidelines',
 862        '#format' => $format,
 863      );
 864    }
 865  
 866    // Use the default format for this user if none was selected.
 867    if (!isset($element['#format'])) {
 868      $element['#format'] = filter_default_format($user);
 869    }
 870  
 871    $element['format']['format'] = array(
 872      '#type' => 'select',
 873      '#title' => t('Text format'),
 874      '#options' => $options,
 875      '#default_value' => $element['#format'],
 876      '#access' => count($formats) > 1,
 877      '#weight' => 10,
 878      '#attributes' => array('class' => array('filter-list')),
 879      '#parents' => array_merge($element['#parents'], array('format')),
 880    );
 881  
 882    $element['format']['help'] = array(
 883      '#type' => 'container',
 884      '#theme' => 'filter_tips_more_info',
 885      '#attributes' => array('class' => array('filter-help')),
 886      '#weight' => 0,
 887    );
 888  
 889    $all_formats = filter_formats();
 890    $format_exists = isset($all_formats[$element['#format']]);
 891    $user_has_access = isset($formats[$element['#format']]);
 892    $user_is_admin = user_access('administer filters');
 893  
 894    // If the stored format does not exist, administrators have to assign a new
 895    // format.
 896    if (!$format_exists && $user_is_admin) {
 897      $element['format']['format']['#required'] = TRUE;
 898      $element['format']['format']['#default_value'] = NULL;
 899      // Force access to the format selector (it may have been denied above if
 900      // the user only has access to a single format).
 901      $element['format']['format']['#access'] = TRUE;
 902    }
 903    // Disable this widget, if the user is not allowed to use the stored format,
 904    // or if the stored format does not exist. The 'administer filters' permission
 905    // only grants access to the filter administration, not to all formats.
 906    elseif (!$user_has_access || !$format_exists) {
 907      // Overload default values into #value to make them unalterable.
 908      $element['value']['#value'] = $element['value']['#default_value'];
 909      $element['format']['format']['#value'] = $element['format']['format']['#default_value'];
 910  
 911      // Prepend #pre_render callback to replace field value with user notice
 912      // prior to rendering.
 913      $element['value'] += array('#pre_render' => array());
 914      array_unshift($element['value']['#pre_render'], 'filter_form_access_denied');
 915  
 916      // Cosmetic adjustments.
 917      if (isset($element['value']['#rows'])) {
 918        $element['value']['#rows'] = 3;
 919      }
 920      $element['value']['#disabled'] = TRUE;
 921      $element['value']['#resizable'] = FALSE;
 922  
 923      // Hide the text format selector and any other child element (such as text
 924      // field's summary).
 925      foreach (element_children($element) as $key) {
 926        if ($key != 'value') {
 927          $element[$key]['#access'] = FALSE;
 928        }
 929      }
 930    }
 931  
 932    return $element;
 933  }
 934  
 935  /**
 936   * #pre_render callback for #type 'text_format' to hide field value from prying eyes.
 937   *
 938   * To not break form processing and previews if a user does not have access to a
 939   * stored text format, the expanded form elements in filter_process_format() are
 940   * forced to take over the stored #default_values for 'value' and 'format'.
 941   * However, to prevent the unfiltered, original #value from being displayed to
 942   * the user, we replace it with a friendly notice here.
 943   *
 944   * @see filter_process_format()
 945   */
 946  function filter_form_access_denied($element) {
 947    $element['#value'] = t('This field has been disabled because you do not have sufficient permissions to edit it.');
 948    return $element;
 949  }
 950  
 951  /**
 952   * Returns HTML for a text format-enabled form element.
 953   *
 954   * @param $variables
 955   *   An associative array containing:
 956   *   - element: A render element containing #children and #description.
 957   *
 958   * @ingroup themeable
 959   */
 960  function theme_text_format_wrapper($variables) {
 961    $element = $variables['element'];
 962    $output = '<div class="text-format-wrapper">';
 963    $output .= $element['#children'];
 964    if (!empty($element['#description'])) {
 965      $output .= '<div class="description">' . $element['#description'] . '</div>';
 966    }
 967    $output .= "</div>\n";
 968  
 969    return $output;
 970  }
 971  
 972  /**
 973   * Checks if a user has access to a particular text format.
 974   *
 975   * @param $format
 976   *   An object representing the text format.
 977   * @param $account
 978   *   (optional) The user account to check access for; if omitted, the currently
 979   *   logged-in user is used.
 980   *
 981   * @return
 982   *   Boolean TRUE if the user is allowed to access the given format.
 983   */
 984  function filter_access($format, $account = NULL) {
 985    global $user;
 986    if (!isset($account)) {
 987      $account = $user;
 988    }
 989    // Handle special cases up front. All users have access to the fallback
 990    // format.
 991    if ($format->format == filter_fallback_format()) {
 992      return TRUE;
 993    }
 994    // Check the permission if one exists; otherwise, we have a non-existent
 995    // format so we return FALSE.
 996    $permission = filter_permission_name($format);
 997    return !empty($permission) && user_access($permission, $account);
 998  }
 999  
1000  /**
1001   * Helper function for fetching filter tips.
1002   */
1003  function _filter_tips($format_id, $long = FALSE) {
1004    global $user;
1005  
1006    $formats = filter_formats($user);
1007    $filter_info = filter_get_filters();
1008  
1009    $tips = array();
1010  
1011    // If only listing one format, extract it from the $formats array.
1012    if ($format_id != -1) {
1013      $formats = array($formats[$format_id]);
1014    }
1015  
1016    foreach ($formats as $format) {
1017      $filters = filter_list_format($format->format);
1018      $tips[$format->name] = array();
1019      foreach ($filters as $name => $filter) {
1020        if ($filter->status && isset($filter_info[$name]['tips callback']) && function_exists($filter_info[$name]['tips callback'])) {
1021          $tip = $filter_info[$name]['tips callback']($filter, $format, $long);
1022          if (isset($tip)) {
1023            $tips[$format->name][$name] = array('tip' => $tip, 'id' => $name);
1024          }
1025        }
1026      }
1027    }
1028  
1029    return $tips;
1030  }
1031  
1032  /**
1033   * Parses an HTML snippet and returns it as a DOM object.
1034   *
1035   * This function loads the body part of a partial (X)HTML document
1036   * and returns a full DOMDocument object that represents this document.
1037   * You can use filter_dom_serialize() to serialize this DOMDocument
1038   * back to a XHTML snippet.
1039   *
1040   * @param $text
1041   *   The partial (X)HTML snippet to load. Invalid mark-up
1042   *   will be corrected on import.
1043   * @return
1044   *   A DOMDocument that represents the loaded (X)HTML snippet.
1045   */
1046  function filter_dom_load($text) {
1047    $dom_document = new DOMDocument();
1048    // Ignore warnings during HTML soup loading.
1049    @$dom_document->loadHTML('<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"><html xmlns="http://www.w3.org/1999/xhtml"><head><meta http-equiv="Content-Type" content="text/html; charset=utf-8" /></head><body>' . $text . '</body></html>');
1050  
1051    return $dom_document;
1052  }
1053  
1054  /**
1055   * Converts a DOM object back to an HTML snippet.
1056   *
1057   * The function serializes the body part of a DOMDocument
1058   * back to an XHTML snippet.
1059   *
1060   * The resulting XHTML snippet will be properly formatted
1061   * to be compatible with HTML user agents.
1062   *
1063   * @param $dom_document
1064   *   A DOMDocument object to serialize, only the tags below
1065   *   the first <body> node will be converted.
1066   * @return
1067   *   A valid (X)HTML snippet, as a string.
1068   */
1069  function filter_dom_serialize($dom_document) {
1070    $body_node = $dom_document->getElementsByTagName('body')->item(0);
1071    $body_content = '';
1072  
1073    foreach ($body_node->getElementsByTagName('script') as $node) {
1074      filter_dom_serialize_escape_cdata_element($dom_document, $node);
1075    }
1076  
1077    foreach ($body_node->getElementsByTagName('style') as $node) {
1078      filter_dom_serialize_escape_cdata_element($dom_document, $node, '/*', '*/');
1079    }
1080  
1081    foreach ($body_node->childNodes as $child_node) {
1082      $body_content .= $dom_document->saveXML($child_node);
1083    }
1084    return preg_replace('|<([^> ]*)/>|i', '<$1 />', $body_content);
1085  }
1086  
1087  /**
1088   * Adds comments around the <!CDATA section in a dom element.
1089   *
1090   * DOMDocument::loadHTML in filter_dom_load() makes CDATA sections from the
1091   * contents of inline script and style tags.  This can cause HTML 4 browsers to
1092   * throw exceptions.
1093   *
1094   * This function attempts to solve the problem by creating a DocumentFragment
1095   * and imitating the behavior in drupal_get_js(), commenting the CDATA tag.
1096   *
1097   * @param $dom_document
1098   *   The DOMDocument containing the $dom_element.
1099   * @param $dom_element
1100   *   The element potentially containing a CDATA node.
1101   * @param $comment_start
1102   *   String to use as a comment start marker to escape the CDATA declaration.
1103   * @param $comment_end
1104   *   String to use as a comment end marker to escape the CDATA declaration.
1105   */
1106  function filter_dom_serialize_escape_cdata_element($dom_document, $dom_element, $comment_start = '//', $comment_end = '') {
1107    foreach ($dom_element->childNodes as $node) {
1108      if (get_class($node) == 'DOMCdataSection') {
1109        // See drupal_get_js().  This code is more or less duplicated there.
1110        $embed_prefix = "\n<!--{$comment_start}--><![CDATA[{$comment_start} ><!--{$comment_end}\n";
1111        $embed_suffix = "\n{$comment_start}--><!]]>{$comment_end}\n";
1112  
1113        // Prevent invalid cdata escaping as this would throw a DOM error.
1114        // This is the same behavior as found in libxml2.
1115        // Related W3C standard: http://www.w3.org/TR/REC-xml/#dt-cdsection
1116        // Fix explanation: http://en.wikipedia.org/wiki/CDATA#Nesting
1117        $data = str_replace(']]>', ']]]]><![CDATA[>', $node->data);
1118  
1119        $fragment = $dom_document->createDocumentFragment();
1120        $fragment->appendXML($embed_prefix . $data . $embed_suffix);
1121        $dom_element->appendChild($fragment);
1122        $dom_element->removeChild($node);
1123      }
1124    }
1125  }
1126  
1127  /**
1128   * Returns HTML for a link to the more extensive filter tips.
1129   *
1130   * @ingroup themeable
1131   */
1132  function theme_filter_tips_more_info() {
1133    return '<p>' . l(t('More information about text formats'), 'filter/tips', array('attributes' => array('target' => '_blank'))) . '</p>';
1134  }
1135  
1136  /**
1137   * Returns HTML for guidelines for a text format.
1138   *
1139   * @param $variables
1140   *   An associative array containing:
1141   *   - format: An object representing a text format.
1142   *
1143   * @ingroup themeable
1144   */
1145  function theme_filter_guidelines($variables) {
1146    $format = $variables['format'];
1147    $attributes['class'][] = 'filter-guidelines-item';
1148    $attributes['class'][] = 'filter-guidelines-' . $format->format;
1149    $output = '<div' . drupal_attributes($attributes) . '>';
1150    $output .= '<h3>' . check_plain($format->name) . '</h3>';
1151    $output .= theme('filter_tips', array('tips' => _filter_tips($format->format, FALSE)));
1152    $output .= '</div>';
1153    return $output;
1154  }
1155  
1156  /**
1157   * @defgroup standard_filters Standard filters
1158   * @{
1159   * Filters implemented by the filter.module.
1160   */
1161  
1162  /**
1163   * Implements hook_filter_info().
1164   */
1165  function filter_filter_info() {
1166    $filters['filter_html'] = array(
1167      'title' => t('Limit allowed HTML tags'),
1168      'process callback' => '_filter_html',
1169      'settings callback' => '_filter_html_settings',
1170      'default settings' => array(
1171        'allowed_html' => '<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>',
1172        'filter_html_help' => 1,
1173        'filter_html_nofollow' => 0,
1174      ),
1175      'tips callback' => '_filter_html_tips',
1176      'weight' => -10,
1177    );
1178    $filters['filter_autop'] = array(
1179      'title' => t('Convert line breaks into HTML (i.e. <code>&lt;br&gt;</code> and <code>&lt;p&gt;</code>)'),
1180      'process callback' => '_filter_autop',
1181      'tips callback' => '_filter_autop_tips',
1182    );
1183    $filters['filter_url'] = array(
1184      'title' => t('Convert URLs into links'),
1185      'process callback' => '_filter_url',
1186      'settings callback' => '_filter_url_settings',
1187      'default settings' => array(
1188        'filter_url_length' => 72,
1189      ),
1190      'tips callback' => '_filter_url_tips',
1191    );
1192    $filters['filter_htmlcorrector'] = array(
1193      'title' =>  t('Correct faulty and chopped off HTML'),
1194      'process callback' => '_filter_htmlcorrector',
1195      'weight' => 10,
1196    );
1197    $filters['filter_html_escape'] = array(
1198      'title' => t('Display any HTML as plain text'),
1199      'process callback' => '_filter_html_escape',
1200      'tips callback' => '_filter_html_escape_tips',
1201      'weight' => -10,
1202    );
1203    return $filters;
1204  }
1205  
1206  /**
1207   * Settings callback for the HTML filter.
1208   */
1209  function _filter_html_settings($form, &$form_state, $filter, $format, $defaults) {
1210    $filter->settings += $defaults;
1211  
1212    $settings['allowed_html'] = array(
1213      '#type' => 'textfield',
1214      '#title' => t('Allowed HTML tags'),
1215      '#default_value' => $filter->settings['allowed_html'],
1216      '#maxlength' => 1024,
1217      '#description' => t('A list of HTML tags that can be used. JavaScript event attributes, JavaScript URLs, and CSS are always stripped.'),
1218    );
1219    $settings['filter_html_help'] = array(
1220      '#type' => 'checkbox',
1221      '#title' => t('Display basic HTML help in long filter tips'),
1222      '#default_value' => $filter->settings['filter_html_help'],
1223    );
1224    $settings['filter_html_nofollow'] = array(
1225      '#type' => 'checkbox',
1226      '#title' => t('Add rel="nofollow" to all links'),
1227      '#default_value' => $filter->settings['filter_html_nofollow'],
1228    );
1229    return $settings;
1230  }
1231  
1232  /**
1233   * HTML filter. Provides filtering of input into accepted HTML.
1234   */
1235  function _filter_html($text, $filter) {
1236    $allowed_tags = preg_split('/\s+|<|>/', $filter->settings['allowed_html'], -1, PREG_SPLIT_NO_EMPTY);
1237    $text = filter_xss($text, $allowed_tags);
1238  
1239    if ($filter->settings['filter_html_nofollow']) {
1240      $html_dom = filter_dom_load($text);
1241      $links = $html_dom->getElementsByTagName('a');
1242      foreach ($links as $link) {
1243        $link->setAttribute('rel', 'nofollow');
1244      }
1245      $text = filter_dom_serialize($html_dom);
1246    }
1247  
1248    return trim($text);
1249  }
1250  
1251  /**
1252   * Filter tips callback for HTML filter.
1253   */
1254  function _filter_html_tips($filter, $format, $long = FALSE) {
1255    global $base_url;
1256  
1257    if (!($allowed_html = $filter->settings['allowed_html'])) {
1258      return;
1259    }
1260    $output = t('Allowed HTML tags: @tags', array('@tags' => $allowed_html));
1261    if (!$long) {
1262      return $output;
1263    }
1264  
1265    $output = '<p>' . $output . '</p>';
1266    if (!$filter->settings['filter_html_help']) {
1267      return $output;
1268    }
1269  
1270    $output .= '<p>' . t('This site allows HTML content. While learning all of HTML may feel intimidating, learning how to use a very small number of the most basic HTML "tags" is very easy. This table provides examples for each tag that is enabled on this site.') . '</p>';
1271    $output .= '<p>' . t('For more information see W3C\'s <a href="@html-specifications">HTML Specifications</a> or use your favorite search engine to find other sites that explain HTML.', array('@html-specifications' => 'http://www.w3.org/TR/html/')) . '</p>';
1272    $tips = array(
1273      'a' => array(t('Anchors are used to make links to other pages.'), '<a href="' . $base_url . '">' . check_plain(variable_get('site_name', 'Drupal')) . '</a>'),
1274      'br' => array(t('By default line break tags are automatically added, so use this tag to add additional ones. Use of this tag is different because it is not used with an open/close pair like all the others. Use the extra " /" inside the tag to maintain XHTML 1.0 compatibility'), t('Text with <br />line break')),
1275      'p' => array(t('By default paragraph tags are automatically added, so use this tag to add additional ones.'), '<p>' . t('Paragraph one.') . '</p> <p>' . t('Paragraph two.') . '</p>'),
1276      'strong' => array(t('Strong', array(), array('context' => 'Font weight')), '<strong>' . t('Strong', array(), array('context' => 'Font weight')) . '</strong>'),
1277      'em' => array(t('Emphasized'), '<em>' . t('Emphasized') . '</em>'),
1278      'cite' => array(t('Cited'), '<cite>' . t('Cited') . '</cite>'),
1279      'code' => array(t('Coded text used to show programming source code'), '<code>' . t('Coded') . '</code>'),
1280      'b' => array(t('Bolded'), '<b>' . t('Bolded') . '</b>'),
1281      'u' => array(t('Underlined'), '<u>' . t('Underlined') . '</u>'),
1282      'i' => array(t('Italicized'), '<i>' . t('Italicized') . '</i>'),
1283      'sup' => array(t('Superscripted'), t('<sup>Super</sup>scripted')),
1284      'sub' => array(t('Subscripted'), t('<sub>Sub</sub>scripted')),
1285      'pre' => array(t('Preformatted'), '<pre>' . t('Preformatted') . '</pre>'),
1286      'abbr' => array(t('Abbreviation'), t('<abbr title="Abbreviation">Abbrev.</abbr>')),
1287      'acronym' => array(t('Acronym'), t('<acronym title="Three-Letter Acronym">TLA</acronym>')),
1288      'blockquote' => array(t('Block quoted'), '<blockquote>' . t('Block quoted') . '</blockquote>'),
1289      'q' => array(t('Quoted inline'), '<q>' . t('Quoted inline') . '</q>'),
1290      // Assumes and describes tr, td, th.
1291      'table' => array(t('Table'), '<table> <tr><th>' . t('Table header') . '</th></tr> <tr><td>' . t('Table cell') . '</td></tr> </table>'),
1292      'tr' => NULL, 'td' => NULL, 'th' => NULL,
1293      'del' => array(t('Deleted'), '<del>' . t('Deleted') . '</del>'),
1294      'ins' => array(t('Inserted'), '<ins>' . t('Inserted') . '</ins>'),
1295       // Assumes and describes li.
1296      'ol' => array(t('Ordered list - use the &lt;li&gt; to begin each list item'), '<ol> <li>' . t('First item') . '</li> <li>' . t('Second item') . '</li> </ol>'),
1297      'ul' => array(t('Unordered list - use the &lt;li&gt; to begin each list item'), '<ul> <li>' . t('First item') . '</li> <li>' . t('Second item') . '</li> </ul>'),
1298      'li' => NULL,
1299      // Assumes and describes dt and dd.
1300      'dl' => array(t('Definition lists are similar to other HTML lists. &lt;dl&gt; begins the definition list, &lt;dt&gt; begins the definition term and &lt;dd&gt; begins the definition description.'), '<dl> <dt>' . t('First term') . '</dt> <dd>' . t('First definition') . '</dd> <dt>' . t('Second term') . '</dt> <dd>' . t('Second definition') . '</dd> </dl>'),
1301      'dt' => NULL, 'dd' => NULL,
1302      'h1' => array(t('Heading'), '<h1>' . t('Title') . '</h1>'),
1303      'h2' => array(t('Heading'), '<h2>' . t('Subtitle') . '</h2>'),
1304      'h3' => array(t('Heading'), '<h3>' . t('Subtitle three') . '</h3>'),
1305      'h4' => array(t('Heading'), '<h4>' . t('Subtitle four') . '</h4>'),
1306      'h5' => array(t('Heading'), '<h5>' . t('Subtitle five') . '</h5>'),
1307      'h6' => array(t('Heading'), '<h6>' . t('Subtitle six') . '</h6>')
1308    );
1309    $header = array(t('Tag Description'), t('You Type'), t('You Get'));
1310    preg_match_all('/<([a-z0-9]+)[^a-z0-9]/i', $allowed_html, $out);
1311    foreach ($out[1] as $tag) {
1312      if (!empty($tips[$tag])) {
1313        $rows[] = array(
1314          array('data' => $tips[$tag][0], 'class' => array('description')),
1315          array('data' => '<code>' . check_plain($tips[$tag][1]) . '</code>', 'class' => array('type')),
1316          array('data' => $tips[$tag][1], 'class' => array('get'))
1317        );
1318      }
1319      else {
1320        $rows[] = array(
1321          array('data' => t('No help provided for tag %tag.', array('%tag' => $tag)), 'class' => array('description'), 'colspan' => 3),
1322        );
1323      }
1324    }
1325    $output .= theme('table', array('header' => $header, 'rows' => $rows));
1326  
1327    $output .= '<p>' . t('Most unusual characters can be directly entered without any problems.') . '</p>';
1328    $output .= '<p>' . t('If you do encounter problems, try using HTML character entities. A common example looks like &amp;amp; for an ampersand &amp; character. For a full list of entities see HTML\'s <a href="@html-entities">entities</a> page. Some of the available characters include:', array('@html-entities' => 'http://www.w3.org/TR/html4/sgml/entities.html')) . '</p>';
1329  
1330    $entities = array(
1331      array(t('Ampersand'), '&amp;'),
1332      array(t('Greater than'), '&gt;'),
1333      array(t('Less than'), '&lt;'),
1334      array(t('Quotation mark'), '&quot;'),
1335    );
1336    $header = array(t('Character Description'), t('You Type'), t('You Get'));
1337    unset($rows);
1338    foreach ($entities as $entity) {
1339      $rows[] = array(
1340        array('data' => $entity[0], 'class' => array('description')),
1341        array('data' => '<code>' . check_plain($entity[1]) . '</code>', 'class' => array('type')),
1342        array('data' => $entity[1], 'class' => array('get'))
1343      );
1344    }
1345    $output .= theme('table', array('header' => $header, 'rows' => $rows));
1346    return $output;
1347  }
1348  
1349  /**
1350   * Settings callback for URL filter.
1351   */
1352  function _filter_url_settings($form, &$form_state, $filter, $format, $defaults) {
1353    $filter->settings += $defaults;
1354  
1355    $settings['filter_url_length'] = array(
1356      '#type' => 'textfield',
1357      '#title' => t('Maximum link text length'),
1358      '#default_value' => $filter->settings['filter_url_length'],
1359      '#size' => 5,
1360      '#maxlength' => 4,
1361      '#field_suffix' => t('characters'),
1362      '#description' => t('URLs longer than this number of characters will be truncated to prevent long strings that break formatting. The link itself will be retained; just the text portion of the link will be truncated.'),
1363      '#element_validate' => array('element_validate_integer_positive'),
1364    );
1365    return $settings;
1366  }
1367  
1368  /**
1369   * URL filter. Automatically converts text into hyperlinks.
1370   *
1371   * This filter identifies and makes clickable three types of "links".
1372   * - URLs like http://example.com.
1373   * - E-mail addresses like name@example.com.
1374   * - Web addresses without the "http://" protocol defined, like www.example.com.
1375   * Each type must be processed separately, as there is no one regular
1376   * expression that could possibly match all of the cases in one pass.
1377   */
1378  function _filter_url($text, $filter) {
1379    // Tags to skip and not recurse into.
1380    $ignore_tags = 'a|script|style|code|pre';
1381  
1382    // Pass length to regexp callback.
1383    _filter_url_trim(NULL, $filter->settings['filter_url_length']);
1384  
1385    // Create an array which contains the regexps for each type of link.
1386    // The key to the regexp is the name of a function that is used as
1387    // callback function to process matches of the regexp. The callback function
1388    // is to return the replacement for the match. The array is used and
1389    // matching/replacement done below inside some loops.
1390    $tasks = array();
1391  
1392    // Prepare protocols pattern for absolute URLs.
1393    // check_url() will replace any bad protocols with HTTP, so we need to support
1394    // the identical list. While '//' is technically optional for MAILTO only,
1395    // we cannot cleanly differ between protocols here without hard-coding MAILTO,
1396    // so '//' is optional for all protocols.
1397    // @see filter_xss_bad_protocol()
1398    $protocols = variable_get('filter_allowed_protocols', array('http', 'https', 'ftp', 'news', 'nntp', 'telnet', 'mailto', 'irc', 'ssh', 'sftp', 'webcal', 'rtsp'));
1399    $protocols = implode(':(?://)?|', $protocols) . ':(?://)?';
1400  
1401    // Prepare domain name pattern.
1402    // The ICANN seems to be on track towards accepting more diverse top level
1403    // domains, so this pattern has been "future-proofed" to allow for TLDs
1404    // of length 2-64.
1405    $domain = '(?:[A-Za-z0-9._+-]+\.)?[A-Za-z]{2,64}\b';
1406    $ip = '(?:[0-9]{1,3}\.){3}[0-9]{1,3}';
1407    $auth = '[a-zA-Z0-9:%_+*~#?&=.,/;-]+@';
1408    $trail = '[a-zA-Z0-9:%_+*~#&\[\]=/;?!\.,-]*[a-zA-Z0-9:%_+*~#&\[\]=/;-]';
1409  
1410    // Prepare pattern for optional trailing punctuation.
1411    // Even these characters could have a valid meaning for the URL, such usage is
1412    // rare compared to using a URL at the end of or within a sentence, so these
1413    // trailing characters are optionally excluded.
1414    $punctuation = '[\.,?!]*?';
1415  
1416    // Match absolute URLs.
1417    $url_pattern = "(?:$auth)?(?:$domain|$ip)/?(?:$trail)?";
1418    $pattern = "`((?:$protocols)(?:$url_pattern))($punctuation)`";
1419    $tasks['_filter_url_parse_full_links'] = $pattern;
1420  
1421    // Match e-mail addresses.
1422    $url_pattern = "[A-Za-z0-9._-]{1,254}@(?:$domain)";
1423    $pattern = "`($url_pattern)`";
1424    $tasks['_filter_url_parse_email_links'] = $pattern;
1425  
1426    // Match www domains.
1427    $url_pattern = "www\.(?:$domain)/?(?:$trail)?";
1428    $pattern = "`($url_pattern)($punctuation)`";
1429    $tasks['_filter_url_parse_partial_links'] = $pattern;
1430  
1431    // Each type of URL needs to be processed separately. The text is joined and
1432    // re-split after each task, since all injected HTML tags must be correctly
1433    // protected before the next task.
1434    foreach ($tasks as $task => $pattern) {
1435      // HTML comments need to be handled separately, as they may contain HTML
1436      // markup, especially a '>'. Therefore, remove all comment contents and add
1437      // them back later.
1438      _filter_url_escape_comments('', TRUE);
1439      $text = preg_replace_callback('`<!--(.*?)-->`s', '_filter_url_escape_comments', $text);
1440  
1441      // Split at all tags; ensures that no tags or attributes are processed.
1442      $chunks = preg_split('/(<.+?>)/is', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
1443      // PHP ensures that the array consists of alternating delimiters and
1444      // literals, and begins and ends with a literal (inserting NULL as
1445      // required). Therefore, the first chunk is always text:
1446      $chunk_type = 'text';
1447      // If a tag of $ignore_tags is found, it is stored in $open_tag and only
1448      // removed when the closing tag is found. Until the closing tag is found,
1449      // no replacements are made.
1450      $open_tag = '';
1451  
1452      for ($i = 0; $i < count($chunks); $i++) {
1453        if ($chunk_type == 'text') {
1454          // Only process this text if there are no unclosed $ignore_tags.
1455          if ($open_tag == '') {
1456            // If there is a match, inject a link into this chunk via the callback
1457            // function contained in $task.
1458            $chunks[$i] = preg_replace_callback($pattern, $task, $chunks[$i]);
1459          }
1460          // Text chunk is done, so next chunk must be a tag.
1461          $chunk_type = 'tag';
1462        }
1463        else {
1464          // Only process this tag if there are no unclosed $ignore_tags.
1465          if ($open_tag == '') {
1466            // Check whether this tag is contained in $ignore_tags.
1467            if (preg_match("`<($ignore_tags)(?:\s|>)`i", $chunks[$i], $matches)) {
1468              $open_tag = $matches[1];
1469            }
1470          }
1471          // Otherwise, check whether this is the closing tag for $open_tag.
1472          else {
1473            if (preg_match("`<\/$open_tag>`i", $chunks[$i], $matches)) {
1474              $open_tag = '';
1475            }
1476          }
1477          // Tag chunk is done, so next chunk must be text.
1478          $chunk_type = 'text';
1479        }
1480      }
1481  
1482      $text = implode($chunks);
1483      // Revert back to the original comment contents
1484      _filter_url_escape_comments('', FALSE);
1485      $text = preg_replace_callback('`<!--(.*?)-->`', '_filter_url_escape_comments', $text);
1486    }
1487  
1488    return $text;
1489  }
1490  
1491  /**
1492   * preg_replace callback to make links out of absolute URLs.
1493   */
1494  function _filter_url_parse_full_links($match) {
1495    // The $i:th parenthesis in the regexp contains the URL.
1496    $i = 1;
1497  
1498    $match[$i] = decode_entities($match[$i]);
1499    $caption = check_plain(_filter_url_trim($match[$i]));
1500    $match[$i] = check_plain($match[$i]);
1501    return '<a href="' . $match[$i] . '">' . $caption . '</a>' . $match[$i + 1];
1502  }
1503  
1504  /**
1505   * preg_replace callback to make links out of e-mail addresses.
1506   */
1507  function _filter_url_parse_email_links($match) {
1508    // The $i:th parenthesis in the regexp contains the URL.
1509    $i = 0;
1510  
1511    $match[$i] = decode_entities($match[$i]);
1512    $caption = check_plain(_filter_url_trim($match[$i]));
1513    $match[$i] = check_plain($match[$i]);
1514    return '<a href="mailto:' . $match[$i] . '">' . $caption . '</a>';
1515  }
1516  
1517  /**
1518   * preg_replace callback to make links out of domain names starting with "www."
1519   */
1520  function _filter_url_parse_partial_links($match) {
1521    // The $i:th parenthesis in the regexp contains the URL.
1522    $i = 1;
1523  
1524    $match[$i] = decode_entities($match[$i]);
1525    $caption = check_plain(_filter_url_trim($match[$i]));
1526    $match[$i] = check_plain($match[$i]);
1527    return '<a href="http://' . $match[$i] . '">' . $caption . '</a>' . $match[$i + 1];
1528  }
1529  
1530  /**
1531   * preg_replace callback to escape contents of HTML comments
1532   *
1533   * @param $match
1534   *   An array containing matches to replace from preg_replace_callback(),
1535   *   whereas $match[1] is expected to contain the content to be filtered.
1536   * @param $escape
1537   *   (optional) Boolean whether to escape (TRUE) or unescape comments (FALSE).
1538   *   Defaults to neither. If TRUE, statically cached $comments are reset.
1539   */
1540  function _filter_url_escape_comments($match, $escape = NULL) {
1541    static $mode, $comments = array();
1542  
1543    if (isset($escape)) {
1544      $mode = $escape;
1545      if ($escape){
1546        $comments = array();
1547      }
1548      return;
1549    }
1550  
1551    // Replace all HTML coments with a '<!-- [hash] -->' placeholder.
1552    if ($mode) {
1553      $content = $match[1];
1554      $hash = md5($content);
1555      $comments[$hash] = $content;
1556      return "<!-- $hash -->";
1557    }
1558    // Or replace placeholders with actual comment contents.
1559    else {
1560      $hash = $match[1];
1561      $hash = trim($hash);
1562      $content = $comments[$hash];
1563      return "<!--$content-->";
1564    }
1565  }
1566  
1567  /**
1568   * Shortens long URLs to http://www.example.com/long/url...
1569   */
1570  function _filter_url_trim($text, $length = NULL) {
1571    static $_length;
1572    if ($length !== NULL) {
1573      $_length = $length;
1574    }
1575  
1576    // Use +3 for '...' string length.
1577    if ($_length && strlen($text) > $_length + 3) {
1578      $text = substr($text, 0, $_length) . '...';
1579    }
1580  
1581    return $text;
1582  }
1583  
1584  /**
1585   * Filter tips callback for URL filter.
1586   */
1587  function _filter_url_tips($filter, $format, $long = FALSE) {
1588    return t('Web page addresses and e-mail addresses turn into links automatically.');
1589  }
1590  
1591  /**
1592   * Scan input and make sure that all HTML tags are properly closed and nested.
1593   */
1594  function _filter_htmlcorrector($text) {
1595    return filter_dom_serialize(filter_dom_load($text));
1596  }
1597  
1598  /**
1599   * Convert line breaks into <p> and <br> in an intelligent fashion.
1600   * Based on: http://photomatt.net/scripts/autop
1601   */
1602  function _filter_autop($text) {
1603    // All block level tags
1604    $block = '(?:table|thead|tfoot|caption|colgroup|tbody|tr|td|th|div|dl|dd|dt|ul|ol|li|pre|select|form|blockquote|address|p|h[1-6]|hr)';
1605  
1606    // Split at opening and closing PRE, SCRIPT, STYLE, OBJECT, IFRAME tags
1607    // and comments. We don't apply any processing to the contents of these tags
1608    // to avoid messing up code. We look for matched pairs and allow basic
1609    // nesting. For example:
1610    // "processed <pre> ignored <script> ignored </script> ignored </pre> processed"
1611    $chunks = preg_split('@(<!--.*?-->|</?(?:pre|script|style|object|iframe|!--)[^>]*>)@i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
1612    // Note: PHP ensures the array consists of alternating delimiters and literals
1613    // and begins and ends with a literal (inserting NULL as required).
1614    $ignore = FALSE;
1615    $ignoretag = '';
1616    $output = '';
1617    foreach ($chunks as $i => $chunk) {
1618      if ($i % 2) {
1619        $comment = (substr($chunk, 0, 4) == '<!--');
1620        if ($comment) {
1621          // Nothing to do, this is a comment.
1622          $output .= $chunk;
1623          continue;
1624        }
1625        // Opening or closing tag?
1626        $open = ($chunk[1] != '/');
1627        list($tag) = preg_split('/[ >]/', substr($chunk, 2 - $open), 2);
1628        if (!$ignore) {
1629          if ($open) {
1630            $ignore = TRUE;
1631            $ignoretag = $tag;
1632          }
1633        }
1634        // Only allow a matching tag to close it.
1635        elseif (!$open && $ignoretag == $tag) {
1636          $ignore = FALSE;
1637          $ignoretag = '';
1638        }
1639      }
1640      elseif (!$ignore) {
1641        $chunk = preg_replace('|\n*$|', '', $chunk) . "\n\n"; // just to make things a little easier, pad the end
1642        $chunk = preg_replace('|<br />\s*<br />|', "\n\n", $chunk);
1643        $chunk = preg_replace('!(<' . $block . '[^>]*>)!', "\n$1", $chunk); // Space things out a little
1644        $chunk = preg_replace('!(</' . $block . '>)!', "$1\n\n", $chunk); // Space things out a little
1645        $chunk = preg_replace("/\n\n+/", "\n\n", $chunk); // take care of duplicates
1646        $chunk = preg_replace('/^\n|\n\s*\n$/', '', $chunk);
1647        $chunk = '<p>' . preg_replace('/\n\s*\n\n?(.)/', "</p>\n<p>$1", $chunk) . "</p>\n"; // make paragraphs, including one at the end
1648        $chunk = preg_replace("|<p>(<li.+?)</p>|", "$1", $chunk); // problem with nested lists
1649        $chunk = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $chunk);
1650        $chunk = str_replace('</blockquote></p>', '</p></blockquote>', $chunk);
1651        $chunk = preg_replace('|<p>\s*</p>\n?|', '', $chunk); // under certain strange conditions it could create a P of entirely whitespace
1652        $chunk = preg_replace('!<p>\s*(</?' . $block . '[^>]*>)!', "$1", $chunk);
1653        $chunk = preg_replace('!(</?' . $block . '[^>]*>)\s*</p>!', "$1", $chunk);
1654        $chunk = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $chunk); // make line breaks
1655        $chunk = preg_replace('!(</?' . $block . '[^>]*>)\s*<br />!', "$1", $chunk);
1656        $chunk = preg_replace('!<br />(\s*</?(?:p|li|div|th|pre|td|ul|ol)>)!', '$1', $chunk);
1657        $chunk = preg_replace('/&([^#])(?![A-Za-z0-9]{1,8};)/', '&amp;$1', $chunk);
1658      }
1659      $output .= $chunk;
1660    }
1661    return $output;
1662  }
1663  
1664  /**
1665   * Filter tips callback for auto-paragraph filter.
1666   */
1667  function _filter_autop_tips($filter, $format, $long = FALSE) {
1668    if ($long) {
1669      return t('Lines and paragraphs are automatically recognized. The &lt;br /&gt; line break, &lt;p&gt; paragraph and &lt;/p&gt; close paragraph tags are inserted automatically. If paragraphs are not recognized simply add a couple blank lines.');
1670    }
1671    else {
1672      return t('Lines and paragraphs break automatically.');
1673    }
1674  }
1675  
1676  /**
1677   * Escapes all HTML tags, so they will be visible instead of being effective.
1678   */
1679  function _filter_html_escape($text) {
1680    return trim(check_plain($text));
1681  }
1682  
1683  /**
1684   * Filter tips callback for HTML escaping filter.
1685   */
1686  function _filter_html_escape_tips($filter, $format, $long = FALSE) {
1687    return t('No HTML tags allowed.');
1688  }
1689  
1690  /**
1691   * @} End of "Standard filters".
1692   */

title

Description

title

Description

title

Description

title

title

Body