PageRenderTime 68ms 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

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

  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_ma

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