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