Projet

Général

Profil

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

root / drupal7 / modules / filter / filter.module @ 01dfd3b5

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['filter/tips/%filter_format'] = array(
97
    'title' => 'Compose tips',
98
    'page callback' => 'filter_tips_long',
99
    'page arguments' => array(2),
100
    'access callback' => 'filter_access',
101
    'access arguments' => array(2),
102
    'file' => 'filter.pages.inc',
103
  );
104
  $items['admin/config/content/formats'] = array(
105
    'title' => 'Text formats',
106
    'description' => 'Configure how content input by users is filtered, including allowed HTML tags. Also allows enabling of module-provided filters.',
107
    'page callback' => 'drupal_get_form',
108
    'page arguments' => array('filter_admin_overview'),
109
    'access arguments' => array('administer filters'),
110
    'file' => 'filter.admin.inc',
111
  );
112
  $items['admin/config/content/formats/list'] = array(
113
    'title' => 'List',
114
    'type' => MENU_DEFAULT_LOCAL_TASK,
115
  );
116
  $items['admin/config/content/formats/add'] = array(
117
    'title' => 'Add text format',
118
    'page callback' => 'filter_admin_format_page',
119
    'access arguments' => array('administer filters'),
120
    'type' => MENU_LOCAL_ACTION,
121
    'weight' => 1,
122
    'file' => 'filter.admin.inc',
123
  );
124
  $items['admin/config/content/formats/%filter_format'] = array(
125
    'title callback' => 'filter_admin_format_title',
126
    'title arguments' => array(4),
127
    'page callback' => 'filter_admin_format_page',
128
    'page arguments' => array(4),
129
    'access arguments' => array('administer filters'),
130
    'file' => 'filter.admin.inc',
131
  );
132
  $items['admin/config/content/formats/%filter_format/disable'] = array(
133
    'title' => 'Disable text format',
134
    'page callback' => 'drupal_get_form',
135
    'page arguments' => array('filter_admin_disable', 4),
136
    'access callback' => '_filter_disable_format_access',
137
    'access arguments' => array(4),
138
    'file' => 'filter.admin.inc',
139
  );
140
  return $items;
141
}
142

    
143
/**
144
 * Access callback: Checks access for disabling text formats.
145
 *
146
 * @param $format
147
 *   A text format object.
148
 *
149
 * @return
150
 *   TRUE if the text format can be disabled by the current user, FALSE
151
 *   otherwise.
152
 *
153
 * @see filter_menu()
154
 */
155
function _filter_disable_format_access($format) {
156
  // The fallback format can never be disabled.
157
  return user_access('administer filters') && ($format->format != filter_fallback_format());
158
}
159

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

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

    
216
  // Insert or update the text format.
217
  $return = db_merge('filter_format')
218
    ->key(array('format' => $format->format))
219
    ->fields(array(
220
      'name' => $format->name,
221
      'cache' => (int) $format->cache,
222
      'status' => (int) $format->status,
223
      'weight' => (int) $format->weight,
224
    ))
225
    ->execute();
226

    
227
  // Programmatic saves may not contain any filters.
228
  if (!isset($format->filters)) {
229
    $format->filters = array();
230
  }
231
  $filter_info = filter_get_filters();
232
  foreach ($filter_info as $name => $filter) {
233
    // If the format does not specify an explicit weight for a filter, assign
234
    // a default weight, either defined in hook_filter_info(), or the default of
235
    // 0 by filter_get_filters()
236
    if (!isset($format->filters[$name]['weight'])) {
237
      $format->filters[$name]['weight'] = $filter['weight'];
238
    }
239
    $format->filters[$name]['status'] = isset($format->filters[$name]['status']) ? $format->filters[$name]['status'] : 0;
240
    $format->filters[$name]['module'] = $filter['module'];
241

    
242
    // If settings were passed, only ensure default settings.
243
    if (isset($format->filters[$name]['settings'])) {
244
      if (isset($filter['default settings'])) {
245
        $format->filters[$name]['settings'] = array_merge($filter['default settings'], $format->filters[$name]['settings']);
246
      }
247
    }
248
    // Otherwise, use default settings or fall back to an empty array.
249
    else {
250
      $format->filters[$name]['settings'] = isset($filter['default settings']) ? $filter['default settings'] : array();
251
    }
252

    
253
    $fields = array();
254
    $fields['weight'] = $format->filters[$name]['weight'];
255
    $fields['status'] = $format->filters[$name]['status'];
256
    $fields['module'] = $format->filters[$name]['module'];
257
    $fields['settings'] = serialize($format->filters[$name]['settings']);
258

    
259
    db_merge('filter')
260
      ->key(array(
261
        'format' => $format->format,
262
        'name' => $name,
263
      ))
264
      ->fields($fields)
265
      ->execute();
266
  }
