PHP and Javascript implementations of a simple markdown parser
Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

markdown.php 75KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306230723082309231023112312231323142315231623172318231923202321232223232324232523262327232823292330233123322333233423352336233723382339234023412342234323442345234623472348234923502351235223532354235523562357235823592360236123622363236423652366236723682369237023712372237323742375237623772378237923802381238223832384238523862387238823892390239123922393239423952396239723982399240024012402240324042405240624072408240924102411241224132414241524162417241824192420242124222423242424252426242724282429243024312432243324342435243624372438243924402441244224432444244524462447244824492450245124522453245424552456245724582459246024612462246324642465246624672468246924702471247224732474247524762477247824792480248124822483248424852486248724882489249024912492249324942495
  1. <?php
  2. declare(strict_types=1);
  3. /**
  4. * Static utilities.
  5. */
  6. class MDUtils {
  7. // Modified from https://urlregex.com/ to remove capture groups. Matches fully qualified URLs only.
  8. public static $baseURLRegex = '(?:(?:(?:[a-z]{3,9}:(?:\\/\\/)?)(?:[\\-;:&=\\+\\$,\\w]+@)?[a-z0-9\\.\\-]+|(?:www\\.|[\\-;:&=\\+\\$,\\w]+@)[a-z0-9\\.\\-]+)(?:(?:\\/[\\+~%\\/\\.\\w\\-_]*)?\\??(?:[\\-\\+=&;%@\\.\\w_]*)#?(?:[\\.\\!\\/\\\\\\w]*))?)';
  9. // Modified from https://emailregex.com/ to remove capture groups.
  10. public static $baseEmailRegex = '(?:(?:[^<>()\\[\\]\\\\.,;:\\s@"]+(?:\\.[^<>()\\[\\]\\\\.,;:\\s@"]+)*)|(?:".+"))@(?:(?:\\[[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}\\.[0-9]{1,3}])|(?:(?:[a-z\\-0-9]+\\.)+[a-z]{2,}))';
  11. /**
  12. * Encodes characters as HTML numeric entities to make it marginally more
  13. * difficult for web scrapers to grab sensitive info. If `text` starts with
  14. * `mailto:` only the email address following it will be obfuscated.
  15. */
  16. public static function escapeObfuscated(string $text): string {
  17. if (str_starts_with($text, 'mailto:')) {
  18. return 'mailto:' . self::escapeObfuscated(mb_substr($text, 7));
  19. }
  20. $html = '';
  21. $l = mb_strlen($text);
  22. for ($p = 0; $p < $l; $p++) {
  23. $cp = mb_ord(mb_substr($text, $p, 1));
  24. $html .= "&#{{$cp}}";
  25. }
  26. return $html;
  27. }
  28. /**
  29. * Removes illegal characters from an HTML attribute name.
  30. */
  31. public static function scrubAttributeName(string $name): string {
  32. return mb_ereg_replace('[\\t\\n\\f \\/>"\'=]+', '', $name);
  33. }
  34. /**
  35. * Strips one or more leading indents from a line or lines of markdown. An
  36. * indent is defined as 4 spaces or one tab. Incomplete indents (i.e. 1-3
  37. * spaces) are treated like one indent level.
  38. *
  39. * @param string|string[] $line
  40. * @param int $levels
  41. * @return string|string[]
  42. */
  43. public static function stripIndent(string|array &$line, int $levels=1): string|array {
  44. $regex = "^(?: {1,4}|\\t){{$levels}}";
  45. return is_array($line) ? array_map(fn(string $l): string => mb_ereg_replace($regex, '', $l), $line) : mb_ereg_replace($regex, '', $line);
  46. }
  47. /**
  48. * Counts the number of indent levels in a line of text. Partial indents
  49. * (1 to 3 spaces) are counted as one indent level unless `fullIndentsOnly`
  50. * is `true`.
  51. */
  52. public static function countIndents(string &$line, bool $fullIndentsOnly=false): int {
  53. // normalize indents to tabs
  54. $t = mb_ereg_replace($fullIndentsOnly ? "(?: {4}|\\t)" : "(?: {1,4}|\\t)", "\t", $line);
  55. // remove content after indent
  56. $t = mb_ereg_replace("^(\\t*)(.*?)$", "\\1", $t);
  57. // count tabs
  58. return mb_strlen($t);
  59. }
  60. /**
  61. * Returns a copy of an array without any whitespace-only lines at the end.
  62. *
  63. * @param string[] $lines
  64. * @return string[]
  65. */
  66. public static function withoutTrailingBlankLines(array &$lines): array {
  67. $stripped = $lines;
  68. while (sizeof($stripped) > 0 && mb_strlen(trim($stripped[sizeof($stripped) - 1])) == 0) {
  69. array_pop($stripped);
  70. }
  71. return $stripped;
  72. }
  73. /**
  74. * Tests if an array of lines contains at least one blank. A blank line
  75. * can contain whitespace.
  76. *
  77. * @param string[] $lines
  78. */
  79. public static function containsBlankLine(array &$lines): bool {
  80. foreach ($lines as $line) {
  81. if (mb_strlen(trim($line)) == 0) return true;
  82. }
  83. return false;
  84. }
  85. public static function equalAssocArrays(array &$a, array &$b) {
  86. return empty(array_diff_assoc($a, $b));
  87. }
  88. }
  89. /**
  90. * Token type enum for `MDToken`.
  91. */
  92. enum MDTokenType {
  93. case Text;
  94. /**
  95. * Only used for the leading and trailing whitespace around a run of text,
  96. * not every single whitespace character.
  97. */
  98. case Whitespace;
  99. case Underscore;
  100. case Asterisk;
  101. case Slash;
  102. case Tilde;
  103. case Bang;
  104. case Backtick;
  105. case Equal;
  106. case Caret;
  107. case Label; // content=label
  108. case URL; // content=URL, extra=title
  109. case Email; // content=email address, extra=title
  110. case SimpleLink; // content=URL
  111. case SimpleEmail; // content=email address
  112. case Footnote; // content=symbol
  113. case Modifier; // modifier=MDTagModifier
  114. case HTMLTag; // tag=MDHTMLTag
  115. /** Wildcard for `MDToken::findFirstTokens` */
  116. case META_AnyNonWhitespace;
  117. /** Wildcard for `MDToken::findFirstTokens` */
  118. case META_OptionalWhitespace;
  119. }
  120. /**
  121. * Search results from `MDToken.findFirstTokens`.
  122. */
  123. class MDTokenMatch {
  124. /** @var MDToken{} */
  125. public array $tokens;
  126. public int $index;
  127. /**
  128. * @param MDToken[] $tokens
  129. * @param int $index
  130. */
  131. public function __construct(array $tokens, int $index) {
  132. $this->tokens = $tokens;
  133. $this->index = $index;
  134. }
  135. }
  136. /**
  137. * Search results from `MDToken.findPairedTokens`.
  138. */
  139. class MDPairedTokenMatch {
  140. /** @var MDToken[] */
  141. public array $startTokens;
  142. /** @var MDToken[] */
  143. public array $contentTokens;
  144. /** @var MDToken[] */
  145. public array $endTokens;
  146. public int $startIndex;
  147. public int $contentIndex;
  148. public int $endIndex;
  149. public int $totalLength;
  150. public function __construct(array $startTokens, array $contentTokens,
  151. array $endTokens, int $startIndex, int $contentIndex, int $endIndex,
  152. int $totalLength) {
  153. $this->startTokens = $startTokens;
  154. $this->contentTokens = $contentTokens;
  155. $this->endTokens = $endTokens;
  156. $this->startIndex = $startIndex;
  157. $this->contentIndex = $contentIndex;
  158. $this->endIndex = $endIndex;
  159. $this->totalLength = $totalLength;
  160. }
  161. }
  162. /**
  163. * One lexical unit in inline markdown syntax parsing.
  164. */
  165. class MDToken {
  166. /**
  167. * The original verbatim token string. Required as a plaintext fallback if
  168. * the token remains unresolved.
  169. */
  170. public string $original;
  171. public MDTokenType $type;
  172. public ?string $content = null;
  173. public ?string $extra = null;
  174. public ?MDHTMLTag $tag = null;
  175. public ?MDTagModifier $modifier = null;
  176. /**
  177. * Creates a token.
  178. *
  179. * @param string $original verbatim token string
  180. * @param MDTokenType $type token type
  181. * @param string|MDTagModifier|MDHTMLTag|null $content primary content of
  182. * the token
  183. * @param string|null $extra additional content
  184. */
  185. public function __construct(string $original, MDTokenType $type,
  186. string|MDTagModifier|MDHTMLTag|null $content=null,
  187. ?string $extra=null) {
  188. $this->original = $original;
  189. $this->type = $type;
  190. if ($content instanceof MDTagModifier) {
  191. $this->modifier = $content;
  192. } elseif ($content instanceof MDHTMLTag) {
  193. $this->tag = $content;
  194. } else {
  195. $this->content = $content;
  196. }
  197. $this->extra = $extra;
  198. }
  199. public function __toString(): string {
  200. $classname = get_class($this);
  201. return "({$classname} type={$this->type} content={$this->content})";
  202. }
  203. /**
  204. * Attempts to parse a label token from the beginning of `line`. A label is
  205. * of the form `[content]`. If found, returns an array:
  206. * - `0`: the entire label including brackets
  207. * - `1`: the content of the label
  208. *
  209. * @param string $line
  210. * @return ?string[] match groups or null if not found
  211. */
  212. public static function tokenizeLabel(string $line): ?array {
  213. if (!str_starts_with($line, '[')) return null;
  214. $parenCount = 0;
  215. $bracketCount = 0;
  216. $l = mb_strlen($line);
  217. for ($p = 1; $p < $l; $p++) {
  218. $ch = mb_substr($line, $p, 1);
  219. if ($ch == '\\') {
  220. $p++;
  221. } elseif ($ch == '(') {
  222. $parenCount++;
  223. } elseif ($ch == ')') {
  224. $parenCount--;
  225. if ($parenCount < 0) return null;
  226. } elseif ($ch == '[') {
  227. $bracketCount++;
  228. } elseif ($ch == ']') {
  229. if ($bracketCount > 0) {
  230. $bracketCount--;
  231. } else {
  232. return [ mb_substr($line, 0, $p + 1), mb_substr($line, 1, $p - 1) ];
  233. }
  234. }
  235. }
  236. return null;
  237. }
  238. private static $urlWithTitleRegex = '^\\((\\S+?)\\s+"(.*?)"\\)'; // 1=URL, 2=title
  239. private static $urlRegex = '^\\((\\S+?)\\)'; // 1=URL
  240. /**
  241. * Attempts to parse a URL token from the beginning of `line`. A URL token
  242. * is of the form `(url)` or `(url "title")`. If found, returns an array:
  243. * - `0`: the entire URL token including parentheses
  244. * - `1`: the URL
  245. * - `2`: the optional title, or `null`
  246. *
  247. * @param string $line
  248. * @return ?array token tuple
  249. */
  250. public static function tokenizeURL(string $line): ?array {
  251. $groups = [];
  252. if (mb_eregi(self::$urlWithTitleRegex, $line, $groups)) {
  253. if (self::tokenizeEmail($line)) return null; // make sure it's not better described as an email address
  254. return $groups;
  255. }
  256. if (mb_eregi(self::$urlRegex, $line, $groups)) {
  257. if (self::tokenizeEmail($line)) return null;
  258. return [ $groups[0], $groups[1], null ];
  259. }
  260. return null;
  261. }
  262. /**
  263. * Attempts to parse an email address from the beginning of `line`. An
  264. * email address is of the form `(user@example.com)` or
  265. * `(user@example.com "link title")`. If found, returns an array:
  266. * - `0`: the entire token including parentheses
  267. * - `1`: the email address
  268. * - `2`: the optional link title, or `null`
  269. *
  270. * @param string $line
  271. * @return ?string[] token tuple
  272. */
  273. public static function tokenizeEmail(string $line): ?array {
  274. $groups;
  275. if (mb_eregi("^\\(\\s*(" . MDUtils::$baseEmailRegex . ")\\s+\"(.*?)\"\\s*\\)",
  276. $line, $groups)) {
  277. return $groups;
  278. }
  279. if (mb_eregi("^\\(\\s*(" . MDUtils::$baseEmailRegex . ")\\s*\\)", $line, $groups)) {
  280. return [ $groups[0], $groups[1], null ];
  281. }
  282. return null;
  283. }
  284. /**
  285. * Searches an array of `MDToken` for the given pattern of `MDTokenType`s.
  286. * If found, returns a `MDTokenMatch`, otherwise `null`.
  287. *
  288. * Special token types `META_AnyNonWhitespace` and `META_OptionalWhitespace`
  289. * are special supported token types. Note that `META_OptionalWhitespace`
  290. * may give a result with a variable number of tokens.
  291. *
  292. * @param (MDToken|MDNode)[] $tokensToSearch - mixed array of `MDToken` and
  293. * `MDNode` elements
  294. * @param MDTokenType[] $pattern - contiguous run of token types to find
  295. * @param int $startIndex - token index to begin searching (defaults to 0)
  296. * @return ?MDTokenMatch match object, or `null` if not found
  297. */
  298. public static function findFirstTokens(array $tokensToSearch, array $pattern, int $startIndex=0): ?MDTokenMatch {
  299. $matched = [];
  300. for ($t = $startIndex; $t < sizeof($tokensToSearch); $t++) {
  301. $matchedAll = true;
  302. $matched = [];
  303. $patternOffset = 0;
  304. for ($p = 0; $p < mb_strlen($pattern); $p++) {
  305. $t0 = $t + $p + $patternOffset;
  306. if ($t0 >= sizeof($tokensToSearch)) return null;
  307. $token = $tokensToSearch[$t0];
  308. $elem = $pattern[$p];
  309. if ($elem == MDTokenType::META_OptionalWhitespace) {
  310. if ($token instanceof MDToken && $token->type == MDTokenType::Whitespace) {
  311. array_push($matched, $token);
  312. } else {
  313. $patternOffset--;
  314. }
  315. } elseif ($elem == MDTokenType::META_AnyNonWhitespace) {
  316. if ($token instanceof MDToken && $token->type == MDTokenType::Whitespace) {
  317. $matchedAll = false;
  318. break;
  319. }
  320. array_push($matched, $token);
  321. } else {
  322. if (!($token instanceof MDToken) || $token->type != $elem) {
  323. $matchedAll = false;
  324. break;
  325. }
  326. array_push($matched, $token);
  327. }
  328. }
  329. if ($matchedAll) {
  330. return new MDTokenMatch($matched, $t);
  331. }
  332. }
  333. return null;
  334. }
  335. /**
  336. * Searches an array of MDToken for a given starting pattern and ending
  337. * pattern and returns match info about both and the tokens in between.
  338. *
  339. * If `contentValidator` is specified, it will be called with the content
  340. * tokens of a potential match. If the validator returns `true`, the result
  341. * will be accepted and returned by this method. If the validator returns
  342. * `false`, this method will keep looking for another matching pair. If no
  343. * validator is given the first match will be returned regardless of content.
  344. *
  345. * If a match is found, a `MDPairedTokenMatch` is returned with details
  346. * of the opening tokens, closing tokens, and content tokens between. Otherwise
  347. * `null` is returned.
  348. *
  349. * @param MDToken[] $tokensToSearch - array of `MDToken` to search in
  350. * @param MDTokenType[] $startPattern - array of `MDTokenType` to find first
  351. * @param MDTokenType[] $endPattern - array of `MDTokenType` to find positioned after `startPattern`
  352. * @param ?callable $contentValidator - optional validator function. If provided, will be passed an array of inner `MDToken`, and the function can return `true` to accept the contents or `false` to keep searching
  353. * @param number $startIndex - token index where searching should begin
  354. * @return ?MDPairedTokenMatch match, or `null`
  355. */
  356. public static function findPairedTokens(array $tokensToSearch,
  357. array $startPattern, array $endPattern, ?callable $contentValidator=null,
  358. int $startIndex=0): ?MDPairedTokenMatch {
  359. for ($s = $startIndex; $s < sizeof($tokensToSearch); $s++) {
  360. $startMatch = findFirstTokens($tokensToSearch, $startPattern, $s);
  361. if ($startMatch === null) return null;
  362. $endStart = $startMatch->index + sizeof($startMatch->tokens);
  363. while ($endStart < sizeof($tokensToSearch)) {
  364. $endMatch = findFirstTokens($tokensToSearch, $endPattern, $endStart);
  365. if ($endMatch === null) break;
  366. $contentStart = $startMatch->index + sizeof($startMatch->tokens);
  367. $contentLength = $endMatch->index - $contentStart;
  368. $contents = array_slice($tokensToSearch, $contentStart, $contentLength);
  369. if (sizeof($contents) > 0 && ($contentValidator === null || $contentValidator($contents))) {
  370. return new MDPairedTokenMatch($startMatch->tokens,
  371. $contents,
  372. $endMatch->tokens,
  373. $startMatch->index,
  374. $startMatch->index + sizeof($startMatch->tokens),
  375. $endMatch->index,
  376. $endMatch->index + sizeof($endMatch->tokens) - $startMatch->index);
  377. } else {
  378. // Contents rejected. Try next end match.
  379. $endStart = $endMatch->index + 1;
  380. }
  381. }
  382. // No end matches. Increment start match.
  383. $s = $startMatch->index;
  384. }
  385. return null;
  386. }
  387. public function equals($other) {
  388. if (!($other instanceof MDToken)) return false;
  389. if ($other->original !== $this->original) return false;
  390. if ($other->type != $this->type) return false;
  391. if ($other->content !== $this->content) return false;
  392. if ($other->extra !== $this->extra) return false;
  393. if ($other->tag !== $this->tag) return false;
  394. if ($other->modifier != $this->modifier) return false;
  395. return true;
  396. }
  397. }
  398. /**
  399. * Parsing and rendering state. Passed around throughout the parsing process.
  400. *
  401. * States are hierarchical. A sub-state can be created by calling `.copy()` with
  402. * a new array of lines. The sub-state points back to its parent state. This
  403. * is done to parse inner content of a syntax as its own standalone document.
  404. *
  405. * If a custom `MDReader` implementation wants to store data in this object,
  406. * always do so on `state.root` to ensure it's stored on the original state,
  407. * not a child state. Otherwise data may be lost when the sub-state is discarded.
  408. */
  409. class MDState {
  410. /**
  411. * Ascends the parent chain to the root `MDState` instance. This should be
  412. * used when referencing most stored fields except `lines` and `p`.
  413. */
  414. public function root(): MDState {
  415. return $this->parent ? $this->parent->root() : $this;
  416. }
  417. /**
  418. * Lines of the markdown document. The current line index is pointed to by `p`.
  419. *
  420. * @var string[]
  421. */
  422. public array $lines;
  423. /**
  424. * The current line in `lines`.
  425. */
  426. public function currentLine(): ?string {
  427. return ($this->p < sizeof($this->lines)) ? $this->lines[$this->p] : null;
  428. }
  429. /**
  430. * Current line pointer into array `lines`.
  431. */
  432. public int $p = 0;
  433. private ?MDState $parent = null;
  434. /**
  435. * Array of `MDReader`s sorted by block reading priority.
  436. * @var MDReader[]
  437. */
  438. public array $readersByBlockPriority = [];
  439. /**
  440. * Array of `MDReader`s sorted by tokenization priority.
  441. * @var MDReader[]
  442. */
  443. public array $readersByTokenPriority = [];
  444. /**
  445. * Array of tuples of `pass:number` and `MDReader` sorted by substitution
  446. * priority.
  447. * @var array[]
  448. */
  449. public array $readersBySubstitutePriority = [];
  450. /**
  451. * Prefix to include in any generated `id` attributes on HTML elements.
  452. * Useful for keeping elements unique in multiple parsed documents in the
  453. * same HTML page.
  454. */
  455. public string $elementIdPrefix = '';
  456. /**
  457. * Filter for removing unapproved HTML tags, attributes, and values.
  458. */
  459. public MDHTMLFilter $tagFilter;
  460. private static string $textWhitespaceRegex = '^(\\s*)(?:(\\S|\\S.*\\S)(\\s*?))?$'; // 1=leading WS, 2=text, 3=trailing WS
  461. /**
  462. * @param string[] $lines - lines of markdown text
  463. */
  464. public function __construct(array $lines) {
  465. $this->lines = $lines;
  466. }
  467. /**
  468. * Creates a copy of this state with new lines. Useful for parsing nested
  469. * content.
  470. *
  471. * @param string[] $lines
  472. * @return MDState copied sub-state
  473. */
  474. public function copy(array $lines) {
  475. $cp = new MDState($lines);
  476. $cp->parent = $this;
  477. return $cp;
  478. }
  479. /**
  480. * Tests if there are at least `minCount` lines available to read. If `p`
  481. * is not provided it will be relative to `this.p`.
  482. */
  483. public function hasLines(int $minCount, ?int $p=null): bool {
  484. $relativeTo = ($p === null) ? $this->p : $p;
  485. return $relativeTo + $minCount <= sizeof($this->lines);
  486. }
  487. /**
  488. * Reads and returns an array of blocks from the current line pointer.
  489. *
  490. * @return MDBlockNode[] parsed blocks
  491. */
  492. public function readBlocks(): array {
  493. $blocks = [];
  494. while ($this->hasLines(1)) {
  495. $block = $this->readNextBlock();
  496. if ($block) {
  497. array_push($blocks, $block);
  498. } else {
  499. break;
  500. }
  501. }
  502. return $blocks;
  503. }
  504. /**
  505. * Creates a simple `MDBlockNode` if no other registered blocks match.
  506. */
  507. private function readFallbackBlock(): ?MDBlockNode {
  508. if ($this->p >= sizeof($this->lines)) return null;
  509. $lines = MDUtils::withoutTrailingBlankLines(array_slice($this->lines, $this->p));
  510. if (sizeof($lines) == 0) return null;
  511. $this->p = sizeof($this->lines);
  512. return $this->inlineMarkdownToNode(implode("\n", $lines));
  513. }
  514. /**
  515. * Attempts to read one block from the current line pointer. The pointer
  516. * will be positioned just after the end of the block.
  517. */
  518. private function readNextBlock(): ?MDBlockNode {
  519. while ($this->hasLines(1) && mb_strlen(trim($this->lines[$this->p])) == 0) {
  520. $this->p++;
  521. }
  522. if (!$this->hasLines(1)) return null;
  523. foreach ($this->root()->readersByBlockPriority as $reader) {
  524. $startP = $this->p;
  525. $block = $reader->readBlock($this);
  526. if ($block) {
  527. if ($this->p == $startP) {
  528. $readerClassName = get_class($reader);
  529. $blockClassName = get_class($block);
  530. throw new Error("{$readerClassName} returned an " +
  531. "{$blockClassName} without incrementing MDState.p. " +
  532. "This could lead to an infinite loop.");
  533. }
  534. return $block;
  535. }
  536. }
  537. $fallback = $this->readFallbackBlock();
  538. return $fallback;
  539. }
  540. /**
  541. * @param string $line
  542. * @return MDToken[]
  543. */
  544. private function inlineMarkdownToTokens(string $line): array {
  545. if ($this->parent) return $this->parent->inlineMarkdownToTokens($line);
  546. $tokens = [];
  547. $text = '';
  548. $expectLiteral = false;
  549. /**
  550. * Flushes accumulated content in `text` to `tokens`.
  551. */
  552. function endText() {
  553. if (mb_strlen($text) == 0) return;
  554. $textGroups = null;
  555. if (mb_eregi(MDState::$textWhitespaceRegex, $text, $textGroups)) {
  556. if (mb_strlen($textGroups[1]) > 0) {
  557. array_push($tokens, new MDToken($textGroups[1], MDTokenType::Whitespace, $textGroups[1]));
  558. }
  559. if ($textGroups[2] && mb_strlen($textGroups[2]) > 0) {
  560. $tokens.push(new MDToken($textGroups[2], MDTokenType::Text, $textGroups[2]));
  561. }
  562. if ($textGroups[3] && mb_strlen($textGroups[3]) > 0) {
  563. $tokens.push(new MDToken($textGroups[3], MDTokenType::Whitespace, $textGroups[3]));
  564. }
  565. } else {
  566. array_push($tokens, new MDToken($text, MDTokenType::Text, $text));
  567. }
  568. $text = '';
  569. }
  570. for ($p = 0; $p < mb_strlen(line); $p++) {
  571. $ch = mb_substr($line, p, 1);
  572. $remainder = mb_substr($line, $p);
  573. if ($expectLiteral) {
  574. $text .= $ch;
  575. $expectLiteral = false;
  576. continue;
  577. }
  578. if ($ch == '\\') {
  579. $expectLiteral = true;
  580. continue;
  581. }
  582. $found = false;
  583. foreach ($this->root()->readersByTokenPriority as $reader) {
  584. $token = $reader->readToken($this, $remainder);
  585. if ($token === null) continue;
  586. endText();
  587. array_push($tokens, $token);
  588. if ($token->original == null || mb_strlen($token->original) == 0) {
  589. $readerClassName = get_class($reader);
  590. throw new Error(`{$readerClassName} returned a token with an empty .original. This would cause an infinite loop.`);
  591. }
  592. $p += mb_strlen($token->original) - 1;
  593. $found = true;
  594. break;
  595. }
  596. if (!$found) {
  597. $text += $ch;
  598. }
  599. }
  600. endText();
  601. return $tokens;
  602. }
  603. /**
  604. * Converts a line of markdown to an `MDInlineNode`.
  605. *
  606. * @param string|string[] $line
  607. * @return MDInlineNode
  608. */
  609. public function inlineMarkdownToNode(string|array $line): MDInlineNode {
  610. $nodes = $this->inlineMarkdownToNodes($line);
  611. return (sizeof($nodes) == 1) ? $nodes[0] : new MDInlineNode($nodes);
  612. }
  613. /**
  614. * Converts a line of markdown to an array of `MDInlineNode`s.
  615. *
  616. * @param string|string[] $line
  617. * @return MDInlineNode[]
  618. */
  619. public function inlineMarkdownToNodes(string|array $line): array {
  620. $tokens = $this->inlineMarkdownToTokens(is_array($line) ? implode("\n", $line) : $line);
  621. return $this->tokensToNodes($tokens);
  622. }
  623. /**
  624. * Converts a mixed array of `MDToken` and `MDInlineNode` elements into an array
  625. * of only `MDInlineNode` via repeated `MDReader` substition.
  626. *
  627. * @param (MDToken|MDInlineNode)[] $tokens
  628. * @return MDInlineNode[]
  629. */
  630. public function tokensToNodes(array $tokens): array {
  631. $nodes = $tokens;
  632. // Perform repeated substitutions, converting sequences of tokens into
  633. // nodes, until no more substitutions can be made.
  634. $anyChanges = false;
  635. do {
  636. $anyChanges = false;
  637. foreach ($this->root->readersBySubstitutePriority as $readerTuple) {
  638. /** @var int */
  639. $pass = $readerTuple[0];
  640. /** @var MDReader */
  641. $reader = $readerTuple[1];
  642. $changed = $reader->substituteTokens($this, $pass, $nodes);
  643. if (!$changed) continue;
  644. $anyChanges = true;
  645. break;
  646. }
  647. } while ($anyChanges);
  648. // Convert any remaining tokens to text nodes. Also apply any inline
  649. // CSS modifiers.
  650. $lastNode = null;
  651. $me = $this;
  652. $nodes = array_map(function($node) use ($lastNode, $me) {
  653. if ($node instanceof MDToken) {
  654. /** @var MDToken */
  655. $token = $node;
  656. if ($token->type == MDTokenType::Modifier && $lastNode) {
  657. $me->root()->tagFilter->scrubModifier($token->modifier);
  658. $token->modifier->applyTo($lastNode);
  659. $lastNode = null;
  660. return new MDTextNode('');
  661. }
  662. $lastNode = null;
  663. return new MDTextNode($token->original);
  664. } elseif ($node instanceof MDNode) {
  665. $lastNode = ($node instanceof MDTextNode) ? null : $node;
  666. return $node;
  667. } else {
  668. $nodeClassName = get_class($node);
  669. throw new Error("Unexpected node type {$nodeClassName}");
  670. }
  671. }, $nodes);
  672. return $nodes;
  673. }
  674. /**
  675. * Mapping of reference symbols to URLs. Used by `MDReferencedLinkReader`
  676. * and `MDReferencedImageReader`.
  677. * @var array symbol -> URL
  678. */
  679. private array $referenceToURL = [];
  680. /**
  681. * Mapping of reference symbols to titles. Used by `MDReferencedLinkReader`
  682. * and `MDReferencedImageReader`.
  683. * @var array symbol -> title string
  684. */
  685. private array $referenceToTitle = [];
  686. /**
  687. * Defines a URL by reference symbol.
  688. */
  689. public function defineURL(string $reference, string $url, ?string $title=null) {
  690. $this->root->referenceToURL[mb_strtolower($reference)] = $url;
  691. if ($title !== null) $this->root()->referenceToTitle[mb_strtolower($reference)] = $title;
  692. }
  693. /**
  694. * Returns the URL associated with a reference symbol.
  695. */
  696. public function urlForReference(string $reference): ?string {
  697. return $this->root()->referenceToURL[mb_strtolower($reference)] ?? null;
  698. }
  699. /**
  700. * Returns the link title associated with a reference symbol.
  701. */
  702. public function urlTitleForReference(string $reference): ?string {
  703. return $this->root()->referenceToTitle[mb_strtolower($reference)] ?? null;
  704. }
  705. }
  706. /**
  707. * Defines a set of allowable HTML tags, attributes, and CSS.
  708. */
  709. class MDHTMLFilter {
  710. /**
  711. * Mapping of permitted lowercase tag names to objects containing allowable
  712. * attributes for those tags. Does not need to include those attributes
  713. * defined in `allowableGlobalAttributes`.
  714. *
  715. * Values are objects with allowable lowercase attribute names mapped to
  716. * allowable value patterns. A `*` means any value is acceptable. Multiple
  717. * allowable values can be joined together with `|`. These special symbols
  718. * represent certain kinds of values and can be used in combination or in
  719. * place of literal values.
  720. *
  721. * - `{classlist}`: A list of legal CSS classnames, separated by spaces
  722. * - `{int}`: An integer
  723. * - `{none}`: No value (an attribute with no `=` or value, like `checked`)
  724. * - `{style}`: One or more CSS declarations, separated by semicolons (simple
  725. * `key: value;` syntax only)
  726. * - `{url}`: A URL
  727. * @type {object}
  728. */
  729. public array $allowableTags = [
  730. 'address' => [
  731. 'cite' => '{url}',
  732. ],
  733. 'h1' => [],
  734. 'h2' => [],
  735. 'h3' => [],
  736. 'h4' => [],
  737. 'h5' => [],
  738. 'h6' => [],
  739. 'blockquote' => [],
  740. 'dl' => [],
  741. 'dt' => [],
  742. 'dd' => [],
  743. 'div' => [],
  744. 'hr' => [],
  745. 'ul' => [],
  746. 'ol' => [
  747. 'start' => '{int}',
  748. 'type' => 'a|A|i|I|1',
  749. ],
  750. 'li' => [
  751. 'value' => '{int}',
  752. ],
  753. 'p' => [],
  754. 'pre' => [],
  755. 'table' => [],
  756. 'thead' => [],
  757. 'tbody' => [],
  758. 'tfoot' => [],
  759. 'tr' => [],
  760. 'td' => [],
  761. 'th' => [],
  762. 'a' => [
  763. 'href' => '{url}',
  764. 'target' => '*',
  765. ],
  766. 'abbr' => [],
  767. 'b' => [],
  768. 'br' => [],
  769. 'cite' => [],
  770. 'code' => [],
  771. 'data' => [
  772. 'value' => '*',
  773. ],
  774. 'dfn' => [],
  775. 'em' => [],
  776. 'i' => [],
  777. 'kbd' => [],
  778. 'mark' => [],
  779. 'q' => [
  780. 'cite' => '{url}',
  781. ],
  782. 's' => [],
  783. 'samp' => [],
  784. 'small' => [],
  785. 'span' => [],
  786. 'strong' => [],
  787. 'sub' => [],
  788. 'sup' => [],
  789. 'time' => [
  790. 'datetime' => '*',
  791. ],
  792. 'u' => [],
  793. 'var' => [],
  794. 'wbr' => [],
  795. 'img' => [
  796. 'alt' => '*',
  797. 'href' => '{url}',
  798. ],
  799. 'figure' => [],
  800. 'figcaption' => [],
  801. 'del' => [],
  802. 'ins' => [],
  803. 'details' => [],
  804. 'summary' => [],
  805. ];
  806. /**
  807. * Mapping of allowable lowercase global attributes to their permitted
  808. * values. Uses same value pattern syntax as described in `allowableTags`.
  809. * @type {object}
  810. */
  811. public array $allowableGlobalAttributes = [
  812. 'class' => '{classlist}',
  813. 'data-*' => '*',
  814. 'dir' => 'ltr|rtl|auto',
  815. 'id' => '*',
  816. 'lang' => '*',
  817. 'style' => '{style}',
  818. 'title' => '*',
  819. 'translate' => 'yes|no|{none}',
  820. ];
  821. /**
  822. * Mapping of allowable CSS style names to their allowable value patterns.
  823. * Multiple values can be delimited with `|` characters. Limited support
  824. * so far.
  825. *
  826. * Recognized special values:
  827. * - `{color}`: A hex or named color
  828. *
  829. * @type {object}
  830. */
  831. public array $allowableStyleKeys = [
  832. 'background-color' => '{color}',
  833. 'color' => '{color}',
  834. ];
  835. /**
  836. * Scrubs all forbidden attributes from an HTML tag. Assumes the tag name
  837. * itself has already been whitelisted.
  838. *
  839. * @param {MDHTMLTag} tag - HTML tag
  840. */
  841. public function scrubTag(MDHTMLTag $tag) {
  842. foreach ($tag->attributes as $name => $value) {
  843. if (!$this->isValidAttributeName($tag->tagName, $name)) {
  844. unset($tag->attributes[$name]);
  845. }
  846. if (!$this->isValidAttributeValue($tag->tagName, $name, $value)) {
  847. unset($tag->attributes[$name]);
  848. }
  849. }
  850. }
  851. /**
  852. * Scrubs all forbidden attributes from an HTML modifier.
  853. *
  854. * @param MDTagModifier $modifier
  855. * @param ?string $tagName HTML tag name, if known, otherwise only
  856. * global attributes will be permitted
  857. */
  858. public function scrubModifier(MDHTMLModifier $modifier, ?string $tagName) {
  859. if (sizeof($modifier->cssClasses) > 0) {
  860. $classList = implode(' ', $modifier->cssClasses);
  861. if (!$this->isValidAttributeValue($tagName, 'class', $classList)) {
  862. $modifier->cssClasses = [];
  863. }
  864. }
  865. if ($modifier->cssId !== null) {
  866. if (!$this->isValidAttributeValue($tagName, 'id', $modifier->cssId)) {
  867. $modifier->cssId = null;
  868. }
  869. }
  870. if (!$this->isValidAttributeName($tagName, 'style')) {
  871. $modifier->cssStyles = [];
  872. } else {
  873. foreach ($modifier->cssStyles as $key => $val) {
  874. if (!$this->isValidStyleValue($key, $val)) {
  875. unset($modifier->cssStyles[$key]);
  876. }
  877. }
  878. }
  879. foreach ($modifier->attributes as $key => $val) {
  880. if (!$this->isValidAttributeValue($tagName, $key, $val)) {
  881. unset($modifier->attributes[$key]);
  882. }
  883. }
  884. }
  885. /**
  886. * Tests if an HTML tag name is permitted.
  887. */
  888. public function isValidTagName(string $tagName): bool {
  889. return ($this->allowableTags[mb_strtolower($tagName)] ?? null) !== null;
  890. }
  891. /**
  892. * Tests if an HTML attribute name is permitted.
  893. */
  894. public function isValidAttributeName(?string $tagName, string $attributeName): bool {
  895. $lcAttributeName = mb_strtolower($attributeName);
  896. if (($this->allowableGlobalAttributes[$lcAttributeName] ?? null) !== null) {
  897. return true;
  898. }
  899. foreach ($this->allowableGlobalAttributes as $pattern => $valuePattern) {
  900. if (!str_ends_with($pattern, '*')) continue;
  901. $patternPrefix = mb_substr($pattern, 0, mb_strlen($pattern) - 1);
  902. if (str_starts_with($lcAttributeName, $patternPrefix)) {
  903. return true;
  904. }
  905. }
  906. if ($tagName === null) return false;
  907. $lcTagName = mb_strtolower($tagName);
  908. $tagAttributes = $this->allowableTags[$lcTagName];
  909. if ($tagAttributes !== null) {
  910. return ($tagAttributes[$lcAttributeName] ?? null) !== null;
  911. }
  912. return false;
  913. }
  914. /**
  915. * Tests if an attribute value is allowable.
  916. */
  917. public function isValidAttributeValue(?string $tagName, string $attributeName, $attributeValue): bool {
  918. $lcAttributeName = mb_strtolower($attributeName);
  919. $globalPattern = $this->allowableGlobalAttributes[$lcAttributeName] ?? null;
  920. if ($globalPattern !== null) {
  921. return $this->attributeValueMatchesPattern($attributeValue, $globalPattern);
  922. }
  923. foreach ($this->allowableGlobalAttributes as $namePattern => $valuePattern) {
  924. if (str_ends_with($namePattern, '*') && str_starts_with($lcAttributeName, mb_substr($namePattern, 0, mb_strlen($namePattern) - 1))) {
  925. return $this->attributeValueMatchesPattern($attributeValue, $valuePattern);
  926. }
  927. }
  928. if ($tagName === null) return false;
  929. $lcTagName = mb_strtolower($tagName);
  930. $tagAttributes = $this->allowableTags[$lcTagName] ?? null;
  931. if ($tagAttributes === null) return false;
  932. $valuePattern = $tagAttributes[$lcAttributeName] ?? null;
  933. if ($valuePattern === null) return false;
  934. return $this->attributeValueMatchesPattern($attributeValue, $valuePattern);
  935. }
  936. private static string $permissiveURLRegex = '^\\S+$';
  937. private static string $integerRegex = '^[\\-]?\\d+$';
  938. private static string $classListRegex = '^-?[_a-zA-Z]+[_a-zA-Z0-9-]*(?:\\s+-?[_a-zA-Z]+[_a-zA-Z0-9-]*)*$';
  939. private function attributeValueMatchesPattern(string|bool $value, string $pattern): bool {
  940. $options = explode('|', $pattern);
  941. foreach ($options as $option) {
  942. switch ($option) {
  943. case '*':
  944. return true;
  945. case '{classlist}':
  946. if (mb_eregi(self::classListRegex, $value)) return true;
  947. break;
  948. case '{int}':
  949. if (mb_eregi(self::integerRegex, $value)) return true;
  950. break;
  951. case '{none}':
  952. if ($value === true) return true;
  953. break;
  954. case '{style}':
  955. if ($this->isValidStyleDeclaration($value)) return true;
  956. break;
  957. case '{url}':
  958. if (mb_eregi(self::permissiveURLRegex, $value)) return true;
  959. break;
  960. default:
  961. if ($value === $option) return true;
  962. break;
  963. }
  964. }
  965. return false;
  966. }
  967. /**
  968. * Tests if a string of one or more style `key: value;` declarations is
  969. * fully allowable.
  970. */
  971. public function isValidStyleDeclaration(string $styles): bool {
  972. $settings = explode(';', $styles);
  973. foreach ($settings as $setting) {
  974. if (mb_strlen(trim($setting)) == 0) continue;
  975. $parts = explode(':', $setting);
  976. if (sizeof($parts) != 2) return false;
  977. $name = trim($parts[0]);
  978. if (!$this->isValidStyleKey($name)) return false;
  979. $value = trim($parts[1]);
  980. if (!$this->isValidStyleValue($name, $value)) return false;
  981. }
  982. return true;
  983. }
  984. /**
  985. * Tests if a CSS style key is allowable.
  986. */
  987. public function isValidStyleKey(string $key): bool {
  988. return ($this->allowableStyleKeys[$key] ?? null) !== null;
  989. }
  990. /**
  991. * Tests if a CSS style value is allowable.
  992. */
  993. public function isValidStyleValue(string $key, string $value): bool {
  994. $pattern = $this->allowableStyleKeys[$key] ?? null;
  995. if ($pattern === null) return false;
  996. $options = explode('|', $pattern);
  997. foreach ($options as $option) {
  998. switch ($option) {
  999. case '{color}':
  1000. if ($this->isValidCSSColor($value)) return true;
  1001. default:
  1002. if ($value === $option) return true;
  1003. }
  1004. }
  1005. return false;
  1006. }
  1007. private static string $styleColorRegex = '^#[0-9a-f]{3}(?:[0-9a-f]{3})?$|^[a-zA-Z]+$';
  1008. private function isValidCSSColor(string $value): bool {
  1009. return mb_eregi(self::$styleColorRegex, $value);
  1010. }
  1011. }
  1012. /**
  1013. * Represents a single HTML tag. Paired tags are represented separately.
  1014. */
  1015. class MDHTMLTag {
  1016. /**
  1017. * Verbatim string of the original parsed tag. Not modified. Should be
  1018. * considered unsafe for inclusion in the final document. Use `toString()`
  1019. * instead.
  1020. */
  1021. public string $original;
  1022. public string $tagName;
  1023. public bool $isCloser;
  1024. /**
  1025. * Map of attribute names to value strings.
  1026. */
  1027. public array $attributes;
  1028. /**
  1029. * @param string $original
  1030. * @param string $tagName
  1031. * @param bool $isCloser
  1032. * @param array $attributes
  1033. */
  1034. public function __construct(string $original, string $tagName, bool $isCloser,
  1035. array $attributes) {
  1036. $this->original = $original;
  1037. $this->tagName = $tagName;
  1038. $this->isCloser = $isCloser;
  1039. $this->attributes = $attributes;
  1040. }
  1041. public function __toString(): string {
  1042. if ($this->isCloser) {
  1043. return "</{$this->tagName}>";
  1044. }
  1045. $html = '<';
  1046. $html .= $this->tagName;
  1047. foreach ($this->attributes as $key => $value) {
  1048. $safeName = MDUtils::scrubAttributeName($key);
  1049. if ($value === true) {
  1050. $html .= " {$safeName}";
  1051. } else {
  1052. $escapedValue = MDUtils::escapeHTML("{$value}");
  1053. $html .= " {$safeName}=\"{$escapedValue}\"";
  1054. }
  1055. }
  1056. $html .= '>';
  1057. return $html;
  1058. }
  1059. public function equals($other): bool {
  1060. if (!($other instanceof MDHTMLTag)) return false;
  1061. if ($other->tagName != $this->tagName) return false;
  1062. if ($other->isCloser != $this->isCloser) return false;
  1063. return MDUtils::equal($other->attributes, $this->attributes);
  1064. }
  1065. private static string $htmlTagNameFirstRegex = '[a-z]';
  1066. private static string $htmlTagNameMedialRegex = '[a-z0-9]';
  1067. private static string $htmlAttributeNameFirstRegex = '[a-z]';
  1068. private static string $htmlAttributeNameMedialRegex = '[a-z0-9-]';
  1069. private static string $whitespaceCharRegex = '\\s';
  1070. /**
  1071. * Checks the start of the given string for presence of an HTML tag.
  1072. */
  1073. public static function fromLineStart(string $line): ?MDHTMLTag {
  1074. $expectOpenBracket = 0;
  1075. $expectCloserOrName = 1;
  1076. $expectName = 2;
  1077. $expectAttributeNameOrEnd = 3;
  1078. $expectEqualsOrAttributeOrEnd = 4;
  1079. $expectAttributeValue = 5;
  1080. $expectCloseBracket = 6;
  1081. $isCloser = false;
  1082. $tagName = '';
  1083. $attributeName = '';
  1084. $attributeValue = '';
  1085. $attributeQuote = null;
  1086. $attributes = [];
  1087. $fullTag = null;
  1088. $endAttribute = function(bool $unescape=false) use (&$attributes, &$attributeName, &$attributeValue, &$attributeQuote) {
  1089. if (mb_strlen($attributeName) > 0) {
  1090. if (mb_strlen($attributeValue) > 0 || $attributeQuote !== null) {
  1091. $attributes[$attributeName] = $unescape ? html_entity_decode($attributeValue, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML401, 'UTF-8') : $attributeValue;
  1092. } else {
  1093. $attributes[$attributeName] = true;
  1094. }
  1095. }
  1096. $attributeName = '';
  1097. $attributeValue = '';
  1098. $attributeQuote = null;
  1099. };
  1100. $expect = $expectOpenBracket;
  1101. for ($p = 0; $p < mb_strlen($line) && $fullTag === null; $p++) {
  1102. $ch = mb_substr($line, $p, 1);
  1103. $isWhitespace = mb_eregi(self::$whitespaceCharRegex, $ch);
  1104. switch ($expect) {
  1105. case $expectOpenBracket:
  1106. if ($ch != '<') return null;
  1107. $expect = $expectCloserOrName;
  1108. break;
  1109. case $expectCloserOrName:
  1110. if ($ch == '/') {
  1111. $isCloser = true;
  1112. } else {
  1113. $p--;
  1114. }
  1115. $expect = $expectName;
  1116. break;
  1117. case $expectName:
  1118. if (mb_strlen($tagName) == 0) {
  1119. if (!mb_eregi(self::$htmlTagNameFirstRegex, $ch)) return null;
  1120. $tagName .= $ch;
  1121. } else {
  1122. if (mb_eregi(self::$htmlTagNameMedialRegex, $ch)) {
  1123. $tagName .= $ch;
  1124. } else {
  1125. $p--;
  1126. $expect = ($isCloser) ? $expectCloseBracket : $expectAttributeNameOrEnd;
  1127. }
  1128. }
  1129. break;
  1130. case $expectAttributeNameOrEnd:
  1131. if (mb_strlen($attributeName) == 0) {
  1132. if ($isWhitespace) {
  1133. // skip whitespace
  1134. } elseif ($ch == '/') {
  1135. $expect = $expectCloseBracket;
  1136. } elseif ($ch == '>') {
  1137. $fullTag = mb_substr($line, 0, $p + 1);
  1138. break;
  1139. } elseif (mb_eregi(self::$htmlAttributeNameFirstRegex, $ch)) {
  1140. $attributeName .= $ch;
  1141. } else {
  1142. return null;
  1143. }
  1144. } elseif ($isWhitespace) {
  1145. $expect = $expectEqualsOrAttributeOrEnd;
  1146. } elseif ($ch == '/') {
  1147. $endAttribute();
  1148. $expect = $expectCloseBracket;
  1149. } elseif ($ch == '>') {
  1150. $endAttribute();
  1151. $fullTag = mb_substr($line, 0, $p + 1);
  1152. break;
  1153. } elseif ($ch == '=') {
  1154. $expect = $expectAttributeValue;
  1155. } elseif (mb_eregi(self::$htmlAttributeNameMedialRegex, $ch)) {
  1156. $attributeName .= $ch;
  1157. } else {
  1158. return null;
  1159. }
  1160. break;
  1161. case $expectEqualsOrAttributeOrEnd:
  1162. if ($ch == '=') {
  1163. $expect = $expectAttributeValue;
  1164. } elseif ($isWhitespace) {
  1165. // skip whitespace
  1166. } elseif ($ch == '/') {
  1167. $expect = $expectCloseBracket;
  1168. } elseif ($ch == '>') {
  1169. $fullTag = mb_substr($line, 0, $p + 1);
  1170. break;
  1171. } elseif (mb_eregi(self::$htmlAttributeNameFirstRegex, $ch)) {
  1172. $endAttribute();
  1173. $expect = $expectAttributeNameOrEnd;
  1174. $p--;
  1175. }
  1176. break;
  1177. case $expectAttributeValue:
  1178. if (mb_strlen($attributeValue) == 0) {
  1179. if ($attributeQuote === null) {
  1180. if ($isWhitespace) {
  1181. // skip whitespace
  1182. } elseif ($ch == '"' || $ch == "'") {
  1183. $attributeQuote = $ch;
  1184. } else {
  1185. $attributeQuote = ''; // explicitly unquoted
  1186. $p--;
  1187. }
  1188. } else {
  1189. if ($ch === $attributeQuote) {
  1190. // Empty string
  1191. $endAttribute($attributeQuote != '');
  1192. $expect = $expectAttributeNameOrEnd;
  1193. } elseif ($attributeQuote === '' && ($ch == '/' || $ch == '>')) {
  1194. return null;
  1195. } else {
  1196. $attributeValue .= $ch;
  1197. }
  1198. }
  1199. } else {
  1200. if ($ch === $attributeQuote) {
  1201. $endAttribute($attributeQuote != '');
  1202. $expect = $expectAttributeNameOrEnd;
  1203. } elseif ($attributeQuote === '' && $isWhitespace) {
  1204. $endAttribute();
  1205. $expect = $expectAttributeNameOrEnd;
  1206. } else {
  1207. $attributeValue .= $ch;
  1208. }
  1209. }
  1210. break;
  1211. case $expectCloseBracket:
  1212. if ($isWhitespace) {
  1213. // ignore whitespace
  1214. } elseif ($ch == '>') {
  1215. $fullTag = mb_substr($line, 0, $p + 1);
  1216. break;
  1217. }
  1218. break;
  1219. }
  1220. }
  1221. if ($fullTag === null) return null;
  1222. $endAttribute();
  1223. return new MDHTMLTag($fullTag, $tagName, $isCloser, $attributes);
  1224. }
  1225. }
  1226. /**
  1227. * Represents HTML modifications to a node, such as CSS classes to add or
  1228. * additional attributes. See `MDHTMLFilter.scrubModifier()` to remove disallowed
  1229. * values.
  1230. */
  1231. class MDTagModifier {
  1232. /**
  1233. * Verbatim markdown syntax. Unmodified by changes to other properties.
  1234. */
  1235. public string $original;
  1236. /** @var string[] */
  1237. public array $cssClasses = [];
  1238. public ?string $cssId = null;
  1239. public array $cssStyles = [];
  1240. public array $attributes = [];
  1241. private static $baseClassRegex = '\\.([a-z_\\-][a-z0-9_\\-]*?)';
  1242. private static $baseIdRegex = '#([a-z_\\-][a-z0-9_\\-]*?)';
  1243. private static $baseAttributeRegex = '([a-z0-9]+?)=([^\\s\\}]+?)';
  1244. private static $baseRegex = '\\{([^}]+?)}';
  1245. private static $leadingClassRegex = '^\\{([^}]+?)}';
  1246. private static $trailingClassRegex = '^(.*?)\\s*\\{([^}]+?)}\\s*$';
  1247. private static $classRegex = '^\\.([a-z_\\-][a-z0-9_\\-]*?)$'; // 1=classname
  1248. private static $idRegex = '^#([a-z_\\-][a-z0-9_\\-]*?)$'; // 1=id
  1249. private static $attributeRegex = '^([a-z0-9]+?)=([^\\s\\}]+?)$'; // 1=attribute name, 2=attribute value
  1250. public function applyTo(MDNode $node) {
  1251. if ($node instanceof MDNode) {
  1252. foreach ($this->cssClasses as $cssClass) {
  1253. $node->addClass($cssClass);
  1254. }
  1255. if ($this->cssId) $node->cssId = $this->cssId;
  1256. foreach ($this->attributes as $name => $value) {
  1257. $node->attributes[$name] = $value;
  1258. }
  1259. foreach ($this->cssStyles as $name => $value) {
  1260. $node->cssStyles[$name] = $value;
  1261. }
  1262. }
  1263. }
  1264. /**
  1265. * Adds a CSS class. If already present it will not be duplicated.
  1266. */
  1267. public function addClass(string $cssClass): bool {
  1268. if (array_search($cssClass, $this->cssClasses) !== false) return false;
  1269. array_push($this->cssClasses, $cssClass);
  1270. return true;
  1271. }
  1272. /**
  1273. * Removes a CSS class.
  1274. */
  1275. public function removeClass(string $cssClass): bool {
  1276. $beforeLength = sizeof($this->cssClasses);
  1277. $this->cssClasses = array_diff($this->cssClasses, [ $cssClass ]);
  1278. return sizeof($this->cssClasses) != beforeLength;
  1279. }
  1280. public function equals($other): bool {
  1281. if (!($other instanceof MDTagModifier)) return false;
  1282. if (!MDUtils::equal($other->cssClasses, $this->cssClasses)) return false;
  1283. if ($other->cssId !== $this->cssId) return false;
  1284. if (!MDUtils::equal($other->attributes, $this->attributes)) return false;
  1285. return true;
  1286. }
  1287. public function __toString(): string {
  1288. return $this->original;
  1289. }
  1290. private static function styleToObject(string $styleValue): array {
  1291. $pairs = explode(';', $styleValue);
  1292. $styles = [];
  1293. foreach ($pairs as $pair) {
  1294. $keyAndValue = explode(':', $pair);
  1295. if (sizeof($keyAndValue) != 2) continue;
  1296. $styles[$keyAndValue[0]] = $keyAndValue[1];
  1297. }
  1298. return $styles;
  1299. }
  1300. private static function fromContents(string $contents): ?MDTagModifier {
  1301. $modifierTokens = mb_split('\\s+', $contents);
  1302. $mod = new MDTagModifier();
  1303. $mod->original = "{{$contents}}";
  1304. foreach ($modifierTokens as $token) {
  1305. if (trim($token) == '') continue;
  1306. if (mb_eregi(self::$classRegex, $token, $groups)) {
  1307. $mod->addClass($groups[1]);
  1308. } elseif (mb_eregi(self::$idRegex, $token, $groups)) {
  1309. $mod->cssId = $groups[1];
  1310. } elseif (mb_eregi(self::$attributeRegex, $token, $groups)) {
  1311. if ($groups[1] == 'style') {
  1312. $mod->cssStyles = self::styleToObject($groups[2]);
  1313. } else {
  1314. $mod->attributes[$groups[1]] = $groups[2];
  1315. }
  1316. } else {
  1317. return null;
  1318. }
  1319. }
  1320. return $mod;
  1321. }
  1322. /**
  1323. * Extracts block modifier from end of a line. Always returns a 2-element
  1324. * tuple array:
  1325. * - `0`: the line without the modifier
  1326. * - `1`: an `MDTagModifier` if found or `null` if not
  1327. *
  1328. * @param string $line
  1329. * @param ?MDState $state
  1330. * @return array tuple with remaining line and `MDTagModifier` or `null`
  1331. */
  1332. public static function fromLine(string $line, ?MDState $state): array {
  1333. if ($state) {
  1334. $found = false;
  1335. foreach ($state->root()->readersByBlockPriority as $reader) {
  1336. if ($reader instanceof MDModifierReader) {
  1337. $found = true;
  1338. break;
  1339. }
  1340. }
  1341. if (!$found) return [ $line, null ];
  1342. }
  1343. if (!mb_eregi(self::$trailingClassRegex, $line, $groups)) return [ $line, null ];
  1344. $bareLine = $groups[1];
  1345. $mod = self::fromContents($groups[2]);
  1346. return [ $bareLine, $mod ];
  1347. }
  1348. /**
  1349. * Attempts to extract modifier from head of string.
  1350. */
  1351. public static function fromStart(string $line): ?MDTagModifier {
  1352. if (!mb_eregi(self::$leadingClassRegex, $line, $groups)) return null;
  1353. return self::fromContents($groups[1]);
  1354. }
  1355. /**
  1356. * Discards any modifiers from a line and returns what remains.
  1357. */
  1358. public static function strip(string $line): string {
  1359. if (!mb_eregi(self::$trailingClassRegex, $line, $groups)) return $line;
  1360. return $groups[1];
  1361. }
  1362. }
  1363. // -- Readers ---------------------------------------------------------------
  1364. /**
  1365. * Base class for readers of various markdown syntax. A `Markdown` instance can
  1366. * be created with any combination of subclasses of these to customize the
  1367. * flavor of markdown parsed.
  1368. *
  1369. * @see {@link custom.md} for details on subclassing
  1370. */
  1371. class MDReader {
  1372. /**
  1373. * Called before processing begins. `state.lines` is populated and the
  1374. * line pointer `state.p` will be at `0`.
  1375. *
  1376. * Default implementation does nothing.
  1377. */
  1378. public function preProcess(MDState $state) {}
  1379. /**
  1380. * Attempts to read an `MDBlockNode` subclass at the current line pointer
  1381. * `state.p`. Only matches if the block pattern starts at the line pointer,
  1382. * not elsewhere in the `state.lines` array. If a block is found, `state.p`
  1383. * should be incremented to the next line _after_ the block structure and
  1384. * a `MDBlockNode` subclass instance is returned. If no block is found,
  1385. * returns `null`.
  1386. *
  1387. * Default implementation always returns `null`.
  1388. */
  1389. public function readBlock(MDState $state): ?MDBlockNode { return null; }
  1390. /**
  1391. * Attempts to read an inline token from the beginning of `line`. Only the
  1392. * start of the given `line` is considered. If a matching token is found, an
  1393. * `MDToken` is returned. Otherwise `null` is returned.
  1394. *
  1395. * Default implementation always returns `null`.
  1396. */
  1397. public function readToken(MDState $state, string $line): ?MDToken { return null; }
  1398. /**
  1399. * Attempts to find a pattern anywhere in `tokens` and perform a _single_
  1400. * in-place substitution with one or more `MDNode` subclass instances.
  1401. * If a substitution is performed, must return `true`, otherwise `false`.
  1402. *
  1403. * Default implementation always returns `false`.
  1404. *
  1405. * @param MDState $state
  1406. * @param int $pass what substitution pass this is, starting with 1
  1407. * @param (MDToken|MDInlineNode)[] $tokens mixed array of `MDToken` and `MDInlineNode` elements
  1408. * @return bool `true` if a substitution was performed, `false` if not
  1409. */
  1410. public function substituteTokens(MDState $state, int $pass, array $tokens): bool { return false; }
  1411. /**
  1412. * Called after all parsing has completed. An array `blocks` is passed of
  1413. * all the top-level `MDBlockNode` elements in the document which this
  1414. * method can traverse or alter in-place via `.splice` operations if
  1415. * necessary.
  1416. *
  1417. * `MDNode.visitChildren` is useful for recursively looking for certain
  1418. * `MDNode` instances. `MDNode.replaceNodes` is useful for swapping in
  1419. * replacements.
  1420. *
  1421. * Default implementation does nothing.
  1422. *
  1423. * @param MDState $state
  1424. * @param MDBlockNode[] $blocks
  1425. */
  1426. public function postProcess(MDState $state, array $blocks) {}
  1427. /**
  1428. * Can be overridden to influence ordering of this reader with respect to
  1429. * another during the block parsing phase. Return `-1` to be ordered before
  1430. * the given reader, `1` to be ordered after it, or `0` for no preference.
  1431. * Only return non-`0` values to resolve specific conflicts.
  1432. *
  1433. * Default implementation always returns `0` (no preference).
  1434. *
  1435. * @param MDReader $other
  1436. * @return int a negative, positive, or 0 value to be ordered before,
  1437. * after, or anwhere relative to `other`, respectively
  1438. */
  1439. public function compareBlockOrdering(MDReader $other): int {
  1440. return 0;
  1441. }
  1442. /**
  1443. * Can be overridden to influence ordering of this reader with respect to
  1444. * another during the tokenizing phase. Return `-1` to be ordered before
  1445. * the given reader, `1` to be ordered after it, or `0` for no preference.
  1446. * Only return non-`0` values to resolve specific conflicts.
  1447. *
  1448. * Default implementation always returns `0` (no preference).
  1449. *
  1450. * @param MDReader $other
  1451. * @return int a negative, positive, or 0 value to be ordered before,
  1452. * after, or anwhere relative to `other`, respectively
  1453. */
  1454. public function compareTokenizeOrdering(MDReader $other): int {
  1455. return 0;
  1456. }
  1457. /**
  1458. * Can be overridden to influence ordering of this reader with respect to
  1459. * another during the substitution phase. Return `-1` to be ordered before
  1460. * the given reader, `1` to be ordered after it, or `0` for no preference.
  1461. * Only return non-`0` values to resolve specific conflicts.
  1462. *
  1463. * Readers are sorted within each substitution pass. All pass 1 readers are
  1464. * processed first, then all pass 2 readers, etc. The number of passes this
  1465. * reader participates in is dictated by `substitionPassCount`.
  1466. *
  1467. * Default implementation always returns `0` (no preference).
  1468. *
  1469. * @param MDReader $other
  1470. * @param int $pass substitution pass, with numbering starting at `1`
  1471. * @return int a negative, positive, or 0 value to be ordered before,
  1472. * after, or anwhere relative to `other`, respectively
  1473. */
  1474. public function compareSubstituteOrdering(MDReader $other, int $pass): int {
  1475. return 0;
  1476. }
  1477. /**
  1478. * How many substitution passes this reader requires. Substitution allows
  1479. * all pass 1 readers to process first, then all pass 2 readers, etc.
  1480. */
  1481. public function substitutionPassCount(): int { return 1; }
  1482. /**
  1483. * For sorting readers with ordering preferences. The `compare` methods
  1484. * don't have the properties of normal sorting compares so need to sort
  1485. * differently.
  1486. *
  1487. * @param MDReader[] $arr array to sort
  1488. * @param callable $compareFn comparison function, taking two array element
  1489. * arguments and returning -1, 0, or 1 for a < b, a == b, and a > b,
  1490. * respectively
  1491. * @param callable $idFn function for returning a unique hashable id for
  1492. * the array element
  1493. * @return MDReader[] sorted array
  1494. */
  1495. private static function kahnTopologicalSort(array $arr, callable $compareFn, callable $idFn): array {
  1496. $graph = [];
  1497. $inDegrees = [];
  1498. $valuesById = [];
  1499. // Build the graph and compute in-degrees
  1500. foreach ($arr as $elem) {
  1501. $id = $idFn($elem);
  1502. $graph[$id] = [];
  1503. $inDegrees[$id] = 0;
  1504. $valuesById[$id] = $elem;
  1505. }
  1506. for ($i = 0; $i < sizeof($arr); $i++) {
  1507. $elemA = $arr[$i];
  1508. $idA = $idFn($elemA);
  1509. for ($j = 0; $j < sizeof($arr); $j++) {
  1510. if ($i === $j) continue;
  1511. $elemB = $arr[$j];
  1512. $idB = $idFn($elemB);
  1513. $comparisonResult = $compareFn($elemA, $elemB);
  1514. if ($comparisonResult < 0) {
  1515. array_push($graph[$idA], push($idB));
  1516. $inDegrees[$idB]++;
  1517. } elseif ($comparisonResult > 0) {
  1518. array_push($graph[$idB], $idA);
  1519. $inDegrees[$idA]++;
  1520. }
  1521. }
  1522. }
  1523. // Initialize the queue with zero-inDegree nodes
  1524. $queue = [];
  1525. foreach ($inDegrees as $elemId) {
  1526. if ($inDegrees[$elemId] === 0) {
  1527. array_push($queue, $elemId);
  1528. }
  1529. }
  1530. // Process the queue and build the topological order list
  1531. $sorted = [];
  1532. while (sizeof($queue) > 0) {
  1533. $elemId = array_shift($queue);
  1534. array_push($sorted, $valuesById[$elemId]);
  1535. unset($valuesById[$elemId]);
  1536. foreach ($graph[$elemId] as $neighbor) {
  1537. $inDegrees[$neighbor]--;
  1538. if ($inDegrees[$neighbor] === 0) {
  1539. array_push($queue, $neighbor);
  1540. }
  1541. }
  1542. }
  1543. // Anything left over can go at the end. No ordering dependencies.
  1544. foreach ($valuesById as $elemId => $value) {
  1545. array_push($sorted, $value);
  1546. }
  1547. return $sorted;
  1548. }
  1549. /**
  1550. * Returns a sorted array of readers by their block priority preferences.
  1551. *
  1552. * @param MDReader[] $readers
  1553. * @return MDReader[] sorted readers
  1554. */
  1555. public static function sortReaderForBlocks(array &$readers) {
  1556. $sorted = $readers;
  1557. return self::kahnTopologicalSort($sorted, function(MDReader $a, MDReader $b): int {
  1558. return $a->compareBlockOrdering($b);
  1559. }, fn($elem) => get_class($elem));
  1560. }
  1561. /**
  1562. * Returns a sorted array of readers by their tokenization priority preferences.
  1563. *
  1564. * @param MDReader[] $readers
  1565. * @return MDReader[] sorted readers
  1566. */
  1567. public static function sortReadersForTokenizing(array $readers): array {
  1568. $sorted = $readers;
  1569. return self::kahnTopologicalSort($sorted, function(MDReader $a, MDReader $b): int {
  1570. return $a->compareTokenizeOrdering($b);
  1571. }, fn($elem) => get_class($elem));
  1572. }
  1573. /**
  1574. * Returns a sorted array of tuples (arrays) containing the substitution
  1575. * pass number and reader instance, sorted by their substitution priority
  1576. * preferences.
  1577. *
  1578. * For readers with `substitutionPassCount` > `1`, the same reader will
  1579. * appear multiple times in the resulting array, one per pass.
  1580. *
  1581. * @param MDReader[] $readers
  1582. * @return MDReader[] sorted array of tuples with the pass number and
  1583. * reader instance in each
  1584. */
  1585. public static function sortReadersForSubstitution(array $readers): array {
  1586. $tuples = [];
  1587. $maxPass = 1;
  1588. foreach ($readers as $reader) {
  1589. $passCount = $reader->substitutionPassCount();
  1590. for ($pass = 1; $pass <= $passCount; $pass++) {
  1591. array_push($tuples, [ $pass, $reader ]);
  1592. }
  1593. $maxPass = max($maxPass, $pass);
  1594. }
  1595. $result = [];
  1596. for ($pass = 1; $pass <= $maxPass; $pass++) {
  1597. $readersThisPass = array_filter(tuples, fn($tup) => $tup[0] == $pass);
  1598. $passResult = self::kahnTopologicalSort($readersThisPass, function(MDReader $a, MDReader $b): int {
  1599. $aReader = $a[1];
  1600. $bReader = $b[1];
  1601. return $aReader->compareSubstituteOrdering($bReader, $pass);
  1602. }, fn($elem) => get_class($elem[1]));
  1603. $result = array_merge($result, $passResult);
  1604. }
  1605. return $result;
  1606. }
  1607. }
  1608. /**
  1609. * Reads markdown blocks for headings denoted with the underline syntax.
  1610. *
  1611. * Supports `MDTagModifier` suffixes.
  1612. */
  1613. class MDUnderlinedHeadingReader extends MDReader {
  1614. public function readBlock(MDState $state): ?MDBlockNode {
  1615. $p = $state->p;
  1616. if (!$state->hasLines(2)) return null;
  1617. $modifier;
  1618. $contentLine = trim($state->lines[$p++]);
  1619. [$contentLine, $modifier] = MDTagModifier.fromLine(contentLine, state);
  1620. $underLine = trim($state->lines[$p++]);
  1621. if ($contentLine == '') return null;
  1622. if (mb_eregi('^=+$', $underLine)) {
  1623. $state->p = $p;
  1624. $block = new MDHeadingNode(1, $state->inlineMarkdownToNodes($contentLine));
  1625. if ($modifier) $modifier->applyTo($block);
  1626. return $block;
  1627. }
  1628. if (mb_eregi('^\-+$', $underLine)) {
  1629. $state->p = $p;
  1630. $block = new MDHeadingNode(2, $state->inlineMarkdownToNodes($contentLine));
  1631. if ($modifier) $modifier->applyTo($block);
  1632. return $block;
  1633. }
  1634. return null;
  1635. }
  1636. }
  1637. /**
  1638. * Reads markdown blocks for headings denoted with hash marks. Heading levels 1
  1639. * to 6 are supported.
  1640. *
  1641. * Supports `MDTagModifier` suffixes.
  1642. */
  1643. class MDHashHeadingReader extends MDReader {
  1644. private static $hashHeadingRegex = '^(#{1,6})\\s*([^#].*?)\\s*\\#*\\s*$'; // 1=hashes, 2=content
  1645. public function readBlock(MDState $state): ?MDBlockNode {
  1646. $p = $state->p;
  1647. $line = $state->lines[$p++];
  1648. $modifier;
  1649. [$line, $modifier] = MDTagModifier::fromLine($line, $state);
  1650. if (!mb_eregi(self::hashHeadingRegex, $line, $groups)) return null;
  1651. $state->p = $p;
  1652. $level = mb_strlen($groups[1]);
  1653. $content = $groups[2];
  1654. $block = new MDHeadingNode($level, $state->inlineMarkdownToNodes($content));
  1655. if ($modifier) $modifier->applyTo($block);
  1656. return $block;
  1657. }
  1658. }
  1659. /**
  1660. * Reads subtext blocks. Subtext is smaller, fainter text for things like
  1661. * disclaimers or sources.
  1662. *
  1663. * Supports `MDTagModifier` suffixes.
  1664. */
  1665. class MDSubtextReader extends MDReader {
  1666. private static $subtextRegex = '^\\-#\\s*(.*?)\\s*$'; // 1=content
  1667. public function readBlock(MDState $state): ?MDBlockNode {
  1668. $p = $state->p;
  1669. $line = $state->lines[$p++];
  1670. $modifier;
  1671. [$line, $modifier] = MDTagModifier::fromLine($line, $state);
  1672. if (!mb_eregi(self::subtextRegex, $line, $groups)) return null;
  1673. $state->p = $p;
  1674. $content = $groups[1];
  1675. $block = new MDSubtextNode($state->inlineMarkdownToNodes($content));
  1676. if ($modifier) $modifier->applyTo($block);
  1677. return $block;
  1678. }
  1679. public function compareBlockOrdering(MDReader $other): int {
  1680. if ($other instanceof MDUnorderedListReader) {
  1681. return -1;
  1682. }
  1683. return 0;
  1684. }
  1685. }
  1686. /**
  1687. * Reads markdown blocks for blockquoted text.
  1688. */
  1689. class MDBlockQuoteReader extends MDReader {
  1690. public function readBlock(MDState $state): ?MDBlockNode {
  1691. $blockquoteLines = [];
  1692. $p = $state->p;
  1693. while ($p < sizeof($state->lines)) {
  1694. $line = $state->lines[$p++];
  1695. if (str_starts_with($line, ">")) {
  1696. array_push($blockquoteLines, $line);
  1697. } else {
  1698. break;
  1699. }
  1700. }
  1701. if (sizeof($blockquoteLines) == 0) return null;
  1702. $contentLines = array_map(fn($line) => mb_eregi_replace('^ {0,3}\\t?', '', mb_substr($line, 1)), $blockquoteLines);
  1703. $substate = $state->copy($contentLines);
  1704. $quotedBlocks = $substate->readBlocks();
  1705. $state->p = $p;
  1706. return new MDBlockquoteNode($quotedBlocks);
  1707. }
  1708. }
  1709. /**
  1710. * Internal abstract base class for ordered and unordered lists.
  1711. */
  1712. class _MDListReader extends MDReader {
  1713. private static function readItemLines(MDState $state, int $firstLineStartPos): array {
  1714. $p = $state->p;
  1715. $lines = [];
  1716. $seenBlankLine = false;
  1717. $stripTrailingBlankLines = true;
  1718. while ($state->hasLines(1, $p)) {
  1719. $isFirstLine = ($p == $state->p);
  1720. $line = $state->lines[$p++];
  1721. if ($isFirstLine) {
  1722. $line = mb_substr($line, $firstLineStartPos);
  1723. }
  1724. if (mb_eregi('^(?:\\*|\\+|\\-|\\d+\\.)\\s+', $line)) {
  1725. // Found next list item
  1726. $stripTrailingBlankLines = false; // because this signals extra spacing intended
  1727. break;
  1728. }
  1729. $isBlankLine = trim($line) == '';
  1730. $isIndented = mb_eregi('^\\s+\\S', $line);
  1731. if ($isBlankLine) {
  1732. $seenBlankLine = true;
  1733. } elseif (!$isIndented && $seenBlankLine) {
  1734. // Post-list content
  1735. break;
  1736. }
  1737. array_push($lines, $line);
  1738. }
  1739. $lines = MDUtils::withoutTrailingBlankLines($lines);
  1740. return MDUtils::stripIndent($lines);
  1741. }
  1742. protected function readListItemContent(MDState $state, int $firstLineStartPos): MDBlockNode {
  1743. $itemLines = $this->readItemLines($state, $firstLineStartPos);
  1744. $state->p += max(sizeof($itemLines), 1);
  1745. if (sizeof($itemLines) == 1) {
  1746. return $state->inlineMarkdownToNode($itemLines[0]);
  1747. }
  1748. $hasBlankLines = sizeof(array_filter($itemLines, fn($line) => trim($line) == '')) > 0;
  1749. if ($hasBlankLines) {
  1750. $substate = $state->copy($itemLines);
  1751. $blocks = $substate->readBlocks();
  1752. return (sizeof($blocks) == 1) ? $blocks[0] : new MDNode($blocks);
  1753. }
  1754. // Multiline content with no blank lines. Search for new block
  1755. // boundaries without the benefit of a blank line to demarcate it.
  1756. for ($p = 1; $p < sizeof($itemLines); $p++) {
  1757. $line = $itemLines[p];
  1758. if (mb_eregi('^(?:\\*|\\-|\\+|\\d+\\.)\\s+', $line)) {
  1759. // Nested list found
  1760. $firstBlock = $state->inlineMarkdownToNode(implode("\n", array_slice($itemLines, 0, $p)));
  1761. $substate = $state->copy(array_slice($itemLines, $p));
  1762. $blocks = $substate->readBlocks();
  1763. return array_merge([ $firstBlock, $blocks ]);
  1764. }
  1765. }
  1766. // Ok, give up and just do a standard block read
  1767. {
  1768. $substate = $state->copy($itemLines);
  1769. $blocks = $substate->readBlocks();
  1770. return (sizeof($blocks) == 1) ? $blocks[0] : new MDNode($blocks);
  1771. }
  1772. }
  1773. public function readBlock(MDState $state): ?MDBlockNode {
  1774. throw new Error(`Abstract readBlock must be overridden in ${this.constructor.name}`);
  1775. }
  1776. }
  1777. /**
  1778. * Block reader for unordered (bulleted) lists.
  1779. */
  1780. class MDUnorderedListReader extends _MDListReader {
  1781. private static string $unorderedListRegex = '^([\\*\\+\\-]\\s+)(.*)$'; // 1=bullet, 2=content
  1782. private function readUnorderedListItem(MDState $state): ?MDListItemNode {
  1783. $p = $state->p;
  1784. $line = $state->lines[$p];
  1785. if (!mb_eregi(self::$unorderedListRegex, $line, $groups)) return null;
  1786. $firstLineOffset = mb_strlen($groups[1]);
  1787. return new MDListItemNode($this->readListItemContent($state, $firstLineOffset));
  1788. }
  1789. public function readBlock(MDState $state): ?MDBlockNode {
  1790. $items = [];
  1791. $item = null;
  1792. do {
  1793. $item = $this->readUnorderedListItem($state);
  1794. if ($item) array_push($items, $item);
  1795. } while ($item);
  1796. if (sizeof($items) == 0) return null;
  1797. return new MDUnorderedListNode($items);
  1798. }
  1799. }
  1800. /**
  1801. * Block reader for ordered (numbered) lists. The number of the first item is
  1802. * used to begin counting. The subsequent items increase by 1, regardless of
  1803. * their value.
  1804. */
  1805. class MDOrderedListReader extends _MDListReader {
  1806. private static string $orderedListRegex = '^(\\d+)(\\.\\s+)(.*)$'; // 1=number, 2=dot, 3=content
  1807. private function readOrderedListItem(MDState $state): ?MDListItemNode {
  1808. $p = $state->p;
  1809. $line = $state->lines[$p];
  1810. if (!mb_eregi(self::$orderedListRegex, $line, $groups)) return null;
  1811. $ordinal = intval($groups[1]);
  1812. $firstLineOffset = mb_strlen($groups[1]) + mb_strlen($groups[2]);
  1813. return new MDListItemNode($this->readListItemContent($state, $firstLineOffset), $ordinal);
  1814. }
  1815. public function readBlock(MDState $state): ?MDBlockNode {
  1816. $items = [];
  1817. $item = null;
  1818. do {
  1819. $item = $this->readOrderedListItem($state);
  1820. if ($item) array_push($items, $item);
  1821. } while ($item);
  1822. if (sizeof($items)) return null;
  1823. return new MDOrderedListNode($items, $items[0]->ordinal);
  1824. }
  1825. }
  1826. /**
  1827. * Block reader for code blocks denoted by pairs of triple tickmarks. If
  1828. * a programming language name, _xyz_, immediately follows the backticks, a
  1829. * `language-xyz` CSS class will be added to the resulting `<code>`
  1830. * element.
  1831. *
  1832. * Supports `MDTagModifier` suffix.
  1833. */
  1834. class MDFencedCodeBlockReader extends MDReader {
  1835. public function readBlock(MDState $state): ?MDBlockNode {
  1836. if (!$state->hasLines(2)) return null;
  1837. $p = $state->p;
  1838. $openFenceLine = $state->lines[$p++];
  1839. [$openFenceLine, $modifier] = MDTagModifier->fromLine($openFenceLine, $state);
  1840. if (!mb_eregi('```\s*([a-z0-9]*)\s*$', $openFenceLine, $groups)) return null;
  1841. $language = mb_strlen($groups[1]) > 0 ? $groups[1] : null;
  1842. $codeLines = [];
  1843. while ($state->hasLines(1, $p)) {
  1844. $line = $state->lines[$p++];
  1845. if (trim($line) == '```') {
  1846. $state->p = $p;
  1847. $block = new MDCodeBlockNode(implode("\n", $codeLines), $language);
  1848. if ($modifier) $modifier->applyTo($block);
  1849. return $block;
  1850. }
  1851. array_push($codeLines, $line);
  1852. }
  1853. return null;
  1854. }
  1855. }
  1856. /**
  1857. * Block reader for code blocks denoted by indenting text.
  1858. */
  1859. class MDIndentedCodeBlockReader extends MDReader {
  1860. public function readBlock(MDState $state): ?MDBlockNode {
  1861. $p = $state->p;
  1862. $codeLines = [];
  1863. while ($state->hasLines(1, $p)) {
  1864. $line = $state->lines[$p++];
  1865. if (MDUtils::countIndents($line, true) < 1) {
  1866. $p--;
  1867. break;
  1868. }
  1869. array_push($codeLines, MDUtils::stripIndent($line));
  1870. }
  1871. if (sizeof($codeLines) == 0) return null;
  1872. $state->p = $p;
  1873. return new MDCodeBlockNode(implode("\n", $codeLines));
  1874. }
  1875. }
  1876. /**
  1877. * Block reader for horizontal rules. Composed of three or more hypens or
  1878. * asterisks on a line by themselves, with or without intermediate whitespace.
  1879. */
  1880. class MDHorizontalRuleReader extends MDReader {
  1881. private static string $horizontalRuleRegex = '^\\s*(?:\\-(?:\\s*\\-){2,}|\\*(?:\\s*\\*){2,})\\s*$';
  1882. public function readBlock(MDState $state): ?MDBlockNode {
  1883. $p = $state->p;
  1884. $line = $state->lines[$p++];
  1885. [$line, $modifier] = MDTagModifier::fromLine($line, $state);
  1886. if (mb_eregi(self::horizontalRuleRegex, $line)) {
  1887. $state->p = $p;
  1888. $block = new MDHorizontalRuleNode();
  1889. if ($modifier) $modifier->applyTo($block);
  1890. return $block;
  1891. }
  1892. return null;
  1893. }
  1894. public function compareBlockOrdering(MDReader $other): int {
  1895. if ($other instanceof MDUnorderedListReader) {
  1896. return -1;
  1897. }
  1898. return 0;
  1899. }
  1900. }
  1901. /**
  1902. * Block reader for tables.
  1903. *
  1904. * Supports `MDTagModifier` suffix.
  1905. */
  1906. class MDTableReader extends MDReader {
  1907. private function readTableRow(MDState $state, bool $isHeader): ?MDTableRowNode {
  1908. if (!$state->hasLines(1)) return null;
  1909. $p = $state->p;
  1910. $line = MDTagModifier::strip(trim($state->lines[$p++]));
  1911. if (!mb_eregi('.*\\|.*', $line)) return null;
  1912. if (str_starts_with($line, '|')) $line = mb_substr($line, 1);
  1913. if (str_ends_with($line, '|')) $line = mb_substr($line, 0, mb_strlen($line) - 1);
  1914. $cellTokens = explode('|', $line);
  1915. $cells = array_map(function($token) use ($isHeader) {
  1916. $content = $state->inlineMarkdownToNode(trim($token));
  1917. return $isHeader ? new MDTableHeaderCellNode($content) : new MDTableCellNode($content);
  1918. }, $cellTokens);
  1919. $state->p = $p;
  1920. return new MDTableRowNode($cells);
  1921. }
  1922. /**
  1923. * @param string $line
  1924. * @return string[]
  1925. */
  1926. private function parseColumnAlignments(string $line): array {
  1927. $line = trim($line);
  1928. if (str_starts_with($line, '|')) $line = mb_substr($line, 1);
  1929. if (str_ends_with($line, '|')) $line = mb_substr($line, 0, mb_strlen($line) - 1);
  1930. return array_map(function($token) {
  1931. if (str_starts_with($token, ':')) {
  1932. if (str_ends_with($token, ':')) {
  1933. return 'center';
  1934. }
  1935. return 'left';
  1936. } elseif (str_ends_with($token, ':')) {
  1937. return 'right';
  1938. }
  1939. return null;
  1940. }, mb_split('\\s*\\|\\s*', $line));
  1941. }
  1942. private static string $tableDividerRegex = '^\\s*[|]?\\s*(?:[:]?-+[:]?)(?:\\s*\\|\\s*[:]?-+[:]?)*\\s*[|]?\\s*$';
  1943. public function readBlock(MDState $state): ?MDBlockNode {
  1944. if (!$state->hasLines(2)) return null;
  1945. $startP = $state->p;
  1946. $firstLine = $state->lines[$startP];
  1947. $modifier = MDTagModifier::fromLine($firstLine, $state)[1];
  1948. $headerRow = $this->readTableRow($state, true);
  1949. if ($headerRow === null) {
  1950. $state->p = $startP;
  1951. return null;
  1952. }
  1953. $dividerLine = $state->lines[$state->p++];
  1954. if (!mb_eregi(self::$tableDividerRegex, $dividerLine, $dividerGroups)) {
  1955. $state->p = $startP;
  1956. return null;
  1957. }
  1958. $columnAlignments = $this->parseColumnAlignments($dividerLine);
  1959. $bodyRows = [];
  1960. while ($state->hasLines(1)) {
  1961. $row = $this->readTableRow($state, false);
  1962. if ($row === null) break;
  1963. array_push($bodyRows, $row);
  1964. }
  1965. $table = new MDTableNode($headerRow, $bodyRows);
  1966. $table->columnAlignments = $columnAlignments;
  1967. if ($modifier) $modifier->applyTo($table);
  1968. return $table;
  1969. }
  1970. }
  1971. /**
  1972. * Block reader for definition lists. Definitions go directly under terms starting
  1973. * with a colon.
  1974. */
  1975. class MDDefinitionListReader extends MDReader {
  1976. public function readBlock(MDState $state): ?MDBlockNode {
  1977. $p = $state->p;
  1978. $groups;
  1979. $termCount = 0;
  1980. $definitionCount = 0;
  1981. $defLines = [];
  1982. while ($state->hasLines(1, $p)) {
  1983. $line = $state->lines[$p++];
  1984. if (trim($line) === '') {
  1985. break;
  1986. }
  1987. if (mb_eregi('^\\s+', $line)) {
  1988. if (sizeof($defLines) == 0) return null;
  1989. $defLines[sizeof($defLines) - 1] .= "\n" . $line;
  1990. } elseif (mb_eregi('^:\\s+', $line)) {
  1991. array_push($defLines, $line);
  1992. $definitionCount++;
  1993. } else {
  1994. array_push($defLines, $line);
  1995. $termCount++;
  1996. }
  1997. }
  1998. if ($termCount == 0 || $definitionCount == 0) return null;
  1999. $blocks = array_map(function($line) {
  2000. if (mb_eregi('^:\\s+(.*?)$', $line)) {
  2001. return new MDDefinitionListDefinitionNode($state->inlineMarkdownToNodes($groups[1]));
  2002. } else {
  2003. return new MDDefinitionListTermNode($state->inlineMarkdownToNodes($line));
  2004. }
  2005. }, $defLines);
  2006. $state->p = $p;
  2007. return new MDDefinitionListNode($blocks);
  2008. }
  2009. }
  2010. /**
  2011. * Block reader for defining footnote contents. Footnotes can be defined anywhere
  2012. * in the document but will always be rendered at the end of a page or end of
  2013. * the document.
  2014. */
  2015. class MDFootnoteReader extends MDReader {
  2016. private static string $footnoteWithTitleRegex = '^\\[\\^([^\\s\\[\\]]+?)\\s+"(.*?)"\\]'; // 1=symbol, 2=title
  2017. private static string $footnoteRegex = '^\\[\\^([^\\s\\[\\]]+?)\\]'; // 1=symbol
  2018. /**
  2019. * @param MDState $state
  2020. * @param string $symbol
  2021. * @param MDNode[] $footnote
  2022. */
  2023. private function defineFootnote(MDState $state, string $symbol, array $footnote) {
  2024. $footnotes = $state->root()['footnotes'] ?? [];
  2025. $footnotes[$symbol] = $footnote;
  2026. $state->root()['footnotes'] = $footnotes;
  2027. }
  2028. private function registerUniqueInstance(MDState $state, string $symbol, int $unique) {
  2029. $footnoteInstances = $state->root()['footnoteInstances'];
  2030. $instances = $footnoteInstances[$symbol] ?? [];
  2031. array_push($instances, $unique);
  2032. $footnoteInstances[$symbol] = $instances;
  2033. }
  2034. private function idForFootnoteSymbol(MDState $state, string $symbol): int {
  2035. $footnoteIds = $state->root()['footnoteIds'];
  2036. $existing = $footnoteIds[$symbol];
  2037. if ($existing) return $existing;
  2038. $nextFootnoteId = $state->root()['nextFootnoteId'];
  2039. $id = $nextFootnoteId++;
  2040. $footnoteIds[$symbol] = $id;
  2041. $state->root()['nextFootnoteId'] = $nextFootnoteId;
  2042. return $id;
  2043. }
  2044. public function preProcess(MDState $state) {
  2045. $state->root()['footnoteInstances'] = [];
  2046. $state->root()['footnotes'] = [];
  2047. $state->root()['footnoteIds'] = [];
  2048. $state->root()['nextFootnoteId'] = 1;
  2049. }
  2050. public function readBlock(MDState $state): ?MDBlockNode {
  2051. $p = $state->p;
  2052. if (!mb_eregi('^\\s*\\[\\^\\s*([^\\]]+)\\s*\\]:\\s+(.*)\\s*$', $state->lines[$p++], $groups)) return null;
  2053. $symbol = $groups[1];
  2054. $def = $groups[2];
  2055. while ($state->hasLines(1, $p)) {
  2056. $line = $state->lines[$p++];
  2057. if (mb_eregi('^\\s+', $line)) {
  2058. $def += "\n" . $line;
  2059. } else {
  2060. $p--;
  2061. break;
  2062. }
  2063. }
  2064. $content = $state->inlineMarkdownToNodes($def);
  2065. $this->defineFootnote($state, $symbol, $content);
  2066. $state->p = $p;
  2067. return new MDNode(); // empty
  2068. }
  2069. public function readToken(MDState $state, string $line): ?MDToken {
  2070. $groups;
  2071. if (mb_eregi(self::$footnoteWithTitleRegex, $line, $groups)) {
  2072. return new MDToken($groups[0], MDTokenType::Footnote, $groups[1], $groups[2]);
  2073. }
  2074. if (mb_eregi(MDFootnoteReader::footnoteRegex, $line, $groups)) {
  2075. return new MDToken($groups[0], MDTokenType::Footnote, $groups[1]);
  2076. }
  2077. return null;
  2078. }
  2079. public function substituteTokens(MDState $state, int $pass, array $tokens): bool {
  2080. if ($match = MDToken::findFirstTokens($tokens, [ MDTokenType::Footnote ])) {
  2081. $symbol = $match->tokens[0]->content;
  2082. array_splice($tokens, $match->index, 1, new MDFootnoteNode($symbol));
  2083. return true;
  2084. }
  2085. return false;
  2086. }
  2087. /**
  2088. * @param {MDState} state
  2089. * @param {MDBlockNode[]} blocks
  2090. */
  2091. public function postProcess(MDState $state, array $blocks) {
  2092. $nextOccurrenceId = 1;
  2093. foreach ($blocks as $block) {
  2094. $block->visitChildren(function($node) use (&$nextOccurrenceId) {
  2095. if (!($node instanceof MDFootnoteNode)) return;
  2096. $node->footnoteId = $this->idForFootnoteSymbol($state, $node->symbol);
  2097. $node->occurrenceId = $nextOccurrenceId++;
  2098. $node->displaySymbol = strval($node->footnoteId);
  2099. $this->$registerUniqueInstance($state, $node->symbol, $node->occurrenceId);
  2100. });
  2101. }
  2102. if (sizeof($state->footnotes) == 0) return;
  2103. array_push($blocks, new MDFootnoteListNode());
  2104. }
  2105. public function compareBlockOrdering(MDReader $other): int {
  2106. if ($other instanceof MDLinkReader || $other instanceof MDImageReader) {
  2107. return -1;
  2108. }
  2109. return 0;
  2110. }
  2111. public function compareTokenizeOrdering(MDReader $other): int {
  2112. if ($other instanceof MDLinkReader || $other instanceof MDImageReader) {
  2113. return -1;
  2114. }
  2115. return 0;
  2116. }
  2117. public function compareSubstituteOrdering(MDReader $other, int $pass): int {
  2118. if ($other instanceof MDLinkReader || $other instanceof MDImageReader) {
  2119. return -1;
  2120. }
  2121. return 0;
  2122. }
  2123. }
  2124. /**
  2125. * Block reader for abbreviation definitions. Anywhere the abbreviation appears
  2126. * in plain text will have its definition available when hovering over it.
  2127. * Definitions can appear anywhere in the document. Their content should only
  2128. * contain simple text, not markdown.
  2129. */
  2130. class MDAbbreviationReader extends MDReader {
  2131. private function defineAbbreviation(MDState $state, string $abbreviation, string $definition) {
  2132. $state->root()->abbreviations[$abbreviation] = $definition;
  2133. $regex = "\\b(" . preg_quote($abbreviation) . ")\\b";
  2134. $state->root()->abbreviationRegexes[$abbreviation] = $regex;
  2135. }
  2136. public function preProcess(MDState $state) {
  2137. $state->root()['abbreviations'] = [];
  2138. $state->root()['abbreviationRegexes'] = [];
  2139. }
  2140. public function readBlock(MDState $state): ?MDBlockNode {
  2141. $p = $state->p;
  2142. $line = $state->lines[$p++];
  2143. if (!mb_eregi('^\\s*\\*\\[([^\\]]+?)\\]:\\s+(.*?)\\s*$', $line, $groups)) return null;
  2144. $abbrev = $groups[1];
  2145. $def = $groups[2];
  2146. $this->defineAbbreviation($state, $abbrev, $def);
  2147. $state->p = $p;
  2148. return new MDNode(); // empty
  2149. }
  2150. /**
  2151. * @param MDState $state
  2152. * @param MDNode[] $blocks
  2153. */
  2154. public function postProcess(MDState $state, array $blocks) {
  2155. $abbreviations = $state->root()['abbreviations'];
  2156. $regexes = $state->root()['abbreviationRegexes'];
  2157. MDNode::replaceNodes($state, $blocks, function($original) {
  2158. if (!($original instanceof MDTextNode)) return null;
  2159. $changed = false;
  2160. $elems = [ $original->text ]; // mix of strings and MDNodes
  2161. for ($i = 0; $i < sizeof($elems); $i++) {
  2162. $text = $elems[i];
  2163. if (!is_string($text)) continue;
  2164. foreach ($abbreviations as $abbreviation) {
  2165. $index = strpos($text, $abbreviation);
  2166. if ($index === false) break;
  2167. $prefix = substr($text, 0, $index);
  2168. $suffix = substr($text, $index + strlen($abbreviation));
  2169. $definition = $abbreviations[$abbreviation];
  2170. array_splice($elems, $i, 1, [ $prefix, new MDAbbreviationNode($abbreviation, $definition), $suffix ]);
  2171. $i = -1; // start over
  2172. $changed = true;
  2173. break;
  2174. }
  2175. }
  2176. if (!$changed) return null;
  2177. $nodes = array_map(fn($elem) => is_string($elem) ? new MDTextNode($elem) : $elem);
  2178. return new MDNode($nodes);
  2179. });
  2180. }
  2181. }
  2182. /**
  2183. * Block reader for simple paragraphs. Paragraphs are separated by a blank (or
  2184. * whitespace-only) line. This reader is prioritized after every other reader
  2185. * since there is no distinguishing syntax.
  2186. */
  2187. class MDParagraphReader extends MDReader {
  2188. public function readBlock(MDState $state): ?MDBlockNode {
  2189. $paragraphLines = [];
  2190. $p = $state->p;
  2191. while ($state->hasLines(1, $p)) {
  2192. $line = $state->lines[$p++];
  2193. if (trim($line) === '') {
  2194. break;
  2195. }
  2196. array_push($paragraphLines, $line);
  2197. }
  2198. if ($state->p == 0 && $p >= sizeof($state->lines)) {
  2199. // If it's the entire document don't wrap it in a paragraph
  2200. return null;
  2201. }
  2202. if (sizeof($paragraphLines) > 0) {
  2203. $state->p = $p;
  2204. $content = implode("\n", $paragraphLines);
  2205. return new MDParagraphNode($state->inlineMarkdownToNodes($content));
  2206. }
  2207. return null;
  2208. }
  2209. public function compareBlockOrdering(MDReader $other): int {
  2210. return 1; // always dead last
  2211. }
  2212. }
  2213. class MDSimplePairInlineReader extends MDReader {}
  2214. class MDEmphasisReader extends MDSimplePairInlineReader {}
  2215. class MDStrongReader extends MDSimplePairInlineReader {}
  2216. class MDStrikethroughReader extends MDSimplePairInlineReader {}
  2217. class MDUnderlineReader extends MDSimplePairInlineReader {}
  2218. class MDHighlightReader extends MDSimplePairInlineReader {}
  2219. class MDCodeSpanReader extends MDSimplePairInlineReader {}
  2220. class MDSubscriptReader extends MDSimplePairInlineReader {}
  2221. class MDSuperscriptReader extends MDSimplePairInlineReader {}
  2222. class MDLinkReader extends MDReader {}
  2223. class MDReferencedLinkReader extends MDLinkReader {}
  2224. class MDImageReader extends MDLinkReader {}
  2225. class MDReferencedImageReader extends MDReferencedLinkReader {}
  2226. class MDLineBreakReader extends MDReader {}
  2227. class MDHTMLTagReader extends MDReader {}
  2228. class MDModifierReader extends MDReader {}
  2229. // -- Nodes -----------------------------------------------------------------
  2230. class MDNode {}
  2231. class MDBlockNode extends MDNode {}
  2232. class MDParagraphNode extends MDBlockNode {}
  2233. class MDHeadingNode extends MDBlockNode {}
  2234. class MDSubtextNode extends MDBlockNode {}
  2235. class MDHorizontalRuleNode extends MDBlockNode {}
  2236. class MDBlockquoteNode extends MDBlockNode {}
  2237. class MDUnorderedListNode extends MDBlockNode {}
  2238. class MDOrderedListNode extends MDBlockNode {}
  2239. class MDListItemNode extends MDBlockNode {}
  2240. class MDCodeBlockNode extends MDBlockNode {}
  2241. class MDTableNode extends MDBlockNode {}
  2242. class MDTableRowNode extends MDBlockNode {}
  2243. class MDTableCellNode extends MDBlockNode {}
  2244. class MDTableHeaderCellNode extends MDBlockNode {}
  2245. class MDDefinitionListNode extends MDBlockNode {}
  2246. class MDDefinitionListTermNode extends MDBlockNode {}
  2247. class MDDefinitionListDefinitionNode extends MDBlockNode {}
  2248. class MDFootnoteListNode extends MDBlockNode {}
  2249. class MDInlineNode extends MDNode {}
  2250. class MDTextNode extends MDInlineNode {}
  2251. class MDObfuscatedTextNode extends MDTextNode {}
  2252. class MDEmphasisNode extends MDInlineNode {}
  2253. class MDStrongNode extends MDInlineNode {}
  2254. class MDStrikethroughNode extends MDInlineNode {}
  2255. class MDUnderlineNode extends MDInlineNode {}
  2256. class MDHighlightNode extends MDInlineNode {}
  2257. class MDSuperscriptNode extends MDInlineNode {}
  2258. class MDSubscriptNode extends MDInlineNode {}
  2259. class MDCodeNode extends MDInlineNode {}
  2260. class MDFootnoteNode extends MDInlineNode {}
  2261. class MDLinkNode extends MDInlineNode {}
  2262. class MDReferencedLinkNode extends MDLinkNode {}
  2263. class MDImageNode extends MDInlineNode {}
  2264. class MDReferencedImageNode extends MDImageNode {}
  2265. class MDAbbreviationNode extends MDInlineNode {}
  2266. class MDLineBreakNode extends MDInlineNode {}
  2267. class MDHTMLTagNode extends MDInlineNode {}
  2268. // -- Main class ------------------------------------------------------------
  2269. class Markdown {}
  2270. ?>