Subversion-Projekte lars-tiefland.laravel_shop

Revision

Revision 148 | Details | Vergleich mit vorheriger | Letzte Änderung | Log anzeigen | RSS feed

Revision Autor Zeilennr. Zeile
148 lars 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 <colinodell@gmail.com>
9
 *
10
 * For the full copyright and license information, please view the LICENSE
11
 * file that was distributed with this source code.
12
 */
13
 
14
namespace League\CommonMark\Extension\Autolink;
15
 
16
use League\CommonMark\Extension\CommonMark\Node\Inline\Link;
17
use League\CommonMark\Parser\Inline\InlineParserInterface;
18
use League\CommonMark\Parser\Inline\InlineParserMatch;
19
use League\CommonMark\Parser\InlineParserContext;
20
 
21
final class UrlAutolinkParser implements InlineParserInterface
22
{
23
    private const ALLOWED_AFTER = [null, ' ', "\t", "\n", "\x0b", "\x0c", "\x0d", '*', '_', '~', '('];
24
 
621 lars 25
    // RegEx adapted from https://github.com/symfony/symfony/blob/6.3/src/Symfony/Component/Validator/Constraints/UrlValidator.php
148 lars 26
    private const REGEX = '~
27
        (
28
            # Must start with a supported scheme + auth, or "www"
29
            (?:
621 lars 30
                (?:%s)://                                                                            # protocol
31
                (?:(?:(?:[\_\.\pL\pN-]|%%[0-9A-Fa-f]{2})+:)?((?:[\_\.\pL\pN-]|%%[0-9A-Fa-f]{2})+)@)? # basic auth
148 lars 32
            |www\.)
33
            (?:
621 lars 34
                (?:
35
                    (?:xn--[a-z0-9-]++\.)*+xn--[a-z0-9-]++            # a domain name using punycode
36
                        |
37
                    (?:[\pL\pN\pS\pM\-\_]++\.)+[\pL\pN\pM]++          # a multi-level domain name
38
                        |
39
                    [a-z0-9\-\_]++                                    # a single-level domain name
40
                )\.?
148 lars 41
                    |                                                 # or
42
                \d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}                    # an IP address
43
                    |                                                 # or
44
                \[
45
                    (?:(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){6})(?:(?:(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?:[0-9a-f]{1,4})):){0,3}(?:(?:[0-9a-f]{1,4})))?::(?:(?:[0-9a-f]{1,4})):)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,4}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:(?:(?:(?:[0-9a-f]{1,4})):(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9]))\.){3}(?:(?:25[0-5]|(?:[1-9]|1[0-9]|2[0-4])?[0-9])))))))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,5}(?:(?:[0-9a-f]{1,4})))?::)(?:(?:[0-9a-f]{1,4})))|(?:(?:(?:(?:(?:(?:[0-9a-f]{1,4})):){0,6}(?:(?:[0-9a-f]{1,4})))?::))))
46
                \]  # an IPv6 address
47
            )
48
            (?::[0-9]+)?                              # a port (optional)
621 lars 49
            (?:/ (?:[\pL\pN\-._\~!$&\'()*+,;=:@]|%%[0-9A-Fa-f]{2})* )*        # a path
50
            (?:\? (?:[\pL\pN\-._\~!$&\'\[\]()*+,;=:@/?]|%%[0-9A-Fa-f]{2})* )? # a query (optional)
51
            (?:\# (?:[\pL\pN\-._\~!$&\'()*+,;=:@/?]|%%[0-9A-Fa-f]{2})* )?     # a fragment (optional)
148 lars 52
        )~ixu';
53
 
54
    /**
55
     * @var string[]
56
     *
57
     * @psalm-readonly
58
     */
59
    private array $prefixes = ['www'];
60
 
61
    /** @psalm-readonly */
62
    private string $finalRegex;
63
 
64
    /**
65
     * @param array<int, string> $allowedProtocols
66
     */
67
    public function __construct(array $allowedProtocols = ['http', 'https', 'ftp'])
68
    {
69
        $this->finalRegex = \sprintf(self::REGEX, \implode('|', $allowedProtocols));
70
 
71
        foreach ($allowedProtocols as $protocol) {
72
            $this->prefixes[] = $protocol . '://';
73
        }
74
    }
75
 
76
    public function getMatchDefinition(): InlineParserMatch
77
    {
78
        return InlineParserMatch::oneOf(...$this->prefixes);
79
    }
80
 
81
    public function parse(InlineParserContext $inlineContext): bool
82
    {
83
        $cursor = $inlineContext->getCursor();
84
 
85
        // Autolinks can only come at the beginning of a line, after whitespace, or certain delimiting characters
86
        $previousChar = $cursor->peek(-1);
87
        if (! \in_array($previousChar, self::ALLOWED_AFTER, true)) {
88
            return false;
89
        }
90
 
91
        // Check if we have a valid URL
92
        if (! \preg_match($this->finalRegex, $cursor->getRemainder(), $matches)) {
93
            return false;
94
        }
95
 
96
        $url = $matches[0];
97
 
98
        // Does the URL end with punctuation that should be stripped?
99
        if (\preg_match('/(.+?)([?!.,:*_~]+)$/', $url, $matches)) {
100
            // Add the punctuation later
101
            $url = $matches[1];
102
        }
103
 
104
        // Does the URL end with something that looks like an entity reference?
105
        if (\preg_match('/(.+)(&[A-Za-z0-9]+;)$/', $url, $matches)) {
106
            $url = $matches[1];
107
        }
108
 
109
        // Does the URL need unmatched parens chopped off?
110
        if (\substr($url, -1) === ')' && ($diff = self::diffParens($url)) > 0) {
111
            $url = \substr($url, 0, -$diff);
112
        }
113
 
114
        $cursor->advanceBy(\mb_strlen($url, 'UTF-8'));
115
 
116
        // Auto-prefix 'http://' onto 'www' URLs
117
        if (\substr($url, 0, 4) === 'www.') {
118
            $inlineContext->getContainer()->appendChild(new Link('http://' . $url, $url));
119
 
120
            return true;
121
        }
122
 
123
        $inlineContext->getContainer()->appendChild(new Link($url, $url));
124
 
125
        return true;
126
    }
127
 
128
    /**
129
     * @psalm-pure
130
     */
131
    private static function diffParens(string $content): int
132
    {
133
        // Scan the entire autolink for the total number of parentheses.
134
        // If there is a greater number of closing parentheses than opening ones,
135
        // we don’t consider ANY of the last characters as part of the autolink,
136
        // in order to facilitate including an autolink inside a parenthesis.
137
        \preg_match_all('/[()]/', $content, $matches);
138
 
139
        $charCount = ['(' => 0, ')' => 0];
140
        foreach ($matches[0] as $char) {
141
            $charCount[$char]++;
142
        }
143
 
144
        return $charCount[')'] - $charCount['('];
145
    }
146
}