PageRenderTime 44ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 1ms

/lib/markdown/Markdown.php

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