summaryrefslogtreecommitdiffstats
path: root/modules/doc/library/Doc/Renderer/DocSectionRenderer.php
blob: c61dfac2a19aa5fe6dc6c9035f42af479c4adb39 (plain)
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
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
<?php
/* Icinga Web 2 | (c) 2014 Icinga Development Team | GPLv2+ */

namespace Icinga\Module\Doc\Renderer;

use DOMDocument;
use DOMXPath;
use Icinga\Module\Doc\DocSection;
use Parsedown;
use RecursiveIteratorIterator;
use Icinga\Data\Tree\SimpleTree;
use Icinga\Module\Doc\Exception\ChapterNotFoundException;
use Icinga\Module\Doc\DocSectionFilterIterator;
use Icinga\Module\Doc\Search\DocSearch;
use Icinga\Module\Doc\Search\DocSearchMatch;
use Icinga\Web\Dom\DomNodeIterator;
use Icinga\Web\Url;
use Icinga\Web\View;

/**
 * Section renderer
 */
class DocSectionRenderer extends DocRenderer
{
    /**
     * Content to render
     *
     * @var array
     */
    protected $content = array();

    /**
     * Search criteria to highlight
     *
     * @var string
     */
    protected $highlightSearch;

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

    /**
     * Documentation tree
     *
     * @var SimpleTree
     */
    protected $tree;

    /**
     * Create a new section renderer
     *
     * @param   SimpleTree  $tree           The documentation tree
     * @param   string|null $chapter        If not null, the chapter to filter for
     *
     * @throws  ChapterNotFoundException    If the chapter to filter for was not found
     */
    public function __construct(SimpleTree $tree, $chapter = null)
    {
        if ($chapter !== null) {
            $filter = new DocSectionFilterIterator($tree->getIterator(), $chapter);
            if ($filter->isEmpty()) {
                throw new ChapterNotFoundException(
                    mt('doc', 'Chapter %s not found'),
                    $chapter
                );
            }
            parent::__construct(
                $filter,
                RecursiveIteratorIterator::SELF_FIRST
            );
        } else {
            parent::__construct($tree->getIterator(), RecursiveIteratorIterator::SELF_FIRST);
        }
        $this->tree = $tree;
        $this->parsedown = Parsedown::instance();
    }

    /**
     * Set the search criteria to highlight
     *
     * @param   string $highlightSearch
     *
     * @return  $this
     */
    public function setHighlightSearch($highlightSearch)
    {
        $this->highlightSearch = $highlightSearch;
        return $this;
    }

    /**
     * Get the search criteria to highlight
     *
     * @return string
     */
    public function getHighlightSearch()
    {
        return $this->highlightSearch;
    }

    /**
     * Syntax highlighting for PHP code
     *
     * @param   array $match
     *
     * @return  string
     */
    protected function highlightPhp($match)
    {
        return '<pre>' . highlight_string(htmlspecialchars_decode($match[1]), true) . '</pre>';
    }

    /**
     * Highlight search criteria
     *
     * @param   string      $html
     * @param   DocSearch   $search Search criteria
     *
     * @return  string
     */
    protected function highlightSearch($html, DocSearch $search)
    {
        $doc = new DOMDocument();
        @$doc->loadHTML($html);
        $iter = new RecursiveIteratorIterator(new DomNodeIterator($doc), RecursiveIteratorIterator::SELF_FIRST);
        foreach ($iter as $node) {
            if ($node->nodeType !== XML_TEXT_NODE
                || ($node->parentNode->nodeType === XML_ELEMENT_NODE && $node->parentNode->tagName === 'code')
            ) {
                continue;
            }
            $text = $node->nodeValue;
            if (($match = $search->search($text)) === null) {
                continue;
            }
            $matches = $match->getMatches();
            ksort($matches);
            $offset = 0;
            $fragment = $doc->createDocumentFragment();
            foreach ($matches as $position => $match) {
                    $fragment->appendChild($doc->createTextNode(substr($text, $offset, $position - $offset)));
                    $fragment->appendChild($doc->createElement('span', $match))
                        ->setAttribute('class', DocSearchMatch::HIGHLIGHT_CSS_CLASS);
                $offset = $position + strlen($match);
            }
            $fragment->appendChild($doc->createTextNode(substr($text, $offset)));
            $node->parentNode->replaceChild($fragment, $node);
        }
        // Remove <!DOCTYPE
        $doc->removeChild($doc->doctype);
        // Remove <html><body> and </body></html>
        return substr($doc->saveHTML(), 12, -15);
    }

    /**
     * Markup notes
     *
     * @param   array $match
     *
     * @return  string
     */
    protected function markupNotes($match)
    {
        $doc = new DOMDocument();
        $doc->loadHTML($match[0]);
        $xpath = new DOMXPath($doc);
        $blockquote = $xpath->query('//blockquote[1]')->item(0);
        /** @var \DOMElement $blockquote */
        if (strtolower(substr(trim($blockquote->nodeValue), 0, 5)) === 'note:') {
            $blockquote->setAttribute('class', 'note');
        }
        return $doc->saveXML($blockquote);
    }

