Croissierd /system/core/core.template.php

Language PHP Lines 3422
MD5 Hash 1df5302c798edffb0e6a4a0cd94a61e7
Repository https://github.com/danboy/Croissierd.git View Raw File View Project SPDX
   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
<?php

/*
=====================================================
 ExpressionEngine - by EllisLab
-----------------------------------------------------
 http://expressionengine.com/
-----------------------------------------------------
 Copyright (c) 2003 - 2010 EllisLab, Inc.
=====================================================
 THIS IS COPYRIGHTED SOFTWARE
 PLEASE READ THE LICENSE AGREEMENT
 http://expressionengine.com/docs/license.html
=====================================================
 File: core.template.php
-----------------------------------------------------
 Purpose: Template parsing class.
=====================================================
*/

if ( ! defined('EXT'))
{
    exit('Invalid file request');
}


class Template {
        
    var $loop_count      	=   0;			// Main loop counter.    
    var $depth           	=   0;			// Sub-template loop depth
    var $in_point        	=  '';			// String position of matched opening tag
    var $template        	=  '';			// The requested template (page)
    var $final_template     =  '';			// The finalized template
    var $fl_tmpl         	=  '';			// 'Floating' copy of the template.  Used as a temporary "work area".
    var $cache_hash      	=  '';			// md5 checksum of the template name.  Used as title of cache file.
    var $cache_status   	=  '';			// Status of page cache (NO_CACHE, CURRENT, EXPIRED)
    var $cache_timestamp	=  ''; 
    var $template_type  	=  '';			// Type of template (webpage, rss)
    var $embed_type			=  '';			// Type of template for embedded template
    var $template_hits   	=   0;
    var $php_parse_location =  'output';	// Where in the chain the PHP gets parsed
	var $template_edit_date	=	'';			// Template edit date
    
    var $encode_email		=  TRUE;		// Whether to use the email encoder.  This is set automatically
    var $hit_lock_override	=  FALSE;		// Set to TRUE if you want hits tracked on sub-templates
    var $hit_lock        	=  FALSE;		// Lets us lock the hit counter if sub-templates are contained in a template
    var $parse_php			=  FALSE;		// Whether to parse PHP or not
    var $protect_javascript =  TRUE;		// Protect javascript in conditionals
  
	var	$templates_sofar	= '';			// Templates processed so far, subtemplate tracker 
    var $tag_data        	= array();		// Data contained in tags
    var $modules         	= array();		// List of installed modules
    var $module_data		= array();		// Data for modules from exp_weblogs
    var $plugins         	= array();		// List of installed plug-ins
    var $native_modules		= array();		// List of native modules with EE
    
    var $var_single      	= array();		// "Single" variables
    var $var_cond        	= array();		// "Conditional" variables
    var $var_pair        	= array();		// "Paired" variables
    var $global_vars        = array();		// This array can be set via the path.php file
    var $embed_vars         = array();		// This array can be set via the {embed} tag
    var $segment_vars		= array();		// Array of segment variables
        
	var $tagparts			= array();		// The parts of the tag: {exp:comment:form}
	var $tagdata			= '';			// The chunk between tag pairs.  This is what modules will utilize
    var $tagproper			= '';			// The full opening tag
    var $no_results			= '';			// The contents of the {if no_results}{/if} conditionals
    var $no_results_block	= '';			// The {if no_results}{/if} chunk
	var $search_fields		= array();		// Tag parameters that begin with 'search:'
    
    var $related_data		= array();		//  A multi-dimensional array containing any related tags
    var $related_id			= '';			// Used temporarily for the related ID number
    var $related_markers	= array();		// Used temporarily
    
    var $site_ids			= array();		// Site IDs for the Sites Request for a Tag
    var $sites				= array();		// Array of sites with site_id as key and site_name as value, used to determine site_ids for tag, above.
    var $site_prefs_cache	= array();		// Array of cached site prefs, to allow fetching of another site's template files

    var $reverse_related_data = array();	//  A multi-dimensional array containing any reverse related tags
   
    var $t_cache_path    	= 'tag_cache/';	 // Location of the tag cache file
    var $p_cache_path    	= 'page_cache/'; // Location of the page cache file
    var $disable_caching	=  FALSE;
    
    var $debugging			= FALSE;		// Template parser debugging on?
    var $cease_processing	= FALSE;		// Used with no_results() method.
    var $log				= array();		// Log of Template processing
    var $start_microtime	= 0;			// For Logging (= microtime())
    
    var $strict_urls		= FALSE;		// Whether to make URLs operate strictly or not.  This is set via a template global pref
    
    var $realm				= 'ExpressionEngine Template';  // Localize?

    var $marker = '0o93H7pQ09L8X1t49cHY01Z5j4TT91fGfr'; // Temporary marker used as a place-holder for template data
    

    /** -------------------------------------
    /**  Constructor
    /** -------------------------------------*/

    function Template()
    {
    	global $IN, $PREFS;
    	
    	$this->native_modules = array('blacklist', 'comment', 'email', 'forum',
    								  'gallery', 'mailinglist', 'member', 'query',
    								  'referrer', 'rss', 'search', 'stats', 
    								  'trackback', 'updated_sites', 'weblog', 
    								  'simple_commerce', 'commerce');
    								  
    	$this->global_vars = $IN->global_vars;
    	
    	if ($PREFS->ini('multiple_sites_enabled') != 'y')
    	{
    		$this->sites[$PREFS->ini('site_id')] = $PREFS->ini('site_short_name');
    	}
    	
    	if ($PREFS->ini('template_debugging') === 'y' && $this->start_microtime == 0)
    	{
    		$this->debugging = TRUE;
    		
    		if (phpversion() < 5)
    		{
    			list($usec, $sec) = explode(" ", microtime());
    			$this->start_microtime = ((float)$usec + (float)$sec);
    		}
    		else
    		{
    			$this->start_microtime = microtime(TRUE);
    		}
    	}
    }
    /* END */
    
    
    
    /** -------------------------------------
    /**  Run the template engine
    /** -------------------------------------*/

    function run_template_engine($template_group = '', $template = '')
    {
        global $OUT, $IN, $FNS, $PREFS;
        
        $this->log_item(" - Begin Template Processing - ");
                
        // Set the name of the cache folder for both tag and page caching
        
        if ($IN->URI != '')
        {          
            $this->t_cache_path .= md5($FNS->fetch_site_index().$IN->URI).'/';
            $this->p_cache_path .= md5($FNS->fetch_site_index().$IN->URI).'/';        
        }
        else
        {
            $this->t_cache_path .= md5($PREFS->ini('site_url').'index'.$IN->QSTR).'/';
            $this->p_cache_path .= md5($PREFS->ini('site_url').'index'.$IN->QSTR).'/';
        }
        
        
		// We limit the total number of cache files in order to
		// keep some sanity with large sites or ones that get
		// hit by over-ambitious crawlers.
		
		if ($this->disable_caching == FALSE)
		{		
			if ($dh = @opendir(PATH_CACHE.'page_cache'))
			{
				$i = 0;
				while (false !== (readdir($dh)))
				{
					$i++;
				}
				
				$max = ( ! $PREFS->ini('max_caches') OR ! is_numeric($PREFS->ini('max_caches')) OR $PREFS->ini('max_caches') > 1000) ? 1000 : $PREFS->ini('max_caches');
				
				if ($i > $max)
				{
					$FNS->clear_caching('page');
				}			
			}   
        }
        
		$this->log_item("URI: ".$IN->URI);
		$this->log_item("Path.php Template: {$template_group}/{$template}");

        $this->process_template($template_group, $template, FALSE);
        
		$this->log_item(" - End Template Processing - ");
		$this->log_item("Parse Global Variables");

		if ($this->template_type == 'static')
		{
			$this->final_template = $this->restore_xml_declaration($this->final_template);
		}
		else
		{
       		$this->final_template = $this->parse_globals($this->final_template);
		}
		
		$this->log_item("Template Parsing Finished");
		
       	$OUT->out_type = $this->template_type;
       	$OUT->build_queue($this->final_template); 
    }
    /* END */
    
    
    
    /** -------------------------------------
    /**  Process Template
    /** -------------------------------------*/

