ParsedownModern.php 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538
  1. <?php
  2. #
  3. #
  4. # Parsedown
  5. # http://parsedown.org
  6. #
  7. # (c) Emanuil Rusev
  8. # http://erusev.com
  9. #
  10. # For the full license information, view the LICENSE file that was distributed
  11. # with this source code.
  12. #
  13. #
  14. class Parsedown
  15. {
  16. # ~
  17. const version = '1.6.0';
  18. # ~
  19. function text($text)
  20. {
  21. # make sure no definitions are set
  22. $this->DefinitionData = array();
  23. # standardize line breaks
  24. $text = str_replace(array("\r\n", "\r"), "\n", $text);
  25. # remove surrounding line breaks
  26. $text = trim($text, "\n");
  27. # split text into lines
  28. $lines = explode("\n", $text);
  29. # iterate through lines to identify blocks
  30. $markup = $this->lines($lines);
  31. # trim line breaks
  32. $markup = trim($markup, "\n");
  33. return $markup;
  34. }
  35. #
  36. # Setters
  37. #
  38. function setBreaksEnabled($breaksEnabled)
  39. {
  40. $this->breaksEnabled = $breaksEnabled;
  41. return $this;
  42. }
  43. protected $breaksEnabled;
  44. function setMarkupEscaped($markupEscaped)
  45. {
  46. $this->markupEscaped = $markupEscaped;
  47. return $this;
  48. }
  49. protected $markupEscaped;
  50. function setUrlsLinked($urlsLinked)
  51. {
  52. $this->urlsLinked = $urlsLinked;
  53. return $this;
  54. }
  55. protected $urlsLinked = true;
  56. #
  57. # Lines
  58. #
  59. protected $BlockTypes = array(
  60. '#' => array('Header'),
  61. '*' => array('Rule', 'List'),
  62. '+' => array('List'),
  63. '-' => array('SetextHeader', 'Table', 'Rule', 'List'),
  64. '0' => array('List'),
  65. '1' => array('List'),
  66. '2' => array('List'),
  67. '3' => array('List'),
  68. '4' => array('List'),
  69. '5' => array('List'),
  70. '6' => array('List'),
  71. '7' => array('List'),
  72. '8' => array('List'),
  73. '9' => array('List'),
  74. ':' => array('Table'),
  75. '<' => array('Comment', 'Markup'),
  76. '=' => array('SetextHeader'),
  77. '>' => array('Quote'),
  78. '[' => array('Reference'),
  79. '_' => array('Rule'),
  80. '`' => array('FencedCode'),
  81. '|' => array('Table'),
  82. '~' => array('FencedCode'),
  83. );
  84. # ~
  85. protected $unmarkedBlockTypes = array(
  86. 'Code',
  87. );
  88. #
  89. # Blocks
  90. #
  91. protected function lines(array $lines)
  92. {
  93. $CurrentBlock = null;
  94. foreach ($lines as $line)
  95. {
  96. if (chop($line) === '')
  97. {
  98. if (isset($CurrentBlock))
  99. {
  100. $CurrentBlock['interrupted'] = true;
  101. }
  102. continue;
  103. }
  104. if (strpos($line, "\t") !== false)
  105. {
  106. $parts = explode("\t", $line);
  107. $line = $parts[0];
  108. unset($parts[0]);
  109. foreach ($parts as $part)
  110. {
  111. $shortage = 4 - mb_strlen($line, 'utf-8') % 4;
  112. $line .= str_repeat(' ', $shortage);
  113. $line .= $part;
  114. }
  115. }
  116. $indent = 0;
  117. while (isset($line[$indent]) and $line[$indent] === ' ')
  118. {
  119. $indent ++;
  120. }
  121. $text = $indent > 0 ? substr($line, $indent) : $line;
  122. # ~
  123. $Line = array('body' => $line, 'indent' => $indent, 'text' => $text);
  124. # ~
  125. if (isset($CurrentBlock['continuable']))
  126. {
  127. $Block = $this->{'block'.$CurrentBlock['type'].'Continue'}($Line, $CurrentBlock);
  128. if (isset($Block))
  129. {
  130. $CurrentBlock = $Block;
  131. continue;
  132. }
  133. else
  134. {
  135. if ($this->isBlockCompletable($CurrentBlock['type']))
  136. {
  137. $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock);
  138. }
  139. }
  140. }
  141. # ~
  142. $marker = $text[0];
  143. # ~
  144. $blockTypes = $this->unmarkedBlockTypes;
  145. if (isset($this->BlockTypes[$marker]))
  146. {
  147. foreach ($this->BlockTypes[$marker] as $blockType)
  148. {
  149. $blockTypes []= $blockType;
  150. }
  151. }
  152. #
  153. # ~
  154. foreach ($blockTypes as $blockType)
  155. {
  156. $Block = $this->{'block'.$blockType}($Line, $CurrentBlock);
  157. if (isset($Block))
  158. {
  159. $Block['type'] = $blockType;
  160. if ( ! isset($Block['identified']))
  161. {
  162. $Blocks []= $CurrentBlock;
  163. $Block['identified'] = true;
  164. }
  165. if ($this->isBlockContinuable($blockType))
  166. {
  167. $Block['continuable'] = true;
  168. }
  169. $CurrentBlock = $Block;
  170. continue 2;
  171. }
  172. }
  173. # ~
  174. if (isset($CurrentBlock) and ! isset($CurrentBlock['type']) and ! isset($CurrentBlock['interrupted']))
  175. {
  176. $CurrentBlock['element']['text'] .= "\n".$text;
  177. }
  178. else
  179. {
  180. $Blocks []= $CurrentBlock;
  181. $CurrentBlock = $this->paragraph($Line);
  182. $CurrentBlock['identified'] = true;
  183. }
  184. }
  185. # ~
  186. if (isset($CurrentBlock['continuable']) and $this->isBlockCompletable($CurrentBlock['type']))
  187. {
  188. $CurrentBlock = $this->{'block'.$CurrentBlock['type'].'Complete'}($CurrentBlock);
  189. }
  190. # ~
  191. $Blocks []= $CurrentBlock;
  192. unset($Blocks[0]);
  193. # ~
  194. $markup = '';
  195. foreach ($Blocks as $Block)
  196. {
  197. if (isset($Block['hidden']))
  198. {
  199. continue;
  200. }
  201. $markup .= "\n";
  202. $markup .= isset($Block['markup']) ? $Block['markup'] : $this->element($Block['element']);
  203. }
  204. $markup .= "\n";
  205. # ~
  206. return $markup;
  207. }
  208. protected function isBlockContinuable($Type)
  209. {
  210. return method_exists($this, 'block'.$Type.'Continue');
  211. }
  212. protected function isBlockCompletable($Type)
  213. {
  214. return method_exists($this, 'block'.$Type.'Complete');
  215. }
  216. #
  217. # Code
  218. protected function blockCode($Line, $Block = null)
  219. {
  220. if (isset($Block) and ! isset($Block['type']) and ! isset($Block['interrupted']))
  221. {
  222. return;
  223. }
  224. if ($Line['indent'] >= 4)
  225. {
  226. $text = substr($Line['body'], 4);
  227. $Block = array(
  228. 'element' => array(
  229. 'name' => 'pre',
  230. 'handler' => 'element',
  231. 'text' => array(
  232. 'name' => 'code',
  233. 'text' => $text,
  234. ),
  235. ),
  236. );
  237. return $Block;
  238. }
  239. }
  240. protected function blockCodeContinue($Line, $Block)
  241. {
  242. if ($Line['indent'] >= 4)
  243. {
  244. if (isset($Block['interrupted']))
  245. {
  246. $Block['element']['text']['text'] .= "\n";
  247. unset($Block['interrupted']);
  248. }
  249. $Block['element']['text']['text'] .= "\n";
  250. $text = substr($Line['body'], 4);
  251. $Block['element']['text']['text'] .= $text;
  252. return $Block;
  253. }
  254. }
  255. protected function blockCodeComplete($Block)
  256. {
  257. $text = $Block['element']['text']['text'];
  258. $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
  259. $Block['element']['text']['text'] = $text;
  260. return $Block;
  261. }
  262. #
  263. # Comment
  264. protected function blockComment($Line)
  265. {
  266. if ($this->markupEscaped)
  267. {
  268. return;
  269. }
  270. if (isset($Line['text'][3]) and $Line['text'][3] === '-' and $Line['text'][2] === '-' and $Line['text'][1] === '!')
  271. {
  272. $Block = array(
  273. 'markup' => $Line['body'],
  274. );
  275. if (preg_match('/-->$/', $Line['text']))
  276. {
  277. $Block['closed'] = true;
  278. }
  279. return $Block;
  280. }
  281. }
  282. protected function blockCommentContinue($Line, array $Block)
  283. {
  284. if (isset($Block['closed']))
  285. {
  286. return;
  287. }
  288. $Block['markup'] .= "\n" . $Line['body'];
  289. if (preg_match('/-->$/', $Line['text']))
  290. {
  291. $Block['closed'] = true;
  292. }
  293. return $Block;
  294. }
  295. #
  296. # Fenced Code
  297. protected function blockFencedCode($Line)
  298. {
  299. if (preg_match('/^['.$Line['text'][0].']{3,}[ ]*([\w-]+)?[ ]*$/', $Line['text'], $matches))
  300. {
  301. $Element = array(
  302. 'name' => 'code',
  303. 'text' => '',
  304. );
  305. if (isset($matches[1]))
  306. {
  307. $class = 'language-'.$matches[1];
  308. $Element['attributes'] = array(
  309. 'class' => $class,
  310. );
  311. }
  312. $Block = array(
  313. 'char' => $Line['text'][0],
  314. 'element' => array(
  315. 'name' => 'pre',
  316. 'handler' => 'element',
  317. 'text' => $Element,
  318. ),
  319. );
  320. return $Block;
  321. }
  322. }
  323. protected function blockFencedCodeContinue($Line, $Block)
  324. {
  325. if (isset($Block['complete']))
  326. {
  327. return;
  328. }
  329. if (isset($Block['interrupted']))
  330. {
  331. $Block['element']['text']['text'] .= "\n";
  332. unset($Block['interrupted']);
  333. }
  334. if (preg_match('/^'.$Block['char'].'{3,}[ ]*$/', $Line['text']))
  335. {
  336. $Block['element']['text']['text'] = substr($Block['element']['text']['text'], 1);
  337. $Block['complete'] = true;
  338. return $Block;
  339. }
  340. $Block['element']['text']['text'] .= "\n".$Line['body'];;
  341. return $Block;
  342. }
  343. protected function blockFencedCodeComplete($Block)
  344. {
  345. $text = $Block['element']['text']['text'];
  346. $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
  347. $Block['element']['text']['text'] = $text;
  348. return $Block;
  349. }
  350. #
  351. # Header
  352. protected function blockHeader($Line)
  353. {
  354. if (isset($Line['text'][1]))
  355. {
  356. $level = 1;
  357. while (isset($Line['text'][$level]) and $Line['text'][$level] === '#')
  358. {
  359. $level ++;
  360. }
  361. if ($level > 6)
  362. {
  363. return;
  364. }
  365. $text = trim($Line['text'], '# ');
  366. $Block = array(
  367. 'element' => array(
  368. 'name' => 'h' . min(6, $level),
  369. 'text' => $text,
  370. 'handler' => 'line',
  371. ),
  372. );
  373. return $Block;
  374. }
  375. }
  376. #
  377. # List
  378. protected function blockList($Line)
  379. {
  380. list($name, $pattern) = $Line['text'][0] <= '-' ? array('ul', '[*+-]') : array('ol', '[0-9]+[.]');
  381. if (preg_match('/^('.$pattern.'[ ]+)(.*)/', $Line['text'], $matches))
  382. {
  383. $Block = array(
  384. 'indent' => $Line['indent'],
  385. 'pattern' => $pattern,
  386. 'element' => array(
  387. 'name' => $name,
  388. 'handler' => 'elements',
  389. ),
  390. );
  391. $Block['li'] = array(
  392. 'name' => 'li',
  393. 'handler' => 'li',
  394. 'text' => array(
  395. $matches[2],
  396. ),
  397. );
  398. $Block['element']['text'] []= & $Block['li'];
  399. return $Block;
  400. }
  401. }
  402. protected function blockListContinue($Line, array $Block)
  403. {
  404. if ($Block['indent'] === $Line['indent'] and preg_match('/^'.$Block['pattern'].'(?:[ ]+(.*)|$)/', $Line['text'], $matches))
  405. {
  406. if (isset($Block['interrupted']))
  407. {
  408. $Block['li']['text'] []= '';
  409. unset($Block['interrupted']);
  410. }
  411. unset($Block['li']);
  412. $text = isset($matches[1]) ? $matches[1] : '';
  413. $Block['li'] = array(
  414. 'name' => 'li',
  415. 'handler' => 'li',
  416. 'text' => array(
  417. $text,
  418. ),
  419. );
  420. $Block['element']['text'] []= & $Block['li'];
  421. return $Block;
  422. }
  423. if ($Line['text'][0] === '[' and $this->blockReference($Line))
  424. {
  425. return $Block;
  426. }
  427. if ( ! isset($Block['interrupted']))
  428. {
  429. $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']);
  430. $Block['li']['text'] []= $text;
  431. return $Block;
  432. }
  433. if ($Line['indent'] > 0)
  434. {
  435. $Block['li']['text'] []= '';
  436. $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']);
  437. $Block['li']['text'] []= $text;
  438. unset($Block['interrupted']);
  439. return $Block;
  440. }
  441. }
  442. #
  443. # Quote
  444. protected function blockQuote($Line)
  445. {
  446. if (preg_match('/^>[ ]?(.*)/', $Line['text'], $matches))
  447. {
  448. $Block = array(
  449. 'element' => array(
  450. 'name' => 'blockquote',
  451. 'handler' => 'lines',
  452. 'text' => (array) $matches[1],
  453. ),
  454. );
  455. return $Block;
  456. }
  457. }
  458. protected function blockQuoteContinue($Line, array $Block)
  459. {
  460. if ($Line['text'][0] === '>' and preg_match('/^>[ ]?(.*)/', $Line['text'], $matches))
  461. {
  462. if (isset($Block['interrupted']))
  463. {
  464. $Block['element']['text'] []= '';
  465. unset($Block['interrupted']);
  466. }
  467. $Block['element']['text'] []= $matches[1];
  468. return $Block;
  469. }
  470. if ( ! isset($Block['interrupted']))
  471. {
  472. $Block['element']['text'] []= $Line['text'];
  473. return $Block;
  474. }
  475. }
  476. #
  477. # Rule
  478. protected function blockRule($Line)
  479. {
  480. if (preg_match('/^(['.$Line['text'][0].'])([ ]*\1){2,}[ ]*$/', $Line['text']))
  481. {
  482. $Block = array(
  483. 'element' => array(
  484. 'name' => 'hr'
  485. ),
  486. );
  487. return $Block;
  488. }
  489. }
  490. #
  491. # Setext
  492. protected function blockSetextHeader($Line, array $Block = null)
  493. {
  494. if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted']))
  495. {
  496. return;
  497. }
  498. if (chop($Line['text'], $Line['text'][0]) === '')
  499. {
  500. $Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2';
  501. return $Block;
  502. }
  503. }
  504. #
  505. # Markup
  506. protected function blockMarkup($Line)
  507. {
  508. if ($this->markupEscaped)
  509. {
  510. return;
  511. }
  512. if (preg_match('/^<(\w*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches))
  513. {
  514. $element = strtolower($matches[1]);
  515. if (in_array($element, $this->textLevelElements))
  516. {
  517. return;
  518. }
  519. $Block = array(
  520. 'name' => $matches[1],
  521. 'depth' => 0,
  522. 'markup' => $Line['text'],
  523. );
  524. $length = strlen($matches[0]);
  525. $remainder = substr($Line['text'], $length);
  526. if (trim($remainder) === '')
  527. {
  528. if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
  529. {
  530. $Block['closed'] = true;
  531. $Block['void'] = true;
  532. }
  533. }
  534. else
  535. {
  536. if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
  537. {
  538. return;
  539. }
  540. if (preg_match('/<\/'.$matches[1].'>[ ]*$/i', $remainder))
  541. {
  542. $Block['closed'] = true;
  543. }
  544. }
  545. return $Block;
  546. }
  547. }
  548. protected function blockMarkupContinue($Line, array $Block)
  549. {
  550. if (isset($Block['closed']))
  551. {
  552. return;
  553. }
  554. if (preg_match('/^<'.$Block['name'].'(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*>/i', $Line['text'])) # open
  555. {
  556. $Block['depth'] ++;
  557. }
  558. if (preg_match('/(.*?)<\/'.$Block['name'].'>[ ]*$/i', $Line['text'], $matches)) # close
  559. {
  560. if ($Block['depth'] > 0)
  561. {
  562. $Block['depth'] --;
  563. }
  564. else
  565. {
  566. $Block['closed'] = true;
  567. }
  568. }
  569. if (isset($Block['interrupted']))
  570. {
  571. $Block['markup'] .= "\n";
  572. unset($Block['interrupted']);
  573. }
  574. $Block['markup'] .= "\n".$Line['body'];
  575. return $Block;
  576. }
  577. #
  578. # Reference
  579. protected function blockReference($Line)
  580. {
  581. if (preg_match('/^\[(.+?)\]:[ ]*<?(\S+?)>?(?:[ ]+["\'(](.+)["\')])?[ ]*$/', $Line['text'], $matches))
  582. {
  583. $id = strtolower($matches[1]);
  584. $Data = array(
  585. 'url' => $matches[2],
  586. 'title' => null,
  587. );
  588. if (isset($matches[3]))
  589. {
  590. $Data['title'] = $matches[3];
  591. }
  592. $this->DefinitionData['Reference'][$id] = $Data;
  593. $Block = array(
  594. 'hidden' => true,
  595. );
  596. return $Block;
  597. }
  598. }
  599. #
  600. # Table
  601. protected function blockTable($Line, array $Block = null)
  602. {
  603. if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted']))
  604. {
  605. return;
  606. }
  607. if (strpos($Block['element']['text'], '|') !== false and chop($Line['text'], ' -:|') === '')
  608. {
  609. $alignments = array();
  610. $divider = $Line['text'];
  611. $divider = trim($divider);
  612. $divider = trim($divider, '|');
  613. $dividerCells = explode('|', $divider);
  614. foreach ($dividerCells as $dividerCell)
  615. {
  616. $dividerCell = trim($dividerCell);
  617. if ($dividerCell === '')
  618. {
  619. continue;
  620. }
  621. $alignment = null;
  622. if ($dividerCell[0] === ':')
  623. {
  624. $alignment = 'left';
  625. }
  626. if (substr($dividerCell, - 1) === ':')
  627. {
  628. $alignment = $alignment === 'left' ? 'center' : 'right';
  629. }
  630. $alignments []= $alignment;
  631. }
  632. # ~
  633. $HeaderElements = array();
  634. $header = $Block['element']['text'];
  635. $header = trim($header);
  636. $header = trim($header, '|');
  637. $headerCells = explode('|', $header);
  638. foreach ($headerCells as $index => $headerCell)
  639. {
  640. $headerCell = trim($headerCell);
  641. $HeaderElement = array(
  642. 'name' => 'th',
  643. 'text' => $headerCell,
  644. 'handler' => 'line',
  645. );
  646. if (isset($alignments[$index]))
  647. {
  648. $alignment = $alignments[$index];
  649. $HeaderElement['attributes'] = array(
  650. 'style' => 'text-align: '.$alignment.';',
  651. );
  652. }
  653. $HeaderElements []= $HeaderElement;
  654. }
  655. # ~
  656. $Block = array(
  657. 'alignments' => $alignments,
  658. 'identified' => true,
  659. 'element' => array(
  660. 'name' => 'table',
  661. 'handler' => 'elements',
  662. ),
  663. );
  664. $Block['element']['text'] []= array(
  665. 'name' => 'thead',
  666. 'handler' => 'elements',
  667. );
  668. $Block['element']['text'] []= array(
  669. 'name' => 'tbody',
  670. 'handler' => 'elements',
  671. 'text' => array(),
  672. );
  673. $Block['element']['text'][0]['text'] []= array(
  674. 'name' => 'tr',
  675. 'handler' => 'elements',
  676. 'text' => $HeaderElements,
  677. );
  678. return $Block;
  679. }
  680. }
  681. protected function blockTableContinue($Line, array $Block)
  682. {
  683. if (isset($Block['interrupted']))
  684. {
  685. return;
  686. }
  687. if ($Line['text'][0] === '|' or strpos($Line['text'], '|'))
  688. {
  689. $Elements = array();
  690. $row = $Line['text'];
  691. $row = trim($row);
  692. $row = trim($row, '|');
  693. preg_match_all('/(?:(\\\\[|])|[^|`]|`[^`]+`|`)+/', $row, $matches);
  694. foreach ($matches[0] as $index => $cell)
  695. {
  696. $cell = trim($cell);
  697. $Element = array(
  698. 'name' => 'td',
  699. 'handler' => 'line',
  700. 'text' => $cell,
  701. );
  702. if (isset($Block['alignments'][$index]))
  703. {
  704. $Element['attributes'] = array(
  705. 'style' => 'text-align: '.$Block['alignments'][$index].';',
  706. );
  707. }
  708. $Elements []= $Element;
  709. }
  710. $Element = array(
  711. 'name' => 'tr',
  712. 'handler' => 'elements',
  713. 'text' => $Elements,
  714. );
  715. $Block['element']['text'][1]['text'] []= $Element;
  716. return $Block;
  717. }
  718. }
  719. #
  720. # ~
  721. #
  722. protected function paragraph($Line)
  723. {
  724. $Block = array(
  725. 'element' => array(
  726. 'name' => 'p',
  727. 'text' => $Line['text'],
  728. 'handler' => 'line',
  729. ),
  730. );
  731. return $Block;
  732. }
  733. #
  734. # Inline Elements
  735. #
  736. protected $InlineTypes = array(
  737. '"' => array('SpecialCharacter'),
  738. '!' => array('Image'),
  739. '&' => array('SpecialCharacter'),
  740. '*' => array('Emphasis'),
  741. ':' => array('Url'),
  742. '<' => array('UrlTag', 'EmailTag', 'Markup', 'SpecialCharacter'),
  743. '>' => array('SpecialCharacter'),
  744. '[' => array('Link'),
  745. '_' => array('Emphasis'),
  746. '`' => array('Code'),
  747. '~' => array('Strikethrough'),
  748. '\\' => array('EscapeSequence'),
  749. );
  750. # ~
  751. protected $inlineMarkerList = '!"*_&[:<>`~\\';
  752. #
  753. # ~
  754. #
  755. public function line($text)
  756. {
  757. $markup = '';
  758. # $excerpt is based on the first occurrence of a marker
  759. while ($excerpt = strpbrk($text, $this->inlineMarkerList))
  760. {
  761. $marker = $excerpt[0];
  762. $markerPosition = strpos($text, $marker);
  763. $Excerpt = array('text' => $excerpt, 'context' => $text);
  764. foreach ($this->InlineTypes[$marker] as $inlineType)
  765. {
  766. $Inline = $this->{'inline'.$inlineType}($Excerpt);
  767. if ( ! isset($Inline))
  768. {
  769. continue;
  770. }
  771. # makes sure that the inline belongs to "our" marker
  772. if (isset($Inline['position']) and $Inline['position'] > $markerPosition)
  773. {
  774. continue;
  775. }
  776. # sets a default inline position
  777. if ( ! isset($Inline['position']))
  778. {
  779. $Inline['position'] = $markerPosition;
  780. }
  781. # the text that comes before the inline
  782. $unmarkedText = substr($text, 0, $Inline['position']);
  783. # compile the unmarked text
  784. $markup .= $this->unmarkedText($unmarkedText);
  785. # compile the inline
  786. $markup .= isset($Inline['markup']) ? $Inline['markup'] : $this->element($Inline['element']);
  787. # remove the examined text
  788. $text = substr($text, $Inline['position'] + $Inline['extent']);
  789. continue 2;
  790. }
  791. # the marker does not belong to an inline
  792. $unmarkedText = substr($text, 0, $markerPosition + 1);
  793. $markup .= $this->unmarkedText($unmarkedText);
  794. $text = substr($text, $markerPosition + 1);
  795. }
  796. $markup .= $this->unmarkedText($text);
  797. return $markup;
  798. }
  799. #
  800. # ~
  801. #
  802. protected function inlineCode($Excerpt)
  803. {
  804. $marker = $Excerpt['text'][0];
  805. if (preg_match('/^('.$marker.'+)[ ]*(.+?)[ ]*(?<!'.$marker.')\1(?!'.$marker.')/s', $Excerpt['text'], $matches))
  806. {
  807. $text = $matches[2];
  808. $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
  809. $text = preg_replace("/[ ]*\n/", ' ', $text);
  810. return array(
  811. 'extent' => strlen($matches[0]),
  812. 'element' => array(
  813. 'name' => 'code',
  814. 'text' => $text,
  815. ),
  816. );
  817. }
  818. }
  819. protected function inlineEmailTag($Excerpt)
  820. {
  821. if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<((mailto:)?\S+?@\S+?)>/i', $Excerpt['text'], $matches))
  822. {
  823. $url = $matches[1];
  824. if ( ! isset($matches[2]))
  825. {
  826. $url = 'mailto:' . $url;
  827. }
  828. return array(
  829. 'extent' => strlen($matches[0]),
  830. 'element' => array(
  831. 'name' => 'a',
  832. 'text' => $matches[1],
  833. 'attributes' => array(
  834. 'href' => $url,
  835. ),
  836. ),
  837. );
  838. }
  839. }
  840. protected function inlineEmphasis($Excerpt)
  841. {
  842. if ( ! isset($Excerpt['text'][1]))
  843. {
  844. return;
  845. }
  846. $marker = $Excerpt['text'][0];
  847. if ($Excerpt['text'][1] === $marker and preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches))
  848. {
  849. $emphasis = 'strong';
  850. }
  851. elseif (preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches))
  852. {
  853. $emphasis = 'em';
  854. }
  855. else
  856. {
  857. return;
  858. }
  859. return array(
  860. 'extent' => strlen($matches[0]),
  861. 'element' => array(
  862. 'name' => $emphasis,
  863. 'handler' => 'line',
  864. 'text' => $matches[1],
  865. ),
  866. );
  867. }
  868. protected function inlineEscapeSequence($Excerpt)
  869. {
  870. if (isset($Excerpt['text'][1]) and in_array($Excerpt['text'][1], $this->specialCharacters))
  871. {
  872. return array(
  873. 'markup' => $Excerpt['text'][1],
  874. 'extent' => 2,
  875. );
  876. }
  877. }
  878. protected function inlineImage($Excerpt)
  879. {
  880. if ( ! isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '[')
  881. {
  882. return;
  883. }
  884. $Excerpt['text']= substr($Excerpt['text'], 1);
  885. $Link = $this->inlineLink($Excerpt);
  886. if ($Link === null)
  887. {
  888. return;
  889. }
  890. $Inline = array(
  891. 'extent' => $Link['extent'] + 1,
  892. 'element' => array(
  893. 'name' => 'img',
  894. 'attributes' => array(
  895. 'src' => $Link['element']['attributes']['href'],
  896. 'alt' => $Link['element']['text'],
  897. ),
  898. ),
  899. );
  900. $Inline['element']['attributes'] += $Link['element']['attributes'];
  901. unset($Inline['element']['attributes']['href']);
  902. return $Inline;
  903. }
  904. protected function inlineLink($Excerpt)
  905. {
  906. $Element = array(
  907. 'name' => 'a',
  908. 'handler' => 'line',
  909. 'text' => null,
  910. 'attributes' => array(
  911. 'href' => null,
  912. 'title' => null,
  913. ),
  914. );
  915. $extent = 0;
  916. $remainder = $Excerpt['text'];
  917. if (preg_match('/\[((?:[^][]|(?R))*)\]/', $remainder, $matches))
  918. {
  919. $Element['text'] = $matches[1];
  920. $extent += strlen($matches[0]);
  921. $remainder = substr($remainder, $extent);
  922. }
  923. else
  924. {
  925. return;
  926. }
  927. if (preg_match('/^[(]((?:[^ ()]|[(][^ )]+[)])+)(?:[ ]+("[^"]*"|\'[^\']*\'))?[)]/', $remainder, $matches))
  928. {
  929. $Element['attributes']['href'] = $matches[1];
  930. if (isset($matches[2]))
  931. {
  932. $Element['attributes']['title'] = substr($matches[2], 1, - 1);
  933. }
  934. $extent += strlen($matches[0]);
  935. }
  936. else
  937. {
  938. if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches))
  939. {
  940. $definition = strlen($matches[1]) ? $matches[1] : $Element['text'];
  941. $definition = strtolower($definition);
  942. $extent += strlen($matches[0]);
  943. }
  944. else
  945. {
  946. $definition = strtolower($Element['text']);
  947. }
  948. if ( ! isset($this->DefinitionData['Reference'][$definition]))
  949. {
  950. return;
  951. }
  952. $Definition = $this->DefinitionData['Reference'][$definition];
  953. $Element['attributes']['href'] = $Definition['url'];
  954. $Element['attributes']['title'] = $Definition['title'];
  955. }
  956. $Element['attributes']['href'] = str_replace(array('&', '<'), array('&amp;', '&lt;'), $Element['attributes']['href']);
  957. return array(
  958. 'extent' => $extent,
  959. 'element' => $Element,
  960. );
  961. }
  962. protected function inlineMarkup($Excerpt)
  963. {
  964. if ($this->markupEscaped or strpos($Excerpt['text'], '>') === false)
  965. {
  966. return;
  967. }
  968. if ($Excerpt['text'][1] === '/' and preg_match('/^<\/\w*[ ]*>/s', $Excerpt['text'], $matches))
  969. {
  970. return array(
  971. 'markup' => $matches[0],
  972. 'extent' => strlen($matches[0]),
  973. );
  974. }
  975. if ($Excerpt['text'][1] === '!' and preg_match('/^<!---?[^>-](?:-?[^-])*-->/s', $Excerpt['text'], $matches))
  976. {
  977. return array(
  978. 'markup' => $matches[0],
  979. 'extent' => strlen($matches[0]),
  980. );
  981. }
  982. if ($Excerpt['text'][1] !== ' ' and preg_match('/^<\w*(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*\/?>/s', $Excerpt['text'], $matches))
  983. {
  984. return array(
  985. 'markup' => $matches[0],
  986. 'extent' => strlen($matches[0]),
  987. );
  988. }
  989. }
  990. protected function inlineSpecialCharacter($Excerpt)
  991. {
  992. if ($Excerpt['text'][0] === '&' and ! preg_match('/^&#?\w+;/', $Excerpt['text']))
  993. {
  994. return array(
  995. 'markup' => '&amp;',
  996. 'extent' => 1,
  997. );
  998. }
  999. $SpecialCharacter = array('>' => 'gt', '<' => 'lt', '"' => 'quot');
  1000. if (isset($SpecialCharacter[$Excerpt['text'][0]]))
  1001. {
  1002. return array(
  1003. 'markup' => '&'.$SpecialCharacter[$Excerpt['text'][0]].';',
  1004. 'extent' => 1,
  1005. );
  1006. }
  1007. }
  1008. protected function inlineStrikethrough($Excerpt)
  1009. {
  1010. if ( ! isset($Excerpt['text'][1]))
  1011. {
  1012. return;
  1013. }
  1014. if ($Excerpt['text'][1] === '~' and preg_match('/^~~(?=\S)(.+?)(?<=\S)~~/', $Excerpt['text'], $matches))
  1015. {
  1016. return array(
  1017. 'extent' => strlen($matches[0]),
  1018. 'element' => array(
  1019. 'name' => 'del',
  1020. 'text' => $matches[1],
  1021. 'handler' => 'line',
  1022. ),
  1023. );
  1024. }
  1025. }
  1026. protected function inlineUrl($Excerpt)
  1027. {
  1028. if ($this->urlsLinked !== true or ! isset($Excerpt['text'][2]) or $Excerpt['text'][2] !== '/')
  1029. {
  1030. return;
  1031. }
  1032. if (preg_match('/\bhttps?:[\/]{2}[^\s<]+\b\/*/ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE))
  1033. {
  1034. $Inline = array(
  1035. 'extent' => strlen($matches[0][0]),
  1036. 'position' => $matches[0][1],
  1037. 'element' => array(
  1038. 'name' => 'a',
  1039. 'text' => $matches[0][0],
  1040. 'attributes' => array(
  1041. 'href' => $matches[0][0],
  1042. ),
  1043. ),
  1044. );
  1045. return $Inline;
  1046. }
  1047. }
  1048. protected function inlineUrlTag($Excerpt)
  1049. {
  1050. if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<(\w+:\/{2}[^ >]+)>/i', $Excerpt['text'], $matches))
  1051. {
  1052. $url = str_replace(array('&', '<'), array('&amp;', '&lt;'), $matches[1]);
  1053. return array(
  1054. 'extent' => strlen($matches[0]),
  1055. 'element' => array(
  1056. 'name' => 'a',
  1057. 'text' => $url,
  1058. 'attributes' => array(
  1059. 'href' => $url,
  1060. ),
  1061. ),
  1062. );
  1063. }
  1064. }
  1065. # ~
  1066. protected function unmarkedText($text)
  1067. {
  1068. if ($this->breaksEnabled)
  1069. {
  1070. $text = preg_replace('/[ ]*\n/', "<br />\n", $text);
  1071. }
  1072. else
  1073. {
  1074. $text = preg_replace('/(?:[ ][ ]+|[ ]*\\\\)\n/', "<br />\n", $text);
  1075. $text = str_replace(" \n", "\n", $text);
  1076. }
  1077. return $text;
  1078. }
  1079. #
  1080. # Handlers
  1081. #
  1082. protected function element(array $Element)
  1083. {
  1084. $markup = '<'.$Element['name'];
  1085. if (isset($Element['attributes']))
  1086. {
  1087. foreach ($Element['attributes'] as $name => $value)
  1088. {
  1089. if ($value === null)
  1090. {
  1091. continue;
  1092. }
  1093. $markup .= ' '.$name.'="'.$value.'"';
  1094. }
  1095. }
  1096. if (isset($Element['text']))
  1097. {
  1098. $markup .= '>';
  1099. if (isset($Element['handler']))
  1100. {
  1101. $markup .= $this->{$Element['handler']}($Element['text']);
  1102. }
  1103. else
  1104. {
  1105. $markup .= $Element['text'];
  1106. }
  1107. $markup .= '</'.$Element['name'].'>';
  1108. }
  1109. else
  1110. {
  1111. $markup .= ' />';
  1112. }
  1113. return $markup;
  1114. }
  1115. protected function elements(array $Elements)
  1116. {
  1117. $markup = '';
  1118. foreach ($Elements as $Element)
  1119. {
  1120. $markup .= "\n" . $this->element($Element);
  1121. }
  1122. $markup .= "\n";
  1123. return $markup;
  1124. }
  1125. # ~
  1126. protected function li($lines)
  1127. {
  1128. $markup = $this->lines($lines);
  1129. $trimmedMarkup = trim($markup);
  1130. if ( ! in_array('', $lines) and substr($trimmedMarkup, 0, 3) === '<p>')
  1131. {
  1132. $markup = $trimmedMarkup;
  1133. $markup = substr($markup, 3);
  1134. $position = strpos($markup, "</p>");
  1135. $markup = substr_replace($markup, '', $position, 4);
  1136. }
  1137. return $markup;
  1138. }
  1139. #
  1140. # Deprecated Methods
  1141. #
  1142. function parse($text)
  1143. {
  1144. $markup = $this->text($text);
  1145. return $markup;
  1146. }
  1147. #
  1148. # Static Methods
  1149. #
  1150. static function instance($name = 'default')
  1151. {
  1152. if (isset(self::$instances[$name]))
  1153. {
  1154. return self::$instances[$name];
  1155. }
  1156. $instance = new static();
  1157. self::$instances[$name] = $instance;
  1158. return $instance;
  1159. }
  1160. private static $instances = array();
  1161. #
  1162. # Fields
  1163. #
  1164. protected $DefinitionData;
  1165. #
  1166. # Read-Only
  1167. protected $specialCharacters = array(
  1168. '\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '>', '#', '+', '-', '.', '!', '|',
  1169. );
  1170. protected $StrongRegex = array(
  1171. '*' => '/^[*]{2}((?:\\\\\*|[^*]|[*][^*]*[*])+?)[*]{2}(?![*])/s',
  1172. '_' => '/^__((?:\\\\_|[^_]|_[^_]*_)+?)__(?!_)/us',
  1173. );
  1174. protected $EmRegex = array(
  1175. '*' => '/^[*]((?:\\\\\*|[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s',
  1176. '_' => '/^_((?:\\\\_|[^_]|__[^_]*__)+?)_(?!_)\b/us',
  1177. );
  1178. protected $regexHtmlAttribute = '[a-zA-Z_:][\w:.-]*(?:\s*=\s*(?:[^"\'=<>`\s]+|"[^"]*"|\'[^\']*\'))?';
  1179. protected $voidElements = array(
  1180. 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source',
  1181. );
  1182. protected $textLevelElements = array(
  1183. 'a', 'br', 'bdo', 'abbr', 'blink', 'nextid', 'acronym', 'basefont',
  1184. 'b', 'em', 'big', 'cite', 'small', 'spacer', 'listing',
  1185. 'i', 'rp', 'del', 'code', 'strike', 'marquee',
  1186. 'q', 'rt', 'ins', 'font', 'strong',
  1187. 's', 'tt', 'sub', 'mark',
  1188. 'u', 'xm', 'sup', 'nobr',
  1189. 'var', 'ruby',
  1190. 'wbr', 'span',
  1191. 'time',
  1192. );
  1193. }