You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

2952 lines
90 KiB

  1. <?php
  2. #
  3. # Markdown Extra - A text-to-HTML conversion tool for web writers
  4. #
  5. # PHP Markdown & Extra
  6. # Copyright (c) 2004-2012 Michel Fortin
  7. # <http://michelf.com/projects/php-markdown/>
  8. #
  9. # Original Markdown
  10. # Copyright (c) 2004-2006 John Gruber
  11. # <http://daringfireball.net/projects/markdown/>
  12. #
  13. define( 'MARKDOWN_VERSION', "1.0.1o" ); # Sun 8 Jan 2012
  14. define( 'MARKDOWNEXTRA_VERSION', "1.2.5" ); # Sun 8 Jan 2012
  15. #
  16. # Global default settings:
  17. #
  18. # Change to ">" for HTML output
  19. @define( 'MARKDOWN_EMPTY_ELEMENT_SUFFIX', " />");
  20. # Define the width of a tab for code blocks.
  21. @define( 'MARKDOWN_TAB_WIDTH', 4 );
  22. # Optional title attribute for footnote links and backlinks.
  23. @define( 'MARKDOWN_FN_LINK_TITLE', "" );
  24. @define( 'MARKDOWN_FN_BACKLINK_TITLE', "" );
  25. # Optional class attribute for footnote links and backlinks.
  26. @define( 'MARKDOWN_FN_LINK_CLASS', "" );
  27. @define( 'MARKDOWN_FN_BACKLINK_CLASS', "" );
  28. #
  29. # WordPress settings:
  30. #
  31. # Change to false to remove Markdown from posts and/or comments.
  32. @define( 'MARKDOWN_WP_POSTS', true );
  33. @define( 'MARKDOWN_WP_COMMENTS', true );
  34. ### Standard Function Interface ###
  35. @define( 'MARKDOWN_PARSER_CLASS', 'MarkdownExtra_Parser' );
  36. function Markdown($text) {
  37. #
  38. # Initialize the parser and return the result of its transform method.
  39. #
  40. # Setup static parser variable.
  41. static $parser;
  42. if (!isset($parser)) {
  43. $parser_class = MARKDOWN_PARSER_CLASS;
  44. $parser = new $parser_class;
  45. }
  46. # Transform text using parser.
  47. return $parser->transform($text);
  48. }
  49. ### WordPress Plugin Interface ###
  50. /*
  51. Plugin Name: Markdown Extra
  52. Plugin URI: http://michelf.com/projects/php-markdown/
  53. Description: <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://michelf.com/projects/php-markdown/">More...</a>
  54. Version: 1.2.5
  55. Author: Michel Fortin
  56. Author URI: http://michelf.com/
  57. */
  58. if (isset($wp_version)) {
  59. # More details about how it works here:
  60. # <http://michelf.com/weblog/2005/wordpress-text-flow-vs-markdown/>
  61. # Post content and excerpts
  62. # - Remove WordPress paragraph generator.
  63. # - Run Markdown on excerpt, then remove all tags.
  64. # - Add paragraph tag around the excerpt, but remove it for the excerpt rss.
  65. if (MARKDOWN_WP_POSTS) {
  66. remove_filter('the_content', 'wpautop');
  67. remove_filter('the_content_rss', 'wpautop');
  68. remove_filter('the_excerpt', 'wpautop');
  69. add_filter('the_content', 'mdwp_MarkdownPost', 6);
  70. add_filter('the_content_rss', 'mdwp_MarkdownPost', 6);
  71. add_filter('get_the_excerpt', 'mdwp_MarkdownPost', 6);
  72. add_filter('get_the_excerpt', 'trim', 7);
  73. add_filter('the_excerpt', 'mdwp_add_p');
  74. add_filter('the_excerpt_rss', 'mdwp_strip_p');
  75. remove_filter('content_save_pre', 'balanceTags', 50);
  76. remove_filter('excerpt_save_pre', 'balanceTags', 50);
  77. add_filter('the_content', 'balanceTags', 50);
  78. add_filter('get_the_excerpt', 'balanceTags', 9);
  79. }
  80. # Add a footnote id prefix to posts when inside a loop.
  81. function mdwp_MarkdownPost($text) {
  82. static $parser;
  83. if (!$parser) {
  84. $parser_class = MARKDOWN_PARSER_CLASS;
  85. $parser = new $parser_class;
  86. }
  87. if (is_single() || is_page() || is_feed()) {
  88. $parser->fn_id_prefix = "";
  89. } else {
  90. $parser->fn_id_prefix = get_the_ID() . ".";
  91. }
  92. return $parser->transform($text);
  93. }
  94. # Comments
  95. # - Remove WordPress paragraph generator.
  96. # - Remove WordPress auto-link generator.
  97. # - Scramble important tags before passing them to the kses filter.
  98. # - Run Markdown on excerpt then remove paragraph tags.
  99. if (MARKDOWN_WP_COMMENTS) {
  100. remove_filter('comment_text', 'wpautop', 30);
  101. remove_filter('comment_text', 'make_clickable');
  102. add_filter('pre_comment_content', 'Markdown', 6);
  103. add_filter('pre_comment_content', 'mdwp_hide_tags', 8);
  104. add_filter('pre_comment_content', 'mdwp_show_tags', 12);
  105. add_filter('get_comment_text', 'Markdown', 6);
  106. add_filter('get_comment_excerpt', 'Markdown', 6);
  107. add_filter('get_comment_excerpt', 'mdwp_strip_p', 7);
  108. global $mdwp_hidden_tags, $mdwp_placeholders;
  109. $mdwp_hidden_tags = explode(' ',
  110. '<p> </p> <pre> </pre> <ol> </ol> <ul> </ul> <li> </li>');
  111. $mdwp_placeholders = explode(' ', str_rot13(
  112. 'pEj07ZbbBZ U1kqgh4w4p pre2zmeN6K QTi31t9pre ol0MP1jzJR '.
  113. 'ML5IjmbRol ulANi1NsGY J7zRLJqPul liA8ctl16T K9nhooUHli'));
  114. }
  115. function mdwp_add_p($text) {
  116. if (!preg_match('{^$|^<(p|ul|ol|dl|pre|blockquote)>}i', $text)) {
  117. $text = '<p>'.$text.'</p>';
  118. $text = preg_replace('{\n{2,}}', "</p>\n\n<p>", $text);
  119. }
  120. return $text;
  121. }
  122. function mdwp_strip_p($t) { return preg_replace('{</?p>}i', '', $t); }
  123. function mdwp_hide_tags($text) {
  124. global $mdwp_hidden_tags, $mdwp_placeholders;
  125. return str_replace($mdwp_hidden_tags, $mdwp_placeholders, $text);
  126. }
  127. function mdwp_show_tags($text) {
  128. global $mdwp_hidden_tags, $mdwp_placeholders;
  129. return str_replace($mdwp_placeholders, $mdwp_hidden_tags, $text);
  130. }
  131. }
  132. ### bBlog Plugin Info ###
  133. function identify_modifier_markdown() {
  134. return array(
  135. 'name' => 'markdown',
  136. 'type' => 'modifier',
  137. 'nicename' => 'PHP Markdown Extra',
  138. 'description' => 'A text-to-HTML conversion tool for web writers',
  139. 'authors' => 'Michel Fortin and John Gruber',
  140. 'licence' => 'GPL',
  141. 'version' => MARKDOWNEXTRA_VERSION,
  142. '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://michelf.com/projects/php-markdown/">More...</a>',
  143. );
  144. }
  145. ### Smarty Modifier Interface ###
  146. function smarty_modifier_markdown($text) {
  147. return Markdown($text);
  148. }
  149. ### Textile Compatibility Mode ###
  150. # Rename this file to "classTextile.php" and it can replace Textile everywhere.
  151. if (strcasecmp(substr(__FILE__, -16), "classTextile.php") == 0) {
  152. # Try to include PHP SmartyPants. Should be in the same directory.
  153. @include_once 'smartypants.php';
  154. # Fake Textile class. It calls Markdown instead.
  155. class Textile {
  156. function TextileThis($text, $lite='', $encode='') {
  157. if ($lite == '' && $encode == '') $text = Markdown($text);
  158. if (function_exists('SmartyPants')) $text = SmartyPants($text);
  159. return $text;
  160. }
  161. # Fake restricted version: restrictions are not supported for now.
  162. function TextileRestricted($text, $lite='', $noimage='') {
  163. return $this->TextileThis($text, $lite);
  164. }
  165. # Workaround to ensure compatibility with TextPattern 4.0.3.
  166. function blockLite($text) { return $text; }
  167. }
  168. }
  169. #
  170. # Markdown Parser Class
  171. #
  172. class Markdown_Parser {
  173. # Regex to match balanced [brackets].
  174. # Needed to insert a maximum bracked depth while converting to PHP.
  175. var $nested_brackets_depth = 6;
  176. var $nested_brackets_re;
  177. var $nested_url_parenthesis_depth = 4;
  178. var $nested_url_parenthesis_re;
  179. # Table of hash values for escaped characters:
  180. var $escape_chars = '\`*_{}[]()>#+-.!';
  181. var $escape_chars_re;
  182. # Change to ">" for HTML output.
  183. var $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX;
  184. var $tab_width = MARKDOWN_TAB_WIDTH;
  185. # Change to `true` to disallow markup or entities.
  186. var $no_markup = false;
  187. var $no_entities = false;
  188. # Predefined urls and titles for reference links and images.
  189. var $predef_urls = array();
  190. var $predef_titles = array();
  191. function Markdown_Parser() {
  192. #
  193. # Constructor function. Initialize appropriate member variables.
  194. #
  195. $this->_initDetab();
  196. $this->prepareItalicsAndBold();
  197. $this->nested_brackets_re =
  198. str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth).
  199. str_repeat('\])*', $this->nested_brackets_depth);
  200. $this->nested_url_parenthesis_re =
  201. str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth).
  202. str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth);
  203. $this->escape_chars_re = '['.preg_quote($this->escape_chars).']';
  204. # Sort document, block, and span gamut in ascendent priority order.
  205. asort($this->document_gamut);
  206. asort($this->block_gamut);
  207. asort($this->span_gamut);
  208. }
  209. # Internal hashes used during transformation.
  210. var $urls = array();
  211. var $titles = array();
  212. var $html_hashes = array();
  213. # Status flag to avoid invalid nesting.
  214. var $in_anchor = false;
  215. function setup() {
  216. #
  217. # Called before the transformation process starts to setup parser
  218. # states.
  219. #
  220. # Clear global hashes.
  221. $this->urls = $this->predef_urls;
  222. $this->titles = $this->predef_titles;
  223. $this->html_hashes = array();
  224. $in_anchor = false;
  225. }
  226. function teardown() {
  227. #
  228. # Called after the transformation process to clear any variable
  229. # which may be taking up memory unnecessarly.
  230. #
  231. $this->urls = array();
  232. $this->titles = array();
  233. $this->html_hashes = array();
  234. }
  235. function transform($text) {
  236. #
  237. # Main function. Performs some preprocessing on the input text
  238. # and pass it through the document gamut.
  239. #
  240. $this->setup();
  241. # Remove UTF-8 BOM and marker character in input, if present.
  242. $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text);
  243. # Standardize line endings:
  244. # DOS to Unix and Mac to Unix
  245. $text = preg_replace('{\r\n?}', "\n", $text);
  246. # Make sure $text ends with a couple of newlines:
  247. $text .= "\n\n";
  248. # Convert all tabs to spaces.
  249. $text = $this->detab($text);
  250. # Turn block-level HTML blocks into hash entries
  251. $text = $this->hashHTMLBlocks($text);
  252. # Strip any lines consisting only of spaces and tabs.
  253. # This makes subsequent regexen easier to write, because we can
  254. # match consecutive blank lines with /\n+/ instead of something
  255. # contorted like /[ ]*\n+/ .
  256. $text = preg_replace('/^[ ]+$/m', '', $text);
  257. # Run document gamut methods.
  258. foreach ($this->document_gamut as $method => $priority) {
  259. $text = $this->$method($text);
  260. }
  261. $this->teardown();
  262. return $text . "\n";
  263. }
  264. var $document_gamut = array(
  265. # Strip link definitions, store in hashes.
  266. "stripLinkDefinitions" => 20,
  267. "runBasicBlockGamut" => 30,
  268. );
  269. function stripLinkDefinitions($text) {
  270. #
  271. # Strips link definitions from text, stores the URLs and titles in
  272. # hash references.
  273. #
  274. $less_than_tab = $this->tab_width - 1;
  275. # Link defs are in the form: ^[id]: url "optional title"
  276. $text = preg_replace_callback('{
  277. ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1
  278. [ ]*
  279. \n? # maybe *one* newline
  280. [ ]*
  281. (?:
  282. <(.+?)> # url = $2
  283. |
  284. (\S+?) # url = $3
  285. )
  286. [ ]*
  287. \n? # maybe one newline
  288. [ ]*
  289. (?:
  290. (?<=\s) # lookbehind for whitespace
  291. ["(]
  292. (.*?) # title = $4
  293. [")]
  294. [ ]*
  295. )? # title is optional
  296. (?:\n+|\Z)
  297. }xm',
  298. array(&$this, '_stripLinkDefinitions_callback'),
  299. $text);
  300. return $text;
  301. }
  302. function _stripLinkDefinitions_callback($matches) {
  303. $link_id = strtolower($matches[1]);
  304. $url = $matches[2] == '' ? $matches[3] : $matches[2];
  305. $this->urls[$link_id] = $url;
  306. $this->titles[$link_id] =& $matches[4];
  307. return ''; # String that will replace the block
  308. }
  309. function hashHTMLBlocks($text) {
  310. if ($this->no_markup) return $text;
  311. $less_than_tab = $this->tab_width - 1;
  312. # Hashify HTML blocks:
  313. # We only want to do this for block-level HTML tags, such as headers,
  314. # lists, and tables. That's because we still want to wrap <p>s around
  315. # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  316. # phrase emphasis, and spans. The list of tags we're looking for is
  317. # hard-coded:
  318. #
  319. # * List "a" is made of tags which can be both inline or block-level.
  320. # These will be treated block-level when the start tag is alone on
  321. # its line, otherwise they're not matched here and will be taken as
  322. # inline later.
  323. # * List "b" is made of tags which are always block-level;
  324. #
  325. $block_tags_a_re = 'ins|del';
  326. $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'.
  327. 'script|noscript|form|fieldset|iframe|math';
  328. # Regular expression for the content of a block tag.
  329. $nested_tags_level = 4;
  330. $attr = '
  331. (?> # optional tag attributes
  332. \s # starts with whitespace
  333. (?>
  334. [^>"/]+ # text outside quotes
  335. |
  336. /+(?!>) # slash not followed by ">"
  337. |
  338. "[^"]*" # text inside double quotes (tolerate ">")
  339. |
  340. \'[^\']*\' # text inside single quotes (tolerate ">")
  341. )*
  342. )?
  343. ';
  344. $content =
  345. str_repeat('
  346. (?>
  347. [^<]+ # content without tag
  348. |
  349. <\2 # nested opening tag
  350. '.$attr.' # attributes
  351. (?>
  352. />
  353. |
  354. >', $nested_tags_level). # end of opening tag
  355. '.*?'. # last level nested tag content
  356. str_repeat('
  357. </\2\s*> # closing nested tag
  358. )
  359. |
  360. <(?!/\2\s*> # other tags with a different name
  361. )
  362. )*',
  363. $nested_tags_level);
  364. $content2 = str_replace('\2', '\3', $content);
  365. # First, look for nested blocks, e.g.:
  366. # <div>
  367. # <div>
  368. # tags for inner block must be indented.
  369. # </div>
  370. # </div>
  371. #
  372. # The outermost tags must start at the left margin for this to match, and
  373. # the inner nested divs must be indented.
  374. # We need to do this before the next, more liberal match, because the next
  375. # match will start at the first `<div>` and stop at the first `</div>`.
  376. $text = preg_replace_callback('{(?>
  377. (?>
  378. (?<=\n\n) # Starting after a blank line
  379. | # or
  380. \A\n? # the beginning of the doc
  381. )
  382. ( # save in $1
  383. # Match from `\n<tag>` to `</tag>\n`, handling nested tags
  384. # in between.
  385. [ ]{0,'.$less_than_tab.'}
  386. <('.$block_tags_b_re.')# start tag = $2
  387. '.$attr.'> # attributes followed by > and \n
  388. '.$content.' # content, support nesting
  389. </\2> # the matching end tag
  390. [ ]* # trailing spaces/tabs
  391. (?=\n+|\Z) # followed by a newline or end of document
  392. | # Special version for tags of group a.
  393. [ ]{0,'.$less_than_tab.'}
  394. <('.$block_tags_a_re.')# start tag = $3
  395. '.$attr.'>[ ]*\n # attributes followed by >
  396. '.$content2.' # content, support nesting
  397. </\3> # the matching end tag
  398. [ ]* # trailing spaces/tabs
  399. (?=\n+|\Z) # followed by a newline or end of document
  400. | # Special case just for <hr />. It was easier to make a special
  401. # case than to make the other regex more complicated.
  402. [ ]{0,'.$less_than_tab.'}
  403. <(hr) # start tag = $2
  404. '.$attr.' # attributes
  405. /?> # the matching end tag
  406. [ ]*
  407. (?=\n{2,}|\Z) # followed by a blank line or end of document
  408. | # Special case for standalone HTML comments:
  409. [ ]{0,'.$less_than_tab.'}
  410. (?s:
  411. <!-- .*? -->
  412. )
  413. [ ]*
  414. (?=\n{2,}|\Z) # followed by a blank line or end of document
  415. | # PHP and ASP-style processor instructions (<? and <%)
  416. [ ]{0,'.$less_than_tab.'}
  417. (?s:
  418. <([?%]) # $2
  419. .*?
  420. \2>
  421. )
  422. [ ]*
  423. (?=\n{2,}|\Z) # followed by a blank line or end of document
  424. )
  425. )}Sxmi',
  426. array(&$this, '_hashHTMLBlocks_callback'),
  427. $text);
  428. return $text;
  429. }
  430. function _hashHTMLBlocks_callback($matches) {
  431. $text = $matches[1];
  432. $key = $this->hashBlock($text);
  433. return "\n\n$key\n\n";
  434. }
  435. function hashPart($text, $boundary = 'X') {
  436. #
  437. # Called whenever a tag must be hashed when a function insert an atomic
  438. # element in the text stream. Passing $text to through this function gives
  439. # a unique text-token which will be reverted back when calling unhash.
  440. #
  441. # The $boundary argument specify what character should be used to surround
  442. # the token. By convension, "B" is used for block elements that needs not
  443. # to be wrapped into paragraph tags at the end, ":" is used for elements
  444. # that are word separators and "X" is used in the general case.
  445. #
  446. # Swap back any tag hash found in $text so we do not have to `unhash`
  447. # multiple times at the end.
  448. $text = $this->unhash($text);
  449. # Then hash the block.
  450. static $i = 0;
  451. $key = "$boundary\x1A" . ++$i . $boundary;
  452. $this->html_hashes[$key] = $text;
  453. return $key; # String that will replace the tag.
  454. }
  455. function hashBlock($text) {
  456. #
  457. # Shortcut function for hashPart with block-level boundaries.
  458. #
  459. return $this->hashPart($text, 'B');
  460. }
  461. var $block_gamut = array(
  462. #
  463. # These are all the transformations that form block-level
  464. # tags like paragraphs, headers, and list items.
  465. #
  466. "doHeaders" => 10,
  467. "doHorizontalRules" => 20,
  468. "doLists" => 40,
  469. "doCodeBlocks" => 50,
  470. "doBlockQuotes" => 60,
  471. );
  472. function runBlockGamut($text) {
  473. #
  474. # Run block gamut tranformations.
  475. #
  476. # We need to escape raw HTML in Markdown source before doing anything
  477. # else. This need to be done for each block, and not only at the
  478. # begining in the Markdown function since hashed blocks can be part of
  479. # list items and could have been indented. Indented blocks would have
  480. # been seen as a code block in a previous pass of hashHTMLBlocks.
  481. $text = $this->hashHTMLBlocks($text);
  482. return $this->runBasicBlockGamut($text);
  483. }
  484. function runBasicBlockGamut($text) {
  485. #
  486. # Run block gamut tranformations, without hashing HTML blocks. This is
  487. # useful when HTML blocks are known to be already hashed, like in the first
  488. # whole-document pass.
  489. #
  490. foreach ($this->block_gamut as $method => $priority) {
  491. $text = $this->$method($text);
  492. }
  493. # Finally form paragraph and restore hashed blocks.
  494. $text = $this->formParagraphs($text);
  495. return $text;
  496. }
  497. function doHorizontalRules($text) {
  498. # Do Horizontal Rules:
  499. return preg_replace(
  500. '{
  501. ^[ ]{0,3} # Leading space
  502. ([-*_]) # $1: First marker
  503. (?> # Repeated marker group
  504. [ ]{0,2} # Zero, one, or two spaces.
  505. \1 # Marker character
  506. ){2,} # Group repeated at least twice
  507. [ ]* # Tailing spaces
  508. $ # End of line.
  509. }mx',
  510. "\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n",
  511. $text);
  512. }
  513. var $span_gamut = array(
  514. #
  515. # These are all the transformations that occur *within* block-level
  516. # tags like paragraphs, headers, and list items.
  517. #
  518. # Process character escapes, code spans, and inline HTML
  519. # in one shot.
  520. "parseSpan" => -30,
  521. # Process anchor and image tags. Images must come first,
  522. # because ![foo][f] looks like an anchor.
  523. "doImages" => 10,
  524. "doAnchors" => 20,
  525. # Make links out of things like `<http://example.com/>`
  526. # Must come after doAnchors, because you can use < and >
  527. # delimiters in inline links like [this](<url>).
  528. "doAutoLinks" => 30,
  529. "encodeAmpsAndAngles" => 40,
  530. "doItalicsAndBold" => 50,
  531. "doHardBreaks" => 60,
  532. );
  533. function runSpanGamut($text) {
  534. #
  535. # Run span gamut tranformations.
  536. #
  537. foreach ($this->span_gamut as $method => $priority) {
  538. $text = $this->$method($text);
  539. }
  540. return $text;
  541. }
  542. function doHardBreaks($text) {
  543. # Do hard breaks:
  544. return preg_replace_callback('/ {2,}\n/',
  545. array(&$this, '_doHardBreaks_callback'), $text);
  546. }
  547. function _doHardBreaks_callback($matches) {
  548. return $this->hashPart("<br$this->empty_element_suffix\n");
  549. }
  550. function doAnchors($text) {
  551. #
  552. # Turn Markdown link shortcuts into XHTML <a> tags.
  553. #
  554. if ($this->in_anchor) return $text;
  555. $this->in_anchor = true;
  556. #
  557. # First, handle reference-style links: [link text] [id]
  558. #
  559. $text = preg_replace_callback('{
  560. ( # wrap whole match in $1
  561. \[
  562. ('.$this->nested_brackets_re.') # link text = $2
  563. \]
  564. [ ]? # one optional space
  565. (?:\n[ ]*)? # one optional newline followed by spaces
  566. \[
  567. (.*?) # id = $3
  568. \]
  569. )
  570. }xs',
  571. array(&$this, '_doAnchors_reference_callback'), $text);
  572. #
  573. # Next, inline-style links: [link text](url "optional title")
  574. #
  575. $text = preg_replace_callback('{
  576. ( # wrap whole match in $1
  577. \[
  578. ('.$this->nested_brackets_re.') # link text = $2
  579. \]
  580. \( # literal paren
  581. [ \n]*
  582. (?:
  583. <(.+?)> # href = $3
  584. |
  585. ('.$this->nested_url_parenthesis_re.') # href = $4
  586. )
  587. [ \n]*
  588. ( # $5
  589. ([\'"]) # quote char = $6
  590. (.*?) # Title = $7
  591. \6 # matching quote
  592. [ \n]* # ignore any spaces/tabs between closing quote and )
  593. )? # title is optional
  594. \)
  595. )
  596. }xs',
  597. array(&$this, '_doAnchors_inline_callback'), $text);
  598. #
  599. # Last, handle reference-style shortcuts: [link text]
  600. # These must come last in case you've also got [link text][1]
  601. # or [link text](/foo)
  602. #
  603. $text = preg_replace_callback('{
  604. ( # wrap whole match in $1
  605. \[
  606. ([^\[\]]+) # link text = $2; can\'t contain [ or ]
  607. \]
  608. )
  609. }xs',
  610. array(&$this, '_doAnchors_reference_callback'), $text);
  611. $this->in_anchor = false;
  612. return $text;
  613. }
  614. function _doAnchors_reference_callback($matches) {
  615. $whole_match = $matches[1];
  616. $link_text = $matches[2];
  617. $link_id =& $matches[3];
  618. if ($link_id == "") {
  619. # for shortcut links like [this][] or [this].
  620. $link_id = $link_text;
  621. }
  622. # lower-case and turn embedded newlines into spaces
  623. $link_id = strtolower($link_id);
  624. $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
  625. if (isset($this->urls[$link_id])) {
  626. $url = $this->urls[$link_id];
  627. $url = $this->encodeAttribute($url);
  628. $result = "<a href=\"$url\"";
  629. if ( isset( $this->titles[$link_id] ) ) {
  630. $title = $this->titles[$link_id];
  631. $title = $this->encodeAttribute($title);
  632. $result .= " title=\"$title\"";
  633. }
  634. $link_text = $this->runSpanGamut($link_text);
  635. $result .= ">$link_text</a>";
  636. $result = $this->hashPart($result);
  637. }
  638. else {
  639. $result = $whole_match;
  640. }
  641. return $result;
  642. }
  643. function _doAnchors_inline_callback($matches) {
  644. $whole_match = $matches[1];
  645. $link_text = $this->runSpanGamut($matches[2]);
  646. $url = $matches[3] == '' ? $matches[4] : $matches[3];
  647. $title =& $matches[7];
  648. $url = $this->encodeAttribute($url);
  649. $result = "<a href=\"$url\"";
  650. if (isset($title)) {
  651. $title = $this->encodeAttribute($title);
  652. $result .= " title=\"$title\"";
  653. }
  654. $link_text = $this->runSpanGamut($link_text);
  655. $result .= ">$link_text</a>";
  656. return $this->hashPart($result);
  657. }
  658. function doImages($text) {
  659. #
  660. # Turn Markdown image shortcuts into <img> tags.
  661. #
  662. #
  663. # First, handle reference-style labeled images: ![alt text][id]
  664. #
  665. $text = preg_replace_callback('{
  666. ( # wrap whole match in $1
  667. !\[
  668. ('.$this->nested_brackets_re.') # alt text = $2
  669. \]
  670. [ ]? # one optional space
  671. (?:\n[ ]*)? # one optional newline followed by spaces
  672. \[
  673. (.*?) # id = $3
  674. \]
  675. )
  676. }xs',
  677. array(&$this, '_doImages_reference_callback'), $text);
  678. #
  679. # Next, handle inline images: ![alt text](url "optional title")
  680. # Don't forget: encode * and _
  681. #
  682. $text = preg_replace_callback('{
  683. ( # wrap whole match in $1
  684. !\[
  685. ('.$this->nested_brackets_re.') # alt text = $2
  686. \]
  687. \s? # One optional whitespace character
  688. \( # literal paren
  689. [ \n]*
  690. (?:
  691. <(\S*)> # src url = $3
  692. |
  693. ('.$this->nested_url_parenthesis_re.') # src url = $4
  694. )
  695. [ \n]*
  696. ( # $5
  697. ([\'"]) # quote char = $6
  698. (.*?) # title = $7
  699. \6 # matching quote
  700. [ \n]*
  701. )? # title is optional
  702. \)
  703. )
  704. }xs',
  705. array(&$this, '_doImages_inline_callback'), $text);
  706. return $text;
  707. }
  708. function _doImages_reference_callback($matches) {
  709. $whole_match = $matches[1];
  710. $alt_text = $matches[2];
  711. $link_id = strtolower($matches[3]);
  712. if ($link_id == "") {
  713. $link_id = strtolower($alt_text); # for shortcut links like ![this][].
  714. }
  715. $alt_text = $this->encodeAttribute($alt_text);
  716. if (isset($this->urls[$link_id])) {
  717. $url = $this->encodeAttribute($this->urls[$link_id]);
  718. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  719. if (isset($this->titles[$link_id])) {
  720. $title = $this->titles[$link_id];
  721. $title = $this->encodeAttribute($title);
  722. $result .= " title=\"$title\"";
  723. }
  724. $result .= $this->empty_element_suffix;
  725. $result = $this->hashPart($result);
  726. }
  727. else {
  728. # If there's no such link ID, leave intact:
  729. $result = $whole_match;
  730. }
  731. return $result;
  732. }
  733. function _doImages_inline_callback($matches) {
  734. $whole_match = $matches[1];
  735. $alt_text = $matches[2];
  736. $url = $matches[3] == '' ? $matches[4] : $matches[3];
  737. $title =& $matches[7];
  738. $alt_text = $this->encodeAttribute($alt_text);
  739. $url = $this->encodeAttribute($url);
  740. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  741. if (isset($title)) {
  742. $title = $this->encodeAttribute($title);
  743. $result .= " title=\"$title\""; # $title already quoted
  744. }
  745. $result .= $this->empty_element_suffix;
  746. return $this->hashPart($result);
  747. }
  748. function doHeaders($text) {
  749. # Setext-style headers:
  750. # Header 1
  751. # ========
  752. #
  753. # Header 2
  754. # --------
  755. #
  756. $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx',
  757. array(&$this, '_doHeaders_callback_setext'), $text);
  758. # atx-style headers:
  759. # # Header 1
  760. # ## Header 2
  761. # ## Header 2 with closing hashes ##
  762. # ...
  763. # ###### Header 6
  764. #
  765. $text = preg_replace_callback('{
  766. ^(\#{1,6}) # $1 = string of #\'s
  767. [ ]*
  768. (.+?) # $2 = Header text
  769. [ ]*
  770. \#* # optional closing #\'s (not counted)
  771. \n+
  772. }xm',
  773. array(&$this, '_doHeaders_callback_atx'), $text);
  774. return $text;
  775. }
  776. function _doHeaders_callback_setext($matches) {
  777. # Terrible hack to check we haven't found an empty list item.
  778. if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1]))
  779. return $matches[0];
  780. $level = $matches[2]{0} == '=' ? 1 : 2;
  781. $block = "<h$level>".$this->runSpanGamut($matches[1])."</h$level>";
  782. return "\n" . $this->hashBlock($block) . "\n\n";
  783. }
  784. function _doHeaders_callback_atx($matches) {
  785. $level = strlen($matches[1]);
  786. $block = "<h$level>".$this->runSpanGamut($matches[2])."</h$level>";
  787. return "\n" . $this->hashBlock($block) . "\n\n";
  788. }
  789. function doLists($text) {
  790. #
  791. # Form HTML ordered (numbered) and unordered (bulleted) lists.
  792. #
  793. $less_than_tab = $this->tab_width - 1;
  794. # Re-usable patterns to match list item bullets and number markers:
  795. $marker_ul_re = '[*+-]';
  796. $marker_ol_re = '\d+[\.]';
  797. $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  798. $markers_relist = array(
  799. $marker_ul_re => $marker_ol_re,
  800. $marker_ol_re => $marker_ul_re,
  801. );
  802. foreach ($markers_relist as $marker_re => $other_marker_re) {
  803. # Re-usable pattern to match any entirel ul or ol list:
  804. $whole_list_re = '
  805. ( # $1 = whole list
  806. ( # $2
  807. ([ ]{0,'.$less_than_tab.'}) # $3 = number of spaces
  808. ('.$marker_re.') # $4 = first list item marker
  809. [ ]+
  810. )
  811. (?s:.+?)
  812. ( # $5
  813. \z
  814. |
  815. \n{2,}
  816. (?=\S)
  817. (?! # Negative lookahead for another list item marker
  818. [ ]*
  819. '.$marker_re.'[ ]+
  820. )
  821. |
  822. (?= # Lookahead for another kind of list
  823. \n
  824. \3 # Must have the same indentation
  825. '.$other_marker_re.'[ ]+
  826. )
  827. )
  828. )
  829. '; // mx
  830. # We use a different prefix before nested lists than top-level lists.
  831. # See extended comment in _ProcessListItems().
  832. if ($this->list_level) {
  833. $text = preg_replace_callback('{
  834. ^
  835. '.$whole_list_re.'
  836. }mx',
  837. array(&$this, '_doLists_callback'), $text);
  838. }
  839. else {
  840. $text = preg_replace_callback('{
  841. (?:(?<=\n)\n|\A\n?) # Must eat the newline
  842. '.$whole_list_re.'
  843. }mx',
  844. array(&$this, '_doLists_callback'), $text);
  845. }
  846. }
  847. return $text;
  848. }
  849. function _doLists_callback($matches) {
  850. # Re-usable patterns to match list item bullets and number markers:
  851. $marker_ul_re = '[*+-]';
  852. $marker_ol_re = '\d+[\.]';
  853. $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  854. $list = $matches[1];
  855. $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol";
  856. $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re );
  857. $list .= "\n";
  858. $result = $this->processListItems($list, $marker_any_re);
  859. $result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>");
  860. return "\n". $result ."\n\n";
  861. }
  862. var $list_level = 0;
  863. function processListItems($list_str, $marker_any_re) {
  864. #
  865. # Process the contents of a single ordered or unordered list, splitting it
  866. # into individual list items.
  867. #
  868. # The $this->list_level global keeps track of when we're inside a list.
  869. # Each time we enter a list, we increment it; when we leave a list,
  870. # we decrement. If it's zero, we're not in a list anymore.
  871. #
  872. # We do this because when we're not inside a list, we want to treat
  873. # something like this:
  874. #
  875. # I recommend upgrading to version
  876. # 8. Oops, now this line is treated
  877. # as a sub-list.
  878. #
  879. # As a single paragraph, despite the fact that the second line starts
  880. # with a digit-period-space sequence.
  881. #
  882. # Whereas when we're inside a list (or sub-list), that line will be
  883. # treated as the start of a sub-list. What a kludge, huh? This is
  884. # an aspect of Markdown's syntax that's hard to parse perfectly
  885. # without resorting to mind-reading. Perhaps the solution is to
  886. # change the syntax rules such that sub-lists must start with a
  887. # starting cardinal number; e.g. "1." or "a.".
  888. $this->list_level++;
  889. # trim trailing blank lines:
  890. $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
  891. $list_str = preg_replace_callback('{
  892. (\n)? # leading line = $1
  893. (^[ ]*) # leading whitespace = $2
  894. ('.$marker_any_re.' # list marker and space = $3
  895. (?:[ ]+|(?=\n)) # space only required if item is not empty
  896. )
  897. ((?s:.*?)) # list item text = $4
  898. (?:(\n+(?=\n))|\n) # tailing blank line = $5
  899. (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n))))
  900. }xm',
  901. array(&$this, '_processListItems_callback'), $list_str);
  902. $this->list_level--;
  903. return $list_str;
  904. }
  905. function _processListItems_callback($matches) {
  906. $item = $matches[4];
  907. $leading_line =& $matches[1];
  908. $leading_space =& $matches[2];
  909. $marker_space = $matches[3];
  910. $tailing_blank_line =& $matches[5];
  911. if ($leading_line || $tailing_blank_line ||
  912. preg_match('/\n{2,}/', $item))
  913. {
  914. # Replace marker with the appropriate whitespace indentation
  915. $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item;
  916. $item = $this->runBlockGamut($this->outdent($item)."\n");
  917. }
  918. else {
  919. # Recursion for sub-lists:
  920. $item = $this->doLists($this->outdent($item));
  921. $item = preg_replace('/\n+$/', '', $item);
  922. $item = $this->runSpanGamut($item);
  923. }
  924. return "<li>" . $item . "</li>\n";
  925. }
  926. function doCodeBlocks($text) {
  927. #
  928. # Process Markdown `<pre><code>` blocks.
  929. #
  930. $text = preg_replace_callback('{
  931. (?:\n\n|\A\n?)
  932. ( # $1 = the code block -- one or more lines, starting with a space/tab
  933. (?>
  934. [ ]{'.$this->tab_width.'} # Lines must start with a tab or a tab-width of spaces
  935. .*\n+
  936. )+
  937. )
  938. ((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
  939. }xm',
  940. array(&$this, '_doCodeBlocks_callback'), $text);
  941. return $text;
  942. }
  943. function _doCodeBlocks_callback($matches) {
  944. $codeblock = $matches[1];
  945. $codeblock = $this->outdent($codeblock);
  946. $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
  947. # trim leading newlines and trailing newlines
  948. $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
  949. $codeblock = "<pre><code>$codeblock\n</code></pre>";
  950. return "\n\n".$this->hashBlock($codeblock)."\n\n";
  951. }
  952. function makeCodeSpan($code) {
  953. #
  954. # Create a code span markup for $code. Called from handleSpanToken.
  955. #
  956. $code = htmlspecialchars(trim($code), ENT_NOQUOTES);
  957. return $this->hashPart("<code>$code</code>");
  958. }
  959. var $em_relist = array(
  960. '' => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?=\S|$)(?![\.,:;]\s)',
  961. '*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
  962. '_' => '(?<=\S|^)(?<!_)_(?!_)',
  963. );
  964. var $strong_relist = array(
  965. '' => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?=\S|$)(?![\.,:;]\s)',
  966. '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
  967. '__' => '(?<=\S|^)(?<!_)__(?!_)',
  968. );
  969. var $em_strong_relist = array(
  970. '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?=\S|$)(?![\.,:;]\s)',
  971. '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
  972. '___' => '(?<=\S|^)(?<!_)___(?!_)',
  973. );
  974. var $em_strong_prepared_relist;
  975. function prepareItalicsAndBold() {
  976. #
  977. # Prepare regular expressions for searching emphasis tokens in any
  978. # context.
  979. #
  980. foreach ($this->em_relist as $em => $em_re) {
  981. foreach ($this->strong_relist as $strong => $strong_re) {
  982. # Construct list of allowed token expressions.
  983. $token_relist = array();
  984. if (isset($this->em_strong_relist["$em$strong"])) {
  985. $token_relist[] = $this->em_strong_relist["$em$strong"];
  986. }
  987. $token_relist[] = $em_re;
  988. $token_relist[] = $strong_re;
  989. # Construct master expression from list.
  990. $token_re = '{('. implode('|', $token_relist) .')}';
  991. $this->em_strong_prepared_relist["$em$strong"] = $token_re;
  992. }
  993. }
  994. }
  995. function doItalicsAndBold($text) {
  996. $token_stack = array('');
  997. $text_stack = array('');
  998. $em = '';
  999. $strong = '';
  1000. $tree_char_em = false;
  1001. while (1) {
  1002. #
  1003. # Get prepared regular expression for seraching emphasis tokens
  1004. # in current context.
  1005. #
  1006. $token_re = $this->em_strong_prepared_relist["$em$strong"];
  1007. #
  1008. # Each loop iteration search for the next emphasis token.
  1009. # Each token is then passed to handleSpanToken.
  1010. #
  1011. $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
  1012. $text_stack[0] .= $parts[0];
  1013. $token =& $parts[1];
  1014. $text =& $parts[2];
  1015. if (empty($token)) {
  1016. # Reached end of text span: empty stack without emitting.
  1017. # any more emphasis.
  1018. while ($token_stack[0]) {
  1019. $text_stack[1] .= array_shift($token_stack);
  1020. $text_stack[0] .= array_shift($text_stack);
  1021. }
  1022. break;
  1023. }
  1024. $token_len = strlen($token);
  1025. if ($tree_char_em) {
  1026. # Reached closing marker while inside a three-char emphasis.
  1027. if ($token_len == 3) {
  1028. # Three-char closing marker, close em and strong.
  1029. array_shift($token_stack);
  1030. $span = array_shift($text_stack);
  1031. $span = $this->runSpanGamut($span);
  1032. $span = "<strong><em>$span</em></strong>";
  1033. $text_stack[0] .= $this->hashPart($span);
  1034. $em = '';
  1035. $strong = '';
  1036. } else {
  1037. # Other closing marker: close one em or strong and
  1038. # change current token state to match the other
  1039. $token_stack[0] = str_repeat($token{0}, 3-$token_len);
  1040. $tag = $token_len == 2 ? "strong" : "em";
  1041. $span = $text_stack[0];
  1042. $span = $this->runSpanGamut($span);
  1043. $span = "<$tag>$span</$tag>";
  1044. $text_stack[0] = $this->hashPart($span);
  1045. $$tag = ''; # $$tag stands for $em or $strong
  1046. }
  1047. $tree_char_em = false;
  1048. } else if ($token_len == 3) {
  1049. if ($em) {
  1050. # Reached closing marker for both em and strong.
  1051. # Closing strong marker:
  1052. for ($i = 0; $i < 2; ++$i) {
  1053. $shifted_token = array_shift($token_stack);
  1054. $tag = strlen($shifted_token) == 2 ? "strong" : "em";
  1055. $span = array_shift($text_stack);
  1056. $span = $this->runSpanGamut($span);
  1057. $span = "<$tag>$span</$tag>";
  1058. $text_stack[0] .= $this->hashPart($span);
  1059. $$tag = ''; # $$tag stands for $em or $strong
  1060. }
  1061. } else {
  1062. # Reached opening three-char emphasis marker. Push on token
  1063. # stack; will be handled by the special condition above.
  1064. $em = $token{0};
  1065. $strong = "$em$em";
  1066. array_unshift($token_stack, $token);
  1067. array_unshift($text_stack, '');
  1068. $tree_char_em = true;
  1069. }
  1070. } else if ($token_len == 2) {
  1071. if ($strong) {
  1072. # Unwind any dangling emphasis marker:
  1073. if (strlen($token_stack[0]) == 1) {
  1074. $text_stack[1] .= array_shift($token_stack);
  1075. $text_stack[0] .= array_shift($text_stack);
  1076. }
  1077. # Closing strong marker:
  1078. array_shift($token_stack);
  1079. $span = array_shift($text_stack);
  1080. $span = $this->runSpanGamut($span);
  1081. $span = "<strong>$span</strong>";
  1082. $text_stack[0] .= $this->hashPart($span);
  1083. $strong = '';
  1084. } else {
  1085. array_unshift($token_stack, $token);
  1086. array_unshift($text_stack, '');
  1087. $strong = $token;
  1088. }
  1089. } else {
  1090. # Here $token_len == 1
  1091. if ($em) {
  1092. if (strlen($token_stack[0]) == 1) {
  1093. # Closing emphasis marker:
  1094. array_shift($token_stack);
  1095. $span = array_shift($text_stack);
  1096. $span = $this->runSpanGamut($span);
  1097. $span = "<em>$span</em>";
  1098. $text_stack[0] .= $this->hashPart($span);
  1099. $em = '';
  1100. } else {
  1101. $text_stack[0] .= $token;
  1102. }
  1103. } else {
  1104. array_unshift($token_stack, $token);
  1105. array_unshift($text_stack, '');
  1106. $em = $token;
  1107. }
  1108. }
  1109. }
  1110. return $text_stack[0];
  1111. }
  1112. function doBlockQuotes($text) {
  1113. $text = preg_replace_callback('/
  1114. ( # Wrap whole match in $1
  1115. (?>
  1116. ^[ ]*>[ ]? # ">" at the start of a line
  1117. .+\n # rest of the first line
  1118. (.+\n)* # subsequent consecutive lines
  1119. \n* # blanks
  1120. )+
  1121. )
  1122. /xm',
  1123. array(&$this, '_doBlockQuotes_callback'), $text);
  1124. return $text;
  1125. }
  1126. function _doBlockQuotes_callback($matches) {
  1127. $bq = $matches[1];
  1128. # trim one level of quoting - trim whitespace-only lines
  1129. $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);
  1130. $bq = $this->runBlockGamut($bq); # recurse
  1131. $bq = preg_replace('/^/m', " ", $bq);
  1132. # These leading spaces cause problem with <pre> content,
  1133. # so we need to fix that:
  1134. $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx',
  1135. array(&$this, '_doBlockQuotes_callback2'), $bq);
  1136. return "\n". $this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n";
  1137. }
  1138. function _doBlockQuotes_callback2($matches) {
  1139. $pre = $matches[1];
  1140. $pre = preg_replace('/^ /m', '', $pre);
  1141. return $pre;
  1142. }
  1143. function formParagraphs($text) {
  1144. #
  1145. # Params:
  1146. # $text - string to process with html <p> tags
  1147. #
  1148. # Strip leading and trailing lines:
  1149. $text = preg_replace('/\A\n+|\n+\z/', '', $text);
  1150. $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
  1151. #
  1152. # Wrap <p> tags and unhashify HTML blocks
  1153. #
  1154. foreach ($grafs as $key => $value) {
  1155. if (!preg_match('/^B\x1A[0-9]+B$/', $value)) {
  1156. # Is a paragraph.
  1157. $value = $this->runSpanGamut($value);
  1158. $value = preg_replace('/^([ ]*)/', "<p>", $value);
  1159. $value .= "</p>";
  1160. $grafs[$key] = $this->unhash($value);
  1161. }
  1162. else {
  1163. # Is a block.
  1164. # Modify elements of @grafs in-place...
  1165. $graf = $value;
  1166. $block = $this->html_hashes[$graf];
  1167. $graf = $block;
  1168. // if (preg_match('{
  1169. // \A
  1170. // ( # $1 = <div> tag
  1171. // <div \s+
  1172. // [^>]*
  1173. // \b
  1174. // markdown\s*=\s* ([\'"]) # $2 = attr quote char
  1175. // 1
  1176. // \2
  1177. // [^>]*
  1178. // >
  1179. // )
  1180. // ( # $3 = contents
  1181. // .*
  1182. // )
  1183. // (</div>) # $4 = closing tag
  1184. // \z
  1185. // }xs', $block, $matches))
  1186. // {
  1187. // list(, $div_open, , $div_content, $div_close) = $matches;
  1188. //
  1189. // # We can't call Markdown(), because that resets the hash;
  1190. // # that initialization code should be pulled into its own sub, though.
  1191. // $div_content = $this->hashHTMLBlocks($div_content);
  1192. //
  1193. // # Run document gamut methods on the content.
  1194. // foreach ($this->document_gamut as $method => $priority) {
  1195. // $div_content = $this->$method($div_content);
  1196. // }
  1197. //
  1198. // $div_open = preg_replace(
  1199. // '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open);
  1200. //
  1201. // $graf = $div_open . "\n" . $div_content . "\n" . $div_close;
  1202. // }
  1203. $grafs[$key] = $graf;
  1204. }
  1205. }
  1206. return implode("\n\n", $grafs);
  1207. }
  1208. function encodeAttribute($text) {
  1209. #
  1210. # Encode text for a double-quoted HTML attribute. This function
  1211. # is *not* suitable for attributes enclosed in single quotes.
  1212. #
  1213. $text = $this->encodeAmpsAndAngles($text);
  1214. $text = str_replace('"', '&quot;', $text);
  1215. return $text;
  1216. }
  1217. function encodeAmpsAndAngles($text) {
  1218. #
  1219. # Smart processing for ampersands and angle brackets that need to
  1220. # be encoded. Valid character entities are left alone unless the
  1221. # no-entities mode is set.
  1222. #
  1223. if ($this->no_entities) {
  1224. $text = str_replace('&', '&amp;', $text);
  1225. } else {
  1226. # Ampersand-encoding based entirely on Nat Irons's Amputator
  1227. # MT plugin: <http://bumppo.net/projects/amputator/>
  1228. $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
  1229. '&amp;', $text);;
  1230. }
  1231. # Encode remaining <'s
  1232. $text = str_replace('<', '&lt;', $text);
  1233. return $text;
  1234. }
  1235. function doAutoLinks($text) {
  1236. $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i',
  1237. array(&$this, '_doAutoLinks_url_callback'), $text);
  1238. # Email addresses: <address@domain.foo>
  1239. $text = preg_replace_callback('{
  1240. <
  1241. (?:mailto:)?
  1242. (
  1243. (?:
  1244. [-!#$%&\'*+/=?^_`.{|}~\w\x80-\xFF]+
  1245. |
  1246. ".*?"
  1247. )
  1248. \@
  1249. (?:
  1250. [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+
  1251. |
  1252. \[[\d.a-fA-F:]+\] # IPv4 & IPv6
  1253. )
  1254. )
  1255. >
  1256. }xi',
  1257. array(&$this, '_doAutoLinks_email_callback'), $text);
  1258. return $text;
  1259. }
  1260. function _doAutoLinks_url_callback($matches) {
  1261. $url = $this->encodeAttribute($matches[1]);
  1262. $link = "<a href=\"$url\">$url</a>";
  1263. return $this->hashPart($link);
  1264. }
  1265. function _doAutoLinks_email_callback($matches) {
  1266. $address = $matches[1];
  1267. $link = $this->encodeEmailAddress($address);
  1268. return $this->hashPart($link);
  1269. }
  1270. function encodeEmailAddress($addr) {
  1271. #
  1272. # Input: an email address, e.g. "foo@example.com"
  1273. #
  1274. # Output: the email address as a mailto link, with each character
  1275. # of the address encoded as either a decimal or hex entity, in
  1276. # the hopes of foiling most address harvesting spam bots. E.g.:
  1277. #
  1278. # <p><a href="&#109;&#x61;&#105;&#x6c;&#116;&#x6f;&#58;&#x66;o&#111;
  1279. # &#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;&#101;&#46;&#x63;&#111;
  1280. # &#x6d;">&#x66;o&#111;&#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;
  1281. # &#101;&#46;&#x63;&#111;&#x6d;</a></p>
  1282. #
  1283. # Based by a filter by Matthew Wickline, posted to BBEdit-Talk.
  1284. # With some optimizations by Milian Wolff.
  1285. #
  1286. $addr = "mailto:" . $addr;
  1287. $chars = preg_split('/(?<!^)(?!$)/', $addr);
  1288. $seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed.
  1289. foreach ($chars as $key => $char) {
  1290. $ord = ord($char);
  1291. # Ignore non-ascii chars.
  1292. if ($ord < 128) {
  1293. $r = ($seed * (1 + $key)) % 100; # Pseudo-random function.
  1294. # roughly 10% raw, 45% hex, 45% dec
  1295. # '@' *must* be encoded. I insist.
  1296. if ($r > 90 && $char != '@') /* do nothing */;
  1297. else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';';
  1298. else $chars[$key] = '&#'.$ord.';';
  1299. }
  1300. }
  1301. $addr = implode('', $chars);
  1302. $text = implode('', array_slice($chars, 7)); # text without `mailto:`
  1303. $addr = "<a href=\"$addr\">$text</a>";
  1304. return $addr;
  1305. }
  1306. function parseSpan($str) {
  1307. #
  1308. # Take the string $str and parse it into tokens, hashing embeded HTML,
  1309. # escaped characters and handling code spans.
  1310. #
  1311. $output = '';
  1312. $span_re = '{
  1313. (
  1314. \\\\'.$this->escape_chars_re.'
  1315. |
  1316. (?<![`\\\\])
  1317. `+ # code span marker
  1318. '.( $this->no_markup ? '' : '
  1319. |
  1320. <!-- .*? --> # comment
  1321. |
  1322. <\?.*?\?> | <%.*?%> # processing instruction
  1323. |
  1324. <[/!$]?[-a-zA-Z0-9:_]+ # regular tags
  1325. (?>
  1326. \s
  1327. (?>[^"\'>]+|"[^"]*"|\'[^\']*\')*
  1328. )?
  1329. >
  1330. ').'
  1331. )
  1332. }xs';
  1333. while (1) {
  1334. #
  1335. # Each loop iteration seach for either the next tag, the next
  1336. # openning code span marker, or the next escaped character.
  1337. # Each token is then passed to handleSpanToken.
  1338. #
  1339. $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE);
  1340. # Create token from text preceding tag.
  1341. if ($parts[0] != "") {
  1342. $output .= $parts[0];
  1343. }
  1344. # Check if we reach the end.
  1345. if (isset($parts[1])) {
  1346. $output .= $this->handleSpanToken($parts[1], $parts[2]);
  1347. $str = $parts[2];
  1348. }
  1349. else {
  1350. break;
  1351. }
  1352. }
  1353. return $output;
  1354. }
  1355. function handleSpanToken($token, &$str) {
  1356. #
  1357. # Handle $token provided by parseSpan by determining its nature and
  1358. # returning the corresponding value that should replace it.
  1359. #
  1360. switch ($token{0}) {
  1361. case "\\":
  1362. return $this->hashPart("&#". ord($token{1}). ";");
  1363. case "`":
  1364. # Search for end marker in remaining text.
  1365. if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm',
  1366. $str, $matches))
  1367. {
  1368. $str = $matches[2];
  1369. $codespan = $this->makeCodeSpan($matches[1]);
  1370. return $this->hashPart($codespan);
  1371. }
  1372. return $token; // return as text since no ending marker found.
  1373. default:
  1374. return $this->hashPart($token);
  1375. }
  1376. }
  1377. function outdent($text) {
  1378. #
  1379. # Remove one level of line-leading tabs or spaces
  1380. #
  1381. return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text);
  1382. }
  1383. # String length function for detab. `_initDetab` will create a function to
  1384. # hanlde UTF-8 if the default function does not exist.
  1385. var $utf8_strlen = 'mb_strlen';
  1386. function detab($text) {
  1387. #
  1388. # Replace tabs with the appropriate amount of space.
  1389. #
  1390. # For each line we separate the line in blocks delemited by
  1391. # tab characters. Then we reconstruct every line by adding the
  1392. # appropriate number of space between each blocks.
  1393. $text = preg_replace_callback('/^.*\t.*$/m',
  1394. array(&$this, '_detab_callback'), $text);
  1395. return $text;
  1396. }
  1397. function _detab_callback($matches) {
  1398. $line = $matches[0];
  1399. $strlen = $this->utf8_strlen; # strlen function for UTF-8.
  1400. # Split in blocks.
  1401. $blocks = explode("\t", $line);
  1402. # Add each blocks to the line.
  1403. $line = $blocks[0];
  1404. unset($blocks[0]); # Do not add first block twice.
  1405. foreach ($blocks as $block) {
  1406. # Calculate amount of space, insert spaces, insert block.
  1407. $amount = $this->tab_width -
  1408. $strlen($line, 'UTF-8') % $this->tab_width;
  1409. $line .= str_repeat(" ", $amount) . $block;
  1410. }
  1411. return $line;
  1412. }
  1413. function _initDetab() {
  1414. #
  1415. # Check for the availability of the function in the `utf8_strlen` property
  1416. # (initially `mb_strlen`). If the function is not available, create a
  1417. # function that will loosely count the number of UTF-8 characters with a
  1418. # regular expression.
  1419. #
  1420. if (function_exists($this->utf8_strlen)) return;
  1421. $this->utf8_strlen = create_function('$text', 'return preg_match_all(
  1422. "/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/",
  1423. $text, $m);');
  1424. }
  1425. function unhash($text) {
  1426. #
  1427. # Swap back in all the tags hashed by _HashHTMLBlocks.
  1428. #
  1429. return preg_replace_callback('/(.)\x1A[0-9]+\1/',
  1430. array(&$this, '_unhash_callback'), $text);
  1431. }
  1432. function _unhash_callback($matches) {
  1433. return $this->html_hashes[$matches[0]];
  1434. }
  1435. }
  1436. #
  1437. # Markdown Extra Parser Class
  1438. #
  1439. class MarkdownExtra_Parser extends Markdown_Parser {
  1440. # Prefix for footnote ids.
  1441. var $fn_id_prefix = "";
  1442. # Optional title attribute for footnote links and backlinks.
  1443. var $fn_link_title = MARKDOWN_FN_LINK_TITLE;
  1444. var $fn_backlink_title = MARKDOWN_FN_BACKLINK_TITLE;
  1445. # Optional class attribute for footnote links and backlinks.
  1446. var $fn_link_class = MARKDOWN_FN_LINK_CLASS;
  1447. var $fn_backlink_class = MARKDOWN_FN_BACKLINK_CLASS;
  1448. # Predefined abbreviations.
  1449. var $predef_abbr = array();
  1450. function MarkdownExtra_Parser() {
  1451. #
  1452. # Constructor function. Initialize the parser object.
  1453. #
  1454. # Add extra escapable characters before parent constructor
  1455. # initialize the table.
  1456. $this->escape_chars .= ':|';
  1457. # Insert extra document, block, and span transformations.
  1458. # Parent constructor will do the sorting.
  1459. $this->document_gamut += array(
  1460. "doFencedCodeBlocks" => 5,
  1461. "stripFootnotes" => 15,
  1462. "stripAbbreviations" => 25,
  1463. "appendFootnotes" => 50,
  1464. );
  1465. $this->block_gamut += array(
  1466. "doFencedCodeBlocks" => 5,
  1467. "doTables" => 15,
  1468. "doDefLists" => 45,
  1469. );
  1470. $this->span_gamut += array(
  1471. "doFootnotes" => 5,
  1472. "doAbbreviations" => 70,
  1473. );
  1474. parent::Markdown_Parser();
  1475. }
  1476. # Extra variables used during extra transformations.
  1477. var $footnotes = array();
  1478. var $footnotes_ordered = array();
  1479. var $abbr_desciptions = array();
  1480. var $abbr_word_re = '';
  1481. # Give the current footnote number.
  1482. var $footnote_counter = 1;
  1483. function setup() {
  1484. #
  1485. # Setting up Extra-specific variables.
  1486. #
  1487. parent::setup();
  1488. $this->footnotes = array();
  1489. $this->footnotes_ordered = array();
  1490. $this->abbr_desciptions = array();
  1491. $this->abbr_word_re = '';
  1492. $this->footnote_counter = 1;
  1493. foreach ($this->predef_abbr as $abbr_word => $abbr_desc) {
  1494. if ($this->abbr_word_re)
  1495. $this->abbr_word_re .= '|';
  1496. $this->abbr_word_re .= preg_quote($abbr_word);
  1497. $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
  1498. }
  1499. }
  1500. function teardown() {
  1501. #
  1502. # Clearing Extra-specific variables.
  1503. #
  1504. $this->footnotes = array();
  1505. $this->footnotes_ordered = array();
  1506. $this->abbr_desciptions = array();
  1507. $this->abbr_word_re = '';
  1508. parent::teardown();
  1509. }
  1510. ### HTML Block Parser ###
  1511. # Tags that are always treated as block tags:
  1512. var $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend';
  1513. # Tags treated as block tags only if the opening tag is alone on it's line:
  1514. var $context_block_tags_re = 'script|noscript|math|ins|del';
  1515. # Tags where markdown="1" default to span mode:
  1516. var $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address';
  1517. # Tags which must not have their contents modified, no matter where
  1518. # they appear:
  1519. var $clean_tags_re = 'script|math';
  1520. # Tags that do not need to be closed.
  1521. var $auto_close_tags_re = 'hr|img';
  1522. function hashHTMLBlocks($text) {
  1523. #
  1524. # Hashify HTML Blocks and "clean tags".
  1525. #
  1526. # We only want to do this for block-level HTML tags, such as headers,
  1527. # lists, and tables. That's because we still want to wrap <p>s around
  1528. # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  1529. # phrase emphasis, and spans. The list of tags we're looking for is
  1530. # hard-coded.
  1531. #
  1532. # This works by calling _HashHTMLBlocks_InMarkdown, which then calls
  1533. # _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1"
  1534. # attribute is found whitin a tag, _HashHTMLBlocks_InHTML calls back
  1535. # _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag.
  1536. # These two functions are calling each other. It's recursive!
  1537. #
  1538. #
  1539. # Call the HTML-in-Markdown hasher.
  1540. #
  1541. list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text);
  1542. return $text;
  1543. }
  1544. function _hashHTMLBlocks_inMarkdown($text, $indent = 0,
  1545. $enclosing_tag_re = '', $span = false)
  1546. {
  1547. #
  1548. # Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags.
  1549. #
  1550. # * $indent is the number of space to be ignored when checking for code
  1551. # blocks. This is important because if we don't take the indent into
  1552. # account, something like this (which looks right) won't work as expected:
  1553. #
  1554. # <div>
  1555. # <div markdown="1">
  1556. # Hello World. <-- Is this a Markdown code block or text?
  1557. # </div> <-- Is this a Markdown code block or a real tag?
  1558. # <div>
  1559. #
  1560. # If you don't like this, just don't indent the tag on which
  1561. # you apply the markdown="1" attribute.
  1562. #
  1563. # * If $enclosing_tag_re is not empty, stops at the first unmatched closing
  1564. # tag with that name. Nested tags supported.
  1565. #
  1566. # * If $span is true, text inside must treated as span. So any double
  1567. # newline will be replaced by a single newline so that it does not create
  1568. # paragraphs.
  1569. #
  1570. # Returns an array of that form: ( processed text , remaining text )
  1571. #
  1572. if ($text === '') return array('', '');
  1573. # Regex to check for the presense of newlines around a block tag.
  1574. $newline_before_re = '/(?:^\n?|\n\n)*$/';
  1575. $newline_after_re =
  1576. '{
  1577. ^ # Start of text following the tag.
  1578. (?>[ ]*<!--.*?-->)? # Optional comment.
  1579. [ ]*\n # Must be followed by newline.
  1580. }xs';
  1581. # Regex to match any tag.
  1582. $block_tag_re =
  1583. '{
  1584. ( # $2: Capture hole tag.
  1585. </? # Any opening or closing tag.
  1586. (?> # Tag name.
  1587. '.$this->block_tags_re.' |
  1588. '.$this->context_block_tags_re.' |
  1589. '.$this->clean_tags_re.' |
  1590. (?!\s)'.$enclosing_tag_re.'
  1591. )
  1592. (?:
  1593. (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name.
  1594. (?>
  1595. ".*?" | # Double quotes (can contain `>`)
  1596. \'.*?\' | # Single quotes (can contain `>`)
  1597. .+? # Anything but quotes and `>`.
  1598. )*?
  1599. )?
  1600. > # End of tag.
  1601. |
  1602. <!-- .*? --> # HTML Comment
  1603. |
  1604. <\?.*?\?> | <%.*?%> # Processing instruction
  1605. |
  1606. <!\[CDATA\[.*?\]\]> # CData Block
  1607. |
  1608. # Code span marker
  1609. `+
  1610. '. ( !$span ? ' # If not in span.
  1611. |
  1612. # Indented code block
  1613. (?: ^[ ]*\n | ^ | \n[ ]*\n )
  1614. [ ]{'.($indent+4).'}[^\n]* \n
  1615. (?>
  1616. (?: [ ]{'.($indent+4).'}[^\n]* | [ ]* ) \n
  1617. )*
  1618. |
  1619. # Fenced code block marker
  1620. (?> ^ | \n )
  1621. [ ]{0,'.($indent).'}~~~+[ ]*\n
  1622. ' : '' ). ' # End (if not is span).
  1623. )
  1624. }xs';
  1625. $depth = 0; # Current depth inside the tag tree.
  1626. $parsed = ""; # Parsed text that will be returned.
  1627. #
  1628. # Loop through every tag until we find the closing tag of the parent
  1629. # or loop until reaching the end of text if no parent tag specified.
  1630. #
  1631. do {
  1632. #
  1633. # Split the text using the first $tag_match pattern found.
  1634. # Text before pattern will be first in the array, text after
  1635. # pattern will be at the end, and between will be any catches made
  1636. # by the pattern.
  1637. #
  1638. $parts = preg_split($block_tag_re, $text, 2,
  1639. PREG_SPLIT_DELIM_CAPTURE);
  1640. # If in Markdown span mode, add a empty-string span-level hash
  1641. # after each newline to prevent triggering any block element.
  1642. if ($span) {
  1643. $void = $this->hashPart("", ':');
  1644. $newline = "$void\n";
  1645. $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void;
  1646. }
  1647. $parsed .= $parts[0]; # Text before current tag.
  1648. # If end of $text has been reached. Stop loop.
  1649. if (count($parts) < 3) {
  1650. $text = "";
  1651. break;
  1652. }
  1653. $tag = $parts[1]; # Tag to handle.
  1654. $text = $parts[2]; # Remaining text after current tag.
  1655. $tag_re = preg_quote($tag); # For use in a regular expression.
  1656. #
  1657. # Check for: Code span marker
  1658. #
  1659. if ($tag{0} == "`") {
  1660. # Find corresponding end marker.
  1661. $tag_re = preg_quote($tag);
  1662. if (preg_match('{^(?>.+?|\n(?!\n))*?(?<!`)'.$tag_re.'(?!`)}',
  1663. $text, $matches))
  1664. {
  1665. # End marker found: pass text unchanged until marker.
  1666. $parsed .= $tag . $matches[0];
  1667. $text = substr($text, strlen($matches[0]));
  1668. }
  1669. else {
  1670. # Unmatched marker: just skip it.
  1671. $parsed .= $tag;
  1672. }
  1673. }
  1674. #
  1675. # Check for: Fenced code block marker.
  1676. #
  1677. else if (preg_match('{^\n?[ ]{0,'.($indent+3).'}~}', $tag)) {
  1678. # Fenced code block marker: find matching end marker.
  1679. $tag_re = preg_quote(trim($tag));
  1680. if (preg_match('{^(?>.*\n)+?[ ]{0,'.($indent).'}'.$tag_re.'[ ]*\n}', $text,
  1681. $matches))
  1682. {
  1683. # End marker found: pass text unchanged until marker.
  1684. $parsed .= $tag . $matches[0];
  1685. $text = substr($text, strlen($matches[0]));
  1686. }
  1687. else {
  1688. # No end marker: just skip it.
  1689. $parsed .= $tag;
  1690. }
  1691. }
  1692. #
  1693. # Check for: Indented code block.
  1694. #
  1695. else if ($tag{0} == "\n" || $tag{0} == " ") {
  1696. # Indented code block: pass it unchanged, will be handled
  1697. # later.
  1698. $parsed .= $tag;
  1699. }
  1700. #
  1701. # Check for: Opening Block level tag or
  1702. # Opening Context Block tag (like ins and del)
  1703. # used as a block tag (tag is alone on it's line).
  1704. #
  1705. else if (preg_match('{^<(?:'.$this->block_tags_re.')\b}', $tag) ||
  1706. ( preg_match('{^<(?:'.$this->context_block_tags_re.')\b}', $tag) &&
  1707. preg_match($newline_before_re, $parsed) &&
  1708. preg_match($newline_after_re, $text) )
  1709. )
  1710. {
  1711. # Need to parse tag and following text using the HTML parser.
  1712. list($block_text, $text) =
  1713. $this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true);
  1714. # Make sure it stays outside of any paragraph by adding newlines.
  1715. $parsed .= "\n\n$block_text\n\n";
  1716. }
  1717. #
  1718. # Check for: Clean tag (like script, math)
  1719. # HTML Comments, processing instructions.
  1720. #
  1721. else if (preg_match('{^<(?:'.$this->clean_tags_re.')\b}', $tag) ||
  1722. $tag{1} == '!' || $tag{1} == '?')
  1723. {
  1724. # Need to parse tag and following text using the HTML parser.
  1725. # (don't check for markdown attribute)
  1726. list($block_text, $text) =
  1727. $this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false);
  1728. $parsed .= $block_text;
  1729. }
  1730. #
  1731. # Check for: Tag with same name as enclosing tag.
  1732. #
  1733. else if ($enclosing_tag_re !== '' &&
  1734. # Same name as enclosing tag.
  1735. preg_match('{^</?(?:'.$enclosing_tag_re.')\b}', $tag))
  1736. {
  1737. #
  1738. # Increase/decrease nested tag count.
  1739. #
  1740. if ($tag{1} == '/') $depth--;
  1741. else if ($tag{strlen($tag)-2} != '/') $depth++;
  1742. if ($depth < 0) {
  1743. #
  1744. # Going out of parent element. Clean up and break so we
  1745. # return to the calling function.
  1746. #
  1747. $text = $tag . $text;
  1748. break;
  1749. }
  1750. $parsed .= $tag;
  1751. }
  1752. else {
  1753. $parsed .= $tag;
  1754. }
  1755. } while ($depth >= 0);
  1756. return array($parsed, $text);
  1757. }
  1758. function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) {
  1759. #
  1760. # Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags.
  1761. #
  1762. # * Calls $hash_method to convert any blocks.
  1763. # * Stops when the first opening tag closes.
  1764. # * $md_attr indicate if the use of the `markdown="1"` attribute is allowed.
  1765. # (it is not inside clean tags)
  1766. #
  1767. # Returns an array of that form: ( processed text , remaining text )
  1768. #
  1769. if ($text === '') return array('', '');
  1770. # Regex to match `markdown` attribute inside of a tag.
  1771. $markdown_attr_re = '
  1772. {
  1773. \s* # Eat whitespace before the `markdown` attribute
  1774. markdown
  1775. \s*=\s*
  1776. (?>
  1777. (["\']) # $1: quote delimiter
  1778. (.*?) # $2: attribute value
  1779. \1 # matching delimiter
  1780. |
  1781. ([^\s>]*) # $3: unquoted attribute value
  1782. )
  1783. () # $4: make $3 always defined (avoid warnings)
  1784. }xs';
  1785. # Regex to match any tag.
  1786. $tag_re = '{
  1787. ( # $2: Capture hole tag.
  1788. </? # Any opening or closing tag.
  1789. [\w:$]+ # Tag name.
  1790. (?:
  1791. (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name.
  1792. (?>
  1793. ".*?" | # Double quotes (can contain `>`)
  1794. \'.*?\' | # Single quotes (can contain `>`)
  1795. .+? # Anything but quotes and `>`.
  1796. )*?
  1797. )?
  1798. > # End of tag.
  1799. |
  1800. <!-- .*? --> # HTML Comment
  1801. |
  1802. <\?.*?\?> | <%.*?%> # Processing instruction
  1803. |
  1804. <!\[CDATA\[.*?\]\]> # CData Block
  1805. )
  1806. }xs';
  1807. $original_text = $text; # Save original text in case of faliure.
  1808. $depth = 0; # Current depth inside the tag tree.
  1809. $block_text = ""; # Temporary text holder for current text.
  1810. $parsed = ""; # Parsed text that will be returned.
  1811. #
  1812. # Get the name of the starting tag.
  1813. # (This pattern makes $base_tag_name_re safe without quoting.)
  1814. #
  1815. if (preg_match('/^<([\w:$]*)\b/', $text, $matches))
  1816. $base_tag_name_re = $matches[1];
  1817. #
  1818. # Loop through every tag until we find the corresponding closing tag.
  1819. #
  1820. do {
  1821. #
  1822. # Split the text using the first $tag_match pattern found.
  1823. # Text before pattern will be first in the array, text after
  1824. # pattern will be at the end, and between will be any catches made
  1825. # by the pattern.
  1826. #
  1827. $parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
  1828. if (count($parts) < 3) {
  1829. #
  1830. # End of $text reached with unbalenced tag(s).
  1831. # In that case, we return original text unchanged and pass the
  1832. # first character as filtered to prevent an infinite loop in the
  1833. # parent function.
  1834. #
  1835. return array($original_text{0}, substr($original_text, 1));
  1836. }
  1837. $block_text .= $parts[0]; # Text before current tag.
  1838. $tag = $parts[1]; # Tag to handle.
  1839. $text = $parts[2]; # Remaining text after current tag.
  1840. #
  1841. # Check for: Auto-close tag (like <hr/>)
  1842. # Comments and Processing Instructions.
  1843. #
  1844. if (preg_match('{^</?(?:'.$this->auto_close_tags_re.')\b}', $tag) ||
  1845. $tag{1} == '!' || $tag{1} == '?')
  1846. {
  1847. # Just add the tag to the block as if it was text.
  1848. $block_text .= $tag;
  1849. }
  1850. else {
  1851. #
  1852. # Increase/decrease nested tag count. Only do so if
  1853. # the tag's name match base tag's.
  1854. #
  1855. if (preg_match('{^</?'.$base_tag_name_re.'\b}', $tag)) {
  1856. if ($tag{1} == '/') $depth--;
  1857. else if ($tag{strlen($tag)-2} != '/') $depth++;
  1858. }
  1859. #
  1860. # Check for `markdown="1"` attribute and handle it.
  1861. #
  1862. if ($md_attr &&
  1863. preg_match($markdown_attr_re, $tag, $attr_m) &&
  1864. preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3]))
  1865. {
  1866. # Remove `markdown` attribute from opening tag.
  1867. $tag = preg_replace($markdown_attr_re, '', $tag);
  1868. # Check if text inside this tag must be parsed in span mode.
  1869. $this->mode = $attr_m[2] . $attr_m[3];
  1870. $span_mode = $this->mode == 'span' || $this->mode != 'block' &&
  1871. preg_match('{^<(?:'.$this->contain_span_tags_re.')\b}', $tag);
  1872. # Calculate indent before tag.
  1873. if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) {
  1874. $strlen = $this->utf8_strlen;
  1875. $indent = $strlen($matches[1], 'UTF-8');
  1876. } else {
  1877. $indent = 0;
  1878. }
  1879. # End preceding block with this tag.
  1880. $block_text .= $tag;
  1881. $parsed .= $this->$hash_method($block_text);
  1882. # Get enclosing tag name for the ParseMarkdown function.
  1883. # (This pattern makes $tag_name_re safe without quoting.)
  1884. preg_match('/^<([\w:$]*)\b/', $tag, $matches);
  1885. $tag_name_re = $matches[1];
  1886. # Parse the content using the HTML-in-Markdown parser.
  1887. list ($block_text, $text)
  1888. = $this->_hashHTMLBlocks_inMarkdown($text, $indent,
  1889. $tag_name_re, $span_mode);
  1890. # Outdent markdown text.
  1891. if ($indent > 0) {
  1892. $block_text = preg_replace("/^[ ]{1,$indent}/m", "",
  1893. $block_text);
  1894. }
  1895. # Append tag content to parsed text.
  1896. if (!$span_mode) $parsed .= "\n\n$block_text\n\n";
  1897. else $parsed .= "$block_text";
  1898. # Start over a new block.
  1899. $block_text = "";
  1900. }
  1901. else $block_text .= $tag;
  1902. }
  1903. } while ($depth > 0);
  1904. #
  1905. # Hash last block text that wasn't processed inside the loop.
  1906. #
  1907. $parsed .= $this->$hash_method($block_text);
  1908. return array($parsed, $text);
  1909. }
  1910. function hashClean($text) {
  1911. #
  1912. # Called whenever a tag must be hashed when a function insert a "clean" tag
  1913. # in $text, it pass through this function and is automaticaly escaped,
  1914. # blocking invalid nested overlap.
  1915. #
  1916. return $this->hashPart($text, 'C');
  1917. }
  1918. function doHeaders($text) {
  1919. #
  1920. # Redefined to add id attribute support.
  1921. #
  1922. # Setext-style headers:
  1923. # Header 1 {#header1}
  1924. # ========
  1925. #
  1926. # Header 2 {#header2}
  1927. # --------
  1928. #
  1929. $text = preg_replace_callback(
  1930. '{
  1931. (^.+?) # $1: Header text
  1932. (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? # $2: Id attribute
  1933. [ ]*\n(=+|-+)[ ]*\n+ # $3: Header footer
  1934. }mx',
  1935. array(&$this, '_doHeaders_callback_setext'), $text);
  1936. # atx-style headers:
  1937. # # Header 1 {#header1}
  1938. # ## Header 2 {#header2}
  1939. # ## Header 2 with closing hashes ## {#header3}
  1940. # ...
  1941. # ###### Header 6 {#header2}
  1942. #
  1943. $text = preg_replace_callback('{
  1944. ^(\#{1,6}) # $1 = string of #\'s
  1945. [ ]*
  1946. (.+?) # $2 = Header text
  1947. [ ]*
  1948. \#* # optional closing #\'s (not counted)
  1949. (?:[ ]+\{\#([-_:a-zA-Z0-9]+)\})? # id attribute
  1950. [ ]*
  1951. \n+
  1952. }xm',
  1953. array(&$this, '_doHeaders_callback_atx'), $text);
  1954. return $text;
  1955. }
  1956. private $_headerTags = array();
  1957. function _generateHeaderID($title) {
  1958. $base = trim(preg_replace('/[^a-z0-9]+/i', '-', strtolower(trim($title))), '-');
  1959. $index = 1;
  1960. $id = $base;
  1961. while(array_key_exists($id, $this->_headerTags)) {
  1962. $id = $base . '-' . $index;
  1963. $index++;
  1964. }
  1965. $this->_headerTags[$id] = $title;
  1966. return $id;
  1967. }
  1968. function _doHeaders_attr($attr, $title) {
  1969. if (empty($attr)) {
  1970. $id = $this->_generateHeaderID($title);
  1971. return " id=\"$id\"";
  1972. } else {
  1973. $this->_headerTags[$attr] = $title;
  1974. return " id=\"$attr\"";
  1975. }
  1976. }
  1977. function _doHeaders_callback_setext($matches) {
  1978. if ($matches[3] == '-' && preg_match('{^- }', $matches[1]))
  1979. return $matches[0];
  1980. $level = $matches[3]{0} == '=' ? 1 : 2;
  1981. $attr = $this->_doHeaders_attr($id =& $matches[2], $matches[1]);
  1982. $block = "<h$level$attr>".$this->runSpanGamut($matches[1])."</h$level>";
  1983. return "\n" . $this->hashBlock($block) . "\n\n";
  1984. }
  1985. function _doHeaders_callback_atx($matches) {
  1986. $level = strlen($matches[1]);
  1987. $attr = $this->_doHeaders_attr($id =& $matches[3], $matches[2]);
  1988. $block = "<h$level$attr>".$this->runSpanGamut($matches[2])."</h$level>";
  1989. return "\n" . $this->hashBlock($block) . "\n\n";
  1990. }
  1991. function doTables($text) {
  1992. #
  1993. # Form HTML tables.
  1994. #
  1995. $less_than_tab = $this->tab_width - 1;
  1996. #
  1997. # Find tables with leading pipe.
  1998. #
  1999. # | Header 1 | Header 2
  2000. # | -------- | --------
  2001. # | Cell 1 | Cell 2
  2002. # | Cell 3 | Cell 4
  2003. #
  2004. $text = preg_replace_callback('
  2005. {
  2006. ^ # Start of a line
  2007. [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
  2008. [|] # Optional leading pipe (present)
  2009. (.+) \n # $1: Header row (at least one pipe)
  2010. [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
  2011. [|] ([ ]*[-:]+[-| :]*) \n # $2: Header underline
  2012. ( # $3: Cells
  2013. (?>
  2014. [ ]* # Allowed whitespace.
  2015. [|] .* \n # Row content.
  2016. )*
  2017. )
  2018. (?=\n|\Z) # Stop at final double newline.
  2019. }xm',
  2020. array(&$this, '_doTable_leadingPipe_callback'), $text);
  2021. #
  2022. # Find tables without leading pipe.
  2023. #
  2024. # Header 1 | Header 2
  2025. # -------- | --------
  2026. # Cell 1 | Cell 2
  2027. # Cell 3 | Cell 4
  2028. #
  2029. $text = preg_replace_callback('
  2030. {
  2031. ^ # Start of a line
  2032. [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
  2033. (\S.*[|].*) \n # $1: Header row (at least one pipe)
  2034. [ ]{0,'.$less_than_tab.'} # Allowed whitespace.
  2035. ([-:]+[ ]*[|][-| :]*) \n # $2: Header underline
  2036. ( # $3: Cells
  2037. (?>
  2038. .* [|] .* \n # Row content
  2039. )*
  2040. )
  2041. (?=\n|\Z) # Stop at final double newline.
  2042. }xm',
  2043. array(&$this, '_DoTable_callback'), $text);
  2044. return $text;
  2045. }
  2046. function _doTable_leadingPipe_callback($matches) {
  2047. $head = $matches[1];
  2048. $underline = $matches[2];
  2049. $content = $matches[3];
  2050. # Remove leading pipe for each row.
  2051. $content = preg_replace('/^ *[|]/m', '', $content);
  2052. return $this->_doTable_callback(array($matches[0], $head, $underline, $content));
  2053. }
  2054. function _doTable_callback($matches) {
  2055. $head = $matches[1];
  2056. $underline = $matches[2];
  2057. $content = $matches[3];
  2058. # Remove any tailing pipes for each line.
  2059. $head = preg_replace('/[|] *$/m', '', $head);
  2060. $underline = preg_replace('/[|] *$/m', '', $underline);
  2061. $content = preg_replace('/[|] *$/m', '', $content);
  2062. # Reading alignement from header underline.
  2063. $separators = preg_split('/ *[|] */', $underline);
  2064. foreach ($separators as $n => $s) {
  2065. if (preg_match('/^ *-+: *$/', $s)) $attr[$n] = ' align="right"';
  2066. else if (preg_match('/^ *:-+: *$/', $s))$attr[$n] = ' align="center"';
  2067. else if (preg_match('/^ *:-+ *$/', $s)) $attr[$n] = ' align="left"';
  2068. else $attr[$n] = '';
  2069. }
  2070. # Parsing span elements, including code spans, character escapes,
  2071. # and inline HTML tags, so that pipes inside those gets ignored.
  2072. $head = $this->parseSpan($head);
  2073. $headers = preg_split('/ *[|] */', $head);
  2074. $col_count = count($headers);
  2075. # Write column headers.
  2076. $text = "<table>\n";
  2077. $text .= "<thead>\n";
  2078. $text .= "<tr>\n";
  2079. foreach ($headers as $n => $header)
  2080. $text .= " <th$attr[$n]>".$this->runSpanGamut(trim($header))."</th>\n";
  2081. $text .= "</tr>\n";
  2082. $text .= "</thead>\n";
  2083. # Split content by row.
  2084. $rows = explode("\n", trim($content, "\n"));
  2085. $text .= "<tbody>\n";
  2086. foreach ($rows as $row) {
  2087. # Parsing span elements, including code spans, character escapes,
  2088. # and inline HTML tags, so that pipes inside those gets ignored.
  2089. $row = $this->parseSpan($row);
  2090. # Split row by cell.
  2091. $row_cells = preg_split('/ *[|] */', $row, $col_count);
  2092. $row_cells = array_pad($row_cells, $col_count, '');
  2093. $text .= "<tr>\n";
  2094. foreach ($row_cells as $n => $cell)
  2095. $text .= " <td$attr[$n]>".$this->runSpanGamut(trim($cell))."</td>\n";
  2096. $text .= "</tr>\n";
  2097. }
  2098. $text .= "</tbody>\n";
  2099. $text .= "</table>";
  2100. return $this->hashBlock($text) . "\n";
  2101. }
  2102. function doDefLists($text) {
  2103. #
  2104. # Form HTML definition lists.
  2105. #
  2106. $less_than_tab = $this->tab_width - 1;
  2107. # Re-usable pattern to match any entire dl list:
  2108. $whole_list_re = '(?>
  2109. ( # $1 = whole list
  2110. ( # $2
  2111. [ ]{0,'.$less_than_tab.'}
  2112. ((?>.*\S.*\n)+) # $3 = defined term
  2113. \n?
  2114. [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
  2115. )
  2116. (?s:.+?)
  2117. ( # $4
  2118. \z
  2119. |
  2120. \n{2,}
  2121. (?=\S)
  2122. (?! # Negative lookahead for another term
  2123. [ ]{0,'.$less_than_tab.'}
  2124. (?: \S.*\n )+? # defined term
  2125. \n?
  2126. [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
  2127. )
  2128. (?! # Negative lookahead for another definition
  2129. [ ]{0,'.$less_than_tab.'}:[ ]+ # colon starting definition
  2130. )
  2131. )
  2132. )
  2133. )'; // mx
  2134. $text = preg_replace_callback('{
  2135. (?>\A\n?|(?<=\n\n))
  2136. '.$whole_list_re.'
  2137. }mx',
  2138. array(&$this, '_doDefLists_callback'), $text);
  2139. return $text;
  2140. }
  2141. function _doDefLists_callback($matches) {
  2142. # Re-usable patterns to match list item bullets and number markers:
  2143. $list = $matches[1];
  2144. # Turn double returns into triple returns, so that we can make a
  2145. # paragraph for the last item in a list, if necessary:
  2146. $result = trim($this->processDefListItems($list));
  2147. $result = "<dl>\n" . $result . "\n</dl>";
  2148. return $this->hashBlock($result) . "\n\n";
  2149. }
  2150. function processDefListItems($list_str) {
  2151. #
  2152. # Process the contents of a single definition list, splitting it
  2153. # into individual term and definition list items.
  2154. #
  2155. $less_than_tab = $this->tab_width - 1;
  2156. # trim trailing blank lines:
  2157. $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
  2158. # Process definition terms.
  2159. $list_str = preg_replace_callback('{
  2160. (?>\A\n?|\n\n+) # leading line
  2161. ( # definition terms = $1
  2162. [ ]{0,'.$less_than_tab.'} # leading whitespace
  2163. (?![:][ ]|[ ]) # negative lookahead for a definition
  2164. # mark (colon) or more whitespace.
  2165. (?> \S.* \n)+? # actual term (not whitespace).
  2166. )
  2167. (?=\n?[ ]{0,3}:[ ]) # lookahead for following line feed
  2168. # with a definition mark.
  2169. }xm',
  2170. array(&$this, '_processDefListItems_callback_dt'), $list_str);
  2171. # Process actual definitions.
  2172. $list_str = preg_replace_callback('{
  2173. \n(\n+)? # leading line = $1
  2174. ( # marker space = $2
  2175. [ ]{0,'.$less_than_tab.'} # whitespace before colon
  2176. [:][ ]+ # definition mark (colon)
  2177. )
  2178. ((?s:.+?)) # definition text = $3
  2179. (?= \n+ # stop at next definition mark,
  2180. (?: # next term or end of text
  2181. [ ]{0,'.$less_than_tab.'} [:][ ] |
  2182. <dt> | \z
  2183. )
  2184. )
  2185. }xm',
  2186. array(&$this, '_processDefListItems_callback_dd'), $list_str);
  2187. return $list_str;
  2188. }
  2189. function _processDefListItems_callback_dt($matches) {
  2190. $terms = explode("\n", trim($matches[1]));
  2191. $text = '';
  2192. foreach ($terms as $term) {
  2193. $term = $this->runSpanGamut(trim($term));
  2194. $text .= "\n<dt>" . $term . "</dt>";
  2195. }
  2196. return $text . "\n";
  2197. }
  2198. function _processDefListItems_callback_dd($matches) {
  2199. $leading_line = $matches[1];
  2200. $marker_space = $matches[2];
  2201. $def = $matches[3];
  2202. if ($leading_line || preg_match('/\n{2,}/', $def)) {
  2203. # Replace marker with the appropriate whitespace indentation
  2204. $def = str_repeat(' ', strlen($marker_space)) . $def;
  2205. $def = $this->runBlockGamut($this->outdent($def . "\n\n"));
  2206. $def = "\n". $def ."\n";
  2207. }
  2208. else {
  2209. $def = rtrim($def);
  2210. $def = $this->runSpanGamut($this->outdent($def));
  2211. }
  2212. return "\n<dd>" . $def . "</dd>\n";
  2213. }
  2214. function doFencedCodeBlocks($text) {
  2215. #
  2216. # Adding the fenced code block syntax to regular Markdown:
  2217. #
  2218. # ~~~
  2219. # Code block
  2220. # ~~~
  2221. #
  2222. $less_than_tab = $this->tab_width;
  2223. $text = preg_replace_callback('{
  2224. (?:\n|\A)
  2225. # 1: Opening marker
  2226. (
  2227. ~{3,} # Marker: three tilde or more.
  2228. )
  2229. [ ]* \n # Whitespace and newline following marker.
  2230. # 2: Content
  2231. (
  2232. (?>
  2233. (?!\1 [ ]* \n) # Not a closing marker.
  2234. .*\n+
  2235. )+
  2236. )
  2237. # Closing marker.
  2238. \1 [ ]* \n
  2239. }xm',
  2240. array(&$this, '_doFencedCodeBlocks_callback'), $text);
  2241. return $text;
  2242. }
  2243. function _doFencedCodeBlocks_callback($matches) {
  2244. $codeblock = $matches[2];
  2245. $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
  2246. $codeblock = preg_replace_callback('/^\n+/',
  2247. array(&$this, '_doFencedCodeBlocks_newlines'), $codeblock);
  2248. $codeblock = "<pre><code>$codeblock</code></pre>";
  2249. return "\n\n".$this->hashBlock($codeblock)."\n\n";
  2250. }
  2251. function _doFencedCodeBlocks_newlines($matches) {
  2252. return str_repeat("<br$this->empty_element_suffix",
  2253. strlen($matches[0]));
  2254. }
  2255. #
  2256. # Redefining emphasis markers so that emphasis by underscore does not
  2257. # work in the middle of a word.
  2258. #
  2259. var $em_relist = array(
  2260. '' => '(?:(?<!\*)\*(?!\*)|(?<![a-zA-Z0-9_])_(?!_))(?=\S|$)(?![\.,:;]\s)',
  2261. '*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
  2262. '_' => '(?<=\S|^)(?<!_)_(?![a-zA-Z0-9_])',
  2263. );
  2264. var $strong_relist = array(
  2265. '' => '(?:(?<!\*)\*\*(?!\*)|(?<![a-zA-Z0-9_])__(?!_))(?=\S|$)(?![\.,:;]\s)',
  2266. '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
  2267. '__' => '(?<=\S|^)(?<!_)__(?![a-zA-Z0-9_])',
  2268. );
  2269. var $em_strong_relist = array(
  2270. '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<![a-zA-Z0-9_])___(?!_))(?=\S|$)(?![\.,:;]\s)',
  2271. '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
  2272. '___' => '(?<=\S|^)(?<!_)___(?![a-zA-Z0-9_])',
  2273. );
  2274. function formParagraphs($text) {
  2275. #
  2276. # Params:
  2277. # $text - string to process with html <p> tags
  2278. #
  2279. # Strip leading and trailing lines:
  2280. $text = preg_replace('/\A\n+|\n+\z/', '', $text);
  2281. $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
  2282. #
  2283. # Wrap <p> tags and unhashify HTML blocks
  2284. #
  2285. foreach ($grafs as $key => $value) {
  2286. $value = trim($this->runSpanGamut($value));
  2287. # Check if this should be enclosed in a paragraph.
  2288. # Clean tag hashes & block tag hashes are left alone.
  2289. $is_p = !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value);
  2290. if ($is_p) {
  2291. $value = "<p>$value</p>";
  2292. }
  2293. $grafs[$key] = $value;
  2294. }
  2295. # Join grafs in one text, then unhash HTML tags.
  2296. $text = implode("\n\n", $grafs);
  2297. # Finish by removing any tag hashes still present in $text.
  2298. $text = $this->unhash($text);
  2299. return $text;
  2300. }
  2301. ### Footnotes
  2302. function stripFootnotes($text) {
  2303. #
  2304. # Strips link definitions from text, stores the URLs and titles in
  2305. # hash references.
  2306. #
  2307. $less_than_tab = $this->tab_width - 1;
  2308. # Link defs are in the form: [^id]: url "optional title"
  2309. $text = preg_replace_callback('{
  2310. ^[ ]{0,'.$less_than_tab.'}\[\^(.+?)\][ ]?: # note_id = $1
  2311. [ ]*
  2312. \n? # maybe *one* newline
  2313. ( # text = $2 (no blank lines allowed)
  2314. (?:
  2315. .+ # actual text
  2316. |
  2317. \n # newlines but
  2318. (?!\[\^.+?\]:\s)# negative lookahead for footnote marker.
  2319. (?!\n+[ ]{0,3}\S)# ensure line is not blank and followed
  2320. # by non-indented content
  2321. )*
  2322. )
  2323. }xm',
  2324. array(&$this, '_stripFootnotes_callback'),
  2325. $text);
  2326. return $text;
  2327. }
  2328. function _stripFootnotes_callback($matches) {
  2329. $note_id = $this->fn_id_prefix . $matches[1];
  2330. $this->footnotes[$note_id] = $this->outdent($matches[2]);
  2331. return ''; # String that will replace the block
  2332. }
  2333. function doFootnotes($text) {
  2334. #
  2335. # Replace footnote references in $text [^id] with a special text-token
  2336. # which will be replaced by the actual footnote marker in appendFootnotes.
  2337. #
  2338. if (!$this->in_anchor) {
  2339. $text = preg_replace('{\[\^(.+?)\]}', "F\x1Afn:\\1\x1A:", $text);
  2340. }
  2341. return $text;
  2342. }
  2343. function appendFootnotes($text) {
  2344. #
  2345. # Append footnote list to text.
  2346. #
  2347. $text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
  2348. array(&$this, '_appendFootnotes_callback'), $text);
  2349. if (!empty($this->footnotes_ordered)) {
  2350. $text .= "\n\n";
  2351. $text .= "<div class=\"footnotes\">\n";
  2352. $text .= "<hr". $this->empty_element_suffix ."\n";
  2353. $text .= "<ol>\n\n";
  2354. $attr = " rev=\"footnote\"";
  2355. if ($this->fn_backlink_class != "") {
  2356. $class = $this->fn_backlink_class;
  2357. $class = $this->encodeAttribute($class);
  2358. $attr .= " class=\"$class\"";
  2359. }
  2360. if ($this->fn_backlink_title != "") {
  2361. $title = $this->fn_backlink_title;
  2362. $title = $this->encodeAttribute($title);
  2363. $attr .= " title=\"$title\"";
  2364. }
  2365. $num = 0;
  2366. while (!empty($this->footnotes_ordered)) {
  2367. $footnote = reset($this->footnotes_ordered);
  2368. $note_id = key($this->footnotes_ordered);
  2369. unset($this->footnotes_ordered[$note_id]);
  2370. $footnote .= "\n"; # Need to append newline before parsing.
  2371. $footnote = $this->runBlockGamut("$footnote\n");
  2372. $footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
  2373. array(&$this, '_appendFootnotes_callback'), $footnote);
  2374. $attr = str_replace("%%", ++$num, $attr);
  2375. $note_id = $this->encodeAttribute($note_id);
  2376. # Add backlink to last paragraph; create new paragraph if needed.
  2377. $backlink = "<a href=\"#fnref:$note_id\"$attr>&#8617;</a>";
  2378. if (preg_match('{</p>$}', $footnote)) {
  2379. $footnote = substr($footnote, 0, -4) . "&#160;$backlink</p>";
  2380. } else {
  2381. $footnote .= "\n\n<p>$backlink</p>";
  2382. }
  2383. $text .= "<li id=\"fn:$note_id\">\n";
  2384. $text .= $footnote . "\n";
  2385. $text .= "</li>\n\n";
  2386. }
  2387. $text .= "</ol>\n";
  2388. $text .= "</div>";
  2389. }
  2390. return $text;
  2391. }
  2392. function _appendFootnotes_callback($matches) {
  2393. $node_id = $this->fn_id_prefix . $matches[1];
  2394. # Create footnote marker only if it has a corresponding footnote *and*
  2395. # the footnote hasn't been used by another marker.
  2396. if (isset($this->footnotes[$node_id])) {
  2397. # Transfert footnote content to the ordered list.
  2398. $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id];
  2399. unset($this->footnotes[$node_id]);
  2400. $num = $this->footnote_counter++;
  2401. $attr = " rel=\"footnote\"";
  2402. if ($this->fn_link_class != "") {
  2403. $class = $this->fn_link_class;
  2404. $class = $this->encodeAttribute($class);
  2405. $attr .= " class=\"$class\"";
  2406. }
  2407. if ($this->fn_link_title != "") {
  2408. $title = $this->fn_link_title;
  2409. $title = $this->encodeAttribute($title);
  2410. $attr .= " title=\"$title\"";
  2411. }
  2412. $attr = str_replace("%%", $num, $attr);
  2413. $node_id = $this->encodeAttribute($node_id);
  2414. return
  2415. "<sup id=\"fnref:$node_id\">".
  2416. "<a href=\"#fn:$node_id\"$attr>$num</a>".
  2417. "</sup>";
  2418. }
  2419. return "[^".$matches[1]."]";
  2420. }
  2421. ### Abbreviations ###
  2422. function stripAbbreviations($text) {
  2423. #
  2424. # Strips abbreviations from text, stores titles in hash references.
  2425. #
  2426. $less_than_tab = $this->tab_width - 1;
  2427. # Link defs are in the form: [id]*: url "optional title"
  2428. $text = preg_replace_callback('{
  2429. ^[ ]{0,'.$less_than_tab.'}\*\[(.+?)\][ ]?: # abbr_id = $1
  2430. (.*) # text = $2 (no blank lines allowed)
  2431. }xm',
  2432. array(&$this, '_stripAbbreviations_callback'),
  2433. $text);
  2434. return $text;
  2435. }
  2436. function _stripAbbreviations_callback($matches) {
  2437. $abbr_word = $matches[1];
  2438. $abbr_desc = $matches[2];
  2439. if ($this->abbr_word_re)
  2440. $this->abbr_word_re .= '|';
  2441. $this->abbr_word_re .= preg_quote($abbr_word);
  2442. $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
  2443. return ''; # String that will replace the block
  2444. }
  2445. function doAbbreviations($text) {
  2446. #
  2447. # Find defined abbreviations in text and wrap them in <abbr> elements.
  2448. #
  2449. if ($this->abbr_word_re) {
  2450. // cannot use the /x modifier because abbr_word_re may
  2451. // contain significant spaces:
  2452. $text = preg_replace_callback('{'.
  2453. '(?<![\w\x1A])'.
  2454. '(?:'.$this->abbr_word_re.')'.
  2455. '(?![\w\x1A])'.
  2456. '}',
  2457. array(&$this, '_doAbbreviations_callback'), $text);
  2458. }
  2459. return $text;
  2460. }
  2461. function _doAbbreviations_callback($matches) {
  2462. $abbr = $matches[0];
  2463. if (isset($this->abbr_desciptions[$abbr])) {
  2464. $desc = $this->abbr_desciptions[$abbr];
  2465. if (empty($desc)) {
  2466. return $this->hashPart("<abbr>$abbr</abbr>");
  2467. } else {
  2468. $desc = $this->encodeAttribute($desc);
  2469. return $this->hashPart("<abbr title=\"$desc\">$abbr</abbr>");
  2470. }
  2471. } else {
  2472. return $matches[0];
  2473. }
  2474. }
  2475. }
  2476. /*
  2477. PHP Markdown Extra
  2478. ==================
  2479. Description
  2480. -----------
  2481. This is a PHP port of the original Markdown formatter written in Perl
  2482. by John Gruber. This special "Extra" version of PHP Markdown features
  2483. further enhancements to the syntax for making additional constructs
  2484. such as tables and definition list.
  2485. Markdown is a text-to-HTML filter; it translates an easy-to-read /
  2486. easy-to-write structured text format into HTML. Markdown's text format
  2487. is most similar to that of plain text email, and supports features such
  2488. as headers, *emphasis*, code blocks, blockquotes, and links.
  2489. Markdown's syntax is designed not as a generic markup language, but
  2490. specifically to serve as a front-end to (X)HTML. You can use span-level
  2491. HTML tags anywhere in a Markdown document, and you can use block level
  2492. HTML tags (like <div> and <table> as well).
  2493. For more information about Markdown's syntax, see:
  2494. <http://daringfireball.net/projects/markdown/>
  2495. Bugs
  2496. ----
  2497. To file bug reports please send email to:
  2498. <michel.fortin@michelf.com>
  2499. Please include with your report: (1) the example input; (2) the output you
  2500. expected; (3) the output Markdown actually produced.
  2501. Version History
  2502. ---------------
  2503. See the readme file for detailed release notes for this version.
  2504. Copyright and License
  2505. ---------------------
  2506. PHP Markdown & Extra
  2507. Copyright (c) 2004-2009 Michel Fortin
  2508. <http://michelf.com/>
  2509. All rights reserved.
  2510. Based on Markdown
  2511. Copyright (c) 2003-2006 John Gruber
  2512. <http://daringfireball.net/>
  2513. All rights reserved.
  2514. Redistribution and use in source and binary forms, with or without
  2515. modification, are permitted provided that the following conditions are
  2516. met:
  2517. * Redistributions of source code must retain the above copyright notice,
  2518. this list of conditions and the following disclaimer.
  2519. * Redistributions in binary form must reproduce the above copyright
  2520. notice, this list of conditions and the following disclaimer in the
  2521. documentation and/or other materials provided with the distribution.
  2522. * Neither the name "Markdown" nor the names of its contributors may
  2523. be used to endorse or promote products derived from this software
  2524. without specific prior written permission.
  2525. This software is provided by the copyright holders and contributors "as
  2526. is" and any express or implied warranties, including, but not limited
  2527. to, the implied warranties of merchantability and fitness for a
  2528. particular purpose are disclaimed. In no event shall the copyright owner
  2529. or contributors be liable for any direct, indirect, incidental, special,
  2530. exemplary, or consequential damages (including, but not limited to,
  2531. procurement of substitute goods or services; loss of use, data, or
  2532. profits; or business interruption) however caused and on any theory of
  2533. liability, whether in contract, strict liability, or tort (including
  2534. negligence or otherwise) arising in any way out of the use of this
  2535. software, even if advised of the possibility of such damage.
  2536. */
  2537. ?>