1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
declare(strict_types=1); |
4
|
|
|
|
5
|
|
|
/* |
6
|
|
|
* (c) Christian Gripp <[email protected]> |
7
|
|
|
* |
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
9
|
|
|
* file that was distributed with this source code. |
10
|
|
|
*/ |
11
|
|
|
|
12
|
|
|
namespace Core23\Twig\Extension; |
13
|
|
|
|
14
|
|
|
use Twig\Extension\AbstractExtension; |
15
|
|
|
use Twig\TwigFilter; |
16
|
|
|
|
17
|
|
|
final class UrlAutoConverterTwigExtension extends AbstractExtension |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* {@inheritdoc} |
21
|
|
|
*/ |
22
|
|
|
public function getFilters() |
23
|
|
|
{ |
24
|
|
|
return [ |
25
|
|
|
new TwigFilter('converturls', [$this, 'convertLinks'], [ |
26
|
|
|
'is_safe' => ['html'], |
27
|
|
|
]), |
28
|
|
|
]; |
29
|
|
|
} |
30
|
|
|
|
31
|
|
|
/** |
32
|
|
|
* @param string $text |
33
|
|
|
* @param array $options |
34
|
|
|
* |
35
|
|
|
* @return string |
36
|
|
|
*/ |
37
|
|
|
public function convertLinks(string $text, array $options = []): string |
38
|
|
|
{ |
39
|
|
|
$text = $this->replaceProtocol($text); |
40
|
|
|
$ret = ' '.$text; |
41
|
|
|
|
42
|
|
|
$attr = ''; |
43
|
|
|
foreach ($options as $key => $value) { |
44
|
|
|
$attr .= ' '.$key.'="'.$value.'"'; |
45
|
|
|
} |
46
|
|
|
|
47
|
|
|
// Replace Links with http:// |
48
|
|
|
$ret = (string) preg_replace("#(^|[\n ])([\\w]+?://[\\w\\#$%&~/.\\-;:=,?@\\[\\]+]*)#is", '\\1<a href="\\2"'.$attr.'>\\2</a>', $ret); |
49
|
|
|
|
50
|
|
|
// Replace Links without http:// |
51
|
|
|
$ret = (string) preg_replace("#(^|[\n ])((www|ftp)\\.[\\w\\#$%&~/.\\-;:=,?@\\[\\]+]*)#is", '\\1<a href="http://\\2"'.$attr.'>\\2</a>', $ret); |
52
|
|
|
|
53
|
|
|
// Replace Email Addresses |
54
|
|
|
$ret = (string) preg_replace("#(^|[\n ])([a-z0-9&\\-_.]+?)@([\\w\\-]+\\.([\\w\\-\\.]+\\.)*[\\w]+)#i", '\\1<a href="mailto:\\2@\\3"'.$attr.'>\\2@\\3</a>', $ret); |
55
|
|
|
|
56
|
|
|
return substr($ret, 1); |
57
|
|
|
} |
58
|
|
|
|
59
|
|
|
/** |
60
|
|
|
* @param string $text |
61
|
|
|
* |
62
|
|
|
* @return string |
63
|
|
|
* |
64
|
|
|
* @see https://bitbucket.org/kwi/urllinker/ |
65
|
|
|
*/ |
66
|
|
|
private function replaceProtocol(string $text): string |
67
|
|
|
{ |
68
|
|
|
return preg_replace('#(script|about|applet|activex|chrome):#is', '\\1:', $text) ?: ''; |
69
|
|
|
} |
70
|
|
|
} |
71
|
|
|
|