Source

php-bootstrap-boilerplate / lib / base.php

Full commit
   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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
<?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 <bong.cosca@yahoo.com>

		@package Base
		@version 2.0.13
**/

//! Base structure
class Base {

	//@{ Framework details
	const
		TEXT_AppName='Fat-Free Framework',
		TEXT_Version='2.0.13',
		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,
		$classes,
		$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')?
					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 $exp?pow(1024,strpos($greek,$exp)+1)*(int)$str:$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::resolve('{{'.$match.'}}');
				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++;
		}
		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
			@param $append bool
			@public
	**/
	static function putfile($file,$data,$append=FALSE) {
		if (!function_exists('flock'))
			$out=self::mutex(
				function() use($file,$data) {
					$flag=LOCK_EX;
					if ($append)
						$flag=$flag|FILE_APPEND;
					return file_put_contents($file,$data,$arg);
				},
				$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=NULL) {
		$all=($resolve===TRUE);
		if (is_null($resolve))
			$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) && $all) {
				$var=array();
				// Recursive token substitution
				foreach ($val as $subk=>$subv) {
					$subp=$key.'['.var_export($subk,TRUE).']';
					self::set($subp,$subv,FALSE,$all);
					$val[$subk]=self::ref($subp);
				}
			}
		}
		$var=$val;
		if (preg_match('/^(?:GET|POST|COOKIE)/',$key,$php)) {
			// Sync with REQUEST
			$var=&self::ref(preg_replace('/^'.$php[0].'\b/','REQUEST',$key));
			$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($val);
		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))
				for ($i=0,$c=count($ini);$i<$c;$i++) {
					// cut off CR / LF
					$line = rtrim($ini[$i],"\r\n");
					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]) {
						if (substr($line, -1) == "\\") {
							// multiline string
							$lines = rtrim($parts[4],"\\");
							while (++$i < $c) {
								$line = rtrim($ini[$i],"\r\n");
								$lines.= PHP_EOL .rtrim($line,"\\");
								if (substr($line,-1) !== "\\")
									break;
							}
							$parts[4] = $lines;
						}
						$parts[4]=preg_replace('/(?<=")(.+?)(?=")/',
							"\x00\\1",$parts[4]);
						// Key-value pair
						$csv=array_map(
							function($val) {
								$q='';
								if ($val[0]=="\x00")
									$q='"';
								$val=trim($val);
								return is_numeric($val) ||
									preg_match('/^\w+$/i',$val) &&
									defined($val)?
									eval('return '.$q.$val.$q.';'):$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).','.
							(is_array($val) && $sec!='globals'?
								self::csv($val):self::stringify($val)).');'.
							"\n";
			$save=ob_get_clean();
			// Compress and save to cache
			Cache::set($hash,$save);
		}
		// Execute cached PHP code
		eval($save);
		if (!is_null(self::$vars['ERROR']))
			// Remove from cache
			Cache::clear($hash);
	}

	/**
		Convert special characters to HTML entities using globally-
		defined character set
			@return string
			@param $str string
			@param $all bool
			@public
	**/
	static function htmlencode($str,$all=FALSE) {
		return is_string($str)?
			call_user_func($all?'htmlentities':'htmlspecialchars',
				$str,ENT_COMPAT,self::$vars['ENCODING'],FALSE):
			$str;
	}

	/**
		Convert HTML entities back to their equivalent characters
			@return string
			@param $str string
			@param $all bool
			@public
	**/
	static function htmldecode($str,$all=FALSE) {
		return is_string($str)?
			($all?
				html_entity_decode($str,ENT_COMPAT,self::$vars['ENCODING']):
				htmlspecialchars_decode($str,ENT_COMPAT)):
			$str;
	}

	/**
		Send HTTP status header; Return text equivalent of status code
			@return mixed
			@param $code int
			@public
	**/
	static function status($code) {
		if (!defined('self::HTTP_'.$code)) {
			// Invalid status code
			trigger_error(sprintf(self::TEXT_HTTP,$code));
			return FALSE;
		}
		// Get description
		$response=constant('self::HTTP_'.$code);
		// Send raw HTTP header
		if (PHP_SAPI!='cli' && !headers_sent())
			header($_SERVER['SERVER_PROTOCOL'].' '.$code.' '.$response);
		return $response;
	}

	/**
		Retrieve HTTP headers
			@return array
			@public
	**/
	static function headers() {
		if (PHP_SAPI!='cli') {
			if (function_exists('getallheaders'))
				// Apache server
				return getallheaders();
			// Workaround
			$req=array();
			foreach ($_SERVER as $key=>$val)
				if (substr($key,0,5)=='HTTP_')
					$req[strtr(ucwords(strtolower(
						strtr(substr($key,5),'_',' '))),' ','-')]=$val;
			return $req;
		}
		return array();
	}

	/**
		Send HTTP header with expiration date (seconds from current time)
			@param $secs int
			@public
	**/
	static function expire($secs=0) {
		if (PHP_SAPI!='cli' && !headers_sent()) {
			$time=time();
			$req=self::headers();
			if (isset($req[self::HTTP_IfMod]) &&
				strtotime($req[self::HTTP_IfMod])+$secs>$time) {
				self::status(304);
				die;
			}
			header(self::HTTP_Powered.': '.self::TEXT_AppName.' '.
				'('.self::TEXT_AppURL.')');
			if ($secs) {
				header_remove(self::HTTP_Pragma);
				header(self::HTTP_Expires.': '.gmdate('r',$time+$secs));
				header(self::HTTP_Cache.': max-age='.$secs);
				header(self::HTTP_LastMod.': '.gmdate('r'));
			}
			else {
				header(self::HTTP_Pragma.': no-cache');
				header(self::HTTP_Cache.': no-cache, must-revalidate');
			}
		}
	}

	/**
		Reroute to specified URI
			@param $uri string
			@public
	**/
	static function reroute($uri) {
		$uri=self::resolve($uri);
		if (PHP_SAPI!='cli' && !headers_sent()) {
			// HTTP redirect
			self::status($_SERVER['REQUEST_METHOD']=='GET'?301:303);
			if (session_id())
				session_commit();
			header(self::HTTP_Location.': '.
				(preg_match('/^https?:\/\//',$uri)?
					$uri:(self::$vars['BASE'].$uri)));
			die;
		}
		self::mock('GET '.$uri);
		self::run();
	}

	/**
		Assign handler to route pattern
			@param $pattern string
			@param $funcs mixed
			@param $ttl int
			@param $throttle int
			@param $hotlink bool
			@public
	**/
	static function route($pattern,$funcs,$ttl=0,$throttle=0,$hotlink=TRUE) {
		list($methods,$uri)=
			preg_split('/\s+/',$pattern,2,PREG_SPLIT_NO_EMPTY);
		foreach (self::split($methods) as $method)
			// Use pattern and HTTP methods as route indexes
			self::$vars['ROUTES'][$uri][strtoupper($method)]=
				// Save handler, cache timeout and hotlink permission
				array($funcs,$ttl,$throttle,$hotlink);
	}

	/**
		Provide REST interface by mapping URL to object/class
			@param $url string
			@param $class mixed
			@param $ttl int
			@param $throttle int
			@param $hotlink bool
			@param $prefix string
			@public
	**/
	static function map(
		$url,$class,$ttl=0,$throttle=0,$hotlink=TRUE,$prefix='') {
		foreach (explode('|',self::HTTP_Methods) as $method) {
			$func=$prefix.$method;
			if (method_exists($class,$func)) {
				$ref=new ReflectionMethod($class,$func);
				self::route(
					$method.' '.$url,
					$ref->isStatic()?
						array($class,$func):
						array(new $class,$func),
					$ttl,$throttle,$hotlink
				);
				unset($ref);
			}
		}
	}

	/**
		Call route handler
			@return mixed
			@param $funcs string
			@param $listen bool
			@public
	**/
	static function call($funcs,$listen=FALSE) {
		$funcs=is_string($funcs)?self::split($funcs):array($funcs);
		$out=NULL;
		foreach ($funcs as $func) {
			if (is_string($func)) {
				$func=self::resolve($func);
				if (preg_match('/(.+)\s*(->|::)\s*(.+)/s',$func,$match)) {
					if (!class_exists($match[1]) ||
						!method_exists($match[1],'__call') &&
						!method_exists($match[1],$match[3])) {
						self::error(404);
						return FALSE;
					}
					$func=array($match[2]=='->'?
						new $match[1]:$match[1],$match[3]);
				}
				elseif (!function_exists($func)) {
					$found=FALSE;
					if (preg_match('/\.php$/i',$func)) {
						$found=FALSE;
						foreach (self::split(self::$vars['IMPORTS'])
							as $path)
							if (is_file($file=$path.$func)) {
								$instance=new F3instance;
								if ($instance->sandbox($file)===FALSE)
									return FALSE;
								$found=TRUE;
							}
						if ($found)
							continue;
					}
					self::error(404);
					return FALSE;
				}
			}
			if (!is_callable($func)) {
				self::error(404);
				return FALSE;
			}
			$oop=is_array($func) &&
				(is_object($func[0]) || is_string($func[0]));
			if ($listen && $oop &&
				method_exists($func[0],$before='beforeRoute')) {
				// Execute beforeRoute() once per class
				$key=is_object($func[0])?get_class($func[0]):$func[0];
				if (!isset(self::$classes[$key]) ||
					!isset(self::$classes[$key][0]) ||
					!self::$classes[$key][0]) {
					self::$classes[$key][0]=TRUE;
					if (call_user_func(array($func[0],$before))===FALSE)
						return FALSE;
				}
			}
			$out=call_user_func($func);
			if ($listen && $oop &&
				method_exists($func[0],$after='afterRoute')) {
				// Execute afterRoute() once per class
				$key=is_object($func[0])?get_class($func[0]):$func[0];
				if (!isset(self::$classes[$key]) ||
					!isset(self::$classes[$key][1]) ||
					!self::$classes[$key][1]) {
					self::$classes[$key][1]=TRUE;
					if (call_user_func(array($func[0],$after))===FALSE)
						return FALSE;
				}
			}
		}
		return $out;
	}

	/**
		Process routes based on incoming URI
			@public
	**/
	static function run() {
		// Validate user against spam blacklists
		if (self::$vars['DNSBL'] && !self::privateip($addr=self::realip()) &&
			(!self::$vars['EXEMPT'] ||
			!in_array($addr,self::split(self::$vars['EXEMPT'])))) {
			// Convert to reverse IP dotted quad
			$quad=implode('.',array_reverse(explode('.',$addr)));
			foreach (self::split(self::$vars['DNSBL']) as $list)
				// Check against DNS blacklist
				if (gethostbyname($quad.'.'.$list)!=$quad.'.'.$list) {
					if (self::$vars['SPAM'])
						// Spammer detected; Send to blackhole
						self::reroute(self::$vars['SPAM']);
					else {
						// Forbidden
						self::error(403);
						die;
					}
				}
		}
		// Process routes
		if (!isset(self::$vars['ROUTES']) || !self::$vars['ROUTES']) {
			trigger_error(self::TEXT_NoRoutes);
			return;
		}
		$allowed=array();
		// Detailed routes get matched first
		krsort(self::$vars['ROUTES']);
		$time=time();
		$case=self::$vars['CASELESS']?'i':'';
		$req=preg_replace('/^'.preg_quote(self::$vars['BASE'],'/').
			'\b(.+)/'.$case,'\1',
			rawurldecode($_SERVER['REQUEST_URI']));
		foreach (self::$vars['ROUTES'] as $uri=>$route) {
			if (!preg_match('/^'.
				preg_replace(
					'/(?:\\\{\\\{)?@(\w+\b)(?:\\\}\\\})?/',
					// Delimiter-based matching
					'(?P<\1>[^\/&\?]+)',
					// Wildcard character in URI
					str_replace('\*','(.*)',preg_quote($uri,'/'))
				).'\/?(?:\?.*)?$/'.$case.'um',
				$req,$args))
				continue;
			$wild=is_int(strpos($uri,'/*'));
			// Inspect each defined route
			foreach ($route as $method=>$proc) {
				if (!preg_match('/HEAD|'.$method.'/',
					$_SERVER['REQUEST_METHOD']))
					continue;
				if ($method=='GET' &&
					strlen($path=parse_url($req,PHP_URL_PATH))>1 &&
					substr($path,-1)=='/') {
					$query=parse_url($req,PHP_URL_QUERY);
					self::reroute(substr($path,0,-1).
						($query?('?'.$query):''));
				}
				self::$vars['PATTERN']=$uri;
				list($funcs,$ttl,$throttle,$hotlink)=$proc;
				if (!$hotlink && isset(self::$vars['HOTLINK']) &&
					isset($_SERVER['HTTP_REFERER']) &&
					parse_url($_SERVER['HTTP_REFERER'],PHP_URL_HOST)!=
						$_SERVER['SERVER_NAME'])
					// Hot link detected; Redirect page
					self::reroute(self::$vars['HOTLINK']);
				if (!$wild)
					// Save named uri captures
					foreach (array_keys($args) as $key)
						// Remove non-zero indexed elements
						if (is_numeric($key) && $key)
							unset($args[$key]);
				self::$vars['PARAMS']=$args;
				// Default: Do not cache
				self::expire(0);
				if ($_SERVER['REQUEST_METHOD']=='GET' && $ttl) {
					$_SERVER['REQUEST_TTL']=$ttl;
					// Get HTTP request headers
					$req=self::headers();
					// Content divider
					$div=chr(0);
					// Get hash code for this Web page
					$hash='url.'.self::hash(
						$_SERVER['REQUEST_METHOD'].' '.
						$_SERVER['REQUEST_URI']
					);
					$cached=Cache::cached($hash);
					$uri='/^'.self::HTTP_Content.':.+/';
					if ($cached && $time-$cached<$ttl) {
						if (!isset($req[self::HTTP_IfMod]) ||
							$cached>strtotime($req[self::HTTP_IfMod])) {
							// Activate cache timer
							self::expire($cached+$ttl-$time);
							// Retrieve from cache
							$buffer=Cache::get($hash);
							$type=strstr($buffer,$div,TRUE);
							if (PHP_SAPI!='cli' && !headers_sent() &&
								preg_match($uri,$type,$match))
								// Cached MIME type
								header($match[0]);
							// Save response
							self::$vars['RESPONSE']=substr(
								strstr($buffer,$div),1);
						}
						else {
							// Client-side cache is still fresh
							self::status(304);
							die;
						}
					}
					else {
						// Activate cache timer
						self::expire($ttl);
						$type='';
						foreach (headers_list() as $hdr)
							if (preg_match($uri,$hdr)) {
								// Add Content-Type header to buffer
								$type=$hdr;
								break;
							}
						// Cache this page
						ob_start();
						self::call($funcs,TRUE);
						self::$vars['RESPONSE']=ob_get_clean();
						if (!self::$vars['ERROR'] &&
							self::$vars['RESPONSE'])
							// Compress and save to cache
							Cache::set($hash,
								$type.$div.self::$vars['RESPONSE']);
					}
				}
				else {
					// Capture output
					ob_start();
					self::$vars['REQBODY']=file_get_contents('php://input');
					self::call($funcs,TRUE);
					self::$vars['RESPONSE']=ob_get_clean();
				}
				$elapsed=time()-$time;
				$throttle=$throttle?:self::$vars['THROTTLE'];
				if ($throttle/1e3>$elapsed)
					// Delay output
					usleep(1e6*($throttle/1e3-$elapsed));
				if (strlen(self::$vars['RESPONSE']) && !self::$vars['QUIET'])
					// Display response
					echo self::$vars['RESPONSE'];
				// Hail the conquering hero
				return;
			}
			$allowed=array_keys($route);
		}
		if (!$allowed) {
			// No such Web page
			self::error(404);
			return;
		}
		// Method not allowed
		if (PHP_SAPI!='cli' && !headers_sent())
			header(self::HTTP_Allow.': '.implode(',',$allowed));
		self::error(405);
	}

	/**
		Transmit a file for downloading by HTTP client; If kilobytes per
		second is specified, output is throttled (bandwidth will not be
		controlled by default); Return TRUE if successful, FALSE otherwise;
		Support for partial downloads is indicated by third argument;
		Download as attachment if fourth argument is TRUE
			@param $file string
			@param $kbps int
			@param $partial bool
			@param $attach bool
			@public
	**/
	static function send($file,$kbps=0,$partial=TRUE,$attach=FALSE) {
		$file=self::resolve($file);
		if (!is_file($file)) {
			self::error(404);
			return FALSE;
		}
		if (PHP_SAPI!='cli' && !headers_sent()) {
			header(self::HTTP_Content.': application/octet-stream');
			header(self::HTTP_Partial.': '.($partial?'bytes':'none'));
			header(self::HTTP_Length.': '.filesize($file));
			if ($attach)
				header(self::HTTP_Disposition.': attachment; '.
					'filename="'.basename($file).'"');
			flush();
		}
		$ctr=1;
		$handle=fopen($file,'r');
		$time=microtime(TRUE);
		while (!feof($handle) && !connection_aborted()) {
			if ($kbps) {
				// Throttle bandwidth
				$ctr++;
				if (($ctr/$kbps)>$elapsed=microtime(TRUE)-$time)
					usleep(1e6*($ctr/$kbps-$elapsed));
			}
			// Send 1KiB and reset timer
			echo fread($handle,1024);
			flush();
		}
		fclose($handle);
		die;
	}

	/**
		Remove HTML tags (except those enumerated) to protect against
		XSS/code injection attacks
			@return mixed
			@param $input string
			@param $tags string
			@public
	**/
	static function scrub($input,$tags=NULL) {
		if (is_array($input))
			foreach ($input as &$val)
				$val=self::scrub($val,$tags);
		if (is_string($input)) {
			$input=($tags=='*')?
				$input:strip_tags($input,is_string($tags)?
					('<'.implode('><',self::split($tags)).'>'):$tags);
		}
		return $input;
	}

	/**
		Call form field handler
			@param $fields string
			@param $funcs mixed
			@param $tags string
			@param $filter int
			@param $opt array
			@param $assign bool
			@public
	**/
	static function input($fields,$funcs=NULL,
		$tags=NULL,$filter=FILTER_UNSAFE_RAW,$opt=array(),$assign=TRUE) {
		$funcs=is_string($funcs)?self::split($funcs):array($funcs);
		$found=FALSE;
		foreach (self::split($fields) as $field)
			// Sanitize relevant globals
			foreach (explode('|','GET|POST|REQUEST') as $var)
				if (self::exists($var.'.'.$field)) {
					$key=&self::ref($var.'.'.$field);
					if (is_array($key))
						foreach ($key as $sub)
							self::input(
								$sub,$funcs,$tags,$filter,$opt,$assign
							);
					else {
						$key=self::scrub($key,$tags);
						$val=filter_var($key,$filter,$opt);
						$out=NULL;
						foreach ($funcs as $func) {
							if (is_string($func)) {
								$func=self::resolve($func);
								if (preg_match('/(.+)\s*(->|::)\s*(.+)/s',
									$func,$match)) {
									if (!class_exists($match[1]) ||
										!method_exists($match[1],'__call') &&
										!method_exists($match[1],$match[3])) {
										// Invalid handler
										trigger_error(
											sprintf(self::TEXT_Form,$field)
										);
										return;
									}
									$func=array($match[2]=='->'?
										new $match[1]:$match[1],$match[3]);
								}
								elseif (!function_exists($func)) {
									// Invalid handler
									trigger_error(
										sprintf(self::TEXT_Form,$field)
									);
									return;
								}
							}
							if (!is_callable($func)) {
								// Invalid handler
								trigger_error(
									sprintf(self::TEXT_Form,$field)
								);
								return;
							}
							$found=TRUE;
							$out=call_user_func($func,$val,$field);
							if ($assign && $out)
								$key=$out;
						}
					}
				}
		if (!$found)
			// Invalid handler
			trigger_error(sprintf(self::TEXT_Form,$field));
		return;
	}

	/**
		Render user interface
			@return string
			@param $file string
			@public
	**/
	static function render($file) {
		$file=self::resolve($file);
		foreach (self::split(self::$vars['GUI']) as $gui)
			if (is_file($view=self::fixslashes($gui.$file))) {
				$instance=new F3instance;
				$out=$instance->grab($view);
				return self::$vars['TIDY']?self::tidy($out):$out;
			}
		trigger_error(sprintf(self::TEXT_Render,$view));
	}

	/**
		Return runtime performance analytics
			@return array
			@public
	**/
	static function profile() {
		$stats=&self::$vars['STATS'];
		// Compute elapsed time
		$stats['TIME']['elapsed']=microtime(TRUE)-$stats['TIME']['start'];
		// Compute memory consumption
		$stats['MEMORY']['current']=memory_get_usage();
		$stats['MEMORY']['peak']=memory_get_peak_usage();
		return $stats;
	}

	/**
		Mock environment for command-line use and/or unit testing
			@param $pattern string
			@param $args array
			@public
	**/
	static function mock($pattern,array $args=NULL) {
		list($method,$uri)=explode(' ',$pattern,2);
		$method=strtoupper($method);
		$url=parse_url($uri);
		$query='';
		if ($args)
			$query.=http_build_query($args);
		$query.=isset($url['query'])?(($query?'&':'').$url['query']):'';
		if ($query) {
			parse_str($query,$GLOBALS['_'.$method]);
			parse_str($query,$GLOBALS['_REQUEST']);
		}
		$_SERVER['REQUEST_METHOD']=$method;
		$_SERVER['REQUEST_URI']=self::$vars['BASE'].$url['path'].
			($query?('?'.$query):'');
	}

	/**
		Perform test and append result to TEST global variable
			@return string
			@param $cond bool
			@param $pass string
			@param $fail string
			@public
	**/
	static function expect($cond,$pass=NULL,$fail=NULL) {
		if (is_string($cond))
			$cond=self::resolve($cond);
		$text=$cond?$pass:$fail;
		self::$vars['TEST'][]=array(
			'result'=>(int)(boolean)$cond,
			'text'=>is_string($text)?
				self::resolve($text):var_export($text,TRUE)
		);
		return $text;
	}

	/**
		Display default error page; Use custom page if found
			@param $code int
			@param $str string
			@param $trace array
			@param $fatal bool
			@public
	**/
	static function error($code,$str='',array $trace=NULL,$fatal=FALSE) {
		$prior=self::$vars['ERROR'];
		$out='';
		switch ($code) {
			case 404:
				$str=sprintf(self::TEXT_NotFound,$_SERVER['REQUEST_URI']);
				break;
			case 405:
				$str=sprintf(self::TEXT_NotAllowed,
					$_SERVER['REQUEST_METHOD'],$_SERVER['REQUEST_URI']);
				break;
			default:
				// Generate internal server error if code is zero
				if (!$code)
					$code=500;
				if (!self::$vars['DEBUG'])
					// Disable stack trace
					$trace=NULL;
				elseif ($code==500 && !$trace)
					$trace=debug_backtrace();
				if (is_array($trace)) {
					$line=0;
					$plugins=is_array(
						$plugins=glob(self::$vars['PLUGINS'].'*.php'))?
						array_map('self::fixslashes',$plugins):array();
					// Stringify the stack trace
					ob_start();
					foreach ($trace as $nexus) {
						// Remove stack trace noise
						if (self::$vars['DEBUG']<3 && !$fatal &&
							(!isset($nexus['file']) ||
							self::$vars['DEBUG']<2 &&
							(strrchr(basename($nexus['file']),'.')=='.tmp' ||
							in_array(self::fixslashes(
								$nexus['file']),$plugins)) ||
							isset($nexus['function']) &&
							preg_match('/^(call_user_func(?:_array)?|'.
								'trigger_error|{.+}|'.__FUNCTION__.'|__)/',
									$nexus['function'])))
							continue;
						echo '#'.$line.' '.
							(isset($nexus['line'])?
								(urldecode(self::fixslashes(
									$nexus['file'])).':'.
									$nexus['line'].' '):'').
							(isset($nexus['function'])?
								((isset($nexus['class'])?
									($nexus['class'].$nexus['type']):'').
										$nexus['function'].
								'('.(!preg_match('/{{.+}}/',
									$nexus['function']) &&
									isset($nexus['args'])?
									(self::csv($nexus['args'])):'').')'):'').
								"\n";
						$line++;
					}
					$out=ob_get_clean();
				}
		}
		// Save error details
		self::$vars['ERROR']=array(
			'code'=>$code,
			'title'=>self::status($code),
			'text'=>preg_replace('/\v/','',$str),
			'trace'=>self::$vars['DEBUG']?$out:''
		);
		$error=&self::$vars['ERROR'];
		if (self::$vars['DEBUG']<2 && self::$vars['QUIET'])
			return;
		// Write to server's error log (with complete stack trace)
		error_log($error['text']);
		foreach (explode("\n",$out) as $str)
			if ($str)
				error_log(strip_tags($str));
		if ($prior || self::$vars['QUIET'])
			return;
		foreach (array('title','text','trace') as $sub)
			// Convert to HTML entities for safety
			$error[$sub]=self::htmlencode(rawurldecode($error[$sub]));
		$error['trace']=nl2br($error['trace']);
		$func=self::$vars['ONERROR'];
		if ($func && !$fatal)
			self::call($func,TRUE);
		else
			echo '<html>'.
				'<head>'.
					'<title>'.$error['code'].' '.$error['title'].'</title>'.
				'</head>'.
				'<body>'.
					'<h1>'.$error['title'].'</h1>'.
					'<p><i>'.$error['text'].'</i></p>'.
					'<p>'.$error['trace'].'</p>'.
				'</body>'.
			'</html>';
		if (self::$vars['STRICT'])
			die;
	}

	/**
		Bootstrap code
			@public
	**/
	static function start() {
		// Prohibit multiple calls
		if (self::$vars)
			return;
		// Handle all exceptions/non-fatal errors
		error_reporting(E_ALL|E_STRICT);
		$charset='utf-8';
		ini_set('default_charset',$charset);
		ini_set('display_errors',0);
		ini_set('register_globals',0);
		// Get PHP settings
		$ini=ini_get_all(NULL,FALSE);
		$self=__CLASS__;
		// Intercept errors and send output to browser
		set_error_handler(
			function($errno,$errstr) use($self) {
				if (error_reporting())
					// Error suppression (@) is not enabled
					$self::error(500,$errstr);
			}
		);
		// Do the same for PHP exceptions
		set_exception_handler(
			function($ex) use($self) {
				if (!count($trace=$ex->getTrace())) {
					// Translate exception trace
					list($trace)=debug_backtrace();
					$arg=$trace['args'][0];
					$trace=array(
						array(
							'file'=>$arg->getFile(),
							'line'=>$arg->getLine(),
							'function'=>'{main}',
							'args'=>array()
						)
					);
				}
				$self::error(500,$ex->getMessage(),$trace);
				// PHP aborts at this point
			}
		);
		// Apache mod_rewrite enabled?
		if (function_exists('apache_get_modules') &&
			!in_array('mod_rewrite',apache_get_modules())) {
			trigger_error(self::TEXT_Apache);
			return;
		}
		// Fix Apache's VirtualDocumentRoot limitation
		$_SERVER['DOCUMENT_ROOT']=
			self::fixslashes(dirname($_SERVER['SCRIPT_FILENAME']));
		// Adjust HTTP request time precision
		$_SERVER['REQUEST_TIME']=microtime(TRUE);
		if (PHP_SAPI=='cli') {
			// Command line: Parse GET variables in URL, if any
			if (isset($_SERVER['argc']) && $_SERVER['argc']<2)
				array_push($_SERVER['argv'],'/');
			// Detect host name from environment
			$_SERVER['SERVER_NAME']=gethostname();
			// Convert URI to human-readable string
			self::mock('GET '.$_SERVER['argv'][1]);
		}
		// Hydrate framework variables
		$base=implode('/',array_map('urlencode',
			explode('/',self::fixslashes(
			preg_replace('/\/[^\/]+$/','',$_SERVER['SCRIPT_NAME'])))));
		$scheme=PHP_SAPI=='cli'?
			NULL:
			isset($_SERVER['HTTPS']) && $_SERVER['HTTPS']!='off' ||
			isset($_SERVER['HTTP_X_FORWARDED_PROTO']) &&
			$_SERVER['HTTP_X_FORWARDED_PROTO']=='https'?'https':'http';
		self::$vars=array(
			// Autoload folders
			'AUTOLOAD'=>'./',
			// Web root folder
			'BASE'=>$base,
			// Cache backend to use (autodetect if true; disable if false)
			'CACHE'=>FALSE,
			// Case-sensitivity of route patterns
			'CASELESS'=>TRUE,
			// Stack trace verbosity:
			// 0-no stack trace, 1-noise removed, 2-normal, 3-verbose
			'DEBUG'=>1,
			// DNS black lists
			'DNSBL'=>NULL,
			// Document encoding
			'ENCODING'=>$charset,
			// Last error
			'ERROR'=>NULL,
			// Auto-escape feature
			'ESCAPE'=>FALSE,
			// Allow/prohibit framework class extension
			'EXTEND'=>TRUE,
			// IP addresses exempt from spam detection
			'EXEMPT'=>NULL,
			// User interface folders
			'GUI'=>'./',
			// URL for hotlink redirection
			'HOTLINK'=>NULL,
			// Include path for procedural code
			'IMPORTS'=>'./',
			// Default cookie settings
			'JAR'=>array(
				'expire'=>0,
				'path'=>$base?:'/',
				'domain'=>isset($_SERVER['SERVER_NAME']) &&
					is_int(strpos($_SERVER['SERVER_NAME'],'.')) &&
					!filter_var($_SERVER['SERVER_NAME'],FILTER_VALIDATE_IP)?
					$_SERVER['SERVER_NAME']:'',
				'secure'=>($scheme=='https'),
				'httponly'=>TRUE
			),
			// Default language (auto-detect if null)
			'LANGUAGE'=>NULL,
			// Autoloaded classes
			'LOADED'=>NULL,
			// Dictionary folder
			'LOCALES'=>'./',
			// Maximum POST size
			'MAXSIZE'=>self::bytes($ini['post_max_size']),
			// Max mutex lock duration
			'MUTEX'=>60,
			// Custom error handler
			'ONERROR'=>NULL,
			// Plugins folder
			'PLUGINS'=>self::fixslashes(__DIR__).'/',
			// Scheme/protocol
			'PROTOCOL'=>$scheme,
			// Allow framework to proxy for plugins
			'PROXY'=>FALSE,
			// Stream handle for HTTP PUT method
			'PUT'=>NULL,
			// Output suppression switch
			'QUIET'=>FALSE,
			// Absolute path to document root folder
			'ROOT'=>$_SERVER['DOCUMENT_ROOT'].'/',
			// Framework routes
			'ROUTES'=>NULL,
			// URL for spam redirection
			'SPAM'=>NULL,
			// Stop script on error?
			'STRICT'=>TRUE,
			// Profiler statistics
			'STATS'=>array(
				'MEMORY'=>array('start'=>memory_get_usage()),
				'TIME'=>array('start'=>microtime(TRUE))
			),
			// Temporary folder
			'TEMP'=>'temp/',
			// Minimum script execution time
			'THROTTLE'=>0,
			// Tidy options
			'TIDY'=>array(),
			// Default timezone
			'TZ'=>'UTC',
			// Framework version
			'VERSION'=>self::TEXT_AppName.' '.self::TEXT_Version,
			// Default whois server
			'WHOIS'=>'whois.internic.net'
		);
		// Alias the GUI variable (2.0+)
		self::$vars['UI']=&self::$vars['GUI'];
		// Create convenience containers for PHP globals
		foreach (explode('|',self::PHP_Globals) as $var) {
			// Sync framework and PHP globals
			self::$vars[$var]=&$GLOBALS['_'.$var];
			if (isset($ini['magic_quotes_gpc']) &&
				$ini['magic_quotes_gpc'] && preg_match('/^[GPCR]/',$var) &&
				self::$vars[$var])
				// Corrective action on PHP magic quotes
				array_walk_recursive(
					self::$vars[$var],
					function(&$val) {
						$val=stripslashes($val);
					}
				);
		}
		// Initialize autoload stack and shutdown sequence
		spl_autoload_register($self.'::autoload',TRUE,TRUE);
		register_shutdown_function($self.'::stop');
	}

	/**
		Execute shutdown function
			@public
	**/
	static function stop() {
		chdir(self::$vars['ROOT']);
		$error=error_get_last();
		if ($error && !self::$vars['QUIET'] && in_array($error['type'],
			array(E_ERROR,E_PARSE,E_CORE_ERROR,E_COMPILE_ERROR)))
			// Intercept fatal error
			self::error(500,sprintf(self::TEXT_Fatal,$error['message']),
				array($error),TRUE);
		if (isset(self::$vars['UNLOAD']))
			self::call(self::$vars['UNLOAD']);
	}

	/**
		onLoad event handler (static class initializer)
			@public
	**/
	static function loadstatic($class) {
		$loaded=&self::$vars['LOADED'];
		$lower=strtolower($class);
		if (!isset($loaded[$lower])) {
			$loaded[$lower]=
				array_map('strtolower',get_class_methods($class));
			if (in_array('onload',$loaded[$lower])) {
				// Execute onload method
				$method=new ReflectionMethod($class,'onload');
				if ($method->isStatic())
					call_user_func(array($class,'onload'));
				else
					trigger_error(sprintf(self::TEXT_Static,
						$class.'::onload'));
			}
		}
	}

	/**
		Intercept instantiation of objects in undefined classes
			@param $class string
			@public
	**/
	static function autoload($class) {
		foreach (self::split(
			self::$vars['PLUGINS'].';'.self::$vars['AUTOLOAD']) as $auto) {
			$ns='';
			$iter=ltrim($class,'\\');
			for (;;) {
				if ($glob=glob($auto.self::fixslashes($ns).'*')) {
					$grep=preg_grep('/^'.preg_quote($auto,'/').
						implode('[\/\.]',explode('\\',$ns.$iter)).
						'(?:\.class)?\.php/i',$glob);
					if ($file=current($grep)) {
						unset($grep);
						$instance=new F3instance;
						$instance->sandbox($file);
						// Verify that the class was loaded
						if (class_exists($class,FALSE)) {
							// Run onLoad event handler if defined
							self::loadstatic($class);
							return;
						}
						elseif (interface_exists($class,FALSE))
							return;
					}
					$parts=explode('\\',$iter,2);
					if (count($parts)>1) {
						$iter=$parts[1];
						$grep=preg_grep('/^'.
							preg_quote($auto.self::fixslashes($ns).
							$parts[0],'/').'$/i',$glob);
						if ($file=current($grep)) {
							$ns=str_replace('/','\\',preg_replace('/^'.
								preg_quote($auto,'/').'/','',$file)).'\\';
							continue;
						}
						$ns.=$parts[0].'\\';
					}
				}
				break;
			}
		}
	}

	/**
		Intercept calls to undefined static methods and proxy for the
		called class if found in the plugins folder
			@return mixed
			@param $func string
			@param $args array
			@public
	**/
	static function __callStatic($func,array $args) {
		if (self::$vars['PROXY'] &&
			$glob=glob(self::fixslashes(
				self::$vars['PLUGINS'].'/*.php'),GLOB_NOSORT))
			foreach ($glob as $file) {
				$class=strstr(basename($file),'.php',TRUE);
				// Prevent recursive calls
				$found=FALSE;
				foreach (debug_backtrace() as $trace)
					if (isset($trace['class']) &&
						// Support namespaces
						preg_match('/\b'.preg_quote($trace['class']).'\b/i',
						strtolower($class)) &&
						preg_match('/'.$trace['function'].'/i',
						strtolower($func))) {
						$found=TRUE;
						break;
					}
				if ($found)
					continue;
				// Run onLoad event handler if defined
				self::loadstatic($class);
				if (in_array($func,self::$vars['LOADED'][$class]))
					// Proxy for plugin
					return call_user_func_array(array($class,$func),$args);
			}
		if (count(spl_autoload_functions())==1)
			// No other registered autoload functions exist
			trigger_error(sprintf(self::TEXT_Method,$func));
		return FALSE;
	}

}

