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 = $this->tokenizeSearchHighlightField(
60 $bookmark->getDescription() ?? '',
61 $bookmark->getAdditionalContentEntry('search_highlight')['description'] ?? []
63 $processedDescription = $this->filterProtocols($processedDescription);
64 $processedDescription = $this->formatHashTags($processedDescription);
65 $processedDescription = $this->reverseEscapedHtml($processedDescription);
66 $processedDescription = $this->parsedown
67 ->setMarkupEscaped($this->escape
)
68 ->setBreaksEnabled(true)
69 ->text($processedDescription);
70 $processedDescription = $this->sanitizeHtml($processedDescription);
71 $processedDescription = $this->replaceTokens($processedDescription);
73 if (!empty($processedDescription)) {
74 $processedDescription = '<div class="markdown">'. $processedDescription . '</div>';
77 return $processedDescription;
81 * Remove the NO markdown tag if it is present
85 protected function formatTagList($bookmark)
87 $out = parent
::formatTagList($bookmark);
88 if ($this->isLoggedIn
=== false && ($pos = array_search(self
::NO_MD_TAG
, $out)) !== false) {
90 return array_values($out);
96 * Replace not whitelisted protocols with http:// in given description.
97 * Also adds `index_url` to relative links if it's specified
99 * @param string $description input description text.
101 * @return string $description without malicious link.
103 protected function filterProtocols($description)
105 $allowedProtocols = $this->allowedProtocols
;
106 $indexUrl = ! empty($this->contextData
['index_url']) ? $this->contextData
['index_url'] : '';
108 return preg_replace_callback(
110 function ($match) use ($allowedProtocols, $indexUrl) {
111 $link = startsWith($match[1], '?') || startsWith($match[1], '/') ? $indexUrl : '';
112 $link .= whitelist_protocols($match[1], $allowedProtocols);
113 return ']('. $link.')';
120 * Replace hashtag in Markdown links format
121 * E.g. `#hashtag` becomes `[#hashtag](./add-tag/hashtag)`
122 * It includes the index URL if specified.
124 * @param string $description
128 protected function formatHashTags($description)
130 $indexUrl = ! empty($this->contextData
['index_url']) ? $this->contextData
['index_url'] : '';
133 * To support unicode: http://stackoverflow.com/a/35498078/1484919
134 * \p{Pc} - to match underscore
135 * \p{N} - numeric character in any script
136 * \p{L} - letter from any language
137 * \p{Mn} - any non marking space (accents, umlauts, etc)
139 $regex = '/(^|\s)#([\p{Pc}\p{N}\p{L}\p{Mn}]+)/mui';
140 $replacement = '$1[#$2]('. $indexUrl .'./add-tag/$2)';
142 $descriptionLines = explode(PHP_EOL
, $description);
143 $descriptionOut = '';
144 $codeBlockOn = false;
147 foreach ($descriptionLines as $descriptionLine) {
148 // Detect line of code: starting with 4 spaces,
149 // except lists which can start with +/*/- or `2.` after spaces.
150 $codeLineOn = preg_match('/^ +(?=[^\+\*\-])(?=(?!\d\.).)/', $descriptionLine) > 0;
151 // Detect and toggle block of code
153 $codeBlockOn = preg_match('/^```/', $descriptionLine) > 0;
154 } elseif (preg_match('/^```/', $descriptionLine) > 0) {
155 $codeBlockOn = false;
158 if (!$codeBlockOn && !$codeLineOn) {
159 $descriptionLine = preg_replace($regex, $replacement, $descriptionLine);
162 $descriptionOut .= $descriptionLine;
163 if ($lineCount++
< count($descriptionLines) - 1) {
164 $descriptionOut .= PHP_EOL
;
168 return $descriptionOut;
172 * Remove dangerous HTML tags (tags, iframe, etc.).
173 * Doesn't affect <code> content (already escaped by Parsedown).
175 * @param string $description input description text.
177 * @return string given string escaped.
179 protected function sanitizeHtml($description)
189 foreach ($escapeTags as $tag) {
190 $description = preg_replace_callback(
191 '#<\s*'. $tag .'[^>]*>(.*</\s*'. $tag .'[^>]*>)?#is',
193 return escape($match[0]);
198 $description = preg_replace(
199 '#(<[^>]+\s)on[a-z]*="?[^ "]*"?#is',
206 protected function reverseEscapedHtml($description)
208 return unescape($description);