/_inc/lib/markdown/extra.php

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