File: WikiDB.php

package info (click to toggle)
phpwiki 1.3.14-3
  • links: PTS
  • area: main
  • in suites: lenny
  • size: 15,716 kB
  • ctags: 23,548
  • sloc: php: 88,295; sql: 1,476; sh: 1,378; perl: 765; makefile: 602; awk: 28
file content (2672 lines) | stat: -rwxr-xr-x 95,440 bytes parent folder | download
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
<?php //-*-php-*-
rcs_id('$Id: WikiDB.php,v 1.153 2007/06/07 16:54:29 rurban Exp $');

require_once('lib/PageType.php');

/**
 * The classes in the file define the interface to the
 * page database.
 *
 * @package WikiDB
 * @author Geoffrey T. Dairiki <dairiki@dairiki.org>
 * Minor enhancements by Reini Urban
 */

/**
 * Force the creation of a new revision.
 * @see WikiDB_Page::createRevision()
 */
if (!defined('WIKIDB_FORCE_CREATE'))
    define('WIKIDB_FORCE_CREATE', -1);

/** 
 * Abstract base class for the database used by PhpWiki.
 *
 * A <tt>WikiDB</tt> is a container for <tt>WikiDB_Page</tt>s which in
 * turn contain <tt>WikiDB_PageRevision</tt>s.
 *
 * Conceptually a <tt>WikiDB</tt> contains all possible
 * <tt>WikiDB_Page</tt>s, whether they have been initialized or not.
 * Since all possible pages are already contained in a WikiDB, a call
 * to WikiDB::getPage() will never fail (barring bugs and
 * e.g. filesystem or SQL database problems.)
 *
 * Also each <tt>WikiDB_Page</tt> always contains at least one
 * <tt>WikiDB_PageRevision</tt>: the default content (e.g. "Describe
 * [PageName] here.").  This default content has a version number of
 * zero.
 *
 * <tt>WikiDB_PageRevision</tt>s have read-only semantics. One can
 * only create new revisions or delete old ones --- one can not modify
 * an existing revision.
 */
class WikiDB {
    /**
     * Open a WikiDB database.
     *
     * This is a static member function. This function inspects its
     * arguments to determine the proper subclass of WikiDB to
     * instantiate, and then it instantiates it.
     *
     * @access public
     *
     * @param hash $dbparams Database configuration parameters.
     * Some pertinent paramters are:
     * <dl>
     * <dt> dbtype
     * <dd> The back-end type.  Current supported types are:
     *   <dl>
     *   <dt> SQL
     *     <dd> Generic SQL backend based on the PEAR/DB database abstraction
     *       library. (More stable and conservative)
     *   <dt> ADODB
     *     <dd> Another generic SQL backend. (More current features are tested here. Much faster)
     *   <dt> dba
     *     <dd> Dba based backend. The default and by far the fastest.
     *   <dt> cvs
     *     <dd> 
     *   <dt> file
     *     <dd> flat files
     *   </dl>
     *
     * <dt> dsn
     * <dd> (Used by the SQL and ADODB backends.)
     *      The DSN specifying which database to connect to.
     *
     * <dt> prefix
     * <dd> Prefix to be prepended to database tables (and file names).
     *
     * <dt> directory
     * <dd> (Used by the dba backend.)
     *      Which directory db files reside in.
     *
     * <dt> timeout
     * <dd> Used only by the dba backend so far. 
     *      And: When optimizing mysql it closes timed out mysql processes.
     *      otherwise only used for dba: Timeout in seconds for opening (and 
     *      obtaining lock) on the dbm file.
     *
     * <dt> dba_handler
     * <dd> (Used by the dba backend.)
     *
     *      Which dba handler to use. Good choices are probably either
     *      'gdbm' or 'db2'.
     * </dl>
     *
     * @return WikiDB A WikiDB object.
     **/
    function open ($dbparams) {
        $dbtype = $dbparams{'dbtype'};
        include_once("lib/WikiDB/$dbtype.php");
				
        $class = 'WikiDB_' . $dbtype;
        return new $class ($dbparams);
    }


    /**
     * Constructor.
     *
     * @access private
     * @see open()
     */
    function WikiDB (&$backend, $dbparams) {
        $this->_backend = &$backend;
        // don't do the following with the auth_dsn!
        if (isset($dbparams['auth_dsn'])) return;
        
        $this->_cache = new WikiDB_cache($backend);
        if (!empty($GLOBALS['request'])) $GLOBALS['request']->_dbi = $this;

        // If the database doesn't yet have a timestamp, initialize it now.
        if ($this->get('_timestamp') === false)
            $this->touch();
        
        // devel checking.
        if ((int)DEBUG & _DEBUG_SQL) {
            $this->_backend->check();
	}
    }
    
    /**
     * Close database connection.
     *
     * The database may no longer be used after it is closed.
     *
     * Closing a WikiDB invalidates all <tt>WikiDB_Page</tt>s,
     * <tt>WikiDB_PageRevision</tt>s and <tt>WikiDB_PageIterator</tt>s
     * which have been obtained from it.
     *
     * @access public
     */
    function close () {
        $this->_backend->close();
        $this->_cache->close();
    }
    
    /**
     * Get a WikiDB_Page from a WikiDB.
     *
     * A {@link WikiDB} consists of the (infinite) set of all possible pages,
     * therefore this method never fails.
     *
     * @access public
     * @param string $pagename Which page to get.
     * @return WikiDB_Page The requested WikiDB_Page.
     */
    function getPage($pagename) {
        static $error_displayed = false;
        $pagename = (string) $pagename;
        if ((int)DEBUG) {
            if ($pagename === '') {
                if ($error_displayed) return false;
                $error_displayed = true;
                if (function_exists("xdebug_get_function_stack"))
                    var_dump(xdebug_get_function_stack());
                trigger_error("empty pagename", E_USER_WARNING);
                return false;
            }
        } else {
            assert($pagename != '');
        }
        return new WikiDB_Page($this, $pagename);
    }

    /**
     * Determine whether page exists (in non-default form).
     *
     * <pre>
     *   $is_page = $dbi->isWikiPage($pagename);
     * </pre>
     * is equivalent to
     * <pre>
     *   $page = $dbi->getPage($pagename);
     *   $current = $page->getCurrentRevision();
     *   $is_page = ! $current->hasDefaultContents();
     * </pre>
     * however isWikiPage may be implemented in a more efficient
     * manner in certain back-ends.
     *
     * @access public
     * @param string $pagename string Which page to check.
     * @return boolean True if the page actually exists with
     * non-default contents in the WikiDataBase.
     */
    function isWikiPage ($pagename) {
        $page = $this->getPage($pagename);
        return ($page and $page->exists());
    }

    /**
     * Delete page from the WikiDB. 
     *
     * Deletes the page from the WikiDB with the possibility to revert and diff.
     * //Also resets all page meta-data to the default values.
     *
     * Note: purgePage() effectively destroys all revisions of the page from the WikiDB. 
     *
     * @access public
     * @param string $pagename Name of page to delete.
     * @see purgePage
     */
    function deletePage($pagename) {
    	// don't create empty revisions of already purged pages.
        if ($this->_backend->get_latest_version($pagename))
            $result = $this->_cache->delete_page($pagename);
        else 
            $result = -1;

        /* Generate notification emails */
        include_once("lib/MailNotify.php");
        $MailNotify = new MailNotify($pagename);
        $MailNotify->onDeletePage ($this, $pagename);

        //How to create a RecentChanges entry with explaining summary? Dynamically
        /*
        $page = $this->getPage($pagename);
        $current = $page->getCurrentRevision();
        $meta = $current->_data;
        $version = $current->getVersion();
        $meta['summary'] = _("removed");
        $page->save($current->getPackedContent(), $version + 1, $meta);
        */
        return $result;
    }

    /**
     * Completely remove the page from the WikiDB, without undo possibility.
     * @access public
     * @param string $pagename Name of page to delete.
     * @see deletePage
     */
    function purgePage($pagename) {
        $result = $this->_cache->purge_page($pagename);
        $this->deletePage($pagename); // just for the notification
        return $result;
    }
    
    /**
     * Retrieve all pages.
     *
     * Gets the set of all pages with non-default contents.
     *
     * @access public
     *
     * @param boolean $include_empty Optional. Normally pages whose most
     * recent revision has empty content are considered to be
     * non-existant. Unless $include_defaulted is set to true, those
     * pages will not be returned.
     * @param string or false $sortby Optional. "+-column,+-column2". 
     *		If false the result is faster in natural order.
     * @param string or false $limit Optional. Encoded as "$offset,$count".
     * 		$offset defaults to 0.
     * @param string $exclude: Optional comma-seperated list of pagenames. 
     *
     * @return WikiDB_PageIterator A WikiDB_PageIterator which contains all pages
     *     in the WikiDB which have non-default contents.
     */
    function getAllPages($include_empty=false, $sortby='', $limit='', $exclude='') 
    {
        // HACK: memory_limit=8M will fail on too large pagesets. old php on unix only!
        if (USECACHE) {
            $mem = ini_get("memory_limit");
            if ($mem and !$limit and !isWindows() and !check_php_version(4,3)) {
                $limit = 450;
                $GLOBALS['request']->setArg('limit', $limit);
                $GLOBALS['request']->setArg('paging', 'auto');
            }
        }
        $result = $this->_backend->get_all_pages($include_empty, $sortby, $limit, 
                                                 $exclude);
        return new WikiDB_PageIterator($this, $result, 
                                       array('include_empty' => $include_empty, 
                                             'exclude' => $exclude,
                                             'limit' => $limit));
    }

    /**
     * @access public
     *
     * @param boolean $include_empty If true include also empty pages
     * @param string $exclude: comma-seperated list of pagenames. 
     * 			TBD: array of pagenames
     * @return integer
     * 
     */
    function numPages($include_empty=false, $exclude='') {
    	if (method_exists($this->_backend, 'numPages'))
            // FIXME: currently are all args ignored.
            $count = $this->_backend->numPages($include_empty, $exclude);
        else {
            // FIXME: exclude ignored.
            $iter = $this->getAllPages($include_empty, false, false, $exclude);
            $count = $iter->count();
            $iter->free();
        }
        return (int)$count;
    }
    
    /**
     * Title search.
     *
     * Search for pages containing (or not containing) certain words
     * in their names.
     *
     * Pages are returned in alphabetical order whenever it is
     * practical to do so.
     * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
     *
     * @access public
     * @param TextSearchQuery $search A TextSearchQuery object
     * @param string or false $sortby Optional. "+-column,+-column2". 
     *		If false the result is faster in natural order.
     * @param string or false $limit Optional. Encoded as "$offset,$count".
     * 		$offset defaults to 0.
     * @param string $exclude: Optional comma-seperated list of pagenames. 
     * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
     * @see TextSearchQuery
     */
    function titleSearch($search, $sortby='pagename', $limit='', $exclude='') {
        $result = $this->_backend->text_search($search, false, $sortby, $limit, $exclude);
        return new WikiDB_PageIterator($this, $result,
                                       array('exclude' => $exclude,
                                             'limit' => $limit));
    }