    function process_template($template_group = '', $template = '', $sub = FALSE, $site_id = '')
    {
        global $LOC, $PREFS, $REGX, $LANG, $IN, $FNS;
        
		// add this template to our subtemplate tracker
		$this->templates_sofar = $this->templates_sofar.'|'.$site_id.':'.$template_group.'/'.$template.'|';

		/** -------------------------------------
        /**  Fetch the requested template
        /** -------------------------------------*/
		// The template can either come from the DB or a cache file

		// Do not use a reference!
		
        $this->cache_status = 'NO_CACHE';
        
        $this->log_item("Retrieving Template");
						        
		$this->template = ($template_group != '' AND $template != '') ? $this->fetch_template($template_group, $template, FALSE, $site_id) : $this->parse_template_uri();
			
		$this->log_item("Template Type: ".$this->template_type);	
			
		/** -------------------------------------
        /**  Static Content, No Parsing
        /** -------------------------------------*/
				
		if ($this->template_type == 'static' OR $this->embed_type == 'static')
		{
			if ($sub == FALSE)
			{
				$this->final_template = $this->template;
			}
			
			return;
		}
		
		/* -------------------------------------
		/*  "Smart" Static Parsing
		/*  
		/*  Performed on embedded webpage templates only that do not have 
		/*	ExpressionEngine tags or PHP in them.
		/*  
		/*  Hidden Configuration Variable
		/*  - smart_static_parsing => Bypass parsing of templates that could be 
		/*	of the type 'static' but aren't? (y/n)
		/* -------------------------------------*/

		if ($PREFS->ini('smart_static_parsing') !== 'n' && $this->embed_type == 'webpage' && ! stristr($this->template, LD) && ! stristr($this->template, '<?'))
		{
			$this->log_item("Smart Static Parsing Triggered");
			
			if ($sub == FALSE)
			{
				$this->final_template = $this->template;
			}
			
			return;
		}
		
		/** -------------------------------------
        /**  Replace "logged_out" variables
        /** -------------------------------------*/
		// We do this for backward compatibility
		// Note:  My plan is to deprecate this, but we need to update
		// every template in an installation with the new syntax.
		// I would have done it for 1.2 but I added this late, after the
		// beta testers already got a copy, so we'll do it in a future update.
		
		$logvars = array('NOT_LOGGED_IN' => 'logged_out', 'not_logged_in' => 'logged_out', 'LOGGED_IN' => 'logged_in');
		
		foreach($logvars as $key => $val)
		{
			$this->template = str_replace(LD.'if '.$key.RD, LD.'if '.$val.RD, $this->template);
        }
                
		/** -------------------------------------
        /**  Parse URI segments
        /** -------------------------------------*/
        
        // This code lets admins fetch URI segments which become
        // available as:  {segment_1} {segment_2}        
                
		for ($i = 1; $i < 10; $i++)
		{
			$this->template = str_replace(LD.'segment_'.$i.RD, $IN->fetch_uri_segment($i), $this->template); 
			$this->segment_vars['segment_'.$i] = $IN->fetch_uri_segment($i);
		}
		
		/** -------------------------------------
        /**  Parse {embed} tag variables
        /** -------------------------------------*/
		
		if ($sub === TRUE && count($this->embed_vars) > 0)
		{
			$this->log_item("Embed Variables (Keys): ".implode('|', array_keys($this->embed_vars)));
			$this->log_item("Embed Variables (Values): ".trim(implode('|', $this->embed_vars)));
		
			foreach ($this->embed_vars as $key => $val)
			{
				// add 'embed:' to the key for replacement and so these variables work in conditionals
				$this->embed_vars['embed:'.$key] = $val;
				unset($this->embed_vars[$key]);
				$this->template = str_replace(LD.'embed:'.$key.RD, $val, $this->template); 
			}
		}
		
		// cleanup of leftover/undeclared embed variables
		// don't worry with undeclared embed: vars in conditionals as the conditionals processor will handle that adequately
		if (strpos($this->template, LD.'embed:') !== FALSE)
		{
			$this->template = preg_replace('/'.LD.'embed:(.+?)'.RD.'/', '', $this->template);
		}
		
		/** --------------------------------------------------
        /**  Parse 'Site' variables
        /** --------------------------------------------------*/

		$this->log_item("Parsing Site Variables");

		// load site variables into the global_vars array
		foreach (array('site_id', 'site_label', 'site_short_name') as $site_var)
		{
			$this->global_vars[$site_var] = stripslashes($PREFS->ini($site_var));
		}
		
		/** -------------------------------------
        /**  Parse manual variables
        /** -------------------------------------*/
		// These are variables that can be set in the path.php file
		
		if (count($this->global_vars) > 0)
		{
			$this->log_item("Global Path.php Variables (Keys): ".implode('|', array_keys($this->global_vars)));
			$this->log_item("Global Path.php Variables (Values): ".trim(implode('|', $this->global_vars)));
		
			foreach ($this->global_vars as $key => $val)
			{
				$this->template = str_replace(LD.$key.RD, $val, $this->template); 
			}
		}
		
		/** -------------------------------------
		/**  Parse date format string "constants"
		/** -------------------------------------*/
		
		$date_constants	= array('DATE_ATOM'		=>	'%Y-%m-%dT%H:%i:%s%Q',
								'DATE_COOKIE'	=>	'%l, %d-%M-%y %H:%i:%s UTC',
								'DATE_ISO8601'	=>	'%Y-%m-%dT%H:%i:%s%O',
								'DATE_RFC822'	=>	'%D, %d %M %y %H:%i:%s %O',
								'DATE_RFC850'	=>	'%l, %d-%M-%y %H:%m:%i UTC',
								'DATE_RFC1036'	=>	'%D, %d %M %y %H:%i:%s %O',
								'DATE_RFC1123'	=>	'%D, %d %M %Y %H:%i:%s %O',
								'DATE_RFC2822'	=>	'%D, %d %M %Y %H:%i:%s %O',
								'DATE_RSS'		=>	'%D, %d %M %Y %H:%i:%s %O',
								'DATE_W3C'		=>	'%Y-%m-%dT%H:%i:%s%Q'
								);
		foreach ($date_constants as $key => $val)
		{
			$this->template = str_replace(LD.$key.RD, $val, $this->template);
		}
		
		$this->log_item("Parse Date Format String Constants");
		
        /** --------------------------------------------------
        /**  Template's Last Edit time {template_edit_date format="%Y %m %d %H:%i:%s"}
        /** --------------------------------------------------*/

   		if (strpos($this->template, LD.'template_edit_date') !== FALSE && preg_match_all("/".LD."template_edit_date\s+format=([\"\'])([^\\1]*?)\\1".RD."/", $this->template, $matches))
   		{	
			for ($j = 0; $j < count($matches['0']); $j++)
			{				
				$this->template = preg_replace("/".$matches['0'][$j]."/", $LOC->decode_date($matches['2'][$j], $this->template_edit_date), $this->template, 1);				
			}
		}  

		/** --------------------------------------------------
        /**  Current time {current_time format="%Y %m %d %H:%i:%s"}
        /** --------------------------------------------------*/

   		if (strpos($this->template, LD.'current_time') !== FALSE && preg_match_all("/".LD."current_time\s+format=([\"\'])([^\\1]*?)\\1".RD."/", $this->template, $matches))
   		{	
			for ($j = 0; $j < count($matches['0']); $j++)
			{				
				$this->template = preg_replace("/".preg_quote($matches['0'][$j], '/')."/", $LOC->decode_date($matches['2'][$j], $LOC->now), $this->template, 1);				
			}
		}
		
		$this->template = str_replace(LD.'current_time'.RD, $LOC->now, $this->template);
		
		$this->log_item("Parse Current Time Variables");
		
		/** -------------------------------------
        /**  Is the main template cached?
        /** -------------------------------------*/
        // If a cache file exists for the primary template
        // there is no reason to go further.
        // However we do need to fetch any subtemplates

        if ($this->cache_status == 'CURRENT' AND $sub == FALSE)
        {
        	$this->log_item("Cached Template Used");
        
        	$this->template = $this->parse_nocache($this->template);
        
        	/** -------------------------------------
			/**  Smite Our Enemies:  Advanced Conditionals
			/** -------------------------------------*/
			
			if (stristr($this->template, LD.'if'))
			{
				$this->template = $this->advanced_conditionals($this->template);
			}
			
			$this->log_item("Conditionals Parsed, Processing Sub Templates");
        
			$this->final_template = $this->template;
			$this->process_sub_templates($this->template); 	
			return;
        }

        // Remove whitespace from variables.
        // This helps prevent errors, particularly if PHP is used in a template
        $this->template = preg_replace("/".LD."\s*(\S+)\s*".RD."/U", LD."\\1".RD, $this->template);

		/** -------------------------------------
		/**  Parse Input Stage PHP
		/** -------------------------------------*/
		
		if ($this->parse_php == TRUE AND $this->php_parse_location == 'input' AND $this->cache_status != 'CURRENT')
		{
			$this->log_item("Parsing PHP on Input");
			$this->template = $this->parse_template_php($this->template);	
		}
		
		/** -------------------------------------
		/**  Smite Our Enemies:  Conditionals
		/** -------------------------------------*/
		
		$this->log_item("Parsing Segment, Embed, and Global Vars Conditionals");
		
		$this->template = $this->segment_conditionals($this->template);
		$this->template = $this->array_conditionals($this->template, $this->embed_vars);
		$this->template = $this->array_conditionals($this->template, $this->global_vars);

		/** -------------------------------------
		/**  Set global variable assignment
		/** -------------------------------------*/

   		if (preg_match_all("/".LD."assign_variable:(.+?)=([\"\'])([^\\2]*?)\\2".RD."/i", $this->template, $matches))
   		{	
   			$this->log_item("Processing Assigned Variables: ".trim(implode('|', $matches['1'])));
   			
			for ($j = 0; $j < count($matches['0']); $j++)
			{				
				$this->template = str_replace($matches['0'][$j], "", $this->template);
				$this->template = str_replace(LD.$matches['1'][$j].RD, $matches['3'][$j], $this->template);
			}
		}
		
		/** -------------------------------------
		/**  Process the template
		/** -------------------------------------*/
		
		// Replace forward slashes with entity to prevent preg_replace errors.
		$this->template = str_replace('/', SLASH, $this->template);

		// Fetch installed modules and plugins if needed
		if (count($this->modules) == 0)
		{
			$this->fetch_modules();
		}
		
		if (count($this->plugins) == 0)
		{
			$this->fetch_plugins();
		}
	
		// Parse the template.
		
		$this->log_item(" - Beginning Tag Processing - ");
		
		while (is_int(strpos($this->template, LD.'exp:')))
		{
			// Initialize values between loops
			$this->tag_data 	= array();
			$this->var_single	= array();
			$this->var_cond		= array();
			$this->var_pair		= array(); 
			$this->loop_count 	= 0;
			
			$this->log_item("Parsing Tags in Template");

			// Run the template parser
			$this->parse_template();
			
			$this->log_item("Processing Tags");
			
			// Run the class/method handler
			$this->class_handler();
			
			if ($this->cease_processing === TRUE)
			{
				return;
			}
		}
		
		$this->log_item(" - End Tag Processing - ");
		
		// Decode forward slash entities back to ascii
		
		$this->template = str_replace(SLASH, '/', $this->template);
		
		/** -------------------------------------
		/**  Parse Output Stage PHP
		/** -------------------------------------*/
		
		if ($this->parse_php == TRUE AND $this->php_parse_location == 'output' AND $this->cache_status != 'CURRENT')
		{
			$this->log_item("Parsing PHP on Output");
			$this->template = $this->parse_template_php($this->template);	
		}
					
		/** -------------------------------------
        /**  Write the cache file if needed
        /** -------------------------------------*/
				
		if ($this->cache_status == 'EXPIRED')
		{ 
			$this->template = $FNS->insert_action_ids($this->template);
			$this->write_cache_file($this->cache_hash, $this->template, 'template');
		}
		
		/** -------------------------------------
		/**  Parse Our Uncacheable Forms
		/** -------------------------------------*/
		
		$this->template = $this->parse_nocache($this->template);
		
		/** -------------------------------------
		/**  Smite Our Enemies:  Advanced Conditionals
		/** -------------------------------------*/
		
		if (stristr($this->template, LD.'if'))
		{
			$this->log_item("Processing Advanced Conditionals");
			$this->template = $this->advanced_conditionals($this->template);
		}
		
		// <?php  This fixes a BBEdit bug that makes the list of function not work right.  Seems related to the PHP declarations above.
		
		
		/** -------------------------------------
        /**  Build finalized template
        /** -------------------------------------*/
		
		// We only do this on the first pass.
		// The sub-template routine will insert embedded
		// templates into the master template
        
        if ($sub == FALSE)
        {
        	$this->final_template = $this->template;
			$this->process_sub_templates($this->template); 
        }
     }
    /* END */
        
     
        
    /** -------------------------------------
    /**  Parse embedded sub-templates
    /** -------------------------------------*/

    function process_sub_templates($template)
    {
        global $REGX, $FNS, $LANG, $PREFS, $DB;

		/** -------------------------------------
		/**  Match all {embed=bla/bla} tags
		/** -------------------------------------*/
        
        $matches = array();
    
        if ( ! preg_match_all("/(".LD."embed\s*=)(.*?)".RD."/s", $template, $matches))
        {
			return;
        }

		/** -------------------------------------
		/**  Loop until we have parsed all sub-templates
		/** -------------------------------------*/
		
		// For each embedded tag we encounter we'll run the template parsing
		// function - AND - through the beauty of recursive functions we
		// will also call THIS function as well, allowing us to parse 
		// infinitely nested sub-templates in one giant loop o' love
        
        $this->log_item(" - Processing Sub Templates (Depth: ".($this->depth+1).") - ");
        
        $i = 0;
        $this->depth++;
        
        $this->log_item("List of Embeds: ".str_replace(array('"', "'"), '', trim(implode(',', $matches['2']))));

		// re-match the full tag of each if necessary before we start processing
		// necessary evil in case template globals are used inside the embed tag,
		// doing this within the processing loop will result in leaving unparsed
		// embed tags e.g. {embed="foo/bar" var="{global_var}/{custom_field}"}
		$temp = $template;
		foreach ($matches[2] as $key => $val)
		{
			if (strpos($val, LD) !== FALSE)
			{
				$matches[0][$key] = $FNS->full_tag($matches[0][$key], $temp);
				$matches[2][$key] = substr(str_replace($matches[1][$key], '', $matches[0][$key]), 0, -1);
				$temp = str_replace($matches[0][$key], '', $temp);
			}
		}

        foreach($matches['2'] as $key => $val)
		{ 
			$parts = preg_split("/\s+/", $val, 2);
			
			$this->embed_vars = (isset($parts['1'])) ? $FNS->assign_parameters($parts['1']) : array();
			
			if ($this->embed_vars === FALSE)
			{
				$this->embed_vars = array();
			}
			
			$val = $REGX->trim_slashes($REGX->strip_quotes($parts['0']));

			if ( ! stristr($val, '/'))
			{   
				continue;
			}
	
			$ex = explode("/", trim($val));
			
			if (count($ex) != 2)
			{
				continue;
			}
			
			/** ----------------------------------
			/**  Determine Site
			/** ----------------------------------*/
			
			$site_id = $PREFS->ini('site_id');
			
			if (stristr($ex[0], ':'))
			{
				$name = substr($ex[0], 0, strpos($ex[0], ':'));
				
				if ($PREFS->ini('multiple_sites_enabled') == 'y')
				{
					if (sizeof($this->sites) == 0)
					{
						$sites_query = $DB->query("SELECT site_id, site_name FROM exp_sites");
						
						foreach($sites_query->result as $row)
						{
							$this->sites[$row['site_id']] = $row['site_name'];
						}
					}
					
					$site_id = array_search($name, $this->sites);
					
					if (empty($site_id))
					{
						$site_id = $PREFS->ini('site_id');
					}
				}
				
				$ex[0] = str_replace($name.':', '', $ex[0]);
			}
			
			
			/** ----------------------------------
			/**  Loop Prevention
			/** ----------------------------------*/

			/* -------------------------------------------
			/*	Hidden Configuration Variable
			/*	- template_loop_prevention => 'n' 
				Whether or not loop prevention is enabled - y/n
			/* -------------------------------------------*/
		
			if (substr_count($this->templates_sofar, '|'.$site_id.':'.$ex['0'].'/'.$ex['1'].'|') > 1 && $PREFS->ini('template_loop_prevention') != 'n')
			{
				$this->final_template = ($PREFS->ini('debug') >= 1) ? str_replace('%s', $ex['0'].'/'.$ex['1'], $LANG->line('template_loop')) : "";
				return;				
			}
				
			/** ----------------------------------
			/**  Process Subtemplate
			/** ----------------------------------*/
			
			$this->log_item("Processing Sub Template: ".$ex['0']."/".$ex['1']);
				
			$this->process_template($ex['0'], $ex['1'], TRUE, $site_id);

			$this->final_template = str_replace($matches['0'][$key], $this->template, $this->final_template);

			$this->embed_type = '';
			
			// Here we go again!  Wheeeeeee.....				
			$this->process_sub_templates($this->template);
			
			// pull the subtemplate tracker back a level to the parent template
			$this->templates_sofar = substr($this->templates_sofar, 0, - strlen('|'.$site_id.':'.$ex[0].'/'.$ex[1].'|'));
		}

        $this->depth--;

        if ($this->depth == 0)
        {
        	$this->templates_sofar = '';
        }
        
    }
    /* END */



    /** -------------------------------------
    /**  Parse the template
    /** -------------------------------------*/

