• Home
  • Features
  • Pricing
  • Docs
  • Announcements
  • Sign In

dg / texy / 22262497275

21 Feb 2026 07:01PM UTC coverage: 93.057% (+0.7%) from 92.367%
22262497275

push

github

dg
added CLAUDE.md

2426 of 2607 relevant lines covered (93.06%)

0.93 hits per line

Source File
Press 'n' to go to next uncovered line, 'b' for previous

96.55
/src/Texy/Modules/LinkModule.php
1
<?php declare(strict_types=1);
2

3
/**
4
 * This file is part of the Texy! (https://texy.nette.org)
5
 * Copyright (c) 2004 David Grudl (https://davidgrudl.com)
6
 */
7

8
namespace Texy\Modules;
9

10
use Texy;
11
use Texy\HandlerInvocation;
12
use Texy\LineParser;
13
use Texy\Link;
14
use Texy\Patterns;
15
use function iconv_strlen, iconv_substr, link, preg_match, str_contains, str_replace, strlen, strncasecmp, strpos, substr, trim, urlencode;
16

17

18
/**
19
 * Processes links, email addresses, and URL references.
20
 */
21
final class LinkModule extends Texy\Module
22
{
23
        /** root of relative links */
24
        public ?string $root = null;
25

26
        /** @deprecated */
27
        public ?string $imageClass = null;
28

29
        /** always use rel="nofollow" for absolute links? */
30
        public bool $forceNoFollow = false;
31

32
        /** shorten URLs to more readable form? */
33
        public bool $shorten = true;
34

35
        /** @var array<string, Link> link references */
36
        private array $references = [];
37

38
        /** @var array<string, true> */
39
        private static array $livelock;
40

41
        private static string $EMAIL;
42

43

44
        public function __construct(Texy\Texy $texy)
1✔
45
        {
46
                $this->texy = $texy;
1✔
47

48
                $texy->allowed['link/definition'] = true;
1✔
49
                $texy->addHandler('newReference', $this->solveNewReference(...));
1✔
50
                $texy->addHandler('linkReference', $this->solve(...));
1✔
51
                $texy->addHandler('linkEmail', $this->solveUrlEmail(...));
1✔
52
                $texy->addHandler('linkURL', $this->solveUrlEmail(...));
1✔
53
                $texy->addHandler('beforeParse', $this->beforeParse(...));
1✔
54

55
                // [reference]
56
                $texy->registerLinePattern(
1✔
57
                        $this->patternReference(...),
1✔
58
                        '#(\[[^\[\]\*\n' . Patterns::MARK . ']++\])#U',
1✔
59
                        'link/reference',
1✔
60
                );
61

62
                // direct url; charaters not allowed in URL <>[\]^`{|}
63
                $texy->registerLinePattern(
1✔
64
                        $this->patternUrlEmail(...),
1✔
65
                        '#(?<=^|[\s([<:\x17])(?:https?://|www\.|ftp://)[0-9.' . Patterns::CHAR . '-][/\d' . Patterns::CHAR . '+\.~%&?@=_:;\#$!,*()\x{ad}-]{1,1000}[/\d' . Patterns::CHAR . '+~?@=_\#$*]#u',
1✔
66
                        'link/url',
1✔
67
                        '#(?:https?://|www\.|ftp://)#u',
1✔
68
                );
69

70
                // direct email
71
                self::$EMAIL = '[' . Patterns::CHAR . '][0-9.+_' . Patterns::CHAR . '-]{0,63}@[0-9.+_' . Patterns::CHAR . '\x{ad}-]{1,252}\.[' . Patterns::CHAR . '\x{ad}]{2,19}';
1✔
72
                $texy->registerLinePattern(
1✔
73
                        $this->patternUrlEmail(...),
1✔
74
                        '#(?<=^|[\s([<\x17])' . self::$EMAIL . '#u',
1✔
75
                        'link/email',
1✔
76
                        '#' . self::$EMAIL . '#u',
1✔
77
                );
78
        }
1✔
79

80

81
        /**
82
         * Text pre-processing.
83
         */
84
        private function beforeParse(Texy\Texy $texy, string &$text): void
1✔
85
        {
86
                self::$livelock = [];
1✔
87

88
                // [la trine]: http://www.latrine.cz/ text odkazu .(title)[class]{style}
89
                if (!empty($texy->allowed['link/definition'])) {
1✔
90
                        $text = Texy\Regexp::replace(
1✔
91
                                $text,
1✔
92
                                '#^\[([^\[\]\#\?\*\n]{1,100})\]:\ ++(\S{1,1000})([\ \t].{1,1000})?' . Patterns::MODIFIER . '?\s*()$#mUu',
1✔
93
                                $this->patternReferenceDef(...),
1✔
94
                        );
95
                }
96
        }
1✔
97

98

99
        /**
100
         * Callback for: [la trine]: http://www.latrine.cz/ text odkazu .(title)[class]{style}.
101
         * @param  string[]  $matches
102
         */
103
        private function patternReferenceDef(array $matches): string
1✔
104
        {
105
                [, $mRef, $mLink, $mLabel, $mMod] = $matches;
1✔
106
                // [1] => [ (reference) ]
107
                // [2] => link
108
                // [3] => ...
109
                // [4] => .(title)[class]{style}
110

111
                $link = new Link($mLink);
1✔
112
                $link->label = trim($mLabel);
1✔
113
                $link->modifier->setProperties($mMod);
1✔
114
                $this->checkLink($link);
1✔
115
                $this->addReference($mRef, $link);
1✔
116
                return '';
1✔
117
        }
118

119

120
        /**
121
         * Callback for: [ref].
122
         * @param  string[]  $matches
123
         */
124
        public function patternReference(LineParser $parser, array $matches): Texy\HtmlElement|string|null
1✔
125
        {
126
                [, $mRef] = $matches;
1✔
127
                // [1] => [ref]
128

129
                $texy = $this->texy;
1✔
130
                $name = substr($mRef, 1, -1);
1✔
131
                $link = $this->getReference($name);
1✔
132

133
                if (!$link) {
1✔
134
                        return $texy->invokeAroundHandlers('newReference', $parser, [$name]);
1✔
135
                }
136

137
                $link->type = $link::BRACKET;
1✔
138

139
                if ($link->label != '') { // null or ''
1✔
140
                        // prevent circular references
141
                        assert($link->name !== null);
142
                        if (isset(self::$livelock[$link->name])) {
1✔
143
                                $content = $link->label;
×
144
                        } else {
145
                                self::$livelock[$link->name] = true;
1✔
146
                                $el = new Texy\HtmlElement;
1✔
147
                                $lineParser = new LineParser($texy, $el);
1✔
148
                                $lineParser->parse($link->label);
1✔
149
                                $content = $el->toString($texy);
1✔
150
                                unset(self::$livelock[$link->name]);
1✔
151
                        }
152
                } else {
153
                        $content = $this->textualUrl($link);
1✔
154
                        $content = $this->texy->protect($content, $texy::CONTENT_TEXTUAL);
1✔
155
                }
156

157
                return $texy->invokeAroundHandlers('linkReference', $parser, [$link, $content]);
1✔
158
        }
159

160

161
        /**
162
         * Callback for: http://davidgrudl.com david@grudl.com.
163
         * @param  string[]  $matches
164
         */
165
        public function patternUrlEmail(LineParser $parser, array $matches, string $name): Texy\HtmlElement|string|null
1✔
166
        {
167
                [$mURL] = $matches;
1✔
168
                // [0] => URL
169

170
                $link = new Link($mURL);
1✔
171
                $this->checkLink($link);
1✔
172

173
                return $this->texy->invokeAroundHandlers(
1✔
174
                        $name === 'link/email' ? 'linkEmail' : 'linkURL',
1✔
175
                        $parser,
176
                        [$link],
1✔
177
                );
178
        }
179

180

181
        /**
182
         * Adds new named reference.
183
         */
184
        public function addReference(string $name, Link $link): void
1✔
185
        {
186
                $link->name = Texy\Helpers::toLower($name);
1✔
187
                $this->references[$link->name] = $link;
1✔
188
        }
1✔
189

190

191
        /**
192
         * Returns named reference.
193
         */
194
        public function getReference(string $name): ?Link
1✔
195
        {
196
                $name = Texy\Helpers::toLower($name);
1✔
197
                if (isset($this->references[$name])) {
1✔
198
                        return clone $this->references[$name];
1✔
199

200
                } else {
201
                        $pos = strpos($name, '?');
1✔
202
                        if ($pos === false) {
1✔
203
                                $pos = strpos($name, '#');
1✔
204
                        }
205

206
                        if ($pos !== false) { // try to extract ?... #... part
1✔
207
                                $name2 = substr($name, 0, $pos);
1✔
208
                                if (isset($this->references[$name2])) {
1✔
209
                                        $link = clone $this->references[$name2];
1✔
210
                                        $link->URL .= substr($name, $pos);
1✔
211
                                        return $link;
1✔
212
                                }
213
                        }
214
                }
215

216
                return null;
1✔
217
        }
218

219

220
        public function factoryLink(string $dest, ?string $mMod, ?string $label): Link
1✔
221
        {
222
                $texy = $this->texy;
1✔
223
                $type = Link::COMMON;
1✔
224

225
                // [ref]
226
                if (strlen($dest) > 1 && $dest[0] === '[' && $dest[1] !== '*') {
1✔
227
                        $type = Link::BRACKET;
1✔
228
                        $dest = substr($dest, 1, -1);
1✔
229
                        $link = $this->getReference($dest);
1✔
230

231
                // [* image *]
232
                } elseif (strlen($dest) > 1 && $dest[0] === '[' && $dest[1] === '*') {
1✔
233
                        $type = Link::IMAGE;
1✔
234
                        $dest = trim(substr($dest, 2, -2));
1✔
235
                        $image = $texy->imageModule->getReference($dest);
1✔
236
                        if ($image) {
1✔
237
                                $link = new Link($image->linkedURL ?? $image->URL);
1✔
238
                                $link->modifier = $image->modifier;
1✔
239
                        }
240
                }
241

242
                if (empty($link)) {
1✔
243
                        $link = new Link(trim($dest));
1✔
244
                        $this->checkLink($link);
1✔
245
                }
246

247
                if (str_contains((string) $link->URL, '%s')) {
1✔
248
                        $link->URL = str_replace('%s', urlencode($texy->stringToText($label)), $link->URL);
×
249
                }
250

251
                $link->modifier->setProperties($mMod);
1✔
252
                $link->type = $type;
1✔
253
                return $link;
1✔
254
        }
255

256

257
        /**
258
         * Finish invocation.
259
         */
260
        public function solve(
1✔
261
                ?HandlerInvocation $invocation,
262
                Link $link,
263
                Texy\HtmlElement|string|null $content = null,
264
        ): Texy\HtmlElement|string|null
265
        {
266
                if ($link->URL === null) {
1✔
267
                        return $content;
1✔
268
                }
269

270
                $texy = $this->texy;
1✔
271

272
                $el = new Texy\HtmlElement('a');
1✔
273

274
                if (empty($link->modifier)) {
1✔
275
                        $nofollow = false;
×
276
                } else {
277
                        $nofollow = isset($link->modifier->classes['nofollow']);
1✔
278
                        unset($link->modifier->classes['nofollow']);
1✔
279
                        $el->attrs['href'] = null; // trick - move to front
1✔
280
                        $link->modifier->decorate($texy, $el);
1✔
281
                }
282

283
                if ($link->type === Link::IMAGE) {
1✔
284
                        // image
285
                        $el->attrs['href'] = Texy\Helpers::prependRoot($link->URL, $texy->imageModule->linkedRoot);
1✔
286
                        if ($this->imageClass) {
1✔
287
                                $el->attrs['class'] = (array) ($el->attrs['class'] ?? []);
×
288
                                $el->attrs['class'][] = $this->imageClass;
1✔
289
                        }
290
                } else {
291
                        $el->attrs['href'] = Texy\Helpers::prependRoot($link->URL, $this->root);
1✔
292

293
                        // rel="nofollow"
294
                        if ($nofollow || ($this->forceNoFollow && str_contains($el->attrs['href'], '//'))) {
1✔
295
                                $el->attrs['rel'] = 'nofollow';
1✔
296
                        }
297
                }
298

299
                if ($content !== null) {
1✔
300
                        $el->add($content);
1✔
301
                }
302

303
                $texy->summary['links'][] = $el->attrs['href'];
1✔
304

305
                return $el;
1✔
306
        }
307

308

309
        /**
310
         * Finish invocation.
311
         */
312
        private function solveUrlEmail(HandlerInvocation $invocation, Link $link): Texy\HtmlElement|string|null
1✔
313
        {
314
                $content = $this->textualUrl($link);
1✔
315
                $content = $this->texy->protect($content, Texy\Texy::CONTENT_TEXTUAL);
1✔
316
                return $this->solve(null, $link, $content);
1✔
317
        }
318

319

320
        /**
321
         * Finish invocation.
322
         */
323
        private function solveNewReference(HandlerInvocation $invocation, string $name): void
1✔
324
        {
325
                // no change
326
        }
1✔
327

328

329
        /**
330
         * Checks and corrects $URL.
331
         */
332
        private function checkLink(Link $link): void
1✔
333
        {
334
                if ($link->URL === null) {
1✔
335
                        return;
×
336
                }
337

338
                // remove soft hyphens; if not removed by Texy\Texy::process()
339
                $link->URL = str_replace("\u{AD}", '', $link->URL);
1✔
340

341
                if (strncasecmp($link->URL, 'www.', 4) === 0) {
1✔
342
                        // special supported case
343
                        $link->URL = 'http://' . $link->URL;
1✔
344

345
                } elseif (preg_match('#' . self::$EMAIL . '$#Au', $link->URL)) {
1✔
346
                        // email
347
                        $link->URL = 'mailto:' . $link->URL;
1✔
348

349
                } elseif (!$this->texy->checkURL($link->URL, Texy\Texy::FILTER_ANCHOR)) {
1✔
350
                        $link->URL = null;
1✔
351

352
                } else {
353
                        $link->URL = str_replace('&amp;', '&', $link->URL); // replace unwanted &amp;
1✔
354
                }
355
        }
1✔
356

357

358
        /**
359
         * Returns textual representation of URL.
360
         */
361
        private function textualUrl(Link $link): string
1✔
362
        {
363
                if ($this->texy->obfuscateEmail && preg_match('#^' . self::$EMAIL . '$#u', $link->raw)) { // email
1✔
364
                        return str_replace('@', '&#64;<!-- -->', $link->raw);
1✔
365
                }
366

367
                if ($this->shorten && preg_match('#^(https?://|ftp://|www\.|/)#i', $link->raw)) {
1✔
368
                        $raw = strncasecmp($link->raw, 'www.', 4) === 0
1✔
369
                                ? 'none://' . $link->raw
1✔
370
                                : $link->raw;
1✔
371

372
                        // parse_url() in PHP damages UTF-8 - use regular expression
373
                        if (!preg_match('~^(?:(?P<scheme>[a-z]+):)?(?://(?P<host>[^/?#]+))?(?P<path>(?:/|^)(?!/)[^?#]*)?(?:\?(?P<query>[^#]*))?(?:#(?P<fragment>.*))?()$~', $raw, $parts)) {
1✔
374
                                return $link->raw;
×
375
                        }
376

377
                        $res = '';
1✔
378
                        if ($parts['scheme'] !== '' && $parts['scheme'] !== 'none') {
1✔
379
                                $res .= $parts['scheme'] . '://';
1✔
380
                        }
381

382
                        if ($parts['host'] !== '') {
1✔
383
                                $res .= $parts['host'];
1✔
384
                        }
385

386
                        if ($parts['path'] !== '') {
1✔
387
                                $res .= (iconv_strlen($parts['path'], 'UTF-8') > 16 ? ("/\u{2026}" . iconv_substr($parts['path'], -12, 12, 'UTF-8')) : $parts['path']);
1✔
388
                        }
389

390
                        if ($parts['query'] !== '') {
1✔
391
                                $res .= iconv_strlen($parts['query'], 'UTF-8') > 4
1✔
392
                                        ? "?\u{2026}"
1✔
393
                                        : ('?' . $parts['query']);
1✔
394
                        } elseif ($parts['fragment'] !== '') {
1✔
395
                                $res .= iconv_strlen($parts['fragment'], 'UTF-8') > 4
1✔
396
                                        ? "#\u{2026}"
1✔
397
                                        : ('#' . $parts['fragment']);
1✔
398
                        }
399

400
                        return $res;
1✔
401
                }
402

403
                return $link->raw;
1✔
404
        }
405
}
STATUS · Troubleshooting · Open an Issue · Sales · Support · CAREERS · ENTERPRISE · START FREE · SCHEDULE DEMO
ANNOUNCEMENTS · TWITTER · TOS & SLA · Supported CI Services · What's a CI service? · Automated Testing

© 2026 Coveralls, Inc