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
|
|
|
* @var array Permitted ASCII table chars in interger format. |
26
|
|
|
*/ |
27
|
|
|
private const PERMITTED = [ |
28
|
|
|
32,48,49,50,51,52,53,54,55,56,57,65,66,67,68, |
29
|
|
|
69,70,71,72,73,74,75,76,77,78,79,80,81,82,83, |
30
|
|
|
84,85,86,87,88,89,90,97,98,99,100,101,102,103, |
31
|
|
|
104,105,106,107,108,109,110,111,112,113,114, |
32
|
|
|
115,116,117,118,119,120,121,122 |
33
|
|
|
]; |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Sanitize. |
37
|
|
|
* |
38
|
|
|
* @param mixed $value |
39
|
|
|
*/ |
40
|
18 |
|
public function sanitize(&$value): void |
41
|
|
|
{ |
42
|
18 |
|
$value = $this->htmlEscape($value); |
43
|
18 |
|
} |
44
|
|
|
|
45
|
|
|
/** |
46
|
|
|
* Return numerical part of the HTML encoding of the Unicode character. |
47
|
|
|
* |
48
|
|
|
* @param string $char |
49
|
|
|
* @return int |
50
|
|
|
*/ |
51
|
18 |
|
private function ordutf8(string $char): int |
52
|
|
|
{ |
53
|
18 |
|
$code = ord($char[0]); |
54
|
|
|
|
55
|
18 |
|
if ($code > 239) { |
56
|
5 |
|
return ((ord(substr($char, 1, 1)) - 128) * |
57
|
5 |
|
64 + ord(substr($char, 2, 1)) - 128) * |
58
|
5 |
|
64 + ord(substr($char, 3, 1)) - 128; |
59
|
|
|
} |
60
|
|
|
|
61
|
14 |
|
if ($code > 223) { |
62
|
2 |
|
return (($code - 224) * 64 + ord(substr($char, 1, 1)) - 128) * |
63
|
2 |
|
64 + ord(substr($char, 2, 1)) - 128; |
64
|
|
|
} |
65
|
|
|
|
66
|
13 |
|
if ($code > 127) { |
67
|
3 |
|
return ($code - 192) * 64 + ord(substr($char, 1, 1)) - 128; |
68
|
|
|
} |
69
|
|
|
|
70
|
10 |
|
return $code; |
71
|
|
|
} |
72
|
|
|
|
73
|
|
|
/** |
74
|
|
|
* Convert char to html entities. |
75
|
|
|
* |
76
|
|
|
* @param string $string |
77
|
|
|
* @return string |
78
|
|
|
*/ |
79
|
18 |
|
private function htmlEscape(string $string): string |
80
|
|
|
{ |
81
|
18 |
|
$chars = preg_split('//u', $string, 0, PREG_SPLIT_NO_EMPTY); |
82
|
18 |
|
$escaped = ''; |
83
|
|
|
|
84
|
18 |
|
foreach ($chars as $char) { |
85
|
18 |
|
$ord = $this->ordutf8($char); |
86
|
|
|
|
87
|
18 |
|
if (in_array($ord, self::PERMITTED)) { |
88
|
8 |
|
$escaped .= $char; |
89
|
8 |
|
continue; |
90
|
|
|
} |
91
|
|
|
|
92
|
14 |
|
$escaped .= "&#{$ord};"; |
93
|
|
|
} |
94
|
|
|
|
95
|
18 |
|
return $escaped; |
96
|
|
|
} |
97
|
|
|
} |
98
|
|
|
|