3 namespace Shaarli\Formatter
;
5 use Shaarli\Config\ConfigManager
;
8 * Class BookmarkMarkdownFormatter
10 * Format bookmark description into Markdown format.
12 * @package Shaarli\Formatter
14 class BookmarkMarkdownFormatter
extends BookmarkDefaultFormatter
17 * When this tag is present in a bookmark, its description should not be processed with Markdown
19 const NO_MD_TAG
= 'nomarkdown';
21 /** @var \Parsedown instance */
24 /** @var bool used to escape HTML in Markdown or not.
25 * It MUST be set to true for shared instance as HTML content can
26 * introduce XSS vulnerabilities.
31 * @var array List of allowed protocols for links inside bookmark's description.
33 protected $allowedProtocols;
36 * LinkMarkdownFormatter constructor.
38 * @param ConfigManager $conf instance
39 * @param bool $isLoggedIn
41 public function __construct(ConfigManager
$conf, bool $isLoggedIn)
43 parent
::__construct($conf, $isLoggedIn);
45 $this->parsedown
= new \
Parsedown();
46 $this->escape
= $conf->get('security.markdown_escape', true);
47 $this->allowedProtocols
= $conf->get('security.allowed_protocols', []);
53 public function formatDescription($bookmark)
55 if (in_array(self
::NO_MD_TAG
, $bookmark->getTags())) {
56 return parent
::formatDescription($bookmark);
59 $processedDescription = $bookmark->getDescription();
60 $processedDescription = $this->filterProtocols($processedDescription);
61 $processedDescription = $this->formatHashTags($processedDescription);
62 $processedDescription = $this->reverseEscapedHtml($processedDescription);
63 $processedDescription = $this->parsedown
64 ->setMarkupEscaped($this->escape
)
65 ->setBreaksEnabled(true)
66 ->text($processedDescription);
67 $processedDescription = $this->sanitizeHtml($processedDescription);
69 if (!empty($processedDescription)) {
70 $processedDescription = '<div class="markdown">'. $processedDescription . '</div>';
73 return $processedDescription;
77 * Remove the NO markdown tag if it is present
81 protected function formatTagList($bookmark)
83 $out = parent
::formatTagList($bookmark);
84 if ($this->isLoggedIn
=== false && ($pos = array_search(self
::NO_MD_TAG
, $out)) !== false) {
86 return array_values($out);
92 * Replace not whitelisted protocols with http:// in given description.
93 * Also adds `index_url` to relative links if it's specified
95 * @param string $description input description text.
97 * @return string $description without malicious link.
99 protected function filterProtocols($description)
101 $allowedProtocols = $this->allowedProtocols
;
102 $indexUrl = ! empty($this->contextData
['index_url']) ? $this->contextData
['index_url'] : '';
104 return preg_replace_callback(
106 function ($match) use ($allowedProtocols, $indexUrl) {
107 $link = startsWith($match[1], '?') || startsWith($match[1], '/') ? $indexUrl : '';
108 $link .= whitelist_protocols($match[1], $allowedProtocols);
109 return ']('. $link.')';
116 * Replace hashtag in Markdown links format
117 * E.g. `#hashtag` becomes `[#hashtag](./add-tag/hashtag)`
118 * It includes the index URL if specified.
120 * @param string $description
124 protected function formatHashTags($description)
126 $indexUrl = ! empty($this->contextData
['index_url']) ? $this->contextData
['index_url'] : '';
129 * To support unicode: http://stackoverflow.com/a/35498078/1484919
130 * \p{Pc} - to match underscore
131 * \p{N} - numeric character in any script
132 * \p{L} - letter from any language
133 * \p{Mn} - any non marking space (accents, umlauts, etc)
135 $regex = '/(^|\s)#([\p{Pc}\p{N}\p{L}\p{Mn}]+)/mui';
136 $replacement = '$1[#$2]('. $indexUrl .'./add-tag/$2)';
138 $descriptionLines = explode(PHP_EOL
, $description);
139 $descriptionOut = '';
140 $codeBlockOn = false;
143 foreach ($descriptionLines as $descriptionLine) {
144 // Detect line of code: starting with 4 spaces,
145 // except lists which can start with +/*/- or `2.` after spaces.
146 $codeLineOn = preg_match('/^ +(?=[^\+\*\-])(?=(?!\d\.).)/', $descriptionLine) > 0;
147 // Detect and toggle block of code
149 $codeBlockOn = preg_match('/^```/', $descriptionLine) > 0;
150 } elseif (preg_match('/^```/', $descriptionLine) > 0) {
151 $codeBlockOn = false;
154 if (!$codeBlockOn && !$codeLineOn) {
155 $descriptionLine = preg_replace($regex, $replacement, $descriptionLine);
158 $descriptionOut .= $descriptionLine;
159 if ($lineCount++
< count($descriptionLines) - 1) {
160 $descriptionOut .= PHP_EOL
;
164 return $descriptionOut;
168 * Remove dangerous HTML tags (tags, iframe, etc.).
169 * Doesn't affect <code> content (already escaped by Parsedown).
171 * @param string $description input description text.
173 * @return string given string escaped.
175 protected function sanitizeHtml($description)
185 foreach ($escapeTags as $tag) {
186 $description = preg_replace_callback(
187 '#<\s*'. $tag .'[^>]*>(.*</\s*'. $tag .'[^>]*>)?#is',
189 return escape($match[0]);
194 $description = preg_replace(
195 '#(<[^>]+\s)on[a-z]*="?[^ "]*"?#is',
202 protected function reverseEscapedHtml($description)
204 return unescape($description);