    /**
     * Full text search.
     *
     * Search for pages containing (or not containing) certain words
     * in their entire text (this includes the page content and the
     * page name).
     *
     * Pages are returned in alphabetical order whenever it is
     * practical to do so.
     * TODO: Sort by ranking. Only postgresql with tsearch2 can do ranking so far.
     *
     * @access public
     *
     * @param TextSearchQuery $search A TextSearchQuery object.
     * @param string or false $sortby Optional. "+-column,+-column2". 
     *		If false the result is faster in natural order.
     * @param string or false $limit Optional. Encoded as "$offset,$count".
     * 		$offset defaults to 0.
     * @param string $exclude: Optional comma-seperated list of pagenames. 
     * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching pages.
     * @see TextSearchQuery
     */
    function fullSearch($search, $sortby='pagename', $limit='', $exclude='') {
        $result = $this->_backend->text_search($search, true, $sortby, $limit, $exclude);
        return new WikiDB_PageIterator($this, $result,
                                       array('exclude' => $exclude,
                                             'limit'   => $limit,
                                             'stoplisted' => $result->stoplisted
                                             ));
    }

    /**
     * Find the pages with the greatest hit counts.
     *
     * Pages are returned in reverse order by hit count.
     *
     * @access public
     *
     * @param integer $limit The maximum number of pages to return.
     * Set $limit to zero to return all pages.  If $limit < 0, pages will
     * be sorted in decreasing order of popularity.
     * @param string or false $sortby Optional. "+-column,+-column2". 
     *		If false the result is faster in natural order.
     *
     * @return WikiDB_PageIterator A WikiDB_PageIterator containing the matching
     * pages.
     */
    function mostPopular($limit = 20, $sortby = '-hits') {
        $result = $this->_backend->most_popular($limit, $sortby);
        return new WikiDB_PageIterator($this, $result);
    }

    /**
     * Find recent page revisions.
     *
     * Revisions are returned in reverse order by creation time.
     *
     * @access public
     *
     * @param hash $params This hash is used to specify various optional
     *   parameters:
     * <dl>
     * <dt> limit 
     *    <dd> (integer) At most this many revisions will be returned.
     * <dt> since
     *    <dd> (integer) Only revisions since this time (unix-timestamp) 
     *		will be returned. 
     * <dt> include_minor_revisions
     *    <dd> (boolean) Also include minor revisions.  (Default is not to.)
     * <dt> exclude_major_revisions
     *    <dd> (boolean) Don't include non-minor revisions.
     *         (Exclude_major_revisions implies include_minor_revisions.)
     * <dt> include_all_revisions
     *    <dd> (boolean) Return all matching revisions for each page.
     *         Normally only the most recent matching revision is returned
     *         for each page.
     * </dl>
     *
     * @return WikiDB_PageRevisionIterator A WikiDB_PageRevisionIterator 
     * containing the matching revisions.
     */
    function mostRecent($params = false) {
        $result = $this->_backend->most_recent($params);
        return new WikiDB_PageRevisionIterator($this, $result);
    }

    /**
     * @access public
     *
     * @param string or false $sortby Optional. "+-column,+-column2". 
     *		If false the result is faster in natural order.
     * @param string or false $limit Optional. Encoded as "$offset,$count".
     * 		$offset defaults to 0.
     * @return Iterator A generic iterator containing rows of 
     * 		(duplicate) pagename, wantedfrom.
     */
    function wantedPages($exclude_from='', $exclude='', $sortby='', $limit='') {
        return $this->_backend->wanted_pages($exclude_from, $exclude, $sortby, $limit);
        //return new WikiDB_PageIterator($this, $result);
    }

    /**
     * Generic interface to the link table. Esp. useful to search for rdf triples as in 
     * SemanticSearch and ListRelations.
     *
     * @access public
     *
     * @param $pages  object A TextSearchQuery object.
     * @param $search object A TextSearchQuery object.
     * @param string $linktype One of "linkto", "linkfrom", "relation", "attribute".
     *   linktype parameter:
     * <dl>
     * <dt> "linkto"
     *    <dd> search for simple out-links
     * <dt> "linkfrom"
     *    <dd> in-links, i.e BackLinks
     * <dt> "relation"
     *    <dd> the first part in a <>::<> link 
     * <dt> "attribute"
     *    <dd> the first part in a <>:=<> link 
     * </dl>
     * @param $relation object An optional TextSearchQuery to match the 
     * relation name. Ignored on simple in-out links.
     *
     * @return Iterator A generic iterator containing links to pages or values.
     *                  hash of "pagename", "linkname", "linkvalue. 
     */
    function linkSearch($pages, $search, $linktype, $relation=false) {
        return $this->_backend->link_search($pages, $search, $linktype, $relation);
    }

    /**
     * Return a simple list of all defined relations (and attributes), mainly 
     * for the SemanticSearch autocompletion.
     *
     * @access public
     *
     * @return array of strings
     */
    function listRelations($also_attributes=false, $only_attributes=false, $sorted=true) {
        if (method_exists($this->_backend, "list_relations"))
            return $this->_backend->list_relations($also_attributes, $only_attributes, $sorted);
	// dumb, slow fallback. no iter, so simply define it here.
        $relations = array();
        $iter = $this->getAllPages();
        while ($page = $iter->next()) {
            $reliter = $page->getRelations();
            $names = array();
            while ($rel = $reliter->next()) {
		// if there's no pagename it's an attribute
                $names[] = $rel->getName();
            }
            $relations = array_merge($relations, $names);
            $reliter->free();
        }
        $iter->free();
	if ($sorted) {
	    sort($relations);
	    reset($relations);
	}
        return $relations;
    }

    /**
     * Call the appropriate backend method.
     *
     * @access public
     * @param string $from Page to rename
     * @param string $to   New name
     * @param boolean $updateWikiLinks If the text in all pages should be replaced.
     * @return boolean     true or false
     */
    function renamePage($from, $to, $updateWikiLinks = false) {
        assert(is_string($from) && $from != '');
        assert(is_string($to) && $to != '');
        $result = false;
        if (method_exists($this->_backend, 'rename_page')) {
            $oldpage = $this->getPage($from);
            $newpage = $this->getPage($to);
            //update all WikiLinks in existing pages
            //non-atomic! i.e. if rename fails the links are not undone
            if ($updateWikiLinks) {
                require_once('lib/plugin/WikiAdminSearchReplace.php');
                $links = $oldpage->getBackLinks();
                while ($linked_page = $links->next()) {
                    WikiPlugin_WikiAdminSearchReplace::replaceHelper($this,
                                                                     $linked_page->getName(),
                                                                     $from, $to);
                }
                $links = $newpage->getBackLinks();
                while ($linked_page = $links->next()) {
                    WikiPlugin_WikiAdminSearchReplace::replaceHelper($this,
                                                                     $linked_page->getName(),
                                                                     $from, $to);
                }
            }
            if ($oldpage->exists() and ! $newpage->exists()) {
                if ($result = $this->_backend->rename_page($from, $to)) {
                    //create a RecentChanges entry with explaining summary
                    $page = $this->getPage($to);
                    $current = $page->getCurrentRevision();
                    $meta = $current->_data;
                    $version = $current->getVersion();
                    $meta['summary'] = sprintf(_("renamed from %s"), $from);
		    unset($meta['mtime']); // force new date
                    $page->save($current->getPackedContent(), $version + 1, $meta);
                }
            } elseif (!$oldpage->getCurrentRevision(false) and !$newpage->exists()) {
                // if a version 0 exists try it also.
                $result = $this->_backend->rename_page($from, $to);
            }
        } else {
            trigger_error(_("WikiDB::renamePage() not yet implemented for this backend"),
                          E_USER_WARNING);
        }
        /* Generate notification emails? */
        if ($result and !isa($GLOBALS['request'], 'MockRequest')) {
            $notify = $this->get('notify');
            if (!empty($notify) and is_array($notify)) {
                include_once("lib/MailNotify.php");
                $MailNotify = new MailNotify($from);
                $MailNotify->onRenamePage ($this, $from, $to);
            }
        }
        return $result;
    }

    /** Get timestamp when database was last modified.
     *
     * @return string A string consisting of two integers,
     * separated by a space.  The first is the time in
     * unix timestamp format, the second is a modification
     * count for the database.
     *
     * The idea is that you can cast the return value to an
     * int to get a timestamp, or you can use the string value
     * as a good hash for the entire database.
     */
    function getTimestamp() {
        $ts = $this->get('_timestamp');
        return sprintf("%d %d", $ts[0], $ts[1]);
    }
    
    /**
     * Update the database timestamp.
     *
     */
    function touch() {
        $ts = $this->get('_timestamp');
        $this->set('_timestamp', array(time(), $ts[1] + 1));
    }

    /**
     * Roughly similar to the float in phpwiki_version(). Set by action=upgrade.
     */
    function get_db_version() {
        return (float) $this->get('_db_version');
    }
    function set_db_version($ver) {
        return $this->set('_db_version', (float)$ver);
    }
        
    /**
     * Access WikiDB global meta-data.
     *
     * NOTE: this is currently implemented in a hackish and
     * not very efficient manner.
     *
     * @access public
     *
     * @param string $key Which meta data to get.
     * Some reserved meta-data keys are:
     * <dl>
     * <dt>'_timestamp' <dd> Data used by getTimestamp().
     * </dl>
     *
     * @return scalar The requested value, or false if the requested data
     * is not set.
     */
    function get($key) {
        if (!$key || $key[0] == '%')
            return false;
        /*
         * Hack Alert: We can use any page (existing or not) to store
         * this data (as long as we always use the same one.)
         */
        $gd = $this->getPage('global_data');
        $data = $gd->get('__global');

        if ($data && isset($data[$key]))
            return $data[$key];
        else
            return false;
    }

    /**
     * Set global meta-data.
     *
     * NOTE: this is currently implemented in a hackish and
     * not very efficient manner.
     *
     * @see get
     * @access public
     *
     * @param string $key  Meta-data key to set.
     * @param string $newval  New value.
     */
    function set($key, $newval) {
        if (!$key || $key[0] == '%')
            return;
        
        $gd = $this->getPage('global_data');
        $data = $gd->get('__global');
        if ($data === false)
            $data = array();

        if (empty($newval))
            unset($data[$key]);
        else
            $data[$key] = $newval;

        $gd->set('__global', $data);
    }

    /* TODO: these are really backend methods */

    // SQL result: for simple select or create/update queries
    // returns the database specific resource type
    function genericSqlQuery($sql, $args=false) {
        if (function_exists('debug_backtrace')) { // >= 4.3.0
            echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
        }
        trigger_error("no SQL database", E_USER_ERROR);
        return false;
    }

    // SQL iter: for simple select or create/update queries
    // returns the generic iterator object (count,next)
    function genericSqlIter($sql, $field_list = NULL) {
        if (function_exists('debug_backtrace')) { // >= 4.3.0
            echo "<pre>", printSimpleTrace(debug_backtrace()), "</pre>\n";
        }
        trigger_error("no SQL database", E_USER_ERROR);
        return false;
    }
    
