6 * Shaare's descriptions are parsed with Markdown.
9 use Shaarli\Config\ConfigManager
;
12 * If this tag is used on a shaare, the description won't be processed by Parsedown.
14 define('NO_MD_TAG', 'nomarkdown');
17 * Parse linklist descriptions.
19 * @param array $data linklist data.
20 * @param ConfigManager $conf instance.
22 * @return mixed linklist data parsed in markdown (and converted to HTML).
24 function hook_markdown_render_linklist($data, $conf)
26 foreach ($data['links'] as &$value) {
27 if (!empty($value['tags']) && noMarkdownTag($value['tags'])) {
28 $value = stripNoMarkdownTag($value);
31 $value['description'] = process_markdown(
32 $value['description'],
33 $conf->get('security.markdown_escape', true),
34 $conf->get('security.allowed_protocols')
41 * Parse feed linklist descriptions.
43 * @param array $data linklist data.
44 * @param ConfigManager $conf instance.
46 * @return mixed linklist data parsed in markdown (and converted to HTML).
48 function hook_markdown_render_feed($data, $conf)
50 foreach ($data['links'] as &$value) {
51 if (!empty($value['tags']) && noMarkdownTag($value['tags'])) {
52 $value = stripNoMarkdownTag($value);
55 $value['description'] = reverse_feed_permalink($value['description']);
56 $value['description'] = process_markdown(
57 $value['description'],
58 $conf->get('security.markdown_escape', true),
59 $conf->get('security.allowed_protocols')
67 * Parse daily descriptions.
69 * @param array $data daily data.
70 * @param ConfigManager $conf instance.
72 * @return mixed daily data parsed in markdown (and converted to HTML).
74 function hook_markdown_render_daily($data, $conf)
76 //var_dump($data);die;
77 // Manipulate columns data
78 foreach ($data['linksToDisplay'] as &$value) {
79 if (!empty($value['tags']) && noMarkdownTag($value['tags'])) {
80 $value = stripNoMarkdownTag($value);
83 $value['formatedDescription'] = process_markdown(
84 $value['formatedDescription'],
85 $conf->get('security.markdown_escape', true),
86 $conf->get('security.allowed_protocols')
94 * Check if noMarkdown is set in tags.
96 * @param string $tags tag list
98 * @return bool true if markdown should be disabled on this link.
100 function noMarkdownTag($tags)
102 return preg_match('/(^|\s)'. NO_MD_TAG
.'(\s|$)/', $tags);
106 * Remove the no-markdown meta tag so it won't be displayed.
108 * @param array $link Link data.
110 * @return array Updated link without no markdown tag.
112 function stripNoMarkdownTag($link)
114 if (! empty($link['taglist'])) {
115 $offset = array_search(NO_MD_TAG
, $link['taglist']);
116 if ($offset !== false) {
117 unset($link['taglist'][$offset]);
121 if (!empty($link['tags'])) {
122 str_replace(NO_MD_TAG
, '', $link['tags']);
129 * When link list is displayed, include markdown CSS.
131 * @param array $data includes data.
133 * @return mixed - includes data with markdown CSS file added.
135 function hook_markdown_render_includes($data)
137 if ($data['_PAGE_'] == Router
::$PAGE_LINKLIST
138 || $data['_PAGE_'] == Router
::$PAGE_DAILY
139 || $data['_PAGE_'] == Router
::$PAGE_EDITLINK
142 $data['css_files'][] = PluginManager
::$PLUGINS_PATH . '/markdown/markdown.css';
149 * Hook render_editlink.
150 * Adds an help link to markdown syntax.
152 * @param array $data data passed to plugin
154 * @return array altered $data.
156 function hook_markdown_render_editlink($data)
158 // Load help HTML into a string
159 $txt = file_get_contents(PluginManager
::$PLUGINS_PATH .'/markdown/help.html');
161 t('Description will be rendered with'),
162 t('Markdown syntax documentation'),
163 t('Markdown syntax'),
165 $data['edit_link_plugin'][] = vsprintf($txt, $translations);
166 // Add no markdown 'meta-tag' in tag list if it was never used, for autocompletion.
167 if (! in_array(NO_MD_TAG
, $data['tags'])) {
168 $data['tags'][NO_MD_TAG
] = 0;
176 * Remove HTML links auto generated by Shaarli core system.
177 * Keeps HREF attributes.
179 * @param string $description input description text.
181 * @return string $description without HTML links.
183 function reverse_text2clickable($description)
185 $descriptionLines = explode(PHP_EOL
, $description);
186 $descriptionOut = '';
187 $codeBlockOn = false;
190 foreach ($descriptionLines as $descriptionLine) {
191 // Detect line of code: starting with 4 spaces,
192 // except lists which can start with +/*/- or `2.` after spaces.
193 $codeLineOn = preg_match('/^ +(?=[^\+\*\-])(?=(?!\d\.).)/', $descriptionLine) > 0;
194 // Detect and toggle block of code
196 $codeBlockOn = preg_match('/^```/', $descriptionLine) > 0;
198 elseif (preg_match('/^```/', $descriptionLine) > 0) {
199 $codeBlockOn = false;
202 $hashtagTitle = ' title="Hashtag [^"]+"';
203 // Reverse `inline code` hashtags.
204 $descriptionLine = preg_replace(
205 '!(`[^`\n]*)<a href="[^ ]*"'. $hashtagTitle .'>([^<]+)</a>([^`\n]*`)!m',
210 // Reverse all links in code blocks, only non hashtag elsewhere.
211 $hashtagFilter = (!$codeBlockOn && !$codeLineOn) ? '(?!'. $hashtagTitle .')': '(?:'. $hashtagTitle .')?';
212 $descriptionLine = preg_replace(
213 '#<a href="[^ ]*"'. $hashtagFilter .'>([^<]+)</a>#m',
218 $descriptionOut .= $descriptionLine;
219 if ($lineCount++ < count($descriptionLines) - 1) {
220 $descriptionOut .= PHP_EOL;
223 return $descriptionOut;
227 * Remove <br> tag to let markdown handle it.
229 * @param string $description input description text.
231 * @return string $description without <br> tags.
233 function reverse_nl2br($description)
235 return preg_replace('!<br */
?>!im
', '', $description);
239 * Remove HTML spaces ' 
;' auto generated by Shaarli core system.
241 * @param string $description input description text.
243 * @return string $description without HTML links.
245 function reverse_space2nbsp($description)
247 return preg_replace('/(^
| ) 
;/m
', '$1 ', $description);
250 function reverse_feed_permalink($description)
252 return preg_replace('@— <a href="([^"]+)" title="[^"]+">(\w+)</a>$@im', '— [$2]($1)', $description);
256 * Replace not whitelisted protocols with http:// in given description.
258 * @param string $description input description text.
259 * @param array $allowedProtocols list of allowed protocols.
261 * @return string $description without malicious link.
263 function filter_protocols($description, $allowedProtocols)
265 return preg_replace_callback(
267 function ($match) use ($allowedProtocols) {
268 return ']('. whitelist_protocols($match[1], $allowedProtocols) .')';
275 * Remove dangerous HTML tags (tags, iframe, etc.).
276 * Doesn't affect <code> content (already escaped by Parsedown).
278 * @param string $description input description text.
280 * @return string given string escaped.
282 function sanitize_html($description)
292 foreach ($escapeTags as $tag) {
293 $description = preg_replace_callback(
294 '#<\s*'. $tag .'[^>]*>(.*</\s*'. $tag .'[^>]*>)?#is',
295 function ($match) { return escape($match
[0]); },
298 $description = preg_replace(
299 '#(<[^>]+\s)on[a-z]*="?[^ "]*"?#is',
306 * Render shaare contents through Markdown parser.
307 * 1. Remove HTML generated by Shaarli core.
308 * 2. Reverse the escape function.
309 * 3. Generate markdown descriptions.
310 * 4. Sanitize sensible HTML tags for security.
311 * 5. Wrap description in 'markdown
' CSS class.
313 * @param string $description input description text.
314 * @param bool $escape escape HTML entities
316 * @return string HTML processed $description.
318 function process_markdown($description, $escape = true, $allowedProtocols = [])
320 $parsedown = new Parsedown();
322 $processedDescription = $description;
323 $processedDescription = reverse_nl2br($processedDescription);
324 $processedDescription = reverse_space2nbsp($processedDescription);
325 $processedDescription = reverse_text2clickable($processedDescription);
326 $processedDescription = filter_protocols($processedDescription, $allowedProtocols);
327 $processedDescription = unescape($processedDescription);
328 $processedDescription = $parsedown
329 ->setMarkupEscaped($escape)
330 ->setBreaksEnabled(true)
331 ->text($processedDescription);
332 $processedDescription = sanitize_html($processedDescription);
334 if(!empty($processedDescription)){
335 $processedDescription = '<div
class="markdown">'. $processedDescription . '</div
>';
338 return $processedDescription;
342 * This function is never called, but contains translation calls for GNU gettext extraction.
344 function markdown_dummy_translation()
347 t('Render shaare description with Markdown syntax
.<br
><strong
>Warning
</strong
>:
348 If your shaared descriptions contained HTML tags before enabling the markdown plugin
,
349 enabling it might
break your page
.
350 See the
<a href
="https://github.com/shaarli/Shaarli/tree/master/plugins/markdown#html-rendering">README
</a
>.');