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

dg / texy / 22262381750

25 Jan 2026 11:44PM UTC coverage: 92.367% (-0.7%) from 93.057%
22262381750

push

github

dg
cs

9 of 11 new or added lines in 8 files covered. (81.82%)

161 existing lines in 23 files now uncovered.

2384 of 2581 relevant lines covered (92.37%)

0.92 hits per line

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

97.08
/src/Texy/Modules/LinkModule.php
1
<?php
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
declare(strict_types=1);
9

10
namespace Texy\Modules;
11

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

19

20
/**
21
 * Links module.
22
 */
23
final class LinkModule extends Texy\Module
24
{
25
        /** root of relative links */
26
        public ?string $root = null;
27

28
        /** linked image class */
29
        public ?string $imageClass = null;
30

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

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

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

40
        /** @var array<string, bool> */
41
        private static array $livelock;
42

43
        private static string $EMAIL;
44

45

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

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

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

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

72
                // direct email
73
                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✔
74
                $texy->registerLinePattern(
1✔
75
                        $this->patternUrlEmail(...),
1✔
76
                        '#(?<=^|[\s([<\x17])' . self::$EMAIL . '#u',
1✔
77
                        'link/email',
1✔
78
                        '#' . self::$EMAIL . '#u',
1✔
79
                );
80
        }
1✔
81

82

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

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

100

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

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

120

121
        /**
122
         * Callback for: [ref].
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
                        if (isset(self::$livelock[$link->name])) {
1✔
UNCOV
142
                                $content = $link->label;
×
143
                        } else {
144
                                self::$livelock[$link->name] = true;
1✔
145
                                $el = new Texy\HtmlElement;
1✔
146
                                $lineParser = new LineParser($texy, $el);
1✔
147
                                $lineParser->parse($link->label);
1✔
148
                                $content = $el->toString($texy);
1✔
149
                                unset(self::$livelock[$link->name]);
1✔
150
                        }
151
                } else {
152
                        $content = $this->textualUrl($link);
1✔
153
                        $content = $this->texy->protect($content, $texy::CONTENT_TEXTUAL);
1✔
154
                }
155

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

159

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

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

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

178

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

188

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

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

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

214
                return null;
1✔
215
        }
216

217

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

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

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

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

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

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

254

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

268
                $texy = $this->texy;
1✔
269

270
                $el = new Texy\HtmlElement('a');
1✔
271

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

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

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

296
                if ($content !== null) {
1✔
297
                        $el->add($content);
1✔
298
                }
299

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

302
                return $el;
1✔
303
        }
304

305

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

316

317
        /**
318
         * Finish invocation.
319
         */
320
        private function solveNewReference(HandlerInvocation $invocation, string $name)
1✔
321
        {
322
                // no change
323
        }
1✔
324

325

326
        /**
327
         * Checks and corrects $URL.
328
         */
329
        private function checkLink(Link $link): void
1✔
330
        {
331
                // remove soft hyphens; if not removed by Texy\Texy::process()
332
                $link->URL = str_replace("\u{AD}", '', $link->URL);
1✔
333

334
                if (strncasecmp($link->URL, 'www.', 4) === 0) {
1✔
335
                        // special supported case
336
                        $link->URL = 'http://' . $link->URL;
1✔
337

338
                } elseif (preg_match('#' . self::$EMAIL . '$#Au', $link->URL)) {
1✔
339
                        // email
340
                        $link->URL = 'mailto:' . $link->URL;
1✔
341

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

345
                } else {
346
                        $link->URL = str_replace('&amp;', '&', $link->URL); // replace unwanted &amp;
1✔
347
                }
348
        }
1✔
349

350

351
        /**
352
         * Returns textual representation of URL.
353
         */
354
        private function textualUrl(Link $link): string
1✔
355
        {
356
                if ($this->texy->obfuscateEmail && preg_match('#^' . self::$EMAIL . '$#u', $link->raw)) { // email
1✔
357
                        return str_replace('@', '&#64;<!-- -->', $link->raw);
1✔
358
                }
359

360
                if ($this->shorten && preg_match('#^(https?://|ftp://|www\.|/)#i', $link->raw)) {
1✔
361
                        $raw = strncasecmp($link->raw, 'www.', 4) === 0
1✔
362
                                ? 'none://' . $link->raw
1✔
363
                                : $link->raw;
1✔
364

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

370
                        $res = '';
1✔
371
                        if ($parts['scheme'] !== '' && $parts['scheme'] !== 'none') {
1✔
372
                                $res .= $parts['scheme'] . '://';
1✔
373
                        }
374

375
                        if ($parts['host'] !== '') {
1✔
376
                                $res .= $parts['host'];
1✔
377
                        }
378

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

383
                        if ($parts['query'] !== '') {
1✔
384
                                $res .= iconv_strlen($parts['query'], 'UTF-8') > 4
1✔
UNCOV
385
                                        ? "?\u{2026}"
×
386
                                        : ('?' . $parts['query']);
1✔
387
                        } elseif ($parts['fragment'] !== '') {
1✔
388
                                $res .= iconv_strlen($parts['fragment'], 'UTF-8') > 4
1✔
389
                                        ? "#\u{2026}"
1✔
390
                                        : ('#' . $parts['fragment']);
1✔
391
                        }
392

393
                        return $res;
1✔
394
                }
395

396
                return $link->raw;
1✔
397
        }
398
}
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