markdown.php 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351
  1. <?php
  2. /**
  3. * Plugin Markdown.
  4. *
  5. * Shaare's descriptions are parsed with Markdown.
  6. */
  7. use Shaarli\Config\ConfigManager;
  8. /*
  9. * If this tag is used on a shaare, the description won't be processed by Parsedown.
  10. */
  11. define('NO_MD_TAG', 'nomarkdown');
  12. /**
  13. * Parse linklist descriptions.
  14. *
  15. * @param array $data linklist data.
  16. * @param ConfigManager $conf instance.
  17. *
  18. * @return mixed linklist data parsed in markdown (and converted to HTML).
  19. */
  20. function hook_markdown_render_linklist($data, $conf)
  21. {
  22. foreach ($data['links'] as &$value) {
  23. if (!empty($value['tags']) && noMarkdownTag($value['tags'])) {
  24. $value = stripNoMarkdownTag($value);
  25. continue;
  26. }
  27. $value['description'] = process_markdown(
  28. $value['description'],
  29. $conf->get('security.markdown_escape', true),
  30. $conf->get('security.allowed_protocols')
  31. );
  32. }
  33. return $data;
  34. }
  35. /**
  36. * Parse feed linklist descriptions.
  37. *
  38. * @param array $data linklist data.
  39. * @param ConfigManager $conf instance.
  40. *
  41. * @return mixed linklist data parsed in markdown (and converted to HTML).
  42. */
  43. function hook_markdown_render_feed($data, $conf)
  44. {
  45. foreach ($data['links'] as &$value) {
  46. if (!empty($value['tags']) && noMarkdownTag($value['tags'])) {
  47. $value = stripNoMarkdownTag($value);
  48. continue;
  49. }
  50. $value['description'] = reverse_feed_permalink($value['description']);
  51. $value['description'] = process_markdown(
  52. $value['description'],
  53. $conf->get('security.markdown_escape', true),
  54. $conf->get('security.allowed_protocols')
  55. );
  56. }
  57. return $data;
  58. }
  59. /**
  60. * Parse daily descriptions.
  61. *
  62. * @param array $data daily data.
  63. * @param ConfigManager $conf instance.
  64. *
  65. * @return mixed daily data parsed in markdown (and converted to HTML).
  66. */
  67. function hook_markdown_render_daily($data, $conf)
  68. {
  69. //var_dump($data);die;
  70. // Manipulate columns data
  71. foreach ($data['linksToDisplay'] as &$value) {
  72. if (!empty($value['tags']) && noMarkdownTag($value['tags'])) {
  73. $value = stripNoMarkdownTag($value);
  74. continue;
  75. }
  76. $value['formatedDescription'] = process_markdown(
  77. $value['formatedDescription'],
  78. $conf->get('security.markdown_escape', true),
  79. $conf->get('security.allowed_protocols')
  80. );
  81. }
  82. return $data;
  83. }
  84. /**
  85. * Check if noMarkdown is set in tags.
  86. *
  87. * @param string $tags tag list
  88. *
  89. * @return bool true if markdown should be disabled on this link.
  90. */
  91. function noMarkdownTag($tags)
  92. {
  93. return preg_match('/(^|\s)'. NO_MD_TAG .'(\s|$)/', $tags);
  94. }
  95. /**
  96. * Remove the no-markdown meta tag so it won't be displayed.
  97. *
  98. * @param array $link Link data.
  99. *
  100. * @return array Updated link without no markdown tag.
  101. */
  102. function stripNoMarkdownTag($link)
  103. {
  104. if (! empty($link['taglist'])) {
  105. $offset = array_search(NO_MD_TAG, $link['taglist']);
  106. if ($offset !== false) {
  107. unset($link['taglist'][$offset]);
  108. }
  109. }
  110. if (!empty($link['tags'])) {
  111. str_replace(NO_MD_TAG, '', $link['tags']);
  112. }
  113. return $link;
  114. }
  115. /**
  116. * When link list is displayed, include markdown CSS.
  117. *
  118. * @param array $data includes data.
  119. *
  120. * @return mixed - includes data with markdown CSS file added.
  121. */
  122. function hook_markdown_render_includes($data)
  123. {
  124. if ($data['_PAGE_'] == Router::$PAGE_LINKLIST
  125. || $data['_PAGE_'] == Router::$PAGE_DAILY
  126. || $data['_PAGE_'] == Router::$PAGE_EDITLINK
  127. ) {
  128. $data['css_files'][] = PluginManager::$PLUGINS_PATH . '/markdown/markdown.css';
  129. }
  130. return $data;
  131. }
  132. /**
  133. * Hook render_editlink.
  134. * Adds an help link to markdown syntax.
  135. *
  136. * @param array $data data passed to plugin
  137. *
  138. * @return array altered $data.
  139. */
  140. function hook_markdown_render_editlink($data)
  141. {
  142. // Load help HTML into a string
  143. $txt = file_get_contents(PluginManager::$PLUGINS_PATH .'/markdown/help.html');
  144. $translations = [
  145. t('Description will be rendered with'),
  146. t('Markdown syntax documentation'),
  147. t('Markdown syntax'),
  148. ];
  149. $data['edit_link_plugin'][] = vsprintf($txt, $translations);
  150. // Add no markdown 'meta-tag' in tag list if it was never used, for autocompletion.
  151. if (! in_array(NO_MD_TAG, $data['tags'])) {
  152. $data['tags'][NO_MD_TAG] = 0;
  153. }
  154. return $data;
  155. }
  156. /**
  157. * Remove HTML links auto generated by Shaarli core system.
  158. * Keeps HREF attributes.
  159. *
  160. * @param string $description input description text.
  161. *
  162. * @return string $description without HTML links.
  163. */
  164. function reverse_text2clickable($description)
  165. {
  166. $descriptionLines = explode(PHP_EOL, $description);
  167. $descriptionOut = '';
  168. $codeBlockOn = false;
  169. $lineCount = 0;
  170. foreach ($descriptionLines as $descriptionLine) {
  171. // Detect line of code: starting with 4 spaces,
  172. // except lists which can start with +/*/- or `2.` after spaces.
  173. $codeLineOn = preg_match('/^ +(?=[^\+\*\-])(?=(?!\d\.).)/', $descriptionLine) > 0;
  174. // Detect and toggle block of code
  175. if (!$codeBlockOn) {
  176. $codeBlockOn = preg_match('/^```/', $descriptionLine) > 0;
  177. }
  178. elseif (preg_match('/^```/', $descriptionLine) > 0) {
  179. $codeBlockOn = false;
  180. }
  181. $hashtagTitle = ' title="Hashtag [^"]+"';
  182. // Reverse `inline code` hashtags.
  183. $descriptionLine = preg_replace(
  184. '!(`[^`\n]*)<a href="[^ ]*"'. $hashtagTitle .'>([^<]+)</a>([^`\n]*`)!m',
  185. '$1$2$3',
  186. $descriptionLine
  187. );
  188. // Reverse all links in code blocks, only non hashtag elsewhere.
  189. $hashtagFilter = (!$codeBlockOn && !$codeLineOn) ? '(?!'. $hashtagTitle .')': '(?:'. $hashtagTitle .')?';
  190. $descriptionLine = preg_replace(
  191. '#<a href="[^ ]*"'. $hashtagFilter .'>([^<]+)</a>#m',
  192. '$1',
  193. $descriptionLine
  194. );
  195. $descriptionOut .= $descriptionLine;
  196. if ($lineCount++ < count($descriptionLines) - 1) {
  197. $descriptionOut .= PHP_EOL;
  198. }
  199. }
  200. return $descriptionOut;
  201. }
  202. /**
  203. * Remove <br> tag to let markdown handle it.
  204. *
  205. * @param string $description input description text.
  206. *
  207. * @return string $description without <br> tags.
  208. */
  209. function reverse_nl2br($description)
  210. {
  211. return preg_replace('!<br */?>!im', '', $description);
  212. }
  213. /**
  214. * Remove HTML spaces '&nbsp;' auto generated by Shaarli core system.
  215. *
  216. * @param string $description input description text.
  217. *
  218. * @return string $description without HTML links.
  219. */
  220. function reverse_space2nbsp($description)
  221. {
  222. return preg_replace('/(^| )&nbsp;/m', '$1 ', $description);
  223. }
  224. function reverse_feed_permalink($description)
  225. {
  226. return preg_replace('@&#8212; <a href="([^"]+)" title="[^"]+">(\w+)</a>$@im', '&#8212; [$2]($1)', $description);
  227. }
  228. /**
  229. * Replace not whitelisted protocols with http:// in given description.
  230. *
  231. * @param string $description input description text.
  232. * @param array $allowedProtocols list of allowed protocols.
  233. *
  234. * @return string $description without malicious link.
  235. */
  236. function filter_protocols($description, $allowedProtocols)
  237. {
  238. return preg_replace_callback(
  239. '#]\((.*?)\)#is',
  240. function ($match) use ($allowedProtocols) {
  241. return ']('. whitelist_protocols($match[1], $allowedProtocols) .')';
  242. },
  243. $description
  244. );
  245. }
  246. /**
  247. * Remove dangerous HTML tags (tags, iframe, etc.).
  248. * Doesn't affect <code> content (already escaped by Parsedown).
  249. *
  250. * @param string $description input description text.
  251. *
  252. * @return string given string escaped.
  253. */
  254. function sanitize_html($description)
  255. {
  256. $escapeTags = array(
  257. 'script',
  258. 'style',
  259. 'link',
  260. 'iframe',
  261. 'frameset',
  262. 'frame',
  263. );
  264. foreach ($escapeTags as $tag) {
  265. $description = preg_replace_callback(
  266. '#<\s*'. $tag .'[^>]*>(.*</\s*'. $tag .'[^>]*>)?#is',
  267. function ($match) { return escape($match[0]); },
  268. $description);
  269. }
  270. $description = preg_replace(
  271. '#(<[^>]+\s)on[a-z]*="?[^ "]*"?#is',
  272. '$1',
  273. $description);
  274. return $description;
  275. }
  276. /**
  277. * Render shaare contents through Markdown parser.
  278. * 1. Remove HTML generated by Shaarli core.
  279. * 2. Reverse the escape function.
  280. * 3. Generate markdown descriptions.
  281. * 4. Sanitize sensible HTML tags for security.
  282. * 5. Wrap description in 'markdown' CSS class.
  283. *
  284. * @param string $description input description text.
  285. * @param bool $escape escape HTML entities
  286. *
  287. * @return string HTML processed $description.
  288. */
  289. function process_markdown($description, $escape = true, $allowedProtocols = [])
  290. {
  291. $parsedown = new Parsedown();
  292. $processedDescription = $description;
  293. $processedDescription = reverse_nl2br($processedDescription);
  294. $processedDescription = reverse_space2nbsp($processedDescription);
  295. $processedDescription = reverse_text2clickable($processedDescription);
  296. $processedDescription = filter_protocols($processedDescription, $allowedProtocols);
  297. $processedDescription = unescape($processedDescription);
  298. $processedDescription = $parsedown
  299. ->setMarkupEscaped($escape)
  300. ->setBreaksEnabled(true)
  301. ->text($processedDescription);
  302. $processedDescription = sanitize_html($processedDescription);
  303. if(!empty($processedDescription)){
  304. $processedDescription = '<div class="markdown">'. $processedDescription . '</div>';
  305. }
  306. return $processedDescription;
  307. }
  308. /**
  309. * This function is never called, but contains translation calls for GNU gettext extraction.
  310. */
  311. function markdown_dummy_translation()
  312. {
  313. // meta
  314. t('Render shaare description with Markdown syntax.<br><strong>Warning</strong>:
  315. If your shaared descriptions contained HTML tags before enabling the markdown plugin,
  316. enabling it might break your page.
  317. See the <a href="https://github.com/shaarli/Shaarli/tree/master/plugins/markdown#html-rendering">README</a>.');
  318. }