Projet

Général

Profil

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

root / htmltest / modules / filter / filter.module @ 85ad3d82

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
    'restrict access' => TRUE,
344
  );
345

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
617
  return $filters;
618
}
619

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
811
  return $text;
812
}
813

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
970
  return $element;
971
}
972

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

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

    
1007
  return $output;
1008
}
1009

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

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

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

    
1060
  $tips = array();
1061

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

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

    
1080
  return $tips;
1081
}
1082

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

    
1102
  return $dom_document;
1103
}
1104

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1304
  return trim($text);
1305
}
1306

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

    
1554
  return $text;
1555
}
1556

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

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

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

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

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

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

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

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

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

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

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

    
1656
  return $text;
1657
}
1658

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

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

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

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

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

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

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

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