    function parse_template()
    {
    	global $FNS;
    
        while (TRUE)  
        {
            // Make a "floating" copy of the template which we'll progressively slice into pieces with each loop
            
            $this->fl_tmpl = $this->template;
                    
            // Identify the string position of the first occurence of a matched tag
            
            $this->in_point = strpos($this->fl_tmpl, LD.'exp:');
                              
            // If the above variable returns false we are done looking for tags
            // This single conditional keeps the template engine from spiraling 
            // out of control in an infinite loop.        
            
            if (FALSE === $this->in_point)
            {
                break;
            }
            else
            {
                /** ------------------------------------------
                /**  Process the tag data
                /** ------------------------------------------*/
                
                // These REGEXs parse out the various components contained in any given tag.
                
                // Grab the opening portion of the tag: {exp:some:tag param="value" param="value"}

                if ( ! preg_match("/".LD.'exp:'.".*?".RD."/s", $this->fl_tmpl, $matches))
                {
                	$this->template = preg_replace("/".LD.'exp:'.".*?$/", '', $this->template);
                	break;
                }
                
                $this->log_item("Tag: ".$matches['0']);
                
                // Checking for variables/tags embedded within tags
                // {exp:weblog:entries weblog="{master_weblog_name}"}                
                if (stristr(substr($matches['0'], 1), LD) !== false)
                {
                	$matches['0'] = $FNS->full_tag($matches['0']);
                }
                                
                $raw_tag = preg_replace("/(\r\n)|(\r)|(\n)|(\t)/", ' ', $matches['0']);
                                
                $tag_length = strlen($raw_tag);
                
                $data_start = $this->in_point + $tag_length;

                $tag  = trim(substr($raw_tag, 1, -1));
                $args = trim((preg_match("/\s+.*/", $tag, $matches))) ? $matches['0'] : '';
                $tag  = trim(str_replace($args, '', $tag));  
                
                $cur_tag_close = LD.SLASH.$tag.RD;
                
                // -----------------------------------------
                
                // Assign the class name/method name and any parameters
                 
                $class = $this->assign_class(substr($tag, strlen('exp') + 1));
                $args  = $FNS->assign_parameters($args);
                
				// standardized mechanism for "search" type parameters get some extra lovin'
				
				$search_fields = array();
				
				if ($args !== FALSE)
				{
					foreach ($args as $key => $val)
					{
						if (strncmp($key, 'search:', 7) == 0)
						{
							$search_fields[substr($key, 7)] = str_replace(SLASH, '/', $val);
						}
					}					
				}
				
                // Trim the floating template, removing the tag we just parsed.
                
                $this->fl_tmpl = substr($this->fl_tmpl, $this->in_point + $tag_length);
                
                $out_point = strpos($this->fl_tmpl, $cur_tag_close);
                
                // Do we have a tag pair?
                
                if (FALSE !== $out_point)
                { 
                    // Assign the data contained between the opening/closing tag pair
                    
                    $this->log_item("Closing Tag Found");
                
                    $block = substr($this->template, $data_start, $out_point);  
                    
                    // Fetch the "no_results" data
                    
                    $no_results = '';
                    $no_results_block = '';
                    
					if (preg_match("/".LD."if no_results".RD."(.*?)".LD.SLASH."if".RD."/s", $block, $match)) 
					{
						// Match the entirety of the conditional, dude.  Bad Rick!
						
						if (stristr($match['1'], LD.'if'))
						{
							$match['0'] = $FNS->full_tag($match['0'], $block, LD.'if', LD.SLASH."if".RD);
						}
						
						$no_results = substr($match['0'], strlen(LD."if no_results".RD), -strlen(LD.SLASH."if".RD));
						
						$no_results_block = $match['0'];
					}
					        
                    // Define the entire "chunk" - from the left edge of the opening tag 
                    // to the right edge of closing tag.

                    $out_point = $out_point + $tag_length + strlen($cur_tag_close);
                                        
                    $chunk = substr($this->template, $this->in_point, $out_point);
                }
                else
                {
                    // Single tag...
                    
                    $this->log_item("No Closing Tag");
                    
                    $block = ''; // Single tags don't contain data blocks
                    
					$no_results = '';
					$no_results_block = '';
                
                    // Define the entire opening tag as a "chunk"
                
                    $chunk = substr($this->template, $this->in_point, $tag_length);                
                }
                                
                // Strip the "chunk" from the template, replacing it with a unique marker.
                
                if (stristr($raw_tag, 'random'))
                {
                	$this->template = preg_replace("|".preg_quote($chunk)."|s", 'M'.$this->loop_count.$this->marker, $this->template, 1);
				}
				else
				{
					$this->template = str_replace($chunk, 'M'.$this->loop_count.$this->marker, $this->template);
				}
				
                $cfile = md5($chunk); // This becomes the name of the cache file

                // Build a multi-dimensional array containing all of the tag data we've assembled
                  
                $this->tag_data[$this->loop_count]['tag']				= $raw_tag;
                $this->tag_data[$this->loop_count]['class']				= $class['0'];
                $this->tag_data[$this->loop_count]['method']			= $class['1'];
                $this->tag_data[$this->loop_count]['tagparts']			= $class;
                $this->tag_data[$this->loop_count]['params']			= $args;
                $this->tag_data[$this->loop_count]['chunk']				= $chunk; // Matched data block - including opening/closing tags          
                $this->tag_data[$this->loop_count]['block']				= $block; // Matched data block - no tags
                $this->tag_data[$this->loop_count]['cache']				= $this->cache_status($cfile, $args); 
                $this->tag_data[$this->loop_count]['cfile']				= $cfile;
                $this->tag_data[$this->loop_count]['no_results']		= $no_results;
                $this->tag_data[$this->loop_count]['no_results_block']	= $no_results_block;
				$this->tag_data[$this->loop_count]['search_fields']		= $search_fields;
            
            } // END IF

          // Increment counter            
          $this->loop_count++;  

       } // END WHILE
    }
    /* END */


    /** -------------------------------------
    /**  Class/Method handler
    /** -------------------------------------*/

    function class_handler()
    {    
    	global $FNS, $TMPL, $DB, $PREFS;
    
        $classes = array();
        
        // Fill an array with the names of all the classes that we previously extracted from the tags
                
        for ($i = 0; $i < count($this->tag_data); $i++)
        {
            // Should we use the tag cache file?

            if ($this->tag_data[$i]['cache'] == 'CURRENT')
            {            
                // If so, replace the marker in the tag with the cache data
                
                $this->log_item("Tag Cached and Cache is Current");
                
                $this->replace_marker($i, $this->get_cache_file($this->tag_data[$i]['cfile']));
            }
            else
            {
                // Is a module or plug-in being requested?
            
                if ( ! in_array($this->tag_data[$i]['class'] , $this->modules))
                {                 
                    if ( ! in_array($this->tag_data[$i]['class'] , $this->plugins))
                    {                    
                        global $LANG, $PREFS, $OUT;
                        
                        $this->log_item("Invalid Tag");

                        if ($PREFS->ini('debug') >= 1)
                        {
                        	if ($this->tag_data[$i]['tagparts']['0'] == $this->tag_data[$i]['tagparts']['1'] &&
                        		! isset($this->tag_data[$i]['tagparts']['2']))
                        	{
                        		unset($this->tag_data[$i]['tagparts']['1']);
                        	}
                        
                            $error  = $LANG->line('error_tag_syntax');
                            $error .= '<br /><br />';
                            $error .= htmlspecialchars(LD);
                            $error .= 'exp:'.implode(':', $this->tag_data[$i]['tagparts']);                
                            $error .= htmlspecialchars(RD);
                            $error .= '<br /><br />';
                            $error .= $LANG->line('error_fix_syntax');
            
                            $OUT->fatal_error($error);                         
                        }
                        else
                            return false;             
                    }
                    else
                    {
                        $classes[] = 'pi.'.$this->tag_data[$i]['class'];
                        $this->log_item("Plugin Tag: ".ucfirst($this->tag_data[$i]['class']).'/'.$this->tag_data[$i]['method']);
                    }
                }
                else
                {
                    $classes[] = $this->tag_data[$i]['class'];
                    $this->log_item("Module Tag: ".ucfirst($this->tag_data[$i]['class']).'/'.$this->tag_data[$i]['method']);
                }
            }
        }

        // Remove duplicate class names and re-order the array
        
        $classes = array_values(array_unique($classes));
        
        // Dynamically require the file that contains each class
        
        $this->log_item("Including Files for Tag and Modules");
        
        for ($i = 0; $i < count($classes); $i++)
        {
            // But before we do, make sure it hasn't already been included...
            
			if ( ! class_exists($classes[$i]))
			{
                if (substr($classes[$i], 0, 3) == 'pi.')
                {
                    require_once PATH_PI.$classes[$i].EXT;                 
                }
                else
                {
                    require_once PATH_MOD.$classes[$i].'/mod.'.$classes[$i].EXT;
                }
			}
        }
        
        /** -----------------------------------
        /**  Only Retrieve Data if Not Done Before and Modules Being Called
        /** -----------------------------------*/
        
        if (sizeof($this->module_data) == 0 && sizeof(array_intersect($this->modules, $classes)) > 0)
        {
        	$query = $DB->query("SELECT module_version, module_name FROM exp_modules");
        	
        	foreach($query->result as $row)
        	{
        		$this->module_data[$row['module_name']] = array('version' => $row['module_version']);
        	}
        }
                
        // Final data processing

        // Loop through the master array containing our extracted template data
        
        $this->log_item("Beginning Final Tag Data Processing");
        
        reset($this->tag_data);
        
        for ($i = 0; $i < count($this->tag_data); $i++)
        { 
            if ($this->tag_data[$i]['cache'] != 'CURRENT')
            {
            	$this->log_item("Calling Class/Method: ".ucfirst($this->tag_data[$i]['class'])."/".$this->tag_data[$i]['method']);
            
            	/* ---------------------------------
				/*  Plugin as Parameter
				/*
				/*  - Example: weblog="{exp:some_plugin}"
				/*  - A bit of a hidden feature.  Has been tested but not quite
				/*  ready to say it is ready for prime time as I might want to 
				/*  move it to earlier in processing so that if there are 
				/*  multiple plugins being used as parameters it is only called
				/*  once instead of for every single parameter. - Paul
				/* ---------------------------------*/
				
				if (substr_count($this->tag_data[$i]['tag'], LD.'exp') > 1 && isset($this->tag_data[$i]['params']['parse']) && $this->tag_data[$i]['params']['parse'] == 'inward')
				{
					foreach($this->tag_data[$i]['params'] as $name => $param)
					{
						if (stristr($this->tag_data[$i]['params'][$name], LD.'exp'))
						{
							$this->log_item("Plugin in Parameter, Processing Plugin First");
						
							$TMPL2 = $FNS->clone_object($this);
							
							while (is_int(strpos($TMPL2->tag_data[$i]['params'][$name], LD.'exp:')))
							{
								$TMPL = new Template();
								$TMPL->start_microtime = $this->start_microtime;
								$TMPL->template = $TMPL2->tag_data[$i]['params'][$name];
								$TMPL->tag_data	= array();
								$TMPL->var_single = array();
								$TMPL->var_cond	= array();
								$TMPL->var_pair	= array();
								$TMPL->plugins = $TMPL2->plugins;
								$TMPL->modules = $TMPL2->modules;
								$TMPL->parse_template();
								$TMPL->class_handler();
								$TMPL->loop_count = 0;
								$TMPL2->tag_data[$i]['params'][$name] = $TMPL->template;
								$TMPL2->log = array_merge($TMPL2->log, $TMPL->log);
							}
							
							foreach (get_object_vars($TMPL2) as $key => $value)
							{
								$this->$key = $value;
							}
							
							unset($TMPL2);
						
							$TMPL = $this;
						}
					}
				}
            
				/** ---------------------------------
				/**  Nested Plugins...
				/** ---------------------------------*/
				
				if (in_array($this->tag_data[$i]['class'] , $this->plugins) && strpos($this->tag_data[$i]['block'], LD.'exp:') !== false)
				{
					if ( ! isset($this->tag_data[$i]['params']['parse']) OR $this->tag_data[$i]['params']['parse'] != 'inward')
					{
						$this->log_item("Nested Plugins in Tag, Parsing Outward First");
						
						$TMPL2 = $FNS->clone_object($this);
					
						while (is_int(strpos($TMPL2->tag_data[$i]['block'], LD.'exp:')))
						{
							$TMPL = new Template();
							$TMPL->start_microtime = $this->start_microtime;
							$TMPL->template = $TMPL2->tag_data[$i]['block'];
							$TMPL->tag_data	= array();
							$TMPL->var_single = array();
							$TMPL->var_cond	= array();
							$TMPL->var_pair	= array();
							$TMPL->plugins = $TMPL2->plugins;
							$TMPL->modules = $TMPL2->modules;
							$TMPL->parse_template();
							$TMPL->class_handler();
							$TMPL->loop_count = 0;
							$TMPL2->tag_data[$i]['block'] = $TMPL->template;
							$TMPL2->log = array_merge($TMPL2->log, $TMPL->log);
						}
						
						foreach (get_object_vars($TMPL2) as $key => $value)
						{
  							$this->$key = $value;
						}
						
						unset($TMPL2);
					
						$TMPL = $this;
					}
				}
				
                // Assign the data chunk, parameters
                
                // We moved the no_results_block here because of nested tags. The first 
                // parsed tag has priority for that conditional.
                $this->tagdata   		= str_replace($this->tag_data[$i]['no_results_block'], '', $this->tag_data[$i]['block']);
                $this->tagparams 		= $this->tag_data[$i]['params']; 
                $this->tagchunk  		= $this->tag_data[$i]['chunk'];
                $this->tagproper		= $this->tag_data[$i]['tag'];
                $this->tagparts			= $this->tag_data[$i]['tagparts'];
                $this->no_results		= $this->tag_data[$i]['no_results'];
				$this->search_fields	= $this->tag_data[$i]['search_fields'];
                
				/** -------------------------------------
				/**  Assign Sites for Tag
				/** -------------------------------------*/
                
				$this->_fetch_site_ids();
                
				/** -------------------------------------
				/**  Relationship Data Pulled Out
				/** -------------------------------------*/
				
				// If the weblog:entries tag or search:search_results is being called
                // we need to extract any relationship data that might be present.
                // Note: This needs to happen before extracting the variables
                // in the tag so it doesn't get confused as to which entry the
                // variables belong to.
                
                if (($this->tag_data[$i]['class'] == 'weblog' AND $this->tag_data[$i]['method'] == 'entries')
					OR ($this->tag_data[$i]['class'] == 'search' AND $this->tag_data[$i]['method'] == 'search_results'))
                {                
                	$this->tagdata = $this->assign_relationship_data($this->tagdata);
                }         

                // Fetch the variables for this particular tag
                                                              
                $vars = $FNS->assign_variables($this->tag_data[$i]['block']);
                
                if (count($this->related_markers) > 0)
                {
                	foreach ($this->related_markers as $mkr)
                	{
                		if ( ! isset($vars['var_single'][$mkr]))
                		{
                			$vars['var_single'][$mkr] = $mkr;
                		}
                	}

                	$this->related_markers = array();
                }

                $this->var_single	= $vars['var_single'];
                $this->var_pair		= $vars['var_pair'];

                //  Redundant see above loop for related_markers - R.S.
                //if ($this->related_id != '')
                //{
                //	$this->var_single[$this->related_id] = $this->related_id;
                //	$this->related_id = '';
                //}
                
				//  Assign Conditional Variables
				
				if ( ! in_array($this->tag_data[$i]['class'],$this->native_modules))
				{
					$this->var_cond = $FNS->assign_conditional_variables($this->tag_data[$i]['block'], SLASH, LD, RD);
                }
                
                // Assign the class name and method name
            
                $class_name = ucfirst($this->tag_data[$i]['class']);
                
                if ($class_name == 'Commerce')
                {
                	// The Commerce module is special in that it has its own modules and its 
                	// constructor handles everything for us
                	$meth_name = 'commerce';
                }
                else
                {
                	$meth_name  = $this->tag_data[$i]['method'];
                }
                
                // Dynamically instantiate the class.
                // If module, only if it is installed...
                
                if (in_array($this->tag_data[$i]['class'], $this->modules) && ! isset($this->module_data[$class_name]))
                {
                	$this->log_item("Problem Processing Module: Module Not Installed");
                }
                else
                {
                	$this->log_item(" -> Class Called: ".$class_name);
                	
                	$EE = new $class_name();
                }
                
                /** ----------------------------------
				/**  Does method exist?  Is This A Module and Is It Installed?
				/** ----------------------------------*/
        
                if ((in_array($this->tag_data[$i]['class'], $this->modules) && ! isset($this->module_data[$class_name])) OR ! method_exists($EE, $meth_name))
                {
                    global $LANG, $PREFS, $OUT;
                    
                    $this->log_item("Tag Not Processed: Method Inexistent or Module Not Installed");

                    if ($PREFS->ini('debug') >= 1)
                    {                        
                        if ($this->tag_data[$i]['tagparts']['0'] == $this->tag_data[$i]['tagparts']['1'] &&
                        	! isset($this->tag_data[$i]['tagparts']['2']))
                        {
                        	unset($this->tag_data[$i]['tagparts']['1']);
                        }
                        
                        $error  = $LANG->line('error_tag_module_processing');
                        $error .= '<br /><br />';
                        $error .= htmlspecialchars(LD);
                        $error .= 'exp:'.implode(':', $this->tag_data[$i]['tagparts']);                 
                        $error .= htmlspecialchars(RD);
                        $error .= '<br /><br />';
                        $error .= str_replace('%x', $this->tag_data[$i]['class'], str_replace('%y', $meth_name, $LANG->line('error_fix_module_processing')));
                        
                        $OUT->fatal_error($error);
                     }
                     else
                        return;
                }    
                
                /*
                
                OK, lets grab the data returned from the class.
                
                First, however, lets determine if the tag has one or two segments.  
                If it only has one, we don't want to call the constructor again since
                it was already called during instantiation.
         
                Note: If it only has one segment, only the object constructor will be called.
                Since constructors can't return a value just by initialializing the object
                the output of the class must be assigned to a variable called $this->return_data
                               
                */
                
                $this->log_item(" -> Method Called: ".$meth_name);
                
                if (strtolower($class_name) == $meth_name)
                {
                    $return_data = (isset($EE->return_data)) ? $EE->return_data : '';
                }
                else
                {
                    $return_data = $EE->$meth_name();
                }
                
                /** ----------------------------------
                /**  404 Page Triggered, Cease All Processing of Tags From Now On
                /** ----------------------------------*/
                
                if ($this->cease_processing === TRUE)
                {
                	return;
                }
                
                $this->log_item(" -> Data Returned");
              
               // Write cache file if needed
               
                if ($this->tag_data[$i]['cache'] == 'EXPIRED')
                {
                    $this->write_cache_file($this->tag_data[$i]['cfile'], $return_data);
                }
                
                // Replace the temporary markers we added earlier with the fully parsed data
              
                $this->replace_marker($i, $return_data);
                
                // Initialize data in case there are susequent loops                
                
                $this->var_single = array();
                $this->var_cond   = array();
                $this->var_pair   = array();
                
                unset($return_data);
                unset($class_name);    
                unset($meth_name);    
                unset($EE);
            }
        }
    }
    /* END */

