PageRenderTime 71ms CodeModel.GetById 23ms RepoModel.GetById 0ms app.codeStats 1ms

/wire/modules/Textformatter/TextformatterMarkdownExtra/parsedown/Parsedown.php

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