Markdown.php 50 KB

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