summaryrefslogtreecommitdiffstats
path: root/library/Icinga/Web/Helper/Markdown/LinkTransformer.php
blob: f323085d5f0e8a3134ee2cfc7cf691146f8164b4 (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
<?php
/* Icinga Web 2 | (c) 2021 Icinga GmbH | GPLv2+ */

namespace Icinga\Web\Helper\Markdown;

use HTMLPurifier_AttrTransform;
use HTMLPurifier_Config;
use ipl\Web\Url;

class LinkTransformer extends HTMLPurifier_AttrTransform
{
    /**
     * Link targets that are considered to have a thumbnail
     *
     * @var string[]
     */
    public static $IMAGE_FILES = [
        'jpg',
        'jpeg',
        'png',
        'bmp',
        'gif',
        'heif',
        'heic',
        'webp'
    ];

    public function transform($attr, $config, $context)
    {
        if (! isset($attr['href'])) {
            return $attr;
        }

        $url = Url::fromPath($attr['href']);
        $fileName = basename($url->getPath());

        $ext = null;
        if (($extAt = strrpos($fileName, '.')) !== false) {
            $ext = substr($fileName, $extAt + 1);
        }

        $hasThumbnail = $ext !== null && in_array($ext, static::$IMAGE_FILES, true);
        if ($hasThumbnail) {
            // I would have liked to not only base this off of the extension, but also by
            // whether there is an actual img tag inside the anchor. Seems not possible :(
            $attr['class'] = 'with-thumbnail';
        }

        if (! isset($attr['target'])) {
            if ($url->isExternal()) {
                $attr['target'] = '_blank';
            } else {
                $attr['data-base-target'] = '_next';
            }
        }

        return $attr;
    }

    public static function attachTo(HTMLPurifier_Config $config)
    {
        $module = $config->getHTMLDefinition(true)
            ->getAnonymousModule();

        if (isset($module->info['a'])) {
            $a = $module->info['a'];
        } else {
            $a = $module->addBlankElement('a');
        }

        $a->attr_transform_post[] = new self();
    }
}