MarkdownExtra.php 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780178117821783178417851786178717881789179017911792179317941795
  1. <?php
  2. /**
  3. * Markdown Extra - 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 Extra Parser Class
  13. */
  14. class MarkdownExtra extends \Michelf\Markdown {
  15. /**
  16. * Configuration variables
  17. */
  18. /**
  19. * Prefix for footnote ids.
  20. * @var string
  21. */
  22. public $fn_id_prefix = "";
  23. /**
  24. * Optional title attribute for footnote links and backlinks.
  25. * @var string
  26. */
  27. public $fn_link_title = "";
  28. public $fn_backlink_title = "";
  29. /**
  30. * Optional class attribute for footnote links and backlinks.
  31. * @var string
  32. */
  33. public $fn_link_class = "footnote-ref";
  34. public $fn_backlink_class = "footnote-backref";
  35. /**
  36. * Content to be displayed within footnote backlinks. The default is '↩';
  37. * the U+FE0E on the end is a Unicode variant selector used to prevent iOS
  38. * from displaying the arrow character as an emoji.
  39. * @var string
  40. */
  41. public $fn_backlink_html = '&#8617;&#xFE0E;';
  42. /**
  43. * Class name for table cell alignment (%% replaced left/center/right)
  44. * For instance: 'go-%%' becomes 'go-left' or 'go-right' or 'go-center'
  45. * If empty, the align attribute is used instead of a class name.
  46. * @var string
  47. */
  48. public $table_align_class_tmpl = '';
  49. /**
  50. * Optional class prefix for fenced code block.
  51. * @var string
  52. */
  53. public $code_class_prefix = "";
  54. /**
  55. * Class attribute for code blocks goes on the `code` tag;
  56. * setting this to true will put attributes on the `pre` tag instead.
  57. * @var boolean
  58. */
  59. public $code_attr_on_pre = false;
  60. /**
  61. * Predefined abbreviations.
  62. * @var array
  63. */
  64. public $predef_abbr = array();
  65. /**
  66. * Only convert atx-style headers if there's a space between the header and #
  67. * @var boolean
  68. */
  69. public $hashtag_protection = false;
  70. /**
  71. * Parser implementation
  72. */
  73. /**
  74. * Constructor function. Initialize the parser object.
  75. * @return void
  76. */
  77. public function __construct() {
  78. // Add extra escapable characters before parent constructor
  79. // initialize the table.
  80. $this->escape_chars .= ':|';
  81. // Insert extra document, block, and span transformations.
  82. // Parent constructor will do the sorting.
  83. $this->document_gamut += array(
  84. "doFencedCodeBlocks" => 5,
  85. "stripFootnotes" => 15,
  86. "stripAbbreviations" => 25,
  87. "appendFootnotes" => 50,
  88. );
  89. $this->block_gamut += array(
  90. "doFencedCodeBlocks" => 5,
  91. "doTables" => 15,
  92. "doDefLists" => 45,
  93. );
  94. $this->span_gamut += array(
  95. "doFootnotes" => 5,
  96. "doAbbreviations" => 70,
  97. );
  98. $this->enhanced_ordered_list = true;
  99. parent::__construct();
  100. }
  101. /**
  102. * Extra variables used during extra transformations.
  103. * @var array
  104. */
  105. protected $footnotes = array();
  106. protected $footnotes_ordered = array();
  107. protected $footnotes_ref_count = array();
  108. protected $footnotes_numbers = array();
  109. protected $abbr_desciptions = array();
  110. /** @var string */
  111. protected $abbr_word_re = '';
  112. /**
  113. * Give the current footnote number.
  114. * @var integer
  115. */
  116. protected $footnote_counter = 1;
  117. /**
  118. * Setting up Extra-specific variables.
  119. */
  120. protected function setup() {
  121. parent::setup();
  122. $this->footnotes = array();
  123. $this->footnotes_ordered = array();
  124. $this->footnotes_ref_count = array();
  125. $this->footnotes_numbers = array();
  126. $this->abbr_desciptions = array();
  127. $this->abbr_word_re = '';
  128. $this->footnote_counter = 1;
  129. foreach ($this->predef_abbr as $abbr_word => $abbr_desc) {
  130. if ($this->abbr_word_re)
  131. $this->abbr_word_re .= '|';
  132. $this->abbr_word_re .= preg_quote($abbr_word);
  133. $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
  134. }
  135. }
  136. /**
  137. * Clearing Extra-specific variables.
  138. */
  139. protected function teardown() {
  140. $this->footnotes = array();
  141. $this->footnotes_ordered = array();
  142. $this->footnotes_ref_count = array();
  143. $this->footnotes_numbers = array();
  144. $this->abbr_desciptions = array();
  145. $this->abbr_word_re = '';
  146. parent::teardown();
  147. }
  148. /**
  149. * Extra attribute parser
  150. */
  151. /**
  152. * Expression to use to catch attributes (includes the braces)
  153. * @var string
  154. */
  155. protected $id_class_attr_catch_re = '\{((?>[ ]*[#.a-z][-_:a-zA-Z0-9=]+){1,})[ ]*\}';
  156. /**
  157. * Expression to use when parsing in a context when no capture is desired
  158. * @var string
  159. */
  160. protected $id_class_attr_nocatch_re = '\{(?>[ ]*[#.a-z][-_:a-zA-Z0-9=]+){1,}[ ]*\}';
  161. /**
  162. * Parse attributes caught by the $this->id_class_attr_catch_re expression
  163. * and return the HTML-formatted list of attributes.
  164. *
  165. * Currently supported attributes are .class and #id.
  166. *
  167. * In addition, this method also supports supplying a default Id value,
  168. * which will be used to populate the id attribute in case it was not
  169. * overridden.
  170. * @param string $tag_name
  171. * @param string $attr
  172. * @param mixed $defaultIdValue
  173. * @param array $classes
  174. * @return string
  175. */
  176. protected function doExtraAttributes($tag_name, $attr, $defaultIdValue = null, $classes = array()) {
  177. if (empty($attr) && !$defaultIdValue && empty($classes)) return "";
  178. // Split on components
  179. preg_match_all('/[#.a-z][-_:a-zA-Z0-9=]+/', $attr, $matches);
  180. $elements = $matches[0];
  181. // Handle classes and IDs (only first ID taken into account)
  182. $attributes = array();
  183. $id = false;
  184. foreach ($elements as $element) {
  185. if ($element{0} == '.') {
  186. $classes[] = substr($element, 1);
  187. } else if ($element{0} == '#') {
  188. if ($id === false) $id = substr($element, 1);
  189. } else if (strpos($element, '=') > 0) {
  190. $parts = explode('=', $element, 2);
  191. $attributes[] = $parts[0] . '="' . $parts[1] . '"';
  192. }
  193. }
  194. if (!$id) $id = $defaultIdValue;
  195. // Compose attributes as string
  196. $attr_str = "";
  197. if (!empty($id)) {
  198. $attr_str .= ' id="'.$this->encodeAttribute($id) .'"';
  199. }
  200. if (!empty($classes)) {
  201. $attr_str .= ' class="'. implode(" ", $classes) . '"';
  202. }
  203. if (!$this->no_markup && !empty($attributes)) {
  204. $attr_str .= ' '.implode(" ", $attributes);
  205. }
  206. return $attr_str;
  207. }
  208. /**
  209. * Strips link definitions from text, stores the URLs and titles in
  210. * hash references.
  211. * @param string $text
  212. * @return string
  213. */
  214. protected function stripLinkDefinitions($text) {
  215. $less_than_tab = $this->tab_width - 1;
  216. // Link defs are in the form: ^[id]: url "optional title"
  217. $text = preg_replace_callback('{
  218. ^[ ]{0,'.$less_than_tab.'}\[(.+)\][ ]?: # id = $1
  219. [ ]*
  220. \n? # maybe *one* newline
  221. [ ]*
  222. (?:
  223. <(.+?)> # url = $2
  224. |
  225. (\S+?) # url = $3
  226. )
  227. [ ]*
  228. \n? # maybe one newline
  229. [ ]*
  230. (?:
  231. (?<=\s) # lookbehind for whitespace
  232. ["(]
  233. (.*?) # title = $4
  234. [")]
  235. [ ]*
  236. )? # title is optional
  237. (?:[ ]* '.$this->id_class_attr_catch_re.' )? # $5 = extra id & class attr
  238. (?:\n+|\Z)
  239. }xm',
  240. array($this, '_stripLinkDefinitions_callback'),
  241. $text);
  242. return $text;
  243. }
  244. /**
  245. * Strip link definition callback
  246. * @param array $matches
  247. * @return string
  248. */
  249. protected function _stripLinkDefinitions_callback($matches) {
  250. $link_id = strtolower($matches[1]);
  251. $url = $matches[2] == '' ? $matches[3] : $matches[2];
  252. $this->urls[$link_id] = $url;
  253. $this->titles[$link_id] =& $matches[4];
  254. $this->ref_attr[$link_id] = $this->doExtraAttributes("", $dummy =& $matches[5]);
  255. return ''; // String that will replace the block
  256. }
  257. /**
  258. * HTML block parser
  259. */
  260. /**
  261. * Tags that are always treated as block tags
  262. * @var string
  263. */
  264. protected $block_tags_re = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend|article|section|nav|aside|hgroup|header|footer|figcaption|figure';
  265. /**
  266. * Tags treated as block tags only if the opening tag is alone on its line
  267. * @var string
  268. */
  269. protected $context_block_tags_re = 'script|noscript|style|ins|del|iframe|object|source|track|param|math|svg|canvas|audio|video';
  270. /**
  271. * Tags where markdown="1" default to span mode:
  272. * @var string
  273. */
  274. protected $contain_span_tags_re = 'p|h[1-6]|li|dd|dt|td|th|legend|address';
  275. /**
  276. * Tags which must not have their contents modified, no matter where
  277. * they appear
  278. * @var string
  279. */
  280. protected $clean_tags_re = 'script|style|math|svg';
  281. /**
  282. * Tags that do not need to be closed.
  283. * @var string
  284. */
  285. protected $auto_close_tags_re = 'hr|img|param|source|track';
  286. /**
  287. * Hashify HTML Blocks and "clean tags".
  288. *
  289. * We only want to do this for block-level HTML tags, such as headers,
  290. * lists, and tables. That's because we still want to wrap <p>s around
  291. * "paragraphs" that are wrapped in non-block-level tags, such as anchors,
  292. * phrase emphasis, and spans. The list of tags we're looking for is
  293. * hard-coded.
  294. *
  295. * This works by calling _HashHTMLBlocks_InMarkdown, which then calls
  296. * _HashHTMLBlocks_InHTML when it encounter block tags. When the markdown="1"
  297. * attribute is found within a tag, _HashHTMLBlocks_InHTML calls back
  298. * _HashHTMLBlocks_InMarkdown to handle the Markdown syntax within the tag.
  299. * These two functions are calling each other. It's recursive!
  300. * @param string $text
  301. * @return string
  302. */
  303. protected function hashHTMLBlocks($text) {
  304. if ($this->no_markup) {
  305. return $text;
  306. }
  307. // Call the HTML-in-Markdown hasher.
  308. list($text, ) = $this->_hashHTMLBlocks_inMarkdown($text);
  309. return $text;
  310. }
  311. /**
  312. * Parse markdown text, calling _HashHTMLBlocks_InHTML for block tags.
  313. *
  314. * * $indent is the number of space to be ignored when checking for code
  315. * blocks. This is important because if we don't take the indent into
  316. * account, something like this (which looks right) won't work as expected:
  317. *
  318. * <div>
  319. * <div markdown="1">
  320. * Hello World. <-- Is this a Markdown code block or text?
  321. * </div> <-- Is this a Markdown code block or a real tag?
  322. * <div>
  323. *
  324. * If you don't like this, just don't indent the tag on which
  325. * you apply the markdown="1" attribute.
  326. *
  327. * * If $enclosing_tag_re is not empty, stops at the first unmatched closing
  328. * tag with that name. Nested tags supported.
  329. *
  330. * * If $span is true, text inside must treated as span. So any double
  331. * newline will be replaced by a single newline so that it does not create
  332. * paragraphs.
  333. *
  334. * Returns an array of that form: ( processed text , remaining text )
  335. *
  336. * @param string $text
  337. * @param integer $indent
  338. * @param string $enclosing_tag_re
  339. * @param boolean $span
  340. * @return array
  341. */
  342. protected function _hashHTMLBlocks_inMarkdown($text, $indent = 0,
  343. $enclosing_tag_re = '', $span = false)
  344. {
  345. if ($text === '') return array('', '');
  346. // Regex to check for the presense of newlines around a block tag.
  347. $newline_before_re = '/(?:^\n?|\n\n)*$/';
  348. $newline_after_re =
  349. '{
  350. ^ # Start of text following the tag.
  351. (?>[ ]*<!--.*?-->)? # Optional comment.
  352. [ ]*\n # Must be followed by newline.
  353. }xs';
  354. // Regex to match any tag.
  355. $block_tag_re =
  356. '{
  357. ( # $2: Capture whole tag.
  358. </? # Any opening or closing tag.
  359. (?> # Tag name.
  360. ' . $this->block_tags_re . ' |
  361. ' . $this->context_block_tags_re . ' |
  362. ' . $this->clean_tags_re . ' |
  363. (?!\s)'.$enclosing_tag_re . '
  364. )
  365. (?:
  366. (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name.
  367. (?>
  368. ".*?" | # Double quotes (can contain `>`)
  369. \'.*?\' | # Single quotes (can contain `>`)
  370. .+? # Anything but quotes and `>`.
  371. )*?
  372. )?
  373. > # End of tag.
  374. |
  375. <!-- .*? --> # HTML Comment
  376. |
  377. <\?.*?\?> | <%.*?%> # Processing instruction
  378. |
  379. <!\[CDATA\[.*?\]\]> # CData Block
  380. ' . ( !$span ? ' # If not in span.
  381. |
  382. # Indented code block
  383. (?: ^[ ]*\n | ^ | \n[ ]*\n )
  384. [ ]{' . ($indent + 4) . '}[^\n]* \n
  385. (?>
  386. (?: [ ]{' . ($indent + 4) . '}[^\n]* | [ ]* ) \n
  387. )*
  388. |
  389. # Fenced code block marker
  390. (?<= ^ | \n )
  391. [ ]{0,' . ($indent + 3) . '}(?:~{3,}|`{3,})
  392. [ ]*
  393. (?: \.?[-_:a-zA-Z0-9]+ )? # standalone class name
  394. [ ]*
  395. (?: ' . $this->id_class_attr_nocatch_re . ' )? # extra attributes
  396. [ ]*
  397. (?= \n )
  398. ' : '' ) . ' # End (if not is span).
  399. |
  400. # Code span marker
  401. # Note, this regex needs to go after backtick fenced
  402. # code blocks but it should also be kept outside of the
  403. # "if not in span" condition adding backticks to the parser
  404. `+
  405. )
  406. }xs';
  407. $depth = 0; // Current depth inside the tag tree.
  408. $parsed = ""; // Parsed text that will be returned.
  409. // Loop through every tag until we find the closing tag of the parent
  410. // or loop until reaching the end of text if no parent tag specified.
  411. do {
  412. // Split the text using the first $tag_match pattern found.
  413. // Text before pattern will be first in the array, text after
  414. // pattern will be at the end, and between will be any catches made
  415. // by the pattern.
  416. $parts = preg_split($block_tag_re, $text, 2,
  417. PREG_SPLIT_DELIM_CAPTURE);
  418. // If in Markdown span mode, add a empty-string span-level hash
  419. // after each newline to prevent triggering any block element.
  420. if ($span) {
  421. $void = $this->hashPart("", ':');
  422. $newline = "\n$void";
  423. $parts[0] = $void . str_replace("\n", $newline, $parts[0]) . $void;
  424. }
  425. $parsed .= $parts[0]; // Text before current tag.
  426. // If end of $text has been reached. Stop loop.
  427. if (count($parts) < 3) {
  428. $text = "";
  429. break;
  430. }
  431. $tag = $parts[1]; // Tag to handle.
  432. $text = $parts[2]; // Remaining text after current tag.
  433. $tag_re = preg_quote($tag); // For use in a regular expression.
  434. // Check for: Fenced code block marker.
  435. // Note: need to recheck the whole tag to disambiguate backtick
  436. // fences from code spans
  437. if (preg_match('{^\n?([ ]{0,' . ($indent + 3) . '})(~{3,}|`{3,})[ ]*(?:\.?[-_:a-zA-Z0-9]+)?[ ]*(?:' . $this->id_class_attr_nocatch_re . ')?[ ]*\n?$}', $tag, $capture)) {
  438. // Fenced code block marker: find matching end marker.
  439. $fence_indent = strlen($capture[1]); // use captured indent in re
  440. $fence_re = $capture[2]; // use captured fence in re
  441. if (preg_match('{^(?>.*\n)*?[ ]{' . ($fence_indent) . '}' . $fence_re . '[ ]*(?:\n|$)}', $text,
  442. $matches))
  443. {
  444. // End marker found: pass text unchanged until marker.
  445. $parsed .= $tag . $matches[0];
  446. $text = substr($text, strlen($matches[0]));
  447. }
  448. else {
  449. // No end marker: just skip it.
  450. $parsed .= $tag;
  451. }
  452. }
  453. // Check for: Indented code block.
  454. else if ($tag{0} == "\n" || $tag{0} == " ") {
  455. // Indented code block: pass it unchanged, will be handled
  456. // later.
  457. $parsed .= $tag;
  458. }
  459. // Check for: Code span marker
  460. // Note: need to check this after backtick fenced code blocks
  461. else if ($tag{0} == "`") {
  462. // Find corresponding end marker.
  463. $tag_re = preg_quote($tag);
  464. if (preg_match('{^(?>.+?|\n(?!\n))*?(?<!`)' . $tag_re . '(?!`)}',
  465. $text, $matches))
  466. {
  467. // End marker found: pass text unchanged until marker.
  468. $parsed .= $tag . $matches[0];
  469. $text = substr($text, strlen($matches[0]));
  470. }
  471. else {
  472. // Unmatched marker: just skip it.
  473. $parsed .= $tag;
  474. }
  475. }
  476. // Check for: Opening Block level tag or
  477. // Opening Context Block tag (like ins and del)
  478. // used as a block tag (tag is alone on it's line).
  479. else if (preg_match('{^<(?:' . $this->block_tags_re . ')\b}', $tag) ||
  480. ( preg_match('{^<(?:' . $this->context_block_tags_re . ')\b}', $tag) &&
  481. preg_match($newline_before_re, $parsed) &&
  482. preg_match($newline_after_re, $text) )
  483. )
  484. {
  485. // Need to parse tag and following text using the HTML parser.
  486. list($block_text, $text) =
  487. $this->_hashHTMLBlocks_inHTML($tag . $text, "hashBlock", true);
  488. // Make sure it stays outside of any paragraph by adding newlines.
  489. $parsed .= "\n\n$block_text\n\n";
  490. }
  491. // Check for: Clean tag (like script, math)
  492. // HTML Comments, processing instructions.
  493. else if (preg_match('{^<(?:' . $this->clean_tags_re . ')\b}', $tag) ||
  494. $tag{1} == '!' || $tag{1} == '?')
  495. {
  496. // Need to parse tag and following text using the HTML parser.
  497. // (don't check for markdown attribute)
  498. list($block_text, $text) =
  499. $this->_hashHTMLBlocks_inHTML($tag . $text, "hashClean", false);
  500. $parsed .= $block_text;
  501. }
  502. // Check for: Tag with same name as enclosing tag.
  503. else if ($enclosing_tag_re !== '' &&
  504. // Same name as enclosing tag.
  505. preg_match('{^</?(?:' . $enclosing_tag_re . ')\b}', $tag))
  506. {
  507. // Increase/decrease nested tag count.
  508. if ($tag{1} == '/') $depth--;
  509. else if ($tag{strlen($tag)-2} != '/') $depth++;
  510. if ($depth < 0) {
  511. // Going out of parent element. Clean up and break so we
  512. // return to the calling function.
  513. $text = $tag . $text;
  514. break;
  515. }
  516. $parsed .= $tag;
  517. }
  518. else {
  519. $parsed .= $tag;
  520. }
  521. } while ($depth >= 0);
  522. return array($parsed, $text);
  523. }
  524. /**
  525. * Parse HTML, calling _HashHTMLBlocks_InMarkdown for block tags.
  526. *
  527. * * Calls $hash_method to convert any blocks.
  528. * * Stops when the first opening tag closes.
  529. * * $md_attr indicate if the use of the `markdown="1"` attribute is allowed.
  530. * (it is not inside clean tags)
  531. *
  532. * Returns an array of that form: ( processed text , remaining text )
  533. * @param string $text
  534. * @param string $hash_method
  535. * @param string $md_attr
  536. * @return array
  537. */
  538. protected function _hashHTMLBlocks_inHTML($text, $hash_method, $md_attr) {
  539. if ($text === '') return array('', '');
  540. // Regex to match `markdown` attribute inside of a tag.
  541. $markdown_attr_re = '
  542. {
  543. \s* # Eat whitespace before the `markdown` attribute
  544. markdown
  545. \s*=\s*
  546. (?>
  547. (["\']) # $1: quote delimiter
  548. (.*?) # $2: attribute value
  549. \1 # matching delimiter
  550. |
  551. ([^\s>]*) # $3: unquoted attribute value
  552. )
  553. () # $4: make $3 always defined (avoid warnings)
  554. }xs';
  555. // Regex to match any tag.
  556. $tag_re = '{
  557. ( # $2: Capture whole tag.
  558. </? # Any opening or closing tag.
  559. [\w:$]+ # Tag name.
  560. (?:
  561. (?=[\s"\'/a-zA-Z0-9]) # Allowed characters after tag name.
  562. (?>
  563. ".*?" | # Double quotes (can contain `>`)
  564. \'.*?\' | # Single quotes (can contain `>`)
  565. .+? # Anything but quotes and `>`.
  566. )*?
  567. )?
  568. > # End of tag.
  569. |
  570. <!-- .*? --> # HTML Comment
  571. |
  572. <\?.*?\?> | <%.*?%> # Processing instruction
  573. |
  574. <!\[CDATA\[.*?\]\]> # CData Block
  575. )
  576. }xs';
  577. $original_text = $text; // Save original text in case of faliure.
  578. $depth = 0; // Current depth inside the tag tree.
  579. $block_text = ""; // Temporary text holder for current text.
  580. $parsed = ""; // Parsed text that will be returned.
  581. // Get the name of the starting tag.
  582. // (This pattern makes $base_tag_name_re safe without quoting.)
  583. if (preg_match('/^<([\w:$]*)\b/', $text, $matches))
  584. $base_tag_name_re = $matches[1];
  585. // Loop through every tag until we find the corresponding closing tag.
  586. do {
  587. // Split the text using the first $tag_match pattern found.
  588. // Text before pattern will be first in the array, text after
  589. // pattern will be at the end, and between will be any catches made
  590. // by the pattern.
  591. $parts = preg_split($tag_re, $text, 2, PREG_SPLIT_DELIM_CAPTURE);
  592. if (count($parts) < 3) {
  593. // End of $text reached with unbalenced tag(s).
  594. // In that case, we return original text unchanged and pass the
  595. // first character as filtered to prevent an infinite loop in the
  596. // parent function.
  597. return array($original_text{0}, substr($original_text, 1));
  598. }
  599. $block_text .= $parts[0]; // Text before current tag.
  600. $tag = $parts[1]; // Tag to handle.
  601. $text = $parts[2]; // Remaining text after current tag.
  602. // Check for: Auto-close tag (like <hr/>)
  603. // Comments and Processing Instructions.
  604. if (preg_match('{^</?(?:' . $this->auto_close_tags_re . ')\b}', $tag) ||
  605. $tag{1} == '!' || $tag{1} == '?')
  606. {
  607. // Just add the tag to the block as if it was text.
  608. $block_text .= $tag;
  609. }
  610. else {
  611. // Increase/decrease nested tag count. Only do so if
  612. // the tag's name match base tag's.
  613. if (preg_match('{^</?' . $base_tag_name_re . '\b}', $tag)) {
  614. if ($tag{1} == '/') $depth--;
  615. else if ($tag{strlen($tag)-2} != '/') $depth++;
  616. }
  617. // Check for `markdown="1"` attribute and handle it.
  618. if ($md_attr &&
  619. preg_match($markdown_attr_re, $tag, $attr_m) &&
  620. preg_match('/^1|block|span$/', $attr_m[2] . $attr_m[3]))
  621. {
  622. // Remove `markdown` attribute from opening tag.
  623. $tag = preg_replace($markdown_attr_re, '', $tag);
  624. // Check if text inside this tag must be parsed in span mode.
  625. $this->mode = $attr_m[2] . $attr_m[3];
  626. $span_mode = $this->mode == 'span' || $this->mode != 'block' &&
  627. preg_match('{^<(?:' . $this->contain_span_tags_re . ')\b}', $tag);
  628. // Calculate indent before tag.
  629. if (preg_match('/(?:^|\n)( *?)(?! ).*?$/', $block_text, $matches)) {
  630. $strlen = $this->utf8_strlen;
  631. $indent = $strlen($matches[1], 'UTF-8');
  632. } else {
  633. $indent = 0;
  634. }
  635. // End preceding block with this tag.
  636. $block_text .= $tag;
  637. $parsed .= $this->$hash_method($block_text);
  638. // Get enclosing tag name for the ParseMarkdown function.
  639. // (This pattern makes $tag_name_re safe without quoting.)
  640. preg_match('/^<([\w:$]*)\b/', $tag, $matches);
  641. $tag_name_re = $matches[1];
  642. // Parse the content using the HTML-in-Markdown parser.
  643. list ($block_text, $text)
  644. = $this->_hashHTMLBlocks_inMarkdown($text, $indent,
  645. $tag_name_re, $span_mode);
  646. // Outdent markdown text.
  647. if ($indent > 0) {
  648. $block_text = preg_replace("/^[ ]{1,$indent}/m", "",
  649. $block_text);
  650. }
  651. // Append tag content to parsed text.
  652. if (!$span_mode) $parsed .= "\n\n$block_text\n\n";
  653. else $parsed .= "$block_text";
  654. // Start over with a new block.
  655. $block_text = "";
  656. }
  657. else $block_text .= $tag;
  658. }
  659. } while ($depth > 0);
  660. // Hash last block text that wasn't processed inside the loop.
  661. $parsed .= $this->$hash_method($block_text);
  662. return array($parsed, $text);
  663. }
  664. /**
  665. * Called whenever a tag must be hashed when a function inserts a "clean" tag
  666. * in $text, it passes through this function and is automaticaly escaped,
  667. * blocking invalid nested overlap.
  668. * @param string $text
  669. * @return string
  670. */
  671. protected function hashClean($text) {
  672. return $this->hashPart($text, 'C');
  673. }
  674. /**
  675. * Turn Markdown link shortcuts into XHTML <a> tags.
  676. * @param string $text
  677. * @return string
  678. */
  679. protected function doAnchors($text) {
  680. if ($this->in_anchor) {
  681. return $text;
  682. }
  683. $this->in_anchor = true;
  684. // First, handle reference-style links: [link text] [id]
  685. $text = preg_replace_callback('{
  686. ( # wrap whole match in $1
  687. \[
  688. (' . $this->nested_brackets_re . ') # link text = $2
  689. \]
  690. [ ]? # one optional space
  691. (?:\n[ ]*)? # one optional newline followed by spaces
  692. \[
  693. (.*?) # id = $3
  694. \]
  695. )
  696. }xs',
  697. array($this, '_doAnchors_reference_callback'), $text);
  698. // Next, inline-style links: [link text](url "optional title")
  699. $text = preg_replace_callback('{
  700. ( # wrap whole match in $1
  701. \[
  702. (' . $this->nested_brackets_re . ') # link text = $2
  703. \]
  704. \( # literal paren
  705. [ \n]*
  706. (?:
  707. <(.+?)> # href = $3
  708. |
  709. (' . $this->nested_url_parenthesis_re . ') # href = $4
  710. )
  711. [ \n]*
  712. ( # $5
  713. ([\'"]) # quote char = $6
  714. (.*?) # Title = $7
  715. \6 # matching quote
  716. [ \n]* # ignore any spaces/tabs between closing quote and )
  717. )? # title is optional
  718. \)
  719. (?:[ ]? ' . $this->id_class_attr_catch_re . ' )? # $8 = id/class attributes
  720. )
  721. }xs',
  722. array($this, '_doAnchors_inline_callback'), $text);
  723. // Last, handle reference-style shortcuts: [link text]
  724. // These must come last in case you've also got [link text][1]
  725. // or [link text](/foo)
  726. $text = preg_replace_callback('{
  727. ( # wrap whole match in $1
  728. \[
  729. ([^\[\]]+) # link text = $2; can\'t contain [ or ]
  730. \]
  731. )
  732. }xs',
  733. array($this, '_doAnchors_reference_callback'), $text);
  734. $this->in_anchor = false;
  735. return $text;
  736. }
  737. /**
  738. * Callback for reference anchors
  739. * @param array $matches
  740. * @return string
  741. */
  742. protected function _doAnchors_reference_callback($matches) {
  743. $whole_match = $matches[1];
  744. $link_text = $matches[2];
  745. $link_id =& $matches[3];
  746. if ($link_id == "") {
  747. // for shortcut links like [this][] or [this].
  748. $link_id = $link_text;
  749. }
  750. // lower-case and turn embedded newlines into spaces
  751. $link_id = strtolower($link_id);
  752. $link_id = preg_replace('{[ ]?\n}', ' ', $link_id);
  753. if (isset($this->urls[$link_id])) {
  754. $url = $this->urls[$link_id];
  755. $url = $this->encodeURLAttribute($url);
  756. $result = "<a href=\"$url\"";
  757. if ( isset( $this->titles[$link_id] ) ) {
  758. $title = $this->titles[$link_id];
  759. $title = $this->encodeAttribute($title);
  760. $result .= " title=\"$title\"";
  761. }
  762. if (isset($this->ref_attr[$link_id]))
  763. $result .= $this->ref_attr[$link_id];
  764. $link_text = $this->runSpanGamut($link_text);
  765. $result .= ">$link_text</a>";
  766. $result = $this->hashPart($result);
  767. }
  768. else {
  769. $result = $whole_match;
  770. }
  771. return $result;
  772. }
  773. /**
  774. * Callback for inline anchors
  775. * @param array $matches
  776. * @return string
  777. */
  778. protected function _doAnchors_inline_callback($matches) {
  779. $whole_match = $matches[1];
  780. $link_text = $this->runSpanGamut($matches[2]);
  781. $url = $matches[3] == '' ? $matches[4] : $matches[3];
  782. $title =& $matches[7];
  783. $attr = $this->doExtraAttributes("a", $dummy =& $matches[8]);
  784. // if the URL was of the form <s p a c e s> it got caught by the HTML
  785. // tag parser and hashed. Need to reverse the process before using the URL.
  786. $unhashed = $this->unhash($url);
  787. if ($unhashed != $url)
  788. $url = preg_replace('/^<(.*)>$/', '\1', $unhashed);
  789. $url = $this->encodeURLAttribute($url);
  790. $result = "<a href=\"$url\"";
  791. if (isset($title)) {
  792. $title = $this->encodeAttribute($title);
  793. $result .= " title=\"$title\"";
  794. }
  795. $result .= $attr;
  796. $link_text = $this->runSpanGamut($link_text);
  797. $result .= ">$link_text</a>";
  798. return $this->hashPart($result);
  799. }
  800. /**
  801. * Turn Markdown image shortcuts into <img> tags.
  802. * @param string $text
  803. * @return string
  804. */
  805. protected function doImages($text) {
  806. // First, handle reference-style labeled images: ![alt text][id]
  807. $text = preg_replace_callback('{
  808. ( # wrap whole match in $1
  809. !\[
  810. (' . $this->nested_brackets_re . ') # alt text = $2
  811. \]
  812. [ ]? # one optional space
  813. (?:\n[ ]*)? # one optional newline followed by spaces
  814. \[
  815. (.*?) # id = $3
  816. \]
  817. )
  818. }xs',
  819. array($this, '_doImages_reference_callback'), $text);
  820. // Next, handle inline images: ![alt text](url "optional title")
  821. // Don't forget: encode * and _
  822. $text = preg_replace_callback('{
  823. ( # wrap whole match in $1
  824. !\[
  825. (' . $this->nested_brackets_re . ') # alt text = $2
  826. \]
  827. \s? # One optional whitespace character
  828. \( # literal paren
  829. [ \n]*
  830. (?:
  831. <(\S*)> # src url = $3
  832. |
  833. (' . $this->nested_url_parenthesis_re . ') # src url = $4
  834. )
  835. [ \n]*
  836. ( # $5
  837. ([\'"]) # quote char = $6
  838. (.*?) # title = $7
  839. \6 # matching quote
  840. [ \n]*
  841. )? # title is optional
  842. \)
  843. (?:[ ]? ' . $this->id_class_attr_catch_re . ' )? # $8 = id/class attributes
  844. )
  845. }xs',
  846. array($this, '_doImages_inline_callback'), $text);
  847. return $text;
  848. }
  849. /**
  850. * Callback for referenced images
  851. * @param array $matches
  852. * @return string
  853. */
  854. protected function _doImages_reference_callback($matches) {
  855. $whole_match = $matches[1];
  856. $alt_text = $matches[2];
  857. $link_id = strtolower($matches[3]);
  858. if ($link_id == "") {
  859. $link_id = strtolower($alt_text); // for shortcut links like ![this][].
  860. }
  861. $alt_text = $this->encodeAttribute($alt_text);
  862. if (isset($this->urls[$link_id])) {
  863. $url = $this->encodeURLAttribute($this->urls[$link_id]);
  864. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  865. if (isset($this->titles[$link_id])) {
  866. $title = $this->titles[$link_id];
  867. $title = $this->encodeAttribute($title);
  868. $result .= " title=\"$title\"";
  869. }
  870. if (isset($this->ref_attr[$link_id]))
  871. $result .= $this->ref_attr[$link_id];
  872. $result .= $this->empty_element_suffix;
  873. $result = $this->hashPart($result);
  874. }
  875. else {
  876. // If there's no such link ID, leave intact:
  877. $result = $whole_match;
  878. }
  879. return $result;
  880. }
  881. /**
  882. * Callback for inline images
  883. * @param array $matches
  884. * @return string
  885. */
  886. protected function _doImages_inline_callback($matches) {
  887. $whole_match = $matches[1];
  888. $alt_text = $matches[2];
  889. $url = $matches[3] == '' ? $matches[4] : $matches[3];
  890. $title =& $matches[7];
  891. $attr = $this->doExtraAttributes("img", $dummy =& $matches[8]);
  892. $alt_text = $this->encodeAttribute($alt_text);
  893. $url = $this->encodeURLAttribute($url);
  894. $result = "<img src=\"$url\" alt=\"$alt_text\"";
  895. if (isset($title)) {
  896. $title = $this->encodeAttribute($title);
  897. $result .= " title=\"$title\""; // $title already quoted
  898. }
  899. $result .= $attr;
  900. $result .= $this->empty_element_suffix;
  901. return $this->hashPart($result);
  902. }
  903. /**
  904. * Process markdown headers. Redefined to add ID and class attribute support.
  905. * @param string $text
  906. * @return string
  907. */
  908. protected function doHeaders($text) {
  909. // Setext-style headers:
  910. // Header 1 {#header1}
  911. // ========
  912. //
  913. // Header 2 {#header2 .class1 .class2}
  914. // --------
  915. //
  916. $text = preg_replace_callback(
  917. '{
  918. (^.+?) # $1: Header text
  919. (?:[ ]+ ' . $this->id_class_attr_catch_re . ' )? # $3 = id/class attributes
  920. [ ]*\n(=+|-+)[ ]*\n+ # $3: Header footer
  921. }mx',
  922. array($this, '_doHeaders_callback_setext'), $text);
  923. // atx-style headers:
  924. // # Header 1 {#header1}
  925. // ## Header 2 {#header2}
  926. // ## Header 2 with closing hashes ## {#header3.class1.class2}
  927. // ...
  928. // ###### Header 6 {.class2}
  929. //
  930. $text = preg_replace_callback('{
  931. ^(\#{1,6}) # $1 = string of #\'s
  932. [ ]'.($this->hashtag_protection ? '+' : '*').'
  933. (.+?) # $2 = Header text
  934. [ ]*
  935. \#* # optional closing #\'s (not counted)
  936. (?:[ ]+ ' . $this->id_class_attr_catch_re . ' )? # $3 = id/class attributes
  937. [ ]*
  938. \n+
  939. }xm',
  940. array($this, '_doHeaders_callback_atx'), $text);
  941. return $text;
  942. }
  943. /**
  944. * Callback for setext headers
  945. * @param array $matches
  946. * @return string
  947. */
  948. protected function _doHeaders_callback_setext($matches) {
  949. if ($matches[3] == '-' && preg_match('{^- }', $matches[1])) {
  950. return $matches[0];
  951. }
  952. $level = $matches[3]{0} == '=' ? 1 : 2;
  953. $defaultId = is_callable($this->header_id_func) ? call_user_func($this->header_id_func, $matches[1]) : null;
  954. $attr = $this->doExtraAttributes("h$level", $dummy =& $matches[2], $defaultId);
  955. $block = "<h$level$attr>" . $this->runSpanGamut($matches[1]) . "</h$level>";
  956. return "\n" . $this->hashBlock($block) . "\n\n";
  957. }
  958. /**
  959. * Callback for atx headers
  960. * @param array $matches
  961. * @return string
  962. */
  963. protected function _doHeaders_callback_atx($matches) {
  964. $level = strlen($matches[1]);
  965. $defaultId = is_callable($this->header_id_func) ? call_user_func($this->header_id_func, $matches[2]) : null;
  966. $attr = $this->doExtraAttributes("h$level", $dummy =& $matches[3], $defaultId);
  967. $block = "<h$level$attr>" . $this->runSpanGamut($matches[2]) . "</h$level>";
  968. return "\n" . $this->hashBlock($block) . "\n\n";
  969. }
  970. /**
  971. * Form HTML tables.
  972. * @param string $text
  973. * @return string
  974. */
  975. protected function doTables($text) {
  976. $less_than_tab = $this->tab_width - 1;
  977. // Find tables with leading pipe.
  978. //
  979. // | Header 1 | Header 2
  980. // | -------- | --------
  981. // | Cell 1 | Cell 2
  982. // | Cell 3 | Cell 4
  983. $text = preg_replace_callback('
  984. {
  985. ^ # Start of a line
  986. [ ]{0,' . $less_than_tab . '} # Allowed whitespace.
  987. [|] # Optional leading pipe (present)
  988. (.+) \n # $1: Header row (at least one pipe)
  989. [ ]{0,' . $less_than_tab . '} # Allowed whitespace.
  990. [|] ([ ]*[-:]+[-| :]*) \n # $2: Header underline
  991. ( # $3: Cells
  992. (?>
  993. [ ]* # Allowed whitespace.
  994. [|] .* \n # Row content.
  995. )*
  996. )
  997. (?=\n|\Z) # Stop at final double newline.
  998. }xm',
  999. array($this, '_doTable_leadingPipe_callback'), $text);
  1000. // Find tables without leading pipe.
  1001. //
  1002. // Header 1 | Header 2
  1003. // -------- | --------
  1004. // Cell 1 | Cell 2
  1005. // Cell 3 | Cell 4
  1006. $text = preg_replace_callback('
  1007. {
  1008. ^ # Start of a line
  1009. [ ]{0,' . $less_than_tab . '} # Allowed whitespace.
  1010. (\S.*[|].*) \n # $1: Header row (at least one pipe)
  1011. [ ]{0,' . $less_than_tab . '} # Allowed whitespace.
  1012. ([-:]+[ ]*[|][-| :]*) \n # $2: Header underline
  1013. ( # $3: Cells
  1014. (?>
  1015. .* [|] .* \n # Row content
  1016. )*
  1017. )
  1018. (?=\n|\Z) # Stop at final double newline.
  1019. }xm',
  1020. array($this, '_DoTable_callback'), $text);
  1021. return $text;
  1022. }
  1023. /**
  1024. * Callback for removing the leading pipe for each row
  1025. * @param array $matches
  1026. * @return string
  1027. */
  1028. protected function _doTable_leadingPipe_callback($matches) {
  1029. $head = $matches[1];
  1030. $underline = $matches[2];
  1031. $content = $matches[3];
  1032. $content = preg_replace('/^ *[|]/m', '', $content);
  1033. return $this->_doTable_callback(array($matches[0], $head, $underline, $content));
  1034. }
  1035. /**
  1036. * Make the align attribute in a table
  1037. * @param string $alignname
  1038. * @return string
  1039. */
  1040. protected function _doTable_makeAlignAttr($alignname)
  1041. {
  1042. if (empty($this->table_align_class_tmpl)) {
  1043. return " align=\"$alignname\"";
  1044. }
  1045. $classname = str_replace('%%', $alignname, $this->table_align_class_tmpl);
  1046. return " class=\"$classname\"";
  1047. }
  1048. /**
  1049. * Calback for processing tables
  1050. * @param array $matches
  1051. * @return string
  1052. */
  1053. protected function _doTable_callback($matches) {
  1054. $head = $matches[1];
  1055. $underline = $matches[2];
  1056. $content = $matches[3];
  1057. // Remove any tailing pipes for each line.
  1058. $head = preg_replace('/[|] *$/m', '', $head);
  1059. $underline = preg_replace('/[|] *$/m', '', $underline);
  1060. $content = preg_replace('/[|] *$/m', '', $content);
  1061. // Reading alignement from header underline.
  1062. $separators = preg_split('/ *[|] */', $underline);
  1063. foreach ($separators as $n => $s) {
  1064. if (preg_match('/^ *-+: *$/', $s))
  1065. $attr[$n] = $this->_doTable_makeAlignAttr('right');
  1066. else if (preg_match('/^ *:-+: *$/', $s))
  1067. $attr[$n] = $this->_doTable_makeAlignAttr('center');
  1068. else if (preg_match('/^ *:-+ *$/', $s))
  1069. $attr[$n] = $this->_doTable_makeAlignAttr('left');
  1070. else
  1071. $attr[$n] = '';
  1072. }
  1073. // Parsing span elements, including code spans, character escapes,
  1074. // and inline HTML tags, so that pipes inside those gets ignored.
  1075. $head = $this->parseSpan($head);
  1076. $headers = preg_split('/ *[|] */', $head);
  1077. $col_count = count($headers);
  1078. $attr = array_pad($attr, $col_count, '');
  1079. // Write column headers.
  1080. $text = "<table>\n";
  1081. $text .= "<thead>\n";
  1082. $text .= "<tr>\n";
  1083. foreach ($headers as $n => $header)
  1084. $text .= " <th$attr[$n]>" . $this->runSpanGamut(trim($header)) . "</th>\n";
  1085. $text .= "</tr>\n";
  1086. $text .= "</thead>\n";
  1087. // Split content by row.
  1088. $rows = explode("\n", trim($content, "\n"));
  1089. $text .= "<tbody>\n";
  1090. foreach ($rows as $row) {
  1091. // Parsing span elements, including code spans, character escapes,
  1092. // and inline HTML tags, so that pipes inside those gets ignored.
  1093. $row = $this->parseSpan($row);
  1094. // Split row by cell.
  1095. $row_cells = preg_split('/ *[|] */', $row, $col_count);
  1096. $row_cells = array_pad($row_cells, $col_count, '');
  1097. $text .= "<tr>\n";
  1098. foreach ($row_cells as $n => $cell)
  1099. $text .= " <td$attr[$n]>" . $this->runSpanGamut(trim($cell)) . "</td>\n";
  1100. $text .= "</tr>\n";
  1101. }
  1102. $text .= "</tbody>\n";
  1103. $text .= "</table>";
  1104. return $this->hashBlock($text) . "\n";
  1105. }
  1106. /**
  1107. * Form HTML definition lists.
  1108. * @param string $text
  1109. * @return string
  1110. */
  1111. protected function doDefLists($text) {
  1112. $less_than_tab = $this->tab_width - 1;
  1113. // Re-usable pattern to match any entire dl list:
  1114. $whole_list_re = '(?>
  1115. ( # $1 = whole list
  1116. ( # $2
  1117. [ ]{0,' . $less_than_tab . '}
  1118. ((?>.*\S.*\n)+) # $3 = defined term
  1119. \n?
  1120. [ ]{0,' . $less_than_tab . '}:[ ]+ # colon starting definition
  1121. )
  1122. (?s:.+?)
  1123. ( # $4
  1124. \z
  1125. |
  1126. \n{2,}
  1127. (?=\S)
  1128. (?! # Negative lookahead for another term
  1129. [ ]{0,' . $less_than_tab . '}
  1130. (?: \S.*\n )+? # defined term
  1131. \n?
  1132. [ ]{0,' . $less_than_tab . '}:[ ]+ # colon starting definition
  1133. )
  1134. (?! # Negative lookahead for another definition
  1135. [ ]{0,' . $less_than_tab . '}:[ ]+ # colon starting definition
  1136. )
  1137. )
  1138. )
  1139. )'; // mx
  1140. $text = preg_replace_callback('{
  1141. (?>\A\n?|(?<=\n\n))
  1142. ' . $whole_list_re . '
  1143. }mx',
  1144. array($this, '_doDefLists_callback'), $text);
  1145. return $text;
  1146. }
  1147. /**
  1148. * Callback for processing definition lists
  1149. * @param array $matches
  1150. * @return string
  1151. */
  1152. protected function _doDefLists_callback($matches) {
  1153. // Re-usable patterns to match list item bullets and number markers:
  1154. $list = $matches[1];
  1155. // Turn double returns into triple returns, so that we can make a
  1156. // paragraph for the last item in a list, if necessary:
  1157. $result = trim($this->processDefListItems($list));
  1158. $result = "<dl>\n" . $result . "\n</dl>";
  1159. return $this->hashBlock($result) . "\n\n";
  1160. }
  1161. /**
  1162. * Process the contents of a single definition list, splitting it
  1163. * into individual term and definition list items.
  1164. * @param string $list_str
  1165. * @return string
  1166. */
  1167. protected function processDefListItems($list_str) {
  1168. $less_than_tab = $this->tab_width - 1;
  1169. // Trim trailing blank lines:
  1170. $list_str = preg_replace("/\n{2,}\\z/", "\n", $list_str);
  1171. // Process definition terms.
  1172. $list_str = preg_replace_callback('{
  1173. (?>\A\n?|\n\n+) # leading line
  1174. ( # definition terms = $1
  1175. [ ]{0,' . $less_than_tab . '} # leading whitespace
  1176. (?!\:[ ]|[ ]) # negative lookahead for a definition
  1177. # mark (colon) or more whitespace.
  1178. (?> \S.* \n)+? # actual term (not whitespace).
  1179. )
  1180. (?=\n?[ ]{0,3}:[ ]) # lookahead for following line feed
  1181. # with a definition mark.
  1182. }xm',
  1183. array($this, '_processDefListItems_callback_dt'), $list_str);
  1184. // Process actual definitions.
  1185. $list_str = preg_replace_callback('{
  1186. \n(\n+)? # leading line = $1
  1187. ( # marker space = $2
  1188. [ ]{0,' . $less_than_tab . '} # whitespace before colon
  1189. \:[ ]+ # definition mark (colon)
  1190. )
  1191. ((?s:.+?)) # definition text = $3
  1192. (?= \n+ # stop at next definition mark,
  1193. (?: # next term or end of text
  1194. [ ]{0,' . $less_than_tab . '} \:[ ] |
  1195. <dt> | \z
  1196. )
  1197. )
  1198. }xm',
  1199. array($this, '_processDefListItems_callback_dd'), $list_str);
  1200. return $list_str;
  1201. }
  1202. /**
  1203. * Callback for <dt> elements in definition lists
  1204. * @param array $matches
  1205. * @return string
  1206. */
  1207. protected function _processDefListItems_callback_dt($matches) {
  1208. $terms = explode("\n", trim($matches[1]));
  1209. $text = '';
  1210. foreach ($terms as $term) {
  1211. $term = $this->runSpanGamut(trim($term));
  1212. $text .= "\n<dt>" . $term . "</dt>";
  1213. }
  1214. return $text . "\n";
  1215. }
  1216. /**
  1217. * Callback for <dd> elements in definition lists
  1218. * @param array $matches
  1219. * @return string
  1220. */
  1221. protected function _processDefListItems_callback_dd($matches) {
  1222. $leading_line = $matches[1];
  1223. $marker_space = $matches[2];
  1224. $def = $matches[3];
  1225. if ($leading_line || preg_match('/\n{2,}/', $def)) {
  1226. // Replace marker with the appropriate whitespace indentation
  1227. $def = str_repeat(' ', strlen($marker_space)) . $def;
  1228. $def = $this->runBlockGamut($this->outdent($def . "\n\n"));
  1229. $def = "\n". $def ."\n";
  1230. }
  1231. else {
  1232. $def = rtrim($def);
  1233. $def = $this->runSpanGamut($this->outdent($def));
  1234. }
  1235. return "\n<dd>" . $def . "</dd>\n";
  1236. }
  1237. /**
  1238. * Adding the fenced code block syntax to regular Markdown:
  1239. *
  1240. * ~~~
  1241. * Code block
  1242. * ~~~
  1243. *
  1244. * @param string $text
  1245. * @return string
  1246. */
  1247. protected function doFencedCodeBlocks($text) {
  1248. $less_than_tab = $this->tab_width;
  1249. $text = preg_replace_callback('{
  1250. (?:\n|\A)
  1251. # 1: Opening marker
  1252. (
  1253. (?:~{3,}|`{3,}) # 3 or more tildes/backticks.
  1254. )
  1255. [ ]*
  1256. (?:
  1257. \.?([-_:a-zA-Z0-9]+) # 2: standalone class name
  1258. )?
  1259. [ ]*
  1260. (?:
  1261. ' . $this->id_class_attr_catch_re . ' # 3: Extra attributes
  1262. )?
  1263. [ ]* \n # Whitespace and newline following marker.
  1264. # 4: Content
  1265. (
  1266. (?>
  1267. (?!\1 [ ]* \n) # Not a closing marker.
  1268. .*\n+
  1269. )+
  1270. )
  1271. # Closing marker.
  1272. \1 [ ]* (?= \n )
  1273. }xm',
  1274. array($this, '_doFencedCodeBlocks_callback'), $text);
  1275. return $text;
  1276. }
  1277. /**
  1278. * Callback to process fenced code blocks
  1279. * @param array $matches
  1280. * @return string
  1281. */
  1282. protected function _doFencedCodeBlocks_callback($matches) {
  1283. $classname =& $matches[2];
  1284. $attrs =& $matches[3];
  1285. $codeblock = $matches[4];
  1286. if ($this->code_block_content_func) {
  1287. $codeblock = call_user_func($this->code_block_content_func, $codeblock, $classname);
  1288. } else {
  1289. $codeblock = htmlspecialchars($codeblock, ENT_NOQUOTES);
  1290. }
  1291. $codeblock = preg_replace_callback('/^\n+/',
  1292. array($this, '_doFencedCodeBlocks_newlines'), $codeblock);
  1293. $classes = array();
  1294. if ($classname != "") {
  1295. if ($classname{0} == '.')
  1296. $classname = substr($classname, 1);
  1297. $classes[] = $this->code_class_prefix . $classname;
  1298. }
  1299. $attr_str = $this->doExtraAttributes($this->code_attr_on_pre ? "pre" : "code", $attrs, null, $classes);
  1300. $pre_attr_str = $this->code_attr_on_pre ? $attr_str : '';
  1301. $code_attr_str = $this->code_attr_on_pre ? '' : $attr_str;
  1302. $codeblock = "<pre$pre_attr_str><code$code_attr_str>$codeblock</code></pre>";
  1303. return "\n\n".$this->hashBlock($codeblock)."\n\n";
  1304. }
  1305. /**
  1306. * Replace new lines in fenced code blocks
  1307. * @param array $matches
  1308. * @return string
  1309. */
  1310. protected function _doFencedCodeBlocks_newlines($matches) {
  1311. return str_repeat("<br$this->empty_element_suffix",
  1312. strlen($matches[0]));
  1313. }
  1314. /**
  1315. * Redefining emphasis markers so that emphasis by underscore does not
  1316. * work in the middle of a word.
  1317. * @var array
  1318. */
  1319. protected $em_relist = array(
  1320. '' => '(?:(?<!\*)\*(?!\*)|(?<![a-zA-Z0-9_])_(?!_))(?![\.,:;]?\s)',
  1321. '*' => '(?<![\s*])\*(?!\*)',
  1322. '_' => '(?<![\s_])_(?![a-zA-Z0-9_])',
  1323. );
  1324. protected $strong_relist = array(
  1325. '' => '(?:(?<!\*)\*\*(?!\*)|(?<![a-zA-Z0-9_])__(?!_))(?![\.,:;]?\s)',
  1326. '**' => '(?<![\s*])\*\*(?!\*)',
  1327. '__' => '(?<![\s_])__(?![a-zA-Z0-9_])',
  1328. );
  1329. protected $em_strong_relist = array(
  1330. '' => '(?:(?<!\*)\*\*\*(?!\*)|(?<![a-zA-Z0-9_])___(?!_))(?![\.,:;]?\s)',
  1331. '***' => '(?<![\s*])\*\*\*(?!\*)',
  1332. '___' => '(?<![\s_])___(?![a-zA-Z0-9_])',
  1333. );
  1334. /**
  1335. * Parse text into paragraphs
  1336. * @param string $text String to process in paragraphs
  1337. * @param boolean $wrap_in_p Whether paragraphs should be wrapped in <p> tags
  1338. * @return string HTML output
  1339. */
  1340. protected function formParagraphs($text, $wrap_in_p = true) {
  1341. // Strip leading and trailing lines:
  1342. $text = preg_replace('/\A\n+|\n+\z/', '', $text);
  1343. $grafs = preg_split('/\n{2,}/', $text, -1, PREG_SPLIT_NO_EMPTY);
  1344. // Wrap <p> tags and unhashify HTML blocks
  1345. foreach ($grafs as $key => $value) {
  1346. $value = trim($this->runSpanGamut($value));
  1347. // Check if this should be enclosed in a paragraph.
  1348. // Clean tag hashes & block tag hashes are left alone.
  1349. $is_p = $wrap_in_p && !preg_match('/^B\x1A[0-9]+B|^C\x1A[0-9]+C$/', $value);
  1350. if ($is_p) {
  1351. $value = "<p>$value</p>";
  1352. }
  1353. $grafs[$key] = $value;
  1354. }
  1355. // Join grafs in one text, then unhash HTML tags.
  1356. $text = implode("\n\n", $grafs);
  1357. // Finish by removing any tag hashes still present in $text.
  1358. $text = $this->unhash($text);
  1359. return $text;
  1360. }
  1361. /**
  1362. * Footnotes - Strips link definitions from text, stores the URLs and
  1363. * titles in hash references.
  1364. * @param string $text
  1365. * @return string
  1366. */
  1367. protected function stripFootnotes($text) {
  1368. $less_than_tab = $this->tab_width - 1;
  1369. // Link defs are in the form: [^id]: url "optional title"
  1370. $text = preg_replace_callback('{
  1371. ^[ ]{0,' . $less_than_tab . '}\[\^(.+?)\][ ]?: # note_id = $1
  1372. [ ]*
  1373. \n? # maybe *one* newline
  1374. ( # text = $2 (no blank lines allowed)
  1375. (?:
  1376. .+ # actual text
  1377. |
  1378. \n # newlines but
  1379. (?!\[.+?\][ ]?:\s)# negative lookahead for footnote or link definition marker.
  1380. (?!\n+[ ]{0,3}\S)# ensure line is not blank and followed
  1381. # by non-indented content
  1382. )*
  1383. )
  1384. }xm',
  1385. array($this, '_stripFootnotes_callback'),
  1386. $text);
  1387. return $text;
  1388. }
  1389. /**
  1390. * Callback for stripping footnotes
  1391. * @param array $matches
  1392. * @return string
  1393. */
  1394. protected function _stripFootnotes_callback($matches) {
  1395. $note_id = $this->fn_id_prefix . $matches[1];
  1396. $this->footnotes[$note_id] = $this->outdent($matches[2]);
  1397. return ''; // String that will replace the block
  1398. }
  1399. /**
  1400. * Replace footnote references in $text [^id] with a special text-token
  1401. * which will be replaced by the actual footnote marker in appendFootnotes.
  1402. * @param string $text
  1403. * @return string
  1404. */
  1405. protected function doFootnotes($text) {
  1406. if (!$this->in_anchor) {
  1407. $text = preg_replace('{\[\^(.+?)\]}', "F\x1Afn:\\1\x1A:", $text);
  1408. }
  1409. return $text;
  1410. }
  1411. /**
  1412. * Append footnote list to text
  1413. * @param string $text
  1414. * @return string
  1415. */
  1416. protected function appendFootnotes($text) {
  1417. $text = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
  1418. array($this, '_appendFootnotes_callback'), $text);
  1419. if (!empty($this->footnotes_ordered)) {
  1420. $text .= "\n\n";
  1421. $text .= "<div class=\"footnotes\" role=\"doc-endnotes\">\n";
  1422. $text .= "<hr" . $this->empty_element_suffix . "\n";
  1423. $text .= "<ol>\n\n";
  1424. $attr = "";
  1425. if ($this->fn_backlink_class != "") {
  1426. $class = $this->fn_backlink_class;
  1427. $class = $this->encodeAttribute($class);
  1428. $attr .= " class=\"$class\"";
  1429. }
  1430. if ($this->fn_backlink_title != "") {
  1431. $title = $this->fn_backlink_title;
  1432. $title = $this->encodeAttribute($title);
  1433. $attr .= " title=\"$title\"";
  1434. $attr .= " aria-label=\"$title\"";
  1435. }
  1436. $attr .= " role=\"doc-backlink\"";
  1437. $backlink_text = $this->fn_backlink_html;
  1438. $num = 0;
  1439. while (!empty($this->footnotes_ordered)) {
  1440. $footnote = reset($this->footnotes_ordered);
  1441. $note_id = key($this->footnotes_ordered);
  1442. unset($this->footnotes_ordered[$note_id]);
  1443. $ref_count = $this->footnotes_ref_count[$note_id];
  1444. unset($this->footnotes_ref_count[$note_id]);
  1445. unset($this->footnotes[$note_id]);
  1446. $footnote .= "\n"; // Need to append newline before parsing.
  1447. $footnote = $this->runBlockGamut("$footnote\n");
  1448. $footnote = preg_replace_callback('{F\x1Afn:(.*?)\x1A:}',
  1449. array($this, '_appendFootnotes_callback'), $footnote);
  1450. $attr = str_replace("%%", ++$num, $attr);
  1451. $note_id = $this->encodeAttribute($note_id);
  1452. // Prepare backlink, multiple backlinks if multiple references
  1453. $backlink = "<a href=\"#fnref:$note_id\"$attr>$backlink_text</a>";
  1454. for ($ref_num = 2; $ref_num <= $ref_count; ++$ref_num) {
  1455. $backlink .= " <a href=\"#fnref$ref_num:$note_id\"$attr>$backlink_text</a>";
  1456. }
  1457. // Add backlink to last paragraph; create new paragraph if needed.
  1458. if (preg_match('{</p>$}', $footnote)) {
  1459. $footnote = substr($footnote, 0, -4) . "&#160;$backlink</p>";
  1460. } else {
  1461. $footnote .= "\n\n<p>$backlink</p>";
  1462. }
  1463. $text .= "<li id=\"fn:$note_id\" role=\"doc-endnote\">\n";
  1464. $text .= $footnote . "\n";
  1465. $text .= "</li>\n\n";
  1466. }
  1467. $text .= "</ol>\n";
  1468. $text .= "</div>";
  1469. }
  1470. return $text;
  1471. }
  1472. /**
  1473. * Callback for appending footnotes
  1474. * @param array $matches
  1475. * @return string
  1476. */
  1477. protected function _appendFootnotes_callback($matches) {
  1478. $node_id = $this->fn_id_prefix . $matches[1];
  1479. // Create footnote marker only if it has a corresponding footnote *and*
  1480. // the footnote hasn't been used by another marker.
  1481. if (isset($this->footnotes[$node_id])) {
  1482. $num =& $this->footnotes_numbers[$node_id];
  1483. if (!isset($num)) {
  1484. // Transfer footnote content to the ordered list and give it its
  1485. // number
  1486. $this->footnotes_ordered[$node_id] = $this->footnotes[$node_id];
  1487. $this->footnotes_ref_count[$node_id] = 1;
  1488. $num = $this->footnote_counter++;
  1489. $ref_count_mark = '';
  1490. } else {
  1491. $ref_count_mark = $this->footnotes_ref_count[$node_id] += 1;
  1492. }
  1493. $attr = "";
  1494. if ($this->fn_link_class != "") {
  1495. $class = $this->fn_link_class;
  1496. $class = $this->encodeAttribute($class);
  1497. $attr .= " class=\"$class\"";
  1498. }
  1499. if ($this->fn_link_title != "") {
  1500. $title = $this->fn_link_title;
  1501. $title = $this->encodeAttribute($title);
  1502. $attr .= " title=\"$title\"";
  1503. }
  1504. $attr .= " role=\"doc-noteref\"";
  1505. $attr = str_replace("%%", $num, $attr);
  1506. $node_id = $this->encodeAttribute($node_id);
  1507. return
  1508. "<sup id=\"fnref$ref_count_mark:$node_id\">".
  1509. "<a href=\"#fn:$node_id\"$attr>$num</a>".
  1510. "</sup>";
  1511. }
  1512. return "[^" . $matches[1] . "]";
  1513. }
  1514. /**
  1515. * Abbreviations - strips abbreviations from text, stores titles in hash
  1516. * references.
  1517. * @param string $text
  1518. * @return string
  1519. */
  1520. protected function stripAbbreviations($text) {
  1521. $less_than_tab = $this->tab_width - 1;
  1522. // Link defs are in the form: [id]*: url "optional title"
  1523. $text = preg_replace_callback('{
  1524. ^[ ]{0,' . $less_than_tab . '}\*\[(.+?)\][ ]?: # abbr_id = $1
  1525. (.*) # text = $2 (no blank lines allowed)
  1526. }xm',
  1527. array($this, '_stripAbbreviations_callback'),
  1528. $text);
  1529. return $text;
  1530. }
  1531. /**
  1532. * Callback for stripping abbreviations
  1533. * @param array $matches
  1534. * @return string
  1535. */
  1536. protected function _stripAbbreviations_callback($matches) {
  1537. $abbr_word = $matches[1];
  1538. $abbr_desc = $matches[2];
  1539. if ($this->abbr_word_re) {
  1540. $this->abbr_word_re .= '|';
  1541. }
  1542. $this->abbr_word_re .= preg_quote($abbr_word);
  1543. $this->abbr_desciptions[$abbr_word] = trim($abbr_desc);
  1544. return ''; // String that will replace the block
  1545. }
  1546. /**
  1547. * Find defined abbreviations in text and wrap them in <abbr> elements.
  1548. * @param string $text
  1549. * @return string
  1550. */
  1551. protected function doAbbreviations($text) {
  1552. if ($this->abbr_word_re) {
  1553. // cannot use the /x modifier because abbr_word_re may
  1554. // contain significant spaces:
  1555. $text = preg_replace_callback('{' .
  1556. '(?<![\w\x1A])' .
  1557. '(?:' . $this->abbr_word_re . ')' .
  1558. '(?![\w\x1A])' .
  1559. '}',
  1560. array($this, '_doAbbreviations_callback'), $text);
  1561. }
  1562. return $text;
  1563. }
  1564. /**
  1565. * Callback for processing abbreviations
  1566. * @param array $matches
  1567. * @return string
  1568. */
  1569. protected function _doAbbreviations_callback($matches) {
  1570. $abbr = $matches[0];
  1571. if (isset($this->abbr_desciptions[$abbr])) {
  1572. $desc = $this->abbr_desciptions[$abbr];
  1573. if (empty($desc)) {
  1574. return $this->hashPart("<abbr>$abbr</abbr>");
  1575. } else {
  1576. $desc = $this->encodeAttribute($desc);
  1577. return $this->hashPart("<abbr title=\"$desc\">$abbr</abbr>");
  1578. }
  1579. } else {
  1580. return $matches[0];
  1581. }
  1582. }
  1583. }