PageRenderTime 106ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/site/markdown.php

https://bitbucket.org/rohitkumbhar/breezingforms_gc
PHP | 1974 lines | 1166 code | 244 blank | 564 comment | 93 complexity | a03c1749c3f371339cac7573f6a92a90 MD5 | raw file
Possible License(s): LGPL-2.1

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. /**
  3. * BreezingForms - A Joomla Forms Application
  4. * @version 1.7.3
  5. * @package BreezingForms
  6. * @copyright (C) 2008-2011 by Markus Bopp
  7. * @license Released under the terms of the GNU General Public License
  8. **/
  9. global $MarkdownPHPVersion, $MarkdownSyntaxVersion,
  10. $md_empty_element_suffix, $md_tab_width,
  11. $md_nested_brackets_depth, $md_nested_brackets,
  12. $md_escape_table, $md_backslash_escape_table,
  13. $md_list_level;
  14. $MarkdownPHPVersion = 'Extra 1.0.1';
  15. $MarkdownSyntaxVersion = '1.0.1';
  16. #
  17. # Global default settings:
  18. #
  19. $md_empty_element_suffix = " />"; # Change to ">" for HTML output
  20. $md_tab_width = 4;
  21. $md_wp_posts = true; # Set to false to remove Markdown from posts.
  22. $md_wp_comments = true; # Set to false to remove Markdown from comments.
  23. if (isset($wp_version)) {
  24. # Post content and excerpts
  25. if ($md_wp_posts) {
  26. remove_filter('the_content', 'wpautop');
  27. remove_filter('the_excerpt', 'wpautop');
  28. add_filter('the_content', 'Markdown', 6);
  29. add_filter('get_the_excerpt', 'Markdown', 6);
  30. add_filter('get_the_excerpt', 'trim', 7);
  31. add_filter('the_excerpt', 'md_add_p');
  32. add_filter('the_excerpt_rss', 'md_strip_p');
  33. remove_filter('content_save_pre', 'balanceTags', 50);
  34. remove_filter('excerpt_save_pre', 'balanceTags', 50);
  35. add_filter('the_content', 'balanceTags', 50);
  36. add_filter('get_the_excerpt', 'balanceTags', 9);
  37. function md_add_p($text) {
  38. if (strlen($text) == 0) return;
  39. if (strcasecmp(substr($text, -3), '<p>') == 0) return $text;
  40. return '<p>'.$text.'</p>';
  41. }
  42. function md_strip_p($t) { return preg_replace('{</?[pP]>}', '', $t); }
  43. }
  44. # Comments
  45. if ($md_wp_comments) {
  46. remove_filter('comment_text', 'wpautop');
  47. remove_filter('comment_text', 'make_clickable');
  48. add_filter('pre_comment_content', 'Markdown', 6);
  49. add_filter('pre_comment_content', 'md_hide_tags', 8);
  50. add_filter('pre_comment_content', 'md_show_tags', 12);
  51. add_filter('get_comment_text', 'Markdown', 6);
  52. add_filter('get_comment_excerpt', 'Markdown', 6);
  53. add_filter('get_comment_excerpt', 'md_strip_p', 7);
  54. global $md_hidden_tags;
  55. $md_hidden_tags = array(
  56. '<p>' => md5('<p>'), '</p>' => md5('</p>'),
  57. '<pre>' => md5('<pre>'), '</pre>'=> md5('</pre>'),
  58. '<ol>' => md5('<ol>'), '</ol>' => md5('</ol>'),
  59. '<ul>' => md5('<ul>'), '</ul>' => md5('</ul>'),
  60. '<li>' => md5('<li>'), '</li>' => md5('</li>'),
  61. );
  62. function md_hide_tags($text) {
  63. global $md_hidden_tags;
  64. return str_replace(array_keys($md_hidden_tags),
  65. array_values($md_hidden_tags), $text);
  66. }
  67. function md_show_tags($text) {
  68. global $md_hidden_tags;
  69. return str_replace(array_values($md_hidden_tags),
  70. array_keys($md_hidden_tags), $text);
  71. }
  72. }
  73. }
  74. # -- bBlog Plugin Info --------------------------------------------------------
  75. function identify_modifier_markdown() {
  76. global $MarkdownPHPVersion;
  77. return array(
  78. 'name' => 'markdown',
  79. 'type' => 'modifier',
  80. 'nicename' => 'PHP Markdown Extra',
  81. 'description' => 'A text-to-HTML conversion tool for web writers',
  82. 'authors' => 'Michel Fortin and John Gruber',
  83. 'licence' => 'GPL',
  84. 'version' => $MarkdownPHPVersion,
  85. 'help' => '<a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by <a href="http://daringfireball.net/">John Gruber</a>. <a href="http://www.michelf.com/projects/php-markdown/">More...</a>'
  86. );
  87. }
  88. # -- Smarty Modifier Interface ------------------------------------------------
  89. function smarty_modifier_markdown($text) {
  90. return Markdown($text);
  91. }
  92. # -- Textile Compatibility Mode -----------------------------------------------
  93. # Rename this file to "classTextile.php" and it can replace Textile anywhere.
  94. if (strcasecmp(substr(__FILE__, -16), "classTextile.php") == 0) {
  95. # Try to include PHP SmartyPants. Should be in the same directory.
  96. @include_once 'smartypants.php';
  97. # Fake Textile class. It calls Markdown instead.
  98. class Textile {
  99. function TextileThis($text, $lite='', $encode='', $noimage='', $strict='') {
  100. if ($lite == '' && $encode == '') $text = Markdown($text);
  101. if (function_exists('SmartyPants')) $text = SmartyPants($text);
  102. return $text;
  103. }
  104. }
  105. }
  106. #
  107. # Globals:
  108. #
  109. # Regex to match balanced [brackets].
  110. # Needed to insert a maximum bracked depth while converting to PHP.
  111. $md_nested_brackets_depth = 6;
  112. $md_nested_brackets =
  113. str_repeat('(?>[^\[\]]+|\[', $md_nested_brackets_depth).
  114. str_repeat('\])*', $md_nested_brackets_depth);
  115. # Table of hash values for escaped characters:
  116. $md_escape_table = array(
  117. "\\" => md5("\\"),
  118. "`" => md5("`"),
  119. "*" => md5("*"),
  120. "_" => md5("_"),
  121. "{" => md5("{"),
  122. "}" => md5("}"),
  123. "[" => md5("["),
  124. "]" => md5("]"),
  125. "(" => md5("("),
  126. ")" => md5(")"),
  127. ">" => md5(">"),
  128. "#" => md5("#"),
  129. "+" => md5("+"),
  130. "-" => md5("-"),
  131. "." => md5("."),
  132. "!" => md5("!"),
  133. ":" => md5(":"),
  134. "|" => md5("|"),
  135. );
  136. # Create an identical table but for escaped characters.
  137. $md_backslash_escape_table;
  138. foreach ($md_escape_table as $key => $char)
  139. $md_backslash_escape_table["\\$key"] = $char;
  140. function Markdown($text) {
  141. #
  142. # Main function. The order in which other subs are called here is
  143. # essential. Link and image substitutions need to happen before
  144. # _EscapeSpecialCharsWithinTagAttributes(), so that any *'s or _'s in the <a>
  145. # and <img> tags get encoded.
  146. #
  147. # Clear the global hashes. If we don't clear these, you get conflicts
  148. # from other articles when generating a page which contains more than
  149. # one article (e.g. an index page that shows the N most recent
  150. # articles):
  151. global $md_urls, $md_titles, $md_html_blocks, $md_html_hashes;
  152. $md_urls = array();
  153. $md_titles = array();
  154. $md_html_blocks = array();
  155. $md_html_hashes = array();
  156. # Standardize line endings:
  157. # DOS to Unix and Mac to Unix
  158. $text = str_replace(array("\r\n", "\r"), "\n", $text);
  159. # Make sure $text ends with a couple of newlines:
  160. $text .= "\n\n";
  161. # Convert all tabs to spaces.
  162. $text = _Detab($text);
  163. # Turn block-level HTML blocks into hash entries
  164. $text = _HashHTMLBlocks($text);
  165. # Strip any lines consisting only of spaces and tabs.
  166. # This makes subsequent regexen easier to write, because we can
  167. # match consecutive blank lines with /\n+/ instead of something
  168. # contorted like /[ \t]*\n+/ .
  169. $text = preg_replace('/^[ \t]+$/m', '', $text);
  170. # Strip link definitions, store in hashes.
  171. $text = _StripLinkDefinitions($text);
  172. $text = _RunBlockGamut($text, FALSE);
  173. $text = _UnescapeSpecialChars($text);
  174. return $text . "\n";
  175. }
  176. function _StripLinkDefinitions($text) {
  177. #
  178. # Strips link definitions from text, stores the URLs and titles in
  179. # hash references.
  180. #
  181. global $md_tab_width;
  182. $less_than_tab = $md_tab_width - 1;
  183. # Link defs are in the form: ^[id]: url "optional title"
  184. $text = preg_replace_callback('{
  185. ^[ ]{0,'.$less_than_tab.'}\[(.+)\]: # id = $1
  186. [ \t]*
  187. \n? # maybe *one* newline
  188. [ \t]*
  189. <?(\S+?)>? # url = $2
  190. [ \t]*
  191. \n? # maybe one newline
  192. [ \t]*
  193. (?:
  194. (?<=\s) # lookbehind for whitespace
  195. ["(]
  196. (.+?) # title = $3
  197. [")]
  198. [ \t]*
  199. )? # title is optional
  200. (?:\n+|\Z)
  201. }xm',
  202. '_StripLinkDefinitions_callback',
  203. $text);
  204. return $text;
  205. }
  206. function _StripLinkDefinitions_callback($matches) {
  207. global $md_urls, $md_titles;
  208. $link_id = strtolower($matches[1]);
  209. $md_urls[$link_id] = _EncodeAmpsAndAngles($matches[2]);
  210. if (isset($matches[3]))
  211. $md_titles[$link_id] = str_replace('"', '&quot;', $matches[3]);
  212. return ''; # String that will replace the block
  213. }
  214. function _HashHTMLBlocks($text) {
  215. #
  216. # Hashify HTML Blocks and "clean tags".
  217. #
  218. # We only want to do this for block-level HTML tags, such as headers,
  219. # lists, and tables. That's because we still want to wrap <p>s around
  220. # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  221. # phrase emphasis, and spans. The list of tags we're looking for is
  222. # hard-coded.
  223. #
  224. # This works by calling _HashHTMLBlocks_InMarkdown, which then calls
  225. # _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1"
  226. # attribute is found whitin a tag, _HashHTMLBlocks_InHTML calls back
  227. # _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag.
  228. # These two functions are calling each other. It's recursive!
  229. #
  230. global $block_tags, $context_block_tags, $contain_span_tags,
  231. $clean_tags, $auto_close_tags;
  232. # Tags that are always treated as block tags:
  233. $block_tags = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|'.
  234. 'form|fieldset|iframe|hr|legend';
  235. # Tags treated as block tags only if the opening tag is alone on it's line:
  236. $context_block_tags = 'script|noscript|math|ins|del';
  237. # Tags where markdown="1" default to span mode:
  238. $contain_span_tags = 'p|h[1-6]|li|dd|dt|td|th|legend';
  239. # Tags which must not have their contents modified, no matter where
  240. # they appear:
  241. $clean_tags = 'script|math';
  242. # Tags that do not need to be closed.
  243. $auto_close_tags = 'hr|img';
  244. # Regex to match any tag.
  245. global $tag_match;
  246. $tag_match =
  247. '{
  248. ( # $2: Capture hole tag.
  249. </? # Any opening or closing tag.
  250. [\w:$]+ # Tag name.
  251. \s* # Whitespace.
  252. (?:
  253. ".*?" | # Double quotes (can contain `>`)
  254. \'.*?\' | # Single quotes (can contain `>`)
  255. .+? # Anything but quotes and `>`.
  256. )*?
  257. > # End of tag.
  258. |
  259. <!-- .*? --> # HTML Comment
  260. |
  261. <\? .*? \?> # Processing instruction
  262. |
  263. <!\[CDATA\[.*?\]\]> # CData Block
  264. )
  265. }xs';
  266. #
  267. # Call the HTML-in-Markdown hasher.
  268. #
  269. list($text, ) = _HashHTMLBlocks_InMarkdown($text);
  270. return $text;
  271. }
  272. function _HashHTMLBlocks_InMarkdown($text, $indent = 0,
  273. $enclosing_tag = '', $md_span = false)
  274. {
  275. #
  276. # Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags.
  277. #
  278. # * $indent is the number of space to be ignored when checking for code
  279. # blocks. This is important because if we don't take the indent into
  280. # account, something like this (which looks right) won't work as expected:
  281. #
  282. # <div>
  283. # <div markdown="1">
  284. # Hello World. <-- Is this a Markdown code block or text?
  285. # </div> <-- Is this a Markdown code block or a real tag?
  286. # <div>
  287. #
  288. # If you don't like this, just don't indent the tag on which
  289. # you apply the markdown="1" attribute.
  290. #
  291. # * If $enclosing_tag is not empty, stops at the first unmatched closing
  292. # tag with that name. Nested tags supported.
  293. #
  294. # * If $md_span is true, text inside must treated as span. So any double
  295. # newline will be replaced by a single newline so that it does not create
  296. # paragraphs.
  297. #
  298. # Returns an array of that form: ( processed text , remaining text )
  299. #
  300. global $block_tags, $context_block_tags, $clean_tags, $auto_close_tags,
  301. $tag_match;
  302. if ($text === '') return array('', '');
  303. # Regex to check for the presense of newlines around a block tag.
  304. $newline_match_before = "/(?:^\n?|\n\n) *$/";
  305. $newline_match_after =
  306. '{
  307. ^ # Start of text following the tag.
  308. (?:[ ]*<!--.*?-->)? # Optional comment.
  309. [ ]*\n # Must be followed by newline.
  310. }xs';
  311. # Regex to match any tag.
  312. $block_tag_match =
  313. '{
  314. ( # $2: Capture hole tag.
  315. </? # Any opening or closing tag.
  316. (?: # Tag name.
  317. '.$block_tags.' |
  318. '.$context_block_tags.' |
  319. '.$clean_tags.' |
  320. (?!\s)'.$enclosing_tag.'
  321. )
  322. \s* # Whitespace.
  323. (?:
  324. ".*?" | # Double quotes (can contain `>`)
  325. \'.*?\' | # Single quotes (can contain `>`)
  326. .+? # Anything but quotes and `>`.
  327. )*?
  328. > # End of tag.
  329. |
  330. <!-- .*? --> # HTML Comment
  331. |
  332. <\? .*? \?> # Processing instruction
  333. |
  334. <!\[CDATA\[.*?\]\]> # CData Block
  335. )
  336. }xs';
  337. $depth = 0; # Current depth inside the tag tree.
  338. $parsed = ""; # Parsed text that will be returned.
  339. #
  340. # Loop through every tag until we find the closing tag of the parent
  341. # or loop until reaching the end of text if no parent tag specified.
  342. #
  343. do {
  344. #
  345. # Split the text using the first $tag_match pattern found.
  346. # Text before pattern will be first in the array, text after
  347. # pattern will be at the end, and between will be any catches made
  348. # by the pattern.
  349. #
  350. $parts = preg_split($block_tag_match, $text, 2,
  351. PREG_SPLIT_DELIM_CAPTURE);
  352. # If in Markdown span mode, replace any multiple newlines that would
  353. # trigger a new paragraph.
  354. if ($md_span) {
  355. $parts[0] = preg_replace('/\n\n/', "\n", $parts[0]);
  356. }
  357. $parsed .= $parts[0]; # Text before current tag.
  358. # If end of $text has been reached. Stop loop.
  359. if (count($parts) < 3) {
  360. $text = "";
  361. break;
  362. }
  363. $tag = $parts[1]; # Tag to handle.
  364. $text = $parts[2]; # Remaining text after current tag.
  365. #
  366. # Check for: Tag inside code block or span
  367. #
  368. if (# Find current paragraph
  369. preg_match('/(?>^\n?|\n\n)((?>.\n?)+?)$/', $parsed, $matches) &&
  370. (
  371. # Then match in it either a code block...
  372. preg_match('/^ {'.($indent+4).'}.*(?>\n {'.($indent+4).'}.*)*'.
  373. '(?!\n)$/', $matches[1], $x) ||
  374. # ...or unbalenced code span markers. (the regex matches balenced)
  375. !preg_match('/^(?>[^`]+|(`+)(?>[^`]+|(?!\1[^`])`)*?\1(?!`))*$/s',
  376. $matches[1])
  377. ))
  378. {
  379. # Tag is in code block or span and may not be a tag at all. So we
  380. # simply skip the first char (should be a `<`).
  381. $parsed .= $tag{0};
  382. $text = substr($tag, 1) . $text; # Put back $tag minus first char.
  383. }
  384. #
  385. # Check for: Opening Block level tag or
  386. # Opening Content Block tag (like ins and del)
  387. # used as a block tag (tag is alone on it's line).
  388. #
  389. else if (preg_match("{^<(?:$block_tags)\b}", $tag) ||
  390. ( preg_match("{^<(?:$context_block_tags)\b}", $tag) &&
  391. preg_match($newline_match_before, $parsed) &&
  392. preg_match($newline_match_after, $text) )
  393. )
  394. {
  395. # Need to parse tag and following text using the HTML parser.
  396. list($block_text, $text) =
  397. _HashHTMLBlocks_InHTML($tag . $text,
  398. "_HashHTMLBlocks_HashBlock", TRUE);
  399. # Make sure it stays outside of any paragraph by adding newlines.
  400. $parsed .= "\n\n$block_text\n\n";
  401. }
  402. #
  403. # Check for: Clean tag (like script, math)
  404. # HTML Comments, processing instructions.
  405. #
  406. else if (preg_match("{^<(?:$clean_tags)\b}", $tag) ||
  407. $tag{1} == '!' || $tag{1} == '?')
  408. {
  409. # Need to parse tag and following text using the HTML parser.
  410. # (don't check for markdown attribute)
  411. list($block_text, $text) =
  412. _HashHTMLBlocks_InHTML($tag . $text,
  413. "_HashHTMLBlocks_HashClean", FALSE);
  414. $parsed .= $block_text;
  415. }
  416. #
  417. # Check for: Tag with same name as enclosing tag.
  418. #
  419. else if ($enclosing_tag !== '' &&
  420. # Same name as enclosing tag.
  421. preg_match("{^</?(?:$enclosing_tag)\b}", $tag))
  422. {
  423. #
  424. # Increase/decrease nested tag count.
  425. #
  426. if ($tag{1} == '/') $depth--;
  427. else if ($tag{strlen($tag)-2} != '/') $depth++;
  428. if ($depth < 0) {
  429. #
  430. # Going out of parent element. Clean up and break so we
  431. # return to the calling function.
  432. #
  433. $text = $tag . $text;
  434. break;
  435. }
  436. $parsed .= $tag;
  437. }
  438. else {
  439. $parsed .= $tag;
  440. }
  441. } while ($depth >= 0);
  442. return array($parsed, $text);
  443. }
  444. function _HashHTMLBlocks_InHTML($text, $hash_function, $md_attr) {
  445. #
  446. # Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags.
  447. #
  448. # * Calls $hash_function to convert any blocks.
  449. # * Stops when the first opening tag closes.
  450. # * $md_attr indicate if the use of the `markdown="1"` attribute is allowed.
  451. # (it is not inside clean tags)
  452. #
  453. # Returns an array of that form: ( processed text , remaining text )
  454. #
  455. global $auto_close_tags, $contain_span_tags, $tag_match;
  456. if ($text === '') return array('', '');
  457. # Regex to match `markdown` attribute inside of a tag.
  458. $markdown_attr_match = '
  459. {
  460. \s* # Eat whitespace before the `markdown` attribute
  461. markdown
  462. \s*=\s*
  463. (["\']) # $1: quote delimiter
  464. (.*?) # $2: attribute value
  465. \1 # matching delimiter
  466. }xs';
  467. $original_text = $text; # Save original text in case of faliure.
  468. $depth = 0; # Current depth inside the tag tree.
  469. $block_text = ""; # Temporary text holder for current text.
  470. $parsed = ""; # Parsed text that will be returned.
  471. #
  472. # Get the name of the starting tag.
  473. #
  474. if (preg_match("/^<([\w:$]*)\b/", $text, $matches))
  475. $base_tag_name = $matches[1];
  476. #
  477. # Loop through every tag until we find the corresponding closing tag.
  478. #
  479. do {
  480. #
  481. # Split the text using the first $tag_match pattern found.
  482. # Text before pattern will be first in the array, text after
  483. # pattern will be at the end, and between will be any catches made
  484. # by the pattern.
  485. #
  486. $parts = preg_split($tag_match, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
  487. if (count($parts) < 3) {
  488. #
  489. # End of $text reached with unbalenced tag(s).
  490. # In that case, we return original text unchanged and pass the
  491. # first character as filtered to prevent an infinite loop in the
  492. # parent function.
  493. #
  494. return array($original_text{0}, substr($original_text, 1));
  495. }
  496. $block_text .= $parts[0]; # Text before current tag.
  497. $tag = $parts[1]; # Tag to handle.
  498. $text = $parts[2]; # Remaining text after current tag.
  499. #
  500. # Check for: Auto-close tag (like <hr/>)
  501. # Comments and Processing Instructions.
  502. #
  503. if (preg_match("{^</?(?:$auto_close_tags)\b}", $tag) ||
  504. $tag{1} == '!' || $tag{1} == '?')
  505. {
  506. # Just add the tag to the block as if it was text.
  507. $block_text .= $tag;
  508. }
  509. else {
  510. #
  511. # Increase/decrease nested tag count. Only do so if
  512. # the tag's name match base tag's.
  513. #
  514. if (preg_match("{^</?$base_tag_name\b}", $tag)) {
  515. if ($tag{1} == '/') $depth--;
  516. else if ($tag{strlen($tag)-2} != '/') $depth++;
  517. }
  518. #
  519. # Check for `markdown="1"` attribute and handle it.
  520. #
  521. if ($md_attr &&
  522. preg_match($markdown_attr_match, $tag, $attr_matches) &&
  523. preg_match('/^(?:1|block|span)$/', $attr_matches[2]))
  524. {
  525. # Remove `markdown` attribute from opening tag.
  526. $tag = preg_replace($markdown_attr_match, '', $tag);
  527. # Check if text inside this tag must be parsed in span mode.
  528. $md_mode = $attr_matches[2];
  529. $span_mode = $md_mode == 'span' || $md_mode != 'block' &&
  530. preg_match("{^<(?:$contain_span_tags)\b}", $tag);
  531. # Calculate indent before tag.
  532. preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches);
  533. $indent = strlen($matches[1]);
  534. # End preceding block with this tag.
  535. $block_text .= $tag;
  536. $parsed .= $hash_function($block_text, $span_mode);
  537. # Get enclosing tag name for the ParseMarkdown function.
  538. preg_match('/^<([\w:$]*)\b/', $tag, $matches);
  539. $tag_name = $matches[1];
  540. # Parse the content using the HTML-in-Markdown parser.
  541. list ($block_text, $text)
  542. = _HashHTMLBlocks_InMarkdown($text, $indent,
  543. $tag_name, $span_mode);
  544. # Outdent markdown text.
  545. if ($indent > 0) {
  546. $block_text = preg_replace("/^[ ]{1,$indent}/m", "",
  547. $block_text);
  548. }
  549. # Append tag content to parsed text.
  550. if (!$span_mode) $parsed .= "\n\n$block_text\n\n";
  551. else $parsed .= "$block_text";
  552. # Start over a new block.
  553. $block_text = "";
  554. }
  555. else $block_text .= $tag;
  556. }
  557. } while ($depth > 0);
  558. #
  559. # Hash last block text that wasn't processed inside the loop.
  560. #
  561. $parsed .= $hash_function($block_text);
  562. return array($parsed, $text);
  563. }
  564. function _HashHTMLBlocks_HashBlock($text) {
  565. global $md_html_hashes, $md_html_blocks;
  566. $key = md5($text);
  567. $md_html_hashes[$key] = $text;
  568. $md_html_blocks[$key] = $text;
  569. return $key; # String that will replace the tag.
  570. }
  571. function _HashHTMLBlocks_HashClean($text) {
  572. global $md_html_hashes;
  573. $key = md5($text);
  574. $md_html_hashes[$key] = $text;
  575. return $key; # String that will replace the clean tag.
  576. }
  577. function _HashBlock($text) {
  578. #
  579. # Called whenever a tag must be hashed. When a function insert a block-level
  580. # tag in $text, it pass through this function and is automaticaly escaped,
  581. # which remove the need to call _HashHTMLBlocks at every step.
  582. #
  583. # Swap back any tag hash found in $text so we do not have to _UnhashTags
  584. # multiple times at the end. Must do this because of
  585. $text = _UnhashTags($text);
  586. # Then hash the block as normal.
  587. return _HashHTMLBlocks_HashBlock($text);
  588. }
  589. function _RunBlockGamut($text, $hash_html_blocks = TRUE) {
  590. #
  591. # These are all the transformations that form block-level
  592. # tags like paragraphs, headers, and list items.
  593. #
  594. if ($hash_html_blocks) {
  595. # We need to escape raw HTML in Markdown source before doing anything
  596. # else. This need to be done for each block, and not only at the
  597. # begining in the Markdown function since hashed blocks can be part of
  598. # a list item and could have been indented. Indented blocks would have
  599. # been seen as a code block in previous pass of _HashHTMLBlocks.
  600. $text = _HashHTMLBlocks($text);
  601. }
  602. $text = _DoHeaders($text);
  603. $text = _DoTables($text);
  604. # Do Horizontal Rules:
  605. global $md_empty_element_suffix;
  606. $text = preg_replace(
  607. array('{^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$}emx',
  608. '{^[ ]{0,2}([ ]? -[ ]?){3,}[ \t]*$}emx',
  609. '{^[ ]{0,2}([ ]? _[ ]?){3,}[ \t]*$}emx'),
  610. "_HashBlock('\n<hr$md_empty_element_suffix\n')",
  611. $text);
  612. $text = _DoLists($text);
  613. $text = _DoDefLists($text);
  614. $text = _DoCodeBlocks($text);
  615. $text = _DoBlockQuotes($text);
  616. $text = _FormParagraphs($text);
  617. return $text;
  618. }
  619. function _RunSpanGamut($text) {
  620. #
  621. # These are all the transformations that occur *within* block-level
  622. # tags like paragraphs, headers, and list items.
  623. #
  624. global $md_empty_element_suffix;
  625. $text = _DoCodeSpans($text);
  626. $text = _EscapeSpecialChars($text);
  627. # Process anchor and image tags. Images must come first,
  628. # because ![foo][f] looks like an anchor.
  629. $text = _DoImages($text);
  630. $text = _DoAnchors($text);
  631. # Make links out of things like `<http://example.com/>`
  632. # Must come after _DoAnchors(), because you can use < and >
  633. # delimiters in inline links like [this](<url>).
  634. $text = _DoAutoLinks($text);
  635. $text = _EncodeAmpsAndAngles($text);
  636. $text = _DoItalicsAndBold($text);
  637. # Do hard breaks:
  638. $text = preg_replace('/ {2,}\n/', "<br$md_empty_element_suffix\n", $text);
  639. return $text;
  640. }
  641. function _EscapeSpecialChars($text) {
  642. global $md_escape_table;
  643. $tokens = _TokenizeHTML($text);
  644. $text = ''; # rebuild $text from the tokens
  645. # $in_pre = 0; # Keep track of when we're inside <pre> or <code> tags.
  646. # $tags_to_skip = "!<(/?)(?:pre|code|kbd|script|math)[\s>]!";
  647. foreach ($tokens as $cur_token) {
  648. if ($cur_token[0] == 'tag') {
  649. # Within tags, encode * and _ so they don't conflict
  650. # with their use in Markdown for italics and strong.
  651. # We're replacing each such character with its
  652. # corresponding MD5 checksum value; this is likely
  653. # overkill, but it should prevent us from colliding
  654. # with the escape values by accident.
  655. $cur_token[1] = str_replace(array('*', '_'),
  656. array($md_escape_table['*'], $md_escape_table['_']),
  657. $cur_token[1]);
  658. $text .= $cur_token[1];
  659. } else {
  660. $t = $cur_token[1];
  661. $t = _EncodeBackslashEscapes($t);
  662. $text .= $t;
  663. }
  664. }
  665. return $text;
  666. }
  667. function _DoAnchors($text) {
  668. #
  669. # Turn Markdown link shortcuts into XHTML <a> tags.
  670. #
  671. global $md_nested_brackets;
  672. #
  673. # First, handle reference-style links: [link text] [id]
  674. #
  675. $text = preg_replace_callback("{
  676. ( # wrap whole match in $1
  677. \\[
  678. ($md_nested_brackets) # link text = $2
  679. \\]
  680. [ ]? # one optional space
  681. (?:\\n[ ]*)? # one optional newline followed by spaces
  682. \\[
  683. (.*?) # id = $3
  684. \\]
  685. )
  686. }xs",
  687. '_DoAnchors_reference_callback', $text);
  688. #
  689. # Next, inline-style links: [link text](url "optional title")
  690. #
  691. $text = preg_replace_callback("{
  692. ( # wrap whole match in $1
  693. \\[
  694. ($md_nested_brackets) # link text = $2
  695. \\]
  696. \\( # literal paren
  697. [ \\t]*
  698. <?(.*?)>? # href = $3
  699. [ \\t]*
  700. ( # $4
  701. (['\"]) # quote char = $5
  702. (.*?) # Title = $6
  703. \\5 # matching quote
  704. )? # title is optional
  705. \\)
  706. )
  707. }xs",
  708. '_DoAnchors_inline_callback', $text);
  709. return $text;
  710. }
  711. function _DoAnchors_reference_callback($matches) {
  712. global $md_urls, $md_titles, $md_escape_table;
  713. $whole_match = $matches[1];
  714. $link_text = $matches[2];
  715. $link_id = strtolower($matches[3]);
  716. if ($link_id == "") {
  717. $link_id = strtolower($link_text); # for shortcut links like [this][].
  718. }
  719. if (isset($md_urls[$link_id])) {
  720. $url = $md_urls[$link_id];
  721. # We've got to encode these to avoid conflicting with italics/bold.
  722. $url = str_replace(array('*', '_'),
  723. array($md_escape_table['*'], $md_escape_table['_']),
  724. $url);
  725. $result = "<a href=\"$url\"";
  726. if ( isset( $md_titles[$link_id] ) ) {
  727. $title = $md_titles[$link_id];
  728. $title = str_replace(array('*', '_'),
  729. array($md_escape_table['*'],
  730. $md_escape_table['_']), $title);
  731. $result .= " title=\"$title\"";
  732. }
  733. $result .= ">$link_text</a>";
  734. }
  735. else {
  736. $result = $whole_match;
  737. }
  738. return $result;
  739. }
  740. function _DoAnchors_inline_callback($matches) {
  741. global $md_escape_table;
  742. $whole_match = $matches[1];
  743. $link_text = $matches[2];
  744. $url = $matches[3];
  745. $title =& $matches[6];
  746. # We've got to encode these to avoid conflicting with italics/bold.
  747. $url = str_replace(array('*', '_'),
  748. array($md_escape_table['*'], $md_escape_table['_']),
  749. $url);
  750. $result = "<a href=\"$url\"";
  751. if (isset($title)) {
  752. $title = str_replace('"', '&quot;', $title);
  753. $title = str_replace(array('*', '_'),
  754. array($md_escape_table['*'], $md_escape_table['_']),
  755. $title);
  756. $result .= " title=\"$title\"";
  757. }
  758. $result .= ">$link_text</a>";
  759. return $result;
  760. }
  761. function _DoImages($text) {
  762. #
  763. # Turn Markdown image shortcuts into <img> tags.
  764. #
  765. global $md_nested_brackets;
  766. #
  767. # First, handle reference-style labeled images: ![alt text][id]
  768. #
  769. $text = preg_replace_callback('{
  770. ( # wrap whole match in $1
  771. !\[
  772. ('.$md_nested_brackets.') # alt text = $2
  773. \]
  774. [ ]? # one optional space
  775. (?:\n[ ]*)? # one optional newline followed by spaces
  776. \[
  777. (.*?) # id = $3
  778. \]
  779. )
  780. }xs',
  781. '_DoImages_reference_callback', $text);
  782. #
  783. # Next, handle inline images: ![alt text](url "optional title")
  784. # Don't forget: encode * and _
  785. $text = preg_replace_callback('{
  786. ( # wrap whole match in $1
  787. !\[
  788. ('.$md_nested_brackets.') # alt text = $2
  789. \]
  790. \( # literal paren
  791. [ \t]*
  792. <?(\S+?)>? # src url = $3
  793. [ \t]*
  794. ( # $4
  795. ([\'"]) # quote char = $5
  796. (.*?) # title = $6
  797. \5 # matching quote
  798. [ \t]*
  799. )? # title is optional
  800. \)
  801. )
  802. }xs',
  803. '_DoImages_inline_callback', $text);
  804. return $text;
  805. }
  806. function _DoImages_reference_callback($matches) {
  807. global $md_urls, $md_titles, $md_empty_element_suffix, $md_escape_table;
  808. $whole_match = $matches[1];
  809. $alt_text = $matches[2];
  810. $link_id = strtolower($matches[3]);
  811. if ($link_id == "") {
  812. $link_id = strtolower($alt_text); # for shortcut links like ![this][].
  813. }
  814. $alt_text = str_replace('"', '&quot;', $alt_text);
  815. if (isset($md_urls[$link_id])) {
  816. $url = $md_urls[$link_id];
  817. # We've got to encode these to avoid conflicting with italics/bold.
  818. $url = str_replace(array('*', '_'),
  819. array($md_escape_table['*'], $md_escape_table['_']),
  820. $url);
  821. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  822. if (isset($md_titles[$link_id])) {
  823. $title = $md_titles[$link_id];
  824. $title = str_replace(array('*', '_'),
  825. array($md_escape_table['*'],
  826. $md_escape_table['_']), $title);
  827. $result .= " title=\"$title\"";
  828. }
  829. $result .= $md_empty_element_suffix;
  830. }
  831. else {
  832. # If there's no such link ID, leave intact:
  833. $result = $whole_match;
  834. }
  835. return $result;
  836. }
  837. function _DoImages_inline_callback($matches) {
  838. global $md_empty_element_suffix, $md_escape_table;
  839. $whole_match = $matches[1];
  840. $alt_text = $matches[2];
  841. $url = $matches[3];
  842. $title = '';
  843. if (isset($matches[6])) {
  844. $title = $matches[6];
  845. }
  846. $alt_text = str_replace('"', '&quot;', $alt_text);
  847. $title = str_replace('"', '&quot;', $title);
  848. # We've got to encode these to avoid conflicting with italics/bold.
  849. $url = str_replace(array('*', '_'),
  850. array($md_escape_table['*'], $md_escape_table['_']),
  851. $url);
  852. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  853. if (isset($title)) {
  854. $title = str_replace(array('*', '_'),
  855. array($md_escape_table['*'], $md_escape_table['_']),
  856. $title);
  857. $result .= " title=\"$title\""; # $title already quoted
  858. }
  859. $result .= $md_empty_element_suffix;
  860. return $result;
  861. }
  862. function _DoHeaders($text) {
  863. # Setext-style headers:
  864. # Header 1
  865. # ========
  866. #
  867. # Header 2
  868. # --------
  869. #
  870. $text = preg_replace(
  871. array('{ (^.+?) (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? [ \t]*\n=+[ \t]*\n+ }emx',
  872. '{ (^.+?) (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? [ \t]*\n-+[ \t]*\n+ }emx'),
  873. array("_HashBlock('<h1'. ('\\2'? ' id=\"'._UnslashQuotes('\\2').'\"':'').
  874. '>'._RunSpanGamut(_UnslashQuotes('\\1')).'</h1>'
  875. ) . '\n\n'",
  876. "_HashBlock('<h2'. ('\\2'? ' id=\"'._UnslashQuotes('\\2').'\"':'').
  877. '>'._RunSpanGamut(_UnslashQuotes('\\1')).'</h2>'
  878. ) . '\n\n'"),
  879. $text);
  880. # atx-style headers:
  881. # # Header 1
  882. # ## Header 2
  883. # ## Header 2 with closing hashes ##
  884. # ...
  885. # ###### Header 6
  886. #
  887. $text = preg_replace('{
  888. ^(\#{1,6}) # $1 = string of #\'s
  889. [ \t]*
  890. (.+?) # $2 = Header text
  891. [ \t]*
  892. \#* # optional closing #\'s (not counted)
  893. (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\}[ ]*)? # id attribute
  894. \n+
  895. }xme',
  896. "_HashBlock(
  897. '<h'.strlen('\\1'). ('\\3'? ' id=\"'._UnslashQuotes('\\3').'\"':'').'>'.
  898. _RunSpanGamut(_UnslashQuotes('\\2')).
  899. '</h'.strlen('\\1').'>'
  900. ) . '\n\n'",
  901. $text);
  902. return $text;
  903. }
  904. function _DoTables($text) {
  905. #
  906. # Form HTML tables.
  907. #
  908. global $md_tab_width;
  909. $less_than_tab = $md_tab_width - 1;
  910. #
  911. # Find tables with leading pipe.
  912. #
  913. # | Header 1 | Header 2
  914. # | -------- | --------
  915. # | Cell 1 | Cell 2
  916. # | Cell 3 | Cell 4
  917. #
  918. $text = preg_replace_callback('
  919. {
  920. ^ # Start of a line
  921. [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
  922. [|] # Optional leading pipe (present)
  923. (.+) \n # $1: Header row (at least one pipe)
  924. [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
  925. [|] ([ ]*[-:]+[-| :]*) \n # $2: Header underline
  926. ( # $3: Cells
  927. (?:
  928. [ ]* # Allowed whitespace.
  929. [|] .* \n # Row content.
  930. )*
  931. )
  932. (?=\n|\Z) # Stop at final double newline.
  933. }xm',
  934. '_DoTable_LeadingPipe_callback', $text);
  935. #
  936. # Find tables without leading pipe.
  937. #
  938. # Header 1 | Header 2
  939. # -------- | --------
  940. # Cell 1 | Cell 2
  941. # Cell 3 | Cell 4
  942. #
  943. $text = preg_replace_callback('
  944. {
  945. ^ # Start of a line
  946. [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
  947. (\S.*[|].*) \n # $1: Header row (at least one pipe)
  948. [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
  949. ([-:]+[ ]*[|][-| :]*) \n # $2: Header underline
  950. ( # $3: Cells
  951. (?:
  952. .* [|] .* \n # Row content
  953. )*
  954. )
  955. (?=\n|\Z) # Stop at final double newline.
  956. }xm',
  957. '_DoTable_callback', $text);
  958. return $text;
  959. }
  960. function _DoTable_LeadingPipe_callback($matches) {
  961. $head = $matches[1];
  962. $underline = $matches[2];
  963. $content = $matches[3];
  964. # Remove leading pipe for each row.
  965. $content = preg_replace('/^ *[|]/m', '', $content);
  966. return _DoTable_callback(array($matches[0], $head, $underline, $content));
  967. }
  968. function _DoTable_callback($matches) {
  969. $head = $matches[1];
  970. $underline = $matches[2];
  971. $content = $matches[3];
  972. # Remove any tailing pipes for each line.
  973. $head = preg_replace('/[|] *$/m', '', $head);
  974. $underline = preg_replace('/[|] *$/m', '', $underline);
  975. $content = preg_replace('/[|] *$/m', '', $content);
  976. # Reading alignement from header underline.
  977. $separators = preg_split('/ *[|] */', $underline);
  978. foreach ($separators as $n => $s) {
  979. if (preg_match('/^ *-+: *$/', $s)) $attr[$n] = ' align="right"';
  980. else if (preg_match('/^ *:-+: *$/', $s))$attr[$n] = ' align="center"';
  981. else if (preg_match('/^ *:-+ *$/', $s)) $attr[$n] = ' align="left"';
  982. else $attr[$n] = '';
  983. }
  984. # Creating code spans before splitting the row is an easy way to
  985. # handle a code span containg pipes.
  986. $head = _DoCodeSpans($head);
  987. $headers = preg_split('/ *[|] */', $head);
  988. $col_count = count($headers);
  989. # Write column headers.
  990. $text = "<table>\n";
  991. $text .= "<thead>\n";
  992. $text .= "<tr>\n";
  993. foreach ($headers as $n => $header)
  994. $text .= " <th$attr[$n]>"._RunSpanGamut(trim($header))."</th>\n";
  995. $text .= "</tr>\n";
  996. $text .= "</thead>\n";
  997. # Split content by row.
  998. $rows = explode("\n", trim($content, "\n"));
  999. $text .= "<tbody>\n";
  1000. foreach ($rows as $row) {
  1001. # Creating code spans before splitting the row is an easy way to
  1002. # handle a code span containg pipes.
  1003. $row = _DoCodeSpans($row);
  1004. # Split row by cell.
  1005. $row_cells = preg_split('/ *[|] */', $row, $col_count);
  1006. $row_cells = array_pad($row_cells, $col_count, '');
  1007. $text .= "<tr>\n";
  1008. foreach ($row_cells as $n => $cell)
  1009. $text .= " <td$attr[$n]>"._RunSpanGamut(trim($cell))."</td>\n";
  1010. $text .= "</tr>\n";
  1011. }
  1012. $text .= "</tbody>\n";
  1013. $text .= "</table>";
  1014. return _HashBlock($text) . "\n";
  1015. }
  1016. function _DoLists($text) {
  1017. #
  1018. # Form HTML ordered (numbered) and unordered (bulleted) lists.
  1019. #
  1020. global $md_tab_width, $md_list_level;
  1021. $less_than_tab = $md_tab_width - 1;
  1022. # Re-usable patterns to match list item bullets and number markers:
  1023. $marker_ul = '[*+-]';
  1024. $marker_ol = '\d+[.]';
  1025. $marker_any = "(?:$marker_ul|$marker_ol)";
  1026. $markers = array($marker_ul, $marker_ol);
  1027. foreach ($markers as $marker) {
  1028. # Re-usable pattern to match any entirel ul or ol list:
  1029. $whole_list = '
  1030. ( # $1 = whole list
  1031. ( # $2
  1032. [ ]{0,'.$less_than_tab.'}
  1033. ('.$marker.') # $3 = first list item marker
  1034. [ \t]+
  1035. )
  1036. (?s:.+?)
  1037. ( # $4
  1038. \z
  1039. |
  1040. \n{2,}
  1041. (?=\S)
  1042. (?! # Negative lookahead for another list item marker
  1043. [ \t]*
  1044. '.$marker.'[ \t]+
  1045. )
  1046. )
  1047. )
  1048. '; // mx
  1049. # We use a different prefix before nested lists than top-level lists.
  1050. # See extended comment in _ProcessListItems().
  1051. if ($md_list_level) {
  1052. $text = preg_replace_callback('{
  1053. ^
  1054. '.$whole_list.'
  1055. }mx',
  1056. '_DoLists_callback', $text);
  1057. }
  1058. else {
  1059. $text = preg_replace_callback('{
  1060. (?:(?<=\n\n)|\A\n?)
  1061. '.$whole_list.'
  1062. }mx',
  1063. '_DoLists_callback', $text);
  1064. }
  1065. }
  1066. return $text;
  1067. }
  1068. function _DoLists_callback($matches) {
  1069. # Re-usable patterns to match list item bullets and number markers:
  1070. $marker_ul = '[*+-]';
  1071. $marker_ol = '\d+[.]';
  1072. $marker_any = "(?:$marker_ul|$marker_ol)";
  1073. $list = $matches[1];
  1074. $list_type = preg_match("/$marker_ul/", $matches[3]) ? "ul" : "ol";
  1075. $marker_any = ( $list_type == "ul" ? $marker_ul : $marker_ol );
  1076. # Turn double returns into triple returns, so that we can make a
  1077. # paragraph for the last item in a list, if necessary:
  1078. $list = preg_replace("/\n{2,}/", "\n\n\n", $list);
  1079. $result = _ProcessListItems($list, $marker_any);
  1080. $result = "<$list_type>\n" . $result . "</$list_type>";
  1081. return "\n" . _HashBlock($result) . "\n\n";
  1082. }
  1083. function _ProcessListItems($list_str, $marker_any) {
  1084. #
  1085. # Process the contents of a single ordered or unordered list, splitting it
  1086. # into individual list items.
  1087. #
  1088. global $md_list_level;
  1089. # The $md_list_level global keeps track of when we're inside a list.
  1090. # Each time we enter a list, we increment it; when we leave a list,
  1091. # we decrement. If it's zero, we're not in a list anymore.
  1092. #
  1093. # We do this because when we're not inside a list, we want to treat
  1094. # something like this:
  1095. #
  1096. # I recommend upgrading to version
  1097. # 8. Oops, now this line is treated
  1098. # as a sub-list.
  1099. #
  1100. # As a single paragraph, despite the fact that the second line starts
  1101. # with a digit-period-space sequence.
  1102. #
  1103. # Whereas when we're inside a list (or sub-list), that line will be
  1104. # treated as the start of a sub-list. What a kludge, huh? This is
  1105. # an aspect of Markdown's syntax that's hard to parse perfectly
  1106. # without resorting to mind-reading. Perhaps the solution is to
  1107. # change the syntax rules such that sub-lists must start with a
  1108. # starting cardinal number; e.g. "1." or "a.".
  1109. $md_list_level++;
  1110. # trim trailing blank lines:
  1111. $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
  1112. $list_str = preg_replace_callback('{
  1113. (\n)? # leading line = $1
  1114. (^[ \t]*) # leading whitespace = $2
  1115. ('.$marker_any.') [ \t]+ # list marker = $3
  1116. ((?s:.+?) # list item text = $4
  1117. (\n{1,2}))
  1118. (?= \n* (\z | \2 ('.$marker_any.') [ \t]+))
  1119. }xm',
  1120. '_ProcessListItems_callback', $list_str);
  1121. $md_list_level--;
  1122. return $list_str;
  1123. }
  1124. function _ProcessListItems_callback($matches) {
  1125. $item = $matches[4];
  1126. $leading_line =& $matches[1];
  1127. $leading_space =& $matches[2];
  1128. if ($leading_line || preg_match('/\n{2,}/', $item)) {
  1129. $item = _RunBlockGamut(_Outdent($item));
  1130. }
  1131. else {
  1132. # Recursion for sub-lists:
  1133. $item = _DoLists(_Outdent($item));
  1134. $item = preg_replace('/\n+$/', '', $item);
  1135. $item = _RunSpanGamut($item);
  1136. }
  1137. return "<li>" . $item . "</li>\n";
  1138. }
  1139. function _DoDefLists($text) {
  1140. #
  1141. # Form HTML definition lists.
  1142. #
  1143. global $md_tab_width;
  1144. $less_than_tab = $md_tab_width - 1;
  1145. # Re-usable patterns to match list item bullets and number markers:
  1146. # Re-usable pattern to match any entire dl list:
  1147. $whole_list = '
  1148. ( # $1 = whole list
  1149. ( # $2
  1150. [ ]{0,'.$less_than_tab.'}
  1151. ((?>.*\S.*\n)+) # $3 = defined term
  1152. \n?
  1153. [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
  1154. )
  1155. (?s:.+?)
  1156. ( # $4
  1157. \z
  1158. |
  1159. \n{2,}
  1160. (?=\S)
  1161. (?! # Negative lookahead for another term
  1162. [ ]{0,'.$less_than_tab.'}
  1163. (?: \S.*\n )+? # defined term
  1164. \n?
  1165. [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
  1166. )
  1167. (?! # Negative lookahead for another definition
  1168. [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
  1169. )
  1170. )
  1171. )
  1172. '; // mx
  1173. $text = preg_replace_callback('{
  1174. (?:(?<=\n\n)|\A\n?)
  1175. '.$whole_list.'
  1176. }mx',
  1177. '_DoDefLists_callback', $text);
  1178. return $text;
  1179. }
  1180. function _DoDefLists_callback($matches) {
  1181. # Re-usable patterns to match list item bullets and number markers:
  1182. $list = $matches[1];
  1183. # Turn double returns into triple returns, so that we can make a
  1184. # paragraph for the last item in a list, if necessary:
  1185. $result = trim(_ProcessDefListItems($list));
  1186. $result = "<dl>\n" . $result . "\n</dl>";
  1187. return _HashBlock($result) . "\n\n";
  1188. }
  1189. function _ProcessDefListItems($list_str) {
  1190. #
  1191. # Process the contents of a single ordered or unordered list, splitting it
  1192. # into individual list items.
  1193. #
  1194. global $md_tab_width;
  1195. $less_than_tab = $md_tab_width - 1;
  1196. # trim trailing blank lines:
  1197. $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
  1198. # Process definition terms.
  1199. $list_str = preg_replace_callback('{
  1200. (?:\n\n+|\A\n?) # leading line
  1201. ( # definition terms = $1
  1202. [ ]{0,'.$less_than_tab.'} # leading whitespace
  1203. (?![:][ ]|[ ]) # negative lookahead for a definition
  1204. # mark (colon) or more whitespace.
  1205. (?: \S.* \n)+? # actual term (not whitespace).
  1206. )
  1207. (?=\n?[ ]{0,3}:[ ]) # lookahead for following line feed
  1208. # with a definition mark.
  1209. }xm',
  1210. '_ProcessDefListItems_callback_dt', $list_str);
  1211. # Process actual definitions.
  1212. $list_str = preg_replace_callback('{
  1213. \n(\n+)? # leading line = $1
  1214. [ ]{0,'.$less_than_tab.'} # whitespace before colon
  1215. [:][ ]+ # definition mark (colon)
  1216. ((?s:.+?)) # definition text = $2
  1217. (?= \n+ # stop at next definition mark,
  1218. (?: # next term or end of text
  1219. [ ]{0,'.$less_than_tab.'} [:][ ] |
  1220. <dt> | \z
  1221. )
  1222. )
  1223. }xm',
  1224. '_ProcessDefListItems_callback_dd', $list_str);
  1225. return $list_str;
  1226. }
  1227. function _ProcessDefListItems_callback_dt($matches) {
  1228. $terms = explode("\n", trim($matches[1]));
  1229. $text = '';
  1230. foreach ($terms as $term) {
  1231. $term = _RunSpanGamut(trim($term));
  1232. $text .= "\n<dt>" . $term . "</dt>";
  1233. }
  1234. return $text . "\n";
  1235. }
  1236. function _ProcessDefListItems_callback_dd($matches) {
  1237. $leading_line = $matches[1];
  1238. $def = $matches[2];
  1239. if ($leading_line || preg_match('/\n{2,}/', $def)) {
  1240. $def = _RunBlockGamut(_Outdent($def . "\n\n"));
  1241. $def = "\n". $def ."\n";
  1242. }
  1243. else {
  1244. $def = rtrim($def);
  1245. $def = _RunSpanGamut(_Outdent($def));
  1246. }
  1247. return "\n<dd>" . $def . "</dd>\n";
  1248. }
  1249. function _DoCodeBlocks($text) {
  1250. #
  1251. # Process Markdown `<pre><code>` blocks.
  1252. #
  1253. global $md_tab_width;
  1254. $text = preg_replace_callback('{
  1255. (?:\n\n|\A)
  1256. ( # $1 = the code block -- one or more lines, starting with a space/tab
  1257. (?:
  1258. (?:[ ]{'.$md_tab_width.'} | \t) # Lines must start with a tab or a tab-width of spaces
  1259. .*\n+
  1260. )+
  1261. )
  1262. ((?=^[ ]{0,'.$md_tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
  1263. }xm',
  1264. '_DoCodeBlocks_callback', $text);
  1265. return $text;
  1266. }
  1267. function _DoCodeBlocks_callback($matches) {
  1268. $codeblock = $matches[1];
  1269. $codeblock = _EncodeCode(_Outdent($codeblock));
  1270. // $codeblock = _Detab($codeblock);
  1271. # trim leading newlines and trailing whitespace
  1272. $codeblock = preg_replace(array('/\A\n+/', '/\s+\z/'), '', $codeblock);
  1273. $result = "<pre><code>" . $codeblock . "\n</code></pre>";
  1274. return "\n\n" . _HashBlock($result) . "\n\n";
  1275. }
  1276. function _DoCodeSpans($text) {
  1277. #
  1278. # * Backtick quotes are used for <code></code> spans.
  1279. #
  1280. # * You can use multiple backticks as the delimiters if you want to
  1281. # include literal backticks in the code span. So, this input:
  1282. #
  1283. # Just type ``foo `bar` baz`` at the prompt.
  1284. #
  1285. # Will translate to:
  1286. #
  1287. # <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
  1288. #
  1289. # There's no arbitrary limit to the number of backticks you
  1290. # can use as delimters. If you need three consecutive backticks
  1291. # in your code, use four for delimiters, etc.
  1292. #
  1293. # * You can use spaces to get literal backticks at the edges:
  1294. #
  1295. # ... type `` `bar` `` ...
  1296. #
  1297. # Turns to:
  1298. #
  1299. # ... type <code>`bar`</code> ...
  1300. #
  1301. $text = preg_replace_callback('@
  1302. (?<!\\\) # Character before opening ` can\'t be a backslash
  1303. (`+) # $1 = Opening run of `
  1304. (.+?) # $2 = The code block
  1305. (?<!`)
  1306. \1 # Matching closer
  1307. (?!`)
  1308. @xs',
  1309. '_DoCodeSpans_callback', $text);
  1310. return $text;
  1311. }
  1312. function _DoCodeSpans_callback($matches) {
  1313. $c = $matches[2];
  1314. $c = preg_replace('/^[ \t]*/', '', $c); # leading whitespace
  1315. $c = preg_replace('/[ \t]*$/', '', $c); # trailing whitespace
  1316. $c = _EncodeCode($c);
  1317. return "<code>$c</code>";
  1318. }
  1319. function _EncodeCode($_) {
  1320. #
  1321. # Encode/escape certain characters inside Markdown code runs.
  1322. # The point is that in code, these characters are literals,
  1323. # and lose their special Markdown meanings.
  1324. #
  1325. global $md_escape_table;
  1326. # Encode all ampersands; HTML entities are not
  1327. # entities within a Markdown code span.
  1328. $_ = str_replace('&', '&amp;', $_);
  1329. # Do the angle bracket song and dance:
  1330. $_ = str_replace(array('<', '>'),
  1331. array('&lt;', '&gt;'), $_);
  1332. # Now, escape characters that are magic in Markdown:
  1333. $_ = str_replace(array_keys($md_escape_table),
  1334. array_values($md_escape_table), $_);
  1335. return $_;
  1336. }
  1337. function _DoItalicsAndBold($text) {
  1338. # <strong> must go first:
  1339. $text = preg_replace(array(
  1340. '{
  1341. ( (?<!\w) __ ) # $1: Marker (not preceded by alphanum)
  1342. (?=\S) # Not followed by whitespace
  1343. (?!__) # or two others marker chars.
  1344. ( # $2: Content
  1345. (?>
  1346. [^_]+? # Anthing not em markers.
  1347. |
  1348. # Balence any regular _ emphasis inside.
  1349. (?<![a-zA-Z0-9])_ (?=\S) (?! _) (.+?)
  1350. (?<=\S) _ (?![a-zA-Z0-9])
  1351. )+?
  1352. )
  1353. (?<=\S) __ # End mark not preceded by whitespace.
  1354. (?!\w) # Not followed by alphanum.
  1355. }sx',
  1356. '{
  1357. ( (?<!\*\*) \*\* ) # $1: Marker (not preceded by two *)
  1358. (?=\S) # Not followed by whitespace
  1359. (?!\1) # or two others marker chars.
  1360. ( # $2: Content
  1361. (?>
  1362. [^*]+? # Anthing not em markers.
  1363. |
  1364. # Balence any regular * emphasis inside.
  1365. \* (?=\S) (?! \*) (.+?) (?<=\S) \*
  1366. )+?
  1367. )
  1368. (?<=\S) \*\* # End mark not preceded by whitespace.
  1369. }sx',
  1370. ),
  1371. '<strong>\2</strong>', $text);
  1372. # Then <em>:
  1373. $text = preg_replace(array(
  1374. '{ ( (?<!\w) _ ) (?=\S) (?! _) (.+?) (?<=\S) _ (?!\w) }sx',
  1375. '{ ( (?<!\*)\* ) (?=\S) (?! \*) (.+?) (?<=\S) \* }sx',
  1376. ),
  1377. '<em>\2</em>', $text);
  1378. return $text;
  1379. }
  1380. function _DoBlockQuotes($text) {
  1381. $text = preg_replace_callback('/
  1382. ( # Wrap whole match in $1
  1383. (
  1384. ^[ \t]*>[ \t]? # ">" at the start of a line
  1385. .+\n # rest of the first line
  1386. (.+\n)* # subsequent consecutive lines
  1387. \n* # blanks
  1388. )+
  1389. )
  1390. /xm',
  1391. '_DoBlockQuotes_callback', $text);
  1392. return $text;
  1393. }
  1394. function _DoBlockQuotes_callback($matches) {
  1395. $bq = $matches[1];
  1396. # trim one level of quoting - trim whitespace-only lines
  1397. $bq = preg_replace(array('/^[ \t]*>[ \t]?/m', '/^[ \t]+$/m'), '', $bq);
  1398. $bq = _RunBlockGamut($bq); # recurse
  1399. $bq = preg_replace('/^/m', " ", $bq);
  1400. # These leading spaces screw with <pre> content, so we need to fix that:
  1401. $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx',
  1402. '_DoBlockQuotes_callback2', $bq);
  1403. return _HashBlock("<blockquote>\n$bq\n</blockquote>") . "\n\n";
  1404. }
  1405. function _DoBlockQuotes_callback2($matches) {
  1406. $pre = $matches[1];
  1407. $pre = preg_replace('/^ /m', '', $pre);
  1408. return $pre;
  1409. }
  1410. function _FormParagraphs($text) {
  1411. #
  1412. # Params:
  1413. # $text - string to process with html <p> tags
  1414. #
  1415. global $md_html_blocks, $md_html_hashes;
  1416. # Strip leading and trailing lines:
  1417. $text = preg_replace(array('/\A\n+/', '/\n+\z/'), '', $text);
  1418. $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
  1419. #
  1420. # Wrap <p> tags and unhashify HTML blocks
  1421. #
  1422. foreach ($grafs as $key => $value) {
  1423. $value = trim(_RunSpanGamut($value));
  1424. # Check if this should be enclosed in a paragraph.
  1425. # Text equaling to a clean tag hash are not enclosed.
  1426. # Text starting with a block tag hash are not either.
  1427. $clean_key = $value;
  1428. $block_key = substr($value, 0, 32);
  1429. $is_p = (!isset($md_html_blocks[$block_key]) &&
  1430. !isset($md_html_hashes[$clean_key]));
  1431. if ($is_p) {
  1432. $value = "<p>$value</p>";
  1433. }
  1434. $grafs[$key] = $value;
  1435. }
  1436. # Join grafs in one text, then unhash HTML tags.
  1437. $text = implode("\n\n", $grafs);
  1438. # Finish by removing any tag hashes still present in $text.
  1439. $text = _UnhashTags($text);
  1440. return $text;
  1441. }
  1442. function _EncodeAmpsAndAngles($text) {
  1443. # Smart processing for ampersands and angle brackets that need to be encoded.
  1444. # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
  1445. # http://bumppo.net/projects/amputator/
  1446. $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
  1447. '&amp;', $text);;
  1448. # Encode naked <'s
  1449. $text = preg_replace('{<(?![a-z/?\$!])}i', '&lt;', $text);
  1450. return $text;
  1451. }
  1452. function _EncodeBackslashEscapes($text) {
  1453. #
  1454. # Parameter: String.
  1455. # Returns: The string, with after processing the following backslash
  1456. # escape sequences.
  1457. #
  1458. global $md_escape_table, $md_backslash_escape_table;
  1459. # Must process escaped backslashes first.
  1460. return str_replace(array_keys($md_backslash_escape_table),
  1461. array_values($md_backslash_escape_table), $text);
  1462. }
  1463. function _DoAutoLinks($text) {
  1464. $text = preg_replace("!<((https?|ftp):[^'\">\\s]+)>!",
  1465. '<a href="\1">\1</a>', $text);
  1466. # Email addresses: <address@domain.foo>
  1467. $text = preg_replace('{
  1468. <
  1469. (?:mailto:)?
  1470. (
  1471. [-.\w]+
  1472. \@
  1473. [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
  1474. )
  1475. >
  1476. }exi',
  1477. "_EncodeEmailAddress(_UnescapeSpecialChars(_UnslashQuotes('\\1')))",
  1478. $text);
  1479. return $text;
  1480. }
  1481. function _EncodeEmailAddress($addr) {
  1482. #
  1483. # Input: an email address, e.g. "foo@example.com"
  1484. #
  1485. # Output: the email address as a mailto link, with each character
  1486. # of the address encoded as either a decimal or hex entity, in
  1487. # the hopes of foiling most address harvesting spam bots. E.g.:
  1488. #
  1489. # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;
  1490. # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111;
  1491. # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>
  1492. #
  1493. # Based by a filter by Matthew Wickline, posted to the BBEdit-Talk
  1494. # mailing list: <http://tinyurl.com/yu7ue>
  1495. #
  1496. $addr = "mailto:" . $addr;
  1497. $length = strlen($addr);
  1498. # leave ':' alone (to spot mailto: later)
  1499. $addr = preg_replace_callback('/([^\:])/',
  1500. '_EncodeEmailAddress_callback', $addr);
  1501. $addr = "<a href=\"$addr\">$addr</a>";
  1502. # strip the mailto: from the visible part
  1503. $addr = preg_replace('/">.+?:/', '">', $addr);
  1504. return $addr;
  1505. }
  1506. function _EncodeEmailAddress_callback($matches) {
  1507. $char = $matches[1];
  1508. $r = rand(0, 100);
  1509. # roughly 10% raw, 45% hex, 45% dec
  1510. # '@' *must* be encoded. I insist.
  1511. if ($r > 90 && $char != '@') return $char;
  1512. if ($r < 45) return '&#x'.dechex(ord($char)).';';
  1513. return '&#'.ord($char).';';
  1514. }
  1515. function _UnescapeSpecialChars($text) {
  1516. #
  1517. # Swap back in all the special characters we've hidden.
  1518. #
  1519. global $md_escape_table;
  1520. return str_replace(array_values($md_escape_table),
  1521. array_keys($md_escape_table), $text);
  1522. }
  1523. function _UnhashTags($text) {
  1524. #
  1525. # Swap back in all the tags hashed by _HashHTMLBlocks.
  1526. #
  1527. global $md_html_hashes;
  1528. return str_replace(array_keys($md_html_hashes),
  1529. array_values($md_html_hashes), $text);
  1530. }
  1531. # _TokenizeHTML is shared between PHP Markdown and PHP SmartyPants.
  1532. # We only define it if it is not already defined.
  1533. if (!function_exists('_TokenizeHTML')) :
  1534. function _TokenizeHTML($str) {
  1535. #
  1536. # Parameter: String containing HTML markup.
  1537. # Returns: An array of the tokens comprising the input
  1538. # string. Each token is either a tag (possibly with nested,
  1539. # tags contained therein, such as <a href="<MTFoo>">, or a
  1540. # …

Large files files are truncated, but you can click here to view the full file