267

    
268
  if ($return == SAVED_NEW) {
269
    module_invoke_all('filter_format_insert', $format);
270
  }
271
  else {
272
    module_invoke_all('filter_format_update', $format);
273
    // Explicitly indicate that the format was updated. We need to do this
274
    // since if the filters were updated but the format object itself was not,
275
    // the merge query above would not return an indication that anything had
276
    // changed.
277
    $return = SAVED_UPDATED;
278

    
279
    // Clear the filter cache whenever a text format is updated.
280
    cache_clear_all($format->format . ':', 'cache_filter', TRUE);
281
  }
282

    
283
  filter_formats_reset();
284

    
285
  return $return;
286
}
287

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

    
305
  // Allow modules to react on text format deletion.
306
  module_invoke_all('filter_format_disable', $format);
307

    
308
  // Clear the filter cache whenever a text format is disabled.
309
  filter_formats_reset();
310
  cache_clear_all($format->format . ':', 'cache_filter', TRUE);
311
}
312

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

    
330
/**
331
 * Displays a text format form title.
332
 *
333
 * @param object $format
334
 *   A format object.
335
 *
336
 * @return string
337
 *   The name of the format.
338
 *
339
 * @see filter_menu()
340
 */
341
function filter_admin_format_title($format) {
342
  return $format->name;
343
}
344

    
345
/**
346
 * Implements hook_permission().
347
 */
348
function filter_permission() {
349
  $perms['administer filters'] = array(
350
    'title' => t('Administer text formats and filters'),
351
    'description' => t('Define how text is handled by combining filters into <a href="@url">text formats</a>.', array('@url' => url('admin/config/content/formats'))),
352
    'restrict access' => TRUE,
353
  );
354

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

    
370
/**
371
 * Returns the machine-readable permission name for a provided text format.
372
 *
373
 * @param $format
374
 *   An object representing a text format.
375
 *
376
 * @return
377
 *   The machine-readable permission name, or FALSE if the provided text format
378
 *   is malformed or is the fallback format (which is available to all users).
379
 */
380
function filter_permission_name($format) {
381
  if (isset($format->format) && $format->format != filter_fallback_format()) {
382
    return 'use text format ' . $format->format;
383
  }
384
  return FALSE;
385
}
386

    
387
/**
388
 * Implements hook_modules_enabled().
389
 */
390
function filter_modules_enabled($modules) {
391
  // Reset the static cache of module-provided filters, in case any of the
392
  // newly enabled modules defines a new filter or alters existing ones.
393
  drupal_static_reset('filter_get_filters');
394
}
395

    
396
/**
397
 * Implements hook_modules_disabled().
398
 */
399
function filter_modules_disabled($modules) {
400
  // Reset the static cache of module-provided filters, in case any of the
401
  // newly disabled modules defined or altered any filters.
402
  drupal_static_reset('filter_get_filters');
403
}
404

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

    
423
  // All available formats are cached for performance.
424
  if (!isset($formats['all'])) {
425
    if ($cache = cache_get("filter_formats:{$language->language}")) {
426
      $formats['all'] = $cache->data;
427
    }
428
    else {
429
      $formats['all'] = db_select('filter_format', 'ff')
430
        ->addTag('translatable')
431
        ->fields('ff')
432
        ->condition('status', 1)
433
        ->orderBy('weight')
434
        ->execute()
435
        ->fetchAllAssoc('format');
436

    
437
      cache_set("filter_formats:{$language->language}", $formats['all']);
438
    }
439
  }
440

    
441
  // Build a list of user-specific formats.
442
  if (isset($account) && !isset($formats['user'][$account->uid])) {
443
    $formats['user'][$account->uid] = array();
444
    foreach ($formats['all'] as $format) {
445
      if (filter_access($format, $account)) {
446
        $formats['user'][$account->uid][$format->format] = $format;
447
      }
448
    }
449
  }
450

    
451
  return isset($account) ? $formats['user'][$account->uid] : $formats['all'];
452
}
453

    
454
/**
455
 * Resets the text format caches.
456
 *
457
 * @see filter_formats()
458
 */
459
function filter_formats_reset() {
460
  cache_clear_all('filter_formats', 'cache', TRUE);
461
  cache_clear_all('filter_list_format', 'cache', TRUE);
462
  drupal_static_reset('filter_list_format');
463
  drupal_static_reset('filter_formats');
464
}
465

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

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

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

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

    
582
/**
583
 * Returns the title of the fallback text format.
584
 *
585
 * @return string
586
 *   The title of the fallback text format.
587
 */
