PageRenderTime 52ms CodeModel.GetById 13ms RepoModel.GetById 0ms app.codeStats 1ms

/components/Markdown.php

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