-
-
Notifications
You must be signed in to change notification settings - Fork 1.4k
/
Utils.php
2191 lines (1911 loc) · 63.8 KB
/
Utils.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
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
/**
* @package Grav\Common
*
* @copyright Copyright (c) 2015 - 2023 Trilby Media, LLC. All rights reserved.
* @license MIT License; see LICENSE file for details.
*/
namespace Grav\Common;
use DateTime;
use DateTimeZone;
use Exception;
use Grav\Common\Flex\Types\Pages\PageObject;
use Grav\Common\Helpers\Truncator;
use Grav\Common\Page\Interfaces\PageInterface;
use Grav\Common\Markdown\Parsedown;
use Grav\Common\Markdown\ParsedownExtra;
use Grav\Common\Page\Markdown\Excerpts;
use Grav\Common\Page\Pages;
use Grav\Framework\Flex\Flex;
use Grav\Framework\Flex\Interfaces\FlexObjectInterface;
use Grav\Framework\Media\Interfaces\MediaInterface;
use InvalidArgumentException;
use Negotiation\Accept;
use Negotiation\Negotiator;
use RocketTheme\Toolbox\Event\Event;
use RocketTheme\Toolbox\ResourceLocator\UniformResourceLocator;
use RuntimeException;
use function array_key_exists;
use function array_slice;
use function count;
use function extension_loaded;
use function function_exists;
use function in_array;
use function is_array;
use function is_callable;
use function is_string;
use function strlen;
/**
* Class Utils
* @package Grav\Common
*/
abstract class Utils
{
/** @var array */
protected static $nonces = [];
protected const ROOTURL_REGEX = '{^((?:http[s]?:\/\/[^\/]+)|(?:\/\/[^\/]+))(.*)}';
// ^((?:http[s]?:)?[\/]?(?:\/))
/**
* Simple helper method to make getting a Grav URL easier
*
* @param string|object $input
* @param bool $domain
* @param bool $fail_gracefully
* @return string|false
*/
public static function url($input, $domain = false, $fail_gracefully = false)
{
if ((!is_string($input) && !is_callable([$input, '__toString'])) || !trim($input)) {
if ($fail_gracefully) {
$input = '/';
} else {
return false;
}
}
$input = (string)$input;
if (Uri::isExternal($input)) {
return $input;
}
$grav = Grav::instance();
/** @var Uri $uri */
$uri = $grav['uri'];
$resource = false;
if (static::contains((string)$input, '://')) {
// Url contains a scheme (https:// , user:// etc).
/** @var UniformResourceLocator $locator */
$locator = $grav['locator'];
$parts = Uri::parseUrl($input);
if (is_array($parts)) {
// Make sure we always have scheme, host, port and path.
$scheme = $parts['scheme'] ?? '';
$host = $parts['host'] ?? '';
$port = $parts['port'] ?? '';
$path = $parts['path'] ?? '';
if ($scheme && !$port) {
// If URL has a scheme, we need to check if it's one of Grav streams.
if (!$locator->schemeExists($scheme)) {
// If scheme does not exists as a stream, assume it's external.
return str_replace(' ', '%20', $input);
}
// Attempt to find the resource (because of parse_url() we need to put host back to path).
$resource = $locator->findResource("{$scheme}://{$host}{$path}", false);
if ($resource === false) {
if (!$fail_gracefully) {
return false;
}
// Return location where the file would be if it was saved.
$resource = $locator->findResource("{$scheme}://{$host}{$path}", false, true);
}
} elseif ($host || $port) {
// If URL doesn't have scheme but has host or port, it is external.
return str_replace(' ', '%20', $input);
}
if (!empty($resource)) {
// Add query string back.
if (isset($parts['query'])) {
$resource .= '?' . $parts['query'];
}
// Add fragment back.
if (isset($parts['fragment'])) {
$resource .= '#' . $parts['fragment'];
}
}
} else {
// Not a valid URL (can still be a stream).
$resource = $locator->findResource($input, false);
}
} else {
// Just a path.
/** @var Pages $pages */
$pages = $grav['pages'];
// Is this a page?
$page = $pages->find($input, true);
if ($page && $page->routable()) {
return $page->url($domain);
}
$root = preg_quote($uri->rootUrl(), '#');
$pattern = '#(' . $root . '$|' . $root . '/)#';
if (!empty($root) && preg_match($pattern, $input, $matches)) {
$input = static::replaceFirstOccurrence($matches[0], '', $input);
}
$input = ltrim($input, '/');
$resource = $input;
}
if (!$fail_gracefully && $resource === false) {
return false;
}
$domain = $domain ?: $grav['config']->get('system.absolute_urls', false);
return rtrim($uri->rootUrl($domain), '/') . '/' . ($resource ?: '');
}
/**
* Helper method to find the full path to a file, be it a stream, a relative path, or
* already a full path
*
* @param string $path
* @return string
*/
public static function fullPath($path)
{
$locator = Grav::instance()['locator'];
if ($locator->isStream($path)) {
$path = $locator->findResource($path, true);
} elseif (!static::startsWith($path, GRAV_ROOT)) {
$base_url = Grav::instance()['base_url'];
$path = GRAV_ROOT . '/' . ltrim(static::replaceFirstOccurrence($base_url, '', $path), '/');
}
return $path;
}
/**
* Check if the $haystack string starts with the substring $needle
*
* @param string $haystack
* @param string|string[] $needle
* @param bool $case_sensitive
* @return bool
*/
public static function startsWith($haystack, $needle, $case_sensitive = true)
{
$status = false;
$compare_func = $case_sensitive ? 'mb_strpos' : 'mb_stripos';
foreach ((array)$needle as $each_needle) {
$status = $each_needle === '' || $compare_func($haystack, $each_needle) === 0;
if ($status) {
break;
}
}
return $status;
}
/**
* Check if the $haystack string ends with the substring $needle
*
* @param string $haystack
* @param string|string[] $needle
* @param bool $case_sensitive
* @return bool
*/
public static function endsWith($haystack, $needle, $case_sensitive = true)
{
$status = false;
$compare_func = $case_sensitive ? 'mb_strrpos' : 'mb_strripos';
foreach ((array)$needle as $each_needle) {
$expectedPosition = mb_strlen($haystack) - mb_strlen($each_needle);
$status = $each_needle === '' || $compare_func($haystack, $each_needle, 0) === $expectedPosition;
if ($status) {
break;
}
}
return $status;
}
/**
* Check if the $haystack string contains the substring $needle
*
* @param string $haystack
* @param string|string[] $needle
* @param bool $case_sensitive
* @return bool
*/
public static function contains($haystack, $needle, $case_sensitive = true)
{
$status = false;
$compare_func = $case_sensitive ? 'mb_strpos' : 'mb_stripos';
foreach ((array)$needle as $each_needle) {
$status = $each_needle === '' || $compare_func($haystack, $each_needle) !== false;
if ($status) {
break;
}
}
return $status;
}
/**
* Function that can match wildcards
*
* match_wildcard('foo*', $test), // TRUE
* match_wildcard('bar*', $test), // FALSE
* match_wildcard('*bar*', $test), // TRUE
* match_wildcard('**blob**', $test), // TRUE
* match_wildcard('*a?d*', $test), // TRUE
* match_wildcard('*etc**', $test) // TRUE
*
* @param string $wildcard_pattern
* @param string $haystack
* @return false|int
*/
public static function matchWildcard($wildcard_pattern, $haystack)
{
$regex = str_replace(
array("\*", "\?"), // wildcard chars
array('.*', '.'), // regexp chars
preg_quote($wildcard_pattern, '/')
);
return preg_match('/^' . $regex . '$/is', $haystack);
}
/**
* Render simple template filling up the variables in it. If value is not defined, leave it as it was.
*
* @param string $template Template string
* @param array $variables Variables with values
* @param array $brackets Optional array of opening and closing brackets or symbols
* @return string Final string filled with values
*/
public static function simpleTemplate(string $template, array $variables, array $brackets = ['{', '}']): string
{
$opening = $brackets[0] ?? '{';
$closing = $brackets[1] ?? '}';
$expression = '/' . preg_quote($opening, '/') . '(.*?)' . preg_quote($closing, '/') . '/';
$callback = static function ($match) use ($variables) {
return $variables[$match[1]] ?? $match[0];
};
return preg_replace_callback($expression, $callback, $template);
}
/**
* Returns the substring of a string up to a specified needle. if not found, return the whole haystack
*
* @param string $haystack
* @param string $needle
* @param bool $case_sensitive
*
* @return string
*/
public static function substrToString($haystack, $needle, $case_sensitive = true)
{
$compare_func = $case_sensitive ? 'mb_strpos' : 'mb_stripos';
if (static::contains($haystack, $needle, $case_sensitive)) {
return mb_substr($haystack, 0, $compare_func($haystack, $needle, $case_sensitive));
}
return $haystack;
}
/**
* Utility method to replace only the first occurrence in a string
*
* @param string $search
* @param string $replace
* @param string $subject
*
* @return string
*/
public static function replaceFirstOccurrence($search, $replace, $subject)
{
if (!$search) {
return $subject;
}
$pos = mb_strpos($subject, $search);
if ($pos !== false) {
$subject = static::mb_substr_replace($subject, $replace, $pos, mb_strlen($search));
}
return $subject;
}
/**
* Utility method to replace only the last occurrence in a string
*
* @param string $search
* @param string $replace
* @param string $subject
* @return string
*/
public static function replaceLastOccurrence($search, $replace, $subject)
{
$pos = strrpos($subject, $search);
if ($pos !== false) {
$subject = static::mb_substr_replace($subject, $replace, $pos, mb_strlen($search));
}
return $subject;
}
/**
* Multibyte compatible substr_replace
*
* @param string $original
* @param string $replacement
* @param int $position
* @param int $length
* @return string
*/
public static function mb_substr_replace($original, $replacement, $position, $length)
{
$startString = mb_substr($original, 0, $position, 'UTF-8');
$endString = mb_substr($original, $position + $length, mb_strlen($original), 'UTF-8');
return $startString . $replacement . $endString;
}
/**
* Merge two objects into one.
*
* @param object $obj1
* @param object $obj2
*
* @return object
*/
public static function mergeObjects($obj1, $obj2)
{
return (object)array_merge((array)$obj1, (array)$obj2);
}
/**
* @param array $array
* @return bool
*/
public static function isAssoc(array $array)
{
return (array_values($array) !== $array);
}
/**
* Lowercase an entire array. Useful when combined with `in_array()`
*
* @param array $a
* @return array|false
*/
public static function arrayLower(array $a)
{
return array_map('mb_strtolower', $a);
}
/**
* Simple function to remove item/s in an array by value
*
* @param array $search
* @param string|array $value
* @return array
*/
public static function arrayRemoveValue(array $search, $value)
{
foreach ((array)$value as $val) {
$key = array_search($val, $search);
if ($key !== false) {
unset($search[$key]);
}
}
return $search;
}
/**
* Recursive Merge with uniqueness
*
* @param array $array1
* @param array $array2
* @return array
*/
public static function arrayMergeRecursiveUnique($array1, $array2)
{
if (empty($array1)) {
// Optimize the base case
return $array2;
}
foreach ($array2 as $key => $value) {
if (is_array($value) && isset($array1[$key]) && is_array($array1[$key])) {
$value = static::arrayMergeRecursiveUnique($array1[$key], $value);
}
$array1[$key] = $value;
}
return $array1;
}
/**
* Returns an array with the differences between $array1 and $array2
*
* @param array $array1
* @param array $array2
* @return array
*/
public static function arrayDiffMultidimensional($array1, $array2)
{
$result = array();
foreach ($array1 as $key => $value) {
if (!is_array($array2) || !array_key_exists($key, $array2)) {
$result[$key] = $value;
continue;
}
if (is_array($value)) {
$recursiveArrayDiff = static::ArrayDiffMultidimensional($value, $array2[$key]);
if (count($recursiveArrayDiff)) {
$result[$key] = $recursiveArrayDiff;
}
continue;
}
if ($value != $array2[$key]) {
$result[$key] = $value;
}
}
return $result;
}
/**
* Array combine but supports different array lengths
*
* @param array $arr1
* @param array $arr2
* @return array|false
*/
public static function arrayCombine($arr1, $arr2)
{
$count = min(count($arr1), count($arr2));
return array_combine(array_slice($arr1, 0, $count), array_slice($arr2, 0, $count));
}
/**
* Array is associative or not
*
* @param array $arr
* @return bool
*/
public static function arrayIsAssociative($arr)
{
if ([] === $arr) {
return false;
}
return array_keys($arr) !== range(0, count($arr) - 1);
}
/**
* Return the Grav date formats allowed
*
* @return array
*/
public static function dateFormats()
{
$now = new DateTime();
$date_formats = [
'd-m-Y H:i' => 'd-m-Y H:i (e.g. ' . $now->format('d-m-Y H:i') . ')',
'Y-m-d H:i' => 'Y-m-d H:i (e.g. ' . $now->format('Y-m-d H:i') . ')',
'm/d/Y h:i a' => 'm/d/Y h:i a (e.g. ' . $now->format('m/d/Y h:i a') . ')',
'H:i d-m-Y' => 'H:i d-m-Y (e.g. ' . $now->format('H:i d-m-Y') . ')',
'h:i a m/d/Y' => 'h:i a m/d/Y (e.g. ' . $now->format('h:i a m/d/Y') . ')',
];
$default_format = Grav::instance()['config']->get('system.pages.dateformat.default');
if ($default_format) {
$date_formats = array_merge([$default_format => $default_format . ' (e.g. ' . $now->format($default_format) . ')'], $date_formats);
}
return $date_formats;
}
/**
* Get current date/time
*
* @param string|null $default_format
* @return string
* @throws Exception
*/
public static function dateNow($default_format = null)
{
$now = new DateTime();
if (null === $default_format) {
$default_format = Grav::instance()['config']->get('system.pages.dateformat.default');
}
return $now->format($default_format);
}
/**
* Truncate text by number of characters but can cut off words.
*
* @param string $string
* @param int $limit Max number of characters.
* @param bool $up_to_break truncate up to breakpoint after char count
* @param string $break Break point.
* @param string $pad Appended padding to the end of the string.
* @return string
*/
public static function truncate($string, $limit = 150, $up_to_break = false, $break = ' ', $pad = '…')
{
// return with no change if string is shorter than $limit
if (mb_strlen($string) <= $limit) {
return $string;
}
// is $break present between $limit and the end of the string?
if ($up_to_break && false !== ($breakpoint = mb_strpos($string, $break, $limit))) {
if ($breakpoint < mb_strlen($string) - 1) {
$string = mb_substr($string, 0, $breakpoint) . $pad;
}
} else {
$string = mb_substr($string, 0, $limit) . $pad;
}
return $string;
}
/**
* Truncate text by number of characters in a "word-safe" manor.
*
* @param string $string
* @param int $limit
* @return string
*/
public static function safeTruncate($string, $limit = 150)
{
return static::truncate($string, $limit, true);
}
/**
* Truncate HTML by number of characters. not "word-safe"!
*
* @param string $text
* @param int $length in characters
* @param string $ellipsis
* @return string
*/
public static function truncateHtml($text, $length = 100, $ellipsis = '...')
{
return Truncator::truncateLetters($text, $length, $ellipsis);
}
/**
* Truncate HTML by number of characters in a "word-safe" manor.
*
* @param string $text
* @param int $length in words
* @param string $ellipsis
* @return string
*/
public static function safeTruncateHtml($text, $length = 25, $ellipsis = '...')
{
return Truncator::truncateWords($text, $length, $ellipsis);
}
/**
* Generate a random string of a given length
*
* @param int $length
* @return string
*/
public static function generateRandomString($length = 5)
{
return substr(str_shuffle('0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'), 0, $length);
}
/**
* Generates a random string with configurable length, prefix and suffix.
* Unlike the built-in `uniqid()`, this string is non-conflicting and safe
*
* @param int $length
* @param array $options
* @return string
* @throws Exception
*/
public static function uniqueId(int $length = 13, array $options = []): string
{
$options = array_merge(['prefix' => '', 'suffix' => ''], $options);
$bytes = random_bytes(ceil($length / 2));
return $options['prefix'] . substr(bin2hex($bytes), 0, $length) . $options['suffix'];
}
/**
* Provides the ability to download a file to the browser
*
* @param string $file the full path to the file to be downloaded
* @param bool $force_download as opposed to letting browser choose if to download or render
* @param int $sec Throttling, try 0.1 for some speed throttling of downloads
* @param int $bytes Size of chunks to send in bytes. Default is 1024
* @param array $options Extra options: [mime, download_name, expires]
* @throws Exception
*/
public static function download($file, $force_download = true, $sec = 0, $bytes = 1024, array $options = [])
{
$grav = Grav::instance();
if (file_exists($file)) {
// fire download event
$grav->fireEvent('onBeforeDownload', new Event(['file' => $file, 'options' => &$options]));
$file_parts = static::pathinfo($file);
$mimetype = $options['mime'] ?? static::getMimeByExtension($file_parts['extension']);
$size = filesize($file); // File size
$grav->cleanOutputBuffers();
// required for IE, otherwise Content-Disposition may be ignored
if (ini_get('zlib.output_compression')) {
ini_set('zlib.output_compression', 'Off');
}
header('Content-Type: ' . $mimetype);
header('Accept-Ranges: bytes');
if ($force_download) {
// output the regular HTTP headers
header('Content-Disposition: attachment; filename="' . ($options['download_name'] ?? $file_parts['basename']) . '"');
}
// multipart-download and download resuming support
if (isset($_SERVER['HTTP_RANGE'])) {
[$a, $range] = explode('=', $_SERVER['HTTP_RANGE'], 2);
[$range] = explode(',', $range, 2);
[$range, $range_end] = explode('-', $range);
$range = (int)$range;
if (!$range_end) {
$range_end = $size - 1;
} else {
$range_end = (int)$range_end;
}
$new_length = $range_end - $range + 1;
header('HTTP/1.1 206 Partial Content');
header("Content-Length: {$new_length}");
header("Content-Range: bytes {$range}-{$range_end}/{$size}");
} else {
$range = 0;
$new_length = $size;
header('Content-Length: ' . $size);
if ($grav['config']->get('system.cache.enabled')) {
$expires = $options['expires'] ?? $grav['config']->get('system.pages.expires');
if ($expires > 0) {
$expires_date = gmdate('D, d M Y H:i:s T', time() + $expires);
header('Cache-Control: max-age=' . $expires);
header('Expires: ' . $expires_date);
header('Pragma: cache');
}
header('Last-Modified: ' . gmdate('D, d M Y H:i:s T', filemtime($file)));
// Return 304 Not Modified if the file is already cached in the browser
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) &&
strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($file)) {
header('HTTP/1.1 304 Not Modified');
exit();
}
}
}
/* output the file itself */
$chunksize = $bytes * 8; //you may want to change this
$bytes_send = 0;
$fp = @fopen($file, 'rb');
if ($fp) {
if ($range) {
fseek($fp, $range);
}
while (!feof($fp) && (!connection_aborted()) && ($bytes_send < $new_length)) {
$buffer = fread($fp, $chunksize);
echo($buffer); //echo($buffer); // is also possible
flush();
usleep($sec * 1000000);
$bytes_send += strlen($buffer);
}
fclose($fp);
} else {
throw new RuntimeException('Error - can not open file.');
}
exit;
}
}
/**
* Returns the output render format, usually the extension provided in the URL. (e.g. `html`, `json`, `xml`, etc).
*
* @return string
*/
public static function getPageFormat(): string
{
/** @var Uri $uri */
$uri = Grav::instance()['uri'];
// Set from uri extension
$uri_extension = $uri->extension();
if (is_string($uri_extension) && $uri->isValidExtension($uri_extension)) {
return ($uri_extension);
}
// Use content negotiation via the `accept:` header
$http_accept = $_SERVER['HTTP_ACCEPT'] ?? null;
if (is_string($http_accept)) {
$negotiator = new Negotiator();
$supported_types = static::getSupportPageTypes(['html', 'json']);
$priorities = static::getMimeTypes($supported_types);
$media_type = $negotiator->getBest($http_accept, $priorities);
$mimetype = $media_type instanceof Accept ? $media_type->getValue() : '';
return static::getExtensionByMime($mimetype);
}
return 'html';
}
/**
* Return the mimetype based on filename extension
*
* @param string $extension Extension of file (eg "txt")
* @param string $default
* @return string
*/
public static function getMimeByExtension($extension, $default = 'application/octet-stream')
{
$extension = strtolower($extension);
// look for some standard types
switch ($extension) {
case null:
return $default;
case 'json':
return 'application/json';
case 'html':
return 'text/html';
case 'atom':
return 'application/atom+xml';
case 'rss':
return 'application/rss+xml';
case 'xml':
return 'application/xml';
}
$media_types = Grav::instance()['config']->get('media.types');
return $media_types[$extension]['mime'] ?? $default;
}
/**
* Get all the mimetypes for an array of extensions
*
* @param array $extensions
* @return array
*/
public static function getMimeTypes(array $extensions)
{
$mimetypes = [];
foreach ($extensions as $extension) {
$mimetype = static::getMimeByExtension($extension, false);
if ($mimetype && !in_array($mimetype, $mimetypes)) {
$mimetypes[] = $mimetype;
}
}
return $mimetypes;
}
/**
* Return all extensions for given mimetype. The first extension is the default one.
*
* @param string $mime Mime type (eg 'image/jpeg')
* @return string[] List of extensions eg. ['jpg', 'jpe', 'jpeg']
*/
public static function getExtensionsByMime($mime)
{
$mime = strtolower($mime);
$media_types = (array)Grav::instance()['config']->get('media.types');
$list = [];
foreach ($media_types as $extension => $type) {
if ($extension === '' || $extension === 'defaults') {
continue;
}
if (isset($type['mime']) && $type['mime'] === $mime) {
$list[] = $extension;
}
}
return $list;
}
/**
* Return the mimetype based on filename extension
*
* @param string $mime mime type (eg "text/html")
* @param string $default default value
* @return string
*/
public static function getExtensionByMime($mime, $default = 'html')
{
$mime = strtolower($mime);
// look for some standard mime types
switch ($mime) {
case '*/*':
case 'text/*':
case 'text/html':
return 'html';
case 'application/json':
return 'json';
case 'application/atom+xml':
return 'atom';
case 'application/rss+xml':
return 'rss';
case 'application/xml':
return 'xml';
}
$media_types = (array)Grav::instance()['config']->get('media.types');
foreach ($media_types as $extension => $type) {
if ($extension === 'defaults') {
continue;
}
if (isset($type['mime']) && $type['mime'] === $mime) {
return $extension;
}
}
return $default;
}
/**
* Get all the extensions for an array of mimetypes
*
* @param array $mimetypes
* @return array
*/
public static function getExtensions(array $mimetypes)
{
$extensions = [];
foreach ($mimetypes as $mimetype) {
$extension = static::getExtensionByMime($mimetype, false);
if ($extension && !in_array($extension, $extensions, true)) {
$extensions[] = $extension;
}
}
return $extensions;
}
/**
* Return the mimetype based on filename
*
* @param string $filename Filename or path to file
* @param string $default default value
* @return string
*/
public static function getMimeByFilename($filename, $default = 'application/octet-stream')
{
return static::getMimeByExtension(static::pathinfo($filename, PATHINFO_EXTENSION), $default);
}
/**
* Return the mimetype based on existing local file
*
* @param string $filename Path to the file
* @param string $default
* @return string|bool
*/
public static function getMimeByLocalFile($filename, $default = 'application/octet-stream')
{
$type = false;
// For local files we can detect type by the file content.
if (!stream_is_local($filename) || !file_exists($filename)) {
return false;
}
// Prefer using finfo if it exists.
if (extension_loaded('fileinfo')) {
$finfo = finfo_open(FILEINFO_SYMLINK | FILEINFO_MIME_TYPE);
$type = finfo_file($finfo, $filename);
finfo_close($finfo);
} else {
// Fall back to use getimagesize() if it is available (not recommended, but better than nothing)
$info = @getimagesize($filename);
if ($info) {
$type = $info['mime'];
}
}
return $type ?: static::getMimeByFilename($filename, $default);
}
/**
* Returns true if filename is considered safe.
*
* @param string $filename
* @return bool
*/
public static function checkFilename($filename)
{
$dangerous_extensions = Grav::instance()['config']->get('security.uploads_dangerous_extensions', []);
$extension = static::pathinfo($filename, PATHINFO_EXTENSION);
return !(
// Empty filenames are not allowed.
!$filename
// Filename should not contain horizontal/vertical tabs, newlines, nils or back/forward slashes.
|| strtr($filename, "\t\v\n\r\0\\/", '_______') !== $filename
// Filename should not start or end with dot or space.
|| trim($filename, '. ') !== $filename
// File extension should not be part of configured dangerous extensions
|| in_array($extension, $dangerous_extensions)
);
}
/**
* Unicode-safe version of PHP’s pathinfo() function.
*
* @link https://www.php.net/manual/en/function.pathinfo.php