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

/tags/1.5/wp-content/plugins/markdown.php

#
PHP | 1282 lines | 745 code | 157 blank | 380 comment | 30 complexity | c692f4843943502a09a93df5f3b50a63 MD5 | raw file
Possible License(s): AGPL-1.0, LGPL-2.0, LGPL-2.1, GPL-2.0
  1. <?php
  2. #
  3. # Markdown - A text-to-HTML conversion tool for web writers
  4. #
  5. # Copyright (c) 2004 John Gruber
  6. # <http://daringfireball.net/projects/markdown/>
  7. #
  8. # Copyright (c) 2004 Michel Fortin - PHP Port
  9. # <http://www.michelf.com/projects/php-markdown/>
  10. #
  11. global $MarkdownPHPVersion, $MarkdownSyntaxVersion,
  12. $md_empty_element_suffix, $md_tab_width,
  13. $md_nested_brackets_depth, $md_nested_brackets,
  14. $md_escape_table, $md_backslash_escape_table,
  15. $md_list_level;
  16. $MarkdownPHPVersion = '1.0.1'; # Fri 17 Dec 2004
  17. $MarkdownSyntaxVersion = '1.0.1'; # Sun 12 Dec 2004
  18. #
  19. # Global default settings:
  20. #
  21. $md_empty_element_suffix = " />"; # Change to ">" for HTML output
  22. $md_tab_width = 4;
  23. # -- WordPress Plugin Interface -----------------------------------------------
  24. /*
  25. Plugin Name: Markdown
  26. Plugin URI: http://www.michelf.com/projects/php-markdown/
  27. 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>
  28. Version: 1.0.1
  29. Author: Michel Fortin
  30. Author URI: http://www.michelf.com/
  31. */
  32. if (isset($wp_version)) {
  33. # Remove default WordPress auto-paragraph filter.
  34. remove_filter('the_content', 'wpautop');
  35. remove_filter('the_excerpt', 'wpautop');
  36. remove_filter('comment_text', 'wpautop');
  37. # Add Markdown filter with priority 6 (same as Textile).
  38. add_filter('the_content', 'Markdown', 6);
  39. add_filter('the_excerpt', 'Markdown', 6);
  40. add_filter('comment_text', 'Markdown', 6);
  41. }
  42. # -- bBlog Plugin Info --------------------------------------------------------
  43. function identify_modifier_markdown() {
  44. global $MarkdownPHPVersion;
  45. return array(
  46. 'name' => 'markdown',
  47. 'type' => 'modifier',
  48. 'nicename' => 'Markdown',
  49. 'description' => 'A text-to-HTML conversion tool for web writers',
  50. 'authors' => 'Michel Fortin and John Gruber',
  51. 'licence' => 'GPL',
  52. 'version' => $MarkdownPHPVersion,
  53. '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>'
  54. );
  55. }
  56. # -- Smarty Modifier Interface ------------------------------------------------
  57. function smarty_modifier_markdown($text) {
  58. return Markdown($text);
  59. }
  60. # -- Textile Compatibility Mode -----------------------------------------------
  61. # Rename this file to "classTextile.php" and it can replace Textile anywhere.
  62. if (strcasecmp(substr(__FILE__, -16), "classTextile.php") == 0) {
  63. # Try to include PHP SmartyPants. Should be in the same directory.
  64. @include_once 'smartypants.php';
  65. # Fake Textile class. It calls Markdown instead.
  66. class Textile {
  67. function TextileThis($text, $lite='', $encode='', $noimage='', $strict='') {
  68. if ($lite == '' && $encode == '') $text = Markdown($text);
  69. if (function_exists('SmartyPants')) $text = SmartyPants($text);
  70. return $text;
  71. }
  72. }
  73. }
  74. #
  75. # Globals:
  76. #
  77. # Regex to match balanced [brackets].
  78. # Needed to insert a maximum bracked depth while converting to PHP.
  79. $md_nested_brackets_depth = 6;
  80. $md_nested_brackets =
  81. str_repeat('(?>[^\[\]]+|\[', $md_nested_brackets_depth).
  82. str_repeat('\])*', $md_nested_brackets_depth);
  83. # Table of hash values for escaped characters:
  84. $md_escape_table = array(
  85. "\\" => md5("\\"),
  86. "`" => md5("`"),
  87. "*" => md5("*"),
  88. "_" => md5("_"),
  89. "{" => md5("{"),
  90. "}" => md5("}"),
  91. "[" => md5("["),
  92. "]" => md5("]"),
  93. "(" => md5("("),
  94. ")" => md5(")"),
  95. ">" => md5(">"),
  96. "#" => md5("#"),
  97. "+" => md5("+"),
  98. "-" => md5("-"),
  99. "." => md5("."),
  100. "!" => md5("!")
  101. );
  102. # Create an identical table but for escaped characters.
  103. $md_backslash_escape_table;
  104. foreach ($md_escape_table as $key => $char)
  105. $md_backslash_escape_table["\\$key"] = $char;
  106. function Markdown($text) {
  107. #
  108. # Main function. The order in which other subs are called here is
  109. # essential. Link and image substitutions need to happen before
  110. # _EscapeSpecialChars(), so that any *'s or _'s in the <a>
  111. # and <img> tags get encoded.
  112. #
  113. # Clear the global hashes. If we don't clear these, you get conflicts
  114. # from other articles when generating a page which contains more than
  115. # one article (e.g. an index page that shows the N most recent
  116. # articles):
  117. global $md_urls, $md_titles, $md_html_blocks;
  118. $md_urls = array();
  119. $md_titles = array();
  120. $md_html_blocks = array();
  121. # Standardize line endings:
  122. # DOS to Unix and Mac to Unix
  123. $text = str_replace(array("\r\n", "\r"), "\n", $text);
  124. # Make sure $text ends with a couple of newlines:
  125. $text .= "\n\n";
  126. # Convert all tabs to spaces.
  127. $text = _Detab($text);
  128. # Strip any lines consisting only of spaces and tabs.
  129. # This makes subsequent regexen easier to write, because we can
  130. # match consecutive blank lines with /\n+/ instead of something
  131. # contorted like /[ \t]*\n+/ .
  132. $text = preg_replace('/^[ \t]+$/m', '', $text);
  133. # Turn block-level HTML blocks into hash entries
  134. $text = _HashHTMLBlocks($text);
  135. # Strip link definitions, store in hashes.
  136. $text = _StripLinkDefinitions($text);
  137. $text = _RunBlockGamut($text);
  138. $text = _UnescapeSpecialChars($text);
  139. return $text . "\n";
  140. }
  141. function _StripLinkDefinitions($text) {
  142. #
  143. # Strips link definitions from text, stores the URLs and titles in
  144. # hash references.
  145. #
  146. global $md_tab_width;
  147. $less_than_tab = $md_tab_width - 1;
  148. # Link defs are in the form: ^[id]: url "optional title"
  149. $text = preg_replace_callback('{
  150. ^[ ]{0,'.$less_than_tab.'}\[(.+)\]: # id = $1
  151. [ \t]*
  152. \n? # maybe *one* newline
  153. [ \t]*
  154. <?(\S+?)>? # url = $2
  155. [ \t]*
  156. \n? # maybe one newline
  157. [ \t]*
  158. (?:
  159. (?<=\s) # lookbehind for whitespace
  160. ["(]
  161. (.+?) # title = $3
  162. [")]
  163. [ \t]*
  164. )? # title is optional
  165. (?:\n+|\Z)
  166. }xm',
  167. '_StripLinkDefinitions_callback',
  168. $text);
  169. return $text;
  170. }
  171. function _StripLinkDefinitions_callback($matches) {
  172. global $md_urls, $md_titles;
  173. $link_id = strtolower($matches[1]);
  174. $md_urls[$link_id] = _EncodeAmpsAndAngles($matches[2]);
  175. if (isset($matches[3]))
  176. $md_titles[$link_id] = str_replace('"', '&quot;', $matches[3]);
  177. return ''; # String that will replace the block
  178. }
  179. function _HashHTMLBlocks($text) {
  180. global $md_tab_width;
  181. $less_than_tab = $md_tab_width - 1;
  182. # Hashify HTML blocks:
  183. # We only want to do this for block-level HTML tags, such as headers,
  184. # lists, and tables. That's because we still want to wrap <p>s around
  185. # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  186. # phrase emphasis, and spans. The list of tags we're looking for is
  187. # hard-coded:
  188. $block_tags_a = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|'.
  189. 'script|noscript|form|fieldset|iframe|math|ins|del';
  190. $block_tags_b = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|'.
  191. 'script|noscript|form|fieldset|iframe|math';
  192. # First, look for nested blocks, e.g.:
  193. # <div>
  194. # <div>
  195. # tags for inner block must be indented.
  196. # </div>
  197. # </div>
  198. #
  199. # The outermost tags must start at the left margin for this to match, and
  200. # the inner nested divs must be indented.
  201. # We need to do this before the next, more liberal match, because the next
  202. # match will start at the first `<div>` and stop at the first `</div>`.
  203. $text = preg_replace_callback("{
  204. ( # save in $1
  205. ^ # start of line (with /m)
  206. <($block_tags_a) # start tag = $2
  207. \\b # word break
  208. (.*\\n)*? # any number of lines, minimally matching
  209. </\\2> # the matching end tag
  210. [ \\t]* # trailing spaces/tabs
  211. (?=\\n+|\\Z) # followed by a newline or end of document
  212. )
  213. }xm",
  214. '_HashHTMLBlocks_callback',
  215. $text);
  216. #
  217. # Now match more liberally, simply from `\n<tag>` to `</tag>\n`
  218. #
  219. $text = preg_replace_callback("{
  220. ( # save in $1
  221. ^ # start of line (with /m)
  222. <($block_tags_b) # start tag = $2
  223. \\b # word break
  224. (.*\\n)*? # any number of lines, minimally matching
  225. .*</\\2> # the matching end tag
  226. [ \\t]* # trailing spaces/tabs
  227. (?=\\n+|\\Z) # followed by a newline or end of document
  228. )
  229. }xm",
  230. '_HashHTMLBlocks_callback',
  231. $text);
  232. # Special case just for <hr />. It was easier to make a special case than
  233. # to make the other regex more complicated.
  234. $text = preg_replace_callback('{
  235. (?:
  236. (?<=\n\n) # Starting after a blank line
  237. | # or
  238. \A\n? # the beginning of the doc
  239. )
  240. ( # save in $1
  241. [ ]{0,'.$less_than_tab.'}
  242. <(hr) # start tag = $2
  243. \b # word break
  244. ([^<>])*? #
  245. /?> # the matching end tag
  246. [ \t]*
  247. (?=\n{2,}|\Z) # followed by a blank line or end of document
  248. )
  249. }x',
  250. '_HashHTMLBlocks_callback',
  251. $text);
  252. # Special case for standalone HTML comments:
  253. $text = preg_replace_callback('{
  254. (?:
  255. (?<=\n\n) # Starting after a blank line
  256. | # or
  257. \A\n? # the beginning of the doc
  258. )
  259. ( # save in $1
  260. [ ]{0,'.$less_than_tab.'}
  261. (?s:
  262. <!
  263. (--.*?--\s*)+
  264. >
  265. )
  266. [ \t]*
  267. (?=\n{2,}|\Z) # followed by a blank line or end of document
  268. )
  269. }x',
  270. '_HashHTMLBlocks_callback',
  271. $text);
  272. return $text;
  273. }
  274. function _HashHTMLBlocks_callback($matches) {
  275. global $md_html_blocks;
  276. $text = $matches[1];
  277. $key = md5($text);
  278. $md_html_blocks[$key] = $text;
  279. return "\n\n$key\n\n"; # String that will replace the block
  280. }
  281. function _RunBlockGamut($text) {
  282. #
  283. # These are all the transformations that form block-level
  284. # tags like paragraphs, headers, and list items.
  285. #
  286. global $md_empty_element_suffix;
  287. $text = _DoHeaders($text);
  288. # Do Horizontal Rules:
  289. $text = preg_replace(
  290. array('{^[ ]{0,2}([ ]?\*[ ]?){3,}[ \t]*$}mx',
  291. '{^[ ]{0,2}([ ]? -[ ]?){3,}[ \t]*$}mx',
  292. '{^[ ]{0,2}([ ]? _[ ]?){3,}[ \t]*$}mx'),
  293. "\n<hr$md_empty_element_suffix\n",
  294. $text);
  295. $text = _DoLists($text);
  296. $text = _DoCodeBlocks($text);
  297. $text = _DoBlockQuotes($text);
  298. # We already ran _HashHTMLBlocks() before, in Markdown(), but that
  299. # was to escape raw HTML in the original Markdown source. This time,
  300. # we're escaping the markup we've just created, so that we don't wrap
  301. # <p> tags around block-level tags.
  302. $text = _HashHTMLBlocks($text);
  303. $text = _FormParagraphs($text);
  304. return $text;
  305. }
  306. function _RunSpanGamut($text) {
  307. #
  308. # These are all the transformations that occur *within* block-level
  309. # tags like paragraphs, headers, and list items.
  310. #
  311. global $md_empty_element_suffix;
  312. $text = _DoCodeSpans($text);
  313. $text = _EscapeSpecialChars($text);
  314. # Process anchor and image tags. Images must come first,
  315. # because ![foo][f] looks like an anchor.
  316. $text = _DoImages($text);
  317. $text = _DoAnchors($text);
  318. # Make links out of things like `<http://example.com/>`
  319. # Must come after _DoAnchors(), because you can use < and >
  320. # delimiters in inline links like [this](<url>).
  321. $text = _DoAutoLinks($text);
  322. # Fix unencoded ampersands and <'s:
  323. $text = _EncodeAmpsAndAngles($text);
  324. $text = _DoItalicsAndBold($text);
  325. # Do hard breaks:
  326. $text = preg_replace('/ {2,}\n/', "<br$md_empty_element_suffix\n", $text);
  327. return $text;
  328. }
  329. function _EscapeSpecialChars($text) {
  330. global $md_escape_table;
  331. $tokens = _TokenizeHTML($text);
  332. $text = ''; # rebuild $text from the tokens
  333. # $in_pre = 0; # Keep track of when we're inside <pre> or <code> tags.
  334. # $tags_to_skip = "!<(/?)(?:pre|code|kbd|script|math)[\s>]!";
  335. foreach ($tokens as $cur_token) {
  336. if ($cur_token[0] == 'tag') {
  337. # Within tags, encode * and _ so they don't conflict
  338. # with their use in Markdown for italics and strong.
  339. # We're replacing each such character with its
  340. # corresponding MD5 checksum value; this is likely
  341. # overkill, but it should prevent us from colliding
  342. # with the escape values by accident.
  343. $cur_token[1] = str_replace(array('*', '_'),
  344. array($md_escape_table['*'], $md_escape_table['_']),
  345. $cur_token[1]);
  346. $text .= $cur_token[1];
  347. } else {
  348. $t = $cur_token[1];
  349. $t = _EncodeBackslashEscapes($t);
  350. $text .= $t;
  351. }
  352. }
  353. return $text;
  354. }
  355. function _DoAnchors($text) {
  356. #
  357. # Turn Markdown link shortcuts into XHTML <a> tags.
  358. #
  359. global $md_nested_brackets;
  360. #
  361. # First, handle reference-style links: [link text] [id]
  362. #
  363. $text = preg_replace_callback("{
  364. ( # wrap whole match in $1
  365. \\[
  366. ($md_nested_brackets) # link text = $2
  367. \\]
  368. [ ]? # one optional space
  369. (?:\\n[ ]*)? # one optional newline followed by spaces
  370. \\[
  371. (.*?) # id = $3
  372. \\]
  373. )
  374. }xs",
  375. '_DoAnchors_reference_callback', $text);
  376. #
  377. # Next, inline-style links: [link text](url "optional title")
  378. #
  379. $text = preg_replace_callback("{
  380. ( # wrap whole match in $1
  381. \\[
  382. ($md_nested_brackets) # link text = $2
  383. \\]
  384. \\( # literal paren
  385. [ \\t]*
  386. <?(.*?)>? # href = $3
  387. [ \\t]*
  388. ( # $4
  389. (['\"]) # quote char = $5
  390. (.*?) # Title = $6
  391. \\5 # matching quote
  392. )? # title is optional
  393. \\)
  394. )
  395. }xs",
  396. '_DoAnchors_inline_callback', $text);
  397. return $text;
  398. }
  399. function _DoAnchors_reference_callback($matches) {
  400. global $md_urls, $md_titles, $md_escape_table;
  401. $whole_match = $matches[1];
  402. $link_text = $matches[2];
  403. $link_id = strtolower($matches[3]);
  404. if ($link_id == "") {
  405. $link_id = strtolower($link_text); # for shortcut links like [this][].
  406. }
  407. if (isset($md_urls[$link_id])) {
  408. $url = $md_urls[$link_id];
  409. # We've got to encode these to avoid conflicting with italics/bold.
  410. $url = str_replace(array('*', '_'),
  411. array($md_escape_table['*'], $md_escape_table['_']),
  412. $url);
  413. $result = "<a href=\"$url\"";
  414. if ( isset( $md_titles[$link_id] ) ) {
  415. $title = $md_titles[$link_id];
  416. $title = str_replace(array('*', '_'),
  417. array($md_escape_table['*'],
  418. $md_escape_table['_']), $title);
  419. $result .= " title=\"$title\"";
  420. }
  421. $result .= ">$link_text</a>";
  422. }
  423. else {
  424. $result = $whole_match;
  425. }
  426. return $result;
  427. }
  428. function _DoAnchors_inline_callback($matches) {
  429. global $md_escape_table;
  430. $whole_match = $matches[1];
  431. $link_text = $matches[2];
  432. $url = $matches[3];
  433. $title =& $matches[6];
  434. # We've got to encode these to avoid conflicting with italics/bold.
  435. $url = str_replace(array('*', '_'),
  436. array($md_escape_table['*'], $md_escape_table['_']),
  437. $url);
  438. $result = "<a href=\"$url\"";
  439. if (isset($title)) {
  440. $title = str_replace('"', '&quot;', $title);
  441. $title = str_replace(array('*', '_'),
  442. array($md_escape_table['*'], $md_escape_table['_']),
  443. $title);
  444. $result .= " title=\"$title\"";
  445. }
  446. $result .= ">$link_text</a>";
  447. return $result;
  448. }
  449. function _DoImages($text) {
  450. #
  451. # Turn Markdown image shortcuts into <img> tags.
  452. #
  453. #
  454. # First, handle reference-style labeled images: ![alt text][id]
  455. #
  456. $text = preg_replace_callback('{
  457. ( # wrap whole match in $1
  458. !\[
  459. (.*?) # alt text = $2
  460. \]
  461. [ ]? # one optional space
  462. (?:\n[ ]*)? # one optional newline followed by spaces
  463. \[
  464. (.*?) # id = $3
  465. \]
  466. )
  467. }xs',
  468. '_DoImages_reference_callback', $text);
  469. #
  470. # Next, handle inline images: ![alt text](url "optional title")
  471. # Don't forget: encode * and _
  472. $text = preg_replace_callback("{
  473. ( # wrap whole match in $1
  474. !\\[
  475. (.*?) # alt text = $2
  476. \\]
  477. \\( # literal paren
  478. [ \\t]*
  479. <?(\S+?)>? # src url = $3
  480. [ \\t]*
  481. ( # $4
  482. (['\"]) # quote char = $5
  483. (.*?) # title = $6
  484. \\5 # matching quote
  485. [ \\t]*
  486. )? # title is optional
  487. \\)
  488. )
  489. }xs",
  490. '_DoImages_inline_callback', $text);
  491. return $text;
  492. }
  493. function _DoImages_reference_callback($matches) {
  494. global $md_urls, $md_titles, $md_empty_element_suffix, $md_escape_table;
  495. $whole_match = $matches[1];
  496. $alt_text = $matches[2];
  497. $link_id = strtolower($matches[3]);
  498. if ($link_id == "") {
  499. $link_id = strtolower($alt_text); # for shortcut links like ![this][].
  500. }
  501. $alt_text = str_replace('"', '&quot;', $alt_text);
  502. if (isset($md_urls[$link_id])) {
  503. $url = $md_urls[$link_id];
  504. # We've got to encode these to avoid conflicting with italics/bold.
  505. $url = str_replace(array('*', '_'),
  506. array($md_escape_table['*'], $md_escape_table['_']),
  507. $url);
  508. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  509. if (isset($md_titles[$link_id])) {
  510. $title = $md_titles[$link_id];
  511. $title = str_replace(array('*', '_'),
  512. array($md_escape_table['*'],
  513. $md_escape_table['_']), $title);
  514. $result .= " title=\"$title\"";
  515. }
  516. $result .= $md_empty_element_suffix;
  517. }
  518. else {
  519. # If there's no such link ID, leave intact:
  520. $result = $whole_match;
  521. }
  522. return $result;
  523. }
  524. function _DoImages_inline_callback($matches) {
  525. global $md_empty_element_suffix, $md_escape_table;
  526. $whole_match = $matches[1];
  527. $alt_text = $matches[2];
  528. $url = $matches[3];
  529. $title = '';
  530. if (isset($matches[6])) {
  531. $title = $matches[6];
  532. }
  533. $alt_text = str_replace('"', '&quot;', $alt_text);
  534. $title = str_replace('"', '&quot;', $title);
  535. # We've got to encode these to avoid conflicting with italics/bold.
  536. $url = str_replace(array('*', '_'),
  537. array($md_escape_table['*'], $md_escape_table['_']),
  538. $url);
  539. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  540. if (isset($title)) {
  541. $title = str_replace(array('*', '_'),
  542. array($md_escape_table['*'], $md_escape_table['_']),
  543. $title);
  544. $result .= " title=\"$title\""; # $title already quoted
  545. }
  546. $result .= $md_empty_element_suffix;
  547. return $result;
  548. }
  549. function _DoHeaders($text) {
  550. # Setext-style headers:
  551. # Header 1
  552. # ========
  553. #
  554. # Header 2
  555. # --------
  556. #
  557. $text = preg_replace(
  558. array('{ ^(.+)[ \t]*\n=+[ \t]*\n+ }emx',
  559. '{ ^(.+)[ \t]*\n-+[ \t]*\n+ }emx'),
  560. array("'<h1>'._RunSpanGamut(_UnslashQuotes('\\1')).'</h1>\n\n'",
  561. "'<h2>'._RunSpanGamut(_UnslashQuotes('\\1')).'</h2>\n\n'"),
  562. $text);
  563. # atx-style headers:
  564. # # Header 1
  565. # ## Header 2
  566. # ## Header 2 with closing hashes ##
  567. # ...
  568. # ###### Header 6
  569. #
  570. $text = preg_replace("{
  571. ^(\\#{1,6}) # $1 = string of #'s
  572. [ \\t]*
  573. (.+?) # $2 = Header text
  574. [ \\t]*
  575. \\#* # optional closing #'s (not counted)
  576. \\n+
  577. }xme",
  578. "'<h'.strlen('\\1').'>'._RunSpanGamut(_UnslashQuotes('\\2')).'</h'.strlen('\\1').'>\n\n'",
  579. $text);
  580. return $text;
  581. }
  582. function _DoLists($text) {
  583. #
  584. # Form HTML ordered (numbered) and unordered (bulleted) lists.
  585. #
  586. global $md_tab_width, $md_list_level;
  587. $less_than_tab = $md_tab_width - 1;
  588. # Re-usable patterns to match list item bullets and number markers:
  589. $marker_ul = '[*+-]';
  590. $marker_ol = '\d+[.]';
  591. $marker_any = "(?:$marker_ul|$marker_ol)";
  592. # Re-usable pattern to match any entirel ul or ol list:
  593. $whole_list = '
  594. ( # $1 = whole list
  595. ( # $2
  596. [ ]{0,'.$less_than_tab.'}
  597. ('.$marker_any.') # $3 = first list item marker
  598. [ \t]+
  599. )
  600. (?s:.+?)
  601. ( # $4
  602. \z
  603. |
  604. \n{2,}
  605. (?=\S)
  606. (?! # Negative lookahead for another list item marker
  607. [ \t]*
  608. '.$marker_any.'[ \t]+
  609. )
  610. )
  611. )
  612. '; // mx
  613. # We use a different prefix before nested lists than top-level lists.
  614. # See extended comment in _ProcessListItems().
  615. if ($md_list_level) {
  616. $text = preg_replace_callback('{
  617. ^
  618. '.$whole_list.'
  619. }mx',
  620. '_DoLists_callback', $text);
  621. }
  622. else {
  623. $text = preg_replace_callback('{
  624. (?:(?<=\n\n)|\A\n?)
  625. '.$whole_list.'
  626. }mx',
  627. '_DoLists_callback', $text);
  628. }
  629. return $text;
  630. }
  631. function _DoLists_callback($matches) {
  632. # Re-usable patterns to match list item bullets and number markers:
  633. $marker_ul = '[*+-]';
  634. $marker_ol = '\d+[.]';
  635. $marker_any = "(?:$marker_ul|$marker_ol)";
  636. $list = $matches[1];
  637. $list_type = preg_match("/$marker_ul/", $matches[3]) ? "ul" : "ol";
  638. # Turn double returns into triple returns, so that we can make a
  639. # paragraph for the last item in a list, if necessary:
  640. $list = preg_replace("/\n{2,}/", "\n\n\n", $list);
  641. $result = _ProcessListItems($list, $marker_any);
  642. $result = "<$list_type>\n" . $result . "</$list_type>\n";
  643. return $result;
  644. }
  645. function _ProcessListItems($list_str, $marker_any) {
  646. #
  647. # Process the contents of a single ordered or unordered list, splitting it
  648. # into individual list items.
  649. #
  650. global $md_list_level;
  651. # The $md_list_level global keeps track of when we're inside a list.
  652. # Each time we enter a list, we increment it; when we leave a list,
  653. # we decrement. If it's zero, we're not in a list anymore.
  654. #
  655. # We do this because when we're not inside a list, we want to treat
  656. # something like this:
  657. #
  658. # I recommend upgrading to version
  659. # 8. Oops, now this line is treated
  660. # as a sub-list.
  661. #
  662. # As a single paragraph, despite the fact that the second line starts
  663. # with a digit-period-space sequence.
  664. #
  665. # Whereas when we're inside a list (or sub-list), that line will be
  666. # treated as the start of a sub-list. What a kludge, huh? This is
  667. # an aspect of Markdown's syntax that's hard to parse perfectly
  668. # without resorting to mind-reading. Perhaps the solution is to
  669. # change the syntax rules such that sub-lists must start with a
  670. # starting cardinal number; e.g. "1." or "a.".
  671. $md_list_level++;
  672. # trim trailing blank lines:
  673. $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
  674. $list_str = preg_replace_callback('{
  675. (\n)? # leading line = $1
  676. (^[ \t]*) # leading whitespace = $2
  677. ('.$marker_any.') [ \t]+ # list marker = $3
  678. ((?s:.+?) # list item text = $4
  679. (\n{1,2}))
  680. (?= \n* (\z | \2 ('.$marker_any.') [ \t]+))
  681. }xm',
  682. '_ProcessListItems_callback', $list_str);
  683. $md_list_level--;
  684. return $list_str;
  685. }
  686. function _ProcessListItems_callback($matches) {
  687. $item = $matches[4];
  688. $leading_line =& $matches[1];
  689. $leading_space =& $matches[2];
  690. if ($leading_line || preg_match('/\n{2,}/', $item)) {
  691. $item = _RunBlockGamut(_Outdent($item));
  692. }
  693. else {
  694. # Recursion for sub-lists:
  695. $item = _DoLists(_Outdent($item));
  696. $item = rtrim($item, "\n");
  697. $item = _RunSpanGamut($item);
  698. }
  699. return "<li>" . $item . "</li>\n";
  700. }
  701. function _DoCodeBlocks($text) {
  702. #
  703. # Process Markdown `<pre><code>` blocks.
  704. #
  705. global $md_tab_width;
  706. $text = preg_replace_callback("{
  707. (?:\\n\\n|\\A)
  708. ( # $1 = the code block -- one or more lines, starting with a space/tab
  709. (?:
  710. (?:[ ]\{$md_tab_width} | \\t) # Lines must start with a tab or a tab-width of spaces
  711. .*\\n+
  712. )+
  713. )
  714. ((?=^[ ]{0,$md_tab_width}\\S)|\\Z) # Lookahead for non-space at line-start, or end of doc
  715. }xm",
  716. '_DoCodeBlocks_callback', $text);
  717. return $text;
  718. }
  719. function _DoCodeBlocks_callback($matches) {
  720. $codeblock = $matches[1];
  721. $codeblock = _EncodeCode(_Outdent($codeblock));
  722. // $codeblock = _Detab($codeblock);
  723. # trim leading newlines and trailing whitespace
  724. $codeblock = preg_replace(array('/\A\n+/', '/\s+\z/'), '', $codeblock);
  725. $result = "\n\n<pre><code>" . $codeblock . "\n</code></pre>\n\n";
  726. return $result;
  727. }
  728. function _DoCodeSpans($text) {
  729. #
  730. # * Backtick quotes are used for <code></code> spans.
  731. #
  732. # * You can use multiple backticks as the delimiters if you want to
  733. # include literal backticks in the code span. So, this input:
  734. #
  735. # Just type ``foo `bar` baz`` at the prompt.
  736. #
  737. # Will translate to:
  738. #
  739. # <p>Just type <code>foo `bar` baz</code> at the prompt.</p>
  740. #
  741. # There's no arbitrary limit to the number of backticks you
  742. # can use as delimters. If you need three consecutive backticks
  743. # in your code, use four for delimiters, etc.
  744. #
  745. # * You can use spaces to get literal backticks at the edges:
  746. #
  747. # ... type `` `bar` `` ...
  748. #
  749. # Turns to:
  750. #
  751. # ... type <code>`bar`</code> ...
  752. #
  753. $text = preg_replace_callback("@
  754. (`+) # $1 = Opening run of `
  755. (.+?) # $2 = The code block
  756. (?<!`)
  757. \\1
  758. (?!`)
  759. @xs",
  760. '_DoCodeSpans_callback', $text);
  761. return $text;
  762. }
  763. function _DoCodeSpans_callback($matches) {
  764. $c = $matches[2];
  765. $c = preg_replace('/^[ \t]*/', '', $c); # leading whitespace
  766. $c = preg_replace('/[ \t]*$/', '', $c); # trailing whitespace
  767. $c = _EncodeCode($c);
  768. return "<code>$c</code>";
  769. }
  770. function _EncodeCode($_) {
  771. #
  772. # Encode/escape certain characters inside Markdown code runs.
  773. # The point is that in code, these characters are literals,
  774. # and lose their special Markdown meanings.
  775. #
  776. global $md_escape_table;
  777. # Encode all ampersands; HTML entities are not
  778. # entities within a Markdown code span.
  779. $_ = str_replace('&', '&amp;', $_);
  780. # Do the angle bracket song and dance:
  781. $_ = str_replace(array('<', '>'),
  782. array('&lt;', '&gt;'), $_);
  783. # Now, escape characters that are magic in Markdown:
  784. $_ = str_replace(array_keys($md_escape_table),
  785. array_values($md_escape_table), $_);
  786. return $_;
  787. }
  788. function _DoItalicsAndBold($text) {
  789. # <strong> must go first:
  790. $text = preg_replace('{ (\*\*|__) (?=\S) (.+?[*_]*) (?<=\S) \1 }sx',
  791. '<strong>\2</strong>', $text);
  792. # Then <em>:
  793. $text = preg_replace('{ (\*|_) (?=\S) (.+?) (?<=\S) \1 }sx',
  794. '<em>\2</em>', $text);
  795. return $text;
  796. }
  797. function _DoBlockQuotes($text) {
  798. $text = preg_replace_callback('/
  799. ( # Wrap whole match in $1
  800. (
  801. ^[ \t]*>[ \t]? # ">" at the start of a line
  802. .+\n # rest of the first line
  803. (.+\n)* # subsequent consecutive lines
  804. \n* # blanks
  805. )+
  806. )
  807. /xm',
  808. '_DoBlockQuotes_callback', $text);
  809. return $text;
  810. }
  811. function _DoBlockQuotes_callback($matches) {
  812. $bq = $matches[1];
  813. # trim one level of quoting - trim whitespace-only lines
  814. $bq = preg_replace(array('/^[ \t]*>[ \t]?/m', '/^[ \t]+$/m'), '', $bq);
  815. $bq = _RunBlockGamut($bq); # recurse
  816. $bq = preg_replace('/^/m', " ", $bq);
  817. # These leading spaces screw with <pre> content, so we need to fix that:
  818. $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx',
  819. '_DoBlockQuotes_callback2', $bq);
  820. return "<blockquote>\n$bq\n</blockquote>\n\n";
  821. }
  822. function _DoBlockQuotes_callback2($matches) {
  823. $pre = $matches[1];
  824. $pre = preg_replace('/^ /m', '', $pre);
  825. return $pre;
  826. }
  827. function _FormParagraphs($text) {
  828. #
  829. # Params:
  830. # $text - string to process with html <p> tags
  831. #
  832. global $md_html_blocks;
  833. # Strip leading and trailing lines:
  834. $text = preg_replace(array('/\A\n+/', '/\n+\z/'), '', $text);
  835. $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
  836. #
  837. # Wrap <p> tags.
  838. #
  839. foreach ($grafs as $key => $value) {
  840. if (!isset( $md_html_blocks[$value] )) {
  841. $value = _RunSpanGamut($value);
  842. $value = preg_replace('/^([ \t]*)/', '<p>', $value);
  843. $value .= "</p>";
  844. $grafs[$key] = $value;
  845. }
  846. }
  847. #
  848. # Unhashify HTML blocks
  849. #
  850. foreach ($grafs as $key => $value) {
  851. if (isset( $md_html_blocks[$value] )) {
  852. $grafs[$key] = $md_html_blocks[$value];
  853. }
  854. }
  855. return implode("\n\n", $grafs);
  856. }
  857. function _EncodeAmpsAndAngles($text) {
  858. # Smart processing for ampersands and angle brackets that need to be encoded.
  859. # Ampersand-encoding based entirely on Nat Irons's Amputator MT plugin:
  860. # http://bumppo.net/projects/amputator/
  861. $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
  862. '&amp;', $text);;
  863. # Encode naked <'s
  864. $text = preg_replace('{<(?![a-z/?\$!])}i', '&lt;', $text);
  865. return $text;
  866. }
  867. function _EncodeBackslashEscapes($text) {
  868. #
  869. # Parameter: String.
  870. # Returns: The string, with after processing the following backslash
  871. # escape sequences.
  872. #
  873. global $md_escape_table, $md_backslash_escape_table;
  874. # Must process escaped backslashes first.
  875. return str_replace(array_keys($md_backslash_escape_table),
  876. array_values($md_backslash_escape_table), $text);
  877. }
  878. function _DoAutoLinks($text) {
  879. $text = preg_replace("!<((https?|ftp):[^'\">\\s]+)>!",
  880. '<a href="\1">\1</a>', $text);
  881. # Email addresses: <address@domain.foo>
  882. $text = preg_replace('{
  883. <
  884. (?:mailto:)?
  885. (
  886. [-.\w]+
  887. \@
  888. [-a-z0-9]+(\.[-a-z0-9]+)*\.[a-z]+
  889. )
  890. >
  891. }exi',
  892. "_EncodeEmailAddress(_UnescapeSpecialChars(_UnslashQuotes('\\1')))",
  893. $text);
  894. return $text;
  895. }
  896. function _EncodeEmailAddress($addr) {
  897. #
  898. # Input: an email address, e.g. "foo@example.com"
  899. #
  900. # Output: the email address as a mailto link, with each character
  901. # of the address encoded as either a decimal or hex entity, in
  902. # the hopes of foiling most address harvesting spam bots. E.g.:
  903. #
  904. # <a href="&#x6D;&#97;&#105;&#108;&#x74;&#111;:&#102;&#111;&#111;&#64;&#101;
  905. # x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;">&#102;&#111;&#111;
  906. # &#64;&#101;x&#x61;&#109;&#x70;&#108;&#x65;&#x2E;&#99;&#111;&#109;</a>
  907. #
  908. # Based by a filter by Matthew Wickline, posted to the BBEdit-Talk
  909. # mailing list: <http://tinyurl.com/yu7ue>
  910. #
  911. $addr = "mailto:" . $addr;
  912. $length = strlen($addr);
  913. # leave ':' alone (to spot mailto: later)
  914. $addr = preg_replace_callback('/([^\:])/',
  915. '_EncodeEmailAddress_callback', $addr);
  916. $addr = "<a href=\"$addr\">$addr</a>";
  917. # strip the mailto: from the visible part
  918. $addr = preg_replace('/">.+?:/', '">', $addr);
  919. return $addr;
  920. }
  921. function _EncodeEmailAddress_callback($matches) {
  922. $char = $matches[1];
  923. $r = rand(0, 100);
  924. # roughly 10% raw, 45% hex, 45% dec
  925. # '@' *must* be encoded. I insist.
  926. if ($r > 90 && $char != '@') return $char;
  927. if ($r < 45) return '&#x'.dechex(ord($char)).';';
  928. return '&#'.ord($char).';';
  929. }
  930. function _UnescapeSpecialChars($text) {
  931. #
  932. # Swap back in all the special characters we've hidden.
  933. #
  934. global $md_escape_table;
  935. return str_replace(array_values($md_escape_table),
  936. array_keys($md_escape_table), $text);
  937. }
  938. # _TokenizeHTML is shared between PHP Markdown and PHP SmartyPants.
  939. # We only define it if it is not already defined.
  940. if (!function_exists('_TokenizeHTML')) :
  941. function _TokenizeHTML($str) {
  942. #
  943. # Parameter: String containing HTML markup.
  944. # Returns: An array of the tokens comprising the input
  945. # string. Each token is either a tag (possibly with nested,
  946. # tags contained therein, such as <a href="<MTFoo>">, or a
  947. # run of text between tags. Each element of the array is a
  948. # two-element array; the first is either 'tag' or 'text';
  949. # the second is the actual value.
  950. #
  951. #
  952. # Regular expression derived from the _tokenize() subroutine in
  953. # Brad Choate's MTRegex plugin.
  954. # <http://www.bradchoate.com/past/mtregex.php>
  955. #
  956. $index = 0;
  957. $tokens = array();
  958. $match = '(?s:<!(?:--.*?--\s*)+>)|'. # comment
  959. '(?s:<\?.*?\?>)|'. # processing instruction
  960. '(?:</?[\w:$]+\b(?>[^"\'>]+|"[^"]*"|\'[^\']*\')*>)'; # regular tags
  961. $parts = preg_split("{($match)}", $str, -1, PREG_SPLIT_DELIM_CAPTURE);
  962. foreach ($parts as $part) {
  963. if (++$index % 2 && $part != '')
  964. array_push($tokens, array('text', $part));
  965. else
  966. array_push($tokens, array('tag', $part));
  967. }
  968. return $tokens;
  969. }
  970. endif;
  971. function _Outdent($text) {
  972. #
  973. # Remove one level of line-leading tabs or spaces
  974. #
  975. global $md_tab_width;
  976. return preg_replace("/^(\\t|[ ]{1,$md_tab_width})/m", "", $text);
  977. }
  978. function _Detab($text) {
  979. #
  980. # Replace tabs with the appropriate amount of space.
  981. #
  982. global $md_tab_width;
  983. # For each line we separate the line in blocks delemited by
  984. # tab characters. Then we reconstruct the line adding the appropriate
  985. # number of space charcters.
  986. $lines = explode("\n", $text);
  987. $text = "";
  988. foreach ($lines as $line) {
  989. # Split in blocks.
  990. $blocks = explode("\t", $line);
  991. # Add each blocks to the line.
  992. $line = $blocks[0];
  993. unset($blocks[0]); # Do not add first block twice.
  994. foreach ($blocks as $block) {
  995. # Calculate amount of space, insert spaces, insert block.
  996. $amount = $md_tab_width - strlen($line) % $md_tab_width;
  997. $line .= str_repeat(" ", $amount) . $block;
  998. }
  999. $text .= "$line\n";
  1000. }
  1001. return $text;
  1002. }
  1003. function _UnslashQuotes($text) {
  1004. #
  1005. # This function is useful to remove automaticaly slashed double quotes
  1006. # when using preg_replace and evaluating an expression.
  1007. # Parameter: String.
  1008. # Returns: The string with any slash-double-quote (\") sequence replaced
  1009. # by a single double quote.
  1010. #
  1011. return str_replace('\"', '"', $text);
  1012. }
  1013. /*
  1014. PHP Markdown
  1015. ============
  1016. Description
  1017. -----------
  1018. This is a PHP translation of the original Markdown formatter written in
  1019. Perl by John Gruber.
  1020. Markdown is a text-to-HTML filter; it translates an easy-to-read /
  1021. easy-to-write structured text format into HTML. Markdown's text format
  1022. is most similar to that of plain text email, and supports features such
  1023. as headers, *emphasis*, code blocks, blockquotes, and links.
  1024. Markdown's syntax is designed not as a generic markup language, but
  1025. specifically to serve as a front-end to (X)HTML. You can use span-level
  1026. HTML tags anywhere in a Markdown document, and you can use block level
  1027. HTML tags (like <div> and <table> as well).
  1028. For more information about Markdown's syntax, see:
  1029. <http://daringfireball.net/projects/markdown/>
  1030. Bugs
  1031. ----
  1032. To file bug reports please send email to:
  1033. <michel.fortin@michelf.com>
  1034. Please include with your report: (1) the example input; (2) the output you
  1035. expected; (3) the output Markdown actually produced.
  1036. Version History
  1037. ---------------
  1038. See the readme file for detailed release notes for this version.
  1039. 1.0.1 - 17 Dec 2004
  1040. 1.0 - 21 Aug 2004
  1041. Author & Contributors
  1042. ---------------------
  1043. Original Perl version by John Gruber
  1044. <http://daringfireball.net/>
  1045. PHP port and other contributions by Michel Fortin
  1046. <http://www.michelf.com/>
  1047. Copyright and License
  1048. ---------------------
  1049. Copyright (c) 2004 Michel Fortin
  1050. <http://www.michelf.com/>
  1051. All rights reserved.
  1052. Copyright (c) 2003-2004 John Gruber
  1053. <http://daringfireball.net/>
  1054. All rights reserved.
  1055. Redistribution and use in source and binary forms, with or without
  1056. modification, are permitted provided that the following conditions are
  1057. met:
  1058. * Redistributions of source code must retain the above copyright notice,
  1059. this list of conditions and the following disclaimer.
  1060. * Redistributions in binary form must reproduce the above copyright
  1061. notice, this list of conditions and the following disclaimer in the
  1062. documentation and/or other materials provided with the distribution.
  1063. * Neither the name "Markdown" nor the names of its contributors may
  1064. be used to endorse or promote products derived from this software
  1065. without specific prior written permission.
  1066. This software is provided by the copyright holders and contributors "as
  1067. is" and any express or implied warranties, including, but not limited
  1068. to, the implied warranties of merchantability and fitness for a
  1069. particular purpose are disclaimed. In no event shall the copyright owner
  1070. or contributors be liable for any direct, indirect, incidental, special,
  1071. exemplary, or consequential damages (including, but not limited to,
  1072. procurement of substitute goods or services; loss of use, data, or
  1073. profits; or business interruption) however caused and on any theory of
  1074. liability, whether in contract, strict liability, or tort (including
  1075. negligence or otherwise) arising in any way out of the use of this
  1076. software, even if advised of the possibility of such damage.
  1077. */
  1078. ?>