//! Cache engine
class Cache extends Base {

	private static
		//! Cache engine
		$engine,
		//! Resource/reference
		$ref;

	/**
		Return timestamp of cache entry or FALSE if not found
			@return float|FALSE
			@param $key string
	**/
	static function cached($key) {
		if (!self::$engine)
			return FALSE;
		$ndx=self::hash(__DIR__).'.'.$key;
		switch (self::$engine['type']) {
			case 'apc':
				if ($data=apc_fetch($ndx))
					break;
				return FALSE;
			case 'xcache':
				if ($data=xcache_get($ndx))
					break;
				return FALSE;
			case 'shmop':
				if ($ref=self::$ref) {
					$data=self::mutex(
						function() use($ref,$ndx) {
							$dir=unserialize(trim(shmop_read($ref,0,0xFFFF)));
							return isset($dir[$ndx])?
								shmop_read($ref,$dir[$ndx][0],$dir[$ndx][1]):
								FALSE;
						},
						self::$vars['TEMP'].$_SERVER['SERVER_NAME']
					);
					if ($data)
						break;
				}
				return FALSE;
			case 'memcache':
				if ($data=memcache_get(self::$ref,$ndx))
					break;
				return FALSE;
			case 'folder':
				if (is_file($file=self::$ref.$ndx) &&
					$data=self::getfile($file))
					break;
				return FALSE;
		}
		if (isset($data)) {
			self::$engine['data']=
				list($time,$ttl,$val)=unserialize($data);
			if (!$ttl || $time+$ttl>microtime(TRUE))
				return $time;
			self::clear($key);
		}
		return FALSE;
	}