588
function filter_fallback_format_title() {
589
  $fallback_format = filter_format_load(filter_fallback_format());
590
  return filter_admin_format_title($fallback_format);
591
}
592

    
593
/**
594
 * Returns a list of all filters provided by modules.
595
 *
596
 * @return array
597
 *   An array of filter formats.
598
 */
599
function filter_get_filters() {
600
  $filters = &drupal_static(__FUNCTION__, array());
601

    
602
  if (empty($filters)) {
603
    foreach (module_implements('filter_info') as $module) {
604
      $info = module_invoke($module, 'filter_info');
605
      if (isset($info) && is_array($info)) {
606
        // Assign the name of the module implementing the filters and ensure
607
        // default values.
608
        foreach (array_keys($info) as $name) {
609
          $info[$name]['module'] = $module;
610
          $info[$name] += array(
611
            'description' => '',
612
            'weight' => 0,
613
          );
614
        }
615
        $filters = array_merge($filters, $info);
616
      }
617
    }
618
    // Allow modules to alter filter definitions.
619
    drupal_alter('filter_info', $filters);
620

    
621
    uasort($filters, '_filter_list_cmp');
622
  }
623

    
624
  return $filters;
625
}
626

    
627
/**
628
 * Sorts an array of filters by filter name.
629
 *
630
 * Callback for uasort() within filter_get_filters().
631
 */
632
function _filter_list_cmp($a, $b) {
633
  return strcmp($a['title'], $b['title']);
634
}
635

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

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

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

    
702
  if (!isset($filters['all'])) {
703
    if ($cache = cache_get('filter_list_format')) {
704
      $filters['all'] = $cache->data;
705
    }
706
    else {
707
      $result = db_query('SELECT * FROM {filter} ORDER BY weight, module, name');
708
      foreach ($result as $record) {
709
        $filters['all'][$record->format][$record->name] = $record;
710
      }
711
      cache_set('filter_list_format', $filters['all']);
712
    }
713
  }
714

    
715
  if (!isset($filters[$format_id])) {
716
    $format_filters = array();
717
    $filter_map = isset($filters['all'][$format_id]) ? $filters['all'][$format_id] : array();
718
    foreach ($filter_map as $name => $filter) {
719
      if (isset($filter_info[$name])) {
720
        $filter->title = $filter_info[$name]['title'];
721
        // Unpack stored filter settings.
722
        $filter->settings = (isset($filter->settings) ? unserialize($filter->settings) : array());
723
        // Merge in default settings.
724
        if (isset($filter_info[$name]['default settings'])) {
725
          $filter->settings += $filter_info[$name]['default settings'];
726
        }
727

    
728
        $format_filters[$name] = $filter;
729
      }
730
    }
731
    $filters[$format_id] = $format_filters;
732
  }
733

    
734
  return isset($filters[$format_id]) ? $filters[$format_id] : array();
735
}
736

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

    
776
  // Check for a cached version of this piece of text.
777
  $cache = $cache && !empty($format->cache);
778
  $cache_id = '';
779
  if ($cache) {
780
    $cache_id = $format->format . ':' . $langcode . ':' . hash('sha256', $text);
781
    if ($cached = cache_get($cache_id, 'cache_filter')) {
782
      return $cached->data;
783
    }
784
  }
785

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

    
790
  // Get a complete list of filters, ordered properly.
791
  $filters = filter_list_format($format->format);
792
  $filter_info = filter_get_filters();
793

    
794
  // Give filters the chance to escape HTML-like data such as code or formulas.
795
  foreach ($filters as $name => $filter) {
796
    if ($filter->status && isset($filter_info[$name]['prepare callback']) && function_exists($filter_info[$name]['prepare callback'])) {
797
      $function = $filter_info[$name]['prepare callback'];
798
      $text = $function($text, $filter, $format, $langcode, $cache, $cache_id);
799
    }
800
  }
801

    
802
  // Perform filtering.
803
  foreach ($filters as $name => $filter) {
804
    if ($filter->status && isset($filter_info[$name]['process callback']) && function_exists($filter_info[$name]['process callback'])) {
805
      $function = $filter_info[$name]['process callback'];
806
      $text = $function($text, $filter, $format, $langcode, $cache, $cache_id);
807
    }
808
  }
809

    
810
  // Cache the filtered text. This cache is infinitely valid. It becomes
811
  // obsolete when $text changes (which leads to a new $cache_id). It is
812
  // automatically flushed when the text format is updated.
813
  // @see filter_format_save()
814
  if ($cache) {
815
    cache_set($cache_id, $text, 'cache_filter');
816
  }
817

    
818
  return $text;
819
}
820

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

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

    
881
  $element['value']['#type'] = $element['#base_type'];
882
  $element['value'] += element_info($element['#base_type']);
883

    
884
  // Turn original element into a text format wrapper.
885
  $path = drupal_get_path('module', 'filter');
