Parsedown.php 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548
  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. if($name === 'ol')
  392. {
  393. $listStart = stristr($matches[0], '.', true);
  394. if($listStart !== '1')
  395. {
  396. $Block['element']['attributes'] = array('start' => $listStart);
  397. }
  398. }
  399. $Block['li'] = array(
  400. 'name' => 'li',
  401. 'handler' => 'li',
  402. 'text' => array(
  403. $matches[2],
  404. ),
  405. );
  406. $Block['element']['text'] []= & $Block['li'];
  407. return $Block;
  408. }
  409. }
  410. protected function blockListContinue($Line, array $Block)
  411. {
  412. if ($Block['indent'] === $Line['indent'] and preg_match('/^'.$Block['pattern'].'(?:[ ]+(.*)|$)/', $Line['text'], $matches))
  413. {
  414. if (isset($Block['interrupted']))
  415. {
  416. $Block['li']['text'] []= '';
  417. unset($Block['interrupted']);
  418. }
  419. unset($Block['li']);
  420. $text = isset($matches[1]) ? $matches[1] : '';
  421. $Block['li'] = array(
  422. 'name' => 'li',
  423. 'handler' => 'li',
  424. 'text' => array(
  425. $text,
  426. ),
  427. );
  428. $Block['element']['text'] []= & $Block['li'];
  429. return $Block;
  430. }
  431. if ($Line['text'][0] === '[' and $this->blockReference($Line))
  432. {
  433. return $Block;
  434. }
  435. if ( ! isset($Block['interrupted']))
  436. {
  437. $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']);
  438. $Block['li']['text'] []= $text;
  439. return $Block;
  440. }
  441. if ($Line['indent'] > 0)
  442. {
  443. $Block['li']['text'] []= '';
  444. $text = preg_replace('/^[ ]{0,4}/', '', $Line['body']);
  445. $Block['li']['text'] []= $text;
  446. unset($Block['interrupted']);
  447. return $Block;
  448. }
  449. }
  450. #
  451. # Quote
  452. protected function blockQuote($Line)
  453. {
  454. if (preg_match('/^>[ ]?(.*)/', $Line['text'], $matches))
  455. {
  456. $Block = array(
  457. 'element' => array(
  458. 'name' => 'blockquote',
  459. 'handler' => 'lines',
  460. 'text' => (array) $matches[1],
  461. ),
  462. );
  463. return $Block;
  464. }
  465. }
  466. protected function blockQuoteContinue($Line, array $Block)
  467. {
  468. if ($Line['text'][0] === '>' and preg_match('/^>[ ]?(.*)/', $Line['text'], $matches))
  469. {
  470. if (isset($Block['interrupted']))
  471. {
  472. $Block['element']['text'] []= '';
  473. unset($Block['interrupted']);
  474. }
  475. $Block['element']['text'] []= $matches[1];
  476. return $Block;
  477. }
  478. if ( ! isset($Block['interrupted']))
  479. {
  480. $Block['element']['text'] []= $Line['text'];
  481. return $Block;
  482. }
  483. }
  484. #
  485. # Rule
  486. protected function blockRule($Line)
  487. {
  488. if (preg_match('/^(['.$Line['text'][0].'])([ ]*\1){2,}[ ]*$/', $Line['text']))
  489. {
  490. $Block = array(
  491. 'element' => array(
  492. 'name' => 'hr'
  493. ),
  494. );
  495. return $Block;
  496. }
  497. }
  498. #
  499. # Setext
  500. protected function blockSetextHeader($Line, array $Block = null)
  501. {
  502. if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted']))
  503. {
  504. return;
  505. }
  506. if (chop($Line['text'], $Line['text'][0]) === '')
  507. {
  508. $Block['element']['name'] = $Line['text'][0] === '=' ? 'h1' : 'h2';
  509. return $Block;
  510. }
  511. }
  512. #
  513. # Markup
  514. protected function blockMarkup($Line)
  515. {
  516. if ($this->markupEscaped)
  517. {
  518. return;
  519. }
  520. if (preg_match('/^<(\w*)(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*(\/)?>/', $Line['text'], $matches))
  521. {
  522. $element = strtolower($matches[1]);
  523. if (in_array($element, $this->textLevelElements))
  524. {
  525. return;
  526. }
  527. $Block = array(
  528. 'name' => $matches[1],
  529. 'depth' => 0,
  530. 'markup' => $Line['text'],
  531. );
  532. $length = strlen($matches[0]);
  533. $remainder = substr($Line['text'], $length);
  534. if (trim($remainder) === '')
  535. {
  536. if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
  537. {
  538. $Block['closed'] = true;
  539. $Block['void'] = true;
  540. }
  541. }
  542. else
  543. {
  544. if (isset($matches[2]) or in_array($matches[1], $this->voidElements))
  545. {
  546. return;
  547. }
  548. if (preg_match('/<\/'.$matches[1].'>[ ]*$/i', $remainder))
  549. {
  550. $Block['closed'] = true;
  551. }
  552. }
  553. return $Block;
  554. }
  555. }
  556. protected function blockMarkupContinue($Line, array $Block)
  557. {
  558. if (isset($Block['closed']))
  559. {
  560. return;
  561. }
  562. if (preg_match('/^<'.$Block['name'].'(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*>/i', $Line['text'])) # open
  563. {
  564. $Block['depth'] ++;
  565. }
  566. if (preg_match('/(.*?)<\/'.$Block['name'].'>[ ]*$/i', $Line['text'], $matches)) # close
  567. {
  568. if ($Block['depth'] > 0)
  569. {
  570. $Block['depth'] --;
  571. }
  572. else
  573. {
  574. $Block['closed'] = true;
  575. }
  576. }
  577. if (isset($Block['interrupted']))
  578. {
  579. $Block['markup'] .= "\n";
  580. unset($Block['interrupted']);
  581. }
  582. $Block['markup'] .= "\n".$Line['body'];
  583. return $Block;
  584. }
  585. #
  586. # Reference
  587. protected function blockReference($Line)
  588. {
  589. if (preg_match('/^\[(.+?)\]:[ ]*<?(\S+?)>?(?:[ ]+["\'(](.+)["\')])?[ ]*$/', $Line['text'], $matches))
  590. {
  591. $id = strtolower($matches[1]);
  592. $Data = array(
  593. 'url' => $matches[2],
  594. 'title' => null,
  595. );
  596. if (isset($matches[3]))
  597. {
  598. $Data['title'] = $matches[3];
  599. }
  600. $this->DefinitionData['Reference'][$id] = $Data;
  601. $Block = array(
  602. 'hidden' => true,
  603. );
  604. return $Block;
  605. }
  606. }
  607. #
  608. # Table
  609. protected function blockTable($Line, array $Block = null)
  610. {
  611. if ( ! isset($Block) or isset($Block['type']) or isset($Block['interrupted']))
  612. {
  613. return;
  614. }
  615. if (strpos($Block['element']['text'], '|') !== false and chop($Line['text'], ' -:|') === '')
  616. {
  617. $alignments = array();
  618. $divider = $Line['text'];
  619. $divider = trim($divider);
  620. $divider = trim($divider, '|');
  621. $dividerCells = explode('|', $divider);
  622. foreach ($dividerCells as $dividerCell)
  623. {
  624. $dividerCell = trim($dividerCell);
  625. if ($dividerCell === '')
  626. {
  627. continue;
  628. }
  629. $alignment = null;
  630. if ($dividerCell[0] === ':')
  631. {
  632. $alignment = 'left';
  633. }
  634. if (substr($dividerCell, - 1) === ':')
  635. {
  636. $alignment = $alignment === 'left' ? 'center' : 'right';
  637. }
  638. $alignments []= $alignment;
  639. }
  640. # ~
  641. $HeaderElements = array();
  642. $header = $Block['element']['text'];
  643. $header = trim($header);
  644. $header = trim($header, '|');
  645. $headerCells = explode('|', $header);
  646. foreach ($headerCells as $index => $headerCell)
  647. {
  648. $headerCell = trim($headerCell);
  649. $HeaderElement = array(
  650. 'name' => 'th',
  651. 'text' => $headerCell,
  652. 'handler' => 'line',
  653. );
  654. if (isset($alignments[$index]))
  655. {
  656. $alignment = $alignments[$index];
  657. $HeaderElement['attributes'] = array(
  658. 'style' => 'text-align: '.$alignment.';',
  659. );
  660. }
  661. $HeaderElements []= $HeaderElement;
  662. }
  663. # ~
  664. $Block = array(
  665. 'alignments' => $alignments,
  666. 'identified' => true,
  667. 'element' => array(
  668. 'name' => 'table',
  669. 'handler' => 'elements',
  670. ),
  671. );
  672. $Block['element']['text'] []= array(
  673. 'name' => 'thead',
  674. 'handler' => 'elements',
  675. );
  676. $Block['element']['text'] []= array(
  677. 'name' => 'tbody',
  678. 'handler' => 'elements',
  679. 'text' => array(),
  680. );
  681. $Block['element']['text'][0]['text'] []= array(
  682. 'name' => 'tr',
  683. 'handler' => 'elements',
  684. 'text' => $HeaderElements,
  685. );
  686. return $Block;
  687. }
  688. }
  689. protected function blockTableContinue($Line, array $Block)
  690. {
  691. if (isset($Block['interrupted']))
  692. {
  693. return;
  694. }
  695. if ($Line['text'][0] === '|' or strpos($Line['text'], '|'))
  696. {
  697. $Elements = array();
  698. $row = $Line['text'];
  699. $row = trim($row);
  700. $row = trim($row, '|');
  701. preg_match_all('/(?:(\\\\[|])|[^|`]|`[^`]+`|`)+/', $row, $matches);
  702. foreach ($matches[0] as $index => $cell)
  703. {
  704. $cell = trim($cell);
  705. $Element = array(
  706. 'name' => 'td',
  707. 'handler' => 'line',
  708. 'text' => $cell,
  709. );
  710. if (isset($Block['alignments'][$index]))
  711. {
  712. $Element['attributes'] = array(
  713. 'style' => 'text-align: '.$Block['alignments'][$index].';',
  714. );
  715. }
  716. $Elements []= $Element;
  717. }
  718. $Element = array(
  719. 'name' => 'tr',
  720. 'handler' => 'elements',
  721. 'text' => $Elements,
  722. );
  723. $Block['element']['text'][1]['text'] []= $Element;
  724. return $Block;
  725. }
  726. }
  727. #
  728. # ~
  729. #
  730. protected function paragraph($Line)
  731. {
  732. $Block = array(
  733. 'element' => array(
  734. 'name' => 'p',
  735. 'text' => $Line['text'],
  736. 'handler' => 'line',
  737. ),
  738. );
  739. return $Block;
  740. }
  741. #
  742. # Inline Elements
  743. #
  744. protected $InlineTypes = array(
  745. '"' => array('SpecialCharacter'),
  746. '!' => array('Image'),
  747. '&' => array('SpecialCharacter'),
  748. '*' => array('Emphasis'),
  749. ':' => array('Url'),
  750. '<' => array('UrlTag', 'EmailTag', 'Markup', 'SpecialCharacter'),
  751. '>' => array('SpecialCharacter'),
  752. '[' => array('Link'),
  753. '_' => array('Emphasis'),
  754. '`' => array('Code'),
  755. '~' => array('Strikethrough'),
  756. '\\' => array('EscapeSequence'),
  757. );
  758. # ~
  759. protected $inlineMarkerList = '!"*_&[:<>`~\\';
  760. #
  761. # ~
  762. #
  763. public function line($text)
  764. {
  765. $markup = '';
  766. # $excerpt is based on the first occurrence of a marker
  767. while ($excerpt = strpbrk($text, $this->inlineMarkerList))
  768. {
  769. $marker = $excerpt[0];
  770. $markerPosition = strpos($text, $marker);
  771. $Excerpt = array('text' => $excerpt, 'context' => $text);
  772. foreach ($this->InlineTypes[$marker] as $inlineType)
  773. {
  774. $Inline = $this->{'inline'.$inlineType}($Excerpt);
  775. if ( ! isset($Inline))
  776. {
  777. continue;
  778. }
  779. # makes sure that the inline belongs to "our" marker
  780. if (isset($Inline['position']) and $Inline['position'] > $markerPosition)
  781. {
  782. continue;
  783. }
  784. # sets a default inline position
  785. if ( ! isset($Inline['position']))
  786. {
  787. $Inline['position'] = $markerPosition;
  788. }
  789. # the text that comes before the inline
  790. $unmarkedText = substr($text, 0, $Inline['position']);
  791. # compile the unmarked text
  792. $markup .= $this->unmarkedText($unmarkedText);
  793. # compile the inline
  794. $markup .= isset($Inline['markup']) ? $Inline['markup'] : $this->element($Inline['element']);
  795. # remove the examined text
  796. $text = substr($text, $Inline['position'] + $Inline['extent']);
  797. continue 2;
  798. }
  799. # the marker does not belong to an inline
  800. $unmarkedText = substr($text, 0, $markerPosition + 1);
  801. $markup .= $this->unmarkedText($unmarkedText);
  802. $text = substr($text, $markerPosition + 1);
  803. }
  804. $markup .= $this->unmarkedText($text);
  805. return $markup;
  806. }
  807. #
  808. # ~
  809. #
  810. protected function inlineCode($Excerpt)
  811. {
  812. $marker = $Excerpt['text'][0];
  813. if (preg_match('/^('.$marker.'+)[ ]*(.+?)[ ]*(?<!'.$marker.')\1(?!'.$marker.')/s', $Excerpt['text'], $matches))
  814. {
  815. $text = $matches[2];
  816. $text = htmlspecialchars($text, ENT_NOQUOTES, 'UTF-8');
  817. $text = preg_replace("/[ ]*\n/", ' ', $text);
  818. return array(
  819. 'extent' => strlen($matches[0]),
  820. 'element' => array(
  821. 'name' => 'code',
  822. 'text' => $text,
  823. ),
  824. );
  825. }
  826. }
  827. protected function inlineEmailTag($Excerpt)
  828. {
  829. if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<((mailto:)?\S+?@\S+?)>/i', $Excerpt['text'], $matches))
  830. {
  831. $url = $matches[1];
  832. if ( ! isset($matches[2]))
  833. {
  834. $url = 'mailto:' . $url;
  835. }
  836. return array(
  837. 'extent' => strlen($matches[0]),
  838. 'element' => array(
  839. 'name' => 'a',
  840. 'text' => $matches[1],
  841. 'attributes' => array(
  842. 'href' => $url,
  843. ),
  844. ),
  845. );
  846. }
  847. }
  848. protected function inlineEmphasis($Excerpt)
  849. {
  850. if ( ! isset($Excerpt['text'][1]))
  851. {
  852. return;
  853. }
  854. $marker = $Excerpt['text'][0];
  855. if ($Excerpt['text'][1] === $marker and preg_match($this->StrongRegex[$marker], $Excerpt['text'], $matches))
  856. {
  857. $emphasis = 'strong';
  858. }
  859. elseif (preg_match($this->EmRegex[$marker], $Excerpt['text'], $matches))
  860. {
  861. $emphasis = 'em';
  862. }
  863. else
  864. {
  865. return;
  866. }
  867. return array(
  868. 'extent' => strlen($matches[0]),
  869. 'element' => array(
  870. 'name' => $emphasis,
  871. 'handler' => 'line',
  872. 'text' => $matches[1],
  873. ),
  874. );
  875. }
  876. protected function inlineEscapeSequence($Excerpt)
  877. {
  878. if (isset($Excerpt['text'][1]) and in_array($Excerpt['text'][1], $this->specialCharacters))
  879. {
  880. return array(
  881. 'markup' => $Excerpt['text'][1],
  882. 'extent' => 2,
  883. );
  884. }
  885. }
  886. protected function inlineImage($Excerpt)
  887. {
  888. if ( ! isset($Excerpt['text'][1]) or $Excerpt['text'][1] !== '[')
  889. {
  890. return;
  891. }
  892. $Excerpt['text']= substr($Excerpt['text'], 1);
  893. $Link = $this->inlineLink($Excerpt);
  894. if ($Link === null)
  895. {
  896. return;
  897. }
  898. $Inline = array(
  899. 'extent' => $Link['extent'] + 1,
  900. 'element' => array(
  901. 'name' => 'img',
  902. 'attributes' => array(
  903. 'src' => $Link['element']['attributes']['href'],
  904. 'alt' => $Link['element']['text'],
  905. ),
  906. ),
  907. );
  908. $Inline['element']['attributes'] += $Link['element']['attributes'];
  909. unset($Inline['element']['attributes']['href']);
  910. return $Inline;
  911. }
  912. protected function inlineLink($Excerpt)
  913. {
  914. $Element = array(
  915. 'name' => 'a',
  916. 'handler' => 'line',
  917. 'text' => null,
  918. 'attributes' => array(
  919. 'href' => null,
  920. 'title' => null,
  921. ),
  922. );
  923. $extent = 0;
  924. $remainder = $Excerpt['text'];
  925. if (preg_match('/\[((?:[^][]++|(?R))*+)\]/', $remainder, $matches))
  926. {
  927. $Element['text'] = $matches[1];
  928. $extent += strlen($matches[0]);
  929. $remainder = substr($remainder, $extent);
  930. }
  931. else
  932. {
  933. return;
  934. }
  935. if (preg_match('/^[(]\s*+((?:[^ ()]++|[(][^ )]+[)])++)(?:[ ]+("[^"]*"|\'[^\']*\'))?\s*[)]/', $remainder, $matches))
  936. {
  937. $Element['attributes']['href'] = $matches[1];
  938. if (isset($matches[2]))
  939. {
  940. $Element['attributes']['title'] = substr($matches[2], 1, - 1);
  941. }
  942. $extent += strlen($matches[0]);
  943. }
  944. else
  945. {
  946. if (preg_match('/^\s*\[(.*?)\]/', $remainder, $matches))
  947. {
  948. $definition = strlen($matches[1]) ? $matches[1] : $Element['text'];
  949. $definition = strtolower($definition);
  950. $extent += strlen($matches[0]);
  951. }
  952. else
  953. {
  954. $definition = strtolower($Element['text']);
  955. }
  956. if ( ! isset($this->DefinitionData['Reference'][$definition]))
  957. {
  958. return;
  959. }
  960. $Definition = $this->DefinitionData['Reference'][$definition];
  961. $Element['attributes']['href'] = $Definition['url'];
  962. $Element['attributes']['title'] = $Definition['title'];
  963. }
  964. $Element['attributes']['href'] = str_replace(array('&', '<'), array('&amp;', '&lt;'), $Element['attributes']['href']);
  965. return array(
  966. 'extent' => $extent,
  967. 'element' => $Element,
  968. );
  969. }
  970. protected function inlineMarkup($Excerpt)
  971. {
  972. if ($this->markupEscaped or strpos($Excerpt['text'], '>') === false)
  973. {
  974. return;
  975. }
  976. if ($Excerpt['text'][1] === '/' and preg_match('/^<\/\w*[ ]*>/s', $Excerpt['text'], $matches))
  977. {
  978. return array(
  979. 'markup' => $matches[0],
  980. 'extent' => strlen($matches[0]),
  981. );
  982. }
  983. if ($Excerpt['text'][1] === '!' and preg_match('/^<!---?[^>-](?:-?[^-])*-->/s', $Excerpt['text'], $matches))
  984. {
  985. return array(
  986. 'markup' => $matches[0],
  987. 'extent' => strlen($matches[0]),
  988. );
  989. }
  990. if ($Excerpt['text'][1] !== ' ' and preg_match('/^<\w*(?:[ ]*'.$this->regexHtmlAttribute.')*[ ]*\/?>/s', $Excerpt['text'], $matches))
  991. {
  992. return array(
  993. 'markup' => $matches[0],
  994. 'extent' => strlen($matches[0]),
  995. );
  996. }
  997. }
  998. protected function inlineSpecialCharacter($Excerpt)
  999. {
  1000. if ($Excerpt['text'][0] === '&' and ! preg_match('/^&#?\w+;/', $Excerpt['text']))
  1001. {
  1002. return array(
  1003. 'markup' => '&amp;',
  1004. 'extent' => 1,
  1005. );
  1006. }
  1007. $SpecialCharacter = array('>' => 'gt', '<' => 'lt', '"' => 'quot');
  1008. if (isset($SpecialCharacter[$Excerpt['text'][0]]))
  1009. {
  1010. return array(
  1011. 'markup' => '&'.$SpecialCharacter[$Excerpt['text'][0]].';',
  1012. 'extent' => 1,
  1013. );
  1014. }
  1015. }
  1016. protected function inlineStrikethrough($Excerpt)
  1017. {
  1018. if ( ! isset($Excerpt['text'][1]))
  1019. {
  1020. return;
  1021. }
  1022. if ($Excerpt['text'][1] === '~' and preg_match('/^~~(?=\S)(.+?)(?<=\S)~~/', $Excerpt['text'], $matches))
  1023. {
  1024. return array(
  1025. 'extent' => strlen($matches[0]),
  1026. 'element' => array(
  1027. 'name' => 'del',
  1028. 'text' => $matches[1],
  1029. 'handler' => 'line',
  1030. ),
  1031. );
  1032. }
  1033. }
  1034. protected function inlineUrl($Excerpt)
  1035. {
  1036. if ($this->urlsLinked !== true or ! isset($Excerpt['text'][2]) or $Excerpt['text'][2] !== '/')
  1037. {
  1038. return;
  1039. }
  1040. if (preg_match('/\bhttps?:[\/]{2}[^\s<]+\b\/*/ui', $Excerpt['context'], $matches, PREG_OFFSET_CAPTURE))
  1041. {
  1042. $Inline = array(
  1043. 'extent' => strlen($matches[0][0]),
  1044. 'position' => $matches[0][1],
  1045. 'element' => array(
  1046. 'name' => 'a',
  1047. 'text' => $matches[0][0],
  1048. 'attributes' => array(
  1049. 'href' => $matches[0][0],
  1050. ),
  1051. ),
  1052. );
  1053. return $Inline;
  1054. }
  1055. }
  1056. protected function inlineUrlTag($Excerpt)
  1057. {
  1058. if (strpos($Excerpt['text'], '>') !== false and preg_match('/^<(\w+:\/{2}[^ >]+)>/i', $Excerpt['text'], $matches))
  1059. {
  1060. $url = str_replace(array('&', '<'), array('&amp;', '&lt;'), $matches[1]);
  1061. return array(
  1062. 'extent' => strlen($matches[0]),
  1063. 'element' => array(
  1064. 'name' => 'a',
  1065. 'text' => $url,
  1066. 'attributes' => array(
  1067. 'href' => $url,
  1068. ),
  1069. ),
  1070. );
  1071. }
  1072. }
  1073. # ~
  1074. protected function unmarkedText($text)
  1075. {
  1076. if ($this->breaksEnabled)
  1077. {
  1078. $text = preg_replace('/[ ]*\n/', "<br />\n", $text);
  1079. }
  1080. else
  1081. {
  1082. $text = preg_replace('/(?:[ ][ ]+|[ ]*\\\\)\n/', "<br />\n", $text);
  1083. $text = str_replace(" \n", "\n", $text);
  1084. }
  1085. return $text;
  1086. }
  1087. #
  1088. # Handlers
  1089. #
  1090. protected function element(array $Element)
  1091. {
  1092. $markup = '<'.$Element['name'];
  1093. if (isset($Element['attributes']))
  1094. {
  1095. foreach ($Element['attributes'] as $name => $value)
  1096. {
  1097. if ($value === null)
  1098. {
  1099. continue;
  1100. }
  1101. $markup .= ' '.$name.'="'.$value.'"';
  1102. }
  1103. }
  1104. if (isset($Element['text']))
  1105. {
  1106. $markup .= '>';
  1107. if (isset($Element['handler']))
  1108. {
  1109. $markup .= $this->{$Element['handler']}($Element['text']);
  1110. }
  1111. else
  1112. {
  1113. $markup .= $Element['text'];
  1114. }
  1115. $markup .= '</'.$Element['name'].'>';
  1116. }
  1117. else
  1118. {
  1119. $markup .= ' />';
  1120. }
  1121. return $markup;
  1122. }
  1123. protected function elements(array $Elements)
  1124. {
  1125. $markup = '';
  1126. foreach ($Elements as $Element)
  1127. {
  1128. $markup .= "\n" . $this->element($Element);
  1129. }
  1130. $markup .= "\n";
  1131. return $markup;
  1132. }
  1133. # ~
  1134. protected function li($lines)
  1135. {
  1136. $markup = $this->lines($lines);
  1137. $trimmedMarkup = trim($markup);
  1138. if ( ! in_array('', $lines) and substr($trimmedMarkup, 0, 3) === '<p>')
  1139. {
  1140. $markup = $trimmedMarkup;
  1141. $markup = substr($markup, 3);
  1142. $position = strpos($markup, "</p>");
  1143. $markup = substr_replace($markup, '', $position, 4);
  1144. }
  1145. return $markup;
  1146. }
  1147. #
  1148. # Deprecated Methods
  1149. #
  1150. function parse($text)
  1151. {
  1152. $markup = $this->text($text);
  1153. return $markup;
  1154. }
  1155. #
  1156. # Static Methods
  1157. #
  1158. static function instance($name = 'default')
  1159. {
  1160. if (isset(self::$instances[$name]))
  1161. {
  1162. return self::$instances[$name];
  1163. }
  1164. $instance = new static();
  1165. self::$instances[$name] = $instance;
  1166. return $instance;
  1167. }
  1168. private static $instances = array();
  1169. #
  1170. # Fields
  1171. #
  1172. protected $DefinitionData;
  1173. #
  1174. # Read-Only
  1175. protected $specialCharacters = array(
  1176. '\\', '`', '*', '_', '{', '}', '[', ']', '(', ')', '>', '#', '+', '-', '.', '!', '|',
  1177. );
  1178. protected $StrongRegex = array(
  1179. '*' => '/^[*]{2}((?:\\\\\*|[^*]|[*][^*]*[*])+?)[*]{2}(?![*])/s',
  1180. '_' => '/^__((?:\\\\_|[^_]|_[^_]*_)+?)__(?!_)/us',
  1181. );
  1182. protected $EmRegex = array(
  1183. '*' => '/^[*]((?:\\\\\*|[^*]|[*][*][^*]+?[*][*])+?)[*](?![*])/s',
  1184. '_' => '/^_((?:\\\\_|[^_]|__[^_]*__)+?)_(?!_)\b/us',
  1185. );
  1186. protected $regexHtmlAttribute = '[a-zA-Z_:][\w:.-]*(?:\s*=\s*(?:[^"\'=<>`\s]+|"[^"]*"|\'[^\']*\'))?';
  1187. protected $voidElements = array(
  1188. 'area', 'base', 'br', 'col', 'command', 'embed', 'hr', 'img', 'input', 'link', 'meta', 'param', 'source',
  1189. );
  1190. protected $textLevelElements = array(
  1191. 'a', 'br', 'bdo', 'abbr', 'blink', 'nextid', 'acronym', 'basefont',
  1192. 'b', 'em', 'big', 'cite', 'small', 'spacer', 'listing',
  1193. 'i', 'rp', 'del', 'code', 'strike', 'marquee',
  1194. 'q', 'rt', 'ins', 'font', 'strong',
  1195. 's', 'tt', 'kbd', 'mark',
  1196. 'u', 'xm', 'sub', 'nobr',
  1197. 'sup', 'ruby',
  1198. 'var', 'span',
  1199. 'wbr', 'time',
  1200. );
  1201. }