PageRenderTime 71ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/inc/lib/markdown.php

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