Projet

Général

Profil

Paste
Télécharger (66,1 ko) Statistiques
| Branche: | Révision:

root / drupal7 / modules / filter / filter.module @ db2d93dd

1
<?php
2

    
3
/**
4
 * @file
5
 * Framework for handling the 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
 * @see text_format_wrapper()
75
 */
76
function filter_element_info() {
77
  $type['text_format'] = array(
78
    '#process' => array('filter_process_format'),
79
    '#base_type' => 'textarea',
80
    '#theme_wrappers' => array('text_format_wrapper'),
81
  );
82
  return $type;
83
}
84

    
85
/**
86
 * Implements hook_menu().
87
 */
88
function filter_menu() {
89
  $items['filter/tips'] = array(
90
    'title' => 'Compose tips',
91
    'page callback' => 'filter_tips_long',
92
    'access callback' => TRUE,
93
    'type' => MENU_SUGGESTED_ITEM,
94
    'file' => 'filter.pages.inc',
95
  );
96
  $items['admin/config/content/formats'] = array(
97
    'title' => 'Text formats',
98
    'description' => 'Configure how content input by users is filtered, including allowed HTML tags. Also allows enabling of module-provided filters.',
99
    'page callback' => 'drupal_get_form',
100
    'page arguments' => array('filter_admin_overview'),
101
    'access arguments' => array('administer filters'),
102
    'file' => 'filter.admin.inc',
103
  );
104
  $items['admin/config/content/formats/list'] = array(
105
    'title' => 'List',
106
    'type' => MENU_DEFAULT_LOCAL_TASK,
107
  );
108
  $items['admin/config/content/formats/add'] = array(
109
    'title' => 'Add text format',
110
    'page callback' => 'filter_admin_format_page',
111
    'access arguments' => array('administer filters'),
112
    'type' => MENU_LOCAL_ACTION,
113
    'weight' => 1,
114
    'file' => 'filter.admin.inc',
115
  );
116
  $items['admin/config/content/formats/%filter_format'] = array(
117
    'title callback' => 'filter_admin_format_title',
118
    'title arguments' => array(4),
119
    'page callback' => 'filter_admin_format_page',
120
    'page arguments' => array(4),
121
    'access arguments' => array('administer filters'),
122
    'file' => 'filter.admin.inc',
123
  );
124
  $items['admin/config/content/formats/%filter_format/disable'] = array(
125
    'title' => 'Disable text format',
126
    'page callback' => 'drupal_get_form',
127
    'page arguments' => array('filter_admin_disable', 4),
128
    'access callback' => '_filter_disable_format_access',
129
    'access arguments' => array(4),
130
    'file' => 'filter.admin.inc',
131
  );
132
  return $items;
133
}
134

    
135
/**
136
 * Access callback: Checks access for disabling text formats.
137
 *
138
 * @param $format
139
 *   A text format object.
140
 *
141
 * @return
142
 *   TRUE if the text format can be disabled by the current user, FALSE
143
 *   otherwise.
144
 *
145
 * @see filter_menu()
146
 */
147
function _filter_disable_format_access($format) {
148
  // The fallback format can never be disabled.
149
  return user_access('administer filters') && ($format->format != filter_fallback_format());
150
}
151

    
152
/**
153
 * Loads a text format object from the database.
154
 *
155
 * @param $format_id
156
 *   The format ID.
157
 *
158
 * @return
159
 *   A fully-populated text format object, if the requested format exists and
160
 *   is enabled. If the format does not exist, or exists in the database but
161
 *   has been marked as disabled, FALSE is returned.
162
 *
163
 * @see filter_format_exists()
164
 */
165
function filter_format_load($format_id) {
166
  $formats = filter_formats();
167
  return isset($formats[$format_id]) ? $formats[$format_id] : FALSE;
168
}
169

    
170
/**
171
 * Saves a text format object to the database.
172
 *
173
 * @param $format
174
 *   A format object having the properties:
175
 *   - format: A machine-readable name representing the ID of the text format
176
 *     to save. If this corresponds to an existing text format, that format
177
 *     will be updated; otherwise, a new format will be created.
178
 *   - name: The title of the text format.
179
 *   - status: (optional) An integer indicating whether the text format is
180
 *     enabled (1) or not (0). Defaults to 1.
181
 *   - weight: (optional) The weight of the text format, which controls its
182
 *     placement in text format lists. If omitted, the weight is set to 0.
183
 *   - filters: (optional) An associative, multi-dimensional array of filters
184
 *     assigned to the text format, keyed by the name of each filter and using
185
 *     the properties:
186
 *     - weight: (optional) The weight of the filter in the text format. If
187
 *       omitted, either the currently stored weight is retained (if there is
188
 *       one), or the filter is assigned a weight of 10, which will usually
189
 *       put it at the bottom of the list.
190
 *     - status: (optional) A boolean indicating whether the filter is
191
 *       enabled in the text format. If omitted, the filter will be disabled.
192
 *     - settings: (optional) An array of configured settings for the filter.
193
 *       See hook_filter_info() for details.
194
 *
195
 * @return
196
 *   SAVED_NEW or SAVED_UPDATED.
197
 */
198
function filter_format_save($format) {
199
  $format->name = trim($format->name);
200
  $format->cache = _filter_format_is_cacheable($format);
201
  if (!isset($format->status)) {
202
    $format->status = 1;
203
  }
204
  if (!isset($format->weight)) {
205
    $format->weight = 0;
206
  }
207

    
208
  // Insert or update the text format.
209
  $return = db_merge('filter_format')
210
    ->key(array('format' => $format->format))
211
    ->fields(array(
212
      'name' => $format->name,
213
      'cache' => (int) $format->cache,
214
      'status' => (int) $format->status,
215
      'weight' => (int) $format->weight,
216
    ))
217
    ->execute();
218

    
219
  // Programmatic saves may not contain any filters.
220
  if (!isset($format->filters)) {
221
    $format->filters = array();
222
  }
223
  $filter_info = filter_get_filters();
224
  foreach ($filter_info as $name => $filter) {
225
    // If the format does not specify an explicit weight for a filter, assign
226
    // a default weight, either defined in hook_filter_info(), or the default of
227
    // 0 by filter_get_filters()
228
    if (!isset($format->filters[$name]['weight'])) {
229
      $format->filters[$name]['weight'] = $filter['weight'];
230
    }
231
    $format->filters[$name]['status'] = isset($format->filters[$name]['status']) ? $format->filters[$name]['status'] : 0;
232
    $format->filters[$name]['module'] = $filter['module'];
233

    
234
    // If settings were passed, only ensure default settings.
235
    if (isset($format->filters[$name]['settings'])) {
236
      if (isset($filter['default settings'])) {
237
        $format->filters[$name]['settings'] = array_merge($filter['default settings'], $format->filters[$name]['settings']);
238
      }
239
    }
240
    // Otherwise, use default settings or fall back to an empty array.
241
    else {
242
      $format->filters[$name]['settings'] = isset($filter['default settings']) ? $filter['default settings'] : array();
243
    }
244

    
245
    $fields = array();
246
    $fields['weight'] = $format->filters[$name]['weight'];
247
    $fields['status'] = $format->filters[$name]['status'];
248
    $fields['module'] = $format->filters[$name]['module'];
249
    $fields['settings'] = serialize($format->filters[$name]['settings']);
250

    
251
    db_merge('filter')
252
      ->key(array(
253
        'format' => $format->format,
254
        'name' => $name,
255
      ))
256
      ->fields($fields)
257
      ->execute();
258
  }
259

    
260
  if ($return == SAVED_NEW) {
261
    module_invoke_all('filter_format_insert', $format);
262
  }
263
  else {
264
    module_invoke_all('filter_format_update', $format);
265
    // Explicitly indicate that the format was updated. We need to do this
266
    // since if the filters were updated but the format object itself was not,
267
    // the merge query above would not return an indication that anything had
268
    // changed.
269
    $return = SAVED_UPDATED;
270

    
271
    // Clear the filter cache whenever a text format is updated.
272
    cache_clear_all($format->format . ':', 'cache_filter', TRUE);
273
  }
274

    
275
  filter_formats_reset();
276

    
277
  return $return;
278
}
279

    
280
/**
281
 * Disables a text format.
282
 *
283
 * There is no core facility to re-enable a disabled format. It is not deleted
284
 * to keep information for contrib and to make sure the format ID is never
285
 * reused. As there might be content using the disabled format, this would lead
286
 * to data corruption.
287
 *
288
 * @param $format
289
 *   The text format object to be disabled.
290
 */
