File: class.t3lib_tcemain.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 (5712 lines) | stat: -rw-r--r-- 237,893 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
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
3649
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
3694
3695
3696
3697
3698
3699
3700
3701
3702
3703
3704
3705
3706
3707
3708
3709
3710
3711
3712
3713
3714
3715
3716
3717
3718
3719
3720
3721
3722
3723
3724
3725
3726
3727
3728
3729
3730
3731
3732
3733
3734
3735
3736
3737
3738
3739
3740
3741
3742
3743
3744
3745
3746
3747
3748
3749
3750
3751
3752
3753
3754
3755
3756
3757
3758
3759
3760
3761
3762
3763
3764
3765
3766
3767
3768
3769
3770
3771
3772
3773
3774
3775
3776
3777
3778
3779
3780
3781
3782
3783
3784
3785
3786
3787
3788
3789
3790
3791
3792
3793
3794
3795
3796
3797
3798
3799
3800
3801
3802
3803
3804
3805
3806
3807
3808
3809
3810
3811
3812
3813
3814
3815
3816
3817
3818
3819
3820
3821
3822
3823
3824
3825
3826
3827
3828
3829
3830
3831
3832
3833
3834
3835
3836
3837
3838
3839
3840
3841
3842
3843
3844
3845
3846
3847
3848
3849
3850
3851
3852
3853
3854
3855
3856
3857
3858
3859
3860
3861
3862
3863
3864
3865
3866
3867
3868
3869
3870
3871
3872
3873
3874
3875
3876
3877
3878
3879
3880
3881
3882
3883
3884
3885
3886
3887
3888
3889
3890
3891
3892
3893
3894
3895
3896
3897
3898
3899
3900
3901
3902
3903
3904
3905
3906
3907
3908
3909
3910
3911
3912
3913
3914
3915
3916
3917
3918
3919
3920
3921
3922
3923
3924
3925
3926
3927
3928
3929
3930
3931
3932
3933
3934
3935
3936
3937
3938
3939
3940
3941
3942
3943
3944
3945
3946
3947
3948
3949
3950
3951
3952
3953
3954
3955
3956
3957
3958
3959
3960
3961
3962
3963
3964
3965
3966
3967
3968
3969
3970
3971
3972
3973
3974
3975
3976
3977
3978
3979
3980
3981
3982
3983
3984
3985
3986
3987
3988
3989
3990
3991
3992
3993
3994
3995
3996
3997
3998
3999
4000
4001
4002
4003
4004
4005
4006
4007
4008
4009
4010
4011
4012
4013
4014
4015
4016
4017
4018
4019
4020
4021
4022
4023
4024
4025
4026
4027
4028
4029
4030
4031
4032
4033
4034
4035
4036
4037
4038
4039
4040
4041
4042
4043
4044
4045
4046
4047
4048
4049
4050
4051
4052
4053
4054
4055
4056
4057
4058
4059
4060
4061
4062
4063
4064
4065
4066
4067
4068
4069
4070
4071
4072
4073
4074
4075
4076
4077
4078
4079
4080
4081
4082
4083
4084
4085
4086
4087
4088
4089
4090
4091
4092
4093
4094
4095
4096
4097
4098
4099
4100
4101
4102
4103
4104
4105
4106
4107
4108
4109
4110
4111
4112
4113
4114
4115
4116
4117
4118
4119
4120
4121
4122
4123
4124
4125
4126
4127
4128
4129
4130
4131
4132
4133
4134
4135
4136
4137
4138
4139
4140
4141
4142
4143
4144
4145
4146
4147
4148
4149
4150
4151
4152
4153
4154
4155
4156
4157
4158
4159
4160
4161
4162
4163
4164
4165
4166
4167
4168
4169
4170
4171
4172
4173
4174
4175
4176
4177
4178
4179
4180
4181
4182
4183
4184
4185
4186
4187
4188
4189
4190
4191
4192
4193
4194
4195
4196
4197
4198
4199
4200
4201
4202
4203
4204
4205
4206
4207
4208
4209
4210
4211
4212
4213
4214
4215
4216
4217
4218
4219
4220
4221
4222
4223
4224
4225
4226
4227
4228
4229
4230
4231
4232
4233
4234
4235
4236
4237
4238
4239
4240
4241
4242
4243
4244
4245
4246
4247
4248
4249
4250
4251
4252
4253
4254
4255
4256
4257
4258
4259
4260
4261
4262
4263
4264
4265
4266
4267
4268
4269
4270
4271
4272
4273
4274
4275
4276
4277
4278
4279
4280
4281
4282
4283
4284
4285
4286
4287
4288
4289
4290
4291
4292
4293
4294
4295
4296
4297
4298
4299
4300
4301
4302
4303
4304
4305
4306
4307
4308
4309
4310
4311
4312
4313
4314
4315
4316
4317
4318
4319
4320
4321
4322
4323
4324
4325
4326
4327
4328
4329
4330
4331
4332
4333
4334
4335
4336
4337
4338
4339
4340
4341
4342
4343
4344
4345
4346
4347
4348
4349
4350
4351
4352
4353
4354
4355
4356
4357
4358
4359
4360
4361
4362
4363
4364
4365
4366
4367
4368
4369
4370
4371
4372
4373
4374
4375
4376
4377
4378
4379
4380
4381
4382
4383
4384
4385
4386
4387
4388
4389
4390
4391
4392
4393
4394
4395
4396
4397
4398
4399
4400
4401
4402
4403
4404
4405
4406
4407
4408
4409
4410
4411
4412
4413
4414
4415
4416
4417
4418
4419
4420
4421
4422
4423
4424
4425
4426
4427
4428
4429
4430
4431
4432
4433
4434
4435
4436
4437
4438
4439
4440
4441
4442
4443
4444
4445
4446
4447
4448
4449
4450
4451
4452
4453
4454
4455
4456
4457
4458
4459
4460
4461
4462
4463
4464
4465
4466
4467
4468
4469
4470
4471
4472
4473
4474
4475
4476
4477
4478
4479
4480
4481
4482
4483
4484
4485
4486
4487
4488
4489
4490
4491
4492
4493
4494
4495
4496
4497
4498
4499
4500
4501
4502
4503
4504
4505
4506
4507
4508
4509
4510
4511
4512
4513
4514
4515
4516
4517
4518
4519
4520
4521
4522
4523
4524
4525
4526
4527
4528
4529
4530
4531
4532
4533
4534
4535
4536
4537
4538
4539
4540
4541
4542
4543
4544
4545
4546
4547
4548
4549
4550
4551
4552
4553
4554
4555
4556
4557
4558
4559
4560
4561
4562
4563
4564
4565
4566
4567
4568
4569
4570
4571
4572
4573
4574
4575
4576
4577
4578
4579
4580
4581
4582
4583
4584
4585
4586
4587
4588
4589
4590
4591
4592
4593
4594
4595
4596
4597
4598
4599
4600
4601
4602
4603
4604
4605
4606
4607
4608
4609
4610
4611
4612
4613
4614
4615
4616
4617
4618
4619
4620
4621
4622
4623
4624
4625
4626
4627
4628
4629
4630
4631
4632
4633
4634
4635
4636
4637
4638
4639
4640
4641
4642
4643
4644
4645
4646
4647
4648
4649
4650
4651
4652
4653
4654
4655
4656
4657
4658
4659
4660
4661
4662
4663
4664
4665
4666
4667
4668
4669
4670
4671
4672
4673
4674
4675
4676
4677
4678
4679
4680
4681
4682
4683
4684
4685
4686
4687
4688
4689
4690
4691
4692
4693
4694
4695
4696
4697
4698
4699
4700
4701
4702
4703
4704
4705
4706
4707
4708
4709
4710
4711
4712
4713
4714
4715
4716
4717
4718
4719
4720
4721
4722
4723
4724
4725
4726
4727
4728
4729
4730
4731
4732
4733
4734
4735
4736
4737
4738
4739
4740
4741
4742
4743
4744
4745
4746
4747
4748
4749
4750
4751
4752
4753
4754
4755
4756
4757
4758
4759
4760
4761
4762
4763
4764
4765
4766
4767
4768
4769
4770
4771
4772
4773
4774
4775
4776
4777
4778
4779
4780
4781
4782
4783
4784
4785
4786
4787
4788
4789
4790
4791
4792
4793
4794
4795
4796
4797
4798
4799
4800
4801
4802
4803
4804
4805
4806
4807
4808
4809
4810
4811
4812
4813
4814
4815
4816
4817
4818
4819
4820
4821
4822
4823
4824
4825
4826
4827
4828
4829
4830
4831
4832
4833
4834
4835
4836
4837
4838
4839
4840
4841
4842
4843
4844
4845
4846
4847
4848
4849
4850
4851
4852
4853
4854
4855
4856
4857
4858
4859
4860
4861
4862
4863
4864
4865
4866
4867
4868
4869
4870
4871
4872
4873
4874
4875
4876
4877
4878
4879
4880
4881
4882
4883
4884
4885
4886
4887
4888
4889
4890
4891
4892
4893
4894
4895
4896
4897
4898
4899
4900
4901
4902
4903
4904
4905
4906
4907
4908
4909
4910
4911
4912
4913
4914
4915
4916
4917
4918
4919
4920
4921
4922
4923
4924
4925
4926
4927
4928
4929
4930
4931
4932
4933
4934
4935
4936
4937
4938
4939
4940
4941
4942
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957
4958
4959
4960
4961
4962
4963
4964
4965
4966
4967
4968
4969
4970
4971
4972
4973
4974
4975
4976
4977
4978
4979
4980
4981
4982
4983
4984
4985
4986
4987
4988
4989
4990
4991
4992
4993
4994
4995
4996
4997
4998
4999
5000
5001
5002
5003
5004
5005
5006
5007
5008
5009
5010
5011
5012
5013
5014
5015
5016
5017
5018
5019
5020
5021
5022
5023
5024
5025
5026
5027
5028
5029
5030
5031
5032
5033
5034
5035
5036
5037
5038
5039
5040
5041
5042
5043
5044
5045
5046
5047
5048
5049
5050
5051
5052
5053
5054
5055
5056
5057
5058
5059
5060
5061
5062
5063
5064
5065
5066
5067
5068
5069
5070
5071
5072
5073
5074
5075
5076
5077
5078
5079
5080
5081
5082
5083
5084
5085
5086
5087
5088
5089
5090
5091
5092
5093
5094
5095
5096
5097
5098
5099
5100
5101
5102
5103
5104
5105
5106
5107
5108
5109
5110
5111
5112
5113
5114
5115
5116
5117
5118
5119
5120
5121
5122
5123
5124
5125
5126
5127
5128
5129
5130
5131
5132
5133
5134
5135
5136
5137
5138
5139
5140
5141
5142
5143
5144
5145
5146
5147
5148
5149
5150
5151
5152
5153
5154
5155
5156
5157
5158
5159
5160
5161
5162
5163
5164
5165
5166
5167
5168
5169
5170
5171
5172
5173
5174
5175
5176
5177
5178
5179
5180
5181
5182
5183
5184
5185
5186
5187
5188
5189
5190
5191
5192
5193
5194
5195
5196
5197
5198
5199
5200
5201
5202
5203
5204
5205
5206
5207
5208
5209
5210
5211
5212
5213
5214
5215
5216
5217
5218
5219
5220
5221
5222
5223
5224
5225
5226
5227
5228
5229
5230
5231
5232
5233
5234
5235
5236
5237
5238
5239
5240
5241
5242
5243
5244
5245
5246
5247
5248
5249
5250
5251
5252
5253
5254
5255
5256
5257
5258
5259
5260
5261
5262
5263
5264
5265
5266
5267
5268
5269
5270
5271
5272
5273
5274
5275
5276
5277
5278
5279
5280
5281
5282
5283
5284
5285
5286
5287
5288
5289
5290
5291
5292
5293
5294
5295
5296
5297
5298
5299
5300
5301
5302
5303
5304
5305
5306
5307
5308
5309
5310
5311
5312
5313
5314
5315
5316
5317
5318
5319
5320
5321
5322
5323
5324
5325
5326
5327
5328
5329
5330
5331
5332
5333
5334
5335
5336
5337
5338
5339
5340
5341
5342
5343
5344
5345
5346
5347
5348
5349
5350
5351
5352
5353
5354
5355
5356
5357
5358
5359
5360
5361
5362
5363
5364
5365
5366
5367
5368
5369
5370
5371
5372
5373
5374
5375
5376
5377
5378
5379
5380
5381
5382
5383
5384
5385
5386
5387
5388
5389
5390
5391
5392
5393
5394
5395
5396
5397
5398
5399
5400
5401
5402
5403
5404
5405
5406
5407
5408
5409
5410
5411
5412
5413
5414
5415
5416
5417
5418
5419
5420
5421
5422
5423
5424
5425
5426
5427
5428
5429
5430
5431
5432
5433
5434
5435
5436
5437
5438
5439
5440
5441
5442
5443
5444
5445
5446
5447
5448
5449
5450
5451
5452
5453
5454
5455
5456
5457
5458
5459
5460
5461
5462
5463
5464
5465
5466
5467
5468
5469
5470
5471
5472
5473
5474
5475
5476
5477
5478
5479
5480
5481
5482
5483
5484
5485
5486
5487
5488
5489
5490
5491
5492
5493
5494
5495
5496
5497
5498
5499
5500
5501
5502
5503
5504
5505
5506
5507
5508
5509
5510
5511
5512
5513
5514
5515
5516
5517
5518
5519
5520
5521
5522
5523
5524
5525
5526
5527
5528
5529
5530
5531
5532
5533
5534
5535
5536
5537
5538
5539
5540
5541
5542
5543
5544
5545
5546
5547
5548
5549
5550
5551
5552
5553
5554
5555
5556
5557
5558
5559
5560
5561
5562
5563
5564
5565
5566
5567
5568
5569
5570
5571
5572
5573
5574
5575
5576
5577
5578
5579
5580
5581
5582
5583
5584
5585
5586
5587
5588
5589
5590
5591
5592
5593
5594
5595
5596
5597
5598
5599
5600
5601
5602
5603
5604
5605
5606
5607
5608
5609
5610
5611
5612
5613
5614
5615
5616
5617
5618
5619
5620
5621
5622
5623
5624
5625
5626
5627
5628
5629
5630
5631
5632
5633
5634
5635
5636
5637
5638
5639
5640
5641
5642
5643
5644
5645
5646
5647
5648
5649
5650
5651
5652
5653
5654
5655
5656
5657
5658
5659
5660
5661
5662
5663
5664
5665
5666
5667
5668
5669
5670
5671
5672
5673
5674
5675
5676
5677
5678
5679
5680
5681
5682
5683
5684
5685
5686
5687
5688
5689
5690
5691
5692
5693
5694
5695
5696
5697
5698
5699
5700
5701
5702
5703
5704
5705
5706
5707
5708
5709
5710
5711
5712
<?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!
***************************************************************/
/**
 * Contains the TYPO3 Core Engine
 *
 * $Id: class.t3lib_tcemain.php 1657 2006-07-26 17:54:15Z mundaun $
 * Revised for TYPO3 3.9 October 2005 by Kasper Skaarhoj
 *
 * @author	Kasper Skaarhoj <kasperYYYY@typo3.com>
 */
/**
 * [CLASS/FUNCTION INDEX of SCRIPT]
 *
 *
 *
 *  229: class t3lib_TCEmain
 *  348:     function start($data,$cmd,$altUserObject='')
 *  387:     function setMirror($mirror)
 *  412:     function setDefaultsFromUserTS($userTS)
 *  435:     function process_uploads($postFiles)
 *  473:     function process_uploads_traverseArray(&$outputArr,$inputArr,$keyToSet)
 *
 *              SECTION: PROCESSING DATA
 *  509:     function process_datamap()
 *  815:     function placeholderShadowing($table,$id)
 *  851:     function fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$realPid,$status,$tscPID)
 *
 *              SECTION: Evaluation of input values
 * 1072:     function checkValue($table,$field,$value,$id,$status,$realPid,$tscPID)
 * 1132:     function checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$uploadedFiles,$tscPID)
 * 1178:     function checkValue_input($res,$value,$tcaFieldConf,$PP,$field='')
 * 1216:     function checkValue_check($res,$value,$tcaFieldConf,$PP)
 * 1239:     function checkValue_radio($res,$value,$tcaFieldConf,$PP)
 * 1265:     function checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field)
 * 1366:     function checkValue_group_select_file($valueArray,$tcaFieldConf,$curValue,$uploadedFileArray,$status,$table,$id,$recFID)
 * 1536:     function checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field)
 * 1609:     function checkValue_flexArray2Xml($array)
 * 1621:     function _DELETE_FLEX_FORMdata(&$valueArrayToRemoveFrom,$deleteCMDS)
 * 1643:     function _MOVE_FLEX_FORMdata(&$valueArrayToMoveIn, $moveCMDS, $direction)
 *
 *              SECTION: Helper functions for evaluation functions.
 * 1705:     function getUnique($table,$field,$value,$id,$newPid=0)
 * 1743:     function checkValue_input_Eval($value,$evalArray,$is_in)
 * 1839:     function checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,$type)
 * 1872:     function checkValue_group_select_explodeSelectGroupValue($value)
 * 1896:     function checkValue_flex_procInData($dataPart,$dataPart_current,$uploadedFiles,$dataStructArray,$pParams,$callBackFunc='')
 * 1935:     function checkValue_flex_procInData_travDS(&$dataValues,$dataValues_current,$uploadedFiles,$DSelements,$pParams,$callBackFunc,$structurePath)
 *
 *              SECTION: PROCESSING COMMANDS
 * 2081:     function process_cmdmap()
 *
 *              SECTION: Cmd: Copying
 * 2221:     function copyRecord($table,$uid,$destPid,$first=0,$overrideValues=array(),$excludeFields='')
 * 2343:     function copyPages($uid,$destPid)
 * 2397:     function copySpecificPage($uid,$destPid,$copyTablesArray,$first=0)
 * 2431:     function copyRecord_raw($table,$uid,$pid,$overrideArray=array())
 * 2495:     function rawCopyPageContent($old_pid,$new_pid,$copyTablesArray)
 * 2519:     function insertNewCopyVersion($table,$fieldArray,$realPid)
 * 2570:     function copyRecord_procBasedOnFieldType($table,$uid,$field,$value,$row,$conf)
 * 2626:     function copyRecord_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)
 * 2654:     function copyRecord_procFilesRefs($conf, $uid, $value)
 *
 *              SECTION: Cmd: Moving, Localizing
 * 2723:     function moveRecord($table,$uid,$destPid)
 * 2910:     function localize($table,$uid,$language)
 *
 *              SECTION: Cmd: Deleting
 * 2994:     function deleteAction($table, $id)
 * 3041:     function deleteEl($table, $uid, $noRecordCheck=FALSE, $forceHardDelete=FALSE)
 * 3056:     function undeleteRecord($table,$uid)
 * 3073:     function deleteRecord($table,$uid, $noRecordCheck=FALSE, $forceHardDelete=FALSE,$undeleteRecord=FALSE)
 * 3159:     function deletePages($uid,$force=FALSE,$forceHardDelete=FALSE)
 * 3187:     function deleteSpecificPage($uid,$forceHardDelete=FALSE)
 * 3210:     function canDeletePage($uid)
 * 3237:     function cannotDeleteRecord($table,$id)
 *
 *              SECTION: Cmd: Versioning
 * 3275:     function versionizeRecord($table,$id,$label,$delete=FALSE,$versionizeTree=-1)
 * 3351:     function versionizePages($uid,$label,$versionizeTree)
 * 3414:     function version_swap($table,$id,$swapWith,$swapIntoWS=0)
 * 3585:     function version_clearWSID($table,$id)
 * 3619:     function version_setStage($table,$id,$stageId,$comment='')
 *
 *              SECTION: Cmd: Helper functions
 * 3664:     function remapListedDBRecords()
 * 3741:     function remapListedDBRecords_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)
 * 3767:     function remapListedDBRecords_procDBRefs($conf, $value, $MM_localUid)
 *
 *              SECTION: Access control / Checking functions
 * 3832:     function checkModifyAccessList($table)
 * 3844:     function isRecordInWebMount($table,$id)
 * 3858:     function isInWebMount($pid)
 * 3872:     function checkRecordUpdateAccess($table,$id)
 * 3896:     function checkRecordInsertAccess($insertTable,$pid,$action=1)
 * 3930:     function isTableAllowedForThisPage($page_uid, $checkTable)
 * 3963:     function doesRecordExist($table,$id,$perms)
 * 4024:     function doesRecordExist_pageLookUp($id, $perms)
 * 4050:     function doesBranchExist($inList,$pid,$perms,$recurse)
 * 4084:     function tableReadOnly($table)
 * 4096:     function tableAdminOnly($table)
 * 4110:     function destNotInsideSelf($dest,$id)
 * 4142:     function getExcludeListArray()
 * 4165:     function doesPageHaveUnallowedTables($page_uid,$doktype)
 *
 *              SECTION: Information lookup
 * 4214:     function pageInfo($id,$field)
 * 4234:     function recordInfo($table,$id,$fieldList)
 * 4255:     function getRecordProperties($table,$id,$noWSOL=FALSE)
 * 4271:     function getRecordPropertiesFromRow($table,$row)
 *
 *              SECTION: Storing data to Database Layer
 * 4314:     function updateDB($table,$id,$fieldArray)
 * 4366:     function insertDB($table,$id,$fieldArray,$newVersion=FALSE,$suggestedUid=0,$dontSetNewIdIndex=FALSE)
 * 4439:     function checkStoredRecord($table,$id,$fieldArray,$action)
 * 4476:     function setHistory($table,$id,$logId)
 * 4509:     function clearHistory($maxAgeSeconds=604800,$table)
 * 4523:     function updateRefIndex($table,$id)
 *
 *              SECTION: Misc functions
 * 4555:     function getSortNumber($table,$uid,$pid)
 * 4628:     function resorting($table,$pid,$sortRow, $return_SortNumber_After_This_Uid)
 * 4659:     function setTSconfigPermissions($fieldArray,$TSConfig_p)
 * 4676:     function newFieldArray($table)
 * 4708:     function addDefaultPermittedLanguageIfNotSet($table,&$incomingFieldArray)
 * 4732:     function overrideFieldArray($table,$data)
 * 4748:     function compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray)
 * 4794:     function assemblePermissions($string)
 * 4811:     function rmComma($input)
 * 4821:     function convNumEntityToByteValue($input)
 * 4843:     function destPathFromUploadFolder($folder)
 * 4853:     function deleteClause($table)
 * 4869:     function getTCEMAIN_TSconfig($tscPID)
 * 4884:     function getTableEntries($table,$TSconfig)
 * 4897:     function getPID($table,$uid)
 * 4910:     function dbAnalysisStoreExec()
 * 4926:     function removeRegisteredFiles()
 * 4938:     function removeCacheFiles()
 * 4952:     function int_pageTreeInfo($CPtable,$pid,$counter, $rootID)
 * 4973:     function compileAdminTables()
 * 4990:     function fixUniqueInPid($table,$uid)
 * 5026:     function fixCopyAfterDuplFields($table,$uid,$prevUid,$update, $newData=array())
 * 5051:     function extFileFields($table)
 * 5072:     function getUniqueFields($table)
 * 5097:     function isReferenceField($conf)
 * 5112:     function getCopyHeader($table,$pid,$field,$value,$count,$prevTitle='')
 * 5141:     function prependLabel($table)
 * 5158:     function resolvePid($table,$pid)
 * 5188:     function clearPrefixFromValue($table,$value)
 * 5203:     function extFileFunctions($table,$field,$filelist,$func)
 * 5233:     function noRecordsFromUnallowedTables($inList)
 * 5259:     function notifyStageChange($stat,$stageId,$table,$id,$comment)
 * 5354:     function notifyStageChange_getEmails($listOfUsers,$noTablePrefix=FALSE)
 *
 *              SECTION: Clearing cache
 * 5400:     function clear_cache($table,$uid)
 * 5510:     function clear_cacheCmd($cacheCmd)
 *
 *              SECTION: Logging
 * 5616:     function log($table,$recuid,$action,$recpid,$error,$details,$details_nr=-1,$data=array(),$event_pid=-1,$NEWid='')
 * 5633:     function newlog($message, $error=0)
 * 5643:     function printLogErrorMessages($redirect)
 *
 * TOTAL FUNCTIONS: 115
 * (This index is automatically created/updated by the extension "extdeveval")
 *
 */




// *******************************
// Including necessary libraries
// *******************************
require_once (PATH_t3lib.'class.t3lib_loaddbgroup.php');
require_once (PATH_t3lib.'class.t3lib_parsehtml_proc.php');
require_once (PATH_t3lib.'class.t3lib_stdgraphic.php');
require_once (PATH_t3lib.'class.t3lib_basicfilefunc.php');
require_once (PATH_t3lib.'class.t3lib_refindex.php');
require_once (PATH_t3lib.'class.t3lib_flexformtools.php');











/**
 * This is the TYPO3 Core Engine class for manipulation of the database
 * This class is used by eg. the tce_db.php script which provides an the interface for POST forms to this class.
 *
 * Dependencies:
 * - $GLOBALS['TCA'] must exist
 * - $GLOBALS['LANG'] (languageobject) may be preferred, but not fatal.
 *
 * tce_db.php for further comments and SYNTAX! Also see document 'TYPO3 Core API' for details.
 *
 * @author	Kasper Skaarhoj <kasperYYYY@typo3.com>
 * @package TYPO3
 * @subpackage t3lib
 */
class t3lib_TCEmain	{


		// *********************
		// Public variables you can configure before using the class:
		// *********************

	var $storeLogMessages = TRUE;			// Boolean: If true, the default log-messages will be stored. This should not be necessary if the locallang-file for the log-display is properly configured. So disabling this will just save some database-space as the default messages are not saved.
	var $enableLogging = TRUE;				// Boolean: If true, actions are logged to sys_log.
	var $reverseOrder = FALSE;				// Boolean: If true, the datamap array is reversed in the order, which is a nice thing if you're creating a whole new bunch of records.
	var $checkSimilar = TRUE;				// Boolean: If true, only fields which are different from the database values are saved! In fact, if a whole input array is similar, it's not saved then.
	var $stripslashes_values = TRUE;		// Boolean: If true, incoming values in the data-array have their slashes stripped. ALWAYS SET THIS TO ZERO and supply an unescaped data array instead. This switch may totally disappear in future versions of this class!
	var $checkStoredRecords = TRUE;			// Boolean: This will read the record after having updated or inserted it. If anything is not properly submitted an error is written to the log. This feature consumes extra time by selecting records
	var $checkStoredRecords_loose = TRUE;	// Boolean: If set, values '' and 0 will equal each other when the stored records are checked.
	var $deleteTree = FALSE;				// Boolean. If this is set, then a page is deleted by deleting the whole branch under it (user must have deletepermissions to it all). If not set, then the page is deleted ONLY if it has no branch
	var $neverHideAtCopy = FALSE;			// Boolean. If set, then the 'hideAtCopy' flag for tables will be ignored.
	var $dontProcessTransformations = FALSE;	// Boolean: If set, then transformations are NOT performed on the input.
	var $bypassWorkspaceRestrictions = FALSE;	// Boolean: If true, workspace restrictions are bypassed on edit an create actions (process_datamap()). YOU MUST KNOW what you do if you use this feature!

	var $copyWhichTables = '*';				// String. Comma-list. This list of tables decides which tables will be copied. If empty then none will. If '*' then all will (that the user has permission to of course)
	var $generalComment = '';				// General comment, eg. for staging in workspaces.

	var $copyTree = 0;						// Integer. If 0 then branch is NOT copied. If 1 then pages on the 1st level is copied. If 2 then pages on the second level is copied ... and so on

	var $defaultValues = array();			// Array [table][fields]=value: New records are created with default values and you can set this array on the form $defaultValues[$table][$field] = $value to override the default values fetched from TCA. If ->setDefaultsFromUserTS is called UserTSconfig default values will overrule existing values in this array (thus UserTSconfig overrules externally set defaults which overrules TCA defaults)
	var $overrideValues = array();			// Array [table][fields]=value: You can set this array on the form $overrideValues[$table][$field] = $value to override the incoming data. You must set this externally. You must make sure the fields in this array are also found in the table, because it's not checked. All columns can be set by this array!
	var $alternativeFileName = array();		// Array [filename]=alternative_filename: Use this array to force another name onto a file. Eg. if you set ['/tmp/blablabal'] = 'my_file.txt' and '/tmp/blablabal' is set for a certain file-field, then 'my_file.txt' will be used as the name instead.
	var $data_disableFields=array();		// If entries are set in this array corresponding to fields for update, they are ignored and thus NOT updated. You could set this array from a series of checkboxes with value=0 and hidden fields before the checkbox with 1. Then an empty checkbox will disable the field.
	var $suggestedInsertUids=array();		// Use this array to validate suggested uids for tables by setting [table]:[uid]. This is a dangerous option since it will force the inserted record to have a certain UID. The value just have to be true, but if you set it to "DELETE" it will make sure any record with that UID will be deleted first (raw delete). The option is used for import of T3D files when synchronizing between two mirrored servers. As a security measure this feature is available only for Admin Users (for now)

	var $callBackObj;						// Object. Call back object for flex form traversation. Useful when external classes wants to use the iteration functions inside tcemain for traversing a FlexForm structure.




		// *********************
		// Internal variables (mapping arrays) which can be used (read-only) from outside
		// *********************
	var $autoVersionIdMap = Array();			// Contains mapping of auto-versionized records.
	var $substNEWwithIDs = Array();				// When new elements are created, this array contains a map between their "NEW..." string IDs and the eventual UID they got when stored in database
	var $substNEWwithIDs_table = Array();		// Like $substNEWwithIDs, but where each old "NEW..." id is mapped to the table it was from.
	var $copyMappingArray_merged = Array();		// This array is the sum of all copying operations in this class. May be READ from outside, thus partly public.
	var $copiedFileMap = Array();				// A map between input file name and final destination for files being attached to records.
	var	$errorLog = Array();					// Errors are collected in this variable.



		// *********************
		// Internal Variables, do not touch.
		// *********************

		// Variables set in init() function:
	var $BE_USER;		// The user-object the script uses. If not set from outside, this is set to the current global $BE_USER.
	var $userid;		// will be set to uid of be_user executing this script
	var $username;		// will be set to username of be_user executing this script
	var $admin;			// will be set if user is admin

	var $defaultPermissions = array(		// Can be overridden from $TYPO3_CONF_VARS
		'user' => 'show,edit,delete,new,editcontent',
		'group' => 'show,edit,new,editcontent',
		'everybody' => ''
	);

	var $exclude_array;			// The list of <table>-<fields> that cannot be edited by user. This is compiled from TCA/exclude-flag combined with non_exclude_fields for the user.
	var $datamap = Array();		// Set with incoming data array
	var $cmdmap = Array();		// Set with incoming cmd array

		// Internal static:
	var $pMap = Array(		// Permission mapping
		'show' => 1,			// 1st bit
		'edit' => 2,			// 2nd bit
		'delete' => 4,			// 3rd bit
		'new' => 8,				// 4th bit
		'editcontent' => 16		// 5th bit
	);
	var $sortIntervals = 256;					// Integer: The interval between sorting numbers used with tables with a 'sorting' field defined. Min 1