    // see backend upstream methods
    // ADODB adds surrounding quotes, SQL not yet!
    function quote ($s) {
        return $s;
    }

    function isOpen () {
        global $request;
        if (!$request->_dbi) return false;
        else return false; /* so far only needed for sql so false it. 
                            later we have to check dba also */
    }

    function getParam($param) {
        global $DBParams;
        if (isset($DBParams[$param])) return $DBParams[$param];
        elseif ($param == 'prefix') return '';
        else return false;
    }

    function getAuthParam($param) {
        global $DBAuthParams;
        if (isset($DBAuthParams[$param])) return $DBAuthParams[$param];
        elseif ($param == 'USER_AUTH_ORDER') return $GLOBALS['USER_AUTH_ORDER'];
        elseif ($param == 'USER_AUTH_POLICY') return $GLOBALS['USER_AUTH_POLICY'];
        else return false;
    }
};


/**
 * An abstract base class which representing a wiki-page within a
 * WikiDB.
 *
 * A WikiDB_Page contains a number (at least one) of
 * WikiDB_PageRevisions.
 */
class WikiDB_Page 
{
    function WikiDB_Page(&$wikidb, $pagename) {
        $this->_wikidb = &$wikidb;
        $this->_pagename = $pagename;
        if ((int)DEBUG) {
            if (!(is_string($pagename) and $pagename != '')) {
                if (function_exists("xdebug_get_function_stack")) {
                    echo "xdebug_get_function_stack(): "; var_dump(xdebug_get_function_stack());
                } elseif (function_exists("debug_backtrace")) { // >= 4.3.0
                    printSimpleTrace(debug_backtrace());
                }
                trigger_error("empty pagename", E_USER_WARNING);
                return false;
            }
        } else {
            assert(is_string($pagename) and $pagename != '');
        }
    }

    /**
     * Get the name of the wiki page.
     *
     * @access public
     *
     * @return string The page name.
     */
    function getName() {
        return $this->_pagename;
    }
    
    // To reduce the memory footprint for larger sets of pagelists,
    // we don't cache the content (only true or false) and 
    // we purge the pagedata (_cached_html) also
    function exists() {
        if (isset($this->_wikidb->_cache->_id_cache[$this->_pagename])) return true;
        $current = $this->getCurrentRevision(false);
        if (!$current) return false;
        return ! $current->hasDefaultContents();
    }

    /**
     * Delete an old revision of a WikiDB_Page.
     *
     * Deletes the specified revision of the page.
     * It is a fatal error to attempt to delete the current revision.
     *
     * @access public
     *
     * @param integer $version Which revision to delete.  (You can also
     *  use a WikiDB_PageRevision object here.)
     */
    function deleteRevision($version) {
        $backend = &$this->_wikidb->_backend;
        $cache = &$this->_wikidb->_cache;
        $pagename = &$this->_pagename;

        $version = $this->_coerce_to_version($version);
        if ($version == 0)
            return;

        $backend->lock(array('page','version'));
        $latestversion = $cache->get_latest_version($pagename);
        if ($latestversion && ($version == $latestversion)) {
            $backend->unlock(array('page','version'));
            trigger_error(sprintf("Attempt to delete most recent revision of '%s'",
                                  $pagename), E_USER_ERROR);
            return;
        }

        $cache->delete_versiondata($pagename, $version);
        $backend->unlock(array('page','version'));
    }

    /*
     * Delete a revision, or possibly merge it with a previous
     * revision.
     *
     * The idea is this:
     * Suppose an author make a (major) edit to a page.  Shortly
     * after that the same author makes a minor edit (e.g. to fix
     * spelling mistakes he just made.)
     *
     * Now some time later, where cleaning out old saved revisions,
     * and would like to delete his minor revision (since there's
     * really no point in keeping minor revisions around for a long
     * time.)
     *
     * Note that the text after the minor revision probably represents
     * what the author intended to write better than the text after
     * the preceding major edit.
     *
     * So what we really want to do is merge the minor edit with the
     * preceding edit.
     *
     * We will only do this when:
     * <ul>
     * <li>The revision being deleted is a minor one, and
     * <li>It has the same author as the immediately preceding revision.
     * </ul>
     */
    function mergeRevision($version) {
        $backend = &$this->_wikidb->_backend;
        $cache = &$this->_wikidb->_cache;
        $pagename = &$this->_pagename;

        $version = $this->_coerce_to_version($version);
        if ($version == 0)
            return;

        $backend->lock(array('version'));
        $latestversion = $cache->get_latest_version($pagename);
        if ($latestversion && $version == $latestversion) {
            $backend->unlock(array('version'));
            trigger_error(sprintf("Attempt to merge most recent revision of '%s'",
                                  $pagename), E_USER_ERROR);
            return;
        }

        $versiondata = $cache->get_versiondata($pagename, $version, true);
        if (!$versiondata) {
            // Not there? ... we're done!
            $backend->unlock(array('version'));
            return;
        }

        if ($versiondata['is_minor_edit']) {
            $previous = $backend->get_previous_version($pagename, $version);
            if ($previous) {
                $prevdata = $cache->get_versiondata($pagename, $previous);
                if ($prevdata['author_id'] == $versiondata['author_id']) {
                    // This is a minor revision, previous version is
                    // by the same author. We will merge the
                    // revisions.
                    $cache->update_versiondata($pagename, $previous,
                                               array('%content' => $versiondata['%content'],
                                                     '_supplanted' => $versiondata['_supplanted']));
                }
            }
        }

        $cache->delete_versiondata($pagename, $version);
        $backend->unlock(array('version'));
    }

    
    /**
     * Create a new revision of a {@link WikiDB_Page}.
     *
     * @access public
     *
     * @param int $version Version number for new revision.  
     * To ensure proper serialization of edits, $version must be
     * exactly one higher than the current latest version.
     * (You can defeat this check by setting $version to
     * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
     *
     * @param string $content Contents of new revision.
     *
     * @param hash $metadata Metadata for new revision.
     * All values in the hash should be scalars (strings or integers).
     *
     * @param hash $links List of linkto=>pagename, relation=>pagename which this page links to.
     *
     * @return WikiDB_PageRevision  Returns the new WikiDB_PageRevision object. If
     * $version was incorrect, returns false
     */
    function createRevision($version, &$content, $metadata, $links) {
        $backend = &$this->_wikidb->_backend;
        $cache = &$this->_wikidb->_cache;
        $pagename = &$this->_pagename;
        $cache->invalidate_cache($pagename);
        
        $backend->lock(array('version','page','recent','link','nonempty'));

        $latestversion = $backend->get_latest_version($pagename);
        $newversion = ($latestversion ? $latestversion : 0) + 1;
        assert($newversion >= 1);

        if ($version != WIKIDB_FORCE_CREATE and $version != $newversion) {
            $backend->unlock(array('version','page','recent','link','nonempty'));
            return false;
        }

        $data = $metadata;
        
        foreach ($data as $key => $val) {
            if (empty($val) || $key[0] == '_' || $key[0] == '%')
                unset($data[$key]);
        }
			
        assert(!empty($data['author']));
        if (empty($data['author_id']))
            @$data['author_id'] = $data['author'];
		
        if (empty($data['mtime']))
            $data['mtime'] = time();

        if ($latestversion and $version != WIKIDB_FORCE_CREATE) {
            // Ensure mtimes are monotonic.
            $pdata = $cache->get_versiondata($pagename, $latestversion);
            if ($data['mtime'] < $pdata['mtime']) {
                trigger_error(sprintf(_("%s: Date of new revision is %s"),
                                      $pagename,"'non-monotonic'"),
                              E_USER_NOTICE);
                $data['orig_mtime'] = $data['mtime'];
                $data['mtime'] = $pdata['mtime'];
            }
            
	    // FIXME: use (possibly user specified) 'mtime' time or
	    // time()?
            $cache->update_versiondata($pagename, $latestversion,
                                       array('_supplanted' => $data['mtime']));
        }

        $data['%content'] = &$content;

        $cache->set_versiondata($pagename, $newversion, $data);

        //$cache->update_pagedata($pagename, array(':latestversion' => $newversion,
        //':deleted' => empty($content)));
        
        $backend->set_links($pagename, $links);

        $backend->unlock(array('version','page','recent','link','nonempty'));

        return new WikiDB_PageRevision($this->_wikidb, $pagename, $newversion,
                                       $data);
    }

    /** A higher-level interface to createRevision.
     *
     * This takes care of computing the links, and storing
     * a cached version of the transformed wiki-text.
     *
     * @param string $wikitext  The page content.
     *
     * @param int $version Version number for new revision.  
     * To ensure proper serialization of edits, $version must be
     * exactly one higher than the current latest version.
     * (You can defeat this check by setting $version to
     * {@link WIKIDB_FORCE_CREATE} --- not usually recommended.)
     *
     * @param hash $meta  Meta-data for new revision.
     */
    function save($wikitext, $version, $meta, $formatted = null) {
	if (is_null($formatted))
	    $formatted = new TransformedText($this, $wikitext, $meta);
        $type = $formatted->getType();
	$meta['pagetype'] = $type->getName();
	$links = $formatted->getWikiPageLinks(); // linkto => relation
        $attributes = array();
        foreach ($links as $link) {
            if ($link['linkto'] === "" and $link['relation']) {
                $attributes[$link['relation']] = $this->getAttribute($link['relation']);
            }
        }
        $meta['attribute'] = $attributes;

	$backend = &$this->_wikidb->_backend;
	$newrevision = $this->createRevision($version, $wikitext, $meta, $links);
	if ($newrevision and !WIKIDB_NOCACHE_MARKUP)
            $this->set('_cached_html', $formatted->pack());

	// FIXME: probably should have some global state information
	// in the backend to control when to optimize.
        //
        // We're doing this here rather than in createRevision because
        // postgresql can't optimize while locked.
        if (((int)DEBUG & _DEBUG_SQL)
	    or (DATABASE_OPTIMISE_FREQUENCY > 0 and 
                (time() % DATABASE_OPTIMISE_FREQUENCY == 0))) {
            if ($backend->optimize()) {
                if ((int)DEBUG)
                    trigger_error(_("Optimizing database"), E_USER_NOTICE);
            }
        }

        /* Generate notification emails? */
        if (isa($newrevision, 'WikiDB_PageRevision')) {
            // Save didn't fail because of concurrent updates.
            $notify = $this->_wikidb->get('notify');
            if (!empty($notify) 
		and is_array($notify) 
		and !isa($GLOBALS['request'],'MockRequest')) 
	    {
                include_once("lib/MailNotify.php");
                $MailNotify = new MailNotify($newrevision->getName());
		$MailNotify->onChangePage ($this->_wikidb, $wikitext, $version, $meta);
            }
            $newrevision->_transformedContent = $formatted;
        }

	return $newrevision;
    }

