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

/modules/userguide/vendor/markdown/markdown.php

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