filter.module 66 KB

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