File: class.t3lib_befunc.php

package info (click to toggle)
typo3-src 4.0.2%2Bdebian-3
  • links: PTS
  • area: main
  • in suites: etch-m68k
  • size: 29,856 kB
  • ctags: 33,382
  • sloc: php: 134,523; xml: 6,976; sql: 1,084; sh: 168; makefile: 45
file content (3610 lines) | stat: -rw-r--r-- 143,195 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
3310
3311
3312
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
3370
3371
3372
3373
3374
3375
3376
3377
3378
3379
3380
3381
3382
3383
3384
3385
3386
3387
3388
3389
3390
3391
3392
3393
3394
3395
3396
3397
3398
3399
3400
3401
3402
3403
3404
3405
3406
3407
3408
3409
3410
3411
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
3478
3479
3480
3481
3482
3483
3484
3485
3486
3487
3488
3489
3490
3491
3492
3493
3494
3495
3496
3497
3498
3499
3500
3501
3502
3503
3504
3505
3506
3507
3508
3509
3510
3511
3512
3513
3514
3515
3516
3517
3518
3519
3520
3521
3522
3523
3524
3525
3526
3527
3528
3529
3530
3531
3532
3533
3534
3535
3536
3537
3538
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
3562
3563
3564
3565
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
<?php
/***************************************************************
*  Copyright notice
*
*  (c) 1999-2006 Kasper Skaarhoj (kasperYYYY@typo3.com)
*  All rights reserved
*
*  This script is part of the TYPO3 project. The TYPO3 project is
*  free software; you can redistribute it and/or modify
*  it under the terms of the GNU General Public License as published by
*  the Free Software Foundation; either version 2 of the License, or
*  (at your option) any later version.
*
*  The GNU General Public License can be found at
*  http://www.gnu.org/copyleft/gpl.html.
*  A copy is found in the textfile GPL.txt and important notices to the license
*  from the author is found in LICENSE.txt distributed with these scripts.
*
*
*  This script is distributed in the hope that it will be useful,
*  but WITHOUT ANY WARRANTY; without even the implied warranty of
*  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
*  GNU General Public License for more details.
*
*  This copyright notice MUST APPEAR in all copies of the script!
***************************************************************/
/**
 * Standard functions available for the TYPO3 backend.
 * You are encouraged to use this class in your own applications (Backend Modules)
 *
 * Call ALL methods without making an object!
 * Eg. to get a page-record 51 do this: 't3lib_BEfunc::getRecord('pages',51)'
 *
 * $Id: class.t3lib_befunc.php 1704 2006-08-31 10:52:20Z baschny $
 * Usage counts are based on search 22/2 2003 through whole backend source of typo3/
 * Revised for TYPO3 3.6 July/2003 by Kasper Skaarhoj
 * XHTML compliant
 *
 * @author	Kasper Skaarhoj <kasperYYYY@typo3.com>
 */
/**
 * [CLASS/FUNCTION INDEX of SCRIPT]
 *
 *
 *
 *  183: class t3lib_BEfunc
 *
 *              SECTION: SQL-related, selecting records, searching
 *  204:     function deleteClause($table,$tableAlias='')
 *  227:     function getRecord($table,$uid,$fields='*',$where='')
 *  245:     function getRecordWSOL($table,$uid,$fields='*',$where='')
 *  278:     function getRecordRaw($table,$where='',$fields='*')
 *  300:     function getRecordsByField($theTable,$theField,$theValue,$whereClause='',$groupBy='',$orderBy='',$limit='')
 *  333:     function searchQuery($searchWords,$fields,$table='')
 *  348:     function listQuery($field,$value)
 *  360:     function splitTable_Uid($str)
 *  375:     function getSQLselectableList($in_list,$tablename,$default_tablename)
 *  403:     function BEenableFields($table,$inv=0)
 *
 *              SECTION: SQL-related, DEPRECATED functions
 *  467:     function mm_query($select,$local_table,$mm_table,$foreign_table,$whereClause='',$groupBy='',$orderBy='',$limit='')
 *  489:     function DBcompileInsert($table,$fields_values)
 *  503:     function DBcompileUpdate($table,$where,$fields_values)
 *
 *              SECTION: Page tree, TCA related
 *  533:     function BEgetRootLine($uid,$clause='',$workspaceOL=FALSE)
 *  589:     function openPageTree($pid,$clearExpansion)
 *  634:     function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit=0)
 *  677:     function getExcludeFields()
 *  707:     function getExplicitAuthFieldValues()
 *  778:     function getSystemLanguages()
 *  803:     function readPageAccess($id,$perms_clause)
 *  834:     function getTCAtypes($table,$rec,$useFieldNameAsKey=0)
 *  887:     function getTCAtypeValue($table,$rec)
 *  910:     function getSpecConfParts($str, $defaultExtras)
 *  941:     function getSpecConfParametersFromArray($pArr)
 *  969:     function getFlexFormDS($conf,$row,$table,$fieldName='',$WSOL=TRUE)
 *
 *              SECTION: Caching related
 * 1096:     function storeHash($hash,$data,$ident)
 * 1116:     function getHash($hash,$expTime=0)
 *
 *              SECTION: TypoScript related
 * 1152:     function getPagesTSconfig($id,$rootLine='',$returnPartArray=0)
 * 1208:     function updatePagesTSconfig($id,$pageTS,$TSconfPrefix,$impParams='')
 * 1263:     function implodeTSParams($p,$k='')
 *
 *              SECTION: Users / Groups related
 * 1300:     function getUserNames($fields='username,usergroup,usergroup_cached_list,uid',$where='')
 * 1318:     function getGroupNames($fields='title,uid', $where='')
 * 1335:     function getListGroupNames($fields='title,uid')
 * 1354:     function blindUserNames($usernames,$groupArray,$excludeBlindedFlag=0)
 * 1387:     function blindGroupNames($groups,$groupArray,$excludeBlindedFlag=0)
 *
 *              SECTION: Output related
 * 1428:     function daysUntil($tstamp)
 * 1440:     function date($tstamp)
 * 1451:     function datetime($value)
 * 1463:     function time($value)
 * 1479:     function calcAge($seconds,$labels = 'min|hrs|days|yrs')
 * 1505:     function dateTimeAge($tstamp,$prefix=1,$date='')
 * 1523:     function titleAttrib($content='',$hsc=0)
 * 1536:     function titleAltAttrib($content)
 * 1560:     function thumbCode($row,$table,$field,$backPath,$thumbScript='',$uploaddir=NULL,$abs=0,$tparams='',$size='')
 * 1628:     function getThumbNail($thumbScript,$theFile,$tparams='',$size='')
 * 1645:     function titleAttribForPages($row,$perms_clause='',$includeAttrib=1)
 * 1707:     function getRecordIconAltText($row,$table='pages')
 * 1749:     function getLabelFromItemlist($table,$col,$key)
 * 1775:     function getItemLabel($table,$col,$printAllWrap='')
 * 1800:     function getRecordTitle($table,$row,$prep=0)
 * 1838:     function getProcessedValue($table,$col,$value,$fixed_lgd_chars=0,$defaultPassthrough=0,$noRecordLookup=FALSE,$uid=0)
 * 1989:     function getProcessedValueExtra($table,$fN,$fV,$fixed_lgd_chars=0,$uid=0)
 * 2013:     function getFileIcon($ext)
 * 2027:     function getCommonSelectFields($table,$prefix='')
 * 2070:     function makeConfigForm($configArray,$defaults,$dataPrefix)
 *
 *              SECTION: Backend Modules API functions
 * 2145:     function helpTextIcon($table,$field,$BACK_PATH,$force=0)
 * 2167:     function helpText($table,$field,$BACK_PATH,$styleAttrib='')
 * 2219:     function cshItem($table,$field,$BACK_PATH,$wrap='',$onlyIconMode=FALSE, $styleAttrib='')
 * 2257:     function editOnClick($params,$backPath='',$requestUri='')
 * 2276:     function viewOnClick($id,$backPath='',$rootLine='',$anchor='',$altUrl='',$addGetVars='',$switchFocus=TRUE)
 * 2308:     function getModTSconfig($id,$TSref)
 * 2329:     function getFuncMenu($mainParams,$elementName,$currentValue,$menuItems,$script='',$addparams='')
 * 2372:     function getFuncCheck($mainParams,$elementName,$currentValue,$script='',$addparams='',$tagParams='')
 * 2397:     function getFuncInput($mainParams,$elementName,$currentValue,$size=10,$script="",$addparams="")
 * 2418:     function unsetMenuItems($modTSconfig,$itemArray,$TSref)
 * 2441:     function getSetUpdateSignal($set='')
 * 2492:     function getModuleData($MOD_MENU, $CHANGED_SETTINGS, $modName, $type='', $dontValidateList='', $setDefaultList='')
 *
 *              SECTION: Core
 * 2565:     function compilePreviewKeyword($getVarsStr, $beUserUid, $ttl=172800)
 * 2593:     function lockRecords($table='',$uid=0,$pid=0)
 * 2622:     function isRecordLocked($table,$uid)
 * 2662:     function exec_foreign_table_where_query($fieldValue,$field='',$TSconfig=array(),$prefix='')
 * 2743:     function getTCEFORM_TSconfig($table,$row)
 * 2794:     function getTSconfig_pidValue($table,$uid,$pid)
 * 2824:     function getPidForModTSconfig($table,$uid,$pid)
 * 2840:     function getTSCpid($table,$uid,$pid)
 * 2856:     function firstDomainRecord($rootLine)
 * 2878:     function getDomainStartPage($domain, $path='')
 * 2908:     function RTEsetup($RTEprop,$table,$field,$type='')
 * 2927:     function &RTEgetObj()
 * 2966:     function &softRefParserObj($spKey)
 * 2998:     function explodeSoftRefParserList($parserList)
 * 3030:     function isModuleSetInTBE_MODULES($modName)
 * 3053:     function referenceCount($table,$ref,$msg='')
 *
 *              SECTION: Workspaces / Versioning
 * 3112:     function selectVersionsOfRecord($table, $uid, $fields='*', $workspace=0)
 * 3160:     function fixVersioningPid($table,&$rr,$ignoreWorkspaceMatch=FALSE)
 * 3200:     function workspaceOL($table,&$row,$wsid=-99)
 * 3248:     function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields='*')
 * 3277:     function getLiveVersionOfRecord($table,$uid,$fields='*')
 * 3299:     function isPidInVersionizedBranch($pid, $table='',$returnStage=FALSE)
 * 3322:     function versioningPlaceholderClause($table)
 * 3336:     function countVersionsOfRecordsOnPage($workspace,$pageId, $allTables=FALSE)
 * 3371:     function wsMapId($table,$uid)
 *
 *              SECTION: Miscellaneous
 * 3401:     function typo3PrintError($header,$text,$js='',$head=1)
 * 3445:     function TYPO3_copyRightNotice()
 * 3469:     function displayWarningMessages()
 * 3526:     function getPathType_web_nonweb($path)
 * 3538:     function ADMCMD_previewCmds($pageinfo)
 * 3560:     function processParams($params)
 * 3586:     function getListOfBackendModules($name,$perms_clause,$backPath='',$script='index.php')
 *
 * TOTAL FUNCTIONS: 99
 * (This index is automatically created/updated by the extension "extdeveval")
 *
 */


/**
 * Standard functions available for the TYPO3 backend.
 * Don't instantiate - call functions with "t3lib_BEfunc::" prefixed the function name.
 *
 * @author	Kasper Skaarhoj <kasperYYYY@typo3.com>
 * @package TYPO3
 * @subpackage t3lib
 */
class t3lib_BEfunc	{



	/*******************************************
	 *
	 * SQL-related, selecting records, searching
	 *
	 *******************************************/


	/**
	 * Returns the WHERE clause " AND NOT [tablename].[deleted-field]" if a deleted-field is configured in $TCA for the tablename, $table
	 * This function should ALWAYS be called in the backend for selection on tables which are configured in TCA since it will ensure consistent selection of records, even if they are marked deleted (in which case the system must always treat them as non-existent!)
	 * In the frontend a function, ->enableFields(), is known to filter hidden-field, start- and endtime and fe_groups as well. But that is a job of the frontend, not the backend. If you need filtering on those fields as well in the backend you can use ->BEenableFields() though.
	 * Usage: 71
	 *
	 * @param	string		Table name present in $TCA
	 * @param	string		Table alias if any
	 * @return	string		WHERE clause for filtering out deleted records, eg " AND tablename.deleted=0"
	 */
	function deleteClause($table,$tableAlias='')	{
		global $TCA;
		if ($TCA[$table]['ctrl']['delete'])	{
			return ' AND '.($tableAlias ? $tableAlias : $table).'.'.$TCA[$table]['ctrl']['delete'].'=0';
		} else {
			return '';
		}
	}

