aboutsummaryrefslogtreecommitdiffhomepage
path: root/application/formatter/BookmarkMarkdownFormatter.php
blob: 5d244d4c92de249721f0c1c6e18ab79ba2222752 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
<?php

namespace Shaarli\Formatter;

use Shaarli\Config\ConfigManager;

/**
 * Class BookmarkMarkdownFormatter
 *
 * Format bookmark description into Markdown format.
 *
 * @package Shaarli\Formatter
 */
class BookmarkMarkdownFormatter extends BookmarkDefaultFormatter
{
    /**
     * When this tag is present in a bookmark, its description should not be processed with Markdown
     */
    const NO_MD_TAG = 'nomarkdown';

    /** @var \Parsedown instance */
    protected $parsedown;

    /** @var bool used to escape HTML in Markdown or not.
     *            It MUST be set to true for shared instance as HTML content can
     *            introduce XSS vulnerabilities.
     */
    protected $escape;

    /**
     * @var array List of allowed protocols for links inside bookmark's description.
     */
    protected $allowedProtocols;

    /**
     * LinkMarkdownFormatter constructor.
     *
     * @param ConfigManager $conf instance
     * @param bool          $isLoggedIn
     */
    public function __construct(ConfigManager $conf, bool $isLoggedIn)
    {
        parent::__construct($conf, $isLoggedIn);

        $this->parsedown = new \Parsedown();
        $this->escape = $conf->get('security.markdown_escape', true);
        $this->allowedProtocols = $conf->get('security.allowed_protocols', []);
    }

    /**
     * @inheritdoc
     */
    public function formatDescription($bookmark)
    {
        if (in_array(self::NO_MD_TAG, $bookmark->getTags())) {
            return parent::formatDescription($bookmark);
        }

        $processedDescription = $bookmark->getDescription();
        $processedDescription = $this->filterProtocols($processedDescription);
        $processedDescription = $this->formatHashTags($processedDescription);
        $processedDescription = $this->reverseEscapedHtml($processedDescription);
        $processedDescription = $this->parsedown
            ->setMarkupEscaped($this->escape)
            ->setBreaksEnabled(true)
            ->text($processedDescription);
        $processedDescription = $this->sanitizeHtml($processedDescription);

        if (!empty($processedDescription)) {
            $processedDescription = '<div class="markdown">'. $processedDescription . '</div>';
        }

        return $processedDescription;
    }

    /**
     * Remove the NO markdown tag if it is present
     *
     * @inheritdoc
     */
    protected function formatTagList($bookmark)
    {
        $out = parent::formatTagList($bookmark);
        if ($this->isLoggedIn === false && ($pos = array_search(self::NO_MD_TAG, $out)) !== false) {
            unset($out[$pos]);
            return array_values($out);
        }
        return $out;
    }

    /**
     * Replace not whitelisted protocols with http:// in given description.
     * Also adds `index_url` to relative links if it's specified
     *
     * @param string $description      input description text.
     *
     * @return string $description without malicious link.
     */
    protected function filterProtocols($description)
    {
        $allowedProtocols = $this->allowedProtocols;
        $indexUrl = ! empty($this->contextData['index_url']) ? $this->contextData['index_url'] : '';

        return preg_replace_callback(
            '#]\((.*?)\)#is',
            function ($match) use ($allowedProtocols, $indexUrl) {
                $link = startsWith($match[1], '?') || startsWith($match[1], '/') ? $indexUrl : '';
                $link .= whitelist_protocols($match[1], $allowedProtocols);
                return ']('. $link.')';
            },
            $description
        );
    }

    /**
     * Replace hashtag in Markdown links format
     * E.g. `#hashtag` becomes `[#hashtag](./add-tag/hashtag)`
     * It includes the index URL if specified.
     *
     * @param string $description
     *
     * @return string
     */
    protected function formatHashTags($description)
    {
        $indexUrl = ! empty($this->contextData['index_url']) ? $this->contextData['index_url'] : '';

        /*
         * To support unicode: http://stackoverflow.com/a/35498078/1484919
         * \p{Pc} - to match underscore
         * \p{N} - numeric character in any script
         * \p{L} - letter from any language
         * \p{Mn} - any non marking space (accents, umlauts, etc)
         */
        $regex = '/(^|\s)#([\p{Pc}\p{N}\p{L}\p{Mn}]+)/mui';
        $replacement = '$1[#$2]('. $indexUrl .'./add-tag/$2)';

        $descriptionLines = explode(PHP_EOL, $description);
        $descriptionOut = '';
        $codeBlockOn = false;
        $lineCount = 0;

        foreach ($descriptionLines as $descriptionLine) {
            // Detect line of code: starting with 4 spaces,
            // except lists which can start with +/*/- or `2.` after spaces.
            $codeLineOn = preg_match('/^    +(?=[^\+\*\-])(?=(?!\d\.).)/', $descriptionLine) > 0;
            // Detect and toggle block of code
            if (!$codeBlockOn) {
                $codeBlockOn = preg_match('/^```/', $descriptionLine) > 0;
            } elseif (preg_match('/^```/', $descriptionLine) > 0) {
                $codeBlockOn = false;
            }

            if (!$codeBlockOn && !$codeLineOn) {
                $descriptionLine = preg_replace($regex, $replacement, $descriptionLine);
            }

            $descriptionOut .= $descriptionLine;
            if ($lineCount++ < count($descriptionLines) - 1) {
                $descriptionOut .= PHP_EOL;
            }
        }

        return $descriptionOut;
    }

    /**
     * Remove dangerous HTML tags (tags, iframe, etc.).
     * Doesn't affect <code> content (already escaped by Parsedown).
     *
     * @param string $description input description text.
     *
     * @return string given string escaped.
     */
    protected function sanitizeHtml($description)
    {
        $escapeTags = array(
            'script',
            'style',
            'link',
            'iframe',
            'frameset',
            'frame',
        );
        foreach ($escapeTags as $tag) {
            $description = preg_replace_callback(
                '#<\s*'. $tag .'[^>]*>(.*</\s*'. $tag .'[^>]*>)?#is',
                function ($match) {
                    return escape($match[0]);
                },
                $description
            );
        }
        $description = preg_replace(
            '#(<[^>]+\s)on[a-z]*="?[^ "]*"?#is',
            '$1',
            $description
        );
        return $description;
    }

    protected function reverseEscapedHtml($description)
    {
        return unescape($description);
    }
}