summaryrefslogtreecommitdiff
path: root/includes/classes/BitSystem.php
blob: a0ea714a8b64c39cff4f8d5243d01ff777c4333e (plain)
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
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
<?php
/**
 * Main bitweaver systems functions
  *
 * @version $Header$
 *
 * Copyright (c) 2004 bitweaver.org
 * All Rights Reserved. See below for details and a complete list of authors.
 * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE. See http://www.gnu.org/copyleft/lesser.html for details
 *
 * Virtual base class (as much as one can have such things in PHP) for all
 * derived tikiwiki classes that require database access.
 *
 * created 2004/8/15
 *
 * @author spider <spider@steelsun.com>
 * @package  kernel
 */

namespace Bitweaver;
use Bitweaver\Users\BitHybridAuthManager;
use Bitweaver\Wiki\BitPage;
use Bitweaver\KernelTools;

/**
 * required setup
 */

define( 'DEFAULT_PACKAGE', 'kernel' );
define( 'CENTER_COLUMN', 'c' );
define( 'HOMEPAGE_LAYOUT', 'home' );

/**
 * kernel::BitSystem
 *
 * Purpose:
 *
 *     This is the main system class that does the work of seeing bitweaver has an
 * 	operable environment and has methods for modifying that environment.
 *
 * 	Currently gBitSystem derives from this class for backward compatibility sake.
 * 	Ultimate goal is to put system code from BitBase here, and base code from
 * 	gBitSystem (code that ALL features need) into BitBase and code gBitSystem that
 * 	is Package specific should be moved into that package
 *
 * @author spider <spider@steelsun.com>
 *
 * @package kernel
 */
class BitSystem extends BitSingleton {

	// Initiate class variables

	// Essential information about packages
	public $mPackages = [];

	// An array of object keys to clear from cache on page destruction
	private $mClearCacheKeys = [];

	// Cross Reference Package Directory Name => Package Key used as index into $mPackages
	public $mPackagesDirNameXref = [];

	// Contains site style information
	public $mStyle = [];

	// Information about package menus used in all menu modules and top bar
	public $mAppMenu = [];

	// The currently active page
	private $mActivePackage;

	// Modules that need to be inserted during installation
	public $mInstallModules = [];

	// Javascript to be added to the <body onload> attribute
	public $mOnload = [];

	// Javascript to be added to the <body onunload> attribute
	public $mOnunload = [];

	// Used by packages to register notification events that can be subscribed to.
	public $mNotifyEvents = [];

	// Used to store contents of kernel_config
	public $mConfig;

	// Used to monitor if ::registerPackage() was called. This is used to determine whether to auto-register a package
	public $mRegisterCalled;

	// The name of the package that is currently being processed
	public $mPackageFileName;

	// Content classes.
	public $mContentClasses = [];

	// Debug HTML to be displayed just after the HTML headers
	public $mDebugHtml = "";
	public $mErrorRep;
	public $mMimeTypes = [];
	public $mPermHash = [];
	public$mRequirements = [];
	public $mServerTimestamp;
	public $mTimer;
	
	// Output http status
	public $mHttpStatus = HttpStatusCodes::HTTP_OK;

    protected static $singleton = null;
	protected static function getSingleInstance() {
		return static::$singleton;
	}

	// === BitSystem constructor
	/**
	 * base constructor, auto assigns member db variable
	 *
	 * @access public
	 */
	// Constructor receiving a PEAR::Db database object.
	public function __construct() {
		global $gBitTimer;
		// Call DB constructor which will create the database member variable
		parent::__construct();

		$this->mAppMenu = [];

		if (!isset($gBitTimer)) {
			$gBitTimer = new BitTimer();
			$gBitTimer->start();
		}
		$this->mTimer = $gBitTimer;
		$this->mServerTimestamp = new BitDate();

		$this->loadConfig();

		// Critical Preflight Checks
		$this->checkEnvironment();

		$this->mRegisterCalled = false;

		// Set the separator for PHP generated tags to be &amp; instead of &
		// This is necessary for XHTML compliance
		ini_set( "arg_separator.output", "&amp;" );
		// Remove automatic quotes added to POST/COOKIE by PHP
		foreach( $_REQUEST as $k => $v ) {
			if( !is_array( $_REQUEST[$k] ) ) {
				$_REQUEST[$k] = stripslashes( $v );
			}
		}

		$this->defineTempDir();

	}

	public function __destruct() {
		parent::__destruct();
		// Hopefully gBitSystem is among the last objects destroyed and can force cache purging of any leftover objects that might be in an inconsistent state due to multiple object copies invoked in the same page load
		foreach( array_keys( $this->mClearCacheKeys ) as $cacheKey ) {
			// $ret = apcu_delete( $cacheKey );
		}
	}

	public function __sleep() {
		return array_merge( parent::__sleep(), [ 'mPackages', 'mPackagesDirNameXref', 'mStyle', 'mAppMenu', 'mInstallModules', 'mOnload', 'mOnunload', 'mNotifyEvents', 'mConfig', 'mRegisterCalled', 'mPackageFileName', 'mContentClasses' ] );
	}

	public function isPurgedFromCache( $pCacheKey ) {
		return !empty( $this->mClearCacheKeys[$pCacheKey] );
	}

	public function queueClearFromCache( $pCacheKey ): void {
		$this->mClearCacheKeys[$pCacheKey] = true;
	}

	public static function loadFromCache( $pCacheKey, $pContentTypeGuid = null ) {
		global $gBitTimer;
		if( $ret = parent::loadFromCache( $pCacheKey ) ) {
			$ret->setHttpStatus( HttpStatusCodes::HTTP_OK );
			if (!isset($gBitTimer)) {
				$gBitTimer = new BitTimer();
				$gBitTimer->start();
			}
			$ret->mTimer = $gBitTimer;
			$ret->mTimer->start();
			$ret->mOnload = [];
			$ret->mAppMenu = [];
			$ret->defineTempDir();
			$ret->mServerTimestamp = new BitDate();
		}
		return $ret;
	}

	

	/**
	 * Load all preferences and store them in $this->mConfig
	 *
	 * @param $pPackage optionally get preferences only for selected package
	 */
	public function loadConfig( $pPackage = null ) {
		$queryVars = [];
		$whereClause = '';

		if( $pPackage ) {
			array_push( $queryVars, $pPackage );
			$whereClause = ' WHERE `package`=? ';
		}

		if ( empty( $this->mConfig ) && $this->mDb->tableExists('kernel_config') ) {
			$this->mConfig = [];
			$query = "SELECT `config_name` ,`config_value`, `package` FROM `" . BIT_DB_PREFIX . "kernel_config` " . $whereClause;
			if( $rs = $this->mDb->query( $query, $queryVars, -1, -1 ) ) {
				while( $row = $rs->fetchRow() ) {
					$this->mConfig[$row['config_name']] = $row['config_value'];
				}
			}
			return count( $this->mConfig );
		}
		return 0;
	}

	// <<< getConfig
	/**
	 * Add getConfig / setConfig for more uniform handling of config variables instead of spreading global vars.
	 * easily get the value of any given preference stored in kernel_config
	 *
	 * @param string $pName Perl regular expression
	 * @param string $pDefault only manipulate settings with this value set
	 * @access public
	 **/
	public function getConfig( string $pName, string $pDefault = '' ): string {
		if( empty( $this->mConfig ) ) {
			$this->loadConfig();
		}
		return empty( $this->mConfig[$pName] ) ? $pDefault : $this->mConfig[$pName] ?? '';
	}

	// <<< getConfigMatch
	/**
	 * retreive a group of config variables
	 *
	 * @param string $pPattern Perl regular expression
	 * @param string $pSelectValue only manipulate settings with this value set
	 * @access public
	 **/
	public function getConfigMatch( $pPattern, $pSelectValue = '' ): array {
		if( empty( $this->mConfig ) ) {
			$this->loadConfig();
		}

		$matching_keys = preg_grep( $pPattern, array_keys( $this->mConfig ));
		$new_array = [];
		foreach( $matching_keys as $key=>$value ) {
			if ( empty( $pSelectValue ) || ( !empty( $pSelectValue ) && $this->mConfig[$value] == $pSelectValue )) {
				$new_array[$value] = $this->mConfig[$value];
			}
		}
		return $new_array;
	}

	/**
	 * storeConfigMatch set a group of config variables
	 *
	 * @param string $pPattern Perl regular expression
	 * @param string $pSelectValue only manipulate settings with this value set
	 * @param string $pNewValue New value that should be set for the matching settings (null will remove the entries from the DB)
	 * @param string $pPackage Package for which the settings are
	 * @return void
	 */
	public function storeConfigMatch( $pPattern, $pSelectValue = "", $pNewValue = null, $pPackage = null ): void {
		if( empty( $this->mConfig ) ) {
			$this->loadConfig();
		}

		$matchingKeys = preg_grep( $pPattern, array_keys( $this->mConfig ));
		foreach( $matchingKeys as $key => $config_name ) {
			if( empty( $pSelectValue ) || ( !empty( $pSelectValue ) && $this->mConfig[$config_name] == $pSelectValue )) {
				$this->storeConfig( $config_name, $pNewValue, $pPackage );
			}
		}
	}

	/**
	 * Set a hash value in the mConfig hash. This does *NOT* store the value in
	 * the database. It does no checking for existing or duplicate values. the
	 * main point of this function is to limit direct accessing of the mConfig
	 * hash. I will probably make mConfig private one day.
	 *
	 * @param string Hash key for the mConfig value
	 * @param string Value for the mConfig hash key
	 */
	public function setConfig( $pName, $pValue ) {
		$this->mConfig[$pName] = $pValue;
		return true;
	}

	// <<< storeConfig
	/**
	 * bitweaver needs lots of settings just to operate.
	 * loadConfig assigns itself the default preferences, then loads just the differences from the database.
	 * In storeConfig (and only when storeConfig is called) we make a second copy of defaults to see if
	 * preferences you are changing is different from the default.
	 * if it is the same, don't store it!
	 * So instead updating the whole prefs table, only updat "delta" of the changes delta from defaults.
	 *
	 * @access public
	 **/
	public function storeConfig( $pName, $pValue, $pPackage = '' ) {
		global $gMultisites;
		//stop undefined offset error being thrown after packages are installed
		if( !empty( $this->mConfig )) {
			// store the pref if we have a value _AND_ it is different from the default
			if( ( empty( $this->mConfig[$pName] ) || ( $this->mConfig[$pName] != $pValue ))) {
				// make sure the value doesn't exceede database limitations
				$pValue = substr( $pValue ?? '', 0, 250 );

				// store the preference in multisites, if used
				if( $this->isPackageActive( 'multisites' ) && BitBase::verifyId( $gMultisites->mMultisiteId ) && isset( $gMultisites->mConfig[$pName] )) {
					$query = "UPDATE `".BIT_DB_PREFIX."multisite_preferences` SET `config_value`=? WHERE `multisite_id`=? AND `config_name`=?";
					$result = $this->mDb->query( $query, [ empty( $pValue ) ? '' : $pValue, $gMultisites->mMultisiteId, $pName ] );
				} else {
					$this->StartTrans();
					$query = "DELETE FROM `".BIT_DB_PREFIX."kernel_config` WHERE `config_name`=?";
					$result = $this->mDb->query( $query, [ $pName ] );
					// make sure only non-empty values get saved, including '0'
					if( isset( $pValue ) && ( !empty( $pValue ) || is_numeric( $pValue ))) {
						$query = "INSERT INTO `".BIT_DB_PREFIX."kernel_config`(`config_name`,`config_value`,`package`) VALUES (?,?,?)";
						$result = $this->mDb->query( $query, [ $pName, $pValue, strtolower( $pPackage ) ]);
					}
					$this->CompleteTrans();
				}

				// Force the ADODB cache to flush
				$isCaching = $this->mDb->isCachingActive();
				$this->mDb->setCaching( false );
				$this->loadConfig();
				$this->mDb->setCaching( $isCaching );
				$this->clearFromCache();
			}
		}
		$this->setConfig( $pName, $pValue );
		return true;
	}

	// <<< expungePackageConfig
	/**
	 * Delete all prefences for the given package
	 * @access public
	 **/
	public function expungePackageConfig( $pPackageName ) {
		if( !empty( $pPackageName ) ) {
			$query = "DELETE FROM `".BIT_DB_PREFIX."kernel_config` WHERE `package`=?";
			$result = $this->mDb->query( $query, [ strtolower( $pPackageName ) ] );
			// let's force a reload of the prefs
			unset( $this->mConfig );
			$this->loadConfig();
		}
	}

	// === hasValidSenderEmail
	/**
	 * Determines if this site has a legitimate sender address set.
	 *
	 * @param string $pSenderEmail
	 * @access public
	 */
	public function hasValidSenderEmail( $pSenderEmail=null ) {
		if( empty( $pSenderEmail ) ) {
			$pSenderEmail = $this->getConfig( 'site_sender_email' );
		}
		return !empty( $pSenderEmail ) && !preg_match( '/.*localhost$/', $pSenderEmail );
	}