886
  $element['#attached']['js'][] = $path . '/filter.js';
887
  $element['#attached']['css'][] = $path . '/filter.css';
888

    
889
  // Setup child container for the text format widget.
890
  $element['format'] = array(
891
    '#type' => 'fieldset',
892
    '#attributes' => array('class' => array('filter-wrapper')),
893
  );
894

    
895
  // Prepare text format guidelines.
896
  $element['format']['guidelines'] = array(
897
    '#type' => 'container',
898
    '#attributes' => array('class' => array('filter-guidelines')),
899
    '#weight' => 20,
900
  );
901
  // Get a list of formats that the current user has access to.
902
  $formats = filter_formats($user);
903
  foreach ($formats as $format) {
904
    $options[$format->format] = $format->name;
905
    $element['format']['guidelines'][$format->format] = array(
906
      '#theme' => 'filter_guidelines',
907
      '#format' => $format,
908
    );
909
  }
910

    
911
  // Use the default format for this user if none was selected.
912
  if (!isset($element['#format'])) {
913
    $element['#format'] = filter_default_format($user);
914
  }
915

    
916
  $element['format']['format'] = array(
917
    '#type' => 'select',
918
    '#title' => t('Text format'),
919
    '#options' => $options,
920
    '#default_value' => $element['#format'],
921
    '#access' => count($formats) > 1,
922
    '#weight' => 10,
923
    '#attributes' => array('class' => array('filter-list')),
924
    '#parents' => array_merge($element['#parents'], array('format')),
925
  );
926

    
927
  $element['format']['help'] = array(
928
    '#type' => 'container',
929
    '#theme' => 'filter_tips_more_info',
930
    '#attributes' => array('class' => array('filter-help')),
931
    '#weight' => 0,
932
  );
933

    
934
  $all_formats = filter_formats();
935
  $format_exists = isset($all_formats[$element['#format']]);
936
  $user_has_access = isset($formats[$element['#format']]);
937
  $user_is_admin = user_access('administer filters');
938

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

    
956
    // Prepend #pre_render callback to replace field value with user notice
957
    // prior to rendering.
958
    $element['value'] += array('#pre_render' => array());
959
    array_unshift($element['value']['#pre_render'], 'filter_form_access_denied');
960

    
961
    // Cosmetic adjustments.
962
    if (isset($element['value']['#rows'])) {
963
      $element['value']['#rows'] = 3;
964
    }
965
    $element['value']['#disabled'] = TRUE;
966
    $element['value']['#resizable'] = FALSE;
967

    
968
    // Hide the text format selector and any other child element (such as text
969
    // field's summary).
970
    foreach (element_children($element) as $key) {
971
      if ($key != 'value') {
972
        $element[$key]['#access'] = FALSE;
973
      }
974
    }
975
  }
976

    
977
  return $element;
978
}
979

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

    
996
/**
997
 * Returns HTML for a text format-enabled form element.
998
 *
999
 * @param $variables
1000
 *   An associative array containing:
1001
 *   - element: A render element containing #children and #description.
1002
 *
1003
 * @ingroup themeable
1004
 */
1005
function theme_text_format_wrapper($variables) {
1006
  $element = $variables['element'];
1007
  $output = '<div class="text-format-wrapper">';
1008
  $output .= $element['#children'];
1009
  if (!empty($element['#description'])) {
1010
    $output .= '<div class="description">' . $element['#description'] . '</div>';
1011
  }
1012
  $output .= "</div>\n";
1013

    
1014
  return $output;
1015
}
1016

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

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

    
1064
  $formats = filter_formats($user);
1065
  $filter_info = filter_get_filters();
1066

    
1067
  $tips = array();
1068

    
1069
  // If only listing one format, extract it from the $formats array.
1070
  if ($format_id != -1) {
1071
    $formats = array($formats[$format_id]);
1072
  }
1073

    
1074
  foreach ($formats as $format) {
1075
    $filters = filter_list_format($format->format);
1076
    $tips[$format->name] = array();
1077
    foreach ($filters as $name => $filter) {
1078
      if ($filter->status && isset($filter_info[$name]['tips callback']) && function_exists($filter_info[$name]['tips callback'])) {
1079
        $tip = $filter_info[$name]['tips callback']($filter, $format, $long);
1080
        if (isset($tip)) {
1081
          $tips[$format->name][$name] = array('tip' => $tip, 'id' => $name);
1082
        }
1083
      }
1084
    }
1085
  }
1086

    
1087
  return $tips;
1088
}
1089

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

    
1109
  return $dom_document;
