summaryrefslogtreecommitdiff
path: root/app/Services/HtmlService.php
blob: aa87e30dbfd785d8a12719800db27e818907e640 (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
<?php
/**
 * webtrees: online genealogy
 * Copyright (C) 2019 webtrees development team
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program. If not, see <http://www.gnu.org/licenses/>.
 */
declare(strict_types=1);

namespace Fisharebest\Webtrees\Services;

use HTMLPurifier;
use HTMLPurifier_AttrDef_Enum;
use HTMLPurifier_Config;

/**
 * Filter/sanitize HTML
 */
class HtmlService
{
    /**
     * Take some dirty HTML (as provided by the user), and clean it before
     * we save/display it.
     *
     * @param string $html
     *
     * @return string
     */
    public function sanitize(string $html): string
    {
        $config = HTMLPurifier_Config::createDefault();

        $config->set('Cache.DefinitionImpl', null);

        $config->set('HTML.TidyLevel', 'none'); // Only XSS cleaning now

        $def = $config->getHTMLDefinition(true);

        // Allow image maps
        $def->addAttribute('img', 'usemap', 'CDATA');

        $map = $def->addElement('map', 'Block', 'Flow', 'Common', [
            'name'  => 'CDATA',
            'id'    => 'ID',
            'title' => 'CDATA',
        ]);

        $map->excludes = ['map' => true];

        $area = $def->addElement('area', 'Block', 'Empty', 'Common', [
            'name'      => 'CDATA',
            'id'        => 'ID',
            'alt'       => 'Text',
            'coords'    => 'CDATA',
            'accesskey' => 'Character',
            'nohref'    => new HTMLPurifier_AttrDef_Enum(['nohref']),
            'href'      => 'URI',
            'shape'     => new HTMLPurifier_AttrDef_Enum(['rect', 'circle', 'poly', 'default']),
            'tabindex'  => 'Number',
            'target'    => new HTMLPurifier_AttrDef_Enum(['_blank', '_self', '_target', '_top']),
        ]);

        $area->excludes = ['area' => true];

        $purifier = new HTMLPurifier($config);

        return $purifier->purify($html);
    }
}