	// === getErrorEmail
	/**
	 * Smartly determines where error emails should go
	 *
	 * @access public
	 */
	public function getErrorEmail() {
		if( defined('ERROR_EMAIL') ) {
			$ret = ERROR_EMAIL;
		} elseif( $this->getConfig( 'site_sender_email' ) ) {
			$ret = $this->getConfig( 'site_sender_email' );
		} elseif( !empty( $_SERVER['SERVER_ADMIN'] ) ) {
			$ret = $_SERVER['SERVER_ADMIN'];
		} else {
			$ret = 'root@localhost';
		}
	}

	// === sendEmail
	/**
	 * centralized function for send emails
	 *
	 * @param array $pMailHash
	 * @access public
	 */
	public function sendEmail( $pMailHash ) {
		$fromEmail = !empty( $pMailHash['from'] ) ? $pMailHash['from'] : $this->getConfig( 'site_sender_email' );

		$extraHeaders = "Return-Path: $fromEmail\r\n";
		if( $this->getConfig( 'bcc_email' ) ) {
			$extraHeaders .= "Bcc: ".$this->getConfig( 'bcc_email' )."\r\n";
		}
		if( !empty( $pMailHash['Reply-to'] ) ) {
			$extraHeaders .= "Reply-to: ".$pMailHash['Reply-to']."\r\n";
		}

		mail($pMailHash['email'],
			$pMailHash['subject'].' '.$_SERVER["SERVER_NAME"],
			$pMailHash['body'],
			"From: ".$fromEmail."\r\nContent-type: text/plain;charset=utf-8\r\n$extraHeaders"
		);
	}


	/**
	 * Set the http status, most notably for 404 not found for deleted content
	 *
	 * @param  $pHttpStatus numerical HTTP status, most typically 404 (not found) or 403 (forbidden)
	 * @access public
	 */
	public function setHttpStatus( $pHttpStatus ) {
		$this->mHttpStatus = $pHttpStatus;
	}


	public function outputHeader() {
		// Add the user to an apache ENV variable so it can be logged, like:
		// LogFormat "%V %h %l %{USERID}e %t \"%r\" %>s %b \"%{Referer}i\" \"%{User-agent}i\" \"%{Cookie}n\""  combinedcookie
		global $gBitUser;
		if( is_object( $gBitUser ) ) {
//			apache_setenv( 'USERID', $gBitUser->getField('login', '-'), true );
		}

		// see if we have a custom status other than 200 OK
		header( $_SERVER["SERVER_PROTOCOL"].' '.HttpStatusCodes::getMessageForCode( $this->mHttpStatus ) );
	}

	public function outputJson( $pOutput, $pStatusCode=200  ) {
		global $gBitSmarty, $gBitThemes;

		$gBitThemes->setFormatHeader( 'json' );

		$this->setHttpStatus( $pStatusCode );

		$this->outputHeader();

		if( is_array( $pOutput ) ) {
			$gBitSmarty->assign( 'jsonHash', $pOutput );
		}

		print $gBitSmarty->fetch( 'bitpackage:kernel/json_output.tpl' );
		die;
	}

	public function outputRaw( $pOutput, $pStatusCode=200  ) {
		global $gBitSmarty, $gBitThemes;

		$gBitThemes->setFormatHeader( 'text' );

		$this->setHttpStatus( $pStatusCode );

		$this->outputHeader();

		if( is_array( $pOutput ) ) {
			foreach( $pOutput as $out ) {
				print "$out\n";
			}
		} else {
			print $pOutput;
		}

		die;
	}

	/**
	 * Display the main page template
	 *
	 * @param string $pMid the name of the template for the page content
	 * @param string $pBrowserTitle a string to be displayed in the top browser bar
	 * @param array $pOptionsHash
	 */
	public function display( $pMid, $pBrowserTitle = null, $pOptionsHash = [] ) {
		global $gBitSmarty, $gBitThemes, $gContent;
		$gBitSmarty->verifyCompileDir();
		
		$this->outputHeader();
		if( $this->mHttpStatus != 200 ) {
//			error_log( "HTTP/1.0 ".HttpStatusCodes::getMessageForCode( $this->mHttpStatus )." http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] );
		}

		$gBitThemes->preLoadStyle();
		if( file_exists(THEMES_STYLE_PATH."theme_head_inc.tpl") ) {
			$gBitSmarty->assign( 'theme_head', THEMES_STYLE_PATH."theme_head_inc.tpl" );
		}
		// set the correct headers if it hasn't been done yet
		if( empty( $gBitThemes->mFormatHeader )) {
			// display is the last thing we call and therefore we need to set a default
			$gBitThemes->setFormatHeader( !empty( $pOptionsHash['format'] ) ? $pOptionsHash['format'] : 'html' );
		}

		// set the desired display mode - this lets bitweaver know what type of page we are viewing
		if( empty( $gBitThemes->mDisplayMode )) {
			// display is the last thing we call and therefore we need to set a default
			$gBitThemes->setDisplayMode( !empty( $pOptionsHash['display_mode'] ) ? $pOptionsHash['display_mode'] : 'display' );
		}

		if( $pMid == 'error.tpl' ) {
			$this->setBrowserTitle( !empty( $pBrowserTitle ) ? $pBrowserTitle : KernelTools::tra( 'Error' ) );
			$pMid = 'bitpackage:kernel/error.tpl';
		}

		// only using the default html header will print modules and all the rest of it.
		if( $gBitThemes->mFormatHeader != 'html' ) {
			$gBitSmarty->display( $pMid );
			return;
		}

		if( !empty( $pBrowserTitle )) {
			$this->setBrowserTitle( $pBrowserTitle ); 
		}

		// populate meta description with something useful so you are not penalized/ignored by web crawlers
		if( is_object( $gContent ) && is_a( $gContent, 'LibertyContent' ) ) {
			if( $desc = $gContent->generateDescription() ) {
				$desc = preg_replace( '/\s+/', ' ', strip_tags( $desc ));  // $gContent->getContentTypeName().': '.
				$gBitSmarty->assign( 'metaDescription', substr( $desc, 0, 256 ) );
			}
		}

		$this->preDisplay( $pMid );
		$gBitSmarty->assign( 'mid', $pMid );
		if( defined( 'ROLE_MODEL' ) ) {
			$gBitSmarty->assign( 'role_model', true );
		}

		// Create key for CSP nonce value ... TODO ? this could be the tk ticket value
		// tk only exists when logged in ;)
		global $gBitUser;
		if (empty($_SESSION['csp_nonce'])) {
			$_SESSION['csp_nonce'] = $gBitUser->mTicket ?? bin2hex(random_bytes(16));
		}
		$gBitSmarty->assign( 'cspNonce', $_SESSION['csp_nonce'] );

		// Make sure that the gBitSystem symbol available to templates is correct and up-to-date.
		print $gBitSmarty->fetch( 'bitpackage:kernel/html.tpl' );
		$this->postDisplay( $pMid );
	}


	// === preDisplay
	/**
	 * Take care of any processing that needs to happen just before the template is displayed
	 *
	 * @param string
	 * @access private
	 */
	public function preDisplay( $pMid ) {
		global $gCenterPieces, $gBitSmarty, $gBitThemes, $gDefaultCenter;
		if( !defined( 'JSCALENDAR_PKG_URL' ) ) {
			define( 'JSCALENDAR_PKG_URL', UTIL_PKG_URL.'javascript/libs/dynarch/jscalendar/' );
		}

		$gBitThemes->loadLayout();

		// check to see if we are working with a dynamic center area
		if( $pMid == 'bitpackage:kernel/dynamic.tpl' ) {
			$gBitSmarty->assign( 'gCenterPieces', $gCenterPieces );
		}

		$gBitThemes->preLoadStyle();

		/* @TODO - fetch module php files before rendering tpls.
		 * The basic problem here is center_list and module files are
		 * processed during page rendering, which means code in those
		 * files can not set <head> information before rendering. Kinda sucks.
		 *
		 * So what this does is, this calls on a service function allowing any
		 * package to check if its center or other module file is going to be
		 * called and gives it a chance to set any information for <head> first.
		 *
		 * Remove when TODO is complete. -wjames5
		 */
		global $gBitUser;
		if( isset( $gBitUser )) {
			//SMARTY3 $gBitUser->invokeServices( 'module_display_function' );
		}

		// process layout
		// SMARTY3 require_once( THEMES_PKG_INCLUDE_PATH.'modules_inc.php' );

		$gBitThemes->loadStyle();

		/* force the session to close *before* displaying. Why? Note this very important comment from http://us4.php.net/exec
			edwin at bit dot nl
			23-Jan-2002 04:47
				If you are using sessions and want to start a background process, you might
				have the following problem:
				The first time you call your script everything goes fine, but when you call it again
				and the process is STILL running, your script seems to "freeze" until you kill the
				process you started the first time.

				You'll have to call session_write_close(); to solve this problem. It has something
				to do with the fact that only one script/process can operate at once on a session.
				(others will be lockedout until the script finishes)

				I don't know why it somehow seems to be influenced by background processes,
				but I tried everything and this is the only solution. (i had a perl script that
				"daemonized" it's self like the example in the perl manuals)

				Took me a long time to figure out, thanks ian@virtisp.net! :-)

			... and a similar issue can happen for very long display times.
		 */
		session_write_close();
	}

	// === postDisplay
	/**
	 * Take care of any processing that needs to happen just after the template is displayed
	 *
	 * @param string
	 * @access private
	 */
	public function postDisplay( $pMid ) {
	}

	// === setHelpInfo
	/**
	 * Set the smarty variables needed to display the help link for a page.
	 *
	 * @param string $package Package Name
	 * @param string $context Context of the help within the package
	 * @param string $desc Description of the help link (not the help itself)
	 */
	public function setHelpInfo( $package, $context, $desc ) {
		global $gBitSmarty;
		$gBitSmarty->assign( 'BitweaverHelpInfo', [ 'URL' => "http://doc.bitweaver.org/wiki/index.php?page=$package$context", 'Desc' => $desc ] );
	}

	// === getPackageStatus
	/**
	 * find out a packages installation status
	 * @param string $pPackageName the name of the package to test
	 *        where the package name is in the form used to index $mPackages
	 * @return string where
	 *              'i' is installed but not active
	 *              'y' is installed and active
	 *              'n' is not installed
	 */
	public function getPackageStatus( $pPackageName ) {

		// A package is installed if
		//    $this->getConfig('package_'.$name) == 'i'
		// or $this->getConfig('package_'.$name) == 'y'
		//
		// A package is installed and active if
		//     <package name>_PKG_NAME is defined
		// and $this->getConfig('package_'.$name) == 'y'

		$ret = 'n';
		if( defined( strtoupper( $pPackageName ).'_PKG_NAME' ) ) {
			if( $name = strtolower( @constant( strtoupper( $pPackageName ).'_PKG_NAME' ))) {
				// kernel always active
				$ret = $name == 'kernel' ? $ret = 'y' : $this->getConfig( 'package_'.$name, 'n' );
			}
		}

		return $ret;
	}

	// === isPackageActive
	/**
	 * check's if a package is active.
	 * @param $pPackageName the name of the package to test
	 *        where the package name is in the form used to index $mPackages
	 *        See comments in scanPackages for more information
	 * @return bool
	 * @access public
	 */
	public function isPackageActive( $pPackageName ) {

		return $this->getPackageStatus( $pPackageName ) == 'y';
	}

	// === isPackageActiveEarly
	/**
	 * check if a package is active; but only do this after making sure a package
	 * has had it's bit_setup_inc loaded if possible.  This func exists for use in
	 * other packages bit_setup_inc's to avoid dependency on load order and ugly code
	 * @param $pPackageName the name of the package to test
	 *        where the package name is in the form used to index $mPackages
	 *        See comments in scanPackages for more information
	 * @return bool
	 * @access public
	 */
	public function isPackageActiveEarly( $pPackageName ) {

		$ret = false;
		$pkgname_l = strtolower( $pPackageName );
		if( is_file(BIT_ROOT_PATH.$pkgname_l.'/includes/bit_setup_inc.php') ) {
			require_once BIT_ROOT_PATH.$pkgname_l.'/includes/bit_setup_inc.php';
			$ret = $this->isPackageActive( $pPackageName );
		} elseif( $pkgname_l == 'kernel' ) {
			$ret = true;
		}

		return $ret;
	}

	// === isPackageInstalled
	/**
	 * check's if a package is Installed
	 * @param $pPackageName the name of the package to test
	 *        where the package name is in the form used to index $mPackages
	 *        See comments in scanPackages for more information
	 * @return bool
	 * @access public
	 */
	public function isPackageInstalled( $pPackageName ) {

		$pkgstatus = $this->getPackageStatus( $pPackageName );

		return ( $pkgstatus == 'y' ) || ( $pkgstatus == 'i' );
	}

	// === verifyPackage
	/**
	 * It will verify that the given package is active or it will display the error template and die()
	 * @param $pPackageName the name of the package to test
	 *        where the package name is in the form used to index $mPackages
	 *        See comments in scanPackages for more information
	 * @return bool
	 * @access public
	 */
	public function verifyPackage( $pPackageName ) {
		if( !$this->isPackageActive( $pPackageName ) ) {
			$this->fatalError( KernelTools::tra("This package is disabled").": $pPackageName", null, null, HttpStatusCodes::HTTP_NOT_FOUND );
		}

		return true;
	}

