forked from Polycademy/upgradephp
-
Notifications
You must be signed in to change notification settings - Fork 0
/
upgrade.php.prefixed
3411 lines (2828 loc) · 87.4 KB
/
upgrade.php.prefixed
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
/**
* api: php
* title: upgrade.php
* description: Emulates functions from new PHP versions on older interpreters.
* version: 18.1
* license: Public Domain
* url: http://freshmeat.net/projects/upgradephp
* type: functions
* category: library
* priority: auto
* load_if: (PHP_VERSION<5.2)
* sort: -255
* provides: upgrade-php, api:php5, json
*
*
* By loading this library you get PHP version independence. It provides
* downwards compatibility to older PHP interpreters by emulating missing
* functions or constants using IDENTICAL NAMES. So this doesn't slow down
* script execution on setups where the native functions already exist. It
* is meant as quick drop-in solution. It spares you from rewriting code or
* using cumbersome workarounds instead of the more powerful v5 functions.
*
* It cannot mirror PHP5s extended OO-semantics and functionality into PHP4
* however. A few features are added here that weren't part of PHP yet. And
* some other function collections are separated out into the ext/ directory.
* It doesn't produce many custom error messages (YAGNI), and instead leaves
* reporting to invoked functions or for native PHP execution.
*
* And further this is PUBLIC DOMAIN (no copyright, no license, no warranty)
* so therefore compatible to ALL open source licenses. You could rip this
* paragraph out to republish this instead only under more restrictive terms
* or your favorite license (GNU LGPL/GPL, BSDL, MPL/CDDL, Artistic/PHPL, ..)
*
* Any contribution is appreciated. <milky*users#sf#net>
*
*/
/**
* -------------------------- FUTURE ---
* @group SVN
* @since future
*
* Following functions aren't implemented in current PHP versions, but
* might already be in CVS/SVN.
*
* @removed
* setcookie2
*
*/
/**
* ------------------------ OVERRIDE ---
*
*/
if (defined("UPGRADEPHP_OVERRIDE") and function_exists("runkit_function_remove")) {
ini_set("runkit.internal_override", 1);
runkit_function_rename("json_encode", "php::json_encode");
runkit_function_rename("json_decode", "php::json_encode");
}
/**
* ----------------------------- 5.4 ---
* @group 5_4
* @since 5.4
*
* Extensions in PHP 5.4
*
* @emulated
* gzdecode
* hex2bin
* session_status -> basic probing
*
* @stub
* class_uses
* trait_exists
* get_declared_traits
*
* @missing
* libxml_set_external_entity_loader
* zlib_encode -> PHP_ZLIB_ENCODE_FUNC(zlib_encode, 0);
* zlib_decode -> PHP_ZLIB_DECODE_FUNC(zlib_decode, PHP_ZLIB_ENCODING_ANY);
* session_register_shutdown
* socket_import_stream
* getimagesizefromstring
* header_register_callback
* http_response_code
* stream_set_chunk_size
* CallbackFilterIterator
* RecursiveCallbackFilterIterator
* SessionHandler
* ReflectionZendExtension
*
* @unimplementable
* imageantialias
* imagelayereffect
*
*/
/**
* Simple convenience function for pack H*,
* Converts a hextuplet string into its binary representation.
*
*/
function up_hex2bin($hex) {
return pack("H*", $hex);
}
/**
* Set or get HTTP status code.
*
*/
function up_http_response_code($which=NULL) {
$cgi = ini_get("cgi.rfc2616_headers");
$headers = preg_grep("#^Status:|^HTTP/\d\.\d#i", headers_list());
# override
if ($which >= 100 and $which <= 999) {
if ($headers) {
header_remove(current($headers));
}
# implicit notices for headers_sent()
header($cgi ? "HTTP/1.0 $which n/a" : "Status: $which n/a");
}
# get current
elseif ($which == NULL) {
if (!$headers || !preg_match("/\d\d\d/", current($headers), $m)) {
return 200; #default
}
return intval($m[0]);
}
else trigger_error("invalid status number", E_USER_WARNING);
}
/**
* Sends a Location: header. Unlike the PHP-builtin, it won't complete relative URLs.
* So it's RFC6616 compliant, not anal about the original HTTP/1.1 revision RFC2616.
* The <meta> fallback is also extraneous.
* Belongs to http extensions actually. (Will be grouped out in later upgradephp revision.)
*
*/
function up_http_redirect($url, $params=array(), $session=false, $status=0) {
if ($session) {
$params[session_name()] = session_id();
}
if ($params) {
$url .= strstr($url, "?") ? "&" : "?";
$url .= http_build_query($params);
}
header("Location: $url"); #, $status ? $status : 301);
$url = htmlspecialchars($url, ENT_QUOTES, "UTF-8");
print "Redirecting to <a href=\"$url\">$url</a>\n";
print "<meta http-equiv=\"Location\" content=\"$url\" />\n";
exit; // built-in exit
}
/**
* Sends a Content-Type: header
* Belongs to http extensions actually. (Will be grouped out in later upgradephp revision.)
*
*/
function up_http_send_content_type($content_type="application/x-octetstream") {
return header("Content-Type: $content_type");
}
/**
* @stub
* Traits (partial classes, elaborate syntactic and academic workaround, because MI is
* hard to implement in *compiled* languages) cannot be emulated in older interpreters.
*
*/
function up_class_uses($trait) {
return false;
}
function up_trait_exists($trait) {
return false;
}
function up_get_declared_traits($trait) {
return (array)NULL;
}
/**
* Long predicted, officially available @since 5.4.
*
* Inflates a string enriched with gzip headers. Counterpart to gzencode().
*
*/
function up_gzdecode($gzdata, $maxlen=NULL) {
#-- decode header
$len = strlen($gzdata);
if ($len < 20) {
return;
}
$head = substr($gzdata, 0, 10);
$head = unpack("n1id/C1cm/C1flg/V1mtime/C1xfl/C1os", $head);
list($ID, $CM, $FLG, $MTIME, $XFL, $OS) = array_values($head);
$FTEXT = 1<<0;
$FHCRC = 1<<1;
$FEXTRA = 1<<2;
$FNAME = 1<<3;
$FCOMMENT = 1<<4;
$head = unpack("V1crc/V1isize", substr($gzdata, $len-8, 8));
list($CRC32, $ISIZE) = array_values($head);
#-- check gzip stream identifier
if ($ID != 0x1f8b) {
trigger_error("up_gzdecode: not in gzip format", E_USER_WARNING);
return;
}
#-- check for deflate algorithm
if ($CM != 8) {
trigger_error("up_gzdecode: cannot decode anything but deflated streams", E_USER_WARNING);
return;
}
#-- start of data, skip bonus fields
$s = 10;
if ($FLG & $FEXTRA) {
$s += $XFL;
}
if ($FLG & $FNAME) {
$s = strpos($gzdata, "\000", $s) + 1;
}
if ($FLG & $FCOMMENT) {
$s = strpos($gzdata, "\000", $s) + 1;
}
if ($FLG & $FHCRC) {
$s += 2; // cannot check
}
#-- get data, uncompress
$gzdata = substr($gzdata, $s, $len-$s);
if ($maxlen) {
$gzdata = gzinflate($gzdata, $maxlen);
return($gzdata); // no checks(?!)
}
else {
$gzdata = gzinflate($gzdata);
}
#-- check+fin
$chk = crc32($gzdata);
if ($CRC32 != $chk) {
trigger_error("up_gzdecode: checksum failed (real$chk != comp$CRC32)", E_USER_WARNING);
}
elseif ($ISIZE != strlen($gzdata)) {
trigger_error("up_gzdecode: stream size mismatch", E_USER_WARNING);
}
else {
return($gzdata);
}
}
/**
* Probes for format(?) before decoding with one of the gz* functions.
*
*/
function up_zlib_decode($data) {
if (!strncmp($data, "\x1F\x8B", 2)) {
return gzdecode($data);
}
elseif (!strncmp($data, "\x78\x9C", 2)) {
return gzuncompress($data);
}
else {
return gzinflate($data);
}
}
/**
* Weird constants, not documented in the manual yet, but that's how the function declaration looks.
*
*/
define("ZLIB_ENCODING_DEFLATE", 15);
define("ZLIB_ENCODING_RAW", -15);
define("ZLIB_ENCODING_GZIP", 31);
function up_zlib_encode($data, $method) {
if ($method == ZLIB_ENCODING_RAW) {
return gzdeflate($data);
}
elseif ($method == ZLIB_ENCODING_DEFLATE) {
return gzcompress($data);
}
elseif ($method == ZLIB_ENCODING_GZIP) {
return gzencode($data);
}
else trigger_error("encoding mode must be either ZLIB_ENCODING_RAW, ZLIB_ENCODING_GZIP or ZLIB_ENCODING_DEFLATE", E_USER_WARNING);
}
/**
* @stub Tests whether a session is established.
*
*/
define("PHP_SESSION_DISABLED", 0);
define("PHP_SESSION_NONE", 1);
define("PHP_SESSION_ACTIVE", 2);
function up_session_status() {
return (ini_get("session.name") != "") ? PHP_SESSION_DISABLED :
(isset($_SESSION) ? PHP_SESSION_ACTIVE : PHP_SESSION_NONE);
}
/**
* ----------------------------- 5.3 ---
* @group 5_3
* @since 5.3
*
* Known additions of PHP 5.3
*
* @emulated
* ob_get_headers (stub)
* preg_filter
* lcfirst
* class_alias
* header_remove
* parse_ini_string
* array_replace
* array_replace_recursive
* str_getcsv
* forward_static_call
* forward_static_call_array
* quoted_printable_encode
* E_DEPRECATED
* E_USER_DEPRECATED
*
* @missing
* get_called_class
* stream_context_get_params
* stream_context_set_default
* stream_supports_lock
* hash_copy
* date_create_from_format
* date_parse_from_format
* date_get_last_errors
* date_add
* date_sub
* date_diff
* date_timestamp_set
* date_timestamp_get
* timezone_location_get
* date_interval_create_from_date_string
* date_interval_format
*
*/
/**
* @since PHP 5.3.0
*/
if (!defined('E_DEPRECATED')) { define('E_DEPRECATED', 8192); }
if (!defined('E_USER_DEPRECATED')) { define('E_USER_DEPRECATED', 16384); }
/**
* preg_replace() variant, which filters out any unmatched $subject.
*
*/
function up_preg_filter($pattern, $replacement, $subject, $limit=-1, $count=NULL) {
// just do the replacing first, and eventually filter later
$r = preg_replace($pattern, $replacement, $subject, $limit, $count);
// look at subject lines one-by-one, remove from result per index
foreach ((array)$subject as $si=>$s) {
$any = 0;
foreach ((array)$pattern as $p) {
$any = $any ||preg_match($p, $s);
}
// remove if NONE of the patterns matched
if (!$any) {
if (is_array($r)) {
unset($r[$si]); // del from result array
}
else {
return NULL; // subject was a str
}
}
}
return $r; // is already string if $subject was too
}
/**
* Lowercase first character.
*
* @param string
* @return string
*/
function up_lcfirst($str) {
return strlen($str) ? strtolower($str[0]) . substr($str, 1) : "";
}
/**
* @stub cannot be emulated, because output buffering functions
* already swallow up any sent http header
* @since 5.3.?
*
* get all ob_ soaked headers(),
*
*/
function up_ob_get_headers() {
return (array)NULL;
}
/**
* @stub Cannot be emulated correctly, but let's try.
*
*/
function up_header_remove($name="") {
if (strlen($name) and ($name = preg_replace("/[^-_.\w\d]+/", "", $name))) header("$name: \t");
// Apache1.3? removed duplettes, empty header overrides previous.
// ONLY if case was identical to previous header() call. (Very uncertain for applications which need to resort to such code smell.)
}
/**
* WTF?
* At least an explaning reference was available on the php.net manual.
* Why the parameters are supposed to be optional is a mystery.
*
*/
function up_class_alias($original, $alias) {
$abstract = "";
if (class_exists("ReflectionClass")) {
$oc = new ReflectionClass($original);
$abstract = $oc->isAbstract() ? "abstract" : "";
}
eval("$abstract class $alias extends $original { /* identical subclass */ }");
return get_parent_class($alias) == $original;
}
/**
* Hey, reimplementin is fun.
* (Could have used a data: wrapper for parse_ini_file, but that wouldn't work for php<5.2, and the data:// (!) wrapper is flaky anyway.)
*
*/
function up_parse_ini_string($ini, $sectioned=false, $raw=0) {
$r = array();
$map = array("true"=>1, "yes"=>1, "1"=>1, "null"=>"", "false"=>"", "no"=>"", "0"=>0);
$section = "";
foreach (explode("\n", $ini) as $line) {
if (!strlen($line)) {
}
// handle [sections]
elseif (($line[0] == "[") and preg_match("/\[([-_\w ]+)\]/", $line, $uu)) {
$section = $uu[1];
}
elseif (/*deprecated*/($line[0] != "#") && ($line[0] != ";") && ($i = strpos($line, "="))) {
// key=value split
$n = trim(substr($line, 0, $i));
$v = trim(substr($line, $i+1));
// replace special values
if (!$raw) {
$v=trim($v, '"'); // should actually use regex, to handle key="..\n.." multiline values
$v=trim($v, "'");
if (isset($map[$v])) {
$v=$map[$v];
}
}
// special array[]= keys allowed
if ($i = strpos($n, "[")) {
$r[$section][substr($n, 0, $i)][] = $v;
}
else {
$r[$section][$n] = $v;
}
}
}
return $sectioned ? $r : call_user_func_array("array_merge", $r);
}
/**
* Inject values from supplemental arrays into $target, according to its keys.
*
* @param array $targt
* @param+ array $supplements
* @return array
*/
function up_array_replace(/* & (?) */$target/*, $from, $from2, ...*/) {
$merge = func_get_args();
array_shift($merge);
foreach ($merge as $add) {
foreach ($add as $i=>$v) {
$target[$i] = $v;
}
}
return $target;
}
/**
* Descends into sub-arrays when replacing values by key in $target array.
*
*/
function up_array_replace_recursive($target/*, $from1, $from2, ...*/) {
$merge = func_get_args();
array_shift($merge);
// loop through all merge arrays
foreach ($merge as $from) {
foreach ($from as $i=>$v) {
// just add (wether array or scalar) if key does not exist yet
if (!isset($target[$i])) {
$target[$i] = $v;
}
// dive in
elseif (is_array($v) && is_array($target[$i])) {
$target[$i] = up_array_replace_recursive($target[$i], $v);
}
// replace
else {
$target[$i] = $v;
}
}
}
return $target;
}
/**
* Breaks up a SINGLE LINE in CSV format.
* abc,123,"text with spaces",xy,"\""
*
*/
function up_str_getcsv($line, $del=",", $q='"', $esc="\\", $rm_spaces="\s*") {
$line = rtrim($line, "\r\n");
preg_match_all("/\G $rm_spaces ([^$q$del]*?) $rm_spaces $del | $q(( [$esc$esc][$q]|[^$q]* )+)$q \s* $del /xms", $line.$del, $r);
foreach ($r[1] as $i=>$v) { // merge both captures
if (empty($v) && strlen($r[2][$i])) {
$r[1][$i] = str_replace("$esc$q", "$q", $r[2][$i]); // remove escape character
} # use stripcslashes to support standard CSV \r \n escapes
}
return($r[1]);
}
/**
* @stub: Basically aliases for function calls; just throw an error if called from main() and not from within a class.
* The real implementations would behave on late static binding, though.
*
*/
function up_forward_static_call_array($callback, $args=NULL) {
return call_user_func_array($callback, $args);
}
function up_forward_static_call($callback /*, ... */) {
$args = func_get_args();
array_shift($args);
return call_user_func_array($callback, $args);
}
/**
* Encodes special chars as =0D=0A patterns. Soft-break at 76 characters.
*
*/
function up_quoted_printable_encode($str) {
$str = preg_replace("/([\\000-\\041=\\176-\\377])/e", "'='.strtoupper(dechex(ord('\$1')))", $str);
$str = preg_replace("/(.{1,76})(?<=[^=][^=])/ims", "\$1=\r\n", $str); // QP-soft-break
return $str;
}
/**
* ------------------------------ 5.2 ---
* @group 5_2
* @since 5.2
*
* Additions of PHP 5.2.0
* - some listed here might have appeared earlier or in release candidates
*
* @emulated
* json_encode
* json_decode
* error_get_last
* preg_last_error
* lchown
* lchgrp
* E_RECOVERABLE_ERROR
* M_SQRTPI
* M_LNPI
* M_EULER
* M_SQRT3
* array_fill_keys (@doc: 4.2 or 5.2 ?)
* array_diff_key (@doc: 5.1 or 5.2 ?)
* array_diff_ukey
* array_product
* inet_ntop
* inet_pton
* array_intersect_key
* array_intersect_ukey
* mysql_set_charset
*
* @missing
* sys_getloadavg
* ftp_ssl_connect
* XmlReader
* XmlWriter
* PDO*
* pdo_drivers (should be in ext/pdo)
*
* @unimplementable
* stream_*
*
*/
/**
* @since unknown
*/
if (!defined("E_RECOVERABLE_ERROR")) { define("E_RECOVERABLE_ERROR", 4096); }
/**
* Converts PHP variable or array into a "JSON" (JavaScript value expression
* or "object notation") string.
*
* @compat
* Output seems identical to PECL versions. "Only" 20x slower than PECL version.
* @bugs
* Doesn't take care with unicode too much - leaves UTF-8 sequences alone.
*
* @param $var mixed PHP variable/array/object
* @return string transformed into JSON equivalent
*/
if (!defined("JSON_HEX_TAG")) {
define("JSON_HEX_TAG", 1);
define("JSON_HEX_AMP", 2);
define("JSON_HEX_APOS", 4);
define("JSON_HEX_QUOT", 8);
define("JSON_FORCE_OBJECT", 16);
}
if (!defined("JSON_NUMERIC_CHECK")) {
define("JSON_NUMERIC_CHECK", 32); // 5.3.3
}
if (!defined("JSON_UNESCAPED_SLASHES")) {
define("JSON_UNESCAPED_SLASHES", 64); // 5.4.0
define("JSON_PRETTY_PRINT", 128); // 5.4.0
define("JSON_UNESCAPED_UNICODE", 256); // 5.4.0
}
function up_json_encode($var, $options=0, $_indent="") {
#-- prepare JSON string
$obj = ($options & JSON_FORCE_OBJECT);
list($_space, $_tab, $_nl) = ($options & JSON_PRETTY_PRINT) ? array(" ", " $_indent", "\n") : array("", "", "");
$json = "$_indent";
if ($options & JSON_NUMERIC_CHECK and is_string($var) and is_numeric($var)) {
$var = (strpos($var, ".") || strpos($var, "e")) ? floatval($var) : intval($var);
}
#-- add array entries
if (is_array($var) || ($obj=is_object($var))) {
#-- check if array is associative
if (!$obj) {
$keys = array_keys((array)$var);
$obj = !($keys == array_keys($keys)); // keys must be in 0,1,2,3, ordering, but PHP treats integers==strings otherwise
}
#-- concat individual entries
$empty = 0; $json = "";
foreach ((array)$var as $i=>$v) {
$json .= ($empty++ ? ",$_nl" : "") // comma separators
. $_tab . ($obj ? (up_json_encode($i, $options, $_tab) . ":$_space") : "") // assoc prefix
. (up_json_encode($v, $options, $_tab)); // value
}
#-- enclose into braces or brackets
$json = $obj ? "{"."$_nl$json$_nl$_indent}" : "[$_nl$json$_nl$_indent]";
}
#-- strings need some care
elseif (is_string($var)) {
if (!utf8_decode($var)) {
trigger_error("up_json_encode: invalid UTF-8 encoding in string, cannot proceed.", E_USER_WARNING);
$var = NULL;
}
$rewrite = array(
"\\" => "\\\\",
"\"" => "\\\"",
"\010" => "\\b",
"\f" => "\\f",
"\n" => "\\n",
"\r" => "\\r",
"\t" => "\\t",
"/" => $options & JSON_UNESCAPED_SLASHES ? "/" : "\\/",
"<" => $options & JSON_HEX_TAG ? "\\u003C" : "<",
">" => $options & JSON_HEX_TAG ? "\\u003E" : ">",
"'" => $options & JSON_HEX_APOS ? "\\u0027" : "'",
"\"" => $options & JSON_HEX_QUOT ? "\\u0022" : "\"",
"&" => $options & JSON_HEX_AMP ? "\\u0026" : "&",
);
$var = strtr($var, $rewrite);
//@COMPAT control chars should probably be stripped beforehand, not escaped as here
if (function_exists("iconv") && ($options & JSON_UNESCAPED_UNICODE) == 0) {
$var = preg_replace("/[^\\x{0020}-\\x{007F}]/ue", "'\\u'.current(unpack('H*', iconv('UTF-8', 'UCS-2BE', '$0')))", $var);
}
$json = '"' . $var . '"';
}
#-- basic types
elseif (is_bool($var)) {
$json = $var ? "true" : "false";
}
elseif ($var === NULL) {
$json = "null";
}
elseif (is_int($var) || is_float($var)) {
$json = "$var";
}
#-- something went wrong
else {
trigger_error("up_json_encode: don't know what a '" .gettype($var). "' is.", E_USER_WARNING);
}
#-- done
return($json);
}
/**
* Parses a JSON (JavaScript value expression) string into a PHP variable
* (array or object).
*
* @compat
* Behaves similar to PECL version, but is less quiet on errors.
* Now even decodes unicode \uXXXX string escapes into UTF-8.
* "Only" 27 times slower than native function.
* @bugs
* Might parse some misformed representations, when other implementations
* would scream error or explode.
* @code
* This is state machine spaghetti code. Needs the extranous parameters to
* process subarrays, etc. When it recursively calls itself, $n is the
* current position, and $waitfor a string with possible end-tokens.
*
* @param $json string JSON encoded values
* @param $assoc bool pack data into php array/hashes instead of objects
* @return mixed parsed into PHP variable/array/object
*/
define("JSON_OBJECT_AS_ARRAY", 1); // undocumented
define("JSON_BIGINT_AS_STRING", 2); // 5.4.0
define("JSON_PARSE_JAVASCRIPT", 4); // unquoted object keys, and single quotes ' strings identical to double quoted, more relaxed parsing
function up_json_decode($json, $assoc=FALSE, $limit=512, $options=0, /*emu_args*/$n=0,$state=0,$waitfor=0) {
global ${'.json_last_error'}; ${'.json_last_error'} = JSON_ERROR_NONE;
#-- result var
$val = NULL;
$FAILURE = array(/*$val:=*/ NULL, /*$n:=*/ 1<<31);
static $lang_eq = array("true" => TRUE, "false" => FALSE, "null" => NULL);
static $str_eq = array("n"=>"\012", "r"=>"\015", "\\"=>"\\", '"'=>'"', "f"=>"\f", "b"=>"\010", "t"=>"\t", "/"=>"/");
if ($limit<0) { ${'.json_last_error'} = JSON_ERROR_DEPTH; return /* __cannot_compensate */; }
#-- strip UTF-8 BOM (the native version doesn't do this, but .. should)
while (strncmp($json, "\xEF\xBB\xBF", 3) == 0) {
trigger_error("UTF-8 BOM prefaces JSON, that's invalid for PHPs native up_json_decode", E_USER_ERROR);
$json = substr($json, 3);
}
#-- flat char-wise parsing
for (/*$n=0,*/ $len = strlen($json); $n<$len; /*$n++*/) {
$c = $json[$n];
#-= in-string
if ($state==='"' or $state==="'") {
if ($c == '\\') {
$c = $json[++$n];
// simple C escapes
if (isset($str_eq[$c])) {
$val .= $str_eq[$c];
}
// here we transform \uXXXX Unicode (always 4 nibbles) references to UTF-8
elseif ($c == "u") {
// read just 16bit (therefore value can't be negative)
$hex = hexdec( substr($json, $n+1, 4) );
$n += 4;
// Unicode ranges
if ($hex < 0x80) { // plain ASCII character
$val .= chr($hex);
}
elseif ($hex < 0x800) { // 110xxxxx 10xxxxxx
$val .= chr(0xC0 + $hex>>6) . chr(0x80 + $hex&63);
}
elseif ($hex <= 0xFFFF) { // 1110xxxx 10xxxxxx 10xxxxxx
$val .= chr(0xE0 + $hex>>12) . chr(0x80 + ($hex>>6)&63) . chr(0x80 + $hex&63);
}
// other ranges, like 0x1FFFFF=0xF0, 0x3FFFFFF=0xF8 and 0x7FFFFFFF=0xFC do not apply
}
// for JS (not JSON) the extraneous backslash just gets omitted
elseif ($options & JSON_PARSE_JAVASCRIPT) {
if (is_numeric($c) and preg_match("/[0-3][0-7][0-7]|[0-7]{1,2}/", substr($json, $n), $m)) {
$val .= chr(octdec($m[0]));
$n += strlen($m[0]) - 1;
}
else {
$val .= $c;
}
}
// redundant backslashes disallowed in JSON
else {
$val .= "\\$c";
${'.json_last_error'} = JSON_ERROR_CTRL_CHAR; // not quite, but
trigger_error("Invalid backslash escape for JSON \\$c", E_USER_WARNING);
return $FAILURE;
}
}
// end of string
elseif ($c == $state) {
$state = 0;
}
//@COMPAT: specialchars check - but native json doesn't do it?
#elseif (ord($c) < 32) && !in_array($c, $str_eq)) {
# ${'.json_last_error'} = JSON_ERROR_CTRL_CHAR;
#}
// a single character was found
else/*if (ord($c) >= 32)*/ {
$val .= $c;
}
}
#-> end of sub-call (array/object)
elseif ($waitfor && (strpos($waitfor, $c) !== false)) {
return array($val, $n); // return current value and state
}
#-= in-array
elseif ($state===']') {
list($v, $n) = up_json_decode($json, $assoc, $limit, $options, $n, 0, ",]");
$val[] = $v;
if ($json[$n] == "]") { return array($val, $n); }
}
#-= in-object
elseif ($state==='}') {
// quick regex parsing cheat for unquoted JS object keys
if ($options & JSON_PARSE_JAVASCRIPT and $c != '"' and preg_match("/^\s*(?!\d)(\w\pL*)\s*/u", substr($json, $n), $m)) {
$i = $m[1];
$n = $n + strlen($m[0]);
}
else {
// this allowed non-string indicies
list($i, $n) = up_json_decode($json, $assoc, $limit, $options, $n, 0, ":");
}
list($v, $n) = up_json_decode($json, $assoc, $limit, $options, $n+1, 0, ",}");
$val[$i] = $v;
if ($json[$n] == "}") { return array($val, $n); }
}
#-- looking for next item (0)
else {
#-> whitespace
if (preg_match("/\s/", $c)) {
// skip
}
#-> string begin
elseif ($c == '"') {
$state = $c;
}
#-> object
elseif ($c == "{") {
list($val, $n) = up_json_decode($json, $assoc, $limit-1, $options, $n+1, '}', "}");
if ($val && $n) {
$val = $assoc ? (array)$val : (object)$val;
}
}
#-> array
elseif ($c == "[") {
list($val, $n) = up_json_decode($json, $assoc, $limit-1, $options, $n+1, ']', "]");
}
#-> numbers
elseif (preg_match("#^(-?\d+(?:\.\d+)?)(?:[eE]([-+]?\d+))?#", substr($json, $n), $uu)) {
$val = $uu[1];
$n += strlen($uu[0]) - 1;
if (strpos($val, ".")) { // float
$val = floatval($val);
}
elseif ($val[0] == "0") { // oct
$val = octdec($val);
}
else {
$toobig = strval(intval($val)) !== strval($val);
if ($toobig and !isset($uu[2]) and ($options & JSON_BIGINT_AS_STRING)) {
$val = $val; // keep lengthy numbers as string
}
elseif ($toobig or isset($uu[2])) { // must become float anyway
$val = floatval($val);
}
else { // int
$val = intval($val);
}
}
// exponent?
if (isset($uu[2])) {
$val *= pow(10, (int)$uu[2]);
}
}
#-> boolean or null
elseif (preg_match("#^(true|false|null)\b#", substr($json, $n), $uu)) {
$val = $lang_eq[$uu[1]];
$n += strlen($uu[1]) - 1;
}
#-> JS-string begin
elseif ($options & JSON_PARSE_JAVASCRIPT and $c == "'") {
$state = $c;
}
#-> comment
elseif ($options & JSON_PARSE_JAVASCRIPT and ($c == "/") and ($json[$n+1]=="*")) {
// just find end, skip over
($n = strpos($json, "*/", $n+1)) or ($n = strlen($json));
}
#-- parsing error
else {
// PHPs native up_json_decode() breaks here usually and QUIETLY
trigger_error("up_json_decode: error parsing '$c' at position $n", E_USER_WARNING);
${'.json_last_error'} = JSON_ERROR_SYNTAX;
return $waitfor ? $FAILURE : NULL;