		// Internal caching arrays
	var $recUpdateAccessCache = Array();		// Used by function checkRecordUpdateAccess() to store whether a record is updateable or not.
	var $recInsertAccessCache = Array();		// User by function checkRecordInsertAccess() to store whether a record can be inserted on a page id
	var $isRecordInWebMount_Cache=array();		// Caching array for check of whether records are in a webmount
	var $isInWebMount_Cache=array();			// Caching array for page ids in webmounts
	var $cachedTSconfig = array();				// Caching for collecting TSconfig for page ids
	var $pageCache = Array();					// Used for caching page records in pageInfo()
	var $checkWorkspaceCache = Array();			// Array caching workspace access for BE_USER

		// Other arrays:
	var $dbAnalysisStore=array();				// For accumulation of MM relations that must be written after new records are created.
	var $removeFilesStore=array();				// For accumulation of files which must be deleted after processing of all input content
	var $uploadedFileArray = array();			// Uploaded files, set by process_uploads()
	var $registerDBList=array();				// Used for tracking references that might need correction after operations
	var $copyMappingArray = Array();			// Used by the copy action to track the ids of new pages so subpages are correctly inserted! THIS is internally cleared for each executed copy operation! DO NOT USE THIS FROM OUTSIDE! Read from copyMappingArray_merged instead which is accumulating this information.

		// Various
	var $fileFunc;								// For "singleTon" file-manipulation object
	var $checkValue_currentRecord=array();		// Set to "currentRecord" during checking of values.
	var $autoVersioningUpdate = FALSE;			// A signal flag used to tell file processing that autoversioning has happend and hence certain action should be applied.












	/**
	 * Initializing.
	 * For details, see 'TYPO3 Core API' document.
	 * This function does not start the processing of data, but merely initializes the object
	 *
	 * @param	array		Data to be modified or inserted in the database
	 * @param	array		Commands to copy, move, delete, localize, versionize records.
	 * @param	object		An alternative userobject you can set instead of the default, which is $GLOBALS['BE_USER']
	 * @return	void
	 */
	function start($data,$cmd,$altUserObject='')	{

			// Initializing BE_USER
		$this->BE_USER = is_object($altUserObject) ? $altUserObject : $GLOBALS['BE_USER'];
		$this->userid = $this->BE_USER->user['uid'];
		$this->username = $this->BE_USER->user['username'];
		$this->admin = $this->BE_USER->user['admin'];

		if ($GLOBALS['BE_USER']->uc['recursiveDelete'])    {
			$this->deleteTree = 1;
		}

			// Initializing default permissions for pages
		$defaultPermissions = $GLOBALS['TYPO3_CONF_VARS']['BE']['defaultPermissions'];
		if (isset($defaultPermissions['user']))		{$this->defaultPermissions['user'] = $defaultPermissions['user'];}
		if (isset($defaultPermissions['group']))		{$this->defaultPermissions['group'] = $defaultPermissions['group'];}
		if (isset($defaultPermissions['everybody']))		{$this->defaultPermissions['everybody'] = $defaultPermissions['everybody'];}

			// generates the excludelist, based on TCA/exclude-flag and non_exclude_fields for the user:
		$this->exclude_array = $this->admin ? array() : $this->getExcludeListArray();

			// Setting the data and cmd arrays
		if (is_array($data)) {
			reset($data);
			$this->datamap = $data;
		}
		if (is_array($cmd))	{
			reset($cmd);
			$this->cmdmap = $cmd;
		}
	}

	/**
	 * Function that can mirror input values in datamap-array to other uid numbers.
	 * Example: $mirror[table][11] = '22,33' will look for content in $this->datamap[table][11] and copy it to $this->datamap[table][22] and $this->datamap[table][33]
	 *
	 * @param	array		This array has the syntax $mirror[table_name][uid] = [list of uids to copy data-value TO!]
	 * @return	void
	 */
	function setMirror($mirror)	{
		if (is_array($mirror))	{
			reset($mirror);
			while(list($table,$uid_array)=each($mirror))	{
				if (isset($this->datamap[$table]))	{
					reset($uid_array);
					while (list($id,$uidList) = each($uid_array))	{
						if (isset($this->datamap[$table][$id]))	{
							$theIdsInArray = t3lib_div::trimExplode(',',$uidList,1);
							while(list(,$copyToUid)=each($theIdsInArray))	{
								$this->datamap[$table][$copyToUid] = $this->datamap[$table][$id];
							}
						}
					}
				}
			}
		}
	}

	/**
	 * Initializes default values coming from User TSconfig
	 *
	 * @param	array		User TSconfig array
	 * @return	void
	 */
	function setDefaultsFromUserTS($userTS)	{
		global $TCA;
		if (is_array($userTS))	{
			foreach($userTS as $k => $v)	{
				$k = substr($k,0,-1);
				if ($k && is_array($v) && isset($TCA[$k]))	{
					if (is_array($this->defaultValues[$k]))	{
						$this->defaultValues[$k] = array_merge($this->defaultValues[$k],$v);
					} else {
						$this->defaultValues[$k] = $v;
					}
				}
			}
		}
	}

	/**
	 * Processing of uploaded files.
	 * It turns out that some versions of PHP arranges submitted data for files different if sent in an array. This function will unify this so the internal array $this->uploadedFileArray will always contain files arranged in the same structure.
	 *
	 * @param	array		$_FILES array
	 * @return	void
	 */
	function process_uploads($postFiles)	{

		if (is_array($postFiles))	{

				// Editing frozen:
			if ($this->BE_USER->workspace!==0 && $this->BE_USER->workspaceRec['freeze'])	{
				$this->newlog('All editing in this workspace has been frozen!',1);
				return FALSE;
			}

			reset($postFiles);
			$subA = current($postFiles);
			if (is_array($subA))	{
				if (is_array($subA['name']) && is_array($subA['type']) && is_array($subA['tmp_name']) && is_array($subA['size']))	{
						// Initialize the uploadedFilesArray:
					$this->uploadedFileArray=array();

						// For each entry:
					foreach($subA as $key => $values)	{
						$this->process_uploads_traverseArray($this->uploadedFileArray,$values,$key);
					}
				} else {
					$this->uploadedFileArray=$subA;
				}
			}
		}
	}

	/**
	 * Traverse the upload array if needed to rearrange values.
	 *
	 * @param	array		$this->uploadedFileArray passed by reference
	 * @param	array		Input array  ($_FILES parts)
	 * @param	string		The current $_FILES array key to set on the outermost level.
	 * @return	void
	 * @access private
	 * @see process_uploads()
	 */
	function process_uploads_traverseArray(&$outputArr,$inputArr,$keyToSet)	{
		if (is_array($inputArr))	{
			foreach($inputArr as $key => $value)	{
				$this->process_uploads_traverseArray($outputArr[$key],$inputArr[$key],$keyToSet);
			}
		} else {
			$outputArr[$keyToSet]=$inputArr;
		}
	}















	/*********************************************
	 *
	 * PROCESSING DATA
	 *
	 *********************************************/

	/**
	 * Processing the data-array
	 * Call this function to process the data-array set by start()
	 *
	 * @return	void
	 */
	function process_datamap() {
		global $TCA, $TYPO3_CONF_VARS;

			// Editing frozen:
		if ($this->BE_USER->workspace!==0 && $this->BE_USER->workspaceRec['freeze'])	{
			$this->newlog('All editing in this workspace has been frozen!',1);
			return FALSE;
		}

			// First prepare user defined objects (if any) for hooks which extend this function:
		$hookObjectsArr = array();
		if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'])) {
			foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processDatamapClass'] as $classRef) {
				$hookObjectsArr[] = &t3lib_div::getUserObj($classRef);
			}
		}

			// Organize tables so that the pages-table is always processed first. This is required if you want to make sure that content pointing to a new page will be created.
		$orderOfTables = Array();
		if (isset($this->datamap['pages']))	{		// Set pages first.
			$orderOfTables[]='pages';
		}
		reset($this->datamap);
		while (list($table,) = each($this->datamap))	{
			if ($table!='pages')	{
				$orderOfTables[]=$table;
			}
		}

			// Process the tables...
		foreach($orderOfTables as $table)	{
				/* Check if
					- table is set in $TCA,
					- table is NOT readOnly
					- the table is set with content in the data-array (if not, there's nothing to process...)
					- permissions for tableaccess OK
				*/
			$modifyAccessList = $this->checkModifyAccessList($table);
			if (!$modifyAccessList)	{
				$id = 0;
				$this->log($table,$id,2,0,1,"Attempt to modify table '%s' without permission",1,array($table));
			}
			if (isset($TCA[$table]) && !$this->tableReadOnly($table) && is_array($this->datamap[$table]) && $modifyAccessList)	{
				if ($this->reverseOrder)	{
					$this->datamap[$table] = array_reverse($this->datamap[$table], 1);
				}

					// For each record from the table, do:
					// $id is the record uid, may be a string if new records...
					// $incomingFieldArray is the array of fields
				foreach($this->datamap[$table] as $id => $incomingFieldArray)	{
					if (is_array($incomingFieldArray))	{

							// Hook: processDatamap_preProcessIncomingFieldArray
						foreach($hookObjectsArr as $hookObj)	{
							if (method_exists($hookObj, 'processDatamap_preProcessFieldArray')) {
								$hookObj->processDatamap_preProcessFieldArray($incomingFieldArray, $table, $id, $this);
							}
						}

							// ******************************
							// Checking access to the record
							// ******************************
						$createNewVersion = FALSE;
						$recordAccess = FALSE;
						$old_pid_value = '';
						$resetRejected = FALSE;
						$this->autoVersioningUpdate = FALSE;

						if (!t3lib_div::testInt($id)) {               // Is it a new record? (Then Id is a string)
							$fieldArray = $this->newFieldArray($table);	// Get a fieldArray with default values
							if (isset($incomingFieldArray['pid']))	{	// A pid must be set for new records.
									// $value = the pid
		 						$pid_value = $incomingFieldArray['pid'];

									// Checking and finding numerical pid, it may be a string-reference to another value
								$OK = 1;
								if (strstr($pid_value,'NEW'))	{	// If a NEW... id
									if (substr($pid_value,0,1)=='-') {$negFlag=-1;$pid_value=substr($pid_value,1);} else {$negFlag=1;}
									if (isset($this->substNEWwithIDs[$pid_value]))	{	// Trying to find the correct numerical value as it should be mapped by earlier processing of another new record.
										$old_pid_value = $pid_value;
										$pid_value=intval($negFlag*$this->substNEWwithIDs[$pid_value]);
									} else {$OK = 0;}	// If not found in the substArray we must stop the process...
								} elseif ($pid_value>=0 && $this->BE_USER->workspace!==0 && $TCA[$table]['ctrl']['versioning_followPages'])	{	// PID points to page, the workspace is an offline space and the table follows page during versioning: This means we must check if the PID page has a version in the workspace with swapmode set to 0 (zero = page+content) and if so, change the pid to the uid of that version.
									if ($WSdestPage = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, 'pages', $pid_value, 'uid,t3ver_swapmode'))	{	// Looks for workspace version of page.
										if ($WSdestPage['t3ver_swapmode']==0)	{	// if swapmode is zero, then change pid value.
											$pid_value = $WSdestPage['uid'];
										}
									}
								}
								$pid_value = intval($pid_value);

									// The $pid_value is now the numerical pid at this point
								if ($OK)	{
									$sortRow = $TCA[$table]['ctrl']['sortby'];
									if ($pid_value>=0)	{	// Points to a page on which to insert the element, possibly in the top of the page
										if ($sortRow)	{	// If this table is sorted we better find the top sorting number
											$fieldArray[$sortRow] = $this->getSortNumber($table,0,$pid_value);
										}
										$fieldArray['pid'] = $pid_value;	// The numerical pid is inserted in the data array
									} else {	// points to another record before ifself
										if ($sortRow)	{	// If this table is sorted we better find the top sorting number
											$tempArray=$this->getSortNumber($table,0,$pid_value);	// Because $pid_value is < 0, getSortNumber returns an array
											$fieldArray['pid'] = $tempArray['pid'];
											$fieldArray[$sortRow] = $tempArray['sortNumber'];
										} else {	// Here we fetch the PID of the record that we point to...
											$tempdata = $this->recordInfo($table,abs($pid_value),'pid');
											$fieldArray['pid']=$tempdata['pid'];
										}
									}
								}
							}
							$theRealPid = $fieldArray['pid'];

								// Now, check if we may insert records on this pid.
							if ($theRealPid>=0)	{
								$recordAccess = $this->checkRecordInsertAccess($table,$theRealPid);		// Checks if records can be inserted on this $pid.
								if ($recordAccess)	{
									$this->addDefaultPermittedLanguageIfNotSet($table,$incomingFieldArray);
									$recordAccess = $this->BE_USER->recordEditAccessInternals($table,$incomingFieldArray,TRUE);
									if (!$recordAccess)		{
										$this->newlog("recordEditAccessInternals() check failed. [".$this->BE_USER->errorMsg."]",1);
									} elseif(!$this->bypassWorkspaceRestrictions)	{
											// Workspace related processing:
										if ($res = $this->BE_USER->workspaceAllowLiveRecordsInPID($theRealPid,$table))	{	// If LIVE records cannot be created in the current PID due to workspace restrictions, prepare creation of placeholder-record
											if ($res<0)	{
												$recordAccess = FALSE;
												$this->newlog('Stage for versioning root point and users access level did not allow for editing',1);
											}
										} else {	// So, if no live records were allowed, we have to create a new version of this record:
											if ($TCA[$table]['ctrl']['versioningWS'])	{
												$createNewVersion = TRUE;
											} else {
												$recordAccess = FALSE;
												$this->newlog('Record could not be created in this workspace in this branch',1);
											}
										}
									}
								}
							} else {
								debug('Internal ERROR: pid should not be less than zero!');
							}
							$status = 'new';						// Yes new record, change $record_status to 'insert'
						} else {	// Nope... $id is a number
							$fieldArray = array();
							$recordAccess = $this->checkRecordUpdateAccess($table,$id);
							if (!$recordAccess)		{
								$propArr = $this->getRecordProperties($table,$id);
								$this->log($table,$id,2,0,1,"Attempt to modify record '%s' (%s) without permission. Or non-existing page.",2,array($propArr['header'],$table.':'.$id),$propArr['event_pid']);
							} else {	// Next check of the record permissions (internals)
								$recordAccess = $this->BE_USER->recordEditAccessInternals($table,$id);
								if (!$recordAccess)		{
									$propArr = $this->getRecordProperties($table,$id);
									$this->newlog("recordEditAccessInternals() check failed. [".$this->BE_USER->errorMsg."]",1);
								} else {	// Here we fetch the PID of the record that we point to...
									$tempdata = $this->recordInfo($table,$id,'pid'.($TCA[$table]['ctrl']['versioningWS']?',t3ver_wsid,t3ver_stage':''));
									$theRealPid = $tempdata['pid'];

										// Prepare the reset of the rejected flag if set:
									if ($TCA[$table]['ctrl']['versioningWS'] && $tempdata['t3ver_stage']<0)	{
										$resetRejected = TRUE;
									}

										// Checking access in case of offline workspace:
									if (!$this->bypassWorkspaceRestrictions && $errorCode = $this->BE_USER->workspaceCannotEditRecord($table,$tempdata))	{
										$recordAccess = FALSE;		// Versioning is required and it must be offline version!

											// Auto-creation of version: In offline workspace, test if versioning is enabled and look for workspace version of input record. If there is no versionized record found we will create one and save to that.
										if ($this->BE_USER->workspaceAllowAutoCreation($table,$id,$theRealPid))	{
											$tce = t3lib_div::makeInstance('t3lib_TCEmain');
											$tce->stripslashes_values = 0;

												// Setting up command for creating a new version of the record:
											$cmd = array();
											$cmd[$table][$id]['version'] = array(
												'action' => 'new',
												'treeLevels' => -1,	// Default is to create a version of the individual records...
												'label' => 'Auto-created for WS #'.$this->BE_USER->workspace
											);
											$tce->start(array(),$cmd);
											$tce->process_cmdmap();
											$this->errorLog = array_merge($this->errorLog,$tce->errorLog);

											if ($tce->copyMappingArray[$table][$id])	{
												$this->uploadedFileArray[$table][$tce->copyMappingArray[$table][$id]] = $this->uploadedFileArray[$table][$id];
												$id = $this->autoVersionIdMap[$table][$id] = $tce->copyMappingArray[$table][$id];
												$recordAccess = TRUE;
												$this->autoVersioningUpdate = TRUE;
											} else $this->newlog("Could not be edited in offline workspace in the branch where found (failure state: '".$errorCode."'). Auto-creation of version failed!",1);
										} else $this->newlog("Could not be edited in offline workspace in the branch where found (failure state: '".$errorCode."'). Auto-creation of version not allowed in workspace!",1);
									}
								}
							}
							$status = 'update';	// the default is 'update'
						}

							// If access was granted above, proceed to create or update record:
						if ($recordAccess)	{

							list($tscPID) = t3lib_BEfunc::getTSCpid($table,$id,$old_pid_value ? $old_pid_value : $fieldArray['pid']);	// Here the "pid" is set IF NOT the old pid was a string pointing to a place in the subst-id array.
							$TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
							if ($status=='new' && $table=='pages' && is_array($TSConfig['permissions.']))	{
								$fieldArray = $this->setTSconfigPermissions($fieldArray,$TSConfig['permissions.']);
							}
							if ($createNewVersion)	{
								$newVersion_placeholderFieldArray = $fieldArray;
							}

								// Processing of all fields in incomingFieldArray and setting them in $fieldArray
							$fieldArray = $this->fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$theRealPid,$status,$tscPID);

								// NOTICE! All manipulation beyond this point bypasses both "excludeFields" AND possible "MM" relations / file uploads to field!

								// Forcing some values unto field array:
							$fieldArray = $this->overrideFieldArray($table,$fieldArray);	// NOTICE: This overriding is potentially dangerous; permissions per field is not checked!!!
							if ($createNewVersion)	{
								$newVersion_placeholderFieldArray = $this->overrideFieldArray($table,$newVersion_placeholderFieldArray);
							}

								// Setting system fields
							if ($status=='new')	{
								if ($TCA[$table]['ctrl']['crdate'])	{
									$fieldArray[$TCA[$table]['ctrl']['crdate']]=time();
									if ($createNewVersion)	$newVersion_placeholderFieldArray[$TCA[$table]['ctrl']['crdate']]=time();
								}
								if ($TCA[$table]['ctrl']['cruser_id'])	{
									$fieldArray[$TCA[$table]['ctrl']['cruser_id']]=$this->userid;
									if ($createNewVersion)	$newVersion_placeholderFieldArray[$TCA[$table]['ctrl']['cruser_id']]=$this->userid;
								}
							} elseif ($this->checkSimilar) {	// Removing fields which are equal to the current value:
								$fieldArray = $this->compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray);
							}
							if ($TCA[$table]['ctrl']['tstamp'] && count($fieldArray))	{
								$fieldArray[$TCA[$table]['ctrl']['tstamp']]=time();
								if ($createNewVersion)	$newVersion_placeholderFieldArray[$TCA[$table]['ctrl']['tstamp']]=time();
							}
							if ($resetRejected)	{
								$fieldArray['t3ver_stage'] = 0;
							}

								// Hook: processDatamap_postProcessFieldArray
							foreach($hookObjectsArr as $hookObj)	{
								if (method_exists($hookObj, 'processDatamap_postProcessFieldArray')) {
									$hookObj->processDatamap_postProcessFieldArray($status, $table, $id, $fieldArray, $this);
								}
							}

								// Performing insert/update. If fieldArray has been unset by some userfunction (see hook above), don't do anything
								// Kasper: Unsetting the fieldArray is dangerous; MM relations might be saved already and files could have been uploaded that are now "lost"
							if (is_array($fieldArray)) {
								if ($status=='new')	{
									if ($createNewVersion)	{	// This creates a new version of the record with online placeholder and offline version
										$versioningType = $table==='pages' ? $this->BE_USER->workspaceVersioningTypeGetClosest(t3lib_div::intInRange($TYPO3_CONF_VARS['BE']['newPagesVersioningType'],-1,1)) : -1;
										if ($this->BE_USER->workspaceVersioningTypeAccess($versioningType))	{
											$newVersion_placeholderFieldArray['t3ver_label'] = 'INITIAL PLACEHOLDER';
											$newVersion_placeholderFieldArray['t3ver_state'] = 1;	// Setting placeholder state value for temporary record
											$newVersion_placeholderFieldArray['t3ver_wsid'] = $this->BE_USER->workspace;	// Setting workspace - only so display of place holders can filter out those from other workspaces.
											$newVersion_placeholderFieldArray[$TCA[$table]['ctrl']['label']] = '[PLACEHOLDER, WS#'.$this->BE_USER->workspace.']';
											$this->insertDB($table,$id,$newVersion_placeholderFieldArray,FALSE);	// Saving placeholder as 'original'

												// For the actual new offline version, set versioning values to point to placeholder:
											$fieldArray['pid'] = -1;
											$fieldArray['t3ver_oid'] = $this->substNEWwithIDs[$id];
											$fieldArray['t3ver_id'] = 1;
											$fieldArray['t3ver_state'] = -1;	// Setting placeholder state value for version (so it can know it is currently a new version...)
											$fieldArray['t3ver_label'] = 'First draft version';
											$fieldArray['t3ver_wsid'] = $this->BE_USER->workspace;
											if ($table==='pages') {		// Swap mode set to "branch" so we can build branches for pages.
												$fieldArray['t3ver_swapmode'] = $versioningType;
											}
											$phShadowId = $this->insertDB($table,$id,$fieldArray,TRUE,0,TRUE);	// When inserted, $this->substNEWwithIDs[$id] will be changed to the uid of THIS version and so the interface will pick it up just nice!
											if ($phShadowId)	{
												$this->placeholderShadowing($table,$phShadowId);
											}
										} else $this->newlog('Versioning type "'.$versioningType.'" was not allowed, so could not create new record.',1);
									} else {
										$this->insertDB($table,$id,$fieldArray,FALSE,$incomingFieldArray['uid']);
									}
								} else {
									$this->updateDB($table,$id,$fieldArray);
									$this->placeholderShadowing($table,$id);
								}
							}

								// Hook: processDatamap_afterDatabaseOperations
							foreach($hookObjectsArr as $hookObj)	{
								if (method_exists($hookObj, 'processDatamap_afterDatabaseOperations')) {
									$hookObj->processDatamap_afterDatabaseOperations($status, $table, $id, $fieldArray, $this);
								}
							}
						}	// if ($recordAccess)	{
					}	// if (is_array($incomingFieldArray))	{
				}
			}
		}
		$this->dbAnalysisStoreExec();
		$this->removeRegisteredFiles();
	}

	/**
	 * Fix shadowing of data in case we are editing a offline version of a live "New" placeholder record:
	 *
	 * @param	string		Table name
	 * @param	integer		Record uid
	 * @return	void
	 */
	function placeholderShadowing($table,$id)	{
		global $TCA;

		if ($liveRec = t3lib_BEfunc::getLiveVersionOfRecord($table,$id,'*'))	{
			if ((int)$liveRec['t3ver_state']===1)	{
				$justStoredRecord = t3lib_BEfunc::getRecord($table,$id);
				$newRecord = array();

				$shadowColumns = t3lib_div::trimExplode(',', $TCA[$table]['ctrl']['shadowColumnsForNewPlaceholders'],1);
				foreach($shadowColumns as $fieldName)	{
					if (strcmp($justStoredRecord[$fieldName],$liveRec[$fieldName]))	{
						$newRecord[$fieldName] = $justStoredRecord[$fieldName];
					}
				}

				if (count($newRecord))	{
					$this->newlog('Shadowing done on fields '.implode(',',array_keys($newRecord)).' in Placeholder record '.$table.':'.$liveRec['uid'].' (offline version UID='.$id.')');
					$this->updateDB($table,$liveRec['uid'],$newRecord);
				}
			}
		}
	}

	/**
	 * Filling in the field array
	 * $this->exclude_array is used to filter fields if needed.
	 *
	 * @param	string		Table name
	 * @param	[type]		$id: ...
	 * @param	array		Default values, Preset $fieldArray with 'pid' maybe (pid and uid will be not be overridden anyway)
	 * @param	array		$incomingFieldArray is which fields/values you want to set. There are processed and put into $fieldArray if OK
	 * @param	integer		The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted.
	 * @param	string		$status = 'new' or 'update'
	 * @param	[type]		$tscPID: ...
	 * @return	[type]		...
	 */
	function fillInFieldArray($table,$id,$fieldArray,$incomingFieldArray,$realPid,$status,$tscPID)	{
		global $TCA;

			// Initialize:
		t3lib_div::loadTCA($table);
		$originalLanguageRecord = NULL;
		$originalLanguage_diffStorage = NULL;
		$diffStorageFlag = FALSE;

			// Setting 'currentRecord' and 'checkValueRecord':
		if (strstr($id,'NEW'))	{
			$currentRecord = $checkValueRecord = $fieldArray;	// must have the 'current' array - not the values after processing below...

				// IF $incomingFieldArray is an array, overlay it.
				// The point is that when new records are created as copies with flex type fields there might be a field containing information about which DataStructure to use and without that information the flexforms cannot be correctly processed.... This should be OK since the $checkValueRecord is used by the flexform evaluation only anyways...
			if (is_array($incomingFieldArray) && is_array($checkValueRecord))	{
				$checkValueRecord = t3lib_div::array_merge_recursive_overrule($checkValueRecord, $incomingFieldArray);
			}
		} else {
			$currentRecord = $checkValueRecord = $this->recordInfo($table,$id,'*');	// We must use the current values as basis for this!

				// Get original language record if available:
			if (is_array($currentRecord)
					&& $TCA[$table]['ctrl']['transOrigDiffSourceField']
					&& $TCA[$table]['ctrl']['languageField']
					&& $currentRecord[$TCA[$table]['ctrl']['languageField']] > 0
					&& $TCA[$table]['ctrl']['transOrigPointerField']
					&& intval($currentRecord[$TCA[$table]['ctrl']['transOrigPointerField']]) > 0)	{

				$lookUpTable = $TCA[$table]['ctrl']['transOrigPointerTable'] ? $TCA[$table]['ctrl']['transOrigPointerTable'] : $table;
				$originalLanguageRecord = $this->recordInfo($lookUpTable,$currentRecord[$TCA[$table]['ctrl']['transOrigPointerField']],'*');
				t3lib_BEfunc::workspaceOL($lookUpTable,$originalLanguageRecord);
				$originalLanguage_diffStorage = unserialize($currentRecord[$TCA[$table]['ctrl']['transOrigDiffSourceField']]);
			}
		}
		$this->checkValue_currentRecord = $checkValueRecord;

			/*
				In the following all incoming value-fields are tested:
				- Are the user allowed to change the field?
				- Is the field uid/pid (which are already set)
				- perms-fields for pages-table, then do special things...
				- If the field is nothing of the above and the field is configured in TCA, the fieldvalues are evaluated by ->checkValue

				If everything is OK, the field is entered into $fieldArray[]
			*/
		foreach($incomingFieldArray as $field => $fieldValue)	{
			if (!in_array($table.'-'.$field, $this->exclude_array) && !$this->data_disableFields[$table][$id][$field])	{	// The field must be editable.

					// Checking if a value for language can be changed:
				$languageDeny = $TCA[$table]['ctrl']['languageField'] && !strcmp($TCA[$table]['ctrl']['languageField'], $field) && !$this->BE_USER->checkLanguageAccess($fieldValue);

				if (!$languageDeny)	{
						// Stripping slashes - will probably be removed the day $this->stripslashes_values is removed as an option...
					if ($this->stripslashes_values)	{
						if (is_array($fieldValue))	{
							t3lib_div::stripSlashesOnArray($fieldValue);
						} else $fieldValue = stripslashes($fieldValue);
					}

					switch ($field)	{
						case 'uid':
						case 'pid':
							// Nothing happens, already set
						break;
						case 'perms_userid':
						case 'perms_groupid':
						case 'perms_user':
						case 'perms_group':
						case 'perms_everybody':
								// Permissions can be edited by the owner or the administrator
							if ($table=='pages' && ($this->admin || $status=='new' || $this->pageInfo($id,'perms_userid')==$this->userid) )	{
								$value=intval($fieldValue);
								switch($field)	{
									case 'perms_userid':
										$fieldArray[$field]=$value;
									break;
									case 'perms_groupid':
										$fieldArray[$field]=$value;
									break;
									default:
										if ($value>=0 && $value<pow(2,5))	{
											$fieldArray[$field]=$value;
										}
									break;
								}
							}
						break;
						case 't3ver_oid':
						case 't3ver_id':
						case 't3ver_wsid':
						case 't3ver_state':
						case 't3ver_swapmode':
						case 't3ver_count':
						case 't3ver_stage':
						case 't3ver_tstamp':
							// t3ver_label is not here because it CAN be edited as a regular field!
						break;
						default:
							if (isset($TCA[$table]['columns'][$field]))	{
									// Evaluating the value.
								$res = $this->checkValue($table,$field,$fieldValue,$id,$status,$realPid,$tscPID);
								if (isset($res['value']))	{
									$fieldArray[$field]=$res['value'];

										// Add the value of the original record to the diff-storage content:
									if ($TCA[$table]['ctrl']['transOrigDiffSourceField'])	{
										$originalLanguage_diffStorage[$field] = $originalLanguageRecord[$field];
										$diffStorageFlag = TRUE;
									}
								}
							} elseif ($TCA[$table]['ctrl']['origUid']===$field) {	// Allow value for original UID to pass by...
								$fieldArray[$field] = $fieldValue;
							}
						break;
					}
				}	// Checking language.
			}	// Check exclude fields / disabled fields...
		}

			// Add diff-storage information:
		if ($diffStorageFlag && !isset($fieldArray[$TCA[$table]['ctrl']['transOrigDiffSourceField']]))	{	// If the field is set it would probably be because of an undo-operation - in which case we should not update the field of course...
			 $fieldArray[$TCA[$table]['ctrl']['transOrigDiffSourceField']] = serialize($originalLanguage_diffStorage);
		}

			// Checking for RTE-transformations of fields:
		$types_fieldConfig = t3lib_BEfunc::getTCAtypes($table,$currentRecord);
		$theTypeString = t3lib_BEfunc::getTCAtypeValue($table,$currentRecord);
		if (is_array($types_fieldConfig))	{
			reset($types_fieldConfig);
			while(list(,$vconf) = each($types_fieldConfig))	{
					// Write file configuration:
				$eFile = t3lib_parsehtml_proc::evalWriteFile($vconf['spec']['static_write'],array_merge($currentRecord,$fieldArray));	// inserted array_merge($currentRecord,$fieldArray) 170502

					// RTE transformations:
				if (!$this->dontProcessTransformations)	{
					if (isset($fieldArray[$vconf['field']]))	{
							// Look for transformation flag:
						switch((string)$incomingFieldArray['_TRANSFORM_'.$vconf['field']])	{
							case 'RTE':
								$RTEsetup = $this->BE_USER->getTSConfig('RTE',t3lib_BEfunc::getPagesTSconfig($tscPID));
								$thisConfig = t3lib_BEfunc::RTEsetup($RTEsetup['properties'],$table,$vconf['field'],$theTypeString);

									// Set alternative relative path for RTE images/links:
								$RTErelPath = is_array($eFile) ? dirname($eFile['relEditFile']) : '';

									// Get RTE object, draw form and set flag:
								$RTEobj = &t3lib_BEfunc::RTEgetObj();
								if (is_object($RTEobj))	{
									$fieldArray[$vconf['field']] = $RTEobj->transformContent('db',$fieldArray[$vconf['field']],$table,$vconf['field'],$currentRecord,$vconf['spec'],$thisConfig,$RTErelPath,$currentRecord['pid']);
								} else {
									debug('NO RTE OBJECT FOUND!');
								}
							break;
						}
					}
				}

					// Write file configuration:
				if (is_array($eFile))	{
					$mixedRec = array_merge($currentRecord,$fieldArray);
					$SW_fileContent = t3lib_div::getUrl($eFile['editFile']);
					$parseHTML = t3lib_div::makeInstance('t3lib_parsehtml_proc');
					$parseHTML->init('','');

					$eFileMarker = $eFile['markerField']&&trim($mixedRec[$eFile['markerField']]) ? trim($mixedRec[$eFile['markerField']]) : '###TYPO3_STATICFILE_EDIT###';
					$insertContent = str_replace($eFileMarker,'',$mixedRec[$eFile['contentField']]);	// must replace the marker if present in content!

					$SW_fileNewContent = $parseHTML->substituteSubpart($SW_fileContent, $eFileMarker, chr(10).$insertContent.chr(10), 1, 1);
					t3lib_div::writeFile($eFile['editFile'],$SW_fileNewContent);

						// Write status:
					if (!strstr($id,'NEW') && $eFile['statusField'])	{
						$GLOBALS['TYPO3_DB']->exec_UPDATEquery(
							$table,
							'uid='.intval($id),
							array(
								$eFile['statusField'] => $eFile['relEditFile'].' updated '.date('d-m-Y H:i:s').', bytes '.strlen($mixedRec[$eFile['contentField']])
							)
						);
					}
				} elseif ($eFile && is_string($eFile))	{
					$this->log($table,$id,2,0,1,"Write-file error: '%s'",13,array($eFile),$realPid);
				}
			}
		}
			// Return fieldArray
		return $fieldArray;
	}












	/*********************************************
	 *
	 * Evaluation of input values
	 *
	 ********************************************/

	/**
	 * Evaluates a value according to $table/$field settings.
	 * This function is for real database fields - NOT FlexForm "pseudo" fields.
	 * NOTICE: Calling this function expects this: 1) That the data is saved! (files are copied and so on) 2) That files registered for deletion IS deleted at the end (with ->removeRegisteredFiles() )
	 *
	 * @param	string		Table name
	 * @param	string		Field name
	 * @param	string		Value to be evaluated. Notice, this is the INPUT value from the form. The original value (from any existing record) must be manually looked up inside the function if needed - or taken from $currentRecord array.
	 * @param	string		The record-uid, mainly - but not exclusively - used for logging
	 * @param	string		'update' or 'new' flag
	 * @param	integer		The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
	 * @param	integer		$tscPID
	 * @return	array		Returns the evaluated $value as key "value" in this array. Can be checked with isset($res['value']) ...
	 */
	function checkValue($table,$field,$value,$id,$status,$realPid,$tscPID)	{
		global $TCA, $PAGES_TYPES;
		t3lib_div::loadTCA($table);

		$res = Array();	// result array
		$recFID = $table.':'.$id.':'.$field;

			// Processing special case of field pages.doktype
		if ($table=='pages' && $field=='doktype')	{
				// If the user may not use this specific doktype, we issue a warning
			if (! ($this->admin || t3lib_div::inList($this->BE_USER->groupData['pagetypes_select'],$value)))	{
				$propArr = $this->getRecordProperties($table,$id);
				$this->log($table,$id,5,0,1,"You cannot change the 'doktype' of page '%s' to the desired value.",1,array($propArr['header']),$propArr['event_pid']);
				return $res;
			};
			if ($status=='update')	{
					// This checks 1) if we should check for disallowed tables and 2) if there are records from disallowed tables on the current page
				$onlyAllowedTables = isset($PAGES_TYPES[$value]['onlyAllowedTables']) ? $PAGES_TYPES[$value]['onlyAllowedTables'] : $PAGES_TYPES['default']['onlyAllowedTables'];
				if ($onlyAllowedTables)	{
					$theWrongTables = $this->doesPageHaveUnallowedTables($id,$value);
					if ($theWrongTables)	{
						$propArr = $this->getRecordProperties($table,$id);
						$this->log($table,$id,5,0,1,"'doktype' of page '%s' could not be changed because the page contains records from disallowed tables; %s",2,array($propArr['header'],$theWrongTables),$propArr['event_pid']);
						return $res;
					}
				}
			}
		}

			// Get current value:
		$curValueRec = $this->recordInfo($table,$id,$field);
		$curValue = $curValueRec[$field];

			// Getting config for the field
		$tcaFieldConf = $TCA[$table]['columns'][$field]['config'];

			// Preform processing:
		$res = $this->checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$this->uploadedFileArray[$table][$id][$field],$tscPID);

		return $res;
	}

	/**
	 * Branches out evaluation of a field value based on its type as configured in TCA
	 * Can be called for FlexForm pseudo fields as well, BUT must not have $field set if so.
	 *
	 * @param	array		The result array. The processed value (if any!) is set in the "value" key.
	 * @param	string		The value to set.
	 * @param	array		Field configuration from TCA
	 * @param	string		Table name
	 * @param	integer		Return UID
	 * @param	[type]		$curValue: ...
	 * @param	[type]		$status: ...
	 * @param	integer		The real PID value of the record. For updates, this is just the pid of the record. For new records this is the PID of the page where it is inserted. If $realPid is -1 it means that a new version of the record is being inserted.
	 * @param	[type]		$recFID: ...
	 * @param	string		Field name. Must NOT be set if the call is for a flexform field (since flexforms are not allowed within flexforms).
	 * @param	[type]		$uploadedFiles: ...
	 * @param	[type]		$tscPID: ...
	 * @return	array		Returns the evaluated $value as key "value" in this array.
	 */
	function checkValue_SW($res,$value,$tcaFieldConf,$table,$id,$curValue,$status,$realPid,$recFID,$field,$uploadedFiles,$tscPID)	{

		$PP = array($table,$id,$curValue,$status,$realPid,$recFID,$tscPID);

		switch ($tcaFieldConf['type']) {
			case 'text':
			case 'passthrough':
			case 'user':
				$res['value'] = $value;
			break;
			case 'input':
				$res = $this->checkValue_input($res,$value,$tcaFieldConf,$PP,$field);
			break;
			case 'check':
				$res = $this->checkValue_check($res,$value,$tcaFieldConf,$PP);
			break;
			case 'radio':
				$res = $this->checkValue_radio($res,$value,$tcaFieldConf,$PP);
			break;
			case 'group':
			case 'select':
				$res = $this->checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field);
			break;
			case 'flex':
				if ($field)	{	// FlexForms are only allowed for real fields.
					$res = $this->checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field);
				}
			break;
			default:
				#debug(array($tcaFieldConf,$res,$value),'NON existing field type:');
			break;
		}

		return $res;
	}

	/**
	 * Evaluate "input" type values.
	 *
	 * @param	array		The result array. The processed value (if any!) is set in the "value" key.
	 * @param	string		The value to set.
	 * @param	array		Field configuration from TCA
	 * @param	array		Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
	 * @param	string		Field name
	 * @return	array		Modified $res array
	 */
	function checkValue_input($res,$value,$tcaFieldConf,$PP,$field='')	{
		list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;

			// Secures the string-length to be less than max. Will probably make problems with multi-byte strings!
		if (intval($tcaFieldConf['max'])>0)	{$value = substr($value,0,intval($tcaFieldConf['max']));}

			// Checking range of value:
		if ($tcaFieldConf['range'] && $value!=$tcaFieldConf['checkbox'])	{	// If value is not set to the allowed checkbox-value then it is checked against the ranges
			if (isset($tcaFieldConf['range']['upper'])&&$value>$tcaFieldConf['range']['upper'])	{$value=$tcaFieldConf['range']['upper'];}
			if (isset($tcaFieldConf['range']['lower'])&&$value<$tcaFieldConf['range']['lower'])	{$value=$tcaFieldConf['range']['lower'];}
		}

			// Process evaluation settings:
		$evalCodesArray = t3lib_div::trimExplode(',',$tcaFieldConf['eval'],1);
		$res = $this->checkValue_input_Eval($value,$evalCodesArray,$tcaFieldConf['is_in']);

			// Process UNIQUE settings:
		if ($field && $realPid>=0)	{	// Field is NOT set for flexForms - which also means that uniqueInPid and unique is NOT available for flexForm fields! Also getUnique should not be done for versioning and if PID is -1 ($realPid<0) then versioning is happening...
			if ($res['value'] && in_array('uniqueInPid',$evalCodesArray))	{
				$res['value'] = $this->getUnique($table,$field,$res['value'],$id,$realPid);
			}
			if ($res['value'] && in_array('unique',$evalCodesArray))	{
				$res['value'] = $this->getUnique($table,$field,$res['value'],$id);
			}
		}

		return $res;
	}

	/**
	 * Evaluates 'check' type values.
	 *
	 * @param	array		The result array. The processed value (if any!) is set in the 'value' key.
	 * @param	string		The value to set.
	 * @param	array		Field configuration from TCA
	 * @param	array		Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
	 * @return	array		Modified $res array
	 */
	function checkValue_check($res,$value,$tcaFieldConf,$PP)	{
		list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;

		$itemC = count($tcaFieldConf['items']);
		if (!$itemC)	{$itemC=1;}
		$maxV = pow(2,$itemC);

		if ($value<0)	{$value=0;}
		if ($value>$maxV)	{$value=$maxV;}
		$res['value'] = $value;

		return $res;
	}

	/**
	 * Evaluates 'radio' type values.
	 *
	 * @param	array		The result array. The processed value (if any!) is set in the 'value' key.
	 * @param	string		The value to set.
	 * @param	array		Field configuration from TCA
	 * @param	array		Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
	 * @return	array		Modified $res array
	 */
	function checkValue_radio($res,$value,$tcaFieldConf,$PP)	{
		list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;

		if (is_array($tcaFieldConf['items']))	{
			foreach($tcaFieldConf['items'] as $set)	{
				if (!strcmp($set[1],$value))	{
					$res['value'] = $value;
					break;
				}
			}
		}

		return $res;
	}

	/**
	 * Evaluates 'group' or 'select' type values.
	 *
	 * @param	array		The result array. The processed value (if any!) is set in the 'value' key.
	 * @param	string		The value to set.
	 * @param	array		Field configuration from TCA
	 * @param	array		Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
	 * @param	[type]		$uploadedFiles: ...
	 * @param	string		Field name
	 * @return	array		Modified $res array
	 */
	function checkValue_group_select($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field)	{

		list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;

			// Detecting if value sent is an array and if so, implode it around a comma:
		if (is_array($value))	{
			$value = implode(',',$value);
		}

			// This converts all occurencies of '&#123;' to the byte 123 in the string - this is needed in very rare cases where filenames with special characters (like ???, umlaud etc) gets sent to the server as HTML entities instead of bytes. The error is done only by MSIE, not Mozilla and Opera.
			// Anyways, this should NOT disturb anything else:
		$value = $this->convNumEntityToByteValue($value);

			// When values are sent as group or select they come as comma-separated values which are exploded by this function:
		$valueArray = $this->checkValue_group_select_explodeSelectGroupValue($value);

			// If not multiple is set, then remove duplicates:
		if (!$tcaFieldConf['multiple'])	{
			$valueArray = array_unique($valueArray);
		}

			// If an exclusive key is found, discard all others:
		if ($tcaFieldConf['type']=='select' && $tcaFieldConf['exclusiveKeys'])	{
			$exclusiveKeys = t3lib_div::trimExplode(',', $tcaFieldConf['exclusiveKeys']);
			foreach($valueArray as $kk => $vv)	{
				if (in_array($vv, $exclusiveKeys))	{	// $vv is the item key!
					$valueArray = Array($kk => $vv);
					break;
				}
			}
		}

		// This could be a good spot for parsing the array through a validation-function which checks if the values are alright (except that database references are not in their final form - but that is the point, isn't it?)
		// NOTE!!! Must check max-items of files before the later check because that check would just leave out filenames if there are too many!!

			// Checking for select / authMode, removing elements from $valueArray if any of them is not allowed!
		if ($tcaFieldConf['type']=='select' && $tcaFieldConf['authMode'])	{
			$preCount = count($valueArray);
			foreach($valueArray as $kk => $vv)	{
				if (!$this->BE_USER->checkAuthMode($table,$field,$vv,$tcaFieldConf['authMode']))	{
					unset($valueArray[$kk]);
				}
			}

				// During the check it turns out that the value / all values were removed - we respond by simply returning an empty array so nothing is written to DB for this field.
			if ($preCount && !count($valueArray))	{
				return array();
			}
		}

			// For group types:
		if ($tcaFieldConf['type']=='group')	{
			switch($tcaFieldConf['internal_type'])	{
				case 'file':
					$valueArray = $this->checkValue_group_select_file(
						$valueArray,
						$tcaFieldConf,
						$curValue,
						$uploadedFiles,
						$status,
						$table,
						$id,
						$recFID
					);
				break;
				case 'db':
					$valueArray = $this->checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,'group');
				break;
			}
		}
			// For select types which has a foreign table attached:
		if ($tcaFieldConf['type']=='select' && $tcaFieldConf['foreign_table'])	{
			$valueArray = $this->checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,'select');
		}