291
function filter_format_disable($format) {
292
  db_update('filter_format')
293
    ->fields(array('status' => 0))
294
    ->condition('format', $format->format)
295
    ->execute();
296

    
297
  // Allow modules to react on text format deletion.
298
  module_invoke_all('filter_format_disable', $format);
299

    
300
  // Clear the filter cache whenever a text format is disabled.
301
  filter_formats_reset();
302
  cache_clear_all($format->format . ':', 'cache_filter', TRUE);
303
}
304

    
305
/**
306
 * Determines if a text format exists.
307
 *
308
 * @param $format_id
309
 *   The ID of the text format to check.
310
 *
311
 * @return
312
 *   TRUE if the text format exists, FALSE otherwise. Note that for disabled
313
 *   formats filter_format_exists() will return TRUE while filter_format_load()
314
 *   will return FALSE.
315
 *
316
 * @see filter_format_load()
317
 */
318
function filter_format_exists($format_id) {
319
  return (bool) db_query_range('SELECT 1 FROM {filter_format} WHERE format = :format', 0, 1, array(':format' => $format_id))->fetchField();
320
}
321

    
322
/**
323
 * Displays a text format form title.
324
 *
325
 * @param object $format
326
 *   A format object.
327
 *
328
 * @return string
329
 *   The name of the format.
330
 *
331
 * @see filter_menu()
332
 */
333
function filter_admin_format_title($format) {
334
  return $format->name;
335
}
336

    
337
/**
338
 * Implements hook_permission().
339
 */
340
function filter_permission() {
341
  $perms['administer filters'] = array(
342
    'title' => t('Administer text formats and filters'),
343
    'description' => t('Define how text is handled by combining filters into <a href="@url">text formats</a>.', array('@url' => url('admin/config/content/formats'))),
344
    'restrict access' => TRUE,
345
  );
346

    
347
  // Generate permissions for each text format. Warn the administrator that any
348
  // of them are potentially unsafe.
349
  foreach (filter_formats() as $format) {
350
    $permission = filter_permission_name($format);
351
    if (!empty($permission)) {
352
      $format_name_replacement = l($format->name, 'admin/config/content/formats/' . $format->format);
353
      $perms[$permission] = array(
354
        'title' => t("Use the !text_format text format", array('!text_format' => $format_name_replacement,)),
355
        'description' => drupal_placeholder(t('Warning: This permission may have security implications depending on how the text format is configured.')),
356
      );
357
    }
358
  }
359
  return $perms;
360
}
361

    
362
/**
363
 * Returns the machine-readable permission name for a provided text format.
364
 *
365
 * @param $format
366
 *   An object representing a text format.
367
 *
368
 * @return
369
 *   The machine-readable permission name, or FALSE if the provided text format
370
 *   is malformed or is the fallback format (which is available to all users).
371
 */
372
function filter_permission_name($format) {
373
  if (isset($format->format) && $format->format != filter_fallback_format()) {
374
    return 'use text format ' . $format->format;
375
  }
376
  return FALSE;
377
}
378

    
379
/**
380
 * Implements hook_modules_enabled().
381
 */
382
function filter_modules_enabled($modules) {
383
  // Reset the static cache of module-provided filters, in case any of the
384
  // newly enabled modules defines a new filter or alters existing ones.
385
  drupal_static_reset('filter_get_filters');
386
}
387

    
388
/**
389
 * Implements hook_modules_disabled().
390
 */
391
function filter_modules_disabled($modules) {
392
  // Reset the static cache of module-provided filters, in case any of the
393
  // newly disabled modules defined or altered any filters.
394
  drupal_static_reset('filter_get_filters');
395
}
396

    
397
/**
398
 * Retrieves a list of text formats, ordered by weight.
399
 *
400
 * @param $account
401
 *   (optional) If provided, only those formats that are allowed for this user
402
 *   account will be returned. All formats will be returned otherwise. Defaults
403
 *   to NULL.
404
 *
405
 * @return
406
 *   An array of text format objects, keyed by the format ID and ordered by
407
 *   weight.
408
 *
409
 * @see filter_formats_reset()
410
 */
411
function filter_formats($account = NULL) {
412
  global $language;
413
  $formats = &drupal_static(__FUNCTION__, array());
414

    
415
  // All available formats are cached for performance.
416
  if (!isset($formats['all'])) {
417
    if ($cache = cache_get("filter_formats:{$language->language}")) {
418
      $formats['all'] = $cache->data;
419
    }
420
    else {
421
      $formats['all'] = db_select('filter_format', 'ff')
422
        ->addTag('translatable')
423
        ->fields('ff')
424
        ->condition('status', 1)
425
        ->orderBy('weight')
426
        ->execute()
427
        ->fetchAllAssoc('format');
428

    
429
      cache_set("filter_formats:{$language->language}", $formats['all']);
430
    }
431
  }
432

    
433
  // Build a list of user-specific formats.
434
  if (isset($account) && !isset($formats['user'][$account->uid])) {
435
    $formats['user'][$account->uid] = array();
436
    foreach ($formats['all'] as $format) {
437
      if (filter_access($format, $account)) {
438
        $formats['user'][$account->uid][$format->format] = $format;
439
      }
440
    }
441
  }
442

    
443
  return isset($account) ? $formats['user'][$account->uid] : $formats['all'];
444
}
445

    
446
/**
447
 * Resets the text format caches.
448
 *
449
 * @see filter_formats()
450
 */
451
function filter_formats_reset() {
452
  cache_clear_all('filter_formats', 'cache', TRUE);
453
  cache_clear_all('filter_list_format', 'cache', TRUE);
454
  drupal_static_reset('filter_list_format');
455
  drupal_static_reset('filter_formats');
456
}
457

    
458
/**
459
 * Retrieves a list of roles that are allowed to use a given text format.
460
 *
461
 * @param $format
462
 *   An object representing the text format.
463
 *
464
 * @return
465
 *   An array of role names, keyed by role ID.
466
 */
467
function filter_get_roles_by_format($format) {
468
  // Handle the fallback format upfront (all roles have access to this format).
469
  if ($format->format == filter_fallback_format()) {
470
    return user_roles();
471
  }
472
  // Do not list any roles if the permission does not exist.
473
  $permission = filter_permission_name($format);
474
  return !empty($permission) ? user_roles(FALSE, $permission) : array();
475
}
476

    
477
/**
478
 * Retrieves a list of text formats that are allowed for a given role.
479
 *
480
 * @param $rid
481
 *   The user role ID to retrieve text formats for.
482
 *
483
 * @return
484
 *   An array of text format objects that are allowed for the role, keyed by
485
 *   the text format ID and ordered by weight.
486
 */
487
function filter_get_formats_by_role($rid) {
488
  $formats = array();
489
  foreach (filter_formats() as $format) {
490
    $roles = filter_get_roles_by_format($format);
491
    if (isset($roles[$rid])) {
492
      $formats[$format->format] = $format;
493
    }
494
  }
495
  return $formats;
496
}
497

    
498
/**
499
 * Returns the ID of the default text format for a particular user.
500
 *
501
 * The default text format is the first available format that the user is
502
 * allowed to access, when the formats are ordered by weight. It should
503
 * generally be used as a default choice when presenting the user with a list
504
 * of possible text formats (for example, in a node creation form).
505
 *
506
 * Conversely, when existing content that does not have an assigned text format
507
 * needs to be filtered for display, the default text format is the wrong
508
 * choice, because it is not guaranteed to be consistent from user to user, and
509
 * some trusted users may have an unsafe text format set by default, which
510
 * should not be used on text of unknown origin. Instead, the fallback format
511
 * returned by filter_fallback_format() should be used, since that is intended
512
 * to be a safe, consistent format that is always available to all users.
513
 *
514
 * @param $account
515
 *   (optional) The user account to check. Defaults to the currently logged-in
516
 *   user. Defaults to NULL.
517
 *
518
 * @return
519
 *   The ID of the user's default text format.
520
 *
521
 * @see filter_fallback_format()
522
 */
523
function filter_default_format($account = NULL) {
524
  global $user;
525
  if (!isset($account)) {
526
    $account = $user;
527
  }
528
  // Get a list of formats for this user, ordered by weight. The first one
529
  // available is the user's default format.
530
  $formats = filter_formats($account);
531
  $format = reset($formats);
532
  return $format->format;
533
}
534

    
535
/**
536
 * Returns the ID of the fallback text format that all users have access to.
537
 *
538
 * The fallback text format is a regular text format in every respect, except
539
 * it does not participate in the filter permission system and cannot be
540
 * disabled. It needs to exist because any user who has permission to create
541
 * formatted content must always have at least one text format they can use.
542
 *
543
 * Because the fallback format is available to all users, it should always be
544
 * configured securely. For example, when the Filter module is installed, this
545
 * format is initialized to output plain text. Installation profiles and site
546
 * administrators have the freedom to configure it further.
547
 *
548
 * Note that the fallback format is completely distinct from the default format,
549
 * which differs per user and is simply the first format which that user has
550
 * access to. The default and fallback formats are only guaranteed to be the
551
 * same for users who do not have access to any other format; otherwise, the
552
 * fallback format's weight determines its placement with respect to the user's
553
 * other formats.
554
 *
555
 * Any modules implementing a format deletion functionality must not delete this
556
 * format.
557
 *
558
 * @return
559
 *   The ID of the fallback text format.
560
 *
561
 * @see hook_filter_format_disable()
562
 * @see filter_default_format()
563
 */
