PageRenderTime 66ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/kirby/parsers/markdown.extra.php

https://github.com/AndreasDriesen/kirbycms
PHP | 2943 lines | 1881 code | 327 blank | 735 comment | 180 complexity | e57b884ea65735afd9c548454c0178b6 MD5 | raw file

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

  1. <?php
  2. // direct access protection
  3. if(!defined('KIRBY')) die('Direct access is not allowed');
  4. function md($text) {
  5. return markdown($text);
  6. }
  7. #
  8. # Markdown Extra - A text-to-HTML conversion tool for web writers
  9. #
  10. # PHP Markdown & Extra
  11. # Copyright (c) 2004-2012 Michel Fortin
  12. # <http://michelf.com/projects/php-markdown/>
  13. #
  14. # Original Markdown
  15. # Copyright (c) 2004-2006 John Gruber
  16. # <http://daringfireball.net/projects/markdown/>
  17. #
  18. define( 'MARKDOWN_VERSION', "1.0.1o" ); # Sun 8 Jan 2012
  19. define( 'MARKDOWNEXTRA_VERSION', "1.2.5" ); # Sun 8 Jan 2012
  20. #
  21. # Global default settings:
  22. #
  23. # Change to ">" for HTML output
  24. @define( 'MARKDOWN_EMPTY_ELEMENT_SUFFIX', " />");
  25. # Define the width of a tab for code blocks.
  26. @define( 'MARKDOWN_TAB_WIDTH', 4 );
  27. # Optional title attribute for footnote links and backlinks.
  28. @define( 'MARKDOWN_FN_LINK_TITLE', "" );
  29. @define( 'MARKDOWN_FN_BACKLINK_TITLE', "" );
  30. # Optional class attribute for footnote links and backlinks.
  31. @define( 'MARKDOWN_FN_LINK_CLASS', "" );
  32. @define( 'MARKDOWN_FN_BACKLINK_CLASS', "" );
  33. #
  34. # WordPress settings:
  35. #
  36. # Change to false to remove Markdown from posts and/or comments.
  37. @define( 'MARKDOWN_WP_POSTS', true );
  38. @define( 'MARKDOWN_WP_COMMENTS', true );
  39. ### Standard Function Interface ###
  40. @define( 'MARKDOWN_PARSER_CLASS', 'MarkdownExtra_Parser' );
  41. function Markdown($text) {
  42. #
  43. # Initialize the parser and return the result of its transform method.
  44. #
  45. # Setup static parser variable.
  46. static $parser;
  47. if (!isset($parser)) {
  48. $parser_class = MARKDOWN_PARSER_CLASS;
  49. $parser = new $parser_class;
  50. }
  51. # Transform text using parser.
  52. return $parser->transform($text);
  53. }
  54. ### WordPress Plugin Interface ###
  55. /*
  56. Plugin Name: Markdown Extra
  57. Plugin URI: http://michelf.com/projects/php-markdown/
  58. Description: <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by <a href="http://daringfireball.net/">John Gruber</a>. <a href="http://michelf.com/projects/php-markdown/">More...</a>
  59. Version: 1.2.5
  60. Author: Michel Fortin
  61. Author URI: http://michelf.com/
  62. */
  63. if (isset($wp_version)) {
  64. # More details about how it works here:
  65. # <http://michelf.com/weblog/2005/wordpress-text-flow-vs-markdown/>
  66. # Post content and excerpts
  67. # - Remove WordPress paragraph generator.
  68. # - Run Markdown on excerpt, then remove all tags.
  69. # - Add paragraph tag around the excerpt, but remove it for the excerpt rss.
  70. if (MARKDOWN_WP_POSTS) {
  71. remove_filter('the_content', 'wpautop');
  72. remove_filter('the_content_rss', 'wpautop');
  73. remove_filter('the_excerpt', 'wpautop');
  74. add_filter('the_content', 'mdwp_MarkdownPost', 6);
  75. add_filter('the_content_rss', 'mdwp_MarkdownPost', 6);
  76. add_filter('get_the_excerpt', 'mdwp_MarkdownPost', 6);
  77. add_filter('get_the_excerpt', 'trim', 7);
  78. add_filter('the_excerpt', 'mdwp_add_p');
  79. add_filter('the_excerpt_rss', 'mdwp_strip_p');
  80. remove_filter('content_save_pre', 'balanceTags', 50);
  81. remove_filter('excerpt_save_pre', 'balanceTags', 50);
  82. add_filter('the_content', 'balanceTags', 50);
  83. add_filter('get_the_excerpt', 'balanceTags', 9);
  84. }
  85. # Add a footnote id prefix to posts when inside a loop.
  86. function mdwp_MarkdownPost($text) {
  87. static $parser;
  88. if (!$parser) {
  89. $parser_class = MARKDOWN_PARSER_CLASS;
  90. $parser = new $parser_class;
  91. }
  92. if (is_single() || is_page() || is_feed()) {
  93. $parser->fn_id_prefix = "";
  94. } else {
  95. $parser->fn_id_prefix = get_the_ID() . ".";
  96. }
  97. return $parser->transform($text);
  98. }
  99. # Comments
  100. # - Remove WordPress paragraph generator.
  101. # - Remove WordPress auto-link generator.
  102. # - Scramble important tags before passing them to the kses filter.
  103. # - Run Markdown on excerpt then remove paragraph tags.
  104. if (MARKDOWN_WP_COMMENTS) {
  105. remove_filter('comment_text', 'wpautop', 30);
  106. remove_filter('comment_text', 'make_clickable');
  107. add_filter('pre_comment_content', 'Markdown', 6);
  108. add_filter('pre_comment_content', 'mdwp_hide_tags', 8);
  109. add_filter('pre_comment_content', 'mdwp_show_tags', 12);
  110. add_filter('get_comment_text', 'Markdown', 6);
  111. add_filter('get_comment_excerpt', 'Markdown', 6);
  112. add_filter('get_comment_excerpt', 'mdwp_strip_p', 7);
  113. global $mdwp_hidden_tags, $mdwp_placeholders;
  114. $mdwp_hidden_tags = explode(' ',
  115. '<p> </p> <pre> </pre> <ol> </ol> <ul> </ul> <li> </li>');
  116. $mdwp_placeholders = explode(' ', str_rot13(
  117. 'pEj07ZbbBZ U1kqgh4w4p pre2zmeN6K QTi31t9pre ol0MP1jzJR '.
  118. 'ML5IjmbRol ulANi1NsGY J7zRLJqPul liA8ctl16T K9nhooUHli'));
  119. }
  120. function mdwp_add_p($text) {
  121. if (!preg_match('{^$|^<(p|ul|ol|dl|pre|blockquote)>}i', $text)) {
  122. $text = '<p>'.$text.'</p>';
  123. $text = preg_replace('{\n{2,}}', "</p>\n\n<p>", $text);
  124. }
  125. return $text;
  126. }
  127. function mdwp_strip_p($t) { return preg_replace('{</?p>}i', '', $t); }
  128. function mdwp_hide_tags($text) {
  129. global $mdwp_hidden_tags, $mdwp_placeholders;
  130. return str_replace($mdwp_hidden_tags, $mdwp_placeholders, $text);
  131. }
  132. function mdwp_show_tags($text) {
  133. global $mdwp_hidden_tags, $mdwp_placeholders;
  134. return str_replace($mdwp_placeholders, $mdwp_hidden_tags, $text);
  135. }
  136. }
  137. ### bBlog Plugin Info ###
  138. function identify_modifier_markdown() {
  139. return array(
  140. 'name' => 'markdown',
  141. 'type' => 'modifier',
  142. 'nicename' => 'PHP Markdown Extra',
  143. 'description' => 'A text-to-HTML conversion tool for web writers',
  144. 'authors' => 'Michel Fortin and John Gruber',
  145. 'licence' => 'GPL',
  146. 'version' => MARKDOWNEXTRA_VERSION,
  147. 'help' => '<a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by <a href="http://daringfireball.net/">John Gruber</a>. <a href="http://michelf.com/projects/php-markdown/">More...</a>',
  148. );
  149. }
  150. ### Smarty Modifier Interface ###
  151. function smarty_modifier_markdown($text) {
  152. return Markdown($text);
  153. }
  154. ### Textile Compatibility Mode ###
  155. # Rename this file to "classTextile.php" and it can replace Textile everywhere.
  156. if (strcasecmp(substr(__FILE__, -16), "classTextile.php") == 0) {
  157. # Try to include PHP SmartyPants. Should be in the same directory.
  158. @include_once 'smartypants.php';
  159. # Fake Textile class. It calls Markdown instead.
  160. class Textile {
  161. function TextileThis($text, $lite='', $encode='') {
  162. if ($lite == '' && $encode == '') $text = Markdown($text);
  163. if (function_exists('SmartyPants')) $text = SmartyPants($text);
  164. return $text;
  165. }
  166. # Fake restricted version: restrictions are not supported for now.
  167. function TextileRestricted($text, $lite='', $noimage='') {
  168. return $this->TextileThis($text, $lite);
  169. }
  170. # Workaround to ensure compatibility with TextPattern 4.0.3.
  171. function blockLite($text) { return $text; }
  172. }
  173. }
  174. #
  175. # Markdown Parser Class
  176. #
  177. class Markdown_Parser {
  178. # Regex to match balanced [brackets].
  179. # Needed to insert a maximum bracked depth while converting to PHP.
  180. var $nested_brackets_depth = 6;
  181. var $nested_brackets_re;
  182. var $nested_url_parenthesis_depth = 4;
  183. var $nested_url_parenthesis_re;
  184. # Table of hash values for escaped characters:
  185. var $escape_chars = '\`*_{}[]()>#+-.!';
  186. var $escape_chars_re;
  187. # Change to ">" for HTML output.
  188. var $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX;
  189. var $tab_width = MARKDOWN_TAB_WIDTH;
  190. # Change to `true` to disallow markup or entities.
  191. var $no_markup = false;
  192. var $no_entities = false;
  193. # Predefined urls and titles for reference links and images.
  194. var $predef_urls = array();
  195. var $predef_titles = array();
  196. function Markdown_Parser() {
  197. #
  198. # Constructor function. Initialize appropriate member variables.
  199. #
  200. $this->_initDetab();
  201. $this->prepareItalicsAndBold();
  202. $this->nested_brackets_re =
  203. str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth).
  204. str_repeat('\])*', $this->nested_brackets_depth);
  205. $this->nested_url_parenthesis_re =
  206. str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth).
  207. str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth);
  208. $this->escape_chars_re = '['.preg_quote($this->escape_chars).']';
  209. # Sort document, block, and span gamut in ascendent priority order.
  210. asort($this->document_gamut);
  211. asort($this->block_gamut);
  212. asort($this->span_gamut);
  213. }
  214. # Internal hashes used during transformation.
  215. var $urls = array();
  216. var $titles = array();
  217. var $html_hashes = array();
  218. # Status flag to avoid invalid nesting.
  219. var $in_anchor = false;
  220. function setup() {
  221. #
  222. # Called before the transformation process starts to setup parser
  223. # states.
  224. #
  225. # Clear global hashes.
  226. $this->urls = $this->predef_urls;
  227. $this->titles = $this->predef_titles;
  228. $this->html_hashes = array();
  229. $in_anchor = false;
  230. }
  231. function teardown() {
  232. #
  233. # Called after the transformation process to clear any variable
  234. # which may be taking up memory unnecessarly.
  235. #
  236. $this->urls = array();
  237. $this->titles = array();
  238. $this->html_hashes = array();
  239. }
  240. function transform($text) {
  241. #
  242. # Main function. Performs some preprocessing on the input text
  243. # and pass it through the document gamut.
  244. #
  245. $this->setup();
  246. # Remove UTF-8 BOM and marker character in input, if present.
  247. $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text);
  248. # Standardize line endings:
  249. # DOS to Unix and Mac to Unix
  250. $text = preg_replace('{\r\n?}', "\n", $text);
  251. # Make sure $text ends with a couple of newlines:
  252. $text .= "\n\n";
  253. # Convert all tabs to spaces.
  254. $text = $this->detab($text);
  255. # Turn block-level HTML blocks into hash entries
  256. $text = $this->hashHTMLBlocks($text);
  257. # Strip any lines consisting only of spaces and tabs.
  258. # This makes subsequent regexen easier to write, because we can
  259. # match consecutive blank lines with /\n+/ instead of something
  260. # contorted like /[ ]*\n+/ .
  261. $text = preg_replace('/^[ ]+$/m', '', $text);
  262. # Run document gamut methods.
  263. foreach ($this->document_gamut as $method => $priority) {
  264. $text = $this->$method($text);
  265. }
  266. $this->teardown();
  267. return $text . "\n";
  268. }
  269. var $document_gamut = array(
  270. # Strip link definitions, store in hashes.
  271. "stripLinkDefinitions" => 20,
  272. "runBasicBlockGamut" => 30,
  273. );
  274. function stripLinkDefinitions($text) {
  275. #
  276. # Strips link definitions from text, stores the URLs and titles in
  277. # hash references.
  278. #
  279. $less_than_tab = $this->tab_width - 1;
  280. # Link defs are in the form: ^[id]: url "optional title"
  281. $text = preg_replace_callback('{
  282. ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1
  283. [ ]*
  284. \n? # maybe *one* newline
  285. [ ]*
  286. (?:
  287. <(.+?)> # url = $2
  288. |
  289. (\S+?) # url = $3
  290. )
  291. [ ]*
  292. \n? # maybe one newline
  293. [ ]*
  294. (?:
  295. (?<=\s) # lookbehind for whitespace
  296. ["(]
  297. (.*?) # title = $4
  298. [")]
  299. [ ]*
  300. )? # title is optional
  301. (?:\n+|\Z)
  302. }xm',
  303. array(&$this, '_stripLinkDefinitions_callback'),
  304. $text);
  305. return $text;
  306. }
  307. function _stripLinkDefinitions_callback($matches) {
  308. $link_id = strtolower($matches[1]);
  309. $url = $matches[2] == '' ? $matches[3] : $matches[2];
  310. $this->urls[$link_id] = $url;
  311. $this->titles[$link_id] =& $matches[4];
  312. return ''; # String that will replace the block
  313. }
  314. function hashHTMLBlocks($text) {
  315. if ($this->no_markup) return $text;
  316. $less_than_tab = $this->tab_width - 1;
  317. # Hashify HTML blocks:
  318. # We only want to do this for block-level HTML tags, such as headers,
  319. # lists, and tables. That's because we still want to wrap <p>s around
  320. # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  321. # phrase emphasis, and spans. The list of tags we're looking for is
  322. # hard-coded:
  323. #
  324. # * List "a" is made of tags which can be both inline or block-level.
  325. # These will be treated block-level when the start tag is alone on
  326. # its line, otherwise they're not matched here and will be taken as
  327. # inline later.
  328. # * List "b" is made of tags which are always block-level;
  329. #
  330. $block_tags_a_re = 'ins|del';
  331. $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'.
  332. 'script|noscript|form|fieldset|iframe|math';
  333. # Regular expression for the content of a block tag.
  334. $nested_tags_level = 4;
  335. $attr = '
  336. (?> # optional tag attributes
  337. \s # starts with whitespace
  338. (?>
  339. [^>"/]+ # text outside quotes
  340. |
  341. /+(?!>) # slash not followed by ">"
  342. |
  343. "[^"]*" # text inside double quotes (tolerate ">")
  344. |
  345. \'[^\']*\' # text inside single quotes (tolerate ">")
  346. )*
  347. )?
  348. ';
  349. $content =
  350. str_repeat('
  351. (?>
  352. [^<]+ # content without tag
  353. |
  354. <\2 # nested opening tag
  355. '.$attr.' # attributes
  356. (?>
  357. />
  358. |
  359. >', $nested_tags_level). # end of opening tag
  360. '.*?'. # last level nested tag content
  361. str_repeat('
  362. </\2\s*> # closing nested tag
  363. )
  364. |
  365. <(?!/\2\s*> # other tags with a different name
  366. )
  367. )*',
  368. $nested_tags_level);
  369. $content2 = str_replace('\2', '\3', $content);
  370. # First, look for nested blocks, e.g.:
  371. # <div>
  372. # <div>
  373. # tags for inner block must be indented.
  374. # </div>
  375. # </div>
  376. #
  377. # The outermost tags must start at the left margin for this to match, and
  378. # the inner nested divs must be indented.
  379. # We need to do this before the next, more liberal match, because the next
  380. # match will start at the first `<div>` and stop at the first `</div>`.
  381. $text = preg_replace_callback('{(?>
  382. (?>
  383. (?<=\n\n) # Starting after a blank line
  384. | # or
  385. \A\n? # the beginning of the doc
  386. )
  387. ( # save in $1
  388. # Match from `\n<tag>` to `</tag>\n`, handling nested tags
  389. # in between.
  390. [ ]{0,'.$less_than_tab.'}
  391. <('.$block_tags_b_re.')# start tag = $2
  392. '.$attr.'> # attributes followed by > and \n
  393. '.$content.' # content, support nesting
  394. </\2> # the matching end tag
  395. [ ]* # trailing spaces/tabs
  396. (?=\n+|\Z) # followed by a newline or end of document
  397. | # Special version for tags of group a.
  398. [ ]{0,'.$less_than_tab.'}
  399. <('.$block_tags_a_re.')# start tag = $3
  400. '.$attr.'>[ ]*\n # attributes followed by >
  401. '.$content2.' # content, support nesting
  402. </\3> # the matching end tag
  403. [ ]* # trailing spaces/tabs
  404. (?=\n+|\Z) # followed by a newline or end of document
  405. | # Special case just for <hr />. It was easier to make a special
  406. # case than to make the other regex more complicated.
  407. [ ]{0,'.$less_than_tab.'}
  408. <(hr) # start tag = $2
  409. '.$attr.' # attributes
  410. /?> # the matching end tag
  411. [ ]*
  412. (?=\n{2,}|\Z) # followed by a blank line or end of document
  413. | # Special case for standalone HTML comments:
  414. [ ]{0,'.$less_than_tab.'}
  415. (?s:
  416. <!-- .*? -->
  417. )
  418. [ ]*
  419. (?=\n{2,}|\Z) # followed by a blank line or end of document
  420. | # PHP and ASP-style processor instructions (<? and <%)
  421. [ ]{0,'.$less_than_tab.'}
  422. (?s:
  423. <([?%]) # $2
  424. .*?
  425. \2>
  426. )
  427. [ ]*
  428. (?=\n{2,}|\Z) # followed by a blank line or end of document
  429. )
  430. )}Sxmi',
  431. array(&$this, '_hashHTMLBlocks_callback'),
  432. $text);
  433. return $text;
  434. }
  435. function _hashHTMLBlocks_callback($matches) {
  436. $text = $matches[1];
  437. $key = $this->hashBlock($text);
  438. return "\n\n$key\n\n";
  439. }
  440. function hashPart($text, $boundary = 'X') {
  441. #
  442. # Called whenever a tag must be hashed when a function insert an atomic
  443. # element in the text stream. Passing $text to through this function gives
  444. # a unique text-token which will be reverted back when calling unhash.
  445. #
  446. # The $boundary argument specify what character should be used to surround
  447. # the token. By convension, "B" is used for block elements that needs not
  448. # to be wrapped into paragraph tags at the end, ":" is used for elements
  449. # that are word separators and "X" is used in the general case.
  450. #
  451. # Swap back any tag hash found in $text so we do not have to `unhash`
  452. # multiple times at the end.
  453. $text = $this->unhash($text);
  454. # Then hash the block.
  455. static $i = 0;
  456. $key = "$boundary\x1A" . ++$i . $boundary;
  457. $this->html_hashes[$key] = $text;
  458. return $key; # String that will replace the tag.
  459. }
  460. function hashBlock($text) {
  461. #
  462. # Shortcut function for hashPart with block-level boundaries.
  463. #
  464. return $this->hashPart($text, 'B');
  465. }
  466. var $block_gamut = array(
  467. #
  468. # These are all the transformations that form block-level
  469. # tags like paragraphs, headers, and list items.
  470. #
  471. "doHeaders" => 10,
  472. "doHorizontalRules" => 20,
  473. "doLists" => 40,
  474. "doCodeBlocks" => 50,
  475. "doBlockQuotes" => 60,
  476. );
  477. function runBlockGamut($text) {
  478. #
  479. # Run block gamut tranformations.
  480. #
  481. # We need to escape raw HTML in Markdown source before doing anything
  482. # else. This need to be done for each block, and not only at the
  483. # begining in the Markdown function since hashed blocks can be part of
  484. # list items and could have been indented. Indented blocks would have
  485. # been seen as a code block in a previous pass of hashHTMLBlocks.
  486. $text = $this->hashHTMLBlocks($text);
  487. return $this->runBasicBlockGamut($text);
  488. }
  489. function runBasicBlockGamut($text) {
  490. #
  491. # Run block gamut tranformations, without hashing HTML blocks. This is
  492. # useful when HTML blocks are known to be already hashed, like in the first
  493. # whole-document pass.
  494. #
  495. foreach ($this->block_gamut as $method => $priority) {
  496. $text = $this->$method($text);
  497. }
  498. # Finally form paragraph and restore hashed blocks.
  499. $text = $this->formParagraphs($text);
  500. return $text;
  501. }
  502. function doHorizontalRules($text) {
  503. # Do Horizontal Rules:
  504. return preg_replace(
  505. '{
  506. ^[ ]{0,3} # Leading space
  507. ([-*_]) # $1: First marker
  508. (?> # Repeated marker group
  509. [ ]{0,2} # Zero, one, or two spaces.
  510. \1 # Marker character
  511. ){2,} # Group repeated at least twice
  512. [ ]* # Tailing spaces
  513. $ # End of line.
  514. }mx',
  515. "\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n",
  516. $text);
  517. }
  518. var $span_gamut = array(
  519. #
  520. # These are all the transformations that occur *within* block-level
  521. # tags like paragraphs, headers, and list items.
  522. #
  523. # Process character escapes, code spans, and inline HTML
  524. # in one shot.
  525. "parseSpan" => -30,
  526. # Process anchor and image tags. Images must come first,
  527. # because ![foo][f] looks like an anchor.
  528. "doImages" => 10,
  529. "doAnchors" => 20,
  530. # Make links out of things like `<http://example.com/>`
  531. # Must come after doAnchors, because you can use < and >
  532. # delimiters in inline links like [this](<url>).
  533. "doAutoLinks" => 30,
  534. "encodeAmpsAndAngles" => 40,
  535. "doItalicsAndBold" => 50,
  536. "doHardBreaks" => 60,
  537. );
  538. function runSpanGamut($text) {
  539. #
  540. # Run span gamut tranformations.
  541. #
  542. foreach ($this->span_gamut as $method => $priority) {
  543. $text = $this->$method($text);
  544. }
  545. return $text;
  546. }
  547. function doHardBreaks($text) {
  548. if(c::get('markdown.breaks')) {
  549. # Do hard breaks:
  550. return preg_replace_callback('/ {2,}\n|\n{1}/', array(&$this, '_doHardBreaks_callback'), $text);
  551. } else {
  552. return preg_replace_callback('/ {2,}\n/',
  553. array(&$this, '_doHardBreaks_callback'), $text);
  554. }
  555. }
  556. function _doHardBreaks_callback($matches) {
  557. return $this->hashPart("<br$this->empty_element_suffix\n");
  558. }
  559. function doAnchors($text) {
  560. #
  561. # Turn Markdown link shortcuts into XHTML <a> tags.
  562. #
  563. if ($this->in_anchor) return $text;
  564. $this->in_anchor = true;
  565. #
  566. # First, handle reference-style links: [link text] [id]
  567. #
  568. $text = preg_replace_callback('{
  569. ( # wrap whole match in $1
  570. \[
  571. ('.$this->nested_brackets_re.') # link text = $2
  572. \]
  573. [ ]? # one optional space
  574. (?:\n[ ]*)? # one optional newline followed by spaces
  575. \[
  576. (.*?) # id = $3
  577. \]
  578. )
  579. }xs',
  580. array(&$this, '_doAnchors_reference_callback'), $text);
  581. #
  582. # Next, inline-style links: [link text](url "optional title")
  583. #
  584. $text = preg_replace_callback('{
  585. ( # wrap whole match in $1
  586. \[
  587. ('.$this->nested_brackets_re.') # link text = $2
  588. \]
  589. \( # literal paren
  590. [ \n]*
  591. (?:
  592. <(.+?)> # href = $3
  593. |
  594. ('.$this->nested_url_parenthesis_re.') # href = $4
  595. )
  596. [ \n]*
  597. ( # $5
  598. ([\'"]) # quote char = $6
  599. (.*?) # Title = $7
  600. \6 # matching quote
  601. [ \n]* # ignore any spaces/tabs between closing quote and )
  602. )? # title is optional
  603. \)
  604. )
  605. }xs',
  606. array(&$this, '_doAnchors_inline_callback'), $text);
  607. #
  608. # Last, handle reference-style shortcuts: [link text]
  609. # These must come last in case you've also got [link text][1]
  610. # or [link text](/foo)
  611. #
  612. $text = preg_replace_callback('{
  613. ( # wrap whole match in $1
  614. \[
  615. ([^\[\]]+) # link text = $2; can\'t contain [ or ]
  616. \]
  617. )
  618. }xs',
  619. array(&$this, '_doAnchors_reference_callback'), $text);
  620. $this->in_anchor = false;
  621. return $text;
  622. }
  623. function _doAnchors_reference_callback($matches) {
  624. $whole_match = $matches[1];
  625. $link_text = $matches[2];
  626. $link_id =& $matches[3];
  627. if ($link_id == "") {
  628. # for shortcut links like [this][] or [this].
  629. $link_id = $link_text;
  630. }
  631. # lower-case and turn embedded newlines into spaces
  632. $link_id = strtolower($link_id);
  633. $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
  634. if (isset($this->urls[$link_id])) {
  635. $url = $this->urls[$link_id];
  636. $url = $this->encodeAttribute($url);
  637. $result = "<a href=\"$url\"";
  638. if ( isset( $this->titles[$link_id] ) ) {
  639. $title = $this->titles[$link_id];
  640. $title = $this->encodeAttribute($title);
  641. $result .= " title=\"$title\"";
  642. }
  643. $link_text = $this->runSpanGamut($link_text);
  644. $result .= ">$link_text</a>";
  645. $result = $this->hashPart($result);
  646. }
  647. else {
  648. $result = $whole_match;
  649. }
  650. return $result;
  651. }
  652. function _doAnchors_inline_callback($matches) {
  653. $whole_match = $matches[1];
  654. $link_text = $this->runSpanGamut($matches[2]);
  655. $url = $matches[3] == '' ? $matches[4] : $matches[3];
  656. $title =& $matches[7];
  657. $url = $this->encodeAttribute($url);
  658. $result = "<a href=\"$url\"";
  659. if (isset($title)) {
  660. $title = $this->encodeAttribute($title);
  661. $result .= " title=\"$title\"";
  662. }
  663. $link_text = $this->runSpanGamut($link_text);
  664. $result .= ">$link_text</a>";
  665. return $this->hashPart($result);
  666. }
  667. function doImages($text) {
  668. #
  669. # Turn Markdown image shortcuts into <img> tags.
  670. #
  671. #
  672. # First, handle reference-style labeled images: ![alt text][id]
  673. #
  674. $text = preg_replace_callback('{
  675. ( # wrap whole match in $1
  676. !\[
  677. ('.$this->nested_brackets_re.') # alt text = $2
  678. \]
  679. [ ]? # one optional space
  680. (?:\n[ ]*)? # one optional newline followed by spaces
  681. \[
  682. (.*?) # id = $3
  683. \]
  684. )
  685. }xs',
  686. array(&$this, '_doImages_reference_callback'), $text);
  687. #
  688. # Next, handle inline images: ![alt text](url "optional title")
  689. # Don't forget: encode * and _
  690. #
  691. $text = preg_replace_callback('{
  692. ( # wrap whole match in $1
  693. !\[
  694. ('.$this->nested_brackets_re.') # alt text = $2
  695. \]
  696. \s? # One optional whitespace character
  697. \( # literal paren
  698. [ \n]*
  699. (?:
  700. <(\S*)> # src url = $3
  701. |
  702. ('.$this->nested_url_parenthesis_re.') # src url = $4
  703. )
  704. [ \n]*
  705. ( # $5
  706. ([\'"]) # quote char = $6
  707. (.*?) # title = $7
  708. \6 # matching quote
  709. [ \n]*
  710. )? # title is optional
  711. \)
  712. )
  713. }xs',
  714. array(&$this, '_doImages_inline_callback'), $text);
  715. return $text;
  716. }
  717. function _doImages_reference_callback($matches) {
  718. $whole_match = $matches[1];
  719. $alt_text = $matches[2];
  720. $link_id = strtolower($matches[3]);
  721. if ($link_id == "") {
  722. $link_id = strtolower($alt_text); # for shortcut links like ![this][].
  723. }
  724. $alt_text = $this->encodeAttribute($alt_text);
  725. if (isset($this->urls[$link_id])) {
  726. $url = $this->encodeAttribute($this->urls[$link_id]);
  727. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  728. if (isset($this->titles[$link_id])) {
  729. $title = $this->titles[$link_id];
  730. $title = $this->encodeAttribute($title);
  731. $result .= " title=\"$title\"";
  732. }
  733. $result .= $this->empty_element_suffix;
  734. $result = $this->hashPart($result);
  735. }
  736. else {
  737. # If there's no such link ID, leave intact:
  738. $result = $whole_match;
  739. }
  740. return $result;
  741. }
  742. function _doImages_inline_callback($matches) {
  743. $whole_match = $matches[1];
  744. $alt_text = $matches[2];
  745. $url = $matches[3] == '' ? $matches[4] : $matches[3];
  746. $title =& $matches[7];
  747. $alt_text = $this->encodeAttribute($alt_text);
  748. $url = $this->encodeAttribute($url);
  749. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  750. if (isset($title)) {
  751. $title = $this->encodeAttribute($title);
  752. $result .= " title=\"$title\""; # $title already quoted
  753. }
  754. $result .= $this->empty_element_suffix;
  755. return $this->hashPart($result);
  756. }
  757. function doHeaders($text) {
  758. # Setext-style headers:
  759. # Header 1
  760. # ========
  761. #
  762. # Header 2
  763. # --------
  764. #
  765. $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx',
  766. array(&$this, '_doHeaders_callback_setext'), $text);
  767. # atx-style headers:
  768. # # Header 1
  769. # ## Header 2
  770. # ## Header 2 with closing hashes ##
  771. # ...
  772. # ###### Header 6
  773. #
  774. $text = preg_replace_callback('{
  775. ^(\#{1,6}) # $1 = string of #\'s
  776. [ ]*
  777. (.+?) # $2 = Header text
  778. [ ]*
  779. \#* # optional closing #\'s (not counted)
  780. \n+
  781. }xm',
  782. array(&$this, '_doHeaders_callback_atx'), $text);
  783. return $text;
  784. }
  785. function _doHeaders_callback_setext($matches) {
  786. # Terrible hack to check we haven't found an empty list item.
  787. if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1]))
  788. return $matches[0];
  789. $level = $matches[2]{0} == '=' ? 1 : 2;
  790. $block = "<h$level>".$this->runSpanGamut($matches[1])."</h$level>";
  791. return "\n" . $this->hashBlock($block) . "\n\n";
  792. }
  793. function _doHeaders_callback_atx($matches) {
  794. $level = strlen($matches[1]);
  795. $block = "<h$level>".$this->runSpanGamut($matches[2])."</h$level>";
  796. return "\n" . $this->hashBlock($block) . "\n\n";
  797. }
  798. function doLists($text) {
  799. #
  800. # Form HTML ordered (numbered) and unordered (bulleted) lists.
  801. #
  802. $less_than_tab = $this->tab_width - 1;
  803. # Re-usable patterns to match list item bullets and number markers:
  804. $marker_ul_re = '[*+-]';
  805. $marker_ol_re = '\d+[\.]';
  806. $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  807. $markers_relist = array(
  808. $marker_ul_re => $marker_ol_re,
  809. $marker_ol_re => $marker_ul_re,
  810. );
  811. foreach ($markers_relist as $marker_re => $other_marker_re) {
  812. # Re-usable pattern to match any entirel ul or ol list:
  813. $whole_list_re = '
  814. ( # $1 = whole list
  815. ( # $2
  816. ([ ]{0,'.$less_than_tab.'}) # $3 = number of spaces
  817. ('.$marker_re.') # $4 = first list item marker
  818. [ ]+
  819. )
  820. (?s:.+?)
  821. ( # $5
  822. \z
  823. |
  824. \n{2,}
  825. (?=\S)
  826. (?! # Negative lookahead for another list item marker
  827. [ ]*
  828. '.$marker_re.'[ ]+
  829. )
  830. |
  831. (?= # Lookahead for another kind of list
  832. \n
  833. \3 # Must have the same indentation
  834. '.$other_marker_re.'[ ]+
  835. )
  836. )
  837. )
  838. '; // mx
  839. # We use a different prefix before nested lists than top-level lists.
  840. # See extended comment in _ProcessListItems().
  841. if ($this->list_level) {
  842. $text = preg_replace_callback('{
  843. ^
  844. '.$whole_list_re.'
  845. }mx',
  846. array(&$this, '_doLists_callback'), $text);
  847. }
  848. else {
  849. $text = preg_replace_callback('{
  850. (?:(?<=\n)\n|\A\n?) # Must eat the newline
  851. '.$whole_list_re.'
  852. }mx',
  853. array(&$this, '_doLists_callback'), $text);
  854. }
  855. }
  856. return $text;
  857. }
  858. function _doLists_callback($matches) {
  859. # Re-usable patterns to match list item bullets and number markers:
  860. $marker_ul_re = '[*+-]';
  861. $marker_ol_re = '\d+[\.]';
  862. $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  863. $list = $matches[1];
  864. $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol";
  865. $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re );
  866. $list .= "\n";
  867. $result = $this->processListItems($list, $marker_any_re);
  868. $result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>");
  869. return "\n". $result ."\n\n";
  870. }
  871. var $list_level = 0;
  872. function processListItems($list_str, $marker_any_re) {
  873. #
  874. # Process the contents of a single ordered or unordered list, splitting it
  875. # into individual list items.
  876. #
  877. # The $this->list_level global keeps track of when we're inside a list.
  878. # Each time we enter a list, we increment it; when we leave a list,
  879. # we decrement. If it's zero, we're not in a list anymore.
  880. #
  881. # We do this because when we're not inside a list, we want to treat
  882. # something like this:
  883. #
  884. # I recommend upgrading to version
  885. # 8. Oops, now this line is treated
  886. # as a sub-list.
  887. #
  888. # As a single paragraph, despite the fact that the second line starts
  889. # with a digit-period-space sequence.
  890. #
  891. # Whereas when we're inside a list (or sub-list), that line will be
  892. # treated as the start of a sub-list. What a kludge, huh? This is
  893. # an aspect of Markdown's syntax that's hard to parse perfectly
  894. # without resorting to mind-reading. Perhaps the solution is to
  895. # change the syntax rules such that sub-lists must start with a
  896. # starting cardinal number; e.g. "1." or "a.".
  897. $this->list_level++;
  898. # trim trailing blank lines:
  899. $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
  900. $list_str = preg_replace_callback('{
  901. (\n)? # leading line = $1
  902. (^[ ]*) # leading whitespace = $2
  903. ('.$marker_any_re.' # list marker and space = $3
  904. (?:[ ]+|(?=\n)) # space only required if item is not empty
  905. )
  906. ((?s:.*?)) # list item text = $4
  907. (?:(\n+(?=\n))|\n) # tailing blank line = $5
  908. (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n))))
  909. }xm',
  910. array(&$this, '_processListItems_callback'), $list_str);
  911. $this->list_level--;
  912. return $list_str;
  913. }
  914. function _processListItems_callback($matches) {
  915. $item = $matches[4];
  916. $leading_line =& $matches[1];
  917. $leading_space =& $matches[2];
  918. $marker_space = $matches[3];
  919. $tailing_blank_line =& $matches[5];
  920. if ($leading_line || $tailing_blank_line ||
  921. preg_match('/\n{2,}/', $item))
  922. {
  923. # Replace marker with the appropriate whitespace indentation
  924. $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item;
  925. $item = $this->runBlockGamut($this->outdent($item)."\n");
  926. }
  927. else {
  928. # Recursion for sub-lists:
  929. $item = $this->doLists($this->outdent($item));
  930. $item = preg_replace('/\n+$/', '', $item);
  931. $item = $this->runSpanGamut($item);
  932. }
  933. return "<li>" . $item . "</li>\n";
  934. }
  935. function doCodeBlocks($text) {
  936. #
  937. # Process Markdown `<pre><code>` blocks.
  938. #
  939. $text = preg_replace_callback('{
  940. (?:\n\n|\A\n?)
  941. ( # $1 = the code block -- one or more lines, starting with a space/tab
  942. (?>
  943. [ ]{'.$this->tab_width.'} # Lines must start with a tab or a tab-width of spaces
  944. .*\n+
  945. )+
  946. )
  947. ((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
  948. }xm',
  949. array(&$this, '_doCodeBlocks_callback'), $text);
  950. return $text;
  951. }
  952. function _doCodeBlocks_callback($matches) {
  953. $codeblock = $matches[1];
  954. $codeblock = $this->outdent($codeblock);
  955. $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
  956. # trim leading newlines and trailing newlines
  957. $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
  958. $codeblock = "<pre><code>$codeblock\n</code></pre>";
  959. return "\n\n".$this->hashBlock($codeblock)."\n\n";
  960. }
  961. function makeCodeSpan($code) {
  962. #
  963. # Create a code span markup for $code. Called from handleSpanToken.
  964. #
  965. $code = htmlspecialchars(trim($code), ENT_NOQUOTES);
  966. return $this->hashPart("<code>$code</code>");
  967. }
  968. var $em_relist = array(
  969. '' => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?=\S|$)(?![\.,:;]\s)',
  970. '*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
  971. '_' => '(?<=\S|^)(?<!_)_(?!_)',
  972. );
  973. var $strong_relist = array(
  974. '' => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?=\S|$)(?![\.,:;]\s)',
  975. '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
  976. '__' => '(?<=\S|^)(?<!_)__(?!_)',
  977. );
  978. var $em_strong_relist = array(
  979. '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?=\S|$)(?![\.,:;]\s)',
  980. '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
  981. '___' => '(?<=\S|^)(?<!_)___(?!_)',
  982. );
  983. var $em_strong_prepared_relist;
  984. function prepareItalicsAndBold() {
  985. #
  986. # Prepare regular expressions for searching emphasis tokens in any
  987. # context.
  988. #
  989. foreach ($this->em_relist as $em => $em_re) {
  990. foreach ($this->strong_relist as $strong => $strong_re) {
  991. # Construct list of allowed token expressions.
  992. $token_relist = array();
  993. if (isset($this->em_strong_relist["$em$strong"])) {
  994. $token_relist[] = $this->em_strong_relist["$em$strong"];
  995. }
  996. $token_relist[] = $em_re;
  997. $token_relist[] = $strong_re;
  998. # Construct master expression from list.
  999. $token_re = '{('. implode('|', $token_relist) .')}';
  1000. $this->em_strong_prepared_relist["$em$strong"] = $token_re;
  1001. }
  1002. }
  1003. }
  1004. function doItalicsAndBold($text) {
  1005. $token_stack = array('');
  1006. $text_stack = array('');
  1007. $em = '';
  1008. $strong = '';
  1009. $tree_char_em = false;
  1010. while (1) {
  1011. #
  1012. # Get prepared regular expression for seraching emphasis tokens
  1013. # in current context.
  1014. #
  1015. $token_re = $this->em_strong_prepared_relist["$em$strong"];
  1016. #
  1017. # Each loop iteration search for the next emphasis token.
  1018. # Each token is then passed to handleSpanToken.
  1019. #
  1020. $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
  1021. $text_stack[0] .= $parts[0];
  1022. $token =& $parts[1];
  1023. $text =& $parts[2];
  1024. if (empty($token)) {
  1025. # Reached end of text span: empty stack without emitting.
  1026. # any more emphasis.
  1027. while ($token_stack[0]) {
  1028. $text_stack[1] .= array_shift($token_stack);
  1029. $text_stack[0] .= array_shift($text_stack);
  1030. }
  1031. break;
  1032. }
  1033. $token_len = strlen($token);
  1034. if ($tree_char_em) {
  1035. # Reached closing marker while inside a three-char emphasis.
  1036. if ($token_len == 3) {
  1037. # Three-char closing marker, close em and strong.
  1038. array_shift($token_stack);
  1039. $span = array_shift($text_stack);
  1040. $span = $this->runSpanGamut($span);
  1041. $span = "<strong><em>$span</em></strong>";
  1042. $text_stack[0] .= $this->hashPart($span);
  1043. $em = '';
  1044. $strong = '';
  1045. } else {
  1046. # Other closing marker: close one em or strong and
  1047. # change current token state to match the other
  1048. $token_stack[0] = str_repeat($token{0}, 3-$token_len);
  1049. $tag = $token_len == 2 ? "strong" : "em";
  1050. $span = $text_stack[0];
  1051. $span = $this->runSpanGamut($span);
  1052. $span = "<$tag>$span</$tag>";
  1053. $text_stack[0] = $this->hashPart($span);
  1054. $$tag = ''; # $$tag stands for $em or $strong
  1055. }
  1056. $tree_char_em = false;
  1057. } else if ($token_len == 3) {
  1058. if ($em) {
  1059. # Reached closing marker for both em and strong.
  1060. # Closing strong marker:
  1061. for ($i = 0; $i < 2; ++$i) {
  1062. $shifted_token = array_shift($token_stack);
  1063. $tag = strlen($shifted_token) == 2 ? "strong" : "em";
  1064. $span = array_shift($text_stack);
  1065. $span = $this->runSpanGamut($span);
  1066. $span = "<$tag>$span</$tag>";
  1067. $text_stack[0] .= $this->hashPart($span);
  1068. $$tag = ''; # $$tag stands for $em or $strong
  1069. }
  1070. } else {
  1071. # Reached opening three-char emphasis marker. Push on token
  1072. # stack; will be handled by the special condition above.
  1073. $em = $token{0};
  1074. $strong = "$em$em";
  1075. array_unshift($token_stack, $token);
  1076. array_unshift($text_stack, '');
  1077. $tree_char_em = true;
  1078. }
  1079. } else if ($token_len == 2) {
  1080. if ($strong) {
  1081. # Unwind any dangling emphasis marker:
  1082. if (strlen($token_stack[0]) == 1) {
  1083. $text_stack[1] .= array_shift($token_stack);
  1084. $text_stack[0] .= array_shift($text_stack);
  1085. }
  1086. # Closing strong marker:
  1087. array_shift($token_stack);
  1088. $span = array_shift($text_stack);
  1089. $span = $this->runSpanGamut($span);
  1090. $span = "<strong>$span</strong>";
  1091. $text_stack[0] .= $this->hashPart($span);
  1092. $strong = '';
  1093. } else {
  1094. array_unshift($token_stack, $token);
  1095. array_unshift($text_stack, '');
  1096. $strong = $token;
  1097. }
  1098. } else {
  1099. # Here $token_len == 1
  1100. if ($em) {
  1101. if (strlen($token_stack[0]) == 1) {
  1102. # Closing emphasis marker:
  1103. array_shift($token_stack);
  1104. $span = array_shift($text_stack);
  1105. $span = $this->runSpanGamut($span);
  1106. $span = "<em>$span</em>";
  1107. $text_stack[0] .= $this->hashPart($span);
  1108. $em = '';
  1109. } else {
  1110. $text_stack[0] .= $token;
  1111. }
  1112. } else {
  1113. array_unshift($token_stack, $token);
  1114. array_unshift($text_stack, '');
  1115. $em = $token;
  1116. }
  1117. }
  1118. }
  1119. return $text_stack[0];
  1120. }
  1121. function doBlockQuotes($text) {
  1122. $text = preg_replace_callback('/
  1123. ( # Wrap whole match in $1
  1124. (?>
  1125. ^[ ]*>[ ]? # ">" at the start of a line
  1126. .+\n # rest of the first line
  1127. (.+\n)* # subsequent consecutive lines
  1128. \n* # blanks
  1129. )+
  1130. )
  1131. /xm',
  1132. array(&$this, '_doBlockQuotes_callback'), $text);
  1133. return $text;
  1134. }
  1135. function _doBlockQuotes_callback($matches) {
  1136. $bq = $matches[1];
  1137. # trim one level of quoting - trim whitespace-only lines
  1138. $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);
  1139. $bq = $this->runBlockGamut($bq); # recurse
  1140. $bq = preg_replace('/^/m', " ", $bq);
  1141. # These leading spaces cause problem with <pre> content,
  1142. # so we need to fix that:
  1143. $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx',
  1144. array(&$this, '_doBlockQuotes_callback2'), $bq);
  1145. return "\n". $this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n";
  1146. }
  1147. function _doBlockQuotes_callback2($matches) {
  1148. $pre = $matches[1];
  1149. $pre = preg_replace('/^ /m', '', $pre);
  1150. return $pre;
  1151. }
  1152. function formParagraphs($text) {
  1153. #
  1154. # Params:
  1155. # $text - string to process with html <p> tags
  1156. #
  1157. # Strip leading and trailing lines:
  1158. $text = preg_replace('/\A\n+|\n+\z/', '', $text);
  1159. $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
  1160. #
  1161. # Wrap <p> tags and unhashify HTML blocks
  1162. #
  1163. foreach ($grafs as $key => $value) {
  1164. if (!preg_match('/^B\x1A[0-9]+B$/', $value)) {
  1165. # Is a paragraph.
  1166. $value = $this->runSpanGamut($value);
  1167. $value = preg_replace('/^([ ]*)/', "<p>", $value);
  1168. $value .= "</p>";
  1169. $grafs[$key] = $this->unhash($value);
  1170. }
  1171. else {
  1172. # Is a block.
  1173. # Modify elements of @grafs in-place...
  1174. $graf = $value;
  1175. $block = $this->html_hashes[$graf];
  1176. $graf = $block;
  1177. // if (preg_match('{
  1178. // \A
  1179. // ( # $1 = <div> tag
  1180. // <div \s+
  1181. // [^>]*
  1182. // \b
  1183. // markdown\s*=\s* ([\'"]) # $2 = attr quote char
  1184. // 1
  1185. // \2
  1186. // [^>]*
  1187. // >
  1188. // )
  1189. // ( # $3 = contents
  1190. // .*
  1191. // )
  1192. // (</div>) # $4 = closing tag
  1193. // \z
  1194. // }xs', $block, $matches))
  1195. // {
  1196. // list(, $div_open, , $div_content, $div_close) = $matches;
  1197. //
  1198. // # We can't call Markdown(), because that resets the hash;
  1199. // # that initialization code should be pulled into its own sub, though.
  1200. // $div_content = $this->hashHTMLBlocks($div_content);
  1201. //
  1202. // # Run document gamut methods on the content.
  1203. // foreach ($this->document_gamut as $method => $priority) {
  1204. // $div_content = $this->$method($div_content);
  1205. // }
  1206. //
  1207. // $div_open = preg_replace(
  1208. // '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open);
  1209. //
  1210. // $graf = $div_open . "\n" . $div_content . "\n" . $div_close;
  1211. // }
  1212. $grafs[$key] = $graf;
  1213. }
  1214. }
  1215. return implode("\n\n", $grafs);
  1216. }
  1217. function encodeAttribute($text) {
  1218. #
  1219. # Encode text for a double-quoted HTML attribute. This function
  1220. # is *not* suitable for attributes enclosed in single quotes.
  1221. #
  1222. $text = $this->encodeAmpsAndAngles($text);
  1223. $text = str_replace('"', '&quot;', $text);
  1224. return $text;
  1225. }
  1226. function encodeAmpsAndAngles($text) {
  1227. #
  1228. # Smart processing for ampersands and angle brackets that need to
  1229. # be encoded. Valid character entities are left alone unless the
  1230. # no-entities mode is set.
  1231. #
  1232. if ($this->no_entities) {
  1233. $text = str_replace('&', '&amp;', $text);
  1234. } else {
  1235. # Ampersand-encoding based entirely on Nat Irons's Amputator
  1236. # MT plugin: <http://bumppo.net/projects/amputator/>
  1237. $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
  1238. '&amp;', $text);;
  1239. }
  1240. # Encode remaining <'s
  1241. $text = str_replace('<', '&lt;', $text);
  1242. return $text;
  1243. }
  1244. function doAutoLinks($text) {
  1245. $text = preg_replace_callback('{<((https?|ftp|dict):[^\'">\s]+)>}i',
  1246. array(&$this, '_doAutoLinks_url_callback'), $text);
  1247. # Email addresses: <address@domain.foo>
  1248. $text = preg_replace_callback('{
  1249. <
  1250. (?:mailto:)?
  1251. (
  1252. (?:
  1253. [-!#$%&\'*+/=?^_`.{|}~\w\x80-\xFF]+
  1254. |
  1255. ".*?"
  1256. )
  1257. \@
  1258. (?:
  1259. [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+
  1260. |
  1261. \[[\d.a-fA-F:]+\] # IPv4 & IPv6
  1262. )
  1263. )
  1264. >
  1265. }xi',
  1266. array(&$this, '_doAutoLinks_email_callback'), $text);
  1267. return $text;
  1268. }
  1269. function _doAutoLinks_url_callback($matches) {
  1270. $url = $this->encodeAttribute($matches[1]);
  1271. $link = "<a href=\"$url\">$url</a>";
  1272. return $this->hashPart($link);
  1273. }
  1274. function _doAutoLinks_email_callback($matches) {
  1275. $address = $matches[1];
  1276. $link = $this->encodeEmailAddress($address);
  1277. return $this->hashPart($link);
  1278. }
  1279. function encodeEmailAddress($addr) {
  1280. #
  1281. # Input: an email address, e.g. "foo@example.com"
  1282. #
  1283. # Output: the email address as a mailto link, with each character
  1284. # of the address encoded as either a decimal or hex entity, in
  1285. # the hopes of foiling most address harvesting spam bots. E.g.:
  1286. #
  1287. # <p><a href="&#109;&#x61;&#105;&#x6c;&#116;&#x6f;&#58;&#x66;o&#111;
  1288. # &#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;&#101;&#46;&#x63;&#111;
  1289. # &#x6d;">&#x66;o&#111;&#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;
  1290. # &#101;&#46;&#x63;&#111;&#x6d;</a></p>
  1291. #
  1292. # Based by a filter by Matthew Wickline, posted to BBEdit-Talk.
  1293. # With some optimizations by Milian Wolff.
  1294. #
  1295. $addr = "mailto:" . $addr;
  1296. $chars = preg_split('/(?<!^)(?!$)/', $addr);
  1297. $seed = (int)abs(crc32($addr) / strlen($addr)); # Deterministic seed.
  1298. foreach ($chars as $key => $char) {
  1299. $ord = ord($char);
  1300. # Ignore non-ascii chars.
  1301. if ($ord < 128) {
  1302. $r = ($seed * (1 + $key)) % 100; # Pseudo-random function.
  1303. # roughly 10% raw, 45% hex, 45% dec
  1304. # '@' *must* be encoded. I insist.
  1305. if ($r > 90 && $char != '@') /* do nothing */;
  1306. else if ($r < 45) $chars[$key] = '&#x'.dechex($ord).';';
  1307. else $chars[$key] = '&#'.$ord.';';
  1308. }
  1309. }
  1310. $addr = implode('', $chars);
  1311. $text = implode('', array_slice($chars, 7)); # text without `mailto:`
  1312. $addr = "<a href=\"$addr\">$text</a>";
  1313. return $addr;
  1314. }
  1315. function parseSpan($str) {
  1316. #
  1317. # Take the string $str and parse it into tokens, hashing embeded HTML,
  1318. # escaped characters and handling code spans.
  1319. #
  1320. $output = '';
  1321. $span_re = '{
  1322. (
  1323. \\\\'.$this->escape_chars_re.'
  1324. |
  1325. (?<![`\\\\])
  1326. `+ # code span marker
  1327. '.( $this->no_markup ? '' : '
  1328. |
  1329. <!-- .*? --> # comment
  1330. |
  1331. <\?.*?\?> | <%.*?%> # processing instruction
  1332. |
  1333. <[/!$]?[-a-zA-Z0-9:_]+ # regular tags
  1334. (?>
  1335. \s
  1336. (?>[^"\'>]+|"[^"]*"|\'[^\']*\')*
  1337. )?
  1338. >
  1339. ').'
  1340. )
  1341. }xs';
  1342. while (1) {
  1343. #
  1344. # Each loop iteration seach for either the next tag, the next
  1345. # openning code span marker, or the next escaped character.
  1346. # Each token is then passed to handleSpanToken.
  1347. #
  1348. $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE);
  1349. # Create token from text preceding tag.
  1350. if ($parts[0] != "") {
  1351. $output .= $parts[0];
  1352. }
  1353. # Check if we reach the end.
  1354. if (isset($parts[1])) {
  1355. $output .= $this->handleSpanToken($parts[1], $parts[2]);
  1356. $str = $parts[2];
  1357. }
  1358. else {
  1359. break;
  1360. }
  1361. }
  1362. return $output;
  1363. }
  1364. function handleSpanToken($token, &$str) {
  1365. #
  1366. # Handle $token provided by parseSpan by determining its nature and
  1367. # returning the corresponding value that should replace it.
  1368. #
  1369. switch ($token{0}) {
  1370. case "\\":
  1371. return $this->hashPart("&#". ord($token{1}). ";");
  1372. case "`":
  1373. # Search for end marker in remaining text.
  1374. if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm',
  1375. $str, $matches))
  1376. {
  1377. $str = $matches[2];
  1378. $codespan = $this->makeCodeSpan($matches[1]);
  1379. return $this->hashPart($codespan);
  1380. }
  1381. return $token; // return as text since no ending marker found.
  1382. default:
  1383. return $this->hashPart($token);
  1384. }
  1385. }
  1386. function outdent($text) {
  1387. #
  1388. # Remove one level of line-leading tabs or spaces
  1389. #
  1390. return preg_replace('/^(\t|[ ]{1,'.$this->tab_width.'})/m', '', $text);
  1391. }
  1392. # String length function for detab. `_initDetab` will create a function to
  1393. # hanlde UTF-8 if the default function does not exist.
  1394. var $utf8_strlen = 'mb_strlen';
  1395. function detab($text) {
  1396. #
  1397. # Replace tabs with the appropriate amount of space.
  1398. #
  1399. # For each line we separate the line in blocks delemited by
  1400. # tab characters. Then we reconstruct every line by adding the
  1401. # appropriate number of space between each blocks.
  1402. $text = preg_replace_callback('/^.*\t.*$/m',
  1403. array(&$this, '_detab_callback'), $text);
  1404. return $text;
  1405. }
  1406. function _detab_callback($matches) {
  1407. $line = $matches[0];
  1408. $strlen = $this->utf8_strlen; # strlen function for UTF-8.
  1409. # Split in blocks.
  1410. $blocks = explode("\t", $line);
  1411. # Add each blocks to the line.
  1412. $line = $blocks[0];
  1413. unset($blocks[0]); # Do not add first block twice.
  1414. foreach ($blocks as $block) {
  1415. # Calculate amount of space, insert spaces, insert block.
  1416. $amount = $this->tab_width -
  1417. $strlen($line, 'UTF-8') % $this->tab_width;
  1418. $line .= str_repeat(" ", $amount) . $block;
  1419. }
  1420. return $line;
  1421. }
  1422. function _initDetab() {
  1423. #
  1424. # Check for the availability of the function in the `utf8_strlen` property
  1425. # (initially `mb_strlen`). If the function is not available, create a
  1426. # function that will loosely count the number of UTF-8 characters with a
  1427. # regular expression.
  1428. #
  1429. if (function_exists($this->utf8_strlen)) return;
  1430. $this->utf8_strlen = create_function('$text', 'return preg_match_all(
  1431. "/[\\\\x00-\\\\xBF]|[\\\\xC0-\\\\xFF][\\\\x80-\\\\xBF]*/",
  1432. $text, $m);');
  1433. }
  1434. function unhash($text) {
  1435. #
  1436. # Swap back in all the tags hashed by _HashHTMLBlocks.
  1437. #
  1438. return preg_replace_callback('/(.)\x1A[0-9]+\1/',
  1439. array(&$this, '_unhash_callback'), $text);
  1440. }
  1441. function _unhash_callback($matches) {
  1442. return $this->html_hashes[$matches[0]];
  1443. }
  1444. }
  1445. #
  1446. # Markdown Extra Parser Class
  1447. #
  1448. class MarkdownExtra_Parser extends Markdown_Parser {
  1449. # Prefix for footnote ids.
  1450. var $fn_id_prefix = "";
  1451. # Optional title attribute for footnote links and backlinks.
  1452. var $fn_link_title = MARKDOWN_FN_LINK_TITLE;
  1453. var $fn_backlink_title = MARKDOWN_FN_BACKLINK_TITLE;
  1454. # Optional class attribute for footnote links and backlinks.
  1455. var $fn_link_class = MARKDOWN_FN_LINK_CLASS;
  1456. var $fn_backlink_class = MARKDOWN_FN_BACKLINK_CLASS;
  1457. # Predefined abbreviations.
  1458. var $predef_abbr = array();
  1459. function MarkdownExtra_Parser() {
  1460. #
  1461. # Constructor function. Initialize the parser object.
  1462. #
  1463. # Add extra escapable characters before parent constructor
  1464. # initialize the table.
  1465. $this->escape_chars .= ':|';
  1466. # Insert extra document, block, and span transformations.
  1467. # Parent constructor will do the sorting.
  1468. $this->document_gamut += array(
  1469. "doFencedCodeBlocks" => 5,
  1470. "stripFootnotes" => 15,
  1471. "stripAbbreviations" => 25,
  1472. "appendFootnotes" => 50,
  1473. );
  1474. $this->block_gamut += array(
  1475. "doFencedCodeBlocks" => 5,
  1476. "doTables" => 15,
  1477. "doDefLists" => 45,
  1478. );
  1479. $this->span_gamut += array(
  1480. "doFootnotes" => 5,
  1481. "doAbbreviations" => 70,
  1482. );
  1483. parent::Markdown_Parser();
  1484. }
  1485. # Extra variables used during extra transformations.
  1486. var $footnotes = array();
  1487. var $footnotes_ordered = array();
  1488. var $abbr_desciptions = array();
  1489. var $abbr_word_re = '';
  1490. # Give the current footnote number.
  1491. var $footnote_counter = 1;
  1492. function setup() {
  1493. #
  1494. # Setting up Extra-specific variables.
  1495. #
  1496. parent::setup();
  1497. $this->footnotes = array();
  1498. $this->footnotes_ordered = array();
  1499. $this->abbr_desciptions = array();
  1500. $this->abbr_word_re = '';
  1501. $this->footnote_counter = 1;
  1502. foreach ($this->predef_abbr as $abbr_word => $abbr_desc) {
  1503. if ($this->abbr_word_re)
  1504. $this->abbr_word_re .= '|';
  1505. $this->abbr_word_re .= preg_quote($abbr_word);
  1506. $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
  1507. }
  1508. }
  1509. function teardown() {
  1510. #
  1511. # Clearing Extra-specific variables.
  1512. #
  1513. $this->footnotes = array();
  1514. $this->footnotes_ordered = array();
  1515. $this->abbr_desciptions = array();
  1516. $this->abbr_word_re = '';
  1517. parent::teardown();
  1518. }
  1519. ### HTML Block Parser ###
  1520. # Tags that are always treated as block tags:
  1521. var $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend';
  1522. # Tags treated as block tags only if the opening tag is alone on it's line:
  1523. var $context_block_tags_re = 'script|noscript|math|ins|del';
  1524. # Tags where markdown="1" default to span mode:
  1525. var $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address';
  1526. # Tags which must not have their contents modified, no matter where
  1527. # they appear:
  1528. var $clean_tags_re = 'script|math';
  1529. # Tags that do not need to be closed.

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