// BTW, checking for min and max items here does NOT make any sense when MM is used because the above function calls will just return an array with a single item (the count) if MM is used... Why didn't I perform the check before? Probably because we could not evaluate the validity of record uids etc... Hmm...

			// Checking the number of items, that it is correct.
			// If files, there MUST NOT be too many files in the list at this point, so check that prior to this code.
		$valueArrayC = count($valueArray);
		$minI = isset($tcaFieldConf['minitems']) ? intval($tcaFieldConf['minitems']):0;

			// NOTE to the comment: It's not really possible to check for too few items, because you must then determine first, if the field is actual used regarding the CType.
		$maxI = isset($tcaFieldConf['maxitems']) ? intval($tcaFieldConf['maxitems']):1;
		if ($valueArrayC > $maxI)	{$valueArrayC=$maxI;}	// Checking for not too many elements

			// Dumping array to list
		$newVal=array();
		foreach($valueArray as $nextVal)	{
			if ($valueArrayC==0)	{break;}
			$valueArrayC--;
			$newVal[]=$nextVal;
		}
		$res['value'] = implode(',',$newVal);

		return $res;
	}

	/**
	 * Handling files for group/select function
	 *
	 * @param	[type]		$valueArray: ...
	 * @param	[type]		$tcaFieldConf: ...
	 * @param	[type]		$curValue: ...
	 * @param	[type]		$uploadedFileArray: ...
	 * @param	[type]		$status: ...
	 * @param	[type]		$table: ...
	 * @param	[type]		$id: ...
	 * @param	[type]		$recFID: ...
	 * @return	array		Modified value array
	 * @see checkValue_group_select()
	 */
	function checkValue_group_select_file($valueArray,$tcaFieldConf,$curValue,$uploadedFileArray,$status,$table,$id,$recFID)	{

			// If any files are uploaded:
		if (is_array($uploadedFileArray) &&
			$uploadedFileArray['name'] &&
			strcmp($uploadedFileArray['tmp_name'],'none'))	{
				$valueArray[]=$uploadedFileArray['tmp_name'];
				$this->alternativeFileName[$uploadedFileArray['tmp_name']] = $uploadedFileArray['name'];
		}

			// Creating fileFunc object.
		if (!$this->fileFunc)	{
			$this->fileFunc = t3lib_div::makeInstance('t3lib_basicFileFunctions');
			$this->include_filefunctions=1;
		}
			// Setting permitted extensions.
		$all_files = Array();
		$all_files['webspace']['allow'] = $tcaFieldConf['allowed'];
		$all_files['webspace']['deny'] = $tcaFieldConf['disallowed'] ? $tcaFieldConf['disallowed'] : '*';
		$all_files['ftpspace'] = $all_files['webspace'];
		$this->fileFunc->init('', $all_files);

			// If there is an upload folder defined:
		if ($tcaFieldConf['uploadfolder'])	{
				// For logging..
			$propArr = $this->getRecordProperties($table,$id);

				// Get destrination path:
			$dest = $this->destPathFromUploadFolder($tcaFieldConf['uploadfolder']);

				// If we are updating:
			if ($status=='update')	{

					// Traverse the input values and convert to absolute filenames in case the update happens to an autoVersionized record.
					// Background: This is a horrible workaround! The problem is that when a record is auto-versionized the files of the record get copied and therefore get new names which is overridden with the names from the original record in the incoming data meaning both lost files and double-references!
					// The only solution I could come up with (except removing support for managing files when autoversioning) was to convert all relative files to absolute names so they are copied again (and existing files deleted). This should keep references intact but means that some files are copied, then deleted after being copied _again_.
					// Actually, the same problem applies to database references in case auto-versioning would include sub-records since in such a case references are remapped - and they would be overridden due to the same principle then.
					// Illustration of the problem comes here:
					// We have a record 123 with a file logo.gif. We open and edit the files header in a workspace. So a new version is automatically made.
					// The versions uid is 456 and the file is copied to "logo_01.gif". But the form data that we sents was based on uid 123 and hence contains the filename "logo.gif" from the original.
					// The file management code below will do two things: First it will blindly accept "logo.gif" as a file attached to the record (thus creating a double reference) and secondly it will find that "logo_01.gif" was not in the incoming filelist and therefore should be deleted.
					// If we prefix the incoming file "logo.gif" with its absolute path it will be seen as a new file added. Thus it will be copied to "logo_02.gif". "logo_01.gif" will still be deleted but since the files are the same the difference is zero - only more processing and file copying for no reason. But it will work.
				if ($this->autoVersioningUpdate===TRUE)	{
					foreach($valueArray as $key => $theFile)	{
						if ($theFile===basename($theFile))	{
							$valueArray[$key] = PATH_site.$tcaFieldConf['uploadfolder'].'/'.$theFile;
						}
					}
				}

					// Finding the CURRENT files listed, either from MM or from the current record.
				$theFileValues=array();
				if ($tcaFieldConf['MM'])	{	// If MM relations for the files also!
					$dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
					$dbAnalysis->start('','files',$tcaFieldConf['MM'],$id);
					reset($dbAnalysis->itemArray);
					while (list($somekey,$someval)=each($dbAnalysis->itemArray))	{
						if ($someval['id'])	{
							$theFileValues[]=$someval['id'];
						}
					}
				} else {
					$theFileValues=t3lib_div::trimExplode(',',$curValue,1);
				}

					// DELETE files: If existing files were found, traverse those and register files for deletion which has been removed:
				if (count($theFileValues))	{
						// Traverse the input values and for all input values which match an EXISTING value, remove the existing from $theFileValues array (this will result in an array of all the existing files which should be deleted!)
					foreach($valueArray as $key => $theFile)	{
						if ($theFile && !strstr(t3lib_div::fixWindowsFilePath($theFile),'/'))	{
							$theFileValues = t3lib_div::removeArrayEntryByValue($theFileValues,$theFile);
						}
					}

						// This array contains the filenames in the uploadfolder that should be deleted:
					foreach($theFileValues as $key => $theFile)	{
						$theFile = trim($theFile);
						if (@is_file($dest.'/'.$theFile))	{
							$this->removeFilesStore[]=$dest.'/'.$theFile;
						} elseif ($theFile) {
							$this->log($table,$id,5,0,1,"Could not delete file '%s' (does not exist). (%s)",10,array($dest.'/'.$theFile, $recFID),$propArr['event_pid']);
						}
					}
				}
			}

				// Traverse the submitted values:
			foreach($valueArray as $key => $theFile)	{
					// NEW FILES? If the value contains '/' it indicates, that the file is new and should be added to the uploadsdir (whether its absolute or relative does not matter here)
				if (strstr(t3lib_div::fixWindowsFilePath($theFile),'/'))	{
						// Init:
					$maxSize = intval($tcaFieldConf['max_size']);
					$cmd='';
					$theDestFile='';		// Must be cleared. Else a faulty fileref may be inserted if the below code returns an error!! (Change: 22/12/2000)

						// Check various things before copying file:
					if (@is_dir($dest) && (@is_file($theFile) || @is_uploaded_file($theFile)))	{		// File and destination must exist

							// Finding size. For safe_mode we have to rely on the size in the upload array if the file is uploaded.
						if (is_uploaded_file($theFile) && $theFile==$uploadedFileArray['tmp_name'])	{
							$fileSize = $uploadedFileArray['size'];
						} else {
							$fileSize = filesize($theFile);
						}

						if (!$maxSize || $fileSize<=($maxSize*1024))	{	// Check file size:
								// Prepare filename:
							$theEndFileName = isset($this->alternativeFileName[$theFile]) ? $this->alternativeFileName[$theFile] : $theFile;
							$fI = t3lib_div::split_fileref($theEndFileName);

								// Check for allowed extension:
							if ($this->fileFunc->checkIfAllowed($fI['fileext'], $dest, $theEndFileName)) {
								$theDestFile = $this->fileFunc->getUniqueName($this->fileFunc->cleanFileName($fI['file']), $dest);

									// If we have a unique destination filename, then write the file:
								if ($theDestFile)	{
									t3lib_div::upload_copy_move($theFile,$theDestFile);
									$this->copiedFileMap[$theFile] = $theDestFile;
									clearstatcache();
									if (!@is_file($theDestFile))	$this->log($table,$id,5,0,1,"Copying file '%s' failed!: The destination path (%s) may be write protected. Please make it write enabled!. (%s)",16,array($theFile, dirname($theDestFile), $recFID),$propArr['event_pid']);
								} else $this->log($table,$id,5,0,1,"Copying file '%s' failed!: No destination file (%s) possible!. (%s)",11,array($theFile, $theDestFile, $recFID),$propArr['event_pid']);
							} else $this->log($table,$id,5,0,1,"Fileextension '%s' not allowed. (%s)",12,array($fI['fileext'], $recFID),$propArr['event_pid']);
						} else $this->log($table,$id,5,0,1,"Filesize (%s) of file '%s' exceeds limit (%s). (%s)",13,array(t3lib_div::formatSize($fileSize),$theFile,t3lib_div::formatSize($maxSize*1024),$recFID),$propArr['event_pid']);
					} else $this->log($table,$id,5,0,1,'The destination (%s) or the source file (%s) does not exist. (%s)',14,array($dest, $theFile, $recFID),$propArr['event_pid']);

						// If the destination file was created, we will set the new filename in the value array, otherwise unset the entry in the value array!
					if (@is_file($theDestFile))	{
						$info = t3lib_div::split_fileref($theDestFile);
						$valueArray[$key]=$info['file']; // The value is set to the new filename
					} else {
						unset($valueArray[$key]);	// The value is set to the new filename
					}
				}
			}

				// If MM relations for the files, we will set the relations as MM records and change the valuearray to contain a single entry with a count of the number of files!
			if ($tcaFieldConf['MM'])	{
				$dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
				$dbAnalysis->tableArray['files']=array();	// dummy

				reset($valueArray);
				while (list($key,$theFile)=each($valueArray))	{
						// explode files
						$dbAnalysis->itemArray[]['id']=$theFile;
				}
				if ($status=='update')	{
					$dbAnalysis->writeMM($tcaFieldConf['MM'],$id,0);
				} else {
					$this->dbAnalysisStore[] = array($dbAnalysis, $tcaFieldConf['MM'], $id, 0);	// This will be traversed later to execute the actions
				}
				$cc=count($dbAnalysis->itemArray);
				$valueArray = array($cc);
			}
		}

		return $valueArray;
	}

	/**
	 * Evaluates 'flex' type values.
	 *
	 * @param	array		The result array. The processed value (if any!) is set in the 'value' key.
	 * @param	string		The value to set.
	 * @param	array		Field configuration from TCA
	 * @param	array		Additional parameters in a numeric array: $table,$id,$curValue,$status,$realPid,$recFID
	 * @param	array		Uploaded files for the field
	 * @param	array		Current record array.
	 * @param	string		Field name
	 * @return	array		Modified $res array
	 */
	function checkValue_flex($res,$value,$tcaFieldConf,$PP,$uploadedFiles,$field)	{
		list($table,$id,$curValue,$status,$realPid,$recFID) = $PP;

		if (is_array($value))	{

				// Get current value array:
			$dataStructArray = t3lib_BEfunc::getFlexFormDS($tcaFieldConf,$this->checkValue_currentRecord,$table);
#debug($this->checkValue_currentRecord);
			$currentValueArray = t3lib_div::xml2array($curValue);
			if (!is_array($currentValueArray))	$currentValueArray = array();
			if (is_array($currentValueArray['meta']['currentLangId']))		unset($currentValueArray['meta']['currentLangId']);	// Remove all old meta for languages...

				// Evaluation of input values:
			$value['data'] = $this->checkValue_flex_procInData($value['data'],$currentValueArray['data'],$uploadedFiles['data'],$dataStructArray,$PP);

				// Create XML and convert charsets from input value:
			$xmlValue = $this->checkValue_flexArray2Xml($value,TRUE);

				// If we wanted to set UTF fixed:
			// $storeInCharset='utf-8';
			// $currentCharset=$GLOBALS['LANG']->charSet;
			// $xmlValue = $GLOBALS['LANG']->csConvObj->conv($xmlValue,$currentCharset,$storeInCharset,1);
			$storeInCharset=$GLOBALS['LANG']->charSet;

				// Merge them together IF they are both arrays:
				// Here we convert the currently submitted values BACK to an array, then merge the two and then BACK to XML again. This is needed to ensure the charsets are the same (provided that the current value was already stored IN the charset that the new value is converted to).
			if (is_array($currentValueArray))	{
				$arrValue = t3lib_div::xml2array($xmlValue);
				$arrValue = t3lib_div::array_merge_recursive_overrule($currentValueArray,$arrValue);
				$xmlValue = $this->checkValue_flexArray2Xml($arrValue,TRUE);
			}

				// Temporary fix to delete flex form elements:
			$deleteCMDs = t3lib_div::_GP('_DELETE_FLEX_FORMdata');
			if (is_array($deleteCMDs[$table][$id][$field]['data']))	{
				$arrValue = t3lib_div::xml2array($xmlValue);
				$this->_DELETE_FLEX_FORMdata($arrValue['data'],$deleteCMDs[$table][$id][$field]['data']);
				$xmlValue = $this->checkValue_flexArray2Xml($arrValue,TRUE);
			}

				// Temporary fix to move flex form elements up:
			$moveCMDs = t3lib_div::_GP('_MOVEUP_FLEX_FORMdata');
			if (is_array($moveCMDs[$table][$id][$field]['data']))	{
				$arrValue = t3lib_div::xml2array($xmlValue);
				$this->_MOVE_FLEX_FORMdata($arrValue['data'],$moveCMDs[$table][$id][$field]['data'], 'up');
				$xmlValue = $this->checkValue_flexArray2Xml($arrValue,TRUE);
			}

				// Temporary fix to move flex form elements down:
			$moveCMDs = t3lib_div::_GP('_MOVEDOWN_FLEX_FORMdata');
			if (is_array($moveCMDs[$table][$id][$field]['data']))	{
				$arrValue = t3lib_div::xml2array($xmlValue);
				$this->_MOVE_FLEX_FORMdata($arrValue['data'],$moveCMDs[$table][$id][$field]['data'], 'down');
				$xmlValue = $this->checkValue_flexArray2Xml($arrValue,TRUE);
			}

				// Create the value XML:
			$res['value']='';
			$res['value'].=$xmlValue;
		} else {	// Passthrough...:
			$res['value']=$value;
		}

		return $res;
	}

	/**
	 * Converts an array to FlexForm XML
	 *
	 * @param	array		Array with FlexForm data
	 * @param	boolean		If set, the XML prologue is returned as well.
	 * @return	string		Input array converted to XML
	 */
	function checkValue_flexArray2Xml($array, $addPrologue=FALSE)	{
		$flexObj = t3lib_div::makeInstance('t3lib_flexformtools');
		return $flexObj->flexArray2Xml($array, $addPrologue);
	}

	/**
	 * Deletes a flex form element
	 *
	 * @param	array		&$valueArrayToRemoveFrom: by reference
	 * @param	[type]		$deleteCMDS: ...	 *
	 * @return	void
	 */
	function _DELETE_FLEX_FORMdata(&$valueArrayToRemoveFrom,$deleteCMDS)	{
		if (is_array($valueArrayToRemoveFrom) && is_array($deleteCMDS))	{
			foreach($deleteCMDS as $key => $value)	{
				if (is_array($deleteCMDS[$key]))	{
					$this->_DELETE_FLEX_FORMdata($valueArrayToRemoveFrom[$key],$deleteCMDS[$key]);
				} else {
					unset($valueArrayToRemoveFrom[$key]);
				}
			}
		}
	}

	/**
	 * Deletes a flex form element
	 *
	 * TODO: Like _DELETE_FLEX_FORMdata, this is only a temporary solution!
	 *
	 * @param	array		&$valueArrayToMoveIn: by reference
	 * @param	[type]		$moveCMDS: ...	 *
	 * @param	string		$direction: 'up' or 'down'
	 * @return	void
	 */
	function _MOVE_FLEX_FORMdata(&$valueArrayToMoveIn, $moveCMDS, $direction)	{
		if (is_array($valueArrayToMoveIn) && is_array($moveCMDS))	{

				// Only execute the first move command:
			list ($key, $value) = each ($moveCMDS);

			if (is_array($moveCMDS[$key]))	{
				$this->_MOVE_FLEX_FORMdata($valueArrayToMoveIn[$key],$moveCMDS[$key], $direction);
			} else {
				switch ($direction) {
					case 'up':
						if ($key > 1) {
							$tmpArr = $valueArrayToMoveIn[$key];
							$valueArrayToMoveIn[$key] = $valueArrayToMoveIn[$key-1];
							$valueArrayToMoveIn[$key-1] = $tmpArr;
						}
					break;
					case 'down':
						if ($key < count($valueArrayToMoveIn)) {
							$tmpArr = $valueArrayToMoveIn[$key];
							$valueArrayToMoveIn[$key] = $valueArrayToMoveIn[$key+1];
							$valueArrayToMoveIn[$key+1] = $tmpArr;
						}
					break;
				}
			}
		}
	}


















	/*********************************************
	 *
	 * Helper functions for evaluation functions.
	 *
	 ********************************************/

	/**
	 * Gets a unique value for $table/$id/$field based on $value
	 *
	 * @param	string		Table name
	 * @param	string		Field name for which $value must be unique
	 * @param	string		Value string.
	 * @param	integer		UID to filter out in the lookup (the record itself...)
	 * @param	integer		If set, the value will be unique for this PID
	 * @return	string		Modified value (if not-unique). Will be the value appended with a number (until 100, then the function just breaks).
	 */
	function getUnique($table,$field,$value,$id,$newPid=0)	{
		global $TCA;

			// Initialize:
		t3lib_div::loadTCA($table);
		$whereAdd='';
		$newValue='';
		if (intval($newPid))	{ $whereAdd.=' AND pid='.intval($newPid); } else { $whereAdd.=' AND pid>=0'; }	// "AND pid>=0" for versioning
		$whereAdd.=$this->deleteClause($table);

			// If the field is configured in TCA, proceed:
		if (is_array($TCA[$table]) && is_array($TCA[$table]['columns'][$field]))	{

				// Look for a record which might already have the value:
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $field.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($value, $table).' AND uid!='.intval($id).$whereAdd);
			$counter = 0;

				// For as long as records with the test-value existing, try again (with incremented numbers appended).
			while ($GLOBALS['TYPO3_DB']->sql_num_rows($res))	{
				$newValue = $value.$counter;
				$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, $field.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($newValue, $table).' AND uid!='.intval($id).$whereAdd);
				$counter++;
				if ($counter>100)	{ break; }	// At "100" it will give up and accept a duplicate - should probably be fixed to a small hash string instead...!
			}
				// If the new value is there:
			$value = strlen($newValue) ? $newValue : $value;
		}
		return $value;
	}

	/**
	 * Evaluation of 'input'-type values based on 'eval' list
	 *
	 * @param	string		Value to evaluate
	 * @param	array		Array of evaluations to traverse.
	 * @param	string		Is-in string
	 * @return	string		Modified $value
	 */
	function checkValue_input_Eval($value,$evalArray,$is_in)	{
		$res = Array();
		$newValue = $value;
		$set = true;

		foreach($evalArray as $func)	{
			switch($func)	{
				case 'int':
				case 'year':
				case 'date':
				case 'datetime':
				case 'time':
				case 'timesec':
					$value = intval($value);
				break;
				case 'double2':
					$theDec = 0;
					for ($a=strlen($value); $a>0; $a--)	{
						if (substr($value,$a-1,1)=='.' || substr($value,$a-1,1)==',')	{
							$theDec = substr($value,$a);
							$value = substr($value,0,$a-1);
							break;
						}
					}
					$theDec = ereg_replace('[^0-9]','',$theDec).'00';
					$value = intval(str_replace(' ','',$value)).'.'.substr($theDec,0,2);
				break;
				case 'md5':
					if (strlen($value)!=32){$set=false;}
				break;
				case 'trim':
					$value = trim($value);
				break;
				case 'upper':
					$value = strtoupper($value);
#					$value = strtr($value, '', '');	// WILL make trouble with other charsets than ISO-8859-1, so what do we do here? PHP-function which can handle this for other charsets? Currently the browsers JavaScript will fix it.
				break;
				case 'lower':
					$value = strtolower($value);
#					$value = strtr($value, '', '');	// WILL make trouble with other charsets than ISO-8859-1, so what do we do here? PHP-function which can handle this for other charsets? Currently the browsers JavaScript will fix it.
				break;
				case 'required':
					if (!$value)	{$set=0;}
				break;
				case 'is_in':
					$c=strlen($value);
					if ($c)	{
						$newVal = '';
						for ($a=0;$a<$c;$a++)	{
							$char = substr($value,$a,1);
							if (strstr($is_in,$char))	{
								$newVal.=$char;
							}
						}
						$value = $newVal;
					}
				break;
				case 'nospace':
					$value = str_replace(' ','',$value);
				break;
				case 'alpha':
					$value = ereg_replace('[^a-zA-Z]','',$value);
				break;
				case 'num':
					$value = ereg_replace('[^0-9]','',$value);
				break;
				case 'alphanum':
					$value = ereg_replace('[^a-zA-Z0-9]','',$value);
				break;
				case 'alphanum_x':
					$value = ereg_replace('[^a-zA-Z0-9_-]','',$value);
				break;
				default:
					if (substr($func, 0, 3) == 'tx_')	{
						$evalObj = t3lib_div::getUserObj($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tce']['formevals'][$func].':&'.$func);
						if(is_object($evalObj) && method_exists($evalObj, 'evaluateFieldValue'))	{
							$value = $evalObj->evaluateFieldValue($value, $is_in, $set);
						}
					}
				break;
			}
		}
		if ($set)	{$res['value'] = $value;}
		return $res;
	}

	/**
	 * Returns data for group/db and select fields
	 *
	 * @param	array		Current value array
	 * @param	array		TCA field config
	 * @param	integer		Record id, used for look-up of MM relations (local_uid)
	 * @param	string		Status string ('update' or 'new')
	 * @param	string		The type, either 'select' or 'group'
	 * @return	array		Modified value array
	 */
	function checkValue_group_select_processDBdata($valueArray,$tcaFieldConf,$id,$status,$type)	{
		$tables = $type=='group'?$tcaFieldConf['allowed']:$tcaFieldConf['foreign_table'].','.$tcaFieldConf['neg_foreign_table'];
		$prep = $type=='group'?$tcaFieldConf['prepend_tname']:$tcaFieldConf['neg_foreign_table'];

		$dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
		$dbAnalysis->registerNonTableValues=$tcaFieldConf['allowNonIdValues'] ? 1 : 0;
		$dbAnalysis->start(implode(',',$valueArray),$tables);

		if ($tcaFieldConf['MM'])	{
			if ($status=='update')	{
				$dbAnalysis->writeMM($tcaFieldConf['MM'],$id,$prep);
			} else {
				$this->dbAnalysisStore[] = array($dbAnalysis,$tcaFieldConf['MM'],$id,$prep);	// This will be traversed later to execute the actions
			}
			$cc=count($dbAnalysis->itemArray);
			$valueArray = array($cc);
		} else {
			$valueArray = $dbAnalysis->getValueArray($prep);
			if ($type=='select' && $prep)	{
				$valueArray = $dbAnalysis->convertPosNeg($valueArray,$tcaFieldConf['foreign_table'],$tcaFieldConf['neg_foreign_table']);
			}
		}

			// Here we should se if 1) the records exist anymore, 2) which are new and check if the BE_USER has read-access to the new ones.
		return $valueArray;
	}

	/**
	 * Explodes the $value, which is a list of files/uids (group select)
	 *
	 * @param	string		Input string, comma separated values. For each part it will also be detected if a '|' is found and the first part will then be used if that is the case. Further the value will be rawurldecoded.
	 * @return	array		The value array.
	 */
	function checkValue_group_select_explodeSelectGroupValue($value)	{
		$valueArray = t3lib_div::trimExplode(',',$value,1);
		reset($valueArray);
		while(list($key,$newVal)=each($valueArray))	{
			$temp=explode('|',$newVal,2);
			$valueArray[$key] = str_replace(',','',str_replace('|','',rawurldecode($temp[0])));
		}
		return $valueArray;
	}

	/**
	 * Starts the processing the input data for flexforms. This will traverse all sheets / languages and for each it will traverse the sub-structure.
	 * See checkValue_flex_procInData_travDS() for more details.
	 * WARNING: Currently, it traverses based on the actual _data_ array and NOT the _structure_. This means that values for non-valid fields, lKey/vKey/sKeys will be accepted! For traversal of data with a call back function you should rather use class.t3lib_flexformtools.php
	 *
	 * @param	array		The 'data' part of the INPUT flexform data
	 * @param	array		The 'data' part of the CURRENT flexform data
	 * @param	array		The uploaded files for the 'data' part of the INPUT flexform data
	 * @param	array		Data structure for the form (might be sheets or not). Only values in the data array which has a configuration in the data structure will be processed.
	 * @param	array		A set of parameters to pass through for the calling of the evaluation functions
	 * @param	string		Optional call back function, see checkValue_flex_procInData_travDS()  DEPRICATED, use class.t3lib_flexformtools.php instead for traversal!
	 * @return	array		The modified 'data' part.
	 * @see checkValue_flex_procInData_travDS()
	 */
	function checkValue_flex_procInData($dataPart,$dataPart_current,$uploadedFiles,$dataStructArray,$pParams,$callBackFunc='')	{
#debug(array($dataPart,$dataPart_current,$dataStructArray));
		if (is_array($dataPart))	{
			foreach($dataPart as $sKey => $sheetDef)	{
				list ($dataStruct,$actualSheet) = t3lib_div::resolveSheetDefInDS($dataStructArray,$sKey);
#debug(array($dataStruct,$actualSheet,$sheetDef,$actualSheet,$sKey));
				if (is_array($dataStruct) && $actualSheet==$sKey && is_array($sheetDef))	{
					foreach($sheetDef as $lKey => $lData)	{
						$this->checkValue_flex_procInData_travDS(
							$dataPart[$sKey][$lKey],
							$dataPart_current[$sKey][$lKey],
							$uploadedFiles[$sKey][$lKey],
							$dataStruct['ROOT']['el'],
							$pParams,
							$callBackFunc,
							$sKey.'/'.$lKey.'/'
						);
					}
				}
			}
		}

		return $dataPart;
	}

	/**
	 * Processing of the sheet/language data array
	 * When it finds a field with a value the processing is done by ->checkValue_SW() by default but if a call back function name is given that method in this class will be called for the processing instead.
	 *
	 * @param	array		New values (those being processed): Multidimensional Data array for sheet/language, passed by reference!
	 * @param	array		Current values: Multidimensional Data array. May be empty array() if not needed (for callBackFunctions)
	 * @param	array		Uploaded files array for sheet/language. May be empty array() if not needed (for callBackFunctions)
	 * @param	array		Data structure which fits the data array
	 * @param	array		A set of parameters to pass through for the calling of the evaluation functions / call back function
	 * @param	string		Call back function, default is checkValue_SW(). If $this->callBackObj is set to an object, the callback function in that object is called instead.
	 * @param	[type]		$structurePath: ...
	 * @return	void
	 * @see checkValue_flex_procInData()
	 */
	function checkValue_flex_procInData_travDS(&$dataValues,$dataValues_current,$uploadedFiles,$DSelements,$pParams,$callBackFunc,$structurePath)	{
		if (is_array($DSelements))	{

				// For each DS element:
			foreach($DSelements as $key => $dsConf)	{

						// Array/Section:
				if ($DSelements[$key]['type']=='array')	{
					if (is_array($dataValues[$key]['el']))	{
						if ($DSelements[$key]['section'])	{
							foreach($dataValues[$key]['el'] as $ik => $el)	{
								$theKey = key($el);
								if (is_array($dataValues[$key]['el'][$ik][$theKey]['el']))	{
									$this->checkValue_flex_procInData_travDS(
											$dataValues[$key]['el'][$ik][$theKey]['el'],
											$dataValues_current[$key]['el'][$ik][$theKey]['el'],
											$uploadedFiles[$key]['el'][$ik][$theKey]['el'],
											$DSelements[$key]['el'][$theKey]['el'],
											$pParams,
											$callBackFunc,
											$structurePath.$key.'/el/'.$ik.'/'.$theKey.'/el/'
										);
								}
							}
						} else {
							if (!isset($dataValues[$key]['el']))	$dataValues[$key]['el']=array();
							$this->checkValue_flex_procInData_travDS(
									$dataValues[$key]['el'],
									$dataValues_current[$key]['el'],
									$uploadedFiles[$key]['el'],
									$DSelements[$key]['el'],
									$pParams,
									$callBackFunc,
									$structurePath.$key.'/el/'
								);
						}
					}
				} else {
					if (is_array($dsConf['TCEforms']['config']) && is_array($dataValues[$key]))	{
						foreach($dataValues[$key] as $vKey => $data)	{

							if ($callBackFunc)	{
								if (is_object($this->callBackObj))	{
									$res = $this->callBackObj->$callBackFunc(
												$pParams,
												$dsConf['TCEforms']['config'],
												$dataValues[$key][$vKey],
												$dataValues_current[$key][$vKey],
												$uploadedFiles[$key][$vKey],
												$structurePath.$key.'/'.$vKey.'/'
											);
								} else {
									$res = $this->$callBackFunc(
												$pParams,
												$dsConf['TCEforms']['config'],
												$dataValues[$key][$vKey],
												$dataValues_current[$key][$vKey],
												$uploadedFiles[$key][$vKey]
											);
								}
							} else {	// Default
								list($CVtable,$CVid,$CVcurValue,$CVstatus,$CVrealPid,$CVrecFID,$CVtscPID) = $pParams;

								$res = $this->checkValue_SW(
											array(),
											$dataValues[$key][$vKey],
											$dsConf['TCEforms']['config'],
											$CVtable,
											$CVid,
											$dataValues_current[$key][$vKey],
											$CVstatus,
											$CVrealPid,
											$CVrecFID,
											'',
											$uploadedFiles[$key][$vKey],
											array(),
											$CVtscPID
										);

									// Look for RTE transformation of field:
								if ($dataValues[$key]['_TRANSFORM_'.$vKey] == 'RTE' && !$this->dontProcessTransformations)	{

										// Unsetting trigger field - we absolutely don't want that into the data storage!
									unset($dataValues[$key]['_TRANSFORM_'.$vKey]);

									if (isset($res['value']))	{

											// Calculating/Retrieving some values here:
										list(,,$recFieldName) = explode(':', $CVrecFID);
										$theTypeString = t3lib_BEfunc::getTCAtypeValue($CVtable,$this->checkValue_currentRecord);
										$specConf = t3lib_BEfunc::getSpecConfParts('',$dsConf['TCEforms']['defaultExtras']);

											// Find, thisConfig:
										$RTEsetup = $this->BE_USER->getTSConfig('RTE',t3lib_BEfunc::getPagesTSconfig($CVtscPID));
										$thisConfig = t3lib_BEfunc::RTEsetup($RTEsetup['properties'],$CVtable,$recFieldName,$theTypeString);

											// Get RTE object, draw form and set flag:
										$RTEobj = &t3lib_BEfunc::RTEgetObj();
										if (is_object($RTEobj))	{
											$res['value'] = $RTEobj->transformContent('db',$res['value'],$CVtable,$recFieldName,$this->checkValue_currentRecord,$specConf,$thisConfig,'',$CVrealPid);
										} else {
											debug('NO RTE OBJECT FOUND!');
										}
									}
								}
							}

								// Adding the value:
							if (isset($res['value']))	{
								$dataValues[$key][$vKey] = $res['value'];
							}
						}
					}
				}
			}
		}
	}

















	/*********************************************
	 *
	 * PROCESSING COMMANDS
	 *
	 ********************************************/

	/**
	 * Processing the cmd-array
	 * See "TYPO3 Core API" for a description of the options.
	 *
	 * @return	void
	 */
	function process_cmdmap() {
		global $TCA, $TYPO3_CONF_VARS;

			// Editing frozen:
		if ($this->BE_USER->workspace!==0 && $this->BE_USER->workspaceRec['freeze'])	{
			$this->newlog('All editing in this workspace has been frozen!',1);
			return FALSE;
		}

			// Hook initialization:
		$hookObjectsArr = array();
		if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'])) {
			foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['processCmdmapClass'] as $classRef) {
				$hookObjectsArr[] = &t3lib_div::getUserObj($classRef);
			}
		}

			// Traverse command map:
		reset($this->cmdmap);
		while(list($table,) = each($this->cmdmap))	{

				// Check if the table may be modified!
			$modifyAccessList = $this->checkModifyAccessList($table);
			if (!$modifyAccessList)	{
				$id = 0;
				$this->log($table,$id,2,0,1,"Attempt to modify table '%s' without permission",1,array($table));
			}	// FIXME: $id not set here (Comment added by Sebastian Kurfuerst)

				// Check basic permissions and circumstances:
			if (isset($TCA[$table]) && !$this->tableReadOnly($table) && is_array($this->cmdmap[$table]) && $modifyAccessList)	{

					// Traverse the command map:
				foreach($this->cmdmap[$table] as $id => $incomingCmdArray)	{
					if (is_array($incomingCmdArray))	{	// have found a command.

							// Get command and value (notice, only one command is observed at a time!):
						reset($incomingCmdArray);
						$command = key($incomingCmdArray);
						$value = current($incomingCmdArray);

						foreach($hookObjectsArr as $hookObj) {
							if (method_exists($hookObj, 'processCmdmap_preProcess')) {
								$hookObj->processCmdmap_preProcess($command, $table, $id, $value, $this);
							}
						}

							// Init copyMapping array:
						$this->copyMappingArray = Array();		// Must clear this array before call from here to those functions: Contains mapping information between new and old id numbers.

							// Branch, based on command
						switch ($command)	{
							case 'move':
								$this->moveRecord($table,$id,$value);
							break;
							case 'copy':
								if ($table === 'pages')	{
									$this->copyPages($id,$value);
								} else {
									$this->copyRecord($table,$id,$value,1);
								}
							break;
							case 'localize':
								$this->localize($table,$id,$value);
							break;
							case 'version':
								switch ((string)$value['action'])	{
									case 'new':
										$versionizeTree = t3lib_div::intInRange(!isset($value['treeLevels'])?-1:$value['treeLevels'],-1,100);
										if ($table == 'pages' && $versionizeTree>=0)	{
											$this->versionizePages($id,$value['label'],$versionizeTree);
										} else {
											$this->versionizeRecord($table,$id,$value['label']);
										}
									break;
									case 'swap':
										$this->version_swap($table,$id,$value['swapWith'],$value['swapIntoWS']);
									break;
									case 'clearWSID':
										$this->version_clearWSID($table,$id);
									break;
									case 'setStage':
										$idList = t3lib_div::trimExplode(',',$id,1);
										foreach($idList as $id)	{
											$this->version_setStage($table,$id,$value['stageId'],$value['comment']?$value['comment']:$this->generalComment);
										}
									break;
								}
							break;
							case 'delete':
								$this->deleteAction($table, $id);
							break;
							case 'undelete':
								$this->undeleteRecord($table, $id);
							break;
						}

						foreach($hookObjectsArr as $hookObj) {
							if (method_exists($hookObj, 'processCmdmap_postProcess')) {
								$hookObj->processCmdmap_postProcess($command, $table, $id, $value, $this);
							}
						}

							// Merging the copy-array info together for remapping purposes.
						$this->copyMappingArray_merged= t3lib_div::array_merge_recursive_overrule($this->copyMappingArray_merged,$this->copyMappingArray);
					}
				}
			}
		}

			// Finally, before exit, check if there are ID references to remap. This might be the case if versioning or copying has taken place!
		$this->remapListedDBRecords();
	}











	/*********************************************
	 *
	 * Cmd: Copying
	 *
	 ********************************************/

	/**
	 * Copying a single record
	 *
	 * @param	string		Element table
	 * @param	integer		Element UID
	 * @param	integer		$destPid: >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
	 * @param	boolean		$first is a flag set, if the record copied is NOT a 'slave' to another record copied. That is, if this record was asked to be copied in the cmd-array
	 * @param	array		Associative array with field/value pairs to override directly. Notice; Fields must exist in the table record and NOT be among excluded fields!
	 * @param	string		Commalist of fields to exclude from the copy process (might get default values)
	 * @return	integer		ID of new record, if any
	 */
	function copyRecord($table,$uid,$destPid,$first=0,$overrideValues=array(),$excludeFields='')	{
		global $TCA;

		$uid = $origUid = intval($uid);
		if ($TCA[$table] && $uid)	{
			t3lib_div::loadTCA($table);
/*
				// In case the record to be moved turns out to be an offline version, we have to find the live version and work on that one (this case happens for pages with "branch" versioning type)
			if ($lookForLiveVersion = t3lib_BEfunc::getLiveVersionOfRecord($table,$uid,'uid'))	{
				$uid = $lookForLiveVersion['uid'];
			}
				// Get workspace version of the source record, if any: Then we will copy workspace version instead:
			if ($WSversion = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $uid, 'uid,t3ver_oid'))	{
				$uid = $WSversion['uid'];
			}
				// Now, the $uid is the actual record we will copy while $origUid is the record we asked to get copied - but that could be a live version.
*/
			if ($this->doesRecordExist($table,$uid,'show'))	{		// This checks if the record can be selected which is all that a copy action requires.
				$data = Array();

				$nonFields = array_unique(t3lib_div::trimExplode(',','uid,perms_userid,perms_groupid,perms_user,perms_group,perms_everybody,t3ver_oid,t3ver_wsid,t3ver_id,t3ver_label,t3ver_state,t3ver_swapmode,t3ver_count,t3ver_stage,t3ver_tstamp,'.$excludeFields,1));

				// $row = $this->recordInfo($table,$uid,'*');
				$row = t3lib_BEfunc::getRecordWSOL($table,$uid);	// So it copies (and localized) content from workspace...
				if (is_array($row))	{

						// Initializing:
					$theNewID = uniqid('NEW');
					$enableField = isset($TCA[$table]['ctrl']['enablecolumns']) ? $TCA[$table]['ctrl']['enablecolumns']['disabled'] : '';
					$headerField = $TCA[$table]['ctrl']['label'];

						// Getting default data:
					$defaultData = $this->newFieldArray($table);

						// Getting "copy-after" fields if applicable:
						// origDestPid is retrieve before it may possibly be converted to resolvePid if the table is not sorted anyway. In this way, copying records to after another records which are not sorted still lets you use this function in order to copy fields from the one before.
					$copyAfterFields = $destPid<0 ? $this->fixCopyAfterDuplFields($table,$uid,abs($destPid),0) : array();

						// Page TSconfig related:
					$tscPID = t3lib_BEfunc::getTSconfig_pidValue($table,$uid,$destPid);	// NOT using t3lib_BEfunc::getTSCpid() because we need the real pid - not the ID of a page, if the input is a page...
					$TSConfig = $this->getTCEMAIN_TSconfig($tscPID);
					$tE = $this->getTableEntries($table,$TSConfig);

						// Traverse ALL fields of the selected record:
					foreach($row as $field => $value)	{
						if (!in_array($field,$nonFields))	{

								// Get TCA configuration for the field:
							$conf = $TCA[$table]['columns'][$field]['config'];

								// Preparation/Processing of the value:
							if ($field=='pid')	{	// "pid" is hardcoded of course:
								$value = $destPid;
							} elseif (isset($overrideValues[$field]))	{	// Override value...
								$value = $overrideValues[$field];
							} elseif (isset($copyAfterFields[$field]))	{	// Copy-after value if available:
								$value = $copyAfterFields[$field];
							} elseif ($TCA[$table]['ctrl']['setToDefaultOnCopy'] && t3lib_div::inList($TCA[$table]['ctrl']['setToDefaultOnCopy'],$field))	{	// Revert to default for some fields:
								$value = $defaultData[$field];
							} else {
									// Hide at copy may override:
								if ($first && $field==$enableField && $TCA[$table]['ctrl']['hideAtCopy'] && !$this->neverHideAtCopy && !$tE['disableHideAtCopy'])	{
									$value=1;
								}
									// Prepend label on copy:
								if ($first && $field==$headerField && $TCA[$table]['ctrl']['prependAtCopy'] && !$tE['disablePrependAtCopy'])	{
									$value = $this->getCopyHeader($table,$this->resolvePid($table,$destPid),$field,$this->clearPrefixFromValue($table,$value),0);
								}
									// Processing based on the TCA config field type (files, references, flexforms...)
								$value = $this->copyRecord_procBasedOnFieldType($table,$uid,$field,$value,$row,$conf);
							}

								// Add value to array.
							$data[$table][$theNewID][$field] = $value;
						}
					}

						// Overriding values:
					if ($TCA[$table]['ctrl']['editlock'])	{
						$data[$table][$theNewID][$TCA[$table]['ctrl']['editlock']] = 0;
					}

						// Setting original UID:
					if ($TCA[$table]['ctrl']['origUid'])	{
						$data[$table][$theNewID][$TCA[$table]['ctrl']['origUid']] = $uid;
					}

						// Do the copy by simply submitting the array through TCEmain:
					$copyTCE = t3lib_div::makeInstance('t3lib_TCEmain');
					$copyTCE->stripslashes_values = 0;
					$copyTCE->copyTree = $this->copyTree;
					$copyTCE->cachedTSconfig = $this->cachedTSconfig;	// Copy forth the cached TSconfig
					$copyTCE->dontProcessTransformations=1;		// Transformations should NOT be carried out during copy

					$copyTCE->start($data,'',$this->BE_USER);
					$copyTCE->process_datamap();

						// Getting the new UID:
					$theNewSQLID = $copyTCE->substNEWwithIDs[$theNewID];
					if ($theNewSQLID)	{
						$this->copyMappingArray[$table][$origUid] = $theNewSQLID;
					}

						// Copy back the cached TSconfig
					$this->cachedTSconfig = $copyTCE->cachedTSconfig;
					$this->errorLog = array_merge($this->errorLog,$copyTCE->errorLog);
					unset($copyTCE);

					return $theNewSQLID;
				} else $this->log($table,$uid,3,0,1,'Attempt to copy record that did not exist!');
			} else $this->log($table,$uid,3,0,1,'Attempt to copy record without permission');
		}
	}

	/**
	 * Copying pages
	 * Main function for copying pages.
	 *
	 * @param	integer		Page UID to copy
	 * @param	integer		Destination PID: >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
	 * @return	void
	 */
	function copyPages($uid,$destPid)	{

			// Initialize:
		$uid = intval($uid);
		$destPid = intval($destPid);

			// Finding list of tables to copy.
		$copyTablesArray = $this->admin ? $this->compileAdminTables() : explode(',',$this->BE_USER->groupData['tables_modify']);	// These are the tables, the user may modify
		if (!strstr($this->copyWhichTables,'*'))	{		// If not all tables are allowed then make a list of allowed tables: That is the tables that figure in both allowed tables AND the copyTable-list
			foreach($copyTablesArray as $k => $table)	{
				if (!$table || !t3lib_div::inList($this->copyWhichTables.',pages',$table))	{	// pages are always going...
					unset($copyTablesArray[$k]);
				}
			}
		}
		$copyTablesArray = array_unique($copyTablesArray);

			// Begin to copy pages if we're allowed to:
		if ($this->admin || in_array('pages',$copyTablesArray))	{

				// Copy this page we're on. And set first-flag (this will trigger that the record is hidden if that is configured)!
			$theNewRootID = $this->copySpecificPage($uid,$destPid,$copyTablesArray,1);

				// If we're going to copy recursively...:
			if ($theNewRootID && $this->copyTree)	{

					// Get ALL subpages to copy (read-permissions are respected!):
				$CPtable = $this->int_pageTreeInfo(Array(), $uid, intval($this->copyTree), $theNewRootID);

					// Now copying the subpages:
				foreach($CPtable as $thePageUid => $thePagePid)	{
					$newPid = $this->copyMappingArray['pages'][$thePagePid];
					if (isset($newPid))	{
						$this->copySpecificPage($thePageUid,$newPid,$copyTablesArray);
					} else {
						$this->log('pages',$uid,5,0,1,'Something went wrong during copying branch');
						break;
					}
				}
			}	// else the page was not copied. Too bad...
		} else {
			$this->log('pages',$uid,5,0,1,'Attempt to copy page without permission to this table');
		}
	}

	/**
	 * Copying a single page ($uid) to $destPid and all tables in the array copyTablesArray.
	 *
	 * @param	integer		Page uid
	 * @param	integer		Destination PID: >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
	 * @param	array		Table on pages to copy along with the page.
	 * @param	boolean		$first is a flag set, if the record copied is NOT a 'slave' to another record copied. That is, if this record was asked to be copied in the cmd-array
	 * @return	integer		The id of the new page, if applicable.
	 */
	function copySpecificPage($uid,$destPid,$copyTablesArray,$first=0)	{
		global $TCA;

			// Copy the page itself:
		$theNewRootID = $this->copyRecord('pages',$uid,$destPid,$first);

			// If a new page was created upon the copy operation we will proceed with all the tables ON that page:
		if ($theNewRootID)	{
			foreach($copyTablesArray as $table)	{
				if ($table && is_array($TCA[$table]) && $table!='pages')	{	// all records under the page is copied.
					$mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, 'pid='.intval($uid).$this->deleteClause($table), '', ($TCA[$table]['ctrl']['sortby'] ? $TCA[$table]['ctrl']['sortby'].' DESC' : ''));
					while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres))	{
						$this->copyRecord($table,$row['uid'], $theNewRootID);	// Copying each of the underlying records...
					}
				}
			}
			return $theNewRootID;
		}
	}

	/**
	 * Copying records, but makes a "raw" copy of a record.
	 * Basically the only thing observed is field processing like the copying of files and correction of ids. All other fields are 1-1 copied.
	 * Technically the copy is made with THIS instance of the tcemain class contrary to copyRecord() which creates a new instance and uses the processData() function.
	 * The copy is created by insertNewCopyVersion() which bypasses most of the regular input checking associated with processData() - maybe copyRecord() should even do this as well!?
	 * This function is used to create new versions of a record.
	 * NOTICE: DOES NOT CHECK PERMISSIONS to create! And since page permissions are just passed through and not changed to the user who executes the copy we cannot enforce permissions without getting an incomplete copy - unless we change permissions of course.
	 *
	 * @param	string		Element table
	 * @param	integer		Element UID
	 * @param	integer		Element PID (real PID, not checked)
	 * @param	array		Override array - must NOT contain any fields not in the table!
	 * @return	integer		Returns the new ID of the record (if applicable)
	 */
	function copyRecord_raw($table,$uid,$pid,$overrideArray=array())	{
		global $TCA;

		$uid = intval($uid);
		if ($TCA[$table] && $uid)	{
			t3lib_div::loadTCA($table);
			if ($this->doesRecordExist($table,$uid,'show'))	{

					// Set up fields which should not be processed. They are still written - just passed through no-questions-asked!
				$nonFields = array('uid','pid','t3ver_id','t3ver_oid','t3ver_wsid','t3ver_label','t3ver_state','t3ver_swapmode','t3ver_count','t3ver_stage','t3ver_tstamp','perms_userid','perms_groupid','perms_user','perms_group','perms_everybody');

					// Select main record:
				$row = $this->recordInfo($table,$uid,'*');
				if (is_array($row))	{

						// Merge in override array.
					$row = array_merge($row,$overrideArray);

						// Traverse ALL fields of the selected record:
					foreach($row as $field => $value)	{
						if (!in_array($field,$nonFields))	{

								// Get TCA configuration for the field:
							$conf = $TCA[$table]['columns'][$field]['config'];
							if (is_array($conf))	{
									// Processing based on the TCA config field type (files, references, flexforms...)
								$value = $this->copyRecord_procBasedOnFieldType($table,$uid,$field,$value,$row,$conf);
							}

								// Add value to array.
							$row[$field] = $value;
						}
					}

						// Force versioning related fields:
					$row['pid'] = $pid;

						// Setting original UID:
					if ($TCA[$table]['ctrl']['origUid'])	{
						$row[$TCA[$table]['ctrl']['origUid']] = $uid;
					}

						// Do the copy by internal function
					$theNewSQLID = $this->insertNewCopyVersion($table,$row,$pid);
					if ($theNewSQLID)	{
						$this->dbAnalysisStoreExec();
						$this->dbAnalysisStore = array();
						return $this->copyMappingArray[$table][$uid] = $theNewSQLID;
					}
				} else $this->log($table,$uid,3,0,1,'Attempt to rawcopy/versionize record that did not exist!');
			} else $this->log($table,$uid,3,0,1,'Attempt to rawcopy/versionize record without copy permission');
		}
	}

	/**
	 * Copies all records from tables in $copyTablesArray from page with $old_pid to page with $new_pid
	 * Uses raw-copy for the operation (meant for versioning!)
	 *
	 * @param	integer		Current page id.
	 * @param	integer		New page id
	 * @param	array		Array of tables from which to copy
	 * @return	void
	 * @see versionizePages()
	 */
	function rawCopyPageContent($old_pid,$new_pid,$copyTablesArray)	{
		global $TCA;

		if ($new_pid)	{
			foreach($copyTablesArray as $table)	{
				if ($table && is_array($TCA[$table]) && $table!='pages')	{	// all records under the page is copied.
					$mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, 'pid='.intval($old_pid).$this->deleteClause($table));
					while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres))	{
						$this->copyRecord_raw($table,$row['uid'],$new_pid);	// Copying each of the underlying records (method RAW)
					}
				}
			}
		}
	}

	/**
	 * Inserts a record in the database, passing TCA configuration values through checkValue() but otherwise does NOTHING and checks nothing regarding permissions.
	 * Passes the "version" parameter to insertDB() so the copy will look like a new version in the log - should probably be changed or modified a bit for more broad usage...
	 *
	 * @param	string		Table name
	 * @param	array		Field array to insert as a record
	 * @param	integer		The value of PID field.  -1 is indication that we are creating a new version!
	 * @return	integer		Returns the new ID of the record (if applicable)
	 */
	function insertNewCopyVersion($table,$fieldArray,$realPid)	{
		global $TCA;

		$id = uniqid('NEW');

			// $fieldArray is set as current record.
			// The point is that when new records are created as copies with flex type fields there might be a field containing information about which DataStructure to use and without that information the flexforms cannot be correctly processed.... This should be OK since the $checkValueRecord is used by the flexform evaluation only anyways...
		$this->checkValue_currentRecord = $fieldArray;

			// Traverse record and input-process each value:
		foreach($fieldArray as $field => $fieldValue)	{
			if (isset($TCA[$table]['columns'][$field]))	{
					// Evaluating the value.
				$res = $this->checkValue($table,$field,$fieldValue,$id,'new',$realPid,0);
				if (isset($res['value']))	{
					$fieldArray[$field] = $res['value'];
				}
			}
		}

			// System fields being set:
		if ($TCA[$table]['ctrl']['crdate'])	{
			$fieldArray[$TCA[$table]['ctrl']['crdate']]=time();
		}
		if ($TCA[$table]['ctrl']['cruser_id'])	{
			$fieldArray[$TCA[$table]['ctrl']['cruser_id']]=$this->userid;
		}
		if ($TCA[$table]['ctrl']['tstamp'])	{
			$fieldArray[$TCA[$table]['ctrl']['tstamp']]=time();
		}

			// Finally, insert record:
		$this->insertDB($table,$id,$fieldArray, TRUE);

			// Return new id:
		return $this->substNEWwithIDs[$id];
	}

	/**
	 * Processing/Preparing content for copyRecord() function
	 *
	 * @param	string		Table name
	 * @param	integer		Record uid
	 * @param	string		Field name being processed
	 * @param	string		Input value to be processed.
	 * @param	array		Record array
	 * @param	array		TCA field configuration
	 * @return	mixed		Processed value. Normally a string/integer, but can be an array for flexforms!
	 * @access private
	 * @see copyRecord()
	 */
	function copyRecord_procBasedOnFieldType($table,$uid,$field,$value,$row,$conf)	{
		global $TCA;

			// Process references and files, currently that means only the files, prepending absolute paths (so the TCEmain engine will detect the file as new and one that should be made into a copy)
		$value = $this->copyRecord_procFilesRefs($conf, $uid, $value);


			// Register if there are references to take care of (no change to value):
		if ($this->isReferenceField($conf))	{
			$allowedTables = $conf['type']=='group' ? $conf['allowed'] : $conf['foreign_table'].','.$conf['neg_foreign_table'];
			$prependName = $conf['type']=='group' ? $conf['prepend_tname'] : $conf['neg_foreign_table'];
			if ($conf['MM'])	{
				$dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
				$dbAnalysis->start('',$allowedTables,$conf['MM'],$uid);
				$value = implode(',',$dbAnalysis->getValueArray($prependName));
			}
			if ($value)	{	// Setting the value in this array will notify the remapListedDBRecords() function that this field MAY need references to be corrected
				$this->registerDBList[$table][$uid][$field] = $value;
			}
		}

			// For "flex" fieldtypes we need to traverse the structure for two reasons: If there are file references they have to be prepended with absolute paths and if there are database reference they MIGHT need to be remapped (still done in remapListedDBRecords())
		if ($conf['type']=='flex')	{

				// Get current value array:
			$dataStructArray = t3lib_BEfunc::getFlexFormDS($conf, $row, $table);
			$currentValueArray = t3lib_div::xml2array($value);

				// Traversing the XML structure, processing files:
			if (is_array($currentValueArray))	{
				$currentValueArray['data'] = $this->checkValue_flex_procInData(
							$currentValueArray['data'],
							array(),	// Not used.
							array(),	// Not used.
							$dataStructArray,
							array($table,$uid,$field),	// Parameters.
							'copyRecord_flexFormCallBack'
						);
				$value = $currentValueArray;	// Setting value as an array! -> which means the input will be processed according to the 'flex' type when the new copy is created.
			}
		}

		return $value;
	}

	/**
	 * Callback function for traversing the FlexForm structure in relation to creating copied files of file relations inside of flex form structures.
	 *
	 * @param	array		Array of parameters in num-indexes: table, uid, field
	 * @param	array		TCA field configuration (from Data Structure XML)
	 * @param	string		The value of the flexForm field
	 * @param	string		Not used.
	 * @param	string		Not used.
	 * @return	array		Result array with key "value" containing the value of the processing.
	 * @see copyRecord(), checkValue_flex_procInData_travDS()
	 */
	function copyRecord_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)	{

			// Extract parameters:
		list($table, $uid, $field) = $pParams;

			// Process references and files, currently that means only the files, prepending absolute paths:
		$dataValue = $this->copyRecord_procFilesRefs($dsConf, $uid, $dataValue);

			// If references are set for this field, set flag so they can be corrected later (in ->remapListedDBRecords())
		if ($this->isReferenceField($dsConf) && strlen($dataValue)) {
			$this->registerDBList[$table][$uid][$field] = 'FlexForm_reference';
		}

			// Return
		return array('value' => $dataValue);
	}

	/**
	 * Modifying a field value for any situation regarding files/references:
	 * For attached files: take current filenames and prepend absolute paths so they get copied.
	 * For DB references: Nothing done.
	 *
	 * @param	array		TCE field config
	 * @param	integer		Record UID
	 * @param	string		Field value (eg. list of files)
	 * @return	string		The (possibly modified) value
	 * @see copyRecord(), copyRecord_flexFormCallBack()
	 */
	function copyRecord_procFilesRefs($conf, $uid, $value)	{

			// Prepend absolute paths to files:
		if ($conf['type']=='group' && $conf['internal_type']=='file')	{

				// Get an array with files as values:
			if ($conf['MM'])	{
				$theFileValues = array();

				$dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
				$dbAnalysis->start('', 'files', $conf['MM'], $uid);

				foreach($dbAnalysis->itemArray as $somekey => $someval)	{
					if ($someval['id'])	{
						$theFileValues[] = $someval['id'];
					}
				}
			} else {
				$theFileValues = t3lib_div::trimExplode(',',$value,1);
			}

				// Traverse this array of files:
			$uploadFolder = $conf['uploadfolder'];
			$dest = $this->destPathFromUploadFolder($uploadFolder);
			$newValue = array();

			foreach($theFileValues as $file)	{
				if (trim($file))	{
					$realFile = $dest.'/'.trim($file);
					if (@is_file($realFile))	{
						$newValue[] = $realFile;
					}
				}
			}

				// Implode the new filelist into the new value (all files have absolute paths now which means they will get copied when entering TCEmain as new values...)
			$value = implode(',',$newValue);
		}

			// Return the new value:
		return $value;
	}













	/*********************************************
	 *
	 * Cmd: Moving, Localizing
	 *
	 ********************************************/

	/**
	 * Moving single records
	 *
	 * @param	string		Table name to move
	 * @param	integer		Record uid to move
	 * @param	integer		Position to move to: $destPid: >=0 then it points to a page-id on which to insert the record (as the first element). <0 then it points to a uid from its own table after which to insert it (works if
	 * @return	void
	 */
	function moveRecord($table,$uid,$destPid)	{
		global $TCA, $TYPO3_CONF_VARS;

		if ($TCA[$table])	{

				// Prepare user defined objects (if any) for hooks which extend this function:
			$hookObjectsArr = array();
			if (is_array ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['moveRecordClass'])) {
				foreach ($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['moveRecordClass'] as $classRef) {
					$hookObjectsArr[] = &t3lib_div::getUserObj($classRef);
				}
			}

				// In case the record to be moved turns out to be an offline version, we have to find the live version and work on that one (this case happens for pages with "branch" versioning type)
			if ($lookForLiveVersion = t3lib_BEfunc::getLiveVersionOfRecord($table,$uid,'uid'))	{
				$uid = $lookForLiveVersion['uid'];
			}

				// Get workspace version of the source record, if any:
			$WSversion = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $uid, 'uid,t3ver_oid');

				// Initialize:
			$sortRow = $TCA[$table]['ctrl']['sortby'];
			$destPid = intval($destPid);
			$origDestPid = $destPid;

			$propArr = $this->getRecordProperties($table,$uid);	// Get this before we change the pid (for logging)
			$moveRec = $this->getRecordProperties($table,$uid,TRUE);
			$resolvedPid = $this->resolvePid($table,$destPid);	// This is the actual pid of the moving to destination

				// Finding out, if the record may be moved from where it is. If the record is a non-page, then it depends on edit-permissions.
				// If the record is a page, then there are two options: If the page is moved within itself, (same pid) it's edit-perms of the pid. If moved to another place then its both delete-perms of the pid and new-page perms on the destination.
			if ($table!='pages' || $resolvedPid==$moveRec['pid'])	{
				$mayMoveAccess = $this->checkRecordUpdateAccess($table,$uid);	// Edit rights for the record...
			} else {
				$mayMoveAccess = $this->doesRecordExist($table,$uid,'delete');
			}

				// Finding out, if the record may be moved TO another place. Here we check insert-rights (non-pages = edit, pages = new), unless the pages are moved on the same pid, then edit-rights are checked
			if ($table!='pages' || $resolvedPid!=$moveRec['pid'])	{
				$mayInsertAccess = $this->checkRecordInsertAccess($table,$resolvedPid,4);	// Insert rights for the record...
			} else {
				$mayInsertAccess = $this->checkRecordUpdateAccess($table,$uid);
			}

				// Check workspace permissions:
			$workspaceAccessBlocked = array();
			$recIsNewVersion = !strcmp($moveRec['_ORIG_pid'],'') && (int)$moveRec['t3ver_state']==1;	// Element was an online version AND it was in "New state" so it can be moved...
			$destRes = $this->BE_USER->workspaceAllowLiveRecordsInPID($resolvedPid,$table);
				// Workspace source check:
			if ($errorCode = $this->BE_USER->workspaceCannotEditRecord($table, $WSversion['uid'] ? $WSversion['uid'] : $uid))	{
				$workspaceAccessBlocked['src1']='Record could not be edited in workspace: '.$errorCode.' ';
			} else {
				if (!$recIsNewVersion && $this->BE_USER->workspaceAllowLiveRecordsInPID($moveRec['pid'],$table)<=0)	{
					$workspaceAccessBlocked['src2']='Could not remove record from table "'.$table.'" from its page "'.$moveRec['pid'].'" ';
				}
			}
				// Workspace destination check:
			if (!($destRes>0 || ($recIsNewVersion && !$destRes)))	{	// All records can be inserted if $destRes is greater than zero. Only new versions can be inserted if $destRes is false. NO RECORDS can be inserted if $destRes is negative which indicates a stage not allowed for use.
				$workspaceAccessBlocked['dest1']='Could not insert record from table "'.$table.'" in destination PID "'.$resolvedPid.'" ';
			} elseif ($destRes==1 && $WSversion['uid'])	{
				$workspaceAccessBlocked['dest2']='Could not insert other versions in destination PID ';
			}

				// Checking if the pid is negative, but no sorting row is defined. In that case, find the correct pid. Basically this check make the error message 4-13 meaning less... But you can always remove this check if you prefer the error instead of a no-good action (which is to move the record to its own page...)
			if (($destPid<0 && !$sortRow) || $destPid>=0)	{	// $destPid>=0 because we must correct pid in case of versioning "page" types.
				$destPid = $resolvedPid;
			}

				// Timestamp field:
			$updateFields = array();
			if ($TCA[$table]['ctrl']['tstamp'])	{
				$updateFields[$TCA[$table]['ctrl']['tstamp']] = time();
			}

					// If moving is allowed, begin the processing:
			if (!count($workspaceAccessBlocked))	{
				if ($mayMoveAccess)	{
					if ($destPid>=0)	{	// insert as first element on page (where uid = $destPid)
						if ($mayInsertAccess)	{
							if ($table!='pages' || $this->destNotInsideSelf($destPid,$uid))	{
								$this->clear_cache($table,$uid);	// clear cache before moving

								$updateFields['pid'] = $destPid;	// Setting PID

									// table is sorted by 'sortby'
								if ($sortRow)	{
									$sortNumber = $this->getSortNumber($table,$uid,$destPid);
									$updateFields[$sortRow] = $sortNumber;
								}
									// Create query for update:
								$GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);

									// Call post processing hooks:
								foreach($hookObjectsArr as $hookObj) {
									if (method_exists($hookObj, 'moveRecord_firstElementPostProcess')) {
										$hookObj->moveRecord_firstElementPostProcess($table, $uid, $destPid, $moveRec, $updateFields, $this);
									}
								}

									// Logging...
								$newPropArr = $this->getRecordProperties($table,$uid);
								$oldpagePropArr = $this->getRecordProperties('pages',$propArr['pid']);
								$newpagePropArr = $this->getRecordProperties('pages',$destPid);

								if ($destPid!=$propArr['pid'])	{
									$this->log($table,$uid,4,$destPid,0,"Moved record '%s' (%s) to page '%s' (%s)",2,array($propArr['header'],$table.':'.$uid, $newpagePropArr['header'], $newPropArr['pid']),$propArr['pid']);	// Logged to old page
									$this->log($table,$uid,4,$destPid,0,"Moved record '%s' (%s) from page '%s' (%s)",3,array($propArr['header'],$table.':'.$uid, $oldpagePropArr['header'], $propArr['pid']),$destPid);	// Logged to new page
								} else {
									$this->log($table,$uid,4,$destPid,0,"Moved record '%s' (%s) on page '%s' (%s)",4,array($propArr['header'],$table.':'.$uid, $oldpagePropArr['header'], $propArr['pid']),$destPid);	// Logged to new page
								}
								$this->clear_cache($table,$uid);	// clear cache after moving
								$this->fixUniqueInPid($table,$uid);
									// fixCopyAfterDuplFields
								if ($origDestPid<0)	{$this->fixCopyAfterDuplFields($table,$uid,abs($origDestPid),1);}	// origDestPid is retrieve before it may possibly be converted to resolvePid if the table is not sorted anyway. In this way, copying records to after another records which are not sorted still lets you use this function in order to copy fields from the one before.
							} else {
								$destPropArr = $this->getRecordProperties('pages',$destPid);
								$this->log($table,$uid,4,0,1,"Attempt to move page '%s' (%s) to inside of its own rootline (at page '%s' (%s))",10,array($propArr['header'],$uid, $destPropArr['header'], $destPid),$propArr['pid']);
							}
						}
					} else {	// Put after another record
						if ($sortRow)	{	// table is being sorted
							$sortInfo = $this->getSortNumber($table,$uid,$destPid);
							$destPid = $sortInfo['pid'];	// Setting the destPid to the new pid of the record.
							if (is_array($sortInfo))	{	// If not an array, there was an error (which is already logged)
								if ($mayInsertAccess)	{
									if ($table!='pages' || $this->destNotInsideSelf($destPid,$uid))	{
										$this->clear_cache($table,$uid);	// clear cache before moving

											// We now update the pid and sortnumber
										$updateFields['pid'] = $destPid;
										$updateFields[$sortRow] = $sortInfo['sortNumber'];
										$GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);

											// Call post processing hooks:
										foreach($hookObjectsArr as $hookObj) {
											if (method_exists($hookObj, 'moveRecord_afterAnotherElementPostProcess')) {
												$hookObj->moveRecord_afterAnotherElementPostProcess($table, $uid, $destPid, $origDestPid, $moveRec, $updateFields, $this);
											}
										}

											// Logging...
										$newPropArr = $this->getRecordProperties($table,$uid);
										$oldpagePropArr = $this->getRecordProperties('pages',$propArr['pid']);
										if ($destPid!=$propArr['pid'])	{
											$newpagePropArr = $this->getRecordProperties('pages',$destPid);
											$this->log($table,$uid,4,0,0,"Moved record '%s' (%s) to page '%s' (%s)",2,array($propArr['header'],$table.':'.$uid, $newpagePropArr['header'], $newPropArr['pid']),$propArr['pid']);	// Logged to old page
											$this->log($table,$uid,4,0,0,"Moved record '%s' (%s) from page '%s' (%s)",3,array($propArr['header'],$table.':'.$uid, $oldpagePropArr['header'], $propArr['pid']),$destPid);	// Logged to new page
										} else {
											$this->log($table,$uid,4,0,0,"Moved record '%s' (%s) on page '%s' (%s)",4,array($propArr['header'],$table.':'.$uid, $oldpagePropArr['header'], $propArr['pid']),$destPid);	// Logged to new page
										}

											// clear cache after moving
										$this->clear_cache($table,$uid);

											// fixUniqueInPid
										$this->fixUniqueInPid($table,$uid);

											// fixCopyAfterDuplFields
										if ($origDestPid<0)	{$this->fixCopyAfterDuplFields($table,$uid,abs($origDestPid),1);}
									} else {
										$destPropArr = $this->getRecordProperties('pages',$destPid);
										$this->log($table,$uid,4,0,1,"Attempt to move page '%s' (%s) to inside of its own rootline (at page '%s' (%s))",10,array($propArr['header'],$uid, $destPropArr['header'], $destPid),$propArr['pid']);
									}
								}
							}
						} else {
							$this->log($table,$uid,4,0,1,"Attempt to move record '%s' (%s) to after another record, although the table has no sorting row.",13,array($propArr['header'],$table.':'.$uid),$propArr['event_pid']);
						}
					}
				} else {
					$this->log($table,$uid,4,0,1,"Attempt to move record '%s' (%s) without having permissions to do so",14,array($propArr['header'],$table.':'.$uid),$propArr['event_pid']);
				}
			} else {
				$this->newlog("Move attempt failed due to workspace restrictions: ".implode(' ',$workspaceAccessBlocked),1);
			}
		}
	}

	/**
	 * Localizes a record to another system language
	 *
	 * @param	string		Table name
	 * @param	integer		Record uid (to be localized)
	 * @param	integer		Language ID (from sys_language table)
	 * @return	void
	 */
	function localize($table,$uid,$language)	{
		global $TCA;

		$uid = intval($uid);

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

			if ($TCA[$table]['ctrl']['languageField'] && $TCA[$table]['ctrl']['transOrigPointerField'])	{
				if ($langRec = t3lib_BEfunc::getRecord('sys_language',intval($language),'uid,title'))	{
					if ($this->doesRecordExist($table,$uid,'show'))	{

						$row = t3lib_BEfunc::getRecordWSOL($table,$uid);	// Getting workspace overlay if possible - this will localize versions in workspace if any
						if (is_array($row))	{
							if ($row[$TCA[$table]['ctrl']['languageField']] <= 0)	{
								if ($row[$TCA[$table]['ctrl']['transOrigPointerField']] == 0)	{
									if (!t3lib_BEfunc::getRecordsByField($table,$TCA[$table]['ctrl']['transOrigPointerField'],$uid,'AND pid='.intval($row['pid']).' AND '.$TCA[$table]['ctrl']['languageField'].'='.intval($langRec['uid'])))	{

											// Initialize:
										$overrideValues = array();
										$excludeFields = array();

											// Set override values:
										$overrideValues[$TCA[$table]['ctrl']['languageField']] = $langRec['uid'];
										$overrideValues[$TCA[$table]['ctrl']['transOrigPointerField']] = $uid;

											// Set exclude Fields:
										foreach($TCA[$table]['columns'] as $fN => $fCfg)	{
											if ($fCfg['l10n_mode']=='prefixLangTitle')	{	// Check if we are just prefixing:
												if (($fCfg['config']['type']=='text' || $fCfg['config']['type']=='input') && strlen($row[$fN]))	{
													list($tscPID) = t3lib_BEfunc::getTSCpid($table,$uid,'');
													$TSConfig = $this->getTCEMAIN_TSconfig($tscPID);

													if (isset($TSConfig['translateToMessage']) && strlen($TSConfig['translateToMessage']))	{
														$translateToMsg = @sprintf($TSConfig['translateToMessage'], $langRec['title']);
													}
													if (!strlen($translateToMsg))	{
														$translateToMsg = 'Translate to '.$langRec['title'].':';
													}

													$overrideValues[$fN] = '['.$translateToMsg.'] '.$row[$fN];
												}
											} elseif (t3lib_div::inList('exclude,noCopy,mergeIfNotBlank',$fCfg['l10n_mode']) && $fN!=$TCA[$table]['ctrl']['languageField'] && $fN!=$TCA[$table]['ctrl']['transOrigPointerField']) {	 // Otherwise, do not copy field (unless it is the language field or pointer to the original language)
												$excludeFields[] = $fN;
											}
										}
											// Execute the copy:
										$this->copyRecord($table,$uid,-$uid,1,$overrideValues,implode(',',$excludeFields));
									} else $this->newlog('Localization failed; There already was a localization for this language of the record!',1);
								} else $this->newlog('Localization failed; Source record contained a reference to an original default record (which is strange)!',1);
							} else $this->newlog('Localization failed; Source record had another language than "Default" or "All" defined!',1);
						} else $this->newlog('Attempt to localize record that did not exist!',1);
					} else $this->newlog('Attempt to localize record without permission',1);
				} else $this->newlog('Sys language UID "'.$language.'" not found valid!',1);
			} else $this->newlog('Localization failed; "languageField" and "transOrigPointerField" must be defined for the table!',1);
		}
	}














	/*********************************************
	 *
	 * Cmd: Deleting
	 *
	 ********************************************/

	/**
	 * Delete a single record
	 *
	 * @param	string		Table name
	 * @param	integer		Record UID
	 * @return	void
	 */
	function deleteAction($table, $id)	{
		global $TCA;

		$delRec = t3lib_BEfunc::getRecord($table, $id);

		if (is_array($delRec))	{	// Record asked to be deleted was found:

				// For Live version, try if there is a workspace version because if so, rather "delete" that instead
			if ($delRec['pid']!=-1)	{	// Look, if record is an offline version, then delete directly:
				if ($wsVersion = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, $table, $id))	{
					$delRec = $wsVersion;
					$id = $delRec['uid'];
				}
			}

			if ($delRec['pid']==-1)	{	// Look, if record is an offline version, then delete directly:
				if ($TCA[$table]['ctrl']['versioningWS'])	{
					if ($this->BE_USER->workspace==0 || (int)$delRec['t3ver_wsid']==$this->BE_USER->workspace)	{	// In Live workspace, delete any. In other workspaces there must be match.
						$liveRec = t3lib_BEfunc::getLiveVersionOfRecord($table,$id,'uid,t3ver_state');

						if ($delRec['t3ver_wsid']==0 || (int)$liveRec['t3ver_state']!==1)	{	// Delete those in WS 0 + if their live records state was not "Placeholder".
							$this->deleteEl($table, $id);
						} else {	// If live record was placeholder, rather clear it from workspace (because it clears both version and placeholder).
							$this->version_clearWSID($table,$id);
						}
					} else $this->newlog('Tried to delete record from another workspace',1);
				} else $this->newlog('Versioning not enabled for record with PID = -1!',2);
			} elseif ($res = $this->BE_USER->workspaceAllowLiveRecordsInPID($delRec['pid'], $table))	{	// Look, if record is "online" or in a versionized branch, then delete directly.
				if ($res>0)	{
					$this->deleteEl($table, $id);
				} else $this->newlog('Stage of root point did not allow for deletion',1);
			} else {
				// Otherwise, try to delete by versionization:
				$this->versionizeRecord($table,$id,'DELETED!',TRUE);
			}
		}
	}

	/**
	 * Delete element from any table
	 *
	 * @param	string		Table name
	 * @param	integer		Record UID
	 * @param	boolean		Flag: If $noRecordCheck is set, then the function does not check permission to delete record
	 * @param	boolean		If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
	 * @return	void
	 */
	function deleteEl($table, $uid, $noRecordCheck=FALSE, $forceHardDelete=FALSE)	{
		if ($table == 'pages')	{
			$this->deletePages($uid, $noRecordCheck, $forceHardDelete);
		} else {
			$this->deleteRecord($table, $uid, $noRecordCheck, $forceHardDelete);
		}
	}

	/**
	 * Undelete a single record
	 *
	 * @param	string		Table name
	 * @param	integer		Record UID
	 * @return	void
	 */
	function undeleteRecord($table,$uid)	{
		$this->deleteRecord($table,$uid,TRUE,FALSE,TRUE);
	}

	/**
	 * Deleting/Undeleting a record
	 * This function may not be used to delete pages-records unless the underlying records are already deleted
	 * Deletes a record regardless of versioning state (live of offline, doesn't matter, the uid decides)
	 * If both $noRecordCheck and $forceHardDelete are set it could even delete a "deleted"-flagged record!
	 *
	 * @param	string		Table name
	 * @param	integer		Record UID
	 * @param	boolean		Flag: If $noRecordCheck is set, then the function does not check permission to delete record
	 * @param	boolean		If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
	 * @param	boolean		If TRUE, the "deleted" flag is set to 0 again and thus, the item is undeleted.
	 * @return	void
	 */
	function deleteRecord($table,$uid, $noRecordCheck=FALSE, $forceHardDelete=FALSE,$undeleteRecord=FALSE)	{
		global $TCA;

		$uid = intval($uid);
		if ($TCA[$table] && $uid)	{
			if ($noRecordCheck || $this->doesRecordExist($table,$uid,'delete'))	{
				$this->clear_cache($table,$uid);	// clear cache before deleting the record, else the correct page cannot be identified by clear_cache

				$propArr = $this->getRecordProperties($table, $uid);
				$pagePropArr = $this->getRecordProperties('pages', $propArr['pid']);

				$deleteRow = $TCA[$table]['ctrl']['delete'];
				if ($deleteRow && !$forceHardDelete)	{
					$value = $undeleteRecord ? 0 : 1;
					$updateFields = array(
						$deleteRow => $value
					);

					if ($TCA[$table]['ctrl']['tstamp']) {
						$updateFields[$TCA[$table]['ctrl']['tstamp']] = time();
					}

						// If the table is sorted, then the sorting number is set very high
					if ($TCA[$table]['ctrl']['sortby'] && !$undeleteRecord)	{
						$updateFields[$TCA[$table]['ctrl']['sortby']] = 1000000000;
					}

					$GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), $updateFields);
				} else {

						// Fetches all fields that holds references to files
					$fileFieldArr = $this->extFileFields($table);
					if (count($fileFieldArr))	{
						$mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(implode(',',$fileFieldArr), $table, 'uid='.intval($uid));
						if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres))	{
							$fArray = $fileFieldArr;
							foreach($fArray as $theField)	{	// MISSING: Support for MM file relations!
								$this->extFileFunctions($table,$theField,$row[$theField],'deleteAll');		// This deletes files that belonged to this record.
							}
						} else {
							$this->log($table,$uid,3,0,100,'Delete: Zero rows in result when trying to read filenames from record which should be deleted');
						}
					}

					$GLOBALS['TYPO3_DB']->exec_DELETEquery($table, 'uid='.intval($uid));
				}

				$state = $undeleteRecord ? 1 : 3;	// 1 means insert, 3 means delete
				if (!$GLOBALS['TYPO3_DB']->sql_error())	{
					if ($forceHardDelete) {
						$message = "Record '%s' (%s) was deleted unrecoverable from page '%s' (%s)";
					}
					else {
						$message = $state == 1 ?
							"Record '%s' (%s) was restored on page '%s' (%s)" :
							"Record '%s' (%s) was deleted from page '%s' (%s)";
					}
					$this->log($table, $uid, $state, 0, 0,
								$message, 0,
								array(
									$propArr['header'],
									$table.':'.$uid,
									$pagePropArr['header'],
									$propArr['pid']
									),
								$propArr['pid']);

				} else {
					$this->log($table,$uid,$state,0,100,$GLOBALS['TYPO3_DB']->sql_error());
				}

					// Update reference index:
				$this->updateRefIndex($table,$uid);

			} else $this->log($table,$uid,3,0,1,'Attempt to delete record without delete-permissions');
		}
	}

	/**
	 * Used to delete page because it will check for branch below pages and unallowed tables on the page as well.
	 *
	 * @param	integer		Page id
	 * @param	boolean		If TRUE, pages are not checked for permission.
	 * @param	boolean		If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
	 * @return	void
	 */
	function deletePages($uid,$force=FALSE,$forceHardDelete=FALSE)	{
			// Getting list of pages to delete:
		if ($force)	{
			$brExist = $this->doesBranchExist('',$uid,0,1);		// returns the branch WITHOUT permission checks (0 secures that)
			$res = t3lib_div::trimExplode(',',$brExist.$uid,1);
		} else {
			$res = $this->canDeletePage($uid);
		}

			// Perform deletion if not error:
		if (is_array($res))	{
			foreach($res as $deleteId)	{
				$this->deleteSpecificPage($deleteId,$forceHardDelete);
			}
		} else {
			$this->newlog($res,1);
		}
	}

	/**
	 * Delete a page and all records on it.
	 *
	 * @param	integer		Page id
	 * @param	boolean		If TRUE, the "deleted" flag is ignored if applicable for record and the record is deleted COMPLETELY!
	 * @return	void
	 * @access private
	 * @see deletePages()
	 */
	function deleteSpecificPage($uid,$forceHardDelete=FALSE)	{
		global $TCA;
		reset ($TCA);
		$uid = intval($uid);
		if ($uid)	{
			while (list($table)=each($TCA))	{
				if ($table!='pages')	{
					$mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, 'pid='.intval($uid).$this->deleteClause($table));
					while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres))	{
						$this->deleteRecord($table,$row['uid'], TRUE, $forceHardDelete);
					}
				}
			}
			$this->deleteRecord('pages',$uid, TRUE, $forceHardDelete);
		}
	}

	/**
	 * Used to evaluate if a page can be deleted
	 *
	 * @param	integer		Page id
	 * @return	mixed		If array: List of page uids to traverse and delete (means OK), if string: error code.
	 */
	function canDeletePage($uid)	{
		if ($this->doesRecordExist('pages',$uid,'delete'))	{	// If we may at all delete this page
			if ($this->deleteTree)	{
				$brExist = $this->doesBranchExist('',$uid,$this->pMap['delete'],1);	// returns the branch
				if ($brExist != -1)	{	// Checks if we had permissions
					if ($this->noRecordsFromUnallowedTables($brExist.$uid))	{
						return t3lib_div::trimExplode(',',$brExist.$uid,1);
					} else return 'Attempt to delete records from disallowed tables';
				} else return 'Attempt to delete pages in branch without permissions';
			} else {
				$brExist = $this->doesBranchExist('',$uid,$this->pMap['delete'],1);	// returns the branch
				if ($brExist == '')	{	// Checks if branch exists
					if ($this->noRecordsFromUnallowedTables($uid))	{
						return array($uid);
					} else return 'Attempt to delete records from disallowed tables';
				} else return 'Attempt to delete page which has subpages';
			}
		} else return 'Attempt to delete page without permissions';
	}

	/**
	 * Returns true if record CANNOT be deleted, otherwise false. Used to check before the versioning API allows a record to be marked for deletion.
	 *
	 * @param	string		Record Table
	 * @param	integer		Record UID
	 * @return	string		Returns a string IF there is an error (error string explaining). FALSE means record can be deleted
	 */
	function cannotDeleteRecord($table,$id)	{
		if ($table==='pages')	{
			$res = $this->canDeletePage($id);
			return is_array($res) ? FALSE : $res;
		} else {
			return $this->doesRecordExist($table,$id,'delete') ? FALSE : 'No permission to delete record';
		}
	}












	/*********************************************
	 *
	 * Cmd: Versioning
	 *
	 ********************************************/

	/**
	 * Creates a new version of a record
	 * (Requires support in the table)
	 *
	 * @param	string		Table name
	 * @param	integer		Record uid to versionize
	 * @param	string		Version label
	 * @param	boolean		If true, the version is created to delete the record.
	 * @param	integer		Indicating "treeLevel" - or versioning type - "element" (-1), "page" (0) or "branch" (>=1)
	 * @return	integer		Returns the id of the new version (if any)
	 * @see copyRecord()
	 */
	function versionizeRecord($table,$id,$label,$delete=FALSE,$versionizeTree=-1)	{
		global $TCA;

		$id = intval($id);

		if ($TCA[$table] && $TCA[$table]['ctrl']['versioningWS'] && $id>0)	{
			if ($this->doesRecordExist($table,$id,'show'))	{
				if ($this->BE_USER->workspaceVersioningTypeAccess($versionizeTree))	{

						// Select main record:
					$row = $this->recordInfo($table,$id,'pid,t3ver_id');
					if (is_array($row))	{
						if ($row['pid']>=0)	{	// record must be online record
							if (!$delete || !$this->cannotDeleteRecord($table,$id)) {

									// Look for next version number:
								$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
									't3ver_id',
									$table,
									'(t3ver_oid='.$id.' OR uid='.$id.')'.$this->deleteClause($table),
									'',
									't3ver_id DESC',
									'1'
								);
								list($highestVerNumber) = $GLOBALS['TYPO3_DB']->sql_fetch_row($res);

									// Look for version number of the current:
								$subVer = $row['t3ver_id'].'.'.($highestVerNumber+1);

									// Set up the values to override when making a raw-copy:
								$overrideArray = array(
									't3ver_id' => $highestVerNumber+1,
									't3ver_oid' => $id,
									't3ver_label' => ($label ? $label : $subVer.' / '.date('d-m-Y H:m:s')),
									't3ver_wsid' => $this->BE_USER->workspace,
									't3ver_state' => $delete ? 2 : 0,
									't3ver_count' => 0,
									't3ver_stage' => 0,
									't3ver_tstamp' => 0
								);
								if ($TCA[$table]['ctrl']['editlock'])	{
									$overrideArray[$TCA[$table]['ctrl']['editlock']] = 0;
								}
								if ($table==='pages')	{
									$overrideArray['t3ver_swapmode'] = $versionizeTree;
								}

									// Checking if the record already has a version in the current workspace of the backend user
								$workspaceCheck = TRUE;
								if ($this->BE_USER->workspace!==0)	{
										// Look for version already in workspace:
									$workspaceCheck = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace,$table,$id,'uid') ? FALSE : TRUE;
								}

								if ($workspaceCheck)	{

										// Create raw-copy and return result:
									return $this->copyRecord_raw($table,$id,-1,$overrideArray);
								} else $this->newlog('Record you wanted to versionize was already a version in the workspace (wsid='.$this->BE_USER->workspace.')!',1);
							} else $this->newlog('Record cannot be deleted: '.$this->cannotDeleteRecord($table,$id),1);
						} else $this->newlog('Record you wanted to versionize was already a version in archive (pid=-1)!',1);
					} else $this->newlog('Record you wanted to versionize did not exist!',1);
				} else $this->newlog('The versioning type '.$versionizeTree.' mode you requested was not allowed',1);
			} else $this->newlog('You didnt have correct permissions to make a new version (copy) of this record "'.$table.'" / '.$id,1);
		} else $this->newlog('Versioning is not supported for this table "'.$table.'" / '.$id,1);
	}

	/**
	 * Creates a new version of a page including content and possible subpages.
	 *
	 * @param	integer		Page uid to create new version of.
	 * @param	string		Version label
	 * @param	integer		Indicating "treeLevel" - "page" (0) or "branch" (>=1) ["element" type must call versionizeRecord() directly]
	 * @return	void
	 * @see copyPages()
	 */
	function versionizePages($uid,$label,$versionizeTree)	{
		global $TCA;

		$uid = intval($uid);
		$brExist = $this->doesBranchExist('',$uid,$this->pMap['show'],1);	// returns the branch

		if ($brExist != -1)	{	// Checks if we had permissions

				// Finding list of tables ALLOWED to be copied
			$allowedTablesArray = $this->admin ? $this->compileAdminTables() : explode(',',$this->BE_USER->groupData['tables_modify']);	// These are the tables, the user may modify
			$allowedTablesArray = $this->compileAdminTables();	// These are ALL tables because a new version should be ALL of them regardless of permission of the user executing the request.

				// Make list of tables that should come along with a new version of the page:
			$verTablesArray = array();
			$allTables = array_keys($TCA);
			foreach($allTables as $tN)	{
				if ($tN!='pages' && ($versionizeTree>0 || $TCA[$tN]['ctrl']['versioning_followPages']) && ($this->admin || in_array($tN, $allowedTablesArray)))	{
					$verTablesArray[] = $tN;
				}
			}

				// Begin to copy pages if we're allowed to:
			if ($this->admin || in_array('pages',$allowedTablesArray))	{
				if ($this->BE_USER->workspaceVersioningTypeAccess($versionizeTree))	{
						// Versionize this page:
					$theNewRootID = $this->versionizeRecord('pages',$uid,$label,FALSE,$versionizeTree);
					if ($theNewRootID)	{
						$this->rawCopyPageContent($uid,$theNewRootID,$verTablesArray);

							// If we're going to copy recursively...:
						if ($versionizeTree>0)	{

								// Get ALL subpages to copy (read permissions respected - they should NOT be...):
							$CPtable = $this->int_pageTreeInfo(Array(), $uid, intval($versionizeTree), $theNewRootID);

								// Now copying the subpages:
							foreach($CPtable as $thePageUid => $thePagePid)	{
								$newPid = $this->copyMappingArray['pages'][$thePagePid];
								if (isset($newPid))	{
									$theNewRootID = $this->copyRecord_raw('pages',$thePageUid,$newPid);
									$this->rawCopyPageContent($thePageUid,$theNewRootID,$verTablesArray);
								} else {
									$this->newlog('Something went wrong during copying branch (for versioning)',1);
									break;
								}
							}
						}	// else the page was not copied. Too bad...
					} else $this->newlog('The root version could not be created!',1);
				} else $this->newlog('Versioning type "'.$versionizeTree.'" was not allowed in workspace',1);
			} else $this->newlog('Attempt to versionize page without permission to this table',1);
		} else $this->newlog('Could not read all subpages to versionize.',1);
	}

	/**
	 * Swapping versions of a record
	 * Version from archive (future/past, called "swap version") will get the uid of the "t3ver_oid", the official element with uid = "t3ver_oid" will get the new versions old uid. PIDs are swapped also
	 *
	 * @param	string		Table name
	 * @param	integer		UID of the online record to swap
	 * @param	integer		UID of the archived version to swap with!
	 * @param	boolean		If set, swaps online into workspace instead of publishing out of workspace.
	 * @return	void
	 */
	function version_swap($table,$id,$swapWith,$swapIntoWS=0)	{
		global $TCA;

		/*
		Version ID swapping principles:
		  - Version from archive (future/past, called "swap version") will get the uid of the "t3ver_oid", the official element with uid = "t3ver_oid" will get the new versions old uid. PIDs are swapped also

			uid		pid			uid		t3ver_oid	pid
		1:	13		123	 -->	-13		247			123		(Original has negated UID, and sets t3ver_oid to the final UID (which is nice to know for recovery). PID is unchanged at this point)
		2:	247		-1	 -->	13		13			123		(Swap version gets original UID, correct t3ver_oid (not required for online version) and is moved to the final PID (123))
		3:	-13		123	 -->	247		13			-1		(Original gets the swap versions old UID, has t3ver_oid set correctly (important) and the ver. repository PID set right.)

			13 is online UID,
			247 is specific versions UID
			123 is the PID of the original record
			-1 is the versioning repository PID

			Recovery Process:
				Search for negative UID (here "-13"):
					YES: Step 1 completed, but at least step 3 didn't.
						Search for the negativ UIDs positive (here: "13")
							YES: Step 2 completed: Rollback: "t3ver_oid" of the -uid record shows the original UID of the swap record. Use that to change back UID and pid to -1. After that, proceed with recovery for step 1 (see below)
							NO: Only Step 1 completed! Rollback: Just change uid "-13" to "13" and "t3ver_oid" to "13" (not important)
					NO: No problems.
		*/

			// First, check if we may actually edit the online record
		if ($this->checkRecordUpdateAccess($table,$id))	{

				// Select the two versions:
			$curVersion = t3lib_BEfunc::getRecord($table,$id,'*');
			$swapVersion = t3lib_BEfunc::getRecord($table,$swapWith,'*');

			if (is_array($curVersion) && is_array($swapVersion))	{
				if ($this->BE_USER->workspacePublishAccess($swapVersion['t3ver_wsid']))	{
					$wsAccess = $this->BE_USER->checkWorkspace($swapVersion['t3ver_wsid']);
					if ($swapVersion['t3ver_wsid']<=0 || !($wsAccess['publish_access']&1) || (int)$swapVersion['t3ver_stage']===10)	{
						if ($this->doesRecordExist($table,$swapWith,'show') && $this->checkRecordUpdateAccess($table,$swapWith)) {
							if (!$swapIntoWS || $this->BE_USER->workspaceSwapAccess())	{

									// Check if the swapWith record really IS a version of the original!
								if ((int)$swapVersion['pid']==-1 && (int)$curVersion['pid']>=0 && !strcmp($swapVersion['t3ver_oid'],$id))	{

										// Lock file name:
									$lockFileName = PATH_site.'typo3temp/swap_locking/'.$table.':'.$id.'.ser';

									if (!@is_file($lockFileName))	{

											// Write lock-file:
										t3lib_div::writeFileToTypo3tempDir($lockFileName,serialize(array(
											'tstamp'=>time(),
											'user'=>$GLOBALS['BE_USER']->user['username'],
											'curVersion'=>$curVersion,
											'swapVersion'=>$swapVersion
										)));

											// Find fields to keep
										$keepFields = $this->getUniqueFields($table);
										if ($TCA[$table]['ctrl']['sortby'])	{
											$keepFields[] = $TCA[$table]['ctrl']['sortby'];
										}

											// Swap "keepfields"
										foreach($keepFields as $fN)	{
											$tmp = $swapVersion[$fN];
											$swapVersion[$fN] = $curVersion[$fN];
											$curVersion[$fN] = $tmp;
										}

											// Preserve states:
										$t3ver_state = array();
										$t3ver_state['swapVersion'] = $swapVersion['t3ver_state'];
										$t3ver_state['curVersion'] = $curVersion['t3ver_state'];

											// Modify offline version to become online:
										$tmp_wsid = $swapVersion['t3ver_wsid'];
										unset($swapVersion['uid']);
										$swapVersion['pid'] = intval($curVersion['pid']);	// Set pid for ONLINE
										$swapVersion['t3ver_oid'] = intval($id);
										$swapVersion['t3ver_wsid'] = $swapIntoWS ? intval($curVersion['t3ver_wsid']) : 0;
										$swapVersion['t3ver_tstamp'] = time();
										$swapVersion['t3ver_stage'] = $swapVersion['t3ver_state'] = 0;

											// Modify online version to become offline:
										unset($curVersion['uid']);
										$curVersion['pid'] = -1;	// Set pid for OFFLINE
										$curVersion['t3ver_oid'] = intval($id);
										$curVersion['t3ver_wsid'] = $swapIntoWS ? intval($tmp_wsid) : 0;
										$curVersion['t3ver_tstamp'] = time();
										$curVersion['t3ver_count'] = $curVersion['t3ver_count']+1;	// Increment lifecycle counter
										$curVersion['t3ver_stage'] = $curVersion['t3ver_state'] = 0;

										if ($table==='pages') {		// Keeping the swapmode state
												$curVersion['t3ver_swapmode'] = $swapVersion['t3ver_swapmode'];
										}

											// Execute swapping:
										$sqlErrors = array();
										$GLOBALS['TYPO3_DB']->exec_UPDATEquery($table,'uid='.intval($id),$swapVersion);
										if ($GLOBALS['TYPO3_DB']->sql_error())		{
											$sqlErrors[] = $GLOBALS['TYPO3_DB']->sql_error();
										} else {
											$GLOBALS['TYPO3_DB']->exec_UPDATEquery($table,'uid='.intval($swapWith),$curVersion);
											if ($GLOBALS['TYPO3_DB']->sql_error())	{
												$sqlErrors[]=$GLOBALS['TYPO3_DB']->sql_error();
											} else {
												unlink($lockFileName);
											}
										}

										if (!count($sqlErrors))	{

												// Checking for delete:
											if ($t3ver_state['swapVersion']==2)	{
												$this->deleteEl($table,$id,TRUE);	// Force delete
											}

											$this->newlog('Swapping successful for table "'.$table.'" uid '.$id.'=>'.$swapWith);

												// Update reference index:
											$this->updateRefIndex($table,$id);
											$this->updateRefIndex($table,$swapWith);

												// SWAPPING pids for subrecords:
											if ($table=='pages' && $swapVersion['t3ver_swapmode']>=0)	{

													// Collect table names that should be copied along with the tables:
												foreach($TCA as $tN => $tCfg)	{
													if ($swapVersion['t3ver_swapmode']>0 || $TCA[$tN]['ctrl']['versioning_followPages'])	{	// For "Branch" publishing swap ALL, otherwise for "page" publishing, swap only "versioning_followPages" tables
														$temporaryPid = -($id+1000000);

														$GLOBALS['TYPO3_DB']->exec_UPDATEquery($tN,'pid='.intval($id),array('pid'=>$temporaryPid));
														if ($GLOBALS['TYPO3_DB']->sql_error())	$sqlErrors[]=$GLOBALS['TYPO3_DB']->sql_error();

														$GLOBALS['TYPO3_DB']->exec_UPDATEquery($tN,'pid='.intval($swapWith),array('pid'=>$id));
														if ($GLOBALS['TYPO3_DB']->sql_error())	$sqlErrors[]=$GLOBALS['TYPO3_DB']->sql_error();

														$GLOBALS['TYPO3_DB']->exec_UPDATEquery($tN,'pid='.intval($temporaryPid),array('pid'=>$swapWith));
														if ($GLOBALS['TYPO3_DB']->sql_error())	$sqlErrors[]=$GLOBALS['TYPO3_DB']->sql_error();

														if (count($sqlErrors))	{
															$this->newlog('During Swapping: SQL errors happend: '.implode('; ',$sqlErrors),2);
														}
													}
												}
											}
												// Clear cache:
											$this->clear_cache($table,$id);

												// Checking for "new-placeholder" and if found, delete it (BUT FIRST after swapping!):
											if ($t3ver_state['curVersion']==1)	{
												$this->deleteEl($table, $swapWith, TRUE, TRUE); 	// For delete + completely delete!
											}
										} else $this->newlog('During Swapping: SQL errors happend: '.implode('; ',$sqlErrors),2);
									} else $this->newlog('A swapping lock file was present. Either another swap process is already running or a previous swap process failed. Ask your administrator to handle the situation.',2);
								} else $this->newlog('In swap version, either pid was not -1 or the t3ver_oid didn\'t match the id of the online version as it must!',2);
							} else $this->newlog('Workspace #'.$swapVersion['t3ver_wsid'].' does not support swapping.',1);
						} else $this->newlog('You cannot publish a record you do not have edit and show permissions for',1);
					} else $this->newlog('Records in workspace #'.$swapVersion['t3ver_wsid'].' can only be published when in "Publish" stage.',1);
				} else $this->newlog('User could not publish records from workspace #'.$swapVersion['t3ver_wsid'],1);
			} else $this->newlog('Error: Either online or swap version could not be selected!',2);
		} else $this->newlog('Error: You cannot swap versions for a record you do not have access to edit!',1);
	}

	/**
	 * Release version from this workspace (and into "Live" workspace but as an offline version).
	 *
	 * @param	string		Table name
	 * @param	integer		Record UID
	 * @return	void
	 */
	function version_clearWSID($table,$id)	{
		if ($errorCode = $this->BE_USER->workspaceCannotEditOfflineVersion($table, $id))	{
			$this->newlog('Attempt to reset workspace for record failed: '.$errorCode,1);
		} elseif ($this->checkRecordUpdateAccess($table,$id)) {
			if ($liveRec = t3lib_BEfunc::getLiveVersionOfRecord($table,$id,'uid,t3ver_state'))	{
					// Clear workspace ID:
				$sArray = array();
				$sArray['t3ver_wsid'] = 0;
				$GLOBALS['TYPO3_DB']->exec_UPDATEquery($table,'uid='.intval($id),$sArray);

					// Clear workspace ID for live version AND DELETE IT as well because it is a new record!
				if ((int)$liveRec['t3ver_state']===1)	{
					$GLOBALS['TYPO3_DB']->exec_UPDATEquery($table,'uid='.intval($liveRec['uid']),$sArray);
					$this->deleteEl($table, $liveRec['uid'], TRUE);	// THIS assumes that the record was placeholder ONLY for ONE record (namely $id)
				}

					// If "deleted" flag is set for the version that got released it doesn't make sense to keep that "placeholder" anymore and we delete it completly.
				$wsRec = t3lib_BEfunc::getRecord($table,$id);
				if ((int)$wsRec['t3ver_state']===2)	{
					$this->deleteEl($table, $id, TRUE, TRUE);
				}
			}
		} else $this->newlog('Attempt to reset workspace for record failed because you do not have edit access',1);
	}

	/**
	 * Setting stage of record
	 *
	 * @param	string		Table name
	 * @param	integer		Record UID
	 * @param	integer		Stage ID to set
	 * @param	string		Comment that goes into log
	 * @return	void
	 */
	function version_setStage($table,$id,$stageId,$comment='')	{
		if ($errorCode = $this->BE_USER->workspaceCannotEditOfflineVersion($table, $id))	{
			$this->newlog('Attempt to set stage for record failed: '.$errorCode,1);
		} elseif ($this->checkRecordUpdateAccess($table,$id)) {
			$stat = $this->BE_USER->checkWorkspaceCurrent();
			if (t3lib_div::inList('admin,online,offline,reviewer,owner', $stat['_ACCESS']) || ($stageId<=1 && $stat['_ACCESS']==='member'))	{

					// Set stage of record:
				$sArray = array();
				$sArray['t3ver_stage'] = $stageId;
				$GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($id), $sArray);
				$this->newlog('Stage for record was changed to '.$stageId.'. Comment was: "'.substr($comment,0,100).'"');
// TEMPORARY, except 6-30 as action/detail number which is observed elsewhere!
$this->log($table,$id,6,0,0,'Stage raised...',30,array('comment'=>$comment,'stage'=>$stageId));

				if ((int)$stat['stagechg_notification']>0)	{
					$this->notifyStageChange($stat,$stageId,$table,$id,$comment);
				}
			} else $this->newlog('The member user tried to set a stage value "'.$stageId.'" that was not allowed',1);
		} else $this->newlog('Attempt to set stage for record failed because you do not have edit access',1);
	}













	/*********************************************
	 *
	 * Cmd: Helper functions
	 *
	 ********************************************/

	/**
	 * Processes the fields with references as registered during the copy process. This includes all FlexForm fields which had references.
	 *
	 * @return	void
	 */
	function remapListedDBRecords()	{
		global $TCA;

		if (count($this->registerDBList))	{
			reset($this->registerDBList);
			while(list($table,$records)=each($this->registerDBList))	{
				t3lib_div::loadTCA($table);
				reset($records);
				while(list($uid,$fields)=each($records))	{
					$newData = array();
					$theUidToUpdate = $this->copyMappingArray_merged[$table][$uid];
					$theUidToUpdate_saveTo = t3lib_BEfunc::wsMapId($table,$theUidToUpdate);

					foreach($fields as $fieldName => $value)	{
						$conf = $TCA[$table]['columns'][$fieldName]['config'];

						switch($conf['type'])	{
							case 'group':
							case 'select':
								$vArray = $this->remapListedDBRecords_procDBRefs($conf, $value, $theUidToUpdate);
								if (is_array($vArray))	{
									$newData[$fieldName] = implode(',',$vArray);
								}
							break;
							case 'flex':
								if ($value=='FlexForm_reference')	{
									$origRecordRow = $this->recordInfo($table,$theUidToUpdate,'*');	// This will fetch the new row for the element

									if (is_array($origRecordRow))	{
										t3lib_BEfunc::workspaceOL($table,$origRecordRow);

											// Get current data structure and value array:
										$dataStructArray = t3lib_BEfunc::getFlexFormDS($conf, $origRecordRow, $table);
										$currentValueArray = t3lib_div::xml2array($origRecordRow[$fieldName]);

											// Do recursive processing of the XML data:
										$currentValueArray['data'] = $this->checkValue_flex_procInData(
													$currentValueArray['data'],
													array(),	// Not used.
													array(),	// Not used.
													$dataStructArray,
													array($table,$theUidToUpdate,$fieldName),	// Parameters.
													'remapListedDBRecords_flexFormCallBack'
												);

											// The return value should be compiled back into XML, ready to insert directly in the field (as we call updateDB() directly later):
										if (is_array($currentValueArray['data']))	{
											$newData[$fieldName] =
												$this->checkValue_flexArray2Xml($currentValueArray,TRUE);
										}
									}
								}
							break;
							default:
								debug('Field type should not appear here: '. $conf['type']);
							break;
						}
					}

					if (count($newData))	{	// If any fields were changed, those fields are updated!
						$this->updateDB($table,$theUidToUpdate_saveTo,$newData);
					}
				}
			}
		}
	}

	/**
	 * Callback function for traversing the FlexForm structure in relation to creating copied files of file relations inside of flex form structures.
	 *
	 * @param	array		Set of parameters in numeric array: table, uid, field
	 * @param	array		TCA config for field (from Data Structure of course)
	 * @param	string		Field value (from FlexForm XML)
	 * @param	string		Not used
	 * @param	string		Not used
	 * @return	array		Array where the "value" key carries the value.
	 * @see checkValue_flex_procInData_travDS(), remapListedDBRecords()
	 */
	function remapListedDBRecords_flexFormCallBack($pParams, $dsConf, $dataValue, $dataValue_ext1, $dataValue_ext2)	{

			// Extract parameters:
		list($table,$uid,$field)	= $pParams;

			// If references are set for this field, set flag so they can be corrected later:
		if ($this->isReferenceField($dsConf) && strlen($dataValue)) {
			$vArray = $this->remapListedDBRecords_procDBRefs($dsConf, $dataValue, $uid);
			if (is_array($vArray))	{
				$dataValue = implode(',',$vArray);
			}
		}

			// Return
		return array('value' => $dataValue);
	}

	/**
	 * Performs remapping of old UID values to NEW uid values for a DB reference field.
	 *
	 * @param	array		TCA field config
	 * @param	string		Field value
	 * @param	integer		UID of local record (for MM relations - might need to change if support for FlexForms should be done!)
	 * @return	array		Returns array of items ready to implode for field content.
	 * @see remapListedDBRecords()
	 */
	function remapListedDBRecords_procDBRefs($conf, $value, $MM_localUid)	{

			// Initialize variables
		$set = FALSE;	// Will be set true if an upgrade should be done...
		$allowedTables = $conf['type']=='group' ? $conf['allowed'] : $conf['foreign_table'].','.$conf['neg_foreign_table'];		// Allowed tables for references.
		$prependName = $conf['type']=='group' ? $conf['prepend_tname'] : '';	// Table name to prepend the UID
		$dontRemapTables = t3lib_div::trimExplode(',',$conf['dontRemapTablesOnCopy'],1);	// Which tables that should possibly not be remapped

			// Convert value to list of references:
		$dbAnalysis = t3lib_div::makeInstance('t3lib_loadDBGroup');
		$dbAnalysis->registerNonTableValues = ($conf['type']=='select' && $conf['allowNonIdValues']) ? 1 : 0;
		$dbAnalysis->start($value, $allowedTables, $conf['MM'], $MM_localUid);

			// Traverse those references and map IDs:
		foreach($dbAnalysis->itemArray as $k => $v)	{
			$mapID = $this->copyMappingArray_merged[$v['table']][$v['id']];
			if ($mapID && !in_array($v['table'],$dontRemapTables))	{
				$dbAnalysis->itemArray[$k]['id'] = $mapID;
				$set = TRUE;
			}
		}

			// If a change has been done, set the new value(s)
		if ($set)	{
			if ($conf['MM'])	{
// FIXME $theUidToUpdate is undefined
				$dbAnalysis->writeMM($conf['MM'], $theUidToUpdate, $prependName);
			} else {
				$vArray = $dbAnalysis->getValueArray($prependName);
				if ($conf['type']=='select')	{
					$vArray = $dbAnalysis->convertPosNeg($vArray, $conf['foreign_table'], $conf['neg_foreign_table']);
				}
				return $vArray;
			}
		}
	}

















	/*****************************
	 *
	 * Access control / Checking functions
	 *
	 *****************************/

	/**
	 * Checking group modify_table access list
	 *
	 * @param	string		Table name
	 * @return	boolean		Returns true if the user has general access to modify the $table
	 */
	function checkModifyAccessList($table)	{
		$res = ($this->admin || (!$this->tableAdminOnly($table) && t3lib_div::inList($this->BE_USER->groupData['tables_modify'],$table)));
		return $res;
	}

	/**
	 * Checking if a record with uid $id from $table is in the BE_USERS webmounts which is required for editing etc.
	 *
	 * @param	string		Table name
	 * @param	integer		UID of record
	 * @return	boolean		Returns true if OK. Cached results.
	 */
	function isRecordInWebMount($table,$id)	{
		if (!isset($this->isRecordInWebMount_Cache[$table.':'.$id]))	{
			$recP=$this->getRecordProperties($table,$id);
			$this->isRecordInWebMount_Cache[$table.':'.$id]=$this->isInWebMount($recP['event_pid']);
		}
		return $this->isRecordInWebMount_Cache[$table.':'.$id];
	}

	/**
	 * Checks if the input page ID is in the BE_USER webmounts
	 *
	 * @param	integer		Page ID to check
	 * @return	boolean		True if OK. Cached results.
	 */
	function isInWebMount($pid)	{
		if (!isset($this->isInWebMount_Cache[$pid]))	{
			$this->isInWebMount_Cache[$pid]=$this->BE_USER->isInWebMount($pid);
		}
		return $this->isInWebMount_Cache[$pid];
	}

	/**
	 * Checks if user may update a record with uid=$id from $table
	 *
	 * @param	string		Record table
	 * @param	integer		Record UID
	 * @return	boolean		Returns true if the user may update the record given by $table and $id
	 */
	function checkRecordUpdateAccess($table,$id)	{
		global $TCA;
		$res = 0;
		if ($TCA[$table] && intval($id)>0)	{
			if (isset($this->recUpdateAccessCache[$table][$id]))	{	// If information is cached, return it
				return $this->recUpdateAccessCache[$table][$id];
				// Check if record exists and 1) if 'pages' the page may be edited, 2) if page-content the page allows for editing
			} elseif ($this->doesRecordExist($table,$id,'edit'))	{
				$res = 1;
			}
			$this->recUpdateAccessCache[$table][$id]=$res;	// Cache the result
		}
		return $res;
	}

	/**
	 * Checks if user may insert a record from $insertTable on $pid
	 * Does not check for workspace, use BE_USER->workspaceAllowLiveRecordsInPID for this in addition to this function call.
	 *
	 * @param	string		Tablename to check
	 * @param	integer		Integer PID
	 * @param	integer		For logging: Action number.
	 * @return	boolean		Returns true if the user may insert a record from table $insertTable on page $pid
	 */
	function checkRecordInsertAccess($insertTable,$pid,$action=1)	{
		global $TCA;

		$res = 0;
		$pid = intval($pid);
		if ($pid>=0)	{
			if (isset($this->recInsertAccessCache[$insertTable][$pid]))	{	// If information is cached, return it
				return $this->recInsertAccessCache[$insertTable][$pid];
			} else {
					// If either admin and root-level or if page record exists and 1) if 'pages' you may create new ones 2) if page-content, new content items may be inserted on the $pid page
				if ( (!$pid && $this->admin) || $this->doesRecordExist('pages',$pid,($insertTable=='pages'?$this->pMap['new']:$this->pMap['editcontent'])) )	{		// Check permissions
					if ($this->isTableAllowedForThisPage($pid, $insertTable))	{
						$res = 1;
						$this->recInsertAccessCache[$insertTable][$pid]=$res;	// Cache the result
					} else {
						$propArr = $this->getRecordProperties('pages',$pid);
						$this->log($insertTable,$pid,$action,0,1,"Attempt to insert record on page '%s' (%s) where this table, %s, is not allowed",11,array($propArr['header'],$pid,$insertTable),$propArr['event_pid']);
					}
				} else {
					$propArr = $this->getRecordProperties('pages',$pid);
					$this->log($insertTable,$pid,$action,0,1,"Attempt to insert a record on page '%s' (%s) from table '%s' without permissions. Or non-existing page.",12,array($propArr['header'],$pid,$insertTable),$propArr['event_pid']);
				}
			}
		}
		return $res;
	}

	/**
	 * Checks if a table is allowed on a certain page id according to allowed tables set for the page "doktype" and its [ctrl][rootLevel]-settings if any.
	 *
	 * @param	integer		Page id for which to check, including 0 (zero) if checking for page tree root.
	 * @param	string		Table name to check
	 * @return	boolean		True if OK
	 */
	function isTableAllowedForThisPage($page_uid, $checkTable)	{
		global $TCA, $PAGES_TYPES;
		$page_uid = intval($page_uid);

			// Check if rootLevel flag is set and we're trying to insert on rootLevel - and reversed - and that the table is not "pages" which are allowed anywhere.
		if (($TCA[$checkTable]['ctrl']['rootLevel'] xor !$page_uid) && $TCA[$checkTable]['ctrl']['rootLevel']!=-1 && $checkTable!='pages')	{
			return false;
		}

			// Check root-level
		if (!$page_uid)	{
			if ($this->admin)	{
				return true;
			}
		} else {
				// Check non-root-level
			$doktype = $this->pageInfo($page_uid,'doktype');
			$allowedTableList = isset($PAGES_TYPES[$doktype]['allowedTables']) ? $PAGES_TYPES[$doktype]['allowedTables'] : $PAGES_TYPES['default']['allowedTables'];
			$allowedArray = t3lib_div::trimExplode(',',$allowedTableList,1);
			if (strstr($allowedTableList,'*') || in_array($checkTable,$allowedArray))	{		// If all tables or the table is listed as a allowed type, return true
				return true;
			}
		}
	}

	/**
	 * Checks if record can be selected based on given permission criteria
	 *
	 * @param	string		Record table name
	 * @param	integer		Record UID
	 * @param	mixed		Permission restrictions to observe: Either an integer that will be bitwise AND'ed or a string, which points to a key in the ->pMap array
	 * @return	boolean		Returns true if the record given by $table, $id and $perms can be selected
	 */
	function doesRecordExist($table,$id,$perms)	{
		global $TCA;

		$res = 0;
		$id = intval($id);

			// Processing the incoming $perms (from possible string to integer that can be AND'ed)
		if (!t3lib_div::testInt($perms))	{
			if ($table!='pages')	{
				switch($perms)	{
					case 'edit':
					case 'delete':
					case 'new':
						$perms = 'editcontent';		// This holds it all in case the record is not page!!
					break;
				}
			}
			$perms = intval($this->pMap[$perms]);
		} else {
			$perms = intval($perms);
		}

		if (!$perms)	{die('Internal ERROR: no permissions to check for non-admin user.');}

			// For all tables: Check if record exists:
		if (is_array($TCA[$table]) && $id>0 && ($this->isRecordInWebMount($table,$id) || $this->admin))	{
			if ($table != 'pages')	{

					// Find record without checking page:
				$mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid,pid', $table, 'uid='.intval($id).$this->deleteClause($table));	// THIS SHOULD CHECK FOR editlock I think!
				$output = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres);
				t3lib_BEfunc::fixVersioningPid($table,$output,TRUE);

					// If record found, check page as well:
				if (is_array($output))	{

						// Looking up the page for record:
					$mres = $this->doesRecordExist_pageLookUp($output['pid'], $perms);
					$pageRec = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres);
						// Return true if either a page was found OR if the PID is zero AND the user is ADMIN (in which case the record is at root-level):
					if (is_array($pageRec) || (!$output['pid'] && $this->admin))	{
						return TRUE;
					}
				}
				return FALSE;
			} else {
				$mres = $this->doesRecordExist_pageLookUp($id, $perms);
				return $GLOBALS['TYPO3_DB']->sql_num_rows($mres);
			}
		}
	}

	/**
	 * Looks up a page based on permissions.
	 *
	 * @param	integer		Page id
	 * @param	integer		Permission integer
	 * @return	pointer		MySQL result pointer (from exec_SELECTquery())
	 * @access private
	 * @see doesRecordExist()
	 */
	function doesRecordExist_pageLookUp($id, $perms)	{
		global $TCA;

		return $GLOBALS['TYPO3_DB']->exec_SELECTquery(
			'uid',
			'pages',
			'uid='.intval($id).
				$this->deleteClause('pages').
				($perms && !$this->admin ? ' AND '.$this->BE_USER->getPagePermsClause($perms) : '').
				(!$this->admin && $TCA['pages']['ctrl']['editlock'] && ($perms & (2+4+16)) ? ' AND '.$TCA['pages']['ctrl']['editlock'].'=0':'')	// admin users don't need check
		);
	}

	/**
	 * Checks if a whole branch of pages exists
	 *
	 * Tests the branch under $pid (like doesRecordExist). It doesn't test the page with $pid as uid. Use doesRecordExist() for this purpose
	 * Returns an ID-list or "" if OK. Else -1 which means that somewhere there was no permission (eg. to delete).
	 * if $recurse is set, then the function will follow subpages. This MUST be set, if we need the idlist for deleting pages or else we get an incomplete list
	 *
	 * @param	string		List of page uids, this is added to and outputted in the end
	 * @param	integer		Page ID to select subpages from.
	 * @param	integer		Perms integer to check each page record for.
	 * @param	boolean		Recursion flag: If set, it will go out through the branch.
	 * @return	string		List of integers in branch
	 */
	function doesBranchExist($inList,$pid,$perms,$recurse)	{
		global $TCA;
		$pid = intval($pid);
		$perms = intval($perms);

		if ($pid>=0)	{
			$mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
				'uid, perms_userid, perms_groupid, perms_user, perms_group, perms_everybody',
				'pages',
				'pid='.intval($pid).$this->deleteClause('pages'),
				'',
				'sorting'
			);
			while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres))	{
				if ($this->admin || $this->BE_USER->doesUserHaveAccess($row,$perms))	{	// IF admin, then it's OK
					$inList.=$row['uid'].',';
					if ($recurse)	{	// Follow the subpages recursively...
						$inList = $this->doesBranchExist($inList, $row['uid'], $perms, $recurse);
						if ($inList == -1)	{return -1;}		// No permissions somewhere in the branch
					}
				} else {
					return -1;		// No permissions
				}
			}
		}
		return $inList;
	}

	/**
	 * Checks if the $table is readOnly
	 *
	 * @param	string		Table name
	 * @return	boolean		True, if readonly
	 */
	function tableReadOnly($table)	{
			// returns true if table is readonly
		global $TCA;
		return ($TCA[$table]['ctrl']['readOnly'] ? 1 : 0);
	}

	/**
	 * Checks if the $table is only editable by admin-users
	 *
	 * @param	string		Table name
	 * @return	boolean		True, if readonly
	 */
	function tableAdminOnly($table)	{
			// returns true if table is admin-only
		global $TCA;
		return ($TCA[$table]['ctrl']['adminOnly'] ? 1 : 0);
	}

	/**
	 * Checks if piage $id is a uid in the rootline from page id, $dest
	 * Used when moving a page
	 *
	 * @param	integer		Destination Page ID to test
	 * @param	integer		Page ID to test for presence inside Destination
	 * @return	boolean		Returns false if ID is inside destination (including equal to)
	 */
	function destNotInsideSelf($dest,$id)	{
		$loopCheck = 100;
		$dest = intval($dest);
		$id = intval($id);

		if ($dest==$id)	{
			return FALSE;
		}

		while ($dest!=0 && $loopCheck>0)	{
			$loopCheck--;
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid, uid, t3ver_oid,t3ver_wsid', 'pages', 'uid='.intval($dest).$this->deleteClause('pages'));
			if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))	{
				t3lib_BEfunc::fixVersioningPid('pages',$row);
				if ($row['pid']==$id)	{
					return FALSE;
				} else {
					$dest = $row['pid'];
				}
			} else {
				return FALSE;
			}
		}
		return TRUE;
	}

	/**
	 * Generate an array of fields to be excluded from editing for the user. Based on "exclude"-field in TCA and a look up in non_exclude_fields
	 * Will also generate this list for admin-users so they must be check for before calling the function
	 *
	 * @return	array		Array of [table]-[field] pairs to exclude from editing.
	 */
	function getExcludeListArray()	{
		global $TCA;

		$list = array();
		reset($TCA);
		while (list($table)=each($TCA))	{
			t3lib_div::loadTCA($table);
			while (list($field,$config)=each($TCA[$table]['columns']))	{
				if ($config['exclude'] && !t3lib_div::inList($this->BE_USER->groupData['non_exclude_fields'],$table.':'.$field))	{
					$list[]=$table.'-'.$field;
				}
			}
		}
		return $list;
	}

	/**
	 * Checks if there are records on a page from tables that are not allowed
	 *
	 * @param	integer		Page ID
	 * @param	integer		Page doktype
	 * @return	array		Returns a list of the tables that are 'present' on the page but not allowed with the page_uid/doktype
	 */
	function doesPageHaveUnallowedTables($page_uid,$doktype)	{
		global $TCA, $PAGES_TYPES;

		$page_uid = intval($page_uid);
		if (!$page_uid)	{
			return FALSE; 	// Not a number. Probably a new page
		}

		$allowedTableList = isset($PAGES_TYPES[$doktype]['allowedTables']) ? $PAGES_TYPES[$doktype]['allowedTables'] : $PAGES_TYPES['default']['allowedTables'];
		$allowedArray = t3lib_div::trimExplode(',',$allowedTableList,1);
		if (strstr($allowedTableList,'*'))	{	// If all tables is OK the return true
			return FALSE;	// OK...
		}

		reset ($TCA);
		$tableList = array();
		while (list($table)=each($TCA))	{
			if (!in_array($table,$allowedArray))	{	// If the table is not in the allowed list, check if there are records...
				$mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('count(*)', $table, 'pid='.intval($page_uid));
				$count = $GLOBALS['TYPO3_DB']->sql_fetch_row($mres);
				if ($count[0])	{
					$tableList[]=$table;
				}
			}
		}
		return implode(',',$tableList);
	}








	/*****************************
	 *
	 * Information lookup
	 *
	 *****************************/

	/**
	 * Returns the value of the $field from page $id
	 * NOTICE; the function caches the result for faster delivery next time. You can use this function repeatedly without performanceloss since it doesn't look up the same record twice!
	 *
	 * @param	integer		Page uid
	 * @param	string		Field name for which to return value
	 * @return	string		Value of the field. Result is cached in $this->pageCache[$id][$field] and returned from there next time!
	 */
	function pageInfo($id,$field)	{
		if (!isset($this->pageCache[$id]))	{
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', 'pages', 'uid='.intval($id));
			if ($GLOBALS['TYPO3_DB']->sql_num_rows($res))	{
				$this->pageCache[$id] = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
			}
			$GLOBALS['TYPO3_DB']->sql_free_result($res);
		}
		return $this->pageCache[$id][$field];
	}

	/**
	 * Returns the row of a record given by $table and $id and $fieldList (list of fields, may be '*')
	 * NOTICE: No check for deleted or access!
	 *
	 * @param	string		Table name
	 * @param	integer		UID of the record from $table
	 * @param	string		Field list for the SELECT query, eg. "*" or "uid,pid,..."
	 * @return	mixed		Returns the selected record on success, otherwise false.
	 */
	function recordInfo($table,$id,$fieldList)	{
		global $TCA;
		if (is_array($TCA[$table]))	{
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($fieldList, $table, 'uid='.intval($id));
			if ($GLOBALS['TYPO3_DB']->sql_num_rows($res))	{
				return $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);
			}
		}
	}

	/**
	 * Returns an array with record properties, like header and pid
	 * No check for deleted or access is done!
	 * For versionized records, pid is resolved to its live versions pid.
	 * Used for loggin
	 *
	 * @param	string		Table name
	 * @param	integer		Uid of record
	 * @param	boolean		If set, no workspace overlay is performed
	 * @return	array		Properties of record
	 */
	function getRecordProperties($table,$id,$noWSOL=FALSE)	{
		$row = ($table=='pages' && !$id) ? array('title'=>'[root-level]', 'uid' => 0, 'pid' => 0) :$this->recordInfo($table,$id,'*');
		if (!$noWSOL)	{
			t3lib_BEfunc::workspaceOL($table,$row);
		}
		t3lib_BEfunc::fixVersioningPid($table,$row);
		return $this->getRecordPropertiesFromRow($table,$row);
	}

	/**
	 * Returns an array with record properties, like header and pid, based on the row
	 *
	 * @param	string		Table name
	 * @param	array		Input row
	 * @return	array		Output array
	 */
	function getRecordPropertiesFromRow($table,$row)	{
		global $TCA;
		if ($TCA[$table])	{
			$out = array(
				'header' => $row[$TCA[$table]['ctrl']['label']],
				'pid' => $row['pid'],
				'event_pid' => ($table=='pages'?$row['uid']:$row['pid']),
				't3ver_state' => $TCA[$table]['ctrl']['versioningWS'] ? $row['t3ver_state'] : '',
				'_ORIG_pid' => $row['_ORIG_pid']
			);
			return $out;
		}
	}















	/*********************************************
	 *
	 * Storing data to Database Layer
	 *
	 ********************************************/

	/**
	 * Update database record
	 * Does not check permissions but expects them to be verified on beforehand
	 *
	 * @param	string		Record table name
	 * @param	integer		Record uid
	 * @param	array		Array of field=>value pairs to insert. FIELDS MUST MATCH the database FIELDS. No check is done.
	 * @return	void
	 */
	function updateDB($table,$id,$fieldArray)	{
		global $TCA;

		if (is_array($fieldArray) && is_array($TCA[$table]) && intval($id))	{
			unset($fieldArray['uid']);	// Do NOT update the UID field, ever!

			if (count($fieldArray))	{

					// Execute the UPDATE query:
				$GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($id), $fieldArray);

					// If succees, do...:
				if (!$GLOBALS['TYPO3_DB']->sql_error())	{

					if ($this->checkStoredRecords)	{
						$newRow = $this->checkStoredRecord($table,$id,$fieldArray,2);
					}

						// Update reference index:
					$this->updateRefIndex($table,$id);

						// Set log entry:
					$propArr = $this->getRecordPropertiesFromRow($table,$newRow);
					$theLogId = $this->log($table,$id,2,$propArr['pid'],0,"Record '%s' (%s) was updated.",10,array($propArr['header'],$table.':'.$id),$propArr['event_pid']);

						// Set History data:
					$this->setHistory($table,$id,$theLogId);

						// Clear cache for relevant pages:
					$this->clear_cache($table,$id);

						// Unset the pageCache for the id if table was page.
					if ($table=='pages')	unset($this->pageCache[$id]);
				} else {
					$this->log($table,$id,2,0,2,"SQL error: '%s' (%s)",12,array($GLOBALS['TYPO3_DB']->sql_error(),$table.':'.$id));
				}
			}
		}
	}

	/**
	 * Insert into database
	 * Does not check permissions but expects them to be verified on beforehand
	 *
	 * @param	string		Record table name
	 * @param	string		"NEW...." uid string
	 * @param	array		Array of field=>value pairs to insert. FIELDS MUST MATCH the database FIELDS. No check is done. "pid" must point to the destination of the record!
	 * @param	boolean		Set to true if new version is created.
	 * @param	integer		Suggested UID value for the inserted record. See the array $this->suggestedInsertUids; Admin-only feature
	 * @param	boolean		If true, the ->substNEWwithIDs array is not updated. Only useful in very rare circumstances!
	 * @return	integer		Returns ID on success.
	 */
	function insertDB($table,$id,$fieldArray,$newVersion=FALSE,$suggestedUid=0,$dontSetNewIdIndex=FALSE)	{
		global $TCA;

		if (is_array($fieldArray) && is_array($TCA[$table]) && isset($fieldArray['pid']))	{
			unset($fieldArray['uid']);	// Do NOT insert the UID field, ever!

			if (count($fieldArray))	{

					// Check for "suggestedUid".
					// This feature is used by the import functionality to force a new record to have a certain UID value.
					// This is only recommended for use when the destination server is a passive mirrow of another server.
					// As a security measure this feature is available only for Admin Users (for now)
				$suggestedUid = intval($suggestedUid);
				if ($this->BE_USER->isAdmin() && $suggestedUid && $this->suggestedInsertUids[$table.':'.$suggestedUid])	{
						// When the value of ->suggestedInsertUids[...] is "DELETE" it will try to remove the previous record
					if ($this->suggestedInsertUids[$table.':'.$suggestedUid]==='DELETE')	{
							// DELETE:
						$GLOBALS['TYPO3_DB']->exec_DELETEquery($table, 'uid='.intval($suggestedUid));
					}
					$fieldArray['uid'] = $suggestedUid;
				}

					// Execute the INSERT query:
				$GLOBALS['TYPO3_DB']->exec_INSERTquery($table, $fieldArray);

					// If succees, do...:
				if (!$GLOBALS['TYPO3_DB']->sql_error())	{

						// Set mapping for NEW... -> real uid:
					$NEW_id = $id;		// the NEW_id now holds the 'NEW....' -id
					$id = $GLOBALS['TYPO3_DB']->sql_insert_id();
					if (!$dontSetNewIdIndex)	{
						$this->substNEWwithIDs[$NEW_id] = $id;
						$this->substNEWwithIDs_table[$NEW_id] = $table;
					}

						// Checking the record is properly saved and writing to log
					if ($this->checkStoredRecords)	{
						$newRow = $this->checkStoredRecord($table,$id,$fieldArray,1);
					}

						// Update reference index:
					$this->updateRefIndex($table,$id);

					if ($newVersion)	{
						$this->log($table,$id,1,0,0,"New version created of table '%s', uid '%s'",10,array($table,$fieldArray['t3ver_oid']),$newRow['pid'],$NEW_id);
					} else {
						$propArr = $this->getRecordPropertiesFromRow($table,$newRow);
						$page_propArr = $this->getRecordProperties('pages',$propArr['pid']);
						$this->log($table,$id,1,0,0,"Record '%s' (%s) was inserted on page '%s' (%s)",10,array($propArr['header'],$table.':'.$id,$page_propArr['header'],$newRow['pid']),$newRow['pid'],$NEW_id);

							// Clear cache for relavant pages:
						$this->clear_cache($table,$id);
					}

					return $id;
				} else {
					$this->log($table,$id,1,0,2,"SQL error: '%s' (%s)",12,array($GLOBALS['TYPO3_DB']->sql_error(),$table.':'.$id));
				}
			}
		}
	}

	/**
	 * Checking stored record to see if the written values are properly updated.
	 *
	 * @param	string		Record table name
	 * @param	integer		Record uid
	 * @param	array		Array of field=>value pairs to insert/update
	 * @param	string		Action, for logging only.
	 * @return	array		Selected row
	 * @see insertDB(), updateDB()
	 */
	function checkStoredRecord($table,$id,$fieldArray,$action)	{
		global $TCA;

		$id = intval($id);
		if (is_array($TCA[$table]) && $id)	{
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, 'uid='.intval($id));
			if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))	{
					// Traverse array of values that was inserted into the database and compare with the actually stored value:
				$errorString = array();
				foreach($fieldArray as $key => $value)	{
					if ($this->checkStoredRecords_loose && !$value && !$row[$key])	{
						// Nothing...
					} elseif (strcmp($value,$row[$key]))	{
						$errorString[] = $key;
					}
				}

					// Set log message if there were fields with unmatching values:
				if (count($errorString))	{
					$this->log($table,$id,$action,0,102,'These fields are not properly updated in database: ('.implode(',',$errorString).') Probably value mismatch with fieldtype.');
				}

					// Return selected rows:
				return $row;
			}
			$GLOBALS['TYPO3_DB']->sql_free_result($res);
		}
	}

	/**
	 * Setting sys_history record, based on content previously set in $this->historyRecords[$table.':'.$id] (by compareFieldArrayWithCurrentAndUnset())
	 *
	 * @param	string		Table name
	 * @param	integer		Record ID
	 * @param	integer		Log entry ID, important for linking between log and history views
	 * @return	void
	 */
	function setHistory($table,$id,$logId)		{
		if (isset($this->historyRecords[$table.':'.$id]))	{

				// Initialize settings:
			list($tscPID) = t3lib_BEfunc::getTSCpid($table,$id,'');
			$TSConfig = $this->getTCEMAIN_TSconfig($tscPID);

			$tE = $this->getTableEntries($table,$TSConfig);
			$maxAgeSeconds = 60*60*24*(strcmp($tE['history.']['maxAgeDays'],'') ? t3lib_div::intInRange($tE['history.']['maxAgeDays'],0,365) : 30);	// one month

				// Garbage collect old entries:
			$this->clearHistory($maxAgeSeconds, $table);

				// Set history data:
				$fields_values = array();
				$fields_values['history_data'] = serialize($this->historyRecords[$table.':'.$id]);
				$fields_values['fieldlist'] = implode(',',array_keys($this->historyRecords[$table.':'.$id]['newRecord']));
				$fields_values['tstamp'] = time();
				$fields_values['tablename'] = $table;
				$fields_values['recuid'] = $id;
				$fields_values['sys_log_uid'] = $logId;

				$GLOBALS['TYPO3_DB']->exec_INSERTquery('sys_history', $fields_values);
			}
		}

	/**
	 * Clearing sys_history table from older entries that are expired.
	 *
	 * @param	integer		$maxAgeSeconds (int+) however will set a max age in seconds so that any entry older than current time minus the age removed no matter what. If zero, this is not effective.
	 * @param	string		table where the history should be cleared
	 * @return	void
	 */
	function clearHistory($maxAgeSeconds=604800,$table)	{
		$tstampLimit = $maxAgeSeconds ? time()-$maxAgeSeconds : 0;

		$GLOBALS['TYPO3_DB']->exec_DELETEquery('sys_history', 'tstamp<'.intval($tstampLimit).' AND tablename='.$GLOBALS['TYPO3_DB']->fullQuoteStr($table, 'sys_history'));
		}

	/**
	 * Update Reference Index (sys_refindex) for a record
	 * Should be called any almost any update to a record which could affect references inside the record.
	 *
	 * @param	string		Table name
	 * @param	integer		Record UID
	 * @return	void
	 */
	function updateRefIndex($table,$id)	{
		$refIndexObj = t3lib_div::makeInstance('t3lib_refindex');
		$result = $refIndexObj->updateRefIndexTable($table,$id);
	}













	/*********************************************
	 *
	 * Misc functions
	 *
	 ********************************************/

	/**
	 * Returning sorting number for tables with a "sortby" column
	 * Using when new records are created and existing records are moved around.
	 *
	 * @param	string		Table name
	 * @param	integer		Uid of record to find sorting number for. May be zero in case of new.
	 * @param	integer		Positioning PID, either >=0 (pointing to page in which case we find sorting number for first record in page) or <0 (pointing to record in which case to find next sorting number after this record)
	 * @return	mixed		Returns integer if PID is >=0, otherwise an array with PID and sorting number. Possibly false in case of error.
	 */
	function getSortNumber($table,$uid,$pid)	{
		global $TCA;
		if ($TCA[$table] && $TCA[$table]['ctrl']['sortby'])	{
			$sortRow = $TCA[$table]['ctrl']['sortby'];
			if ($pid>=0)	{	// Sorting number is in the top
				$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($sortRow.',pid,uid', $table, 'pid='.intval($pid).$this->deleteClause($table), '', $sortRow.' ASC', '1');		// Fetches the first record under this pid
				if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))	{	// There was an element
					if ($row['uid']==$uid)	{	// The top record was the record it self, so we return its current sortnumber
						return $row[$sortRow];
					}
					if ($row[$sortRow] < 1) {	// If the pages sortingnumber < 1 we must resort the records under this pid
						$this->resorting($table,$pid,$sortRow,0);
						return $this->sortIntervals;	// First sorting number after resorting
					} else {
						return floor($row[$sortRow]/2);	// Sorting number between current top element and zero
					}
				} else {	// No pages, so we choose the default value as sorting-number
					return $this->sortIntervals;	// First sorting number if no elements.
				}
			} else {	// Sorting number is inside the list
				$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery($sortRow.',pid,uid', $table, 'uid='.abs($pid).$this->deleteClause($table));		// Fetches the record which is supposed to be the prev record
				if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res))	{	// There was a record

						// Look, if the record UID happens to be an offline record. If so, find its live version. Offline uids will be used when a page is versionized as "branch" so this is when we must correct - otherwise a pid of "-1" and a wrong sort-row number is returned which we don't want.
					if ($lookForLiveVersion = t3lib_BEfunc::getLiveVersionOfRecord($table,$row['uid'],$sortRow.',pid,uid'))	{
						$row = 	$lookForLiveVersion;
					}

						// If the record happends to be it self
					if ($row['uid']==$uid)	{
						$sortNumber = $row[$sortRow];
					} else {
						$subres = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
										$sortRow.',pid,uid',
										$table,
										'pid='.intval($row['pid']).' AND '.$sortRow.'>='.intval($row[$sortRow]).$this->deleteClause($table),
										'',
										$sortRow.' ASC',
										'2'
									);		// Fetches the next record in order to calculate the in between sortNumber
						if ($GLOBALS['TYPO3_DB']->sql_num_rows($subres)==2)	{	// There was a record afterwards
							$GLOBALS['TYPO3_DB']->sql_fetch_assoc($subres);				// Forward to the second result...
							$subrow = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($subres);	// There was a record afterwards
							$sortNumber = $row[$sortRow]+ floor(($subrow[$sortRow]-$row[$sortRow])/2);	// The sortNumber is found in between these values
							if ($sortNumber<=$row[$sortRow] || $sortNumber>=$subrow[$sortRow])	{	// The sortNumber happend NOT to be between the two surrounding numbers, so we'll have to resort the list
								$sortNumber = $this->resorting($table,$row['pid'],$sortRow,  $row['uid']);	// By this special param, resorting reserves and returns the sortnumber after the uid
							}
						} else {	// If after the last record in the list, we just add the sortInterval to the last sortvalue
							$sortNumber = $row[$sortRow]+$this->sortIntervals;
						}
					}
					return Array('pid' => $row['pid'], 'sortNumber' => $sortNumber);
				} else {
					$propArr = $this->getRecordProperties($table,$uid);
					$this->log($table,$uid,4,0,1,"Attempt to move record '%s' (%s) to after a non-existing record (uid=%s)",1,array($propArr['header'],$table.':'.$uid,abs($pid)),$propArr['pid']);	// OK, dont insert $propArr['event_pid'] here...
					return false;	// There MUST be a page or else this cannot work
				}
			}
		}
	}

	/**
	 * Resorts a table.
	 * Used internally by getSortNumber()
	 *
	 * @param	string		Table name
	 * @param	integer		Pid in which to resort records.
	 * @param	string		Sorting row
	 * @param	integer		Uid of record from $table in this $pid and for which the return value will be set to a free sorting number after that record. This is used to return a sortingValue if the list is resorted because of inserting records inside the list and not in the top
	 * @return	integer		If $return_SortNumber_After_This_Uid is set, will contain usable sorting number after that record if found (otherwise 0)
	 * @access private
	 * @see getSortNumber()
	 */
	function resorting($table,$pid,$sortRow, $return_SortNumber_After_This_Uid) {
		global $TCA;
		if ($TCA[$table] && $sortRow && $TCA[$table]['ctrl']['sortby']==$sortRow)	{
			$returnVal = 0;
			$intervals = $this->sortIntervals;
			$i = $intervals*2;

			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, 'pid='.intval($pid).$this->deleteClause($table), '', $sortRow.' ASC');
			while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res)) {
				$uid=intval($row['uid']);
				if ($uid)	{
					$GLOBALS['TYPO3_DB']->exec_UPDATEquery($table, 'uid='.intval($uid), array($sortRow=>$i));
					if ($uid==$return_SortNumber_After_This_Uid)	{		// This is used to return a sortingValue if the list is resorted because of inserting records inside the list and not in the top
						$i = $i+$intervals;
						$returnVal=$i;
					}
				} else {die ('Fatal ERROR!! No Uid at resorting.');}
				$i = $i+$intervals;
			}
			return $returnVal;
		}
	}

	/**
	 * Setting up perms_* fields in $fieldArray based on TSconfig input
	 * Used for new pages
	 *
	 * @param	array		Field Array, returned with modifications
	 * @param	array		TSconfig properties
	 * @return	array		Modified Field Array
	 */
	function setTSconfigPermissions($fieldArray,$TSConfig_p)	{
		if (strcmp($TSConfig_p['userid'],''))	$fieldArray['perms_userid']=intval($TSConfig_p['userid']);
		if (strcmp($TSConfig_p['groupid'],''))	$fieldArray['perms_groupid']=intval($TSConfig_p['groupid']);
		if (strcmp($TSConfig_p['user'],''))			$fieldArray['perms_user']=t3lib_div::testInt($TSConfig_p['user']) ? $TSConfig_p['user'] : $this->assemblePermissions($TSConfig_p['user']);
		if (strcmp($TSConfig_p['group'],''))		$fieldArray['perms_group']=t3lib_div::testInt($TSConfig_p['group']) ? $TSConfig_p['group'] : $this->assemblePermissions($TSConfig_p['group']);
		if (strcmp($TSConfig_p['everybody'],''))	$fieldArray['perms_everybody']=t3lib_div::testInt($TSConfig_p['everybody']) ? $TSConfig_p['everybody'] : $this->assemblePermissions($TSConfig_p['everybody']);

		return $fieldArray;
	}

	/**
	 * Returns a fieldArray with default values. Values will be picked up from the TCA array looking at the config key "default" for each column. If values are set in ->defaultValues they will overrule though.
	 * Used for new records and during copy operations for defaults
	 *
	 * @param	string		Table name for which to set default values.
	 * @return	array		Array with default values.
	 */
	function newFieldArray($table)	{
		global $TCA;

		t3lib_div::loadTCA($table);
		$fieldArray=Array();
		if (is_array($TCA[$table]['columns']))	{
			reset ($TCA[$table]['columns']);
			while (list($field,$content)=each($TCA[$table]['columns']))	{
				if (isset($this->defaultValues[$table][$field]))	{
					$fieldArray[$field] = $this->defaultValues[$table][$field];
				} elseif (isset($content['config']['default']))	{
					$fieldArray[$field] = $content['config']['default'];
				}
			}
		}
		if ($table==='pages')	{		// Set default permissions for a page.
			$fieldArray['perms_userid'] = $this->userid;
			$fieldArray['perms_groupid'] = intval($this->BE_USER->firstMainGroup);
			$fieldArray['perms_user'] = $this->assemblePermissions($this->defaultPermissions['user']);
			$fieldArray['perms_group'] = $this->assemblePermissions($this->defaultPermissions['group']);
			$fieldArray['perms_everybody'] = $this->assemblePermissions($this->defaultPermissions['everybody']);
		}
		return $fieldArray;
	}

	/**
	 * If a "languageField" is specified for $table this function will add a possible value to the incoming array if none is found in there already.
	 *
	 * @param	string		Table name
	 * @param	array		Incoming array (passed by reference)
	 * @return	void
	 */
	function addDefaultPermittedLanguageIfNotSet($table,&$incomingFieldArray)	{
		global $TCA;

			// Checking languages:
		if ($TCA[$table]['ctrl']['languageField'])	{
			if (!isset($incomingFieldArray[$TCA[$table]['ctrl']['languageField']]))	{	// Language field must be found in input row - otherwise it does not make sense.
				$rows = array_merge(array(array('uid'=>0)),$GLOBALS['TYPO3_DB']->exec_SELECTgetRows('uid','sys_language','pid=0'.t3lib_BEfunc::deleteClause('sys_language')),array(array('uid'=>-1)));
				foreach($rows as $r)	{
					if ($this->BE_USER->checkLanguageAccess($r['uid']))		{
						$incomingFieldArray[$TCA[$table]['ctrl']['languageField']] = $r['uid'];
						break;
					}
				}
			}
		}
	}

	/**
	 * Returns the $data array from $table overridden in the fields defined in ->overrideValues.
	 *
	 * @param	string		Table name
	 * @param	array		Data array with fields from table. These will be overlaid with values in $this->overrideValues[$table]
	 * @return	array		Data array, processed.
	 */
	function overrideFieldArray($table,$data)	{
		if (is_array($this->overrideValues[$table]))	{
			$data = array_merge($data,$this->overrideValues[$table]);
		}
		return $data;
	}

	/**
	 * Compares the incoming field array with the current record and unsets all fields which are the same.
	 * Used for existing records being updated
	 *
	 * @param	string		Record table name
	 * @param	integer		Record uid
	 * @param	array		Array of field=>value pairs intended to be inserted into the database. All keys with values matching exactly the current value will be unset!
	 * @return	array		Returns $fieldArray. If the returned array is empty, then the record should not be updated!
	 */
	function compareFieldArrayWithCurrentAndUnset($table,$id,$fieldArray)	{

			// Fetch the original record:
		$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('*', $table, 'uid='.intval($id));
		$currentRecord = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);

			// If the current record exists (which it should...), begin comparison:
		if (is_array($currentRecord))	{

				// Read all field types:
			$c = 0;
			$cRecTypes = array();
			foreach($currentRecord as $col => $val)	{
				$cRecTypes[$col] = $GLOBALS['TYPO3_DB']->sql_field_type($res,$c);
				$c++;
			}

				// Free result:
			$GLOBALS['TYPO3_DB']->sql_free_result($res);

				// Unset the fields which are similar:
			foreach($fieldArray as $col => $val)	{
				if (
						!strcmp($val,$currentRecord[$col]) ||	// Unset fields which matched exactly.
						($cRecTypes[$col]=='int' && $currentRecord[$col]==0 && !strcmp($val,''))	// Now, a situation where TYPO3 tries to put an empty string into an integer field, we should not strcmp the integer-zero and '', but rather accept them to be similar.
					)	{
					unset($fieldArray[$col]);
				} else {
					$this->historyRecords[$table.':'.$id]['oldRecord'][$col] = $currentRecord[$col];
					$this->historyRecords[$table.':'.$id]['newRecord'][$col] = $fieldArray[$col];
				}
			}
		} else {	// If the current record does not exist this is an error anyways and we just return an empty array here.
			$fieldArray = array();
		}

		return $fieldArray;
	}

	/**
	 * Calculates the bitvalue of the permissions given in a string, comma-sep
	 *
	 * @param	string		List of pMap strings
	 * @return	integer		Integer mask
	 * @see setTSconfigPermissions(), newFieldArray()
	 */
	function assemblePermissions($string)	{
		$keyArr = t3lib_div::trimExplode(',',$string,1);
		$value=0;
		while(list(,$key)=each($keyArr))	{
			if ($key && isset($this->pMap[$key]))	{
				$value |= $this->pMap[$key];
			}
		}
		return $value;
	}

	/**
	 * Returns the $input string without a comma in the end
	 *
	 * @param	string		Input string
	 * @return	string		Output string with any comma in the end removed, if any.
	 */
	function rmComma($input)	{
		return ereg_replace(',$','',$input);
	}

	/**
	 * Converts a HTML entity (like &#123;) to the character '123'
	 *
	 * @param	string		Input string
	 * @return	string		Output string
	 */
	function convNumEntityToByteValue($input)	{
		$token = md5(microtime());
		$parts = explode($token,ereg_replace('(&#([0-9]+);)',$token.'\2'.$token,$input));

		foreach($parts as $k => $v)	{
			if ($k%2)	{
				$v = intval($v);
				if ($v > 32)	{	// Just to make sure that control bytes are not converted.
					$parts[$k] =chr(intval($v));
				}
			}
		}

		return implode('',$parts);
	}

	/**
	 * Returns absolute destination path for the uploadfolder, $folder
	 *
	 * @param	string		Upload folder name, relative to PATH_site
	 * @return	string		Input string prefixed with PATH_site
	 */
	function destPathFromUploadFolder($folder)	{
		return PATH_site.$folder;
	}

	/**
	 * Returns delete-clause for the $table
	 *
	 * @param	string		Table name
	 * @return	string		Delete clause
	 */
	function deleteClause($table)	{
			// Returns the proper delete-clause if any for a table from TCA
		global $TCA;
		if ($TCA[$table]['ctrl']['delete'])	{
			return ' AND '.$table.'.'.$TCA[$table]['ctrl']['delete'].'=0';
		} else {
			return '';
		}
	}

	/**
	 * Return TSconfig for a page id
	 *
	 * @param	integer		Page id (PID) from which to get configuration.
	 * @return	array		TSconfig array, if any
	 */
	function getTCEMAIN_TSconfig($tscPID)	{
		if (!isset($this->cachedTSconfig[$tscPID]))	{
			$this->cachedTSconfig[$tscPID] = $this->BE_USER->getTSConfig('TCEMAIN',t3lib_BEfunc::getPagesTSconfig($tscPID));
		}
		return $this->cachedTSconfig[$tscPID]['properties'];
	}

	/**
	 * Extract entries from TSconfig for a specific table. This will merge specific and default configuration together.
	 *
	 * @param	string		Table name
	 * @param	array		TSconfig for page
	 * @return	array		TSconfig merged
	 * @see getTCEMAIN_TSconfig()
	 */
	function getTableEntries($table,$TSconfig)	{
		$tA = is_array($TSconfig['table.'][$table.'.']) ? $TSconfig['table.'][$table.'.'] : array();;
		$dA = is_array($TSconfig['default.']) ? $TSconfig['default.'] : array();
		return t3lib_div::array_merge_recursive_overrule($dA,$tA);
	}

	/**
	 * Returns the pid of a record from $table with $uid
	 *
	 * @param	string		Table name
	 * @param	integer		Record uid
	 * @return	integer		PID value (unless the record did not exist in which case FALSE)
	 */
	function getPID($table,$uid)	{
		$res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid', $table, 'uid='.intval($uid));
		if ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp))	{
			return $row['pid'];
		}
	}

	/**
	 * Executing dbAnalysisStore
	 * This will save MM relations for new records but is executed after records are created because we need to know the ID of them
	 *
	 * @return	void
	 */
	function dbAnalysisStoreExec()	{
		reset($this->dbAnalysisStore);
		while(list($k,$v)=each($this->dbAnalysisStore))	{
			$id = $this->substNEWwithIDs[$v[2]];
			if ($id)	{
				$v[2] = $id;
				$v[0]->writeMM($v[1],$v[2],$v[3]);
			}
		}
	}

	/**
	 * Removing files registered for removal before exit
	 *
	 * @return	void
	 */
	function removeRegisteredFiles()	{
		reset($this->removeFilesStore);
		while(list($k,$v)=each($this->removeFilesStore))	{
			unlink($v);
		}
	}

	/**
	 * Unlink (delete) typo3conf/temp_CACHED_*.php cache files
	 *
	 * @return	integer		The number of files deleted
	 */
	function removeCacheFiles()	{
		return t3lib_extMgm::removeCacheFiles();
	}

	/**
	 * Returns array, $CPtable, of pages under the $pid going down to $counter levels.
	 * Selecting ONLY pages which the user has read-access to!
	 *
	 * @param	array		Accumulation of page uid=>pid pairs in branch of $pid
	 * @param	integer		Page ID for which to find subpages
	 * @param	integer		Number of levels to go down.
	 * @param	integer		ID of root point for new copied branch: The idea seems to be that a copy is not made of the already new page!
	 * @return	array		Return array.
	 */
	function int_pageTreeInfo($CPtable,$pid,$counter, $rootID)	{
		if ($counter)	{
			$addW =  !$this->admin ? ' AND '.$this->BE_USER->getPagePermsClause($this->pMap['show']) : '';
	 		$mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', 'pages', 'pid='.intval($pid).$this->deleteClause('pages').$addW, '', 'sorting DESC');
	 		while($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($mres))	{
				if ($row['uid']!=$rootID)	{
		 			$CPtable[$row['uid']] = $pid;
		 			if ($counter-1)	{	// If the uid is NOT the rootID of the copyaction and if we are supposed to walk further down
		 				$CPtable = $this->int_pageTreeInfo($CPtable,$row['uid'],$counter-1, $rootID);
		 			}
				}
	 		}
		}
	 	return $CPtable;
	}

	/**
	 * List of all tables (those administrators has access to = array_keys of $TCA)
	 *
	 * @return	array		Array of all TCA table names
	 */
	function compileAdminTables()	{
		global $TCA;
		reset ($TCA);
		$listArr = array();
		while (list($table)=each($TCA))	{
			$listArr[]=$table;
		}
		return $listArr;
	}

	/**
	 * Checks if any uniqueInPid eval input fields are in the record and if so, they are re-written to be correct.
	 *
	 * @param	string		Table name
	 * @param	integer		Record UID
	 * @return	void
	 */
	function fixUniqueInPid($table,$uid)	{
		global $TCA;
		if ($TCA[$table])	{
			t3lib_div::loadTCA($table);
			reset ($TCA[$table]['columns']);
			$curData=$this->recordInfo($table,$uid,'*');
			$newData=array();
			while (list($field,$conf)=each($TCA[$table]['columns']))	{
				if ($conf['config']['type']=='input')	{
					$evalCodesArray = t3lib_div::trimExplode(',',$conf['config']['eval'],1);
					if (in_array('uniqueInPid',$evalCodesArray))	{
						$newV = $this->getUnique($table,$field,$curData[$field],$uid,$curData['pid']);
						if (strcmp($newV,$curData[$field]))	{
							$newData[$field]=$newV;
						}
					}
				}
			}
				// IF there are changed fields, then update the database
			if (count($newData))	{
				$this->updateDB($table,$uid,$newData);
			}
		}
	}

	/**
	 * When er record is copied you can specify fields from the previous record which should be copied into the new one
	 * This function is also called with new elements. But then $update must be set to zero and $newData containing the data array. In that case data in the incoming array is NOT overridden. (250202)
	 *
	 * @param	string		Table name
	 * @param	integer		Record UID
	 * @param	integer		UID of previous record
	 * @param	boolean		If set, updates the record
	 * @param	array		Input array. If fields are already specified AND $update is not set, values are not set in output array.
	 * @return	array		Output array (For when the copying operation needs to get the information instead of updating the info)
	 */
	function fixCopyAfterDuplFields($table,$uid,$prevUid,$update, $newData=array())	{
		global $TCA;
		if ($TCA[$table] && $TCA[$table]['ctrl']['copyAfterDuplFields'])	{
			t3lib_div::loadTCA($table);
			$prevData=$this->recordInfo($table,$prevUid,'*');
			$theFields = t3lib_div::trimExplode(',',$TCA[$table]['ctrl']['copyAfterDuplFields'],1);
			reset($theFields);
			while(list(,$field)=each($theFields))	{
				if ($TCA[$table]['columns'][$field] && ($update || !isset($newData[$field])))	{
					$newData[$field]=$prevData[$field];
				}
			}
			if ($update && count($newData))	{
				$this->updateDB($table,$uid,$newData);
			}
		}
		return $newData;
	}

	/**
	 * Returns all fieldnames from a table which are a list of files
	 *
	 * @param	string		Table name
	 * @return	array		Array of fieldnames that are either "group" or "file" types.
	 */
	function extFileFields($table)	{
		global $TCA;
		$listArr=array();
		t3lib_div::loadTCA($table);
		if ($TCA[$table]['columns'])	{
			reset($TCA[$table]['columns']);
			while (list($field,$configArr)=each($TCA[$table]['columns']))	{
				if ($configArr['config']['type']=='group' && $configArr['config']['internal_type']=='file')	{
					$listArr[]=$field;
				}
			}
		}
		return $listArr;
	}

	/**
	 * Returns all fieldnames from a table which have the unique evaluation type set.
	 *
	 * @param	string		Table name
	 * @return	array		Array of fieldnames
	 */
	function getUniqueFields($table)	{
		global $TCA;

		$listArr=array();
		t3lib_div::loadTCA($table);
		if ($TCA[$table]['columns'])	{
			reset($TCA[$table]['columns']);
			while (list($field,$configArr)=each($TCA[$table]['columns']))	{
				if ($configArr['config']['type']==='input')	{
					$evalCodesArray = t3lib_div::trimExplode(',',$configArr['config']['eval'],1);
					if (in_array('uniqueInPid',$evalCodesArray) || in_array('unique',$evalCodesArray))	{
						$listArr[]=$field;
					}
				}
			}
		}
		return $listArr;
	}

	/**
	 * Returns true if the TCA/columns field type is a DB reference field
	 *
	 * @param	array		config array for TCA/columns field
	 * @return	boolean		True if DB reference field (group/db or select with foreign-table)
	 */
	function isReferenceField($conf)	{
		return ($conf['type']=='group' && $conf['internal_type']=='db') ||	($conf['type']=='select' && $conf['foreign_table']);
	}

	/**
	 * Get modified header for a copied record
	 *
	 * @param	string		Table name
	 * @param	integer		PID value in which other records to test might be
	 * @param	string		Field name to get header value for.
	 * @param	string		Current field value
	 * @param	integer		Counter (number of recursions)
	 * @param	string		Previous title we checked for (in previous recursion)
	 * @return	string		The field value, possibly appended with a "copy label"
	 */
	function getCopyHeader($table,$pid,$field,$value,$count,$prevTitle='')	{
		global $TCA;

			// Set title value to check for:
		if ($count)	{
			$checkTitle = $value.rtrim(' '.sprintf($this->prependLabel($table),$count));
		}	else {
			$checkTitle = $value;
		}

			// Do check:
		if ($prevTitle != $checkTitle || $count<100)	{
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('uid', $table, 'pid='.intval($pid).' AND '.$field.'='.$GLOBALS['TYPO3_DB']->fullQuoteStr($checkTitle, $table).$this->deleteClause($table), '', '', '1');
			if ($GLOBALS['TYPO3_DB']->sql_num_rows($res))	{
				return $this->getCopyHeader($table,$pid,$field,$value,$count+1,$checkTitle);
			}
		}

			// Default is to just return the current input title if no other was returned before:
		return $checkTitle;
	}

	/**
	 * Return "copy" label for a table. Although the name is "prepend" it actually APPENDs the label (after ...)
	 *
	 * @param	string		Table name
	 * @return	string		Label to append, containing "%s" for the number
	 * @see getCopyHeader()
	 */
	function prependLabel($table)	{
		global $TCA;
		if (is_object($GLOBALS['LANG']))	{
			$label = $GLOBALS['LANG']->sL($TCA[$table]['ctrl']['prependAtCopy']);
		} else {
			list($label) = explode('|',$TCA[$table]['ctrl']['prependAtCopy']);
		}
		return $label;
	}

	/**
	 * Get the final pid based on $table and $pid ($destPid type... pos/neg)
	 *
	 * @param	string		Table name
	 * @param	integer		"Destination pid" : If the value is >= 0 it's just returned directly (through intval() though) but if the value is <0 then the method looks up the record with the uid equal to abs($pid) (positive number) and returns the PID of that record! The idea is that negative numbers point to the record AFTER WHICH the position is supposed to be!
	 * @return	integer
	 */
	function resolvePid($table,$pid)	{
		global $TCA;
		$pid = intval($pid);
		if ($pid < 0)	{
			$res = $GLOBALS['TYPO3_DB']->exec_SELECTquery('pid', $table, 'uid='.abs($pid));
			$row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res);

				// Look, if the record UID happens to be an offline record. If so, find its live version. Offline uids will be used when a page is versionized as "branch" so this is when we must correct - otherwise a pid of "-1" and a wrong sort-row number is returned which we don't want.
			if ($lookForLiveVersion = t3lib_BEfunc::getLiveVersionOfRecord($table,abs($pid),'pid'))	{
				$row = $lookForLiveVersion;
			}

			$pid = intval($row['pid']);
		} elseif ($this->BE_USER->workspace!==0 && $TCA[$table]['ctrl']['versioning_followPages']) { // PID points to page, the workspace is an offline space and the table follows page during versioning: This means we must check if the PID page has a version in the workspace with swapmode set to 0 (zero = page+content) and if so, change the pid to the uid of that version.
			if ($WSdestPage = t3lib_BEfunc::getWorkspaceVersionOfRecord($this->BE_USER->workspace, 'pages', $pid, 'uid,t3ver_swapmode'))	{	// Looks for workspace version of page.
				if ($WSdestPage['t3ver_swapmode']==0)	{	// if swapmode is zero, then change pid value.
					$pid = $WSdestPage['uid'];
				}
			}
		}
		return $pid;
	}

	/**
	 * Removes the prependAtCopy prefix on values
	 *
	 * @param	string		Table name
	 * @param	string		The value to fix
	 * @return	string		Clean name
	 */
	function clearPrefixFromValue($table,$value)	{
		global $TCA;
		$regex = sprintf(quotemeta($this->prependLabel($table)),'[0-9]*').'$';
		return @ereg_replace($regex,'',$value);
	}

	/**
	 * File functions on external file references. eg. deleting files when deleting record
	 *
	 * @param	string		Table name
	 * @param	string		Field name
	 * @param	string		List of files to work on from field
	 * @param	string		Function, eg. "deleteAll" which will delete all files listed.
	 * @return	void
	 */
	function extFileFunctions($table,$field,$filelist,$func)	{
		global $TCA;
		t3lib_div::loadTCA($table);
		$uploadFolder = $TCA[$table]['columns'][$field]['config']['uploadfolder'];
		if ($uploadFolder && trim($filelist))	{
			$uploadPath = $this->destPathFromUploadFolder($uploadFolder);
			$fileArray = explode(',',$filelist);
			while (list(,$theFile)=each($fileArray))	{
				$theFile=trim($theFile);
				if ($theFile)	{
					switch($func)	{
						case 'deleteAll':
							if (@is_file($uploadPath.'/'.$theFile))	{
								unlink ($uploadPath.'/'.$theFile);
							} else {
								$this->log($table,0,3,0,100,"Delete: Referenced file that was supposed to be deleted together with it's record didn't exist");
							}
						break;
					}
				}
			}
		}
	}

	/**
	 * Used by the deleteFunctions to check if there are records from disallowed tables under the pages to be deleted.
	 *
	 * @param	string		List of page integers
	 * @return	boolean		Return true, if permission granted
	 */
	function noRecordsFromUnallowedTables($inList)	{
		global $TCA;
		reset ($TCA);
		$inList = trim($this->rmComma(trim($inList)));
		if ($inList && !$this->admin)	{
			while (list($table) = each($TCA))	{
				$mres = $GLOBALS['TYPO3_DB']->exec_SELECTquery('count(*)', $table, 'pid IN ('.$inList.')'.t3lib_BEfunc::deleteClause($table));
				$count = $GLOBALS['TYPO3_DB']->sql_fetch_row($mres);
				if ($count[0] && ($this->tableReadOnly($table) || !$this->checkModifyAccessList($table)))	{
					return FALSE;
				}
			}
		}
		return TRUE;
	}

	/**
	 * Send an email notification to users in workspace
	 *
	 * @param	array		Workspace access array (from t3lib_userauthgroup::checkWorkspace())
	 * @param	integer		New Stage number: 0 = editing, 1= just ready for review, 10 = ready for publication, -1 = rejected!
	 * @param	string		Table name of element
	 * @param	integer		Record uid of element
	 * @param	string		User comment sent along with action
	 * @return	void
	 */
	function notifyStageChange($stat,$stageId,$table,$id,$comment)	{
		$workspaceRec = t3lib_BEfunc::getRecord('sys_workspace', $stat['uid']);

		if (is_array($workspaceRec))	{

				// Compile label:
			switch((int)$stageId)	{
				case 1:
					$newStage = 'Ready for review';
				break;
				case 10:
					$newStage = 'Ready for publishing';
				break;
				case -1:
					$newStage = 'Element was rejected!';
				break;
				case 0:
					$newStage = 'Rejected element was noticed and edited';
				break;
				default:
					$newStage = 'Unknown state change!?';
				break;
			}

				// Compile list of recipients:
			$emails = array();
			switch((int)$stat['stagechg_notification'])	{
				case 1:
					switch((int)$stageId)	{
						case 1:
							$emails = $this->notifyStageChange_getEmails($workspaceRec['reviewers']);
						break;
						case 10:
							$emails = $this->notifyStageChange_getEmails($workspaceRec['adminusers'], TRUE);
						break;
						case -1:
							$emails = $this->notifyStageChange_getEmails($workspaceRec['reviewers']);
							$emails = array_merge($emails,$this->notifyStageChange_getEmails($workspaceRec['members']));
						break;
						case 0:
							$emails = $this->notifyStageChange_getEmails($workspaceRec['members']);
						break;
 						default:
							$emails = $this->notifyStageChange_getEmails($workspaceRec['adminusers'], TRUE);
						break;
					}
				break;
				case 10:
					$emails = $this->notifyStageChange_getEmails($workspaceRec['adminusers'], TRUE);
					$emails = array_merge($emails,$this->notifyStageChange_getEmails($workspaceRec['reviewers']));
					$emails = array_merge($emails,$this->notifyStageChange_getEmails($workspaceRec['members']));
				break;
			}
			$emails = array_unique($emails);

				// Send email:
			if (count($emails))	{
				$message = sprintf('
At the TYPO3 site "%s" (%s)
in workspace "%s" (#%s)
the stage has changed for the element "%s":

==> %s

User Comment:
"%s"

State was change by %s (username: %s)
				',
				$GLOBALS['TYPO3_CONF_VARS']['SYS']['sitename'],
				t3lib_div::getIndpEnv('TYPO3_SITE_URL').TYPO3_mainDir,
				$workspaceRec['title'],
				$workspaceRec['uid'],
				$table.':'.$id,
				$newStage,
				$comment,
				$this->BE_USER->user['realName'],
				$this->BE_USER->user['username']);

				t3lib_div::plainMailEncoded(
					implode(',',$emails),
					'TYPO3 Workspace Note: Stage Change for '.$table.':'.$id,
					trim($message)
				);
			}
		}
	}

	/**
	 * Return emails addresses of be_users from input list.
	 *
	 * @param	string		List of backend users, on the form "be_users_10,be_users_2" or "10,2" in case noTablePrefix is set.
	 * @param	boolean		If set, the input list are integers and not strings.
	 * @return	array		Array of emails
	 */
	function notifyStageChange_getEmails($listOfUsers,$noTablePrefix=FALSE)	{
		$users = t3lib_div::trimExplode(',',$listOfUsers,1);
		$emails = array();
		foreach($users as $userIdent)	{
			if ($noTablePrefix)	{
				$id = intval($userIdent);
			} else {
				list($table,$id) = t3lib_div::revExplode('_',$userIdent,2);
			}
			if ($table==='be_users' || $noTablePrefix)	{
				if ($userRecord = t3lib_BEfunc::getRecord('be_users', $id, 'email'))	{
					if (strlen(trim($userRecord['email'])))	{
						$emails[$id] = $userRecord['email'];
					}
				}
			}
		}
		return $emails;
	}












	/******************************
	 *
	 * Clearing cache
	 *
	 ******************************/

	/**
	 * Clearing the cache based on a page being updated
	 * If the $table is 'pages' then cache is cleared for all pages on the same level (and subsequent?)
	 * Else just clear the cache for the parent page of the record.
	 *
	 * @param	string		Table name of record that was just updated.
	 * @param	integer		UID of updated / inserted record
	 * @return	void
	 */
	function clear_cache($table,$uid) {
		global $TCA, $TYPO3_CONF_VARS;

		$uid = intval($uid);
		if (is_array($TCA[$table]) && $uid > 0)	{

				// Get Page TSconfig relavant:
			list($tscPID) = t3lib_BEfunc::getTSCpid($table,$uid,'');
			$TSConfig = $this->getTCEMAIN_TSconfig($tscPID);

			if (!$TSConfig['clearCache_disable'])	{

					// If table is "pages":
				if (t3lib_extMgm::isLoaded('cms'))	{
					$list_cache = array();
					if ($table=='pages')	{

							// Builds list of pages on the SAME level as this page (siblings)
						$res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
										'A.pid AS pid, B.uid AS uid',
										'pages A, pages B',
										'A.uid='.intval($uid).' AND B.pid=A.pid AND B.deleted=0'
									);

						$pid_tmp = 0;
						while ($row_tmp = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp)) {
							$list_cache[] = $row_tmp['uid'];
							$pid_tmp = $row_tmp['pid'];

								// Add children as well:
							if ($TSConfig['clearCache_pageSiblingChildren'])	{
								$res_tmp2 = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
												'uid',
												'pages',
												'pid='.intval($row_tmp['uid']).' AND deleted=0'
											);
								while ($row_tmp2 = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp2))	{
									$list_cache[] = $row_tmp2['uid'];
								}
							}
						}

							// Finally, add the parent page as well:
						$list_cache[] = $pid_tmp;

							// Add grand-parent as well:
						if ($TSConfig['clearCache_pageGrandParent'])	{
							$res_tmp = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
											'pid',
											'pages',
											'uid='.intval($pid_tmp)
										);
							if ($row_tmp = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_tmp))	{
								$list_cache[] = $row_tmp['pid'];
							}
						}
					} else {	// For other tables than "pages", delete cache for the records "parent page".
						$list_cache[] = intval($this->getPID($table,$uid));
					}

						// Call pre-processing function for clearing of cache for page ids:
					if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval']))	{
						foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval'] as $funcName)	{
							$_params = array('pageIdArray' => &$list_cache, 'table' => $table, 'uid' => $uid, 'functionID' => 'clear_cache()');
								// Returns the array of ids to clear, false if nothing should be cleared! Never an empty array!
							t3lib_div::callUserFunction($funcName,$_params,$this);
						}
					}

						// Delete cache for selected pages:
					if (is_array($list_cache))	{
						$GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages','page_id IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($list_cache)).')');
						$GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pagesection', 'page_id IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($list_cache)).')');
					}
				}
			}

				// Clear cache for pages entered in TSconfig:
			if ($TSConfig['clearCacheCmd'])	{
				$Commands = t3lib_div::trimExplode(',',strtolower($TSConfig['clearCacheCmd']),1);
				$Commands = array_unique($Commands);
				foreach($Commands as $cmdPart)	{
					$this->clear_cacheCmd($cmdPart);
				}
			}

				// Call post processing function for clear-cache:
			global $TYPO3_CONF_VARS;
			if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc']))	{
