/
functions.php
5901 lines (5328 loc) · 158 KB
/
functions.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
/**
* Main function library.
*
* @package API - Functions
* @copyright (c) Cotonti Team
* @license https://github.com/Cotonti/Cotonti/blob/master/License.txt
*/
defined('COT_CODE') or die('Wrong URL');
// System requirements check
if (!defined('COT_INSTALL')) {
if (
!function_exists('version_compare') ||
!version_compare(PHP_VERSION, '5.4', '>=')
) {
die('Cotonti system requirements: PHP 5.4 or above.'); // TODO: Need translate
}
if (!extension_loaded('mbstring')) {
die('Cotonti system requirements: mbstring PHP extension must be loaded.'); // TODO: Need translate
}
}
// Group constants
define('COT_GROUP_DEFAULT', 0);
define('COT_GROUP_GUESTS', 1);
define('COT_GROUP_INACTIVE', 2);
define('COT_GROUP_BANNED', 3);
define('COT_GROUP_MEMBERS', 4);
define('COT_GROUP_SUPERADMINS', 5);
define('COT_GROUP_MODERATORS', 6);
/* ======== Pre-sets ========= */
$out = array();
$plu = array();
$sys = array();
$usr = array();
$env = array();
$L = array();
$R = array();
$i = explode(' ', microtime());
$sys['starttime'] = $i[1] + $i[0];
$cfg['version'] = '0.9.21';
$cfg['dbversion'] = '0.9.19'; // Not used anywhere
// Set default file permissions if not present in config
if (!isset($cfg['file_perms'])) {
$cfg['file_perms'] = 0664;
}
if (!isset($cfg['dir_perms'])) {
$cfg['dir_perms'] = 0775;
}
/**
* Registry for captcha functions
*/
$cot_captcha = array();
/**
* Registry for extra fields
* @var array
*/
$cot_extrafields = null;
/**
* Registry for hash functions
*/
$cot_hash_funcs = array('md5', 'sha1', 'sha256');
/**
* Array of custom cot_import() filter callbacks
*/
$cot_import_filters = array();
/**
* Custom e-mail send callbacks
*/
$cot_mail_senders = array();
/**
* Custom parser functions registry
*/
$cot_parsers = array();
/**
* Parameters to be automatically appended to all URLs if present
*/
$cot_url_appendix = array();
/**
* Structure tree
* @var array
*/
$structure = array();
/**
* Facade class to access key Cotonti globals regardless of scope
*/
class cot
{
/**
* Cotonti cache
* @var Cache
*/
public static $cache;
/**
* Cotonti configuration
* @var array
*/
public static $cfg;
/**
* Database connection
* @var CotDB
*/
public static $db;
/**
* Database table name prefix
*/
public static $db_x;
/**
* Environment settings
* @var array
*/
public static $env;
/**
* Extra fields
* @var array
*/
public static $extrafields;
/**
* Language strings
* @var array
*/
public static $L;
/**
* Pre-rendered output strings
* @var array
*/
public static $out;
/**
* Resource strings
* @var array
*/
public static $R;
/**
* Structure tree and properties array
* @var array
*/
public static $structure;
/**
* Temporary system variables
* @var array
*/
public static $sys;
/**
* Current user object
* @var array
*/
public static $usr;
/**
* Initializes static members. Call this function once all globals are defined.
*/
public static function init()
{
global $cache, $cfg, $cot_extrafields, $db, $db_x, $env, $L, $out, $R, $structure, $sys, $usr;
// Todo fill some variables with default values
self::$cache =& $cache;
self::$cfg =& $cfg;
self::$db =& $db;
self::$db_x =& $db_x;
self::$env =& $env;
self::$extrafields =& $cot_extrafields;
self::$L =& $L;
self::$out =& $out;
self::$R =& $R;
self::$structure =& $structure;
self::$sys =& $sys;
self::$usr =& $usr;
// Register core DB tables
// On the first step of installer it is not initialized yet
if (!(empty($db) && isset($env['location']) && $env['location'] == 'install')) {
$db->registerTable('auth');
$db->registerTable('cache');
$db->registerTable('cache_bindings');
$db->registerTable('core');
$db->registerTable('config');
$db->registerTable('groups');
$db->registerTable('groups_users');
$db->registerTable('logger');
$db->registerTable('online');
$db->registerTable('extra_fields');
$db->registerTable('plugins');
$db->registerTable('structure');
$db->registerTable('updates');
$db->registerTable('users');
}
// Fill some variables with default values
// May be isset() is not needed
if (!isset(self::$out['head'])) self::$out['head'] = '';
if (!isset(self::$out['subtitle'])) self::$out['subtitle'] = '';
if (!isset(self::$env['ext'])) self::$env['ext'] = null;
}
}
/*
* =========================== System Functions ===============================
*/
/**
* Strips everything but alphanumeric, hyphens and underscores
*
* @param string $text Input
* @return string
*/
function cot_alphaonly($text)
{
return (preg_replace('/[^a-zA-Z0-9\-_]/', '', $text));
}
/**
* Generic autoloader function to be used with spl_autoload_register
*
* @todo PSR-4 autoloader
* @param string $class Class name
*/
function cot_autoload($class)
{
global $cfg, $env;
$type = isset(cot::$env['type']) ? cot::$env['type'] : null;
if ($type == 'module') {
$paths[] = "{$cfg['modules_dir']}/{$env['ext']}/classes/$class.php";
} elseif ($type == 'plug') {
$paths[] = "{$cfg['plugins_dir']}/{$env['ext']}/classes/$class.php";
}
$paths[] = "{$cfg['system_dir']}/classes/$class.php";
foreach ($paths as $path) {
if (file_exists($path)) {
require $path;
return;
}
}
}
/**
* Computes the difference of arrays
* array_diff() for n-dimensional arrays
*
* Native php function array_diff() only checks one dimension of a n-dimensional array.
* When trying to compare n-dimensional ones it generates warning: Array to string conversion because it compares
* elements by their string representation (if (string) $elem1 === (string) $elem2)
* @see https://php.net/manual/en/function.array-diff.php
*
* @param array $array1 The array to compare from
* @param array $array2 The array to compare with
* @return array an array containing all the entries from array1 that are not present in any of the other arrays.
*
* @todo make signature compartaible with native array_diff() function:
* array_diff(array $array, array ...$arrays): array
*/
function cot_array_diff($array1, $array2)
{
$return = array();
foreach ($array1 as $mKey => $mValue) {
if (array_key_exists($mKey, $array2)) {
if (is_array($mValue)) {
$aRecursiveDiff = cot_array_diff($mValue, $array2[$mKey]);
if (count($aRecursiveDiff)) {
$return[$mKey] = $aRecursiveDiff;
}
} else {
if ($mValue != $array2[$mKey]) {
$return[$mKey] = $mValue;
}
}
} else {
$return[$mKey] = $mValue;
}
}
return $return;
}
/**
* Truncates a string
*
* @param string $res Source string
* @param int $l Length
* @return string
*/
function cot_cutstring($res, $l)
{
if (mb_strlen($res)>$l)
{
$res = mb_substr($res, 0, ($l-3)).'...';
}
return $res;
}
/**
* Returns name part of the caller file. Use this in plugins to detect from which file
* current hook part was included. Example:
* <code>
* if (cot_get_caller() == 'users.details')
* {
* // We are called from users.details
* }
* else if (cot_get_caller() == 'header')
* {
* // We are called from header
* }
* </code>
* @return string Caller file basename without .php suffix on success, 'unknown' or error
*/
function cot_get_caller()
{
$bt = debug_backtrace();
if (isset($bt[1]) && in_array($bt[1]['function'], array('include', 'require_once', 'require', 'include_once')))
{
return preg_replace('#\.php$#', '', basename($bt[1]['file']));
}
else
{
return 'unknown';
}
}
/**
* Returns a list of plugins registered for a hook
*
* @param string $hook Hook name
* @param string $cond Permissions
* @return array
* @global Cache $cache
*/
function cot_getextplugins($hook, $cond='R')
{
global $cot_plugins, $cache, $cfg, $cot_hooks_fired;
if ($cfg['debug_mode'])
{
$cot_hooks_fired[] = $hook;
}
$extplugins = array();
if (isset($cot_plugins[$hook]) && is_array($cot_plugins[$hook]))
{
foreach($cot_plugins[$hook] as $k)
{
if ($k['pl_module'])
{
$dir = $cfg['modules_dir'];
$cat = $k['pl_code'];
$opt = 'a';
}
else
{
$dir = $cfg['plugins_dir'];
$cat = 'plug';
$opt = $k['pl_code'];
}
if (cot_auth($cat, $opt, $cond))
{
$extplugins[] = $dir . '/' . $k['pl_file'];
}
}
}
// Trigger cache handlers
$cache && $cache->trigger($hook);
return $extplugins;
}
/**
* Imports data from the outer world
*
* @param string $name Variable name
* @param string $source Source type: G/GET, P/POST, C/COOKIE, R/REQUEST, PUT, DELETE or D/DIRECT (variable filtering)
* @param string $filter Filter type
* @param int $maxlen Length limit
* @param bool $dieonerror Die with fatal error on wrong input
* @param bool $buffer Try to load from input buffer (previously submitted) if current value is empty
* @return mixed
*/
function cot_import($name, $source, $filter, $maxlen = 0, $dieonerror = false, $buffer = false)
{
global $cot_import_filters, $_PUT, $_PATCH, $_DELETE;
if (isset($_SERVER['REQUEST_METHOD'])) {
if ($_SERVER['REQUEST_METHOD'] == 'PUT' && is_null($_PUT)) {
parse_str(file_get_contents('php://input'), $_PUT);
} elseif ($_SERVER['REQUEST_METHOD'] == 'PATCH' && is_null($_PATCH)) {
parse_str(file_get_contents('php://input'), $_PATCH);
} elseif ($_SERVER['REQUEST_METHOD'] == 'DELETE' && is_null($_DELETE)) {
parse_str(file_get_contents('php://input'), $_DELETE);
}
}
$v = NULL;
switch($source) {
case 'G':
case 'GET':
$v = (isset($_GET[$name])) ? $_GET[$name] : NULL;
$log = TRUE;
break;
case 'P':
case 'POST':
$v = (isset($_POST[$name])) ? $_POST[$name] : NULL;
$log = TRUE;
break;
case 'PUT':
$v = (isset($_PUT[$name])) ? $_PUT[$name] : NULL;
$log = TRUE;
break;
case 'PATCH':
$v = (isset($_PATCH[$name])) ? $_PATCH[$name] : NULL;
$log = TRUE;
break;
case 'DELETE':
$v = (isset($_DELETE[$name])) ? $_DELETE[$name] : NULL;
$log = TRUE;
break;
case 'R':
case 'REQUEST':
$v = (isset($_REQUEST[$name])) ? $_REQUEST[$name] : NULL;
$log = TRUE;
break;
case 'C':
case 'COOKIE':
$v = (isset($_COOKIE[$name])) ? $_COOKIE[$name] : NULL;
$log = TRUE;
break;
case 'D':
case 'DIRECT':
$v = $name;
$log = FALSE;
break;
default:
cot_diefatal('Unknown source for a variable : <br />Name = '.$name.'<br />Source = '.$source.' ? (must be G, P, C or D)');
break;
}
if (is_array($v)) {
if ($filter == 'NOC') $filter = 'ARR';
if ($filter != 'ARR') return null;
} else {
if ($filter == 'ARR') return array();
}
if (MQGPC && ($source=='G' || $source=='P' || $source=='C') && $v != NULL && $filter != 'ARR') {
$v = stripslashes($v);
}
if (($v === '' || $v === NULL || $filter == 'ARR') && $buffer) {
$v = cot_import_buffered($name, $v, null);
return $v;
}
if ($v === null) {
return null;
}
if ($maxlen>0) {
$v = mb_substr($v, 0, $maxlen);
}
$pass = FALSE;
$defret = NULL;
// Custom filter support
if (!empty($cot_import_filters[$filter]) && is_array($cot_import_filters[$filter])) {
foreach ($cot_import_filters[$filter] as $func) {
$v = $func($v, $name);
}
return $v;
}
switch ($filter) {
case 'INT':
if (is_numeric($v) && floor($v)==$v) {
$pass = TRUE;
$v = (int) $v;
}
break;
case 'NUM':
if (is_numeric($v)) {
$pass = TRUE;
$v = (float) $v;
}
break;
case 'TXT':
$v = trim($v);
if (mb_strpos($v, '<')===FALSE) {
$pass = TRUE;
} else {
$defret = str_replace('<', '<', $v);
}
break;
case 'ALP':
$v = trim($v);
$f = cot_alphaonly($v);
if ($v == $f) {
$pass = TRUE;
} else {
$defret = $f;
}
break;
/**
* @deprecated
* Old password filter. Not used anymore
*/
case 'PSW':
$v = trim($v);
$f = preg_replace('#[\'"&<>]#', '', $v);
$f = mb_substr($f, 0 ,32);
if ($v == $f)
{
$pass = TRUE;
}
else
{
$defret = $f;
}
break;
case 'HTM':
$v = trim($v);
$pass = TRUE;
break;
case 'ARR':
$pass = TRUE;
break;
case 'BOL':
if ($v == '1' || $v == 'on') {
$pass = TRUE;
$v = TRUE;
} elseif ($v=='0' || $v=='off') {
$pass = TRUE;
$v = FALSE;
} else {
$defret = FALSE;
}
break;
case 'NOC':
$pass = TRUE;
break;
default:
cot_diefatal('Unknown filter for a variable : <br />Var = '.$v.'<br />Filter = "'.$filter.'" ?');
break;
}
if (!$pass || !in_array($filter, array('INT', 'NUM', 'BOL', 'ARR')))
{
$v = preg_replace('/(&#\d+)(?![\d;])/', '$1;', $v);
}
if ($pass)
{
return $v;
}
else
{
if ($log)
{
cot_log_import($source, $filter, $name, $v);
}
if ($dieonerror)
{
cot_diefatal('Wrong input.');
}
else
{
return $defret;
}
}
return null;
}
/**
* Imports data from the outer world by list of Variable names
* Relies on `cot_import` function
*
* @param array|string $nameslist List of Variables names to import, can be:<br />
* string 'name1, name2 , ...' - list of variable names comma separated.<br />
* array('name1', 'name2', ...) - list of variable names only.
* In that case $filter parameter must be specified.<br />
* array('name1' => 'TYPE1', 'name2' => 'TYPE2' ,...) - list of variable names with their filter types
* @param string $source Source type: G/GET, P/POST, C/COOKIE, R/REQUEST, PUT, DELETE or D/DIRECT (variable filtering)
* @param array $origindata Array with origin data that will be extended with imported one
* @param string $nameprefix Unified prefix for Variables names
* @param string $filter Filter type, can be set as:<br />
* string 'FLT' - single filter string for all Variables<br />
* string 'FLT1, FLT2, ...' - comma separated string with filters corresponding to Variable names<br />
* array('FLT1', 'FLT2', ...) - array of filters<br />
* Overrides Filter types specified in $nameslist. If passed as list - number of Filters must be equal to count of
* variables names in $nameslist.
*
* @param bool $arrayprefix Use $nameprefix for array fields
* @param int $maxlen Length limit
* @param bool $dieonerror Die with fatal error on wrong input
* @param bool $buffer Try to load from input buffer (previously submitted) if current value is empty
* @return ?array Returns combined array of data or NULL if wrong parameters set
*/
function cot_import_list(
$nameslist = [],
$source = 'P',
$origindata = [],
$nameprefix = '',
$filter = null,
$arrayprefix = false,
$maxlen = 0,
$dieonerror = false,
$buffer = false
) {
$direct = ($source == 'D' || $source == 'DIRECT');
$filter = empty($filter) ? null : $filter;
$nameslist = empty($nameslist) ? [] : $nameslist;
$origindata = (empty($origindata) || !is_array($origindata)) ? [] : $origindata;
if (empty($nameslist)) {
$nameslist = [];
} elseif (!is_array($nameslist)) {
$nameslist = array_map('trim', explode(',', $nameslist));
}
if (!empty($filter) && !is_array($filter)) {
if (strpos($filter, ',') !== false) {
$filter = array_map('trim', explode(',', $filter));
} else {
$filter = array_fill(
0,
sizeof($direct && empty($nameslist) ? $origindata : $nameslist),
$filter
);
}
}
if (!$direct && sizeof($nameslist) == 0) {
// no proper name list
return null;
} elseif (sizeof($nameslist) == 0) {
// direct by origin
if (is_null($filter)) {
return null;
}
foreach ($origindata as $key => $value) {
$origindata[$key] = cot_import($value, 'D', array_shift($filter), $maxlen, $dieonerror);
}
} else {
// namelist exists
$index = array_keys($nameslist);
$index = array_pop($index);
$types_not_defined = (is_numeric($index) && is_int($index));
if (
(is_array($filter) && sizeof($filter) != sizeof($nameslist))
|| ($types_not_defined && is_null($filter))
) {
// can't rely on filter or no filter exists
return null;
} elseif (is_array($filter)) {
$nameslist = array_combine($types_not_defined ? $nameslist : array_keys($nameslist), $filter);
}
foreach ($nameslist as $name => $filtertype) {
$origindata[($arrayprefix) ? $nameprefix . $name : $name] = cot_import(
$direct ? $origindata[$nameprefix . $name] : $nameprefix . $name,
$source,
$filtertype,
$maxlen,
$dieonerror,
$buffer
);
}
}
return $origindata;
}
/**
* Imports data from the outer world as indexed array of records imported by cot_import_list.
* Used to import table editing data as one array ordered by index (IDs) of table lines.
*
* @see cot_import_list() for parameters
*
* @return ?array Returns indexed array of data or NULL if wrong parameters setted
*/
function cot_import_tabledata($nameslist=array(), $source='P', $nameprefix='', $origindata=array(), $maxlen=0, $dieonerror=false, $buffer=false)
{
$imported_arrays = cot_import_list($nameslist, $source, $origindata, $nameprefix,'ARR', $maxlen, $dieonerror, $buffer);
if (!$imported_arrays) {
return null;
}
$result = array();
$na_data = array();
foreach ($imported_arrays as $name => $data)
{
if (!is_array($data))
{
$na_data[$name] = $data;
unset($imported_arrays[$name]);
}
}
foreach ($imported_arrays as $name => $data)
{
if (is_array($data))
{
foreach ($data as $index => $value)
{
$result[$index][$name] = $value;
foreach ($na_data as $k => $v) {
$result[$index][$k] = $v;
}
}
}
}
return $result;
}
/**
* Puts POST data into the cross-request buffer
*/
function cot_import_buffer_save()
{
// Referer contains an original form link
if (isset($_SERVER['HTTP_REFERER']) && cot_url_check($_SERVER['HTTP_REFERER'])) {
// Extract the server-relative part
$url = parse_url($_SERVER['HTTP_REFERER']);
// Strip ajax param from the query
$url['query'] = str_replace('&_ajax=1', '', $url['query']);
$path = empty($url['query']) ? $url['path'] : $url['path'] . '?' . $url['query'];
$hash = md5($path);
// Save the buffer
$_SESSION['cot_buffer'][$hash] = $_POST;
}
}
/**
* Attempts to fetch a buffered value for a variable previously imported
* if the currently imported value is empty
*
* @param string $name Input name
* @param mixed $value Currently imported value
* @param mixed $null null import
* @return mixed Input value or NULL if the variable is not in the buffer
*/
function cot_import_buffered($name, $value, $null = '')
{
// Params hash for current form
$uri = str_replace('&_ajax=1', '', $_SERVER['REQUEST_URI']);
$hash = md5($uri);
if ($value === '' || $value === null
|| isset($_SESSION['cot_buffer'][$hash][$name]) && !empty($_SESSION['cot_buffer'][$hash][$name]))
{
if (isset($_SESSION['cot_buffer'][$hash][$name]))
{
return $_SESSION['cot_buffer'][$hash][$name];
}
else
{
return $null;
}
}
else
{
return $value;
}
}
/**
* Imports date stamp
*
* @param string $name Variable name
* @param bool $usertimezone Use user timezone
* @param bool $returnarray Return Date Array
* @param string $source Source type: P (POST), C (COOKIE) or D (variable filtering)
* @return int|array{stamp: int, year: int, month: int, day: int, hour: int, minute: int}|null
*/
function cot_import_date($name, $usertimezone = true, $returnarray = false, $source = 'P')
{
if (function_exists('cot_import_date_custom')) {
return cot_import_date_custom($name, $usertimezone, $returnarray, $source);
}
$result = null;
/* === Hook === */
foreach (cot_getextplugins('import.date') as $pl) {
include $pl;
}
/* ===== */
if ($result !== null) {
return $result;
}
//$name = preg_match('#^(\w+)\[(.*?)\]$#', $name, $mt) ? $mt[1] : $name;
$date = cot_import($name, $source, 'ARR');
$timestamp = null;
/**
* Try to parse textual datetime string into a Unix timestamp
* @see https://www.php.net/manual/en/datetime.formats.time.php
*/
if (empty($date)) {
$date = cot_import($name, $source, 'TXT');
if (empty($date)) {
return null;
}
$timestamp = strtotime($date);
if ($timestamp === false) {
return null;
}
}
// Parse datetime array
if ($timestamp === null) {
$date['year'] = isset($date['year']) ? $date['year'] : 0;
$date['month'] = isset($date['month']) ? $date['month'] : 0;
$date['day'] = isset($date['day']) ? $date['day'] : 0;
$date['hour'] = isset($date['hour']) ? $date['hour'] : 0;
$date['minute'] = isset($date['minute']) ? $date['minute'] : 0;
$date['string'] = isset($date['string']) ? $date['string'] : '';
$date['format'] = isset($date['format']) ? $date['format'] : '';
$year = cot_import($date['year'], 'D', 'INT');
$month = cot_import($date['month'], 'D', 'INT');
$day = cot_import($date['day'], 'D', 'INT');
$hour = cot_import($date['hour'], 'D', 'INT');
$minute = cot_import($date['minute'], 'D', 'INT');
if (
count($date) > 0 &&
is_null($year) &&
is_null($month) &&
is_null($day) &&
is_null($hour) &&
is_null($minute) &&
empty($date['string'])
) {
// Datetime field is present in form but it is set to zero date (empty)
return null;
}
$timestamp = 0;
if (($month && $day && $year) || ($day && $minute)) {
$timestamp = cot_mktime($hour, $minute, 0, $month, $day, $year);
} else {
$string = cot_import($date['string'], 'D', 'TXT');
$format = cot_import($date['format'], 'D', 'TXT');
if ($string) {
$format = !empty($format) ? $format : 'Y-m-d H:i';
$timestamp = cot_date2stamp($string, $format);
} else {
return null;
}
}
}
if ($usertimezone) {
$timestamp -= cot::$usr['timezone'] * 3600;
}
if ($returnarray) {
$result = [];
$result['stamp'] = $timestamp;
$result['year'] = (int) date('Y', $timestamp);
$result['month'] = (int) date('m', $timestamp);
$result['day'] = (int) date('d', $timestamp);
$result['hour'] = (int) date('H', $timestamp);
$result['minute'] = (int) date('i', $timestamp);
return $result;
}
return $timestamp;
}
/**
* Imports pagination indexes
*
* @param string $var_name URL parameter name, e.g. 'pg' or 'd'
* @param int $max_items Max items per page
* @return array Array containing 3 items: page number, database offset and argument for URLs
*/
function cot_import_pagenav($var_name, $max_items = 0)
{
global $cfg;
if($max_items <= 0)
{
$max_items = $cfg['maxrowsperpage'];
}
if($max_items <= 0)
{
throw new Exception('Invalid $max_items ('.$max_items.') for pagination.');
}
if ($cfg['easypagenav'])
{
$page = (int) cot_import($var_name, 'G', 'INT');
if ($page < 0)
{
cot_die_message(404);
}
elseif ($page == 0)
{
$page = 1;
}
$offset = ($page - 1) * $max_items;
$urlnum = $page <= 1 ? null : $page;
}
else
{
$offset = (int) cot_import($var_name, 'G', 'INT');
if ($offset < 0)
{
cot_die_message(404);
}
if ($offset % $max_items != 0)
{
$offset -= $offset % $max_items;
}
$page = floor($offset / $max_items) + 1;
$urlnum = $offset;
$urlnum = ($urlnum > 0) ? $urlnum : null;
}
return array($page, $offset, $urlnum);
}
/**
* Checks the email
*
* @param string $res input string
* @return bool True if email valid
*/
function cot_check_email($res)
{
return mb_strlen($res) > 4 && preg_match('#^[\w\p{L}][\.\w\p{L}\-]*@[\w\p{L}\.\-]+\.[\w\p{L}]+$#u', $res);
}
/**
* Sends mail with standard PHP mail().
* If cot_mail_custom() function exists, it will be called instead of the PHP
* function. This way custom mail delivery methods, such as SMTP, are
* supported.
*
* @global $cfg
* @param string $to Recipient
* @param string $subject Subject
* @param string $body Message body
* @param string $headers Message headers
* @param bool $customtemplate Use custom template
* @param string $additional_parameters Additional parameters passed to sendmail
* @return bool
*/
function cot_mail($to, $subject, $body, $headers = '', $customtemplate = false, $additional_parameters = '', $html = false)
{
global $cfg, $cot_mail_senders;
if (function_exists('cot_mail_custom')) {
return cot_mail_custom($to, $subject, $body, $headers, $customtemplate, $additional_parameters, $html);
}