    /**
     * Get the most recent revision of a page.
     *
     * @access public
     *
     * @return WikiDB_PageRevision The current WikiDB_PageRevision object. 
     */
    function getCurrentRevision ($need_content=true) {
        $backend = &$this->_wikidb->_backend;
        $cache = &$this->_wikidb->_cache;
        $pagename = &$this->_pagename;
        
        // Prevent deadlock in case of memory exhausted errors
        // Pure selection doesn't really need locking here.
        //   sf.net bug#927395
        // I know it would be better to lock, but with lots of pages this deadlock is more 
        // severe than occasionally get not the latest revision.
        // In spirit to wikiwiki: read fast, edit slower.
        //$backend->lock();
        $version = $cache->get_latest_version($pagename);
        // getRevision gets the content also!
        $revision = $this->getRevision($version, $need_content);
        //$backend->unlock();
        assert($revision);
        return $revision;
    }

    /**
     * Get a specific revision of a WikiDB_Page.
     *
     * @access public
     *
     * @param integer $version  Which revision to get.
     *
     * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or
     * false if the requested revision does not exist in the {@link WikiDB}.
     * Note that version zero of any page always exists.
     */
    function getRevision ($version, $need_content=true) {
        $cache = &$this->_wikidb->_cache;
        $pagename = &$this->_pagename;
        
        if (! $version or $version == -1) // 0 or false
            return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);

        assert($version > 0);
        $vdata = $cache->get_versiondata($pagename, $version, $need_content);
        if (!$vdata) {
            return new WikiDB_PageRevision($this->_wikidb, $pagename, 0);
        }
        return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
                                       $vdata);
    }

    /**
     * Get previous page revision.
     *
     * This method find the most recent revision before a specified
     * version.
     *
     * @access public
     *
     * @param integer $version  Find most recent revision before this version.
     *  You can also use a WikiDB_PageRevision object to specify the $version.
     *
     * @return WikiDB_PageRevision The requested WikiDB_PageRevision object, or false if the
     * requested revision does not exist in the {@link WikiDB}.  Note that
     * unless $version is greater than zero, a revision (perhaps version zero,
     * the default revision) will always be found.
     */
    function getRevisionBefore ($version=false, $need_content=true) {
        $backend = &$this->_wikidb->_backend;
        $pagename = &$this->_pagename;
        if ($version === false)
            $version = $this->_wikidb->_cache->get_latest_version($pagename);
        else
            $version = $this->_coerce_to_version($version);

        if ($version == 0)
            return false;
        //$backend->lock();
        $previous = $backend->get_previous_version($pagename, $version);
        $revision = $this->getRevision($previous, $need_content);
        //$backend->unlock();
        assert($revision);
        return $revision;
    }

    /**
     * Get all revisions of the WikiDB_Page.
     *
     * This does not include the version zero (default) revision in the
     * returned revision set.
     *
     * @return WikiDB_PageRevisionIterator A
     *   WikiDB_PageRevisionIterator containing all revisions of this
     *   WikiDB_Page in reverse order by version number.
     */
    function getAllRevisions() {
        $backend = &$this->_wikidb->_backend;
        $revs = $backend->get_all_revisions($this->_pagename);
        return new WikiDB_PageRevisionIterator($this->_wikidb, $revs);
    }
    
    /**
     * Find pages which link to or are linked from a page.
     * relations: $backend->get_links is responsible to add the relation to the pagehash 
     * as 'linkrelation' key as pagename. See WikiDB_PageIterator::next 
     *   if (isset($next['linkrelation']))
     *
     * @access public
     *
     * @param boolean $reversed Which links to find: true for backlinks (default).
     *
     * @return WikiDB_PageIterator A WikiDB_PageIterator containing
     * all matching pages.
     */
    function getLinks ($reversed=true, $include_empty=false, $sortby='', 
                       $limit='', $exclude='', $want_relations=false) 
    {
        $backend = &$this->_wikidb->_backend;
        $result =  $backend->get_links($this->_pagename, $reversed, 
                                       $include_empty, $sortby, $limit, $exclude,
                                       $want_relations);
        return new WikiDB_PageIterator($this->_wikidb, $result, 
                                       array('include_empty' => $include_empty,
                                             'sortby'        => $sortby, 
                                             'limit'         => $limit, 
                                             'exclude'       => $exclude,
                                             'want_relations'=> $want_relations));
    }

    /**
     * All Links from other pages to this page.
     */
    function getBackLinks($include_empty=false, $sortby='', $limit='', $exclude='', 
                          $want_relations=false) 
    {
        return $this->getLinks(true, $include_empty, $sortby, $limit, $exclude);
    }
    /**
     * Forward Links: All Links from this page to other pages.
     */
    function getPageLinks($include_empty=false, $sortby='', $limit='', $exclude='', 
                          $want_relations=false) 
    {
        return $this->getLinks(false, $include_empty, $sortby, $limit, $exclude);
    }
    /**
     * Relations: All links from this page to other pages with relation <> 0. 
     * is_a:=page or population:=number
     */
    function getRelations($sortby='', $limit='', $exclude='') {
        $backend = &$this->_wikidb->_backend;
        $result =  $backend->get_links($this->_pagename, false, true,
                                       $sortby, $limit, $exclude, 
                                       true);
        // we do not care for the linked page versiondata, just the pagename and linkrelation
        return new WikiDB_PageIterator($this->_wikidb, $result, 
                                       array('include_empty' => true,
                                             'sortby'        => $sortby, 
                                             'limit'         => $limit, 
                                             'exclude'       => $exclude,
                                             'want_relations'=> true));
    }
    
    /**
     * possibly faster link existance check. not yet accelerated.
     */
    function existLink($link, $reversed=false) {
        $backend = &$this->_wikidb->_backend;
        if (method_exists($backend,'exists_link'))
            return $backend->exists_link($this->_pagename, $link, $reversed);
        //$cache = &$this->_wikidb->_cache;
        // TODO: check cache if it is possible
        $iter = $this->getLinks($reversed, false);
        while ($page = $iter->next()) {
            if ($page->getName() == $link)
                return $page;
        }
        $iter->free();
        return false;
    }

    /* Semantic relations are links with the relation pointing to another page,
       the so-called "RDF Triple".
       [San Diego] is%20a::city
       => "At the page San Diego there is a relation link of 'is a' to the page 'city'."
     */

    /* Semantic attributes for a page. 
       [San Diego] population:=1,305,736
       Attributes are links with the relation pointing to another page.
    */
            
    /**
     * Access WikiDB_Page non version-specific meta-data.
     *
     * @access public
     *
     * @param string $key Which meta data to get.
     * Some reserved meta-data keys are:
     * <dl>
     * <dt>'date'  <dd> Created as unixtime
     * <dt>'locked'<dd> Is page locked? 'yes' or 'no'
     * <dt>'hits'  <dd> Page hit counter.
     * <dt>'_cached_html' <dd> Transformed CachedMarkup object, serialized + optionally gzipped.
     *                         In SQL stored now in an extra column.
     * Optional data:
     * <dt>'pref'  <dd> Users preferences, stored only in homepages.
     * <dt>'owner' <dd> Default: first author_id. We might add a group with a dot here:
     *                  E.g. "owner.users"
     * <dt>'perm'  <dd> Permission flag to authorize read/write/execution of 
     *                  page-headers and content.
     + <dt>'moderation'<dd> ModeratedPage data
     * <dt>'score' <dd> Page score (not yet implement, do we need?)
     * </dl>
     *
     * @return scalar The requested value, or false if the requested data
     * is not set.
     */
    function get($key) {
        $cache = &$this->_wikidb->_cache;
        $backend = &$this->_wikidb->_backend;
        if (!$key || $key[0] == '%')
            return false;
        // several new SQL backends optimize this.
        if (!WIKIDB_NOCACHE_MARKUP
            and $key == '_cached_html' 
            and method_exists($backend, 'get_cached_html')) 
        {
            return $backend->get_cached_html($this->_pagename);
        }
        $data = $cache->get_pagedata($this->_pagename);
        return isset($data[$key]) ? $data[$key] : false;
    }

    /**
     * Get all the page meta-data as a hash.
     *
     * @return hash The page meta-data.
     */
    function getMetaData() {
        $cache = &$this->_wikidb->_cache;
        $data = $cache->get_pagedata($this->_pagename);
        $meta = array();
        foreach ($data as $key => $val) {
            if (/*!empty($val) &&*/ $key[0] != '%')
                $meta[$key] = $val;
        }
        return $meta;
    }

    /**
     * Set page meta-data.
     *
     * @see get
     * @access public
     *
     * @param string $key  Meta-data key to set.
     * @param string $newval  New value.
     */
    function set($key, $newval) {
        $cache = &$this->_wikidb->_cache;
        $backend = &$this->_wikidb->_backend;
        $pagename = &$this->_pagename;
        
        assert($key && $key[0] != '%');

        // several new SQL backends optimize this.
        if (!WIKIDB_NOCACHE_MARKUP 
            and $key == '_cached_html' 
            and method_exists($backend, 'set_cached_html'))
        {
            return $backend->set_cached_html($pagename, $newval);
        }

        $data = $cache->get_pagedata($pagename);

        if (!empty($newval)) {
            if (!empty($data[$key]) && $data[$key] == $newval)
                return;         // values identical, skip update.
        }
        else {
            if (empty($data[$key]))
                return;         // values identical, skip update.
        }

        $cache->update_pagedata($pagename, array($key => $newval));
    }

    /**
     * Increase page hit count.
     *
     * FIXME: IS this needed?  Probably not.
     *
     * This is a convenience function.
     * <pre> $page->increaseHitCount(); </pre>
     * is functionally identical to
     * <pre> $page->set('hits',$page->get('hits')+1); </pre>
     * but less expensive (ignores the pagadata string)
     *
     * Note that this method may be implemented in more efficient ways
     * in certain backends.
     *
     * @access public
     */
    function increaseHitCount() {
        if (method_exists($this->_wikidb->_backend, 'increaseHitCount'))
            $this->_wikidb->_backend->increaseHitCount($this->_pagename);
        else {
            @$newhits = $this->get('hits') + 1;
            $this->set('hits', $newhits);
        }
    }

    /**
     * Return a string representation of the WikiDB_Page
     *
     * This is really only for debugging.
     *
     * @access public
     *
     * @return string Printable representation of the WikiDB_Page.
     */
    function asString () {
        ob_start();
        printf("[%s:%s\n", get_class($this), $this->getName());
        print_r($this->getMetaData());
        echo "]\n";
        $strval = ob_get_contents();
        ob_end_clean();
        return $strval;
    }


    /**
     * @access private
     * @param integer_or_object $version_or_pagerevision
     * Takes either the version number (and int) or a WikiDB_PageRevision
     * object.
     * @return integer The version number.
     */
    function _coerce_to_version($version_or_pagerevision) {
        if (method_exists($version_or_pagerevision, "getContent"))
            $version = $version_or_pagerevision->getVersion();
        else
            $version = (int) $version_or_pagerevision;

        assert($version >= 0);
        return $version;
    }

    function isUserPage ($include_empty = true) {
        if (!$include_empty and !$this->exists()) return false;
        return $this->get('pref') ? true : false;
    }

    // May be empty. Either the stored owner (/Chown), or the first authorized author
    function getOwner() {
        if ($owner = $this->get('owner'))
            return ($owner == _("The PhpWiki programming team")) ? ADMIN_USER : $owner;
        // check all revisions forwards for the first author_id
        $backend = &$this->_wikidb->_backend;
        $pagename = &$this->_pagename;
        $latestversion = $backend->get_latest_version($pagename);
        for ($v=1; $v <= $latestversion; $v++) {
            $rev = $this->getRevision($v,false);
            if ($rev and $owner = $rev->get('author_id')) {
            	return ($owner == _("The PhpWiki programming team")) ? ADMIN_USER : $owner;
            }
        }
        return '';
    }

    // The authenticated author of the first revision or empty if not authenticated then.
    function getCreator() {
        if ($current = $this->getRevision(1,false)) return $current->get('author_id');
        else return '';
    }

    // The authenticated author of the current revision.
    function getAuthor() {
        if ($current = $this->getCurrentRevision(false)) return $current->get('author_id');
        else return '';
    }

    /* Semantic Web value, not stored in the links.
     * todo: unify with some unit knowledge
     */
    function setAttribute($relation, $value) {
    	$attr = $this->get('attributes');
    	if (empty($attr))
    	    $attr = array($relation => $value);
    	else
    	    $attr[$relation] = $value;
    	$this->set('attributes', $attr);
    }

    function getAttribute($relation) {
    	$meta = $this->get('attributes');
    	if (empty($meta))
    	    return '';
    	else
    	    return $meta[$relation];
    }

};

