enanocms /includes/sessions.php

Language PHP Lines 4736
MD5 Hash 496688a8a19ea62f9a4bfaaaf0aec9fa Estimated Cost $89,769 (why?)
Repository https://code.google.com/p/enanocms/ View Raw File
   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
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
<?php

/*
 * Enano - an open-source CMS capable of wiki functions, Drupal-like sidebar blocks, and everything in between
 * Copyright (C) 2006-2009 Dan Fuhry
 * sessions.php - everything related to security and user management
 *
 * This program is Free Software; you can redistribute and/or modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied
 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for details.
 */
 
/**
 * Anything and everything related to security and user management. This includes AES encryption, which is illegal in some countries.
 * Documenting the API was not easy - I hope you folks enjoy it.
 * @package Enano
 * @subpackage Session manager
 * @category security, user management, logins, etc.
 */

class sessionManager {
	
	# Variables
	
	/**
	 * Whether we're logged in or not
	 * @var bool
	 */
	 
	var $user_logged_in = false;
	
	/**
	 * Our current low-privilege session key
	 * @var string
	 */
	
	var $sid;
	
	/**
	 * Username of currently logged-in user, or IP address if not logged in
	 * @var string
	 */
	
	var $username;
	
	/**
	 * User ID of currently logged-in user, or 1 if not logged in
	 * @var int
	 */
	
	var $user_id = 1;
	
	/**
	 * Real name of currently logged-in user, or blank if not logged in
	 * @var string
	 */
	
	var $real_name;
	
	/**
	 * E-mail address of currently logged-in user, or blank if not logged in
	 * @var string
	 */
	
	var $email;
	
	/**
	 * List of "extra" user information fields (IM handles, etc.)
	 * @var array (associative)
	 */
	
	var $user_extra;
	
	/**
	 * User level of current user
	 * USER_LEVEL_GUEST: guest
	 * USER_LEVEL_MEMBER: regular user
	 * USER_LEVEL_CHPREF: default - pseudo-level that allows changing password and e-mail address (requires re-authentication)
	 * USER_LEVEL_MOD: moderator
	 * USER_LEVEL_ADMIN: administrator
	 * @var int
	 */
	
	var $user_level;
	
	/**
	 * High-privilege session key
	 * @var string or false if not running on high-level authentication
	 */
	
	var $sid_super;
	
	/**
	 * The user's theme preference, defaults to $template->default_theme
	 * @var string
	 */
	
	var $theme;
	
	/**
	 * The user's style preference, or style auto-detected based on theme if not logged in
	 * @var string
	 */
	
	var $style;
	
	/**
	 * Signature of current user - appended to comments, etc.
	 * @var string
	 */
	
	var $signature;
	
	/**
	 * UNIX timestamp of when we were registered, or 0 if not logged in
	 * @var int
	 */
	
	var $reg_time;
	
	/**
	 * The number of unread private messages this user has.
	 * @var int
	 */
	
	var $unread_pms = 0;
	
	/**
	 * AES key used to encrypt passwords and session key info.
	 * @var string
	 * @access private
	 */
	 
	protected $private_key;
	
	/**
	 * Regex that defines a valid username, minus the ^ and $, these are added later
	 * @var string
	 */
	 
	var $valid_username = '([^<>&\?\'"%\n\r\t\a\/]+)';
	
	/**
	 * The current user's user title. Defaults to NULL.
	 * @var string
	 */
	
	var $user_title = null;
	 
	/**
	 * What we're allowed to do as far as permissions go. This changes based on the value of the "auth" URI param.
	 * @var string
	 */
	 
	var $auth_level = 1;
	
	/**
	 * Preference for date formatting
	 * @var string
	 */
	
	var $date_format = DATE_4;
	
	/**
	 * Preference for time formatting
	 * @var string
	 */
	
	var $time_format = TIME_24_NS;
	
	/**
	 * State variable to track if a session timed out
	 * @var bool
	 */
	
	var $sw_timed_out = false;
	
	/**
	 * Token appended to some important forms to prevent CSRF.
	 * @var string
	 */
	
	var $csrf_token = false;
	
	/**
	 * Password change disabled, for auth plugins
	 * @var bool
	 */
	
	var $password_change_disabled = false;
	
	/**
	 * Password change page URL + title, for auth plugins
	 * @var array
	 */
	
	var $password_change_dest = array('url' => '', 'title' => '');
	
	/**
	 * Switch to track if we're started or not.
	 * @access private
	 * @var bool
	 */
	 
	var $started = false;
	
	/**
	 * Switch to control compatibility mode (for older Enano websites being upgraded)
	 * @access private
	 * @var bool
	 */
	 
	var $compat = false;
	
	/**
	 * Our list of permission types.
	 * @access private
	 * @var array
	 */
	 
	var $acl_types = Array();
	
	/**
	 * The list of descriptions for the permission types
	 * @var array
	 */
	 
	var $acl_descs = Array();
	
	/**
	 * A list of dependencies for ACL types.
	 * @var array
	 */
	 
	var $acl_deps = Array();
	
	/**
	 * Our tell-all list of permissions. Do not even try to change this.
	 * @access private
	 * @var array
	 */
	 
	var $perms = Array();
	
	/**
	 * A cache variable - saved after sitewide permissions are checked but before page-specific permissions.
	 * @var array
	 * @access private
	 */
	
	var $acl_base_cache = Array();
	
	/**
	 * Stores the scope information for ACL types.
	 * @var array
	 * @access private
	 */
	 
	var $acl_scope = Array();
	
	/**
	 * Array to track which default permissions are being used
	 * @var array
	 * @access private
	 */
	 
	var $acl_defaults_used = Array();
	
	/**
	 * Array to track group membership.
	 * @var array
	 */
	 
	var $groups = Array();
	
	/**
	 * Associative array to track group modship.
	 * @var array
	 */
	 
	var $group_mod = Array();
	
	/**
	 * A constant array of user-level-to-rank default associations.
	 * @var array
	 */
	
	var $level_rank_table = array(
			USER_LEVEL_ADMIN  => RANK_ID_ADMIN,
			USER_LEVEL_MOD    => RANK_ID_MOD,
			USER_LEVEL_MEMBER => RANK_ID_MEMBER,
			USER_LEVEL_CHPREF => RANK_ID_MEMBER,
			USER_LEVEL_GUEST  => RANK_ID_GUEST
		);
	
	/**
	 * A constant array that maps precedence constants to language strings
	 * @var array
	 */
	
	var $acl_inherit_lang_table = array(
			ACL_INHERIT_ENANO_DEFAULT   => 'acl_inherit_enano_default',
			ACL_INHERIT_GLOBAL_EVERYONE => 'acl_inherit_global_everyone',
			ACL_INHERIT_GLOBAL_GROUP    => 'acl_inherit_global_group',
			ACL_INHERIT_GLOBAL_USER     => 'acl_inherit_global_user',
			ACL_INHERIT_PG_EVERYONE     => 'acl_inherit_pg_everyone',
			ACL_INHERIT_PG_GROUP        => 'acl_inherit_pg_group',
			ACL_INHERIT_PG_USER         => 'acl_inherit_pg_user',
			ACL_INHERIT_LOCAL_EVERYONE  => 'acl_inherit_local_everyone',
			ACL_INHERIT_LOCAL_GROUP     => 'acl_inherit_local_group',
			ACL_INHERIT_LOCAL_USER      => 'acl_inherit_local_user'
		);
	
	# Basic functions
	 
	/**
	 * Constructor.
	 */
	 
	function __construct()
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		
		if ( defined('IN_ENANO_INSTALL') && !defined('IN_ENANO_UPGRADE') )
		{
			@include(ENANO_ROOT.'/config.new.php');
		}
		else
		{
			@include(ENANO_ROOT.'/config.php');
		}
		
