filter.module 66 KB

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