1110
}
1111

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

    
1130
  if ($body_node !== NULL) {
1131
    foreach ($body_node->getElementsByTagName('script') as $node) {
1132
      filter_dom_serialize_escape_cdata_element($dom_document, $node);
1133
    }
1134

    
1135
    foreach ($body_node->getElementsByTagName('style') as $node) {
1136
      filter_dom_serialize_escape_cdata_element($dom_document, $node, '/*', '*/');
1137
    }
1138

    
1139
    foreach ($body_node->childNodes as $child_node) {
1140
      $body_content .= $dom_document->saveXML($child_node);
1141
    }
1142
    return preg_replace('|<([^> ]*)/>|i', '<$1 />', $body_content);
1143
  }
1144
  else {
1145
    return $body_content;
1146
  }
1147
}
1148

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

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

    
1183
      $fragment = $dom_document->createDocumentFragment();
1184
      $fragment->appendXML($embed_prefix . $data . $embed_suffix);
1185
      $dom_element->appendChild($fragment);
1186
      $dom_element->removeChild($node);
1187
    }
1188
  }
1189
}
1190

    
1191
/**
1192
 * Returns HTML for a link to the more extensive filter tips.
1193
 *
1194
 * @ingroup themeable
1195
 */
1196
function theme_filter_tips_more_info() {
1197
  return '<p>' . l(t('More information about text formats'), 'filter/tips', array('attributes' => array('target' => '_blank'))) . '</p>';
1198
}
1199

    
1200
/**
1201
 * Returns HTML for guidelines for a text format.
1202
 *
1203
 * @param $variables
1204
 *   An associative array containing:
1205
 *   - format: An object representing a text format.
1206
 *
1207
 * @ingroup themeable
1208
 */
1209
function theme_filter_guidelines($variables) {
1210
  $format = $variables['format'];
1211
  $attributes['class'][] = 'filter-guidelines-item';
1212
  $attributes['class'][] = 'filter-guidelines-' . $format->format;
1213
  $output = '<div' . drupal_attributes($attributes) . '>';
1214
  $output .= '<h3>' . check_plain($format->name) . '</h3>';
1215
  $output .= theme('filter_tips', array('tips' => _filter_tips($format->format, FALSE)));
1216
  $output .= '</div>';
1217
  return $output;
1218
}
1219

    
1220
/**
1221
 * @defgroup standard_filters Standard filters
1222
 * @{
1223
 * Filters implemented by the Filter module.
1224
 */
1225

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

    
1270
/**
1271
 * Implements callback_filter_settings().
1272
 *
1273
 * Filter settings callback for the HTML content filter.
1274
 */
1275
function _filter_html_settings($form, &$form_state, $filter, $format, $defaults) {
1276
  $filter->settings += $defaults;
1277

    
1278
  $settings['allowed_html'] = array(
1279
    '#type' => 'textfield',
1280
    '#title' => t('Allowed HTML tags'),
1281
    '#default_value' => $filter->settings['allowed_html'],
1282
    '#maxlength' => 1024,
1283
    '#description' => t('A list of HTML tags that can be used. JavaScript event attributes, JavaScript URLs, and CSS are always stripped.'),
1284
  );
1285
  $settings['filter_html_help'] = array(
1286
    '#type' => 'checkbox',
1287
    '#title' => t('Display basic HTML help in long filter tips'),
1288
    '#default_value' => $filter->settings['filter_html_help'],
1289
  );
1290
  $settings['filter_html_nofollow'] = array(
1291
    '#type' => 'checkbox',
1292
    '#title' => t('Add rel="nofollow" to all links'),
1293
    '#default_value' => $filter->settings['filter_html_nofollow'],
1294
  );
1295
  return $settings;
1296
}
1297

    
1298
/**
1299
 * Implements callback_filter_process().
1300
 *
1301
 * Provides filtering of input into accepted HTML.
1302
 */
1303
function _filter_html($text, $filter) {
1304
  $allowed_tags = preg_split('/\s+|<|>/', $filter->settings['allowed_html'], -1, PREG_SPLIT_NO_EMPTY);
1305
  $text = filter_xss($text, $allowed_tags);
1306

    
1307
  if ($filter->settings['filter_html_nofollow']) {
1308
    $html_dom = filter_dom_load($text);
1309
    $links = $html_dom->getElementsByTagName('a');
1310
    foreach ($links as $link) {
1311
      $link->setAttribute('rel', 'nofollow');
1312
    }
1313
    $text = filter_dom_serialize($html_dom);
1314
  }
1315

    
1316
  return trim($text);
1317
}
1318

    
1319
/**
1320
 * Implements callback_filter_tips().
1321
 *
1322
 * Provides help for the HTML filter.
1323
 *
1324
 * @see filter_filter_info()
1325
 */