564
function filter_fallback_format() {
565
  // This variable is automatically set in the database for all installations
566
  // of Drupal. In the event that it gets disabled or deleted somehow, there
567
  // is no safe default to return, since we do not want to risk making an
568
  // existing (and potentially unsafe) text format on the site automatically
569
  // available to all users. Returning NULL at least guarantees that this
570
  // cannot happen.
571
  return variable_get('filter_fallback_format');
572
}
573

    
574
/**
575
 * Returns the title of the fallback text format.
576
 *
577
 * @return string
578
 *   The title of the fallback text format.
579
 */
580
function filter_fallback_format_title() {
581
  $fallback_format = filter_format_load(filter_fallback_format());
582
  return filter_admin_format_title($fallback_format);
583
}
584

    
585
/**
586
 * Returns a list of all filters provided by modules.
587
 *
588
 * @return array
589
 *   An array of filter formats.
590
 */
591
function filter_get_filters() {
592
  $filters = &drupal_static(__FUNCTION__, array());
593

    
594
  if (empty($filters)) {
595
    foreach (module_implements('filter_info') as $module) {
596
      $info = module_invoke($module, 'filter_info');
597
      if (isset($info) && is_array($info)) {
598
        // Assign the name of the module implementing the filters and ensure
599
        // default values.
600
        foreach (array_keys($info) as $name) {
601
          $info[$name]['module'] = $module;
602
          $info[$name] += array(
603
            'description' => '',
604
            'weight' => 0,
605
          );
606
        }
607
        $filters = array_merge($filters, $info);
608
      }
609
    }
610
    // Allow modules to alter filter definitions.
611
    drupal_alter('filter_info', $filters);
612

    
613
    uasort($filters, '_filter_list_cmp');
614
  }
615

    
616
  return $filters;
617
}
618

    
619
/**
620
 * Sorts an array of filters by filter name.
621
 *
622
 * Callback for uasort() within filter_get_filters().
623
 */
624
function _filter_list_cmp($a, $b) {
625
  return strcmp($a['title'], $b['title']);
626
}
627

    
628
/**
629
 * Checks if the text in a certain text format is allowed to be cached.
630
 *
631
 * This function can be used to check whether the result of the filtering
632
 * process can be cached. A text format may allow caching depending on the
633
 * filters enabled.
634
 *
635
 * @param $format_id
636
 *   The text format ID to check.
637
 *
638
 * @return
639
 *   TRUE if the given text format allows caching, FALSE otherwise.
640
 */
641
function filter_format_allowcache($format_id) {
642
  $format = filter_format_load($format_id);
643
  return !empty($format->cache);
644
}
645

    
646
/**
647
 * Helper function to determine whether the output of a given text format can be cached.
648
 *
649
 * The output of a given text format can be cached when all enabled filters in
650
 * the text format allow caching.
651
 *
652
 * @param $format
653
 *   The text format object to check.
654
 *
655
 * @return
656
 *   TRUE if all the filters enabled in the given text format allow caching,
657
 *   FALSE otherwise.
658
 *
659
 * @see filter_format_save()
660
 */
661
function _filter_format_is_cacheable($format) {
662
  if (empty($format->filters)) {
663
    return TRUE;
664
  }
665
  $filter_info = filter_get_filters();
666
  foreach ($format->filters as $name => $filter) {
667
    // By default, 'cache' is TRUE for all filters unless specified otherwise.
668
    if (!empty($filter['status']) && isset($filter_info[$name]['cache']) && !$filter_info[$name]['cache']) {
669
      return FALSE;
670
    }
671
  }
672
  return TRUE;
673
}
674

    
675
/**
676
 * Retrieves a list of filters for a given text format.
677
 *
678
 * Note that this function returns all associated filters regardless of whether
679
 * they are enabled or disabled. All functions working with the filter
680
 * information outside of filter administration should test for $filter->status
681
 * before performing actions with the filter.
682
 *
683
 * @param $format_id
684
 *   The format ID to retrieve filters for.
685
 *
686
 * @return
687
 *   An array of filter objects associated to the given text format, keyed by
688
 *   filter name.
689
 */
690
function filter_list_format($format_id) {
691
  $filters = &drupal_static(__FUNCTION__, array());
692
  $filter_info = filter_get_filters();
693

    
694
  if (!isset($filters['all'])) {
695
    if ($cache = cache_get('filter_list_format')) {
696
      $filters['all'] = $cache->data;
697
    }
698
    else {
699
      $result = db_query('SELECT * FROM {filter} ORDER BY weight, module, name');
700
      foreach ($result as $record) {
701
        $filters['all'][$record->format][$record->name] = $record;
702
      }
703
      cache_set('filter_list_format', $filters['all']);
704
    }
705
  }
706

    
707
  if (!isset($filters[$format_id])) {
708
    $format_filters = array();
709
    $filter_map = isset($filters['all'][$format_id]) ? $filters['all'][$format_id] : array();
710
    foreach ($filter_map as $name => $filter) {
711
      if (isset($filter_info[$name])) {
712
        $filter->title = $filter_info[$name]['title'];
713
        // Unpack stored filter settings.
714
        $filter->settings = (isset($filter->settings) ? unserialize($filter->settings) : array());
715
        // Merge in default settings.
716
        if (isset($filter_info[$name]['default settings'])) {
717
          $filter->settings += $filter_info[$name]['default settings'];
718
        }
719

    
720
        $format_filters[$name] = $filter;
721
      }
722
    }
723
    $filters[$format_id] = $format_filters;
724
  }
725

    
726
  return isset($filters[$format_id]) ? $filters[$format_id] : array();
727
}
728

    
729
/**
730
 * Runs all the enabled filters on a piece of text.
731
 *
732
 * Note: Because filters can inject JavaScript or execute PHP code, security is
733
 * vital here. When a user supplies a text format, you should validate it using
734
 * filter_access() before accepting/using it. This is normally done in the
735
 * validation stage of the Form API. You should for example never make a preview
736
 * of content in a disallowed format.
737
 *
738
 * @param $text
739
 *   The text to be filtered.
740
 * @param $format_id
741
 *   (optional) The machine name of the filter format to be used to filter the
742
 *   text. Defaults to the fallback format. See filter_fallback_format().
743
 * @param $langcode
744
 *   (optional) The language code of the text to be filtered, e.g. 'en' for
745
 *   English. This allows filters to be language aware so language specific
746
 *   text replacement can be implemented. Defaults to an empty string.
747
 * @param $cache
748
 *   (optional) A Boolean indicating whether to cache the filtered output in the
749
 *   {cache_filter} table. The caller may set this to FALSE when the output is
750
 *   already cached elsewhere to avoid duplicate cache lookups and storage.
751
 *   Defaults to FALSE.
752
 *
753
 * @return
754
 *   The filtered text.
755
 *
756
 * @ingroup sanitization
757
 */
