1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* This file is part of the league/commonmark package. |
7
|
|
|
* |
8
|
|
|
* (c) Colin O'Dell <[email protected]> |
9
|
|
|
* |
10
|
|
|
* Original code based on the CommonMark JS reference parser (https://bitly.com/commonmark-js) |
11
|
|
|
* - (c) John MacFarlane |
12
|
|
|
* |
13
|
|
|
* For the full copyright and license information, please view the LICENSE |
14
|
|
|
* file that was distributed with this source code. |
15
|
|
|
*/ |
16
|
|
|
|
17
|
|
|
namespace League\Emoji\Renderer; |
18
|
|
|
|
19
|
|
|
use League\Configuration\ConfigurationAwareInterface; |
20
|
|
|
use League\Configuration\ConfigurationInterface; |
21
|
|
|
use League\Emoji\Node\Image; |
22
|
|
|
use League\Emoji\Node\Node; |
23
|
|
|
use League\Emoji\Util\HtmlElement; |
24
|
|
|
|
25
|
|
|
final class ImageRenderer implements NodeRendererInterface, ConfigurationAwareInterface |
26
|
|
|
{ |
27
|
|
|
public const REGEX_UNSAFE_PROTOCOL = '/^javascript:|vbscript:|file:|data:/i'; |
28
|
|
|
public const REGEX_SAFE_DATA_PROTOCOL = '/^data:image\/(?:png|gif|jpeg|webp)/i'; |
29
|
|
|
|
30
|
|
|
/** |
31
|
|
|
* @var ConfigurationInterface |
32
|
|
|
* |
33
|
|
|
* @psalm-readonly-allow-private-mutation |
34
|
|
|
* @psalm-suppress PropertyNotSetInConstructor |
35
|
|
|
*/ |
36
|
|
|
private $config; |
37
|
|
|
|
38
|
|
|
/** |
39
|
|
|
* @param Node $node |
40
|
|
|
* |
41
|
|
|
* {@inheritDoc} |
42
|
|
|
*/ |
43
|
27 |
|
public function render(Node $node) |
44
|
|
|
{ |
45
|
27 |
|
if (! ($node instanceof Image)) { |
46
|
3 |
|
throw new \InvalidArgumentException('Incompatible node type: ' . \get_class($node)); |
47
|
|
|
} |
48
|
|
|
|
49
|
24 |
|
$allowUnsafeLinks = (bool) $this->config->get('allow_unsafe_links'); |
50
|
24 |
|
if (! $allowUnsafeLinks && self::isLinkPotentiallyUnsafe($node->getUrl())) { |
51
|
3 |
|
$node->setAttribute('src', ''); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
/** @var array<string, string|bool> $attributes */ |
55
|
24 |
|
$attributes = $node->getAttributes()->export(); |
56
|
|
|
|
57
|
24 |
|
return new HtmlElement('img', $attributes, '', true); |
58
|
|
|
} |
59
|
|
|
|
60
|
657 |
|
public function setConfiguration(ConfigurationInterface $configuration): void |
61
|
|
|
{ |
62
|
657 |
|
$this->config = $configuration; |
63
|
657 |
|
} |
64
|
|
|
|
65
|
|
|
/** |
66
|
|
|
* @psalm-pure |
67
|
|
|
*/ |
68
|
3 |
|
public static function isLinkPotentiallyUnsafe(string $url): bool |
69
|
|
|
{ |
70
|
3 |
|
return \preg_match(self::REGEX_UNSAFE_PROTOCOL, $url) !== 0 && \preg_match(self::REGEX_SAFE_DATA_PROTOCOL, $url) === 0; |
71
|
|
|
} |
72
|
|
|
} |
73
|
|
|
|