Parsedown.php 40 KB

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