758
function check_markup($text, $format_id = NULL, $langcode = '', $cache = FALSE) {
759
  if (!isset($format_id)) {
760
    $format_id = filter_fallback_format();
761
  }
762
  // If the requested text format does not exist, the text cannot be filtered.
763
  if (!$format = filter_format_load($format_id)) {
764
    watchdog('filter', 'Missing text format: %format.', array('%format' => $format_id), WATCHDOG_ALERT);
765
    return '';
766
  }
767

    
768
  // Check for a cached version of this piece of text.
769
  $cache = $cache && !empty($format->cache);
770
  $cache_id = '';
771
  if ($cache) {
772
    $cache_id = $format->format . ':' . $langcode . ':' . hash('sha256', $text);
773
    if ($cached = cache_get($cache_id, 'cache_filter')) {
774
      return $cached->data;
775
    }
776
  }
777

    
778
  // Convert all Windows and Mac newlines to a single newline, so filters only
779
  // need to deal with one possibility.
780
  $text = str_replace(array("\r\n", "\r"), "\n", $text);
781

    
782
  // Get a complete list of filters, ordered properly.
783
  $filters = filter_list_format($format->format);
784
  $filter_info = filter_get_filters();
785

    
786
  // Give filters the chance to escape HTML-like data such as code or formulas.
787
  foreach ($filters as $name => $filter) {
788
    if ($filter->status && isset($filter_info[$name]['prepare callback']) && function_exists($filter_info[$name]['prepare callback'])) {
789
      $function = $filter_info[$name]['prepare callback'];
790
      $text = $function($text, $filter, $format, $langcode, $cache, $cache_id);
791
    }
792
  }
793

    
794
  // Perform filtering.
795
  foreach ($filters as $name => $filter) {
796
    if ($filter->status && isset($filter_info[$name]['process callback']) && function_exists($filter_info[$name]['process callback'])) {
797
      $function = $filter_info[$name]['process callback'];
798
      $text = $function($text, $filter, $format, $langcode, $cache, $cache_id);
799
    }
800
  }
801

    
802
  // Cache the filtered text. This cache is infinitely valid. It becomes
803
  // obsolete when $text changes (which leads to a new $cache_id). It is
804
  // automatically flushed when the text format is updated.
805
  // @see filter_format_save()
806
  if ($cache) {
807
    cache_set($cache_id, $text, 'cache_filter');
808
  }
809

    
810
  return $text;
811
}
812

    
813
/**
814
 * Expands an element into a base element with text format selector attached.
815
 *
816
 * The form element will be expanded into two separate form elements, one
817
 * holding the original element, and the other holding the text format selector:
818
 * - value: Holds the original element, having its #type changed to the value of
819
 *   #base_type or 'textarea' by default.
820
 * - format: Holds the text format fieldset and the text format selection, using
821
 *   the text format id specified in #format or the user's default format by
822
 *   default, if NULL.
823
 *
824
 * The resulting value for the element will be an array holding the value and
825
 * the format. For example, the value for the body element will be:
826
 * @code
827
 *   $form_state['values']['body']['value'] = 'foo';
828
 *   $form_state['values']['body']['format'] = 'foo';
829
 * @endcode
830
 *
831
 * @param $element
832
 *   The form element to process. Properties used:
833
 *   - #base_type: The form element #type to use for the 'value' element.
834
 *     'textarea' by default.
835
 *   - #format: (optional) The text format ID to preselect. If NULL or not set,
836
 *     the default format for the current user will be used.
837
 *
838
 * @return
839
 *   The expanded element.
840
 */
841
function filter_process_format($element) {
842
  global $user;
843

    
844
  // Ensure that children appear as subkeys of this element.
845
  $element['#tree'] = TRUE;
846
  $blacklist = array(
847
    // Make form_builder() regenerate child properties.
848
    '#parents',
849
    '#id',
850
    '#name',
851
    // Do not copy this #process function to prevent form_builder() from
852
    // recursing infinitely.
853
    '#process',
854
    // Description is handled by theme_text_format_wrapper().
855
    '#description',
856
    // Ensure proper ordering of children.
857
    '#weight',
858
    // Properties already processed for the parent element.
859
    '#prefix',
860
    '#suffix',
861
    '#attached',
862
    '#processed',
863
    '#theme_wrappers',
864
  );
865
  // Move this element into sub-element 'value'.
866
  unset($element['value']);
867
  foreach (element_properties($element) as $key) {
868
    if (!in_array($key, $blacklist)) {
869
      $element['value'][$key] = $element[$key];
870
    }
871
  }
872

    
873
  $element['value']['#type'] = $element['#base_type'];
874
  $element['value'] += element_info($element['#base_type']);
875

    
876
  // Turn original element into a text format wrapper.
877
  $path = drupal_get_path('module', 'filter');
878
  $element['#attached']['js'][] = $path . '/filter.js';
879
  $element['#attached']['css'][] = $path . '/filter.css';
880

    
881
  // Setup child container for the text format widget.
882
  $element['format'] = array(
883
    '#type' => 'fieldset',
884
    '#attributes' => array('class' => array('filter-wrapper')),
885
  );
886

    
887
  // Prepare text format guidelines.
888
  $element['format']['guidelines'] = array(
889
    '#type' => 'container',
890
    '#attributes' => array('class' => array('filter-guidelines')),
891
    '#weight' => 20,
892
  );
893
  // Get a list of formats that the current user has access to.
894
  $formats = filter_formats($user);
895
  foreach ($formats as $format) {
896
    $options[$format->format] = $format->name;
897
    $element['format']['guidelines'][$format->format] = array(
898
      '#theme' => 'filter_guidelines',
899
      '#format' => $format,
900
    );
901
  }
902

    
903
  // Use the default format for this user if none was selected.
904
  if (!isset($element['#format'])) {
905
    $element['#format'] = filter_default_format($user);
906
  }
907

    
908
  $element['format']['format'] = array(
909
    '#type' => 'select',
910
    '#title' => t('Text format'),
911
    '#options' => $options,
912
    '#default_value' => $element['#format'],
913
    '#access' => count($formats) > 1,
914
    '#weight' => 10,
915
    '#attributes' => array('class' => array('filter-list')),
916
    '#parents' => array_merge($element['#parents'], array('format')),
917
  );
918

    
919
  $element['format']['help'] = array(
920
    '#type' => 'container',
921
    '#theme' => 'filter_tips_more_info',
922
    '#attributes' => array('class' => array('filter-help')),
923
    '#weight' => 0,
924
  );
925

    
926
  $all_formats = filter_formats();
927
  $format_exists = isset($all_formats[$element['#format']]);
928
  $user_has_access = isset($formats[$element['#format']]);
929
  $user_is_admin = user_access('administer filters');
930

    
931
  // If the stored format does not exist, administrators have to assign a new
932
  // format.
933
  if (!$format_exists && $user_is_admin) {
934
    $element['format']['format']['#required'] = TRUE;
935
    $element['format']['format']['#default_value'] = NULL;
936
    // Force access to the format selector (it may have been denied above if
937
    // the user only has access to a single format).
938
    $element['format']['format']['#access'] = TRUE;
939
  }
940
  // Disable this widget, if the user is not allowed to use the stored format,
941
  // or if the stored format does not exist. The 'administer filters' permission
942
  // only grants access to the filter administration, not to all formats.
943
  elseif (!$user_has_access || !$format_exists) {
944
    // Overload default values into #value to make them unalterable.
945
    $element['value']['#value'] = $element['value']['#default_value'];
946
    $element['format']['format']['#value'] = $element['format']['format']['#default_value'];
947

    
948
    // Prepend #pre_render callback to replace field value with user notice
949
    // prior to rendering.
950
    $element['value'] += array('#pre_render' => array());
951
    array_unshift($element['value']['#pre_render'], 'filter_form_access_denied');
952

    
953
    // Cosmetic adjustments.
954
    if (isset($element['value']['#rows'])) {
955
      $element['value']['#rows'] = 3;
956
    }
957
    $element['value']['#disabled'] = TRUE;
958
    $element['value']['#resizable'] = FALSE;
959

    
960
    // Hide the text format selector and any other child element (such as text
961
    // field's summary).
962
    foreach (element_children($element) as $key) {
963
      if ($key != 'value') {
964
        $element[$key]['#access'] = FALSE;
965
      }
966
    }
967
  }
968

    
969
  return $element;
970
}
971

    
972
/**
973
 * Render API callback: Hides the field value of 'text_format' elements.
974
 *
975
 * To not break form processing and previews if a user does not have access to a
976
 * stored text format, the expanded form elements in filter_process_format() are
977
 * forced to take over the stored #default_values for 'value' and 'format'.
978
 * However, to prevent the unfiltered, original #value from being displayed to
979
 * the user, we replace it with a friendly notice here.
980
 *
981
 * @see filter_process_format()
982
 */
983
function filter_form_access_denied($element) {
984
  $element['#value'] = t('This field has been disabled because you do not have sufficient permissions to edit it.');
985
  return $element;
986
}
987

    
988
/**
989
 * Returns HTML for a text format-enabled form element.
990
 *
991
 * @param $variables
992
 *   An associative array containing:
993
 *   - element: A render element containing #children and #description.
994
 *
995
 * @ingroup themeable
996
 */
997
function theme_text_format_wrapper($variables) {
998
  $element = $variables['element'];
999
  $output = '<div class="text-format-wrapper">';
1000
  $output .= $element['#children'];
1001
  if (!empty($element['#description'])) {
1002
    $output .= '<div class="description">' . $element['#description'] . '</div>';
1003
  }
1004
  $output .= "</div>\n";
1005

    
1006
  return $output;
1007
}
1008

    
1009
/**
1010
 * Checks if a user has access to a particular text format.
1011
 *
1012
 * @param $format
1013
 *   An object representing the text format.
1014
 * @param $account
1015
 *   (optional) The user account to check access for; if omitted, the currently
1016
 *   logged-in user is used. Defaults to NULL.
1017
 *
1018
 * @return
1019
 *   Boolean TRUE if the user is allowed to access the given format.
1020
 */
