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

/bonfire/helpers/markdown_helper.php

http://github.com/ci-bonfire/Bonfire
PHP | 3383 lines | 2188 code | 371 blank | 824 comment | 212 complexity | d7b525f0db0ae09a964e0e474e273aca 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. * Bonfire
  4. *
  5. * An open source project to allow developers to jumpstart their development of
  6. * CodeIgniter applications.
  7. *
  8. * @package Bonfire
  9. * @author Bonfire Dev Team
  10. * @copyright Copyright (c) 2011 - 2018, Bonfire Dev Team
  11. * @license http://opensource.org/licenses/MIT The MIT License.
  12. * @link http://cibonfire.com
  13. * @since 0.7.2
  14. * @filesource
  15. */
  16. /**
  17. * Markdown Extra Helper
  18. *
  19. * @deprecated since 0.9.0. Use Bonfire's CommonMark library with one of the drivers
  20. * in /application/libraries/CommonMark/drivers/
  21. * @see https://github.com/ci-bonfire/Bonfire/blob/develop/bonfire/docs/commonmark.md
  22. *
  23. * This is here primarily for backwards compatibility, and has been updated only
  24. * because it should be kept up to date until it is removed.
  25. *
  26. * This is PHP Markdown / classic version
  27. * @link https://michelf.ca/projects/php-markdown/classic/
  28. *
  29. * @package Bonfire\Helpers\markdown_helper
  30. * @author Bonfire Dev Team
  31. * @author Michel Fortin
  32. * @author John Gruber
  33. * @link https://github.com/michelf/php-markdown/
  34. * @link https://github.com/ci-bonfire/Bonfire/blob/develop/bonfire/docs/commonmark.md
  35. */
  36. #
  37. # Markdown Extra - A text-to-HTML conversion tool for web writers
  38. #
  39. # PHP Markdown & Extra
  40. # Copyright (c) 2004-2013 Michel Fortin
  41. # <http://michelf.ca/projects/php-markdown/>
  42. #
  43. # Original Markdown
  44. # Copyright (c) 2004-2006 John Gruber
  45. # <http://daringfireball.net/projects/markdown/>
  46. #
  47. define( 'MARKDOWN_VERSION', "1.0.2" ); # 29 Nov 2013
  48. define( 'MARKDOWNEXTRA_VERSION', "1.2.8" ); # 29 Nov 2013
  49. #
  50. # Global default settings:
  51. #
  52. # Change to ">" for HTML output
  53. @define( 'MARKDOWN_EMPTY_ELEMENT_SUFFIX', " />");
  54. # Define the width of a tab for code blocks.
  55. @define( 'MARKDOWN_TAB_WIDTH', 4 );
  56. # Optional title attribute for footnote links and backlinks.
  57. @define( 'MARKDOWN_FN_LINK_TITLE', "" );
  58. @define( 'MARKDOWN_FN_BACKLINK_TITLE', "" );
  59. # Optional class attribute for footnote links and backlinks.
  60. @define( 'MARKDOWN_FN_LINK_CLASS', "" );
  61. @define( 'MARKDOWN_FN_BACKLINK_CLASS', "" );
  62. # Optional class prefix for fenced code block.
  63. @define( 'MARKDOWN_CODE_CLASS_PREFIX', "" );
  64. # Class attribute for code blocks goes on the `code` tag;
  65. # setting this to true will put attributes on the `pre` tag instead.
  66. @define( 'MARKDOWN_CODE_ATTR_ON_PRE', false );
  67. #
  68. # WordPress settings:
  69. #
  70. # Change to false to remove Markdown from posts and/or comments.
  71. @define( 'MARKDOWN_WP_POSTS', true );
  72. @define( 'MARKDOWN_WP_COMMENTS', true );
  73. ### Standard Function Interface ###
  74. @define( 'MARKDOWN_PARSER_CLASS', 'MarkdownExtra_Parser' );
  75. function Markdown($text) {
  76. #
  77. # Initialize the parser and return the result of its transform method.
  78. #
  79. # Setup static parser variable.
  80. static $parser;
  81. if (!isset($parser)) {
  82. $parser_class = MARKDOWN_PARSER_CLASS;
  83. $parser = new $parser_class;
  84. }
  85. # Transform text using parser.
  86. return $parser->transform($text);
  87. }
  88. ### WordPress Plugin Interface ###
  89. /*
  90. Plugin Name: Markdown Extra
  91. Plugin Name: Markdown
  92. Plugin URI: http://michelf.ca/projects/php-markdown/
  93. Description: <a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by <a href="http://daringfireball.net/">John Gruber</a>. <a href="http://michelf.ca/projects/php-markdown/">More...</a>
  94. Version: 1.2.8
  95. Author: Michel Fortin
  96. Author URI: http://michelf.ca/
  97. */
  98. if (isset($wp_version)) {
  99. # More details about how it works here:
  100. # <http://michelf.ca/weblog/2005/wordpress-text-flow-vs-markdown/>
  101. # Post content and excerpts
  102. # - Remove WordPress paragraph generator.
  103. # - Run Markdown on excerpt, then remove all tags.
  104. # - Add paragraph tag around the excerpt, but remove it for the excerpt rss.
  105. if (MARKDOWN_WP_POSTS) {
  106. remove_filter('the_content', 'wpautop');
  107. remove_filter('the_content_rss', 'wpautop');
  108. remove_filter('the_excerpt', 'wpautop');
  109. add_filter('the_content', 'mdwp_MarkdownPost', 6);
  110. add_filter('the_content_rss', 'mdwp_MarkdownPost', 6);
  111. add_filter('get_the_excerpt', 'mdwp_MarkdownPost', 6);
  112. add_filter('get_the_excerpt', 'trim', 7);
  113. add_filter('the_excerpt', 'mdwp_add_p');
  114. add_filter('the_excerpt_rss', 'mdwp_strip_p');
  115. remove_filter('content_save_pre', 'balanceTags', 50);
  116. remove_filter('excerpt_save_pre', 'balanceTags', 50);
  117. add_filter('the_content', 'balanceTags', 50);
  118. add_filter('get_the_excerpt', 'balanceTags', 9);
  119. }
  120. # Add a footnote id prefix to posts when inside a loop.
  121. function mdwp_MarkdownPost($text) {
  122. static $parser;
  123. if (!$parser) {
  124. $parser_class = MARKDOWN_PARSER_CLASS;
  125. $parser = new $parser_class;
  126. }
  127. if (is_single() || is_page() || is_feed()) {
  128. $parser->fn_id_prefix = "";
  129. } else {
  130. $parser->fn_id_prefix = get_the_ID() . ".";
  131. }
  132. return $parser->transform($text);
  133. }
  134. # Comments
  135. # - Remove WordPress paragraph generator.
  136. # - Remove WordPress auto-link generator.
  137. # - Scramble important tags before passing them to the kses filter.
  138. # - Run Markdown on excerpt then remove paragraph tags.
  139. if (MARKDOWN_WP_COMMENTS) {
  140. remove_filter('comment_text', 'wpautop', 30);
  141. remove_filter('comment_text', 'make_clickable');
  142. add_filter('pre_comment_content', 'Markdown', 6);
  143. add_filter('pre_comment_content', 'mdwp_hide_tags', 8);
  144. add_filter('pre_comment_content', 'mdwp_show_tags', 12);
  145. add_filter('get_comment_text', 'Markdown', 6);
  146. add_filter('get_comment_excerpt', 'Markdown', 6);
  147. add_filter('get_comment_excerpt', 'mdwp_strip_p', 7);
  148. global $mdwp_hidden_tags, $mdwp_placeholders;
  149. $mdwp_hidden_tags = explode(' ',
  150. '<p> </p> <pre> </pre> <ol> </ol> <ul> </ul> <li> </li>');
  151. $mdwp_placeholders = explode(' ', str_rot13(
  152. 'pEj07ZbbBZ U1kqgh4w4p pre2zmeN6K QTi31t9pre ol0MP1jzJR '.
  153. 'ML5IjmbRol ulANi1NsGY J7zRLJqPul liA8ctl16T K9nhooUHli'));
  154. }
  155. function mdwp_add_p($text) {
  156. if (!preg_match('{^$|^<(p|ul|ol|dl|pre|blockquote)>}i', $text)) {
  157. $text = '<p>'.$text.'</p>';
  158. $text = preg_replace('{\n{2,}}', "</p>\n\n<p>", $text);
  159. }
  160. return $text;
  161. }
  162. function mdwp_strip_p($t) { return preg_replace('{</?p>}i', '', $t); }
  163. function mdwp_hide_tags($text) {
  164. global $mdwp_hidden_tags, $mdwp_placeholders;
  165. return str_replace($mdwp_hidden_tags, $mdwp_placeholders, $text);
  166. }
  167. function mdwp_show_tags($text) {
  168. global $mdwp_hidden_tags, $mdwp_placeholders;
  169. return str_replace($mdwp_placeholders, $mdwp_hidden_tags, $text);
  170. }
  171. }
  172. ### bBlog Plugin Info ###
  173. function identify_modifier_markdown() {
  174. return array(
  175. 'name' => 'markdown',
  176. 'type' => 'modifier',
  177. 'nicename' => 'PHP Markdown Extra',
  178. 'description' => 'A text-to-HTML conversion tool for web writers',
  179. 'authors' => 'Michel Fortin and John Gruber',
  180. 'licence' => 'GPL',
  181. 'version' => MARKDOWNEXTRA_VERSION,
  182. 'help' => '<a href="http://daringfireball.net/projects/markdown/syntax">Markdown syntax</a> allows you to write using an easy-to-read, easy-to-write plain text format. Based on the original Perl version by <a href="http://daringfireball.net/">John Gruber</a>. <a href="http://michelf.ca/projects/php-markdown/">More...</a>',
  183. );
  184. }
  185. ### Smarty Modifier Interface ###
  186. function smarty_modifier_markdown($text) {
  187. return Markdown($text);
  188. }
  189. ### Textile Compatibility Mode ###
  190. # Rename this file to "classTextile.php" and it can replace Textile everywhere.
  191. if (strcasecmp(substr(__FILE__, -16), "classTextile.php") == 0) {
  192. # Try to include PHP SmartyPants. Should be in the same directory.
  193. @include_once 'smartypants.php';
  194. # Fake Textile class. It calls Markdown instead.
  195. class Textile {
  196. function TextileThis($text, $lite='', $encode='') {
  197. if ($lite == '' && $encode == '') $text = Markdown($text);
  198. if (function_exists('SmartyPants')) $text = SmartyPants($text);
  199. return $text;
  200. }
  201. # Fake restricted version: restrictions are not supported for now.
  202. function TextileRestricted($text, $lite='', $noimage='') {
  203. return $this->TextileThis($text, $lite);
  204. }
  205. # Workaround to ensure compatibility with TextPattern 4.0.3.
  206. function blockLite($text) { return $text; }
  207. }
  208. }
  209. #
  210. # Markdown Parser Class
  211. #
  212. class Markdown_Parser {
  213. ### Configuration Variables ###
  214. # Change to ">" for HTML output.
  215. var $empty_element_suffix = MARKDOWN_EMPTY_ELEMENT_SUFFIX;
  216. var $tab_width = MARKDOWN_TAB_WIDTH;
  217. # Change to `true` to disallow markup or entities.
  218. var $no_markup = false;
  219. var $no_entities = false;
  220. # Predefined urls and titles for reference links and images.
  221. var $predef_urls = array();
  222. var $predef_titles = array();
  223. ### Parser Implementation ###
  224. # Regex to match balanced [brackets].
  225. # Needed to insert a maximum bracked depth while converting to PHP.
  226. var $nested_brackets_depth = 6;
  227. var $nested_brackets_re;
  228. var $nested_url_parenthesis_depth = 4;
  229. var $nested_url_parenthesis_re;
  230. # Table of hash values for escaped characters:
  231. var $escape_chars = '\`*_{}[]()>#+-.!';
  232. var $escape_chars_re;
  233. function __construct() {
  234. #
  235. # Constructor function. Initialize appropriate member variables.
  236. #
  237. $this->_initDetab();
  238. $this->prepareItalicsAndBold();
  239. $this->nested_brackets_re =
  240. str_repeat('(?>[^\[\]]+|\[', $this->nested_brackets_depth).
  241. str_repeat('\])*', $this->nested_brackets_depth);
  242. $this->nested_url_parenthesis_re =
  243. str_repeat('(?>[^()\s]+|\(', $this->nested_url_parenthesis_depth).
  244. str_repeat('(?>\)))*', $this->nested_url_parenthesis_depth);
  245. $this->escape_chars_re = '['.preg_quote($this->escape_chars).']';
  246. # Sort document, block, and span gamut in ascendent priority order.
  247. asort($this->document_gamut);
  248. asort($this->block_gamut);
  249. asort($this->span_gamut);
  250. }
  251. # Internal hashes used during transformation.
  252. var $urls = array();
  253. var $titles = array();
  254. var $html_hashes = array();
  255. # Status flag to avoid invalid nesting.
  256. var $in_anchor = false;
  257. function setup() {
  258. #
  259. # Called before the transformation process starts to setup parser
  260. # states.
  261. #
  262. # Clear global hashes.
  263. $this->urls = $this->predef_urls;
  264. $this->titles = $this->predef_titles;
  265. $this->html_hashes = array();
  266. $this->in_anchor = false;
  267. }
  268. function teardown() {
  269. #
  270. # Called after the transformation process to clear any variable
  271. # which may be taking up memory unnecessarly.
  272. #
  273. $this->urls = array();
  274. $this->titles = array();
  275. $this->html_hashes = array();
  276. }
  277. function transform($text) {
  278. #
  279. # Main function. Performs some preprocessing on the input text
  280. # and pass it through the document gamut.
  281. #
  282. $this->setup();
  283. # Remove UTF-8 BOM and marker character in input, if present.
  284. $text = preg_replace('{^\xEF\xBB\xBF|\x1A}', '', $text);
  285. # Standardize line endings:
  286. # DOS to Unix and Mac to Unix
  287. $text = preg_replace('{\r\n?}', "\n", $text);
  288. # Make sure $text ends with a couple of newlines:
  289. $text .= "\n\n";
  290. # Convert all tabs to spaces.
  291. $text = $this->detab($text);
  292. # Turn block-level HTML blocks into hash entries
  293. $text = $this->hashHTMLBlocks($text);
  294. # Strip any lines consisting only of spaces and tabs.
  295. # This makes subsequent regexen easier to write, because we can
  296. # match consecutive blank lines with /\n+/ instead of something
  297. # contorted like /[ ]*\n+/ .
  298. $text = preg_replace('/^[ ]+$/m', '', $text);
  299. # Run document gamut methods.
  300. foreach ($this->document_gamut as $method => $priority) {
  301. $text = $this->$method($text);
  302. }
  303. $this->teardown();
  304. return $text . "\n";
  305. }
  306. var $document_gamut = array(
  307. # Strip link definitions, store in hashes.
  308. "stripLinkDefinitions" => 20,
  309. "runBasicBlockGamut" => 30,
  310. );
  311. function stripLinkDefinitions($text) {
  312. #
  313. # Strips link definitions from text, stores the URLs and titles in
  314. # hash references.
  315. #
  316. $less_than_tab = $this->tab_width - 1;
  317. # Link defs are in the form: ^[id]: url "optional title"
  318. $text = preg_replace_callback('{
  319. ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1
  320. [ ]*
  321. \n? # maybe *one* newline
  322. [ ]*
  323. (?:
  324. <(.+?)> # url = $2
  325. |
  326. (\S+?) # url = $3
  327. )
  328. [ ]*
  329. \n? # maybe one newline
  330. [ ]*
  331. (?:
  332. (?<=\s) # lookbehind for whitespace
  333. ["(]
  334. (.*?) # title = $4
  335. [")]
  336. [ ]*
  337. )? # title is optional
  338. (?:\n+|\Z)
  339. }xm',
  340. array(&$this, '_stripLinkDefinitions_callback'),
  341. $text);
  342. return $text;
  343. }
  344. function _stripLinkDefinitions_callback($matches) {
  345. $link_id = strtolower($matches[1]);
  346. $url = $matches[2] == '' ? $matches[3] : $matches[2];
  347. $this->urls[$link_id] = $url;
  348. $this->titles[$link_id] =& $matches[4];
  349. return ''; # String that will replace the block
  350. }
  351. function hashHTMLBlocks($text) {
  352. if ($this->no_markup) return $text;
  353. $less_than_tab = $this->tab_width - 1;
  354. # Hashify HTML blocks:
  355. # We only want to do this for block-level HTML tags, such as headers,
  356. # lists, and tables. That's because we still want to wrap <p>s around
  357. # "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  358. # phrase emphasis, and spans. The list of tags we're looking for is
  359. # hard-coded:
  360. #
  361. # * List "a" is made of tags which can be both inline or block-level.
  362. # These will be treated block-level when the start tag is alone on
  363. # its line, otherwise they're not matched here and will be taken as
  364. # inline later.
  365. # * List "b" is made of tags which are always block-level;
  366. #
  367. $block_tags_a_re = 'ins|del';
  368. $block_tags_b_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|'.
  369. 'script|noscript|form|fieldset|iframe|math|svg|'.
  370. 'article|section|nav|aside|hgroup|header|footer|'.
  371. 'figure';
  372. # Regular expression for the content of a block tag.
  373. $nested_tags_level = 4;
  374. $attr = '
  375. (?> # optional tag attributes
  376. \s # starts with whitespace
  377. (?>
  378. [^>"/]+ # text outside quotes
  379. |
  380. /+(?!>) # slash not followed by ">"
  381. |
  382. "[^"]*" # text inside double quotes (tolerate ">")
  383. |
  384. \'[^\']*\' # text inside single quotes (tolerate ">")
  385. )*
  386. )?
  387. ';
  388. $content =
  389. str_repeat('
  390. (?>
  391. [^<]+ # content without tag
  392. |
  393. <\2 # nested opening tag
  394. '.$attr.' # attributes
  395. (?>
  396. />
  397. |
  398. >', $nested_tags_level). # end of opening tag
  399. '.*?'. # last level nested tag content
  400. str_repeat('
  401. </\2\s*> # closing nested tag
  402. )
  403. |
  404. <(?!/\2\s*> # other tags with a different name
  405. )
  406. )*',
  407. $nested_tags_level);
  408. $content2 = str_replace('\2', '\3', $content);
  409. # First, look for nested blocks, e.g.:
  410. # <div>
  411. # <div>
  412. # tags for inner block must be indented.
  413. # </div>
  414. # </div>
  415. #
  416. # The outermost tags must start at the left margin for this to match, and
  417. # the inner nested divs must be indented.
  418. # We need to do this before the next, more liberal match, because the next
  419. # match will start at the first `<div>` and stop at the first `</div>`.
  420. $text = preg_replace_callback('{(?>
  421. (?>
  422. (?<=\n\n) # Starting after a blank line
  423. | # or
  424. \A\n? # the beginning of the doc
  425. )
  426. ( # save in $1
  427. # Match from `\n<tag>` to `</tag>\n`, handling nested tags
  428. # in between.
  429. [ ]{0,'.$less_than_tab.'}
  430. <('.$block_tags_b_re.')# start tag = $2
  431. '.$attr.'> # attributes followed by > and \n
  432. '.$content.' # content, support nesting
  433. </\2> # the matching end tag
  434. [ ]* # trailing spaces/tabs
  435. (?=\n+|\Z) # followed by a newline or end of document
  436. | # Special version for tags of group a.
  437. [ ]{0,'.$less_than_tab.'}
  438. <('.$block_tags_a_re.')# start tag = $3
  439. '.$attr.'>[ ]*\n # attributes followed by >
  440. '.$content2.' # content, support nesting
  441. </\3> # the matching end tag
  442. [ ]* # trailing spaces/tabs
  443. (?=\n+|\Z) # followed by a newline or end of document
  444. | # Special case just for <hr />. It was easier to make a special
  445. # case than to make the other regex more complicated.
  446. [ ]{0,'.$less_than_tab.'}
  447. <(hr) # start tag = $2
  448. '.$attr.' # attributes
  449. /?> # the matching end tag
  450. [ ]*
  451. (?=\n{2,}|\Z) # followed by a blank line or end of document
  452. | # Special case for standalone HTML comments:
  453. [ ]{0,'.$less_than_tab.'}
  454. (?s:
  455. <!-- .*? -->
  456. )
  457. [ ]*
  458. (?=\n{2,}|\Z) # followed by a blank line or end of document
  459. | # PHP and ASP-style processor instructions (<? and <%)
  460. [ ]{0,'.$less_than_tab.'}
  461. (?s:
  462. <([?%]) # $2
  463. .*?
  464. \2>
  465. )
  466. [ ]*
  467. (?=\n{2,}|\Z) # followed by a blank line or end of document
  468. )
  469. )}Sxmi',
  470. array(&$this, '_hashHTMLBlocks_callback'),
  471. $text);
  472. return $text;
  473. }
  474. function _hashHTMLBlocks_callback($matches) {
  475. $text = $matches[1];
  476. $key = $this->hashBlock($text);
  477. return "\n\n$key\n\n";
  478. }
  479. function hashPart($text, $boundary = 'X') {
  480. #
  481. # Called whenever a tag must be hashed when a function insert an atomic
  482. # element in the text stream. Passing $text to through this function gives
  483. # a unique text-token which will be reverted back when calling unhash.
  484. #
  485. # The $boundary argument specify what character should be used to surround
  486. # the token. By convension, "B" is used for block elements that needs not
  487. # to be wrapped into paragraph tags at the end, ":" is used for elements
  488. # that are word separators and "X" is used in the general case.
  489. #
  490. # Swap back any tag hash found in $text so we do not have to `unhash`
  491. # multiple times at the end.
  492. $text = $this->unhash($text);
  493. # Then hash the block.
  494. static $i = 0;
  495. $key = "$boundary\x1A" . ++$i . $boundary;
  496. $this->html_hashes[$key] = $text;
  497. return $key; # String that will replace the tag.
  498. }
  499. function hashBlock($text) {
  500. #
  501. # Shortcut function for hashPart with block-level boundaries.
  502. #
  503. return $this->hashPart($text, 'B');
  504. }
  505. var $block_gamut = array(
  506. #
  507. # These are all the transformations that form block-level
  508. # tags like paragraphs, headers, and list items.
  509. #
  510. "doHeaders" => 10,
  511. "doHorizontalRules" => 20,
  512. "doLists" => 40,
  513. "doCodeBlocks" => 50,
  514. "doBlockQuotes" => 60,
  515. );
  516. function runBlockGamut($text) {
  517. #
  518. # Run block gamut tranformations.
  519. #
  520. # We need to escape raw HTML in Markdown source before doing anything
  521. # else. This need to be done for each block, and not only at the
  522. # begining in the Markdown function since hashed blocks can be part of
  523. # list items and could have been indented. Indented blocks would have
  524. # been seen as a code block in a previous pass of hashHTMLBlocks.
  525. $text = $this->hashHTMLBlocks($text);
  526. return $this->runBasicBlockGamut($text);
  527. }
  528. function runBasicBlockGamut($text) {
  529. #
  530. # Run block gamut tranformations, without hashing HTML blocks. This is
  531. # useful when HTML blocks are known to be already hashed, like in the first
  532. # whole-document pass.
  533. #
  534. foreach ($this->block_gamut as $method => $priority) {
  535. $text = $this->$method($text);
  536. }
  537. # Finally form paragraph and restore hashed blocks.
  538. $text = $this->formParagraphs($text);
  539. return $text;
  540. }
  541. function doHorizontalRules($text) {
  542. # Do Horizontal Rules:
  543. return preg_replace(
  544. '{
  545. ^[ ]{0,3} # Leading space
  546. ([-*_]) # $1: First marker
  547. (?> # Repeated marker group
  548. [ ]{0,2} # Zero, one, or two spaces.
  549. \1 # Marker character
  550. ){2,} # Group repeated at least twice
  551. [ ]* # Tailing spaces
  552. $ # End of line.
  553. }mx',
  554. "\n".$this->hashBlock("<hr$this->empty_element_suffix")."\n",
  555. $text);
  556. }
  557. var $span_gamut = array(
  558. #
  559. # These are all the transformations that occur *within* block-level
  560. # tags like paragraphs, headers, and list items.
  561. #
  562. # Process character escapes, code spans, and inline HTML
  563. # in one shot.
  564. "parseSpan" => -30,
  565. # Process anchor and image tags. Images must come first,
  566. # because ![foo][f] looks like an anchor.
  567. "doImages" => 10,
  568. "doAnchors" => 20,
  569. # Make links out of things like `<http://example.com/>`
  570. # Must come after doAnchors, because you can use < and >
  571. # delimiters in inline links like [this](<url>).
  572. "doAutoLinks" => 30,
  573. "encodeAmpsAndAngles" => 40,
  574. "doItalicsAndBold" => 50,
  575. "doHardBreaks" => 60,
  576. );
  577. function runSpanGamut($text) {
  578. #
  579. # Run span gamut tranformations.
  580. #
  581. foreach ($this->span_gamut as $method => $priority) {
  582. $text = $this->$method($text);
  583. }
  584. return $text;
  585. }
  586. function doHardBreaks($text) {
  587. # Do hard breaks:
  588. return preg_replace_callback('/ {2,}\n/',
  589. array(&$this, '_doHardBreaks_callback'), $text);
  590. }
  591. function _doHardBreaks_callback($matches) {
  592. return $this->hashPart("<br$this->empty_element_suffix\n");
  593. }
  594. function doAnchors($text) {
  595. #
  596. # Turn Markdown link shortcuts into XHTML <a> tags.
  597. #
  598. if ($this->in_anchor) return $text;
  599. $this->in_anchor = true;
  600. #
  601. # First, handle reference-style links: [link text] [id]
  602. #
  603. $text = preg_replace_callback('{
  604. ( # wrap whole match in $1
  605. \[
  606. ('.$this->nested_brackets_re.') # link text = $2
  607. \]
  608. [ ]? # one optional space
  609. (?:\n[ ]*)? # one optional newline followed by spaces
  610. \[
  611. (.*?) # id = $3
  612. \]
  613. )
  614. }xs',
  615. array(&$this, '_doAnchors_reference_callback'), $text);
  616. #
  617. # Next, inline-style links: [link text](url "optional title")
  618. #
  619. $text = preg_replace_callback('{
  620. ( # wrap whole match in $1
  621. \[
  622. ('.$this->nested_brackets_re.') # link text = $2
  623. \]
  624. \( # literal paren
  625. [ \n]*
  626. (?:
  627. <(.+?)> # href = $3
  628. |
  629. ('.$this->nested_url_parenthesis_re.') # href = $4
  630. )
  631. [ \n]*
  632. ( # $5
  633. ([\'"]) # quote char = $6
  634. (.*?) # Title = $7
  635. \6 # matching quote
  636. [ \n]* # ignore any spaces/tabs between closing quote and )
  637. )? # title is optional
  638. \)
  639. )
  640. }xs',
  641. array(&$this, '_doAnchors_inline_callback'), $text);
  642. #
  643. # Last, handle reference-style shortcuts: [link text]
  644. # These must come last in case you've also got [link text][1]
  645. # or [link text](/foo)
  646. #
  647. $text = preg_replace_callback('{
  648. ( # wrap whole match in $1
  649. \[
  650. ([^\[\]]+) # link text = $2; can\'t contain [ or ]
  651. \]
  652. )
  653. }xs',
  654. array(&$this, '_doAnchors_reference_callback'), $text);
  655. $this->in_anchor = false;
  656. return $text;
  657. }
  658. function _doAnchors_reference_callback($matches) {
  659. $whole_match = $matches[1];
  660. $link_text = $matches[2];
  661. $link_id =& $matches[3];
  662. if ($link_id == "") {
  663. # for shortcut links like [this][] or [this].
  664. $link_id = $link_text;
  665. }
  666. # lower-case and turn embedded newlines into spaces
  667. $link_id = strtolower($link_id);
  668. $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
  669. if (isset($this->urls[$link_id])) {
  670. $url = $this->urls[$link_id];
  671. $url = $this->encodeAttribute($url);
  672. $result = "<a href=\"$url\"";
  673. if ( isset( $this->titles[$link_id] ) ) {
  674. $title = $this->titles[$link_id];
  675. $title = $this->encodeAttribute($title);
  676. $result .= " title=\"$title\"";
  677. }
  678. $link_text = $this->runSpanGamut($link_text);
  679. $result .= ">$link_text</a>";
  680. $result = $this->hashPart($result);
  681. }
  682. else {
  683. $result = $whole_match;
  684. }
  685. return $result;
  686. }
  687. function _doAnchors_inline_callback($matches) {
  688. $whole_match = $matches[1];
  689. $link_text = $this->runSpanGamut($matches[2]);
  690. $url = $matches[3] == '' ? $matches[4] : $matches[3];
  691. $title =& $matches[7];
  692. $url = $this->encodeAttribute($url);
  693. $result = "<a href=\"$url\"";
  694. if (isset($title)) {
  695. $title = $this->encodeAttribute($title);
  696. $result .= " title=\"$title\"";
  697. }
  698. $link_text = $this->runSpanGamut($link_text);
  699. $result .= ">$link_text</a>";
  700. return $this->hashPart($result);
  701. }
  702. function doImages($text) {
  703. #
  704. # Turn Markdown image shortcuts into <img> tags.
  705. #
  706. #
  707. # First, handle reference-style labeled images: ![alt text][id]
  708. #
  709. $text = preg_replace_callback('{
  710. ( # wrap whole match in $1
  711. !\[
  712. ('.$this->nested_brackets_re.') # alt text = $2
  713. \]
  714. [ ]? # one optional space
  715. (?:\n[ ]*)? # one optional newline followed by spaces
  716. \[
  717. (.*?) # id = $3
  718. \]
  719. )
  720. }xs',
  721. array(&$this, '_doImages_reference_callback'), $text);
  722. #
  723. # Next, handle inline images: ![alt text](url "optional title")
  724. # Don't forget: encode * and _
  725. #
  726. $text = preg_replace_callback('{
  727. ( # wrap whole match in $1
  728. !\[
  729. ('.$this->nested_brackets_re.') # alt text = $2
  730. \]
  731. \s? # One optional whitespace character
  732. \( # literal paren
  733. [ \n]*
  734. (?:
  735. <(\S*)> # src url = $3
  736. |
  737. ('.$this->nested_url_parenthesis_re.') # src url = $4
  738. )
  739. [ \n]*
  740. ( # $5
  741. ([\'"]) # quote char = $6
  742. (.*?) # title = $7
  743. \6 # matching quote
  744. [ \n]*
  745. )? # title is optional
  746. \)
  747. )
  748. }xs',
  749. array(&$this, '_doImages_inline_callback'), $text);
  750. return $text;
  751. }
  752. function _doImages_reference_callback($matches) {
  753. $whole_match = $matches[1];
  754. $alt_text = $matches[2];
  755. $link_id = strtolower($matches[3]);
  756. if ($link_id == "") {
  757. $link_id = strtolower($alt_text); # for shortcut links like ![this][].
  758. }
  759. $alt_text = $this->encodeAttribute($alt_text);
  760. if (isset($this->urls[$link_id])) {
  761. $url = $this->encodeAttribute($this->urls[$link_id]);
  762. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  763. if (isset($this->titles[$link_id])) {
  764. $title = $this->titles[$link_id];
  765. $title = $this->encodeAttribute($title);
  766. $result .= " title=\"$title\"";
  767. }
  768. $result .= $this->empty_element_suffix;
  769. $result = $this->hashPart($result);
  770. }
  771. else {
  772. # If there's no such link ID, leave intact:
  773. $result = $whole_match;
  774. }
  775. return $result;
  776. }
  777. function _doImages_inline_callback($matches) {
  778. $whole_match = $matches[1];
  779. $alt_text = $matches[2];
  780. $url = $matches[3] == '' ? $matches[4] : $matches[3];
  781. $title =& $matches[7];
  782. $alt_text = $this->encodeAttribute($alt_text);
  783. $url = $this->encodeAttribute($url);
  784. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  785. if (isset($title)) {
  786. $title = $this->encodeAttribute($title);
  787. $result .= " title=\"$title\""; # $title already quoted
  788. }
  789. $result .= $this->empty_element_suffix;
  790. return $this->hashPart($result);
  791. }
  792. function doHeaders($text) {
  793. # Setext-style headers:
  794. # Header 1
  795. # ========
  796. #
  797. # Header 2
  798. # --------
  799. #
  800. $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx',
  801. array(&$this, '_doHeaders_callback_setext'), $text);
  802. # atx-style headers:
  803. # # Header 1
  804. # ## Header 2
  805. # ## Header 2 with closing hashes ##
  806. # ...
  807. # ###### Header 6
  808. #
  809. $text = preg_replace_callback('{
  810. ^(\#{1,6}) # $1 = string of #\'s
  811. [ ]*
  812. (.+?) # $2 = Header text
  813. [ ]*
  814. \#* # optional closing #\'s (not counted)
  815. \n+
  816. }xm',
  817. array(&$this, '_doHeaders_callback_atx'), $text);
  818. return $text;
  819. }
  820. function _doHeaders_callback_setext($matches) {
  821. # Terrible hack to check we haven't found an empty list item.
  822. if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1]))
  823. return $matches[0];
  824. $level = $matches[2]{0} == '=' ? 1 : 2;
  825. $block = "<h$level>".$this->runSpanGamut($matches[1])."</h$level>";
  826. return "\n" . $this->hashBlock($block) . "\n\n";
  827. }
  828. function _doHeaders_callback_atx($matches) {
  829. $level = strlen($matches[1]);
  830. $block = "<h$level>".$this->runSpanGamut($matches[2])."</h$level>";
  831. return "\n" . $this->hashBlock($block) . "\n\n";
  832. }
  833. function doLists($text) {
  834. #
  835. # Form HTML ordered (numbered) and unordered (bulleted) lists.
  836. #
  837. $less_than_tab = $this->tab_width - 1;
  838. # Re-usable patterns to match list item bullets and number markers:
  839. $marker_ul_re = '[*+-]';
  840. $marker_ol_re = '\d+[\.]';
  841. $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  842. $markers_relist = array(
  843. $marker_ul_re => $marker_ol_re,
  844. $marker_ol_re => $marker_ul_re,
  845. );
  846. foreach ($markers_relist as $marker_re => $other_marker_re) {
  847. # Re-usable pattern to match any entirel ul or ol list:
  848. $whole_list_re = '
  849. ( # $1 = whole list
  850. ( # $2
  851. ([ ]{0,'.$less_than_tab.'}) # $3 = number of spaces
  852. ('.$marker_re.') # $4 = first list item marker
  853. [ ]+
  854. )
  855. (?s:.+?)
  856. ( # $5
  857. \z
  858. |
  859. \n{2,}
  860. (?=\S)
  861. (?! # Negative lookahead for another list item marker
  862. [ ]*
  863. '.$marker_re.'[ ]+
  864. )
  865. |
  866. (?= # Lookahead for another kind of list
  867. \n
  868. \3 # Must have the same indentation
  869. '.$other_marker_re.'[ ]+
  870. )
  871. )
  872. )
  873. '; // mx
  874. # We use a different prefix before nested lists than top-level lists.
  875. # See extended comment in _ProcessListItems().
  876. if ($this->list_level) {
  877. $text = preg_replace_callback('{
  878. ^
  879. '.$whole_list_re.'
  880. }mx',
  881. array(&$this, '_doLists_callback'), $text);
  882. }
  883. else {
  884. $text = preg_replace_callback('{
  885. (?:(?<=\n)\n|\A\n?) # Must eat the newline
  886. '.$whole_list_re.'
  887. }mx',
  888. array(&$this, '_doLists_callback'), $text);
  889. }
  890. }
  891. return $text;
  892. }
  893. function _doLists_callback($matches) {
  894. # Re-usable patterns to match list item bullets and number markers:
  895. $marker_ul_re = '[*+-]';
  896. $marker_ol_re = '\d+[\.]';
  897. $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  898. $list = $matches[1];
  899. $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol";
  900. $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re );
  901. $list .= "\n";
  902. $result = $this->processListItems($list, $marker_any_re);
  903. $result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>");
  904. return "\n". $result ."\n\n";
  905. }
  906. var $list_level = 0;
  907. function processListItems($list_str, $marker_any_re) {
  908. #
  909. # Process the contents of a single ordered or unordered list, splitting it
  910. # into individual list items.
  911. #
  912. # The $this->list_level global keeps track of when we're inside a list.
  913. # Each time we enter a list, we increment it; when we leave a list,
  914. # we decrement. If it's zero, we're not in a list anymore.
  915. #
  916. # We do this because when we're not inside a list, we want to treat
  917. # something like this:
  918. #
  919. # I recommend upgrading to version
  920. # 8. Oops, now this line is treated
  921. # as a sub-list.
  922. #
  923. # As a single paragraph, despite the fact that the second line starts
  924. # with a digit-period-space sequence.
  925. #
  926. # Whereas when we're inside a list (or sub-list), that line will be
  927. # treated as the start of a sub-list. What a kludge, huh? This is
  928. # an aspect of Markdown's syntax that's hard to parse perfectly
  929. # without resorting to mind-reading. Perhaps the solution is to
  930. # change the syntax rules such that sub-lists must start with a
  931. # starting cardinal number; e.g. "1." or "a.".
  932. $this->list_level++;
  933. # trim trailing blank lines:
  934. $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
  935. $list_str = preg_replace_callback('{
  936. (\n)? # leading line = $1
  937. (^[ ]*) # leading whitespace = $2
  938. ('.$marker_any_re.' # list marker and space = $3
  939. (?:[ ]+|(?=\n)) # space only required if item is not empty
  940. )
  941. ((?s:.*?)) # list item text = $4
  942. (?:(\n+(?=\n))|\n) # tailing blank line = $5
  943. (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n))))
  944. }xm',
  945. array(&$this, '_processListItems_callback'), $list_str);
  946. $this->list_level--;
  947. return $list_str;
  948. }
  949. function _processListItems_callback($matches) {
  950. $item = $matches[4];
  951. $leading_line =& $matches[1];
  952. $leading_space =& $matches[2];
  953. $marker_space = $matches[3];
  954. $tailing_blank_line =& $matches[5];
  955. if ($leading_line || $tailing_blank_line ||
  956. preg_match('/\n{2,}/', $item))
  957. {
  958. # Replace marker with the appropriate whitespace indentation
  959. $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item;
  960. $item = $this->runBlockGamut($this->outdent($item)."\n");
  961. }
  962. else {
  963. # Recursion for sub-lists:
  964. $item = $this->doLists($this->outdent($item));
  965. $item = preg_replace('/\n+$/', '', $item);
  966. $item = $this->runSpanGamut($item);
  967. }
  968. return "<li>" . $item . "</li>\n";
  969. }
  970. function doCodeBlocks($text) {
  971. #
  972. # Process Markdown `<pre><code>` blocks.
  973. #
  974. $text = preg_replace_callback('{
  975. (?:\n\n|\A\n?)
  976. ( # $1 = the code block -- one or more lines, starting with a space/tab
  977. (?>
  978. [ ]{'.$this->tab_width.'} # Lines must start with a tab or a tab-width of spaces
  979. .*\n+
  980. )+
  981. )
  982. ((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
  983. }xm',
  984. array(&$this, '_doCodeBlocks_callback'), $text);
  985. return $text;
  986. }
  987. function _doCodeBlocks_callback($matches) {
  988. $codeblock = $matches[1];
  989. $codeblock = $this->outdent($codeblock);
  990. $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
  991. # trim leading newlines and trailing newlines
  992. $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
  993. $codeblock = "<pre><code>$codeblock\n</code></pre>";
  994. return "\n\n".$this->hashBlock($codeblock)."\n\n";
  995. }
  996. function makeCodeSpan($code) {
  997. #
  998. # Create a code span markup for $code. Called from handleSpanToken.
  999. #
  1000. $code = htmlspecialchars(trim($code), ENT_NOQUOTES);
  1001. return $this->hashPart("<code>$code</code>");
  1002. }
  1003. var $em_relist = array(
  1004. '' => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?=\S|$)(?![\.,:;]\s)',
  1005. '*' => '(?<=\S|^)(?<!\*)\*(?!\*)',
  1006. '_' => '(?<=\S|^)(?<!_)_(?!_)',
  1007. );
  1008. var $strong_relist = array(
  1009. '' => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?=\S|$)(?![\.,:;]\s)',
  1010. '**' => '(?<=\S|^)(?<!\*)\*\*(?!\*)',
  1011. '__' => '(?<=\S|^)(?<!_)__(?!_)',
  1012. );
  1013. var $em_strong_relist = array(
  1014. '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?=\S|$)(?![\.,:;]\s)',
  1015. '***' => '(?<=\S|^)(?<!\*)\*\*\*(?!\*)',
  1016. '___' => '(?<=\S|^)(?<!_)___(?!_)',
  1017. );
  1018. var $em_strong_prepared_relist;
  1019. function prepareItalicsAndBold() {
  1020. #
  1021. # Prepare regular expressions for searching emphasis tokens in any
  1022. # context.
  1023. #
  1024. foreach ($this->em_relist as $em => $em_re) {
  1025. foreach ($this->strong_relist as $strong => $strong_re) {
  1026. # Construct list of allowed token expressions.
  1027. $token_relist = array();
  1028. if (isset($this->em_strong_relist["$em$strong"])) {
  1029. $token_relist[] = $this->em_strong_relist["$em$strong"];
  1030. }
  1031. $token_relist[] = $em_re;
  1032. $token_relist[] = $strong_re;
  1033. # Construct master expression from list.
  1034. $token_re = '{('. implode('|', $token_relist) .')}';
  1035. $this->em_strong_prepared_relist["$em$strong"] = $token_re;
  1036. }
  1037. }
  1038. }
  1039. function doItalicsAndBold($text) {
  1040. $token_stack = array('');
  1041. $text_stack = array('');
  1042. $em = '';
  1043. $strong = '';
  1044. $tree_char_em = false;
  1045. while (1) {
  1046. #
  1047. # Get prepared regular expression for seraching emphasis tokens
  1048. # in current context.
  1049. #
  1050. $token_re = $this->em_strong_prepared_relist["$em$strong"];
  1051. #
  1052. # Each loop iteration search for the next emphasis token.
  1053. # Each token is then passed to handleSpanToken.
  1054. #
  1055. $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
  1056. $text_stack[0] .= $parts[0];
  1057. $token =& $parts[1];
  1058. $text =& $parts[2];
  1059. if (empty($token)) {
  1060. # Reached end of text span: empty stack without emitting.
  1061. # any more emphasis.
  1062. while ($token_stack[0]) {
  1063. $text_stack[1] .= array_shift($token_stack);
  1064. $text_stack[0] .= array_shift($text_stack);
  1065. }
  1066. break;
  1067. }
  1068. $token_len = strlen($token);
  1069. if ($tree_char_em) {
  1070. # Reached closing marker while inside a three-char emphasis.
  1071. if ($token_len == 3) {
  1072. # Three-char closing marker, close em and strong.
  1073. array_shift($token_stack);
  1074. $span = array_shift($text_stack);
  1075. $span = $this->runSpanGamut($span);
  1076. $span = "<strong><em>$span</em></strong>";
  1077. $text_stack[0] .= $this->hashPart($span);
  1078. $em = '';
  1079. $strong = '';
  1080. } else {
  1081. # Other closing marker: close one em or strong and
  1082. # change current token state to match the other
  1083. $token_stack[0] = str_repeat($token{0}, 3-$token_len);
  1084. $tag = $token_len == 2 ? "strong" : "em";
  1085. $span = $text_stack[0];
  1086. $span = $this->runSpanGamut($span);
  1087. $span = "<$tag>$span</$tag>";
  1088. $text_stack[0] = $this->hashPart($span);
  1089. $$tag = ''; # $$tag stands for $em or $strong
  1090. }
  1091. $tree_char_em = false;
  1092. } else if ($token_len == 3) {
  1093. if ($em) {
  1094. # Reached closing marker for both em and strong.
  1095. # Closing strong marker:
  1096. for ($i = 0; $i < 2; ++$i) {
  1097. $shifted_token = array_shift($token_stack);
  1098. $tag = strlen($shifted_token) == 2 ? "strong" : "em";
  1099. $span = array_shift($text_stack);
  1100. $span = $this->runSpanGamut($span);
  1101. $span = "<$tag>$span</$tag>";
  1102. $text_stack[0] .= $this->hashPart($span);
  1103. $$tag = ''; # $$tag stands for $em or $strong
  1104. }
  1105. } else {
  1106. # Reached opening three-char emphasis marker. Push on token
  1107. # stack; will be handled by the special condition above.
  1108. $em = $token{0};
  1109. $strong = "$em$em";
  1110. array_unshift($token_stack, $token);
  1111. array_unshift($text_stack, '');
  1112. $tree_char_em = true;
  1113. }
  1114. } else if ($token_len == 2) {
  1115. if ($strong) {
  1116. # Unwind any dangling emphasis marker:
  1117. if (strlen($token_stack[0]) == 1) {
  1118. $text_stack[1] .= array_shift($token_stack);
  1119. $text_stack[0] .= array_shift($text_stack);
  1120. }
  1121. # Closing strong marker:
  1122. array_shift($token_stack);
  1123. $span = array_shift($text_stack);
  1124. $span = $this->runSpanGamut($span);
  1125. $span = "<strong>$span</strong>";
  1126. $text_stack[0] .= $this->hashPart($span);
  1127. $strong = '';
  1128. } else {
  1129. array_unshift($token_stack, $token);
  1130. array_unshift($text_stack, '');
  1131. $strong = $token;
  1132. }
  1133. } else {
  1134. # Here $token_len == 1
  1135. if ($em) {
  1136. if (strlen($token_stack[0]) == 1) {
  1137. # Closing emphasis marker:
  1138. array_shift($token_stack);
  1139. $span = array_shift($text_stack);
  1140. $span = $this->runSpanGamut($span);
  1141. $span = "<em>$span</em>";
  1142. $text_stack[0] .= $this->hashPart($span);
  1143. $em = '';
  1144. } else {
  1145. $text_stack[0] .= $token;
  1146. }
  1147. } else {
  1148. array_unshift($token_stack, $token);
  1149. array_unshift($text_stack, '');
  1150. $em = $token;
  1151. }
  1152. }
  1153. }
  1154. return $text_stack[0];
  1155. }
  1156. function doBlockQuotes($text) {
  1157. $text = preg_replace_callback('/
  1158. ( # Wrap whole match in $1
  1159. (?>
  1160. ^[ ]*>[ ]? # ">" at the start of a line
  1161. .+\n # rest of the first line
  1162. (.+\n)* # subsequent consecutive lines
  1163. \n* # blanks
  1164. )+
  1165. )
  1166. /xm',
  1167. array(&$this, '_doBlockQuotes_callback'), $text);
  1168. return $text;
  1169. }
  1170. function _doBlockQuotes_callback($matches) {
  1171. $bq = $matches[1];
  1172. # trim one level of quoting - trim whitespace-only lines
  1173. $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);
  1174. $bq = $this->runBlockGamut($bq); # recurse
  1175. $bq = preg_replace('/^/m', " ", $bq);
  1176. # These leading spaces cause problem with <pre> content,
  1177. # so we need to fix that:
  1178. $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx',
  1179. array(&$this, '_doBlockQuotes_callback2'), $bq);
  1180. return "\n". $this->hashBlock("<blockquote>\n$bq\n</blockquote>")."\n\n";
  1181. }
  1182. function _doBlockQuotes_callback2($matches) {
  1183. $pre = $matches[1];
  1184. $pre = preg_replace('/^ /m', '', $pre);
  1185. return $pre;
  1186. }
  1187. function formParagraphs($text) {
  1188. #
  1189. # Params:
  1190. # $text - string to process with html <p> tags
  1191. #
  1192. # Strip leading and trailing lines:
  1193. $text = preg_replace('/\A\n+|\n+\z/', '', $text);
  1194. $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
  1195. #
  1196. # Wrap <p> tags and unhashify HTML blocks
  1197. #
  1198. foreach ($grafs as $key => $value) {
  1199. if (!preg_match('/^B\x1A[0-9]+B$/', $value)) {
  1200. # Is a paragraph.
  1201. $value = $this->runSpanGamut($value);
  1202. $value = preg_replace('/^([ ]*)/', "<p>", $value);
  1203. $value .= "</p>";
  1204. $grafs[$key] = $this->unhash($value);
  1205. }
  1206. else {
  1207. # Is a block.
  1208. # Modify elements of @grafs in-place..

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