	/**
	 * Gets record with uid=$uid from $table
	 * You can set $field to a list of fields (default is '*')
	 * Additional WHERE clauses can be added by $where (fx. ' AND blabla=1')
	 * Will automatically check if records has been deleted and if so, not return anything.
	 * $table must be found in $TCA
	 * Usage: 99
	 *
	 * @param	string		Table name present in $TCA
	 * @param	integer		UID of record
	 * @param	string		List of fields to select
	 * @param	string		Additional WHERE clause, eg. " AND blablabla=0"
	 * @return	array		Returns the row if found, otherwise nothing
	 */
	function getRecord($table,$uid,$fields='*',$where='')	{
		if ($GLOBALS['TCA'][$table])	{
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, $table, 'uid='.intval($uid).t3lib_BEfunc::deleteClause($table).$where);
			if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))	{
				return $row;
			}
		}
	}

	/**
	 * Like getRecord(), but overlays workspace version if any.
	 *
	 * @param	string		Table name present in $TCA
	 * @param	integer		UID of record
	 * @param	string		List of fields to select
	 * @param	string		Additional WHERE clause, eg. " AND blablabla=0"
	 * @return	array		Returns the row if found, otherwise nothing
	 */
	function getRecordWSOL($table,$uid,$fields='*',$where='') {
		if ($fields !== '*') {
			$internalFields = t3lib_div::uniqueList($fields.',uid,pid'.($table == 'pages' ? ',t3ver_swapmode' : ''));
			$row = t3lib_BEfunc::getRecord($table,$uid,$internalFields,$where);
			t3lib_BEfunc::workspaceOL($table,$row);

			if (is_array ($row)) {
				foreach (array_keys($row) as $key) {
					if (!t3lib_div::inList($fields, $key) && $key{0} !== '_') {
						unset ($row[$key]);
					}
				}
			}
		} else {
			$row = t3lib_BEfunc::getRecord($table,$uid,$fields,$where);
			t3lib_BEfunc::workspaceOL($table,$row);
		}
		return $row;
	}

	/**
	 * Returns the first record found from $table with $where as WHERE clause
	 * This function does NOT check if a record has the deleted flag set.
	 * $table does NOT need to be configured in $TCA
	 * The query used is simply this:
	 * $query='SELECT '.$fields.' FROM '.$table.' WHERE '.$where;
	 * Usage: 5 (ext: sys_todos)
	 *
	 * @param	string		Table name (not necessarily in TCA)
	 * @param	string		WHERE clause
	 * @param	string		$fields is a list of fields to select, default is '*'
	 * @return	array		First row found, if any
	 */
	function getRecordRaw($table,$where='',$fields='*')	{
		$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, $table, $where);
		if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))	{
			return $row;
		}
	}

	/**
	 * Returns records from table, $theTable, where a field ($theField) equals the value, $theValue
	 * The records are returned in an array
	 * If no records were selected, the function returns nothing
	 * Usage: 8
	 *
	 * @param	string		Table name present in $TCA
	 * @param	string		Field to select on
	 * @param	string		Value that $theField must match
	 * @param	string		Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
	 * @param	string		Optional GROUP BY field(s), if none, supply blank string.
	 * @param	string		Optional ORDER BY field(s), if none, supply blank string.
	 * @param	string		Optional LIMIT value ([begin,]max), if none, supply blank string.
	 * @return	mixed		Multidimensional array with selected records (if any is selected)
	 */
	function getRecordsByField($theTable,$theField,$theValue,$whereClause='',$groupBy='',$orderBy='',$limit='')	{
		global $TCA;
		if (is_array($TCA[$theTable])) {
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
						'*',
						$theTable,
						$theField.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($theValue, $theTable).
							t3lib_BEfunc::deleteClause($theTable).' '.
							t3lib_BEfunc::versioningPlaceholderClause($theTable).' '.
							$whereClause,	// whereClauseMightContainGroupOrderBy
						$groupBy,
						$orderBy,
						$limit
					);
			$rows = array();
			while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))	{
				$rows[] = $row;
			}
			$GLOBALS['TYPO3_DB']->sql_free_result($res);
			if (count($rows))	return $rows;
		}
	}

	/**
	 * Returns a WHERE clause which will make an AND search for the words in the $searchWords array in any of the fields in array $fields.
	 * Usage: 0
	 *
	 * @param	array		Array of search words
	 * @param	array		Array of fields
	 * @param	string		Table in which we are searching (for DBAL detection of quoteStr() method)
	 * @return	string		WHERE clause for search
	 * @deprecated		Use $GLOBALS['TYPO3_DB']->searchQuery() directly!
	 */
	function searchQuery($searchWords,$fields,$table='')	{
		return $GLOBALS['TYPO3_DB']->searchQuery($searchWords,$fields,$table);
	}

	/**
	 * Returns a WHERE clause that can find a value ($value) in a list field ($field)
	 * For instance a record in the database might contain a list of numbers, "34,234,5" (with no spaces between). This query would be able to select that record based on the value "34", "234" or "5" regardless of their positioni in the list (left, middle or right).
	 * Is nice to look up list-relations to records or files in TYPO3 database tables.
	 * Usage: 0
	 *
	 * @param	string		Table field name
	 * @param	string		Value to find in list
	 * @return	string		WHERE clause for a query
	 * @deprecated		Use $GLOBALS['TYPO3_DB']->listQuery() directly!
	 */
	function listQuery($field,$value)	{
		return $GLOBALS['TYPO3_DB']->listQuery($field,$value,'');
	}

	/**
	 * Makes an backwards explode on the $str and returns an array with ($table,$uid).
	 * Example: tt_content_45	=>	array('tt_content',45)
	 * Usage: 1
	 *
	 * @param	string		[tablename]_[uid] string to explode
	 * @return	array
	 */
	function splitTable_Uid($str)	{
		list($uid,$table) = explode('_',strrev($str),2);
		return array(strrev($table),strrev($uid));
	}

	/**
	 * Returns a list of pure integers based on $in_list being a list of records with table-names prepended.
	 * Ex: $in_list = "pages_4,tt_content_12,45" would result in a return value of "4,45" if $tablename is "pages" and $default_tablename is 'pages' as well.
	 * Usage: 1 (t3lib_userauthgroup)
	 *
	 * @param	string		Input list
	 * @param	string		Table name from which ids is returned
	 * @param	string		$default_tablename denotes what table the number '45' is from (if nothing is prepended on the value)
	 * @return	string		List of ids
	 */
	function getSQLselectableList($in_list,$tablename,$default_tablename)	{
		$list = Array();
		if ((string)trim($in_list)!='')	{
			$tempItemArray = explode(',',trim($in_list));
			while(list($key,$val)=each($tempItemArray))	{
				$val = strrev($val);
				$parts = explode('_',$val,2);
				if ((string)trim($parts[0])!='')	{
					$theID = intval(strrev($parts[0]));
					$theTable = trim($parts[1]) ? strrev(trim($parts[1])) : $default_tablename;
					if ($theTable==$tablename)	{$list[]=$theID;}
				}
			}
		}
		return implode(',',$list);
	}

	/**
	 * Backend implementation of enableFields()
	 * Notice that "fe_groups" is not selected for - only disabled, starttime and endtime.
	 * Notice that deleted-fields are NOT filtered - you must ALSO call deleteClause in addition.
	 * $GLOBALS["SIM_EXEC_TIME"] is used for date.
	 * Usage: 5
	 *
	 * @param	string		$table is the table from which to return enableFields WHERE clause. Table name must have a 'ctrl' section in $TCA.
	 * @param	boolean		$inv means that the query will select all records NOT VISIBLE records (inverted selection)
	 * @return	string		WHERE clause part
	 */
	function BEenableFields($table,$inv=0)	{
		$ctrl = $GLOBALS['TCA'][$table]['ctrl'];
		$query=array();
		$invQuery=array();
		if (is_array($ctrl))	{
			if (is_array($ctrl['enablecolumns']))	{
				if ($ctrl['enablecolumns']['disabled'])	{
					$field = $table.'.'.$ctrl['enablecolumns']['disabled'];
					$query[]=$field.'=0';
					$invQuery[]=$field.'!=0';
				}
				if ($ctrl['enablecolumns']['starttime'])	{
					$field = $table.'.'.$ctrl['enablecolumns']['starttime'];
					$query[]='('.$field.'<='.$GLOBALS['SIM_EXEC_TIME'].')';
					$invQuery[]='('.$field.'!=0 AND '.$field.'>'.$GLOBALS['SIM_EXEC_TIME'].')';
				}
				if ($ctrl['enablecolumns']['endtime'])	{
					$field = $table.'.'.$ctrl['enablecolumns']['endtime'];
					$query[]='('.$field.'=0 OR '.$field.'>'.$GLOBALS['SIM_EXEC_TIME'].')';
					$invQuery[]='('.$field.'!=0 AND '.$field.'<='.$GLOBALS['SIM_EXEC_TIME'].')';
				}
			}
		}
		$outQ = ' AND '.($inv ? '('.implode(' OR ',$invQuery).')' : implode(' AND ',$query));

		return $outQ;
	}










	/*******************************************
	 *
	 * SQL-related, DEPRECATED functions
	 * (use t3lib_DB functions instead)
	 *
	 *******************************************/


	/**
	 * Returns a SELECT query, selecting fields ($select) from two/three tables joined
	 * $local_table and $mm_table is mandatory. $foreign_table is optional.
	 * The JOIN is done with [$local_table].uid <--> [$mm_table].uid_local  / [$mm_table].uid_foreign <--> [$foreign_table].uid
	 * The function is very useful for selecting MM-relations between tables adhering to the MM-format used by TCE (TYPO3 Core Engine). See the section on $TCA in Inside TYPO3 for more details.
	 * DEPRECATED - Use $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query() instead since that will return the result pointer while this returns the query. Using this function may make your application less fitted for DBAL later.
	 *
	 * @param	string		Field list for SELECT
	 * @param	string		Tablename, local table
	 * @param	string		Tablename, relation table
	 * @param	string		Tablename, foreign table
	 * @param	string		Optional additional WHERE clauses put in the end of the query. DO NOT PUT IN GROUP BY, ORDER BY or LIMIT!
	 * @param	string		Optional GROUP BY field(s), if none, supply blank string.
	 * @param	string		Optional ORDER BY field(s), if none, supply blank string.
	 * @param	string		Optional LIMIT value ([begin,]max), if none, supply blank string.
	 * @return	string		Full SQL query
	 * @deprecated
	 * @see t3lib_DB::exec_SELECT_mm_query()
	 */
	function mm_query($select,$local_table,$mm_table,$foreign_table,$whereClause='',$groupBy='',$orderBy='',$limit='')	{
		$query = $GLOBALS['TYPO3_DB']->SELECTquery(
					$select,
					$local_table.','.$mm_table.($foreign_table?','.$foreign_table:''),
					$local_table.'.uid='.$mm_table.'.uid_local'.($foreign_table?' AND '.$foreign_table.'.uid='.$mm_table.'.uid_foreign':'').' '.
						$whereClause,	// whereClauseMightContainGroupOrderBy
					$groupBy,
					$orderBy,
					$limit
				);
		return $query;
	}

	/**
	 * Creates an INSERT SQL-statement for $table from the array with field/value pairs $fields_values.
	 * DEPRECATED - $GLOBALS['TYPO3_DB']->INSERTquery() directly instead! But better yet, use $GLOBALS['TYPO3_DB']->exec_INSERTquery()
	 *
	 * @param	string		Table name
	 * @param	array		Field values as key=>value pairs.
	 * @return	string		Full SQL query for INSERT
	 * @deprecated
	 */
	function DBcompileInsert($table,$fields_values)	{
		return $GLOBALS['TYPO3_DB']->INSERTquery($table, $fields_values);
	}

	/**
	 * Creates an UPDATE SQL-statement for $table where $where-clause (typ. 'uid=...') from the array with field/value pairs $fields_values.
	 * DEPRECATED - $GLOBALS['TYPO3_DB']->UPDATEquery() directly instead! But better yet, use $GLOBALS['TYPO3_DB']->exec_UPDATEquery()
	 *
	 * @param	string		Database tablename
	 * @param	string		WHERE clause, eg. "uid=1"
	 * @param	array		Field values as key=>value pairs.
	 * @return	string		Full SQL query for UPDATE
	 * @deprecated
	 */
	function DBcompileUpdate($table,$where,$fields_values)	{
		return $GLOBALS['TYPO3_DB']->UPDATEquery($table, $where, $fields_values);
	}










	/*******************************************
	 *
	 * Page tree, TCA related
	 *
	 *******************************************/

	/**
	 * Returns what is called the 'RootLine'. That is an array with information about the page records from a page id ($uid) and back to the root.
	 * By default deleted pages are filtered.
	 * This RootLine will follow the tree all the way to the root. This is opposite to another kind of root line known from the frontend where the rootline stops when a root-template is found.
	 * Usage: 1
	 *
	 * @param	integer		Page id for which to create the root line.
	 * @param	string		$clause can be used to select other criteria. It would typically be where-clauses that stops the process if we meet a page, the user has no reading access to.
	 * @param	boolean		If true, version overlay is applied. This must be requested specifically because it is usually only wanted when the rootline is used for visual output while for permission checking you want the raw thing!
	 * @return	array		Root line array, all the way to the page tree root (or as far as $clause allows!)
	 */
	function BEgetRootLine($uid,$clause='',$workspaceOL=FALSE)	{
		$loopCheck = 100;
		$theRowArray = Array();
		$output = Array();
		while ($uid!=0 && $loopCheck>0)	{
			$loopCheck--;
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
				'pid,uid,title,TSconfig,is_siteroot,storage_pid,t3ver_oid,t3ver_wsid,t3ver_state,t3ver_swapmode,t3ver_stage',
				'pages',
				'uid='.intval($uid).' '.
					t3lib_BEfunc::deleteClause('pages').' '.
					$clause		// whereClauseMightContainGroupOrderBy
			);
			if ($GLOBALS['TYPO3_DB']->sql_error())	{
				debug($GLOBALS['TYPO3_DB']->sql_error(),1);
			}
			if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))	{
				if($workspaceOL)	t3lib_BEfunc::workspaceOL('pages',$row);
				t3lib_BEfunc::fixVersioningPid('pages',$row);
				$uid = $row['pid'];
				$theRowArray[] = $row;
			} else {
				break;
			}
		}
		if ($uid==0) {$theRowArray[] = Array('uid'=>0,'title'=>'');}
		if (is_array($theRowArray))	{
			reset($theRowArray);
			$c=count($theRowArray);
			while(list($key,$val)=each($theRowArray))	{
				$c--;
				$output[$c]['uid'] = $val['uid'];
				$output[$c]['pid'] = $val['pid'];
				if (isset($val['_ORIG_pid'])) $output[$c]['_ORIG_pid'] = $val['_ORIG_pid'];
				$output[$c]['title'] = $val['title'];
				$output[$c]['TSconfig'] = $val['TSconfig'];
				$output[$c]['is_siteroot'] = $val['is_siteroot'];
				$output[$c]['storage_pid'] = $val['storage_pid'];
				$output[$c]['t3ver_oid'] = $val['t3ver_oid'];
				$output[$c]['t3ver_wsid'] = $val['t3ver_wsid'];
				$output[$c]['t3ver_state'] = $val['t3ver_state'];
				$output[$c]['t3ver_swapmode'] = $val['t3ver_swapmode'];
				$output[$c]['t3ver_stage'] = $val['t3ver_stage'];
			}
		}

		return $output;
	}

	/**
	 * Opens the page tree to the specified page id
	 *
	 * @param	integer		Page id.
	 * @param	boolean		If set, then other open branches are closed.
	 * @return	void
	 */
	function openPageTree($pid,$clearExpansion)	{
		global $BE_USER;

			// Get current expansion data:
		if ($clearExpansion)	{
			$expandedPages = array();
		} else {
			$expandedPages = unserialize($BE_USER->uc['browseTrees']['browsePages']);
		}

			// Get rootline:
		$rL = t3lib_BEfunc::BEgetRootLine($pid);

			// First, find out what mount index to use (if more than one DB mount exists):
		$mountIndex = 0;
		$mountKeys = array_flip($BE_USER->returnWebmounts());
		foreach($rL as $rLDat)	{
			if (isset($mountKeys[$rLDat['uid']]))	{
				$mountIndex = $mountKeys[$rLDat['uid']];
				break;
			}
		}

			// Traverse rootline and open paths:
		foreach($rL as $rLDat)	{
			$expandedPages[$mountIndex][$rLDat['uid']] = 1;
		}

			// Write back:
		$BE_USER->uc['browseTrees']['browsePages'] = serialize($expandedPages);
		$BE_USER->writeUC();
	}

	/**
	 * Returns the path (visually) of a page $uid, fx. "/First page/Second page/Another subpage"
	 * Each part of the path will be limited to $titleLimit characters
	 * Deleted pages are filtered out.
	 * Usage: 15
	 *
	 * @param	integer		Page uid for which to create record path
	 * @param	string		$clause is additional where clauses, eg. "
	 * @param	integer		Title limit
	 * @param	integer		Title limit of Full title (typ. set to 1000 or so)
	 * @return	mixed		Path of record (string) OR array with short/long title if $fullTitleLimit is set.
	 */
	function getRecordPath($uid, $clause, $titleLimit, $fullTitleLimit=0)	{
		if (!$titleLimit) { $titleLimit=1000; }

		$loopCheck = 100;
		$output = $fullOutput = '/';
		while ($uid!=0 && $loopCheck>0)	{
			$loopCheck--;
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
						'uid,pid,title,t3ver_oid,t3ver_wsid,t3ver_swapmode',
						'pages',
						'uid='.intval($uid).
							t3lib_BEfunc::deleteClause('pages').
							(strlen(trim($clause)) ? ' AND '.$clause : '')
					);
			if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))	{
				t3lib_BEfunc::workspaceOL('pages',$row);
				t3lib_BEfunc::fixVersioningPid('pages',$row);

				if ($row['_ORIG_pid'] && $row['t3ver_swapmode']>0)	{	// Branch points
					$output = ' [#VEP#]'.$output;		// Adding visual token - Versioning Entry Point - that tells that THIS position was where the versionized branch got connected to the main tree. I will have to find a better name or something...
				}
				$uid = $row['pid'];
				$output = '/'.t3lib_div::fixed_lgd_cs(strip_tags($row['title']),$titleLimit).$output;
				if ($fullTitleLimit)	$fullOutput = '/'.t3lib_div::fixed_lgd_cs(strip_tags($row['title']),$fullTitleLimit).$fullOutput;
			} else {
				break;
			}
		}

		if ($fullTitleLimit)	{
			return array($output, $fullOutput);
		} else {
			return $output;
		}
	}

	/**
	 * Returns an array with the exclude-fields as defined in TCA
	 * Used for listing the exclude-fields in be_groups forms
	 * Usage: 2 (t3lib_tceforms + t3lib_transferdata)
	 *
	 * @return	array		Array of arrays with excludeFields (fieldname, table:fieldname) from all TCA entries
	 */
	function getExcludeFields()	{
		global $TCA;
			// All TCA keys:
		$theExcludeArray = Array();
		$tc_keys = array_keys($TCA);
		foreach($tc_keys as $table)	{
				// Load table
			t3lib_div::loadTCA($table);
				// All field names configured:
			if (is_array($TCA[$table]['columns']))	{
				$f_keys = array_keys($TCA[$table]['columns']);
				foreach($f_keys as $field)	{
					if ($TCA[$table]['columns'][$field]['exclude'])	{
							// Get Human Readable names of fields and table:
						$Fname=$GLOBALS['LANG']->sl($TCA[$table]['ctrl']['title']).': '.$GLOBALS['LANG']->sl($TCA[$table]['columns'][$field]['label']);
							// add entry:
						$theExcludeArray[] = Array($Fname , $table.':'.$field);
					}
				}
			}
		}
		return $theExcludeArray;
	}

	/**
	 * Returns an array with explicit Allow/Deny fields.
	 * Used for listing these field/value pairs in be_groups forms
	 *
	 * @return	array		Array with information from all of $TCA
	 */
	function getExplicitAuthFieldValues()	{
		global $TCA;

			// Initialize:
		$adLabel = array(
			'ALLOW' => $GLOBALS['LANG']->sl('LLL:EXT:lang/locallang_core.xml:labels.allow'),
			'DENY' => $GLOBALS['LANG']->sl('LLL:EXT:lang/locallang_core.xml:labels.deny'),
		);

			// All TCA keys:
		$allowDenyOptions = Array();
		$tc_keys = array_keys($TCA);
		foreach($tc_keys as $table)	{

				// Load table
			t3lib_div::loadTCA($table);

				// All field names configured:
			if (is_array($TCA[$table]['columns']))	{
				$f_keys = array_keys($TCA[$table]['columns']);
				foreach($f_keys as $field)	{
					$fCfg = $TCA[$table]['columns'][$field]['config'];
					if ($fCfg['type']=='select' && $fCfg['authMode'])	{

							// Check for items:
						if (is_array($fCfg['items']))	{
								// Get Human Readable names of fields and table:
							$allowDenyOptions[$table.':'.$field]['tableFieldLabel'] = $GLOBALS['LANG']->sl($TCA[$table]['ctrl']['title']).': '.$GLOBALS['LANG']->sl($TCA[$table]['columns'][$field]['label']);

								// Check for items:
							foreach($fCfg['items'] as $iVal)	{
								if (strcmp($iVal[1],''))	{	// Values '' is not controlled by this setting.

										// Find iMode:
									$iMode = '';
									switch((string)$fCfg['authMode'])	{
										case 'explicitAllow':
											$iMode = 'ALLOW';
										break;
										case 'explicitDeny':
											$iMode = 'DENY';
										break;
										case 'individual':
											if (!strcmp($iVal[4],'EXPL_ALLOW'))	{
												$iMode = 'ALLOW';
											} elseif (!strcmp($iVal[4],'EXPL_DENY'))	{
												$iMode = 'DENY';
											}
										break;
									}

										// Set iMode:
									if ($iMode)	{
										$allowDenyOptions[$table.':'.$field]['items'][$iVal[1]] = array($iMode, $GLOBALS['LANG']->sl($iVal[0]), $adLabel[$iMode]);
									}
								}
							}
						}
					}
				}
			}
		}

		return $allowDenyOptions;
	}

	/**
	 * Returns an array with system languages:
	 *
	 * @return	array		Array with languages
	 */
	function getSystemLanguages()	{

			// Initialize, add default language:
		$sysLanguages = array();
		$sysLanguages[] = array('Default language', 0);

			// Traverse languages
		$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,title,flag','sys_language','pid=0'.t3lib_BEfunc::deleteClause('sys_language'));
		while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))	{
			$sysLanguages[] = array($row['title'].' ['.$row['uid'].']', $row['uid'], ($row['flag'] ? 'flags/'.$row['flag'] : ''));
		}

		return $sysLanguages;
	}

	/**
	 * Returns a page record (of page with $id) with an extra field "_thePath" set to the record path IF the WHERE clause, $perms_clause, selects the record. Thus is works as an access check that returns a page record if access was granted, otherwise not.
	 * If $id is zero a pseudo root-page with "_thePath" set is returned IF the current BE_USER is admin.
	 * In any case ->isInWebMount must return true for the user (regardless of $perms_clause)
	 * Usage: 21
	 *
	 * @param	integer		Page uid for which to check read-access
	 * @param	string		$perms_clause is typically a value generated with $BE_USER->getPagePermsClause(1);
	 * @return	array		Returns page record if OK, otherwise false.
	 */
	function readPageAccess($id,$perms_clause)	{
		if ((string)$id!='')	{
			$id = intval($id);
			if (!$id)	{
				if ($GLOBALS['BE_USER']->isAdmin())	{
					$path = '/';
					$pageinfo['_thePath'] = $path;
					return $pageinfo;
				}
			} else {
				$pageinfo = t3lib_BEfunc::getRecord('pages',$id,'*',($perms_clause ? ' AND '.$perms_clause : ''));
				if ($pageinfo['uid'] && $GLOBALS['BE_USER']->isInWebMount($id,$perms_clause))	{
					t3lib_BEfunc::workspaceOL('pages', $pageinfo);
					t3lib_BEfunc::fixVersioningPid('pages', $pageinfo);
					list($pageinfo['_thePath'],$pageinfo['_thePathFull']) = t3lib_BEfunc::getRecordPath(intval($pageinfo['uid']), $perms_clause, 15, 1000);
					return $pageinfo;
				}
			}
		}
		return false;
	}

	/**
	 * Returns the "types" configuration parsed into an array for the record, $rec, from table, $table
	 * Usage: 6
	 *
	 * @param	string		Table name (present in TCA)
	 * @param	array		Record from $table
	 * @param	boolean		If $useFieldNameAsKey is set, then the fieldname is associative keys in the return array, otherwise just numeric keys.
	 * @return	array
	 */
	function getTCAtypes($table,$rec,$useFieldNameAsKey=0)	{
		global $TCA;

		t3lib_div::loadTCA($table);
		if ($TCA[$table])	{

				// Get type value:
			$fieldValue = t3lib_BEfunc::getTCAtypeValue($table,$rec);

				// Get typesConf
			$typesConf = $TCA[$table]['types'][$fieldValue];

				// Get fields list and traverse it
			$fieldList = explode(',', $typesConf['showitem']);
			$altFieldList = array();

				// Traverse fields in types config and parse the configuration into a nice array:
			foreach($fieldList as $k => $v)	{
				list($pFieldName, $pAltTitle, $pPalette, $pSpec) = t3lib_div::trimExplode(';', $v);
				$defaultExtras = is_array($TCA[$table]['columns'][$pFieldName]) ? $TCA[$table]['columns'][$pFieldName]['defaultExtras'] : '';
				$specConfParts = t3lib_BEfunc::getSpecConfParts($pSpec, $defaultExtras);

				$fieldList[$k]=array(
					'field' => $pFieldName,
					'title' => $pAltTitle,
					'palette' => $pPalette,
					'spec' => $specConfParts,
					'origString' => $v
				);
				if ($useFieldNameAsKey)	{
					$altFieldList[$fieldList[$k]['field']] = $fieldList[$k];
				}
			}
			if ($useFieldNameAsKey)	{
				$fieldList = $altFieldList;
			}

				// Return array:
			return $fieldList;
		}
	}

	/**
	 * Returns the "type" value of $rec from $table which can be used to look up the correct "types" rendering section in $TCA
	 * If no "type" field is configured in the "ctrl"-section of the $TCA for the table, zero is used.
	 * If zero is not an index in the "types" section of $TCA for the table, then the $fieldValue returned will default to 1 (no matter if that is an index or not)
	 * Usage: 7
	 *
	 * @param	string		Table name present in TCA
	 * @param	array		Record from $table
	 * @return	string		Field value
	 * @see getTCAtypes()
	 */
	function getTCAtypeValue($table,$rec)	{
		global $TCA;

			// If no field-value, set it to zero. If there is no type matching the field-value (which now may be zero...) test field-value '1' as default.
		t3lib_div::loadTCA($table);
		if ($TCA[$table])	{
			$field = $TCA[$table]['ctrl']['type'];
			$fieldValue = $field ? ($rec[$field] ? $rec[$field] : 0) : 0;
			if (!is_array($TCA[$table]['types'][$fieldValue]))	$fieldValue = 1;
			return $fieldValue;
		}
	}

	/**
	 * Parses a part of the field lists in the "types"-section of $TCA arrays, namely the "special configuration" at index 3 (position 4)
	 * Elements are splitted by ":" and within those parts, parameters are splitted by "|".
	 * Everything is returned in an array and you should rather see it visually than listen to me anymore now...  Check out example in Inside TYPO3
	 * Usage: 5
	 *
	 * @param	string		Content from the "types" configuration of TCA (the special configuration) - see description of function
	 * @param	string		The ['defaultExtras'] value from field configuration
	 * @return	array
	 */
	function getSpecConfParts($str, $defaultExtras)	{

			// Add defaultExtras:
		$specConfParts = t3lib_div::trimExplode(':', $defaultExtras.':'.$str, 1);

		$reg = array();
		if (count($specConfParts))	{
			foreach($specConfParts as $k2 => $v2)	{
				unset($specConfParts[$k2]);
				if (ereg('(.*)\[(.*)\]',$v2,$reg))	{
					$specConfParts[trim($reg[1])] = array(
						'parameters' => t3lib_div::trimExplode('|', $reg[2], 1)
					);
				} else {
					$specConfParts[trim($v2)] = 1;
				}
			}
		} else {
			$specConfParts = array();
		}
		return $specConfParts;
	}

	/**
	 * Takes an array of "[key]=[value]" strings and returns an array with the keys set as keys pointing to the value.
	 * Better see it in action! Find example in Inside TYPO3
	 * Usage: 6
	 *
	 * @param	array		Array of "[key]=[value]" strings to convert.
	 * @return	array
	 */
	function getSpecConfParametersFromArray($pArr)	{
		$out=array();
		if (is_array($pArr))	{
			reset($pArr);
			while(list($k,$v)=each($pArr))	{
				$parts=explode('=',$v,2);
				if (count($parts)==2)	{
					$out[trim($parts[0])]=trim($parts[1]);
				} else {
					$out[$k]=$v;
				}
			}
		}
		return $out;
	}

	/**
	 * Finds the Data Structure for a FlexForm field
	 * Usage: 5
	 *
	 * @param	array		Field config array
	 * @param	array		Record data
	 * @param	string		The table name
	 * @param	string		Optional fieldname passed to hook object
	 * @param	boolean		Boolean; If set, workspace overlay is applied to records. This is correct behaviour for all presentation and export, but NOT if you want a true reflection of how things are in the live workspace.
	 * @return	mixed		If array, the data structure was found and returned as an array. Otherwise (string) it is an error message.
	 * @see t3lib_TCEforms::getSingleField_typeFlex()
	 */
	function getFlexFormDS($conf,$row,$table,$fieldName='',$WSOL=TRUE)	{
		global $TYPO3_CONF_VARS;

			// Get pointer field etc from TCA-config:
		$ds_pointerField = 	$conf['ds_pointerField'];
		$ds_array = 		$conf['ds'];
		$ds_tableField = 	$conf['ds_tableField'];
		$ds_searchParentField = 	$conf['ds_pointerField_searchParent'];

			// Find source value:
		$dataStructArray='';
		if (is_array($ds_array))	{	// If there is a data source array, that takes precedence
				// If a pointer field is set, take the value from that field in the $row array and use as key.
			if ($ds_pointerField)	{
				$srcPointer = $row[$ds_pointerField];
				$srcPointer = isset($ds_array[$srcPointer]) ? $srcPointer : 'default';
			} else $srcPointer='default';

				// Get Data Source: Detect if it's a file reference and in that case read the file and parse as XML. Otherwise the value is expected to be XML.
			if (substr($ds_array[$srcPointer],0,5)=='FILE:')	{
				$file = t3lib_div::getFileAbsFileName(substr($ds_array[$srcPointer],5));
				if ($file && @is_file($file))	{
					$dataStructArray = t3lib_div::xml2array(t3lib_div::getUrl($file));
				} else $dataStructArray = 'The file "'.substr($ds_array[$srcPointer],5).'" in ds-array key "'.$srcPointer.'" was not found ("'.$file.'")';	// Error message.
			} else {
				$dataStructArray = t3lib_div::xml2array($ds_array[$srcPointer]);
			}

		} elseif ($ds_pointerField) {	// If pointer field AND possibly a table/field is set:
				// Value of field pointed to:
			$srcPointer = $row[$ds_pointerField];

				// Searching recursively back if 'ds_pointerField_searchParent' is defined (typ. a page rootline, or maybe a tree-table):
			if ($ds_searchParentField && !$srcPointer)	{
				$rr = t3lib_BEfunc::getRecord($table,$row['uid'],'uid,'.$ds_searchParentField);	// Get the "pid" field - we cannot know that it is in the input record!
				if ($WSOL)	{
					t3lib_BEfunc::workspaceOL($table,$rr);
					t3lib_BEfunc::fixVersioningPid($table,$rr,TRUE);	// Added "TRUE" 23/03/06 before 4.0. (Also to similar call below!).  Reason: When t3lib_refindex is scanning the system in Live workspace all Pages with FlexForms will not find their inherited datastructure. Thus all references from workspaces are removed! Setting TRUE means that versioning PID doesn't check workspace of the record. I can't see that this should give problems anywhere. See more information inside t3lib_refindex!
				}
				$uidAcc=array();	// Used to avoid looping, if any should happen.
				$subFieldPointer = $conf['ds_pointerField_searchParent_subField'];
				while(!$srcPointer)		{
					$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
									'uid,'.$ds_pointerField.','.$ds_searchParentField.($subFieldPointer?','.$subFieldPointer:''),
									$table,
									'uid='.intval($rr[$ds_searchParentField]).t3lib_BEfunc::deleteClause($table)
								);
					$rr = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);

						// break if no result from SQL db or if looping...
					if (!is_array($rr) || isset($uidAcc[$rr['uid']]))	break;
					$uidAcc[$rr['uid']]=1;

					if ($WSOL)	{
						t3lib_BEfunc::workspaceOL($table,$rr);
						t3lib_BEfunc::fixVersioningPid($table,$rr,TRUE);
					}
					$srcPointer = ($subFieldPointer && $rr[$subFieldPointer]) ? $rr[$subFieldPointer] : $rr[$ds_pointerField];
				}
			}

				// If there is a srcPointer value:
			if ($srcPointer)	{
				if (t3lib_div::testInt($srcPointer))	{	// If integer, then its a record we will look up:
					list($tName,$fName) = explode(':',$ds_tableField,2);
					if ($tName && $fName && is_array($GLOBALS['TCA'][$tName]))	{
						$dataStructRec = t3lib_BEfunc::getRecord($tName, $srcPointer);
						if ($WSOL)	{
							t3lib_BEfunc::workspaceOL($tName,$dataStructRec);
						}
						$dataStructArray = t3lib_div::xml2array($dataStructRec[$fName]);
					} else $dataStructArray = 'No tablename ('.$tName.') or fieldname ('.$fName.') was found an valid!';
				} else {	// Otherwise expect it to be a file:
					$file = t3lib_div::getFileAbsFileName($srcPointer);
					if ($file && @is_file($file))	{
						$dataStructArray = t3lib_div::xml2array(t3lib_div::getUrl($file));
					} else $dataStructArray='The file "'.$srcPointer.'" was not found ("'.$file.'")';	// Error message.
				}
			} else $dataStructArray='No source value in fieldname "'.$ds_pointerField.'"';	// Error message.
		} else $dataStructArray='No proper configuration!';

			// Hook for post-processing the Flexform DS. Introduces the possibility to configure Flexforms via TSConfig
		if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['getFlexFormDSClass'])) {
			foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['getFlexFormDSClass'] as $classRef) {
				$hookObj = &t3lib_div::getUserObj($classRef);
				if (method_exists($hookObj, 'getFlexFormDS_postProcessDS')) {
					$hookObj->getFlexFormDS_postProcessDS($dataStructArray, $conf, $row, $table, $fieldName);
				}
			}
		}

		return $dataStructArray;
	}


















	/*******************************************
	 *
	 * Caching related
	 *
	 *******************************************/

	/**
	 * Stores the string value $data in the 'cache_hash' table with the hash key, $hash, and visual/symbolic identification, $ident
	 * IDENTICAL to the function by same name found in t3lib_page:
	 * Usage: 2
	 *
	 * @param	string		32 bit hash string (eg. a md5 hash of a serialized array identifying the data being stored)
	 * @param	string		The data string. If you want to store an array, then just serialize it first.
	 * @param	string		$ident is just a textual identification in order to inform about the content! May be 20 characters long.
	 * @return	void
	 */
	function storeHash($hash,$data,$ident)	{
		$insertFields = array(
			'hash' => $hash,
			'content' => $data,
			'ident' => $ident,
			'tstamp' => time()
		);
		$GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_hash', 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'cache_hash'));
		$GLOBALS['TYPO3_DB']->exec_INSERTquery('cache_hash', $insertFields);
	}

	/**
	 * Retrieves the string content stored with hash key, $hash, in cache_hash
	 * IDENTICAL to the function by same name found in t3lib_page:
	 * Usage: 2
	 *
	 * @param	string		Hash key, 32 bytes hex
	 * @param	integer		$expTime represents the expire time in seconds. For instance a value of 3600 would allow cached content within the last hour, otherwise nothing is returned.
	 * @return	string
	 */
	function getHash($hash,$expTime=0)	{
			// if expTime is not set, the hash will never expire
		$expTime = intval($expTime);
		if ($expTime)	{
			$whereAdd = ' AND tstamp > '.(time()-$expTime);
		}
		$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('content', 'cache_hash', 'hash='.$GLOBALS['TYPO3_DB']->fullQuoteStr($hash, 'cache_hash').$whereAdd);
		if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))	{
			return $row['content'];
		}
	}








	/*******************************************
	 *
	 * TypoScript related
	 *
	 *******************************************/

	/**
	 * Returns the Page TSconfig for page with id, $id
	 * Requires class "t3lib_TSparser"
	 * Usage: 26 (spec. in ext info_pagetsconfig)
	 *
	 * @param	integer		Page uid for which to create Page TSconfig
	 * @param	array		If $rootLine is an array, that is used as rootline, otherwise rootline is just calculated
	 * @param	boolean		If $returnPartArray is set, then the array with accumulated Page TSconfig is returned non-parsed. Otherwise the output will be parsed by the TypoScript parser.
	 * @return	array		Page TSconfig
	 * @see t3lib_TSparser
	 */
	function getPagesTSconfig($id,$rootLine='',$returnPartArray=0)	{
		$id=intval($id);
		if (!is_array($rootLine))	{
			$rootLine = t3lib_BEfunc::BEgetRootLine($id,'',TRUE);
		}
		ksort($rootLine);	// Order correctly
		$TSdataArray = array();
		$TSdataArray['defaultPageTSconfig']=$GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPageTSconfig'];	// Setting default configuration:
		foreach($rootLine as $k => $v)	{
			$TSdataArray['uid_'.$v['uid']]=$v['TSconfig'];
		}
		$TSdataArray = t3lib_TSparser::checkIncludeLines_array($TSdataArray);
		if ($returnPartArray)	{
			return $TSdataArray;
		}

			// Parsing the user TS (or getting from cache)
		$userTS = implode($TSdataArray,chr(10).'[GLOBAL]'.chr(10));
		$hash = md5('pageTS:'.$userTS);
		$cachedContent = t3lib_BEfunc::getHash($hash,0);
		$TSconfig = array();
		if (isset($cachedContent))	{
			$TSconfig = unserialize($cachedContent);
		} else {
			$parseObj = t3lib_div::makeInstance('t3lib_TSparser');
			$parseObj->parse($userTS);
			$TSconfig = $parseObj->setup;
			t3lib_BEfunc::storeHash($hash,serialize($TSconfig),'PAGES_TSconfig');
		}

			// get User TSconfig overlay
		$userTSconfig = $GLOBALS['BE_USER']->userTS['page.'];
		if (is_array($userTSconfig))	{
			$TSconfig = t3lib_div::array_merge_recursive_overrule($TSconfig, $userTSconfig);
		}
		return $TSconfig;
	}

	/**
	 * Updates Page TSconfig for a page with $id
	 * The function seems to take $pageTS as an array with properties and compare the values with those that already exists for the "object string", $TSconfPrefix, for the page, then sets those values which were not present.
	 * $impParams can be supplied as already known Page TSconfig, otherwise it's calculated.
	 *
	 * THIS DOES NOT CHECK ANY PERMISSIONS. SHOULD IT?
	 * More documentation is needed.
	 *
	 * Usage: 1 (ext. direct_mail)
	 *
	 * @param	integer		Page id
	 * @param	array		Page TS array to write
	 * @param	string		Prefix for object paths
	 * @param	array		[Description needed.]
	 * @return	void
	 * @internal
	 * @see implodeTSParams(), getPagesTSconfig()
	 */
	function updatePagesTSconfig($id,$pageTS,$TSconfPrefix,$impParams='')	{
		$id=intval($id);
		if (is_array($pageTS) && $id>0)	{
			if (!is_array($impParams))	{
				$impParams =t3lib_BEfunc::implodeTSParams(t3lib_BEfunc::getPagesTSconfig($id));
			}
			reset($pageTS);
			$set=array();
			while(list($f,$v)=each($pageTS))	{
				$f = $TSconfPrefix.$f;
				if ((!isset($impParams[$f])&&trim($v)) || strcmp(trim($impParams[$f]),trim($v)))	{
					$set[$f]=trim($v);
				}
			}
			if (count($set))	{
					// Get page record and TS config lines
				$pRec = t3lib_befunc::getRecord('pages',$id);
				$TSlines = explode(chr(10),$pRec['TSconfig']);
				$TSlines = array_reverse($TSlines);
					// Reset the set of changes.
				reset($set);
				while(list($f,$v)=each($set))	{
					reset($TSlines);
					$inserted=0;
					while(list($ki,$kv)=each($TSlines))	{
						if (substr($kv,0,strlen($f)+1)==$f.'=')	{
							$TSlines[$ki]=$f.'='.$v;
							$inserted=1;
							break;
						}
					}
					if (!$inserted)	{
						$TSlines = array_reverse($TSlines);
						$TSlines[]=$f.'='.$v;
						$TSlines = array_reverse($TSlines);
					}
				}
				$TSlines = array_reverse($TSlines);

					// store those changes
				$TSconf = implode(chr(10),$TSlines);

				$GLOBALS['TYPO3_DB']->exec_UPDATEquery('pages', 'uid='.intval($id), array('TSconfig' => $TSconf));
			}
		}
	}

	/**
	 * Implodes a multi dimensional TypoScript array, $p, into a one-dimentional array (return value)
	 * Usage: 3
	 *
	 * @param	array		TypoScript structure
	 * @param	string		Prefix string
	 * @return	array		Imploded TypoScript objectstring/values
	 */
	function implodeTSParams($p,$k='')	{
		$implodeParams=array();
		if (is_array($p))	{
			reset($p);
			while(list($kb,$val)=each($p))	{
				if (is_array($val))	{
					$implodeParams = array_merge($implodeParams,t3lib_BEfunc::implodeTSParams($val,$k.$kb));
				} else {
					$implodeParams[$k.$kb]=$val;
				}
			}
		}
		return $implodeParams;
	}








	/*******************************************
	 *
	 * Users / Groups related
	 *
	 *******************************************/

	/**
	 * Returns an array with be_users records of all user NOT DELETED sorted by their username
	 * Keys in the array is the be_users uid
	 * Usage: 14 (spec. ext. "beuser" and module "web_perm")
	 *
	 * @param	string		Optional $fields list (default: username,usergroup,usergroup_cached_list,uid) can be used to set the selected fields
	 * @param	string		Optional $where clause (fx. "AND username='pete'") can be used to limit query
	 * @return	array
	 */
	function getUserNames($fields='username,usergroup,usergroup_cached_list,uid',$where='')	{
		$be_user_Array=Array();

		$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_users', 'pid=0 '.$where.t3lib_BEfunc::deleteClause('be_users'), '', 'username');
		while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))	{
			$be_user_Array[$row['uid']]=$row;
		}
		return $be_user_Array;
	}

	/**
	 * Returns an array with be_groups records (title, uid) of all groups NOT DELETED sorted by their title
	 * Usage: 8 (spec. ext. "beuser" and module "web_perm")
	 *
	 * @param	string		Field list
	 * @param	string		WHERE clause
	 * @return	array
	 */
	function getGroupNames($fields='title,uid', $where='')	{
		$be_group_Array = Array();
		$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fields, 'be_groups', 'pid=0 '.$where.t3lib_BEfunc::deleteClause('be_groups'), '', 'title');
		while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))	{
			$be_group_Array[$row['uid']] = $row;
		}
		return $be_group_Array;
	}

	/**
	 * Returns an array with be_groups records (like ->getGroupNames) but:
	 * - if the current BE_USER is admin, then all groups are returned, otherwise only groups that the current user is member of (usergroup_cached_list) will be returned.
	 * Usage: 2 (module "web_perm" and ext. taskcenter)
	 *
	 * @param	string		Field list; $fields specify the fields selected (default: title,uid)
	 * @return	array
	 */
	function getListGroupNames($fields='title,uid')	{
		$exQ=' AND hide_in_lists=0';
		if (!$GLOBALS['BE_USER']->isAdmin())	{
			$exQ.=' AND uid IN ('.($GLOBALS['BE_USER']->user['usergroup_cached_list']?$GLOBALS['BE_USER']->user['usergroup_cached_list']:0).')';
		}
		return t3lib_BEfunc::getGroupNames($fields,$exQ);
	}

	/**
	 * Returns the array $usernames with the names of all users NOT IN $groupArray changed to the uid (hides the usernames!).
	 * If $excludeBlindedFlag is set, then these records are unset from the array $usernames
	 * Takes $usernames (array made by t3lib_BEfunc::getUserNames()) and a $groupArray (array with the groups a certain user is member of) as input
	 * Usage: 8
	 *
	 * @param	array		User names
	 * @param	array		Group names
	 * @param	boolean		If $excludeBlindedFlag is set, then these records are unset from the array $usernames
	 * @return	array		User names, blinded
	 */
	function blindUserNames($usernames,$groupArray,$excludeBlindedFlag=0)	{
		if (is_array($usernames) && is_array($groupArray))	{
			while(list($uid,$row)=each($usernames))	{
				$userN=$uid;
				$set=0;
				if ($row['uid']!=$GLOBALS['BE_USER']->user['uid'])	{
					reset($groupArray);
					while(list(,$v)=each($groupArray))	{
						if ($v && t3lib_div::inList($row['usergroup_cached_list'],$v))	{
							$userN = $row['username'];
							$set=1;
						}
					}
				} else {
					$userN = $row['username'];
					$set=1;
				}
				$usernames[$uid]['username']=$userN;
				if ($excludeBlindedFlag && !$set) {unset($usernames[$uid]);}
			}
		}
		return $usernames;
	}

	/**
	 * Corresponds to blindUserNames but works for groups instead
	 * Usage: 2 (module web_perm)
	 *
	 * @param	array		Group names
	 * @param	array		Group names (reference)
	 * @param	boolean		If $excludeBlindedFlag is set, then these records are unset from the array $usernames
	 * @return	array
	 */
	function blindGroupNames($groups,$groupArray,$excludeBlindedFlag=0)	{
		if (is_array($groups) && is_array($groupArray))	{
			while(list($uid,$row)=each($groups))	{
				$groupN=$uid;
				$set=0;
				if (t3lib_div::inArray($groupArray,$uid))	{
					$groupN=$row['title'];
					$set=1;
				}
				$groups[$uid]['title']=$groupN;
				if ($excludeBlindedFlag && !$set) {unset($groups[$uid]);}
			}
		}
		return $groups;
	}













	/*******************************************
	 *
	 * Output related
	 *
	 *******************************************/

	/**
	 * Returns the difference in days between input $tstamp and $EXEC_TIME
	 * Usage: 2 (class t3lib_BEfunc)
	 *
	 * @param	integer		Time stamp, seconds
	 * @return	integer
	 */
	function daysUntil($tstamp)	{
		$delta_t = $tstamp-$GLOBALS['EXEC_TIME'];
		return ceil($delta_t/(3600*24));
	}

	/**
	 * Returns $tstamp formatted as "ddmmyy" (According to $TYPO3_CONF_VARS['SYS']['ddmmyy'])
	 * Usage: 11
	 *
	 * @param	integer		Time stamp, seconds
	 * @return	string		Formatted time
	 */
	function date($tstamp)	{
		return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'],$tstamp);
	}

	/**
	 * Returns $tstamp formatted as "ddmmyy hhmm" (According to $TYPO3_CONF_VARS['SYS']['ddmmyy'] AND $TYPO3_CONF_VARS['SYS']['hhmm'])
	 * Usage: 28
	 *
	 * @param	integer		Time stamp, seconds
	 * @return	string		Formatted time
	 */
	function datetime($value)	{
		return date($GLOBALS['TYPO3_CONF_VARS']['SYS']['ddmmyy'].' '.$GLOBALS['TYPO3_CONF_VARS']['SYS']['hhmm'], $value);
	}

	/**
	 * Returns $value (in seconds) formatted as hh:mm:ss
	 * For instance $value = 3600 + 60*2 + 3 should return "01:02:03"
	 * Usage: 1 (class t3lib_BEfunc)
	 *
	 * @param	integer		Time stamp, seconds
	 * @return	string		Formatted time
	 */
	function time($value)	{
		$hh = floor($value/3600);
		$min = floor(($value-$hh*3600)/60);
		$sec = $value-$hh*3600-$min*60;
		$l = sprintf('%02d',$hh).':'.sprintf('%02d',$min).':'.sprintf('%02d',$sec);
		return $l;
	}

	/**
	 * Returns the "age" in minutes / hours / days / years of the number of $seconds inputted.
	 * Usage: 15
	 *
	 * @param	integer		$seconds could be the difference of a certain timestamp and time()
	 * @param	string		$labels should be something like ' min| hrs| days| yrs'. This value is typically delivered by this function call: $GLOBALS["LANG"]->sL("LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears")
	 * @return	string		Formatted time
	 */
	function calcAge($seconds,$labels = 'min|hrs|days|yrs')	{
		$labelArr = explode('|',$labels);
		$prefix='';
		if ($seconds<0)	{$prefix='-'; $seconds=abs($seconds);}
		if ($seconds<3600)	{
			$seconds = round ($seconds/60).' '.trim($labelArr[0]);
		} elseif ($seconds<24*3600)	{
			$seconds = round ($seconds/3600).' '.trim($labelArr[1]);
		} elseif ($seconds<365*24*3600)	{
			$seconds = round ($seconds/(24*3600)).' '.trim($labelArr[2]);
		} else {
			$seconds = round ($seconds/(365*24*3600)).' '.trim($labelArr[3]);
		}
		return $prefix.$seconds;
	}

	/**
	 * Returns a formatted timestamp if $tstamp is set.
	 * The date/datetime will be followed by the age in parenthesis.
	 * Usage: 3
	 *
	 * @param	integer		Time stamp, seconds
	 * @param	integer		1/-1 depending on polarity of age.
	 * @param	string		$date=="date" will yield "dd:mm:yy" formatting, otherwise "dd:mm:yy hh:mm"
	 * @return	string
	 */
	function dateTimeAge($tstamp,$prefix=1,$date='')	{
		return $tstamp ?
				($date=='date' ? t3lib_BEfunc::date($tstamp) : t3lib_BEfunc::datetime($tstamp)).
				' ('.t3lib_BEfunc::calcAge($prefix*(time()-$tstamp),$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears')).')' : '';
	}

	/**
	 * Returns either title='' or alt='' attribute. This depends on the client browser and whether it supports title='' or not (which is the default)
	 * If no $content is given only the attribute name is returned.
	 * The returned attribute with content will have a leading space char.
	 * Warning: Be careful to submit empty $content var - that will return just the attribute name!
	 * Usage: 0
	 *
	 * @param	string		String to set as title-attribute. If no $content is given only the attribute name is returned.
	 * @param	boolean		If $hsc is set, then content of the attribute is htmlspecialchar()'ed (which is good for XHTML and other reasons...)
	 * @return	string
	 * @deprecated		The idea made sense with older browsers, but now all browsers should support the "title" attribute - so just hardcode the title attribute instead!
	 */
	function titleAttrib($content='',$hsc=0)	{
		global $CLIENT;
		$attrib= ($CLIENT['BROWSER']=='net'&&$CLIENT['VERSION']<5)||$CLIENT['BROWSER']=='konqu' ? 'alt' : 'title';
		return strcmp($content,'')?' '.$attrib.'="'.($hsc?htmlspecialchars($content):$content).'"' : $attrib;
	}

	/**
	 * Returns alt="" and title="" attributes with the value of $content.
	 * Usage: 7
	 *
	 * @param	string		Value for 'alt' and 'title' attributes (will be htmlspecialchars()'ed before output)
	 * @return	string
	 */
	function titleAltAttrib($content)	{
		$out='';
		$out.=' alt="'.htmlspecialchars($content).'"';
		$out.=' title="'.htmlspecialchars($content).'"';
		return $out;
	}

	/**
	 * Returns a linked image-tag for thumbnail(s)/fileicons/truetype-font-previews from a database row with a list of image files in a field
	 * All $TYPO3_CONF_VARS['GFX']['imagefile_ext'] extension are made to thumbnails + ttf file (renders font-example)
	 * Thumbsnails are linked to the show_item.php script which will display further details.
	 * Usage: 7
	 *
	 * @param	array		$row is the database row from the table, $table.
	 * @param	string		Table name for $row (present in TCA)
	 * @param	string		$field is pointing to the field with the list of image files
	 * @param	string		Back path prefix for image tag src="" field
	 * @param	string		Optional: $thumbScript os by default 'thumbs.php' if you don't set it otherwise
	 * @param	string		Optional: $uploaddir is the directory relative to PATH_site where the image files from the $field value is found (Is by default set to the entry in $TCA for that field! so you don't have to!)
	 * @param	boolean		If set, uploaddir is NOT prepended with "../"
	 * @param	string		Optional: $tparams is additional attributes for the image tags
	 * @param	integer		Optional: $size is [w]x[h] of the thumbnail. 56 is default.
	 * @return	string		Thumbnail image tag.
	 */
	function thumbCode($row,$table,$field,$backPath,$thumbScript='',$uploaddir=NULL,$abs=0,$tparams='',$size='')	{
		global $TCA;
			// Load table.
		t3lib_div::loadTCA($table);

			// Find uploaddir automatically
		$uploaddir = (is_null($uploaddir)) ? $TCA[$table]['columns'][$field]['config']['uploadfolder'] : $uploaddir;
		$uploaddir = preg_replace('#/$#','',$uploaddir);

			// Set thumbs-script:
		if (!$GLOBALS['TYPO3_CONF_VARS']['GFX']['thumbnails'])	{
			$thumbScript='gfx/notfound_thumb.gif';
		} elseif(!$thumbScript)	{
			$thumbScript='thumbs.php';
		}
			// Check and parse the size parameter
		$sizeParts=array();
		if ($size = trim($size)) {
			$sizeParts = explode('x', $size.'x'.$size);
			if(!intval($sizeParts[0])) $size='';
		}

			// Traverse files:
		$thumbs = explode(',', $row[$field]);
		$thumbData='';
		while(list(,$theFile)=each($thumbs))	{
			if (trim($theFile))	{
				$fI = t3lib_div::split_fileref($theFile);
				$ext = $fI['fileext'];
						// New 190201 start
				$max=0;
				if (t3lib_div::inList('gif,jpg,png',$ext)) {
					$imgInfo=@getimagesize(PATH_site.$uploaddir.'/'.$theFile);
					if (is_array($imgInfo))	{$max = max($imgInfo[0],$imgInfo[1]);}
				}
					// use the original image if it's size fits to the thumbnail size
				if ($max && $max<=(count($sizeParts)&&max($sizeParts)?max($sizeParts):56))	{
					$theFile = $url = ($abs?'':'../').($uploaddir?$uploaddir.'/':'').trim($theFile);
					$onClick='top.launchView(\''.$theFile.'\',\'\',\''.$backPath.'\');return false;';
					$thumbData.='<a href="#" onclick="'.htmlspecialchars($onClick).'"><img src="'.$backPath.$url.'" '.$imgInfo[3].' hspace="2" border="0" title="'.trim($url).'"'.$tparams.' alt="" /></a> ';
						// New 190201 stop
				} elseif ($ext=='ttf' || t3lib_div::inList($GLOBALS['TYPO3_CONF_VARS']['GFX']['imagefile_ext'],$ext)) {
					$theFile = ($abs?'':'../').($uploaddir?$uploaddir.'/':'').trim($theFile);
					$params = '&file='.rawurlencode($theFile);
					$params .= $size?'&size='.$size:'';
					$url = $thumbScript.'?&dummy='.$GLOBALS['EXEC_TIME'].$params;
					$onClick='top.launchView(\''.$theFile.'\',\'\',\''.$backPath.'\');return false;';
					$thumbData.='<a href="#" onclick="'.htmlspecialchars($onClick).'"><img src="'.htmlspecialchars($backPath.$url).'" hspace="2" border="0" title="'.trim($theFile).'"'.$tparams.' alt="" /></a> ';
				} else {
					$icon = t3lib_BEfunc::getFileIcon($ext);
					$url = 'gfx/fileicons/'.$icon;
					$thumbData.='<img src="'.$backPath.$url.'" hspace="2" border="0" title="'.trim($theFile).'"'.$tparams.' alt="" /> ';
				}
			}
		}
		return $thumbData;
	}

	/**
	 * Returns single image tag to thumbnail using a thumbnail script (like thumbs.php)
	 * Usage: 3
	 *
	 * @param	string		$thumbScript must point to "thumbs.php" relative to the script position
	 * @param	string		$theFile must be the proper reference to the file thumbs.php should show
	 * @param	string		$tparams are additional attributes for the image tag
	 * @param	integer		$size is the size of the thumbnail send along to "thumbs.php"
	 * @return	string		Image tag
	 */
	function getThumbNail($thumbScript,$theFile,$tparams='',$size='')	{
		$params = '&file='.rawurlencode($theFile);
		$params .= trim($size)?'&size='.trim($size):'';
		$url = $thumbScript.'?&dummy='.$GLOBALS['EXEC_TIME'].$params;
		$th='<img src="'.htmlspecialchars($url).'" title="'.trim(basename($theFile)).'"'.($tparams?" ".$tparams:"").' alt="" />';
		return $th;
	}

	/**
	 * Returns title-attribute information for a page-record informing about id, alias, doktype, hidden, starttime, endtime, fe_group etc.
	 * Usage: 8
	 *
	 * @param	array		Input must be a page row ($row) with the proper fields set (be sure - send the full range of fields for the table)
	 * @param	string		$perms_clause is used to get the record path of the shortcut page, if any (and doktype==4)
	 * @param	boolean		If $includeAttrib is set, then the 'title=""' attribute is wrapped about the return value, which is in any case htmlspecialchar()'ed already
	 * @return	string
	 */
	function titleAttribForPages($row,$perms_clause='',$includeAttrib=1)	{
		global $TCA,$LANG;
		$parts=array();
		$parts[] = 'id='.$row['uid'];
		if ($row['alias'])	$parts[]=$LANG->sL($TCA['pages']['columns']['alias']['label']).' '.$row['alias'];
		if ($row['pid']<0)	$parts[] = 'v#1.'.$row['t3ver_id'];
		if ($row['t3ver_state']==1)	$parts[] = 'PLH WSID#'.$row['t3ver_wsid'];
		if ($row['t3ver_state']==-1)	$parts[] = 'New element!';

		if ($row['doktype']=='3')	{
			$parts[]=$LANG->sL($TCA['pages']['columns']['url']['label']).' '.$row['url'];
		} elseif ($row['doktype']=='4')	{
			if ($perms_clause)	{
				$label = t3lib_BEfunc::getRecordPath(intval($row['shortcut']),$perms_clause,20);
			} else {
				$lRec = t3lib_BEfunc::getRecordWSOL('pages',intval($row['shortcut']),'title');
				$label = $lRec['title'];
			}
			if ($row['shortcut_mode']>0)	{
				$label.=', '.$LANG->sL($TCA['pages']['columns']['shortcut_mode']['label']).' '.
							$LANG->sL(t3lib_BEfunc::getLabelFromItemlist('pages','shortcut_mode',$row['shortcut_mode']));
			}
			$parts[]=$LANG->sL($TCA['pages']['columns']['shortcut']['label']).' '.$label;
		} elseif ($row['doktype']=='7')	{
			if ($perms_clause)	{
				$label = t3lib_BEfunc::getRecordPath(intval($row['mount_pid']),$perms_clause,20);
			} else {
				$lRec = t3lib_BEfunc::getRecordWSOL('pages',intval($row['mount_pid']),'title');
				$label = $lRec['title'];
			}
			$parts[]=$LANG->sL($TCA['pages']['columns']['mount_pid']['label']).' '.$label;
			if ($row['mount_pid_ol'])	{
				$parts[] = $LANG->sL($TCA['pages']['columns']['mount_pid_ol']['label']);
			}
		}
		if ($row['nav_hide'])	$parts[] = ereg_replace(':$','',$LANG->sL($TCA['pages']['columns']['nav_hide']['label']));
		if ($row['hidden'])	$parts[] = $LANG->sL('LLL:EXT:lang/locallang_core.php:labels.hidden');
		if ($row['starttime'])	$parts[] = $LANG->sL($TCA['pages']['columns']['starttime']['label']).' '.t3lib_BEfunc::dateTimeAge($row['starttime'],-1,'date');
		if ($row['endtime'])	$parts[] = $LANG->sL($TCA['pages']['columns']['endtime']['label']).' '.t3lib_BEfunc::dateTimeAge($row['endtime'],-1,'date');
		if ($row['fe_group'])	{
			if ($row['fe_group']<0)	{
				$label = $LANG->sL(t3lib_BEfunc::getLabelFromItemlist('pages','fe_group',$row['fe_group']));
			} else {
				$lRec = t3lib_BEfunc::getRecordWSOL('fe_groups',$row['fe_group'],'title');
				$label = $lRec['title'];
			}
			$parts[] = $LANG->sL($TCA['pages']['columns']['fe_group']['label']).' '.$label;
		}
		$out = htmlspecialchars(implode(' - ',$parts));
		return $includeAttrib ? 'title="'.$out.'"' : $out;
	}

	/**
	 * Returns title-attribute information for ANY record (from a table defined in TCA of course)
	 * The included information depends on features of the table, but if hidden, starttime, endtime and fe_group fields are configured for, information about the record status in regard to these features are is included.
	 * "pages" table can be used as well and will return the result of ->titleAttribForPages() for that page.
	 * Usage: 10
	 *
	 * @param	array		Table row; $row is a row from the table, $table
	 * @param	string		Table name
	 * @return	string
	 */
	function getRecordIconAltText($row,$table='pages')	{
		if ($table=='pages')	{
			$out = t3lib_BEfunc::titleAttribForPages($row,'',0);
		} else {
			$ctrl = $GLOBALS['TCA'][$table]['ctrl']['enablecolumns'];

			$out='id='.$row['uid'];	// Uid is added
			if ($table=='pages' && $row['alias'])	{
				$out.=' / '.$row['alias'];
			}
			if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'] && $row['pid']<0)	{
				$out.=' - v#1.'.$row['t3ver_id'];
			}
			if ($GLOBALS['TCA'][$table]['ctrl']['versioningWS'])	{
				if ($row['t3ver_state']==1)	$out.= ' - PLH WSID#'.$row['t3ver_wsid'];
				if ($row['t3ver_state']==-1)	$out.= ' - New element!';
			}

			if ($ctrl['disabled'])	{		// Hidden ...
				$out.=($row[$ctrl['disabled']]?' - '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.hidden'):'');
			}
			if ($ctrl['starttime'])	{
				if ($row[$ctrl['starttime']] > $GLOBALS['EXEC_TIME'])	{
					$out.=' - '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.starttime').':'.t3lib_BEfunc::date($row[$ctrl['starttime']]).' ('.t3lib_BEfunc::daysUntil($row[$ctrl['starttime']]).' '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.days').')';
				}
			}
			if ($row[$ctrl['endtime']])	{
				$out.=' - '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.endtime').': '.t3lib_BEfunc::date($row[$ctrl['endtime']]).' ('.t3lib_BEfunc::daysUntil($row[$ctrl['endtime']]).' '.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.days').')';
			}
		}
		return htmlspecialchars($out);
	}

	/**
	 * Returns the label of the first found entry in an "items" array from $TCA (tablename=$table/fieldname=$col) where the value is $key
	 * Usage: 9
	 *
	 * @param	string		Table name, present in $TCA
	 * @param	string		Field name, present in $TCA
	 * @param	string		items-array value to match
	 * @return	string		Label for item entry
	 */
	function getLabelFromItemlist($table,$col,$key)	{
		global $TCA;
			// Load full TCA for $table
		t3lib_div::loadTCA($table);

			// Check, if there is an "items" array:
		if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col]) && is_array($TCA[$table]['columns'][$col]['config']['items']))	{
				// Traverse the items-array...
			reset($TCA[$table]['columns'][$col]['config']['items']);
			while(list($k,$v)=each($TCA[$table]['columns'][$col]['config']['items']))	{
					// ... and return the first found label where the value was equal to $key
				if (!strcmp($v[1],$key))	return $v[0];
			}
		}
	}

	/**
	 * Returns the label-value for fieldname $col in table, $table
	 * If $printAllWrap is set (to a "wrap") then it's wrapped around the $col value IF THE COLUMN $col DID NOT EXIST in TCA!, eg. $printAllWrap='<b>|</b>' and the fieldname was 'not_found_field' then the return value would be '<b>not_found_field</b>'
	 * Usage: 17
	 *
	 * @param	string		Table name, present in $TCA
	 * @param	string		Field name
	 * @param	string		Wrap value - set function description
	 * @return	string
	 */
	function getItemLabel($table,$col,$printAllWrap='')	{
		global $TCA;
			// Load full TCA for $table
		t3lib_div::loadTCA($table);
			// Check if column exists
		if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col]))	{
				// Re
			return $TCA[$table]['columns'][$col]['label'];
		}
		if ($printAllWrap)	{
			$parts = explode('|',$printAllWrap);
			return $parts[0].$col.$parts[1];
		}
	}

	/**
	 * Returns the "title"-value in record, $row, from table, $table
	 * The field(s) from which the value is taken is determined by the "ctrl"-entries 'label', 'label_alt' and 'label_alt_force'
	 * Usage: 26
	 *
	 * @param	string		Table name, present in TCA
	 * @param	array		Row from table
	 * @param	boolean		If set, result is prepared for output: The output is cropped to a limited lenght (depending on BE_USER->uc['titleLen']) and if no value is found for the title, '<em>[No title]</em>' is returned (localized). Further, the output is htmlspecialchars()'ed
	 * @return	string
	 */
	function getRecordTitle($table,$row,$prep=0)	{
		global $TCA;
		if (is_array($TCA[$table]))	{
			$t = $row[$TCA[$table]['ctrl']['label']];
			if ($TCA[$table]['ctrl']['label_alt'] && ($TCA[$table]['ctrl']['label_alt_force'] || !strcmp($t,'')))	{
				$altFields=t3lib_div::trimExplode(',',$TCA[$table]['ctrl']['label_alt'],1);
				$tA=array();
				$tA[]=$t;
				while(list(,$fN)=each($altFields))	{
					$t = $tA[] = trim(strip_tags($row[$fN]));
					if (strcmp($t,'') && !$TCA[$table]['ctrl']['label_alt_force'])	break;
				}
				if ($TCA[$table]['ctrl']['label_alt_force'])	$t=implode(', ',$tA);
			}
			if ($prep) 	{
				$t = htmlspecialchars(t3lib_div::fixed_lgd_cs($t,$GLOBALS['BE_USER']->uc['titleLen']));
				if (!strcmp(trim($t),''))	$t='<em>['.$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.no_title',1).']</em>';
			}
			return $t;
		}
	}

	/**
	 * Returns a human readable output of a value from a record
	 * For instance a database record relation would be looked up to display the title-value of that record. A checkbox with a "1" value would be "Yes", etc.
	 * $table/$col is tablename and fieldname
	 * REMEMBER to pass the output through htmlspecialchars() if you output it to the browser! (To protect it from XSS attacks and be XHTML compliant)
	 * Usage: 24
	 *
	 * @param	string		Table name, present in TCA
	 * @param	string		Field name, present in TCA
	 * @param	string		$value is the value of that field from a selected record
	 * @param	integer		$fixed_lgd_chars is the max amount of characters the value may occupy
	 * @param	boolean		$defaultPassthrough flag means that values for columns that has no conversion will just be pass through directly (otherwise cropped to 200 chars or returned as "N/A")
	 * @param	boolean		If set, no records will be looked up, UIDs are just shown.
	 * @param	integer		uid of the current record
	 * @return	string
	 */
	function getProcessedValue($table,$col,$value,$fixed_lgd_chars=0,$defaultPassthrough=0,$noRecordLookup=FALSE,$uid=0)	{
		global $TCA;
		global $TYPO3_CONF_VARS;
			// Load full TCA for $table
		t3lib_div::loadTCA($table);
			// Check if table and field is configured:
		if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$col]))	{
				// Depending on the fields configuration, make a meaningful output value.
			$theColConf = $TCA[$table]['columns'][$col]['config'];

				/*****************
				 *HOOK: pre-processing the human readable output from a record
				 ****************/
			if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'])) {
			foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['preProcessValue'] as $_funcRef) {
					t3lib_div::callUserFunction($_funcRef,$theColConf,$this);
				}
			}

			$l='';
			switch((string)$theColConf['type'])	{
				case 'radio':
					$l=t3lib_BEfunc::getLabelFromItemlist($table,$col,$value);
					$l=$GLOBALS['LANG']->sL($l);
				break;
				case 'select':
					if ($theColConf['MM'])	{
							// Display the title of MM related records in lists
							if ($noRecordLookup)	{
								$MMfield = $theColConf['foreign_table'].'.uid';
							} else	{
								$MMfields = array($theColConf['foreign_table'].'.'.$TCA[$theColConf['foreign_table']]['ctrl']['label']);
								foreach (t3lib_div::trimExplode(',', $TCA[$theColConf['foreign_table']]['ctrl']['label_alt'], 1) as $f)	{
									$MMfields[] = $theColConf['foreign_table'].'.'.$f;
								}
								$MMfield = join(',',$MMfields);
							}
							$MMres = $GLOBALS['TYPO3_DB']->exec_SELECT_mm_query(
								$MMfield,
								($table!=$theColConf['foreign_table']?$table:''),
								$theColConf['MM'],
								$theColConf['foreign_table'],
								'AND '.$theColConf['MM'].'.uid_local ='.intval($uid).t3lib_BEfunc::deleteClause($theColConf['foreign_table'])
							);
						if ($MMres) {
							while($MMrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($MMres))	{
								$mmlA[] = ($noRecordLookup?$MMrow['uid']:t3lib_BEfunc::getRecordTitle($theColConf['foreign_table'], $MMrow));
							}
							if (is_array($mmlA)) {
								$l=implode('; ',$mmlA);
							} else {
								$l = '';
							}
						} else {
							$l = 'n/A';
						}
					} else {
						$l = t3lib_BEfunc::getLabelFromItemlist($table,$col,$value);
						$l = $GLOBALS['LANG']->sL($l);
						if ($theColConf['foreign_table'] && !$l && $TCA[$theColConf['foreign_table']])	{
							if ($noRecordLookup)	{
								$l = $value;
							} else {
								$rParts = t3lib_div::trimExplode(',',$value,1);
								reset($rParts);
								$lA = array();
								while(list(,$rVal)=each($rParts))	{
									$rVal = intval($rVal);
									if ($rVal>0) {
										$r=t3lib_BEfunc::getRecordWSOL($theColConf['foreign_table'],$rVal);
									} else {
										$r=t3lib_BEfunc::getRecordWSOL($theColConf['neg_foreign_table'],-$rVal);
									}
									if (is_array($r))	{
										$lA[]=$GLOBALS['LANG']->sL($rVal>0?$theColConf['foreign_table_prefix']:$theColConf['neg_foreign_table_prefix']).t3lib_BEfunc::getRecordTitle($rVal>0?$theColConf['foreign_table']:$theColConf['neg_foreign_table'],$r);
									} else {
										$lA[]=$rVal?'['.$rVal.'!]':'';
									}
								}
								$l = implode(', ',$lA);
							}
						}
					}
				break;
				case 'group':
					$l = implode(', ',t3lib_div::trimExplode(',',$value,1));
				break;
				case 'check':
					if (!is_array($theColConf['items']) || count($theColConf['items'])==1)	{
						$l = $value ? 'Yes' : '';
					} else {
						reset($theColConf['items']);
						$lA=Array();
						while(list($key,$val)=each($theColConf['items']))	{
							if ($value & pow(2,$key))	{$lA[]=$GLOBALS['LANG']->sL($val[0]);}
						}
						$l = implode(', ',$lA);
					}
				break;
				case 'input':
					if ($value)	{
						if (t3lib_div::inList($theColConf['eval'],'date'))	{
							$l = t3lib_BEfunc::date($value).' ('.(time()-$value>0?'-':'').t3lib_BEfunc::calcAge(abs(time()-$value), $GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears')).')';
						} elseif (t3lib_div::inList($theColConf['eval'],'time'))	{
							$l = t3lib_BEfunc::time($value);
						} elseif (t3lib_div::inList($theColConf['eval'],'datetime'))	{
							$l = t3lib_BEfunc::datetime($value);
						} else {
							$l = $value;
						}
					}
				break;
				case 'flex':
					$l = strip_tags($value);
				break;
				default:
					if ($defaultPassthrough)	{
						$l=$value;
					} elseif ($theColConf['MM'])	{
						$l='N/A';
					} elseif ($value)	{
						$l=t3lib_div::fixed_lgd_cs(strip_tags($value),200);
					}
				break;
			}

				/*****************
				 *HOOK: post-processing the human readable output from a record
				 ****************/
			if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'])) {
			foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_befunc.php']['postProcessValue'] as $_funcRef) {
					$params = array(
						'value' => $l,
						'colConf' => $theColConf
					);
					$l = t3lib_div::callUserFunction($_funcRef,$params,$this);
				}
			}

			if ($fixed_lgd_chars)	{
				return t3lib_div::fixed_lgd_cs($l,$fixed_lgd_chars);
			} else {
				return $l;
			}
		}
	}

	/**
	 * Same as ->getProcessedValue() but will go easy on fields like "tstamp" and "pid" which are not configured in TCA - they will be formatted by this function instead.
	 * Usage: 2
	 *
	 * @param	string		Table name, present in TCA
	 * @param	string		Field name
	 * @param	string		Field value
	 * @param	integer		$fixed_lgd_chars is the max amount of characters the value may occupy
	 * @param	integer		uid of the current record
	 * @return	string
	 * @see getProcessedValue()
	 */
	function getProcessedValueExtra($table,$fN,$fV,$fixed_lgd_chars=0,$uid=0)	{
		global $TCA;
		$fVnew = t3lib_BEfunc::getProcessedValue($table,$fN,$fV,$fixed_lgd_chars,0,0,$uid);
		if (!isset($fVnew))	{
			if (is_array($TCA[$table]))	{
				if ($fN==$TCA[$table]['ctrl']['tstamp'] || $fN==$TCA[$table]['ctrl']['crdate'])	{
					$fVnew = t3lib_BEfunc::datetime($fV);
				} elseif ($fN=='pid'){
					$fVnew = t3lib_BEfunc::getRecordPath($fV,'1=1',20);	// Fetches the path with no regard to the users permissions to select pages.
				} else {
					$fVnew = $fV;
				}
			}
		}
		return $fVnew;
	}

	/**
	 * Returns file icon name (from $FILEICONS) for the fileextension $ext
	 * Usage: 10
	 *
	 * @param	string		File extension, lowercase
	 * @return	string		File icon filename
	 */
	function getFileIcon($ext)	{
		return $GLOBALS['FILEICONS'][$ext] ? $GLOBALS['FILEICONS'][$ext] : $GLOBALS['FILEICONS']['default'];
	}

	/**
	 * Returns fields for a table, $table, which would typically be interesting to select
	 * This includes uid, the fields defined for title, icon-field.
	 * Returned as a list ready for query ($prefix can be set to eg. "pages." if you are selecting from the pages table and want the table name prefixed)
	 * Usage: 3
	 *
	 * @param	string		Table name, present in TCA
	 * @param	string		Table prefix
	 * @return	string		List of fields.
	 */
	function getCommonSelectFields($table,$prefix='')	{
		global $TCA;
		$fields = array();
		$fields[] = $prefix.'uid';
		$fields[] = $prefix.$TCA[$table]['ctrl']['label'];

		if ($TCA[$table]['ctrl']['label_alt'])	{
			$secondFields = t3lib_div::trimExplode(',',$TCA[$table]['ctrl']['label_alt'],1);
			foreach($secondFields as $fieldN)	{
				$fields[] = $prefix.$fieldN;
			}
		}
		if ($TCA[$table]['ctrl']['versioningWS'])	{
			$fields[] = $prefix.'t3ver_id';
			$fields[] = $prefix.'t3ver_state';
			$fields[] = $prefix.'t3ver_wsid';
			$fields[] = $prefix.'t3ver_count';
		}

		if ($TCA[$table]['ctrl']['selicon_field'])	$fields[] = $prefix.$TCA[$table]['ctrl']['selicon_field'];
		if ($TCA[$table]['ctrl']['typeicon_column'])	$fields[] = $prefix.$TCA[$table]['ctrl']['typeicon_column'];

		if (is_array($TCA[$table]['ctrl']['enablecolumns']))		{
			if ($TCA[$table]['ctrl']['enablecolumns']['disabled'])	$fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['disabled'];
			if ($TCA[$table]['ctrl']['enablecolumns']['starttime'])	$fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['starttime'];
			if ($TCA[$table]['ctrl']['enablecolumns']['endtime'])	$fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['endtime'];
			if ($TCA[$table]['ctrl']['enablecolumns']['fe_group'])	$fields[] = $prefix.$TCA[$table]['ctrl']['enablecolumns']['fe_group'];
		}

		return implode(',', array_unique($fields));
	}

	/**
	 * Makes a form for configuration of some values based on configuration found in the array $configArray, with default values from $defaults and a data-prefix $dataPrefix
	 * <form>-tags must be supplied separately
	 * Needs more documentation and examples, in particular syntax for configuration array. See Inside TYPO3. That's were you can expect to find example, if anywhere.
	 * Usage: 1 (ext. direct_mail)
	 *
	 * @param	array		Field configuration code.
	 * @param	array		Defaults
	 * @param	string		Prefix for formfields
	 * @return	string		HTML for a form.
	 */
	function makeConfigForm($configArray,$defaults,$dataPrefix)	{
		$params = $defaults;
		if (is_array($configArray))	{
			reset($configArray);
			$lines=array();
			while(list($fname,$config)=each($configArray))	{
				if (is_array($config))	{
					$lines[$fname]='<strong>'.htmlspecialchars($config[1]).'</strong><br />';
					$lines[$fname].=$config[2].'<br />';
					switch($config[0])	{
						case 'string':
						case 'short':
							$formEl = '<input type="text" name="'.$dataPrefix.'['.$fname.']" value="'.$params[$fname].'"'.$GLOBALS['TBE_TEMPLATE']->formWidth($config[0]=='short'?24:48).' />';
						break;
						case 'check':
							$formEl = '<input type="hidden" name="'.$dataPrefix.'['.$fname.']" value="0" /><input type="checkbox" name="'.$dataPrefix.'['.$fname.']" value="1"'.($params[$fname]?' checked="checked"':'').' />';
						break;
						case 'comment':
							$formEl = '';
						break;
						case 'select':
							reset($config[3]);
							$opt=array();
							while(list($k,$v)=each($config[3]))	{
								$opt[]='<option value="'.htmlspecialchars($k).'"'.($params[$fname]==$k?' selected="selected"':'').'>'.htmlspecialchars($v).'</option>';
							}
							$formEl = '<select name="'.$dataPrefix.'['.$fname.']">'.implode('',$opt).'</select>';
						break;
						default:
							debug($config);
						break;
					}
					$lines[$fname].=$formEl;
					$lines[$fname].='<br /><br />';
				} else {
					$lines[$fname]='<hr />';
					if ($config)	$lines[$fname].='<strong>'.strtoupper(htmlspecialchars($config)).'</strong><br />';
					if ($config)	$lines[$fname].='<br />';
				}
			}
		}
		$out = implode('',$lines);
		$out.='<input type="submit" name="submit" value="Update configuration" />';
		return $out;
	}













	/*******************************************
	 *
	 * Backend Modules API functions
	 *
	 *******************************************/

	/**
	 * Returns help-text icon if configured for.
	 * TCA_DESCR must be loaded prior to this function and $BE_USER must have 'edit_showFieldHelp' set to 'icon', otherwise nothing is returned
	 * Usage: 6
	 *
	 * @param	string		Table name
	 * @param	string		Field name
	 * @param	string		Back path
	 * @param	boolean		Force display of icon nomatter BE_USER setting for help
	 * @return	string		HTML content for a help icon/text
	 */
	function helpTextIcon($table,$field,$BACK_PATH,$force=0)	{
		global $TCA_DESCR,$BE_USER;
		if (is_array($TCA_DESCR[$table]) && is_array($TCA_DESCR[$table]['columns'][$field]) && ($BE_USER->uc['edit_showFieldHelp']=='icon' || $force))	{
			$onClick = 'vHWin=window.open(\''.$BACK_PATH.'view_help.php?tfID='.($table.'.'.$field).'\',\'viewFieldHelp\',\'height=400,width=600,status=0,menubar=0,scrollbars=1\');vHWin.focus();return false;';
			return '<a href="#" onclick="'.htmlspecialchars($onClick).'">'.
					'<img'.t3lib_iconWorks::skinImg($BACK_PATH,'gfx/helpbubble.gif','width="14" height="14"').' hspace="2" border="0" class="typo3-csh-icon" alt="" />'.
					'</a>';
		}
	}

	/**
	 * Returns CSH help text (description), if configured for.
	 * TCA_DESCR must be loaded prior to this function and $BE_USER must have "edit_showFieldHelp" set to "text", otherwise nothing is returned
	 * Will automatically call t3lib_BEfunc::helpTextIcon() to get the icon for the text.
	 * Usage: 4
	 *
	 * @param	string		Table name
	 * @param	string		Field name
	 * @param	string		Back path
	 * @param	string		Additional style-attribute content for wrapping table
	 * @return	string		HTML content for help text
	 */
	function helpText($table,$field,$BACK_PATH,$styleAttrib='')	{
		global $TCA_DESCR,$BE_USER;
		if (is_array($TCA_DESCR[$table]) && is_array($TCA_DESCR[$table]['columns'][$field]) && $BE_USER->uc['edit_showFieldHelp']=='text')	{
			$fDat = $TCA_DESCR[$table]['columns'][$field];

				// Get Icon:
			$editIcon = t3lib_BEfunc::helpTextIcon(
									$table,
									$field,
									$BACK_PATH,
									TRUE
								);
				// Add title?
			$onClick = 'vHWin=window.open(\''.$BACK_PATH.'view_help.php?tfID='.($table.'.'.$field).'\',\'viewFieldHelp\',\'height=400,width=600,status=0,menubar=0,scrollbars=1\');vHWin.focus();return false;';
			$text =
					($fDat['alttitle'] ? '<h4><a href="#" onclick="'.htmlspecialchars($onClick).'">'.$fDat['alttitle'].'</a></h4>' : '').
					$fDat['description'];

				// More information to get?
			if ($fDat['image_descr'] || $fDat['seeAlso'] || $fDat['details'] || $fDat['syntax'])	{ // || $fDat['image'];
				$text.=' <a href="#" onclick="'.htmlspecialchars($onClick).'">'.
						'<img'.t3lib_iconWorks::skinImg($BACK_PATH,'gfx/rel_db.gif','width="13" height="12"').' class="absmiddle typo3-csh-more" alt="" />'.
						'</a>';
			}

				// Additional styles?
			$params = $styleAttrib ? ' style="'.$styleAttrib.'"' : '';

				// Compile table with CSH information:
			return '<table border="0" cellpadding="2" cellspacing="0" class="typo3-csh-inline"'.$params.'>
						<tr>
							<td valign="top" width="14">'.$editIcon.'</td>
							<td valign="top">'.$text.'</td>
						</tr>
					</table>';
		}
	}

	/**
	 * API for getting CSH icons/text for use in backend modules.
	 * TCA_DESCR will be loaded if it isn't already
	 * Usage: ?
	 *
	 * @param	string		Table name ('_MOD_'+module name)
	 * @param	string		Field name (CSH locallang main key)
	 * @param	string		Back path
	 * @param	string		Wrap code for icon-mode, splitted by "|". Not used for full-text mode.
	 * @param	boolean		If set, the full text will never be shown (only icon). Useful for places where it will break the page if the table with full text is shown.
	 * @param	string		Additional style-attribute content for wrapping table (full text mode only)
	 * @return	string		HTML content for help text
	 * @see helpText(), helpTextIcon()
	 */
	function cshItem($table,$field,$BACK_PATH,$wrap='',$onlyIconMode=FALSE, $styleAttrib='')	{
		global $TCA_DESCR, $LANG, $BE_USER;
		if ($BE_USER->uc['edit_showFieldHelp'])	{
			$LANG->loadSingleTableDescription($table);

			if (is_array($TCA_DESCR[$table]))	{
					// Creating CSH icon and short description:
				$fullText = t3lib_BEfunc::helpText($table,$field,$BACK_PATH,$styleAttrib);
				$icon = t3lib_BEfunc::helpTextIcon($table,$field,$BACK_PATH,$onlyIconMode);

				if ($fullText && !$onlyIconMode)	{
					$output = $GLOBALS['LANG']->hscAndCharConv($fullText, false);
				} else {
					#$output = '<span style="position:absolute; filter: alpha(opacity=50); -moz-opacity: 0.50;">'.$icon.'</span>';
					$output = $icon;

					if ($output && $wrap)	{
						$wrParts = explode('|',$wrap);
						$output = $wrParts[0].$output.$wrParts[1];
					}
				}

				return $output;
			}
		}
	}

	/**
	 * Returns a JavaScript string (for an onClick handler) which will load the alt_doc.php script that shows the form for editing of the record(s) you have send as params.
	 * REMEMBER to always htmlspecialchar() content in href-properties to ampersands get converted to entities (XHTML requirement and XSS precaution)
	 * Usage: 35
	 *
	 * @param	string		$params is parameters sent along to alt_doc.php. This requires a much more details description which you must seek in Inside TYPO3s documentation of the alt_doc.php API. And example could be '&edit[pages][123]=edit' which will show edit form for page record 123.
	 * @param	string		$backPath must point back to the TYPO3_mainDir directory (where alt_doc.php is)
	 * @param	string		$requestUri is an optional returnUrl you can set - automatically set to REQUEST_URI.
	 * @return	string
	 * @see template::issueCommand()
	 */
	function editOnClick($params,$backPath='',$requestUri='')	{
		$retUrl = 'returnUrl='.($requestUri==-1?"'+T3_THIS_LOCATION+'":rawurlencode($requestUri?$requestUri:t3lib_div::getIndpEnv('REQUEST_URI')));
		return "window.location.href='".$backPath."alt_doc.php?".$retUrl.$params."'; return false;";
	}

	/**
	 * Returns a JavaScript string for viewing the page id, $id
	 * It will detect the correct domain name if needed and provide the link with the right back path. Also it will re-use any window already open.
	 * Usage: 8
	 *
	 * @param	integer		$id is page id
	 * @param	string		$backpath must point back to TYPO3_mainDir (where the site is assumed to be one level above)
	 * @param	array		If root line is supplied the function will look for the first found domain record and use that URL instead (if found)
	 * @param	string		$anchor is optional anchor to the URL
	 * @param	string		$altUrl is an alternative URL which - if set - will make all other parameters ignored: The function will just return the window.open command wrapped around this URL!
	 * @param	string		Additional GET variables.
	 * @param	boolean		If true, then the preview window will gain the focus.
	 * @return	string
	 */
	function viewOnClick($id,$backPath='',$rootLine='',$anchor='',$altUrl='',$addGetVars='',$switchFocus=TRUE)	{
		if ($altUrl)	{
			$url = $altUrl;
		} else {

			if ($GLOBALS['BE_USER']->workspace!=0)	{
				$url = t3lib_div::getIndpEnv('TYPO3_SITE_URL').TYPO3_mainDir.'mod/user/ws/wsol_preview.php?id='.$id.$addGetVars.$anchor;
			} else {
				if ($rootLine)	{
					$parts = parse_url(t3lib_div::getIndpEnv('TYPO3_SITE_URL'));
					if (t3lib_BEfunc::getDomainStartPage($parts['host'],$parts['path']))	{
						$preUrl_temp = t3lib_BEfunc::firstDomainRecord($rootLine);
					}
				}
				$preUrl = $preUrl_temp ? (t3lib_div::getIndpEnv('TYPO3_SSL') ? 'https://' : 'http://').$preUrl_temp : $backPath.'..';
				$url = $preUrl.'/index.php?id='.$id.$addGetVars.$anchor;
			}
		}

		return "previewWin=window.open('".$url."','newTYPO3frontendWindow');".
				($switchFocus ? 'previewWin.focus();' : '');
	}

	/**
	 * Returns the merged User/Page TSconfig for page id, $id.
	 * Please read details about module programming elsewhere!
	 * Usage: 15
	 *
	 * @param	integer		Page uid
	 * @param	string		$TSref is an object string which determines the path of the TSconfig to return.
	 * @return	array
	 */
	function getModTSconfig($id,$TSref)	{
		$pageTS_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref,t3lib_BEfunc::getPagesTSconfig($id));
		$BE_USER_modOptions = $GLOBALS['BE_USER']->getTSConfig($TSref);
		$modTSconfig = t3lib_div::array_merge_recursive_overrule($pageTS_modOptions,$BE_USER_modOptions);
		return $modTSconfig;
	}

	/**
	 * Returns a selector box "function menu" for a module
	 * Requires the JS function jumpToUrl() to be available
	 * See Inside TYPO3 for details about how to use / make Function menus
	 * Usage: 50
	 *
	 * @param	mixed		$id is the "&id=" parameter value to be sent to the module, but it can be also a parameter array which will be passed instead of the &id=...
	 * @param	string		$elementName it the form elements name, probably something like "SET[...]"
	 * @param	string		$currentValue is the value to be selected currently.
	 * @param	array		$menuItems is an array with the menu items for the selector box
	 * @param	string		$script is the script to send the &id to, if empty it's automatically found
	 * @param	string		$addParams is additional parameters to pass to the script.
	 * @return	string		HTML code for selector box
	 */
	function getFuncMenu($mainParams,$elementName,$currentValue,$menuItems,$script='',$addparams='')	{
		if (is_array($menuItems))	{
			if (!is_array($mainParams)) {
				$mainParams = array('id' => $mainParams);
			}
			$mainParams = t3lib_div::implodeArrayForUrl('',$mainParams);

			if (!$script) { $script=basename(PATH_thisScript); }

			$options = array();
			foreach($menuItems as $value => $label)	{
				$options[] = '<option value="'.htmlspecialchars($value).'"'.(!strcmp($currentValue,$value)?' selected="selected"':'').'>'.
								t3lib_div::deHSCentities(htmlspecialchars($label)).
								'</option>';
			}
			if (count($options))	{
				$onChange = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+this.options[this.selectedIndex].value,this);';
				return '

					<!-- Function Menu of module -->
					<select name="'.$elementName.'" onchange="'.htmlspecialchars($onChange).'">
						'.implode('
						',$options).'
					</select>
							';
			}
		}
	}

	/**
	 * Checkbox function menu.
	 * Works like ->getFuncMenu() but takes no $menuItem array since this is a simple checkbox.
	 * Usage: 34
	 *
	 * @param	mixed		$mainParams $id is the "&id=" parameter value to be sent to the module, but it can be also a parameter array which will be passed instead of the &id=...
	 * @param	string		$elementName it the form elements name, probably something like "SET[...]"
	 * @param	string		$currentValue is the value to be selected currently.
	 * @param	string		$script is the script to send the &id to, if empty it's automatically found
	 * @param	string		$addParams is additional parameters to pass to the script.
	 * @param	string		Additional attributes for the checkbox input tag
	 * @return	string		HTML code for checkbox
	 * @see getFuncMenu()
	 */
	function getFuncCheck($mainParams,$elementName,$currentValue,$script='',$addparams='',$tagParams='')	{
		if (!is_array($mainParams)) {
			$mainParams = array('id' => $mainParams);
		}
		$mainParams = t3lib_div::implodeArrayForUrl('',$mainParams);

		if (!$script) {basename(PATH_thisScript);}
		$onClick = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+(this.checked?1:0),this);';
		return '<input type="checkbox" name="'.$elementName.'"'.($currentValue?' checked="checked"':'').' onclick="'.htmlspecialchars($onClick).'"'.($tagParams?' '.$tagParams:'').' />';
	}

	/**
	 * Input field function menu
	 * Works like ->getFuncMenu() / ->getFuncCheck() but displays a input field instead which updates the script "onchange"
	 * Usage: 1
	 *
	 * @param	mixed		$id is the "&id=" parameter value to be sent to the module, but it can be also a parameter array which will be passed instead of the &id=...
	 * @param	string		$elementName it the form elements name, probably something like "SET[...]"
	 * @param	string		$currentValue is the value to be selected currently.
	 * @param	integer		Relative size of input field, max is 48
	 * @param	string		$script is the script to send the &id to, if empty it's automatically found
	 * @param	string		$addParams is additional parameters to pass to the script.
	 * @return	string		HTML code for input text field.
	 * @see getFuncMenu()
	 */
	function getFuncInput($mainParams,$elementName,$currentValue,$size=10,$script="",$addparams="")	{
		if (!is_array($mainParams)) {
			$mainParams = array('id' => $mainParams);
		}
		$mainParams = t3lib_div::implodeArrayForUrl('',$mainParams);

		if (!$script) {basename(PATH_thisScript);}
		$onChange = 'jumpToUrl(\''.$script.'?'.$mainParams.$addparams.'&'.$elementName.'=\'+escape(this.value),this);';
		return '<input type="text"'.$GLOBALS['TBE_TEMPLATE']->formWidth($size).' name="'.$elementName.'" value="'.htmlspecialchars($currentValue).'" onchange="'.htmlspecialchars($onChange).'" />';
	}

	/**
	 * Removes menu items from $itemArray if they are configured to be removed by TSconfig for the module ($modTSconfig)
	 * See Inside TYPO3 about how to program modules and use this API.
	 * Usage: 4
	 *
	 * @param	array		Module TS config array
	 * @param	array		Array of items from which to remove items.
	 * @param	string		$TSref points to the "object string" in $modTSconfig
	 * @return	array		The modified $itemArray is returned.
	 */
	function unsetMenuItems($modTSconfig,$itemArray,$TSref)	{
			// Getting TS-config options for this module for the Backend User:
		$conf = $GLOBALS['BE_USER']->getTSConfig($TSref,$modTSconfig);
		if (is_array($conf['properties']))	{
			reset($conf['properties']);
			while(list($key,$val)=each($conf['properties']))	{
				if (!$val)	{
					unset($itemArray[$key]);
				}
			}
		}
		return $itemArray;
	}

	/**
	 * Call to update the page tree frame (or something else..?) after
	 * t3lib_BEfunc::getSetUpdateSignal('updatePageTree') -> will set the page tree to be updated.
	 * t3lib_BEfunc::getSetUpdateSignal() -> will return some JavaScript that does the update (called in the typo3/template.php file, end() function)
	 * Usage: 11
	 *
	 * @param	string		Whether to set or clear the update signal. When setting, this value contains strings telling WHAT to set. At this point it seems that the value "updatePageTree" is the only one it makes sense to set.
	 * @return	string		HTML code (<script> section)
	 */
	function getSetUpdateSignal($set='')	{
		global $BE_USER;
		$key = 't3lib_BEfunc::getSetUpdateSignal';
		$out='';
		if ($set)	{
			$modData=array();
			$modData['set']=$set;
			$BE_USER->pushModuleData($key,$modData);
		} else {
			$modData = $BE_USER->getModuleData($key,'ses');
			if (trim($modData['set']))	{
				$l=explode(',',$modData['set']);
				while(list(,$v)=each($l))	{
					switch($v)	{
						case 'updatePageTree':
						case 'updateFolderTree':
							$out.='
					<script type="text/javascript">
					/*<![CDATA[*/
							if (top.content && top.content.nav_frame && top.content.nav_frame.refresh_nav)	{
								top.content.nav_frame.refresh_nav();
							}
					/*]]>*/
					</script>';
						break;
					}
				}
				$modData=array();
				$modData['set']='';
				$BE_USER->pushModuleData($key,$modData);
			}
		}
		return $out;
	}


	/**
	 * Returns an array which is most backend modules becomes MOD_SETTINGS containing values from function menus etc. determining the function of the module.
	 * This is kind of session variable management framework for the backend users.
	 * If a key from MOD_MENU is set in the CHANGED_SETTINGS array (eg. a value is passed to the script from the outside), this value is put into the settings-array
	 * Ultimately, see Inside TYPO3 for how to use this function in relation to your modules.
	 * Usage: 23
	 *
	 * @param	array		MOD_MENU is an array that defines the options in menus.
	 * @param	array		CHANGED_SETTINGS represents the array used when passing values to the script from the menus.
	 * @param	string		modName is the name of this module. Used to get the correct module data.
	 * @param	string		If type is 'ses' then the data is stored as session-lasting data. This means that it'll be wiped out the next time the user logs in.
	 * @param	string		dontValidateList can be used to list variables that should not be checked if their value is found in the MOD_MENU array. Used for dynamically generated menus.
	 * @param	string		List of default values from $MOD_MENU to set in the output array (only if the values from MOD_MENU are not arrays)
	 * @return	array		The array $settings, which holds a key for each MOD_MENU key and the values of each key will be within the range of values for each menuitem
	 */
	function getModuleData($MOD_MENU, $CHANGED_SETTINGS, $modName, $type='', $dontValidateList='', $setDefaultList='')	{

		if ($modName && is_string($modName))	{
					// GETTING stored user-data from this module:
			$settings = $GLOBALS['BE_USER']->getModuleData($modName,$type);

			$changed=0;
			if (!is_array($settings))	{
				$changed=1;
				$settings=array();
			}
			if (is_array($MOD_MENU))	{
				foreach ($MOD_MENU as $key=>$var)	{
						// If a global var is set before entering here. eg if submitted, then it's substituting the current value the array.
					if (is_array($CHANGED_SETTINGS) && isset($CHANGED_SETTINGS[$key]) && strcmp($settings[$key],$CHANGED_SETTINGS[$key]))	{
						$settings[$key] = (string)$CHANGED_SETTINGS[$key];
						$changed=1;
					}
						// If the $var is an array, which denotes the existence of a menu, we check if the value is permitted
					if (is_array($var) && (!$dontValidateList || !t3lib_div::inList($dontValidateList,$key)))	{
							// If the setting is an array or not present in the menu-array, MOD_MENU, then the default value is inserted.
						if (is_array($settings[$key]) || !isset($MOD_MENU[$key][$settings[$key]]))	{
							$settings[$key]=(string)key($var);
							$changed=1;
						}
					}
					if ($setDefaultList && !is_array($var))	{	// Sets default values (only strings/checkboxes, not menus)
						if (t3lib_div::inList($setDefaultList,$key) && !isset($settings[$key]))	{
							$settings[$key]=$var;
						}
					}
				}
			} else {die ('No menu!');}

			if ($changed)	{
				$GLOBALS['BE_USER']->pushModuleData($modName,$settings);
			}

			return  $settings;
		} else {die ('Wrong module name: "'.$modName.'"');}
	}













	/*******************************************
	 *
	 * Core
	 *
	 *******************************************/

	/**
	 * Set preview keyword, eg:
	 * 	$previewUrl = t3lib_div::getIndpEnv('TYPO3_SITE_URL').'?ADMCMD_prev='.t3lib_BEfunc::compilePreviewKeyword('id='.$pageId.'&L='.$language.'&ADMCMD_view=1&ADMCMD_editIcons=1&ADMCMD_previewWS='.$this->workspace, $GLOBALS['BE_USER']->user['uid'], 120);
	 *
	 * todo for sys_preview:
	 * - Add a comment which can be shown to previewer in frontend in some way (plus maybe ability to write back, take other action?)
	 * - Add possibility for the preview keyword to work in the backend as well: So it becomes a quick way to a certain action of sorts?
	 *
	 * @param	string		Get variables to preview, eg. 'id=1150&L=0&ADMCMD_view=1&ADMCMD_editIcons=1&ADMCMD_previewWS=8'
	 * @param	string		32 byte MD5 hash keyword for the URL: "?ADMCMD_prev=[keyword]"
	 * @param	integer		Time-To-Live for keyword
	 * @return	string		Returns keyword to use in URL for ADMCMD_prev=
	 */
	function compilePreviewKeyword($getVarsStr, $beUserUid, $ttl=172800)	{
		$field_array = array(
			'keyword' => md5(uniqid(microtime())),
			'tstamp' => time(),
			'endtime' => time()+$ttl,
			'config' => serialize(array(
				'getVars' => $getVarsStr,
				'BEUSER_uid' => $beUserUid
			))
		);

		$GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_preview', $field_array);

		return $field_array['keyword'];
	}

	/**
	 * Unlock or Lock a record from $table with $uid
	 * If $table and $uid is not set, then all locking for the current BE_USER is removed!
	 * Usage: 5
	 *
	 * @param	string		Table name
	 * @param	integer		Record uid
	 * @param	integer		Record pid
	 * @return	void
	 * @internal
	 * @see t3lib_transferData::lockRecord(), alt_doc.php, db_layout.php, db_list.php, wizard_rte.php
	 */
	function lockRecords($table='',$uid=0,$pid=0)	{
		$user_id = intval($GLOBALS['BE_USER']->user['uid']);
		if ($table && $uid)	{
			$fields_values = array(
				'userid' => $user_id,
				'tstamp' => $GLOBALS['EXEC_TIME'],
				'record_table' => $table,
				'record_uid' => $uid,
				'username' => $GLOBALS['BE_USER']->user['username'],
				'record_pid' => $pid
			);

			$GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_lockedrecords', $fields_values);
		} else {
			$GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_lockedrecords', 'userid='.intval($user_id));
		}
	}

	/**
	 * Returns information about whether the record from table, $table, with uid, $uid is currently locked (edited by another user - which should issue a warning).
	 * Notice: Locking is not strictly carried out since locking is abandoned when other backend scripts are activated - which means that a user CAN have a record "open" without having it locked. So this just serves as a warning that counts well in 90% of the cases, which should be sufficient.
	 * Usage: 5
	 *
	 * @param	string		Table name
	 * @param	integer		Record uid
	 * @return	array
	 * @internal
	 * @see class.db_layout.inc, alt_db_navframe.php, alt_doc.php, db_layout.php
	 */
	function isRecordLocked($table,$uid)	{
		global $LOCKED_RECORDS;
		if (!is_array($LOCKED_RECORDS))	{
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
							'*',
							'sys_lockedrecords',
							'sys_lockedrecords.userid!='.intval($GLOBALS['BE_USER']->user['uid']).'
								AND sys_lockedrecords.tstamp > '.($GLOBALS['EXEC_TIME']-2*3600)
						);
			while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))	{
				$LOCKED_RECORDS[$row['record_table'].':'.$row['record_uid']]=$row;
				$LOCKED_RECORDS[$row['record_table'].':'.$row['record_uid']]['msg']=sprintf(
					$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.lockedRecord'),
					$row['username'],
					t3lib_BEfunc::calcAge($GLOBALS['EXEC_TIME']-$row['tstamp'],$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears'))
				);
				if ($row['record_pid'] && !isset($LOCKED_RECORDS[$row['record_table'].':'.$row['record_pid']]))	{
					$LOCKED_RECORDS['pages:'.$row['record_pid']]['msg']=sprintf(
						$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.lockedRecord_content'),
						$row['username'],
						t3lib_BEfunc::calcAge($GLOBALS['EXEC_TIME']-$row['tstamp'],$GLOBALS['LANG']->sL('LLL:EXT:lang/locallang_core.php:labels.minutesHoursDaysYears'))
					);
				}
			}
		}
		return $LOCKED_RECORDS[$table.':'.$uid];
	}

	/**
	 * Returns select statement for MM relations (as used by TCEFORMs etc)
	 * Usage: 3
	 *
	 * @param	array		Configuration array for the field, taken from $TCA
	 * @param	string		Field name
	 * @param	array		TSconfig array from which to get further configuration settings for the field name
	 * @param	string		Prefix string for the key "*foreign_table_where" from $fieldValue array
	 * @return	string		Part of query
	 * @internal
	 * @see t3lib_transferData::renderRecord(), t3lib_TCEforms::foreignTable()
	 */
	function exec_foreign_table_where_query($fieldValue,$field='',$TSconfig=array(),$prefix='')	{
		global $TCA;
		$foreign_table = $fieldValue['config'][$prefix.'foreign_table'];
		$rootLevel = $TCA[$foreign_table]['ctrl']['rootLevel'];

		$fTWHERE = $fieldValue['config'][$prefix.'foreign_table_where'];
		if (strstr($fTWHERE,'###REC_FIELD_'))	{
			$fTWHERE_parts = explode('###REC_FIELD_',$fTWHERE);
			while(list($kk,$vv)=each($fTWHERE_parts))	{
				if ($kk)	{
					$fTWHERE_subpart = explode('###',$vv,2);
					$fTWHERE_parts[$kk]=$TSconfig['_THIS_ROW'][$fTWHERE_subpart[0]].$fTWHERE_subpart[1];
				}
			}
			$fTWHERE = implode('',$fTWHERE_parts);
		}

		$fTWHERE = str_replace('###CURRENT_PID###',intval($TSconfig['_CURRENT_PID']),$fTWHERE);
		$fTWHERE = str_replace('###THIS_UID###',intval($TSconfig['_THIS_UID']),$fTWHERE);
		$fTWHERE = str_replace('###THIS_CID###',intval($TSconfig['_THIS_CID']),$fTWHERE);
		$fTWHERE = str_replace('###STORAGE_PID###',intval($TSconfig['_STORAGE_PID']),$fTWHERE);
		$fTWHERE = str_replace('###SITEROOT###',intval($TSconfig['_SITEROOT']),$fTWHERE);
		$fTWHERE = str_replace('###PAGE_TSCONFIG_ID###',intval($TSconfig[$field]['PAGE_TSCONFIG_ID']),$fTWHERE);
		$fTWHERE = str_replace('###PAGE_TSCONFIG_IDLIST###',$GLOBALS['TYPO3_DB']->cleanIntList($TSconfig[$field]['PAGE_TSCONFIG_IDLIST']),$fTWHERE);
		$fTWHERE = str_replace('###PAGE_TSCONFIG_STR###',$GLOBALS['TYPO3_DB']->quoteStr($TSconfig[$field]['PAGE_TSCONFIG_STR'], $foreign_table),$fTWHERE);

			// rootLevel = -1 is not handled 'properly' here - it goes as if it was rootLevel = 1 (that is pid=0)
		$wgolParts = $GLOBALS['TYPO3_DB']->splitGroupOrderLimit($fTWHERE);
		if ($rootLevel)	{
			$queryParts = array(
				'SELECT' => t3lib_BEfunc::getCommonSelectFields($foreign_table,$foreign_table.'.'),
				'FROM' => $foreign_table,
				'WHERE' => $foreign_table.'.pid=0 '.
							t3lib_BEfunc::deleteClause($foreign_table).' '.
							$wgolParts['WHERE'],
				'GROUPBY' => $wgolParts['GROUPBY'],
				'ORDERBY' => $wgolParts['ORDERBY'],
				'LIMIT' => $wgolParts['LIMIT']
			);
		} else {
			$pageClause = $GLOBALS['BE_USER']->getPagePermsClause(1);
			if ($foreign_table!='pages')	{
				$queryParts = array(
					'SELECT' => t3lib_BEfunc::getCommonSelectFields($foreign_table,$foreign_table.'.'),
					'FROM' => $foreign_table.',pages',
					'WHERE' => 'pages.uid='.$foreign_table.'.pid
								AND pages.deleted=0 '.
								t3lib_BEfunc::deleteClause($foreign_table).
								' AND '.$pageClause.' '.
								$wgolParts['WHERE'],
					'GROUPBY' => $wgolParts['GROUPBY'],
					'ORDERBY' => $wgolParts['ORDERBY'],
					'LIMIT' => $wgolParts['LIMIT']
				);
			} else {
				$queryParts = array(
					'SELECT' => t3lib_BEfunc::getCommonSelectFields($foreign_table,$foreign_table.'.'),
					'FROM' => 'pages',
					'WHERE' => 'pages.deleted=0
								AND '.$pageClause.' '.
								$wgolParts['WHERE'],
					'GROUPBY' => $wgolParts['GROUPBY'],
					'ORDERBY' => $wgolParts['ORDERBY'],
					'LIMIT' => $wgolParts['LIMIT']
				);
			}
		}

		return $GLOBALS['TYPO3_DB']->exec_SELECT_queryArray($queryParts);
	}

	/**
	 * Returns TSConfig for the TCEFORM object in Page TSconfig.
	 * Used in TCEFORMs
	 * Usage: 4
	 *
	 * @param	string		Table name present in TCA
	 * @param	array		Row from table
	 * @return	array
	 * @see t3lib_transferData::renderRecord(), t3lib_TCEforms::setTSconfig(), SC_wizard_list::main(), SC_wizard_add::main()
	 */
	function getTCEFORM_TSconfig($table,$row) {
		t3lib_BEfunc::fixVersioningPid($table,$row);

		$res = array();
		$typeVal = t3lib_BEfunc::getTCAtypeValue($table,$row);

			// Get main config for the table
		list($TScID,$cPid) = t3lib_BEfunc::getTSCpid($table,$row['uid'],$row['pid']);

		$rootLine = t3lib_BEfunc::BEgetRootLine($TScID,'',TRUE);
		if ($TScID>=0)	{
			$tempConf = $GLOBALS['BE_USER']->getTSConfig('TCEFORM.'.$table,t3lib_BEfunc::getPagesTSconfig($TScID,$rootLine));
			if (is_array($tempConf['properties']))	{
				while(list($key,$val)=each($tempConf['properties']))	{
					if (is_array($val))	{
						$fieldN = substr($key,0,-1);
						$res[$fieldN] = $val;
						unset($res[$fieldN]['types.']);
						if (strcmp($typeVal,'') && is_array($val['types.'][$typeVal.'.']))	{
							$res[$fieldN] = t3lib_div::array_merge_recursive_overrule($res[$fieldN],$val['types.'][$typeVal.'.']);
						}
					}
				}
			}
		}
		$res['_CURRENT_PID']=$cPid;
		$res['_THIS_UID']=$row['uid'];
		$res['_THIS_CID']=$row['cid'];
		$res['_THIS_ROW']=$row;	// So the row will be passed to foreign_table_where_query()

		reset($rootLine);
		while(list(,$rC)=each($rootLine))	{
			if (!$res['_STORAGE_PID'])	$res['_STORAGE_PID']=intval($rC['storage_pid']);
			if (!$res['_SITEROOT'])	$res['_SITEROOT']=$rC['is_siteroot']?intval($rC['uid']):0;
		}

		return $res;
	}

	/**
	 * Find the real PID of the record (with $uid from $table). This MAY be impossible if the pid is set as a reference to the former record or a page (if two records are created at one time).
	 * NOTICE: Make sure that the input PID is never negative because the record was an offline version! Therefore, you should always use t3lib_BEfunc::fixVersioningPid($table,$row); on the data you input before calling this function!
	 * Usage: 2
	 *
	 * @param	string		Table name
	 * @param	integer		Record uid
	 * @param	integer		Record pid, could be negative then pointing to a record from same table whose pid to find and return.
	 * @return	integer
	 * @internal
	 * @see t3lib_TCEmain::copyRecord(), getTSCpid()
	 */
	function getTSconfig_pidValue($table,$uid,$pid)	{

		if (t3lib_div::testInt($pid))	{	// If pid is an integer this takes precedence in our lookup.
			$thePidValue = intval($pid);
			if ($thePidValue<0)	{	// If ref to another record, look that record up.
				$pidRec = t3lib_BEfunc::getRecord($table,abs($thePidValue),'pid');
				$thePidValue = is_array($pidRec) ? $pidRec['pid'] : -2;	// Returns -2 if the record did not exist.
			}
			// ... else the pos/zero pid is just returned here.
		} else {	// No integer pid and we are forced to look up the $pid
			$rr = t3lib_BEfunc::getRecord($table,$uid,'pid');	// Try to fetch the record pid from uid. If the uid is 'NEW...' then this will of course return nothing...
			if (is_array($rr))	{
				$thePidValue = $rr['pid'];	// Returning the 'pid' of the record
			} else $thePidValue=-1;	// Returns -1 if the record with the pid was not found.
		}

		return $thePidValue;
	}

	/**
	 * Return $uid if $table is pages and $uid is integer - otherwise the $pid
	 * Usage: 1
	 *
	 * @param	string		Table name
	 * @param	integer		Record uid
	 * @param	integer		Record pid
	 * @return	integer
	 * @internal
	 * @see t3lib_TCEforms::getTSCpid()
	 */
	function getPidForModTSconfig($table,$uid,$pid)	{
		$retVal = ($table=='pages' && t3lib_div::testInt($uid)) ? $uid : $pid;
		return $retVal;
	}

	/**
	 * Returns the REAL pid of the record, if possible. If both $uid and $pid is strings, then pid=-1 is returned as an error indication.
	 * Usage: 8
	 *
	 * @param	string		Table name
	 * @param	integer		Record uid
	 * @param	integer		Record pid
	 * @return	array		Array of two integers; first is the REAL PID of a record and if its a new record negative values are resolved to the true PID, second value is the PID value for TSconfig (uid if table is pages, otherwise the pid)
	 * @internal
	 * @see t3lib_TCEmain::setHistory(), t3lib_TCEmain::process_datamap()
	 */
	function getTSCpid($table,$uid,$pid)	{
			// If pid is negative (referring to another record) the pid of the other record is fetched and returned.
		$cPid = t3lib_BEfunc::getTSconfig_pidValue($table,$uid,$pid);
			// $TScID is the id of $table=pages, else it's the pid of the record.
		$TScID = t3lib_BEfunc::getPidForModTSconfig($table,$uid,$cPid);

		return array($TScID,$cPid);
	}

	/**
	 * Returns first found domain record "domainName" (without trailing slash) if found in the input $rootLine
	 * Usage: 2
	 *
	 * @param	array		Root line array
	 * @return	string		Domain name, if found.
	 */
	function firstDomainRecord($rootLine)	{
		if (t3lib_extMgm::isLoaded('cms'))	{
			reset($rootLine);
			while(list(,$row)=each($rootLine))	{
				$dRec = t3lib_BEfunc::getRecordsByField('sys_domain','pid',$row['uid'],' AND redirectTo=\'\' AND hidden=0', '', 'sorting');
				if (is_array($dRec))	{
					reset($dRec);
					$dRecord = current($dRec);
					return ereg_replace('\/$','',$dRecord['domainName']);
				}
			}
		}
	}

	/**
	 * Returns the sys_domain record for $domain, optionally with $path appended.
	 * Usage: 2
	 *
	 * @param	string		Domain name
	 * @param	string		Appended path
	 * @return	array		Domain record, if found
	 */
	function getDomainStartPage($domain, $path='')	{
		if (t3lib_extMgm::isLoaded('cms'))	{
			$domain = explode(':',$domain);
			$domain = strtolower(ereg_replace('\.$','',$domain[0]));
				// path is calculated.
			$path = trim(ereg_replace('\/[^\/]*$','',$path));
				// stuff:
			$domain.=$path;

			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('sys_domain.*', 'pages,sys_domain', '
				pages.uid=sys_domain.pid
				AND sys_domain.hidden=0
				AND (sys_domain.domainName='.$GLOBALS['TYPO3_DB']->fullQuoteStr($domain, 'sys_domain').' or sys_domain.domainName='.$GLOBALS['TYPO3_DB']->fullQuoteStr($domain.'/', 'sys_domain').')'.
				t3lib_BEfunc::deleteClause('pages'),
				'', '', '1');
			return $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
		}
	}

	/**
	 * Returns overlayered RTE setup from an array with TSconfig. Used in TCEforms and TCEmain
	 * Usage: 8
	 *
	 * @param	array		The properties of Page TSconfig in the key "RTE."
	 * @param	string		Table name
	 * @param	string		Field name
	 * @param	string		Type value of the current record (like from CType of tt_content)
	 * @return	array		Array with the configuration for the RTE
	 * @internal
	 */
	function RTEsetup($RTEprop,$table,$field,$type='')	{
		$thisConfig = is_array($RTEprop['default.']) ? $RTEprop['default.'] : array();
		$thisFieldConf = $RTEprop['config.'][$table.'.'][$field.'.'];
		if (is_array($thisFieldConf))	{
			unset($thisFieldConf['types.']);
			$thisConfig = t3lib_div::array_merge_recursive_overrule($thisConfig,$thisFieldConf);
		}
		if ($type && is_array($RTEprop['config.'][$table.'.'][$field.'.']['types.'][$type.'.']))	{
			$thisConfig = t3lib_div::array_merge_recursive_overrule($thisConfig,$RTEprop['config.'][$table.'.'][$field.'.']['types.'][$type.'.']);
		}
		return $thisConfig;
	}

	/**
	 * Returns first possible RTE object if available.
	 * Usage: $RTEobj = &t3lib_BEfunc::RTEgetObj();
	 *
	 * @return	mixed		If available, returns RTE object, otherwise an array of messages from possible RTEs
	 */
	function &RTEgetObj()	{

			// If no RTE object has been set previously, try to create it:
		if (!isset($GLOBALS['T3_VAR']['RTEobj']))	{

				// Set the object string to blank by default:
			$GLOBALS['T3_VAR']['RTEobj'] = array();

				// Traverse registered RTEs:
			if (is_array($GLOBALS['TYPO3_CONF_VARS']['BE']['RTE_reg']))	{
				foreach($GLOBALS['TYPO3_CONF_VARS']['BE']['RTE_reg'] as $extKey => $rteObjCfg)	{
					$rteObj = &t3lib_div::getUserObj($rteObjCfg['objRef']);
					if (is_object($rteObj))	{
						if ($rteObj->isAvailable())	{
							$GLOBALS['T3_VAR']['RTEobj'] = &$rteObj;
							break;
						} else {
							$GLOBALS['T3_VAR']['RTEobj'] = array_merge($GLOBALS['T3_VAR']['RTEobj'], $rteObj->errorLog);
						}
					}
				}
			}

			if (!count($GLOBALS['T3_VAR']['RTEobj']))	{
				$GLOBALS['T3_VAR']['RTEobj'][] = 'No RTEs configured at all';
			}
		}

			// Return RTE object (if any!)
		return $GLOBALS['T3_VAR']['RTEobj'];
	}

	/**
	 * Returns soft-reference parser for the softRef processing type
	 * Usage: $softRefObj = &t3lib_BEfunc::softRefParserObj('[parser key]');
	 *
	 * @param	string		softRef parser key
	 * @return	mixed		If available, returns Soft link parser object.
	 */
	function &softRefParserObj($spKey)	{

			// If no softRef parser object has been set previously, try to create it:
		if (!isset($GLOBALS['T3_VAR']['softRefParser'][$spKey]))	{

				// Set the object string to blank by default:
			$GLOBALS['T3_VAR']['softRefParser'][$spKey] = '';

				// Now, try to create parser object:
			$objRef = $GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser'][$spKey] ?
							$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser'][$spKey] :
							$GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser_GL'][$spKey];
			if ($objRef)	{
				$softRefParserObj = &t3lib_div::getUserObj($objRef,'');
				if (is_object($softRefParserObj))	{
					$GLOBALS['T3_VAR']['softRefParser'][$spKey] = &$softRefParserObj;
				}
			}
		}

			// Return RTE object (if any!)
		return $GLOBALS['T3_VAR']['softRefParser'][$spKey];
	}

	/**
	 * Returns array of soft parser references
	 *
	 * @param	string		softRef parser list
	 * @param	string		Table name
	 * @param	string		Field name
	 * @return	array		Array where the parser key is the key and the value is the parameter string
	 */
	function explodeSoftRefParserList($parserList)	{

			// Looking for global parsers:
		if (is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser_GL']))	{
			$parserList = implode(',',array_keys($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['GLOBAL']['softRefParser_GL'])).','.$parserList;
		}

			// Return immediately if list is blank:
		if (!strlen($parserList))	return FALSE;

			// Otherwise parse the list:
		$keyList = t3lib_div::trimExplode(',', $parserList, 1);
		$output = array();

		foreach($keyList as $val)	{
			$reg = array();
			if (ereg('^([[:alnum:]_-]+)\[(.*)\]$', $val, $reg))	{
				$output[$reg[1]] = t3lib_div::trimExplode(';', $reg[2], 1);
			} else {
				$output[$val] = '';
			}
		}
		return $output;
	}

	/**
	 * Returns true if $modName is set and is found as a main- or submodule in $TBE_MODULES array
	 * Usage: 1
	 *
	 * @param	string		Module name
	 * @return	boolean
	 */
	function isModuleSetInTBE_MODULES($modName)	{
		reset($GLOBALS['TBE_MODULES']);
		$loaded=array();
		while(list($mkey,$list)=each($GLOBALS['TBE_MODULES']))	{
			$loaded[$mkey]=1;
			if (trim($list))	{
				$subList = t3lib_div::trimExplode(',',$list,1);
				while(list(,$skey)=each($subList))	{
					$loaded[$mkey.'_'.$skey]=1;
				}
			}
		}
		return $modName && isset($loaded[$modName]);
	}

	/**
	 * Counting references to a record/file
	 *
	 * @param	string		Table name (or "_FILE" if its a file)
	 * @param	string		Reference: If table, then integer-uid, if _FILE, then file reference (relative to PATH_site)
	 * @param	string		Message with %s, eg. "There were %s records pointing to this file!"
	 * @return	string		Output string (or integer count value if no msg string specified)
	 */
	function referenceCount($table,$ref,$msg='')	{

		if ($table=='_FILE') {

			if (t3lib_div::isFirstPartOfStr($ref,PATH_site))	{
				$ref = substr($ref,strlen(PATH_site));
			} else return '';

				// Look up the path:
			list($res) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
				'count(*) as count',
				'sys_refindex',
				'ref_table='.$GLOBALS['TYPO3_DB']->fullQuoteStr($table,'sys_refindex').
					' AND ref_string='.$GLOBALS['TYPO3_DB']->fullQuoteStr($ref,'sys_refindex').
					' AND deleted=0'
			);

		} else {
				// Look up the path:
			list($res) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
				'count(*) as count',
				'sys_refindex',
				'ref_table='.$GLOBALS['TYPO3_DB']->fullQuoteStr($table,'sys_refindex').
					' AND ref_uid='.intval($ref).
					' AND deleted=0'
			);
		}

		return $res['count'] ? ($msg ? sprintf($msg,$res['count']) : $res['count']) : '';
	}














	/*******************************************
	 *
	 * Workspaces / Versioning
	 *
	 *******************************************/

	/**
	 * Select all versions of a record, ordered by version id (DESC)
	 *
	 * @param	string		Table name to select from
	 * @param	integer		Record uid for which to find versions.
	 * @param	string		Field list to select
	 * @param	integer		Workspace ID, if zero all versions regardless of workspace is found.
	 * @return	array		Array of versions of table/uid
	 */
	function selectVersionsOfRecord($table, $uid, $fields='*', $workspace=0)	{
		global $TCA;

		if ($TCA[$table] && $TCA[$table]['ctrl']['versioningWS'])	{

				// Select all versions of record:
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
				$fields,
				$table,
				'((t3ver_oid='.intval($uid).($workspace!=0?' AND t3ver_wsid='.intval($workspace):'').') OR uid='.intval($uid).')'.
					t3lib_BEfunc::deleteClause($table),
				'',
				't3ver_id DESC'
			);

				// Add rows to output array:
			$realPid = 0;
			$outputRows = array();
			while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))	{
				if ($uid==$row['uid'])	{
					$row['_CURRENT_VERSION']=TRUE;
					$realPid = $row['pid'];
				}
				$outputRows[] = $row;
			}

				// Set real-pid:
			foreach($outputRows as $idx => $oRow)	{
				$outputRows[$idx]['_REAL_PID'] = $realPid;
			}

			return $outputRows;
		}
	}

	/**
	 * Find page-tree PID for versionized record
	 * Will look if the "pid" value of the input record is -1 and if the table supports versioning - if so, it will translate the -1 PID into the PID of the original record
	 * Used whenever you are tracking something back, like making the root line.
	 * Will only translate if the workspace of the input record matches that of the current user (unless flag set)
	 * Principle; Record offline! => Find online?
	 *
	 * @param	string		Table name
	 * @param	array		Record array passed by reference. As minimum, "pid" and "uid" fields must exist! "t3ver_oid" and "t3ver_wsid" is nice and will save you a DB query.
	 * @param	boolean		Ignore workspace match
	 * @return	void		(Passed by ref). If the record had its pid corrected to the online versions pid, then "_ORIG_pid" is set to the original pid value (-1 of course). The field "_ORIG_pid" is used by various other functions to detect if a record was in fact in a versionized branch.
	 * @see t3lib_page::fixVersioningPid()
	 */
	function fixVersioningPid($table,&$rr,$ignoreWorkspaceMatch=FALSE)	{
		global $TCA;

			// Check that the input record is an offline version from a table that supports versioning:
		if (is_array($rr) && $rr['pid']==-1 && $TCA[$table]['ctrl']['versioningWS'])	{

				// Check values for t3ver_oid and t3ver_wsid:
			if (isset($rr['t3ver_oid']) && isset($rr['t3ver_wsid']))	{	// If "t3ver_oid" is already a field, just set this:
				$oid = $rr['t3ver_oid'];
				$wsid = $rr['t3ver_wsid'];
			} else {	// Otherwise we have to expect "uid" to be in the record and look up based on this:
				$newPidRec = t3lib_BEfunc::getRecord($table,$rr['uid'],'t3ver_oid,t3ver_wsid');
				if (is_array($newPidRec))	{
					$oid = $newPidRec['t3ver_oid'];
					$wsid = $newPidRec['t3ver_wsid'];
				}
			}

				// If ID of current online version is found, look up the PID value of that:
			if ($oid && ($ignoreWorkspaceMatch || !strcmp((int)$wsid,$GLOBALS['BE_USER']->workspace)))	{
				$oidRec = t3lib_BEfunc::getRecord($table,$oid,'pid');
				if (is_array($oidRec))	{
					$rr['_ORIG_pid'] = $rr['pid'];
					$rr['pid'] = $oidRec['pid'];
				}
			}
		}
	}

	/**
	 * Workspace Preview Overlay
	 * Generally ALWAYS used when records are selected based on uid or pid. If records are selected on other fields than uid or pid (eg. "email = ....") then usage might produce undesired results and that should be evaluated on individual basis.
	 * Principle; Record online! => Find offline?
	 *
	 * @param	string		Table name
	 * @param	array		Record array passed by reference. As minimum, the "uid", "pid" and "t3ver_swapmode" (pages) fields must exist! Fake fields cannot exist since the fields in the array is used as field names in the SQL look up.
	 * @param	integer		Workspace ID, if not specified will use $GLOBALS['BE_USER']->workspace
	 * @return	void		(Passed by ref).
	 * @see fixVersioningPid()
	 */
	function workspaceOL($table,&$row,$wsid=-99)	{

			// Initialize workspace ID:
		if ($wsid == -99)	$wsid = $GLOBALS['BE_USER']->workspace;

			// Check if workspace is different from zero and record is set:
		if ($wsid!==0 && is_array($row))	{
			$wsAlt = t3lib_BEfunc::getWorkspaceVersionOfRecord($wsid, $table, $row['uid'], implode(',',array_keys($row)));

				// If version was found, swap the default record with that one.
			if (is_array($wsAlt))	{

					// Always correct PID from -1 to what it should be:
				if (isset($wsAlt['pid']))	{
					$wsAlt['_ORIG_pid'] = $wsAlt['pid'];	// Keep the old (-1) - indicates it was a version...
					$wsAlt['pid'] = $row['pid'];		// Set in the online versions PID.
				}

					// For versions of single elements or page+content, swap UID and PID:
				if ($table!=='pages' || $wsAlt['t3ver_swapmode']<=0)	{
					$wsAlt['_ORIG_uid'] = $wsAlt['uid'];
					$wsAlt['uid'] = $row['uid'];

						// Backend css class:
					$wsAlt['_CSSCLASS'] = $table==='pages' && $wsAlt['t3ver_swapmode']==0 ? 'ver-page' : 'ver-element';
				} else {	// This is only for page-versions with BRANCH below!
					$wsAlt['_ONLINE_uid'] = $row['uid'];

						// Backend css class:
					$wsAlt['_CSSCLASS'] = 'ver-branchpoint';
					$wsAlt['_SUBCSSCLASS'] = 'ver-branch';
				}

					// Changing input record to the workspace version alternative:
				$row = $wsAlt;
			}
		}
	}

	/**
	 * Select the workspace version of a record, if exists
	 *
	 * @param	integer		Workspace ID
	 * @param	string		Table name to select from
	 * @param	integer		Record uid for which to find workspace version.
	 * @param	string		Field list to select
	 * @return	array		If found, return record, otherwise false
	 */
	function getWorkspaceVersionOfRecord($workspace, $table, $uid, $fields='*')	{
		global $TCA;

		if ($workspace!==0 && $TCA[$table] && $TCA[$table]['ctrl']['versioningWS'])	{

				// Select workspace version of record:
			$rows = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows(
				$fields,
				$table,
				'pid=-1 AND
				 t3ver_oid='.intval($uid).' AND
				 t3ver_wsid='.intval($workspace).
					t3lib_BEfunc::deleteClause($table)
			);

			if (is_array($rows[0]))	return $rows[0];
		}

		return FALSE;
	}

	/**
	 * Returns live version of record
	 *
	 * @param	string		Table name
	 * @param	integer		Record UID of draft, offline version
	 * @param	string		Field list, default is *
	 * @return	array		If found, the record, otherwise nothing.
	 */
	function getLiveVersionOfRecord($table,$uid,$fields='*')	{
		global $TCA;

			// Check that table supports versioning:
		if ($TCA[$table] && $TCA[$table]['ctrl']['versioningWS'])	{
			$rec = t3lib_BEfunc::getRecord($table,$uid,'pid,t3ver_oid');

			if ($rec['pid']==-1)	{
				return t3lib_BEfunc::getRecord($table,$rec['t3ver_oid'],$fields);
			}
		}
	}

	/**
	 * Will fetch the rootline for the pid, then check if anywhere in the rootline there is a branch point and if so everything is allowed of course.
	 * Alternatively; if the page of the PID itself is a version and swapmode is zero (page+content) then tables from versioning_followPages are allowed as well.
	 *
	 * @param	integer		Page id inside of which you want to edit/create/delete something.
	 * @param	string		Table name you are checking for. If you don't give the table name ONLY "branch" types are found and returned true. Specifying table you might also get a positive response if the pid is a "page" versioning type AND the table has "versioning_followPages" set.
	 * @param	boolean		If set, the keyword "branchpoint" or "first" is not returned by rather the "t3ver_stage" value of the branch-point.
	 * @return	mixed		Returns either "branchpoint" (if branch) or "first" (if page) or false if nothing. Alternatively, it returns the value of "t3ver_stage" for the branchpoint (if any)
	 */
	function isPidInVersionizedBranch($pid, $table='',$returnStage=FALSE)	{
		$rl = t3lib_BEfunc::BEgetRootLine($pid);
		$c = 0;

		foreach($rl as $rec)	{
			if ($rec['_ORIG_pid']==-1)	{
					// In any case: is it a branchpoint, then OK...
				if ($rec['t3ver_swapmode']>0)	{
					return $returnStage ? (int)$rec['t3ver_stage'] : 'branchpoint';	// OK, we are in a versionized branch
				} elseif ($c==0 && $rec['t3ver_swapmode']==0 && $table && $GLOBALS['TCA'][$table]['ctrl']['versioning_followPages'])	{	// First level: So $table must be versioning_followPages
					return $returnStage ? (int)$rec['t3ver_stage'] : 'first';	// OK, we are in a versionized branch
				}
			}
			$c++;
		}
	}

	/**
	 * Will return where clause de-selecting new-versions from other workspaces.
	 *
	 * @param	string		Table name
	 * @return	string		Where clause if applicable.
	 */
	function versioningPlaceholderClause($table)	{
		if ($GLOBALS['BE_USER']->workspace!==0 && $GLOBALS['TCA'][$table] && $GLOBALS['TCA'][$table]['ctrl']['versioningWS'])	{
			return ' AND ('.$table.'.t3ver_state!=1 OR '.$table.'.t3ver_wsid='.intval($GLOBALS['BE_USER']->workspace).')';
		}
	}

	/**
	 * Count number of versions on a page
	 *
	 * @param	integer		Workspace ID
	 * @param	integer		Page ID
	 * @param	boolean		If set, then all tables and not only "versioning_followPages" are found (except other pages)
	 * @return	array		Overview of records
	 */
	function countVersionsOfRecordsOnPage($workspace,$pageId, $allTables=FALSE)	{
		$output = array();
		if ($workspace!=0)	{
			foreach($GLOBALS['TCA'] as $tableName => $cfg)	{
				if ($tableName!='pages' && $cfg['ctrl']['versioningWS'] && ($cfg['ctrl']['versioning_followPages'] || $allTables))	{

						// Select all records from this table in the database from the workspace
						// This joins the online version with the offline version as tables A and B
					$output[$tableName] = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows (
						'B.uid as live_uid, A.uid as offline_uid',
						$tableName.' A,'.$tableName.' B',
						'A.pid=-1'.	// Table A is the offline version and pid=-1 defines offline
							' AND B.pid='.intval($pageId).
							' AND A.t3ver_wsid='.intval($workspace).
							' AND A.t3ver_oid=B.uid'.	// ... and finally the join between the two tables.
							t3lib_BEfunc::deleteClause($tableName,'A').
							t3lib_BEfunc::deleteClause($tableName,'B')
					);

					if (!is_array($output[$tableName]) || !count($output[$tableName]))	{
						unset($output[$tableName]);
					}
				}
			}
		}
		return $output;
	}

	/**
	 * Performs mapping of new uids to new versions UID in case of import inside a workspace.
	 *
	 * @param	string		Table name
	 * @param	integer		Record uid (of live record placeholder)
	 * @return	integer		Uid of offline version if any, otherwise live uid.
	 */
	function wsMapId($table,$uid)	{
		if ($wsRec = t3lib_BEfunc::getWorkspaceVersionOfRecord($GLOBALS['BE_USER']->workspace,$table,$uid,'uid'))	{
			return $wsRec['uid'];
		} else {
			return $uid;
		}
	}







	/*******************************************
	 *
	 * Miscellaneous
	 *
	 *******************************************/

	/**
	 * Print error message with header, text etc.
	 * Usage: 19
	 *
	 * @param	string		Header string
	 * @param	string		Content string
	 * @param	boolean		Will return an alert() with the content of header and text.
	 * @param	boolean		Print header.
	 * @return	void
	 */
	function typo3PrintError($header,$text,$js='',$head=1)	{
			// This prints out a TYPO3 error message.
			// If $js is set the message will be output in JavaScript
		if ($js)	{
			echo "alert('".t3lib_div::slashJS($header.'\n'.$text)."');";
		} else {
			echo $head?'<html>
				<head>
					<title>Error!</title>
				</head>
				<body bgcolor="white" topmargin="0" leftmargin="0" marginwidth="0" marginheight="0">':'';
			echo '<div align="center">
					<table border="0" cellspacing="0" cellpadding="0" width="333">
						<tr>
							<td align="center">'.
								($GLOBALS['TBE_STYLES']['logo_login']?'<img src="'.$GLOBALS['BACK_PATH'].$GLOBALS['TBE_STYLES']['logo_login'].'" alt="" />':'<img src="'.$GLOBALS['BACK_PATH'].'gfx/typo3logo.gif" width="123" height="34" vspace="10" />').
							'</td>
						</tr>
						<tr>
							<td bgcolor="black">
								<table width="100%" border="0" cellspacing="1" cellpadding="10">
									<tr>
										<td bgcolor="#F4F0E8">
											<font face="verdana,arial,helvetica" size="2">';
			echo '<b><center><font size="+1">'.$header.'</font></center></b><br />'.$text;
			echo '							</font>
										</td>
									</tr>
								</table>
							</td>
						</tr>
					</table>
				</div>';
			echo $head?'
				</body>
			</html>':'';
		}
	}

	/**
	 * Prints TYPO3 Copyright notice for About Modules etc. modules.
	 *
	 * @return	void
	 */
	function TYPO3_copyRightNotice()	{
		global $TYPO3_CONF_VARS;

			// COPYRIGHT NOTICE:
		$loginCopyrightWarrantyProvider = strip_tags(trim($TYPO3_CONF_VARS['SYS']['loginCopyrightWarrantyProvider']));
		$loginCopyrightWarrantyURL = strip_tags(trim($TYPO3_CONF_VARS['SYS']['loginCopyrightWarrantyURL']));

		if (strlen($loginCopyrightWarrantyProvider)>=2 && strlen($loginCopyrightWarrantyURL)>=10)	{
			$warrantyNote='Warranty is supplied by '.htmlspecialchars($loginCopyrightWarrantyProvider).'; <a href="'.htmlspecialchars($loginCopyrightWarrantyURL).'" target="_blank">click for details.</a>';
		} else {
			$warrantyNote='TYPO3 comes with ABSOLUTELY NO WARRANTY; <a href="http://typo3.com/1316.0.html" target="_blank">click for details.</a>';
		}
		$cNotice = '<a href="http://typo3.com/" target="_blank"><img src="gfx/loginlogo_transp.gif" width="75" vspace="2" hspace="4" height="19" alt="TYPO3 logo" align="left" />TYPO3 CMS ver. '.htmlspecialchars(TYPO3_version).'</a>. Copyright &copy; '.htmlspecialchars(TYPO3_copyright_year).' Kasper Sk&aring;rh&oslash;j. Extensions are copyright of their respective owners. Go to <a href="http://typo3.com/" target="_blank">http://typo3.com/</a> for details.
		'.strip_tags($warrantyNote,'<a>').' This is free software, and you are welcome to redistribute it under certain conditions; <a href="http://typo3.com/1316.0.html" target="_blank">click for details</a>. Obstructing the appearance of this notice is prohibited by law.';

		return $cNotice;
	}

	/**
	 * Display some warning messages if this installation is obviously insecure!!
	 * These warnings are only displayed to admin users
	 *
	 * @return	void
	 */
	function displayWarningMessages()	{
		if($GLOBALS['BE_USER']->isAdmin())	{
			$warnings = array();

				// Check if the Install Tool Password is still default: joh316
			if($GLOBALS['TYPO3_CONF_VARS']['BE']['installToolPassword']==md5('joh316'))	{
				$warnings[] = 'The password of your Install Tool is still using the default value "joh316"';
			}

				// Check if there is still a default user 'admin' with password 'password' (MD5sum = 5f4dcc3b5aa765d61d8327deb882cf99)
			$where_clause = 'username='.$GLOBALS['TYPO3_DB']->fullQuoteStr('admin','be_users').' AND password='.$GLOBALS['TYPO3_DB']->fullQuoteStr('5f4dcc3b5aa765d61d8327deb882cf99','be_users').t3lib_BEfunc::deleteClause('be_users');
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('username, password', 'be_users', $where_clause);
			if ($GLOBALS['TYPO3_DB']->sql_num_rows($res))	{
				$warnings[] = 'The backend user "admin" with password "password" is still existing';
			}

				// Check if the encryption key is empty
			if ($GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] == '')	{
				$url = 'install/index.php?redirect_url=index.php'.urlencode('?TYPO3_INSTALL[type]=config#set_encryptionKey');
				$warnings[] = 'The encryption key is not set! Set it in <a href="'.$url.'">$TYPO3_CONF_VARS[SYS][encryptionKey]</a>';
			}

				// check if there are still updates to perform
			if (!t3lib_div::compat_version(TYPO3_branch))	{
				$url = 'install/index.php?redirect_url=index.php'.urlencode('?TYPO3_INSTALL[type]=update');
				$warnings[] = 'This installation is not configured for the TYPO3 version it is running. You probably did so by intention, in this case you can safely ignore this message. If unsure, visit the <a href="'.$url.'" target="_blank">Update Wizard</a> in the Install Tool to see which changes would be affected.';
			}

				// check if sys_refindex is empty
			if (is_object($GLOBALS['TYPO3_DB']))	{
				list($count) = $GLOBALS['TYPO3_DB']->exec_SELECTgetRows('count(*) as rcount','sys_refindex','1=1');
				if (!$count['rcount'])	{
					$warnings[] = 'The Reference Index table is empty which is likely to be the case because you just upgraded your TYPO3 source. Please go to Tools>DB Check and update the reference index.';
				}
			}

			if(count($warnings))	{
				$content = '<table border="0" cellpadding="0" cellspacing="0" class="warningbox"><tr><td>'.
					$GLOBALS['TBE_TEMPLATE']->icons(3).'Important notice!<br />'.
					'- '.implode('<br />- ', $warnings).'<br /><br />'.
					'It is highly recommended that you change this immediately.'.
					'</td></tr></table>';

				unset($warnings);
				return $content;
			}
		}
		return '<p>&nbsp;</p>';
	}

	/**
	 * Returns "web" if the $path (absolute) is within the DOCUMENT ROOT - and thereby qualifies as a "web" folder.
	 * Usage: 4
	 *
	 * @param	string		Path to evaluate
	 * @return	boolean
	 */
	function getPathType_web_nonweb($path)	{
		return t3lib_div::isFirstPartOfStr($path,t3lib_div::getIndpEnv('TYPO3_DOCUMENT_ROOT')) ? 'web' : '';
	}

	/**
	 * Creates ADMCMD parameters for the "viewpage" extension / "cms" frontend
	 * Usage: 1
	 *
	 * @param	array		Page record
	 * @return	string		Query-parameters
	 * @internal
	 */
	function ADMCMD_previewCmds($pageinfo)	{
		if ($pageinfo['fe_group']>0)	{
			$simUser = '&ADMCMD_simUser='.$pageinfo['fe_group'];
		}
		if ($pageinfo['starttime']>time())	{
			$simTime = '&ADMCMD_simTime='.$pageinfo['starttime'];
		}
		if ($pageinfo['endtime']<time() && $pageinfo['endtime']!=0)	{
			$simTime = '&ADMCMD_simTime='.($pageinfo['endtime']-1);
		}
		return $simUser.$simTime;
	}

	/**
	 * Returns an array with key=>values based on input text $params
	 * $params is exploded by line-breaks and each line is supposed to be on the syntax [key] = [some value]
	 * These pairs will be parsed into an array an returned.
	 * Usage: 1
	 *
	 * @param	string		String of parameters on multiple lines to parse into key-value pairs (see function description)
	 * @return	array
	 */
	function processParams($params)	{
		$paramArr=array();
		$lines=explode(chr(10),$params);
		while(list(,$val)=each($lines))	{
			$val = trim($val);
			if ($val)	{
				$pair = explode('=',$val,2);
				$paramArr[trim($pair[0])] = trim($pair[1]);
			}
		}
		return $paramArr;
	}

	/**
	 * Returns "list of backend modules". Most likely this will be obsolete soon / removed. Don't use.
	 * Usage: 3
	 *
	 * @param	array		Module names in array. Must be "addslashes()"ed
	 * @param	string		Perms clause for SQL query
	 * @param	string		Backpath
	 * @param	string		The URL/script to jump to (used in A tag)
	 * @return	array		Two keys, rows and list
	 * @internal
	 * @deprecated
	 * @obsolete
	 */
	function getListOfBackendModules($name,$perms_clause,$backPath='',$script='index.php')	{
		$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'pages', 'doktype!=255 AND module IN (\''.implode('\',\'',$name).'\') AND'.$perms_clause.t3lib_BEfunc::deleteClause('pages'));
		if (!$GLOBALS['TYPO3_DB']->sql_num_rows($res))	return false;

		$out='';
		$theRows=array();
		while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))	{
			$theRows[]=$row;
			$out.='<span class="nobr"><a href="'.htmlspecialchars($script.'?id='.$row['uid']).'">'.
					t3lib_iconWorks::getIconImage('pages',$row,$backPath,'title="'.htmlspecialchars(t3lib_BEfunc::getRecordPath($row['uid'],$perms_clause,20)).'" align="top"').
					htmlspecialchars($row['title']).
					'</a></span><br />';
		}
		return array('rows'=>$theRows,'list'=>$out);
	}
}
?>