    /**
     * Replace img src tags
     *
     * @param   $match
     *
     * @return  string
     */
    protected function replaceImg($match)
    {
        $doc = new DOMDocument();
        $doc->loadHTML($match[0]);
        $xpath = new DOMXPath($doc);
        $img = $xpath->query('//img[1]')->item(0);
        /** @var \DOMElement $img */
        $path = $this->getView()->getHelper('Url')->url(
            array_merge(
                array(
                    'image' => trim($img->getAttribute('src'))
                ),
                $this->urlParams
            ),
            $this->imageUrl,
            false,
            false
        );
        $url = $this->getView()->url($path);
        /** @var Url $url */
        $img->setAttribute('src', $url->getAbsoluteUrl());
        return substr_replace($doc->saveXML($img), '', -2, 1);  // Replace '/>' with '>'
    }

    /**
     * Replace chapter link
     *
     * @param   array $match
     *
     * @return  string
     */
    protected function replaceChapterLink($match)
    {
        if (($chapter = $this->tree->getNode($this->decodeAnchor($match['chapter']))) === null) {
            return $match[0];
        }
        /** @var DocSection $section */
        $path = $this->getView()->getHelper('Url')->url(
            array_merge(
                $this->urlParams,
                array(
                    'chapter' => $this->encodeUrlParam($chapter->getChapter()->getId())
                )
            ),
            $this->url,
            false,
            false
        );
        $url = $this->getView()->url($path);
        /** @var Url $url */
        return sprintf(
            '<a %s%shref="%s"',
            strlen($match['attribs']) ? trim($match['attribs']) . ' ' : '',
            $chapter->getNoFollow() ? 'rel="nofollow" ' : '',
            $url->getAbsoluteUrl()
        );
    }

    /**
     * Replace section link
     *
     * @param   array $match
     *
     * @return  string
     */
    protected function replaceSectionLink($match)
    {
        if (($section = $this->tree->getNode($this->decodeAnchor($match['section']))) === null) {
            return $match[0];
        }
        /** @var DocSection $section */
        $path = $this->getView()->getHelper('Url')->url(
            array_merge(
                $this->urlParams,
                array(
                    'chapter' => $this->encodeUrlParam($section->getChapter()->getId())
                )
            ),
            $this->url,
            false,
            false
        );
        $url = $this->getView()->url($path);
        /** @var Url $url */
        $url->setAnchor($this->encodeAnchor($section->getId()));
        return sprintf(
            '<a %s%shref="%s"',
            strlen($match['attribs']) ? trim($match['attribs']) . ' ' : '',
            $section->getNoFollow() ? 'rel="nofollow" ' : '',
            $url->getAbsoluteUrl()
        );
    }

    /**
     * {@inheritdoc}
     */
    public function render()
    {
        $search = null;
        if (($highlightSearch = $this->getHighlightSearch()) !== null) {
            $search = new DocSearch($highlightSearch);
        }
        foreach ($this as $section) {
            $title = $section->getTitle();
            if ($search !== null && ($match = $search->search($title)) !== null) {
                $title = $match->highlight();
            } else {
                $title = $this->getView()->escape($title);
            }
            $number = '';
            for ($i = 0; $i < $this->getDepth() + 1; ++$i) {
                if ($i > 0) {
                    $number .= '.';
                }
                $number .= $this->getSubIterator($i)->key() + 1;
            }
            $this->content[] = sprintf(
                '<a name="%1$s"></a><h%2$d>%3$s. %4$s</h%2$d>',
                static::encodeAnchor($section->getId()),
                $section->getLevel(),
                $number,
                $title
            );
            $html = $this->parsedown->text(implode('', $section->getContent()));
            if (empty($html)) {
                continue;
            }
            $html = preg_replace_callback(
                '#<pre><code class="language-php">(.*?)</code></pre>#s',
                array($this, 'highlightPhp'),
                $html
            );
            $html = preg_replace_callback(
                '/<img[^>]+>/',
                array($this, 'replaceImg'),
                $html
            );
            $html = preg_replace_callback(
                '#<blockquote>.+?</blockquote>#ms',
                array($this, 'markupNotes'),
                $html
            );
            $html = preg_replace_callback(
                '/<a\s+(?P<attribs>[^>]*?\s+)?href="(?:(?!http:\/\/)[^"#]*)#(?P<section>[^"]+)"/',
                array($this, 'replaceSectionLink'),
                $html
            );
            $html = preg_replace_callback(
                '/<a\s+(?P<attribs>[^>]*?\s+)?href="(?:\d+-)?(?P<chapter>[^\/"#]+).md"/',
                array($this, 'replaceChapterLink'),
                $html
            );
            if ($search !== null) {
                $html = $this->highlightSearch($html, $search);
            }
            $this->content[] = $html;
        }
        return implode("\n", $this->content);
    }
}