	// === getPermissionInfo
	/**
	 * It will get information about a permissions
	 * @param string $pPermission value of a given permission
	 * @param string $pPackageName value of a given package
	 * @return array
	 */
	public function getPermissionInfo( $pPermission = '', $pPackageName = '' ) {
		$ret = null;
		$bindVars = [];
		$sql = 'SELECT * FROM `'.BIT_DB_PREFIX.'users_permissions` ';
		if( !empty( $pPermission ) ) {
			$sql .= ' WHERE `perm_name`=? ';
			array_push( $bindVars, $pPermission );
		} elseif( !empty( $pPackageName ) ) {
			$sql .= ' WHERE `package` = ? ';
			array_push( $bindVars, substr($pPackageName,0,100));
		}
		$ret = $this->mDb->getAssoc( $sql, $bindVars );
		return $ret;
	}

	// === verifyPermission
	/**
	 * DEPRECATED - this function has been moved into BitPermUser, use that
	 */
	public function verifyPermission( $pPermission, $pMsg = null ) {
		global $gBitUser;
		return $gBitUser->verifyPermission( $pPermission, $pMsg );
	}

	// === fatalPermission
	/**
	 * Interupt code execution and show a permission denied message.
	 * This does not show a big nasty denied message if user is simply not logged in.
	 * This *could* lead to a user seeing a denied message twice, however this is
	 * unlikely as logic permission checks should prevent access to non-permed page REQUEST in the first place
	 * @param $pPermission value of a given permission
	 * @param $pMsg optional additional information to present to user
	 * @return void
	 * @access public
	 */
	public function fatalPermission( $pPermission, $pMsg=null ) {
		global $gBitUser, $gBitSmarty, $gBitThemes;
		if( !$gBitUser->isRegistered() ) {
			require_once USERS_PKG_CLASS_PATH.'BitHybridAuthManager.php';
			BitHybridAuthManager::loadSingleton();
			global $gBitHybridAuthManager;
			$gBitSmarty->assign( 'hybridProviders', $gBitHybridAuthManager->getEnabledProviders() );
			$gBitSmarty->assign( 'template', 'bitpackage:users/login_inc.tpl' );
		} else {
			$title = 'Oops!';
			if( empty( $pMsg ) ) {
				$pMsg = $this->getPermissionDeniedMessage( $pPermission );
			}
			$gBitSmarty->assign( 'fatalTitle', KernelTools::tra( "Permission denied." ) );
		}
// bit_error_log( "PERMISSION DENIED: $pPermission $pMsg" );
		$gBitSmarty->assign( 'msg', KernelTools::tra( $pMsg ) );
		$this->setHttpStatus( HttpStatusCodes::HTTP_NOT_FOUND );
		$this->display( "error.tpl" );
		die;
	}

	public function getPermissionDeniedMessage( $pPermission ) {
		$permDesc = $this->getPermissionInfo( $pPermission );
		$ret = "You do not have the required permissions";
		if( !empty( $permDesc[$pPermission]['perm_desc'] ) ) {
			if( preg_match( '/administrator,/i', $permDesc[$pPermission]['perm_desc'] ) ) {
				$ret .= preg_replace( '/^administrator, can/i', ' to ', $permDesc[$pPermission]['perm_desc'] );
			} else {
				$ret .= preg_replace( '/^can /i', ' to ', $permDesc[$pPermission]['perm_desc'] );
			}
		}
		return $ret;
	}

	/**
	 * This code was duplicated _EVERYWHERE_ so here is an easy template to cut that down.
	 * @param $pFormHash documentation needed
	 * @param $pMsg documentation needed
	 * @return void
	 * @access public
	 */
	public function confirmDialog( $pFormHash, $pMsg ) {
		global $gBitSmarty;
		if( !empty( $pMsg ) ) {
			$pageTitle = self::getParameter( $pMsg, 'label', 'Please Confirm' );
			if( empty( $pParamHash['cancel_url'] ) ) {
				$gBitSmarty->assign( 'backJavascript', 'onclick="history.back();"' );
			}
			if( !empty( $pFormHash['input'] ) ) {
				$gBitSmarty->assign( 'inputFields', $pFormHash['input'] );
				unset( $pFormHash['input'] );
			}
			$gBitSmarty->assign( 'msgFields', $pMsg );
			$gBitSmarty->assign( 'hiddenFields', $pFormHash );
			$this->display( 'bitpackage:kernel/confirm.tpl', $pageTitle, [ 'display_mode' => 'edit' ]);
			die;
		}
	}

	// === isFeatureActive
	/**
	 * check's if the specfied feature is active
	 *
	 * @param string $pFeatureName
	 * @return bool
	 */
	public function isFeatureActive( $pFeatureName ) {
		$ret = false;
		if( $pFeatureName ) {
			$featureValue = $this->getConfig($pFeatureName);
			$ret = !empty( $featureValue ) && ( $featureValue != 'n' );
		}
		return $ret;
	}

	// === verifyFeature
	/**
	 * It will verify that the given feature is active or it will display the error template and die()
	 * @param $pFeatureName the name of the package to test
	 * @return bool
	 *
	 * @param  $pKey hash key
	 */
	public function verifyFeature( $pFeatureName ) {
		if( !$this->isFeatureActive( $pFeatureName ) ) {
			$this->fatalError( KernelTools::tra("This feature is disabled").": $pFeatureName" );
		}

		return true;
	}

	// === registerPackage
	/**
	 * Define name, location and url DEFINE's
	 *
	 * @param  $pKey hash key
	 * @return void
	 * @access public
	 */
	public function registerPackage( $pRegisterHash ) {
		if( !isset( $pRegisterHash['package_name'] )) {
			$this->fatalError( KernelTools::tra("Package name not set in ")."registerPackage: $this->mPackageFileName" );;
		} else {
			$name = $pRegisterHash['package_name'];
		}

		if( !isset( $pRegisterHash['package_path'] )) {
			$this->fatalError( KernelTools::tra("Package path not set in ")."registerPackage: $this->mPackageFileName" );;
		} else {
			$path = $pRegisterHash['package_path'];
		}

		$this->mRegisterCalled = true;
		if( empty( $this->mPackages )) {
			$this->mPackages = [];
		}
		$pkgName = str_replace( ' ', '_', strtoupper( $name ));
		$pkgNameKey = strtolower( $pkgName );

		// Some package settings
		$this->mPackages[$pkgNameKey]['homeable'] = !empty( $pRegisterHash['homeable'] );
		$this->mPackages[$pkgNameKey]['required'] = !empty( $pRegisterHash['required_package'] );
		$this->mPackages[$pkgNameKey]['service']  = !empty( $pRegisterHash['service'] ) ? $pRegisterHash['service'] : false;
		$this->mPackages[$pkgNameKey]['status']   = $this->getConfig( 'package_'.$pkgNameKey, 'n');

		# y = Active
		# i = Installed
		# n (or empty/null) = Not Active and Not Installed

		// set package installed and active flag
		$this->mPackages[$pkgNameKey]['active_switch'] = $this->mPackages[$pkgNameKey]['status'] == 'a' || $this->mPackages[$pkgNameKey]['status'] == 'y' ? true : false;

		// set package installed flag (can be installed but not active)
		$this->mPackages[$pkgNameKey]['installed'] = $this->mPackages[$pkgNameKey]['status'] == 'i' || $this->mPackages[$pkgNameKey]['status'] == 'y' ? true : false;

		// Define <PACKAGE>_PKG_PATH
		$pkgDefine = $pkgName.'_PKG_PATH';
		if( !defined( $pkgDefine )) {
			$pkgPath = BIT_ROOT_PATH . basename( $path ) . '/';
			define( $pkgDefine, $pkgPath );
			$arrayHash = [ 
				$pkgName.'_PKG_INCLUDE_PATH' => BIT_ROOT_PATH . basename( $path ) . '/includes/', 
				$pkgName.'_PKG_CLASS_PATH' => BIT_ROOT_PATH . basename( $path ) . '/includes/classes/',
				$pkgName.'_PKG_ADMIN_PATH' => BIT_ROOT_PATH . basename( $path ) . '/admin/' 
			];
			foreach( $arrayHash as $defName => $defPath ) {
				if( !defined( $defName )) {
					define( $defName, is_dir( $defPath ) ? $defPath : $pkgPath );
				}
			}
		}
		$this->mPackages[$pkgNameKey]['url']  = BIT_ROOT_URL . basename( $path ) . '/';
		$this->mPackages[$pkgNameKey]['path']  = BIT_ROOT_PATH . basename( $path ) . '/';

		// Define <PACKAGE>_PKG_URL
		$pkgDefine = (string) $pkgName.'_PKG_URL';
		if( !defined( $pkgDefine )) {
			// Force full URI's for offline or exported content (newsletters, etc.)
			$root = !empty( $_REQUEST['uri_mode'] ) ? BIT_BASE_URI . BIT_ROOT_URL : BIT_ROOT_URL;
			define( $pkgDefine, $root . basename( $path ) . '/' );
		}

		// Define <PACKAGE>_PKG_URI
		$pkgDefine = $pkgName.'_PKG_URI';
		if( !defined( $pkgDefine ) && defined( 'BIT_BASE_URI' )) {
			define( $pkgDefine, BIT_BASE_URI . BIT_ROOT_URL . basename( $path ) . '/' );
		}

		// Define <PACKAGE>_PKG_NAME
		$pkgDefine = $pkgName.'_PKG_NAME';
		if( !defined( $pkgDefine )) {
			define( $pkgDefine, $name );
			$this->mPackages[$pkgNameKey]['activatable']  = isset( $pRegisterHash['activatable'] ) ? $pRegisterHash['activatable'] : true;
		}
		$this->mPackages[$pkgNameKey]['name'] = $name;

		// Define <PACKAGE>_PKG_DIR
		$package_dir_name = basename( $path );
		$pkgDefine = $pkgName.'_PKG_DIR';
		if( !defined( $pkgDefine )) {
			define( $pkgDefine, $package_dir_name );
		}
		$this->mPackages[$pkgNameKey]['dir'] = $package_dir_name;
		$this->mPackagesDirNameXref[$package_dir_name] = $pkgNameKey;

		// Define <PACKAGE>_PKG_TITLE
		$pkgDefine = $pkgName.'_PKG_TITLE';
		if( !defined( $pkgDefine )) {
			define( $pkgDefine, ucfirst( constant( $pkgName.'_PKG_DIR' ) ) );
		}
		$this->mPackages[$pkgNameKey]['dir'] = $package_dir_name;

		// Work around for old versions of IIS that do not support $_SERVER['SCRIPT_FILENAME'] - wolff_borg
		if( !array_key_exists( 'SCRIPT_FILENAME', $_SERVER )) {
			//remove double-backslashes and return
			$_SERVER['SCRIPT_FILENAME'] =  str_replace('\\\\', '\\', $_SERVER['PATH_TRANSLATED'] );
		}
	}

	public function setActivePackage( $pPkgName ) {
		$this->mActivePackage = $pPkgName;
	}

	public function getActivePackage() {
		if( empty( $this->mActivePackage ) ) {
			$this->mActivePackage = 'kernel'; // default to kernel, which has the default layout
			// Define the package we are currently in
			// I tried strpos instead of preg_match here, but it didn't like strings that begin with slash?! - spiderr
			$scriptDir =  basename( dirname( $_SERVER['SCRIPT_FILENAME'] ) );
			foreach( array_keys( $this->mPackages ) as $pkgNameKey ) {
				if( $scriptDir == $this->mPackages[$pkgNameKey]['dir'] ) {
					$this->mActivePackage = $pkgNameKey;
					if( !defined( 'ACTIVE_PACKAGE' ) ) {
						define( 'ACTIVE_PACKAGE', $pkgNameKey );
					}
					break;
				}
			}
		}
		return $this->mActivePackage;
	}