1326
function _filter_html_tips($filter, $format, $long = FALSE) {
1327
  global $base_url;
1328

    
1329
  if (!($allowed_html = $filter->settings['allowed_html'])) {
1330
    return;
1331
  }
1332
  $output = t('Allowed HTML tags: @tags', array('@tags' => $allowed_html));
1333
  if (!$long) {
1334
    return $output;
1335
  }
1336

    
1337
  $output = '<p>' . $output . '</p>';
1338
  if (!$filter->settings['filter_html_help']) {
1339
    return $output;
1340
  }
1341

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

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

    
1402
  $entities = array(
1403
    array(t('Ampersand'), '&amp;'),
1404
    array(t('Greater than'), '&gt;'),
1405
    array(t('Less than'), '&lt;'),
1406
    array(t('Quotation mark'), '&quot;'),
1407
  );
1408
  $header = array(t('Character Description'), t('You Type'), t('You Get'));
1409
  unset($rows);
1410
  foreach ($entities as $entity) {
1411
    $rows[] = array(
1412
      array('data' => $entity[0], 'class' => array('description')),
1413
      array('data' => '<code>' . check_plain($entity[1]) . '</code>', 'class' => array('type')),
1414
      array('data' => $entity[1], 'class' => array('get'))
1415
    );
1416
  }
1417
  $output .= theme('table', array('header' => $header, 'rows' => $rows));
1418
  return $output;
1419
}
1420

    
1421
/**
1422
 * Implements callback_filter_settings().
1423
 *
1424
 * Provides settings for the URL filter.
1425
 *
1426
 * @see filter_filter_info()
1427
 */
1428
function _filter_url_settings($form, &$form_state, $filter, $format, $defaults) {
1429
  $filter->settings += $defaults;
1430

    
1431
  $settings['filter_url_length'] = array(
1432
    '#type' => 'textfield',
1433
    '#title' => t('Maximum link text length'),
1434
    '#default_value' => $filter->settings['filter_url_length'],
1435
    '#size' => 5,
1436
    '#maxlength' => 4,
1437
    '#field_suffix' => t('characters'),
1438
    '#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.'),
1439
    '#element_validate' => array('element_validate_integer_positive'),
1440
  );
1441
  return $settings;
1442
}
1443

    
1444
/**
1445
 * Implements callback_filter_process().
1446
 *
1447
 * Converts text into hyperlinks automatically.
1448
 *
1449
 * This filter identifies and makes clickable three types of "links".
1450
 * - URLs like http://example.com.
1451
 * - E-mail addresses like name@example.com.
1452
 * - Web addresses without the "http://" protocol defined, like www.example.com.
1453
 * Each type must be processed separately, as there is no one regular
1454
 * expression that could possibly match all of the cases in one pass.
1455
 */
