PageRenderTime 39ms CodeModel.GetById 28ms RepoModel.GetById 0ms app.codeStats 0ms

/www/lib/php-markdown-lib-1.6.0/php/Michelf/Markdown.php

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