PageRenderTime 64ms CodeModel.GetById 21ms 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

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

  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. #

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