PageRenderTime 33ms CodeModel.GetById 14ms RepoModel.GetById 8ms app.codeStats 0ms

/fuel/modules/fuel/helpers/markdown_helper.php

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