		unset($dbhost, $dbname, $dbuser, $dbpasswd);
		if(isset($crypto_key))
		{
			$this->private_key = $crypto_key;
			$this->private_key = hexdecode($this->private_key);
		}
		else
		{
			if(is_writable(ENANO_ROOT.'/config.php'))
			{
				// Generate and stash a private key
				// This should only happen during an automated silent gradual migration to the new encryption platform.
				$aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
				$this->private_key = $aes->gen_readymade_key();
				
				$config = file_get_contents(ENANO_ROOT.'/config.php');
				if(!$config)
				{
					die('$session->__construct(): can\'t get the contents of config.php');
				}
				
				$config = str_replace("?>", "\$crypto_key = '{$this->private_key}';\n?>", $config);
				// And while we're at it...
				$config = str_replace('MIDGET_INSTALLED', 'ENANO_INSTALLED', $config);
				$fh = @fopen(ENANO_ROOT.'/config.php', 'w');
				if ( !$fh ) 
				{
					die('$session->__construct(): Couldn\'t open config file for writing to store the private key, I tried to avoid something like this...');
				}
				
				fwrite($fh, $config);
				fclose($fh);
			}
			else
			{
				die_semicritical('Crypto error', '<p>No private key was found in the config file, and we can\'t generate one because we don\'t have write access to the config file. Please CHMOD config.php to 666 or 777 and reload this page.</p>');
			}
		}
		// Check for compatibility mode
		if(defined('IN_ENANO_INSTALL'))
		{
			$q = $db->sql_query('SELECT old_encryption FROM '.table_prefix.'users LIMIT 1;');
			if(!$q)
			{
				$error = mysql_error();
				if(strstr($error, "Unknown column 'old_encryption'"))
					$this->compat = true;
				else
					$db->_die('This should never happen and is a bug - the only error that was supposed to happen here didn\'t happen. (sessions.php in constructor, during compat mode check)');
			}
			$db->free_result();
		}
	}
	
	/**
	 * PHP 4 compatible constructor. Deprecated in 1.1.x.
	 */
	 
	/*
	function sessionManager()
	{
		$this->__construct();
	}
	*/
	
	/**
	 * Wrapper function to sanitize strings for MySQL and HTML
	 * @param string $text The text to sanitize
	 * @return string
	 */
	
	function prepare_text($text)
	{
		global $db;
		return $db->escape(htmlspecialchars($text));
	}
	
	/**
	 * Makes a SQL query and handles error checking
	 * @param string $query The SQL query to make
	 * @return resource
	 */
	
	function sql($query)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		$result = $db->sql_query($query);
		if(!$result)
		{
			$db->_die('The error seems to have occurred somewhere in the session management code.');
		}
		return $result;
	}
	
	/**
	 * Returns true if we're currently on a page that shouldn't be blocked even if we have an inactive or banned account
	 * @param bool strict - if true, whitelist of pages is even stricter (Login, Logout and CSS only). if false (default), admin access is allowed, assuming other factors allow it
	 * @return bool
	 */
	
	function on_critical_page($strict = false)
	{
		global $urlname;
		list($page_id, $namespace) = RenderMan::strToPageID($urlname);
		list($page_id) = explode('/', $page_id);
		
		if ( $strict )
		{
			return $namespace == 'Special' && in_array($page_id, array('CSS', 'Login', 'Logout', 'LangExportJSON', 'ActivateAccount'));
		}
		else
		{
			return $namespace == 'Admin' || ($namespace == 'Special' && in_array($page_id, array('CSS', 'Login', 'Logout', 'Administration', 'LangExportJSON', 'ActivateAccount')));
		}
	}
	
	# Session restoration and permissions
	
	/**
	 * Initializes the basic state of things, including most user prefs, login data, cookie stuff
	 */
	
	function start()
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		global $lang;
		global $timezone;
		if($this->started) return;
		$this->started = true;
		$user = false;
		if ( isset($_COOKIE['sid']) )
		{
			if ( $this->compat )
			{
				$userdata = $this->compat_validate_session($_COOKIE['sid']);
			}
			else
			{
				$userdata = $this->validate_session($_COOKIE['sid']);
			}
			if ( is_array($userdata) )
			{
				$this->sid = $_COOKIE['sid'];
				$this->user_logged_in = true;
				$this->user_id =       intval($userdata['user_id']);
				$this->username =      $userdata['username'];
				$this->user_level =    intval($userdata['user_level']);
				$this->real_name =     $userdata['real_name'];
				$this->email =         $userdata['email'];
				$this->unread_pms =    $userdata['num_pms'];
				$this->user_title =    ( isset($userdata['user_title']) ) ? $userdata['user_title'] : null;
				if(!$this->compat)
				{
					$this->theme =         $userdata['theme'];
					$this->style =         $userdata['style'];
					$this->signature =     $userdata['signature'];
					$this->reg_time =      $userdata['reg_time'];
				}
				$this->auth_level =    USER_LEVEL_MEMBER;
				// generate an anti-CSRF token
				$this->csrf_token =    sha1($this->username . $this->sid . $this->user_id);
				if(!isset($template->named_theme_list[$this->theme]))
				{
					if($this->compat || !is_object($template))
					{
						$this->theme = 'oxygen';
						$this->style = 'bleu';
					}
					else
					{
						$this->theme = $template->default_theme;
						$this->style = $template->default_style;
					}
				}
				$user = true;
				
				// set timezone params
				$GLOBALS['timezone'] = $userdata['user_timezone'];
				$GLOBALS['dst_params'] = explode(';', $userdata['user_dst']);
				foreach ( $GLOBALS['dst_params'] as &$parm )
				{
					if ( substr($parm, -1) != 'd' )
						$parm = intval($parm);
				}
				
				// Set language
				if ( !defined('ENANO_ALLOW_LOAD_NOLANG') )
				{
					$lang_id = intval($userdata['user_lang']);
					$lang = new Language($lang_id);
					@setlocale(LC_ALL, $lang->lang_code);
				}
				
				if(isset($_REQUEST['auth']) && !$this->sid_super)
				{
					// Now he thinks he's a moderator. Or maybe even an administrator. Let's find out if he's telling the truth.
					if($this->compat)
					{
						$key = $_REQUEST['auth'];
						$super = $this->compat_validate_session($key);
					}
					else
					{
						$key = $_REQUEST['auth'];
						if ( !empty($key) && ( strlen($key) / 2 ) % 4 == 0 )
						{
							$super = $this->validate_session($key);
						}
					}
					if(is_array(@$super))
					{
						$this->auth_level = intval($super['auth_level']);
						$this->sid_super = $_REQUEST['auth'];
					}
				}
			}
		}
		if(!$user)
		{
			//exit;
			$this->register_guest_session();
		}
		if(!$this->compat)
		{
			// init groups
			$q = $this->sql('SELECT g.group_name,g.group_id,m.is_mod FROM '.table_prefix.'groups AS g' . "\n"
				. '  LEFT JOIN '.table_prefix.'group_members AS m' . "\n"
				. '    ON g.group_id=m.group_id' . "\n"
				. '  WHERE ( m.user_id='.$this->user_id.'' . "\n" 
				. '    OR g.group_name=\'Everyone\')' . "\n"
				. '    ' . ( /* quick hack for upgrade compatibility reasons */ enano_version() == '1.0RC1' ? '' : 'AND ( m.pending != 1 OR m.pending IS NULL )' ) . '' . "\n"
				. '  ORDER BY group_id ASC;'); // The ORDER BY is to make sure "Everyone" comes first so the permissions can be overridden
			if($row = $db->fetchrow())
			{
				do {
					$this->groups[$row['group_id']] = $row['group_name'];
					$this->group_mod[$row['group_id']] = ( intval($row['is_mod']) == 1 );
				} while($row = $db->fetchrow());
			}
			else
			{
				die('No group info');
			}
			profiler_log('Fetched group memberships');
		}
		
		// make sure we aren't banned
		$this->check_banlist();
		
		// make sure the account is active
		if ( !$this->compat && $this->user_logged_in && $userdata['account_active'] < 1 && !$this->on_critical_page() )
		{
			$this->show_inactive_error($userdata);
		}
		
		// Printable page view? Probably the wrong place to control
		// it but $template is pretty dumb, it will just about always
		// do what you ask it to do, which isn't always what we want
		if ( isset ( $_GET['printable'] ) )
		{
			$this->theme = 'printable';
			$this->style = 'default';
		}
		
		// setup theme ACLs
		$template->process_theme_acls();
		
		profiler_log('Sessions started. Banlist and theme ACLs initialized');
	}
	
	# Logins
	
	/**
	 * Attempts to perform a login using crypto functions
	 * @param string $username The username
	 * @param string $aes_data The encrypted password, hex-encoded
	 * @param string $aes_key The MD5 hash of the encryption key, hex-encoded
	 * @param string $challenge The 256-bit MD5 challenge string - first 128 bits should be the hash, the last 128 should be the challenge salt
	 * @param int $level The privilege level we're authenticating for, defaults to 0
	 * @param string $captcha_hash Optional. If we're locked out and the lockout policy is captcha, this should be the identifier for the code.
	 * @param string $captcha_code Optional. If we're locked out and the lockout policy is captcha, this should be the code the user entered.
	 * @param bool $remember Optional. If true, remembers the session for X days. Otherwise, assigns a short session. Defaults to false.
	 * @param bool $lookup_key Optional. If true (default) this queries the database for the "real" encryption key. Else, uses what is given.
	 * @return string 'success' on success, or error string on failure
	 */
	 
	function login_with_crypto($username, $aes_data, $aes_key_id, $challenge, $level = USER_LEVEL_MEMBER, $captcha_hash = false, $captcha_code = false, $remember = false, $lookup_key = true)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		
		// Instanciate the Rijndael encryption object
		$aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
		
		// Fetch our decryption key
		
		if ( $lookup_key )
		{
			$aes_key = $this->fetch_public_key($aes_key_id);
			if ( !$aes_key )
			{
				// It could be that our key cache is full. If it seems larger than 65KB, clear it
				if ( strlen(getConfig('login_key_cache')) > 65000 )
				{
					setConfig('login_key_cache', '');
					return array(
						'success' => false,
						'error' => 'key_not_found_cleared',
						);
				}
				return array(
					'success' => false,
					'error' => 'key_not_found'
					);
			}
		}
		else
		{
			$aes_key =& $aes_key_id;
		}
		
		// Convert the key to a binary string
		$bin_key = hexdecode($aes_key);
		
		if(strlen($bin_key) != AES_BITS / 8)
			return array(
				'success' => false,
				'error' => 'key_wrong_length'
				);
		
		// Decrypt our password
		$password = $aes->decrypt($aes_data, $bin_key, ENC_HEX);
		
		// Let the LoginAPI do the rest.
		return $this->login_without_crypto($username, $password, false, $level, $captcha_hash, $captcha_code, $remember);
	}
	
	/**
	 * Attempts to login without using crypto stuff, mainly for use when the other side doesn't like Javascript
	 * This method of authentication is inherently insecure, there's really nothing we can do about it except hope and pray that everyone moves to Firefox
	 * Technically it still uses crypto, but it only decrypts the password already stored, which is (obviously) required for authentication
	 * @param string $username The username
	 * @param string $password The password -OR- the MD5 hash of the password if $already_md5ed is true
	 * @param bool $already_md5ed This should be set to true if $password is an MD5 hash, and should be false if it's plaintext. Defaults to false.
	 * @param int $level The privilege level we're authenticating for, defaults to 0
	 * @param bool $remember Optional. If true, remembers the session for X days. Otherwise, assigns a short session. Defaults to false.
	 */
	
	function login_without_crypto($username, $password, $already_md5ed = false, $level = USER_LEVEL_MEMBER, $remember = false)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		
		if ( $already_md5ed )
		{
			// No longer supported
			return array(
					'mode' => 'error',
					'error' => '$already_md5ed is no longer supported (set this parameter to false and make sure the password you send to $session->login_without_crypto() is not hashed)'
				);
		}
		
		// Replace underscores with spaces in username
		// (Added in 1.0.2)
		$username = str_replace('_', ' ', $username);
		
		// Perhaps we're upgrading Enano?
		if($this->compat)
		{
			return $this->login_compat($username, md5($password), $level);
		}
		
		// Instanciate the Rijndael encryption object
		$aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
		
		// Initialize our success switch
		$success = false;
		
		// Retrieve the real password from the database
		$username_db = $db->escape(strtolower($username));
		$username_db_upper = $db->escape($username);
		if ( !$db->sql_query('SELECT password,password_salt,old_encryption,user_id,user_level,temp_password,temp_password_time FROM '.table_prefix."users\n"
	 										. "  WHERE ( " . ENANO_SQLFUNC_LOWERCASE . "(username) = '$username_db' OR username = '$username_db_upper' );") )
		{
			$this->sql('SELECT password,\'\' AS password_salt,old_encryption,user_id,user_level,temp_password,temp_password_time FROM '.table_prefix."users\n"
	 						. "  WHERE ( " . ENANO_SQLFUNC_LOWERCASE . "(username) = '$username_db' OR username = '$username_db_upper' );");
		}
		if ( $db->numrows() < 1 )
		{
			// This wasn't logged in <1.0.2, dunno how it slipped through
			if ( $level > USER_LEVEL_MEMBER )
				$this->sql('INSERT INTO ' . table_prefix . "logs(log_type,action,time_id,date_string,author,edit_summary,page_text) VALUES\n"
	 								. '  (\'security\', \'admin_auth_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', '
											. '\''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
			else
				$this->sql('INSERT INTO ' . table_prefix . "logs(log_type,action,time_id,date_string,author,edit_summary) VALUES\n"
	 								. '  (\'security\', \'auth_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', '
											. '\''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
			
			// Do we also need to increment the lockout countdown?
			if ( !defined('IN_ENANO_INSTALL') )
				$lockout_data = $this->get_lockout_info();
			else
				$lockout_data = array(
					'lockout_policy' => 'disable'
					);
			
			if ( $lockout_data['policy'] != 'disable' && !defined('IN_ENANO_INSTALL') )
			{
				$ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
				// increment fail count
				$this->sql('INSERT INTO '.table_prefix.'lockout(ipaddr, timestamp, action, username) VALUES(\'' . $ipaddr . '\', ' . time() . ', \'credential\', \'' . $db->escape($username) . '\');');
				$lockout_data['fails']++;
				return array(
						'success' => false,
						'error' => ( $lockout_data['fails'] >= $lockout_data['threshold'] ) ? 'locked_out' : 'invalid_credentials',
						'lockout_threshold' => $lockout_data['threshold'],
						'lockout_duration' => ( $lockout_data['duration'] ),
						'lockout_fails' => $lockout_data['fails'],
						'lockout_policy' => $lockout_data['policy']
					);
			}
			
			return array(
				'success' => false,
				'error' => 'invalid_credentials'
			);
		}
		$row = $db->fetchrow();
		
		// Check to see if we're logging in using a temporary password
		
		if((intval($row['temp_password_time']) + 3600*24) > time() )
		{
			$temp_pass = hmac_sha1($password, $row['password_salt']);
			if( $temp_pass === $row['temp_password'] )
			{
				$code = $plugins->setHook('login_password_reset');
				foreach ( $code as $cmd )
				{
					eval($cmd);
				}
				
				return array(
						'success' => false,
						'error' => 'valid_reset',
						'redirect_url' => makeUrlComplete('Special', 'PasswordReset/stage2/' . $row['user_id'] . '/' . $this->pk_encrypt($password))
					);
			}
		}
		
		if ( $row['old_encryption'] == 1 )
		{
			// The user's password is stored using the obsolete and insecure MD5 algorithm - we'll update the field with the new password
			if(md5($password) === $row['password'])
			{
				if ( !defined('IN_ENANO_UPGRADE') )
				{
					$hmac_secret = hexencode(AESCrypt::randkey(20), '', '');
					$password_hmac = hmac_sha1($password, $hmac_secret);
					$this->sql('UPDATE '.table_prefix."users SET password = '$password_hmac', password_salt = '$hmac_secret', old_encryption = 0 WHERE user_id={$row['user_id']};");
				}
				$success = true;
			}
		}
		else if ( $row['old_encryption'] == 2 || ( defined('ENANO_UPGRADE_USE_AES_PASSWORDS') ) && strlen($row['password']) != 40 )
		{
			// Our password field uses the 1.0RC1-1.1.5 encryption format
			$real_pass = $aes->decrypt($row['password'], $this->private_key);
			if($password === $real_pass)
			{
				if ( !defined('IN_ENANO_UPGRADE') )
				{
					$hmac_secret = hexencode(AESCrypt::randkey(20), '', '');
					$password_hmac = hmac_sha1($password, $hmac_secret);
					$this->sql('UPDATE '.table_prefix."users SET password = '$password_hmac', password_salt = '$hmac_secret', old_encryption = 0 WHERE user_id={$row['user_id']};");
				}
				$success = true;
			}
		}
		else
		{
			// Password uses HMAC-SHA1
			$user_challenge = hmac_sha1($password, $row['password_salt']);
			$password_hmac =& $row['password'];
			if ( $user_challenge === $password_hmac )
			{
				$success = true;
			}
		}
		if($success)
		{
			if((int)$level > (int)$row['user_level'])
				return array(
					'success' => false,
					'error' => 'too_big_for_britches'
				);
			
			// grant session
			$sess = $this->register_session($row['user_id'], $username, ( isset($password_hmac) ? $password_hmac : $password ), $level, $remember);
			
			if($sess)
			{
				if ( getConfig('db_version') >= 1125 )
				{
					if($level > USER_LEVEL_MEMBER)
						$this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,author_uid,edit_summary,page_text) VALUES(\'security\', \'admin_auth_good\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', ' . $row['user_id'] . ', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
					else
						$this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,author_uid,edit_summary) VALUES(\'security\', \'auth_good\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', ' . $row['user_id'] . ', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
				}
				else
				{
					if($level > USER_LEVEL_MEMBER)
						$this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary,page_text) VALUES(\'security\', \'admin_auth_good\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
					else
						$this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'auth_good\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
				}
				
				$code = $plugins->setHook('login_success');
				foreach ( $code as $cmd )
				{
					eval($cmd);
				}
				
				return array(
					'success' => true
					);
			}
			else
				return array(
					'success' => false,
					'error' => 'backend_fail'
				);
		}
		else
		{
			if($level > USER_LEVEL_MEMBER)
				$this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary,page_text) VALUES(\'security\', \'admin_auth_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\', ' . intval($level) . ')');
			else
				$this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'auth_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($username).'\', \''.$db->escape($_SERVER['REMOTE_ADDR']).'\')');
				
			// Do we also need to increment the lockout countdown?
			if ( !defined('IN_ENANO_INSTALL') && getConfig('lockout_policy', 'lockout') !== 'disable' )
			{
				$ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
				// increment fail count
				$this->sql('INSERT INTO '.table_prefix.'lockout(ipaddr, timestamp, action, username) VALUES(\'' . $ipaddr . '\', ' . time() . ', \'credential\', \'' . $db->escape($username) . '\');');
			}
				
			return array(
				'success' => false,
				'error' => 'invalid_credentials'
			);
		}
	}
	
	/**
	 * Attempts to log in using the old table structure and algorithm. This is for upgrades from old 1.0.x releases.
	 * @param string $username
	 * @param string $password This should be an MD5 hash
	 * @return string 'success' if successful, or error message on failure
	 */
	
	function login_compat($username, $password, $level = 0)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		$pass_hashed =& $password;
		$this->sql('SELECT password,user_id,user_level FROM '.table_prefix.'users WHERE username=\''.$this->prepare_text($username).'\';');
		if($db->numrows() < 1)
			return 'The username and/or password is incorrect.';
		$row = $db->fetchrow();
		if($row['password'] == $password)
		{
			if((int)$level > (int)$row['user_level'])
				return 'You are not authorized for this level of access.';
			$sess = $this->register_session_compat(intval($row['user_id']), $username, $password, $level);
			if($sess)
				return 'success';
			else
				return 'Your login credentials were correct, but an internal error occured while registering the session key in the database.';
		}
		else
		{
			return 'The username and/or password is incorrect.';
		}
	}
	
	/**
	 * Registers a session key in the database. This function *ASSUMES* that the username and password have already been validated!
	 * Basically the session key is a hex-encoded cookie (encrypted with the site's private key) that says "u=[username];p=[sha1 of password];s=[unique key id]"
	 * @param int $user_id
	 * @param string $username
	 * @param string $password_hmac The HMAC of the user's password, right from the database
	 * @param int $level The level of access to grant, defaults to USER_LEVEL_MEMBER
	 * @param bool $remember Whether the session should be long-term (true) or not (false). Defaults to short-term.
	 * @return bool
	 */
	 
	function register_session($user_id, $username, $password_hmac, $level = USER_LEVEL_MEMBER, $remember = false)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		
		// Random key identifier
		$salt = '';
		for ( $i = 0; $i < 32; $i++ )
		{
			$salt .= chr(mt_rand(32, 126));
		}
		
		// Session key
		if ( defined('ENANO_UPGRADE_USE_AES_PASSWORDS') )
		{
			$session_key = $this->pk_encrypt("u=$username;p=" . sha1($password_hmac) . ";s=$salt");
		}
		else
		{
			$key_pieces = array($password_hmac);
			$sk_mode = 'generate';
			$code = $plugins->setHook('session_key_calc');
			foreach ( $code as $cmd )
			{
				eval($cmd);
			}
			$key_pieces = implode("\xFF", $key_pieces);
			
			$session_key = hmac_sha1($key_pieces, $salt);
		}
		
		// Minimum level
		$level = max(array($level, USER_LEVEL_MEMBER));
		
		// Type of key
		$key_type = ( $level > USER_LEVEL_MEMBER ) ? SK_ELEV : ( $remember ? SK_LONG : SK_SHORT );
		
		// If we're registering an elevated-privilege key, it needs to be on GET
		if($level > USER_LEVEL_MEMBER)
		{
			$this->sid_super = $session_key;
			$_GET['auth'] = $session_key;
		}
		else
		{
			// Stash it in a cookie
			// For now, make the cookie last forever, we can change this in 1.1.x
			setcookie( 'sid', $session_key, time()+15552000, scriptPath.'/', null, $GLOBALS['is_https']);
			$_COOKIE['sid'] = $session_key;
			$this->sid = $session_key;
		}
		// $keyhash is stored in the database, this is for compatibility with the older DB structure
		$keyhash = md5($session_key);
		// Record the user's IP
		$ip = $_SERVER['REMOTE_ADDR'];
		if(!is_valid_ip($ip))
			die('$session->register_session: Remote-Addr was spoofed');
		// The time needs to be stashed to enforce the 15-minute limit on elevated session keys
		$time = time();
		
		// Sanity check
		if(!is_int($user_id))
			die('Somehow an SQL injection attempt crawled into our session registrar! (1)');
		if(!is_int($level))
			die(var_dump($level) . '<br />Somehow an SQL injection attempt crawled into our session registrar! (2)');
		
		// Update RAM
		$this->user_id = $user_id;
		$this->user_level = max(array($this->user_level, $level));
		
		// All done!
		$query = $db->sql_query('INSERT INTO '.table_prefix.'session_keys(session_key, salt, user_id, auth_level, source_ip, time, key_type) VALUES(\''.$keyhash.'\', \''.$db->escape($salt).'\', '.$user_id.', '.$level.', \''.$ip.'\', '.$time.', ' . $key_type . ');');
		if ( !$query && defined('IN_ENANO_UPGRADE') )
			// we're trying to upgrade so the key_type column is probably missing - try it again without specifying the key type
			$this->sql('INSERT INTO '.table_prefix.'session_keys(session_key, salt, user_id, auth_level, source_ip, time) VALUES(\''.$keyhash.'\', \''.$db->escape($salt).'\', '.$user_id.', '.$level.', \''.$ip.'\', '.$time.');');
			
		return true;
	}
	
	/**
	 * Identical to register_session in nature, but uses the old login/table structure. DO NOT use this except in the upgrade script under very controlled circumstances.
	 * @see sessionManager::register_session()
	 * @access private
	 */
	
	function register_session_compat($user_id, $username, $password, $level = 0)
	{
		$salt = md5(microtime() . mt_rand());
		$thekey = md5($password . $salt);
		if($level > 0)
		{
			$this->sid_super = $thekey;
		}
		else
		{
			setcookie( 'sid', $thekey, time()+315360000, scriptPath.'/' );
			$_COOKIE['sid'] = $thekey;
		}
		$ip = ip2hex($_SERVER['REMOTE_ADDR']);
		if(!$ip)
			die('$session->register_session: Remote-Addr was spoofed');
		$time = time();
		if(!is_int($user_id))
			die('Somehow an SQL injection attempt crawled into our session registrar! (1)');
		if(!is_int($level))
			die('Somehow an SQL injection attempt crawled into our session registrar! (2)');
		$query = $this->sql('INSERT INTO '.table_prefix.'session_keys(session_key, salt, user_id, auth_level, source_ip, time) VALUES(\''.$thekey.'\', \''.$salt.'\', '.$user_id.', '.$level.', \''.$ip.'\', '.$time.');');
		return true;
	}
	
	/**
	 * Tells us if we're locked out from logging in or not.
	 * @param reference will be filled with information regarding in-progress lockout
	 * @return bool True if locked out, false otherwise
	 */
	
	function get_lockout_info()
	{
		global $db;
		
		// this has to be initialized to hide warnings
		$lockdata = null;
		
		// Query database for lockout info
		$locked_out = false;
		$threshold = ( $_ = getConfig('lockout_threshold') ) ? intval($_) : 5;
		$duration  = ( $_ = getConfig('lockout_duration') ) ? intval($_) : 15;
		// convert to seconds
		$duration  = $duration * 60;
		// decide on policy
		$policy = ( $x = getConfig('lockout_policy') && in_array(getConfig('lockout_policy'), array('lockout', 'disable', 'captcha')) ) ? getConfig('lockout_policy') : 'lockout';
		if ( $policy != 'disable' )
		{
			// enabled; make decision
			$ipaddr = $db->escape($_SERVER['REMOTE_ADDR']);
			$timestamp_cutoff = time() - $duration;
			$q = $this->sql('SELECT timestamp FROM ' . table_prefix . 'lockout WHERE timestamp > ' . $timestamp_cutoff . ' AND ipaddr = \'' . $ipaddr . '\' ORDER BY timestamp DESC;');
			$fails = $db->numrows($q);
			$row = $db->fetchrow($q);
			$locked_out = ( $fails >= $threshold );
			$lockdata = array(
					'active' => $locked_out,
					'threshold' => $threshold,
					'duration' => ( $duration / 60 ),
					'fails' => $fails,
					'policy' => $policy,
					'last_time' => $row['timestamp'],
					'time_rem' => $locked_out ? ( $duration / 60 ) - round( ( time() - $row['timestamp'] ) / 60 ) : 0,
					'captcha' => $policy == 'captcha' ? $this->make_captcha() : ''
				);
			$db->free_result();
		}
		else
		{
			// disabled; send back default dataset
			$lockdata = array(
				'active' => false,
				'threshold' => $threshold,
				'duration' => ( $duration / 60 ),
				'fails' => 0,
				'policy' => $policy,
				'last_time' => 0,
				'time_rem' => 0,
				'captcha' => ''
			);
		}
		return $lockdata;
	}
	
	/**
	 * Creates/restores a guest session
	 * @todo implement real session management for guests
	 */
	 
	function register_guest_session()
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		global $lang;
		$this->username = $_SERVER['REMOTE_ADDR'];
		$this->user_level = USER_LEVEL_GUEST;
		if($this->compat || defined('IN_ENANO_INSTALL'))
		{
			$this->theme = 'oxygen';
			$this->style = 'bleu';
		}
		else
		{
			$this->theme = ( isset($_GET['theme']) && isset($template->named_theme_list[$_GET['theme']])) ? $_GET['theme'] : $template->default_theme;
			$this->style = ( isset($_GET['style']) && file_exists(ENANO_ROOT.'/themes/'.$this->theme . '/css/'.$_GET['style'].'.css' )) ? $_GET['style'] : preg_replace('/\.css$/', '', $template->named_theme_list[$this->theme]['default_style']);
		}
		$this->user_id = 1;
		// This is a VERY special case we are allowing. It lets the installer create languages using the Enano API.
		if ( !defined('ENANO_ALLOW_LOAD_NOLANG') )
		{
			$language = ( isset($_GET['lang']) && preg_match('/^[a-z0-9-_]+$/', @$_GET['lang']) ) ? $_GET['lang'] : intval(getConfig('default_language'));
			$lang = new Language($language);
			@setlocale(LC_ALL, $lang->lang_code);
		}
		// make a CSRF token
		$this->csrf_token = hmac_sha1($_SERVER['REMOTE_ADDR'], sha1($this->private_key));
	}
	
	/**
	 * Validates a session key, and returns the userdata associated with the key or false
	 * @param string $key The session key to validate
	 * @return array Keys are 'user_id', 'username', 'email', 'real_name', 'user_level', 'theme', 'style', 'signature', 'reg_time', 'account_active', 'activation_key', and 'auth_level' or bool false if validation failed. The key 'auth_level' is the maximum authorization level that this key provides.
	 */
	 
	function validate_session($key)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		profiler_log("SessionManager: checking session: " . sha1($key));
		
		if ( strlen($key) > 48 )
		{
			return $this->validate_aes_session($key);
		}
		
		profiler_log("SessionManager: checking session: " . $key);
		
		return $this->validate_session_shared($key, '');
	}
	
	/**
	 * Validates an old-format AES session key. DO NOT USE THIS. Will return false if called outside of an upgrade.
	 * @param string Session key
	 * @return array
	 */
	
	protected function validate_aes_session($key)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		
		// No valid use except during upgrades
		if ( !preg_match('/^upg-/', enano_version()) && !defined('IN_ENANO_UPGRADE') )
			return false;
		
		$decrypted_key = $this->pk_decrypt($key);
		if ( !$decrypted_key )
		{
			// die_semicritical('AES encryption error', '<p>Something went wrong during the AES decryption process.</p><pre>'.print_r($decrypted_key, true).'</pre>');
			return false;
		}
		
		$n = preg_match('/^u='.$this->valid_username.';p=([A-Fa-f0-9]+?);s=(.{32})$/', $decrypted_key, $keydata);
		if($n < 1)
		{
			echo '(debug) $session->validate_session: Key does not match regex<br />Decrypted key: '.$decrypted_key;
			return false;
		}
		$keyhash = md5($key);
		$salt = $db->escape($keydata[3]);
		
		return $this->validate_session_shared($keyhash, $salt, true);
	}
	
	/**
	 * Shared portion of session validation. Do not try to call this.
	 * @return array
	 * @access private
	 */
	
	protected function validate_session_shared($key, $salt, $loose_call = false)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		
		// using a normal call to $db->sql_query to avoid failing on errors here
		$columns_select  = "u.user_id AS uid, u.username, u.password, u.password_salt, u.email, u.real_name, u.user_level, u.theme,\n"
											. "  u.style,u.signature, u.reg_time, u.account_active, u.activation_key, u.user_lang, u.user_title, k.salt, k.source_ip,\n"
											. "  k.time, k.auth_level, k.key_type, COUNT(p.message_id) AS num_pms, u.user_timezone, u.user_dst, x.*";
		
		$columns_groupby = "u.user_id, u.username, u.password, u.password_salt, u.email, u.real_name, u.user_level, u.theme, u.style, u.signature,\n"
											. "           u.reg_time, u.account_active, u.activation_key, u.user_lang, u.user_timezone, u.user_title, u.user_dst,\n"
											. "           k.salt, k.source_ip, k.time, k.auth_level, k.key_type, x.user_id, x.user_aim, x.user_yahoo, x.user_msn,\n"
											. "           x.user_xmpp, x.user_homepage, x.user_location, x.user_job, x.user_hobbies, x.email_public,\n"
											. "           x.disable_js_fx, x.date_format, x.time_format";
		
		$joins = "  LEFT JOIN " . table_prefix . "users AS u\n"
						. "    ON ( u.user_id=k.user_id )\n"
						. "  LEFT JOIN " . table_prefix . "users_extra AS x\n"
						. "    ON ( u.user_id=x.user_id OR x.user_id IS NULL )\n"
						. "  LEFT JOIN " . table_prefix . "privmsgs AS p\n"
						. "    ON ( p.message_to=u.username AND p.message_read=0 )\n";
		if ( !$loose_call )
		{
			$key_md5 = md5($key);
			$query = $db->sql_query("SELECT $columns_select\n"
														. "FROM " . table_prefix . "session_keys AS k\n"
														. $joins
														. "  WHERE k.session_key='$key_md5'\n"
														. "  GROUP BY $columns_groupby;");
		}
		else
		{
			$query = $db->sql_query("SELECT $columns_select\n"
														. "FROM " . table_prefix . "session_keys AS k\n"
														. $joins
														. "  WHERE k.session_key='$key'\n"
														. "    AND k.salt='$salt'\n"
														. "  GROUP BY $columns_groupby;");
		}
		
		if ( !$query && ( defined('IN_ENANO_INSTALL') or defined('IN_ENANO_UPGRADE') ) )
		{
			$key_md5 = $loose_call ? $key : md5($key);
			$query = $this->sql('SELECT u.user_id AS uid,u.username,u.password,\'\' AS password_salt,u.email,u.real_name,u.user_level,u.theme,u.style,u.signature,u.reg_time,u.account_active,u.activation_key,k.source_ip,k.time,k.auth_level,COUNT(p.message_id) AS num_pms, 1440 AS user_timezone, \'0;0;0;0;60\' AS user_dst, ' . SK_SHORT . ' AS key_type, k.salt FROM '.table_prefix.'session_keys AS k
	 													LEFT JOIN '.table_prefix.'users AS u
	 														ON ( u.user_id=k.user_id )
	 													LEFT JOIN '.table_prefix.'privmsgs AS p
	 														ON ( p.message_to=u.username AND p.message_read=0 )
	 													WHERE k.session_key=\''.$key_md5.'\'
	 													GROUP BY u.user_id,u.username,u.password,u.email,u.real_name,u.user_level,u.theme,u.style,u.signature,u.reg_time,u.account_active,u.activation_key,k.source_ip,k.time,k.auth_level,k.salt;');
		}
		else if ( !$query )
		{
			$db->_die();
		}
		if($db->numrows() < 1)
		{
			// echo '(debug) $session->validate_session: Key was not found in database: ' . $key_md5 . '<br />';
			return false;
		}
		$row = $db->fetchrow();
		profiler_log("SessionManager: session check: selected and fetched results");
		
		$row['user_id'] =& $row['uid'];
		$ip = $_SERVER['REMOTE_ADDR'];
		if($row['auth_level'] > $row['user_level'])
		{
			// Failed authorization check
			// echo '(debug) $session->validate_session: access to this auth level denied<br />';
			return false;
		}
		if($ip != $row['source_ip'])
		{
			// Special exception for 1.1.x upgrade - the 1.1.3 upgrade changes the size of the column and this is what validate_session
			// expects, but if the column size hasn't changed yet just check the first 10 digits of the IP.
			$fail = true;
			if ( defined('IN_ENANO_UPGRADE') )
			{
				if ( substr($ip, 0, 10) == substr($row['source_ip'], 0, 10) )
					$fail = false;
			}
			// Failed IP address check
			// echo '(debug) $session->validate_session: IP address mismatch<br />';
			if ( $fail )
				return false;
		}
		
		// $loose_call is turned on only from validate_aes_session
		if ( !$loose_call )
		{
			$key_pieces = array($row['password']);
			$user_id =& $row['uid'];
			$sk_mode = 'validate';
			$code = $plugins->setHook('session_key_calc');
			foreach ( $code as $cmd )
			{
				eval($cmd);
			}
			$key_pieces = implode("\xFF", $key_pieces);
			$correct_key = hexdecode(hmac_sha1($key_pieces, $row['salt']));
			$user_key = hexdecode($key);
			if ( $correct_key !== $user_key || !is_string($user_key) )
			{
				return false;
			}
		}
		else
		{
			// if this is a "loose call", this only works once (during the final upgrade stage). Destroy the contents of session_keys.
			if ( $row['auth_level'] == USER_LEVEL_ADMIN && preg_match('/^upg-/', enano_version()) )
				$this->sql('DELETE FROM ' . table_prefix . "session_keys;");
		}
		
		// timestamp check
		switch ( $row['key_type'] )
		{
			case SK_SHORT:
				$time_now = time();
				$time_key = $row['time'] + ( 60 * intval(getConfig('session_short', '720')) );
				if ( $time_now > $time_key )
				{
					// Session timed out
					return false;
				}
				break;
			case SK_LONG:
				if ( intval(getConfig('session_remember_time', '0')) === 0 )
				{
					// sessions last infinitely, timestamp validation is therefore successful
					break;
				}
				$time_now = time();
				$time_key = $row['time'] + ( 86400 * intval(getConfig('session_remember_time', '30')) );
				if ( $time_now > $time_key )
				{
					// Session timed out
					return false;
				}
				break;
			case SK_ELEV:
				$time_now = time();
				$time_key = $row['time'] + 900;
				if($time_now > $time_key && $row['auth_level'] > USER_LEVEL_MEMBER)
				{
					// Session timed out
					// echo '(debug) $session->validate_session: super session timed out<br />';
					$this->sw_timed_out = true;
					return false;
				}
				break;
		}
				
		// If this is an elevated-access or short-term session key, update the time
		if( $row['key_type'] == SK_ELEV || $row['key_type'] == SK_SHORT )
		{
			$this->sql('UPDATE '.table_prefix.'session_keys SET time='.time().' WHERE session_key=\''.md5($key).'\';');
		}
		
		$user_extra = array();
		foreach ( array('user_aim', 'user_yahoo', 'user_msn', 'user_xmpp', 'user_homepage', 'user_location', 'user_job', 'user_hobbies', 'email_public', 'disable_js_fx') as $column )
		{
			if ( isset($row[$column]) )
				$user_extra[$column] = $row[$column];
			else
				$user_extra[$column] = '';
		}
		
		if ( isset($row['date_format']) )
			$this->date_format = $row['date_format'];
		if ( isset($row['time_format']) )
			$this->time_format = $row['time_format'];
		
		$this->user_extra = $user_extra;
		// Leave the rest to PHP's automatic garbage collector ;-)
		
		$row['password'] = '';
		$row['user_timezone'] = intval($row['user_timezone']) - 1440;
		
		profiler_log("SessionManager: finished session check");
		
		return $row;
	}
	
	/**
	 * Validates a session key, and returns the userdata associated with the key or false. Optimized for compatibility with the old MD5-based auth system.
	 * @param string $key The session key to validate
	 * @return array Keys are 'user_id', 'username', 'email', 'real_name', 'user_level', 'theme', 'style', 'signature', 'reg_time', 'account_active', 'activation_key', and 'auth_level' or bool false if validation failed. The key 'auth_level' is the maximum authorization level that this key provides.
	 */
	 
	function compat_validate_session($key)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		$key = $db->escape($key);
		
		$query = $this->sql('SELECT u.user_id,u.username,u.password,u.email,u.real_name,u.user_level,k.source_ip,k.salt,k.time,k.auth_level,1440 AS user_timezone FROM '.table_prefix.'session_keys AS k
	 												LEFT JOIN '.table_prefix.'users AS u
	 													ON u.user_id=k.user_id
	 												WHERE k.session_key=\''.$key.'\';');
		if($db->numrows() < 1)
		{
			// echo '(debug) $session->validate_session: Key '.$key.' was not found in database<br />';
			return false;
		}
		$row = $db->fetchrow();
		$ip = ip2hex($_SERVER['REMOTE_ADDR']);
		if($row['auth_level'] > $row['user_level'])
		{
			// Failed authorization check
			// echo '(debug) $session->validate_session: user not authorized for this access level';
			return false;
		}
		if($ip != $row['source_ip'])
		{
			// Failed IP address check
			// echo '(debug) $session->validate_session: IP address mismatch; IP in table: '.$row['source_ip'].'; reported IP: '.$ip.'';
			return false;
		}
		
		// Do the password validation
		$real_key = md5($row['password'] . $row['salt']);
		
		//die('<pre>'.print_r($keydata, true).'</pre>');
		if($real_key != $key)
		{
			// Failed password check
			// echo '(debug) $session->validate_session: supplied password is wrong<br />Real key: '.$real_key.'<br />User key: '.$key;
			return false;
		}
		
		$time_now = time();
		$time_key = $row['time'] + 900;
		if($time_now > $time_key && $row['auth_level'] >= 1)
		{
			$this->sw_timed_out = true;
			// Session timed out
			// echo '(debug) $session->validate_session: super session timed out<br />';
			return false;
		}
		
		$row['user_timezone'] = intval($row['user_timezone']) - 1440;
		
		return $row;
	}
	 
	/**
	 * Demotes us to one less than the specified auth level. AKA destroys elevated authentication and/or logs out the user, depending on $level
	 * @param int $level How low we should go - USER_LEVEL_MEMBER means demote to USER_LEVEL_GUEST, and anything more powerful than USER_LEVEL_MEMBER means demote to USER_LEVEL_MEMBER
	 * @return string 'success' if successful, or error on failure
	 */
	 
	function logout($level = USER_LEVEL_MEMBER)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		$ou = $this->username;
		$oid = $this->user_id;
		if($level > USER_LEVEL_MEMBER)
		{
			$aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
			if(!$this->user_logged_in || $this->auth_level < ( USER_LEVEL_MEMBER + 1))
			{
				return 'success';
			}
			// Destroy elevated privileges
			$keyhash = md5($this->sid_super);
			$this->sql('DELETE FROM '.table_prefix.'session_keys WHERE session_key=\''.$keyhash.'\' AND user_id=\'' . $this->user_id . '\';');
			$this->sid_super = false;
			$this->auth_level = USER_LEVEL_MEMBER;
		}
		else
		{
			if($this->user_logged_in)
			{
				$aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
				// Completely destroy our session
				if($this->auth_level > USER_LEVEL_MEMBER)
				{
					$this->logout(USER_LEVEL_ADMIN);
				}
				$this->sql('DELETE FROM '.table_prefix.'session_keys WHERE session_key=\''.md5($this->sid).'\';');
				setcookie( 'sid', '', time()-(3600*24), scriptPath.'/' );
			}
		}
		$code = $plugins->setHook('logout_success'); // , Array('level'=>$level,'old_username'=>$ou,'old_user_id'=>$oid));
		foreach ( $code as $cmd )
		{
			eval($cmd);
		}
		return 'success';
	}
	
	# Miscellaneous stuff
	
	/**
	 * Alerts the user that their account is inactive, and tells them appropriate steps to remedy the situation. Halts execution.
	 * @param array Return from validate_session()
	 */
	
	function show_inactive_error($userdata)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		global $lang;
		
		global $title;
		$paths->init($title);
		
		$language = intval(getConfig('default_language'));
		$lang = new Language($language);
		@setlocale(LC_ALL, $lang->lang_code);
		
		$a = getConfig('account_activation');
		switch($a)
		{
			case 'none':
			default:
				$solution = $lang->get('user_login_noact_solution_none');
				break;
			case 'user':
				$solution = $lang->get('user_login_noact_solution_user');
				break;
			case 'admin':
				$solution = $lang->get('user_login_noact_solution_admin');
				break;
		}
		
		// admin activation request opportunity
		$q = $db->sql_query('SELECT 1 FROM '.table_prefix.'logs WHERE log_type=\'admin\' AND action=\'activ_req\' AND edit_summary=\'' . $db->escape($userdata['username']) . '\';');
		if ( !$q )
			$db->_die();
		
		$can_request = ( $db->numrows() < 1 );
		$db->free_result();
		
		if ( isset($_POST['logout']) )
		{
			$this->sid = $_COOKIE['sid'];
			$this->user_logged_in = true;
			$this->user_id =       intval($userdata['user_id']);
			$this->username =      $userdata['username'];
			$this->auth_level =    USER_LEVEL_MEMBER;
			$this->user_level =    USER_LEVEL_MEMBER;
			$this->logout();
			redirect(scriptPath . '/', $lang->get('user_login_noact_msg_logout_success_title'), $lang->get('user_login_noact_msg_logout_success_body'), 5);
		}
		
		if ( $can_request && !isset($_POST['activation_request']) )
		{
			$form = '<p>' . $lang->get('user_login_noact_msg_ask_admins') . '</p>
	 						<form action="' . makeUrlNS('System', 'ActivateStub') . '" method="post">
	 							<p><input type="submit" name="activation_request" value="' . $lang->get('user_login_noact_btn_request_activation') . '" /> <input type="submit" name="logout" value="' . $lang->get('user_login_noact_btn_log_out') . '" /></p>
	 						</form>';
		}
		else
		{
			if ( $can_request && isset($_POST['activation_request']) )
			{
				$this->admin_activation_request($userdata['username']);
				$form = '<p>' . $lang->get('user_login_noact_msg_admins_just_asked') . '</p>
	 							<form action="' . makeUrlNS('System', 'ActivateStub') . '" method="post">
	 								<p><input type="submit" name="logout" value="' . $lang->get('user_login_noact_btn_log_out') . '" /></p>
	 							</form>';
			}
			else
			{
				$form = '<p>' . $lang->get('user_login_noact_msg_admins_asked') . '</p>
	 							<form action="' . makeUrlNS('System', 'ActivateStub') . '" method="post">
	 								<p><input type="submit" name="logout" value="' . $lang->get('user_login_noact_btn_log_out') . '" /></p>
	 							</form>';
			}
		}
		
		global $output;
		$output = new Output_HTML();
		$output->set_title($lang->get('user_login_noact_title'));
		die_friendly($lang->get('user_login_noact_title'), '<p>' . $lang->get('user_login_noact_msg_intro') . ' '.$solution.'</p>' . $form);
	}
	
	/**
	 * Appends the high-privilege session key to the URL if we are authorized to do high-privilege stuff
	 * @param string $url The URL to add session data to
	 * @return string
	 */
	
	function append_sid($url)
	{
		$sep = ( strstr($url, '?') ) ? '&' : '?';
		if ( $this->sid_super )
		{
			$url = $url . $sep . 'auth=' . urlencode($this->sid_super);
			// echo($this->sid_super.'<br/>');
		}
		return $url;
	}
	
	/**
	 * Prevent the user from changing their password. Authentication plugins may call this to enforce single sign-on.
	 * @param string URL to page where the user may change their password
	 * @param string Title of the page where the user may change their password
	 * @return null
	 */
	
	function disable_password_change($change_url = false, $change_title = false)
	{
		if ( $this->password_change_disabled )
		{
			// don't allow calling twice. if we have two plugins doing this, somebody is bad at configuring websites.
			return false;
		}
		
		if ( is_string($change_url) && is_string($change_title) )
		{
			$this->password_change_dest = array(
					'url' => $change_url,
					'title' => $change_title
				);
		}
		else
		{
			$this->password_change_dest = array(
					'url' => false,
					'title' => false
				);
		}
		
		$this->password_change_disabled = true;
	}
	
	/**
	 * Grabs the user's password MD5 - NOW DEPRECATED AND DISABLED.
	 * @return bool false
	 */
	 
	function grab_password_hash()
	{
		return false;
	}
	
	/**
	 * Destroys the user's password MD5 in memory
	 */
	
	function disallow_password_grab()
	{
		$this->password_hash = false;
		return false;
	}
	
	/**
	 * Generates an AES key and stashes it in the database
	 * @return string Hex-encoded AES key
	 */
	 
	static function rijndael_genkey()
	{
		$aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
		$key = $aes->gen_readymade_key();
		$keys = getConfig('login_key_cache');
		if(is_string($keys))
			$keys .= $key;
		else
			$keys = $key;
		setConfig('login_key_cache', $keys);
		return $key;
	}
	
	/**
	 * Generate a totally random 128-bit value for MD5 challenges
	 * @return string
	 */
	 
	static function dss_rand()
	{
		$aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
		$random = $aes->randkey(128);
		unset($aes);
		return md5(microtime() . $random);
	}
	
	/**
	 * Fetch a cached login public key using the MD5sum as an identifier. Each key can only be fetched once before it is destroyed.
	 * @param string $md5 The MD5 sum of the key
	 * @return string, or bool false on failure
	 */
	 
	function fetch_public_key($md5)
	{
		$keys = getConfig('login_key_cache');
		$keys = enano_str_split($keys, AES_BITS / 4);
		
		foreach($keys as $i => $k)
		{
			if(md5($k) == $md5)
			{
				unset($keys[$i]);
				if(count($keys) > 0)
				{
					if ( strlen(getConfig('login_key_cache') ) > 64000 )
					{
						// This should only need to be done once every month or so for an average-size site
						setConfig('login_key_cache', '');
					}
					else
					{
						$keys = implode('', array_values($keys));
						setConfig('login_key_cache', $keys);
					}
				}
				else
				{
					setConfig('login_key_cache', '');
				}
				return $k;
			}
		}
		// Couldn't find the key...
		return false;
	}
	
	/**
	 * Adds a user to a group.
	 * @param int User ID
	 * @param int Group ID
	 * @param bool Group moderator - defaults to false
	 * @return bool True on success, false on failure
	 */
	
	function add_user_to_group($user_id, $group_id, $is_mod = false)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		
		// Validation
		if ( !is_int($user_id) || !is_int($group_id) || !is_bool($is_mod) )
			return false;
		if ( $user_id < 1 || $group_id < 1 )
			return false;
		
		$mod_switch = ( $is_mod ) ? '1' : '0';
		$q = $this->sql('SELECT member_id,is_mod FROM '.table_prefix.'group_members WHERE user_id=' . $user_id . ' AND group_id=' . $group_id . ';');
		if ( !$q )
			$db->_die();
		if ( $db->numrows() < 1 )
		{
			// User is not in group
			$this->sql('INSERT INTO '.table_prefix.'group_members(user_id,group_id,is_mod) VALUES(' . $user_id . ', ' . $group_id . ', ' . $mod_switch . ');');
			return true;
		}
		else
		{
			$row = $db->fetchrow();
			// Update modship status
			if ( strval($row['is_mod']) == $mod_switch )
			{
				// Modship unchanged
				return true;
			}
			else
			{
				// Modship changed
				$this->sql('UPDATE '.table_prefix.'group_members SET is_mod=' . $mod_switch . ' WHERE member_id=' . $row['member_id'] . ';');
				return true;
			}
		}
		return false;
	}
	
	/**
	 * Removes a user from a group.
	 * @param int User ID
	 * @param int Group ID
	 * @return bool True on success, false on failure
	 * @todo put a little more error checking in...
	 */
	
	function remove_user_from_group($user_id, $group_id)
	{
		if ( !is_int($user_id) || !is_int($group_id) )
			return false;
		$this->sql('DELETE FROM '.table_prefix."group_members WHERE user_id=$user_id AND group_id=$group_id;");
		return true;
	}
	
	/**
	 * Checks the banlist to ensure that we're an allowed user. Doesn't return anything because it dies if the user is banned.
	 */
	 
	function check_banlist()
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		global $lang;
		
		$col_reason = ( $this->compat ) ? '\'No reason available (session manager is in compatibility mode)\' AS reason' : 'reason';
		$remote_addr = ( strstr($_SERVER['REMOTE_ADDR'], ':') ) ? expand_ipv6_address($_SERVER['REMOTE_ADDR']) : $_SERVER['REMOTE_ADDR'];
		
		$banned = false;
		if ( $this->user_logged_in )
		{
			// check by IP, email, and username
			if ( ENANO_DBLAYER == 'MYSQL' )
			{
				$sql = "SELECT $col_reason, ban_value, ban_type, is_regex FROM " . table_prefix . "banlist WHERE \n"
							. "    ( ban_type = " . BAN_IP    . " AND is_regex = 0 ) OR \n"
							. "    ( ban_type = " . BAN_IP    . " AND is_regex = 1 AND '{$_SERVER['REMOTE_ADDR']}' REGEXP ban_value ) OR \n"
							. "    ( ban_type = " . BAN_USER  . " AND is_regex = 0 AND ban_value = '" . $db->escape($this->username) . "' ) OR \n"
							. "    ( ban_type = " . BAN_USER  . " AND is_regex = 1 AND '" . $db->escape($this->username) . "' REGEXP ban_value ) OR \n"
							. "    ( ban_type = " . BAN_EMAIL . " AND is_regex = 0 AND ban_value = '" . $db->escape($this->email) . "' ) OR \n"
							. "    ( ban_type = " . BAN_EMAIL . " AND is_regex = 1 AND '" . $db->escape($this->email) . "' REGEXP ban_value ) \n"
							. "  ORDER BY ban_type ASC;";
			}
			else if ( ENANO_DBLAYER == 'PGSQL' )
			{
				$sql = "SELECT $col_reason, ban_value, ban_type, is_regex FROM " . table_prefix . "banlist WHERE \n"
							. "    ( ban_type = " . BAN_IP    . " AND is_regex = 0 ) OR \n"
							. "    ( ban_type = " . BAN_IP    . " AND is_regex = 1 AND '{$_SERVER['REMOTE_ADDR']}' ~ ban_value ) OR \n"
							. "    ( ban_type = " . BAN_USER  . " AND is_regex = 0 AND ban_value = '" . $db->escape($this->username) . "' ) OR \n"
							. "    ( ban_type = " . BAN_USER  . " AND is_regex = 1 AND '" . $db->escape($this->username) . "' ~ ban_value ) OR \n"
							. "    ( ban_type = " . BAN_EMAIL . " AND is_regex = 0 AND ban_value = '" . $db->escape($this->email) . "' ) OR \n"
							. "    ( ban_type = " . BAN_EMAIL . " AND is_regex = 1 AND '" . $db->escape($this->email) . "' ~ ban_value ) \n"
							. "  ORDER BY ban_type ASC;";
			}
			$q = $this->sql($sql);
			if ( $db->numrows() > 0 )
			{
				while ( list($reason_temp, $ban_value, $ban_type, $is_regex) = $db->fetchrow_num() )
				{
					if ( $ban_type == BAN_IP && $is_regex != 1 )
					{
						// check range
						$regexp = parse_ip_range_regex($ban_value);
						if ( !$regexp )
						{
							continue;
						}
						if ( preg_match("/$regexp/", $remote_addr) )
						{
							$reason = $reason_temp;
							$banned = true;
						}
					}
					else
					{
						// User is banned
						$banned = true;
						$reason = $reason_temp;
					}
				}
			}
			$db->free_result();
		}
		else
		{
			// check by IP only
			if ( ENANO_DBLAYER == 'MYSQL' )
			{
				$sql = "SELECT $col_reason, ban_value, ban_type, is_regex FROM " . table_prefix . "banlist WHERE
									( ban_type = " . BAN_IP    . " AND is_regex = 0 ) OR
									( ban_type = " . BAN_IP    . " AND is_regex = 1 AND '{$_SERVER['REMOTE_ADDR']}' REGEXP ban_value )
								ORDER BY ban_type ASC;";
			}
			else if ( ENANO_DBLAYER == 'PGSQL' )
			{
				$sql = "SELECT $col_reason, ban_value, ban_type, is_regex FROM " . table_prefix . "banlist WHERE
									( ban_type = " . BAN_IP    . " AND is_regex = 0 ) OR
									( ban_type = " . BAN_IP    . " AND is_regex = 1 AND '{$_SERVER['REMOTE_ADDR']}' ~ ban_value )
								ORDER BY ban_type ASC;";
			}
			$q = $this->sql($sql);
			if ( $db->numrows() > 0 )
			{
				while ( list($reason_temp, $ban_value, $ban_type, $is_regex) = $db->fetchrow_num() )
				{
					if ( $ban_type == BAN_IP && $is_regex != 1 )
					{
						// check range
						$regexp = parse_ip_range_regex($ban_value);
						if ( !$regexp )
						{
							die("bad regexp for $ban_value");
							continue;
						}
						if ( preg_match("/$regexp/", $remote_addr) )
						{
							$reason = $reason_temp;
							$banned = true;
						}
					}
					else
					{
						// User is banned
						$reason = $reason_temp;
						$banned = true;
					}
				}
			}
			$db->free_result();
		}
		if ( $banned && !$this->on_critical_page(true) )
		{
			// This guy is banned - kill the session, kill the database connection, bail out, and be pretty about it
			die_semicritical($lang->get('user_ban_msg_title'), '<p>' . $lang->get('user_ban_msg_body') . '</p><div class="error-box"><b>' . $lang->get('user_ban_lbl_reason') . '</b><br />' . $reason . '</div>');
			exit;
		}
	}
	
	# Registration
	
	/**
	 * Registers a user. This does not perform any type of login.
	 * @param string New user's username
	 * @param string This should be unencrypted.
	 * @param string E-mail address.
	 * @param string Optional, defaults to ''.
	 * @param bool Optional. If true, the account is not activated initially and an admin activation request is sent. The caller is responsible for sending the address info and notice.
	 */
	 
	function create_user($username, $password, $email, $real_name = '', $coppa = false)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		global $lang;
		
		// Initialize AES
		$aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
		
		// Since we're recording IP addresses, make sure the user's IP is safe.
		$ip =& $_SERVER['REMOTE_ADDR'];
		if ( !is_valid_ip($ip) )
			return 'Invalid IP';
		
		if ( !preg_match('#^'.$this->valid_username.'$#', $username) )
			return $lang->get('user_reg_err_username_banned_chars');
		
		$username = str_replace('_', ' ', $username);
		$user_orig = $username;
		$username = $this->prepare_text($username);
		$email = $this->prepare_text($email);
		$real_name = $this->prepare_text($real_name);
		
		$nameclause = ( $real_name != '' ) ? ' OR real_name=\''.$real_name.'\'' : '';
		$q = $this->sql('SELECT * FROM '.table_prefix.'users WHERE ' . ENANO_SQLFUNC_LOWERCASE . '(username)=\''.strtolower($username).'\' OR email=\''.$email.'\''.$nameclause.';');
		if($db->numrows() > 0)
		{
			$row = $db->fetchrow();
			$str = 'user_reg_err_dupe';
			
			if ( $row['username'] == $username )
			{
				$str .= '_username';
			}
			if ( $row['email'] == $email )
			{
				$str .= '_email';
			}
			if ( $row['real_name'] == $real_name && $real_name != '' )
			{
				$str .= '_realname';
			}
			
			return $lang->get($str);
		}
		
		// Is the password strong enough?
		if ( getConfig('pw_strength_enable') )
		{
			$min_score = intval( getConfig('pw_strength_minimum') );
			$pass_score = password_score($password);
			if ( $pass_score < $min_score )
			{
				return $lang->get('user_reg_err_password_too_weak');
			}
		}
		
		// Require the account to be activated?
		switch(getConfig('account_activation'))
		{
			case 'none':
			default:
				$active = '1';
				break;
			case 'user':
				$active = '0';
				break;
			case 'admin':
				$active = '0';
				break;
		}
		if ( $coppa )
			$active = '0';
		
		$coppa_col = ( $coppa ) ? '1' : '0';
		
		// Generate a totally random activation key
		$actkey = sha1 ( microtime() . mt_rand() );

		// We good, create the user
		$this->sql('INSERT INTO ' . table_prefix . "users ( username, email, real_name, theme, style, reg_time, account_active, activation_key, user_level, user_coppa,\n"
	 					. "                                        user_registration_ip, user_lang, user_has_avatar, avatar_type ) VALUES\n"
	 					. "  ( '$username', '$email', '$real_name', '$template->default_theme', '$template->default_style', " . time() . ", $active, '$actkey', \n"
	 					. "    " . USER_LEVEL_CHPREF . ", $coppa_col, '$ip', $lang->lang_id, 0, 'png' );");
		
		// Get user ID and create users_extra entry
		$q = $this->sql('SELECT user_id FROM '.table_prefix."users WHERE username='$username';");
		if ( $db->numrows() > 0 )
		{
			list($user_id) = $db->fetchrow_num();
			$db->free_result();
			
			$this->sql('INSERT INTO '.table_prefix.'users_extra(user_id) VALUES(' . $user_id . ');');
		}
		
		// Set the password
		$this->set_password($user_id, $password);
		
		// Config option added, 1.1.5
		if ( getConfig('userpage_grant_acl', '1') == '1' )             
		{
			// Grant edit and very limited mod access to the userpage
			$acl_data = array(
					'read' => AUTH_ALLOW,
					'view_source' => AUTH_ALLOW,
					'edit_page' => AUTH_ALLOW,
					'post_comments' => AUTH_ALLOW,
					'edit_comments' => AUTH_ALLOW, // only allows editing own comments
					'history_view' => AUTH_ALLOW,
					'history_rollback' => AUTH_ALLOW,
					'rename' => AUTH_ALLOW,
					'delete_page' => AUTH_ALLOW,
					'tag_create' => AUTH_ALLOW,
					'tag_delete_own' => AUTH_ALLOW,
					'tag_delete_other' => AUTH_ALLOW,
					'edit_cat' => AUTH_ALLOW,
					'create_page' => AUTH_ALLOW
				);
			$acl_data = $db->escape($this->perm_to_string($acl_data));
			$userpage = $db->escape(sanitize_page_id($user_orig));
			$cols = "target_type, target_id, page_id, namespace, rules";
			$vals = ACL_TYPE_USER . ", $user_id, '$userpage', 'User', '$acl_data'";
			$q = "INSERT INTO ".table_prefix."acl($cols) VALUES($vals);";
			$this->sql($q);
		}
		
		// Require the account to be activated?
		if ( $coppa )
		{
			$this->admin_activation_request($user_orig);
			$this->send_coppa_mail($user_orig, $email);
		}
		else
		{
			switch(getConfig('account_activation'))
			{
				case 'none':
				default:
					break;
				case 'user':
					$a = $this->send_activation_mail($user_orig);
					if(!$a)
					{
						$this->admin_activation_request($user_orig);
						return $lang->get('user_reg_err_actmail_failed') . ' ' . $a;
					}
					break;
				case 'admin':
					$this->admin_activation_request($user_orig);
					break;
			}
		}
		
		// Leave some data behind for the hook
		$code = $plugins->setHook('user_registered');
		foreach ( $code as $cmd )
		{
			eval($cmd);
		}
		
		return 'success';
	}
	
	/**
	 * Attempts to send an e-mail to the specified user with activation instructions.
	 * @param string $u The usernamd of the user requesting activation
	 * @return bool true on success, false on failure
	 */
	 
	function send_activation_mail($u, $actkey = false)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		global $lang;
		$q = $this->sql('SELECT username,activation_key,account_active,email FROM '.table_prefix.'users WHERE username=\''.$db->escape($u).'\';');
		$r = $db->fetchrow();
		if ( empty($r['email']) )
			$db->_die('BUG: $session->send_activation_mail(): no e-mail address in row');
		
		$aklink = makeUrlComplete('Special', 'ActivateAccount/'.str_replace(' ', '_', $u).'/'. ( ( is_string($actkey) ) ? $actkey : $r['activation_key'] ) );
		$message = $lang->get('user_reg_activation_email', array(
				'activation_link' => $aklink,
				'username' => $u
			));
			
		if ( getConfig('smtp_enabled') == '1' )
		{
			$result = smtp_send_email($r['email'], $lang->get('user_reg_activation_email_subject'), preg_replace("#(?<!\r)\n#s", "\n", $message), getConfig('contact_email'));
			if ( $result == 'success' )
			{
				$result = true;
			}
			else
			{
				echo $result;
				$result = false;
			}
		}
		else
		{
			$result = mail($r['email'], $lang->get('user_reg_activation_email_subject'), preg_replace("#(?<!\r)\n#s", "\n", $message), 'From: '.getConfig('contact_email'));
		}
		return $result;
	}
	
	/**
	 * Attempts to send an e-mail to the specified user's e-mail address on file intended for the parents
	 * @param string $u The usernamd of the user requesting activation
	 * @return bool true on success, false on failure
	 */
	 
	function send_coppa_mail($u, $actkey = false)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		global $lang;
		
		$q = $this->sql('SELECT username,email FROM '.table_prefix.'users WHERE user_id=2 OR user_level=' . USER_LEVEL_ADMIN . ' ORDER BY user_id ASC;');
		$un = $db->fetchrow();
		$admin_user = $un['username'];
		
		$q = $this->sql('SELECT username,activation_key,account_active,email FROM '.table_prefix.'users WHERE username=\''.$db->escape($u).'\';');
		$r = $db->fetchrow();
		if ( empty($r['email']) )
			$db->_die('BUG: $session->send_activation_mail(): no e-mail address in row');
			
		if(isset($_SERVER['HTTPS'])) $prot = 'https';
		else $prot = 'http';                                                                           
		if($_SERVER['SERVER_PORT'] == '80') $p = '';
		else $p = ':'.$_SERVER['SERVER_PORT'];
		$sidbak = false;
		if($this->sid_super)
			$sidbak = $this->sid_super;
		$this->sid_super = false;
		if($sidbak)
			$this->sid_super = $sidbak;
		unset($sidbak);
		$link = "$prot://".$_SERVER['HTTP_HOST'].scriptPath;
		
		$message = $lang->get(
				'user_reg_activation_email_coppa',
				array(
					'username' => $u,
					'admin_user' => $admin_user,
					'site_link' => $link
				)
			);
		
		
		if(getConfig('smtp_enabled') == '1')
		{
			$result = smtp_send_email($r['email'], getConfig('site_name').' website account activation', preg_replace("#(?<!\r)\n#s", "\n", $message), getConfig('contact_email'));
			if($result == 'success') 
			{
				$result = true;
			}
			else
			{
				echo $result;
				$result = false;
			}
		} 
		else
		{
			$result = mail($r['email'], getConfig('site_name').' website account activation', preg_replace("#(?<!\r)\n#s", "\n", $message), 'From: '.getConfig('contact_email'));
		}
		return $result;
	}
	
	/**
	 * Sends an e-mail to a user so they can reset their password.
	 * @param int $user The user ID, or username if it's a string
	 * @return bool true on success, false on failure
	 */
	 
	function mail_password_reset($user)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		global $lang;
		
		if(is_int($user))
		{
			$q = $this->sql('SELECT user_id,username,email FROM '.table_prefix.'users WHERE user_id='.$user.';'); // This is SAFE! This is only called if $user is an integer
		}
		elseif(is_string($user))
		{
			$q = $this->sql('SELECT user_id,username,email FROM '.table_prefix.'users WHERE ' . ENANO_SQLFUNC_LOWERCASE . '(username)=' . ENANO_SQLFUNC_LOWERCASE . '(\''.$db->escape($user).'\');');
		}
		else
		{
			return false;
		}
		
		$row = $db->fetchrow();
		$temp_pass = $this->random_pass();
		
		// check the seclog
		$ts = time() - 15;
		// Prevent resets on the same UID or from the same IP
		// FIXME: Qatar
		// 		(http://www.reddit.com/r/todayilearned/comments/k27x6/til_that_the_entire_nation_of_qatar_has_a_single/)
		$q = $this->sql('SELECT log_id, time_id FROM ' . table_prefix . "logs WHERE log_type = 'security' AND action = 'pass_reset' AND ( edit_summary = '{$_SERVER['REMOTE_ADDR']}' OR author_uid = {$row['user_id']} ) AND time_id > $ts;");
		if ( $db->numrows($q) > 0 )
		{
			// rate limit exceeded... one password reset request every 15 seconds is not appropriate
			$db->free_result();
			return false;
		}
		$db->free_result();
		
		$now = time();
		$uname = $db->escape($row['username']);
		$this->sql('INSERT INTO ' . table_prefix . 'logs ( time_id, log_type, action, author, author_uid, edit_summary ) VALUES'
						. "($now, 'security', 'pass_reset', '$uname', {$row['user_id']}, '{$_SERVER['REMOTE_ADDR']}');");
		$this->register_temp_password($row['user_id'], $temp_pass);
		
		$site_name = getConfig('site_name');
 
		$message = $lang->get('userfuncs_passreset_email', array(
				'username' => $row['username'],
				'site_name' => $site_name,
				'remote_addr' => $_SERVER['REMOTE_ADDR'],
				'temp_pass' => $temp_pass
			));
		
		if(getConfig('smtp_enabled') == '1')
		{
			$result = smtp_send_email($row['email'], getConfig('site_name').' password reset', preg_replace("#(?<!\r)\n#s", "\n", $message), getConfig('contact_email'));
			if($result == 'success')
			{
				$result = true;
			}
			else
			{
				echo '<p>'.$result.'</p>';
				$result = false;
			}
		} else {
			$result = mail($row['email'], getConfig('site_name').' password reset', preg_replace("#(?<!\r)\n#s", "\n", $message), 'From: '.getConfig('contact_email'));
		}
		return $result;
	}
	
	/**
	 * Sets the temporary password for the specified user to whatever is specified.
	 * @param int $user_id
	 * @param string $password
	 * @return bool
	 */
	 
	function register_temp_password($user_id, $password)
	{
		global $db;
		if ( !is_int($user_id) )
			return false;
		
		$this->sql('SELECT password_salt FROM ' . table_prefix . "users WHERE user_id = $user_id;");
		if ( $db->numrows() < 1 )
			return false;
		
		list($salt) = $db->fetchrow_num();
		$db->free_result();
		
		$temp_pass = hmac_sha1($password, $salt);
		$this->sql('UPDATE '.table_prefix.'users SET temp_password=\'' . $temp_pass . '\',temp_password_time='.time().' WHERE user_id='.intval($user_id).';');
	}
	
	/**
	 * Sends a request to the admin panel to have the username $u activated.
	 * @param string $u The username of the user requesting activation
	 */
	
	function admin_activation_request($u)
	{
		global $db;
		$this->sql('INSERT INTO '.table_prefix.'logs(log_type, action, time_id, date_string, author, edit_summary) VALUES(\'admin\', \'activ_req\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$this->username.'\', \''.$db->escape($u).'\');');
	}
	
	/**
	 * Activates a user account. If the action fails, a report is sent to the admin.
	 * @param string $user The username of the user requesting activation
	 * @param string $key The activation key
	 */
	
	function activate_account($user, $key)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		$q = $this->sql('SELECT 1 FROM ' . table_prefix . 'users WHERE username = \''.$db->escape($user).'\' AND activation_key = \''.$db->escape($key).'\'');
		if ( $db->numrows() > 0 )
		{
			$new_key = md5(AESCrypt::randkey());
			$this->sql('UPDATE ' . table_prefix . 'users SET account_active = 1, activation_key = \'' . $new_key . '\' WHERE username=\''.$db->escape($user).'\' AND activation_key=\''.$db->escape($key).'\';');
			$this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'activ_good\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($user).'\', \''.$_SERVER['REMOTE_ADDR'].'\')');
			return true;
		}
		else
		{
			$this->sql('INSERT INTO '.table_prefix.'logs(log_type,action,time_id,date_string,author,edit_summary) VALUES(\'security\', \'activ_bad\', '.time().', \''.enano_date(ED_DATE | ED_TIME).'\', \''.$db->escape($user).'\', \''.$_SERVER['REMOTE_ADDR'].'\')');
			return false;
		}
	}
	
	/**
	 * For a given user level identifier (USER_LEVEL_*), returns a string describing that user level.
	 * @param int User level
	 * @param bool If true, returns a shorter string. Optional.
	 * @return string
	 */
	
	function userlevel_to_string($user_level, $short = false)
	{
		global $lang;
		
		static $levels = array(
				'short' => array(
						USER_LEVEL_GUEST => 'Guest',
						USER_LEVEL_MEMBER => 'Member',
						USER_LEVEL_CHPREF => 'Sensitive preferences changeable',
						USER_LEVEL_MOD => 'Moderator',
						USER_LEVEL_ADMIN => 'Administrative'
					),
				'long' => array(
						USER_LEVEL_GUEST => 'Low - guest privileges',
						USER_LEVEL_MEMBER => 'Standard - normal member level',
						USER_LEVEL_CHPREF => 'Medium - user can change his/her own e-mail address and password',
						USER_LEVEL_MOD => 'High - moderator privileges',
						USER_LEVEL_ADMIN => 'Highest - administrative privileges'
					),
				'l10n' => false
			);
		
		if ( is_object($lang) && !$levels['l10n'] )
		{
			$levels = array(
					'short' => array(
							USER_LEVEL_GUEST => $lang->get('user_level_short_guest'),
							USER_LEVEL_MEMBER => $lang->get('user_level_short_member'),
							USER_LEVEL_CHPREF => $lang->get('user_level_short_chpref'),
							USER_LEVEL_MOD => $lang->get('user_level_short_mod'),
							USER_LEVEL_ADMIN => $lang->get('user_level_short_admin')
						),
					'long' => array(
							USER_LEVEL_GUEST => $lang->get('user_level_long_guest'),
							USER_LEVEL_MEMBER => $lang->get('user_level_long_member'),
							USER_LEVEL_CHPREF => $lang->get('user_level_long_chpref'),
							USER_LEVEL_MOD => $lang->get('user_level_long_mod'),
							USER_LEVEL_ADMIN => $lang->get('user_level_long_admin')
						),
					'l10n' => true
				);
		}
		
		$key = ( $short ) ? 'short' : 'long';
		if ( isset($levels[$key][$user_level]) )
		{
			return $levels[$key][$user_level];
		}
		else
		{
			if ( $short )
			{
				return ( is_object($lang) ) ? $lang->get('user_level_short_unknown', array('user_level' => $user_level)) : "Unknown - $user_level";
			}
			else
			{
				return ( is_object($lang) ) ? $lang->get('user_level_long_unknown', array('user_level' => $user_level)) : "Unknown level ($user_level)";
			}
		}
		
		return 'Linux rocks!';
		
	}
	
	/**
	 * Change a user's e-mail address.
	 * @param int $user_id The user ID of the user to update - this cannot be changed
	 * @param string $email The new e-mail address
	 * @return string 'success' if successful, or array of error strings on failure
	 */
	 
	function change_email($user_id, $email)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		
		// Create some arrays
		
		$errors = array(); // Used to hold error strings
		
		// Scan the user ID for problems
		if ( intval($user_id) < 1 )
			$errors[] = 'SQL injection attempt';
		
		$user_id = intval($user_id);
		
		// Verify e-mail address
		if ( !check_email_address($email) )
			$errors[] = 'user_err_email_not_valid';
		
		if ( count($errors) > 0 )
			return $errors;
		
		// Make query
		$email = $db->escape($email);
		$q = $db->sql_query('UPDATE ' . table_prefix . "users SET email = '$email' WHERE user_id = $user_id;");
		
		// We also need to trigger re-activation.
		switch(getConfig('account_activation', 'none'))
		{
			case 'user':
			case 'admin':
				
				// Note: even with admin activation, activation e-mails are sent when an e-mail is changed.
				
				if ( $session->user_level >= USER_LEVEL_MOD && getConfig('account_activation') == 'admin' )
					// Trust admins and moderators
					break;
				
				// retrieve username
				if ( !$username )
				{
					$q = $this->sql('SELECT username FROM ' . table_prefix . "users WHERE user_id = $user_id;");
					if($db->numrows() < 1)
					{
						$errors[] = 'The username could not be selected.';
					}
					else
					{
						$row = $db->fetchrow();
						$username = $row['username'];
					}
				}
				if ( !$username )
					return $errors;
				
				// Generate an activation key
				$actkey = sha1 ( microtime() . mt_rand() );
				$a = $this->send_activation_mail($username, $actkey);
				if(!$a)
				{
					$this->admin_activation_request($username);
				}
				// Deactivate the account until e-mail is confirmed
				$q = $db->sql_query('UPDATE ' . table_prefix . "users SET account_active = 0, activation_key = '$actkey' WHERE user_id = $user_id;");
				break;
		}
		
		// Yay! We're done
		return 'success';
	}
	
	/**
	 * Sets a user's password.
	 * @param int|string User ID or username
	 * @param string New password
	 */
	
	function set_password($user, $password)
	{
		// Generate new password and salt
		$hmac_secret = hexencode(AESCrypt::randkey(20), '', '');
		$password_hmac = hmac_sha1($password, $hmac_secret);
		
		// Figure out how we want to specify the user
		$uidcol = is_int($user) ? "user_id = $user" : ENANO_SQLFUNC_LOWERCASE . "(username) = '" . strtolower($this->prepare_text($user)) . "'";
		
		// Perform update
		$this->sql('UPDATE ' . table_prefix . "users SET old_encryption = 0, password = '$password_hmac', password_salt = '$hmac_secret' WHERE $uidcol;");
		
		return true;
	}
	
	/**
	 * Encrypts a string using the site's private key.
	 * @param string
	 * @param int Return type - one of ENC_BINARY, ENC_HEX, ENC_BASE64
	 * @return string
	 */
	
	function pk_encrypt($string, $return_type = ENC_HEX)
	{
		$aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
		return $aes->encrypt($string, $this->private_key, $return_type);
	}
	
	/**
	 * Encrypts a string using the site's private key.
	 * @param string
	 * @param int Input type - one of ENC_BINARY, ENC_HEX, ENC_BASE64
	 * @return string
	 */
	
	function pk_decrypt($string, $input_type = ENC_HEX)
	{
		$aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
		return $aes->decrypt($string, $this->private_key, $input_type);
	}
	
	#
	# USER RANKS
	#
	
	/**
	 * SYNOPSIS OF THE RANK SYSTEM
	 * Enano's rank logic calculates a user's rank based on a precedence scale. The way things are checked is:
	 *   1. Check to see if the user has a specific rank assigned. Use that if possible.
	 *   2. Check the user's primary group to see if it specifies a rank. Use that if possible.
	 *   3. Check the other groups a user is in. If one that has a custom rank is encountered, use that rank.
	 *   4. See if the user's user level has a specific rank hard-coded to be associated with it. (Always overrideable as can be seen above)
	 *   5. Use the "member" rank
	 */
	
	/**
	 * Generates a textual SQL query for fetching rank data to be sent to calculate_user_rank().
	 * @param string Text to append, possibly a WHERE clause or so
	 * @return string
	 */
	
	function generate_rank_sql($append = '')
	{
		// Generate level-to-rank associations
		$assoc = array();
		foreach ( $this->level_rank_table as $level => $rank )
		{
			$assoc[] = "        ( u.user_level = $level AND rl.rank_id = $rank )";
		}
		$assoc = implode(" OR\n", $assoc) . "\n";
		
		$gid_col = ( ENANO_DBLAYER == 'PGSQL' ) ?
			'array_to_string(' . table_prefix . 'array_accum(m.group_id), \',\') AS group_list' :
			'GROUP_CONCAT(m.group_id) AS group_list';
		
		// The actual query
		$sql = "SELECT u.user_id, u.username, u.user_level, u.user_group, u.user_rank, u.user_title, g.group_rank,\n"
	 			. "       COALESCE(ru.rank_id,    rg.rank_id,    rl.rank_id,    rd.rank_id   ) AS rank_id,\n"
	 			. "       COALESCE(ru.rank_title, rg.rank_title, rl.rank_title, rd.rank_title) AS rank_title,\n"
	 			. "       COALESCE(ru.rank_style, rg.rank_style, rl.rank_style, rd.rank_style) AS rank_style,\n"
	 			. "       rg.rank_id AS group_rank_id,\n"
	 			. "       ( ru.rank_id IS NULL AND rg.rank_id IS NULL ) AS using_default,\n"
	 			. "       ( ru.rank_id IS NULL AND rg.rank_id IS NOT NULL ) AS using_group,\n"
	 			. "       ( ru.rank_id IS NOT NULL ) AS using_user,\n"
	 			. "       u.user_rank_userset,\n"
	 			. "       $gid_col\n"
	 			. "  FROM " . table_prefix . "users AS u\n"
	 			. "  LEFT JOIN " . table_prefix . "groups AS g\n"
	 			. "    ON ( g.group_id = u.user_group )\n"
	 			. "  LEFT JOIN " . table_prefix . "group_members AS m\n"
	 			. "    ON ( u.user_id = m.user_id AND m.pending < 1 )\n"
	 			. "  LEFT JOIN " . table_prefix . "ranks AS ru\n"
	 			. "    ON ( u.user_rank = ru.rank_id )\n"
	 			. "  LEFT JOIN " . table_prefix . "ranks AS rg\n"
	 			. "    ON ( g.group_rank = rg.rank_id )\n"
	 			. "  LEFT JOIN " . table_prefix . "ranks AS rl\n"
	 			. "    ON (\n"
	 			. $assoc
	 			. "      )\n"
	 			. "  LEFT JOIN " . table_prefix . "ranks AS rd\n"
	 			. "    ON ( rd.rank_id = 1 )$append\n"
	 			. "  GROUP BY u.user_id, u.username, u.user_level, u.user_group, u.user_rank, u.user_title, u.user_rank_userset, g.group_rank,\n"
	 			. "       ru.rank_id, ru.rank_title, ru.rank_style,rg.rank_id, rg.rank_title, rg.rank_style,\n"
	 			. "       rl.rank_id, rl.rank_title, rl.rank_style,rd.rank_id, rd.rank_title, rd.rank_style;";
		
		return $sql;
	}
	
	/**
	 * Returns an associative array with a user's rank information.
	 * The array will contain the following values:
	 *   username: string  The user's username
	 *   user_id:  integer Numerical user ID
	 *   rank_id:  integer Numerical rank ID
	 *   rank:     string  The user's current rank
	 *   title:    string  The user's custom user title if applicable; should be displayed one line below the rank
	 *   style:    string  CSS for the username
	 * @param int|string Username *or* user ID
	 * @return array or false on failure
	 */
	
	function get_user_rank($id)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		global $lang;
		global $user_ranks;
		// cache info in RAM if possible
		static $_cache = array();
		
		if ( is_int($id) && $id == 0 )
			$id = 1;
		
		if ( is_int($id) )
			$col = "u.user_id = $id";
		else if ( is_string($id) )
			$col = ENANO_SQLFUNC_LOWERCASE . "(username) = " . ENANO_SQLFUNC_LOWERCASE . "('" . $db->escape($id) . "')";
		else
			// invalid parameter
			return false;
			
		// check the RAM cache
		if ( isset($_cache[$id]) )
			return $_cache[$id];
		
		// check the disk cache
		if ( is_int($id) )
		{
			if ( isset($user_ranks[$id]) )
			{
				$_cache[$id] =& $user_ranks[$id];
				return $user_ranks[$id];
			}
		}
		else if ( is_string($id) )
		{
			foreach ( $user_ranks as $key => $valarray )
			{
				if ( is_string($key) && strtolower($key) == strtolower($id) )
				{
					$_cache[$id] = $valarray;
					return $valarray;
				}
			}
		}
		
		$sql = $this->generate_rank_sql("\n  WHERE $col");
		
		$q = $this->sql($sql);
		// any results?
		if ( $db->numrows() < 1 )
		{
			// nuttin'.
			$db->free_result();
			$_cache[$id] = false;
			return false;
		}
		
		// Found something.
		$row = $db->fetchrow();
		$db->free_result();
		
		$row = $this->calculate_user_rank($row);
		
		$_cache[$id] = $row;
		return $row;
	}
	
	/**
	 * Performs the actual rank calculation based on the contents of a row.
	 * @param array
	 * @return array
	 */
	
	function calculate_user_rank($row)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		global $lang;
		
		static $rank_cache = array();
		static $group_ranks = array();
		
		// try to cache that rank info
		if ( !isset($rank_cache[ intval($row['rank_id']) ]) && $row['rank_id'] )
		{
			$rank_cache[ intval($row['rank_id']) ] = array(
					'rank_id' => intval($row['rank_id']),
					'rank_title' => intval($row['rank_title']),
					'rank_style' => intval($row['rank_style'])
				);
		}
		// cache group info (if appropriate)
		if ( $row['using_group'] && !isset($group_ranks[ intval($row['user_group']) ]) )
		{
			$group_ranks[ intval($row['user_group']) ] = intval($row['group_rank_id']);
		}
		
		// sanitize and process the as-of-yet rank data
		$row['rank_id'] = intval($row["rank_id"]);
		$row['rank_title'] = $row["rank_title"];
		
		// if we're falling back to some default, then see if we can use one of the user's other groups
		if ( $row['using_default'] && !empty($row['group_list']) )
		{
			$group_list = explode(',', $row['group_list']);
			if ( array_walk($group_list, 'intval') )
			{
				// go through the group list and see if any of them has a rank assigned
				foreach ( $group_list as $group_id )
				{
					// cached in RAM? Preferably use that.
					if ( !isset($group_ranks[$group_id]) )
					{
						// Not cached - grab it
						$q = $this->sql('SELECT group_rank FROM ' . table_prefix . "groups WHERE group_id = $group_id;");
						if ( $db->numrows() < 1 )
						{
							$db->free_result();
							continue;
						}
						list($result) = $db->fetchrow_num();
						$db->free_result();
						
						if ( $result === null || $result < 1 )
						{
							$group_ranks[$group_id] = false;
						}
						else
						{
							$group_ranks[$group_id] = intval($result);
						}
					}
					// we've got it now
					if ( $group_ranks[$group_id] )
					{
						// found a group with a rank assigned
						// so get the rank info
						$rank_id =& $group_ranks[$group_id];
						if ( !isset($rank_cache[$rank_id]) )
						{
							$q = $this->sql('SELECT rank_id, rank_title, rank_style FROM ' . table_prefix . "ranks WHERE rank_id = $rank_id;");
							if ( $db->numrows() < 1 )
							{
								$db->free_result();
								continue;
							}
							$rank_cache[$rank_id] = $db->fetchrow();
							$db->free_result();
						}
						// set the final rank parameters
						// die("found member-of-group exception with uid {$row['user_id']} gid $group_id rid $rank_id rt {$rank_cache[$rank_id]['rank_title']}");
						$row['rank_id'] = $rank_id;
						$row['rank_title'] = $rank_cache[$rank_id]['rank_title'];
						$row['rank_style'] = $rank_cache[$rank_id]['rank_style'];
						break;
					}
				}
			}
		}
		
		if ( $row['user_title'] === NULL )
			$row['user_title'] = false;
		
		$row['user_id'] = intval($row['user_id']);
		$row['user_level'] = intval($row['user_level']);
		$row['user_group'] = intval($row['user_group']);
		
		unset($row['user_rank'], $row['group_rank'], $row['group_list'], $row['using_default'], $row['using_group'], $row['user_level'], $row['user_group'], $row['username']);
		return $row;
	}
	
	/**
	 * Get the list of ranks that a user is allowed to use. Returns false if they cannot change it.
	 * @param string|int User ID or username
	 * @return array Associative by rank ID
	 */
	
	function get_user_possible_ranks($id)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		
		// cache info in RAM if possible
		static $_cache = array();
		
		if ( is_int($id) && $id == 0 )
			$id = 1;
		
		if ( is_int($id) )
			$col = "u.user_id = $id";
		else if ( is_string($id) )
			$col = ENANO_SQLFUNC_LOWERCASE . "(username) = " . ENANO_SQLFUNC_LOWERCASE . "('" . $db->escape($id) . "')";
		else
			// invalid parameter
			return false;
			
		// check the RAM cache
		if ( isset($_cache[$id]) )
			return $_cache[$id];
		
		$sql = $this->generate_rank_sql("\n  WHERE $col");
		
		$q = $this->sql($sql);
		// any results?
		if ( $db->numrows() < 1 )
		{
			// nuttin'.
			$db->free_result();
			$_cache[$id] = false;
			return false;
		}
		
		// Found something.
		$row = $db->fetchrow();
		$db->free_result();
		
		if ( $row['using_user'] && !$row['user_rank_userset'] )
		{
			// The user's rank was set manually by an admin.
			$result = array(
				array(
					'rank_id' => $row['rank_id'],
					'rank_title' => $row['rank_title'],
					'rank_style' => $row['rank_style'],
					'rank_type' => 'user'
					)
				);
			$_cache[$id] = $result;
			return $result;
		}
		
		// copy the result to a more permanent array so we can reference this later
		$current_settings = $row;
		unset($row);
		
		$result = array();
		
		// first rank available to us will be the one set by the user's user level
		if ( isset($this->level_rank_table[$current_settings['user_level']]) )
		{
			$q = $this->sql('SELECT rank_id, rank_title, rank_style FROM ' . table_prefix . "ranks WHERE rank_id = {$this->level_rank_table[$this->user_level]};");
			if ( $db->numrows() > 0 )
			{
				$row = $db->fetchrow();
				$row['rank_type'] = 'ulevel';
				
				$result[] = $row;
			}
			$db->free_result();
		}
		
		// for each group the user is in, figure out if it has a rank associated with it
		$group_list = explode(',', $current_settings['group_list']);
		foreach ( $group_list as $group_id )
		{
			$group_id = intval($group_id);
			$q = $this->sql('SELECT r.rank_id, r.rank_title, r.rank_style FROM ' . table_prefix . "groups AS g\n"
										. "  LEFT JOIN " . table_prefix . "ranks AS r\n"
										. "    ON ( g.group_rank = r.rank_id )\n"
										. "  WHERE g.group_id = $group_id\n"
										. "    AND r.rank_id IS NOT NULL;");
			if ( $db->numrows() > 0 )
			{
				$row = $db->fetchrow();
				$row['rank_type'] = 'group';
				
				$result[] = $row;
			}
			$db->free_result();
		}
		
		$_cache[$id] = $result;
		return $result;
	}
	
	#
	# Access Control Lists
	#
	
	/**
	 * Creates a new permission field in memory. If the permissions are set in the database, they are used. Otherwise, $default_perm is used.
	 * @param string $acl_type An identifier for this field
	 * @param int $default_perm Whether permission should be granted or not if it's not specified in the ACLs.
	 * @param string $desc A human readable name for the permission type
	 * @param array $deps The list of dependencies - this should be an array of ACL types
	 * @param string $scope Which namespaces this field should apply to. This should be either a pipe-delimited list of namespace IDs or just "All".
	 */
	 
	function register_acl_type($acl_type, $default_perm = AUTH_DISALLOW, $desc = false, $deps = Array(), $scope = 'All')
	{
		if(isset($this->acl_types[$acl_type]))
			return false;
		else
		{
			if(!$desc)
			{
				$desc = ucfirst(str_replace('_', ' ', $acl_type));
			}
			$this->acl_types[$acl_type] = $default_perm;
			$this->acl_descs[$acl_type] = $desc;
			$this->acl_deps[$acl_type] = $deps;
			$this->acl_scope[$acl_type] = explode('|', $scope);
		}
		return true;
	}
	
	/**
	 * Tells us whether permission $type is allowed or not based on the current rules.
	 * @param string $type The permission identifier ($acl_type passed to sessionManager::register_acl_type())
	 * @param bool $no_deps If true, disables dependency checking
	 * @return bool True if allowed, false if denied or if an error occured
	 */
	 
	function get_permissions($type, $no_deps = false)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		if ( isset( $this->perms[$type] ) )
		{
			if ( $this->perms[$type] == AUTH_DENY )
				$ret = false;
			else if ( $this->perms[$type] == AUTH_WIKIMODE && $paths->wiki_mode )
				$ret = true;
			else if ( $this->perms[$type] == AUTH_WIKIMODE && !$paths->wiki_mode )
				$ret = false;
			else if ( $this->perms[$type] == AUTH_ALLOW )
				$ret = true;
			else if ( $this->perms[$type] == AUTH_DISALLOW )
				$ret = false;
		}
		else if(isset($this->acl_types[$type]))
		{
			if ( $this->acl_types[$type] == AUTH_DENY )
				$ret = false;
			else if ( $this->acl_types[$type] == AUTH_WIKIMODE && $paths->wiki_mode )
				$ret = true;
			else if ( $this->acl_types[$type] == AUTH_WIKIMODE && !$paths->wiki_mode )
				$ret = false;
			else if ( $this->acl_types[$type] == AUTH_ALLOW )
				$ret = true;
			else if ( $this->acl_types[$type] == AUTH_DISALLOW )
				$ret = false;
		}
		else
		{
			// ACL type is undefined
			trigger_error('Unknown access type "' . $type . '"', E_USER_WARNING);
			return false; // Be on the safe side and deny access
		}
		if ( !$no_deps )
		{
			if ( !$this->acl_check_deps($type) )
				return false;
		}
		return $ret;
	}
	
	/**
	 * Fetch the permissions that apply to the current user for the page specified. The object you get will have the get_permissions method
	 * and several other abilities.
	 * @param string $page_id
	 * @param string $namespace
	 * @return object
	 */
	 
	function fetch_page_acl($page_id, $namespace)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		
		if ( count ( $this->acl_base_cache ) < 1 )
		{
			// Permissions table not yet initialized
			return false;
		}
		
		// cache of permission objects (to save RAM and SQL queries)
		static $objcache = array();
		
		if ( count($objcache) == 0 )
		{
			foreach ( $paths->nslist as $key => $_ )
			{
				$objcache[$key] = array();
			}
		}
		
		if ( isset($objcache[$namespace][$page_id]) )
		{
			return $objcache[$namespace][$page_id];
		}
		
		$objcache[$namespace][$page_id] = new Session_ACLPageInfo( $page_id, $namespace, $this->acl_types, $this->acl_descs, $this->acl_deps, $this->acl_base_cache );
		$object =& $objcache[$namespace][$page_id];
		
		profiler_log("session: fetched ACLs for page {$namespace}:{$page_id}");
		
		return $object;
	}
	
	/**
	 * Fetch the permissions that apply to an arbitrary user for the page specified. The object you get will have the get_permissions method
	 * and several other abilities.
	 * @param int|string $user_id_or_name; user ID *or* username of the user
	 * @param string $page_id; if null, will be default effective permissions. 
	 * @param string $namespace; if null, will be default effective permissions.
	 * @return object
	 */
	
	function fetch_page_acl_user($user_id_or_name, $page_id, $namespace)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		
		// cache user info
		static $user_info_cache = null;
		
		if ( isset($user_info_cache[$user_id_or_name]) )
		{
			$user_id =& $user_info_cache[$user_id_or_name]['user_id'];
			$groups =& $user_info_cache[$user_id_or_name]['groups'];
		}
		else
		{
			$uid_column = ( is_int($user_id_or_name) ) ? "user_id = $user_id_or_name" : "username = '" . $db->escape($user_id_or_name) . "'";
			$q = $db->sql_query('SELECT u.user_id, m.group_id, g.group_name FROM ' . table_prefix . "users AS u\n"
												. "  LEFT JOIN " . table_prefix . "group_members AS m\n"
												. "    ON ( ( u.user_id = m.user_id AND m.pending = 0 ) OR m.member_id IS NULL )\n"
												. "  LEFT JOIN " . table_prefix . "groups AS g\n"
												. "    ON ( g.group_id = m.group_id )\n"
												. "  WHERE $uid_column;");
			if ( !$q )
				$db->_die();
			
			// The l10n engine takes care of this later.
			$groups = array(1 => 'Everyone');
			
			if ( $row = $db->fetchrow() )
			{
				$user_id = intval($row['user_id']);
				if ( $row['group_id'] )
				{
					do
					{
						$groups[ intval($row['group_id'] ) ] = $row['group_name'];
					}
					while ( $row = $db->fetchrow() );
				}
				$db->free_result();
			}
			else
			{
				$db->free_result();
				throw new Exception('Unknown user ID or username');
			}
			
			$user_info_cache[$user_id_or_name] = array(
					'user_id' => $user_id,
					'groups' => $groups
				);
		}
		
		// cache base permissions
		static $base_cache = array();
		if ( !isset($base_cache[$user_id_or_name]) )
		{
			$base_cache[$user_id_or_name] = $this->acl_types;
			$current_perms =& $base_cache[$user_id_or_name];
			$current_perms['__resolve_table'] = array();
			
			$bs = 'SELECT rules, target_type, target_id, rule_id, page_id, namespace, g.group_name FROM '.table_prefix."acl AS a\n"
					. "  LEFT JOIN " . table_prefix . "groups AS g\n"
					. "    ON ( ( a.target_type = " . ACL_TYPE_GROUP . " AND a.target_id = g.group_id ) OR ( a.target_type != " . ACL_TYPE_GROUP . " ) )\n"
					. '  WHERE page_id IS NULL AND namespace IS NULL AND' . "\n"
					. '  ( ';
		
			$q = Array();
			$q[] = '( target_type='.ACL_TYPE_USER.' AND target_id= ' . $user_id . ' )';
			if(count($groups) > 0)
			{
				foreach($groups as $g_id => $g_name)
				{
					$q[] = '( target_type='.ACL_TYPE_GROUP.' AND target_id='.intval($g_id).' )';
				}
			}
			$bs .= implode(" OR \n    ", $q) . " ) \n  ORDER BY target_type ASC, target_id ASC;";
			$q = $this->sql($bs);
			foreach ( $this->acl_types as $perm_type => $_ )
			{
				// init the resolver table with blanks
				$current_perms['__resolve_table'][$perm_type] = array(
						'src' => ACL_INHERIT_ENANO_DEFAULT,
						'rule_id' => -1
					);
			}
			if ( $row = $db->fetchrow() )
			{
				do {
					$rules = $this->string_to_perm($row['rules']);
					$is_everyone = ( $row['target_type'] == ACL_TYPE_GROUP && $row['target_id'] == 1 );
					// track where these rulings are coming from
					$src = ( $is_everyone ) ? ACL_INHERIT_GLOBAL_EVERYONE : ( $row['target_type'] == ACL_TYPE_GROUP ? ACL_INHERIT_GLOBAL_GROUP : ACL_INHERIT_GLOBAL_USER );
					foreach ( $rules as $perm_type => $_ )
					{
						$current_perms['__resolve_table'][$perm_type] = array(
								'src' => $src,
								'rule_id' => $row['rule_id']
							);
						if ( $row['group_name'] )
						{
							$current_perms['__resolve_table'][$perm_type]['group_name'] = $row['group_name'];
						}
					}
					// merge it in
					$current_perms = $this->acl_merge($current_perms, $rules, $is_everyone, $_defaults_used);
				} while ( $row = $db->fetchrow() );
			}
		}
		
		// cache of permission objects (to save RAM and SQL queries)
		static $objcache = array();
		
		if ( count($objcache) == 0 )
		{
			foreach ( $paths->nslist as $key => $_ )
			{
				$objcache[$key] = array();
			}
		}
		
		if ( !isset($objcache[$namespace][$page_id]) )
		{
			$objcache[$namespace][$page_id] = array();
		}
		
		if ( isset($objcache[$namespace][$page_id][$user_id_or_name]) )
		{
			return $objcache[$namespace][$page_id][$user_id_or_name];
		}
		
		//if ( !isset( $paths->pages[$paths->nslist[$namespace] . $page_id] ) )
		//{
		//  // Page does not exist
		//  return false;
		//}
		
		$objcache[$namespace][$page_id][$user_id_or_name] = new Session_ACLPageInfo(
			$page_id,                                        // $page_id, 
			$namespace,                                      // $namespace,
			$this->acl_types,                                // $acl_types,
			$this->acl_descs,                                // $acl_descs,
			$this->acl_deps,                                 // $acl_deps,
			$base_cache[$user_id_or_name],                   // $base,
			$user_info_cache[$user_id_or_name]['user_id'],   // $user_id = null,
			$user_info_cache[$user_id_or_name]['groups'],    // $groups = null,
			$base_cache[$user_id_or_name]['__resolve_table'] // $resolve_table = array()
		);
		$object =& $objcache[$namespace][$page_id][$user_id_or_name];
		
		return $object;
	}
	
	/**
	 * Checks if the given ACL rule type applies to a namespace.
	 * @param string ACL rule type
	 * @param string Namespace
	 * @return bool
	 */
	
	function check_acl_scope($acl_rule, $namespace)
	{
		if ( !isset($this->acl_scope[$acl_rule]) )
			return false;
		if ( $this->acl_scope[$acl_rule] === array('All') )
			return true;
		return ( in_array($namespace, $this->acl_scope[$acl_rule]) ) ? true : false;
	}
	
	/**
	 * Read all of our permissions from the database and process/apply them. This should be called after the page is determined.
	 * @access private
	 */
	
	function init_permissions()
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		// Initialize the permissions list with some defaults
		$this->perms = $this->acl_types;
		$this->acl_defaults_used = $this->perms;
		
		// Fetch sitewide defaults from the permissions table
		$bs = 'SELECT rules, target_type, target_id FROM '.table_prefix.'acl' . "\n"
	 					. '  WHERE page_id IS NULL AND namespace IS NULL AND' . "\n"
	 					. '  ( ';
		
		$q = Array();
		$q[] = '( target_type='.ACL_TYPE_USER.' AND target_id='.$this->user_id.' )';
		if(count($this->groups) > 0)
		{
			foreach($this->groups as $g_id => $g_name)
			{
				$q[] = '( target_type='.ACL_TYPE_GROUP.' AND target_id='.intval($g_id).' )';
			}
		}
		$bs .= implode(" OR \n    ", $q) . " ) \n  ORDER BY target_type ASC, target_id ASC;";
		$q = $this->sql($bs);
		if ( $row = $db->fetchrow() )
		{
			do {
				$rules = $this->string_to_perm($row['rules']);
				$is_everyone = ( $row['target_type'] == ACL_TYPE_GROUP && $row['target_id'] == 1 );
				$this->acl_merge_with_current($rules, $is_everyone);
			} while ( $row = $db->fetchrow() );
		}
		
		// Cache the sitewide permissions for later use
		$this->acl_base_cache = $this->perms;
		
		profiler_log('session: base ACL set calculated');
		
		// Load and calculate permissions for the current page
		$page_acl = $this->fetch_page_acl($paths->page_id, $paths->namespace);
		$this->perms = $page_acl->perms;
		$this->acl_defaults_used = $page_acl->acl_defaults_used;
	}
	
	/**
	 * Extends the scope of a permission type.
	 * @param string The name of the permission type
	 * @param string The namespace(s) that should be covered. This can be either one namespace ID or a pipe-delimited list.
	 * @param object Optional - the current $paths object, in case we're doing this from the acl_rule_init hook
	 */
	 
	function acl_extend_scope($perm_type, $namespaces, &$p_in)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		$p_obj = ( is_object($p_in) ) ? $p_in : $paths;
		$nslist = explode('|', $namespaces);
		foreach ( $nslist as $i => $ns )
		{
			if ( !isset($p_obj->nslist[$ns]) )
			{
				unset($nslist[$i]);
			}
			else
			{
				if ( $this->acl_scope[$perm_type] !== array('All') )
					$this->acl_scope[$perm_type][] = $ns;
				if ( isset($this->acl_types[$perm_type]) && !isset($this->perms[$perm_type]) )
				{
					$this->perms[$perm_type] = $this->acl_types[$perm_type];
				}
			}
		}
	}
	
	/**
	 * Converts a permissions field into a string for database insertion. Similar in spirit to serialize().
	 * @param array $perms An associative array with only integers as values
	 * @return string
	 */
	 
	function perm_to_string($perms)
	{
		$s = '';
		foreach($perms as $perm => $ac)
		{
			if ( $ac == 'i' )
				continue;
			$s .= "$perm=$ac;";
		}
		return $s;
	}
	
	/**
	 * Converts a permissions string back to an array.
	 * @param string $perms The result from sessionManager::perm_to_string()
	 * @return array
	 */
	 
	function string_to_perm($perms)
	{
		$ret = Array();
		preg_match_all('#([a-z0-9_-]+)=([0-9]+);#i', $perms, $matches);
		foreach($matches[1] as $i => $t)
		{
			$ret[$t] = intval($matches[2][$i]);
		}
		return $ret;
	}
	
	/**
	 * Merges two ACL arrays. Both parameters should be permission list arrays. The second group takes precedence over the first, but AUTH_DENY always prevails.
	 * @param array $perm1 The first set of permissions
	 * @param array $perm2 The second set of permissions
	 * @param bool $is_everyone If true, applies exceptions for "Everyone" group
	 * @param array|reference $defaults_used Array that will be filled with default usage data
	 * @return array
	 */
	 
	function acl_merge($perm1, $perm2, $is_everyone = false, &$defaults_used = array())
	{
		$ret = $perm1;
		if ( !is_array(@$defaults_used) )
		{
			$defaults_used = array();
		}
		foreach ( $perm1 as $i => $p )
		{
			if ( isset($perm2[$i]) )
			{
				if ( $is_everyone && isset($defaults_used[$i]) && $defaults_used[$i] === false )
					continue;
				// Decide precedence
				if ( isset($defaults_used[$i]) )
				{
					// echo "$i: default in use, overriding to: {$perm2[$i]}<br />";
					// Defaults are in use, override
					
					// CHANGED - 1.1.4:
					// For some time this has been intentionally relaxed so that the following
					// exception is available to Deny permissions:
					//   If the rule applies to the group "Everyone" on the entire site,
					//   Deny settings could be overriden.
					// This is documented at: http://docs.enanocms.org/Help:4.2
					if ( $perm1[$i] != AUTH_DENY )
					{
						$perm1[$i] = $perm2[$i];
						$defaults_used[$i] = ( $is_everyone );
					}
				}
				else
				{
					// echo "$i: default NOT in use";
					// Defaults are not in use, merge as normal
					if ( $perm1[$i] != AUTH_DENY )
					{
						// echo ", but overriding";
						$perm1[$i] = $perm2[$i];
					}
					// echo "<br />";
				}
			}
		}
		return $perm1;
	}
	
	/**
	 * Merges two ACL arrays, but instead of calculating inheritance for missing permission types, just returns 'i' for that type. Useful
	 * for explicitly requiring inheritance in ACL editing interfaces
	 * @param array $perm1 The first set of permissions
	 * @param array $perm2 The second, authoritative set of permissions
	 */
	
	function acl_merge_inherit($perm1, $perm2)
	{
		foreach ( $perm1 as $type => $level )
		{
			$perm1[$type][$level] = 'i';
		}
		$ret = $perm1;
		foreach ( $perm2 as $type => $level )
		{
			if ( isset( $ret[$type] ) )
			{
				if ( $ret[$type] != AUTH_DENY )
					$ret[$type] = $level;
			}
		}
		return $ret;
	}
	
	/**
	 * Merges the ACL array sent with the current permissions table, deciding precedence based on whether defaults are in effect or not.
	 * @param array The array to merge into the master ACL list
	 * @param bool If true, $perm is treated as the "new default"
	 * @param int 1 if this is a site-wide ACL, 2 if page-specific. Defaults to 2.
	 */
	
	function acl_merge_with_current($perm, $is_everyone = false, $scope = 2)
	{
		$this->perms = $this->acl_merge($this->perms, $perm, $is_everyone, $this->acl_defaults_used);
	}
	
	/**
	 * Merges two ACL arrays. Both parameters should be permission list arrays. The second group takes precedence
	 * over the first, without exceptions. This is used to merge the hardcoded defaults with admin-specified
	 * defaults, which take precedence.
	 * @param array $perm1 The first set of permissions
	 * @param array $perm2 The second set of permissions
	 * @return array
	 */
	 
	function acl_merge_complete($perm1, $perm2)
	{
		$ret = $perm1;
		foreach ( $perm2 as $type => $level )
		{
			$ret[$type] = $level;
		}
		return $ret;
	}
	
	/**
	 * Tell us if the dependencies for a given permission are met.
	 * @param string The ACL permission ID
	 * @return bool
	 */
	 
	function acl_check_deps($type, $debug = false)
	{
		global $paths;
		
		// This will only happen if the permissions table is hacked or improperly accessed
		if(!isset($this->acl_deps[$type]))
			return true;
		// Permission has no dependencies?
		if(sizeof($this->acl_deps[$type]) < 1)
			return true;
		// go through them all and build a flat list of dependencies
		$deps = $this->acl_deps[$type];
		while(true)
		{
			$j = sizeof($deps);
			for ( $i = 0; $i < $j; $i++ )
			{
				$b = $deps;
				if ( !$this->check_acl_scope($deps[$i], $paths->namespace) )
				{
					// Action $type depends on action $deps[$i] which cannot be satisfied because $deps[$i] is out of scope.
					// echo '<pre>' . enano_debug_print_backtrace(true) . '</pre>';
					trigger_error("acl_check_deps: $type depends on {$deps[$i]} which is not within scope of $paths->namespace; this indicates a bug in ACL rule specification. Backtrace:<pre>" . htmlspecialchars(enano_debug_print_backtrace(true)) . "</pre>", E_USER_WARNING);
					return false;
				}
				$deps = array_merge($deps, $this->acl_deps[$deps[$i]]);
				if( $b == $deps )
				{
					break 2;
				}
				$j = sizeof($deps);
			}
		}
		$debugdata = array();
		foreach($deps as $d)
		{
			// Our dependencies are fully resolved, so tell get_permissions() to not recursively call this function
			if ( !$this->get_permissions($d, true) )
			{
				if ( $debug )
				{
					$debugdata[] = $d;
				}
				else
				{
					return false;
				}
			}
		}
		return $debug ? $debugdata : true;
	}
	
	/**
	 * Makes a CAPTCHA code and caches the code in the database
	 * @param int $len The length of the code, in bytes
	 * @param string Optional, the hash to reuse
	 * @return string A unique identifier assigned to the code. This hash should be passed to sessionManager::getCaptcha() to retrieve the code.
	 */
	
	function make_captcha($len = 7, $hash = '')
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		$code = $this->generate_captcha_code($len);
		if ( !preg_match('/^[a-f0-9]{32}([a-z0-9]{8})?$/', $hash) )
			$hash = md5(microtime() . mt_rand());
		$session_data = $db->escape(serialize(array()));
		
		// sanity check
		if ( !is_valid_ip(@$_SERVER['REMOTE_ADDR']) || !is_int($this->user_id) )
			return false;
		
		$this->sql('DELETE FROM ' . table_prefix . "captcha WHERE session_id = '$hash';");
		$this->sql('INSERT INTO ' . table_prefix . 'captcha(session_id, code, session_data, source_ip, user_id)' . " VALUES('$hash', '$code', '$session_data', '{$_SERVER['REMOTE_ADDR']}', {$this->user_id});");
		return $hash;
	}
	
	/**
	 * Generates a "pronouncable" or "human-friendly" word using various phonics rules
	 * @param int Optional. The length of the word.
	 * @return string
	 */
	
	function generate_captcha_code($len = 7)
	{
		// don't use k and x, they get mixed up a lot
		$consonants = 'bcdfghmnpqrsvwyz';
		$vowels = 'aeiou';
		$prev = 'vowel';
		$prev_l = '';
		$word = '';
		$allow_next_vowel = true;
		for ( $i = 0; $i < $len; $i++ )
		{
			if ( $prev == 'vowel' )
			{
				$allow_next_vowel = false;
				if ( $prev_l == 'o' && mt_rand(0, 3) == 3 && $allow_next_vowel )
					$word .= 'i';
				else if ( $prev_l == 'q' && mt_rand(0, 3) != 1 && $allow_next_vowel )
					$word .= 'u';
				else if ( $prev_l == 'o' && mt_rand(0, 3) == 2 && $allow_next_vowel )
					$word .= 'u';
				else if ( $prev_l == 'a' && mt_rand(0, 3) == 3 && $allow_next_vowel )
					$word .= 'i';
				else if ( $prev_l == 'a' && mt_rand(0, 10) == 7 && $allow_next_vowel )
					$word .= 'o';
				else if ( $prev_l == 'a' && mt_rand(0, 7) == 2 && $allow_next_vowel )
					$word .= 'u';
				else
				{
					$allow_next_vowel = true;
					$word .= $consonants{mt_rand(0, (strlen($consonants)-1))};
				}
			}
			else if ( $prev == 'consonant' )
			{
				if ( $prev_l == 'p' && mt_rand(0, 7) == 4 )
					$word .= 't';
				else if ( $prev_l == 'p' && mt_rand(0, 5) == 1 )
					$word .= 'h';
				// this rule allows "ck" which can result in the occasional "dick", "fuck", etc. that tends
				// to end up on /r/funny, but I decided to keep it, because it increases word complexity.
				else if ( $prev_l == 'c' && mt_rand(0, 3) == 1 )
					$word .= 'k';
				else if ( $prev_l == 'q' && mt_rand(0, 5) != 1 )
					$word .= 'u';
				else
					$word .= $vowels{mt_rand(0, (strlen($vowels)-1))};
			}
			$prev_l = substr($word, -1);
			$l = ( mt_rand(0, 1) == 1 ) ? strtoupper($prev_l) : strtolower($prev_l);
			$word = substr($word, 0, -1) . $l;
			if ( strstr('aeiou', $prev_l) )
				$prev = 'vowel';
			else
				$prev = 'consonant';
		}
		return $word;
	}
	
	/**
	 * For the given code ID, returns the correct CAPTCHA code, or false on failure
	 * @param string $hash The unique ID assigned to the code
	 * @param bool If true, the code is NOT deleted from the database. Use with caution!
	 * @return string The correct confirmation code
	 */
	
	function get_captcha($hash, $nodelete = false)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		
		if ( !preg_match('/^[a-f0-9]{32}([a-z0-9]{8})?$/', $hash) )
		{
			die("session manager: bad captcha_hash $hash");
			return false;
		}
		
		// sanity check
		if ( !is_valid_ip(@$_SERVER['REMOTE_ADDR']) )
		{
			die("session manager insanity: bad REMOTE_ADDR or invalid UID");
			return false;
		}
		
		$q = $this->sql('SELECT code_id, code FROM ' . table_prefix . "captcha WHERE session_id = '$hash' AND source_ip = '{$_SERVER['REMOTE_ADDR']}';");
		if ( $db->numrows() < 1 )
		{
			return false;
		}
		
		list($code_id, $code) = $db->fetchrow_num();
		
		$db->free_result();
		
		// delete it
		if ( !$nodelete )
			$this->sql('DELETE FROM ' . table_prefix . "captcha WHERE code_id = $code_id;");
		
		return $code;
	}
	
	/**
	 * (AS OF 1.0.2: Deprecated. Captcha codes are now killed on first fetch for security.) Deletes all CAPTCHA codes cached in the DB for this user.
	 */
	
	function kill_captcha()
	{
		return true;
	}
	
	/**
	 * Generates a random password.
	 * @param int $length Optional - length of password
	 * @return string
	 */
	 
	function random_pass($length = 10)
	{
		$valid_chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_+@#%&<>';
		$valid_chars = enano_str_split($valid_chars);
		$ret = '';
		for ( $i = 0; $i < $length; $i++ )
		{
			$ret .= $valid_chars[mt_rand(0, count($valid_chars)-1)];
		}
		return $ret;
	}
	
	/**
	 * Generates some Javascript that calls the AES encryption library. Put this after your </form>.
	 * @param string The name of the form
	 * @param string The name of the password field
	 * @param string The name of the field that switches encryption on or off
	 * @param string The name of the field that contains the encryption key
	 * @param string The name of the field that will contain the encrypted password
	 * @param string The name of the field that handles MD5 challenge data
	 * @param string The name of the field that tells if the server supports DiffieHellman
	 * @param string The name of the field with the DiffieHellman public key
	 * @param string The name of the field that the client should populate with its public key
	 * @return string
	 */
	 
	static function aes_javascript($form_name, $pw_field, $use_crypt = 'use_crypt', $crypt_key = 'crypt_key', $crypt_data = 'crypt_data', $challenge = 'challenge_data', $dh_supported = 'dh_supported', $dh_pubkey = 'dh_public_key', $dh_client_pubkey = 'dh_client_public_key')
	{
		$code = '
			<script type="text/javascript">
					
					function runEncryption(nowhiteout)
					{
						var frm = document.forms.'.$form_name.';
						if ( !nowhiteout )
							whiteOutForm(frm);
						
						load_component(\'crypto\');
						var testpassed = ' . ( ( isset($_GET['use_crypt']) && $_GET['use_crypt']=='0') ? 'false; // CRYPTO-AUTH DISABLED ON USER REQUEST // ' : '' ) . '( aes_self_test() && md5_vm_test() );
						var use_diffiehellman = false;' . "\n";
		if ( $dh_supported && $dh_pubkey )
		{
			$code .= <<<EOF
						if ( frm.$dh_supported.value == 'true' && !is_iPhone )
							use_diffiehellman = true;
EOF;
		}
		$code .= '
		
						if ( frm[\'' . $dh_supported . '\'] )
						{
							frm[\'' . $dh_supported . '\'].value = ( use_diffiehellman ) ? "true" : "false";
						}
						
						if ( frm["' . $pw_field . '_confirm"] )
						{
							pass1 = frm.' . $pw_field . '.value;
							pass2 = frm.' . $pw_field . '_confirm.value;
							if ( pass1 != pass2 )
							{
								load_component("l10n");
								alert($lang.get("userfuncs_passreset_err_no_match"));
								return false;
							}
							if ( pass1.length < 6 )
							{
								load_component("l10n");
								alert($lang.get("userfuncs_passreset_err_too_short"));
								return false;
							}
							frm.' . $pw_field . '_confirm.value = "";
						}
						
						if ( testpassed && use_diffiehellman )
						{
							// try to blank out the table to prevent double submits and what have you
							var el = frm.' . $pw_field . ';
							while ( el.tagName != "BODY" && el.tagName != "TABLE" )
							{
								el = el.parentNode;
							}
							/*
							if ( el.tagName == "TABLE" )
							{
								whiteOutElement(el);
							}
							*/
							
							frm.'.$use_crypt.'.value = \'yes_dh\';
							
							// Perform Diffie Hellman stuff
							console.info("DiffieHellman: started keygen process");
							var dh_priv = dh_gen_private();
							var dh_pub = dh_gen_public(dh_priv);
							var secret = dh_gen_shared_secret(dh_priv, frm.' . $dh_pubkey . '.value);
							console.info("DiffieHellman: finished keygen process");
							
							// secret_hash is used to verify that the server guesses the correct secret
							var secret_hash = hex_sha1(secret);
							
							// give the server our values
							frm.' . $crypt_key . '.value = secret_hash;
							' . ( $dh_supported ? 'frm.' . $dh_client_pubkey . '.value = dh_pub;' : '' ) . '
							
							// console.info("DiffieHellman: set public values");
							
							// crypt_key is the actual AES key
							var crypt_key = (hex_sha256(secret)).substr(0, (keySizeInBits / 4));
							
							// Perform encryption
							crypt_key = hexToByteArray(crypt_key);
							var pass = frm.'.$pw_field.'.value;
							pass = stringToByteArray(pass);
							var cryptstring = rijndaelEncrypt(pass, crypt_key, \'ECB\');
							if(!cryptstring)
							{
								return false;
							}
							cryptstring = byteArrayToHex(cryptstring);
							console.info("DiffieHellman: finished AES. Result: " + cryptstring);
							console.debug(frm);
							frm.'.$crypt_data.'.value = cryptstring;
							frm.'.$pw_field.'.value = \'\';
							// console.info("DiffieHellman: ready to submit");
						}
						else if ( testpassed && !use_diffiehellman )
						{
							frm.'.$use_crypt.'.value = \'yes\';
							var cryptkey = frm.'.$crypt_key.'.value;
							frm.'.$crypt_key.'.value = hex_md5(cryptkey);
							cryptkey = hexToByteArray(cryptkey);
							if(!cryptkey || ( ( typeof cryptkey == \'string\' || typeof cryptkey == \'object\' ) ) && cryptkey.length != keySizeInBits / 8 )
							{
								if ( frm._login ) frm._login.disabled = true;
								len = ( typeof cryptkey == \'string\' || typeof cryptkey == \'object\' ) ? \'\\nLen: \'+cryptkey.length : \'\';
								alert(\'The key is messed up\\nType: \'+typeof(cryptkey)+len);
							}
							pass = frm.'.$pw_field.'.value;
							chal = frm.'.$challenge.'.value;
							challenge = hex_md5(pass + chal) + chal;
							frm.'.$challenge.'.value = challenge;
							pass = stringToByteArray(pass);
							cryptstring = rijndaelEncrypt(pass, cryptkey, \'ECB\');
							if(!cryptstring)
							{
								return false;
							}
							cryptstring = byteArrayToHex(cryptstring);
							frm.'.$crypt_data.'.value = cryptstring;
							frm.'.$pw_field.'.value = \'\';
						}
					}
				</script>
				';
		return $code;
	}
	
	/**
	 * Generates the HTML form elements required for an encrypted logon experience.
	 * @param reference Optional variable to fill with the server's public and private key. If IN_ENANO_INSTALL is defined, storing and retrieving the key
	 *                  is YOUR responsibility.
	 * @return string
	 */
	
	function generate_aes_form(&$dh_store = array())
	{
		$aes_key = self::rijndael_genkey();
		$dh_store = array('aes' => $aes_key, 'public' => '', 'private' => '');
		
		$return = '<input type="hidden" name="use_crypt" value="no" />';
		$return .= '<input type="hidden" name="crypt_key" value="' . $aes_key . '" />';
		$return .= '<input type="hidden" name="crypt_data" value="" />';
		$return .= '<input type="hidden" name="challenge_data" value="' . self::dss_rand() . '" />';
		
		require_once(ENANO_ROOT . '/includes/math.php');
		require_once(ENANO_ROOT . '/includes/diffiehellman.php');
		
		global $dh_supported, $_math;
		if ( $dh_supported )
		{
			$dh_key_priv = dh_gen_private();
			$dh_key_pub = dh_gen_public($dh_key_priv);
			$dh_key_priv = $_math->str($dh_key_priv);
			$dh_key_pub = $_math->str($dh_key_pub);
			// store the keys in the DB
			$this->sql('INSERT INTO ' . table_prefix . "diffiehellman( public_key, private_key ) VALUES ( '$dh_key_pub', '$dh_key_priv' );");
			// also give the key to the calling function
			$dh_store['public'] = $dh_key_pub;
			$dh_store['private'] = $dh_key_priv;
			
			$return .=  "<input type=\"hidden\" name=\"dh_supported\" value=\"true\" />
						<input type=\"hidden\" name=\"dh_public_key\" value=\"$dh_key_pub\" />
						<input type=\"hidden\" name=\"dh_client_public_key\" value=\"\" />";
		}
		else
		{
			$return .=  "<input type=\"hidden\" name=\"dh_supported\" value=\"false\" />";
		}
		return $return;
	}
	
	/**
	 * Static version of generate_aes_form().
	 * @see sessionManager::generate_aes_form()
	 * @param reference
	 * @return string
	 */
	
	static function generate_aes_form_static(&$dh_store = array())
	{
		$aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
		$aes_key = $aes->gen_readymade_key();
		$dh_store = array('aes' => $aes_key, 'public' => '', 'private' => '');
		
		$return = '<input type="hidden" name="use_crypt" value="no" />';
		$return .= '<input type="hidden" name="crypt_key" value="' . $aes_key . '" />';
		$return .= '<input type="hidden" name="crypt_data" value="" />';
		$return .= '<input type="hidden" name="challenge_data" value="' . self::dss_rand() . '" />';
		
		require_once(ENANO_ROOT . '/includes/math.php');
		require_once(ENANO_ROOT . '/includes/diffiehellman.php');
		
		global $dh_supported, $_math;
		if ( $dh_supported )
		{
			$dh_key_priv = dh_gen_private();
			$dh_key_pub = dh_gen_public($dh_key_priv);
			$dh_key_priv = $_math->str($dh_key_priv);
			$dh_key_pub = $_math->str($dh_key_pub);
			// also give the key to the calling function
			$dh_store['public'] = $dh_key_pub;
			$dh_store['private'] = $dh_key_priv;
			
			$return .=  "<input type=\"hidden\" name=\"dh_supported\" value=\"true\" />
						<input type=\"hidden\" name=\"dh_public_key\" value=\"$dh_key_pub\" />
						<input type=\"hidden\" name=\"dh_client_public_key\" value=\"\" />";
		}
		else
		{
			$return .=  "<input type=\"hidden\" name=\"dh_supported\" value=\"false\" />";
		}
		return $return;
	}
	
	/**
	 * If you used all the same form fields as the normal login interface, this will take care of DiffieHellman for you and return the key.
	 * @param string Password field name (defaults to "password")
	 * @param array Optional associative array with fields "public", "private", and "aes".
	 * @return string
	 */
	
	static function get_aes_post($fieldname = 'password', $keys = false)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		
		$aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
		if ( $_POST['use_crypt'] == 'yes' )
		{
			$is_static = !( isset($this) && get_class($this) === __CLASS__ );
			if ( $is_static && ( !is_array($keys) || (is_array($keys) && !isset($keys['aes'])) ) )
			{
				throw new Exception('ERR_STATIC_REQUIRES_KEY');
			}
			$crypt_key = $is_static ? $keys['aes'] : $this->fetch_public_key($_POST['crypt_key']);
			if ( !$crypt_key )
			{
				throw new Exception($lang->get('user_err_key_not_found'));
			}
			$crypt_key = hexdecode($crypt_key);
			$data = $aes->decrypt($_POST['crypt_data'], $crypt_key, ENC_HEX);
		}
		else if ( $_POST['use_crypt'] == 'yes_dh' )
		{
			require_once(ENANO_ROOT . '/includes/math.php');
			require_once(ENANO_ROOT . '/includes/diffiehellman.php');
			
			global $dh_supported, $_math;
				
			if ( !$dh_supported )
			{
				throw new Exception('Server does not support DiffieHellman, denying request');
			}
			
			// Fetch private key
			$dh_public = $_POST['dh_public_key'];
			if ( !ctype_digit($dh_public) )
			{
				throw new Exception('ERR_DH_KEY_NOT_INTEGER');
			}
			if ( is_array($keys) && isset($keys['public']) && isset($keys['private']) )
			{
				if ( $keys['public'] !== $dh_public )
					throw new Exception('ERR_DH_KEY_NOT_FOUND');
				$dh_private = $keys['private'];
			}
			else
			{
				$q = $db->sql_query('SELECT private_key, key_id FROM ' . table_prefix . "diffiehellman WHERE public_key = '$dh_public';");
				if ( !$q )
					$db->die_json();
				
				if ( $db->numrows() < 1 )
				{
					throw new Exception('ERR_DH_KEY_NOT_FOUND');
				}
				
				list($dh_private, $dh_key_id) = $db->fetchrow_num();
				$db->free_result();
				
				// We have the private key, now delete the key pair, we no longer need it
				$q = $db->sql_query('DELETE FROM ' . table_prefix . "diffiehellman WHERE key_id = $dh_key_id;");
				if ( !$q )
					$db->die_json();
			}
			
			// Generate the shared secret
			$dh_secret = dh_gen_shared_secret($dh_private, $_POST['dh_client_public_key']);
			$dh_secret = $_math->str($dh_secret);
			
			// Did we get all our math right?
			$dh_secret_check = sha1($dh_secret);
			$dh_hash = $_POST['crypt_key'];
			if ( $dh_secret_check !== $dh_hash )
			{
				throw new Exception('ERR_DH_HASH_NO_MATCH');
			}
			
			// All good! Generate the AES key
			$aes_key = substr(sha256($dh_secret), 0, ( AES_BITS / 4 ));
			
			// decrypt user info
			$aes_key = hexdecode($aes_key);
			$aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
			$data = $aes->decrypt($_POST['crypt_data'], $aes_key, ENC_HEX);
		}
		else
		{
			$data = $_POST[$fieldname];
		}
		return $data;
	}
	
	/**
	 * Backend code for the JSON login interface. Basically a frontend to the session API that takes all parameters in one huge array.
	 * @param array LoginAPI request
	 * @return array LoginAPI response
	 */
	
	function process_login_request($req)
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		
		// Setup EnanoMath and Diffie-Hellman
		global $dh_supported;
		if ( !function_exists('dh_gen_private') )
		{
			require_once(ENANO_ROOT.'/includes/math.php');
			
			$dh_supported = true;
			try
			{
				require_once(ENANO_ROOT . '/includes/diffiehellman.php');
			}
			catch ( Exception $e )
			{
				$dh_supported = false;
			}
		}
		global $_math;
		
		// Check for the mode
		if ( !isset($req['mode']) )
		{
			return $this->get_login_response('api_error', 'ERR_JSON_NO_MODE');
		}
		
		// Main processing switch
		switch ( $req['mode'] )
		{
			default:
				return $this->get_login_response('api_error', 'ERR_JSON_INVALID_MODE');
				break;
			case 'getkey':
				
				$this->start();
				
				return $this->get_login_response('initial');
				break;
			case 'login_dh':
				// User is requesting a login and has sent Diffie-Hellman data.
				
				//
				// KEY RECONSTRUCTION
				//
				
				$userinfo_crypt = $req['userinfo'];
				$dh_public = $req['dh_public_key'];
				$dh_hash = $req['dh_secret_hash'];
				
				// Check the key
				if ( !ctype_digit($dh_public) || !ctype_digit($req['dh_client_key']) )
				{
					return $this->get_login_response('api_error', 'ERR_DH_KEY_NOT_NUMERIC');
				}
				
				// Fetch private key
				$q = $db->sql_query('SELECT private_key, key_id FROM ' . table_prefix . "diffiehellman WHERE public_key = '$dh_public';");
				if ( !$q )
					$db->die_json();
				
				if ( $db->numrows() < 1 )
				{
					return $this->get_login_response('api_error', 'ERR_DH_KEY_NOT_FOUND');
				}
				
				list($dh_private, $dh_key_id) = $db->fetchrow_num();
				$db->free_result();
				
				// We have the private key, now delete the key pair, we no longer need it
				$q = $db->sql_query('DELETE FROM ' . table_prefix . "diffiehellman WHERE key_id = $dh_key_id;");
				if ( !$q )
					$db->die_json();
				
				// Generate the shared secret
				$dh_secret = dh_gen_shared_secret($dh_private, $req['dh_client_key']);
				$dh_secret = $_math->str($dh_secret);
				
				// Did we get all our math right?
				$dh_secret_check = sha1($dh_secret);
				if ( $dh_secret_check !== $dh_hash )
				{
					return $this->get_login_response('api_error', 'ERR_DH_HASH_NO_MATCH');
				}
				
				// All good! Generate the AES key
				$aes_key = substr(sha256($dh_secret), 0, ( AES_BITS / 4 ));
			case 'login_aes':
				if ( $req['mode'] == 'login_aes' )
				{
					// login_aes-specific code
					$aes_key = $this->fetch_public_key($req['key_aes']);
					if ( !$aes_key )
					{
						return $this->get_login_response('api_error', 'ERR_AES_LOOKUP_FAILED');
					}
					$userinfo_crypt = $req['userinfo'];
				}
				// shared between the two systems from here on out
				
				// decrypt user info
				$aes_key = hexdecode($aes_key);
				$aes = AESCrypt::singleton(AES_BITS, AES_BLOCKSIZE);
				// using "true" here disables caching of the decrypted login info (which includes the password)
				$userinfo_json = $aes->decrypt($userinfo_crypt, $aes_key, ENC_HEX, true);
				if ( !$userinfo_json )
				{
					return $this->get_login_response('api_error', 'ERR_AES_DECRYPT_FAILED');
				}
				// de-JSON user info
				try
				{
					$userinfo = enano_json_decode($userinfo_json);
				}
				catch ( Exception $e )
				{
					return $this->get_login_response('api_error', 'ERR_USERINFO_DECODE_FAILED');
				}
				
			case 'login_pt':
				// plaintext login
				if ( $req['mode'] == 'login_pt' )
				{
					$userinfo = isset($req['userinfo']) ? $req['userinfo'] : array();
				}
				
				if ( !isset($userinfo['username']) || !isset($userinfo['password']) )
				{
					return $this->get_login_response('api_error', 'ERR_USERINFO_MISSING_VALUES');
				}
				
				$username =& $userinfo['username'];
				$password =& $userinfo['password'];
				
				// locked out? check captcha
				$lockout_data = $this->get_lockout_info();
				if ( $lockout_data['policy'] == 'captcha' && $lockout_data['active'] )
				{
					// policy is captcha -- check if it's correct, and if so, bypass lockout check
					$real_code = $this->get_captcha($req['captcha_hash']);
					if ( strtolower($real_code) !== strtolower($req['captcha_code']) )
					{
						// captcha is bad
						return $this->get_login_response('login_failure', 'lockout_bad_captcha');
					}
				}
				else if ( $lockout_data['policy'] == 'lockout' && $lockout_data['active'] )
				{
					// we're fully locked out
					return $this->get_login_response('login_failure', 'lockout_request_denied');
				}
				
				// At this point if any extra info was injected into the login data packet, we need to let plugins process it
				/**
	 			* Called upon processing an incoming login request. If you added anything to the userinfo object during the jshook
	 			* login_build_userinfo, that will be in the $userinfo array here. Expected return values are: true if your plugin has
	 			* not only succeeded but ALSO issued a session key (bypass the whole Enano builtin login process) and an associative array
	 			* with "mode" set to "error" and an error string in "error" to send an error back to the client. Any return value other
	 			* than these will be treated as a pass-through, and the user's password will be validated through Enano's standard process.
	 			* @hook login_process_userdata_json
	 			*/
				
				$code = $plugins->setHook('login_process_userdata_json', true);
				
				foreach ( $code as $cmd )
				{
					$result = eval($cmd);
					if ( $result === true )
					{
						return $this->get_login_response('login_success', false, array(
								'key' => $this->sid_super,
								'user_id' => $this->user_id,
								'user_level' => $this->user_level,
								'reset' => false
							));
					}
					else if ( is_array($result) )
					{
						if ( isset($result['mode']) && $result['mode'] === 'error' && isset($result['error']) )
						{
							// Pass back any additional information from the error response
							$append = $result;
							unset($append['mode'], $append['error']);
							$append['from_plugin'] = true;
							
							return $this->get_login_response('login_failure', $result['error'], $append);
						}
					}
				}
				
				// attempt the login
				$login_result = $this->login_without_crypto($username, $password, false, intval($req['level']), @$req['remember']);
				
				if ( $login_result['success'] )
				{
					return $this->get_login_response('login_success', false, array(
							'key' => $this->sid_super,
							'user_id' => $this->user_id,
							'user_level' => $this->user_level,
						));
				}
				else if ( !$login_result['success'] && $login_result['error'] === 'valid_reset' )
				{
					return $this->get_login_response('reset_pass_used', false, array(
							'redirect_url' => $login_result['redirect_url']
						));
				}
				else
				{
					return $this->get_login_response('login_failure', 'invalid_credentials');
				}
				
				break;
			case 'clean_key':
				// Clean out a key, since it won't be used.
				// This is called when the user clicks Cancel in the AJAX login interface.
				if ( !empty($req['key_aes']) )
				{
					$this->fetch_public_key($req['key_aes']);
				}
				if ( !empty($req['key_dh']) )
				{
					$pk = $db->escape($req['key_dh']);
					$q = $db->sql_query('DELETE FROM ' . table_prefix . "diffiehellman WHERE public_key = '$pk';");
					if ( !$q )
						$db->die_json();
				}
				return array(
						'mode' => 'noop'
					);
				break;
			case 'respond_password_reset':
				die(enano_json_encode(array(
						'mode' => 'login_success_reset',
						'user_id' => $req['user_id'],
						'temp_password' => $req['temp_password'],
						'respawn_info' => $this->process_login_request(array('mode' => 'getkey'))
					)));
				break;
			case 'logout':
				if ( !$this->started )
					$this->start();
				if ( !isset($req['csrf_token']) )
					return array(
							'mode' => 'error',
							'error' => 'Invalid CSRF token'
						);
				
				if ( $req['csrf_token'] !== $this->csrf_token )
					return array(
							'mode' => 'error',
							'error' => 'Invalid CSRF token'
						);
				$level = isset($req['level']) && is_int($req['level']) ? $req['level'] : USER_LEVEL_MEMBER;
				if ( ($result = $this->logout($level)) === 'success' )
				{
					return array(
						'mode' => 'logout_success'
					);
				}
				else
				{
					return array(
						'mode' => 'error',
						'error' => $result
					);
				}
				break;
		}
		
	}
	
	/**
	 * Generate a packet to send to the client for logins.
	 * @param string mode
	 * @param array 
	 * @return array
	 */
	
	function get_login_response($mode, $error = false, $base = array())
	{
		$this->start();
		
		// init
		$response = $base;
		// modules in the packet
		$response['mode'] = $mode;
		$response['error'] = $error;
		$response['crypto'] = $mode !== 'login_success' ? $this->get_login_crypto_packet() : false;
		$response['lockout'] = $mode !== 'login_success' ? $this->get_lockout_info() : false;
		$response['extended_time'] = intval(getConfig('session_remember_time', '30'));
		$response['username'] = $this->user_logged_in ? $this->username : false;
		return $response;
	}
	
	/**
	 * Get a packet of crypto flags for login.
	 * @return array
	 */
	
	function get_login_crypto_packet()
	{
		global $dh_supported, $_math;
		
		$response = array();
		
		$response['dh_enable'] = $dh_supported;
		$response['aes_key'] = $this->rijndael_genkey();
		
		// Can we do Diffie-Hellman? If so, generate and stash a public/private key pair.
		if ( $dh_supported )
		{
			$dh_key_priv = dh_gen_private();
			$dh_key_pub = dh_gen_public($dh_key_priv);
			$dh_key_priv = $_math->str($dh_key_priv);
			$dh_key_pub = $_math->str($dh_key_pub);
			$response['dh_public_key'] = $dh_key_pub;
			// store the keys in the DB
			$this->sql('INSERT INTO ' . table_prefix . "diffiehellman( public_key, private_key ) VALUES ( '$dh_key_pub', '$dh_key_priv' );");
		}
		
		return $response;
	}
	
}

/**
 * Class used to fetch permissions for a specific page. Used internally by SessionManager.
 * @package Enano
 * @subpackage Session manager
 * @license http://www.gnu.org/copyleft/gpl.html
 * @access private
 */
 
class Session_ACLPageInfo {
	
	/**
	 * The page ID of this ACL info package
	 * @var string
	 */
	 
	var $page_id;
	
	/**
	 * The namespace of the page being checked
	 * @var string
	 */
	 
	var $namespace;
	
	/**
	 * Our list of permission types.
	 * @access private
	 * @var array
	 */
	 
	var $acl_types = Array();
	
	/**
	 * The list of descriptions for the permission types
	 * @var array
	 */
	 
	var $acl_descs = Array();
	
	/**
	 * A list of dependencies for ACL types.
	 * @var array
	 */
	 
	var $acl_deps = Array();
	
	/**
	 * Our tell-all list of permissions. Do not even try to change this.
	 * @access private
	 * @var array
	 */
	 
	var $perms = Array();
	
	/**
	 * Array to track which default permissions are being used
	 * @var array
	 * @access private
	 */
	 
	var $acl_defaults_used = Array();
	
	/**
	 * Tracks whether Wiki Mode is on for the page we're operating on.
	 * @var bool
	 */
	
	var $wiki_mode = false;
	
	/**
	 * Tracks where permissions were calculated using the ACL_INHERIT_* constants. Layout:
	 * array(
	 *   [permission_name] => array(
	 *       [src] => ACL_INHERIT_*
	 *       [rule_id] => integer
	 *     ),
	 *   ...
	 * )
	 *
	 * @var array
	 */
	
	var $perm_resolve_table = array();
	
	#
	# USER PARAMETERS
	#
	
	/**
	 * User ID
	 * @var int
	 */
	
	var $user_id = 1;
	
	/**
	 * Group membership associative array (group_id => group_name)
	 * @var array
	 */
	
	var $groups = array();
	
	/**
	 * Constructor.
	 * @param string $page_id The ID of the page to check
	 * @param string $namespace The namespace of the page to check.
	 * @param array $acl_types List of ACL types
	 * @param array $acl_descs List of human-readable descriptions for permissions (associative)
	 * @param array $acl_deps List of dependencies for permissions. For example, viewing history/diffs depends on the ability to read the page.
	 * @param array $base What to start with - this is an attempt to reduce the number of SQL queries.
	 * @param int|string $user_id_or_name Username or ID to search for, defaults to current user
	 * @param array $resolve_table Debugging info for tracking where rules came from, defaults to a blank array.
	 */
	 
	function __construct($page_id, $namespace, $acl_types, $acl_descs, $acl_deps, $base, $user_id = null, $groups = null, $resolve_table = array())
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		
		// hack
		if ( isset($base['__resolve_table']) )
		{
			unset($base['__resolve_table']);
		}
		
		foreach ( $acl_types as $perm_type => $_ )
		{
			if ( !$session->check_acl_scope($perm_type, $namespace) )
			{
				unset($acl_types[$perm_type]);
				unset($acl_deps[$perm_type]);
				unset($acl_descs[$perm_type]);
				unset($base[$perm_type]);
			}
		}
		
		$this->acl_deps = $acl_deps;
		$this->acl_types = $acl_types;
		$this->acl_descs = $acl_descs;
		
		$this->perms = $acl_types;
		$this->perms = $session->acl_merge_complete($this->perms, $base);
		
		$this->perm_resolve_table = array();
		if ( is_array($resolve_table) )
			$this->perm_resolve_table = $resolve_table;
		
		if ( is_int($user_id) && is_array($groups) )
		{
			$this->user_id = $user_id;
			$this->groups = $groups;
		}
		else
		{
			$this->user_id = $session->user_id;
			$this->groups = $session->groups;
		}
		
		$this->page_id = $page_id;
		$this->namespace = $namespace;
		
		$this->__calculate();
	}
	
	/**
	 * Performs the actual permission calculation.
	 * @access private
	 */
	
	private function __calculate()
	{
		global $db, $session, $paths, $template, $plugins; // Common objects
		
		$page_id =& $this->page_id;
		$namespace =& $this->namespace;
		
		// PAGE group info
		$pg_list = $paths->get_page_groups($page_id, $namespace);
		$pg_info = '';
		foreach ( $pg_list as $g_id )
		{
			$pg_info .= ' ( page_id=\'' . $g_id . '\' AND namespace=\'__PageGroup\' ) OR';
		}
		
		// Build a query to grab ACL info
		$bs = 'SELECT rules,target_type,target_id,page_id,namespace,rule_id,pg.pg_name,g.group_name FROM '.table_prefix."acl AS a\n"
				. "  LEFT JOIN " . table_prefix . "page_groups AS pg\n"
				. "    ON ( ( a.page_id = CAST(pg.pg_id AS char) AND a.namespace = '__PageGroup' ) OR ( a.namespace != '__PageGroup' ) )\n"
				. "  LEFT JOIN " . table_prefix . "groups AS g\n"
				. "    ON ( ( a.target_type = " . ACL_TYPE_GROUP . " AND a.target_id = g.group_id ) OR ( a.target_type != " . ACL_TYPE_GROUP . " ) )\n";
		
		$bs .= '  WHERE ' . "\n"
					. '  ( ';
		$q = Array();
		$q[] = '( target_type='.ACL_TYPE_USER.' AND target_id='.$this->user_id.' )';
		if(count($this->groups) > 0)
		{
			foreach($this->groups as $g_id => $g_name)
			{
				$q[] = '( target_type='.ACL_TYPE_GROUP.' AND target_id='.intval($g_id).' )';
			}
		}
		// The reason we're using an ORDER BY statement here is because ACL_TYPE_GROUP is less than ACL_TYPE_USER, causing the user's individual
		// permissions to override group permissions.
		$bs .= implode(" OR\n    ", $q) . ' ) AND (' . $pg_info . ' ( page_id=\''.$db->escape($page_id).'\' AND namespace=\''.$db->escape($namespace).'\' ) )     
			ORDER BY target_type ASC, page_id ASC, namespace ASC;';
			
		$q = $session->sql($bs);
		if ( $row = $db->fetchrow($q, true) )
		{
			do
			{
				$rules = $session->string_to_perm($row['rules']);
				$is_everyone = ( $row['target_type'] == ACL_TYPE_GROUP && $row['target_id'] == 1 );
				// log where this comes from
				if ( $row['namespace'] == '__PageGroup' )
				{
					$src = ( $is_everyone ) ? ACL_INHERIT_PG_EVERYONE : ( $row['target_type'] == ACL_TYPE_GROUP ? ACL_INHERIT_PG_GROUP : ACL_INHERIT_PG_USER );
					$pg_name = $row['pg_name'];
				}
				else
				{
					$src = ( $is_everyone ) ? ACL_INHERIT_LOCAL_EVERYONE : ( $row['target_type'] == ACL_TYPE_GROUP ? ACL_INHERIT_LOCAL_GROUP : ACL_INHERIT_LOCAL_USER );
				}
				if ( $row['group_name'] )
				{
					$group_name = $row['group_name'];
				}
				foreach ( $rules as $perm_type => $perm_value )
				{
					if ( !isset($this->perms[$perm_type]) )
						continue;
					
					if ( $this->perms[$perm_type] == AUTH_DENY )
						continue;
					
					if ( !$session->check_acl_scope($perm_type, $this->namespace) )
						continue;
					
					$this->perm_resolve_table[$perm_type] = array(
							'src' => $src,
							'rule_id' => $row['rule_id']
						);
					if ( isset($pg_name) )
					{
						$this->perm_resolve_table[$perm_type]['pg_name'] = $pg_name;
					}
					if ( isset($group_name) )
					{
						$this->perm_resolve_table[$perm_type]['group_name'] = $group_name;
					}
				}
				$this->acl_merge_with_current($rules, $is_everyone);
			} while ( $row = $db->fetchrow() );
		}
		
		$this->page_id = $page_id;
		$this->namespace = $namespace;
		
		$pathskey = $paths->nslist[$this->namespace].sanitize_page_id($this->page_id);
		$ns = namespace_factory($this->page_id, $this->namespace);
		$cdata = $ns->get_cdata();
		
		$this->wiki_mode = false;
		$wiki_mode_eligible = ($session->user_logged_in && getConfig('wiki_mode_require_login', 0) == 1) || getConfig('wiki_mode_require_login', 0) == 0;
		$global_wiki_mode = getConfig('wiki_mode', 0) == 1;
		if ( $wiki_mode_eligible && (($cdata['wiki_mode'] == 2 && $global_wiki_mode) || $cdata['wiki_mode'] == 1))
			$this->wiki_mode = true;
	}
	
	/**
	 * Tells us whether permission $type is allowed or not based on the current rules.
	 * @param string $type The permission identifier ($acl_type passed to sessionManager::register_acl_type())
	 * @param bool $no_deps If true, disables dependency checking
	 * @return bool True if allowed, false if denied or if an error occured
	 */
	 
	function get_permissions($type, $no_deps = false)
	{
		// echo '<pre>' . print_r($this->perms, true) . '</pre>';
		global $db, $session, $paths, $template, $plugins; // Common objects
		
		if ( isset( $this->perms[$type] ) )
		{
			if ( $this->perms[$type] == AUTH_DENY )
			{
				$ret = false;
			}
			else if ( $this->perms[$type] == AUTH_WIKIMODE && $this->wiki_mode )
			{
				$ret = true;
			}
			else if ( $this->perms[$type] == AUTH_WIKIMODE && !$this->wiki_mode )
			{
				$ret = false;
			}
			else if ( $this->perms[$type] == AUTH_ALLOW )
			{
				$ret = true;
			}
			else if ( $this->perms[$type] == AUTH_DISALLOW )
			{
				$ret = false;
			}
		}
		else if(isset($this->acl_types[$type]))
		{
			if ( $this->acl_types[$type] == AUTH_DENY )
				$ret = false;
			else if ( $this->acl_types[$type] == AUTH_WIKIMODE && $paths->wiki_mode )
				$ret = true;
			else if ( $this->acl_types[$type] == AUTH_WIKIMODE && !$paths->wiki_mode )
				$ret = false;
			else if ( $this->acl_types[$type] == AUTH_ALLOW )
				$ret = true;
			else if ( $this->acl_types[$type] == AUTH_DISALLOW )
				$ret = false;
		}
		else
		{
			// ACL type is undefined
			$caller = 'unknown';
			if ( function_exists('debug_backtrace') )
			{
				if ( $bt = @debug_backtrace() )
				{
					foreach ( $bt as $trace )
					{
						$file = basename($trace['file']);
						if ( $file != 'sessions.php' )
						{
							$caller = $file . ':' . $trace['line'];
							break;
						}
					}
				}
			}
			trigger_error('Unknown access type "' . $type . '", called from ' . $caller . '', E_USER_WARNING);
			return false; // Be on the safe side and deny access
		}
		if ( !$no_deps )
		{
			if ( !$this->acl_check_deps($type) )
				return false;
		}
		return $ret;
	}
	
	/**
	 * Tell us if the dependencies for a given permission are met.
	 * @param string The ACL permission ID
	 * @param bool If true, does not return a boolean value, but instead returns array of dependencies that fail
	 * @return bool
	 */
	 
	function acl_check_deps($type, $debug = false)
	{
		// This will only happen if the permissions table is hacked or improperly accessed
		if(!isset($this->acl_deps[$type]))
			return $debug ? array() : true;
		// Permission has no dependencies?
		if(sizeof($this->acl_deps[$type]) < 1)
			return $debug ? array() : true;
		// go through them all and build a flat list of dependencies
		$deps = $this->acl_deps[$type];
		while(true)
		{
			$j = sizeof($deps);
			for ( $i = 0; $i < $j; $i++ )
			{
				$b = $deps;
				if ( !isset($this->acl_deps[$deps[$i]]) )
				{
					// Action $type depends on action $deps[$i] which cannot be satisfied because $deps[$i] is out of scope.
					trigger_error("acl_check_deps: $type depends on {$deps[$i]} which is not within scope of $this->namespace; this indicates a bug in ACL rule specification", E_USER_WARNING);
					return false;
				}
				$deps = array_merge($deps, $this->acl_deps[$deps[$i]]);
				if( $b == $deps )
				{
					break 2;
				}
				$j = sizeof($deps);
			}
		}
		$debugdata = array();
		foreach($deps as $d)
		{
			// Our dependencies are fully resolved, so tell get_permissions() to not recursively call this function
			if ( !$this->get_permissions($d, true) )
			{
				if ( $debug )
				{
					$debugdata[] = $d;
				}
				else
				{
					return false;
				}
			}
		}
		return $debug ? $debugdata : true;
	}
	
	/**
	 * Merges the ACL array sent with the current permissions table, deciding precedence based on whether defaults are in effect or not.
	 * @param array The array to merge into the master ACL list
	 * @param bool If true, $perm is treated as the "new default"
	 * @param int 1 if this is a site-wide ACL, 2 if page-specific. Defaults to 2.
	 */
	
	function acl_merge_with_current($perm, $is_everyone = false, $scope = 2)
	{
		foreach ( $this->perms as $i => $p )
		{
			if ( isset($perm[$i]) )
			{
				if ( $is_everyone && !@$this->acl_defaults_used[$i] )
					continue;
				// Decide precedence
				if ( isset($this->acl_defaults_used[$i]) )
				{
					//echo "$i: default in use, overriding to: {$perm[$i]}<br />";
					// Defaults are in use, override
					$this->perms[$i] = $perm[$i];
					$this->acl_defaults_used[$i] = ( $is_everyone );
				}
				else
				{
					//echo "$i: default NOT in use";
					// Defaults are not in use, merge as normal
					if ( $this->perms[$i] != AUTH_DENY )
					{
						//echo ", but overriding";
						$this->perms[$i] = $perm[$i];
					}
					//echo "<br />";
				}
			}
		}
	}
	
}

/**
 * Cron task - clears out the database of Diffie-Hellman keys
 */

function cron_clean_login_cache()
{
	global $db, $session, $paths, $template, $plugins; // Common objects
	
	if ( !$db->sql_query('DELETE FROM ' . table_prefix . 'diffiehellman;') )
		$db->_die();
	
	setConfig('login_key_cache', '');
}

register_cron_task('cron_clean_login_cache', 72);

/**
 * Cron task - clears out outdated high-auth session keys
 */

function cron_clean_old_admin_keys()
{
	global $db, $session, $paths, $template, $plugins; // Common objects
	
	$threshold = time() - ( 15 * 60 );
	$ul_member = USER_LEVEL_MEMBER;
	if ( !$db->sql_query('DELETE FROM ' . table_prefix . "session_keys WHERE time < $threshold AND auth_level > $ul_member;") )
		$db->_die();
}

// Once a week
register_cron_task('cron_clean_old_admin_keys', 168);

/**
 * Cron task - regenerate cached user rank information
 */

register_cron_task('generate_cache_userranks', 0.25);

?>
Back to Top