/**
 * This class represents a specific revision of a WikiDB_Page within
 * a WikiDB.
 *
 * A WikiDB_PageRevision has read-only semantics. You may only create
 * new revisions (and delete old ones) --- you cannot modify existing
 * revisions.
 */
class WikiDB_PageRevision
{
    //var $_transformedContent = false; // set by WikiDB_Page::save()
    
    function WikiDB_PageRevision(&$wikidb, $pagename, $version, $versiondata = false) {
        $this->_wikidb = &$wikidb;
        $this->_pagename = $pagename;
        $this->_version = $version;
        $this->_data = $versiondata ? $versiondata : array();
        $this->_transformedContent = false; // set by WikiDB_Page::save()
    }
    
    /**
     * Get the WikiDB_Page which this revision belongs to.
     *
     * @access public
     *
     * @return WikiDB_Page The WikiDB_Page which this revision belongs to.
     */
    function getPage() {
        return new WikiDB_Page($this->_wikidb, $this->_pagename);
    }

    /**
     * Get the version number of this revision.
     *
     * @access public
     *
     * @return integer The version number of this revision.
     */
    function getVersion() {
        return $this->_version;
    }
    
    /**
     * Determine whether this revision has defaulted content.
     *
     * The default revision (version 0) of each page, as well as any
     * pages which are created with empty content have their content
     * defaulted to something like:
     * <pre>
     *   Describe [ThisPage] here.
     * </pre>
     *
     * @access public
     *
     * @return boolean Returns true if the page has default content.
     */
    function hasDefaultContents() {
        $data = &$this->_data;
        return empty($data['%content']); // FIXME: what if it's the number 0? <>'' or === false
    }

    /**
     * Get the content as an array of lines.
     *
     * @access public
     *
     * @return array An array of lines.
     * The lines should contain no trailing white space.
     */
    function getContent() {
        return explode("\n", $this->getPackedContent());
    }
	
   /**
     * Get the pagename of the revision.
     *
     * @access public
     *
     * @return string pagename.
     */
    function getPageName() {
        return $this->_pagename;
    }
    function getName() {
        return $this->_pagename;
    }

    /**
     * Determine whether revision is the latest.
     *
     * @access public
     *
     * @return boolean True iff the revision is the latest (most recent) one.
     */
    function isCurrent() {
        if (!isset($this->_iscurrent)) {
            $page = $this->getPage();
            $current = $page->getCurrentRevision(false);
            $this->_iscurrent = $this->getVersion() == $current->getVersion();
        }
        return $this->_iscurrent;
    }

    /**
     * Get the transformed content of a page.
     *
     * @param string $pagetype  Override the page-type of the revision.
     *
     * @return object An XmlContent-like object containing the page transformed
     * contents.
     */
    function getTransformedContent($pagetype_override=false) {
	$backend = &$this->_wikidb->_backend;
        
	if ($pagetype_override) {
	    // Figure out the normal page-type for this page.
            $type = PageType::GetPageType($this->get('pagetype'));
	    if ($type->getName() == $pagetype_override)
		$pagetype_override = false; // Not really an override...
	}

        if ($pagetype_override) {
            // Overriden page type, don't cache (or check cache).
	    return new TransformedText($this->getPage(),
                                       $this->getPackedContent(),
                                       $this->getMetaData(),
                                       $pagetype_override);
        }

        $possibly_cache_results = true;

        if (!USECACHE or WIKIDB_NOCACHE_MARKUP) {
            if (WIKIDB_NOCACHE_MARKUP == 'purge') {
                // flush cache for this page.
                $page = $this->getPage();
                $page->set('_cached_html', ''); // ignored with !USECACHE 
            }
            $possibly_cache_results = false;
        }
        elseif (USECACHE and !$this->_transformedContent) {
            //$backend->lock();
            if ($this->isCurrent()) {
                $page = $this->getPage();
                $this->_transformedContent = TransformedText::unpack($page->get('_cached_html'));
            }
            else {
                $possibly_cache_results = false;
            }
            //$backend->unlock();
	}
        
        if (!$this->_transformedContent) {
            $this->_transformedContent
                = new TransformedText($this->getPage(),
                                      $this->getPackedContent(),
                                      $this->getMetaData());
            
            if ($possibly_cache_results and !WIKIDB_NOCACHE_MARKUP) {
                // If we're still the current version, cache the transfomed page.
                //$backend->lock();
                if ($this->isCurrent()) {
                    $page->set('_cached_html', $this->_transformedContent->pack());
                }
                //$backend->unlock();
            }
        }

        return $this->_transformedContent;
    }

    /**
     * Get the content as a string.
     *
     * @access public
     *
     * @return string The page content.
     * Lines are separated by new-lines.
     */
    function getPackedContent() {
        $data = &$this->_data;
        
        if (empty($data['%content'])
            || (!$this->_wikidb->isWikiPage($this->_pagename)
                && $this->isCurrent())) {
            include_once('lib/InlineParser.php');

            // A feature similar to taglines at http://www.wlug.org.nz/
            // Lib from http://www.aasted.org/quote/
            if (defined('FORTUNE_DIR') 
                and is_dir(FORTUNE_DIR) 
                and in_array($GLOBALS['request']->getArg('action'), 
                             array('create','edit')))
            {
                include_once("lib/fortune.php");
                $fortune = new Fortune();
		$quote = $fortune->quoteFromDir(FORTUNE_DIR);
		if ($quote != -1)
		    $quote = "<verbatim>\n"
			. str_replace("\n<br>","\n", $quote)
			. "</verbatim>\n\n";
		else 
		    $quote = "";
                return $quote
		    . sprintf(_("Describe %s here."), 
			      "[" . WikiEscape($this->_pagename) . "]");
            }
            // Replace empty content with default value.
            return sprintf(_("Describe %s here."), 
                           "[" . WikiEscape($this->_pagename) . "]");
        }

        // There is (non-default) content.
        assert($this->_version > 0);
        
        if (!is_string($data['%content'])) {
            // Content was not provided to us at init time.
            // (This is allowed because for some backends, fetching
            // the content may be expensive, and often is not wanted
            // by the user.)
            //
            // In any case, now we need to get it.
            $data['%content'] = $this->_get_content();
            assert(is_string($data['%content']));
        }
        
        return $data['%content'];
    }

    function _get_content() {
        $cache = &$this->_wikidb->_cache;
        $pagename = $this->_pagename;
        $version = $this->_version;

        assert($version > 0);
        
        $newdata = $cache->get_versiondata($pagename, $version, true);
        if ($newdata) {
            assert(is_string($newdata['%content']));
            return $newdata['%content'];
        }
        else {
            // else revision has been deleted... What to do?
            return __sprintf("Oops! Revision %s of %s seems to have been deleted!",
                             $version, $pagename);
        }
    }

    /**
     * Get meta-data for this revision.
     *
     *
     * @access public
     *
     * @param string $key Which meta-data to access.
     *
     * Some reserved revision meta-data keys are:
     * <dl>
     * <dt> 'mtime' <dd> Time this revision was created (seconds since midnight Jan 1, 1970.)
     *        The 'mtime' meta-value is normally set automatically by the database
     *        backend, but it may be specified explicitly when creating a new revision.
     * <dt> orig_mtime
     *  <dd> To ensure consistency of RecentChanges, the mtimes of the versions
     *       of a page must be monotonically increasing.  If an attempt is
     *       made to create a new revision with an mtime less than that of
     *       the preceeding revision, the new revisions timestamp is force
     *       to be equal to that of the preceeding revision.  In that case,
     *       the originally requested mtime is preserved in 'orig_mtime'.
     * <dt> '_supplanted' <dd> Time this revision ceased to be the most recent.
     *        This meta-value is <em>always</em> automatically maintained by the database
     *        backend.  (It is set from the 'mtime' meta-value of the superceding
     *        revision.)  '_supplanted' has a value of 'false' for the current revision.
     *
     * FIXME: this could be refactored:
     * <dt> author
     *  <dd> Author of the page (as he should be reported in, e.g. RecentChanges.)
     * <dt> author_id
     *  <dd> Authenticated author of a page.  This is used to identify
     *       the distinctness of authors when cleaning old revisions from
     *       the database.
     * <dt> 'is_minor_edit' <dd> Set if change was marked as a minor revision by the author.
     * <dt> 'summary' <dd> Short change summary entered by page author.
     * </dl>
     *
     * Meta-data keys must be valid C identifers (they have to start with a letter
     * or underscore, and can contain only alphanumerics and underscores.)
     *
     * @return string The requested value, or false if the requested value
     * is not defined.
     */
    function get($key) {
        if (!$key || $key[0] == '%')
            return false;
        $data = &$this->_data;
        return isset($data[$key]) ? $data[$key] : false;
    }

    /**
     * Get all the revision page meta-data as a hash.
     *
     * @return hash The revision meta-data.
     */
    function getMetaData() {
        $meta = array();
        foreach ($this->_data as $key => $val) {
            if (!empty($val) && $key[0] != '%')
                $meta[$key] = $val;
        }
        return $meta;
    }
    
            
    /**
     * Return a string representation of the revision.
     *
     * This is really only for debugging.
     *
     * @access public
     *
     * @return string Printable representation of the WikiDB_Page.
     */
    function asString () {
        ob_start();
        printf("[%s:%d\n", get_class($this), $this->get('version'));
        print_r($this->_data);
        echo $this->getPackedContent() . "\n]\n";
        $strval = ob_get_contents();
        ob_end_clean();
        return $strval;
    }
};


/**
 * Class representing a sequence of WikiDB_Pages.
 * TODO: Enhance to php5 iterators
 * TODO: 
 *   apply filters for options like 'sortby', 'limit', 'exclude'
 *   for simple queries like titleSearch, where the backend is not ready yet.
 */
