filter.module

You are here

  1. 7 modules/filter/filter.module
  2. 4.6 modules/filter.module
  3. 4.7 modules/filter.module
  4. 5 modules/filter/filter.module
  5. 6 modules/filter/filter.module
  6. 8 core/modules/filter/filter.module

Framework for handling the filtering of content.

Functions

Namesort descending Description
check_markup Runs all the enabled filters on a piece of text.
filter_access Checks if a user has access to a particular text format.
filter_admin_format_title Displays a text format form title.
filter_default_format Returns the ID of the default text format for a particular user.
filter_dom_load Parses an HTML snippet and returns it as a DOM object.
filter_dom_serialize Converts a DOM object back to an HTML snippet.
filter_dom_serialize_escape_cdata_element Adds comments around the <!CDATA section in a dom element.
filter_element_info Implements hook_element_info().
filter_fallback_format Returns the ID of the fallback text format that all users have access to.
filter_fallback_format_title Returns the title of the fallback text format.
filter_filter_info Implements hook_filter_info().
filter_formats Retrieves a list of text formats, ordered by weight.
filter_formats_reset Resets the text format caches.
filter_format_allowcache Checks if the text in a certain text format is allowed to be cached.
filter_format_disable Disables a text format.
filter_format_exists Determines if a text format exists.
filter_format_load Loads a text format object from the database.
filter_format_save Saves a text format object to the database.
filter_form_access_denied Render API callback: Hides the field value of 'text_format' elements.
filter_get_filters Returns a list of all filters provided by modules.
filter_get_formats_by_role Retrieves a list of text formats that are allowed for a given role.
filter_get_roles_by_format Retrieves a list of roles that are allowed to use a given text format.
filter_help Implements hook_help().
filter_list_format Retrieves a list of filters for a given text format.
filter_menu Implements hook_menu().
filter_modules_disabled Implements hook_modules_disabled().
filter_modules_enabled Implements hook_modules_enabled().
filter_permission Implements hook_permission().
filter_permission_name Returns the machine-readable permission name for a provided text format.
filter_process_format Expands an element into a base element with text format selector attached.
filter_theme Implements hook_theme().
theme_filter_guidelines Returns HTML for guidelines for a text format.
theme_filter_tips_more_info Returns HTML for a link to the more extensive filter tips.
theme_text_format_wrapper Returns HTML for a text format-enabled form element.
_filter_autop Implements callback_filter_process().
_filter_autop_tips Implements callback_filter_tips().
_filter_disable_format_access Access callback: Checks access for disabling text formats.
_filter_format_is_cacheable Helper function to determine whether the output of a given text format can be cached.
_filter_html Implements callback_filter_process().
_filter_htmlcorrector Implements callback_filter_process().
_filter_html_escape Implements callback_filter_process().
_filter_html_escape_tips Implements callback_filter_tips().
_filter_html_settings Implements callback_filter_settings().
_filter_html_tips Implements callback_filter_tips().
_filter_list_cmp Sorts an array of filters by filter name.
_filter_tips Retrieves the filter tips.
_filter_url Implements callback_filter_process().
_filter_url_escape_comments Escapes the contents of HTML comments.
_filter_url_parse_email_links Makes links out of e-mail addresses.
_filter_url_parse_full_links Makes links out of absolute URLs.
_filter_url_parse_partial_links Makes links out of domain names starting with "www."
_filter_url_settings Implements callback_filter_settings().
_filter_url_tips Implements callback_filter_tips().
_filter_url_trim Shortens long URLs to http://www.example.com/long/url...

File

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