    /** -------------------------------------
    /**  Assign the related data 
    /** -------------------------------------*/
	
	// Weblog entries can have related entries embedded within them.
	// We'll extract the related tag data, stash it away in an array, and
	// replace it with a marker string so that the template parser
	// doesn't see it.  In the weblog class we'll check to see if the 
	// $TMPL->related_data array contains anything.  If so, we'll celebrate
	// wildly.

	function assign_relationship_data($chunk)
	{
		global $FNS;
		
		$this->related_markers = array();
		
   		if (preg_match_all("/".LD."related_entries\s+id\s*=\s*[\"\'](.+?)[\"\']".RD."(.+?)".LD.SLASH."related_entries".RD."/is", $chunk, $matches))
		{  		
			$this->log_item("Assigning Related Entry Data");
			
			$no_rel_content = '';
			
			for ($j = 0; $j < count($matches['0']); $j++)
			{
				$rand = $FNS->random('alpha', 8);
				$marker = LD.'REL['.$matches['1'][$j].']'.$rand.'REL'.RD;
				
				if (preg_match("/".LD."if no_related_entries".RD."(.*?)".LD.SLASH."if".RD."/s", $matches['2'][$j], $no_rel_match)) 
				{
					// Match the entirety of the conditional
					
					if (stristr($no_rel_match['1'], LD.'if'))
					{
						$match['0'] = $FNS->full_tag($no_rel_match['0'], $matches['2'][$j], LD.'if', LD.SLASH."if".RD);
					}
					
					$no_rel_content = substr($no_rel_match['0'], strlen(LD."if no_related_entries".RD), -strlen(LD.SLASH."if".RD));
				}
				
				$this->related_markers[] = $matches['1'][$j];
				$vars = $FNS->assign_variables($matches['2'][$j]);
				
				// Depreciated as redundant.  R.S.
				//$this->related_id = $matches['1'][$j];
				
				$this->related_data[$rand] = array(
											'marker'			=> $rand,
											'field_name'		=> $matches['1'][$j],
											'tagdata'			=> $matches['2'][$j],
											'var_single'		=> $vars['var_single'],
											'var_pair' 			=> $vars['var_pair'],
											'var_cond'			=> $FNS->assign_conditional_variables($matches['2'][$j], SLASH, LD, RD),
											'no_rel_content'	=> $no_rel_content
										);
										
				$chunk = str_replace($matches['0'][$j], $marker, $chunk);					
			}
		}

		if (preg_match_all("/".LD."reverse_related_entries\s*(.*?)".RD."(.+?)".LD.SLASH."reverse_related_entries".RD."/is", $chunk, $matches))
		{  		
			$this->log_item("Assigning Reverse Related Entry Data");
		
			for ($j = 0; $j < count($matches['0']); $j++)
			{
				$rand = $FNS->random('alpha', 8);
				$marker = LD.'REV_REL['.$rand.']REV_REL'.RD;
				$vars = $FNS->assign_variables($matches['2'][$j]);
				
				$no_rev_content = '';

				if (preg_match("/".LD."if no_reverse_related_entries".RD."(.*?)".LD.SLASH."if".RD."/s", $matches['2'][$j], $no_rev_match)) 
				{
					// Match the entirety of the conditional
					
					if (stristr($no_rev_match['1'], LD.'if'))
					{
						$match['0'] = $FNS->full_tag($no_rev_match['0'], $matches['2'][$j], LD.'if', LD.SLASH."if".RD);
					}
					
					$no_rev_content = substr($no_rev_match['0'], strlen(LD."if no_reverse_related_entries".RD), -strlen(LD.SLASH."if".RD));
				}
				
				$this->reverse_related_data[$rand] = array(
															'marker'			=> $rand,
															'tagdata'			=> $matches['2'][$j],
															'var_single'		=> $vars['var_single'],
															'var_pair' 			=> $vars['var_pair'],
															'var_cond'			=> $FNS->assign_conditional_variables($matches['2'][$j], SLASH, LD, RD),
															'params'			=> $FNS->assign_parameters($matches['1'][$j]),
															'no_rev_content'	=> $no_rev_content
														);
										
				$chunk = str_replace($matches['0'][$j], $marker, $chunk);					
			}
		}
	
		return $chunk;
	}
	/* END */


    /** -------------------------------------
    /**  Assign class and method name
    /** -------------------------------------*/

    function assign_class($tag)
    {
        $result = array();
    
        // Grab the class name and method names contained 
        // in the tag and assign them to variables.
        
		$result = explode(':', $tag);
        
        // Tags can either have one segment or two:
        // {exp:first_segment}
        // {exp:first_segment:second_segment}
        //
        // These two segments represent either a "class:constructor"
        // or a "class:method".  We need to determine which one it is.
        
        if (count($result) == 1)
        {                
            $result['0'] = trim($result['0']);
            $result['1'] = trim($result['0']);
        }
        else
        {                
            foreach($result as $key => $value)
            {
            	$result[$key] = trim($result[$key]);
            }
        }
        
        return $result;
    }
    /* END */


    /** ---------------------------------------
    /**  Fetch a specific parameter
    /** ---------------------------------------*/
        
    function fetch_param($which)
    {
        return ( ! isset($this->tagparams[$which])) ? FALSE : $this->tagparams[$which];
    }
    /* END */


    /** ---------------------------------------
    /**  Swap single variables with final value
    /** ---------------------------------------*/

    function swap_var_single($search, $replace, $source)
    {
        return str_replace(LD.$search.RD, $replace, $source);  
    }
    /* END */


    /** ---------------------------------------
    /**  Swap variable pairs with final value
    /** ---------------------------------------*/

    function swap_var_pairs($open, $close, $source)
    {
        return preg_replace("/".LD.preg_quote($open).RD."(.*?)".LD.SLASH.$close.RD."/s", "\\1", $source); 
    }
    /* END */


    /** ---------------------------------------
    /**  Delete variable pairs
    /** ---------------------------------------*/

    function delete_var_pairs($open, $close, $source)
    {
        return preg_replace("/".LD.preg_quote($open).RD."(.*?)".LD.SLASH.$close.RD."/s", "", $source); 
    }
    /* END */



    /** ---------------------------------------
    /**  Swap conditional variables
    /** ---------------------------------------*/

    function swap_conditional($search, $replace, $source)
    {
        return str_replace($search, $replace, $source); 
    }
    /* END */


    /** -----------------------------------------
    /**  Fetch the data in-between two variables
    /** -----------------------------------------*/

    function fetch_data_between_var_pairs($str, $variable)
    {
        if ($str == '' || $variable == '')
            return;
        
        if ( ! preg_match("/".LD.$variable.".*?".RD."(.*?)".LD.SLASH.$variable.RD."/s", $str, $match))
               return;
 
        return $match['1'];        
    }
    /* END */


    /** -------------------------------------
    /**  Parse PHP in template
    /** -------------------------------------*/

     function parse_template_php($str)
     {
     	global $FNS;
     	
		ob_start();
		
		echo $FNS->evaluate($str);
		
		$str = ob_get_contents();
		
		ob_end_clean(); 
		
		$this->parse_php = FALSE;
		
		return $str;
     }
     /* END */
     

    /** ---------------------------------------
    /**  Replace marker with final data
    /** ---------------------------------------*/

    function replace_marker($i, $return_data)
    {       
        $this->template = str_replace('M'.$i.$this->marker, $return_data, $this->template);
    }
    /* END */


    /** -----------------------------------------
    /**  Set caching status
    /** -----------------------------------------*/

    function cache_status($cfile, $args, $cache_type = 'tag')
    {
        // Three caching states:  

        // NO_CACHE = do not cache 
        // EXPIRED  = cache file has expired
        // CURRENT  = cache file has not expired
                        
        if ( ! isset($args['cache']))
            return 'NO_CACHE';
            
        if ($args['cache'] != 'yes')
            return 'NO_CACHE';

        $cache_dir = ($cache_type == 'tag') ? PATH_CACHE.$this->t_cache_path : $cache_dir = PATH_CACHE.$this->p_cache_path;

        $cache_file = $cache_dir.'t_'.$cfile;
        
        if ( ! file_exists($cache_file))
            return 'EXPIRED';
        
        if ( ! $fp = @fopen($cache_file, 'rb'))
            return 'EXPIRED';
            
            flock($fp, LOCK_SH);
            
			$timestamp = trim(@fread($fp, filesize($cache_file)));
			            
            flock($fp, LOCK_UN);
            
            fclose($fp);
            
            $refresh = ( ! isset($args['refresh'])) ? 0 : $args['refresh']; 
                    
        if (time() > ($timestamp + ($refresh * 60)))
        {
            return 'EXPIRED';   
        }
        else
        {
            if ( ! file_exists($cache_dir.'c_'.$cfile))
            {
                return 'EXPIRED';
            }
            
            $this->cache_timestamp = $timestamp;
            
            return 'CURRENT';
        } 
    }
    /* END */



    /** -----------------------------------------
    /**  Get cache file
    /** -----------------------------------------*/

    function get_cache_file($cfile, $cache_type = 'tag')
    {
        $cache = '';

        $cache_dir = ($cache_type == 'tag') ? PATH_CACHE.$this->t_cache_path : $cache_dir = PATH_CACHE.$this->p_cache_path;

        $fp = @fopen($cache_dir.'c_'.$cfile, 'rb');
        
        flock($fp, LOCK_SH);
                    
        $cache = @fread($fp, filesize($cache_dir.'c_'.$cfile));
                    
        flock($fp, LOCK_UN);
        
        fclose($fp);
        
        return $cache;
    }
    /* END */



    /** -----------------------------------------
    /**  Write cache file
    /** -----------------------------------------*/

    function write_cache_file($cfile, $data, $cache_type = 'tag')
    {
		global $PREFS;
		
    	if ($this->disable_caching == TRUE)
    	{
    		return;
    	}
    	
		/* -------------------------------------
		/*  Disable Tag Caching
		/*  
		/*  All for you, Nevin!  Disables tag caching, which if used unwisely
		/*  on a high traffic site can lead to disastrous disk i/o
		/*  This setting allows quick thinking admins to temporarily disable
		/*  it without hacking or modifying folder permissions
		/*  
		/*  Hidden Configuration Variable
		/*  - disable_tag_caching => Disable tag caching? (y/n)
		/* -------------------------------------*/

		if ($cache_type == 'tag' && $PREFS->ini('disable_tag_caching') == 'y')
		{
			return;
		}

        $cache_dir  = ($cache_type == 'tag') ? PATH_CACHE.$this->t_cache_path : $cache_dir = PATH_CACHE.$this->p_cache_path;
        $cache_base = ($cache_type == 'tag') ? PATH_CACHE.'tag_cache' : PATH_CACHE.'page_cache';
                
        $time_file  = $cache_dir.'t_'.$cfile;
        $cache_file = $cache_dir.'c_'.$cfile;
        
        $dirs = array($cache_base, $cache_dir);
        
        foreach ($dirs as $dir)
        {       
			if ( ! @is_dir($dir))
			{
				if ( ! @mkdir($dir, 0777))
				{
					return;
				}

				if ($dir == $cache_base && $fp = @fopen($dir.'/index.html', 'wb'))
				{
					fclose($fp);					
				}
								
				@chmod($dir, 0777);            
			}
        }
                
        // Write the timestamp file
        if ( ! $fp = @fopen($time_file, 'wb'))
            return;

        flock($fp, LOCK_EX);
        fwrite($fp, time());
        flock($fp, LOCK_UN);
        fclose($fp);
        
		@chmod($time_file, 0777); 

        // Write the data cache

        if ( ! $fp = @fopen($cache_file, 'wb'))
            return;

        flock($fp, LOCK_EX);
        fwrite($fp, $data);
        flock($fp, LOCK_UN);
        fclose($fp);
        
		@chmod($cache_file, 0777); 
    }
    /* END */


