Repository navigation
Expand file tree
/
Copy pathbase.php
More file actions
2358 lines (2262 loc) · 59.3 KB
/
Copy pathbase.php
File metadata and controls
2358 lines (2262 loc) · 59.3 KB
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
/**
PHP Fat-Free Framework
The contents of this file are subject to the terms of the GNU General
Public License Version 3.0. You may not use this file except in
compliance with the license. Any of the license terms and conditions
can be waived if you get permission from the copyright holder.
Copyright (c) 2009-2012 F3::Factory
Bong Cosca <[email protected]>
@package Base
@version 2.0.12
**/
//! Base structure
class Base {
//@{ Framework details
const
TEXT_AppName='Fat-Free Framework',
TEXT_Version='2.0.12',
TEXT_AppURL='http://fatfree.sourceforge.net';
//@}
//@{ Locale-specific error/exception messages
const
TEXT_Illegal='%s is not a valid framework variable name',
TEXT_Config='The configuration file %s was not found',
TEXT_Section='%s is not a valid section',
TEXT_MSet='Invalid multi-variable assignment',
TEXT_NotArray='%s is not an array',
TEXT_PHPExt='PHP extension %s is not enabled',
TEXT_Apache='Apache mod_rewrite module is not enabled',
TEXT_Object='%s cannot be used in object context',
TEXT_Class='Undefined class %s',
TEXT_Method='Undefined method %s',
TEXT_NotFound='The URL %s was not found',
TEXT_NotAllowed='%s request is not allowed for the URL %s',
TEXT_NoRoutes='No routes specified',
TEXT_HTTP='HTTP status code %s is invalid',
TEXT_Render='Unable to render %s - file does not exist',
TEXT_Form='The input handler for %s is invalid',
TEXT_Static='%s must be a static method',
TEXT_Fatal='Fatal error: %s',
TEXT_Write='%s must have write permission on %s',
TEXT_Tags='PHP short tags are not supported by this server';
//@}
//@{ HTTP status codes (RFC 2616)
const
HTTP_100='Continue',
HTTP_101='Switching Protocols',
HTTP_200='OK',
HTTP_201='Created',
HTTP_202='Accepted',
HTTP_203='Non-Authorative Information',
HTTP_204='No Content',
HTTP_205='Reset Content',
HTTP_206='Partial Content',
HTTP_300='Multiple Choices',
HTTP_301='Moved Permanently',
HTTP_302='Found',
HTTP_303='See Other',
HTTP_304='Not Modified',
HTTP_305='Use Proxy',
HTTP_307='Temporary Redirect',
HTTP_400='Bad Request',
HTTP_401='Unauthorized',
HTTP_402='Payment Required',
HTTP_403='Forbidden',
HTTP_404='Not Found',
HTTP_405='Method Not Allowed',
HTTP_406='Not Acceptable',
HTTP_407='Proxy Authentication Required',
HTTP_408='Request Timeout',
HTTP_409='Conflict',
HTTP_410='Gone',
HTTP_411='Length Required',
HTTP_412='Precondition Failed',
HTTP_413='Request Entity Too Large',
HTTP_414='Request-URI Too Long',
HTTP_415='Unsupported Media Type',
HTTP_416='Requested Range Not Satisfiable',
HTTP_417='Expectation Failed',
HTTP_500='Internal Server Error',
HTTP_501='Not Implemented',
HTTP_502='Bad Gateway',
HTTP_503='Service Unavailable',
HTTP_504='Gateway Timeout',
HTTP_505='HTTP Version Not Supported';
//@}
//@{ HTTP headers (RFC 2616)
const
HTTP_AcceptEnc='Accept-Encoding',
HTTP_Agent='User-Agent',
HTTP_Allow='Allow',
HTTP_Cache='Cache-Control',
HTTP_Connect='Connection',
HTTP_Content='Content-Type',
HTTP_Disposition='Content-Disposition',
HTTP_Encoding='Content-Encoding',
HTTP_Expires='Expires',
HTTP_Host='Host',
HTTP_IfMod='If-Modified-Since',
HTTP_Keep='Keep-Alive',
HTTP_LastMod='Last-Modified',
HTTP_Length='Content-Length',
HTTP_Location='Location',
HTTP_Partial='Accept-Ranges',
HTTP_Powered='X-Powered-By',
HTTP_Pragma='Pragma',
HTTP_Referer='Referer',
HTTP_Transfer='Content-Transfer-Encoding',
HTTP_WebAuth='WWW-Authenticate';
//@}
const
//! Framework-mapped PHP globals
PHP_Globals='GET|POST|COOKIE|REQUEST|SESSION|FILES|SERVER|ENV',
//! HTTP methods for RESTful interface
HTTP_Methods='GET|HEAD|POST|PUT|DELETE|OPTIONS|TRACE|CONNECT';
//@{ Global variables and references to constants
protected static
$vars,
$null=NULL,
$true=TRUE,
$false=FALSE;
//@}
private static
//! Read-only framework variables
$readonly='BASE|PROTOCOL|ROUTES|STATS|VERSION';
/**
Convert Windows double-backslashes to slashes; Also for
referencing namespaced classes in subdirectories
@return string
@param $str string
@public
**/
static function fixslashes($str) {
return $str?strtr($str,'\\','/'):$str;
}
/**
Convert PHP expression/value to compressed exportable string
@return string
@param $arg mixed
@public
**/
static function stringify($arg) {
switch (gettype($arg)) {
case 'object':
return method_exists($arg,'__tostring')?
(string)stripslashes($arg):
get_class($arg).'::__set_state()';
case 'array':
$str='';
foreach ($arg as $key=>$val)
$str.=($str?',':'').
self::stringify($key).'=>'.self::stringify($val);
return 'array('.$str.')';
default:
return var_export($arg,TRUE);
}
}
/**
Flatten array values and return as CSV string
@return string
@param $args mixed
@public
**/
static function csv($args) {
return implode(',',array_map('stripcslashes',
array_map('self::stringify',$args)));
}
/**
Split pipe-, semi-colon, comma-separated string
@return array
@param $str string
@public
**/
static function split($str) {
return array_map('trim',
preg_split('/[|;,]/',$str,0,PREG_SPLIT_NO_EMPTY));
}
/**
Generate Base36/CRC32 hash code
@return string
@param $str string
@public
**/
static function hash($str) {
return str_pad(base_convert(
sprintf('%u',crc32($str)),10,36),7,'0',STR_PAD_LEFT);
}
/**
Convert hexadecimal to binary-packed data
@return string
@param $hex string
@public
**/
static function hexbin($hex) {
return pack('H*',$hex);
}
/**
Convert binary-packed data to hexadecimal
@return string
@param $bin string
@public
**/
static function binhex($bin) {
return implode('',unpack('H*',$bin));
}
/**
Returns -1 if the specified number is negative, 0 if zero, or 1 if
the number is positive
@return int
@param $num mixed
@public
**/
static function sign($num) {
return $num?$num/abs($num):0;
}
/**
Convert engineering-notated string to bytes
@return int
@param $str string
@public
**/
static function bytes($str) {
$greek='KMGT';
$exp=strpbrk($str,$greek);
return pow(1024,strpos($greek,$exp)+1)*(int)$str;
}
/**
Convert from JS dot notation to PHP array notation
@return string
@param $key string
@public
**/
static function remix($key) {
$out='';
$obj=FALSE;
foreach (preg_split('/\[\s*[\'"]?|[\'"]?\s*\]|\.|(->)/',
$key,NULL,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE) as $fix)
if (!$out)
$out=$fix;
elseif ($fix=='->')
$obj=TRUE;
elseif ($obj) {
$obj=FALSE;
$out.='->'.$fix;
}
else
$out.='['.self::stringify($fix).']';
return $out;
}
/**
Return TRUE if specified string is a valid framework variable name
@return bool
@param $key string
@public
**/
static function valid($key) {
if (preg_match('/^(\w+(?:\[[^\]]+\]|\.\w+|\s*->\s*\w+)*)$/',$key))
return TRUE;
// Invalid variable name
trigger_error(sprintf(self::TEXT_Illegal,var_export($key,TRUE)));
return FALSE;
}
/**
Get framework variable reference/contents
@return mixed
@param $key string
@param $set bool
@public
**/
static function &ref($key,$set=TRUE) {
// Traverse array
$matches=preg_split(
'/\[\s*[\'"]?|[\'"]?\s*\]|\.|(->)/',$key,
NULL,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
// Referencing SESSION element auto-starts a session
if ($matches[0]=='SESSION' && !session_id()) {
// Use cookie jar setup
call_user_func_array('session_set_cookie_params',
self::$vars['JAR']);
session_start();
// Sync framework and PHP global
self::$vars['SESSION']=&$_SESSION;
}
// Read-only framework variable?
if ($set && !preg_match('/^('.self::$readonly.')\b/',$matches[0]))
$var=&self::$vars;
else
$var=self::$vars;
$obj=FALSE;
$i=0;
foreach ($matches as $match) {
if ($match=='->')
$obj=TRUE;
else {
if (preg_match('/@(\w+)/',$match,$token))
// Token found
$match=&self::ref($token[1]);
if ($set) {
// Create property/array element if not found
if ($obj) {
if (!is_object($var))
$var=new stdClass;
if (!isset($var->$match))
$var->$match=NULL;
$var=&$var->$match;
$obj=FALSE;
}
else
$var=&$var[$match];
}
elseif ($obj &&
(isset($var->$match) || method_exists($var,'__get'))) {
// Object property found
$var=$var->$match;
$obj=FALSE;
}
elseif (is_array($var)) {
// Array element found
if (isset($var[$match]))
// Normal key
$var=$var[$match];
elseif (isset(
$var[$slice=implode(".",array_slice($matches,$i))])) {
// Key contains a dot (.)
$var=$var[$slice];
break;
}
else
// Property/array element doesn't exist
return self::$null;
}
else
// Property/array element doesn't exist
return self::$null;
}
$i++;
}
if ($set && count($matches)>1 &&
preg_match('/GET|POST|COOKIE/',$matches[0],$php)) {
// Sync with REQUEST
$req=&self::ref(preg_replace('/^'.$php[0].'\b/','REQUEST',$key));
$req=$var;
}
return $var;
}
/**
Copy contents of framework variable to another
@param $src string
@param $dst string
@public
**/
static function copy($src,$dst) {
$ref=&self::ref($dst);
$ref=self::ref($src);
}
/**
Concatenate string to framework string variable
@param $var string
@param $val string
@public
**/
static function concat($var,$val) {
$ref=&self::ref($var);
$ref.=$val;
}
/**
Format framework string variable
@return string
@public
**/
static function sprintf() {
return call_user_func_array('sprintf',
array_map('self::resolve',func_get_args()));
}
/**
Add keyed element to the end of framework array variable
@param $var string
@param $key string
@param $val mixed
@public
**/
static function append($var,$key,$val) {
$ref=&self::ref($var);
$ref[self::resolve($key)]=$val;
}
/**
Swap keys and values of framework array variable
@param $var string
@public
**/
static function flip($var) {
$ref=&self::ref($var);
$ref=array_combine(array_values($ref),array_keys($ref));
}
/**
Merge one or more framework array variables
@return array
@public
**/
static function merge() {
$args=func_get_args();
foreach ($args as &$arg) {
if (is_string($arg))
$arg=self::ref($arg);
if (!is_array($arg))
trigger_error(sprintf(self::TEXT_NotArray,
self::stringify($arg)));
}
return call_user_func_array('array_merge',$args);
}
/**
Add element to the end of framework array variable
@param $var string
@param $val mixed
@public
**/
static function push($var,$val) {
$ref=&self::ref($var);
if (!is_array($ref))
$ref=array();
array_push($ref,is_array($val)?
array_map('self::resolve',$val):
(is_string($val)?self::resolve($val):$val));
}
/**
Remove last element of framework array variable and
return the element
@return mixed
@param $var string
@public
**/
static function pop($var) {
$ref=&self::ref($var);
if (is_array($ref))
return array_pop($ref);
trigger_error(sprintf(self::TEXT_NotArray,$var));
return FALSE;
}
/**
Add element to the beginning of framework array variable
@param $var string
@param $val mixed
@public
**/
static function unshift($var,$val) {
$ref=&self::ref($var);
if (!is_array($ref))
$ref=array();
array_unshift($ref,is_array($val)?
array_map('self::resolve',$val):
(is_string($val)?self::resolve($val):$val));
}
/**
Remove first element of framework array variable and
return the element
@return mixed
@param $var string
@public
**/
static function shift($var) {
$ref=&self::ref($var);
if (is_array($ref))
return array_shift($ref);
trigger_error(sprintf(self::TEXT_NotArray,$var));
return FALSE;
}
/**
Execute callback as a mutex operation
@return mixed
@public
**/
static function mutex() {
$args=func_get_args();
$func=array_shift($args);
$handles=array();
foreach ($args as $file) {
$lock=$file.'.lock';
while (TRUE) {
usleep(mt_rand(0,100));
if (is_resource($handle=@fopen($lock,'x'))) {
$handles[$lock]=$handle;
break;
}
if (is_file($lock) &&
filemtime($lock)+self::$vars['MUTEX']<time())
unlink($lock);
}
}
$out=$func();
foreach ($handles as $lock=>$handle) {
fclose($handle);
unlink($lock);
}
return $out;
}
/**
Lock-aware file reader
@param $file string
@public
**/
static function getfile($file) {
$out=FALSE;
if (!function_exists('flock'))
$out=self::mutex(
function() use($file) {
return file_get_contents($file);
},
$file
);
elseif ($handle=@fopen($file,'r')) {
flock($handle,LOCK_EX);
$size=filesize($file);
$out=$size?fread($handle,$size):$out;
flock($handle,LOCK_UN);
fclose($handle);
}
return $out;
}
/**
Lock-aware file writer
@param $file string
@param $data string
@public
**/
static function putfile($file,$data) {
if (!function_exists('flock'))
$out=self::mutex(
function() use($file,$data) {
return file_put_contents($file,$data,LOCK_EX);
},
$file
);
else
$out=file_put_contents($file,$data,LOCK_EX);
return $out;
}
/**
Evaluate template expressions in string
@return string
@param $val mixed
@public
**/
static function resolve($val) {
// Analyze string for correct framework expression syntax
$self=__CLASS__;
$str=preg_replace_callback(
// Expression
'/{{(.+?)}}/i',
function($expr) use($self) {
// Evaluate expression
$out=preg_replace_callback(
// Function
'/(?<!@)\b(\w+)\s*\(([^\)]*)\)/',
function($func) use($self) {
return is_callable($ref=$self::ref($func[1],FALSE))?
// Variable holds an anonymous function
call_user_func_array($ref,str_getcsv($func[2])):
// Check if empty array
($func[1].$func[2]=='array'?'NULL':
($func[1]=='array'?'\'Array\'':$func[0]));
},
preg_replace_callback(
// Framework variable
'/(?<!\w)@(\w+(?:\[[^\]]+\]|\.\w+)*'.
'(?:\s*->\s*\w+)?)\s*(\(([^\)]*)\))?(?:\\\(.+))?/',
function($var) use($self) {
// Retrieve variable contents
$val=$self::ref($var[1],FALSE);
if (isset($var[2]) && is_callable($val))
// Anonymous function
$val=call_user_func_array(
$val,str_getcsv($var[3]));
if (isset($var[4]) && class_exists('ICU',FALSE))
// ICU-formatted string
$val=call_user_func_array('ICU::format',
array($val,str_getcsv($var[4])));
return $self::stringify($val);
},
$expr[1]
)
);
return preg_match('/(?=\w)@/i',$out) ||
($eval=eval('return (string)'.$out.';'))===FALSE?
$out:$eval;
},
$val
);
return $str;
}
/**
Sniff headers for real IP address
@return string
@public
**/
static function realip() {
if (isset($_SERVER['HTTP_CLIENT_IP']))
// Behind proxy
return $_SERVER['HTTP_CLIENT_IP'];
elseif (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
// Use first IP address in list
list($ip)=explode(',',$_SERVER['HTTP_X_FORWARDED_FOR']);
return $ip;
}
return $_SERVER['REMOTE_ADDR'];
}
/**
Return TRUE if IP address is local or within a private IPv4 range
@return bool
@param $addr string
@public
**/
static function privateip($addr=NULL) {
if (!$addr)
$addr=self::realip();
return preg_match('/^127\.0\.0\.\d{1,3}$/',$addr) ||
!filter_var($addr,FILTER_VALIDATE_IP,
FILTER_FLAG_IPV4|FILTER_FLAG_NO_PRIV_RANGE);
}
/**
Clean and repair HTML
@return string
@param $html string
@public
**/
static function tidy($html) {
if (!extension_loaded('tidy'))
return $html;
$tidy=new Tidy;
$tidy->parseString($html,self::$vars['TIDY'],
str_replace('-','',self::$vars['ENCODING']));
$tidy->cleanRepair();
return (string)$tidy;
}
/**
Create folder; Trigger error and return FALSE if script has no
permission to create folder in the specified path
@param $name string
@param $perm int
@param $recursive bool
@public
**/
static function mkdir($name,$perm=0775,$recursive=TRUE) {
$parent=dirname($name);
if (!@is_writable($parent) && !chmod($parent,$perm)) {
$uid=posix_getpwuid(posix_geteuid());
trigger_error(sprintf(self::TEXT_Write,
$uid['name'],realpath(dirname($name))));
return FALSE;
}
// Create the folder
mkdir($name,$perm,$recursive);
}
/**
Intercept calls to undefined methods
@param $func string
@param $args array
@public
**/
function __call($func,array $args) {
trigger_error(sprintf(self::TEXT_Method,get_called_class().'->'.
$func.'('.self::csv($args).')'));
}
/**
Intercept calls to undefined static methods
@param $func string
@param $args array
@public
**/
static function __callStatic($func,array $args) {
trigger_error(sprintf(self::TEXT_Method,get_called_class().'::'.
$func.'('.self::csv($args).')'));
}
/**
Return instance of child class
@public
**/
static function instance() {
$ref=new ReflectionClass(get_called_class());
return $ref->newInstanceArgs(func_get_args());
}
/**
Class constructor
@public
**/
function __construct() {
// Prohibit use of class as an object
trigger_error(sprintf(self::TEXT_Object,get_called_class()));
}
}
//! Main framework code
class F3 extends Base {
/**
Bind value to framework variable
@param $key string
@param $val mixed
@param $persist bool
@param $resolve bool
@public
**/
static function set($key,$val,$persist=FALSE,$resolve=TRUE) {
if (preg_match('/{{.+}}/',$key))
// Variable variable
$key=self::resolve($key);
if (!self::valid($key))
return;
if (preg_match('/COOKIE\b/',$key) && !headers_sent()) {
// Create/modify cookie
$matches=preg_split(
'/\[\s*[\'"]?|[\'"]?\s*\]|\./',self::remix($key),
NULL,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
array_shift($matches);
if ($matches) {
$var='';
foreach ($matches as $match)
if (!$var)
$var=$match;
else
$var.='[\''.$match.'\']';
$val=array($var=>$val);
}
if (is_array($val))
foreach ($val as $var=>$sub) {
$func=self::$vars['JAR'];
array_unshift($func,$var,$sub);
call_user_func_array('setcookie',$func);
}
return;
}
$var=&self::ref($key);
if ($resolve) {
if (is_string($val))
$val=self::resolve($val);
elseif (is_array($val)) {
$var=array();
// Recursive token substitution
foreach ($val as $subk=>$subv) {
$subp=$key.'['.var_export($subk,TRUE).']';
self::set($subp,$subv);
$val[$subk]=self::ref($subp);
}
}
}
$var=$val;
if (preg_match('/LANGUAGE|LOCALES/',$key) && class_exists('ICU'))
// Load appropriate dictionaries
ICU::load();
elseif ($key=='ENCODING')
ini_set('default_charset',$val);
elseif ($key=='TZ')
date_default_timezone_set($val);
// Initialize cache if explicitly defined
elseif ($key=='CACHE' && $val)
self::$vars['CACHE']=Cache::load();
if ($persist) {
$hash='var.'.self::hash(self::remix($key));
Cache::set($hash,$val);
}
}
/**
Retrieve value of framework variable and apply locale rules
@return mixed
@param $key string
@param $args mixed
@public
**/
static function get($key,$args=NULL) {
if (preg_match('/{{.+}}/',$key))
// Variable variable
$key=self::resolve($key);
if (!self::valid($key))
return self::$null;
$val=self::ref($key,FALSE);
if (is_string($val))
return class_exists('ICU',FALSE) && $args?
ICU::format($val,$args):$val;
elseif (is_null($val)) {
// Attempt to retrieve from cache
$hash='var.'.self::hash(self::remix($key));
if (Cache::cached($hash))
$val=Cache::get($hash);
}
return $val;
}
/**
Unset framework variable
@param $key string
@public
**/
static function clear($key) {
if (preg_match('/{{.+}}/',$key))
// Variable variable
$key=self::resolve($key);
if (!self::valid($key))
return;
if (preg_match('/COOKIE/',$key) && !headers_sent()) {
$val=$_COOKIE;
$matches=preg_split(
'/\[\s*[\'"]?|[\'"]?\s*\]|\./',self::remix($key),
NULL,PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE);
array_shift($matches);
if ($matches) {
// Expire specific cookie
$var='';
foreach ($matches as $match)
if (!$var)
$var=$match;
else
$var.='[\''.$match.'\']';
$val=array($var,FALSE);
}
if (is_array($val))
// Expire all cookies
foreach (array_keys($val) as $var) {
$func=self::$vars['JAR'];
$func['expire']=strtotime('-1 year');
array_unshift($func,$var,FALSE);
call_user_func_array('setcookie',$func);
}
return;
}
// Clearing SESSION array ends the current session
if ($key=='SESSION') {
if (!session_id()) {
call_user_func_array('session_set_cookie_params',
self::$vars['JAR']);
session_start();
}
// End the session
session_unset();
session_destroy();
}
preg_match('/^('.self::PHP_Globals.')(.*)$/',$key,$match);
if (isset($match[1])) {
$name=self::remix($key,FALSE);
eval($match[2]?'unset($_'.$name.');':'$_'.$name.'=NULL;');
}
$name=preg_replace('/^(\w+)/','[\'\1\']',self::remix($key));
// Assign NULL to framework variables; do not unset
eval(ctype_upper(preg_replace('/^\w+/','\0',$key))?
'self::$vars'.$name.'=NULL;':'unset(self::$vars'.$name.');');
// Remove from cache
$hash='var.'.self::hash(self::remix($key));
if (Cache::cached($hash))
Cache::clear($hash);
}
/**
Return TRUE if framework variable has been assigned a value
@return bool
@param $key string
@public
**/
static function exists($key) {
if (preg_match('/{{.+}}/',$key))
// Variable variable
$key=self::resolve($key);
if (!self::valid($key))
return FALSE;
$var=&self::ref($key,FALSE);
return isset($var);
}
/**
Multi-variable assignment using associative array
@param $arg array
@param $pfx string
@param $resolve bool
@public
**/
static function mset($arg,$pfx='',$resolve=TRUE) {
if (!is_array($arg))
// Invalid argument
trigger_error(self::TEXT_MSet);
else
// Bind key-value pairs
foreach ($arg as $key=>$val)
self::set($pfx.$key,$val,FALSE,$resolve);
}
/**
Determine if framework variable has been cached
@return mixed
@param $key string
@public
**/
static function cached($key) {
if (preg_match('/{{.+}}/',$key))
// Variable variable
$key=self::resolve($key);
return self::valid($key)?
Cache::cached('var.'.self::hash(self::remix($key))):
FALSE;
}
/**
Configure framework according to INI-style file settings;
Cache auto-generated PHP code to speed up execution
@param $file string
@public
**/
static function config($file) {
// Generate hash code for config file
$hash='php.'.self::hash($file);
$cached=Cache::cached($hash);
if ($cached && filemtime($file)<$cached)
// Retrieve from cache
$save=Cache::get($hash);
else {
if (!is_file($file)) {
// Configuration file not found
trigger_error(sprintf(self::TEXT_Config,$file));
return;
}
// Load the .ini file
$cfg=array();
$sec='';
if ($ini=file($file))
foreach ($ini as $line) {
preg_match('/^\s*(?:(;)|\[(.+)\]|(.+?)\s*=\s*(.+))/',
$line,$parts);
if (isset($parts[1]) && $parts[1])
// Comment
continue;
elseif (isset($parts[2]) && $parts[2])
// Section
$sec=strtolower($parts[2]);
elseif (isset($parts[3]) && $parts[3]) {
// Key-value pair
$csv=array_map(
function($val) {
$val=trim($val);
return is_numeric($val) ||
preg_match('/^\w+$/i',$val) &&
defined($val)?
eval('return '.$val.';'):$val;
},
str_getcsv($parts[4])
);
$cfg[$sec=$sec?:'globals'][$parts[3]]=
count($csv)>1?$csv:$csv[0];
}
}
$plan=array('globals'=>'set','maps'=>'map','routes'=>'route');
ob_start();
foreach ($cfg as $sec=>$pairs)
if (isset($plan[$sec]))
foreach ($pairs as $key=>$val)
echo 'self::'.$plan[$sec].'('.
self::stringify($key).','.