class WikiDB_PageIterator
{
    function WikiDB_PageIterator(&$wikidb, &$iter, $options=false) {
        $this->_iter = $iter; // a WikiDB_backend_iterator
        $this->_wikidb = &$wikidb;
        $this->_options = $options;
    }
    
    function count () {
        return $this->_iter->count();
    }

    /**
     * Get next WikiDB_Page in sequence.
     *
     * @access public
     *
     * @return WikiDB_Page The next WikiDB_Page in the sequence.
     */
    function next () {
        if ( ! ($next = $this->_iter->next()) )
            return false;

        $pagename = &$next['pagename'];
	if (!is_string($pagename)) { // Bug #1327912 fixed by Joachim Lous
	    /*if (is_array($pagename) && isset($pagename['linkto'])) {
		$pagename = $pagename['linkto'];
	    }
            $pagename = strval($pagename);*/
            trigger_error("WikiDB_PageIterator->next pagename", E_USER_WARNING);
	}
        if (!$pagename) {
            if (isset($next['linkrelation']) 
                or isset($next['pagedata']['linkrelation'])) return false;	
            trigger_error('empty pagename in WikiDB_PageIterator::next()', E_USER_WARNING);
            var_dump($next);
            return false;
        }
        // There's always hits, but we cache only if more 
        // (well not with file, cvs and dba)
        if (isset($next['pagedata']) and count($next['pagedata']) > 1) {
            $this->_wikidb->_cache->cache_data($next);
        // cache existing page id's since we iterate over all links in GleanDescription 
        // and need them later for LinkExistingWord
        } elseif ($this->_options and array_key_exists('include_empty', $this->_options)
                  and !$this->_options['include_empty'] and isset($next['id'])) {
            $this->_wikidb->_cache->_id_cache[$next['pagename']] = $next['id'];
        }
        $page = new WikiDB_Page($this->_wikidb, $pagename);
        if (isset($next['linkrelation']))
            $page->set('linkrelation', $next['linkrelation']);
        return $page;
    }

    /**
     * Release resources held by this iterator.
     *
     * The iterator may not be used after free() is called.
     *
     * There is no need to call free(), if next() has returned false.
     * (I.e. if you iterate through all the pages in the sequence,
     * you do not need to call free() --- you only need to call it
     * if you stop before the end of the iterator is reached.)
     *
     * @access public
     */
    function free() {
        $this->_iter->free();
    }
    
    function asArray() {
    	$result = array();
    	while ($page = $this->next())
            $result[] = $page;
        //$this->reset();
        return $result;
    }
    
    /**
     * Apply filters for options like 'sortby', 'limit', 'exclude'
     * for simple queries like titleSearch, where the backend is not ready yet.
     * Since iteration is usually destructive for SQL results,
     * we have to generate a copy.
     */
    function applyFilters($options = false) {
        if (!$options) $options = $this->_options;
        if (isset($options['sortby'])) {
            $array = array();
            /* this is destructive */
            while ($page = $this->next())
                $result[] = $page->getName();
            $this->_doSort($array, $options['sortby']);
        }
        /* the rest is not destructive.
         * reconstruct a new iterator 
         */
        $pagenames = array(); $i = 0;
        if (isset($options['limit']))
            $limit = $options['limit'];
        else 
            $limit = 0;
        if (isset($options['exclude']))
            $exclude = $options['exclude'];
        if (is_string($exclude) and !is_array($exclude))
            $exclude = PageList::explodePageList($exclude, false, false, $limit);
        foreach($array as $pagename) {
            if ($limit and $i++ > $limit)
                return new WikiDB_Array_PageIterator($pagenames);
            if (!empty($exclude) and !in_array($pagename, $exclude))
                $pagenames[] = $pagename;
            elseif (empty($exclude))
                $pagenames[] = $pagename;
        }
        return new WikiDB_Array_PageIterator($pagenames);
    }

    /* pagename only */
    function _doSort(&$array, $sortby) {
        $sortby = PageList::sortby($sortby, 'init');
        if ($sortby == '+pagename')
            sort($array, SORT_STRING);
        elseif ($sortby == '-pagename')
            rsort($array, SORT_STRING);
        reset($array);
    }

};

/**
 * A class which represents a sequence of WikiDB_PageRevisions.
 * TODO: Enhance to php5 iterators
 */
class WikiDB_PageRevisionIterator
{
    function WikiDB_PageRevisionIterator(&$wikidb, &$revisions, $options=false) {
        $this->_revisions = $revisions;
        $this->_wikidb = &$wikidb;
        $this->_options = $options;
    }
    
    function count () {
        return $this->_revisions->count();
    }

    /**
     * Get next WikiDB_PageRevision in sequence.
     *
     * @access public
     *
     * @return WikiDB_PageRevision
     * The next WikiDB_PageRevision in the sequence.
     */
    function next () {
        if ( ! ($next = $this->_revisions->next()) )
            return false;

        //$this->_wikidb->_cache->cache_data($next);

        $pagename = $next['pagename'];
        $version = $next['version'];
        $versiondata = $next['versiondata'];
        if ((int)DEBUG) {
            if (!(is_string($pagename) and $pagename != '')) {
                trigger_error("empty pagename",E_USER_WARNING);
                return false;
            }
        } else assert(is_string($pagename) and $pagename != '');
        if ((int)DEBUG) {
            if (!is_array($versiondata)) {
                trigger_error("empty versiondata",E_USER_WARNING);
                return false;
            }
        } else assert(is_array($versiondata));
        if ((int)DEBUG) {
            if (!($version > 0)) {
                trigger_error("invalid version",E_USER_WARNING);
                return false;
            }
        } else assert($version > 0);

        return new WikiDB_PageRevision($this->_wikidb, $pagename, $version,
                                       $versiondata);
    }

    /**
     * Release resources held by this iterator.
     *
     * The iterator may not be used after free() is called.
     *
     * There is no need to call free(), if next() has returned false.
     * (I.e. if you iterate through all the revisions in the sequence,
     * you do not need to call free() --- you only need to call it
     * if you stop before the end of the iterator is reached.)
     *
     * @access public
     */
    function free() { 
        $this->_revisions->free();
    }

    function asArray() {
    	$result = array();
    	while ($rev = $this->next())
            $result[] = $rev;
        $this->free();
        return $result;
    }
};

/** pseudo iterator
 */
class WikiDB_Array_PageIterator
{
    function WikiDB_Array_PageIterator($pagenames) {
        global $request;
        $this->_dbi = $request->getDbh();
        $this->_pages = $pagenames;
        reset($this->_pages);
    }
    function next() {
        $c =& current($this->_pages);
        next($this->_pages);
        return $c !== false ? $this->_dbi->getPage($c) : false;
    }
    function count() {
        return count($this->_pages);
    }
    function free() {}
    function asArray() {
        reset($this->_pages);
        return $this->_pages;
    }
}

class WikiDB_Array_generic_iter
{
    function WikiDB_Array_generic_iter($result) {
        // $result may be either an array or a query result
        if (is_array($result)) {
            $this->_array = $result;
        } elseif (is_object($result)) {
            $this->_array = $result->asArray();
        } else {
            $this->_array = array();
        }
        if (!empty($this->_array))
            reset($this->_array);
    }
    function next() {
        $c =& current($this->_array);
        next($this->_array);
        return $c !== false ? $c : false;
    }
    function count() {
        return count($this->_array);
    }
    function free() {}
    function asArray() {
        if (!empty($this->_array))
            reset($this->_array);
        return $this->_array;
    }
}

/**
 * Data cache used by WikiDB.
 *
 * FIXME: Maybe rename this to caching_backend (or some such).
 *
 * @access private
 */
class WikiDB_cache 
{
    // FIXME: beautify versiondata cache.  Cache only limited data?

    function WikiDB_cache (&$backend) {
        $this->_backend = &$backend;

        $this->_pagedata_cache = array();
        $this->_versiondata_cache = array();
        array_push ($this->_versiondata_cache, array());
        $this->_glv_cache = array();
        $this->_id_cache = array(); // formerly ->_dbi->_iwpcache (nonempty pages => id)
    }
    
    function close() {
        $this->_pagedata_cache = array();
        $this->_versiondata_cache = array();
        $this->_glv_cache = array();
        $this->_id_cache = array();
    }

    function get_pagedata($pagename) {
        assert(is_string($pagename) && $pagename != '');
        if (USECACHE) {
            $cache = &$this->_pagedata_cache;
            if (!isset($cache[$pagename]) || !is_array($cache[$pagename])) {
                $cache[$pagename] = $this->_backend->get_pagedata($pagename);
                if (empty($cache[$pagename]))
                    $cache[$pagename] = array();
            }
            return $cache[$pagename];
        } else {
            return $this->_backend->get_pagedata($pagename);
        }
    }
    
    function update_pagedata($pagename, $newdata) {
        assert(is_string($pagename) && $pagename != '');
       
        $this->_backend->update_pagedata($pagename, $newdata);

        if (USECACHE) {
            if (!empty($this->_pagedata_cache[$pagename]) 
                and is_array($this->_pagedata_cache[$pagename])) 
            {
                $cachedata = &$this->_pagedata_cache[$pagename];
                foreach($newdata as $key => $val)
                    $cachedata[$key] = $val;
            } else 
                $this->_pagedata_cache[$pagename] = $newdata;
        }
    }

    function invalidate_cache($pagename) {
        unset ($this->_pagedata_cache[$pagename]);
        unset ($this->_versiondata_cache[$pagename]);
        unset ($this->_glv_cache[$pagename]);
        unset ($this->_id_cache[$pagename]);
        //unset ($this->_backend->_page_data);
    }
    
    function delete_page($pagename) {
        $result = $this->_backend->delete_page($pagename);
        $this->invalidate_cache($pagename);
        return $result;
    }

    function purge_page($pagename) {
        $result = $this->_backend->purge_page($pagename);
        $this->invalidate_cache($pagename);
        return $result;
    }

    // FIXME: ugly and wrong. may overwrite full cache with partial cache
    function cache_data($data) {
    	;
        //if (isset($data['pagedata']))
        //    $this->_pagedata_cache[$data['pagename']] = $data['pagedata'];
    }
    
    function get_versiondata($pagename, $version, $need_content = false) {
        //  FIXME: Seriously ugly hackage
        $readdata = false;
	if (USECACHE) {   //temporary - for debugging
            assert(is_string($pagename) && $pagename != '');
            // There is a bug here somewhere which results in an assertion failure at line 105
            // of ArchiveCleaner.php  It goes away if we use the next line.
            //$need_content = true;
            $nc = $need_content ? '1':'0';
            $cache = &$this->_versiondata_cache;
            if (!isset($cache[$pagename][$version][$nc]) 
                || !(is_array ($cache[$pagename])) 
                || !(is_array ($cache[$pagename][$version]))) 
            {
                $cache[$pagename][$version][$nc] = 
                    $this->_backend->get_versiondata($pagename, $version, $need_content);
                $readdata = true;
                // If we have retrieved all data, we may as well set the cache for 
                // $need_content = false
                if ($need_content){
                    $cache[$pagename][$version]['0'] =& $cache[$pagename][$version]['1'];
                }
            }
            $vdata = $cache[$pagename][$version][$nc];
	} else {
            $vdata = $this->_backend->get_versiondata($pagename, $version, $need_content);
            $readdata = true;
	}
        if ($readdata && $vdata && !empty($vdata['%pagedata'])) {
            $this->_pagedata_cache[$pagename] =& $vdata['%pagedata'];
        }
        return $vdata;
    }