    /** -------------------------------------
    /**  Parse Template URI Data
    /** -------------------------------------*/

    function parse_template_uri()
    {
        global $PREFS, $LANG, $OUT, $DB, $LOC, $IN, $REGX;
        
        $this->log_item("Parsing Template URI");
        
        // Does the first segment exist?  No?  Show the default template   
        if ($IN->fetch_uri_segment(1) === FALSE)
        {     
			return $this->fetch_template('', 'index', TRUE);
        }
        // Is only the pagination showing in the URI?
        elseif(count($IN->SEGS) == 1 && preg_match("#^(P\d+)$#", $IN->fetch_uri_segment(1), $match))
        {
        	$IN->QSTR = $match['1'];
        	return $this->fetch_template('', 'index', TRUE);
        }
        
        // Set the strict urls pref
        if ($PREFS->ini('strict_urls') !== FALSE)
        {
        	$this->strict_urls = ($PREFS->ini('strict_urls') == 'y') ? TRUE : FALSE;
        }

        // At this point we know that we have at least one segment in the URI, so  
		// let's try to determine what template group/template we should show
		
		// Is the first segment the name of a template group?
		$query = $DB->query("SELECT group_id FROM exp_template_groups WHERE group_name = '".$DB->escape_str($IN->fetch_uri_segment(1))."' AND site_id = '".$DB->escape_str($PREFS->ini('site_id'))."'");
	
		// Template group found!
		if ($query->num_rows == 1)
		{
			// Set the name of our template group
			$template_group = $IN->fetch_uri_segment(1);

			// Set the group_id so we can use it in the next query
			$group_id = $query->row['group_id'];
		
			// Does the second segment of the URI exist? If so...
			if ($IN->fetch_uri_segment(2) !== FALSE)
			{
				// Is the second segment the name of a valid template?
				$query = $DB->query("SELECT COUNT(*) AS count FROM exp_templates WHERE group_id = '{$group_id}' AND template_name = '".$DB->escape_str($IN->fetch_uri_segment(2))."'");
			
				// We have a template name!
				if ($query->row['count'] == 1)
				{
					// Assign the template name
					$template = $IN->fetch_uri_segment(2);
					
					// Re-assign the query string variable in the Input class so the various tags can show the correct data
					$IN->QSTR = ( ! $IN->fetch_uri_segment(3) AND $IN->fetch_uri_segment(2) != 'index') ? '' : $REGX->trim_slashes(substr($IN->URI, strlen('/'.$IN->fetch_uri_segment(1).'/'.$IN->fetch_uri_segment(2))));
				}
				else // A valid template was not found
				{				
					// Set the template to index		
					$template = 'index';
				   
					// Re-assign the query string variable in the Input class so the various tags can show the correct data
					$IN->QSTR = ( ! $IN->fetch_uri_segment(3)) ? $IN->fetch_uri_segment(2) : $REGX->trim_slashes(substr($IN->URI, strlen('/'.$IN->fetch_uri_segment(1))));
				}
			}
			// The second segment of the URL does not exist
			else
			{
				// Set the template as "index"
				$template = 'index';
			}
		}
		// The first segment in the URL does NOT correlate to a valid template group.  Oh my!
		else 
		{
			// If we are enforcing strict URLs we need to show a 404
			if ($this->strict_urls == TRUE)
			{
				if ($PREFS->ini('site_404'))
				{
					$this->log_item("Template group and template not found, showing 404 page");
					return $this->fetch_template('', '', FALSE);
				}
				else
				{
					return $this->_404();
				}
			}
			
			// We we are not enforcing strict URLs, so Let's fetch the the name of the default template group
			$result = $DB->query("SELECT group_name, group_id FROM exp_template_groups WHERE is_site_default = 'y' AND site_id = '".$DB->escape_str($PREFS->ini('site_id'))."'");

			// No result?  Bail out...
			// There's really nothing else to do here.  We don't have a valid template group in the URL
			// and the admin doesn't have a template group defined as the site default.
			if ($result->num_rows == 0)
			{
				// Turn off caching 
				$this->disable_caching = TRUE;

				// Show the user-specified 404
				if ($PREFS->ini('site_404'))
				{
					$this->log_item("Template group and template not found, showing 404 page");
					return $this->fetch_template('', '', FALSE);
				}
				else
				{
					// Show the default 404
					return $this->_404();
				}
			}
			
			// Since the first URI segment isn't a template group name, could it be the name of a template in the default group?			
			$query = $DB->query("SELECT COUNT(*) AS count FROM exp_templates WHERE group_id = '".$result->row['group_id']."' AND template_name = '".$DB->escape_str($IN->fetch_uri_segment(1))."'");
		
			// We found a valid template!
			if ($query->row['count'] == 1)
			{ 
				// Set the template group name from the prior query result (we use the default template group name)
				$template_group	= $result->row['group_name'];

				// Set the template name
				$template = $IN->fetch_uri_segment(1);				

				// Re-assign the query string variable in the Input class so the various tags can show the correct data
				if ($IN->fetch_uri_segment(2))
				{
					$IN->QSTR = $REGX->trim_slashes(substr($IN->URI, strlen('/'.$IN->fetch_uri_segment(1))));
				}			
			}
			// A valid template was not found.  At this point we do not have either a valid template group or a valid template name in the URL
			else
			{
				// Turn off caching 
				$this->disable_caching = TRUE;

				// is 404 preference set, we wet our group/template names as blank.
				// The fetch_template() function below will fetch the 404 and show it
				if ($PREFS->ini('site_404'))
				{
					$template_group = '';
					$template = '';
					$this->log_item("Template group and template not found, showing 404 page");
				}
				else
				// No 404 preference is set so we will show the index template from the default template group
				{
					$IN->QSTR = $REGX->trim_slashes($IN->URI);
					$template_group	= $result->row['group_name'];
					$template = 'index';
					$this->log_item("Showing index. Template not found: ".$IN->fetch_uri_segment(1));
				}
			}		
		}

		// Fetch the template!
       return $this->fetch_template($template_group, $template, FALSE);
    }
   // END

    /** -----------------------------------------
    /**  404 page
    /** -----------------------------------------*/

	function _404()
	{
		global $OUT;
		$this->log_item("404 Page Returned");
		$OUT->http_status_header(404);
		echo '<html><head><title>404 Page Not Found</title></head><body><h1>Status: 404 Page Not Found</h1></body></html>';
		exit;	
	}


    /** -----------------------------------------
    /**  Fetch the requested template
    /** -----------------------------------------*/

