Site web d'Antopie https://antopie.org
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

539 lines
13 KiB

  1. <?php
  2. #
  3. #
  4. # Parsedown Extra
  5. # https://github.com/erusev/parsedown-extra
  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 ParsedownExtra extends Parsedown
  15. {
  16. # ~
  17. const version = '0.8.1';
  18. # ~
  19. function __construct()
  20. {
  21. if (version_compare(parent::version, '1.7.4') < 0)
  22. {
  23. throw new Exception('ParsedownExtra requires a later version of Parsedown');
  24. }
  25. $this->BlockTypes[':'] []= 'DefinitionList';
  26. $this->BlockTypes['*'] []= 'Abbreviation';
  27. # identify footnote definitions before reference definitions
  28. array_unshift($this->BlockTypes['['], 'Footnote');
  29. # identify footnote markers before before links
  30. array_unshift($this->InlineTypes['['], 'FootnoteMarker');
  31. }
  32. #
  33. # ~
  34. function text($text)
  35. {
  36. $markup = parent::text($text);
  37. # merge consecutive dl elements
  38. $markup = preg_replace('/<\/dl>\s+<dl>\s+/', '', $markup);
  39. # add footnotes
  40. if (isset($this->DefinitionData['Footnote']))
  41. {
  42. $Element = $this->buildFootnoteElement();
  43. $markup .= "\n" . $this->element($Element);
  44. }
  45. return $markup;
  46. }
  47. #
  48. # Blocks
  49. #
  50. #
  51. # Abbreviation
  52. protected function blockAbbreviation($Line)
  53. {
  54. if (preg_match('/^\*\[(.+?)\]:[ ]*(.+?)[ ]*$/', $Line['text'], $matches))
  55. {
  56. $this->DefinitionData['Abbreviation'][$matches[1]] = $matches[2];
  57. $Block = array(
  58. 'hidden' => true,
  59. );
  60. return $Block;
  61. }
  62. }
  63. #
  64. # Footnote
  65. protected function blockFootnote($Line)
  66. {
  67. if (preg_match('/^\[\^(.+?)\]:[ ]?(.*)$/', $Line['text'], $matches))
  68. {
  69. $Block = array(
  70. 'label' => $matches[1],
  71. 'text' => $matches[2],
  72. 'hidden' => true,
  73. );
  74. return $Block;
  75. }
  76. }
  77. protected function blockFootnoteContinue($Line, $Block)
  78. {
  79. if ($Line['text'][0] === '[' and preg_match('/^\[\^(.+?)\]:/', $Line['text']))
  80. {
  81. return;
  82. }
  83. if (isset($Block['interrupted']))
  84. {
  85. if ($Line['indent'] >= 4)
  86. {
  87. $Block['text'] .= "\n\n" . $Line['text'];
  88. return $Block;
  89. }
  90. }
  91. else
  92. {
  93. $Block['text'] .= "\n" . $Line['text'];
  94. return $Block;
  95. }
  96. }
  97. protected function blockFootnoteComplete($Block)
  98. {
  99. $this->DefinitionData['Footnote'][$Block['label']] = array(
  100. 'text' => $Block['text'],
  101. 'count' => null,
  102. 'number' => null,
  103. );
  104. return $Block;
  105. }
  106. #
  107. # Definition List
  108. protected function blockDefinitionList($Line, $Block)
  109. {
  110. if ( ! isset($Block) or isset($Block['type']))
  111. {
  112. return;
  113. }
  114. $Element = array(
  115. 'name' => 'dl',
  116. 'handler' => 'elements',
  117. 'text' => array(),
  118. );
  119. $terms = explode("\n", $Block['element']['text']);
  120. foreach ($terms as $term)
  121. {
  122. $Element['text'] []= array(
  123. 'name' => 'dt',
  124. 'handler' => 'line',
  125. 'text' => $term,
  126. );
  127. }
  128. $Block['element'] = $Element;
  129. $Block = $this->addDdElement($Line, $Block);
  130. return $Block;
  131. }
  132. protected function blockDefinitionListContinue($Line, array $Block)
  133. {
  134. if ($Line['text'][0] === ':')
  135. {
  136. $Block = $this->addDdElement($Line, $Block);
  137. return $Block;
  138. }
  139. else
  140. {
  141. if (isset($Block['interrupted']) and $Line['indent'] === 0)
  142. {
  143. return;
  144. }
  145. if (isset($Block['interrupted']))
  146. {
  147. $Block['dd']['handler'] = 'text';
  148. $Block['dd']['text'] .= "\n\n";
  149. unset($Block['interrupted']);
  150. }
  151. $text = substr($Line['body'], min($Line['indent'], 4));
  152. $Block['dd']['text'] .= "\n" . $text;
  153. return $Block;
  154. }
  155. }
  156. #
  157. # Header
  158. protected function blockHeader($Line)
  159. {
  160. $Block = parent::blockHeader($Line);
  161. if (! isset($Block)) {
  162. return null;
  163. }
  164. if (preg_match('/[ #]*{('.$this->regexAttribute.'+)}[ ]*$/', $Block['element']['text'], $matches, PREG_OFFSET_CAPTURE))
  165. {
  166. $attributeString = $matches[1][0];
  167. $Block['element']['attributes'] = $this->parseAttributeData($attributeString);
  168. $Block['element']['text'] = substr($Block['element']['text'], 0, $matches[0][1]);
  169. }
  170. return $Block;
  171. }
  172. #
  173. # Markup
  174. protected function blockMarkupComplete($Block)
  175. {
  176. if ( ! isset($Block['void']))
  177. {
  178. $Block['markup'] = $this->processTag($Block['markup']);
  179. }
  180. return $Block;
  181. }
  182. #
  183. # Setext
  184. protected function blockSetextHeader($Line, array $Block = null)
  185. {
  186. $Block = parent::blockSetextHeader($Line, $Block);
  187. if (! isset($Block)) {
  188. return null;
  189. }
  190. if (preg_match('/[ ]*{('.$this->regexAttribute.'+)}[ ]*$/', $Block['element']['text'], $matches, PREG_OFFSET_CAPTURE))
  191. {
  192. $attributeString = $matches[1][0];
  193. $Block['element']['attributes'] = $this->parseAttributeData($attributeString);
  194. $Block['element']['text'] = substr($Block['element']['text'], 0, $matches[0][1]);
  195. }
  196. return $Block;
  197. }
  198. #
  199. # Inline Elements
  200. #
  201. #
  202. # Footnote Marker
  203. protected function inlineFootnoteMarker($Excerpt)
  204. {
  205. if (preg_match('/^\[\^(.+?)\]/', $Excerpt['text'], $matches))
  206. {
  207. $name = $matches[1];
  208. if ( ! isset($this->DefinitionData['Footnote'][$name]))
  209. {
  210. return;
  211. }
  212. $this->DefinitionData['Footnote'][$name]['count'] ++;
  213. if ( ! isset($this->DefinitionData['Footnote'][$name]['number']))
  214. {
  215. $this->DefinitionData['Footnote'][$name]['number'] = ++ $this->footnoteCount; # » &
  216. }
  217. $Element = array(
  218. 'name' => 'sup',
  219. 'attributes' => array('id' => 'fnref'.$this->DefinitionData['Footnote'][$name]['count'].':'.$name),
  220. 'handler' => 'element',
  221. 'text' => array(
  222. 'name' => 'a',
  223. 'attributes' => array('href' => '#fn:'.$name, 'class' => 'footnote-ref'),
  224. 'text' => $this->DefinitionData['Footnote'][$name]['number'],
  225. ),
  226. );
  227. return array(
  228. 'extent' => strlen($matches[0]),
  229. 'element' => $Element,
  230. );
  231. }
  232. }
  233. private $footnoteCount = 0;
  234. #
  235. # Link
  236. protected function inlineLink($Excerpt)
  237. {
  238. $Link = parent::inlineLink($Excerpt);
  239. if (! isset($Link)) {
  240. return null;
  241. }
  242. $remainder = substr($Excerpt['text'], $Link['extent']);
  243. if (preg_match('/^[ ]*{('.$this->regexAttribute.'+)}/', $remainder, $matches))
  244. {
  245. $Link['element']['attributes'] += $this->parseAttributeData($matches[1]);
  246. $Link['extent'] += strlen($matches[0]);
  247. }
  248. return $Link;
  249. }
  250. #
  251. # ~
  252. #
  253. protected function unmarkedText($text)
  254. {
  255. $text = parent::unmarkedText($text);
  256. if (isset($this->DefinitionData['Abbreviation']))
  257. {
  258. foreach ($this->DefinitionData['Abbreviation'] as $abbreviation => $meaning)
  259. {
  260. $pattern = '/\b'.preg_quote($abbreviation, '/').'\b/';
  261. $text = preg_replace($pattern, '<abbr title="'.$meaning.'">'.$abbreviation.'</abbr>', $text);
  262. }
  263. }
  264. return $text;
  265. }
  266. #
  267. # Util Methods
  268. #
  269. protected function addDdElement(array $Line, array $Block)
  270. {
  271. $text = substr($Line['text'], 1);
  272. $text = trim($text);
  273. unset($Block['dd']);
  274. $Block['dd'] = array(
  275. 'name' => 'dd',
  276. 'handler' => 'line',
  277. 'text' => $text,
  278. );
  279. if (isset($Block['interrupted']))
  280. {
  281. $Block['dd']['handler'] = 'text';
  282. unset($Block['interrupted']);
  283. }
  284. $Block['element']['text'] []= & $Block['dd'];
  285. return $Block;
  286. }
  287. protected function buildFootnoteElement()
  288. {
  289. $Element = array(
  290. 'name' => 'div',
  291. 'attributes' => array('class' => 'footnotes'),
  292. 'handler' => 'elements',
  293. 'text' => array(
  294. array(
  295. 'name' => 'hr',
  296. ),
  297. array(
  298. 'name' => 'ol',
  299. 'handler' => 'elements',
  300. 'text' => array(),
  301. ),
  302. ),
  303. );
  304. uasort($this->DefinitionData['Footnote'], 'self::sortFootnotes');
  305. foreach ($this->DefinitionData['Footnote'] as $definitionId => $DefinitionData)
  306. {
  307. if ( ! isset($DefinitionData['number']))
  308. {
  309. continue;
  310. }
  311. $text = $DefinitionData['text'];
  312. $text = parent::text($text);
  313. $numbers = range(1, $DefinitionData['count']);
  314. $backLinksMarkup = '';
  315. foreach ($numbers as $number)
  316. {
  317. $backLinksMarkup .= ' <a href="#fnref'.$number.':'.$definitionId.'" rev="footnote" class="footnote-backref">&#8617;</a>';
  318. }
  319. $backLinksMarkup = substr($backLinksMarkup, 1);
  320. if (substr($text, - 4) === '</p>')
  321. {
  322. $backLinksMarkup = '&#160;'.$backLinksMarkup;
  323. $text = substr_replace($text, $backLinksMarkup.'</p>', - 4);
  324. }
  325. else
  326. {
  327. $text .= "\n".'<p>'.$backLinksMarkup.'</p>';
  328. }
  329. $Element['text'][1]['text'] []= array(
  330. 'name' => 'li',
  331. 'attributes' => array('id' => 'fn:'.$definitionId),
  332. 'rawHtml' => "\n".$text."\n",
  333. );
  334. }
  335. return $Element;
  336. }
  337. # ~
  338. protected function parseAttributeData($attributeString)
  339. {
  340. $Data = array();
  341. $attributes = preg_split('/[ ]+/', $attributeString, - 1, PREG_SPLIT_NO_EMPTY);
  342. foreach ($attributes as $attribute)
  343. {
  344. if ($attribute[0] === '#')
  345. {
  346. $Data['id'] = substr($attribute, 1);
  347. }
  348. else # "."
  349. {
  350. $classes []= substr($attribute, 1);
  351. }
  352. }
  353. if (isset($classes))
  354. {
  355. $Data['class'] = implode(' ', $classes);
  356. }
  357. return $Data;
  358. }
  359. # ~
  360. protected function processTag($elementMarkup) # recursive
  361. {
  362. # http://stackoverflow.com/q/1148928/200145
  363. libxml_use_internal_errors(true);
  364. $DOMDocument = new DOMDocument;
  365. # http://stackoverflow.com/q/11309194/200145
  366. $elementMarkup = mb_convert_encoding($elementMarkup, 'HTML-ENTITIES', 'UTF-8');
  367. # http://stackoverflow.com/q/4879946/200145
  368. $DOMDocument->loadHTML($elementMarkup);
  369. $DOMDocument->removeChild($DOMDocument->doctype);
  370. $DOMDocument->replaceChild($DOMDocument->firstChild->firstChild->firstChild, $DOMDocument->firstChild);
  371. $elementText = '';
  372. if ($DOMDocument->documentElement->getAttribute('markdown') === '1')
  373. {
  374. foreach ($DOMDocument->documentElement->childNodes as $Node)
  375. {
  376. $elementText .= $DOMDocument->saveHTML($Node);
  377. }
  378. $DOMDocument->documentElement->removeAttribute('markdown');
  379. $elementText = "\n".$this->text($elementText)."\n";
  380. }
  381. else
  382. {
  383. foreach ($DOMDocument->documentElement->childNodes as $Node)
  384. {
  385. $nodeMarkup = $DOMDocument->saveHTML($Node);
  386. if ($Node instanceof DOMElement and ! in_array($Node->nodeName, $this->textLevelElements))
  387. {
  388. $elementText .= $this->processTag($nodeMarkup);
  389. }
  390. else
  391. {
  392. $elementText .= $nodeMarkup;
  393. }
  394. }
  395. }
  396. # because we don't want for markup to get encoded
  397. $DOMDocument->documentElement->nodeValue = 'placeholder\x1A';
  398. $markup = $DOMDocument->saveHTML($DOMDocument->documentElement);
  399. $markup = str_replace('placeholder\x1A', $elementText, $markup);
  400. return $markup;
  401. }
  402. # ~
  403. protected function sortFootnotes($A, $B) # callback
  404. {
  405. return $A['number'] - $B['number'];
  406. }
  407. #
  408. # Fields
  409. #
  410. protected $regexAttribute = '(?:[#.][-\w]+[ ]*)';
  411. }