1021
function filter_access($format, $account = NULL) {
1022
  global $user;
1023
  if (!isset($account)) {
1024
    $account = $user;
1025
  }
1026
  // Handle special cases up front. All users have access to the fallback
1027
  // format.
1028
  if ($format->format == filter_fallback_format()) {
1029
    return TRUE;
1030
  }
1031
  // Check the permission if one exists; otherwise, we have a non-existent
1032
  // format so we return FALSE.
1033
  $permission = filter_permission_name($format);
1034
  return !empty($permission) && user_access($permission, $account);
1035
}
1036

    
1037
/**
1038
 * Retrieves the filter tips.
1039
 *
1040
 * @param $format_id
1041
 *   The ID of the text format for which to retrieve tips, or -1 to return tips
1042
 *   for all formats accessible to the current user.
1043
 * @param $long
1044
 *   (optional) Boolean indicating whether the long form of tips should be
1045
 *   returned. Defaults to FALSE.
1046
 *
1047
 * @return
1048
 *   An associative array of filtering tips, keyed by filter name. Each
1049
 *   filtering tip is an associative array with elements:
1050
 *   - tip: Tip text.
1051
 *   - id: Filter ID.
1052
 */
1053
function _filter_tips($format_id, $long = FALSE) {
1054
  global $user;
1055

    
1056
  $formats = filter_formats($user);
1057
  $filter_info = filter_get_filters();
1058

    
1059
  $tips = array();
1060

    
1061
  // If only listing one format, extract it from the $formats array.
1062
  if ($format_id != -1) {
1063
    $formats = array($formats[$format_id]);
1064
  }
1065

    
1066
  foreach ($formats as $format) {
1067
    $filters = filter_list_format($format->format);
1068
    $tips[$format->name] = array();
1069
    foreach ($filters as $name => $filter) {
1070
      if ($filter->status && isset($filter_info[$name]['tips callback']) && function_exists($filter_info[$name]['tips callback'])) {
1071
        $tip = $filter_info[$name]['tips callback']($filter, $format, $long);
1072
        if (isset($tip)) {
1073
          $tips[$format->name][$name] = array('tip' => $tip, 'id' => $name);
1074
        }
1075
      }
1076
    }
1077
  }
1078

    
1079
  return $tips;
1080
}
1081

    
1082
/**
1083
 * Parses an HTML snippet and returns it as a DOM object.
1084
 *
1085
 * This function loads the body part of a partial (X)HTML document and returns
1086
 * a full DOMDocument object that represents this document. You can use
1087
 * filter_dom_serialize() to serialize this DOMDocument back to a XHTML
1088
 * snippet.
1089
 *
1090
 * @param $text
1091
 *   The partial (X)HTML snippet to load. Invalid mark-up will be corrected on
1092
 *   import.
1093
 * @return
1094
 *   A DOMDocument that represents the loaded (X)HTML snippet.
1095
 */
1096
function filter_dom_load($text) {
1097
  $dom_document = new DOMDocument();
1098
  // Ignore warnings during HTML soup loading.
1099
  @$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>');
1100

    
1101
  return $dom_document;
1102
}
1103

    
1104
/**
1105
 * Converts a DOM object back to an HTML snippet.
1106
 *
1107
 * The function serializes the body part of a DOMDocument back to an XHTML
1108
 * snippet. The resulting XHTML snippet will be properly formatted to be
1109
 * compatible with HTML user agents.
1110
 *
1111
 * @param $dom_document
1112
 *   A DOMDocument object to serialize, only the tags below
1113
 *   the first <body> node will be converted.
1114
 *
1115
 * @return
1116
 *   A valid (X)HTML snippet, as a string.
1117
 */
1118
function filter_dom_serialize($dom_document) {
1119
  $body_node = $dom_document->getElementsByTagName('body')->item(0);
1120
  $body_content = '';
1121

    
1122
  foreach ($body_node->getElementsByTagName('script') as $node) {
1123
    filter_dom_serialize_escape_cdata_element($dom_document, $node);
1124
  }
1125

    
1126
  foreach ($body_node->getElementsByTagName('style') as $node) {
1127
    filter_dom_serialize_escape_cdata_element($dom_document, $node, '/*', '*/');
1128
  }
1129

    
1130
  foreach ($body_node->childNodes as $child_node) {
1131
    $body_content .= $dom_document->saveXML($child_node);
1132
  }
1133
  return preg_replace('|<([^> ]*)/>|i', '<$1 />', $body_content);
1134
}
1135

    
1136
/**
1137
 * Adds comments around the <!CDATA section in a dom element.
1138
 *
1139
 * DOMDocument::loadHTML in filter_dom_load() makes CDATA sections from the
1140
 * contents of inline script and style tags.  This can cause HTML 4 browsers to
1141
 * throw exceptions.
1142
 *
1143
 * This function attempts to solve the problem by creating a DocumentFragment
1144
 * and imitating the behavior in drupal_get_js(), commenting the CDATA tag.
1145
 *
1146
 * @param $dom_document
1147
 *   The DOMDocument containing the $dom_element.
1148
 * @param $dom_element
1149
 *   The element potentially containing a CDATA node.
1150
 * @param $comment_start
1151
 *   (optional) A string to use as a comment start marker to escape the CDATA
1152
 *   declaration. Defaults to '//'.
1153
 * @param $comment_end
1154
 *   (optional) A string to use as a comment end marker to escape the CDATA
1155
 *   declaration. Defaults to an empty string.
1156
 */
1157
function filter_dom_serialize_escape_cdata_element($dom_document, $dom_element, $comment_start = '//', $comment_end = '') {
1158
  foreach ($dom_element->childNodes as $node) {
1159
    if (get_class($node) == 'DOMCdataSection') {
1160
      // See drupal_get_js().  This code is more or less duplicated there.
1161
      $embed_prefix = "\n<!--{$comment_start}--><![CDATA[{$comment_start} ><!--{$comment_end}\n";
1162
      $embed_suffix = "\n{$comment_start}--><!]]>{$comment_end}\n";
1163

    
1164
      // Prevent invalid cdata escaping as this would throw a DOM error.
1165
      // This is the same behavior as found in libxml2.
1166
      // Related W3C standard: http://www.w3.org/TR/REC-xml/#dt-cdsection
1167
      // Fix explanation: http://en.wikipedia.org/wiki/CDATA#Nesting
1168
      $data = str_replace(']]>', ']]]]><![CDATA[>', $node->data);
1169

    
1170
      $fragment = $dom_document->createDocumentFragment();
1171
      $fragment->appendXML($embed_prefix . $data . $embed_suffix);
1172
      $dom_element->appendChild($fragment);
1173
      $dom_element->removeChild($node);
1174
    }
1175
  }
1176
}
1177

    
1178
/**
1179
 * Returns HTML for a link to the more extensive filter tips.
1180
 *
1181
 * @ingroup themeable
1182
 */
1183
function theme_filter_tips_more_info() {
1184
  return '<p>' . l(t('More information about text formats'), 'filter/tips', array('attributes' => array('target' => '_blank'))) . '</p>';
1185
}
1186

    
1187
/**
1188
 * Returns HTML for guidelines for a text format.
1189
 *
1190
 * @param $variables
1191
 *   An associative array containing:
1192
 *   - format: An object representing a text format.
1193
 *
1194
 * @ingroup themeable
1195
 */
1196
function theme_filter_guidelines($variables) {
1197
  $format = $variables['format'];
1198
  $attributes['class'][] = 'filter-guidelines-item';
1199
  $attributes['class'][] = 'filter-guidelines-' . $format->format;
1200
  $output = '<div' . drupal_attributes($attributes) . '>';
1201
  $output .= '<h3>' . check_plain($format->name) . '</h3>';
1202
  $output .= theme('filter_tips', array('tips' => _filter_tips($format->format, FALSE)));
1203
  $output .= '</div>';
1204
  return $output;
1205
}
1206

    
1207
/**
1208
 * @defgroup standard_filters Standard filters
1209
 * @{
1210
 * Filters implemented by the Filter module.
1211
 */
1212

    
1213
/**
1214
 * Implements hook_filter_info().
1215
 */
