filter.module 66 KB

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