PageRenderTime 32ms CodeModel.GetById 10ms RepoModel.GetById 0ms app.codeStats 1ms

/bonfire/helpers/markdown_helper.php

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