1456
function _filter_url($text, $filter) {
1457
  // Tags to skip and not recurse into.
1458
  $ignore_tags = 'a|script|style|code|pre';
1459

    
1460
  // Pass length to regexp callback.
1461
  _filter_url_trim(NULL, $filter->settings['filter_url_length']);
1462

    
1463
  // Create an array which contains the regexps for each type of link.
1464
  // The key to the regexp is the name of a function that is used as
1465
  // callback function to process matches of the regexp. The callback function
1466
  // is to return the replacement for the match. The array is used and
1467
  // matching/replacement done below inside some loops.
1468
  $tasks = array();
1469

    
1470
  // Prepare protocols pattern for absolute URLs.
1471
  // check_url() will replace any bad protocols with HTTP, so we need to support
1472
  // the identical list. While '//' is technically optional for MAILTO only,
1473
  // we cannot cleanly differ between protocols here without hard-coding MAILTO,
1474
  // so '//' is optional for all protocols.
1475
  // @see filter_xss_bad_protocol()
1476
  $protocols = variable_get('filter_allowed_protocols', array('ftp', 'http', 'https', 'irc', 'mailto', 'news', 'nntp', 'rtsp', 'sftp', 'ssh', 'tel', 'telnet', 'webcal'));
1477
  $protocols = implode(':(?://)?|', $protocols) . ':(?://)?';
1478

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

    
1488
  // Prepare pattern for optional trailing punctuation.
1489
  // Even these characters could have a valid meaning for the URL, such usage is
1490
  // rare compared to using a URL at the end of or within a sentence, so these
1491
  // trailing characters are optionally excluded.
1492
  $punctuation = '[\.,?!]*?';
1493

    
1494
  // Match absolute URLs.
1495
  $url_pattern = "(?:$auth)?(?:$domain|$ip)/?(?:$trail)?";
1496
  $pattern = "`((?:$protocols)(?:$url_pattern))($punctuation)`";
1497
  $tasks['_filter_url_parse_full_links'] = $pattern;
1498

    
1499
  // Match e-mail addresses.
1500
  $url_pattern = "[A-Za-z0-9._+-]{1,254}@(?:$domain)";
1501
  $pattern = "`($url_pattern)`";
1502
  $tasks['_filter_url_parse_email_links'] = $pattern;
1503

    
1504
  // Match www domains.
1505
  $url_pattern = "www\.(?:$domain)/?(?:$trail)?";
1506
  $pattern = "`($url_pattern)($punctuation)`";
1507
  $tasks['_filter_url_parse_partial_links'] = $pattern;
1508

    
1509
  // Each type of URL needs to be processed separately. The text is joined and
1510
  // re-split after each task, since all injected HTML tags must be correctly
1511
  // protected before the next task.
1512
  foreach ($tasks as $task => $pattern) {
1513
    // HTML comments need to be handled separately, as they may contain HTML
1514
    // markup, especially a '>'. Therefore, remove all comment contents and add
1515
    // them back later.
1516
    _filter_url_escape_comments('', TRUE);
1517
    $text = preg_replace_callback('`<!--(.*?)-->`s', '_filter_url_escape_comments', $text);
1518

    
1519
    // Split at all tags; ensures that no tags or attributes are processed.
1520
    $chunks = preg_split('/(<.+?>)/is', $text, -1, PREG_SPLIT_DELIM_CAPTURE);
1521
    // PHP ensures that the array consists of alternating delimiters and
1522
    // literals, and begins and ends with a literal (inserting NULL as
1523
    // required). Therefore, the first chunk is always text:
1524
    $chunk_type = 'text';
1525
    // If a tag of $ignore_tags is found, it is stored in $open_tag and only
1526
    // removed when the closing tag is found. Until the closing tag is found,
1527
    // no replacements are made.
1528
    $open_tag = '';
1529

    
1530
    for ($i = 0; $i < count($chunks); $i++) {
1531
      if ($chunk_type == 'text') {
1532
        // Only process this text if there are no unclosed $ignore_tags.
1533
        if ($open_tag == '') {
1534
          // If there is a match, inject a link into this chunk via the callback
1535
          // function contained in $task.
1536
          $chunks[$i] = preg_replace_callback($pattern, $task, $chunks[$i]);
1537
        }
1538
        // Text chunk is done, so next chunk must be a tag.
1539
        $chunk_type = 'tag';
1540
      }
1541
      else {
1542
        // Only process this tag if there are no unclosed $ignore_tags.
1543
        if ($open_tag == '') {
1544
          // Check whether this tag is contained in $ignore_tags.
1545
          if (preg_match("`<($ignore_tags)(?:\s|>)`i", $chunks[$i], $matches)) {
1546
            $open_tag = $matches[1];
1547
          }
1548
        }
1549
        // Otherwise, check whether this is the closing tag for $open_tag.
1550
        else {
1551
          if (preg_match("`<\/$open_tag>`i", $chunks[$i], $matches)) {
1552
            $open_tag = '';
1553
          }
1554
        }
1555
        // Tag chunk is done, so next chunk must be text.
1556
        $chunk_type = 'text';
1557
      }
1558
    }
1559

    
1560
    $text = implode($chunks);
1561
    // Revert back to the original comment contents
1562
    _filter_url_escape_comments('', FALSE);
1563
    $text = preg_replace_callback('`<!--(.*?)-->`', '_filter_url_escape_comments', $text);
1564
  }
1565

    
1566
  return $text;
1567
}
1568

    
1569
/**
1570
 * Makes links out of absolute URLs.
1571
 *
1572
 * Callback for preg_replace_callback() within _filter_url().
1573
 */
1574
function _filter_url_parse_full_links($match) {
1575
  // The $i:th parenthesis in the regexp contains the URL.
1576
  $i = 1;
1577

    
1578
  $match[$i] = decode_entities($match[$i]);
1579
  $caption = check_plain(_filter_url_trim($match[$i]));
1580
  $match[$i] = check_plain($match[$i]);
1581
  return '<a href="' . $match[$i] . '">' . $caption . '</a>' . $match[$i + 1];
1582
}
1583

    
1584
/**
1585
 * Makes links out of e-mail addresses.
1586
 *
1587
 * Callback for preg_replace_callback() within _filter_url().
1588
 */
1589
function _filter_url_parse_email_links($match) {
1590
  // The $i:th parenthesis in the regexp contains the URL.
1591
  $i = 0;
1592

    
1593
  $match[$i] = decode_entities($match[$i]);
1594
  $caption = check_plain(_filter_url_trim($match[$i]));
1595
  $match[$i] = check_plain($match[$i]);
1596
  return '<a href="mailto:' . $match[$i] . '">' . $caption . '</a>';
1597
}
1598

    
1599
/**
1600
 * Makes links out of domain names starting with "www."
1601
 *
1602
 * Callback for preg_replace_callback() within _filter_url().
1603
 */
