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

/framework/lib/markdown/markdown.php

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