	// === registerAppMenu
	/**
	 * Register global system menu. Due to the startup nature of this method, it need to belong in BitSystem instead of BitThemes, where it would more naturally fit.
	 *
	 * @param  $pKey hash key
	 * @return void
	 * @access public
	 */
	public function registerAppMenu( $pMenuHash, $pMenuTitle = null, $pTitleUrl = null, $pMenuTemplate = null, $pAdminPanel = false ) {
		$menuType = !empty( $pMenuHash['menu_type'] ) ? $pMenuHash['menu_type'] : 'bar';
		if( is_array( $pMenuHash ) ) {
			// shorthand
			$pkg = $pMenuHash['package_name'];

			// prepare hash
			$pMenuHash['style']       = 'display:'.( ( isset( $_COOKIE[$pkg.'menu'] ) && ( $_COOKIE[$pkg.'menu'] == 'o' ) ) ? 'block;' : 'none;' );
			$pMenuHash['is_disabled'] = $this->getConfig( 'menu_'.$pkg ) == 'n';
			$pMenuHash['menu_title']  = $this->getConfig( $pkg.'_menu_text',
				!empty( $pMenuHash['menu_title'] )
				? $pMenuHash['menu_title']
				: ucfirst( constant( strtoupper( $pkg ).'_PKG_DIR' )));
			$pMenuHash['menu_position'] = $this->getConfig( $pkg.'_menu_position', 
				$pMenuHash['menu_position'] ?? '');

			$this->mAppMenu[$menuType][$pkg] = $pMenuHash;
		} else {
			KernelTools::deprecated( 'Please use a menu registration hash instead of individual parameters: $gBitSystem->registerAppMenu( $menuHash )' );
			$this->mAppMenu[$menuType][strtolower( $pMenuHash )] = [
				'menu_title'    => $pMenuTitle,
				'is_disabled'   => ( $this->getConfig( 'menu_' . $pMenuHash ) == 'n' ),
				'index_url'     => $pTitleUrl,
				'menu_template' => $pMenuTemplate,
				'admin_panel'   => $pAdminPanel,
				'style'         => 'display:' . ( empty( $pMenuTitle ) || ( isset( $_COOKIE[$pMenuHash . 'menu'] ) && ( $_COOKIE[$pMenuHash . 'menu'] == 'o' ) ) ? 'block;' : 'none;' )
			];
		}
		uasort( $this->mAppMenu[$menuType], 'Bitweaver\bit_system_menu_sort' );
	}

	/**
	 * registerNotifyEvent
	 *
	 * @param array $pEventHash
	 * @access public
	 * @return void
	 */
	public function registerNotifyEvent( $pEventHash ) {
		$this->mNotifyEvents = array_merge( $this->mNotifyEvents, $pEventHash );
	}

	// === fatalError
	/**
	 * If an unrecoverable error has occurred, this method should be invoked. script exist occurs
	 *
	 * @param string $ pMsg error message to be displayed
	 * @param string template file used to display error
	 * @param string error dialog title. default gets site_error_title config, passing '' will result in no title
	 * @return void this function will DIE DIE DIE!!!
	 * @access public
	 */
	public function fatalError( $pMsg, $pTemplate=null, $pErrorTitle=null, $pHttpStatus = 200  ) {
		global $gBitSmarty, $gBitThemes;
		if( is_null( $pErrorTitle ) ) {
			$pErrorTitle = $this->getConfig( 'site_error_title', '' );
		}

		if( empty( $pTemplate ) ) {
			$pTemplate = 'error.tpl';
		}

		$gBitSmarty->assign( 'fatalTitle', KernelTools::tra( $pErrorTitle ) );
		$gBitSmarty->assign( 'msg', $pMsg );
		// if mHttpStatus is set, we can assume this was an expected fatal, such as a 404 or 403
		if( !isset( $this->mHttpStatus ) ) {
			error_log( "Fatal Error: $pMsg http://".$_SERVER['HTTP_HOST'].$_SERVER['REQUEST_URI'] );
		}

		$this->setHttpStatus( $pHttpStatus );
		if( $gBitThemes->isAjaxRequest() ) {
			$gBitSmarty->display( 'bitpackage:kernel/'.$pTemplate );
		} else {
			$gBitSmarty->assign( 'metaNoIndex', 1 );
			$this->display( $pTemplate );
		}
		die;
	}

	// === loadPackage
	/**
	 * Loads a package
	 *
	 * @param string $ pkgDir = Directory Name of package to load
	 * @param string $ pScanFile file to be looked for
	 * @param string $ autoRegister - true = autoregister any packages that don't register on their own, false = don't
	 * @param string $ pOnce - true = do include_once to load file false = do include to load the file
	 * @return void
	 * @access public
	 */
	public function loadPackage( $pPkgDir, $pScanFile, $pAutoRegister=true, $pOnce=true ) {
		#check if already loaded, loading again won't work with 'include_once' since
		#no register call will be done, so don't auto register.
		if( $pAutoRegister && !empty( $this->mPackagesDirNameXref[$pPkgDir] ) ) {
			$pAutoRegister = false;
		}

		$this->mRegisterCalled = false;
		$scanFile = $pScanFile == 'admin/schema_inc.php' ? BIT_ROOT_PATH.$pPkgDir.'/'.$pScanFile : BIT_ROOT_PATH.$pPkgDir.'/includes/'.$pScanFile;
		$file_exists = 0;

		if( file_exists( $scanFile ) ) {
			$file_exists = 1;
			global $gBitSystem, $gLibertySystem, $gBitSmarty, $gBitUser, $gBitLanguage;
			$this->mPackageFileName = $scanFile;
			if( $pOnce ) {
				include_once $scanFile;
			} else {
				include $scanFile;
			}
		}

		if( ( $file_exists || $pPkgDir == 'kernel' ) && ( $pAutoRegister && !$this->mRegisterCalled ) ) {
			$pRegisterHash = [
				#for auto registered packages Registration Package Name = Package Directory Name
				'package_name' => $pPkgDir,
				'package_path' => BIT_ROOT_PATH . $pPkgDir . '/',
				'activatable'  => false,
			];
			if( $pPkgDir == 'kernel' ) {
				$pRegisterHash = [ ...$pRegisterHash, 'required_package' => true ];
			}
			$this->registerPackage( $pRegisterHash );
		}
	}

	// === scanPackages
	/**
	 *
	 * scan all available packages. This is an *expensive* function. DO NOT call this functionally regularly , or arbitrarily. Failure to comply is punishable by death by jello suffication!
	 *
	 * @param string $ pScanFile file to be looked for
	 * @param string $ pOnce - true = do include_once to load file false = do include to load the file
	 * @param string $ pSelect - empty or 'all' = load all packages, 'installed' = load installed, 'active' = load active, 'x' = load packages with status x
	 * @param string $ autoRegister - true = autoregister any packages that don't register on their own, false = don't
	 * @param string $ fileSystemScan - true = scan file system for packages to load, False = don't
	 * @return void
	 *
	 * Packages have three different names:
	 *    The directory name where they reside on disk
	 *    The Name they register themselves as when they call registerPackage
	 *    The Key for the array $this->mPackages
	 *
	 * Example:
	 *    A package in directory 'stars' that registers itself with a name of 'Star Ratings'
	 *    would have these three names:
	 *
	 *    Directory Name: 'stars'
	 *    Registered Name: Star Ratings'
	 *    $this->mPackages key: 'star_ratings'
	 *
	 *    Of course, its possible for all three names to be the same if the registered name
	 *    is all lower case without spaces and is the same as the diretory name.
	 *
	 *    Functions that expect a package name as a parameter should make clear which form
	 *    of the name they expect.
	 *
	 * @access public
	 */
	public function scanPackages( $pScanFile = 'bit_setup_inc.php', $pOnce=true, $pSelect='', $pAutoRegister=true ) {
		global $gPreScan;
		if( !empty( $gPreScan ) && \is_array( $gPreScan )) {
			// gPreScan may hold a list of packages that must be loaded first
			foreach( $gPreScan as $pkgDir ) {
			    $loadPkgs[] = $pkgDir;
			}
		}
		// load lib configs
		if( $pkgDir = opendir( BIT_ROOT_PATH )) {
			while( false !== ( $dirName = readdir( $pkgDir ))) {
				if( $dirName != '..'  && $dirName != '.' && is_dir( BIT_ROOT_PATH . '/' . $dirName ) && $dirName != 'CVS' && preg_match( '/^\w/', $dirName )) {
					$loadPkgs[] = $dirName;
				}
			}
		}
		$loadPkgs = array_unique( $loadPkgs );

		// load the list of pkgs in the right order
		foreach( $loadPkgs as $loadPkg ) {
            $this->loadPackage( $loadPkg, $pScanFile, $pAutoRegister, $pOnce );
		}


		if( !defined( 'BIT_STYLES_PATH' ) && defined( 'THEMES_PKG_PATH' )) {
			define( 'BIT_STYLES_PATH', THEMES_PKG_PATH.'styles/' );
		}

		if( !defined( 'BIT_STYLES_URL' ) && defined( 'THEMES_PKG_URL' )) {
			define( 'BIT_STYLES_URL', THEMES_PKG_URL.'styles/' );
		}
	}

	/**
	 * getSiteTitle
	 *
	 * @access public
	 * @return string name of website
	 */
	public function getSiteTitle() {
		return $this->getConfig( 'site_title' );
	}

	/**
	 * getDefaultPage
	 *
	 * @access public
	 * @return string URL of site homepage
	 */
	public function getDefaultPage() {
		return $this->getIndexPage( $this->getConfig( "bit_index" ) );
	}

	/**
	 * getIndexPage
	 *
	 * Returns the page for the given type
	 * defaults to the site homepage
	 *
	 * @access public
	 * @return string URL of page by index type
	 */
	public function getIndexPage( $pIndexType = null ){
		global $userlib, $gBitUser, $gBitSystem;
		$pIndexType = !is_null( $pIndexType )? $pIndexType : $this->getConfig( "bit_index" );
		$url = '';
		if( $pIndexType == 'role_home') {
			// See if we have first a user assigned default group id, and second a group default system preference
			if( !$gBitUser->isRegistered() && ( $role_home = $gBitUser->getRoleHome( ANONYMOUS_TEAM_ID ))) {
			} elseif( @$this->verifyId( $gBitUser->mInfo['default_role_id'] ) && ( $role_home = $gBitUser->getRoleHome( $gBitUser->mInfo['default_role_id'] ))) {
			} elseif( $this->getConfig( 'default_home_role' ) && ( $role_home = $gBitUser->getRoleHome( $this->getConfig( 'default_home_role' )))) {
			}

			if( !empty( $role_home )) {
				if( $this->verifyId( $role_home ) ) {
					$url = BIT_ROOT_URL."index.php".( !empty( $role_home ) ? "?content_id=".$role_home : "" );
				// wiki dependence - NO bad idea
				// } elseif( strpos( $group_home, '/' ) === false ) {
				// 	$url = BitPage::getDisplayUrl( $group_home );
				} elseif(  strpos( $role_home, 'http://' ) === false ){
					$url = BIT_ROOT_URL.$role_home;
				} else {
					$url = $role_home;
				}
			}
		} elseif( $pIndexType == 'group_home') {
			// See if we have first a user assigned default group id, and second a group default system preference
			if( !$gBitUser->isRegistered() && ( $group_home = $gBitUser->getGroupHome( ANONYMOUS_GROUP_ID ))) {
			} elseif( @$this->verifyId( $gBitUser->mInfo['default_group_id'] ) && ( $group_home = $gBitUser->getGroupHome( $gBitUser->mInfo['default_group_id'] ))) {
			} elseif( $this->getConfig( 'default_home_group' ) && ( $group_home = $gBitUser->getGroupHome( $this->getConfig( 'default_home_group' )))) {
			}

			if( !empty( $group_home )) {
				if( $this->verifyId( $group_home ) ) {
					$url = BIT_ROOT_URL."index.php".( !empty( $group_home ) ? "?content_id=".$group_home : "" );
				// wiki dependence - NO bad idea
				// } elseif( strpos( $group_home, '/' ) === false ) {
				// 	$url = BitPage::getDisplayUrl( $group_home );
				} elseif(  strpos( $group_home, 'http://' ) === false ){
					$url = BIT_ROOT_URL.$group_home;
				} else {
					$url = $group_home;
				}
			}
		} elseif( $pIndexType == 'my_page' || $pIndexType == 'my_home' || $pIndexType == 'user_home'  ) {
			// TODO: my_home is deprecated, but was the default for BWR1. remove in DILLINGER - spiderr
			if( $gBitUser->isRegistered() ) {
				if( !$gBitUser->isRegistered() ) {
					$url = USERS_PKG_URL.'signin.php';
				} else {
					if( $pIndexType == 'my_page' ) {
						$url = $gBitSystem->getConfig( 'users_login_homepage', USERS_PKG_URL.'my.php' );
						if( $url != USERS_PKG_URL.'my.php' && strpos( $url, 'http://' ) === false ){
							// the safe assumption is that a custom path is a subpath of the site
							// append the root url unless we have a fully qualified uri
							$url = BIT_ROOT_URL.$url;
						}
					} elseif( $pIndexType == 'user_home' ) {
						$url = $gBitUser->getDisplayUrl();
					} else {
						$users_homepage = $gBitUser->getPreference( 'users_homepage' );
						if( isset( $users_homepage ) && !empty( $users_homepage )) {
							$home = [ 'title' => $users_homepage];
							$url = strpos($users_homepage, '/') === false 
								? BitPage::getDisplayUrlFromHash( $home ) 
								: $users_homepage;
						}
					}
				}
			} else {
				$url = USERS_PKG_URL . 'signin.php';
			}
		} elseif( in_array( $pIndexType, array_keys( $gBitSystem->mPackages ) ) ) {
			$work = strtoupper( $pIndexType ).'_PKG_URL';
			if (defined("$work")) {
				$url = constant( $work );
			}

			/* this was commented out with the note that this can send requests to inactive packages -
			 * that should only happen if the admin chooses to point to an inactive pacakge.
			 * commenting this out however completely breaks the custom uri home page feature, so its
			 * turned back on and caviate admin - if the problem is more severe than it seems then
			 * get in touch on irc and we'll work out a better solution than commenting things on and off -wjames5
			 */
		} elseif( !empty( $pIndexType ) ) {
			$url = BIT_ROOT_URL.$pIndexType;
		}

		// if no special case was matched above, default to users' my page
		if( empty( $url ) ) {
			if( $this->isPackageActive( 'wiki' ) ) {
				$url = WIKI_PKG_URL;
			} elseif( !$gBitUser->isRegistered() ) {
				$url = USERS_PKG_URL . 'signin.php';
			} else {
				$url = USERS_PKG_URL . 'my.php';
			}
		}

		if( strpos( $url, 'http://' ) === false ) {
			$url = preg_replace( "#//#", "/", $url );
		}
		
		return $url;
	}
	// === setOnloadScript
	/**
	 * add javascript to the <body onload> attribute
	 *
	 * @param string $pJavascript javascript to be added
	 * @return void
	 * @access public
	 */
	public function setOnloadScript( $pJavscript ) {
		array_push( $this->mOnload, $pJavscript );
	}
	// === setOnunloadScript
	/**
	 * add javascript to the <body onunload> attribute
	 *
	 * @param string $pJavascript javascript to be added
	 * @return void
	 * @access public
	 */
	public function setOnunloadScript( $pJavscript ) {
		array_push( $this->mOnunload, $pJavscript );
	}
	// === getBrowserTitle
	/**
	 * get the title of the browser
	 *
	 * @return string title string
	 * @access public
	 */
	public function getBrowserTitle() {
		global $gPageTitle;
		return $gPageTitle;
	}

