PageRenderTime 60ms CodeModel.GetById 19ms RepoModel.GetById 1ms app.codeStats 0ms

/plugins/Markdown.php

https://github.com/mithrandir/metabbs
PHP | 2709 lines | 1610 code | 356 blank | 743 comment | 136 complexity | acee99be6bbf8d52f135e7a0784363c9 MD5 | raw file
Possible License(s): LGPL-2.1

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

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

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