1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
/** |
4
|
|
|
* Linna Filter |
5
|
|
|
* |
6
|
|
|
* @author Sebastian Rapetti <[email protected]> |
7
|
|
|
* @copyright (c) 2018, Sebastian Rapetti |
8
|
|
|
* @license http://opensource.org/licenses/MIT MIT License |
9
|
|
|
*/ |
10
|
|
|
declare(strict_types = 1); |
11
|
|
|
|
12
|
|
|
namespace Linna\Filter\Rules; |
13
|
|
|
|
14
|
|
|
/** |
15
|
|
|
* Return html entities. |
16
|
|
|
*/ |
17
|
|
|
class Escape |
18
|
|
|
{ |
19
|
|
|
/** |
20
|
|
|
* @var array Arguments expected. |
21
|
|
|
*/ |
22
|
|
|
private $arguments = []; |
|
|
|
|
23
|
|
|
|
24
|
|
|
/** |
25
|
|
|
* Sanitize. |
26
|
|
|
* |
27
|
|
|
* @param mixed $value |
28
|
|
|
*/ |
29
|
12 |
|
public function sanitize(&$value): void |
30
|
|
|
{ |
31
|
12 |
|
$value = $this->htmlEscape($value); |
32
|
12 |
|
} |
33
|
|
|
|
34
|
|
|
/** |
35
|
|
|
* Return numerical part of the HTML encoding of the Unicode character. |
36
|
|
|
* |
37
|
|
|
* @param string $char |
38
|
|
|
* @return int |
39
|
|
|
*/ |
40
|
12 |
|
private function ordutf8(string $char): int |
41
|
|
|
{ |
42
|
12 |
|
$code = ord(substr($char, 0, 1)); |
43
|
|
|
|
44
|
12 |
|
if ($code > 239) { |
45
|
3 |
|
return ((ord(substr($char, 1, 1)) - 128) * |
46
|
3 |
|
64 + ord(substr($char, 2, 1)) - 128) * |
47
|
3 |
|
64 + ord(substr($char, 3, 1)) - 128; |
48
|
|
|
} |
49
|
|
|
|
50
|
10 |
|
if ($code > 223) { |
51
|
2 |
|
return (($code - 224) * 64 + ord(substr($char, 1, 1)) - 128) |
52
|
2 |
|
* 64 + ord(substr($char, 2, 1)) - 128; |
53
|
|
|
} |
54
|
|
|
|
55
|
9 |
|
if ($code > 127) { |
56
|
2 |
|
return ($code - 192) * 64 + ord(substr($char, 1, 1)) - 128; |
57
|
|
|
} |
58
|
|
|
|
59
|
7 |
|
return $code; |
60
|
|
|
} |
61
|
|
|
|
62
|
|
|
/** |
63
|
|
|
* Convert char to html entities. |
64
|
|
|
* |
65
|
|
|
* @param string $string |
66
|
|
|
* @return string |
67
|
|
|
*/ |
68
|
12 |
|
private function htmlEscape(string $string): string |
69
|
|
|
{ |
70
|
12 |
|
$chars = preg_split('//u', $string, 0, PREG_SPLIT_NO_EMPTY); |
71
|
12 |
|
$escaped = ''; |
72
|
|
|
|
73
|
|
|
$permitted = [ |
74
|
12 |
|
32,48,49,50,51,52,53,54,55,56,57,65,66,67,68, |
75
|
|
|
69,70,71,72,73,74,75,76,77,78,79,80,81,82,83, |
76
|
|
|
84,85,86,87,88,89,90,97,98,99,100,101,102,103, |
77
|
|
|
104,105,106,107,108,109,110,111,112,113,114, |
78
|
|
|
115,116,117,118,119,120,121,122 |
79
|
|
|
]; |
80
|
|
|
|
81
|
12 |
|
foreach ($chars as $char) { |
82
|
12 |
|
$ord = $this->ordutf8($char); |
83
|
|
|
|
84
|
12 |
|
if (!in_array($ord, $permitted)) { |
85
|
9 |
|
$escaped .= "&#{$ord};"; |
86
|
9 |
|
continue; |
87
|
|
|
} |
88
|
|
|
|
89
|
7 |
|
$escaped .= $char; |
90
|
|
|
} |
91
|
|
|
|
92
|
12 |
|
return $escaped; |
93
|
|
|
} |
94
|
|
|
} |
95
|
|
|
|