    function set_versiondata($pagename, $version, $data) {
        //unset($this->_versiondata_cache[$pagename][$version]);
        
        $new = $this->_backend->set_versiondata($pagename, $version, $data);
        // Update the cache
        $this->_versiondata_cache[$pagename][$version]['1'] = $data;
        $this->_versiondata_cache[$pagename][$version]['0'] = $data;
        // Is this necessary?
        unset($this->_glv_cache[$pagename]);
    }

    function update_versiondata($pagename, $version, $data) {
        $new = $this->_backend->update_versiondata($pagename, $version, $data);
        // Update the cache
        $this->_versiondata_cache[$pagename][$version]['1'] = $data;
        // FIXME: hack
        $this->_versiondata_cache[$pagename][$version]['0'] = $data;
        // Is this necessary?
        unset($this->_glv_cache[$pagename]);
    }

    function delete_versiondata($pagename, $version) {
        $new = $this->_backend->delete_versiondata($pagename, $version);
        if (isset($this->_versiondata_cache[$pagename][$version]))
            unset ($this->_versiondata_cache[$pagename][$version]);
        // dirty latest version cache only if latest version gets deleted
        if (isset($this->_glv_cache[$pagename]) and $this->_glv_cache[$pagename] == $version)
            unset ($this->_glv_cache[$pagename]);
    }
	
    function get_latest_version($pagename)  {
        if (USECACHE) {
            assert (is_string($pagename) && $pagename != '');
            $cache = &$this->_glv_cache;
            if (!isset($cache[$pagename])) {
                $cache[$pagename] = $this->_backend->get_latest_version($pagename);
                if (empty($cache[$pagename]))
                    $cache[$pagename] = 0;
            }
            return $cache[$pagename];
        } else {
            return $this->_backend->get_latest_version($pagename); 
        }
    }
};

function _sql_debuglog($msg, $newline=true, $shutdown=false) {
    static $fp = false;
    static $i = 0;
    if (!$fp) {
        $stamp = strftime("%y%m%d-%H%M%S");
        $fp = fopen(TEMP_DIR."/sql-$stamp.log", "a");
        register_shutdown_function("_sql_debuglog_shutdown_function");
    } elseif ($shutdown) {
        fclose($fp);
        return;
    }
    if ($newline) fputs($fp, "[$i++] $msg");
    else fwrite($fp, $msg);
}

function _sql_debuglog_shutdown_function() {
    _sql_debuglog('',false,true);
}

