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