	// === setBrowserTitle
	/**
	 * set the title of the browser
	 *
	 * @param string $ pTitle title to be used
	 * @return void
	 * @access public
	 */
	public function setBrowserTitle( $pTitle ) {
		global $gBitSmarty, $gPageTitle;
		$gPageTitle = $pTitle;
		$gBitSmarty->assign( 'browserTitle', $pTitle );
		$gBitSmarty->assign( 'gPageTitle', $pTitle );
	}

	// === setPagination
	/**
	 * set the canonical page title
	 *
	 * @param array $pListInfo
	 * @return void
	 */
	public function setPagination( $pListInfo ): void {
		global $gBitSmarty;
		if( !empty( $pListInfo['total_pages'] ) && !empty( $pListInfo['page_records'] ) ) {
			$relTags = "";
			$baseUrl = isset( $pListInfo['url'] ) ? $pListInfo['url'] : $_SERVER['SCRIPT_URL'];

			if( !empty( $pListInfo['query_string'] ) ) {
				$pageUrl = $baseUrl.'?'.$pListInfo['query_string'];
			} else {
				$queryString = '';
				foreach( [ 'parameters', 'ihash' ] as $paramKey ) {
					if( !empty( $pListInfo[$paramKey] ) ) {
						foreach( $pListInfo['parameters'] as $param=>$value ) {
							if( is_array( $value ) ) {
								foreach( $value as $v ) {
									if( !empty( $v ) ) {
										$queryString .= $param.'[]='.$v.'&amp;';
									}
								}
							} elseif( !empty( $value ) ) {
								$queryString .= $param.'='.$value.'&amp;';
							}
						}
					}
				}

				foreach( [ 'max_records', 'sort_mode', 'find' ] as $paramKey ) {
					if( !empty( $pListInfo[$paramKey] ) ) {
						if( is_array( $pListInfo[$paramKey] ) ) {
							foreach( $pListInfo[$paramKey] as $v ) {
								$queryString = $paramKey.'[]='.$v.'&amp;';
							}
						} else {
							$queryString .= $paramKey.'='.$pListInfo[$paramKey].'&amp;';
						}
					}
				}
				$pageUrl = $baseUrl.'?'.preg_replace( '/"/', '%22', $queryString );
			}
			$currentPage = BitBase::getParameter( $pListInfo, 'current_page' );
			if( $currentPage > 1 ) {
				$relTags .= '<link rel="prev" href="'.$pageUrl.'page='.($currentPage-1).'">';
			}
			if( BitBase::getParameter( $pListInfo, 'next_offset' ) > 0 ) {
				$relTags .= '<link rel="next" href="'.$pageUrl.'page='.($currentPage+1).'">';
			}

			$gBitSmarty->assign( 'relTags', $relTags );
		}
	}

	// === setCanonicalLink
	/**
	 * set the canonical page title
	 *
	 * @param string $ pTitle title to be used
	 * @return void
	 * @access public
	 */
	public function setCanonicalLink( $pRelativeUrl ) {
		global $gBitSmarty;
		$baseUri = defined( 'CANONICAL_BASE_URI' ) ? CANONICAL_BASE_URI : BIT_BASE_URI; 
		$gBitSmarty->assign( 'canonicalLink', $baseUri.$pRelativeUrl );
	}

	/*static*/
	public static function genPass() {
		$vocales = "aeiou";
		$consonantes = "bcdfghjklmnpqrstvwxyz123456789";
		$r = '';
		for( $i = 0; $i < 8; $i++ ) {
			if( $i % 2 ) {
				$r .= $vocales[rand( 0, strlen( $vocales ) - 1 )];
			} else {
				$r .= $consonantes[rand( 0, strlen( $consonantes ) - 1 )];
			}
		}
		return $r;
	}

	// === lookupMimeType
	/**
	 * given an extension, return the mime type
	 *
	 * @param string $pExtension is the extension of the file or the complete file name
	 * @return string mime type of entry and populates $this->mMimeTypes with existing mime types
	 * @access public
	 */
	public function lookupMimeType( $pExtension ) {

		$this->loadMimeTypes();
		if( preg_match( "#\.[0-9a-z]+$#i", $pExtension )) {
			$pExtension = substr( $pExtension, strrpos( $pExtension, '.' ) + 1 );
		}
		// rfc1341 - mime types are case insensitive.
		$pExtension = strtolower( $pExtension );

		return !empty( $this->mMimeTypes[$pExtension] ) ? $this->mMimeTypes[$pExtension] : 'application/binary';
	}

	// === loadMimeTypes
	/**
	 * given an extension, return the mime type
	 *
	 * @param string $pExtension is the extension of the file or the complete file name
	 * @return void mime type of entry and populates $this->mMimeTypes with existing mime types
	 * @access public
	 */
	public function loadMimeTypes() {
		if( empty( $this->mMimeTypes )) {
			// use bitweavers mime.types file to ensure everyone has our set unless user forces his own.
			$mimeFile = defined( 'MIME_TYPES' ) ? MIME_TYPES : KERNEL_PKG_ADMIN_PATH.'mime.types';

			$this->mMimeTypes = [];
			if( $fp = fopen( $mimeFile,"r" ) ) {
				while( false != ( $line = fgets( $fp, 4096 ) ) ) {
					if( !preg_match( "/^\s*(?!#)\s*(\S+)\s+(?=\S)(.+)/", $line, $match ) ) {
						continue;
					}
					$tmp = preg_split( "/\s/",trim( $match[2] ) );
					foreach( $tmp as $type ) {
						$this->mMimeTypes[strtolower( $type )] = $match[1];
					}
				}
				fclose( $fp );
			}
		}
	}

	// === verifyFileExtension
	/**
	 * given a file and optionally desired name, return the correctly extensioned file and mime type
	 *
	 * @param string $pFile is the actual file to inspect for magic numbers to determine type
	 * @param string $pFileName is the desired name the file. This is optional in the even the pFile is non-extensioned, as is the case with file uploads
	 * @return array corrected file name and mime type
	 * @access public
	 */
	public function verifyFileExtension( $pFile, $pFileName=null ) {
		$this->loadMimeTypes();
		if( empty( $pFileName ) ) {
			$pFileName = basename( $pFile );
			$ret = $pFile;
		} else {
			$ret = $pFileName;
		}
		$verifyMime = $this->verifyMimeType( $pFile );
		if( strrpos( $pFileName, '.' ) ) {
			$extension = substr( $pFileName, strrpos( $pFileName, '.' ) + 1 );
			$lookupMime = $this->lookupMimeType( $extension );
		} else {
			// extensionless file uploaded, get ready to add an extension
			$lookupMime = '';
			$pFileName .= '.';
		}

		// if $verifyMime turns out to be 'octet-stream' and the lookupMimeType is a video file, we'll allow the video filetype and extenstion
		// if we don't do this, most uploaded videos are changed to have a '.bin' extenstion which is very annoying.
		if( $verifyMime == 'application/octet-stream' && preg_match( "/^video/", $lookupMime )) {
			$verifyMime = $lookupMime;
		} elseif( $lookupMime != $verifyMime ) {
			if( $verifyExt = $this->getMimeExtension( $verifyMime ) ) {
				$ret = substr( $pFileName, 0, strrpos( $pFileName, '.' ) + 1 ).$verifyExt;
			}
		}

		// if we still don't have an extension, we'll simply append a 'bin'
		if( preg_match( "/\.$/", $pFileName )) {
			$pFileName .= "bin";
		}

		return [ $ret, $verifyMime ];
	}


	// === verifyMimeType
	/**
	 * given a file, return the mime type
	 *
	 * @param string $pExtension is the extension of the file or the complete file name
	 * @return string mime type of entry and populates $this->mMimeTypes with existing mime types
	 * @access public
	 */
	public function verifyMimeType( $pFile ) {
		$mime = null;
		if( file_exists( $pFile ) && filesize( $pFile ) ) {
			if( function_exists( 'finfo_open' ) ) {
				$finfo = KernelTools::is_windows() && defined( 'PHP_MAGIC_PATH' ) && is_readable( PHP_MAGIC_PATH ) 
					? finfo_open( FILEINFO_MIME, PHP_MAGIC_PATH ) 
					: finfo_open( FILEINFO_MIME );
				$mime = finfo_file( $finfo, $pFile );
				finfo_close( $finfo );
			} else {
				if( KernelTools::function_enabled( "escapeshellarg" ) && KernelTools::function_enabled( "exec" )) {
					$mime = exec( trim( 'file -bi ' . escapeshellarg( $pFile )));
				}
			}

			if( empty( $mime ) ) {
				$mime = $this->lookupMimeType( substr( $pFile, strrpos( $pFile, '.' ) + 1 ) );
			}
			if( $len = strpos( $mime, ';' )) {
				$mime = substr( $mime, 0, $len );
			}
		}
		return $mime;
	}

	public function getMimeExtension( $pMimeType ) {
		$ret = '';

		if( $pMimeType == 'image/jpeg' ) {
			$ret = 'jpg'; // jpeg has three options, .jpg is the most common
		} else {
			$this->loadMimeTypes();
			if( !($ret = array_search( $pMimeType, $this->mMimeTypes )) ) {
				// not present in mMimeTypes, here are some custom types
				switch( $pMimeType ) {
					case 'image/bmp':
						$ret = 'bmp'; break;
					case 'image/pipeg':
						$ret = 'jfif'; break;
					case 'image/vnd.adobe.photoshop':
						$ret = 'psd'; break;
					case 'image/x-cmx':
						$ret = 'cmx'; break;
					case 'image/x-jps':
						$ret = 'jps'; break;
					case 'image/x-freehand':
						$ret = 'fh'; break;
				}
			}
		}
		return $ret;
	}

	/**
	 * * Prepend $pPath to the include path
	 * \static
	 */
	public static function prependIncludePath( $pPath ) {
		$include_path = get_include_path();
		$include_path = !empty($include_path) ? $pPath . PATH_SEPARATOR . $include_path : $pPath;
		return set_include_path( $include_path );
	}

	/**
	 * * Append $pPath to the include path
	 * \static
	 */
	public function appendIncludePath( $pPath ) {
		$include_path = get_include_path();
		if( $include_path ) {
			$include_path .= PATH_SEPARATOR . $pPath;
		} else {
			$include_path = $pPath;
		}
		return set_include_path( $include_path );
	}

	private function defineTempDir() {
		// allow for overridden TEMP_PKG_PATH
		if( !defined( 'TEMP_PKG_PATH' ) ) {
			$tempDir = $this->getConfig( 'site_temp_dir', self::getDefaultTempDir() );
			if( strrpos( $tempDir, '/' ) + 1 != strlen( $tempDir ) ) {
				$tempDir .= '/';
			}

			define( 'TEMP_PKG_PATH', $tempDir );
			define( 'TEMP_PKG_URL', BIT_ROOT_URL.'temp/' );
			if( !file_exists( $tempDir ) ) {
				mkdir( $tempDir, 0777, true );
			}
		}
	}

	public function getDefaultTempDir() {
		return sys_get_temp_dir().'/bitweaver/'.$_SERVER['SERVER_NAME'].'/';
	}

