PageRenderTime 29ms CodeModel.GetById 23ms RepoModel.GetById 1ms app.codeStats 0ms

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

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