markdown.php 9.6 KB

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