    function fetch_template($template_group, $template, $show_default = TRUE, $site_id = '')
    {
        global $PREFS, $LANG, $OUT, $DB, $IN, $SESS, $FNS, $LOC;
        
        if ($site_id == '' OR ! is_numeric($site_id))
        {
        	$site_id = $PREFS->ini('site_id');
        }
        
        $this->log_item("Retrieving Template from Database: ".$template_group.'/'.$template);
         
        $sql_404 = '';
        
		/** ---------------------------------------
		/**  Is this template supposed to be "hidden"?
		/** ---------------------------------------*/
		
		/* -------------------------------------------
		/*	Hidden Configuration Variable
		/*	- hidden_template_indicator => '.' 
			The character(s) used to designate a template as "hidden"
		/* -------------------------------------------*/
	
		$hidden_indicator = ($PREFS->ini('hidden_template_indicator') === FALSE) ? '.' : $PREFS->ini('hidden_template_indicator');			
		
		if ($this->depth == 0 AND substr($template, 0, 1) == $hidden_indicator)
		{			
			/* -------------------------------------------
			/*	Hidden Configuration Variable
			/*	- hidden_template_404 => y/n 
				If a hidden template is encountered, the default behavior is
				to throw a 404.  With this set to 'n', the template group's
				index page will be shown instead
			/* -------------------------------------------*/
			
			if ($PREFS->ini('hidden_template_404') !== 'n')
			{				
				$x = explode("/", $PREFS->ini('site_404'));
				
				if (isset($x['0']) AND isset($x['1']))
				{
					$OUT->out_type = '404';
					$this->template_type = '404';
					
					$sql_404 = " AND exp_template_groups.group_name='".$DB->escape_str($x['0'])."' AND exp_templates.template_name='".$DB->escape_str($x['1'])."'";
				}
				else
				{
					$template = 'index';
				}
			}
			else
			{
				$template = 'index';
			}
		}
		
        if ($template_group == '' && $show_default == FALSE && USER_BLOG === FALSE && $PREFS->ini('site_404') != '')
        {
			$treq = $PREFS->ini('site_404');
			
			$x = explode("/", $treq);

			if (isset($x['0']) AND isset($x['1']))
			{
				$OUT->out_type = '404';
				$this->template_type = '404';
				
				$sql_404 = " AND exp_template_groups.group_name='".$DB->escape_str($x['0'])."' AND exp_templates.template_name='".$DB->escape_str($x['1'])."'";
			}	
        }
         
        $sql = "SELECT exp_templates.template_name, 
                       exp_templates.template_id, 
                       exp_templates.template_data, 
                       exp_templates.template_type,
                       exp_templates.edit_date,
                       exp_templates.save_template_file,
                       exp_templates.cache, 
                       exp_templates.refresh, 
                       exp_templates.no_auth_bounce, 
                       exp_templates.enable_http_auth,
                       exp_templates.allow_php, 
                       exp_templates.php_parse_location,
                       exp_templates.hits,
                       exp_template_groups.group_name
                FROM   exp_template_groups, exp_templates
                WHERE  exp_template_groups.group_id = exp_templates.group_id
                AND    exp_template_groups.site_id = '".$DB->escape_str($site_id)."' ";
                
		if ($sql_404 != '')
        {
			$sql .= $sql_404;
		}
		else
		{
			if ($template != '')
				$sql .= " AND exp_templates.template_name = '".$DB->escape_str($template)."' ";
		
			if ($show_default == TRUE && USER_BLOG === FALSE)
			{
				$sql .= "AND exp_template_groups.is_site_default = 'y'";				
			}
			else
			{
				$sql .= "AND exp_template_groups.group_name = '".$DB->escape_str($template_group)."'";
			}
        }
                
        $query = $DB->query($sql);

        if ($query->num_rows == 0)
        {
        	$this->log_item("Template Not Found");
            return FALSE;
        }
        
        $this->log_item("Template Found");
		
		/** ----------------------------------------------------
        /**  HTTP Authentication
        /** ----------------------------------------------------*/
		
		if ($query->row['enable_http_auth'] == 'y')
        {
        	$this->log_item("HTTP Authentication in Progress");
        
        	$results = $DB->query("SELECT member_group 
        						  FROM exp_template_no_access 
        						  WHERE template_id = '".$DB->escape_str($query->row['template_id'])."'");
        						  
        	$not_allowed_groups = array('2', '3', '4');
        	
        	if ($results->num_rows > 0)
        	{
        		foreach($results->result as $row)
        		{
        			$not_allowed_groups[] = $row['member_group'];
        		}
        	}		  
        
        	if ($this->template_authentication_check_basic($not_allowed_groups) !== TRUE)
        	{
        	    $this->template_authentication_basic();
        	}
        }


        /** ----------------------------------------------------
        /**  Is the current user allowed to view this template?
        /** ----------------------------------------------------*/
        
        if ($query->row['enable_http_auth'] != 'y' && $query->row['no_auth_bounce'] != '')
        {
        	$this->log_item("Determining Template Access Privileges");
        
            $result = $DB->query("SELECT count(*) AS count FROM exp_template_no_access WHERE template_id = '".$DB->escape_str($query->row['template_id'])."' AND member_group = '".$DB->escape_str($SESS->userdata['group_id'])."'");
            
            if ($result->row['count'] > 0)
            { 
            	if ($this->depth > 0)
            	{
            		return '';
            	}
            
                $sql = "SELECT	a.template_id, a.template_data, a.template_name, a.template_type, a.edit_date, a.save_template_file, a.cache, a.refresh, a.hits, a.allow_php, a.php_parse_location, b.group_name
                        FROM	exp_templates a, exp_template_groups b
                        WHERE	a.group_id = b.group_id
                        AND		template_id = '".$DB->escape_str($query->row['no_auth_bounce'])."'";
        
                $query = $DB->query($sql);
            }
        }
        
        if ($query->num_rows == 0)
        {
            return false;
        }
        
        /** -----------------------------------------
        /**  Is PHP allowed in this template?
        /** -----------------------------------------*/
        
		if ($query->row['allow_php'] == 'y' AND $PREFS->ini('demo_date') == FALSE)
		{
			$this->parse_php = TRUE;
			
			$this->php_parse_location = ($query->row['php_parse_location'] == 'i') ? 'input' : 'output';
		}
		
        /** -----------------------------------------
        /**  Increment hit counter
        /** -----------------------------------------*/

        if (($this->hit_lock == FALSE OR $this->hit_lock_override == TRUE) AND $PREFS->ini('enable_hit_tracking') != 'n')
        {
            $this->template_hits = $query->row['hits'] + 1;
            $this->hit_lock = TRUE;
            
            $DB->query("UPDATE exp_templates SET hits = '".$this->template_hits."' WHERE template_id = '".$DB->escape_str($query->row['template_id'])."'");
        }
        
        /** -----------------------------------------
        /**  Set template edit date
        /** -----------------------------------------*/

		$this->template_edit_date = $query->row['edit_date'];

        /** -----------------------------------------
        /**  Set template type for our page headers
        /** -----------------------------------------*/

        if ($this->template_type == '')
        { 
            $this->template_type = $query->row['template_type'];
            $FNS->template_type = $query->row['template_type'];
            
            /** -----------------------------------------
			/**  If JS or CSS request, reset Tracker Cookie
			/** -----------------------------------------*/
            
            if ($this->template_type == 'js' OR $this->template_type == 'css')
            {
            	if (sizeof($SESS->tracker) <= 1)
            	{
            		$SESS->tracker = array();
            	}
            	else
            	{
            		$removed = array_shift($SESS->tracker);
            	}
            	
            	$FNS->set_cookie('tracker', serialize($SESS->tracker), '0'); 
            }
        }
        
        if ($this->depth > 0)
        {
        	$this->embed_type = $query->row['template_type'];
        }
        
        /** -----------------------------------------
        /**  Cache Override
        /** -----------------------------------------*/
        
        // We can manually set certian things not to be cached, like the
        // search template and the member directory after it's updated
        
     	// Note: I think search caching is OK.
		// $cache_override = array('member' => 'U', 'search' => FALSE);
		
		$cache_override = array('member');

        foreach ($cache_override as $val)
        {
			if (preg_match("#^/".preg_quote($val, '#')."/#", $IN->URI))
			{
				$query->row['cache'] = 'n';
			}
        }
        
        /** -----------------------------------------
        /**  Retreive cache
        /** -----------------------------------------*/
                      
		$this->cache_hash = md5($site_id.'-'.$template_group.'-'.$template);

        if ($query->row['cache'] == 'y')
        {
            $this->cache_status = $this->cache_status($this->cache_hash, array('cache' => 'yes', 'refresh' => $query->row['refresh']), 'template');
         
            if ($this->cache_status == 'CURRENT')
            {
                return $this->convert_xml_declaration($this->get_cache_file($this->cache_hash, 'template'));                
            }            
        }
        
		/** -----------------------------------------
        /**  Retreive template file if necessary
        /** -----------------------------------------*/
        
        if ($query->row['save_template_file'] == 'y')
        {
        	$site_switch = FALSE;
        	
        	if ($PREFS->ini('site_id') != $site_id)
        	{
        		$site_switch = $PREFS->core_ini;
        		
        		if (isset($this->site_prefs_cache[$site_id]))
        		{
        			$PREFS->core_ini = $this->site_prefs_cache[$site_id];
        		}
        		else
        		{
        			$PREFS->site_prefs('', $site_id);
					$this->site_prefs_cache[$site_id] = $PREFS->core_ini;
        		}
        	}

        	if ($PREFS->ini('save_tmpl_files') == 'y' AND $PREFS->ini('tmpl_file_basepath') != '')
        	{
				$this->log_item("Retrieving Template from File");
				
				$basepath = rtrim($PREFS->ini('tmpl_file_basepath'), '/').'/';
										
				$basepath .= $query->row['group_name'].'/'.$query->row['template_name'].'.php';
				
				if ($fp = @fopen($basepath, 'rb'))
				{
					flock($fp, LOCK_SH);
					
					$query->row['template_data'] = (filesize($basepath) == 0) ? '' : fread($fp, filesize($basepath)); 
					
					flock($fp, LOCK_UN);
					fclose($fp); 
				}
			}
			
			if ($site_switch !== FALSE)
			{
				$PREFS->core_ini = $site_switch;
			}
        }
        
		// standardize newlines
		$query->row['template_data'] = preg_replace("/(\015\012)|(\015)|(\012)/", "\n", $query->row['template_data']); 

        return $this->convert_xml_declaration($this->remove_ee_comments($query->row['template_data']));
    }
    /* END */


	/** -------------------------------------
	/**  "no results" tag
	/** -------------------------------------*/
	
	function no_results()
	{
		global $FNS, $PREFS, $OUT;
	
        if ( ! preg_match("/".LD."redirect\s*=\s*(\042|\047)([^\\1]*?)\\1".RD."/si", $this->no_results, $match))
        {
			$this->log_item("Returning No Results Content");
			return $this->no_results;
        }
        else
        {
			$this->log_item("Processing No Results Redirect");
			
			if ($match['2'] == "404")
			{
				$template = explode('/', $PREFS->ini('site_404'));
				
				if (isset($template['1']))
				{
					$this->log_item('Processing "'.$template['0'].'/'.$template['1'].'" Template as 404 Page');
					$OUT->out_type = "404";
					$this->template_type = "404";
					$this->process_template($template['0'], $template['1']);
					$this->cease_processing = TRUE;
				}
				else
				{
					$this->log_item('404 redirect requested, but no 404 page is specified in the Global Template Preferences');
					return $this->no_results;
				}
			}
			else
			{
				return $FNS->redirect($FNS->create_url($FNS->extract_path("=".str_replace("&#47;", "/", $match['2']))));
			}
        }
	}
	/* END */


	/** -------------------------------------
	/**  Convert XML declaration in RSS page
	/** -------------------------------------*/
	
	// This fixes a parsing error when PHP is used in RSS templates

	function convert_xml_declaration($str)
	{		
		return preg_replace("/\<\?xml(.+?)\?\>/", "<XXML\\1/XXML>", $str);
	}
	/* END */
	
	/** -------------------------------------
	/**  Restore XML declaration in RSS page
	/** -------------------------------------*/
	
	function restore_xml_declaration($str)
	{		
		return preg_replace("/\<XXML(.+?)\/XXML\>/", "<?xml\\1?>", $str); // <?
	}
	/* END */
	
	/** -------------------------------------
	/**  Remove EE Template Comments
	/** -------------------------------------*/

	function remove_ee_comments($str)
	{	
		return preg_replace("/\{!--.*?--\}/s", '', $str);
	}
	/* END */
	

    /** -------------------------------------
    /**  Fetch installed modules
    /** -------------------------------------*/
    
    function fetch_modules()
    {   
        if (sizeof($this->modules) == 0 && $fp = @opendir(PATH_MOD)) 
        { 
            while (false !== ($file = readdir($fp))) 
            {
            	if ( is_dir(PATH_MOD.$file) && ! preg_match("/[^a-z\_0-9]/", $file))
				{
					$this->modules[] = $file;
                }
            } 
			closedir($fp); 
        } 
    }
    /* END */



    /** -------------------------------------
    /**  Fetch installed plugins
    /** -------------------------------------*/
    
    function fetch_plugins()
    {     
        if ($fp = @opendir(PATH_PI)) 
        { 
            while (false !== ($file = readdir($fp))) 
            {
            	if ( preg_match("/pi\.[a-z\_0-9]+?".preg_quote(EXT, '/')."$/", $file))
				{                            
					$this->plugins[] = substr($file, 3, - strlen(EXT));
				}
            } 
            
			closedir($fp); 
        } 
    }
    /* END */



    /** ------------------------------------------------
    /**  Parse global variables and non-cachable stuff
    /** ------------------------------------------------*/

    // The syntax is generally: {global:variable_name}
    
    function parse_globals($str)
    {    
        global $LANG, $PREFS, $FNS, $IN, $DB, $LOC, $SESS;
        
        $charset 	= '';
        $lang		= '';
		$user_vars	= array('member_id', 'group_id', 'group_description', 'group_title', 'member_group', 'username', 'screen_name', 'email', 'ip_address', 'location', 'total_entries', 'total_comments', 'private_messages', 'total_forum_posts', 'total_forum_topics', 'total_forum_replies');            
        
        /** --------------------------------------------------
        /**  Redirect - if we have one of these, no need to go further
        /** --------------------------------------------------*/
     	
		if (strpos($str, LD.'redirect') !== FALSE)
		{
			if (preg_match("/".LD."redirect\s*=\s*(\042|\047)([^\\1]*?)\\1".RD."/si", $str, $match))
			{
				if ($match['2'] == "404")
				{
					$template = explode('/', $PREFS->ini('site_404'));

					if (isset($template['1']))
					{
						$this->log_item('Processing "'.$template['0'].'/'.$template['1'].'" Template as 404 Page');
						$this->template_type = "404";
						$this->process_template($template['0'], $template['1']);
						$this->cease_processing = TRUE;
						// the resulting template will not have globals parsed unless we do this
						return $this->parse_globals($this->final_template);
					}
					else
					{
						$this->log_item('404 redirect requested, but no 404 page is specified in the Global Template Preferences');
						return $this->_404();
					}
				}
				else
				{
					// $FNS->redirect() exit;s on its own
					$FNS->redirect($FNS->create_url($FNS->extract_path("=".str_replace("&#47;", "/", $match['2']))));
				}
			}
		}
		
        /** --------------------------------------------------
        /**  Restore XML declaration if it was encoded
        /** --------------------------------------------------*/
       
        $str = $this->restore_xml_declaration($str);
        
        /** --------------------------------------------------
        /**  {hits}
        /** --------------------------------------------------*/

		$str = str_replace(LD.'hits'.RD, $this->template_hits, $str);  
        
        /** --------------------------------------------------
        /**  {ip_address} and {ip_hostname}
        /** --------------------------------------------------*/
        
		$str = str_replace(LD.'ip_address'.RD, $IN->IP, $str); 
         
		// Turns out gethostbyaddr() is WAY SLOW on many systems so I'm killing it.         
        // $str = str_replace(LD.'ip_hostname'.RD, @gethostbyaddr($IN->IP), $str); 
		
		$str = str_replace(LD.'ip_hostname'.RD, $IN->IP, $str); 
                                
        /** --------------------------------------------------
        /**  {homepage}
        /** --------------------------------------------------*/
        
        $str = str_replace(LD.'homepage'.RD, $FNS->fetch_site_index(), $str); 
                
        /** --------------------------------------------------
        /**  {site_name} {site_url} {site_index}
        /** --------------------------------------------------*/
        
        $str = str_replace(LD.'site_name'.RD, stripslashes($PREFS->ini('site_name')), $str);
        $str = str_replace(LD.'site_url'.RD, stripslashes($PREFS->ini('site_url')), $str);
        $str = str_replace(LD.'site_index'.RD, stripslashes($PREFS->ini('site_index')), $str);
        $str = str_replace(LD.'webmaster_email'.RD, stripslashes($PREFS->ini('webmaster_email')), $str);

        /** --------------------------------------------------
        /**  Stylesheet variable: {stylesheet=group/template}
        /** --------------------------------------------------*/

        $qs = ($PREFS->ini('force_query_string') == 'y') ? '' : '?';
        
        if (preg_match_all("/".LD."\s*stylesheet=[\042\047]?(.*?)[\042\047]?".RD."/", $str, $css_matches))
        {
        	$css_versions = array();
        
        	if ($PREFS->ini('send_headers') == 'y')
        	{
        		$sql = "SELECT t.template_name, tg.group_name, t.edit_date FROM exp_templates t, exp_template_groups tg
        				WHERE  t.group_id = tg.group_id
        				AND    t.template_type = 'css'
        				AND    t.site_id = '".$DB->escape_str($PREFS->ini('site_id'))."'";
        	
        		foreach($css_matches[1] as $css_match)
        		{
        			$ex = explode('/', $css_match, 2);
        			
        			if (isset($ex[1]))
        			{
        				$css_parts[] = "(t.template_name = '".$DB->escape_str($ex[1])."' AND tg.group_name = '".$DB->escape_str($ex[0])."')";
        			}
        		}
				
				$css_query = ( ! isset($css_parts)) ? $DB->query($sql) : $DB->query($sql.' AND ('.implode(' OR ', $css_parts) .')');
        		
        		if ($css_query->num_rows > 0)
        		{
        			foreach($css_query->result as $row)
        			{
        				$css_versions[$row['group_name'].'/'.$row['template_name']] = $row['edit_date'];
        			}
        		}
        	}
        	
        	for($ci=0, $cs=sizeof($css_matches[0]); $ci < $cs; ++$ci)
        	{
        		$str = str_replace($css_matches[0][$ci], $FNS->fetch_site_index().$qs.'css='.$css_matches[1][$ci].(isset($css_versions[$css_matches[1][$ci]]) ? '.v.'.$css_versions[$css_matches[1][$ci]] : ''), $str);
        	}
        
        	unset($css_matches);
        	unset($css_versions);
        }
          
        /** --------------------------------------------------
        /**  Email encode: {encode="you@yoursite.com" title="click Me"}
        /** --------------------------------------------------*/
        
        if ($this->encode_email == TRUE)
        {
			if (preg_match_all("/".LD."encode=(.+?)".RD."/i", $str, $matches))
			{
				for ($j = 0; $j < count($matches['0']); $j++)
				{	
					$str = preg_replace('/'.preg_quote($matches['0'][$j], '/').'/', $FNS->encode_email($matches['1'][$j]), $str, 1);
				}
			}  		
		}
		else
		{
			/* -------------------------------------------
			/*	Hidden Configuration Variable
			/*	- encode_removed_text => Text to display if there is an {encode=""} 
				tag but emails are not to be encoded
			/* -------------------------------------------*/
		
			$str = preg_replace("/".LD."\s*encode=(.+?)".RD."/", 
								($PREFS->ini('encode_removed_text') !== FALSE) ? $PREFS->ini('encode_removed_text') : '', 
								$str);
		}
		
        /** --------------------------------------------------
        /**  Path variable: {path=group/template}
        /** --------------------------------------------------*/
		
		$str = preg_replace_callback("/".LD."\s*path=(.*?)".RD."/", array(&$FNS, 'create_url'), $str);
        
        /** --------------------------------------------------
        /**  Debug mode: {debug_mode}
        /** --------------------------------------------------*/
        
        $str = str_replace(LD.'debug_mode'.RD, ($PREFS->ini('debug') > 0) ? $LANG->line('on') : $LANG->line('off'), $str);
                
        /** --------------------------------------------------
        /**  GZip mode: {gzip_mode}
        /** --------------------------------------------------*/

        $str = str_replace(LD.'gzip_mode'.RD, ($PREFS->ini('gzip_output') == 'y') ? $LANG->line('enabled') : $LANG->line('disabled'), $str);
                
        /** --------------------------------------------------
        /**  App version: {version}
        /** --------------------------------------------------*/
        
        $str = str_replace(LD.'app_version'.RD, APP_VER, $str); 
        $str = str_replace(LD.'version'.RD, APP_VER, $str); 
         
        /** --------------------------------------------------
        /**  App version: {build}
        /** --------------------------------------------------*/
        
        $str = str_replace(LD.'app_build'.RD, APP_BUILD, $str); 
        $str = str_replace(LD.'build'.RD, APP_BUILD, $str);

        /** --------------------------------------------------
        /**  {charset} and {lang}
        /** --------------------------------------------------*/
        
		if (preg_match("/\{charset\}/i", $str) OR preg_match("/\{lang\}/i", $str))
        {
			if ( ! USER_BLOG)
			{
				$str = str_replace(LD.'charset'.RD, $PREFS->ini('charset'), $str); 
				$str = str_replace(LD.'lang'.RD, $PREFS->ini('xml_lang'), $str); 
			}
			else
			{
				$query = $DB->query("SELECT blog_lang, blog_encoding FROM exp_weblogs WHERE weblog_id = '".$DB->escape_str(UB_BLOG_ID)."'");
			
				$str = str_replace(LD.'charset'.RD, $query->row['blog_encoding'], $str); 
				$str = str_replace(LD.'lang'.RD, $query->row['blog_lang'], $str); 
			}
        }
        
        /** --------------------------------------------------
        /**  Parse User-defined Global Variables
        /** --------------------------------------------------*/
     	
		$ub_id = ( ! defined('UB_BLOG_ID')) ? 0 : UB_BLOG_ID; 
     
		$query = $DB->query("SELECT variable_name, variable_data FROM exp_global_variables 
							 WHERE site_id = '".$DB->escape_str($PREFS->ini('site_id'))."' 
							 AND user_blog_id = '".$DB->escape_str($ub_id)."' ");
		
		if ($query->num_rows > 0)
		{
			foreach ($query->result as $row)
			{
				$str = str_replace(LD.$row['variable_name'].RD, $row['variable_data'], $str); 
			}
		}	
		
		/** --------------------------------------------------
		/**  {member_profile_link}
		/** --------------------------------------------------*/

		if ($SESS->userdata('member_id') != 0)
		{
			$name = ($SESS->userdata['screen_name'] == '') ? $SESS->userdata['username'] : $SESS->userdata['screen_name'];
			
			$path = "<a href='".$FNS->create_url('/member/'.$SESS->userdata('member_id'))."'>".$name."</a>";
			
			$str = str_replace(LD.'member_profile_link'.RD, $path, $str);
		}
		else
		{
			$str = str_replace(LD.'member_profile_link'.RD, '', $str);
		}
		
		/** -----------------------------------
		/**  Fetch captcha
		/** -----------------------------------*/
		
		if (preg_match("/({captcha})/", $str))
		{
			$str = preg_replace("/{captcha}/", $FNS->create_captcha(), $str);
		}        
					
		/** -----------------------------------
		/**  Add security hashes to forms
		/** -----------------------------------*/
		
		// We do this here to keep the security hashes from being cached
		
		$str = $FNS->add_form_security_hash($str);
		
		/** -----------------------------------
		/**  Add Action IDs form forms and links
		/** -----------------------------------*/
		
		$str = $FNS->insert_action_ids($str);
		
		/** -----------------------------------
		/**  Parse non-cachable variables
		/** -----------------------------------*/
		
		$SESS->userdata['member_group'] = $SESS->userdata['group_id'];
	
		foreach ($user_vars as $val)
		{
			if (isset($SESS->userdata[$val]) AND ($val == 'group_description' OR strval($SESS->userdata[$val]) != ''))
			{
				$str = str_replace(LD.$val.RD, $SESS->userdata[$val], $str);                 
				$str = str_replace('{out_'.$val.'}', $SESS->userdata[$val], $str);
				$str = str_replace('{global->'.$val.'}', $SESS->userdata[$val], $str);
				$str = str_replace('{logged_in_'.$val.'}', $SESS->userdata[$val], $str);
			}
		}
		
		return $str;
    }
    /* END */
    
    
    /** -----------------------------------
	/**  Parse Forms that Cannot Be Cached
	/** -----------------------------------*/
    
    function parse_nocache($str)
    {
    	global $FNS;
    	
    	if ( ! stristr($str, '{NOCACHE'))
    	{
    		return $str;
    	}
    	
    	/** -----------------------------------
		/**  Generate Comment Form if needed
		/** -----------------------------------*/
		
		// In order for the comment form not to cache the "save info"
		// data we need to generate dynamically if necessary

		if (preg_match_all("#{NOCACHE_(\S+)_FORM=\"(.*?)\"}(.+?){/NOCACHE_FORM}#s", $str, $match))
		{
			for($i=0, $s=sizeof($match['0']); $i < $s; $i++)
			{
				$class = $FNS->filename_security(strtolower($match['1'][$i]));
		
				if ( ! class_exists($class))
				{
					require PATH_MOD.$class.'/mod.'.$class.EXT;
				}
						
				$this->tagdata = $match['3'][$i];
			
				$vars = $FNS->assign_variables($match['3'][$i], '/');			
				$this->var_single	= $vars['var_single'];
				$this->var_pair		= $vars['var_pair'];
				
				$this->tagparams = $FNS->assign_parameters($match['2'][$i]);
				
				$this->var_cond = $FNS->assign_conditional_variables($match['3'][$i], '/', LD, RD);
				
				// Assign sites for the tag
				$this->_fetch_site_ids();

				if ($class == 'gallery')
					$str = str_replace($match['0'][$i], Gallery::comment_form(TRUE, $FNS->cached_captcha), $str);	
				elseif ($class == 'comment')
					$str = str_replace($match['0'][$i], Comment::form(TRUE, $FNS->cached_captcha), $str);	
				
				$str = str_replace('{PREVIEW_TEMPLATE}', $match['2'][$i], $str);	
			}
		}
		/** -----------------------------------
		/**  Generate Stand-alone Publish form
		/** -----------------------------------*/

		if (preg_match_all("#{{NOCACHE_WEBLOG_FORM(.*?)}}(.+?){{/NOCACHE_FORM}}#s", $str, $match))
		{
			for($i=0, $s=sizeof($match['0']); $i < $s; $i++)
			{
				if ( ! class_exists('Weblog'))
				{
					require PATH_MOD.'weblog/mod.weblog'.EXT;
				}
				
				$this->tagdata = $match['2'][$i];
				
				$vars = $FNS->assign_variables($match['2'][$i], '/');
				$this->var_single	= $vars['var_single'];
				$this->var_pair		= $vars['var_pair'];
				
				$this->tagparams = $FNS->assign_parameters($match['1'][$i]);
				
				// Assign sites for the tag
				$this->_fetch_site_ids();

				$XX = new Weblog();
				$str = str_replace($match['0'][$i], $XX->entry_form(TRUE, $FNS->cached_captcha), $str);
				$str = str_replace('{PREVIEW_TEMPLATE}', (isset($_POST['PRV'])) ? $_POST['PRV'] : $this->fetch_param('preview'), $str);	
			}
		}
				
		/** -----------------------------------
		/**  Generate Trackback hash if needed
		/** -----------------------------------*/

		if (preg_match("#{NOCACHE_TRACKBACK_HASH}#s", $str, $match))
		{		
			if ( ! class_exists('Trackback'))
			{
				require PATH_MOD.'trackback/mod.trackback'.EXT;
			}
										
			$str = str_replace($match['0'], Trackback::url(TRUE, $FNS->random('alpha', 8)), $str);	
		}
		
		return $str;
    
    }
    /* END */



	/** -----------------------------------
	/**  Parse advanced conditionals conditionals
	/** -----------------------------------*/

	function advanced_conditionals($str)
	{
		global $SESS, $IN, $FNS, $PREFS, $LOC;
		
		if (stristr($str, LD.'if') === false)
			return $str;
			
		/* ---------------------------------
		/*	Hidden Configuration Variables
		/*  - protect_javascript => Prevents advanced conditional parser from processing anything in <script> tags
		/* ---------------------------------*/
			
		if ($PREFS->ini('protect_javascript') == 'n')
		{
			$this->protect_javascript = FALSE;
		}
		
		$user_vars	= array('member_id', 'group_id', 'group_description', 'group_title', 'username', 'screen_name', 
							'email', 'ip_address', 'location', 'total_entries', 
							'total_comments', 'private_messages', 'total_forum_posts', 'total_forum_topics', 'total_forum_replies');
		
		for($i=0,$s=sizeof($user_vars), $data = array(); $i < $s; ++$i)
		{
			$data[$user_vars[$i]] = $SESS->userdata[$user_vars[$i]];
			$data['logged_in_'.$user_vars[$i]] = $SESS->userdata[$user_vars[$i]];
		}
		
		// Define an alternate variable for {group_id} since some tags use
		// it natively, causing it to be unavailable as a global
		
		$data['member_group'] = $SESS->userdata['group_id'];
		
		// Logged in and logged out variables
		$data['logged_in'] = ($SESS->userdata['member_id'] == 0) ? 'FALSE' : 'TRUE';
		$data['logged_out'] = ($SESS->userdata['member_id'] != 0) ? 'FALSE' : 'TRUE';
		
		// current time
		$data['current_time'] = $LOC->now;
		
		/** ------------------------------------
		/**  Member Group in_group('1') function, Super Secret!  Shhhhh!
		/** ------------------------------------*/
		
		if (preg_match_all("/in_group\(([^\)]+)\)/", $str, $matches))
		{
			$groups = (is_array($SESS->userdata['group_id'])) ? $SESS->userdata['group_id'] : array($SESS->userdata['group_id']);
		
			for($i=0, $s=sizeof($matches[0]); $i < $s; ++$i)
			{
				$check = explode('|', str_replace(array('"', "'"), '', $matches[1][$i]));
				
				$str = str_replace($matches[0][$i], (sizeof(array_intersect($check, $groups)) > 0) ? 'TRUE' : 'FALSE', $str);
			}
		}
		
		/** ------------------------------------
		/**  Final Prep, Safety On
		/** ------------------------------------*/

		$str = $FNS->prep_conditionals($str, array_merge($this->segment_vars, $this->embed_vars, $this->global_vars, $data), 'y');
				
		/** ------------------------------------
		/**  Protect Already Existing Unparsed PHP
		/** ------------------------------------*/
		
		$opener = '90Parse89Me34Not18Open';
		$closer = '90Parse89Me34Not18Close';
		
		$str = str_replace(array('<?', '?'.'>'), 
    					   array($opener.'?', '?'.$closer), 
    					   $str);
    	
    	/** ------------------------------------
		/**  Protect <script> tags
		/** ------------------------------------*/
		
    	$protected = array();
    	$front_protect = '89Protect17';
    	$back_protect  = '21Me01Please47';
		
		if ($this->protect_javascript !== FALSE && 
			stristr($str, '<script') && 
			preg_match_all("/<script.*?".">.*?<\/script>/is", $str, $matches))
		{
			for($i=0, $s=sizeof($matches['0']); $i < $s; ++$i)
			{
				$protected[$front_protect.$i.$back_protect] = $matches['0'][$i];
			}
			
			$str = str_replace(array_values($protected), array_keys($protected), $str);
		}
		
		/** ------------------------------------
		/**  Convert EE Conditionals to PHP 
		/** ------------------------------------*/
		
		$str = str_replace(array(LD.'/if'.RD, LD.'if:else'.RD), array('<?php endif; ?'.'>','<?php else : ?'.'>'), $str);
		$str = preg_replace("/".preg_quote(LD)."((if:(else))*if)\s+(.*?)".preg_quote(RD)."/s", '<?php \\3if(\\4) : ?'.'>', $str);
		$str = $this->parse_template_php($str);
		
		/** ------------------------------------
		/**  Unprotect <script> tags
		/** ------------------------------------*/
		
		if (sizeof($protected) > 0)
		{
			$str = str_replace(array_keys($protected), array_values($protected), $str);
		}
		
		/** ------------------------------------
		/**  Unprotect Already Existing Unparsed PHP
		/** ------------------------------------*/
		
		$str = str_replace(array($opener.'?', '?'.$closer), 
    					   array('<'.'?', '?'.'>'), 
    					   $str);
		
		return $str;
	} 
	/* END */
	
	
	/** -----------------------------------
	/**  Parse segment conditionals
	/** -----------------------------------*/

	function segment_conditionals($str)
	{
		global $SESS, $IN, $FNS;
		
		if ( ! preg_match("/".LD."if\s+segment_.+".RD."/", $str))
		{
			return $str;
		}
		
		$this->var_cond = $FNS->assign_conditional_variables($str);
		
		foreach ($this->var_cond as $val)
		{
			// Make sure this is for a segment conditional
			// And that this is not an advanced conditional
			
			if ( ! preg_match('/^segment_\d+$/i', $val['3']) OR
				sizeof(preg_split("/(\!=|==|<=|>=|<>|<|>|AND|XOR|OR|&&|\|\|)/", $val['0'])) > 2 OR
				stristr($val['2'], 'if:else') OR
				stristr($val['0'], 'if:else'))
			{
				continue;	
			}
			
			$cond = $FNS->prep_conditional($val['0']);
			
			$lcond	= substr($cond, 0, strpos($cond, ' '));
			$rcond	= substr($cond, strpos($cond, ' '));
			
			if ( ! stristr($rcond, '"') && ! stristr($rcond, "'")) continue;
			
			$n = substr($val['3'], 8);
			$temp = (isset($IN->SEGS[$n])) ? $IN->SEGS[$n] : '';

			$lcond = str_replace($val['3'], "\$temp", $lcond);
			
			if (stristr($rcond, '\|') !== FALSE OR stristr($rcond, '&') !== FALSE)
			{
				$rcond	  = trim($rcond);
				$operator = trim(substr($rcond, 0, strpos($rcond, ' ')));
				$check	  = trim(substr($rcond, strpos($rcond, ' ')));
			
				$quote = substr($check, 0, 1);
				
				if (stristr($rcond, '\|') !== FALSE)
				{
					$array =  explode('\|', str_replace($quote, '', $check));
					$break_operator = ' || ';
				}
				else
				{
					$array =  explode('&', str_replace($quote, '', $check));
					$break_operator = ' && ';
				}
				
				$rcond  = $operator.' '.$quote;
				
				$rcond .= implode($quote.$break_operator.$lcond.' '.$operator.' '.$quote, $array).$quote;
			}
			
			$cond = $lcond.' '.$rcond;
			  
			$cond = str_replace("\|", "|", $cond);

			eval("\$result = (".$cond.");");
								
			if ($result)
			{
				$str = str_replace($val['1'], $val['2'], $str);                 
			}
			else
			{
				$str = str_replace($val['1'], '', $str);                 
			}   
		}		
		
		return $str;
		
	} /* END */
	
	
	/** -----------------------------------
	/**  Parse Global Vars conditionals
	/** -----------------------------------*/
	
	function global_vars_conditionals($str)
	{
		return $this->array_conditionals($str, $this->global_vars);
	}

	function array_conditionals($str, $vars = array())
	{
		global $SESS, $IN, $FNS;
		
		if (sizeof($vars) == 0 OR ! stristr($str, LD.'if'))
		{
			return $str;
		}
	
		$this->var_cond = $FNS->assign_conditional_variables($str);
		
		if (sizeof($this->var_cond) == 0)
		{
			return $str;
		}
		
		foreach ($this->var_cond as $val)
		{
			// Make sure there is such a $global_var
			// And that this is not an advanced conditional
			
			if ( ! isset($vars[$val['3']]) OR 
				sizeof(preg_split("/(\!=|==|<=|>=|<>|<|>|AND|XOR|OR|&&|\|\|)/", $val['0'])) > 2 OR 
				stristr($val['2'], 'if:else') OR
				stristr($val['0'], 'if:else'))
			{
				continue;	
			}
			
			$cond = $FNS->prep_conditional($val['0']);
			
			$lcond	= substr($cond, 0, strpos($cond, ' '));
			$rcond	= substr($cond, strpos($cond, ' '));
			
			if ( ! stristr($rcond, '"') && ! stristr($rcond, "'")) continue;
			
			$temp = $vars[$val['3']];

			$lcond = str_replace($val['3'], "\$temp", $lcond);
			
			if (stristr($rcond, '\|') !== FALSE OR stristr($rcond, '&') !== FALSE)
			{
				$rcond	  = trim($rcond);
				$operator = trim(substr($rcond, 0, strpos($rcond, ' ')));
				$check	  = trim(substr($rcond, strpos($rcond, ' ')));
			
				$quote = substr($check, 0, 1);
				
				if (stristr($rcond, '\|') !== FALSE)
				{
					$array =  explode('\|', str_replace($quote, '', $check));
					$break_operator = ' || ';
				}
				else
				{
					$array =  explode('&', str_replace($quote, '', $check));
					$break_operator = ' && ';
				}
				
				$rcond  = $operator.' '.$quote;
				
				$rcond .= implode($quote.$break_operator.$lcond.' '.$operator.' '.$quote, $array).$quote;
			}
			
			$cond = $lcond.' '.$rcond;
			  
			$cond = str_replace("\|", "|", $cond);

			eval("\$result = (".$cond.");");
								
			if ($result)
			{
				$str = str_replace($val['1'], $val['2'], $str);                 
			}
			else
			{
				$str = str_replace($val['1'], '', $str);                 
			}   
		}		
		
		return $str;
		
	} /* END */
	
	
	/** ----------------------------------
	/**  Add an Item to the Template Log
	/** ----------------------------------*/
	
	function log_item($str)
	{
		global $SESS;
		
		if ($this->debugging !== TRUE OR $SESS->userdata['group_id'] != 1)
		{
			return;
		}
	
		if ($this->depth > 0)
		{
			$str = str_repeat('&nbsp;', $this->depth * 5).$str;
		}
		
		if (phpversion() < 5)
		{
			list($usec, $sec) = explode(" ", microtime());
			$time = ((float)$usec + (float)$sec) - $this->start_microtime;
		}
		else
		{
			$time = microtime(TRUE)-$this->start_microtime;
		}
		
		$this->log[] = '('.number_format($time, 6).') '.$str;
	}
	/* END */
	
	
	/** ----------------------------------
	/**  Template Authentication - Basic
	/** ----------------------------------*/
	
	function template_authentication_basic()
	{
		global $PREFS, $OUT;
		
		@header('WWW-Authenticate: Basic realm="'.$this->realm.'"');
    	$OUT->http_status_header(401);
    	@header("Date: ".gmdate("D, d M Y H:i:s")." GMT");
    	exit("HTTP/1.0 401 Unauthorized");
	}
	/* END */
	
	/** ----------------------------------
	/**  Template Authentication - Digest
	/** ----------------------------------*/
	
	function template_authentication_digest()
	{
		global $PREF, $OUT;
		
		@header('WWW-Authenticate: Digest realm="'.$this->realm.'",gop="auth", nonce="'.uniqid('').'", opaque="'.md5($this->realm).'"');
    	$OUT->http_status_header(401);
    	@header("Date: ".gmdate("D, d M Y H:i:s")." GMT");
    	exit("HTTP/1.0 401 Unauthorized");
	}
	/* END */
	
	
	/** ----------------------------------
	/**  Check Template Authentication - Digest
	/** ----------------------------------*/
	
	function template_authentication_check_digest($not_allowed_groups = array())
	{
		global $DB, $SESS, $PREFS, $FNS;
		
		if ( ! in_array('2', $not_allowed_groups))
		{
			$not_allowed_groups[] = 2;
			$not_allowed_groups[] = 3;
			$not_allowed_groups[] = 4;
		}
		
		if (empty($_SERVER) OR ! isset($_SERVER['PHP_AUTH_DIGEST']))
    	{
            return FALSE;
        }
        
        $required = array('uri'			=> '', 
        				  'response'	=> '', 
        				  'realm'		=> $this->realm,
        				  'username'	=> '',
        				  'nonce'		=> 1,
        				  'nc'			=> 1,
        				  'cnonce'		=> 1,
        				  'qop'			=> 1);
        
        $params = $FNS->assign_parameters($_SERVER['PHP_AUTH_DIGEST']);
        
        extract($required);
        extract($params);
        
		/** ----------------------------------------
		/**  Check password lockout status
		/** ----------------------------------------*/
		
		if ($SESS->check_password_lockout() === TRUE)
		{
			return FALSE;   
		}
    	
    	/** ----------------------------------
		/**  Validate Username and Password
		/** ----------------------------------*/
		
		$query = $DB->query("SELECT password, group_id FROM exp_members WHERE username = '".$DB->escape_str($username)."'");
		
		if ($query->num_rows == 0)
		{
			$SESS->save_password_lockout();
			return FALSE;
		}
		
		if (in_array($query->row['group_id'], $not_allowed_groups))
		{
			return FALSE;
		}
		
		$parts = array(
						md5($username.':'.$realm.':'.$query->row['password']),
						md5($_SERVER['REQUEST_METHOD'].':'.$uri)
					  );
					  
		$valid_response = md5($parts['0'].':'.$nonce.':'.$nc.':'.$cnonce.':'.$qop.':'.$parts['1']);
		
		if ($valid_response == $response)
		{
			return TRUE;
		}
		else
		{
			$SESS->save_password_lockout();
			
			return FALSE;
		}
	}
	/* END */
	
	
	/** ----------------------------------
	/**  Check Template Authentication - Basic
	/** ----------------------------------*/
	
	function template_authentication_check_basic($not_allowed_groups = array())
	{
		global $DB, $SESS, $PREFS, $FNS;
		
		if ( ! in_array('2', $not_allowed_groups))
		{
			$not_allowed_groups[] = 2;
			$not_allowed_groups[] = 3;
			$not_allowed_groups[] = 4;
		}
		
		/** ----------------------------------
		/**  Find Username, Please
		/** ----------------------------------*/

    	if ( ! empty($_SERVER) && isset($_SERVER['PHP_AUTH_USER']))
    	{
            $user = $_SERVER['PHP_AUTH_USER'];
        }
        elseif ( !empty($_ENV) && isset($_ENV['REMOTE_USER']))
        {
            $user = $_ENV['REMOTE_USER'];
        }
        elseif ( @getenv('REMOTE_USER'))
        {
            $user = getenv('REMOTE_USER');
        }
        elseif ( ! empty($_ENV) && isset($_ENV['AUTH_USER']))
        {
            $user = $_ENV['AUTH_USER'];
        }
        elseif ( @getenv('AUTH_USER'))
        {
            $user = getenv('AUTH_USER');
        }
        
		/** ----------------------------------
		/**  Find Password, Please
		/** ----------------------------------*/
        
        if ( ! empty($_SERVER) && isset($_SERVER['PHP_AUTH_PW']))
        {
            $pass = $_SERVER['PHP_AUTH_PW'];
        }
        elseif ( ! empty($_ENV) && isset($_ENV['REMOTE_PASSWORD']))
        {
            $pass = $_ENV['REMOTE_PASSWORD'];
        }
        elseif ( @getenv('REMOTE_PASSWORD'))
        {
            $pass = getenv('REMOTE_PASSWORD');
        }
        elseif ( ! empty($_ENV) && isset($_ENV['AUTH_PASSWORD']))
        {
            $pass = $_ENV['AUTH_PASSWORD'];
        }
        elseif ( @getenv('AUTH_PASSWORD'))
        {
            $pass = getenv('AUTH_PASSWORD');
        }
        
        /** ----------------------------------
		/**  Authentication for IIS
		/** ----------------------------------*/
    	
    	if ( ! isset ($user) OR ! isset($pass) OR (empty($user) && empty($pass)))
    	{
			if ( isset($_SERVER['HTTP_AUTHORIZATION']) && substr($_SERVER['HTTP_AUTHORIZATION'], 0, 6) == 'Basic ')
			{
				list($user, $pass) = explode(':', base64_decode(substr($HTTP_AUTHORIZATION, 6)));
			}
			elseif ( ! empty($_ENV) && isset($_ENV['HTTP_AUTHORIZATION']) && substr($_ENV['HTTP_AUTHORIZATION'], 0, 6) == 'Basic ')
			{
				list($user, $pass) = explode(':', base64_decode(substr($_ENV['HTTP_AUTHORIZATION'], 6)));
			}
			elseif (@getenv('HTTP_AUTHORIZATION') && substr(getenv('HTTP_AUTHORIZATION'), 0, 6) == 'Basic ')
			{
				list($user, $pass) = explode(':', base64_decode(substr(getenv('HTTP_AUTHORIZATION'), 6)));
			}
		}
    	
		/** ----------------------------------
		/**  Authentication for FastCGI
		/** ----------------------------------*/
		
		if ( ! isset ($user) OR ! isset($pass) OR (empty($user) && empty($pass)))
		{	
			if (!empty($_ENV) && isset($_ENV['Authorization']) && substr($_ENV['Authorization'], 0, 6) == 'Basic ')
			{
				list($user, $pass) = explode(':', base64_decode(substr($_ENV['Authorization'], 6)));
			}
			elseif (@getenv('Authorization') && substr(getenv('Authorization'), 0, 6) == 'Basic ')
			{
				list($user, $pass) = explode(':', base64_decode(substr(getenv('Authorization'), 6)));
			}
		}
    	
    	if ( ! isset ($user) OR ! isset($pass) OR (empty($user) && empty($pass)))
    	{
    		return FALSE;
    	}
    	
		/** ----------------------------------------
		/**  Check password lockout status
		/** ----------------------------------------*/
		
		if ($SESS->check_password_lockout() === TRUE)
		{
			return FALSE;   
		}
    	
    	/** ----------------------------------
		/**  Validate Username and Password
		/** ----------------------------------*/
		
		$query = $DB->query("SELECT password, group_id FROM exp_members WHERE username = '".$DB->escape_str($user)."'");
		
		if ($query->num_rows == 0)
		{
			$SESS->save_password_lockout();
			return FALSE;
		}
		
		if (in_array($query->row['group_id'], $not_allowed_groups))
		{
			return FALSE;
		}
		
		if ($query->row['password'] == $FNS->hash(stripslashes($pass)))
		{
			return TRUE;
		}
		
		$orig_enc_type = $PREFS->ini('encryption_type');
		$PREFS->core_ini['encryption_type'] = ($PREFS->ini('encryption_type') == 'md5') ? 'sha1' : 'md5';
		
		if ($query->row['password'] == $FNS->hash(stripslashes($pass)))
		{
			return TRUE;
		}
		else
		{
			$SESS->save_password_lockout();
			
			return FALSE;
		}
	}
	/* END */

	
	/** ---------------------------------------
	/**  Fetch Template site id's for tags
	/** ---------------------------------------*/
	
	function _fetch_site_ids()
	{
		global $DB, $PREFS;
		
		$this->site_ids = array();
        
        if (isset($this->tagparams['site']))
        {
        	if (sizeof($this->sites) == 0 && $PREFS->ini('multiple_sites_enabled') == 'y')
        	{
        		$sites_query = $DB->query("SELECT site_id, site_name FROM exp_sites");
        		
        		foreach($sites_query->result as $row)
        		{
        			$this->sites[$row['site_id']] = $row['site_name'];
        		}
        	}
        	
        	if (substr($this->tagparams['site'], 0, 4) == 'not ')
			{
				$sites = array_diff($this->sites, explode('|', substr($this->tagparams['site'], 4)));	
			}
			else
			{
				$sites = array_intersect($this->sites, explode('|', $this->tagparams['site']));
			}
			
			// Let us hear it for the preservation of array keys!
			$this->site_ids = array_flip($sites);
        }
        
        // If no sites were assigned via parameter, then we use the current site's
        // Templates, Weblogs, and various Site data
        
        if (sizeof($this->site_ids) == 0)
        {
        	$this->site_ids[] = $PREFS->ini('site_id');
        }
	}
}
// END CLASS
?>
Back to Top