1604
function _filter_url_parse_partial_links($match) {
1605
  // The $i:th parenthesis in the regexp contains the URL.
1606
  $i = 1;
1607

    
1608
  $match[$i] = decode_entities($match[$i]);
1609
  $caption = check_plain(_filter_url_trim($match[$i]));
1610
  $match[$i] = check_plain($match[$i]);
1611
  return '<a href="http://' . $match[$i] . '">' . $caption . '</a>' . $match[$i + 1];
1612
}
1613

    
1614
/**
1615
 * Escapes the contents of HTML comments.
1616
 *
1617
 * Callback for preg_replace_callback() within _filter_url().
1618
 *
1619
 * @param $match
1620
 *   An array containing matches to replace from preg_replace_callback(),
1621
 *   whereas $match[1] is expected to contain the content to be filtered.
1622
 * @param $escape
1623
 *   (optional) A Boolean indicating whether to escape (TRUE) or unescape
1624
 *   comments (FALSE). Defaults to NULL, indicating neither. If TRUE, statically
1625
 *   cached $comments are reset.
1626
 */
1627
function _filter_url_escape_comments($match, $escape = NULL) {
1628
  static $mode, $comments = array();
1629

    
1630
  if (isset($escape)) {
1631
    $mode = $escape;
1632
    if ($escape){
1633
      $comments = array();
1634
    }
1635
    return;
1636
  }
1637

    
1638
  // Replace all HTML coments with a '<!-- [hash] -->' placeholder.
1639
  if ($mode) {
1640
    $content = $match[1];
1641
    $hash = hash('sha256', $content);
1642
    $comments[$hash] = $content;
1643
    return "<!-- $hash -->";
1644
  }
1645
  // Or replace placeholders with actual comment contents.
1646
  else {
1647
    $hash = $match[1];
1648
    $hash = trim($hash);
1649
    $content = $comments[$hash];
1650
    return "<!--$content-->";
1651
  }
1652
}
1653

    
1654
/**
1655
 * Shortens long URLs to http://www.example.com/long/url...
1656
 */
1657
function _filter_url_trim($text, $length = NULL) {
1658
  static $_length;
1659
  if ($length !== NULL) {
1660
    $_length = $length;
1661
  }
1662

    
1663
  // Use +3 for '...' string length.
1664
  if ($_length && strlen($text) > $_length + 3) {
1665
    $text = substr($text, 0, $_length) . '...';
1666
  }
1667

    
1668
  return $text;
1669
}
1670

    
1671
/**
1672
 * Implements callback_filter_tips().
1673
 *
1674
 * Provides help for the URL filter.
1675
 *
1676
 * @see filter_filter_info()
1677
 */
1678
function _filter_url_tips($filter, $format, $long = FALSE) {
1679
  return t('Web page addresses and e-mail addresses turn into links automatically.');
1680
}
1681

    
1682
/**
1683
 * Implements callback_filter_process().
1684
 *
1685
 * Scans the input and makes sure that HTML tags are properly closed.
1686
 */
1687
function _filter_htmlcorrector($text) {
1688
  return filter_dom_serialize(filter_dom_load($text));
1689
}
1690

    
1691
/**
1692
 * Implements callback_filter_process().
1693
 *
1694
 * Converts line breaks into <p> and <br> in an intelligent fashion.
1695
 *
1696
 * Based on: http://photomatt.net/scripts/autop
1697
 */
1698
function _filter_autop($text) {
1699
  // All block level tags
1700
  $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)';
1701

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

    
1760
/**
1761
 * Implements callback_filter_tips().
1762
 *
1763
 * Provides help for the auto-paragraph filter.
1764
 *
1765
 * @see filter_filter_info()
1766
 */
1767
function _filter_autop_tips($filter, $format, $long = FALSE) {
1768
  if ($long) {
1769
    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.');
1770
  }
1771
  else {
1772
    return t('Lines and paragraphs break automatically.');
1773
  }
1774
}
1775

    
1776
/**
1777
 * Implements callback_filter_process().
1778
 *
1779
 * Escapes all HTML tags, so they will be visible instead of being effective.
1780
 */
1781
function _filter_html_escape($text) {
1782
  return trim(check_plain($text));
1783
}
1784

    
1785
/**
1786
 * Implements callback_filter_tips().
1787
 *
1788
 * Provides help for the HTML escaping filter.
1789
 *
1790
 * @see filter_filter_info()
1791
 */
1792
function _filter_html_escape_tips($filter, $format, $long = FALSE) {
1793
  return t('No HTML tags allowed.');
1794
}
1795

    
1796
/**
1797
 * @} End of "Standard filters".
1798
 */