// $Log: WikiDB.php,v $
// Revision 1.153  2007/06/07 16:54:29  rurban
// enable $MailNotify->onChangePage. support other formatters (MediaWiki, Creole, ...)
//
// Revision 1.152  2007/05/28 20:13:46  rurban
// Overwrite all attributes at once at page->save to delete dangling meta
//
// Revision 1.151  2007/05/01 16:20:12  rurban
// MailNotify->onChangePage only on DEBUG (still broken)
//
// Revision 1.150  2007/03/18 17:35:27  rurban
// Improve comments
//
// Revision 1.149  2007/02/17 14:16:37  rurban
// isWikiPage no error on empty pagenames. MailNotify->onChangePage fix by ??
//
// Revision 1.148  2007/01/27 21:53:03  rurban
// Use TEMP_DIR for debug sql.log
//
// Revision 1.147  2007/01/04 16:41:41  rurban
// Some pageiterators also set ['pagedata']['linkrelation'], hmm
//
// Revision 1.146  2007/01/02 13:20:00  rurban
// rewrote listRelations. added linkSearch. force new date in renamePage. fix fortune error handling. added page->setAttributes. use translated initial owner. Clarify API: sortby,limit and exclude are strings. Enhance documentation.
//
// Revision 1.145  2006/12/22 17:59:55  rurban
// Move mailer functions into seperate MailNotify.php
//
// Revision 1.144  2006/10/12 06:36:09  rurban
// Guard against unwanted DEBUG="DEBUG" logic. In detail (WikiDB),
// and generally by forcing all int constants to be defined as int.
//
// Revision 1.143  2006/09/06 05:46:40  rurban
// do db backend check on _DEBUG_SQL
//
// Revision 1.142  2006/06/10 11:55:58  rurban
// print optimize only when DEBUG
//
// Revision 1.141  2006/04/17 17:28:21  rurban
// honor getWikiPageLinks change linkto=>relation
//
// Revision 1.140  2006/03/19 14:23:51  rurban
// sf.net patch #1377011 by Matt Brown: add DATABASE_OPTIMISE_FREQUENCY
//
// Revision 1.139  2006/01/12 16:38:07  rurban
// add page method listRelations()
// fix bug #1327912 numeric pagenames can break plugins (Joachim Lous)
//
// Revision 1.138  2005/11/14 22:27:07  rurban
// add linkrelation support
//   getPageLinks returns now an array of hashes
// pass stoplist through iterator
//
// Revision 1.137  2005/10/12 06:16:18  rurban
// better From header
//
// Revision 1.136  2005/10/03 16:14:57  rurban
// improve description
//
// Revision 1.135  2005/09/11 14:19:44  rurban
// enable LIMIT support for fulltext search
//
// Revision 1.134  2005/09/10 21:28:10  rurban
// applyFilters hack to use filters after methods, which do not support them (titleSearch)
//
// Revision 1.133  2005/08/27 09:39:10  rurban
// dumphtml when not at admin page: dump the current or given page
//
// Revision 1.132  2005/08/07 10:10:07  rurban
// clean whole version cache
//
// Revision 1.131  2005/04/23 11:30:12  rurban
// allow emtpy WikiDB::getRevisionBefore(), for simplier templates (revert)
//
// Revision 1.130  2005/04/06 06:19:30  rurban
// Revert the previous wrong bugfix #1175761: USECACHE was mixed with WIKIDB_NOCACHE_MARKUP.
// Fix WIKIDB_NOCACHE_MARKUP in main (always set it) and clarify it in WikiDB
//
// Revision 1.129  2005/04/06 05:50:29  rurban
// honor !USECACHE for _cached_html, fixes #1175761
//
// Revision 1.128  2005/04/01 16:11:42  rurban
// just whitespace
//
// Revision 1.127  2005/02/18 20:43:40  uckelman
// WikiDB::genericWarnings() is no longer used.
//
// Revision 1.126  2005/02/04 17:58:06  rurban
// minor versioncache improvement. part 2/3 of Charles Corrigan cache patch. not sure about the 0/1 issue
//
// Revision 1.125  2005/02/03 05:08:39  rurban
// ref fix by Charles Corrigan
//
// Revision 1.124  2005/01/29 20:43:32  rurban
// protect against empty request: on some occasion this happens
//
// Revision 1.123  2005/01/25 06:58:21  rurban
// reformatting
//
// Revision 1.122  2005/01/20 10:18:17  rurban
// reformatting
//
// Revision 1.121  2005/01/04 20:25:01  rurban
// remove old [%pagedata][_cached_html] code
//
// Revision 1.120  2004/12/23 14:12:31  rurban
// dont email on unittest
//
// Revision 1.119  2004/12/20 16:05:00  rurban
// gettext msg unification
//
// Revision 1.118  2004/12/13 13:22:57  rurban
// new BlogArchives plugin for the new blog theme. enable default box method
// for all plugins. Minor search improvement.
//
// Revision 1.117  2004/12/13 08:15:09  rurban
// false is wrong. null might be better but lets play safe.
//
// Revision 1.116  2004/12/10 22:15:00  rurban
// fix $page->get('_cached_html)
// refactor upgrade db helper _convert_cached_html() to be able to call them from WikiAdminUtils also.
// support 2nd genericSqlQuery param (bind huge arg)
//
// Revision 1.115  2004/12/10 02:45:27  rurban
// SQL optimization:
//   put _cached_html from pagedata into a new seperate blob, not huge serialized string.
//   it is only rarelely needed: for current page only, if-not-modified
//   but was extracted for every simple page iteration.
//
// Revision 1.114  2004/12/09 22:24:44  rurban
// optimize on _DEBUG_SQL only. but now again on every 50th request, not just save.
//
// Revision 1.113  2004/12/06 19:49:55  rurban
// enable action=remove which is undoable and seeable in RecentChanges: ADODB ony for now.
// renamed delete_page to purge_page.
// enable action=edit&version=-1 to force creation of a new version.
// added BABYCART_PATH config
// fixed magiqc in adodb.inc.php
// and some more docs
//
// Revision 1.112  2004/11/30 17:45:53  rurban
// exists_links backend implementation
//
// Revision 1.111  2004/11/28 20:39:43  rurban
// deactivate pagecache overwrite: it is wrong
//
// Revision 1.110  2004/11/26 18:39:01  rurban
// new regex search parser and SQL backends (90% complete, glob and pcre backends missing)
//
// Revision 1.109  2004/11/25 17:20:50  rurban
// and again a couple of more native db args: backlinks
//
// Revision 1.108  2004/11/23 13:35:31  rurban
// add case_exact search
//
// Revision 1.107  2004/11/21 11:59:16  rurban
// remove final \n to be ob_cache independent
//
// Revision 1.106  2004/11/20 17:35:56  rurban
// improved WantedPages SQL backends
// PageList::sortby new 3rd arg valid_fields (override db fields)
// WantedPages sql pager inexact for performance reasons:
//   assume 3 wantedfrom per page, to be correct, no getTotal()
// support exclude argument for get_all_pages, new _sql_set()
//
// Revision 1.105  2004/11/20 09:16:27  rurban
// Fix bad-style Cut&Paste programming errors, detected by Charles Corrigan.
//
// Revision 1.104  2004/11/19 19:22:03  rurban
// ModeratePage part1: change status
//
// Revision 1.103  2004/11/16 17:29:04  rurban
// fix remove notification error
// fix creation + update id_cache update
//
// Revision 1.102  2004/11/11 18:31:26  rurban
// add simple backtrace on such general failures to get at least an idea where
//
// Revision 1.101  2004/11/10 19:32:22  rurban
// * optimize increaseHitCount, esp. for mysql.
// * prepend dirs to the include_path (phpwiki_dir for faster searches)
// * Pear_DB version logic (awful but needed)
// * fix broken ADODB quote
// * _extract_page_data simplification
//
// Revision 1.100  2004/11/10 15:29:20  rurban
// * requires newer Pear_DB (as the internal one): quote() uses now escapeSimple for strings
// * ACCESS_LOG_SQL: fix cause request not yet initialized
// * WikiDB: moved SQL specific methods upwards
// * new Pear_DB quoting: same as ADODB and as newer Pear_DB.
//   fixes all around: WikiGroup, WikiUserNew SQL methods, SQL logging
//
// Revision 1.99  2004/11/09 17:11:05  rurban
// * revert to the wikidb ref passing. there's no memory abuse there.
// * use new wikidb->_cache->_id_cache[] instead of wikidb->_iwpcache, to effectively
//   store page ids with getPageLinks (GleanDescription) of all existing pages, which
//   are also needed at the rendering for linkExistingWikiWord().
//   pass options to pageiterator.
//   use this cache also for _get_pageid()
//   This saves about 8 SELECT count per page (num all pagelinks).
// * fix passing of all page fields to the pageiterator.
// * fix overlarge session data which got broken with the latest ACCESS_LOG_SQL changes
//
// Revision 1.98  2004/11/07 18:34:29  rurban
// more logging fixes
//
// Revision 1.97  2004/11/07 16:02:51  rurban
// new sql access log (for spam prevention), and restructured access log class
// dbh->quote (generic)
// pear_db: mysql specific parts seperated (using replace)
//
// Revision 1.96  2004/11/05 22:32:15  rurban
// encode the subject to be 7-bit safe
//
// Revision 1.95  2004/11/05 20:53:35  rurban
// login cleanup: better debug msg on failing login,
// checked password less immediate login (bogo or anon),
// checked olduser pref session error,
// better PersonalPage without password warning on minimal password length=0
//   (which is default now)
//
// Revision 1.94  2004/11/01 10:43:56  rurban
// seperate PassUser methods into seperate dir (memory usage)
// fix WikiUser (old) overlarge data session
// remove wikidb arg from various page class methods, use global ->_dbi instead
// ...
//
// Revision 1.93  2004/10/14 17:17:57  rurban
// remove dbi WikiDB_Page param: use global request object instead. (memory)
// allow most_popular sortby arguments
//
// Revision 1.92  2004/10/05 17:00:04  rurban
// support paging for simple lists
// fix RatingDb sql backend.
// remove pages from AllPages (this is ListPages then)
//
// Revision 1.91  2004/10/04 23:41:19  rurban
// delete notify: fix, @unset syntax error
//
// Revision 1.90  2004/09/28 12:50:22  rurban
// https://sourceforge.net/forum/forum.php?thread_id=1150924&forum_id=18929
//
// Revision 1.89  2004/09/26 10:54:42  rurban
// silence deferred check
//
// Revision 1.88  2004/09/25 18:16:40  rurban
// unset more unneeded _cached_html. (Guess this should fix sf.net now)
//
// Revision 1.87  2004/09/25 16:25:40  rurban
// notify on rename and remove (to be improved)
//
// Revision 1.86  2004/09/23 18:52:06  rurban
// only fortune at create
//
// Revision 1.85  2004/09/16 08:00:51  rurban
// just some comments
//
// Revision 1.84  2004/09/14 10:34:30  rurban
// fix TransformedText call to use refs
//
// Revision 1.83  2004/09/08 13:38:00  rurban
// improve loadfile stability by using markup=2 as default for undefined markup-style.
// use more refs for huge objects.
// fix debug=static issue in WikiPluginCached
//
// Revision 1.82  2004/09/06 12:08:49  rurban
// memory_limit on unix workaround
// VisualWiki: default autosize image
//
// Revision 1.81  2004/09/06 08:28:00  rurban
// rename genericQuery to genericSqlQuery
//
// Revision 1.80  2004/07/09 13:05:34  rurban
// just aesthetics
//
// Revision 1.79  2004/07/09 10:06:49  rurban
// Use backend specific sortby and sortable_columns method, to be able to
// select between native (Db backend) and custom (PageList) sorting.
// Fixed PageList::AddPageList (missed the first)
// Added the author/creator.. name to AllPagesBy...
//   display no pages if none matched.
// Improved dba and file sortby().
// Use &$request reference
//
// Revision 1.78  2004/07/08 21:32:35  rurban
// Prevent from more warnings, minor db and sort optimizations
//
// Revision 1.77  2004/07/08 19:04:42  rurban
// more unittest fixes (file backend, metadata RatingsDb)
//
// Revision 1.76  2004/07/08 17:31:43  rurban
// improve numPages for file (fixing AllPagesTest)
//
// Revision 1.75  2004/07/05 13:56:22  rurban
// sqlite autoincrement fix
//
// Revision 1.74  2004/07/03 16:51:05  rurban
// optional DBADMIN_USER:DBADMIN_PASSWD for action=upgrade (if no ALTER permission)
// added atomic mysql REPLACE for PearDB as in ADODB
// fixed _lock_tables typo links => link
// fixes unserialize ADODB bug in line 180
//
// Revision 1.73  2004/06/29 08:52:22  rurban
// Use ...version() $need_content argument in WikiDB also:
// To reduce the memory footprint for larger sets of pagelists,
// we don't cache the content (only true or false) and
// we purge the pagedata (_cached_html) also.
// _cached_html is only cached for the current pagename.
// => Vastly improved page existance check, ACL check, ...
//
// Now only PagedList info=content or size needs the whole content, esp. if sortable.
//
// Revision 1.72  2004/06/25 14:15:08  rurban
// reduce memory footprint by caching only requested pagedate content (improving most page iterators)
//
// Revision 1.71  2004/06/21 16:22:30  rurban
// add DEFAULT_DUMP_DIR and HTML_DUMP_DIR constants, for easier cmdline dumps,
// fixed dumping buttons locally (images/buttons/),
// support pages arg for dumphtml,
// optional directory arg for dumpserial + dumphtml,
// fix a AllPages warning,
// show dump warnings/errors on DEBUG,
// don't warn just ignore on wikilens pagelist columns, if not loaded.
// RateIt pagelist column is called "rating", not "ratingwidget" (Dan?)
//
// Revision 1.70  2004/06/18 14:39:31  rurban
// actually check USECACHE
//
// Revision 1.69  2004/06/13 15:33:20  rurban
// new support for arguments owner, author, creator in most relevant
// PageList plugins. in WikiAdmin* via preSelectS()
//
// Revision 1.68  2004/06/08 21:03:20  rurban
// updated RssParser for XmlParser quirks (store parser object params in globals)
//
// Revision 1.67  2004/06/07 19:12:49  rurban
// fixed rename version=0, bug #966284
//
// Revision 1.66  2004/06/07 18:57:27  rurban
// fix rename: Change pagename in all linked pages
//
// Revision 1.65  2004/06/04 20:32:53  rurban
// Several locale related improvements suggested by Pierrick Meignen
// LDAP fix by John Cole
// reanable admin check without ENABLE_PAGEPERM in the admin plugins
//
// Revision 1.64  2004/06/04 16:50:00  rurban
// add random quotes to empty pages
//
// Revision 1.63  2004/06/04 11:58:38  rurban
// added USE_TAGLINES
//
// Revision 1.62  2004/06/03 22:24:41  rurban
// reenable admin check on !ENABLE_PAGEPERM, honor s=Wildcard arg, fix warning after Remove
//
// Revision 1.61  2004/06/02 17:13:48  rurban
// fix getRevisionBefore assertion
//
// Revision 1.60  2004/05/28 10:09:58  rurban
// fix bug #962117, incorrect init of auth_dsn
//
// Revision 1.59  2004/05/27 17:49:05  rurban
// renamed DB_Session to DbSession (in CVS also)
// added WikiDB->getParam and WikiDB->getAuthParam method to get rid of globals
// remove leading slash in error message
// added force_unlock parameter to File_Passwd (no return on stale locks)
// fixed adodb session AffectedRows
// added FileFinder helpers to unify local filenames and DATA_PATH names
// editpage.php: new edit toolbar javascript on ENABLE_EDIT_TOOLBAR
//
// Revision 1.58  2004/05/18 13:59:14  rurban
// rename simpleQuery to genericQuery
//
// Revision 1.57  2004/05/16 22:07:35  rurban
// check more config-default and predefined constants
// various PagePerm fixes:
//   fix default PagePerms, esp. edit and view for Bogo and Password users
//   implemented Creator and Owner
//   BOGOUSERS renamed to BOGOUSER
// fixed syntax errors in signin.tmpl
//
// Revision 1.56  2004/05/15 22:54:49  rurban
// fixed important WikiDB bug with DEBUG > 0: wrong assertion
// improved SetAcl (works) and PagePerms, some WikiGroup helpers.
//
// Revision 1.55  2004/05/12 19:27:47  rurban
// revert wrong inline optimization.
//
// Revision 1.54  2004/05/12 10:49:55  rurban
// require_once fix for those libs which are loaded before FileFinder and
//   its automatic include_path fix, and where require_once doesn't grok
//   dirname(__FILE__) != './lib'
// upgrade fix with PearDB
// navbar.tmpl: remove spaces for IE &nbsp; button alignment
//
// Revision 1.53  2004/05/08 14:06:12  rurban
// new support for inlined image attributes: [image.jpg size=50x30 align=right]
// minor stability and portability fixes
//
// Revision 1.52  2004/05/06 19:26:16  rurban
// improve stability, trying to find the InlineParser endless loop on sf.net
//
// remove end-of-zip comments to fix sf.net bug #777278 and probably #859628
//
// Revision 1.51  2004/05/06 17:30:37  rurban
// CategoryGroup: oops, dos2unix eol
// improved phpwiki_version:
//   pre -= .0001 (1.3.10pre: 1030.099)
//   -p1 += .001 (1.3.9-p1: 1030.091)
// improved InstallTable for mysql and generic SQL versions and all newer tables so far.
// abstracted more ADODB/PearDB methods for action=upgrade stuff:
//   backend->backendType(), backend->database(),
//   backend->listOfFields(),
//   backend->listOfTables(),
//
// Revision 1.50  2004/05/04 22:34:25  rurban
// more pdf support
//
// Revision 1.49  2004/05/03 11:16:40  rurban
// fixed sendPageChangeNotification
// subject rewording
//
// Revision 1.48  2004/04/29 23:03:54  rurban
// fixed sf.net bug #940996
//
// Revision 1.47  2004/04/29 19:39:44  rurban
// special support for formatted plugins (one-liners)
//   like <small><plugin BlaBla ></small>
// iter->asArray() helper for PopularNearby
// db_session for older php's (no &func() allowed)
//
// Revision 1.46  2004/04/26 20:44:34  rurban
// locking table specific for better databases
//
// Revision 1.45  2004/04/20 00:06:03  rurban
// themable paging support
//
// Revision 1.44  2004/04/19 18:27:45  rurban
// Prevent from some PHP5 warnings (ref args, no :: object init)
//   php5 runs now through, just one wrong XmlElement object init missing
// Removed unneccesary UpgradeUser lines
// Changed WikiLink to omit version if current (RecentChanges)
//
// Revision 1.43  2004/04/18 01:34:20  rurban
// protect most_popular from sortby=mtime
//
// Revision 1.42  2004/04/18 01:11:51  rurban
// more numeric pagename fixes.
// fixed action=upload with merge conflict warnings.
// charset changed from constant to global (dynamic utf-8 switching)
//

// Local Variables:
// mode: php
// tab-width: 8
// c-basic-offset: 4
// c-hanging-comment-ender-p: nil
// indent-tabs-mode: nil
// End:   
?>