6 * Shaare's descriptions are parsed with Markdown.
9 use Shaarli\Config\ConfigManager
;
13 * If this tag is used on a shaare, the description won't be processed by Parsedown.
15 define('NO_MD_TAG', 'nomarkdown');
18 * Parse linklist descriptions.
20 * @param array $data linklist data.
21 * @param ConfigManager $conf instance.
23 * @return mixed linklist data parsed in markdown (and converted to HTML).
25 function hook_markdown_render_linklist($data, $conf)
27 foreach ($data['links'] as &$value) {
28 if (!empty($value['tags']) && noMarkdownTag($value['tags'])) {
29 $value = stripNoMarkdownTag($value);
32 $value['description_src'] = $value['description'];
33 $value['description'] = process_markdown(
34 $value['description'],
35 $conf->get('security.markdown_escape', true),
36 $conf->get('security.allowed_protocols')
43 * Parse feed linklist descriptions.
45 * @param array $data linklist data.
46 * @param ConfigManager $conf instance.
48 * @return mixed linklist data parsed in markdown (and converted to HTML).
50 function hook_markdown_render_feed($data, $conf)
52 foreach ($data['links'] as &$value) {
53 if (!empty($value['tags']) && noMarkdownTag($value['tags'])) {
54 $value = stripNoMarkdownTag($value);
57 $value['description'] = reverse_feed_permalink($value['description']);
58 $value['description'] = process_markdown(
59 $value['description'],
60 $conf->get('security.markdown_escape', true),
61 $conf->get('security.allowed_protocols')
69 * Parse daily descriptions.
71 * @param array $data daily data.
72 * @param ConfigManager $conf instance.
74 * @return mixed daily data parsed in markdown (and converted to HTML).
76 function hook_markdown_render_daily($data, $conf)
78 //var_dump($data);die;
79 // Manipulate columns data
80 foreach ($data['linksToDisplay'] as &$value) {
81 if (!empty($value['tags']) && noMarkdownTag($value['tags'])) {
82 $value = stripNoMarkdownTag($value);
85 $value['formatedDescription'] = process_markdown(
86 $value['formatedDescription'],
87 $conf->get('security.markdown_escape', true),
88 $conf->get('security.allowed_protocols')
96 * Check if noMarkdown is set in tags.
98 * @param string $tags tag list
100 * @return bool true if markdown should be disabled on this link.
102 function noMarkdownTag($tags)
104 return preg_match('/(^|\s)'. NO_MD_TAG
.'(\s|$)/', $tags);
108 * Remove the no-markdown meta tag so it won't be displayed.
110 * @param array $link Link data.
112 * @return array Updated link without no markdown tag.
114 function stripNoMarkdownTag($link)
116 if (! empty($link['taglist'])) {
117 $offset = array_search(NO_MD_TAG
, $link['taglist']);
118 if ($offset !== false) {
119 unset($link['taglist'][$offset]);
123 if (!empty($link['tags'])) {
124 str_replace(NO_MD_TAG
, '', $link['tags']);
131 * When link list is displayed, include markdown CSS.
133 * @param array $data includes data.
135 * @return mixed - includes data with markdown CSS file added.
137 function hook_markdown_render_includes($data)
139 if ($data['_PAGE_'] == Router
::$PAGE_LINKLIST
140 || $data['_PAGE_'] == Router
::$PAGE_DAILY
141 || $data['_PAGE_'] == Router
::$PAGE_EDITLINK
143 $data['css_files'][] = PluginManager
::$PLUGINS_PATH . '/markdown/markdown.css';
150 * Hook render_editlink.
151 * Adds an help link to markdown syntax.
153 * @param array $data data passed to plugin
155 * @return array altered $data.
157 function hook_markdown_render_editlink($data)
159 // Load help HTML into a string
160 $txt = file_get_contents(PluginManager
::$PLUGINS_PATH .'/markdown/help.html');
162 t('Description will be rendered with'),
163 t('Markdown syntax documentation'),
164 t('Markdown syntax'),
166 $data['edit_link_plugin'][] = vsprintf($txt, $translations);
167 // Add no markdown 'meta-tag' in tag list if it was never used, for autocompletion.
168 if (! in_array(NO_MD_TAG
, $data['tags'])) {
169 $data['tags'][NO_MD_TAG
] = 0;
177 * Remove HTML links auto generated by Shaarli core system.
178 * Keeps HREF attributes.
180 * @param string $description input description text.
182 * @return string $description without HTML links.
184 function reverse_text2clickable($description)
186 $descriptionLines = explode(PHP_EOL
, $description);
187 $descriptionOut = '';
188 $codeBlockOn = false;
191 foreach ($descriptionLines as $descriptionLine) {
192 // Detect line of code: starting with 4 spaces,
193 // except lists which can start with +/*/- or `2.` after spaces.
194 $codeLineOn = preg_match('/^ +(?=[^\+\*\-])(?=(?!\d\.).)/', $descriptionLine) > 0;
195 // Detect and toggle block of code
197 $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 // Make hashtag links markdown ready, otherwise the links will be ignored with escape set to true
219 if (!$codeBlockOn && !$codeLineOn) {
220 $descriptionLine = preg_replace(
221 '#<a href="([^ ]*)"'. $hashtagTitle .'>([^<]+)</a>#m',
227 $descriptionOut .= $descriptionLine;
228 if ($lineCount++
< count($descriptionLines) - 1) {
229 $descriptionOut .= PHP_EOL
;
232 return $descriptionOut;
236 * Remove <br> tag to let markdown handle it.
238 * @param string $description input description text.
240 * @return string $description without <br> tags.
242 function reverse_nl2br($description)
244 return preg_replace('!<br */?>!im', '', $description);
248 * Remove HTML spaces ' ' auto generated by Shaarli core system.
250 * @param string $description input description text.
252 * @return string $description without HTML links.
254 function reverse_space2nbsp($description)
256 return preg_replace('/(^| ) /m', '$1 ', $description);
259 function reverse_feed_permalink($description)
261 return preg_replace('@— <a href="([^"]+)" title="[^"]+">(\w+)</a>$@im', '— [$2]($1)', $description);
265 * Replace not whitelisted protocols with http:// in given description.
267 * @param string $description input description text.
268 * @param array $allowedProtocols list of allowed protocols.
270 * @return string $description without malicious link.
272 function filter_protocols($description, $allowedProtocols)
274 return preg_replace_callback(
276 function ($match) use ($allowedProtocols) {
277 return ']('. whitelist_protocols($match[1], $allowedProtocols) .')';
284 * Remove dangerous HTML tags (tags, iframe, etc.).
285 * Doesn't affect <code> content (already escaped by Parsedown).
287 * @param string $description input description text.
289 * @return string given string escaped.
291 function sanitize_html($description)
301 foreach ($escapeTags as $tag) {
302 $description = preg_replace_callback(
303 '#<\s*'. $tag .'[^>]*>(.*</\s*'. $tag .'[^>]*>)?#is',
305 return escape($match[0]);
310 $description = preg_replace(
311 '#(<[^>]+\s)on[a-z]*="?[^ "]*"?#is',
319 * Render shaare contents through Markdown parser.
320 * 1. Remove HTML generated by Shaarli core.
321 * 2. Reverse the escape function.
322 * 3. Generate markdown descriptions.
323 * 4. Sanitize sensible HTML tags for security.
324 * 5. Wrap description in 'markdown
' CSS class.
326 * @param string $description input description text.
327 * @param bool $escape escape HTML entities
329 * @return string HTML processed $description.
331 function process_markdown($description, $escape = true, $allowedProtocols = [])
333 $parsedown = new Parsedown();
335 $processedDescription = $description;
336 $processedDescription = reverse_nl2br($processedDescription);
337 $processedDescription = reverse_space2nbsp($processedDescription);
338 $processedDescription = reverse_text2clickable($processedDescription);
339 $processedDescription = filter_protocols($processedDescription, $allowedProtocols);
340 $processedDescription = unescape($processedDescription);
341 $processedDescription = $parsedown
342 ->setMarkupEscaped($escape)
343 ->setBreaksEnabled(true)
344 ->text($processedDescription);
345 $processedDescription = sanitize_html($processedDescription);
347 if (!empty($processedDescription)) {
348 $processedDescription = '<div
class="markdown">'. $processedDescription . '</div
>';
351 return $processedDescription;
355 * This function is never called, but contains translation calls for GNU gettext extraction.
357 function markdown_dummy_translation()
360 t('Render shaare description with Markdown syntax
.<br
><strong
>Warning
</strong
>:
361 If your shaared descriptions contained HTML tags before enabling the markdown plugin
,
362 enabling it might
break your page
.
363 See the
<a href
="https://github.com/shaarli/Shaarli/tree/master/plugins/markdown#html-rendering">README
</a
>.');