	/**
		Store value in cache
			@return mixed
			@param $key string
			@param $val mixed
			@param $ttl int
	**/
	static function set($key,$val,$ttl=0) {
		if (!self::$engine)
			return TRUE;
		$ndx=self::hash(__DIR__).'.'.$key;
		self::$engine['data']=NULL;
		$data=serialize(array(microtime(TRUE),$ttl,$val));
		switch (self::$engine['type']) {
			case 'apc':
				return apc_store($ndx,$data,$ttl);
			case 'xcache':
				return xcache_set($ndx,$data,$ttl);
			case 'shmop':
				return ($ref=self::$ref)?
					self::mutex(
						function() use($ref,$ndx,$data) {
							$dir=unserialize(trim(shmop_read($ref,0,0xFFFF)));
							$edge=0xFFFF;
							foreach ($dir as $stub)
								$edge=$stub[0]+$stub[1];
							shmop_write($ref,$data,$edge);
							unset($dir[$ndx]);
							$dir[$ndx]=array($edge,strlen($data));
							shmop_write($ref,serialize($dir).chr(0),0);
						},
						self::$vars['TEMP'].$_SERVER['SERVER_NAME']
					):
					FALSE;
			case 'memcache':
				return memcache_set(self::$ref,$ndx,$data,0,$ttl);
			case 'folder':
				return self::putfile(self::$ref.$ndx,$data);
		}
		return FALSE;
	}

