-
-
Notifications
You must be signed in to change notification settings - Fork 109
/
Filters.php
747 lines (636 loc) · 18.9 KB
/
Filters.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
<?php
/**
* This file is part of the Latte (https://latte.nette.org)
* Copyright (c) 2008 David Grudl (https://davidgrudl.com)
*/
declare(strict_types=1);
namespace Latte\Runtime;
use Latte;
use Latte\Engine;
/**
* Template filters. Uses UTF-8 only.
* @internal
*/
class Filters
{
/** @deprecated */
public static $dateFormat = '%x';
/** @internal @var bool use XHTML syntax? */
public static $xhtml = false;
/**
* Escapes string for use everywhere inside HTML (except for comments).
* @param mixed $s plain text
* @return string HTML
*/
public static function escapeHtml($s): string
{
return htmlspecialchars((string) $s, ENT_QUOTES | ENT_HTML5 | ENT_SUBSTITUTE, 'UTF-8');
}
/**
* Escapes string for use inside HTML text.
* @param mixed $s plain text or HtmlStringable
* @return string HTML
*/
public static function escapeHtmlText($s): string
{
return $s instanceof HtmlStringable || $s instanceof \Nette\Utils\IHtmlString
? $s->__toString(true)
: htmlspecialchars((string) $s, ENT_NOQUOTES | ENT_SUBSTITUTE, 'UTF-8');
}
/**
* Escapes string for use inside HTML attribute value.
* @param mixed $s plain text
* @return string HTML
*/
public static function escapeHtmlAttr($s, bool $double = true): string
{
$double = $double && $s instanceof HtmlStringable ? false : $double;
$s = (string) $s;
if (strpos($s, '`') !== false && strpbrk($s, ' <>"\'') === false) {
$s .= ' '; // protection against innerHTML mXSS vulnerability nette/nette#1496
}
return htmlspecialchars($s, ENT_QUOTES | ENT_HTML5 | ENT_SUBSTITUTE, 'UTF-8', $double);
}
/**
* Escapes HTML for use inside HTML attribute.
* @param mixed $s HTML text
* @return string HTML
*/
public static function escapeHtmlAttrConv($s): string
{
return self::escapeHtmlAttr($s, false);
}
/**
* Escapes string for use inside HTML attribute name.
* @param string $s plain text
* @return string HTML
*/
public static function escapeHtmlAttrUnquoted($s): string
{
$s = (string) $s;
return preg_match('#^[a-z0-9:-]+$#i', $s)
? $s
: '"' . self::escapeHtmlAttr($s) . '"';
}
/**
* Escapes string for use inside HTML/XML comments.
* @param string $s plain text
* @return string HTML
*/
public static function escapeHtmlComment($s): string
{
$s = (string) $s;
if ($s && ($s[0] === '-' || $s[0] === '>' || $s[0] === '!')) {
$s = ' ' . $s;
}
$s = str_replace('--', '- - ', $s);
if (substr($s, -1) === '-') {
$s .= ' ';
}
return $s;
}
/**
* Escapes string for use everywhere inside XML (except for comments).
* @param string $s plain text
* @return string XML
*/
public static function escapeXml($s): string
{
// XML 1.0: \x09 \x0A \x0D and C1 allowed directly, C0 forbidden
// XML 1.1: \x00 forbidden directly and as a character reference,
// \x09 \x0A \x0D \x85 allowed directly, C0, C1 and \x7F allowed as character references
$s = preg_replace('#[\x00-\x08\x0B\x0C\x0E-\x1F]#', "\u{FFFD}", (string) $s);
return htmlspecialchars($s, ENT_QUOTES | ENT_XML1 | ENT_SUBSTITUTE, 'UTF-8');
}
/**
* Escapes string for use inside XML attribute name.
* @param string $s plain text
* @return string XML
*/
public static function escapeXmlAttrUnquoted($s): string
{
$s = (string) $s;
return preg_match('#^[a-z0-9:-]+$#i', $s)
? $s
: '"' . self::escapeXml($s) . '"';
}
/**
* Escapes string for use inside CSS template.
* @param string $s plain text
* @return string CSS
*/
public static function escapeCss($s): string
{
// http://www.w3.org/TR/2006/WD-CSS21-20060411/syndata.html#q6
return addcslashes((string) $s, "\x00..\x1F!\"#$%&'()*+,./:;<=>?@[\\]^`{|}~");
}
/**
* Escapes variables for use inside <script>.
* @param mixed $s plain text
* @return string JSON
*/
public static function escapeJs($s): string
{
if ($s instanceof HtmlStringable || $s instanceof \Nette\Utils\IHtmlString) {
$s = $s->__toString(true);
}
$json = json_encode($s, JSON_UNESCAPED_UNICODE);
if ($error = json_last_error()) {
throw new \RuntimeException(json_last_error_msg(), $error);
}
return str_replace([']]>', '<!'], [']]\x3E', '\x3C!'], $json);
}
/**
* Escapes string for use inside iCal template.
* @param string $s plain text
*/
public static function escapeICal($s): string
{
// https://www.ietf.org/rfc/rfc5545.txt
$s = str_replace("\r", '', (string) $s);
$s = preg_replace('#[\x00-\x08\x0B-\x1F]#', "\u{FFFD}", (string) $s);
return addcslashes($s, "\";\\,:\n");
}
/**
* Escapes CSS/JS for usage in <script> and <style>..
* @param string $s CSS/JS
* @return string HTML RAWTEXT
*/
public static function escapeHtmlRawText($s): string
{
return preg_replace('#</(script|style)#i', '<\/$1', (string) $s);
}
/**
* Converts HTML to plain text.
* @param string $s HTML
* @return string plain text
*/
public static function stripHtml(FilterInfo $info, $s): string
{
if (!in_array($info->contentType, [null, 'html', 'xhtml', 'htmlAttr', 'xhtmlAttr', 'xml', 'xmlAttr'], true)) {
trigger_error('Filter |stripHtml used with incompatible type ' . strtoupper($info->contentType), E_USER_WARNING);
}
$info->contentType = Engine::CONTENT_TEXT;
return html_entity_decode(strip_tags((string) $s), ENT_QUOTES | ENT_HTML5, 'UTF-8');
}
/**
* Removes tags from HTML (but remains HTML entites).
* @param string $s HTML
* @return string HTML
*/
public static function stripTags(FilterInfo $info, $s): string
{
if (!in_array($info->contentType, [null, 'html', 'xhtml', 'htmlAttr', 'xhtmlAttr', 'xml', 'xmlAttr'], true)) {
trigger_error('Filter |stripTags used with incompatible type ' . strtoupper($info->contentType), E_USER_WARNING);
}
return strip_tags((string) $s);
}
/**
* Converts ... to ...
*/
public static function convertTo(FilterInfo $info, string $dest, $s): string
{
$source = $info->contentType ?: Engine::CONTENT_TEXT;
if ($source === $dest) {
return $s;
} elseif ($conv = self::getConvertor($source, $dest)) {
$info->contentType = $dest;
return $conv($s);
} else {
trigger_error('Filters: unable to convert content type ' . strtoupper($source) . ' to ' . strtoupper($dest), E_USER_WARNING);
return $s;
}
}
public static function getConvertor(string $source, string $dest): ?callable
{
static $table = [
Engine::CONTENT_TEXT => [
'html' => 'escapeHtmlText', 'xhtml' => 'escapeHtmlText',
'htmlAttr' => 'escapeHtmlAttr', 'xhtmlAttr' => 'escapeHtmlAttr',
'htmlAttrJs' => 'escapeHtmlAttr', 'xhtmlAttrJs' => 'escapeHtmlAttr',
'htmlAttrCss' => 'escapeHtmlAttr', 'xhtmlAttrCss' => 'escapeHtmlAttr',
'htmlAttrUrl' => 'escapeHtmlAttr', 'xhtmlAttrUrl' => 'escapeHtmlAttr',
'htmlComment' => 'escapeHtmlComment', 'xhtmlComment' => 'escapeHtmlComment',
'xml' => 'escapeXml', 'xmlAttr' => 'escapeXml',
],
Engine::CONTENT_JS => [
'html' => 'escapeHtmlText', 'xhtml' => 'escapeHtmlText',
'htmlAttr' => 'escapeHtmlAttr', 'xhtmlAttr' => 'escapeHtmlAttr',
'htmlAttrJs' => 'escapeHtmlAttr', 'xhtmlAttrJs' => 'escapeHtmlAttr',
'htmlJs' => 'escapeHtmlRawText', 'xhtmlJs' => 'escapeHtmlRawText',
'htmlComment' => 'escapeHtmlComment', 'xhtmlComment' => 'escapeHtmlComment',
],
Engine::CONTENT_CSS => [
'html' => 'escapeHtmlText', 'xhtml' => 'escapeHtmlText',
'htmlAttr' => 'escapeHtmlAttr', 'xhtmlAttr' => 'escapeHtmlAttr',
'htmlAttrCss' => 'escapeHtmlAttr', 'xhtmlAttrCss' => 'escapeHtmlAttr',
'htmlCss' => 'escapeHtmlRawText', 'xhtmlCss' => 'escapeHtmlRawText',
'htmlComment' => 'escapeHtmlComment', 'xhtmlComment' => 'escapeHtmlComment',
],
Engine::CONTENT_HTML => [
'htmlAttr' => 'escapeHtmlAttrConv',
'htmlAttrJs' => 'escapeHtmlAttrConv',
'htmlAttrCss' => 'escapeHtmlAttrConv',
'htmlAttrUrl' => 'escapeHtmlAttrConv',
'htmlComment' => 'escapeHtmlComment',
],
Engine::CONTENT_XHTML => [
'xhtmlAttr' => 'escapeHtmlAttrConv',
'xhtmlAttrJs' => 'escapeHtmlAttrConv',
'xhtmlAttrCss' => 'escapeHtmlAttrConv',
'xhtmlAttrUrl' => 'escapeHtmlAttrConv',
'xhtmlComment' => 'escapeHtmlComment',
],
];
return isset($table[$source][$dest]) ? [self::class, $table[$source][$dest]] : null;
}
/**
* Sanitizes string for use inside href attribute.
* @param string $s plain text
* @return string plain text
*/
public static function safeUrl($s): string
{
$s = (string) $s;
return preg_match('~^(?:(?:https?|ftp)://[^@]+(?:/.*)?|(?:mailto|tel|sms):.+|[/?#].*|[^:]+)$~Di', $s) ? $s : '';
}
/**
* Replaces all repeated white spaces with a single space.
* @param string $s text|HTML
* @return string text|HTML
*/
public static function strip(FilterInfo $info, string $s): string
{
return in_array($info->contentType, [Engine::CONTENT_HTML, Engine::CONTENT_XHTML], true)
? trim(self::spacelessHtml($s))
: trim(self::spacelessText($s));
}
/**
* Replaces all repeated white spaces with a single space.
* @param string $s HTML
* @param bool $strip stripping mode
* @return string HTML
*/
public static function spacelessHtml(string $s, bool &$strip = true): string
{
return preg_replace_callback(
'#[ \t\r\n]+|<(/)?(textarea|pre|script)(?=\W)#si',
function ($m) use (&$strip) {
if (empty($m[2])) {
return $strip ? ' ' : $m[0];
} else {
$strip = !empty($m[1]);
return $m[0];
}
},
$s
);
}
/**
* Output buffering handler for spacelessHtml.
*/
public static function spacelessHtmlHandler(string $s, int $phase = null): string
{
static $strip;
$left = $right = '';
if ($phase & PHP_OUTPUT_HANDLER_START) {
$strip = true;
$tmp = ltrim($s);
$left = substr($s, 0, strlen($s) - strlen($tmp));
$s = $tmp;
}
if ($phase & PHP_OUTPUT_HANDLER_FINAL) {
$tmp = rtrim($s);
$right = substr($s, strlen($tmp));
$s = $tmp;
}
return $left . self::spacelessHtml($s, $strip) . $right;
}
/**
* Replaces all repeated white spaces with a single space.
* @return string text
*/
public static function spacelessText(string $s): string
{
return preg_replace('#[ \t\r\n]+#', ' ', $s);
}
/**
* Indents plain text or HTML the content from the left.
*/
public static function indent(FilterInfo $info, string $s, int $level = 1, string $chars = "\t"): string
{
if ($level < 1) {
// do nothing
} elseif (in_array($info->contentType, [Engine::CONTENT_HTML, Engine::CONTENT_XHTML], true)) {
$s = preg_replace_callback('#<(textarea|pre).*?</\1#si', function ($m) {
return strtr($m[0], " \t\r\n", "\x1F\x1E\x1D\x1A");
}, $s);
if (preg_last_error()) {
throw new Latte\RegexpException(null, preg_last_error());
}
$s = preg_replace('#(?:^|[\r\n]+)(?=[^\r\n])#', '$0' . str_repeat($chars, $level), $s);
$s = strtr($s, "\x1F\x1E\x1D\x1A", " \t\r\n");
} else {
$s = preg_replace('#(?:^|[\r\n]+)(?=[^\r\n])#', '$0' . str_repeat($chars, $level), $s);
}
return $s;
}
/**
* Join array of text or HTML elements with a string.
* @return string text|HTML
*/
public static function implode(array $arr, string $glue = ''): string
{
return implode($glue, $arr);
}
/**
* Repeats text.
* @return string plain text
*/
public static function repeat(FilterInfo $info, $s, int $count): string
{
return str_repeat((string) $s, $count);
}
/**
* Date/time formatting.
* @param string|int|\DateTimeInterface|\DateInterval $time
*/
public static function date($time, string $format = null): ?string
{
if ($time == null) { // intentionally ==
return null;
}
if (!isset($format)) {
$format = self::$dateFormat;
}
if ($time instanceof \DateInterval) {
return $time->format($format);
} elseif (is_numeric($time)) {
$time = new \DateTime('@' . $time);
$time->setTimeZone(new \DateTimeZone(date_default_timezone_get()));
} elseif (!$time instanceof \DateTimeInterface) {
$time = new \DateTime($time);
}
return strpos($format, '%') === false
? $time->format($format) // formats using date()
: strftime($format, $time->format('U') + 0); // formats according to locales
}
/**
* Converts to human readable file size.
* @return string plain text
*/
public static function bytes(float $bytes, int $precision = 2): string
{
$bytes = round($bytes);
$units = ['B', 'kB', 'MB', 'GB', 'TB', 'PB'];
foreach ($units as $unit) {
if (abs($bytes) < 1024 || $unit === end($units)) {
break;
}
$bytes = $bytes / 1024;
}
return round($bytes, $precision) . ' ' . $unit;
}
/**
* Performs a search and replace.
* @param string|array $search
* @param string|array $replacement
*/
public static function replace(FilterInfo $info, $subject, $search, $replacement = ''): string
{
return str_replace($search, $replacement, (string) $subject);
}
/**
* Perform a regular expression search and replace.
*/
public static function replaceRe(string $subject, string $pattern, string $replacement = ''): string
{
$res = preg_replace($pattern, $replacement, $subject);
if (preg_last_error()) {
throw new Latte\RegexpException(null, preg_last_error());
}
return $res;
}
/**
* The data: URI generator.
* @return string plain text
*/
public static function dataStream(string $data, string $type = null): string
{
if ($type === null) {
$type = finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $data);
}
return 'data:' . ($type ? "$type;" : '') . 'base64,' . base64_encode($data);
}
/**
* @param string $s plain text
*/
public static function breaklines($s): Html
{
return new Html(nl2br(htmlspecialchars((string) $s, ENT_NOQUOTES | ENT_SUBSTITUTE, 'UTF-8'), self::$xhtml));
}
/**
* Returns a part of string.
*/
public static function substring($s, int $start, int $length = null): string
{
$s = (string) $s;
if ($length === null) {
$length = self::strLength($s);
}
if (function_exists('mb_substr')) {
return mb_substr($s, $start, $length, 'UTF-8'); // MB is much faster
}
return iconv_substr($s, $start, $length, 'UTF-8');
}
/**
* Truncates string to maximal length.
* @return string plain text
*/
public static function truncate($s, $maxLen, $append = "\u{2026}"): string
{
$s = (string) $s;
if (self::strLength($s) > $maxLen) {
$maxLen = $maxLen - self::strLength($append);
if ($maxLen < 1) {
return $append;
} elseif (preg_match('#^.{1,' . $maxLen . '}(?=[\s\x00-/:-@\[-`{-~])#us', $s, $matches)) {
return $matches[0] . $append;
} else {
return self::substring($s, 0, $maxLen) . $append;
}
}
return $s;
}
/**
* Convert to lower case.
* @param string $s plain text
* @return string plain text
*/
public static function lower($s): string
{
return mb_strtolower((string) $s, 'UTF-8');
}
/**
* Convert to upper case.
* @param string $s plain text
* @return string plain text
*/
public static function upper($s): string
{
return mb_strtoupper((string) $s, 'UTF-8');
}
/**
* Convert first character to upper case.
* @param string $s plain text
* @return string plain text
*/
public static function firstUpper($s): string
{
$s = (string) $s;
return self::upper(self::substring($s, 0, 1)) . self::substring($s, 1);
}
/**
* Capitalize string.
* @param string $s plain text
* @return string plain text
*/
public static function capitalize($s): string
{
return mb_convert_case((string) $s, MB_CASE_TITLE, 'UTF-8');
}
/**
* Returns length of string or iterable.
* @param array|\Countable|\Traversable|string $val
*/
public static function length($val): int
{
if (is_array($val) || $val instanceof \Countable) {
return count($val);
} elseif ($val instanceof \Traversable) {
return iterator_count($val);
} else {
return self::strLength($val);
}
}
private static function strLength(string $s): int
{
return function_exists('mb_strlen') ? mb_strlen($s, 'UTF-8') : strlen(utf8_decode($s));
}
/**
* Strips whitespace.
* @return string
*/
public static function trim(FilterInfo $info, $s, string $charlist = " \t\n\r\0\x0B\u{A0}"): string
{
$charlist = preg_quote($charlist, '#');
$s = preg_replace('#^[' . $charlist . ']+|[' . $charlist . ']+$#Du', '', (string) $s);
if (preg_last_error()) {
throw new Latte\RegexpException(null, preg_last_error());
}
return $s;
}
/**
* Pad a string to a certain length with another string.
*/
public static function padLeft($s, int $length, string $pad = ' '): string
{
$s = (string) $s;
$length = max(0, $length - self::strLength($s));
$padLen = self::strLength($pad);
return str_repeat($pad, (int) ($length / $padLen)) . self::substring($pad, 0, $length % $padLen) . $s;
}
/**
* Pad a string to a certain length with another string.
*/
public static function padRight($s, int $length, string $pad = ' '): string
{
$s = (string) $s;
$length = max(0, $length - self::strLength($s));
$padLen = self::strLength($pad);
return $s . str_repeat($pad, (int) ($length / $padLen)) . self::substring($pad, 0, $length % $padLen);
}
/**
* Reverses string or array.
* @param string|array|\Traversable $val
*/
public static function reverse($val, bool $preserveKeys = false)
{
if (is_array($val)) {
return array_reverse($val, $preserveKeys);
} elseif ($val instanceof \Traversable) {
return array_reverse(iterator_to_array($val), $preserveKeys);
} else {
return iconv('UTF-32LE', 'UTF-8', strrev(iconv('UTF-8', 'UTF-32BE', (string) $val)));
}
}
/**
* Chunks items by returning an array of arrays with the given number of items.
* @param array|\Traversable $list
*/
public static function batch($list, int $size, $rest = null): \Generator
{
$batch = [];
foreach ($list as $key => $value) {
$batch[$key] = $value;
if (count($batch) >= $size) {
yield $batch;
$batch = [];
}
}
if ($batch) {
if ($rest !== null) {
while (count($batch) < $size) {
$batch[] = $rest;
}
}
yield $batch;
}
}
/**
* Returns element's attributes.
*/
public static function htmlAttributes($attrs): string
{
if (!is_array($attrs)) {
return '';
}
$s = '';
foreach ($attrs as $key => $value) {
if ($value === null || $value === false) {
continue;
} elseif ($value === true) {
if (static::$xhtml) {
$s .= ' ' . $key . '="' . $key . '"';
} else {
$s .= ' ' . $key;
}
continue;
} elseif (is_array($value)) {
$tmp = null;
foreach ($value as $k => $v) {
if ($v != null) { // intentionally ==, skip nulls & empty string
// composite 'style' vs. 'others'
$tmp[] = $v === true ? $k : (is_string($k) ? $k . ':' . $v : $v);
}
}
if ($tmp === null) {
continue;
}
$value = implode($key === 'style' || !strncmp($key, 'on', 2) ? ';' : ' ', $tmp);
} else {
$value = (string) $value;
}
$q = strpos($value, '"') === false ? '"' : "'";
$s .= ' ' . $key . '=' . $q
. str_replace(
['&', $q, '<'],
['&', $q === '"' ? '"' : ''', self::$xhtml ? '<' : '<'],
$value
)
. (strpos($value, '`') !== false && strpbrk($value, ' <>"\'') === false ? ' ' : '')
. $q;
}
return $s;
}
}