	/* Check that everything is set up properly
	 * \static
	 */
	public function checkEnvironment() {
		static $checked, $gTempDirs;

		if( $checked ) {
			return;
		}

		$errors = '';

		$docroot = BIT_ROOT_PATH;

        /*	this seems to prevent bw from running on servers where sessions work perfectly,
        	yet /var/lib/php/ is writeable only by php, not by bw (which is better)
        	it seems to be enough to set temp in config/kernel/config_inc.php for a writable dir
        	if session *actually* don't work - other problem
        	the installer has similar code which is also not used anymore

		if( ini_get( 'session.save_handler' ) == 'files' ) {
			$save_path = ini_get( 'session.save_path' );

			if( empty( $save_path ) ) {
				$errors .= "The session.save_path variable is not setup correctly (its empty).\n";
			} else {
				if( strpos( $save_path, ";" ) !== false ) {
					$save_path = substr( $save_path, strpos( $save_path, ";" )+1 );
				}
				$open = ini_get( 'open_basedir' );
				if( !@is_dir( $save_path ) && empty( $open ) ) {
					$errors .= "The directory '$save_path' does not exist or PHP is not allowed to access it (check open_basedir entry in php.ini).\n";
				} elseif( !bw_is_writeable( $save_path ) ) {
					$errors .= "The directory '$save_path' is not writeable.\n";
				}
			}

			if( $errors ) {
				$save_path = get_temp_dir();

				if( is_dir( $save_path ) && bw_is_writeable( $save_path ) ) {
					ini_set( 'session.save_path', $save_path );

					$errors = '';
				}
			}
		}
        */

		$wwwuser = '';
		$wwwgroup = '';

		if( KernelTools::is_windows() ) {
			if( strpos( $_SERVER["SERVER_SOFTWARE"],"IIS" ) && isset( $_SERVER['COMPUTERNAME'] ) ) {
				$wwwuser = 'IUSR_'.$_SERVER['COMPUTERNAME'];
				$wwwgroup = 'IUSR_'.$_SERVER['COMPUTERNAME'];
			} else {
				$wwwuser = 'SYSTEM';
				$wwwgroup = 'SYSTEM';
			}
		}

		if( function_exists( 'posix_getuid' ) ) {
			$userhash = @posix_getpwuid( @posix_getuid() );
			$group = @posix_getpwuid( @posix_getgid() );
			$wwwuser = $userhash ? $userhash['name'] : false;
			$wwwgroup = $group ? $group['name'] : false;
		}

		if( !$wwwuser ) {
			$wwwuser = 'nobody (or the user account the web server is running under)';
		}

		if( !$wwwgroup ) {
			$wwwgroup = 'nobody (or the group account the web server is running under)';
		}

		if( defined( 'TEMP_PKG_PATH' ) ) {
			$this->setConfig( 'site_temp_dir', TEMP_PKG_PATH );
			$permFiles[] = TEMP_PKG_PATH;
		} else {
			$permFiles[] = $this->getConfig( 'site_temp_dir', self::getDefaultTempDir() );
		}
		$permFiles[] = STORAGE_PKG_PATH;

		foreach( $permFiles as $file ) {
			$present = false;
			// Create directories as needed
			$target = $file;
			if( preg_match( '/.*\/$/', $target ) ) {
				// we have a directory
				if( !is_dir( $target ) ) {
					mkdir( $target, 02775, true );
				}
				// Check again and report problems
				if( !is_dir( $target ) ) {
					if( !KernelTools::is_windows() ) {
						$errors .= "
							<p>The directory <strong style='color:red;'>$target</strong> does not exist. To create the directory, execute a command such as:</p>
							<pre>\$ mkdir -m 777 $target</pre>
							";
					} else {
						$errors .= "<p>The directory <strong style='color:red;'>$target</strong> does not exist. Create the directory $target before proceeding</p>";
					}
				} else {
					$present = true;
				}
			} elseif( !file_exists( $target ) ) {
				if( !KernelTools::is_windows() ) {
					$errors .= "<p>The file <b style='color:red;'>$target</b> does not exist. To create the file, execute a command such as:</p>
						<pre>
						\$ touch $target
						\$ chmod 777 $target
						</pre>
						";
				} else {
					$errors .= "<p>The file <b style='color:red;'>$target</b> does not exist. Create a blank file $target before proceeding</p>";
				}
			} else {
				$present = true;
			}

			// chmod( $target, 02775 );
			if( $present && ( !KernelTools::bw_is_writeable( $target ))) {
				if( !KernelTools::is_windows() ) {
					$errors .= "<p><strong style='color:red;'>$target</strong> is not writeable by $wwwuser. To give $wwwuser write permission, execute a command such as:</p>
					<pre>\$ chmod 777 $target</pre>";
				} else {
					$errors .= "<p><b style='color:red;'>$target</b> is not writeable by $wwwuser. Check the security of the file $target before proceeding</p>";
				}
			}
			//if (!is_dir("$docroot/$dir")) {
			//	$errors .= "The directory '$docroot$dir' does not exist.\n";
			//} else if (!bw_is_writeable("$docroot/$dir")) {
			//	$errors .= "The directory '$docroot$dir' is not writeable by $wwwuser.\n";
			//}
		}

		if( $errors ) {
			$PHP_CONFIG_FILE_PATH = PHP_CONFIG_FILE_PATH;

			ob_start();
			phpinfo (INFO_MODULES);
			$httpd_conf = 'httpd.conf';

			if( preg_match( '/Server Root<\/b><\/td><td\s+align="left">([^<]*)</', ob_get_contents(), $m )) {
				$httpd_conf = $m[1] . '/' . $httpd_conf;
			}

			ob_end_clean();

			print "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"DTD/xhtml1-strict.dtd\">
<html xmlns=\"http://www.w3.org/1999/xhtml\" xml:lang=\"en\" lang=\"en\">
	<head>
		<title>bitweaver setup problems</title>
		<meta http-equiv=\"Pragma\" content=\"no-cache\" />
		<meta http-equiv=\"Expires\" content=\"-1\" />
	</head>
	<body>
		<h1 style=\"color:red;\">bitweaver is not properly set up:</h1>
		<blockquote>
			$errors
		</blockquote>";
			if( !$this->isLive() ) {
				if( !KernelTools::is_windows() ) {
					print "<p>Proceed to the installer <strong>at <a href=\"".BIT_ROOT_URL."install/install.php\">".BIT_ROOT_URL."install/install.php</a></strong> after you run the command.";
				} else {
					print "<p>Proceed to the installer <strong>at <a href=\"".BIT_ROOT_URL."install/install.php\">".BIT_ROOT_URL."install/install.php</a></strong> after you have corrected the identified problems.";
				}
				print "<br />Consult the bitweaver <a href='http://www.bitweaver.org/wiki/index.php?page=Technical_Documentation'>Technical Documentation</a> if you need more help.</p></body></html>";
			}

			exit;
		}

		$checked = true;
	}

	/**
	 * isLive returns status of the IS_LIVE constant from config/kernel/config_inc.php
	 *
	 * @access public
	 * @return bool true if IS_LIVE is defined and set to a non empty value, else false
	 */
	public function isLive() {
		return (defined( 'IS_LIVE' ) && IS_LIVE) && !$this->isFeatureActive( 'site_hidden' );
	}

	/**
	 * isIndexed returns if that page should be indexed by search engines
	 *
	 * @access public
	 * @return bool true if page should be indexed by search engines
	 */
	public function isIndexed() {
		return (!defined('SITE_NOINDEX') || !constant('SITE_NOINDEX')) && $this->isLive();
	}

	/**
	 * isTracking returns status of the IS_LIVE constant from config/kernel/config_inc.php
	 *
	 * @access public
	 * @return bool true if IS_LIVE is defined and set to a non empty value, else false
	 */
	public function isTracking() {
		global $gBitUser;
		return $this->getConfig( 'tracking_debug' ) || ($this->isLive() && !$gBitUser->hasPermission( 'p_users_admin' ));
	}

	// {{{=========================== Installer related methods ==============================
	// Keep these methods in BitSystem that we can call verifyInstalledPackages() and other
	// mthods without the need for an install/ package to be present.
	/**
	 * registerSchemaTable
	 *
	 * @param string $pPackage
	 * @param string $pTableName
	 * @param string $pDataDict
	 * @param bool $pRequired
	 * @param array $pTableOptions
	 * @return void
	 */
	public function registerSchemaTable( string $pPackage, string $pTableName, string $pDataDict, bool $pRequired = false, ?array $pTableOptions = null ): void {
		$pPackage = strtolower( $pPackage ); // lower case for uniformity
		if( !empty( $pTableName ) ) {
			$this->mPackages[$pPackage]['tables'][$pTableName] = $pDataDict;
			if( !empty( $pTableOptions ) ) {
				$this->mPackages[$pPackage]['tables']['options'][$pTableName] = $pTableOptions;
			}
		}
	}

	/**
	 * registerSchemaConstraints
	 *
	 * @param string $pPackage
	 * @param string $pTableName
	 * @param array $pConstraints
	 * @access public
	 * @return void
	 */
	public function registerSchemaConstraints( string $pPackage, string $pTableName, array $pConstraints ): void {
		$pPackage = strtolower( $pPackage);
		if( !empty( $pTableName ) ) {
			$this->mPackages[$pPackage]['constraints'][$pTableName] = $pConstraints;
		}
	}

	/**
	 * registerUserPermissions
	 *
	 * @param string $pPackagedir
	 * @param array $pUserpermissions
	 * @return void
	 */
	public function registerUserPermissions( string $pPackagedir, array $pUserpermissions ): void {
		foreach( $pUserpermissions as $perm ) {
			$this->mPermHash[$perm[0]] = $perm;
			$this->mPermHash[$perm[0]]['sql'] = "INSERT INTO `".BIT_DB_PREFIX."users_permissions` (`perm_name`, `perm_desc`, `perm_level`, `package`) VALUES ('$perm[0]', '$perm[1]', '$perm[2]', '$perm[3]')";
			$this->registerSchemaDefault( $pPackagedir,
				"INSERT INTO `".BIT_DB_PREFIX."users_permissions` (`perm_name`, `perm_desc`, `perm_level`, `package`) VALUES ('$perm[0]', '$perm[1]', '$perm[2]', '$perm[3]')");
		}
	}

	/**
	 * registerConfig
	 *
	 * @param string $pPackagedir
	 * @param array|string $pPreferences
	 * @access public
	 * @return void
	 */
	public function registerConfig( $pPackagedir, $pPreferences ) {
		foreach( $pPreferences as $pref ) {
			$this->registerSchemaDefault( $pPackagedir,
				"INSERT INTO `".BIT_DB_PREFIX."kernel_config`(`package`,`config_name`,`config_value`) VALUES ('$pref[0]', '$pref[1]','$pref[2]')");
		}
	}

	/**
	 * registerPreferences
	 *
	 * @param string $pPackagedir
	 * @param array $pPreferences
	 * @access public
	 * @return void
	 */
	public function registerPreferences( $pPackagedir, $pPreferences ) {
		foreach( $pPreferences as $prefHash ) {
			$this->mPackages[$pPackagedir]['default_prefs'][] = [ 'package' => $prefHash[0], 'name' => $prefHash[1], 'value' => $prefHash[2] ];
		}
	}

	/**
	 * registerModules
	 *
	 * @param array $pModuleHash
	 * @access public
	 * @return void
	 */
	public function registerModules( $pModuleHash ) {
		$this->mInstallModules = array_merge( $this->mInstallModules, $pModuleHash );
	}

	/**
	 * registerContentObjects
	 *
	 * @param string $pPackageName the package name
	 * @param array $pClassesHash [$className => $pathToClassFile]
	 * @access public
	 */
	public function registerContentObjects( $pPackageName, $pClassesHash ) {
		$this->mContentClasses[$pPackageName] = $pClassesHash;
	}

	/**
	 * registerPackageInfo
	 *
	 * @param string $pPackage
	 * @param array $pInfoHash
	 * @access public
	 * @return void
	 */
	public function registerPackageInfo( $pPackage, $pInfoHash ) {
		$pPackage = strtolower( $pPackage ); // lower case for uniformity
		$this->mPackages[$pPackage]['info'] = !empty( $this->mPackages[$pPackage]['info'] )
			? array_merge( $this->mPackages[$pPackage]['info'], $pInfoHash ) : $pInfoHash;

		$this->mPackages[$pPackage]['info']['version'] = $this->getVersion( $pPackage );
		$upgrade = $this->getLatestUpgradeVersion( $pPackage );
		if( !empty( $upgrade ) && version_compare( $upgrade, $this->getVersion( $pPackage ), '>' )) {
			if( $this->mPackages[$pPackage]['installed'] ) {
				$this->mPackages[$pPackage]['info']['upgrade'] = $upgrade;
			} else {
				$this->mPackages[$pPackage]['info']['version'] = $upgrade;
			}
		}
	}

	/**
	 * registerSchemaSequences
	 *
	 * @param string $pPackage
	 * @param array $pSeqHash
	 * @access public
	 * @return void
	 */
	public function registerSchemaSequences( $pPackage, $pSeqHash ) {
		$pPackage = strtolower( $pPackage ); // lower case for uniformity
		$this->mPackages[$pPackage]['sequences'] = $pSeqHash;
	}

	/**
	 * registerSchemaIndexes
	 *
	 * @param string $pPackage
	 * @param array $pIndexHash
	 * @access public
	 * @return void
	 */
	public function registerSchemaIndexes( $pPackage, $pIndexHash ) {
		$pPackage = strtolower( $pPackage ); // lower case for uniformity
		$this->mPackages[$pPackage]['indexes'] = $pIndexHash;
	}

