PageRenderTime 63ms CodeModel.GetById 17ms RepoModel.GetById 0ms app.codeStats 0ms

/_sohy/classes/markdown.class.php

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