Markdown.php 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910
  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-2019 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.9.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|null
  75. */
  76. public $url_filter_func = null;
  77. /**
  78. * Optional header id="" generation callback function.
  79. * @var callable|null
  80. */
  81. public $header_id_func = null;
  82. /**
  83. * Optional function for converting code block content to HTML
  84. * @var callable|null
  85. */
  86. public $code_block_content_func = null;
  87. /**
  88. * Optional function for converting code span content to HTML.
  89. * @var callable|null
  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. $link_text = $this->runSpanGamut($matches[2]);
  676. $url = $matches[3] === '' ? $matches[4] : $matches[3];
  677. $title =& $matches[7];
  678. // If the URL was of the form <s p a c e s> it got caught by the HTML
  679. // tag parser and hashed. Need to reverse the process before using
  680. // the URL.
  681. $unhashed = $this->unhash($url);
  682. if ($unhashed !== $url)
  683. $url = preg_replace('/^<(.*)>$/', '\1', $unhashed);
  684. $url = $this->encodeURLAttribute($url);
  685. $result = "<a href=\"$url\"";
  686. if (isset($title)) {
  687. $title = $this->encodeAttribute($title);
  688. $result .= " title=\"$title\"";
  689. }
  690. $link_text = $this->runSpanGamut($link_text);
  691. $result .= ">$link_text</a>";
  692. return $this->hashPart($result);
  693. }
  694. /**
  695. * Turn Markdown image shortcuts into <img> tags.
  696. * @param string $text
  697. * @return string
  698. */
  699. protected function doImages($text) {
  700. // First, handle reference-style labeled images: ![alt text][id]
  701. $text = preg_replace_callback('{
  702. ( # wrap whole match in $1
  703. !\[
  704. ('.$this->nested_brackets_re.') # alt text = $2
  705. \]
  706. [ ]? # one optional space
  707. (?:\n[ ]*)? # one optional newline followed by spaces
  708. \[
  709. (.*?) # id = $3
  710. \]
  711. )
  712. }xs',
  713. array($this, '_doImages_reference_callback'), $text);
  714. // Next, handle inline images: ![alt text](url "optional title")
  715. // Don't forget: encode * and _
  716. $text = preg_replace_callback('{
  717. ( # wrap whole match in $1
  718. !\[
  719. ('.$this->nested_brackets_re.') # alt text = $2
  720. \]
  721. \s? # One optional whitespace character
  722. \( # literal paren
  723. [ \n]*
  724. (?:
  725. <(\S*)> # src url = $3
  726. |
  727. ('.$this->nested_url_parenthesis_re.') # src url = $4
  728. )
  729. [ \n]*
  730. ( # $5
  731. ([\'"]) # quote char = $6
  732. (.*?) # title = $7
  733. \6 # matching quote
  734. [ \n]*
  735. )? # title is optional
  736. \)
  737. )
  738. }xs',
  739. array($this, '_doImages_inline_callback'), $text);
  740. return $text;
  741. }
  742. /**
  743. * Callback to parse references image tags
  744. * @param array $matches
  745. * @return string
  746. */
  747. protected function _doImages_reference_callback($matches) {
  748. $whole_match = $matches[1];
  749. $alt_text = $matches[2];
  750. $link_id = strtolower($matches[3]);
  751. if ($link_id == "") {
  752. $link_id = strtolower($alt_text); // for shortcut links like ![this][].
  753. }
  754. $alt_text = $this->encodeAttribute($alt_text);
  755. if (isset($this->urls[$link_id])) {
  756. $url = $this->encodeURLAttribute($this->urls[$link_id]);
  757. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  758. if (isset($this->titles[$link_id])) {
  759. $title = $this->titles[$link_id];
  760. $title = $this->encodeAttribute($title);
  761. $result .= " title=\"$title\"";
  762. }
  763. $result .= $this->empty_element_suffix;
  764. $result = $this->hashPart($result);
  765. } else {
  766. // If there's no such link ID, leave intact:
  767. $result = $whole_match;
  768. }
  769. return $result;
  770. }
  771. /**
  772. * Callback to parse inline image tags
  773. * @param array $matches
  774. * @return string
  775. */
  776. protected function _doImages_inline_callback($matches) {
  777. $whole_match = $matches[1];
  778. $alt_text = $matches[2];
  779. $url = $matches[3] == '' ? $matches[4] : $matches[3];
  780. $title =& $matches[7];
  781. $alt_text = $this->encodeAttribute($alt_text);
  782. $url = $this->encodeURLAttribute($url);
  783. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  784. if (isset($title)) {
  785. $title = $this->encodeAttribute($title);
  786. $result .= " title=\"$title\""; // $title already quoted
  787. }
  788. $result .= $this->empty_element_suffix;
  789. return $this->hashPart($result);
  790. }
  791. /**
  792. * Parse Markdown heading elements to HTML
  793. * @param string $text
  794. * @return string
  795. */
  796. protected function doHeaders($text) {
  797. /**
  798. * Setext-style headers:
  799. * Header 1
  800. * ========
  801. *
  802. * Header 2
  803. * --------
  804. */
  805. $text = preg_replace_callback('{ ^(.+?)[ ]*\n(=+|-+)[ ]*\n+ }mx',
  806. array($this, '_doHeaders_callback_setext'), $text);
  807. /**
  808. * atx-style headers:
  809. * # Header 1
  810. * ## Header 2
  811. * ## Header 2 with closing hashes ##
  812. * ...
  813. * ###### Header 6
  814. */
  815. $text = preg_replace_callback('{
  816. ^(\#{1,6}) # $1 = string of #\'s
  817. [ ]*
  818. (.+?) # $2 = Header text
  819. [ ]*
  820. \#* # optional closing #\'s (not counted)
  821. \n+
  822. }xm',
  823. array($this, '_doHeaders_callback_atx'), $text);
  824. return $text;
  825. }
  826. /**
  827. * Setext header parsing callback
  828. * @param array $matches
  829. * @return string
  830. */
  831. protected function _doHeaders_callback_setext($matches) {
  832. // Terrible hack to check we haven't found an empty list item.
  833. if ($matches[2] == '-' && preg_match('{^-(?: |$)}', $matches[1])) {
  834. return $matches[0];
  835. }
  836. $level = $matches[2][0] == '=' ? 1 : 2;
  837. // ID attribute generation
  838. $idAtt = $this->_generateIdFromHeaderValue($matches[1]);
  839. $block = "<h$level$idAtt>".$this->runSpanGamut($matches[1])."</h$level>";
  840. return "\n" . $this->hashBlock($block) . "\n\n";
  841. }
  842. /**
  843. * ATX header parsing callback
  844. * @param array $matches
  845. * @return string
  846. */
  847. protected function _doHeaders_callback_atx($matches) {
  848. // ID attribute generation
  849. $idAtt = $this->_generateIdFromHeaderValue($matches[2]);
  850. $level = strlen($matches[1]);
  851. $block = "<h$level$idAtt>".$this->runSpanGamut($matches[2])."</h$level>";
  852. return "\n" . $this->hashBlock($block) . "\n\n";
  853. }
  854. /**
  855. * If a header_id_func property is set, we can use it to automatically
  856. * generate an id attribute.
  857. *
  858. * This method returns a string in the form id="foo", or an empty string
  859. * otherwise.
  860. * @param string $headerValue
  861. * @return string
  862. */
  863. protected function _generateIdFromHeaderValue($headerValue) {
  864. if (!is_callable($this->header_id_func)) {
  865. return "";
  866. }
  867. $idValue = call_user_func($this->header_id_func, $headerValue);
  868. if (!$idValue) {
  869. return "";
  870. }
  871. return ' id="' . $this->encodeAttribute($idValue) . '"';
  872. }
  873. /**
  874. * Form HTML ordered (numbered) and unordered (bulleted) lists.
  875. * @param string $text
  876. * @return string
  877. */
  878. protected function doLists($text) {
  879. $less_than_tab = $this->tab_width - 1;
  880. // Re-usable patterns to match list item bullets and number markers:
  881. $marker_ul_re = '[*+-]';
  882. $marker_ol_re = '\d+[\.]';
  883. $markers_relist = array(
  884. $marker_ul_re => $marker_ol_re,
  885. $marker_ol_re => $marker_ul_re,
  886. );
  887. foreach ($markers_relist as $marker_re => $other_marker_re) {
  888. // Re-usable pattern to match any entirel ul or ol list:
  889. $whole_list_re = '
  890. ( # $1 = whole list
  891. ( # $2
  892. ([ ]{0,'.$less_than_tab.'}) # $3 = number of spaces
  893. ('.$marker_re.') # $4 = first list item marker
  894. [ ]+
  895. )
  896. (?s:.+?)
  897. ( # $5
  898. \z
  899. |
  900. \n{2,}
  901. (?=\S)
  902. (?! # Negative lookahead for another list item marker
  903. [ ]*
  904. '.$marker_re.'[ ]+
  905. )
  906. |
  907. (?= # Lookahead for another kind of list
  908. \n
  909. \3 # Must have the same indentation
  910. '.$other_marker_re.'[ ]+
  911. )
  912. )
  913. )
  914. '; // mx
  915. // We use a different prefix before nested lists than top-level lists.
  916. //See extended comment in _ProcessListItems().
  917. if ($this->list_level) {
  918. $text = preg_replace_callback('{
  919. ^
  920. '.$whole_list_re.'
  921. }mx',
  922. array($this, '_doLists_callback'), $text);
  923. } else {
  924. $text = preg_replace_callback('{
  925. (?:(?<=\n)\n|\A\n?) # Must eat the newline
  926. '.$whole_list_re.'
  927. }mx',
  928. array($this, '_doLists_callback'), $text);
  929. }
  930. }
  931. return $text;
  932. }
  933. /**
  934. * List parsing callback
  935. * @param array $matches
  936. * @return string
  937. */
  938. protected function _doLists_callback($matches) {
  939. // Re-usable patterns to match list item bullets and number markers:
  940. $marker_ul_re = '[*+-]';
  941. $marker_ol_re = '\d+[\.]';
  942. $marker_any_re = "(?:$marker_ul_re|$marker_ol_re)";
  943. $marker_ol_start_re = '[0-9]+';
  944. $list = $matches[1];
  945. $list_type = preg_match("/$marker_ul_re/", $matches[4]) ? "ul" : "ol";
  946. $marker_any_re = ( $list_type == "ul" ? $marker_ul_re : $marker_ol_re );
  947. $list .= "\n";
  948. $result = $this->processListItems($list, $marker_any_re);
  949. $ol_start = 1;
  950. if ($this->enhanced_ordered_list) {
  951. // Get the start number for ordered list.
  952. if ($list_type == 'ol') {
  953. $ol_start_array = array();
  954. $ol_start_check = preg_match("/$marker_ol_start_re/", $matches[4], $ol_start_array);
  955. if ($ol_start_check){
  956. $ol_start = $ol_start_array[0];
  957. }
  958. }
  959. }
  960. if ($ol_start > 1 && $list_type == 'ol'){
  961. $result = $this->hashBlock("<$list_type start=\"$ol_start\">\n" . $result . "</$list_type>");
  962. } else {
  963. $result = $this->hashBlock("<$list_type>\n" . $result . "</$list_type>");
  964. }
  965. return "\n". $result ."\n\n";
  966. }
  967. /**
  968. * Nesting tracker for list levels
  969. * @var integer
  970. */
  971. protected $list_level = 0;
  972. /**
  973. * Process the contents of a single ordered or unordered list, splitting it
  974. * into individual list items.
  975. * @param string $list_str
  976. * @param string $marker_any_re
  977. * @return string
  978. */
  979. protected function processListItems($list_str, $marker_any_re) {
  980. /**
  981. * The $this->list_level global keeps track of when we're inside a list.
  982. * Each time we enter a list, we increment it; when we leave a list,
  983. * we decrement. If it's zero, we're not in a list anymore.
  984. *
  985. * We do this because when we're not inside a list, we want to treat
  986. * something like this:
  987. *
  988. * I recommend upgrading to version
  989. * 8. Oops, now this line is treated
  990. * as a sub-list.
  991. *
  992. * As a single paragraph, despite the fact that the second line starts
  993. * with a digit-period-space sequence.
  994. *
  995. * Whereas when we're inside a list (or sub-list), that line will be
  996. * treated as the start of a sub-list. What a kludge, huh? This is
  997. * an aspect of Markdown's syntax that's hard to parse perfectly
  998. * without resorting to mind-reading. Perhaps the solution is to
  999. * change the syntax rules such that sub-lists must start with a
  1000. * starting cardinal number; e.g. "1." or "a.".
  1001. */
  1002. $this->list_level++;
  1003. // Trim trailing blank lines:
  1004. $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
  1005. $list_str = preg_replace_callback('{
  1006. (\n)? # leading line = $1
  1007. (^[ ]*) # leading whitespace = $2
  1008. ('.$marker_any_re.' # list marker and space = $3
  1009. (?:[ ]+|(?=\n)) # space only required if item is not empty
  1010. )
  1011. ((?s:.*?)) # list item text = $4
  1012. (?:(\n+(?=\n))|\n) # tailing blank line = $5
  1013. (?= \n* (\z | \2 ('.$marker_any_re.') (?:[ ]+|(?=\n))))
  1014. }xm',
  1015. array($this, '_processListItems_callback'), $list_str);
  1016. $this->list_level--;
  1017. return $list_str;
  1018. }
  1019. /**
  1020. * List item parsing callback
  1021. * @param array $matches
  1022. * @return string
  1023. */
  1024. protected function _processListItems_callback($matches) {
  1025. $item = $matches[4];
  1026. $leading_line =& $matches[1];
  1027. $leading_space =& $matches[2];
  1028. $marker_space = $matches[3];
  1029. $tailing_blank_line =& $matches[5];
  1030. if ($leading_line || $tailing_blank_line ||
  1031. preg_match('/\n{2,}/', $item))
  1032. {
  1033. // Replace marker with the appropriate whitespace indentation
  1034. $item = $leading_space . str_repeat(' ', strlen($marker_space)) . $item;
  1035. $item = $this->runBlockGamut($this->outdent($item)."\n");
  1036. } else {
  1037. // Recursion for sub-lists:
  1038. $item = $this->doLists($this->outdent($item));
  1039. $item = $this->formParagraphs($item, false);
  1040. }
  1041. return "<li>" . $item . "</li>\n";
  1042. }
  1043. /**
  1044. * Process Markdown `<pre><code>` blocks.
  1045. * @param string $text
  1046. * @return string
  1047. */
  1048. protected function doCodeBlocks($text) {
  1049. $text = preg_replace_callback('{
  1050. (?:\n\n|\A\n?)
  1051. ( # $1 = the code block -- one or more lines, starting with a space/tab
  1052. (?>
  1053. [ ]{'.$this->tab_width.'} # Lines must start with a tab or a tab-width of spaces
  1054. .*\n+
  1055. )+
  1056. )
  1057. ((?=^[ ]{0,'.$this->tab_width.'}\S)|\Z) # Lookahead for non-space at line-start, or end of doc
  1058. }xm',
  1059. array($this, '_doCodeBlocks_callback'), $text);
  1060. return $text;
  1061. }
  1062. /**
  1063. * Code block parsing callback
  1064. * @param array $matches
  1065. * @return string
  1066. */
  1067. protected function _doCodeBlocks_callback($matches) {
  1068. $codeblock = $matches[1];
  1069. $codeblock = $this->outdent($codeblock);
  1070. if (is_callable($this->code_block_content_func)) {
  1071. $codeblock = call_user_func($this->code_block_content_func, $codeblock, "");
  1072. } else {
  1073. $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
  1074. }
  1075. # trim leading newlines and trailing newlines
  1076. $codeblock = preg_replace('/\A\n+|\n+\z/', '', $codeblock);
  1077. $codeblock = "<pre><code>$codeblock\n</code></pre>";
  1078. return "\n\n" . $this->hashBlock($codeblock) . "\n\n";
  1079. }
  1080. /**
  1081. * Create a code span markup for $code. Called from handleSpanToken.
  1082. * @param string $code
  1083. * @return string
  1084. */
  1085. protected function makeCodeSpan($code) {
  1086. if (is_callable($this->code_span_content_func)) {
  1087. $code = call_user_func($this->code_span_content_func, $code);
  1088. } else {
  1089. $code = htmlspecialchars(trim($code), ENT_NOQUOTES);
  1090. }
  1091. return $this->hashPart("<code>$code</code>");
  1092. }
  1093. /**
  1094. * Define the emphasis operators with their regex matches
  1095. * @var array
  1096. */
  1097. protected $em_relist = array(
  1098. '' => '(?:(?<!\*)\*(?!\*)|(?<!_)_(?!_))(?![\.,:;]?\s)',
  1099. '*' => '(?<![\s*])\*(?!\*)',
  1100. '_' => '(?<![\s_])_(?!_)',
  1101. );
  1102. /**
  1103. * Define the strong operators with their regex matches
  1104. * @var array
  1105. */
  1106. protected $strong_relist = array(
  1107. '' => '(?:(?<!\*)\*\*(?!\*)|(?<!_)__(?!_))(?![\.,:;]?\s)',
  1108. '**' => '(?<![\s*])\*\*(?!\*)',
  1109. '__' => '(?<![\s_])__(?!_)',
  1110. );
  1111. /**
  1112. * Define the emphasis + strong operators with their regex matches
  1113. * @var array
  1114. */
  1115. protected $em_strong_relist = array(
  1116. '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<!_)___(?!_))(?![\.,:;]?\s)',
  1117. '***' => '(?<![\s*])\*\*\*(?!\*)',
  1118. '___' => '(?<![\s_])___(?!_)',
  1119. );
  1120. /**
  1121. * Container for prepared regular expressions
  1122. * @var array
  1123. */
  1124. protected $em_strong_prepared_relist;
  1125. /**
  1126. * Prepare regular expressions for searching emphasis tokens in any
  1127. * context.
  1128. * @return void
  1129. */
  1130. protected function prepareItalicsAndBold() {
  1131. foreach ($this->em_relist as $em => $em_re) {
  1132. foreach ($this->strong_relist as $strong => $strong_re) {
  1133. // Construct list of allowed token expressions.
  1134. $token_relist = array();
  1135. if (isset($this->em_strong_relist["$em$strong"])) {
  1136. $token_relist[] = $this->em_strong_relist["$em$strong"];
  1137. }
  1138. $token_relist[] = $em_re;
  1139. $token_relist[] = $strong_re;
  1140. // Construct master expression from list.
  1141. $token_re = '{(' . implode('|', $token_relist) . ')}';
  1142. $this->em_strong_prepared_relist["$em$strong"] = $token_re;
  1143. }
  1144. }
  1145. }
  1146. /**
  1147. * Convert Markdown italics (emphasis) and bold (strong) to HTML
  1148. * @param string $text
  1149. * @return string
  1150. */
  1151. protected function doItalicsAndBold($text) {
  1152. if ($this->in_emphasis_processing) {
  1153. return $text; // avoid reentrency
  1154. }
  1155. $this->in_emphasis_processing = true;
  1156. $token_stack = array('');
  1157. $text_stack = array('');
  1158. $em = '';
  1159. $strong = '';
  1160. $tree_char_em = false;
  1161. while (1) {
  1162. // Get prepared regular expression for seraching emphasis tokens
  1163. // in current context.
  1164. $token_re = $this->em_strong_prepared_relist["$em$strong"];
  1165. // Each loop iteration search for the next emphasis token.
  1166. // Each token is then passed to handleSpanToken.
  1167. $parts = preg_split($token_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
  1168. $text_stack[0] .= $parts[0];
  1169. $token =& $parts[1];
  1170. $text =& $parts[2];
  1171. if (empty($token)) {
  1172. // Reached end of text span: empty stack without emitting.
  1173. // any more emphasis.
  1174. while ($token_stack[0]) {
  1175. $text_stack[1] .= array_shift($token_stack);
  1176. $text_stack[0] .= array_shift($text_stack);
  1177. }
  1178. break;
  1179. }
  1180. $token_len = strlen($token);
  1181. if ($tree_char_em) {
  1182. // Reached closing marker while inside a three-char emphasis.
  1183. if ($token_len == 3) {
  1184. // Three-char closing marker, close em and strong.
  1185. array_shift($token_stack);
  1186. $span = array_shift($text_stack);
  1187. $span = $this->runSpanGamut($span);
  1188. $span = "<strong><em>$span</em></strong>";
  1189. $text_stack[0] .= $this->hashPart($span);
  1190. $em = '';
  1191. $strong = '';
  1192. } else {
  1193. // Other closing marker: close one em or strong and
  1194. // change current token state to match the other
  1195. $token_stack[0] = str_repeat($token[0], 3-$token_len);
  1196. $tag = $token_len == 2 ? "strong" : "em";
  1197. $span = $text_stack[0];
  1198. $span = $this->runSpanGamut($span);
  1199. $span = "<$tag>$span</$tag>";
  1200. $text_stack[0] = $this->hashPart($span);
  1201. $$tag = ''; // $$tag stands for $em or $strong
  1202. }
  1203. $tree_char_em = false;
  1204. } else if ($token_len == 3) {
  1205. if ($em) {
  1206. // Reached closing marker for both em and strong.
  1207. // Closing strong marker:
  1208. for ($i = 0; $i < 2; ++$i) {
  1209. $shifted_token = array_shift($token_stack);
  1210. $tag = strlen($shifted_token) == 2 ? "strong" : "em";
  1211. $span = array_shift($text_stack);
  1212. $span = $this->runSpanGamut($span);
  1213. $span = "<$tag>$span</$tag>";
  1214. $text_stack[0] .= $this->hashPart($span);
  1215. $$tag = ''; // $$tag stands for $em or $strong
  1216. }
  1217. } else {
  1218. // Reached opening three-char emphasis marker. Push on token
  1219. // stack; will be handled by the special condition above.
  1220. $em = $token[0];
  1221. $strong = "$em$em";
  1222. array_unshift($token_stack, $token);
  1223. array_unshift($text_stack, '');
  1224. $tree_char_em = true;
  1225. }
  1226. } else if ($token_len == 2) {
  1227. if ($strong) {
  1228. // Unwind any dangling emphasis marker:
  1229. if (strlen($token_stack[0]) == 1) {
  1230. $text_stack[1] .= array_shift($token_stack);
  1231. $text_stack[0] .= array_shift($text_stack);
  1232. $em = '';
  1233. }
  1234. // Closing strong marker:
  1235. array_shift($token_stack);
  1236. $span = array_shift($text_stack);
  1237. $span = $this->runSpanGamut($span);
  1238. $span = "<strong>$span</strong>";
  1239. $text_stack[0] .= $this->hashPart($span);
  1240. $strong = '';
  1241. } else {
  1242. array_unshift($token_stack, $token);
  1243. array_unshift($text_stack, '');
  1244. $strong = $token;
  1245. }
  1246. } else {
  1247. // Here $token_len == 1
  1248. if ($em) {
  1249. if (strlen($token_stack[0]) == 1) {
  1250. // Closing emphasis marker:
  1251. array_shift($token_stack);
  1252. $span = array_shift($text_stack);
  1253. $span = $this->runSpanGamut($span);
  1254. $span = "<em>$span</em>";
  1255. $text_stack[0] .= $this->hashPart($span);
  1256. $em = '';
  1257. } else {
  1258. $text_stack[0] .= $token;
  1259. }
  1260. } else {
  1261. array_unshift($token_stack, $token);
  1262. array_unshift($text_stack, '');
  1263. $em = $token;
  1264. }
  1265. }
  1266. }
  1267. $this->in_emphasis_processing = false;
  1268. return $text_stack[0];
  1269. }
  1270. /**
  1271. * Parse Markdown blockquotes to HTML
  1272. * @param string $text
  1273. * @return string
  1274. */
  1275. protected function doBlockQuotes($text) {
  1276. $text = preg_replace_callback('/
  1277. ( # Wrap whole match in $1
  1278. (?>
  1279. ^[ ]*>[ ]? # ">" at the start of a line
  1280. .+\n # rest of the first line
  1281. (.+\n)* # subsequent consecutive lines
  1282. \n* # blanks
  1283. )+
  1284. )
  1285. /xm',
  1286. array($this, '_doBlockQuotes_callback'), $text);
  1287. return $text;
  1288. }
  1289. /**
  1290. * Blockquote parsing callback
  1291. * @param array $matches
  1292. * @return string
  1293. */
  1294. protected function _doBlockQuotes_callback($matches) {
  1295. $bq = $matches[1];
  1296. // trim one level of quoting - trim whitespace-only lines
  1297. $bq = preg_replace('/^[ ]*>[ ]?|^[ ]+$/m', '', $bq);
  1298. $bq = $this->runBlockGamut($bq); // recurse
  1299. $bq = preg_replace('/^/m', " ", $bq);
  1300. // These leading spaces cause problem with <pre> content,
  1301. // so we need to fix that:
  1302. $bq = preg_replace_callback('{(\s*<pre>.+?</pre>)}sx',
  1303. array($this, '_doBlockQuotes_callback2'), $bq);
  1304. return "\n" . $this->hashBlock("<blockquote>\n$bq\n</blockquote>") . "\n\n";
  1305. }
  1306. /**
  1307. * Blockquote parsing callback
  1308. * @param array $matches
  1309. * @return string
  1310. */
  1311. protected function _doBlockQuotes_callback2($matches) {
  1312. $pre = $matches[1];
  1313. $pre = preg_replace('/^ /m', '', $pre);
  1314. return $pre;
  1315. }
  1316. /**
  1317. * Parse paragraphs
  1318. *
  1319. * @param string $text String to process in paragraphs
  1320. * @param boolean $wrap_in_p Whether paragraphs should be wrapped in <p> tags
  1321. * @return string
  1322. */
  1323. protected function formParagraphs($text, $wrap_in_p = true) {
  1324. // Strip leading and trailing lines:
  1325. $text = preg_replace('/\A\n+|\n+\z/', '', $text);
  1326. $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
  1327. // Wrap <p> tags and unhashify HTML blocks
  1328. foreach ($grafs as $key => $value) {
  1329. if (!preg_match('/^B\x1A[0-9]+B$/', $value)) {
  1330. // Is a paragraph.
  1331. $value = $this->runSpanGamut($value);
  1332. if ($wrap_in_p) {
  1333. $value = preg_replace('/^([ ]*)/', "<p>", $value);
  1334. $value .= "</p>";
  1335. }
  1336. $grafs[$key] = $this->unhash($value);
  1337. } else {
  1338. // Is a block.
  1339. // Modify elements of @grafs in-place...
  1340. $graf = $value;
  1341. $block = $this->html_hashes[$graf];
  1342. $graf = $block;
  1343. // if (preg_match('{
  1344. // \A
  1345. // ( # $1 = <div> tag
  1346. // <div \s+
  1347. // [^>]*
  1348. // \b
  1349. // markdown\s*=\s* ([\'"]) # $2 = attr quote char
  1350. // 1
  1351. // \2
  1352. // [^>]*
  1353. // >
  1354. // )
  1355. // ( # $3 = contents
  1356. // .*
  1357. // )
  1358. // (</div>) # $4 = closing tag
  1359. // \z
  1360. // }xs', $block, $matches))
  1361. // {
  1362. // list(, $div_open, , $div_content, $div_close) = $matches;
  1363. //
  1364. // // We can't call Markdown(), because that resets the hash;
  1365. // // that initialization code should be pulled into its own sub, though.
  1366. // $div_content = $this->hashHTMLBlocks($div_content);
  1367. //
  1368. // // Run document gamut methods on the content.
  1369. // foreach ($this->document_gamut as $method => $priority) {
  1370. // $div_content = $this->$method($div_content);
  1371. // }
  1372. //
  1373. // $div_open = preg_replace(
  1374. // '{\smarkdown\s*=\s*([\'"]).+?\1}', '', $div_open);
  1375. //
  1376. // $graf = $div_open . "\n" . $div_content . "\n" . $div_close;
  1377. // }
  1378. $grafs[$key] = $graf;
  1379. }
  1380. }
  1381. return implode("\n\n", $grafs);
  1382. }
  1383. /**
  1384. * Encode text for a double-quoted HTML attribute. This function
  1385. * is *not* suitable for attributes enclosed in single quotes.
  1386. * @param string $text
  1387. * @return string
  1388. */
  1389. protected function encodeAttribute($text) {
  1390. $text = $this->encodeAmpsAndAngles($text);
  1391. $text = str_replace('"', '&quot;', $text);
  1392. return $text;
  1393. }
  1394. /**
  1395. * Encode text for a double-quoted HTML attribute containing a URL,
  1396. * applying the URL filter if set. Also generates the textual
  1397. * representation for the URL (removing mailto: or tel:) storing it in $text.
  1398. * This function is *not* suitable for attributes enclosed in single quotes.
  1399. *
  1400. * @param string $url
  1401. * @param string $text Passed by reference
  1402. * @return string URL
  1403. */
  1404. protected function encodeURLAttribute($url, &$text = null) {
  1405. if (is_callable($this->url_filter_func)) {
  1406. $url = call_user_func($this->url_filter_func, $url);
  1407. }
  1408. if (preg_match('{^mailto:}i', $url)) {
  1409. $url = $this->encodeEntityObfuscatedAttribute($url, $text, 7);
  1410. } else if (preg_match('{^tel:}i', $url)) {
  1411. $url = $this->encodeAttribute($url);
  1412. $text = substr($url, 4);
  1413. } else {
  1414. $url = $this->encodeAttribute($url);
  1415. $text = $url;
  1416. }
  1417. return $url;
  1418. }
  1419. /**
  1420. * Smart processing for ampersands and angle brackets that need to
  1421. * be encoded. Valid character entities are left alone unless the
  1422. * no-entities mode is set.
  1423. * @param string $text
  1424. * @return string
  1425. */
  1426. protected function encodeAmpsAndAngles($text) {
  1427. if ($this->no_entities) {
  1428. $text = str_replace('&', '&amp;', $text);
  1429. } else {
  1430. // Ampersand-encoding based entirely on Nat Irons's Amputator
  1431. // MT plugin: <http://bumppo.net/projects/amputator/>
  1432. $text = preg_replace('/&(?!#?[xX]?(?:[0-9a-fA-F]+|\w+);)/',
  1433. '&amp;', $text);
  1434. }
  1435. // Encode remaining <'s
  1436. $text = str_replace('<', '&lt;', $text);
  1437. return $text;
  1438. }
  1439. /**
  1440. * Parse Markdown automatic links to anchor HTML tags
  1441. * @param string $text
  1442. * @return string
  1443. */
  1444. protected function doAutoLinks($text) {
  1445. $text = preg_replace_callback('{<((https?|ftp|dict|tel):[^\'">\s]+)>}i',
  1446. array($this, '_doAutoLinks_url_callback'), $text);
  1447. // Email addresses: <address@domain.foo>
  1448. $text = preg_replace_callback('{
  1449. <
  1450. (?:mailto:)?
  1451. (
  1452. (?:
  1453. [-!#$%&\'*+/=?^_`.{|}~\w\x80-\xFF]+
  1454. |
  1455. ".*?"
  1456. )
  1457. \@
  1458. (?:
  1459. [-a-z0-9\x80-\xFF]+(\.[-a-z0-9\x80-\xFF]+)*\.[a-z]+
  1460. |
  1461. \[[\d.a-fA-F:]+\] # IPv4 & IPv6
  1462. )
  1463. )
  1464. >
  1465. }xi',
  1466. array($this, '_doAutoLinks_email_callback'), $text);
  1467. return $text;
  1468. }
  1469. /**
  1470. * Parse URL callback
  1471. * @param array $matches
  1472. * @return string
  1473. */
  1474. protected function _doAutoLinks_url_callback($matches) {
  1475. $url = $this->encodeURLAttribute($matches[1], $text);
  1476. $link = "<a href=\"$url\">$text</a>";
  1477. return $this->hashPart($link);
  1478. }
  1479. /**
  1480. * Parse email address callback
  1481. * @param array $matches
  1482. * @return string
  1483. */
  1484. protected function _doAutoLinks_email_callback($matches) {
  1485. $addr = $matches[1];
  1486. $url = $this->encodeURLAttribute("mailto:$addr", $text);
  1487. $link = "<a href=\"$url\">$text</a>";
  1488. return $this->hashPart($link);
  1489. }
  1490. /**
  1491. * Input: some text to obfuscate, e.g. "mailto:foo@example.com"
  1492. *
  1493. * Output: the same text but with most characters encoded as either a
  1494. * decimal or hex entity, in the hopes of foiling most address
  1495. * harvesting spam bots. E.g.:
  1496. *
  1497. * &#109;&#x61;&#105;&#x6c;&#116;&#x6f;&#58;&#x66;o&#111;
  1498. * &#x40;&#101;&#x78;&#97;&#x6d;&#112;&#x6c;&#101;&#46;&#x63;&#111;
  1499. * &#x6d;
  1500. *
  1501. * Note: the additional output $tail is assigned the same value as the
  1502. * ouput, minus the number of characters specified by $head_length.
  1503. *
  1504. * Based by a filter by Matthew Wickline, posted to BBEdit-Talk.
  1505. * With some optimizations by Milian Wolff. Forced encoding of HTML
  1506. * attribute special characters by Allan Odgaard.
  1507. *
  1508. * @param string $text
  1509. * @param string $tail Passed by reference
  1510. * @param integer $head_length
  1511. * @return string
  1512. */
  1513. protected function encodeEntityObfuscatedAttribute($text, &$tail = null, $head_length = 0) {
  1514. if ($text == "") {
  1515. return $tail = "";
  1516. }
  1517. $chars = preg_split('/(?<!^)(?!$)/', $text);
  1518. $seed = (int)abs(crc32($text) / strlen($text)); // Deterministic seed.
  1519. foreach ($chars as $key => $char) {
  1520. $ord = ord($char);
  1521. // Ignore non-ascii chars.
  1522. if ($ord < 128) {
  1523. $r = ($seed * (1 + $key)) % 100; // Pseudo-random function.
  1524. // roughly 10% raw, 45% hex, 45% dec
  1525. // '@' *must* be encoded. I insist.
  1526. // '"' and '>' have to be encoded inside the attribute
  1527. if ($r > 90 && strpos('@"&>', $char) === false) {
  1528. /* do nothing */
  1529. } else if ($r < 45) {
  1530. $chars[$key] = '&#x'.dechex($ord).';';
  1531. } else {
  1532. $chars[$key] = '&#'.$ord.';';
  1533. }
  1534. }
  1535. }
  1536. $text = implode('', $chars);
  1537. $tail = $head_length ? implode('', array_slice($chars, $head_length)) : $text;
  1538. return $text;
  1539. }
  1540. /**
  1541. * Take the string $str and parse it into tokens, hashing embeded HTML,
  1542. * escaped characters and handling code spans.
  1543. * @param string $str
  1544. * @return string
  1545. */
  1546. protected function parseSpan($str) {
  1547. $output = '';
  1548. $span_re = '{
  1549. (
  1550. \\\\'.$this->escape_chars_re.'
  1551. |
  1552. (?<![`\\\\])
  1553. `+ # code span marker
  1554. '.( $this->no_markup ? '' : '
  1555. |
  1556. <!-- .*? --> # comment
  1557. |
  1558. <\?.*?\?> | <%.*?%> # processing instruction
  1559. |
  1560. <[!$]?[-a-zA-Z0-9:_]+ # regular tags
  1561. (?>
  1562. \s
  1563. (?>[^"\'>]+|"[^"]*"|\'[^\']*\')*
  1564. )?
  1565. >
  1566. |
  1567. <[-a-zA-Z0-9:_]+\s*/> # xml-style empty tag
  1568. |
  1569. </[-a-zA-Z0-9:_]+\s*> # closing tag
  1570. ').'
  1571. )
  1572. }xs';
  1573. while (1) {
  1574. // Each loop iteration seach for either the next tag, the next
  1575. // openning code span marker, or the next escaped character.
  1576. // Each token is then passed to handleSpanToken.
  1577. $parts = preg_split($span_re, $str, 2, PREG_SPLIT_DELIM_CAPTURE);
  1578. // Create token from text preceding tag.
  1579. if ($parts[0] != "") {
  1580. $output .= $parts[0];
  1581. }
  1582. // Check if we reach the end.
  1583. if (isset($parts[1])) {
  1584. $output .= $this->handleSpanToken($parts[1], $parts[2]);
  1585. $str = $parts[2];
  1586. } else {
  1587. break;
  1588. }
  1589. }
  1590. return $output;
  1591. }
  1592. /**
  1593. * Handle $token provided by parseSpan by determining its nature and
  1594. * returning the corresponding value that should replace it.
  1595. * @param string $token
  1596. * @param string $str Passed by reference
  1597. * @return string
  1598. */
  1599. protected function handleSpanToken($token, &$str) {
  1600. switch ($token[0]) {
  1601. case "\\":
  1602. return $this->hashPart("&#". ord($token[1]). ";");
  1603. case "`":
  1604. // Search for end marker in remaining text.
  1605. if (preg_match('/^(.*?[^`])'.preg_quote($token).'(?!`)(.*)$/sm',
  1606. $str, $matches))
  1607. {
  1608. $str = $matches[2];
  1609. $codespan = $this->makeCodeSpan($matches[1]);
  1610. return $this->hashPart($codespan);
  1611. }
  1612. return $token; // Return as text since no ending marker found.
  1613. default:
  1614. return $this->hashPart($token);
  1615. }
  1616. }
  1617. /**
  1618. * Remove one level of line-leading tabs or spaces
  1619. * @param string $text
  1620. * @return string
  1621. */
  1622. protected function outdent($text) {
  1623. return preg_replace('/^(\t|[ ]{1,' . $this->tab_width . '})/m', '', $text);
  1624. }
  1625. /**
  1626. * String length function for detab. `_initDetab` will create a function to
  1627. * handle UTF-8 if the default function does not exist.
  1628. * @var string
  1629. */
  1630. protected $utf8_strlen = 'mb_strlen';
  1631. /**
  1632. * Replace tabs with the appropriate amount of spaces.
  1633. *
  1634. * For each line we separate the line in blocks delemited by tab characters.
  1635. * Then we reconstruct every line by adding the appropriate number of space
  1636. * between each blocks.
  1637. *
  1638. * @param string $text
  1639. * @return string
  1640. */
  1641. protected function detab($text) {
  1642. $text = preg_replace_callback('/^.*\t.*$/m',
  1643. array($this, '_detab_callback'), $text);
  1644. return $text;
  1645. }
  1646. /**
  1647. * Replace tabs callback
  1648. * @param string $matches
  1649. * @return string
  1650. */
  1651. protected function _detab_callback($matches) {
  1652. $line = $matches[0];
  1653. $strlen = $this->utf8_strlen; // strlen function for UTF-8.
  1654. // Split in blocks.
  1655. $blocks = explode("\t", $line);
  1656. // Add each blocks to the line.
  1657. $line = $blocks[0];
  1658. unset($blocks[0]); // Do not add first block twice.
  1659. foreach ($blocks as $block) {
  1660. // Calculate amount of space, insert spaces, insert block.
  1661. $amount = $this->tab_width -
  1662. $strlen($line, 'UTF-8') % $this->tab_width;
  1663. $line .= str_repeat(" ", $amount) . $block;
  1664. }
  1665. return $line;
  1666. }
  1667. /**
  1668. * Check for the availability of the function in the `utf8_strlen` property
  1669. * (initially `mb_strlen`). If the function is not available, create a
  1670. * function that will loosely count the number of UTF-8 characters with a
  1671. * regular expression.
  1672. * @return void
  1673. */
  1674. protected function _initDetab() {
  1675. if (function_exists($this->utf8_strlen)) {
  1676. return;
  1677. }
  1678. $this->utf8_strlen = function($text) {
  1679. return preg_match_all('/[\x00-\xBF]|[\xC0-\xFF][\x80-\xBF]*/', $text, $m);
  1680. };
  1681. }
  1682. /**
  1683. * Swap back in all the tags hashed by _HashHTMLBlocks.
  1684. * @param string $text
  1685. * @return string
  1686. */
  1687. protected function unhash($text) {
  1688. return preg_replace_callback('/(.)\x1A[0-9]+\1/',
  1689. array($this, '_unhash_callback'), $text);
  1690. }
  1691. /**
  1692. * Unhashing callback
  1693. * @param array $matches
  1694. * @return string
  1695. */
  1696. protected function _unhash_callback($matches) {
  1697. return $this->html_hashes[$matches[0]];
  1698. }
  1699. }