	/**
	 * registerSchemaDefault
	 *
	 * @param string $pPackage
	 * @param string|array $pMixedDefaultSql
	 * @return void
	 */
	public function registerSchemaDefault( string $pPackage, string|array $pMixedDefaultSql ): void {
		$pPackage = strtolower( $pPackage ); // lower case for uniformity
		if( empty( $this->mPackages[$pPackage]['defaults'] ) ) {
			$this->mPackages[$pPackage]['defaults'] = [];
		}
		if( is_array( $pMixedDefaultSql ) ) {
			foreach( $pMixedDefaultSql as $def ) {
				$this->mPackages[$pPackage]['defaults'][] = $def;
			}
		} elseif( is_string( $pMixedDefaultSql ) ) {
			array_push( $this->mPackages[$pPackage]['defaults'], $pMixedDefaultSql );
		}
	}

	/**
	 * storeVersion will store the version number of a given package
	 *
	 * @param string $pPackage Name of package - if not given, bitweaver_version will be stored
	 * @param string $pVersion Version number
	 * @return bool true on success, false on failure
	 */
	public function storeVersion( $pPackage = null, $pVersion = null ): bool {
		global $gBitSystem;
		$ret = false;
		if( !empty( $pVersion ) && $this->validateVersion( $pVersion )) {
			if( empty( $pPackage )) {
				$gBitSystem->storeConfig( "bitweaver_version", $pVersion, 'kernel' );
				$ret = true;
			} elseif( !empty( $gBitSystem->mPackages[$pPackage] )) {
				$gBitSystem->storeConfig( "package_".$pPackage."_version", $pVersion, $pPackage );
				$ret = true;
			}
		}
		return $ret;
	}

	/**
	 * getVersion will fetch the version number of a given package
	 *
	 * @param string $pPackage Name of package - if not given, bitweaver_version will be stored
	 * @param string $pVersion Version number
	 * @return string version number on success
	 */
	public function getVersion( ?string $pPackage = null, $pDefault = '0.0.0' ) {
		global $gBitSystem;
		$config = empty( $pPackage ) ? 'bitweaver_version' : "package_".$pPackage."_version";

		return $gBitSystem->getConfig( $config, $pDefault );
	}

	/**
	 * getLatestUpgradeVersion will fetch the greatest upgrade number for a given package
	 *
	 * @param string $pPackage package we want to fetch the latest version number for
	 * @return string greatest upgrade number for a given package
	 */
	public function getLatestUpgradeVersion( string $pPackage ) {
		$ret = '0.0.0';
		if( !empty( $pPackage )) {
			$dir = constant( strtoupper( $pPackage )."_PKG_PATH" )."admin/upgrades/";
			if( is_dir( $dir ) && $upDir = opendir( $dir )) {
				while( false !== ( $file = readdir( $upDir ))) {
					if( is_file( $dir.$file )) {
						$upVersion = str_replace( ".php", "", $file );
						// we only want to update $ret if the version of the file is greater than the previous one
						if( $this->validateVersion( $upVersion ) && version_compare( $ret, $upVersion, "<" )) {
							$ret = $upVersion;
						}
					}
				}
			}
		}
		return $ret == '0.0.0' ? false : $ret;
	}

	/**
	 * registerPackageVersion Holds the package version
	 *
	 * @param string $pPackage
	 * @param string $pVersion
	 * @return void
	 */
	public function registerPackageVersion( string $pPackage, string $pVersion ): void {
		if( !empty( $pPackage ) && $this->validateVersion( $pVersion )) {
			$pPackage = strtolower( $pPackage );
			$this->mPackages[$pPackage]['version'] = $pVersion;
		}
	}

	/**
	 * validateVersion
	 *
	 * @param string $pVersion
	 * @return bool|int returns 1 if the pattern matches given subject, 0 if it does not, or false on failure
	 */
	public function validateVersion( string $pVersion ): bool|int {
		return preg_match( "/^(\d+\.\d+\.\d+)(-dev|-alpha|-beta|-pl|-RC\d+)?$/", $pVersion );
	}

	/**
	 * registerRequirements
	 *
	 * @param string $pParams
	 * @param array $pReqHash
	 * @return void
	 */
	public function registerRequirements( string $pPackage, array $pReqHash ): void {
		if( !empty( $pPackage ) && $this->verifyRequirements( $pReqHash )) {
			$pPackage = strtolower( $pPackage );
			$this->mRequirements[$pPackage] = $pReqHash;

			// and we display the info
			$this->mPackages[$pPackage]['info']['requirements'] = '';
			foreach( $pReqHash as $req => $version ) {
				//$this->mPackages[$req]['is_requirement'] = true;

				$this->mPackages[$pPackage]['info']['requirements'] .= '<a class="external" href="http://www.bitweaver.org/wiki/'.ucfirst( $req ).'Package">'.ucfirst( $req ).'</a>';
				$max = !empty( $version['max'] ) ? " - ".$version['max'] : '';
				if( $version['min'] != '0.0.0' ) {
					$this->mPackages[$pPackage]['info']['requirements'] .= " (".$version['min'].$max.")";
				}
				$this->mPackages[$pPackage]['info']['requirements'] .= ", ";
			}
			// remove trailing ,
			$this->mPackages[$pPackage]['info']['requirements'] = rtrim( trim( $this->mPackages[$pPackage]['info']['requirements'] ), "," );
		}
	}

	/**
	 * verifyRequirements
	 *
	 * @param array $pReqHash
	 * @access public
	 * @return bool true on success, false on failure
	 */
	public function verifyRequirements( &$pReqHash ) {
		if( !empty( $pReqHash ) && is_array( $pReqHash )) {
			foreach( $pReqHash as $pkg => $versions ) {
				if( empty( $versions['min'] )) {
					$this->mErrors['version_min'] = "You have to provide a minimum version number for the $pkg requirement. If you just want the required package to be present, please use 0.0.0 as minimum version.";
				} elseif( !$this->validateVersion( $versions['min'] )) {
					$this->mErrors['version_min'] = "Please make sure you use a valid minimum version number for the $pkg requirement.";
				} elseif( !empty( $versions['max'] )) {
					if( !$this->validateVersion( $versions['max'] )) {
						$this->mErrors['version_max'] = "Please make sure you use a valid maximum version number for the $pkg requirement.";
					} elseif( version_compare( $versions['min'], $versions['max'], '>=' )) {
						$this->mErrors['version_max'] = "Please make sure the maximum version is greater than the minimum version for the $pkg requirement.";
					}
				}
			}
		} else {
			$this->mErrors['deps'] = "If you want to register requirements, please do so with a valid requirement hash.";
		}

		// since this should only show up when devs are working, we'll simply display the output:
		if( !empty( $this->mErrors )) {
			bt();
		}

		return count( $this->mErrors ) == 0;
	}

	/**
	 * getRequirements
	 *
	 * @param string $pPackage
	 * @access public
	 * @return array of package requirements
	 */
	public function getRequirements( $pPackage ) {
		$ret = [];
		if( !empty( $pPackage )) {
			$pPackage = strtolower( $pPackage );
			if( !empty( $this->mRequirements[$pPackage] )) {
				return $this->mRequirements[$pPackage];
			}
		}
		return $ret;
	}

	/**
	 * calculateRequirements will calculate all requirements and return a hash of the results
	 *
	 * @param boolean $pInstallVersion Use the actual installed version instead of the version that will be in bitweaver after the upgrade
	 * @access public
	 * @return array
	 */
	public function calculateRequirements( $pInstallVersion = false ) {
		$ret = [];
		// first we gather all version information.
		foreach( array_keys( $this->mPackages ) as $package ) {
			if( $this->isPackageInstalled( $package )) {

				// get the latest upgrade version, since this is the version the package will be at after install
				if( $pInstallVersion || !$version = $this->getLatestUpgradeVersion( $package )) {
					$version = $this->getVersion( $package );
				}
				$installed[$package] = $version;

				if( $this->isPackageActive( $package )) {
					if( $deps = $this->getRequirements( $package )) {
						$requirements[$package] = $deps;
					}
					$inactive[$package] = false;
				} else {
					$inactive[$package] = true;
				}
			}
		}

		if( !empty( $requirements )) {
			foreach( $requirements as $package => $deps ) {
				foreach( $deps as $depPackage => $depVersion ) {
					$hash = [
						'package'          => $package,
						'package_version'  => $installed[$package],
						'requires'         => $depPackage,
						'required_version' => $depVersion,
					];

					if( !empty( $installed[$depPackage] )) {
						$hash['version']['available'] = $installed[$depPackage];
					}

					if( empty( $installed[$depPackage] )) {
						$hash['result'] = 'missing';
					} elseif( version_compare( $depVersion['min'], $installed[$depPackage], '>' )) {
						$hash['result'] = 'min_dep';
					} elseif( !empty( $depVersion['max'] ) && version_compare( $depVersion['max'], $installed[$depPackage], '<' )) {
						$hash['result'] = 'max_dep';
					} elseif( isset( $inactive[$depPackage] ) && $inactive[$depPackage] ) {
						$hash['result'] = 'inactive';
					} else {
						$hash['result'] = 'ok';
					}

					$ret[] = $hash;
				}
			}
		}

		return $ret;
	}

	/**
	 * drawRequirementsGraph Will draw a requirement graph if PEAR::Image_GraphViz is installed
	 *
	 * @param boolean $pInstallVersion Use the actual installed version instead of the version that will be in bitweaver after the upgrade
	 * @param string $pFormat dot output format
	 * @param string $pCommand dot or neato
	 * @access public
	 * @return string|bool true on success, false on failure
	 */
	public function drawRequirementsGraph( $pInstallVersion = false, $pFormat = 'png', $pCommand = 'dot' ) {
		global $gBitSmarty, $gBitThemes;

		// only do this if we can load PEAR GraphViz interface
		if( @include_once UTIL_PKG_INCLUDE_PATH.'pear/Image/GraphViz.php' ) {
			ksort( $this->mPackages );
			$deps = $this->calculateRequirements( $pInstallVersion );
			$delKeys = $matches = [];

			// crazy manipulation of hash to remove duplicate version matches.
			// we do this that we can use double headed arrows in the graph below.
			foreach( $deps as $key => $req ) {
				foreach( $deps as $k => $d ) {
					if( $req['requires'] == $d['package'] && $req['package'] == $d['requires'] && $req['result'] == 'ok' && $d['result'] == 'ok' ) {
						$deps[$key]['dir'] = 'both';
						$matches[$key] = $k;
					}
				}
			}

			// get duplicates
			foreach( $matches as $key => $match ) {
				unset( $delKeys[$match] );
				$delKeys[$key] = $match;
			}

			// remove dupes from hash
			foreach( $delKeys as $key ) {
				unset( $deps[$key] );
			}

			// start drawing stuff
			$graph = new \Image_GraphViz( true, $gBitThemes->getGraphvizGraphAttributes(), 'Requirements', true );

			$fromattributes = $toattributes = $gBitThemes->getGraphvizNodeAttributes();

			foreach( $deps as $node ) {
				//$fromNode = ucfirst( $node['package'] )."\n".$node['package_version'];
				//$toNode   = ucfirst( $node['requires'] )."\n".$node['required_version']['min'];

				$fromNode = ucfirst( $node['package'] );
				$toNode   = ucfirst( $node['requires'] );

				switch( $node['result'] ) {
				case 'max_dep':
					$edgecolor = 'chocolate3';
					$label     = 'Maximum version\nexceeded';
					$toNode   .= "\n".$node['required_version']['min']." - ".$node['required_version']['max'];
					$toattributes['fillcolor'] = 'khaki';
					break;
				case 'min_dep':
					$edgecolor = 'crimson';
					$label     = 'Minimum version\nnot met';
					$toNode   .= "\n".$node['required_version']['min'];
					if( !empty( $node['required_version']['max'] )) {
						$toNode .= " - ".$node['required_version']['max'];
					}
					$toattributes['fillcolor'] = 'pink';
					break;
				case 'missing':
					$edgecolor = 'crimson';
					$label     = 'Not installed\nor activated';
					$toNode   .= "\n".$node['required_version']['min'];
					if( !empty( $node['required_version']['max'] )) {
						$toNode .= " - ".$node['required_version']['max'];
					}
					$toattributes['fillcolor'] = 'pink';
					break;
				default:
					$edgecolor = '';
					$label     = '';
					$toattributes['fillcolor'] = 'white';
					break;
				}

				$fromattributes['URL'] = "http://www.bitweaver.org/wiki/".ucfirst( $node['package'] )."Package";
				$graph->addNode( $fromNode, $fromattributes );

				$toattributes['URL'] = "http://www.bitweaver.org/wiki/".ucfirst( $node['requires'] )."Package";
				$graph->addNode( $toNode, $toattributes );

				$graph->addEdge(
					[ $fromNode => $toNode ],
					$gBitThemes->getGraphvizEdgeAttributes( [
						'dir'       => ( !empty( $node['dir'] ) ? $node['dir'] : '' ),
						'color'     => $edgecolor,
						'fontcolor' => $edgecolor,
						'label'     => $label,
					])
				);
			}

			if( preg_match( "#(png|gif|jpe?g|bmp|svg|tif)#i", $pFormat )) {
				$graph->image( $pFormat, $pCommand );
			} else {
				return $graph->fetch( $pFormat, $pCommand );
			}
		} 
		return false;
	}

