Parsedown.php 40 KB

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