-
Notifications
You must be signed in to change notification settings - Fork 763
/
functions.general.php
4463 lines (4030 loc) · 154 KB
/
functions.general.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
/**
* General functions
*
* @copyright 2009-2016 Vanilla Forums Inc.
* @license http://www.opensource.org/licenses/gpl-2.0.php GNU GPL v2
* @package Core
* @since 2.0
*/
if (!function_exists('absoluteSource')) {
/**
* Get the full url of a source path relative to a base url.
*
* Takes a source path (ie. an image src from an html page), and an
* associated URL (ie. the page that the image appears on), and returns the
* absolute source (including url & protocol) path.
*
* @param string $SrcPath The source path to make absolute (if not absolute already).
* @param string $Url The full url to the page containing the src reference.
* @return string Absolute source path.
*/
function absoluteSource($SrcPath, $Url) {
// If there is a scheme in the srcpath already, just return it.
if (!is_null(parse_url($SrcPath, PHP_URL_SCHEME))) {
return $SrcPath;
}
// Does SrcPath assume root?
if (in_array(substr($SrcPath, 0, 1), array('/', '\\'))) {
return parse_url($Url, PHP_URL_SCHEME)
.'://'
.parse_url($Url, PHP_URL_HOST)
.$SrcPath;
}
// Work with the path in the url & the provided src path to backtrace if necessary
$UrlPathParts = explode('/', str_replace('\\', '/', parse_url($Url, PHP_URL_PATH)));
$SrcParts = explode('/', str_replace('\\', '/', $SrcPath));
$Result = array();
foreach ($SrcParts as $Part) {
if (!$Part || $Part == '.') {
continue;
}
if ($Part == '..') {
array_pop($UrlPathParts);
} else {
$Result[] = $Part;
}
}
// Put it all together & return
return parse_url($Url, PHP_URL_SCHEME)
.'://'
.parse_url($Url, PHP_URL_HOST)
.'/'.implode('/', array_filter(array_merge($UrlPathParts, $Result)));
}
}
if (!function_exists('addActivity')) {
/**
* A convenience function that allows adding to the activity table with a single line.
*
* @param int $ActivityUserID The user committing the activity.
* @param string $ActivityType The type of activity.
* @param string $Story The story section of the activity.
* @param string $RegardingUserID The user the activity is being performed on.
* @param string $Route The path of the data the activity is for.
* @param string $SendEmail Whether or not to send an email with the activity.
* @return int The ID of the new activity or zero on error.
* @deprecated
*/
function addActivity(
$ActivityUserID,
$ActivityType,
$Story = '',
$RegardingUserID = '',
$Route = '',
$SendEmail = ''
) {
$ActivityModel = new ActivityModel();
return $ActivityModel->Add($ActivityUserID, $ActivityType, $Story, $RegardingUserID, '', $Route, $SendEmail);
}
}
/**
* This file is part of the array_column library
*
* For the full copyright and license information, please view the LICENSE
* file that was distributed with this source code.
*
* @copyright Copyright (c) 2013 Ben Ramsey <http://benramsey.com>
* @license http://opensource.org/licenses/MIT MIT
*/
if (!function_exists('array_column')) {
/**
* Returns the values from a single column of the input array, identified by the $columnKey.
*
* Optionally, you may provide an $indexKey to index the values in the returned
* array by the values from the $indexKey column in the input array.
*
* @param array $input A multi-dimensional array (record set) from which to pull a column of values.
* @param mixed $columnKey The column of values to return. This value may be the integer key of the column you wish
* to retrieve, or it may be the string key name for an associative array.
* @param mixed $indexKey The column to use as the index/keys for the returned array. This value may be the integer
* key of the column, or it may be the string key name.
* @return array
*/
function array_column($input = null, $columnKey = null, $indexKey = null) {
// Using func_get_args() in order to check for proper number of
// parameters and trigger errors exactly as the built-in array_column()
// does in PHP 5.5.
$argc = func_num_args();
$params = func_get_args();
if ($argc < 2) {
trigger_error("array_column() expects at least 2 parameters, {$argc} given", E_USER_WARNING);
return null;
}
if (!is_array($params[0])) {
trigger_error(
'array_column() expects parameter 1 to be array, '.gettype($params[0]).' given',
E_USER_WARNING
);
return null;
}
if (!is_int($params[1])
&& !is_float($params[1])
&& !is_string($params[1])
&& $params[1] !== null
&& !(is_object($params[1]) && method_exists($params[1], '__toString'))
) {
trigger_error('array_column(): The column key should be either a string or an integer', E_USER_WARNING);
return false;
}
if (isset($params[2])
&& !is_int($params[2])
&& !is_float($params[2])
&& !is_string($params[2])
&& !(is_object($params[2]) && method_exists($params[2], '__toString'))
) {
trigger_error('array_column(): The index key should be either a string or an integer', E_USER_WARNING);
return false;
}
$paramsInput = $params[0];
$paramsColumnKey = ($params[1] !== null) ? (string)$params[1] : null;
$paramsIndexKey = null;
if (isset($params[2])) {
if (is_float($params[2]) || is_int($params[2])) {
$paramsIndexKey = (int)$params[2];
} else {
$paramsIndexKey = (string)$params[2];
}
}
$resultArray = array();
foreach ($paramsInput as $row) {
$key = $value = null;
$keySet = $valueSet = false;
if ($paramsIndexKey !== null && array_key_exists($paramsIndexKey, $row)) {
$keySet = true;
$key = (string)$row[$paramsIndexKey];
}
if ($paramsColumnKey === null) {
$valueSet = true;
$value = $row;
} elseif (is_array($row) && array_key_exists($paramsColumnKey, $row)) {
$valueSet = true;
$value = $row[$paramsColumnKey];
}
if ($valueSet) {
if ($keySet) {
$resultArray[$key] = $value;
} else {
$resultArray[] = $value;
}
}
}
return $resultArray;
}
}
if (!function_exists('arrayCombine')) {
/**
* PHP's array_combine has a limitation that doesn't allow array_combine to work if either of the arrays are empty.
*
* @param array $Array1 Array of keys to be used. Illegal values for key will be converted to string.
* @param array $Array2 Array of values to be used.
*/
function arrayCombine($Array1, $Array2) {
if (!is_array($Array1)) {
$Array1 = array();
}
if (!is_array($Array2)) {
$Array2 = array();
}
if (count($Array1) > 0 && count($Array2) > 0) {
return array_combine($Array1, $Array2);
} elseif (count($Array1) == 0) {
return $Array2;
} else {
return $Array1;
}
}
}
/*
We now support PHP 5.2.0 - Which should make this declaration unnecessary.
if (!function_exists('array_fill_keys')) {
function array_fill_keys($Keys, $Val) {
return array_combine($Keys,array_fill(0,count($Keys),$Val));
}
}
*/
if (!function_exists('arrayHasValue')) {
/**
* Search an array (and all arrays it contains) for a value.
*
* @param array $Array The array to search.
* @param mixed $Value The value to search for.
*/
function arrayHasValue($Array, $Value) {
if (in_array($Value, $Array)) {
return true;
} else {
foreach ($Array as $k => $v) {
if (is_array($v) && ArrayHasValue($v, $Value) === true) {
return true;
}
}
return false;
}
}
}
if (!function_exists('arrayKeyExistsI')) {
/**
* A case-insensitive array_key_exists search.
*
* @param string|int $Key The key to search for.
* @param array $Search The array to search.
* @return bool Returns true if the array contains the key or false otherwise.
* @see array_key_exists, arrayHasValue
*/
function arrayKeyExistsI($Key, $Search) {
if (is_array($Search)) {
foreach ($Search as $k => $v) {
if (strtolower($Key) == strtolower($k)) {
return true;
}
}
}
return false;
}
}
if (!function_exists('arrayInArray')) {
/**
* Check to see if an array contains another array.
*
* Searches {@link $Haystack} array for items in {@link $Needle} array. If FullMatch is true,
* all items in Needle must also be in Haystack. If FullMatch is false, only
* one-or-more items in Needle must be in Haystack.
*
* @param array $Needle The array containing items to match to Haystack.
* @param array $Haystack The array to search in for Needle items.
* @param bool $FullMatch Should all items in Needle be found in Haystack to return true?
* @deprecated
*/
function arrayInArray($Needle, $Haystack, $FullMatch = true) {
$Count = count($Needle);
$Return = $FullMatch ? true : false;
for ($i = 0; $i < $Count; ++$i) {
if ($FullMatch === true) {
if (in_array($Needle[$i], $Haystack) === false) {
$Return = false;
}
} else {
if (in_array($Needle[$i], $Haystack) === true) {
$Return = true;
break;
}
}
}
return $Return;
}
}
if (!function_exists('arraySearchI')) {
/**
* Case-insensitive version of array_search.
*
* @param array $Value The value to find in array.
* @param array $Search The array to search in for $Value.
* @return mixed Key of $Value in the $Search array.
*/
function arraySearchI($Value, $Search) {
return array_search(strtolower($Value), array_map('strtolower', $Search));
}
}
if (!function_exists('arrayTranslate')) {
/**
* Take all of the items specified in an array and make a new array with them specified by mappings.
*
* @param array $Array The input array to translate.
* @param array $Mappings The mappings to translate the array.
* @param bool $AddRemaining Whether or not to add the remaining items to the array.
* @return array
*/
function arrayTranslate($Array, $Mappings, $AddRemaining = false) {
$Array = (array)$Array;
$Result = array();
foreach ($Mappings as $Index => $Value) {
if (is_numeric($Index)) {
$Key = $Value;
$NewKey = $Value;
} else {
$Key = $Index;
$NewKey = $Value;
}
if ($NewKey === null) {
unset($Array[$Key]);
continue;
}
if (isset($Array[$Key])) {
$Result[$NewKey] = $Array[$Key];
unset($Array[$Key]);
} else {
$Result[$NewKey] = null;
}
}
if ($AddRemaining) {
foreach ($Array as $Key => $Value) {
if (!isset($Result[$Key])) {
$Result[$Key] = $Value;
}
}
}
return $Result;
}
}
if (!function_exists('arrayValue')) {
/**
* Get the value associated with a {@link $Needle} key in a {@link $Haystack} array.
*
* @param string $needle The key to look for in the $Haystack associative array.
* @param array $haystack The associative array in which to search for the $Needle key.
* @param string $default The default value to return if the requested value is not found. Default is false.
* @deprecated since 2.3
*/
function arrayValue($needle, $haystack, $default = false) {
deprecated('arrayValue', 'val');
$result = val($needle, $haystack, $default);
return $result;
}
}
if (!function_exists('arrayValueI')) {
/**
* Get the value associated with the {@link $Needle} in the {@link $Haystack}. This is a CASE-INSENSITIVE search.
*
* @param string $Needle The key to look for in the $Haystack associative array.
* @param array $Haystack The associative array in which to search for the $Needle key.
* @param mixed $Default The default value to return if the requested value is not found. Default is false.
* @return mixed Returns the value at {@link $Needle} in {@link $Haystack} or {@link $Default} if it isn't found.
*/
function arrayValueI($Needle, $Haystack, $Default = false) {
$Return = $Default;
if (is_array($Haystack)) {
foreach ($Haystack as $Key => $Value) {
if (strtolower($Needle) == strtolower($Key)) {
$Return = $Value;
break;
}
}
}
return $Return;
}
}
if (!function_exists('arrayValuesToKeys')) {
/**
* Take an array's values and apply them to a new array as both the keys and values.
*
* @param array $Array The array to combine.
* @deprecated
* @see array_combine()
*/
function arrayValuesToKeys($Array) {
return array_combine(array_values($Array), $Array);
}
}
if (!function_exists('asset')) {
/**
* Takes the path to an asset (image, js file, css file, etc) and prepends the web root.
*
* @param string $Destination The path to the asset.
* @param boolean $WithDomain Whether or not to include the domain.
* @param boolean $AddVersion Whether or not to add a cache-busting querystring parameter to the URL.
* @param string $Version Forced version, skips auto-lookup.
* @return string Returns the URL to the asset.
*/
function asset($Destination = '', $WithDomain = false, $AddVersion = false, $Version = null) {
$Destination = str_replace('\\', '/', $Destination);
if (IsUrl($Destination)) {
$Result = $Destination;
} else {
$Result = Gdn::request()->urlDomain($WithDomain).Gdn::request()->assetRoot().'/'.ltrim($Destination, '/');
}
if ($AddVersion) {
if (strpos($Result, '?') === false) {
$Result .= '?';
} else {
$Result .= '&';
}
// Figure out which version to put after the asset.
if (is_null($Version)) {
$Version = APPLICATION_VERSION;
if (preg_match('`^/([^/]+)/([^/]+)/`', $Destination, $Matches)) {
$Type = $Matches[1];
$Key = $Matches[2];
static $ThemeVersion = null;
switch ($Type) {
case 'plugins':
$PluginInfo = Gdn::pluginManager()->getPluginInfo($Key);
$Version = val('Version', $PluginInfo, $Version);
break;
case 'applications':
$AppInfo = Gdn::applicationManager()->getApplicationInfo(ucfirst($Key));
$Version = val('Version', $AppInfo, $Version);
break;
case 'themes':
if ($ThemeVersion === null) {
$ThemeInfo = Gdn::themeManager()->getThemeInfo(Theme());
if ($ThemeInfo !== false) {
$ThemeVersion = val('Version', $ThemeInfo, $Version);
} else {
$ThemeVersion = $Version;
}
}
$Version = $ThemeVersion;
break;
}
}
}
$Result .= 'v='.urlencode($Version);
}
return $Result;
}
}
if (!function_exists('attribute')) {
/**
* Takes an attribute (or array of attributes) and formats them in attribute="value" format.
*
* @param string|array $Name The attribute array or the name of the attribute.
* @param mixed $ValueOrExclude The value of the attribute or a prefix of attribute names to exclude.
* @return string Returns a string in attribute="value" format.
*/
function attribute($Name, $ValueOrExclude = '') {
$Return = '';
if (!is_array($Name)) {
$Name = array($Name => $ValueOrExclude);
$Exclude = '';
} else {
$Exclude = $ValueOrExclude;
}
foreach ($Name as $Attribute => $Val) {
if ($Exclude && StringBeginsWith($Attribute, $Exclude)) {
continue;
}
if ($Val != '' && $Attribute != 'Standard') {
$Return .= ' '.$Attribute.'="'.htmlspecialchars($Val, ENT_COMPAT, 'UTF-8').'"';
}
}
return $Return;
}
}
if (!function_exists('c')) {
/**
* Retrieves a configuration setting.
*
* @param string|bool $Name The name of the configuration setting.
* Settings in different sections are separated by dots.
* @param mixed $Default The result to return if the configuration setting is not found.
* @return mixed The configuration setting.
* @see Gdn::config()
*/
function c($Name = false, $Default = false) {
return Gdn::config($Name, $Default);
}
}
if (!function_exists('config')) {
/**
* Retrieves a configuration setting.
*
* @param string|bool $Name The name of the configuration setting.
* Settings in different sections are separated by dots.
* @param mixed $Default The result to return if the configuration setting is not found.
* @return mixed The configuration setting.
* @see Gdn::config()
*/
function config($Name = false, $Default = false) {
return Gdn::config($Name, $Default);
}
}
if (!function_exists('cTo')) {
/**
* Set a value in an deep array.
*
* @param array &$Data The array to set.
* @param string $Name A dot separated set of keys to set.
* @param mixed $Value The value to set.
* @deprecated Use {@link setvalr()}.
*/
function cTo(&$Data, $Name, $Value) {
$Name = explode('.', $Name);
$LastKey = array_pop($Name);
$Current =& $Data;
foreach ($Name as $Key) {
if (!isset($Current[$Key])) {
$Current[$Key] = array();
}
$Current =& $Current[$Key];
}
$Current[$LastKey] = $Value;
}
}
if (!function_exists('calculateNumberOfPages')) {
/**
* Calculate the total number of pages based on the total items and items per page.
*
* Based on the total number of items and the number of items per page,
* this function will calculate how many pages there are.
*
* @param int $ItemCount The total number of items.
* @param int $ItemsPerPage The number of items per page.
* @return int Returns the number of pages available.
*/
function calculateNumberOfPages($ItemCount, $ItemsPerPage) {
$TmpCount = ($ItemCount / $ItemsPerPage);
$RoundedCount = intval($TmpCount);
if ($TmpCount > 1) {
if ($TmpCount > $RoundedCount) {
$PageCount = $RoundedCount + 1;
} else {
$PageCount = $RoundedCount;
}
} else {
$PageCount = 1;
}
return $PageCount;
}
}
if (!function_exists('changeBasename')) {
/**
* Change the basename part of a filename for a given path.
*
* @param string $Path The path to alter.
* @param string $NewBasename The new basename. A %s will be replaced by the old basename.
* @return string Return {@link $Path} with the basename changed.
*/
function changeBasename($Path, $NewBasename) {
$NewBasename = str_replace('%s', '$2', $NewBasename);
$Result = preg_replace('/^(.*\/)?(.*?)(\.[^.]+)$/', '$1'.$NewBasename.'$3', $Path);
return $Result;
}
}
// Smarty
if (!function_exists('checkPermission')) {
/**
* A functional version of {@link Gdn_Session::checkPermission()}.
*
* @param string|array[string] $PermissionName The permission or permissions to check.
* @param string $Type The type of permission. Either "Category" or empty.
* @return bool Returns true if the current user has the given permission(s).
*/
function checkPermission($PermissionName, $Type = '') {
$Result = Gdn::session()->checkPermission($PermissionName, false, $Type ? 'Category' : '', $Type);
return $Result;
}
}
// Negative permission check
if (!function_exists('checkRestriction')) {
/**
* Check to see if a user **does not** have a permission.
*
* @param string|array[string] $PermissionName The permission or permissions to check.
* @return bool Returns true if the current user **does not** have the given permission(s).
*/
function checkRestriction($PermissionName) {
$Result = Gdn::session()->checkPermission($PermissionName);
$Unrestricted = Gdn::session()->checkPermission('Garden.Admin.Only');
return $Result && !$Unrestricted;
}
}
// Smarty sux
if (!function_exists('multiCheckPermission')) {
/**
* Check to see if a use has any one of a set of permissions.
*
* @param string|array[string] $PermissionName The permission or permissions to check.
* @return bool Returns true if the current user has any one of the given permission(s).
*/
function multiCheckPermission($PermissionName) {
$Result = Gdn::session()->checkPermission($PermissionName, false);
return $Result;
}
}
if (!function_exists('checkRequirements')) {
/**
* Check an addon's requirements.
*
* @param string $ItemName The name of the item checking requirements.
* @param array $RequiredItems An array of requirements.
* @param array $EnabledItems An array of currently enabled items to check against.
* @throws Gdn_UserException Throws an exception if there are missing requirements.
*/
function checkRequirements($ItemName, $RequiredItems, $EnabledItems) {
// 1. Make sure that $RequiredItems are present
if (is_array($RequiredItems)) {
$MissingRequirements = array();
foreach ($RequiredItems as $RequiredItemName => $RequiredVersion) {
if (!array_key_exists($RequiredItemName, $EnabledItems)) {
$MissingRequirements[] = "$RequiredItemName $RequiredVersion";
} elseif ($RequiredVersion && $RequiredVersion != '*') { // * means any version
// If the item exists and is enabled, check the version
$EnabledVersion = val('Version', val($RequiredItemName, $EnabledItems, array()), '');
// Compare the versions.
if (version_compare($EnabledVersion, $RequiredVersion, '<')) {
$MissingRequirements[] = "$RequiredItemName $RequiredVersion";
}
}
}
if (count($MissingRequirements) > 0) {
$Msg = sprintf(
"%s is missing the following requirement(s): %s.",
$ItemName,
implode(', ', $MissingRequirements)
);
throw new Gdn_UserException($Msg);
}
}
}
}
if (!function_exists('check_utf8')) {
/**
* Check to see if a string is UTF-8.
*
* @param string $str The string to check.
* @return bool Returns true if the string contains only valid UTF-8 characters or false otherwise.
*/
function check_utf8($str) {
$len = strlen($str);
for ($i = 0; $i < $len; $i++) {
$c = ord($str[$i]);
if ($c > 128) {
if (($c > 247)) {
return false;
} elseif ($c > 239) {
$bytes = 4;
} elseif ($c > 223) {
$bytes = 3;
} elseif ($c > 191) {
$bytes = 2;
} else {
return false;
}
if (($i + $bytes) > $len) {
return false;
}
while ($bytes > 1) {
$i++;
$b = ord($str[$i]);
if ($b < 128 || $b > 191) {
return false;
}
$bytes--;
}
}
}
return true;
}
}
if (!function_exists('combinePaths')) {
/**
* Takes an array of path parts and concatenates them using the specified delimiter.
*
* Delimiters will not be duplicated. Example: all of the
* following arrays will generate the path "/path/to/vanilla/applications/dashboard"
* array('/path/to/vanilla', 'applications/dashboard')
* array('/path/to/vanilla/', '/applications/dashboard')
* array('/path', 'to', 'vanilla', 'applications', 'dashboard')
* array('/path/', '/to/', '/vanilla/', '/applications/', '/dashboard')
*
* @param array $Paths The array of paths to concatenate.
* @param string $Delimiter The delimiter to use when concatenating. Defaults to system-defined directory separator.
* @returns string Returns the concatenated path.
*/
function combinePaths($Paths, $Delimiter = DS) {
if (is_array($Paths)) {
$MungedPath = implode($Delimiter, $Paths);
$MungedPath = str_replace(
array($Delimiter.$Delimiter.$Delimiter, $Delimiter.$Delimiter),
array($Delimiter, $Delimiter),
$MungedPath
);
return str_replace(array('http:/', 'https:/'), array('http://', 'https://'), $MungedPath);
} else {
return $Paths;
}
}
}
if (!function_exists('compareHashDigest')) {
/**
* Determine whether or not two strings are equal in a time that is independent of partial matches.
*
* This snippet prevents HMAC Timing attacks (http://codahale.com/a-lesson-in-timing-attacks/).
* Thanks to Eric Karulf (ekarulf @ github) for this fix.
*
* @param string $Digest1 The first digest to compare.
* @param string $Digest2 The second digest to compare.
* @return bool Returns true if the digests match or false otherwise.
*/
function compareHashDigest($Digest1, $Digest2) {
deprecated('compareHashDigest', 'hash_equals');
return hash_equals($Digest1, $Digest2);
}
}
if (!function_exists('concatSep')) {
/**
* Concatenate a string to another string with a separator.
*
* @param string $Sep The separator string to use between the concatenated strings.
* @param string $Str1 The first string in the concatenation chain.
* @param mixed $Str2 The second string in the concatenation chain.
* - This parameter can be an array in which case all of its elements will be concatenated.
* - If this parameter is a string then the function will look for more arguments to concatenate.
* @return string
*/
function concatSep($Sep, $Str1, $Str2) {
if (is_array($Str2)) {
$Strings = array_merge((array)$Str1, $Str2);
} else {
$Strings = func_get_args();
array_shift($Strings);
}
$Result = '';
foreach ($Strings as $String) {
if (!$String) {
continue;
}
if ($Result) {
$Result .= $Sep;
}
$Result .= $String;
}
return $Result;
}
}
if (!function_exists('ConsolidateArrayValuesByKey')) {
/**
* Return the values from a single column in the input array.
*
* Take an array of associative arrays (ie. a dataset array), a $Key, and
* merges all of the values for that key into a single array, returning it.
*
* @param array $Array The input array.
* @param string|int $Key The key to consolidate by.
* @param string|int $ValueKey An optional secondary key to use take the values for.
* @param mixed $DefaultValue The value to use if there is no {@link $ValueKey} in the array.
* @deprecated Use {@link array_column()} instead.
*/
function consolidateArrayValuesByKey($Array, $Key, $ValueKey = '', $DefaultValue = null) {
$Return = array();
foreach ($Array as $Index => $AssociativeArray) {
if (is_object($AssociativeArray)) {
if ($ValueKey === '') {
$Return[] = $AssociativeArray->$Key;
} elseif (property_exists($AssociativeArray, $ValueKey)) {
$Return[$AssociativeArray->$Key] = $AssociativeArray->$ValueKey;
} else {
$Return[$AssociativeArray->$Key] = $DefaultValue;
}
} elseif (is_array($AssociativeArray) && array_key_exists($Key, $AssociativeArray)) {
if ($ValueKey === '') {
$Return[] = $AssociativeArray[$Key];
} elseif (array_key_exists($ValueKey, $AssociativeArray)) {
$Return[$AssociativeArray[$Key]] = $AssociativeArray[$ValueKey];
} else {
$Return[$AssociativeArray[$Key]] = $DefaultValue;
}
}
}
return $Return;
}
}
if (!function_exists('safePrint')) {
/**
* Return/print human-readable and non casted information about a variable.
*
* @param mixed $mixed The variable to return/echo.
* @param bool $returnData Whether or not return the data instead of echoing it.
* @return string|void Returns {@link $mixed} or nothing if {@link $returnData} is false.
*/
function safePrint($mixed, $returnData = false) {
$functionName = __FUNCTION__;
$replaceCastedValues = function (&$value) use (&$replaceCastedValues, $functionName) {
$isObject = is_object($value);
// Replace original object by a shallow copy of itself to keep it from being modified.
if ($isObject) {
$value = clone $value;
}
if ($isObject || is_array($value)) {
foreach ($value as &$content) {
$replaceCastedValues($content);
}
unset($content);
return;
}
if ($value === '') {
$value = $functionName.'{empty string}';
} elseif ($value === true) {
$value = $functionName.'{true}';
} elseif ($value === false) {
$value = $functionName.'{false}';
} elseif ($value === null) {
$value = $functionName.'{null}';
} elseif ($value === 0) {
$value = $functionName.'{0}';
}
};
$replaceCastedValues($mixed);
return print_r($mixed, $returnData);
}
}
if (!function_exists('decho')) {
/**
* Echo debug messages and variables.
*
* @param mixed $mixed The variable to echo.
* @param string $prefix The text to be used as a prefix for the output.
* @param bool $public Whether or not output is visible for everyone.
*/
function decho($mixed, $prefix = 'DEBUG', $public = false) {
$prefix = stringEndsWith($prefix, ': ', true, true).': ';
if ($public || Gdn::session()->checkPermission('Garden.Debug.Allow')) {
$stack = debug_backtrace();
$backtrace = 'Line '.$stack[0]['line'].' in '.$stack[0]['file']."\n";
if (defined('PATH_ROOT')) {
$backtrace = str_replace(PATH_ROOT, '', $backtrace);
}
echo '<pre style="text-align: left; padding: 0 4px;">'.$backtrace.$prefix;
if (is_string($mixed)) {
echo $mixed;
} else {
echo htmlspecialchars(safePrint($mixed, true));
}
echo '</pre>';
}
}
}
if (!function_exists('dateCompare')) {
/**
* Compare two dates.
*
* This function compares two dates in a way that is similar to {@link strcmp()}.
*
* @param int|string $Date1 A timestamp or string representation of a date.
* @param int|string $Date2 A timestamp or string representation of a date.
* @return int Returns < 0 if {@link $Date1} is less than {@link $Date2}; > 0 if {@link $Date1} is greater than
* {@link $Date2}, and 0 if they are equal.
* @since 2.1
*/
function dateCompare($Date1, $Date2) {
if (!is_numeric($Date1)) {
$Date1 = strtotime($Date1);
}
if (!is_numeric($Date2)) {
$Date2 = strtotime($Date2);
}
if ($Date1 == $Date2) {
return 0;
}
if ($Date1 > $Date2) {
return 1;
}
return -1;
}
}
if (!function_exists('debug')) {
/**
* Get or set the current debug state of the application.
*
* @param bool|null $value The new debug value or null to just return the current value.
* @return bool Returns the current debug level.
*/
function debug($value = null) {
static $Debug = false;
if ($value === null) {
return $Debug;
}
$Changed = $Debug != $value;
$Debug = $value;
if ($Debug) {
Logger::logLevel(Logger::DEBUG);
} else {
if ($Changed) {
Logger::logLevel(c('Garden.LogLevel', Logger::INFO));
}
}
return $Debug;
}
}
if (!function_exists('debugMethod')) {
/**
* Format a function or method call for debug output.
*
* @param string $MethodName The name the method.
* @param array $MethodArgs An array of arguments passed to the method.
* @return string Returns the method formatted for debug output.
*/
function debugMethod($MethodName, $MethodArgs = array()) {
echo $MethodName."(";
$SA = array();
foreach ($MethodArgs as $FuncArg) {
if (is_null($FuncArg)) {
$SA[] = 'null';
} elseif (!is_array($FuncArg) && !is_object($FuncArg)) {
$SA[] = "'{$FuncArg}'";
} elseif (is_array($FuncArg)) {
$SA[] = "'Array(".sizeof($FuncArg).")'";
} else {
$SA[] = gettype($FuncArg)."/".get_class($FuncArg);
}
}