1216
function filter_filter_info() {
1217
  $filters['filter_html'] = array(
1218
    'title' => t('Limit allowed HTML tags'),
1219
    'process callback' => '_filter_html',
1220
    'settings callback' => '_filter_html_settings',
1221
    'default settings' => array(
1222
      'allowed_html' => '<a> <em> <strong> <cite> <blockquote> <code> <ul> <ol> <li> <dl> <dt> <dd>',
1223
      'filter_html_help' => 1,
1224
      'filter_html_nofollow' => 0,
1225
    ),
1226
    'tips callback' => '_filter_html_tips',
1227
    'weight' => -10,
1228
  );
1229
  $filters['filter_autop'] = array(
1230
    'title' => t('Convert line breaks into HTML (i.e. <code>&lt;br&gt;</code> and <code>&lt;p&gt;</code>)'),
1231
    'process callback' => '_filter_autop',
1232
    'tips callback' => '_filter_autop_tips',
1233
  );
1234
  $filters['filter_url'] = array(
1235
    'title' => t('Convert URLs into links'),
1236
    'process callback' => '_filter_url',
1237
    'settings callback' => '_filter_url_settings',
1238
    'default settings' => array(
1239
      'filter_url_length' => 72,
1240
    ),
1241
    'tips callback' => '_filter_url_tips',
1242
  );
1243
  $filters['filter_htmlcorrector'] = array(
1244
    'title' =>  t('Correct faulty and chopped off HTML'),
1245
    'process callback' => '_filter_htmlcorrector',
1246
    'weight' => 10,
1247
  );
1248
  $filters['filter_html_escape'] = array(
1249
    'title' => t('Display any HTML as plain text'),
1250
    'process callback' => '_filter_html_escape',
1251
    'tips callback' => '_filter_html_escape_tips',
1252
    'weight' => -10,
1253
  );
1254
  return $filters;
1255
}
1256

    
1257
/**
1258
 * Implements callback_filter_settings().
1259
 *
1260
 * Filter settings callback for the HTML content filter.
1261
 */
1262
function _filter_html_settings($form, &$form_state, $filter, $format, $defaults) {
1263
  $filter->settings += $defaults;
1264

    
1265
  $settings['allowed_html'] = array(
1266
    '#type' => 'textfield',
1267
    '#title' => t('Allowed HTML tags'),
1268
    '#default_value' => $filter->settings['allowed_html'],
1269
    '#maxlength' => 1024,
1270
    '#description' => t('A list of HTML tags that can be used. JavaScript event attributes, JavaScript URLs, and CSS are always stripped.'),
1271
  );
1272
  $settings['filter_html_help'] = array(
1273
    '#type' => 'checkbox',
1274
    '#title' => t('Display basic HTML help in long filter tips'),
1275
    '#default_value' => $filter->settings['filter_html_help'],
1276
  );
1277
  $settings['filter_html_nofollow'] = array(
1278
    '#type' => 'checkbox',
1279
    '#title' => t('Add rel="nofollow" to all links'),
1280
    '#default_value' => $filter->settings['filter_html_nofollow'],
1281
  );
1282
  return $settings;
1283
}
1284

    
1285
/**
1286
 * Implements callback_filter_process().
1287
 *
1288
 * Provides filtering of input into accepted HTML.
1289
 */
1290
function _filter_html($text, $filter) {
1291
  $allowed_tags = preg_split('/\s+|<|>/', $filter->settings['allowed_html'], -1, PREG_SPLIT_NO_EMPTY);
1292
  $text = filter_xss($text, $allowed_tags);
1293

    
1294
  if ($filter->settings['filter_html_nofollow']) {
1295
    $html_dom = filter_dom_load($text);
1296
    $links = $html_dom->getElementsByTagName('a');
1297
    foreach ($links as $link) {
1298
      $link->setAttribute('rel', 'nofollow');
1299
    }
1300
    $text = filter_dom_serialize($html_dom);
1301
  }
1302

    
1303
  return trim($text);
1304
}
1305

    
1306
/**
1307
 * Implements callback_filter_tips().
1308
 *
1309
 * Provides help for the HTML filter.
1310
 *
1311
 * @see filter_filter_info()
1312
 */
1313
function _filter_html_tips($filter, $format, $long = FALSE) {
1314
  global $base_url;
1315

    
1316
  if (!($allowed_html = $filter->settings['allowed_html'])) {
1317
    return;
1318
  }
1319
  $output = t('Allowed HTML tags: @tags', array('@tags' => $allowed_html));
1320
  if (!$long) {
1321
    return $output;
1322
  }
1323

    
1324
  $output = '<p>' . $output . '</p>';
1325
  if (!$filter->settings['filter_html_help']) {
1326
    return $output;
1327
  }
1328

    
1329
  $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>';
1330
  $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>';
1331
  $tips = array(
1332
    'a' => array(t('Anchors are used to make links to other pages.'), '<a href="' . $base_url . '">' . check_plain(variable_get('site_name', 'Drupal')) . '</a>'),
1333
    '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')),
1334
    '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>'),
1335
    'strong' => array(t('Strong', array(), array('context' => 'Font weight')), '<strong>' . t('Strong', array(), array('context' => 'Font weight')) . '</strong>'),
1336
    'em' => array(t('Emphasized'), '<em>' . t('Emphasized') . '</em>'),
1337
    'cite' => array(t('Cited'), '<cite>' . t('Cited') . '</cite>'),
1338
    'code' => array(t('Coded text used to show programming source code'), '<code>' . t('Coded') . '</code>'),
1339
    'b' => array(t('Bolded'), '<b>' . t('Bolded') . '</b>'),
1340
    'u' => array(t('Underlined'), '<u>' . t('Underlined') . '</u>'),
1341
    'i' => array(t('Italicized'), '<i>' . t('Italicized') . '</i>'),
1342
    'sup' => array(t('Superscripted'), t('<sup>Super</sup>scripted')),
1343
    'sub' => array(t('Subscripted'), t('<sub>Sub</sub>scripted')),
1344
    'pre' => array(t('Preformatted'), '<pre>' . t('Preformatted') . '</pre>'),
1345
    'abbr' => array(t('Abbreviation'), t('<abbr title="Abbreviation">Abbrev.</abbr>')),
1346
    'acronym' => array(t('Acronym'), t('<acronym title="Three-Letter Acronym">TLA</acronym>')),
1347
    'blockquote' => array(t('Block quoted'), '<blockquote>' . t('Block quoted') . '</blockquote>'),
1348
    'q' => array(t('Quoted inline'), '<q>' . t('Quoted inline') . '</q>'),
1349
    // Assumes and describes tr, td, th.
1350
    'table' => array(t('Table'), '<table> <tr><th>' . t('Table header') . '</th></tr> <tr><td>' . t('Table cell') . '</td></tr> </table>'),
1351
    'tr' => NULL, 'td' => NULL, 'th' => NULL,
1352
    'del' => array(t('Deleted'), '<del>' . t('Deleted') . '</del>'),
1353
    'ins' => array(t('Inserted'), '<ins>' . t('Inserted') . '</ins>'),
1354
     // Assumes and describes li.
1355
    '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>'),
1356
    '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>'),
1357
    'li' => NULL,
1358
    // Assumes and describes dt and dd.
1359
    '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>'),
1360
    'dt' => NULL, 'dd' => NULL,
1361
    'h1' => array(t('Heading'), '<h1>' . t('Title') . '</h1>'),
1362
    'h2' => array(t('Heading'), '<h2>' . t('Subtitle') . '</h2>'),
1363
    'h3' => array(t('Heading'), '<h3>' . t('Subtitle three') . '</h3>'),
1364
    'h4' => array(t('Heading'), '<h4>' . t('Subtitle four') . '</h4>'),
1365
    'h5' => array(t('Heading'), '<h5>' . t('Subtitle five') . '</h5>'),
1366
    'h6' => array(t('Heading'), '<h6>' . t('Subtitle six') . '</h6>')
1367
  );
1368
  $header = array(t('Tag Description'), t('You Type'), t('You Get'));
1369
  preg_match_all('/<([a-z0-9]+)[^a-z0-9]/i', $allowed_html, $out);
1370
  foreach ($out[1] as $tag) {
1371
    if (!empty($tips[$tag])) {
1372
      $rows[] = array(
1373
        array('data' => $tips[$tag][0], 'class' => array('description')),
1374
        array('data' => '<code>' . check_plain($tips[$tag][1]) . '</code>', 'class' => array('type')),
1375
        array('data' => $tips[$tag][1], 'class' => array('get'))
1376
      );
1377
    }
1378
    else {
1379
      $rows[] = array(
1380
        array('data' => t('No help provided for tag %tag.', array('%tag' => $tag)), 'class' => array('description'), 'colspan' => 3),
1381
      );
1382
    }
1383
  }
1384
  $output .= theme('table', array('header' => $header, 'rows' => $rows));
1385

    
1386
  $output .= '<p>' . t('Most unusual characters can be directly entered without any problems.') . '</p>';
1387
  $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>';
1388

    
1389
  $entities = array(
1390
    array(t('Ampersand'), '&amp;'),
1391
    array(t('Greater than'), '&gt;'),
1392
    array(t('Less than'), '&lt;'),
1393
    array(t('Quotation mark'), '&quot;'),
1394
  );
1395
  $header = array(t('Character Description'), t('You Type'), t('You Get'));
1396
  unset($rows);
