parsedown.php 37 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549
  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', 'sub', 'mark',
  1196. 'u', 'xm', 'sup', 'nobr',
  1197. 'var', 'ruby',
  1198. 'wbr', 'span',
  1199. 'time',
  1200. );
  1201. }