	/**
		Retrieve value of cache entry
			@return mixed
			@param $key string
	**/
	static function get($key) {
		if (!self::$engine || !self::cached($key))
			return FALSE;
		list($time,$ttl,$val)=self::$engine['data'];
		return $val;
	}

	/**
		Delete cache entry
			@return void
			@param $key string
	**/
	static function clear($key) {
		if (!self::$engine)
			return;
		$ndx=self::hash(__DIR__).'.'.$key;
		self::$engine['data']=NULL;
		switch (self::$engine['type']) {
			case 'apc':
				return apc_delete($ndx);
			case 'xcache':
				return xcache_unset($ndx);
			case 'shmop':
				return ($ref=self::$ref) &&
					self::mutex(
						function() use($ref,$ndx) {
							$dir=unserialize(trim(shmop_read($ref,0,0xFFFF)));
							unset($dir[$ndx]);
							shmop_write($ref,serialize($dir).chr(0),0);
						},
						self::$vars['TEMP'].$_SERVER['SERVER_NAME']
					);
			case 'memcache':
				return memcache_delete(self::$ref,$ndx);
			case 'folder':
				return is_file($file=self::$ref.$ndx) && unlink($file);
		}
	}

	/**
		Load and configure backend; Auto-detect if argument is FALSE
			@return string|void
			@param $dsn string|FALSE
	**/
	static function load($dsn=FALSE) {
		if (is_bool($dsn)) {
			// Auto-detect backend
			$ext=array_map('strtolower',get_loaded_extensions());
			$grep=preg_grep('/^(apc|xcache|shmop)/',$ext);
			$dsn=$grep?current($grep):'folder=cache/';
		}
		$parts=explode('=',$dsn);
		if (!preg_match('/apc|xcache|shmop|folder|memcache/',$parts[0]))
			return;
		self::$engine=array('type'=>$parts[0],'data'=>NULL);
		self::$ref=NULL;
		if ($parts[0]=='shmop') {
			$self=__CLASS__;
			self::$ref=self::mutex(
				function() use($self) {
					$ref=@shmop_open(fileinode(__FILE__),'c',0644,
						$self::bytes(ini_get('memory_limit')));
					if ($ref && !unserialize(trim(shmop_read($ref,0,0xFFFF))))
						shmop_write($ref,serialize(array()).chr(0),0);
					return $ref;
				},
				self::$vars['TEMP'].$_SERVER['SERVER_NAME']
			);
			if (!self::$ref)
				return self::load('folder=cache/');
		}
		elseif (isset($parts[1])) {
			if ($parts[0]=='memcache') {
				if (extension_loaded('memcache'))
					foreach (self::split($parts[1]) as $server) {
						$parts=explode(':',$server);
						if (count($parts)<2) {
							$host=$parts[0];
							$port=11211;
						}
						else
							list($host,$port)=$parts;
						if (!self::$ref)
							self::$ref=@memcache_connect($host,$port);
						else
							memcache_add_server(self::$ref,$host,$port);
					}
				else
					return self::$engine=NULL;
			}
			elseif ($parts[0]=='folder') {
				if (!is_dir($parts[1]) && !@mkdir($parts[1],0755,TRUE))
					return self::$engine=NULL;
				self::$ref=$parts[1];
			}
		}
		return $dsn;
	}

}