	/**
	 * verifyInstalledPackages scan all available packages
	 *
	 * @param string $ pScanFile file to be looked for
	 * @return array 
	 * @access public
	 */
	public function verifyInstalledPackages( $pSelect='installed' ) {
		global $gBitDbType;
		#load in any admin/schema_inc.php files that exist for each package
		$this->scanPackages( 'admin/schema_inc.php', true, $pSelect, false );
		$ret = [];

		if( $this->isDatabaseValid() ) {
			if( strlen( BIT_DB_PREFIX ) > 0 ) {
				$lastQuote = strrpos( BIT_DB_PREFIX, '`' );
				if( $lastQuote != false ) {
					$lastQuote++;
				}
				$prefix = substr( BIT_DB_PREFIX, $lastQuote );
			} else {
				$prefix = '';
			}

			$showTables = $prefix ? $prefix.'%' : false;
			$unusedTables = [];
			if( $dbTables = $this->mDb->MetaTables( 'TABLES', false, $showTables ) ) {
				// make a copy that we can keep track of what tables have been used
				$unusedTables = $dbTables;
				foreach( array_keys( $this->mPackages ) as $package ) {
					// Default to true, &= will false out
					$this->mPackages[$package]['installed'] = true;
					if( !empty( $this->mPackages[$package]['tables'] ) ) {
						$this->mPackages[$package]['db_tables_found'] = true;
						foreach( array_keys( $this->mPackages[$package]['tables'] ) as $table ) {
							// painful hardcoded exception for bitcommerce
							$fullTable = $package == 'bitcommerce' ? $table : $prefix.$table;
							$tablePresent = in_array( $fullTable, $dbTables );
							if( $tablePresent ) {
								$ret['present'][$package][] = $table;
							} else {
								$ret['missing'][$package][] = $table;
								// This is a crude but highly effective means of blurting out a very bad situation when an installed package is missing a table
								if( !$this->isLive() && $this->isPackageActive( $package ) ) {
// This needs hiding during install so disabled for now
//								 	vd( "Table Missing => $package : $table" );
								}
							}

							// lets also return the tables that are not in use by bitweaver
							// this is useful when we want to remove old tables or upgrade tables
							if(( $key = array_search( $fullTable, $dbTables )) !== false ) {
								unset( $unusedTables[$key] );
							}

							$this->mPackages[$package]['installed'] &= $tablePresent;
							$this->mPackages[$package]['db_tables_found'] &= $tablePresent;
						}
					} else {
						$this->mPackages[$package]['db_tables_found'] = false;
						if( !$this->getConfig( 'package_'.strtolower( $package ) ) ){
							$this->mPackages[$package]['installed'] = false;
						}
					}

					$this->mPackages[$package]['active_switch'] = $this->getConfig( 'package_'.strtolower( $package ) );
					if( !empty( $this->mPackages[$package]['required'] ) && $this->mPackages[$package]['active_switch'] != 'y' ) {
						// we have a disabled required package. turn it back on!
						$this->storeConfig( 'package_' . $package, 'y', $package );
						$this->mPackages[$package]['active_switch'] = $this->getConfig( 'package_' . $package );
					} elseif( !empty( $this->mPackages[$package]['required'] ) && $this->mPackages[$package]['installed'] &&  $this->getConfig( 'package_'.$package ) != 'i' &&  $this->getConfig( 'package_'.$package ) != 'y' ) {
						$this->storeConfig( 'package_' . $package, 'i', $package );
					} elseif( !empty( $this->mPackages[$package]['installed'] ) && !$this->isFeatureActive( 'package_'.strtolower( $package ) ) ) {
						// set package to i if it is installed but not isFeatureActive (common when re-installing packages)
						$this->storeConfig( 'package_' . $package, 'i', $package );
						if( $version = $this->getLatestUpgradeVersion( $package ) ) {
							$this->storeVersion( $package, $version );
							$this->registerPackageVersion( $package, $version );
							$this->mPackages[$package]['info']['version'] = $version;
							unset( $this->mPackages[$package]['info']['upgrade'] );
						}
					}
				}
			}
			$ret['unused'] = $unusedTables;
		}
		return $ret;
	}
	// }}}

	// {{{=========================== Date and time methods ==============================
	/**
	 * Retrieve a current UTC timestamp
	 * Simple map to BitDate object allowing tidy display elsewhere
	 */
	public function getUTCTime() {
		return	$this->mServerTimestamp->getUTCTime();
	}

	/**
	 * Retrieve a current UTC ISO timestamp
	 * Simple map to BitDate object allowing tidy display elsewhere
	 */
	public function getUTCTimestamp() {
		return	$this->mServerTimestamp->getUTCTimestamp();
	}

	/**
	 * Retrieves the user's preferred offset for displaying dates.
	 */
	public function get_display_offset( $pUser = false ) {
		return $this->mServerTimestamp->get_display_offset( $pUser );
	}

	/**
	 * Retrieves the user's preferred long date format for displaying dates.
	 */
	public function get_long_date_format() {
		static $site_long_date_format = false;

		if( !$site_long_date_format ) {
			$site_long_date_format = $this->getConfig( 'site_long_date_format', '%A, %B %d, %Y' );
		}

		return $site_long_date_format;
	}

	/**
	 * Retrieves the user's preferred short date format for displaying dates.
	 */
	public function get_short_date_format() {
		static $site_short_date_format = false;

		if( !$site_short_date_format ) {
			$site_short_date_format = $this->getConfig( 'site_short_date_format', '%d %b %Y' );
		}

		return $site_short_date_format;
	}

	/**
	 * Retrieves the user's preferred long time format for displaying dates.
	 */
	public function get_long_time_format() {
		static $site_long_time_format = false;

		if( !$site_long_time_format ) {
			$site_long_time_format = $this->getConfig( 'site_long_time_format', '%H:%M:%S %Z' );
		}

		return $site_long_time_format;
	}

	/**
	 * Retrieves the user's preferred short time format for displaying dates.
	 */
	public function get_short_time_format() {
		static $site_short_time_format = false;

		if( !$site_short_time_format ) {
			$site_short_time_format = $this->getConfig( 'site_short_time_format', '%H:%M %Z' );
		}

		return $site_short_time_format;
	}

	/**
	 * Retrieves the user's preferred long date/time format for displaying dates.
	 */
	public function get_long_datetime_format() {
		static $long_datetime_format = false;

		if( !$long_datetime_format ) {
			$long_datetime_format = $this->getConfig( 'site_long_datetime_format', '%A %d of %B, %Y (%H:%M:%S %Z)' );
		}

		return $long_datetime_format;
	}

	/**
	 * Retrieves the user's preferred short date/time format for displaying dates.
	 */
	public function get_short_datetime_format() {
		static $short_datetime_format = false;

		if( !$short_datetime_format ) {
			$short_datetime_format = $this->getConfig( 'site_short_datetime_format', '%d %b %Y (%H:%M %Z)' );
		}

		return $short_datetime_format;
	}

	/*
	 * Only used in rang_lib.php which needs tidying up to use smarty templates
	 */
	public function get_long_datetime( $pTimestamp, $pUser = false ) {
		return $this->mServerTimestamp->strftime( $this->get_long_datetime_format(), $pTimestamp, $pUser );
	}
	// }}}
	/**
	 * getBitVersion will fetch the version of bitweaver as set in kernel/config_defaults_inc.php
	 *
	 * @param boolean $pIncludeLevel Return bitweaver version including BIT_LEVEL
	 * @return string bitweaver version set in kernel/config_defaults_inc.php
	 */
	public function getBitVersion( $pIncludeLevel = true ) {
		$ret = BIT_MAJOR_VERSION.".".BIT_MINOR_VERSION.".".BIT_SUB_VERSION;
		if( $pIncludeLevel && defined( BIT_LEVEL ) && BIT_LEVEL != '' ) {
			$ret .= '-'.BIT_LEVEL;
		}
		return $ret;
	}

	/**
	 * checkBitVersion Check for new version of bitweaver
	 *
	 * @return array an array with information on bitweaver version
	 */
	public function checkBitVersion() {
		$local = $this->getBitVersion( false );
		$ret['local'] = $local;
		$ret['compare'] = 0;
		$ret['release'] = 0;

		$error['number'] = 0;
		$error['string'] = $data = '';

// http://www.bitweaver.org/bitversion.txt is no longer available  
		// cache the bitversion.txt file locally and update only once a day
		// if you don't have a connection to bitweaver.org, you can set a cronjob to 'touch' this file once a day to avoid waiting for a timeout.
/*		if( !is_file( TEMP_PKG_PATH.'bitversion.txt' ) || ( time() - filemtime( TEMP_PKG_PATH.'bitversion.txt' )) > 86400 ) {
			if( $h = fopen( TEMP_PKG_PATH.'bitversion.txt', 'w' )) {
				$data = KernelTools::bit_http_request( 'http://www.bitweaver.org/bitversion.txt' );
				if( !preg_match( "/not found/i", $data )) {
					fwrite( $h, $data );
					fclose( $h );
				}
			}
		}
*/
		if( is_readable( TEMP_PKG_PATH.'bitversion.txt' ) ) {
			$h = fopen( TEMP_PKG_PATH.'bitversion.txt', 'r' );
			if( isset( $h ) ) {
				$data = fread( $h, 1024 );
				fclose( $h );
			}

			// nuke all lines that don't just contain a version number
			$lines = explode( "\n", $data );
			foreach( $lines as $line ) {
				if( preg_match( "/^\d+\.\d+\.\d+$/", $line ) ) {
					$versions[] = $line;
				}
			}

			if( !empty( $data ) && !empty( $versions ) && preg_match( "/\d+\.\d+\.\d+/", $versions[0] ) ) {
				sort( $versions );
				foreach( $versions as $version ) {
					if( preg_match( "/^".BIT_MAJOR_VERSION."\./", $version ) ) {
						$ret['compare'] = version_compare( $local, $version );
						$ret['upgrade'] = $version;
						$ret['page'] = preg_replace( "/\.\d+$/", "", $version );
					}
				}
				// check if there have been any major releases
				$release = explode( '.', array_pop( $versions ) );
				if( $release[0] > BIT_MAJOR_VERSION ) {
					$ret['release'] = implode( '.', $release );
					$ret['page'] = $release[0].'.'.$release[1];
				} elseif( $release[0] < BIT_MAJOR_VERSION ) {
					$ret['compare'] = version_compare( $local, $version );
					$ret['upgrade'] = $version;
				}
			} else {
				$error['number'] = 1;
				$error['string'] = KernelTools::tra( 'No version information available. Check your connection to bitweaver.org' );
			}
		}
		// append any release level
		$ret['local'] .= ' '.BIT_LEVEL;
		$ret['error'] = $error;
		return $ret;
	}

	// should be moved somewhere else. unbreaking things for now - 25-JUN-2005 - spiderr
	// \TODO remove html hardcoded in diff2
	public function diff2( $page1, $page2 ) {
		$page1 = mb_split( "\n", $page1 );
		$page2 = mb_split( "\n", $page2 );
		$z = new \WikiDiff( $page1, $page2 );
		if( $z->isEmpty() ) {
			$html = '<hr /><br />['.KernelTools::tra("Versions are identical").']<br /><br />';
		} else {
			//$fmt = new WikiDiffFormatter;
			$fmt = new \WikiUnifiedDiffFormatter;
			$html = $fmt->format( $z, $page1 );
		}
		return $html;
	}

	/**
	 * getIncludeFiles will get a set of available files with a given filename
	 *
	 * @param array $pPhpFile name of php file
	 * @param array $pTplFile name of tpl file
	 * @return array of includable files
	 */
	public function getIncludeFiles( $pPhpFile = null, $pTplFile = null ) {
		$ret = [];
		global $gBitSystem;
		foreach( $gBitSystem->mPackages as $package ) {
			if( $gBitSystem->isPackageActive( $package['name'] )) {
				if( !empty( $pPhpFile )) {
					$php_file = constant( strtoupper( $package['name'] ).'_PKG_INCLUDE_PATH' ).$pPhpFile;
					if( is_file( $php_file ))  {
						$ret[$package['name']]['php'] = $php_file;
					}
				}

				if( !empty( $pTplFile )) {
					$tpl_file = $package['path'].'templates/'.$pTplFile;
					if( is_readable( $tpl_file )) {
						$ret[$package['name']]['tpl'] = 'bitpackage:'.$package['name'].'/'.$pTplFile;
					}
				}
			}
		}
		return $ret;
	}
}

/* Function for sorting AppMenu by menu_position */
function bit_system_menu_sort( $a, $b ) {
	$pa = empty( $a['menu_position'] ) ? 0 : $a['menu_position'];
	$pb = empty( $b['menu_position'] ) ? 0 : $b['menu_position'];

	if( $pa == 0 && $pb == 0 ) {
		return strcmp( $b['menu_title'], $a['menu_title'] );
	}
	return $pa - $pb;
}