HyperDown.php 49 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847
  1. <?php
  2. namespace Utils;
  3. /**
  4. * Parser
  5. *
  6. * @copyright Copyright (c) 2012 SegmentFault Team. (http://segmentfault.com)
  7. * @author Joyqi <joyqi@segmentfault.com>
  8. * @license BSD License
  9. */
  10. class HyperDown
  11. {
  12. /**
  13. * _whiteList
  14. *
  15. * @var string
  16. */
  17. private $_commonWhiteList = 'kbd|b|i|strong|em|sup|sub|br|code|del|a|hr|small';
  18. /**
  19. * html tags
  20. *
  21. * @var string
  22. */
  23. private $_blockHtmlTags = 'p|div|h[1-6]|blockquote|pre|table|dl|ol|ul|address|form|fieldset|iframe|hr|legend|article|section|nav|aside|hgroup|header|footer|figcaption|svg|script|noscript';
  24. /**
  25. * _specialWhiteList
  26. *
  27. * @var mixed
  28. * @access private
  29. */
  30. private $_specialWhiteList = [
  31. 'table' => 'table|tbody|thead|tfoot|tr|td|th'
  32. ];
  33. /**
  34. * _footnotes
  35. *
  36. * @var array
  37. */
  38. private $_footnotes;
  39. /**
  40. * @var bool
  41. */
  42. private $_html = false;
  43. /**
  44. * @var bool
  45. */
  46. private $_line = false;
  47. /**
  48. * @var array
  49. */
  50. private $blockParsers = [
  51. ['code', 10],
  52. ['shtml', 20],
  53. ['pre', 30],
  54. ['ahtml', 40],
  55. ['shr', 50],
  56. ['list', 60],
  57. ['math', 70],
  58. ['html', 80],
  59. ['footnote', 90],
  60. ['definition', 100],
  61. ['quote', 110],
  62. ['table', 120],
  63. ['sh', 130],
  64. ['mh', 140],
  65. ['dhr', 150],
  66. ['default', 9999]
  67. ];
  68. /**
  69. * _blocks
  70. *
  71. * @var array
  72. */
  73. private $_blocks;
  74. /**
  75. * _current
  76. *
  77. * @var string
  78. */
  79. private $_current;
  80. /**
  81. * _pos
  82. *
  83. * @var int
  84. */
  85. private $_pos;
  86. /**
  87. * _definitions
  88. *
  89. * @var array
  90. */
  91. private $_definitions;
  92. /**
  93. * @var array
  94. */
  95. private $_hooks = [];
  96. /**
  97. * @var array
  98. */
  99. private $_holders;
  100. /**
  101. * @var string
  102. */
  103. private $_uniqid;
  104. /**
  105. * @var int
  106. */
  107. private $_id;
  108. /**
  109. * @var array
  110. */
  111. private $_parsers = [];
  112. /**
  113. * makeHtml
  114. *
  115. * @param mixed $text
  116. *
  117. * @return string
  118. */
  119. public function makeHtml($text): string
  120. {
  121. $this->_footnotes = [];
  122. $this->_definitions = [];
  123. $this->_holders = [];
  124. $this->_uniqid = md5(uniqid());
  125. $this->_id = 0;
  126. usort($this->blockParsers, function ($a, $b) {
  127. return $a[1] < $b[1] ? - 1 : 1;
  128. });
  129. foreach ($this->blockParsers as $parser) {
  130. [$name] = $parser;
  131. if (isset($parser[2])) {
  132. $this->_parsers[$name] = $parser[2];
  133. } else {
  134. $this->_parsers[$name] = [$this, 'parseBlock' . ucfirst($name)];
  135. }
  136. }
  137. $text = $this->initText($text);
  138. $html = $this->parse($text);
  139. $html = $this->makeFootnotes($html);
  140. $html = $this->optimizeLines($html);
  141. return $this->call('makeHtml', $html);
  142. }
  143. /**
  144. * @param bool $html
  145. */
  146. public function enableHtml(bool $html = true)
  147. {
  148. $this->_html = $html;
  149. }
  150. /**
  151. * @param bool $line
  152. */
  153. public function enableLine(bool $line = true)
  154. {
  155. $this->_line = $line;
  156. }
  157. /**
  158. * @param string $type
  159. * @param callable $callback
  160. */
  161. public function hook(string $type, callable $callback)
  162. {
  163. $this->_hooks[$type][] = $callback;
  164. }
  165. /**
  166. * @param string $str
  167. *
  168. * @return string
  169. */
  170. public function makeHolder(string $str): string
  171. {
  172. $key = "\r" . $this->_uniqid . $this->_id . "\r";
  173. $this->_id ++;
  174. $this->_holders[$key] = $str;
  175. return $key;
  176. }
  177. /**
  178. * @param string $text
  179. *
  180. * @return string
  181. */
  182. private function initText(string $text): string
  183. {
  184. $text = str_replace(["\t", "\r"], [' ', ''], $text);
  185. return $text;
  186. }
  187. /**
  188. * @param string $html
  189. *
  190. * @return string
  191. */
  192. private function makeFootnotes(string $html): string
  193. {
  194. if (count($this->_footnotes) > 0) {
  195. $html .= '<div class="footnotes"><hr><ol>';
  196. $index = 1;
  197. while ($val = array_shift($this->_footnotes)) {
  198. if (is_string($val)) {
  199. $val .= " <a href=\"#fnref-{$index}\" class=\"footnote-backref\">&#8617;</a>";
  200. } else {
  201. $val[count($val) - 1] .= " <a href=\"#fnref-{$index}\" class=\"footnote-backref\">&#8617;</a>";
  202. $val = count($val) > 1 ? $this->parse(implode("\n", $val)) : $this->parseInline($val[0]);
  203. }
  204. $html .= "<li id=\"fn-{$index}\">{$val}</li>";
  205. $index ++;
  206. }
  207. $html .= '</ol></div>';
  208. }
  209. return $html;
  210. }
  211. /**
  212. * parse
  213. *
  214. * @param string $text
  215. * @param bool $inline
  216. * @param int $offset
  217. *
  218. * @return string
  219. */
  220. private function parse(string $text, bool $inline = false, int $offset = 0): string
  221. {
  222. $blocks = $this->parseBlock($text, $lines);
  223. $html = '';
  224. // inline mode for single normal block
  225. if ($inline && count($blocks) == 1 && $blocks[0][0] == 'normal') {
  226. $blocks[0][3] = true;
  227. }
  228. foreach ($blocks as $block) {
  229. [$type, $start, $end, $value] = $block;
  230. $extract = array_slice($lines, $start, $end - $start + 1);
  231. $method = 'parse' . ucfirst($type);
  232. $extract = $this->call('before' . ucfirst($method), $extract, $value);
  233. $result = $this->{$method}($extract, $value, $start + $offset, $end + $offset);
  234. $result = $this->call('after' . ucfirst($method), $result, $value);
  235. $html .= $result;
  236. }
  237. return $html;
  238. }
  239. /**
  240. * @param string $text
  241. * @param bool $clearHolders
  242. *
  243. * @return string
  244. */
  245. private function releaseHolder(string $text, bool $clearHolders = true): string
  246. {
  247. $deep = 0;
  248. while (strpos($text, "\r") !== false && $deep < 10) {
  249. $text = str_replace(array_keys($this->_holders), array_values($this->_holders), $text);
  250. $deep ++;
  251. }
  252. if ($clearHolders) {
  253. $this->_holders = [];
  254. }
  255. return $text;
  256. }
  257. /**
  258. * @param int $start
  259. * @param int $end
  260. *
  261. * @return string
  262. */
  263. private function markLine(int $start, int $end = - 1): string
  264. {
  265. if ($this->_line) {
  266. $end = $end < 0 ? $start : $end;
  267. return '<span class="line" data-start="' . $start
  268. . '" data-end="' . $end . '" data-id="' . $this->_uniqid . '"></span>';
  269. }
  270. return '';
  271. }
  272. /**
  273. * @param array $lines
  274. * @param int $start
  275. *
  276. * @return string[]
  277. */
  278. private function markLines(array $lines, int $start): array
  279. {
  280. $i = - 1;
  281. return $this->_line ? array_map(function ($line) use ($start, &$i) {
  282. $i ++;
  283. return $this->markLine($start + $i) . $line;
  284. }, $lines) : $lines;
  285. }
  286. /**
  287. * @param string $html
  288. *
  289. * @return string
  290. */
  291. private function optimizeLines(string $html): string
  292. {
  293. $last = 0;
  294. return $this->_line ?
  295. preg_replace_callback("/class=\"line\" data\-start=\"([0-9]+)\" data\-end=\"([0-9]+)\" (data\-id=\"{$this->_uniqid}\")/",
  296. function ($matches) use (&$last) {
  297. if ($matches[1] != $last) {
  298. $replace = 'class="line" data-start="' . $last . '" data-start-original="' . $matches[1] . '" data-end="' . $matches[2] . '" ' . $matches[3];
  299. } else {
  300. $replace = $matches[0];
  301. }
  302. $last = $matches[2] + 1;
  303. return $replace;
  304. }, $html) : $html;
  305. }
  306. /**
  307. * @param string $type
  308. * @param ...$args
  309. *
  310. * @return mixed
  311. */
  312. private function call(string $type, ...$args)
  313. {
  314. $value = $args[0];
  315. if (empty($this->_hooks[$type])) {
  316. return $value;
  317. }
  318. foreach ($this->_hooks[$type] as $callback) {
  319. $value = call_user_func_array($callback, $args);
  320. $args[0] = $value;
  321. }
  322. return $value;
  323. }
  324. /**
  325. * parseInline
  326. *
  327. * @param string $text
  328. * @param string $whiteList
  329. * @param bool $clearHolders
  330. * @param bool $enableAutoLink
  331. *
  332. * @return string
  333. */
  334. private function parseInline(
  335. string $text,
  336. string $whiteList = '',
  337. bool $clearHolders = true,
  338. bool $enableAutoLink = true
  339. ): string {
  340. $text = $this->call('beforeParseInline', $text);
  341. // code
  342. $text = preg_replace_callback(
  343. "/(^|[^\\\])(`+)(.+?)\\2/",
  344. function ($matches) {
  345. return $matches[1] . $this->makeHolder(
  346. '<code>' . htmlspecialchars($matches[3]) . '</code>'
  347. );
  348. },
  349. $text
  350. );
  351. // mathjax
  352. $text = preg_replace_callback(
  353. "/(^|[^\\\])(\\$+)(.+?)\\2/",
  354. function ($matches) {
  355. return $matches[1] . $this->makeHolder(
  356. $matches[2] . htmlspecialchars($matches[3]) . $matches[2]
  357. );
  358. },
  359. $text
  360. );
  361. // escape
  362. $text = preg_replace_callback(
  363. "/\\\(.)/u",
  364. function ($matches) {
  365. $prefix = preg_match("/^[-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]$/", $matches[1]) ? '' : '\\';
  366. $escaped = htmlspecialchars($matches[1]);
  367. $escaped = str_replace('$', '&dollar;', $escaped);
  368. return $this->makeHolder($prefix . $escaped);
  369. },
  370. $text
  371. );
  372. // link
  373. $text = preg_replace_callback(
  374. "/<(https?:\/\/.+|(?:mailto:)?[_a-z0-9-\.\+]+@[_\w-]+(?:\.[a-z]{2,})+)>/i",
  375. function ($matches) {
  376. $url = $this->cleanUrl($matches[1]);
  377. $link = $this->call('parseLink', $url);
  378. return $this->makeHolder(
  379. "<a href=\"{$url}\">{$link}</a>"
  380. );
  381. },
  382. $text
  383. );
  384. // encode unsafe tags
  385. $text = preg_replace_callback(
  386. "/<(\/?)([a-z0-9-]+)(\s+[^>]*)?>/i",
  387. function ($matches) use ($whiteList) {
  388. if ($this->_html || false !== stripos(
  389. '|' . $this->_commonWhiteList . '|' . $whiteList . '|', '|' . $matches[2] . '|'
  390. )) {
  391. return $this->makeHolder($matches[0]);
  392. } else {
  393. return $this->makeHolder(htmlspecialchars($matches[0]));
  394. }
  395. },
  396. $text
  397. );
  398. if ($this->_html) {
  399. $text = preg_replace_callback("/<!\-\-(.*?)\-\->/", function ($matches) {
  400. return $this->makeHolder($matches[0]);
  401. }, $text);
  402. }
  403. $text = str_replace(['<', '>'], ['&lt;', '&gt;'], $text);
  404. // footnote
  405. $text = preg_replace_callback(
  406. "/\[\^((?:[^\]]|\\\\\]|\\\\\[)+?)\]/",
  407. function ($matches) {
  408. $id = array_search($matches[1], $this->_footnotes);
  409. if (false === $id) {
  410. $id = count($this->_footnotes) + 1;
  411. $this->_footnotes[$id] = $this->parseInline($matches[1], '', false);
  412. }
  413. return $this->makeHolder(
  414. "<sup id=\"fnref-{$id}\"><a href=\"#fn-{$id}\" class=\"footnote-ref\">{$id}</a></sup>"
  415. );
  416. },
  417. $text
  418. );
  419. // image
  420. $text = preg_replace_callback(
  421. "/!\[((?:[^\]]|\\\\\]|\\\\\[)*?)\]\(((?:[^\)]|\\\\\)|\\\\\()+?)\)/",
  422. function ($matches) {
  423. $escaped = htmlspecialchars($this->escapeBracket($matches[1]));
  424. $url = $this->escapeBracket($matches[2]);
  425. [$url, $title] = $this->cleanUrl($url, true);
  426. $title = empty($title) ? $escaped : " title=\"{$title}\"";
  427. return $this->makeHolder(
  428. "<img src=\"{$url}\" alt=\"{$title}\" title=\"{$title}\">"
  429. );
  430. },
  431. $text
  432. );
  433. $text = preg_replace_callback(
  434. "/!\[((?:[^\]]|\\\\\]|\\\\\[)*?)\]\[((?:[^\]]|\\\\\]|\\\\\[)+?)\]/",
  435. function ($matches) {
  436. $escaped = htmlspecialchars($this->escapeBracket($matches[1]));
  437. $result = isset($this->_definitions[$matches[2]]) ?
  438. "<img src=\"{$this->_definitions[$matches[2]]}\" alt=\"{$escaped}\" title=\"{$escaped}\">"
  439. : $escaped;
  440. return $this->makeHolder($result);
  441. },
  442. $text
  443. );
  444. // link
  445. $text = preg_replace_callback(
  446. "/\[((?:[^\]]|\\\\\]|\\\\\[)+?)\]\(((?:[^\)]|\\\\\)|\\\\\()+?)\)/",
  447. function ($matches) {
  448. $escaped = $this->parseInline(
  449. $this->escapeBracket($matches[1]), '', false, false
  450. );
  451. $url = $this->escapeBracket($matches[2]);
  452. [$url, $title] = $this->cleanUrl($url, true);
  453. $title = empty($title) ? '' : " title=\"{$title}\"";
  454. return $this->makeHolder("<a href=\"{$url}\"{$title}>{$escaped}</a>");
  455. },
  456. $text
  457. );
  458. $text = preg_replace_callback(
  459. "/\[((?:[^\]]|\\\\\]|\\\\\[)+?)\]\[((?:[^\]]|\\\\\]|\\\\\[)+?)\]/",
  460. function ($matches) {
  461. $escaped = $this->parseInline(
  462. $this->escapeBracket($matches[1]), '', false
  463. );
  464. $result = isset($this->_definitions[$matches[2]]) ?
  465. "<a href=\"{$this->_definitions[$matches[2]]}\">{$escaped}</a>"
  466. : $escaped;
  467. return $this->makeHolder($result);
  468. },
  469. $text
  470. );
  471. // strong and em and some fuck
  472. $text = $this->parseInlineCallback($text);
  473. $text = preg_replace(
  474. "/<([_a-z0-9-\.\+]+@[^@]+\.[a-z]{2,})>/i",
  475. "<a href=\"mailto:\\1\">\\1</a>",
  476. $text
  477. );
  478. // autolink url
  479. if ($enableAutoLink) {
  480. $text = preg_replace_callback(
  481. "/(^|[^\"])(https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\b([-a-zA-Z0-9@:%_\+.~#?&\/=]*)|(?:mailto:)?[_a-z0-9-\.\+]+@[_\w-]+(?:\.[a-z]{2,})+)($|[^\"])/",
  482. function ($matches) {
  483. $url = $this->cleanUrl($matches[2]);
  484. $link = $this->call('parseLink', $matches[2]);
  485. return "{$matches[1]}<a href=\"{$url}\">{$link}</a>{$matches[5]}";
  486. },
  487. $text
  488. );
  489. }
  490. $text = $this->call('afterParseInlineBeforeRelease', $text);
  491. $text = $this->releaseHolder($text, $clearHolders);
  492. $text = $this->call('afterParseInline', $text);
  493. return $text;
  494. }
  495. /**
  496. * @param string $text
  497. *
  498. * @return string
  499. */
  500. private function parseInlineCallback(string $text): string
  501. {
  502. $text = preg_replace_callback(
  503. "/(\*{3})(.+?)\\1/",
  504. function ($matches) {
  505. return '<strong><em>' .
  506. $this->parseInlineCallback($matches[2]) .
  507. '</em></strong>';
  508. },
  509. $text
  510. );
  511. $text = preg_replace_callback(
  512. "/(\*{2})(.+?)\\1/",
  513. function ($matches) {
  514. return '<strong>' .
  515. $this->parseInlineCallback($matches[2]) .
  516. '</strong>';
  517. },
  518. $text
  519. );
  520. $text = preg_replace_callback(
  521. "/(\*)(.+?)\\1/",
  522. function ($matches) {
  523. return '<em>' .
  524. $this->parseInlineCallback($matches[2]) .
  525. '</em>';
  526. },
  527. $text
  528. );
  529. $text = preg_replace_callback(
  530. "/(\s+|^)(_{3})(.+?)\\2(\s+|$)/",
  531. function ($matches) {
  532. return $matches[1] . '<strong><em>' .
  533. $this->parseInlineCallback($matches[3]) .
  534. '</em></strong>' . $matches[4];
  535. },
  536. $text
  537. );
  538. $text = preg_replace_callback(
  539. "/(\s+|^)(_{2})(.+?)\\2(\s+|$)/",
  540. function ($matches) {
  541. return $matches[1] . '<strong>' .
  542. $this->parseInlineCallback($matches[3]) .
  543. '</strong>' . $matches[4];
  544. },
  545. $text
  546. );
  547. $text = preg_replace_callback(
  548. "/(\s+|^)(_)(.+?)\\2(\s+|$)/",
  549. function ($matches) {
  550. return $matches[1] . '<em>' .
  551. $this->parseInlineCallback($matches[3]) .
  552. '</em>' . $matches[4];
  553. },
  554. $text
  555. );
  556. $text = preg_replace_callback(
  557. "/(~{2})(.+?)\\1/",
  558. function ($matches) {
  559. return '<del>' .
  560. $this->parseInlineCallback($matches[2]) .
  561. '</del>';
  562. },
  563. $text
  564. );
  565. return $text;
  566. }
  567. /**
  568. * parseBlock
  569. *
  570. * @param string $text
  571. * @param array|null $lines
  572. *
  573. * @return array
  574. */
  575. private function parseBlock(string $text, ?array &$lines): array
  576. {
  577. $lines = explode("\n", $text);
  578. $this->_blocks = [];
  579. $this->_current = 'normal';
  580. $this->_pos = - 1;
  581. $state = [
  582. 'special' => implode("|", array_keys($this->_specialWhiteList)),
  583. 'empty' => 0,
  584. 'html' => false
  585. ];
  586. // analyze by line
  587. foreach ($lines as $key => $line) {
  588. $block = $this->getBlock();
  589. $args = [$block, $key, $line, &$state, $lines];
  590. if ($this->_current != 'normal') {
  591. $pass = call_user_func_array($this->_parsers[$this->_current], $args);
  592. if (!$pass) {
  593. continue;
  594. }
  595. }
  596. foreach ($this->_parsers as $name => $parser) {
  597. if ($name != $this->_current) {
  598. $pass = call_user_func_array($parser, $args);
  599. if (!$pass) {
  600. break;
  601. }
  602. }
  603. }
  604. }
  605. return $this->optimizeBlocks($this->_blocks, $lines);
  606. }
  607. /**
  608. * @param array|null $block
  609. * @param int $key
  610. * @param string $line
  611. * @param array|null $state
  612. *
  613. * @return bool
  614. */
  615. private function parseBlockList(?array $block, int $key, string $line, ?array &$state): bool
  616. {
  617. if ($this->isBlock('list') && !preg_match("/^\s*\[((?:[^\]]|\\]|\\[)+?)\]:\s*(.+)$/", $line)) {
  618. if (preg_match("/^(\s*)(~{3,}|`{3,})([^`~]*)$/i", $line)) {
  619. // ignore code
  620. return true;
  621. } elseif ($state['empty'] <= 1
  622. && preg_match("/^(\s*)\S+/", $line, $matches)
  623. && strlen($matches[1]) >= ($block[3][0] + $state['empty'])) {
  624. $state['empty'] = 0;
  625. $this->setBlock($key);
  626. return false;
  627. } elseif (preg_match("/^(\s*)$/", $line) && $state['empty'] == 0) {
  628. $state['empty'] ++;
  629. $this->setBlock($key);
  630. return false;
  631. }
  632. }
  633. if (preg_match("/^(\s*)((?:[0-9]+\.)|\-|\+|\*)\s+/i", $line, $matches)) {
  634. $space = strlen($matches[1]);
  635. $tab = strlen($matches[0]) - $space;
  636. $state['empty'] = 0;
  637. $type = false !== strpos('+-*', $matches[2]) ? 'ul' : 'ol';
  638. // opened
  639. if ($this->isBlock('list')) {
  640. if ($space < $block[3][0] || ($space == $block[3][0] && $type != $block[3][1])) {
  641. $this->startBlock('list', $key, [$space, $type, $tab]);
  642. } else {
  643. $this->setBlock($key);
  644. }
  645. } else {
  646. $this->startBlock('list', $key, [$space, $type, $tab]);
  647. }
  648. return false;
  649. }
  650. return true;
  651. }
  652. /**
  653. * @param array|null $block
  654. * @param int $key
  655. * @param string $line
  656. * @param array|null $state
  657. *
  658. * @return bool
  659. */
  660. private function parseBlockCode(?array $block, int $key, string $line, ?array &$state): bool
  661. {
  662. if (preg_match("/^(\s*)(~{3,}|`{3,})([^`~]*)$/i", $line, $matches)) {
  663. if ($this->isBlock('code')) {
  664. if ($state['code'] != $matches[2]) {
  665. $this->setBlock($key);
  666. return false;
  667. }
  668. $isAfterList = $block[3][2];
  669. if ($isAfterList) {
  670. $state['empty'] = 0;
  671. $this->combineBlock()
  672. ->setBlock($key);
  673. } else {
  674. $this->setBlock($key)
  675. ->endBlock();
  676. }
  677. } else {
  678. $isAfterList = false;
  679. if ($this->isBlock('list')) {
  680. $space = $block[3][0];
  681. $isAfterList = strlen($matches[1]) >= $space + $state['empty'];
  682. }
  683. $state['code'] = $matches[2];
  684. $this->startBlock('code', $key, [
  685. $matches[1], $matches[3], $isAfterList
  686. ]);
  687. }
  688. return false;
  689. } elseif ($this->isBlock('code')) {
  690. $this->setBlock($key);
  691. return false;
  692. }
  693. return true;
  694. }
  695. /**
  696. * @param array|null $block
  697. * @param int $key
  698. * @param string $line
  699. * @param array|null $state
  700. *
  701. * @return bool
  702. */
  703. private function parseBlockShtml(?array $block, int $key, string $line, ?array &$state): bool
  704. {
  705. if ($this->_html) {
  706. if (preg_match("/^(\s*)!!!(\s*)$/", $line, $matches)) {
  707. if ($this->isBlock('shtml')) {
  708. $this->setBlock($key)->endBlock();
  709. } else {
  710. $this->startBlock('shtml', $key);
  711. }
  712. return false;
  713. } elseif ($this->isBlock('shtml')) {
  714. $this->setBlock($key);
  715. return false;
  716. }
  717. }
  718. return true;
  719. }
  720. /**
  721. * @param array|null $block
  722. * @param int $key
  723. * @param string $line
  724. * @param array|null $state
  725. *
  726. * @return bool
  727. */
  728. private function parseBlockAhtml(?array $block, int $key, string $line, ?array &$state): bool
  729. {
  730. if ($this->_html) {
  731. if (preg_match("/^\s*<({$this->_blockHtmlTags})(\s+[^>]*)?>/i", $line, $matches)) {
  732. if ($this->isBlock('ahtml')) {
  733. $this->setBlock($key);
  734. return false;
  735. } elseif (empty($matches[2]) || $matches[2] != '/') {
  736. $this->startBlock('ahtml', $key);
  737. preg_match_all("/<({$this->_blockHtmlTags})(\s+[^>]*)?>/i", $line, $allMatches);
  738. $lastMatch = $allMatches[1][count($allMatches[0]) - 1];
  739. if (strpos($line, "</{$lastMatch}>") !== false) {
  740. $this->endBlock();
  741. } else {
  742. $state['html'] = $lastMatch;
  743. }
  744. return false;
  745. }
  746. } elseif (!!$state['html'] && strpos($line, "</{$state['html']}>") !== false) {
  747. $this->setBlock($key)->endBlock();
  748. $state['html'] = false;
  749. return false;
  750. } elseif ($this->isBlock('ahtml')) {
  751. $this->setBlock($key);
  752. return false;
  753. } elseif (preg_match("/^\s*<!\-\-(.*?)\-\->\s*$/", $line, $matches)) {
  754. $this->startBlock('ahtml', $key)->endBlock();
  755. return false;
  756. }
  757. }
  758. return true;
  759. }
  760. /**
  761. * @param array|null $block
  762. * @param int $key
  763. * @param string $line
  764. *
  765. * @return bool
  766. */
  767. private function parseBlockMath(?array $block, int $key, string $line): bool
  768. {
  769. if (preg_match("/^(\s*)\\$\\$(\s*)$/", $line, $matches)) {
  770. if ($this->isBlock('math')) {
  771. $this->setBlock($key)->endBlock();
  772. } else {
  773. $this->startBlock('math', $key);
  774. }
  775. return false;
  776. } elseif ($this->isBlock('math')) {
  777. $this->setBlock($key);
  778. return false;
  779. }
  780. return true;
  781. }
  782. /**
  783. * @param array|null $block
  784. * @param int $key
  785. * @param string $line
  786. * @param array|null $state
  787. *
  788. * @return bool
  789. */
  790. private function parseBlockPre(?array $block, int $key, string $line, ?array &$state): bool
  791. {
  792. if (preg_match("/^ {4}/", $line)) {
  793. if ($this->isBlock('pre')) {
  794. $this->setBlock($key);
  795. } else {
  796. $this->startBlock('pre', $key);
  797. }
  798. return false;
  799. } elseif ($this->isBlock('pre') && preg_match("/^\s*$/", $line)) {
  800. $this->setBlock($key);
  801. return false;
  802. }
  803. return true;
  804. }
  805. /**
  806. * @param array|null $block
  807. * @param int $key
  808. * @param string $line
  809. * @param array|null $state
  810. *
  811. * @return bool
  812. */
  813. private function parseBlockHtml(?array $block, int $key, string $line, ?array &$state): bool
  814. {
  815. if (preg_match("/^\s*<({$state['special']})(\s+[^>]*)?>/i", $line, $matches)) {
  816. $tag = strtolower($matches[1]);
  817. if (!$this->isBlock('html', $tag) && !$this->isBlock('pre')) {
  818. $this->startBlock('html', $key, $tag);
  819. }
  820. return false;
  821. } elseif (preg_match("/<\/({$state['special']})>\s*$/i", $line, $matches)) {
  822. $tag = strtolower($matches[1]);
  823. if ($this->isBlock('html', $tag)) {
  824. $this->setBlock($key)
  825. ->endBlock();
  826. }
  827. return false;
  828. } elseif ($this->isBlock('html')) {
  829. $this->setBlock($key);
  830. return false;
  831. }
  832. return true;
  833. }
  834. /**
  835. * @param array|null $block
  836. * @param int $key
  837. * @param string $line
  838. *
  839. * @return bool
  840. */
  841. private function parseBlockFootnote(?array $block, int $key, string $line): bool
  842. {
  843. if (preg_match("/^\[\^((?:[^\]]|\\]|\\[)+?)\]:/", $line, $matches)) {
  844. $space = strlen($matches[0]) - 1;
  845. $this->startBlock('footnote', $key, [
  846. $space, $matches[1]
  847. ]);
  848. return false;
  849. }
  850. return true;
  851. }
  852. /**
  853. * @param array|null $block
  854. * @param int $key
  855. * @param string $line
  856. *
  857. * @return bool
  858. */
  859. private function parseBlockDefinition(?array $block, int $key, string $line): bool
  860. {
  861. if (preg_match("/^\s*\[((?:[^\]]|\\]|\\[)+?)\]:\s*(.+)$/", $line, $matches)) {
  862. $this->_definitions[$matches[1]] = $this->cleanUrl($matches[2]);
  863. $this->startBlock('definition', $key)
  864. ->endBlock();
  865. return false;
  866. }
  867. return true;
  868. }
  869. /**
  870. * @param array|null $block
  871. * @param int $key
  872. * @param string $line
  873. *
  874. * @return bool
  875. */
  876. private function parseBlockQuote(?array $block, int $key, string $line): bool
  877. {
  878. if (preg_match("/^(\s*)>/", $line, $matches)) {
  879. if ($this->isBlock('list') && strlen($matches[1]) > 0) {
  880. $this->setBlock($key);
  881. } elseif ($this->isBlock('quote')) {
  882. $this->setBlock($key);
  883. } else {
  884. $this->startBlock('quote', $key);
  885. }
  886. return false;
  887. }
  888. return true;
  889. }
  890. /**
  891. * @param array|null $block
  892. * @param int $key
  893. * @param string $line
  894. * @param array|null $state
  895. * @param array|null $lines
  896. *
  897. * @return bool
  898. */
  899. private function parseBlockTable(?array $block, int $key, string $line, ?array &$state, array $lines): bool
  900. {
  901. if (preg_match("/^((?:(?:(?:\||\+)(?:[ :]*\-+[ :]*)(?:\||\+))|(?:(?:[ :]*\-+[ :]*)(?:\||\+)(?:[ :]*\-+[ :]*))|(?:(?:[ :]*\-+[ :]*)(?:\||\+))|(?:(?:\||\+)(?:[ :]*\-+[ :]*)))+)$/", $line, $matches)) {
  902. if ($this->isBlock('table')) {
  903. $block[3][0][] = $block[3][2];
  904. $block[3][2] ++;
  905. $this->setBlock($key, $block[3]);
  906. } else {
  907. $head = 0;
  908. if (empty($block) ||
  909. $block[0] != 'normal' ||
  910. preg_match("/^\s*$/", $lines[$block[2]])) {
  911. $this->startBlock('table', $key);
  912. } else {
  913. $head = 1;
  914. $this->backBlock(1, 'table');
  915. }
  916. if ($matches[1][0] == '|') {
  917. $matches[1] = substr($matches[1], 1);
  918. if ($matches[1][strlen($matches[1]) - 1] == '|') {
  919. $matches[1] = substr($matches[1], 0, - 1);
  920. }
  921. }
  922. $rows = preg_split("/(\+|\|)/", $matches[1]);
  923. $aligns = [];
  924. foreach ($rows as $row) {
  925. $align = 'none';
  926. if (preg_match("/^\s*(:?)\-+(:?)\s*$/", $row, $matches)) {
  927. if (!empty($matches[1]) && !empty($matches[2])) {
  928. $align = 'center';
  929. } elseif (!empty($matches[1])) {
  930. $align = 'left';
  931. } elseif (!empty($matches[2])) {
  932. $align = 'right';
  933. }
  934. }
  935. $aligns[] = $align;
  936. }
  937. $this->setBlock($key, [[$head], $aligns, $head + 1]);
  938. }
  939. return false;
  940. }
  941. return true;
  942. }
  943. /**
  944. * @param array|null $block
  945. * @param int $key
  946. * @param string $line
  947. *
  948. * @return bool
  949. */
  950. private function parseBlockSh(?array $block, int $key, string $line): bool
  951. {
  952. if (preg_match("/^(#+)(.*)$/", $line, $matches)) {
  953. $num = min(strlen($matches[1]), 6);
  954. $this->startBlock('sh', $key, $num)
  955. ->endBlock();
  956. return false;
  957. }
  958. return true;
  959. }
  960. /**
  961. * @param array|null $block
  962. * @param int $key
  963. * @param string $line
  964. * @param array|null $state
  965. * @param array $lines
  966. *
  967. * @return bool
  968. */
  969. private function parseBlockMh(?array $block, int $key, string $line, ?array &$state, array $lines): bool
  970. {
  971. if (preg_match("/^\s*((=|-){2,})\s*$/", $line, $matches)
  972. && ($block && $block[0] == "normal" && !preg_match("/^\s*$/", $lines[$block[2]]))) { // check if last line isn't empty
  973. if ($this->isBlock('normal')) {
  974. $this->backBlock(1, 'mh', $matches[1][0] == '=' ? 1 : 2)
  975. ->setBlock($key)
  976. ->endBlock();
  977. } else {
  978. $this->startBlock('normal', $key);
  979. }
  980. return false;
  981. }
  982. return true;
  983. }
  984. /**
  985. * @param array|null $block
  986. * @param int $key
  987. * @param string $line
  988. *
  989. * @return bool
  990. */
  991. private function parseBlockShr(?array $block, int $key, string $line): bool
  992. {
  993. if (preg_match("/^(\* *){3,}\s*$/", $line)) {
  994. $this->startBlock('hr', $key)
  995. ->endBlock();
  996. return false;
  997. }
  998. return true;
  999. }
  1000. /**
  1001. * @param array|null $block
  1002. * @param int $key
  1003. * @param string $line
  1004. *
  1005. * @return bool
  1006. */
  1007. private function parseBlockDhr(?array $block, int $key, string $line): bool
  1008. {
  1009. if (preg_match("/^(- *){3,}\s*$/", $line)) {
  1010. $this->startBlock('hr', $key)
  1011. ->endBlock();
  1012. return false;
  1013. }
  1014. return true;
  1015. }
  1016. /**
  1017. * @param array|null $block
  1018. * @param int $key
  1019. * @param string $line
  1020. * @param array|null $state
  1021. *
  1022. * @return bool
  1023. */
  1024. private function parseBlockDefault(?array $block, int $key, string $line, ?array &$state): bool
  1025. {
  1026. if ($this->isBlock('footnote')) {
  1027. preg_match("/^(\s*)/", $line, $matches);
  1028. if (strlen($matches[1]) >= $block[3][0]) {
  1029. $this->setBlock($key);
  1030. } else {
  1031. $this->startBlock('normal', $key);
  1032. }
  1033. } elseif ($this->isBlock('table')) {
  1034. if (false !== strpos($line, '|')) {
  1035. $block[3][2] ++;
  1036. $this->setBlock($key, $block[3]);
  1037. } else {
  1038. $this->startBlock('normal', $key);
  1039. }
  1040. } elseif ($this->isBlock('quote')) {
  1041. if (!preg_match("/^(\s*)$/", $line)) { // empty line
  1042. $this->setBlock($key);
  1043. } else {
  1044. $this->startBlock('normal', $key);
  1045. }
  1046. } else {
  1047. if (empty($block) || $block[0] != 'normal') {
  1048. $this->startBlock('normal', $key);
  1049. } else {
  1050. $this->setBlock($key);
  1051. }
  1052. }
  1053. return true;
  1054. }
  1055. /**
  1056. * @param array $blocks
  1057. * @param array $lines
  1058. *
  1059. * @return array
  1060. */
  1061. private function optimizeBlocks(array $blocks, array $lines): array
  1062. {
  1063. $blocks = $this->call('beforeOptimizeBlocks', $blocks, $lines);
  1064. $key = 0;
  1065. while (isset($blocks[$key])) {
  1066. $moved = false;
  1067. $block = &$blocks[$key];
  1068. $prevBlock = $blocks[$key - 1] ?? null;
  1069. $nextBlock = $blocks[$key + 1] ?? null;
  1070. [$type, $from, $to] = $block;
  1071. if ('pre' == $type) {
  1072. $isEmpty = array_reduce(
  1073. array_slice($lines, $block[1], $block[2] - $block[1] + 1),
  1074. function ($result, $line) {
  1075. return preg_match("/^\s*$/", $line) && $result;
  1076. },
  1077. true
  1078. );
  1079. if ($isEmpty) {
  1080. $block[0] = $type = 'normal';
  1081. }
  1082. }
  1083. if ('normal' == $type) {
  1084. // combine two blocks
  1085. $types = ['list', 'quote'];
  1086. if ($from == $to && preg_match("/^\s*$/", $lines[$from])
  1087. && !empty($prevBlock) && !empty($nextBlock)) {
  1088. if ($prevBlock[0] == $nextBlock[0] && in_array($prevBlock[0], $types)
  1089. && ($prevBlock[0] != 'list'
  1090. || ($prevBlock[3][0] == $nextBlock[3][0] && $prevBlock[3][1] == $nextBlock[3][1]))) {
  1091. // combine 3 blocks
  1092. $blocks[$key - 1] = [
  1093. $prevBlock[0], $prevBlock[1], $nextBlock[2], $prevBlock[3] ?? null
  1094. ];
  1095. array_splice($blocks, $key, 2);
  1096. // do not move
  1097. $moved = true;
  1098. }
  1099. }
  1100. }
  1101. if (!$moved) {
  1102. $key ++;
  1103. }
  1104. }
  1105. return $this->call('afterOptimizeBlocks', $blocks, $lines);
  1106. }
  1107. /**
  1108. * parseCode
  1109. *
  1110. * @param array $lines
  1111. * @param array $parts
  1112. * @param int $start
  1113. *
  1114. * @return string
  1115. */
  1116. private function parseCode(array $lines, array $parts, int $start): string
  1117. {
  1118. [$blank, $lang] = $parts;
  1119. $lang = trim($lang);
  1120. $count = strlen($blank);
  1121. if (!preg_match("/^[_a-z0-9-\+\#\:\.]+$/i", $lang)) {
  1122. $lang = null;
  1123. } else {
  1124. $parts = explode(':', $lang);
  1125. if (count($parts) > 1) {
  1126. [$lang, $rel] = $parts;
  1127. $lang = trim($lang);
  1128. $rel = trim($rel);
  1129. }
  1130. }
  1131. $isEmpty = true;
  1132. $lines = array_map(function ($line) use ($count, &$isEmpty) {
  1133. $line = preg_replace("/^[ ]{{$count}}/", '', $line);
  1134. if ($isEmpty && !preg_match("/^\s*$/", $line)) {
  1135. $isEmpty = false;
  1136. }
  1137. return htmlspecialchars($line);
  1138. }, array_slice($lines, 1, - 1));
  1139. $str = implode("\n", $this->markLines($lines, $start + 1));
  1140. return $isEmpty ? '' :
  1141. '<pre><code' . (!empty($lang) ? " class=\"{$lang}\"" : '')
  1142. . (!empty($rel) ? " rel=\"{$rel}\"" : '') . '>'
  1143. . $str . '</code></pre>';
  1144. }
  1145. /**
  1146. * parsePre
  1147. *
  1148. * @param array $lines
  1149. * @param mixed $value
  1150. * @param int $start
  1151. *
  1152. * @return string
  1153. */
  1154. private function parsePre(array $lines, $value, int $start): string
  1155. {
  1156. foreach ($lines as &$line) {
  1157. $line = htmlspecialchars(substr($line, 4));
  1158. }
  1159. $str = implode("\n", $this->markLines($lines, $start));
  1160. return preg_match("/^\s*$/", $str) ? '' : '<pre><code>' . $str . '</code></pre>';
  1161. }
  1162. /**
  1163. * parseAhtml
  1164. *
  1165. * @param array $lines
  1166. * @param mixed $value
  1167. * @param int $start
  1168. *
  1169. * @return string
  1170. */
  1171. private function parseAhtml(array $lines, $value, int $start): string
  1172. {
  1173. return trim(implode("\n", $this->markLines($lines, $start)));
  1174. }
  1175. /**
  1176. * parseShtml
  1177. *
  1178. * @param array $lines
  1179. * @param mixed $value
  1180. * @param int $start
  1181. *
  1182. * @return string
  1183. */
  1184. private function parseShtml(array $lines, $value, int $start): string
  1185. {
  1186. return trim(implode("\n", $this->markLines(array_slice($lines, 1, - 1), $start + 1)));
  1187. }
  1188. /**
  1189. * parseMath
  1190. *
  1191. * @param array $lines
  1192. * @param mixed $value
  1193. * @param int $start
  1194. * @param int $end
  1195. *
  1196. * @return string
  1197. */
  1198. private function parseMath(array $lines, $value, int $start, int $end): string
  1199. {
  1200. return '<p>' . $this->markLine($start, $end) . htmlspecialchars(implode("\n", $lines)) . '</p>';
  1201. }
  1202. /**
  1203. * parseSh
  1204. *
  1205. * @param array $lines
  1206. * @param int $num
  1207. * @param int $start
  1208. * @param int $end
  1209. *
  1210. * @return string
  1211. */
  1212. private function parseSh(array $lines, int $num, int $start, int $end): string
  1213. {
  1214. $line = $this->markLine($start, $end) . $this->parseInline(trim($lines[0], '# '));
  1215. return preg_match("/^\s*$/", $line) ? '' : "<h{$num}>{$line}</h{$num}>";
  1216. }
  1217. /**
  1218. * parseMh
  1219. *
  1220. * @param array $lines
  1221. * @param int $num
  1222. * @param int $start
  1223. * @param int $end
  1224. *
  1225. * @return string
  1226. */
  1227. private function parseMh(array $lines, int $num, int $start, int $end): string
  1228. {
  1229. return $this->parseSh($lines, $num, $start, $end);
  1230. }
  1231. /**
  1232. * parseQuote
  1233. *
  1234. * @param array $lines
  1235. * @param mixed $value
  1236. * @param int $start
  1237. *
  1238. * @return string
  1239. */
  1240. private function parseQuote(array $lines, $value, int $start): string
  1241. {
  1242. foreach ($lines as &$line) {
  1243. $line = preg_replace("/^\s*> ?/", '', $line);
  1244. }
  1245. $str = implode("\n", $lines);
  1246. return preg_match("/^\s*$/", $str) ? '' : '<blockquote>' . $this->parse($str, true, $start) . '</blockquote>';
  1247. }
  1248. /**
  1249. * parseList
  1250. *
  1251. * @param array $lines
  1252. * @param mixed $value
  1253. * @param int $start
  1254. *
  1255. * @return string
  1256. */
  1257. private function parseList(array $lines, $value, int $start): string
  1258. {
  1259. $html = '';
  1260. [$space, $type, $tab] = $value;
  1261. $rows = [];
  1262. $suffix = '';
  1263. $last = 0;
  1264. foreach ($lines as $key => $line) {
  1265. if (preg_match("/^(\s{" . $space . "})((?:[0-9]+\.?)|\-|\+|\*)(\s+)(.*)$/i", $line, $matches)) {
  1266. if ($type == 'ol' && $key == 0) {
  1267. $olStart = intval($matches[2]);
  1268. if ($olStart != 1) {
  1269. $suffix = ' start="' . $olStart . '"';
  1270. }
  1271. }
  1272. $rows[] = [$matches[4]];
  1273. $last = count($rows) - 1;
  1274. } else {
  1275. $rows[$last][] = preg_replace("/^\s{" . ($tab + $space) . "}/", '', $line);
  1276. }
  1277. }
  1278. foreach ($rows as $row) {
  1279. $html .= "<li>" . $this->parse(implode("\n", $row), true, $start) . "</li>";
  1280. $start += count($row);
  1281. }
  1282. return "<{$type}{$suffix}>{$html}</{$type}>";
  1283. }
  1284. /**
  1285. * @param array $lines
  1286. * @param mixed $value
  1287. * @param int $start
  1288. *
  1289. * @return string
  1290. */
  1291. private function parseTable(array $lines, $value, int $start): string
  1292. {
  1293. [$ignores, $aligns] = $value;
  1294. $head = count($ignores) > 0 && array_sum($ignores) > 0;
  1295. $html = '<table>';
  1296. $body = $head ? null : true;
  1297. $output = false;
  1298. foreach ($lines as $key => $line) {
  1299. if (in_array($key, $ignores)) {
  1300. if ($head && $output) {
  1301. $head = false;
  1302. $body = true;
  1303. }
  1304. continue;
  1305. }
  1306. $line = trim($line);
  1307. $output = true;
  1308. if ($line[0] == '|') {
  1309. $line = substr($line, 1);
  1310. if ($line[strlen($line) - 1] == '|') {
  1311. $line = substr($line, 0, - 1);
  1312. }
  1313. }
  1314. $rows = array_map(function ($row) {
  1315. if (preg_match("/^\s*$/", $row)) {
  1316. return ' ';
  1317. } else {
  1318. return trim($row);
  1319. }
  1320. }, explode('|', $line));
  1321. $columns = [];
  1322. $last = - 1;
  1323. foreach ($rows as $row) {
  1324. if (strlen($row) > 0) {
  1325. $last ++;
  1326. $columns[$last] = [
  1327. isset($columns[$last]) ? $columns[$last][0] + 1 : 1, $row
  1328. ];
  1329. } elseif (isset($columns[$last])) {
  1330. $columns[$last][0] ++;
  1331. } else {
  1332. $columns[0] = [1, $row];
  1333. }
  1334. }
  1335. if ($head) {
  1336. $html .= '<thead>';
  1337. } elseif ($body) {
  1338. $html .= '<tbody>';
  1339. }
  1340. $html .= '<tr' . ($this->_line ? ' class="line" data-start="'
  1341. . ($start + $key) . '" data-end="' . ($start + $key)
  1342. . '" data-id="' . $this->_uniqid . '"' : '') . '>';
  1343. foreach ($columns as $key => $column) {
  1344. [$num, $text] = $column;
  1345. $tag = $head ? 'th' : 'td';
  1346. $html .= "<{$tag}";
  1347. if ($num > 1) {
  1348. $html .= " colspan=\"{$num}\"";
  1349. }
  1350. if (isset($aligns[$key]) && $aligns[$key] != 'none') {
  1351. $html .= " align=\"{$aligns[$key]}\"";
  1352. }
  1353. $html .= '>' . $this->parseInline($text) . "</{$tag}>";
  1354. }
  1355. $html .= '</tr>';
  1356. if ($head) {
  1357. $html .= '</thead>';
  1358. } elseif ($body) {
  1359. $body = false;
  1360. }
  1361. }
  1362. if ($body !== null) {
  1363. $html .= '</tbody>';
  1364. }
  1365. $html .= '</table>';
  1366. return $html;
  1367. }
  1368. /**
  1369. * parseHr
  1370. *
  1371. * @param array $lines
  1372. * @param mixed $value
  1373. * @param int $start
  1374. *
  1375. * @return string
  1376. */
  1377. private function parseHr(array $lines, $value, int $start): string
  1378. {
  1379. return $this->_line ? '<hr class="line" data-start="' . $start . '" data-end="' . $start . '">' : '<hr>';
  1380. }
  1381. /**
  1382. * parseNormal
  1383. *
  1384. * @param array $lines
  1385. * @param mixed $inline
  1386. * @param int $start
  1387. *
  1388. * @return string
  1389. */
  1390. private function parseNormal(array $lines, $inline, int $start): string
  1391. {
  1392. foreach ($lines as $key => &$line) {
  1393. $line = $this->parseInline($line);
  1394. if (!preg_match("/^\s*$/", $line)) {
  1395. $line = $this->markLine($start + $key) . $line;
  1396. }
  1397. }
  1398. $str = trim(implode("\n", $lines));
  1399. $str = preg_replace_callback("/(\n\s*){2,}/", function () use (&$inline) {
  1400. $inline = false;
  1401. return "</p><p>";
  1402. }, $str);
  1403. $str = preg_replace("/\n/", "<br>", $str);
  1404. return preg_match("/^\s*$/", $str) ? '' : ($inline ? $str : "<p>{$str}</p>");
  1405. }
  1406. /**
  1407. * parseFootnote
  1408. *
  1409. * @param array $lines
  1410. * @param array $value
  1411. *
  1412. * @return string
  1413. */
  1414. private function parseFootnote(array $lines, array $value): string
  1415. {
  1416. [$space, $note] = $value;
  1417. $index = array_search($note, $this->_footnotes);
  1418. if (false !== $index) {
  1419. $lines[0] = preg_replace("/^\[\^((?:[^\]]|\\]|\\[)+?)\]:/", '', $lines[0]);
  1420. $this->_footnotes[$index] = $lines;
  1421. }
  1422. return '';
  1423. }
  1424. /**
  1425. * parseDefine
  1426. *
  1427. * @return string
  1428. */
  1429. private function parseDefinition(): string
  1430. {
  1431. return '';
  1432. }
  1433. /**
  1434. * parseHtml
  1435. *
  1436. * @param array $lines
  1437. * @param string $type
  1438. * @param int $start
  1439. *
  1440. * @return string
  1441. */
  1442. private function parseHtml(array $lines, string $type, int $start): string
  1443. {
  1444. foreach ($lines as &$line) {
  1445. $line = $this->parseInline($line,
  1446. $this->_specialWhiteList[$type] ?? '');
  1447. }
  1448. return implode("\n", $this->markLines($lines, $start));
  1449. }
  1450. /**
  1451. * @param $url
  1452. * @param bool $parseTitle
  1453. *
  1454. * @return mixed
  1455. */
  1456. private function cleanUrl($url, bool $parseTitle = false)
  1457. {
  1458. $title = null;
  1459. $url = trim($url);
  1460. if ($parseTitle) {
  1461. $pos = strpos($url, ' ');
  1462. if ($pos !== false) {
  1463. $title = htmlspecialchars(trim(substr($url, $pos + 1), ' "\''));
  1464. $url = substr($url, 0, $pos);
  1465. }
  1466. }
  1467. $url = preg_replace("/[\"'<>\s]/", '', $url);
  1468. if (preg_match("/^(mailto:)?[_a-z0-9-\.\+]+@[_\w-]+(?:\.[a-z]{2,})+$/i", $url, $matches)) {
  1469. if (empty($matches[1])) {
  1470. $url = 'mailto:' . $url;
  1471. }
  1472. }
  1473. if (preg_match("/^\w+:/i", $url) && !preg_match("/^(https?|mailto):/i", $url)) {
  1474. return '#';
  1475. }
  1476. return $parseTitle ? [$url, $title] : $url;
  1477. }
  1478. /**
  1479. * @param $str
  1480. *
  1481. * @return string
  1482. */
  1483. private function escapeBracket($str): string
  1484. {
  1485. return str_replace(
  1486. ['\[', '\]', '\(', '\)'], ['[', ']', '(', ')'], $str
  1487. );
  1488. }
  1489. /**
  1490. * startBlock
  1491. *
  1492. * @param mixed $type
  1493. * @param mixed $start
  1494. * @param mixed $value
  1495. *
  1496. * @return $this
  1497. */
  1498. private function startBlock($type, $start, $value = null): HyperDown
  1499. {
  1500. $this->_pos ++;
  1501. $this->_current = $type;
  1502. $this->_blocks[$this->_pos] = [$type, $start, $start, $value];
  1503. return $this;
  1504. }
  1505. /**
  1506. * endBlock
  1507. *
  1508. * @return $this
  1509. */
  1510. private function endBlock(): HyperDown
  1511. {
  1512. $this->_current = 'normal';
  1513. return $this;
  1514. }
  1515. /**
  1516. * isBlock
  1517. *
  1518. * @param mixed $type
  1519. * @param mixed $value
  1520. *
  1521. * @return bool
  1522. */
  1523. private function isBlock($type, $value = null): bool
  1524. {
  1525. return $this->_current == $type
  1526. && (null === $value || $this->_blocks[$this->_pos][3] == $value);
  1527. }
  1528. /**
  1529. * getBlock
  1530. *
  1531. * @return array
  1532. */
  1533. private function getBlock(): ?array
  1534. {
  1535. return $this->_blocks[$this->_pos] ?? null;
  1536. }
  1537. /**
  1538. * setBlock
  1539. *
  1540. * @param mixed $to
  1541. * @param mixed $value
  1542. *
  1543. * @return $this
  1544. */
  1545. private function setBlock($to = null, $value = null): HyperDown
  1546. {
  1547. if (null !== $to) {
  1548. $this->_blocks[$this->_pos][2] = $to;
  1549. }
  1550. if (null !== $value) {
  1551. $this->_blocks[$this->_pos][3] = $value;
  1552. }
  1553. return $this;
  1554. }
  1555. /**
  1556. * backBlock
  1557. *
  1558. * @param mixed $step
  1559. * @param mixed $type
  1560. * @param mixed $value
  1561. *
  1562. * @return $this
  1563. */
  1564. private function backBlock($step, $type, $value = null): HyperDown
  1565. {
  1566. if ($this->_pos < 0) {
  1567. return $this->startBlock($type, 0, $value);
  1568. }
  1569. $last = $this->_blocks[$this->_pos][2];
  1570. $this->_blocks[$this->_pos][2] = $last - $step;
  1571. if ($this->_blocks[$this->_pos][1] <= $this->_blocks[$this->_pos][2]) {
  1572. $this->_pos ++;
  1573. }
  1574. $this->_current = $type;
  1575. $this->_blocks[$this->_pos] = [
  1576. $type, $last - $step + 1, $last, $value
  1577. ];
  1578. return $this;
  1579. }
  1580. /**
  1581. * @return $this
  1582. */
  1583. private function combineBlock(): HyperDown
  1584. {
  1585. if ($this->_pos < 1) {
  1586. return $this;
  1587. }
  1588. $prev = $this->_blocks[$this->_pos - 1];
  1589. $current = $this->_blocks[$this->_pos];
  1590. $prev[2] = $current[2];
  1591. $this->_blocks[$this->_pos - 1] = $prev;
  1592. $this->_current = $prev[0];
  1593. unset($this->_blocks[$this->_pos]);
  1594. $this->_pos --;
  1595. return $this;
  1596. }
  1597. }