//! F3 object mode
class F3instance {

	//@{ Locale-specific error/exception messages
	const
		TEXT_Conflict='%s conflicts with framework method name';
	//@}

	/**
		Get framework variable reference; Workaround for PHP's
		call_user_func() reference limitation
			@return mixed
			@param $key string
			@param $set bool
			@public
	**/
	function &ref($key,$set=TRUE) {
		return F3::ref($key,$set);
	}

	/**
		Run PHP code in sandbox
			@param $file string
			@param $vars array
			@public
	**/
	function sandbox($file,$vars=array()) {
		extract($vars);
		return require $file;
	}

	/**
		Grab file contents
			@return mixed
			@param $file string
			@public
	**/
	function grab($file) {
		$file=F3::resolve($file);
		if (!ini_get('short_open_tag')) {
			$text=preg_replace_callback(
				'/<\?(?:\s|\s*(=))(.+?)\?>/s',
				function($tag) {
					return '<?php '.($tag[1]?'echo ':'').trim($tag[2]).' ?>';
				},
				$orig=self::getfile($file)
			);
			if (ini_get('allow_url_fopen') && ini_get('allow_url_include'))
				// Stream wrap
				$file='data:text/plain,'.urlencode($text);
			elseif ($text!=$orig) {
				// Save re-tagged file in temporary folder
				if (!is_dir($ref=F3::ref('TEMP')))
					F3::mkdir($ref);
				$temp=$ref.$_SERVER['SERVER_NAME'].'.tpl.'.F3::hash($file);
				if (!is_file($temp))
					self::mutex(
						function() use($temp,$text) {
							file_put_contents($temp,$text);
						}
					);
				$file=$temp;
			}
		}
		ob_start();
		// Render
		$this->sandbox($file);
		return ob_get_clean();
	}

	/**
		Proxy for framework methods
			@return mixed
			@param $func string
			@param $args array
			@public
	**/
	function __call($func,array $args) {
		return call_user_func_array('F3::'.$func,$args);
	}

	/**
		Class constructor
			@param $boot bool
			@public
	**/
	function __construct($boot=FALSE) {
		if ($boot)
			F3::start();
		// Allow application to override framework methods?
		if (F3::ref('EXTEND'))
			// User assumes risk
			return;
		// Get all framework methods not defined in this class
		$def=array_diff(get_class_methods('F3'),get_class_methods(__CLASS__));
		// Check for conflicts
		$class=new ReflectionClass($this);
		foreach ($class->getMethods() as $func)
			if (in_array($func->name,$def))
				trigger_error(sprintf(self::TEXT_Conflict,
					get_called_class().'->'.$func->name));
	}

}

// Bootstrap
return new F3instance(TRUE);