1397
  foreach ($entities as $entity) {
1398
    $rows[] = array(
1399
      array('data' => $entity[0], 'class' => array('description')),
1400
      array('data' => '<code>' . check_plain($entity[1]) . '</code>', 'class' => array('type')),
1401
      array('data' => $entity[1], 'class' => array('get'))
1402
    );
1403
  }
1404
  $output .= theme('table', array('header' => $header, 'rows' => $rows));
1405
  return $output;
1406
}
1407

    
1408
/**
1409
 * Implements callback_filter_settings().
1410
 *
1411
 * Provides settings for the URL filter.
1412
 *
1413
 * @see filter_filter_info()
1414
 */
1415
function _filter_url_settings($form, &$form_state, $filter, $format, $defaults) {
1416
  $filter->settings += $defaults;
1417

    
1418
  $settings['filter_url_length'] = array(
1419
    '#type' => 'textfield',
1420
    '#title' => t('Maximum link text length'),
1421
    '#default_value' => $filter->settings['filter_url_length'],
1422
    '#size' => 5,
1423
    '#maxlength' => 4,
1424
    '#field_suffix' => t('characters'),
1425
    '#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.'),
1426
    '#element_validate' => array('element_validate_integer_positive'),
1427
  );
1428
  return $settings;
1429
}
1430

    
1431
/**
1432
 * Implements callback_filter_process().
1433
 *
1434
 * Converts text into hyperlinks automatically.
1435
 *
1436
 * This filter identifies and makes clickable three types of "links".
1437
 * - URLs like http://example.com.
1438
 * - E-mail addresses like name@example.com.
1439
 * - Web addresses without the "http://" protocol defined, like www.example.com.
1440
 * Each type must be processed separately, as there is no one regular
1441
 * expression that could possibly match all of the cases in one pass.
1442
 */