// FIXME $uid_page is undefined
				$_params = array('table' => $table,'uid' => $uid,'uid_page' => $uid_page,'TSConfig' => $TSConfig);
				foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'] as $_funcRef)	{
					t3lib_div::callUserFunction($_funcRef,$_params,$this);
				}
			}
		}
	}

	/**
	 * Clears the cache based on a command, $cacheCmd
	 *
	 * $cacheCmd='pages':	Clears cache for all pages. Requires admin-flag to be set for BE_USER
	 * $cacheCmd='all':		Clears all cache_tables. This is necessary if templates are updated. Requires admin-flag to be set for BE_USER
	 * $cacheCmd=[integer]:		Clears cache for the page pointed to by $cacheCmd (an integer).
	 *
	 * Can call a list of post processing functions as defined in $TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'] (num array with values being the function references, called by t3lib_div::callUserFunction())
	 *
	 * @param	string		The cache comment, see above description.
	 * @return	void
	 */
	function clear_cacheCmd($cacheCmd)	{
		global $TYPO3_CONF_VARS;

			// Clear cache for either ALL pages or ALL tables!
		switch($cacheCmd)	{
			case 'pages':
				if ($this->admin || $this->BE_USER->getTSConfigVal('options.clearCache.pages'))	{
					if (t3lib_extMgm::isLoaded('cms'))	{
						$GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages','');
					}
				}
			break;
			case 'all':
				if ($this->admin || $this->BE_USER->getTSConfigVal('options.clearCache.all'))	{
					if (t3lib_extMgm::isLoaded('cms'))	{
						$GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages','');
						$GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pagesection','');
					}
					$GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_hash','');

						// Clearing additional cache tables:
					if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearAllCache_additionalTables']))	{
						foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearAllCache_additionalTables'] as $tableName)	{
							if (!ereg('[^[:alnum:]_]',$tableName) && substr($tableName,-5)=='cache')	{
								$GLOBALS['TYPO3_DB']->exec_DELETEquery($tableName,'');
							} else {
								die('Fatal Error: Trying to flush table "'.$tableName.'" with "Clear All Cache"');
							}
						}
					}
				}
			break;
			case 'temp_CACHED':
				if ($this->admin && $TYPO3_CONF_VARS['EXT']['extCache'])	{
					$this->removeCacheFiles();
				}
			break;
		}

			// Clear cache for a page ID!
		if (t3lib_div::testInt($cacheCmd))	{
			if (t3lib_extMgm::isLoaded('cms'))	{

				$list_cache = array($cacheCmd);

					// Call pre-processing function for clearing of cache for page ids:
				if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval']))	{
					foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearPageCacheEval'] as $funcName)	{
						$_params = array('pageIdArray' => &$list_cache, 'cacheCmd' => $cacheCmd, 'functionID' => 'clear_cacheCmd()');
							// Returns the array of ids to clear, false if nothing should be cleared! Never an empty array!
						t3lib_div::callUserFunction($funcName,$_params,$this);
					}
				}

					// Delete cache for selected pages:
				if (is_array($list_cache))	{
					$GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pages','page_id IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($list_cache)).')');
					$GLOBALS['TYPO3_DB']->exec_DELETEquery('cache_pagesection', 'page_id IN ('.implode(',',$GLOBALS['TYPO3_DB']->cleanIntArray($list_cache)).')');	// Originally, cache_pagesection was not cleared with cache_pages!
				}
			}
		}

			// Call post processing function for clear-cache:
		if (is_array($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc']))	{
			$_params = array('cacheCmd'=>$cacheCmd);
			foreach($TYPO3_CONF_VARS['SC_OPTIONS']['t3lib/class.t3lib_tcemain.php']['clearCachePostProc'] as $_funcRef)	{
				t3lib_div::callUserFunction($_funcRef,$_params,$this);
			}
		}
	}














	/*****************************
	 *
	 * Logging
	 *
	 *****************************/

	/**
	 * Logging actions from TCEmain
	 *
	 * @param	string		Table name the log entry is concerned with. Blank if NA
	 * @param	integer		Record UID. Zero if NA
	 * @param	integer		Action number: 0=No category, 1=new record, 2=update record, 3= delete record, 4= move record, 5= Check/evaluate
	 * @param	integer		Normally 0 (zero). If set, it indicates that this log-entry is used to notify the backend of a record which is moved to another location
	 * @param	integer		The severity: 0 = message, 1 = error, 2 = System Error, 3 = security notice (admin)
	 * @param	string		Default error message in english
	 * @param	integer		This number is unique for every combination of $type and $action. This is the error-message number, which can later be used to translate error messages. 0 if not categorized, -1 if temporary
	 * @param	array		Array with special information that may go into $details by '%s' marks / sprintf() when the log is shown
	 * @param	integer		The page_uid (pid) where the event occurred. Used to select log-content for specific pages.
	 * @param	string		NEW id for new records
	 * @return	integer		Log entry UID
	 * @see	class.t3lib_userauthgroup.php
	 */
	function log($table,$recuid,$action,$recpid,$error,$details,$details_nr=-1,$data=array(),$event_pid=-1,$NEWid='') {
		if ($this->enableLogging)	{
			$type=1;	// Type value for tce_db.php
			if (!$this->storeLogMessages)	{$details='';}
			if ($error>0)	$this->errorLog[] = '['.$type.'.'.$action.'.'.$details_nr.']: '.$details;
			return $this->BE_USER->writelog($type,$action,$error,$details_nr,$details,$data,$table,$recuid,$recpid,$event_pid,$NEWid);
		}
	}

	/**
	 * Simple logging function meant to be used when logging messages is not yet fixed.
	 *
	 * @param	string		Message string
	 * @param	integer		Error code, see log()
	 * @return	integer		Log entry UID
	 * @see log()
	 */
	function newlog($message, $error=0)	{
		return $this->log('',0,0,0,$error,$message,-1);
	}

	/**
	 * Print log error messages from the operations of this script instance
	 *
	 * @param	string		Redirect URL (for creating link in message)
	 * @return	void		(Will exit on error)
	 */
	function printLogErrorMessages($redirect)	{

		$res_log = $GLOBALS['TYPO3_DB']->exec_SELECTquery(
					'*',
					'sys_log',
					'type=1 AND userid='.intval($this->BE_USER->user['uid']).' AND tstamp='.intval($GLOBALS['EXEC_TIME']).'	AND error!=0'
				);
		$errorJS = array();
		while ($row = $GLOBALS['TYPO3_DB']->sql_fetch_assoc($res_log)) {
			$log_data = unserialize($row['log_data']);
			$errorJS[] = $row['error'].': '.sprintf($row['details'], $log_data[0],$log_data[1],$log_data[2],$log_data[3],$log_data[4]);
		}

		if (count($errorJS))	{
			$error_doc = t3lib_div::makeInstance('template');
			$error_doc->backPath = $GLOBALS['BACK_PATH'];

			$content.= $error_doc->startPage('tce_db.php Error output');

			$lines[] = '
					<tr class="bgColor5">
						<td colspan="2" align="center"><strong>Errors:</strong></td>
					</tr>';

			foreach($errorJS as $line)	{
				$lines[] = '
					<tr class="bgColor4">
						<td valign="top"><img'.t3lib_iconWorks::skinImg($error_doc->backPath,'gfx/icon_fatalerror.gif','width="18" height="16"').' alt="" /></td>
						<td>'.htmlspecialchars($line).'</td>
					</tr>';
			}

			$lines[] = '
					<tr>
						<td colspan="2" align="center"><br />'.
						'<form action=""><input type="submit" value="Continue" onclick="'.htmlspecialchars('window.location.href=\''.$redirect.'\';return false;').'"></form>'.
						'</td>
					</tr>';

			$content.= '
				<br/><br/>
				<table border="0" cellpadding="1" cellspacing="1" width="300" align="center">
					'.implode('',$lines).'
				</table>';

			$content.= $error_doc->endPage();
			echo $content;
			exit;
		}
	}
}



if (defined('TYPO3_MODE') && $TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_tcemain.php'])	{
	include_once($TYPO3_CONF_VARS[TYPO3_MODE]['XCLASS']['t3lib/class.t3lib_tcemain.php']);
}
?>