1443
function _filter_url($text, $filter) {
1444
  // Tags to skip and not recurse into.
1445
  $ignore_tags = 'a|script|style|code|pre';
1446

    
1447
  // Pass length to regexp callback.
1448
  _filter_url_trim(NULL, $filter->settings['filter_url_length']);
1449

    
1450
  // Create an array which contains the regexps for each type of link.
1451
  // The key to the regexp is the name of a function that is used as
1452
  // callback function to process matches of the regexp. The callback function
1453
  // is to return the replacement for the match. The array is used and
1454
  // matching/replacement done below inside some loops.
1455
  $tasks = array();
1456

    
1457
  // Prepare protocols pattern for absolute URLs.
1458
  // check_url() will replace any bad protocols with HTTP, so we need to support
1459
  // the identical list. While '//' is technically optional for MAILTO only,
1460
  // we cannot cleanly differ between protocols here without hard-coding MAILTO,
1461
  // so '//' is optional for all protocols.
1462
  // @see filter_xss_bad_protocol()
1463
  $protocols = variable_get('filter_allowed_protocols', array('ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', 'webcal'));
1464
  $protocols = implode(':(?://)?|', $protocols) . ':(?://)?';
1465

    
1466
  // Prepare domain name pattern.
1467
  // The ICANN seems to be on track towards accepting more diverse top level
1468
  // domains, so this pattern has been "future-proofed" to allow for TLDs
1469
  // of length 2-64.
1470
  $domain = '(?:[A-Za-z0-9._+-]+\.)?[A-Za-z]{2,64}\b';
1471
  $ip = '(?:[0-9]{1,3}\.){3}[0-9]{1,3}';
1472
  $auth = '[a-zA-Z0-9:%_+*~#?&=.,/;-]+@';
1473
  $trail = '[a-zA-Z0-9:%_+*~#&\[\]=/;?!\.,-]*[a-zA-Z0-9:%_+*~#&\[\]=/;-]';
1474

    
1475
  // Prepare pattern for optional trailing punctuation.
1476
  // Even these characters could have a valid meaning for the URL, such usage is
1477
  // rare compared to using a URL at the end of or within a sentence, so these
1478
  // trailing characters are optionally excluded.
1479
  $punctuation = '[\.,?!]*?';
1480

    
1481
  // Match absolute URLs.
1482
  $url_pattern = "(?:$auth)?(?:$domain|$ip)/?(?:$trail)?";
1483
  $pattern = "`((?:$protocols)(?:$url_pattern))($punctuation)`";
1484
  $tasks['_filter_url_parse_full_links'] = $pattern;
1485

    
1486
  // Match e-mail addresses.
1487
  $url_pattern = "[A-Za-z0-9._-]{1,254}@(?:$domain)";
1488
  $pattern = "`($url_pattern)`";
1489
  $tasks['_filter_url_parse_email_links'] = $pattern;
1490

    
1491
  // Match www domains.
1492
  $url_pattern = "www\.(?:$domain)/?(?:$trail)?";
1493
  $pattern = "`($url_pattern)($punctuation)`";
1494
  $tasks['_filter_url_parse_partial_links'] = $pattern;
1495

    
1496
  // Each type of URL needs to be processed separately. The text is joined and
1497
  // re-split after each task, since all injected HTML tags must be correctly
1498
  // protected before the next task.
1499
  foreach ($tasks as $task => $pattern) {
1500
    // HTML comments need to be handled separately, as they may contain HTML
1501
    // markup, especially a '>'. Therefore, remove all comment contents and add
1502
    // them back later.
1503
    _filter_url_escape_comments('', TRUE);
1504
    $text = preg_replace_callback('`<!--(.*?)-->`s', '_filter_url_escape_comments', $text);
1505

    
1506
    // Split at all tags; ensures that no tags or attributes are processed.
1507
    $chunks = preg_split('/(<.+?>)/is', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
1508
    // PHP ensures that the array consists of alternating delimiters and
1509
    // literals, and begins and ends with a literal (inserting NULL as
1510
    // required). Therefore, the first chunk is always text:
1511
    $chunk_type = 'text';
1512
    // If a tag of $ignore_tags is found, it is stored in $open_tag and only
1513
    // removed when the closing tag is found. Until the closing tag is found,
1514
    // no replacements are made.
1515
    $open_tag = '';
1516

    
1517
    for ($i = 0; $i < count($chunks); $i++) {
1518
      if ($chunk_type == 'text') {
1519
        // Only process this text if there are no unclosed $ignore_tags.
1520
        if ($open_tag == '') {
1521
          // If there is a match, inject a link into this chunk via the callback
1522
          // function contained in $task.
1523
          $chunks[$i] = preg_replace_callback($pattern, $task, $chunks[$i]);
1524
        }
1525
        // Text chunk is done, so next chunk must be a tag.
1526
        $chunk_type = 'tag';
1527
      }
1528
      else {
1529
        // Only process this tag if there are no unclosed $ignore_tags.
1530
        if ($open_tag == '') {
1531
          // Check whether this tag is contained in $ignore_tags.
1532
          if (preg_match("`<($ignore_tags)(?:\s|>)`i", $chunks[$i], $matches)) {
1533
            $open_tag = $matches[1];
1534
          }
1535
        }
1536
        // Otherwise, check whether this is the closing tag for $open_tag.
1537
        else {
1538
          if (preg_match("`<\/$open_tag>`i", $chunks[$i], $matches)) {
1539
            $open_tag = '';
1540
          }
1541
        }
1542
        // Tag chunk is done, so next chunk must be text.
1543
        $chunk_type = 'text';
1544
      }
1545
    }
1546

    
1547
    $text = implode($chunks);
1548
    // Revert back to the original comment contents
1549
    _filter_url_escape_comments('', FALSE);
1550
    $text = preg_replace_callback('`<!--(.*?)-->`', '_filter_url_escape_comments', $text);
1551
  }
1552

    
1553
  return $text;
1554
}
1555

    
1556
/**
1557
 * Makes links out of absolute URLs.
1558
 *
1559
 * Callback for preg_replace_callback() within _filter_url().
1560
 */
1561
function _filter_url_parse_full_links($match) {
1562
  // The $i:th parenthesis in the regexp contains the URL.
1563
  $i = 1;
1564

    
1565
  $match[$i] = decode_entities($match[$i]);
1566
  $caption = check_plain(_filter_url_trim($match[$i]));
1567
  $match[$i] = check_plain($match[$i]);
1568
  return '<a href="' . $match[$i] . '">' . $caption . '</a>' . $match[$i + 1];
1569
}
1570

    
1571
/**
1572
 * Makes links out of e-mail addresses.
1573
 *
1574
 * Callback for preg_replace_callback() within _filter_url().
1575
 */
1576
function _filter_url_parse_email_links($match) {
1577
  // The $i:th parenthesis in the regexp contains the URL.
1578
  $i = 0;
1579

    
1580
  $match[$i] = decode_entities($match[$i]);
1581
  $caption = check_plain(_filter_url_trim($match[$i]));
1582
  $match[$i] = check_plain($match[$i]);
1583
  return '<a href="mailto:' . $match[$i] . '">' . $caption . '</a>';
1584
}
1585

    
1586
/**
1587
 * Makes links out of domain names starting with "www."
1588
 *
1589
 * Callback for preg_replace_callback() within _filter_url().
1590
 */
1591
function _filter_url_parse_partial_links($match) {
1592
  // The $i:th parenthesis in the regexp contains the URL.
1593
  $i = 1;
1594

    
1595
  $match[$i] = decode_entities($match[$i]);
1596
  $caption = check_plain(_filter_url_trim($match[$i]));
1597
  $match[$i] = check_plain($match[$i]);
1598
  return '<a href="http://' . $match[$i] . '">' . $caption . '</a>' . $match[$i + 1];
1599
}
1600

    
1601
/**
1602
 * Escapes the contents of HTML comments.
1603
 *
1604
 * Callback for preg_replace_callback() within _filter_url().
1605
 *
1606
 * @param $match
1607
 *   An array containing matches to replace from preg_replace_callback(),
1608
 *   whereas $match[1] is expected to contain the content to be filtered.
1609
 * @param $escape
1610
 *   (optional) A Boolean indicating whether to escape (TRUE) or unescape
1611
 *   comments (FALSE). Defaults to NULL, indicating neither. If TRUE, statically
1612
 *   cached $comments are reset.
1613
 */
1614
function _filter_url_escape_comments($match, $escape = NULL) {
1615
  static $mode, $comments = array();
1616

    
1617
  if (isset($escape)) {
1618
    $mode = $escape;
1619
    if ($escape){
1620
      $comments = array();
1621
    }
1622
    return;
1623
  }
1624

    
1625
  // Replace all HTML coments with a '<!-- [hash] -->' placeholder.
1626
  if ($mode) {
1627
    $content = $match[1];
1628
    $hash = md5($content);
1629
    $comments[$hash] = $content;
1630
    return "<!-- $hash -->";
1631
  }
1632
  // Or replace placeholders with actual comment contents.
1633
  else {
1634
    $hash = $match[1];
1635
    $hash = trim($hash);
1636
    $content = $comments[$hash];
1637
    return "<!--$content-->";
1638
  }
1639
}
1640

    
1641
/**
1642
 * Shortens long URLs to http://www.example.com/long/url...
1643
 */
1644
function _filter_url_trim($text, $length = NULL) {
1645
  static $_length;
1646
  if ($length !== NULL) {
1647
    $_length = $length;
1648
  }
1649

    
1650
  // Use +3 for '...' string length.
1651
  if ($_length && strlen($text) > $_length + 3) {
1652
    $text = substr($text, 0, $_length) . '...';
1653
  }
1654

    
1655
  return $text;
1656
}
1657

    
1658
/**
1659
 * Implements callback_filter_tips().
1660
 *
1661
 * Provides help for the URL filter.
1662
 *
1663
 * @see filter_filter_info()
1664
 */
1665
function _filter_url_tips($filter, $format, $long = FALSE) {
1666
  return t('Web page addresses and e-mail addresses turn into links automatically.');
1667
}
1668

    
1669
/**
1670
 * Implements callback_filter_process().
1671
 *
1672
 * Scans the input and makes sure that HTML tags are properly closed.
1673
 */
1674
function _filter_htmlcorrector($text) {
1675
  return filter_dom_serialize(filter_dom_load($text));
1676
}
1677

    
1678
/**
1679
 * Implements callback_filter_process().
1680
 *
1681
 * Converts line breaks into <p> and <br> in an intelligent fashion.
1682
 *
1683
 * Based on: http://photomatt.net/scripts/autop
1684
 */
1685
function _filter_autop($text) {
1686
  // All block level tags
1687
  $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)';
1688

    
1689
  // Split at opening and closing PRE, SCRIPT, STYLE, OBJECT, IFRAME tags
1690
  // and comments. We don't apply any processing to the contents of these tags
1691
  // to avoid messing up code. We look for matched pairs and allow basic
1692
  // nesting. For example:
1693
  // "processed <pre> ignored <script> ignored </script> ignored </pre> processed"
1694
  $chunks = preg_split('@(<!--.*?-->|</?(?:pre|script|style|object|iframe|!--)[^>]*>)@i', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
1695
  // Note: PHP ensures the array consists of alternating delimiters and literals
1696
  // and begins and ends with a literal (inserting NULL as required).
1697
  $ignore = FALSE;
1698
  $ignoretag = '';
1699
  $output = '';
1700
  foreach ($chunks as $i => $chunk) {
1701
    if ($i % 2) {
1702
      $comment = (substr($chunk, 0, 4) == '<!--');
1703
      if ($comment) {
1704
        // Nothing to do, this is a comment.
1705
        $output .= $chunk;
1706
        continue;
1707
      }
1708
      // Opening or closing tag?
1709
      $open = ($chunk[1] != '/');
1710
      list($tag) = preg_split('/[ >]/', substr($chunk, 2 - $open), 2);
1711
      if (!$ignore) {
1712
        if ($open) {
1713
          $ignore = TRUE;
1714
          $ignoretag = $tag;
1715
        }
1716
      }
1717
      // Only allow a matching tag to close it.
1718
      elseif (!$open && $ignoretag == $tag) {
1719
        $ignore = FALSE;
1720
        $ignoretag = '';
1721
      }
1722
    }
1723
    elseif (!$ignore) {
1724
      $chunk = preg_replace('|\n*$|', '', $chunk) . "\n\n"; // just to make things a little easier, pad the end
1725
      $chunk = preg_replace('|<br />\s*<br />|', "\n\n", $chunk);
1726
      $chunk = preg_replace('!(<' . $block . '[^>]*>)!', "\n$1", $chunk); // Space things out a little
1727
      $chunk = preg_replace('!(</' . $block . '>)!', "$1\n\n", $chunk); // Space things out a little
1728
      $chunk = preg_replace("/\n\n+/", "\n\n", $chunk); // take care of duplicates
1729
      $chunk = preg_replace('/^\n|\n\s*\n$/', '', $chunk);
1730
      $chunk = '<p>' . preg_replace('/\n\s*\n\n?(.)/', "</p>\n<p>$1", $chunk) . "</p>\n"; // make paragraphs, including one at the end
1731
      $chunk = preg_replace("|<p>(<li.+?)</p>|", "$1", $chunk); // problem with nested lists
1732
      $chunk = preg_replace('|<p><blockquote([^>]*)>|i', "<blockquote$1><p>", $chunk);
1733
      $chunk = str_replace('</blockquote></p>', '</p></blockquote>', $chunk);
1734
      $chunk = preg_replace('|<p>\s*</p>\n?|', '', $chunk); // under certain strange conditions it could create a P of entirely whitespace
1735
      $chunk = preg_replace('!<p>\s*(</?' . $block . '[^>]*>)!', "$1", $chunk);
1736
      $chunk = preg_replace('!(</?' . $block . '[^>]*>)\s*</p>!', "$1", $chunk);
1737
      $chunk = preg_replace('|(?<!<br />)\s*\n|', "<br />\n", $chunk); // make line breaks
1738
      $chunk = preg_replace('!(</?' . $block . '[^>]*>)\s*<br />!', "$1", $chunk);
1739
      $chunk = preg_replace('!<br />(\s*</?(?:p|li|div|th|pre|td|ul|ol)>)!', '$1', $chunk);
1740
      $chunk = preg_replace('/&([^#])(?![A-Za-z0-9]{1,8};)/', '&amp;$1', $chunk);
1741
    }
1742
    $output .= $chunk;
1743
  }
1744
  return $output;
1745
}
1746

    
1747
/**
1748
 * Implements callback_filter_tips().
1749
 *
1750
 * Provides help for the auto-paragraph filter.
1751
 *
1752
 * @see filter_filter_info()
1753
 */
1754
function _filter_autop_tips($filter, $format, $long = FALSE) {
1755
  if ($long) {
1756
    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.');
1757
  }
1758
  else {
1759
    return t('Lines and paragraphs break automatically.');
1760
  }
1761
}
1762

    
1763
/**
1764
 * Implements callback_filter_process().
1765
 *
1766
 * Escapes all HTML tags, so they will be visible instead of being effective.
1767
 */
1768
function _filter_html_escape($text) {
1769
  return trim(check_plain($text));
1770
}
1771

    
1772
/**
1773
 * Implements callback_filter_tips().
1774
 *
1775
 * Provides help for the HTML escaping filter.
1776
 *
1777
 * @see filter_filter_info()
1778
 */
1779
function _filter_html_escape_tips($filter, $format, $long = FALSE) {
1780
  return t('No HTML tags allowed.');
1781
}
1782

    
1783
/**
1784
 * @} End of "Standard filters".
1785
 */