summaryrefslogtreecommitdiff
path: root/library/WT/Report/Base.php
blob: 7627c01abdda5711ff2e9351eeb5e1bc3e48394c (plain)
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
<?php
// Base Report Generator
//
// used by the SAX parser to generate reports from the XML report file.
//
// webtrees: Web based Family History software
// Copyright (C) 2013 webtrees development team.
//
// Derived from PhpGedView
// Copyright (C) 2002 to 2009 PGV Development Team.  All rights reserved.
//
// Modifications Copyright (c) 2010 Greg Roach
//
// This program 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.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

if (!defined('WT_WEBTREES')) {
	header('HTTP/1.0 403 Forbidden');
	exit;
}

/**
 * Enable HTML code to pass for testing
 * false = use the old style, HTML disabled
 * true = use the new style, HTML enabled
 */
define("WT_RNEW", false);

/**
 * Main Report Class
 *
 * Document wide functions and variable defaults that will be inherited of the report modules
 * @package webtrees
 * @subpackage Reports
 */
class WT_Report_Base {
	/**
	* Left Margin (expressed in points) Default: 17.99 mm, 0.7083 inch
	* @see DocSHandler()
	* @var float
	*/
	public $leftmargin = 51;
	/**
	* Right Margin (expressed in points) Default: 9.87 mm, 0.389 inch
	* @see DocSHandler()
	* @var float
	*/
	public $rightmargin = 28;
	/**
	* Top Margin (expressed in points) Default: 26.81 mm
	* @see DocSHandler()
	* @var float
	*/
	public $topmargin = 76;
	/**
	* Bottom Margin (expressed in points) Default: 21.6 mm
	* @see DocSHandler()
	* @var float
	*/
	public $bottommargin = 60;
	/**
	* Header Margin (expressed in points) Default: 4.93 mm
	* @see DocSHandler()
	* @var float
	*/
	public $headermargin = 14;
	/**
	* Footer Margin (expressed in points) Default: 9.88 mm, 0.389 inch
	* @see DocSHandler()
	* @var float
	*/
	public $footermargin = 28;

	/**
	* Page orientation (portrait, landscape)
	* @see DocSHandler()
	* @var string
	*/
	public $orientation = "portrait";
	/**
	* Page format name
	* @see DocSHandler()
	* @see WT_Report_Base::setup()
	* @var string
	*/
	public $pageFormat = "A4";

	/**
	* Height of page format in points
	* @see DocSHandler()
	* @see WT_Report_Base::setup()
	* @var float
	*/
	public $pageh = 0.0;
	/**
	* Width of page format in points
	* @see DocSHandler()
	* @see WT_Report_Base::setup()
	* @var float
	*/
	public $pagew = 0.0;

	/**
	* An array of the Styles elements found in the document
	* @see StyleSHandler()
	* @var array
	*/
	public $Styles = array();
	/**
	* The default Report font name
	* @see StyleSHandler()
	* @var string
	*/
	public $defaultFont = "dejavusans";
	/**
	* The default Report font size
	* @see StyleSHandler()
	* @var int
	*/
	public $defaultFontSize = 12;

	/**
	* Header (H), Page header (PH), Body (B) or Footer (F)
	* @var string
	*/
	public $processing = "H";

	/**
	* RTL Language (false=LTR, true=RTL)
	* @see WT_Report_Base::setup()
	* @var boolean
	*/
	public $rtl = false;

	/**
	* User measure unit.
	* @var string const
	*/
	const unit = "pt";

	/**
	* Show the Generated by... (true=show the text)
	* @see DocSHandler()
	* @var boolean
	*/
	public $showGenText = true;
	/**
	* Generated By... text
	* @see WT_Report_Base::setup()
	* @var string
	*/
	public $generatedby = "";

	/**
	* webtrees URL
	* @var string const
	*/
	const wt_url = WT_WEBTREES_URL;

	/**
	* The report title
	* @see WT_Report_Base::addTitle()
	* @var string
	*/
	public $title = "";
	/**
	* Author of the report, the users full name
	* @var string
	* @todo add the author support
	*/
	public $rauthor = WT_SERVER_NAME;
	/**
	* Keywords
	* @see WT_Report_Base::setup()
	* @var string
	*/
	public $rkeywords = "";
	/**
	* Report Description / Subject
	* @see WT_Report_Base::addDescription()
	* @var string
	*/
	public $rsubject = "";

	/**
	* Initial Setup - WT_Report_Base
	*
	* Setting up document wide defaults that will be inherited of the report modules
	* As DEFAULT A4 and Portrait will be used if not set
	*
	* @see DocSHandler()
	* @todo add page sizes to wiki
	*/
	function setup() {
		global $TEXT_DIRECTION;

		// Set RTL direction
		if ($TEXT_DIRECTION == "rtl") {
			$this->rtl = true;
		}
		// Set the Keywords
		$this->rkeywords = '';
		// Generated By...text
		// I18N: This is a report footer. %s is the name of the application.
		$this->generatedby = WT_I18N::translate('Generated by %s', WT_WEBTREES.' '.WT_VERSION_TEXT);

		// For known size pages
		if (($this->pagew == 0) AND ($this->pageh == 0)) {
			/**
			* The current ISO 216 standard was introduced in 1975 and is a direct follow up to the german DIN 476 standard from 1922. ISO 216 is also called EN 20216 in Europe.
			* The ISO paper sizes are based on the metric system so everything else is aproxiamte
			*
			* The Series A is used for Standard Printing and Stationary.
			* The Series B is used for Posters, Wall-Charts etc.
			* The C series is used for folders, post cards and envelopes. C series envelope is suitable to insert A series sizes.
			* ISO also define format series RA and SRA for untrimmed raw paper, where SRA stands for 'supplementary raw format A'.
			* Japan has adopted the ISO series A sizes, but its series B sizes are slightly different. These sizes are sometimes called JIS B or JB sizes.
			*  sun was a unit of length used in Japan and is equal to about 3.03 cm or 1.193 inches
			* The United States, Canada, and in part Mexico, are today the only industrialized nations in which the ISO standard paper sizes are not yet widely used.
			*
			* A0 & A1        Technical drawings, posters
			* A1 & A2        Flip charts
			* A2 & A3        Drawings, diagrams, large tables
			* A4             Letters, magazines, forms, catalogs, laser printer and copying machine output
			* A5             Note pads
			* A6             Postcards
			* B5, A5, B6  A6 Books
			* C4, C5, C6     Envelopes for A4 letters: unfolded (C4), folded once (C5), folded twice (C6)
			* B4 & A3        Newspapers, supported by most copying machines in addition to A4
			* B8 & A8        Playing cards
			*
			* 1 inch = 72 points
			* 1 mm = 2.8346457 points
			* 1 inch = 25.4 mm
			* 1 point = 0,35278 mm
			*/
			switch ($this->pageFormat) {
				// ISO A series
				case "4A0": {$sizes = array(4767.86,6740.79);break;} // ISO 216, 1682 mm x 2378 mm
				case "2A0": {$sizes = array(3370.39,4767.86);break;} // ISO 216, 1189 mm x 1682 mm
				case "A0":  {$sizes = array(2383.94,3370.39);break;} // ISO 216, 841 mm x 1189mm
				case "A1":  {$sizes = array(1683.78,2383.94);break;} // ISO 216, 594 mm x 841 mm
				case "A2":  {$sizes = array(1190.55,1683.78);break;} // ISO 216, 420 mm x 594 mm
				case "A3":  {$sizes = array( 841.89,1190.55);break;} // ISO 216, 297 mm x 420 mm
				case "A4":  default:{                                // For unknown Page Size Name
							$sizes = array(595.28,841.89);                 // ISO 216, 210 mm 297 mm
							$this->pageFormat = "A4";
							break;}
				case "A5":  {$sizes = array(419.53,595.28);break;} // ISO 216, 148 mm x 210 mm
				case "A6":  {$sizes = array(297.64,419.53);break;} // ISO 216, 105 mm x 148 mm
				case "A7":  {$sizes = array(209.76,297.64);break;} // ISO 216, 74 mm x 105 mm
				case "A8":  {$sizes = array(147.40,209.76);break;} // ISO 216, 52 mm x 74 mm
				case "A9":  {$sizes = array(104.88,147.40);break;} // ISO 216, 37 mm x 52 mm
				case "A10": {$sizes = array( 73.70,104.88);break;} // ISO 216, 26 mm x 37 mm
				// ISO B series
				case "B0":  {$sizes = array(2834.65,4008.19);break;} // ISO 216, 1000 mm x 1414 mm
				case "B1":  {$sizes = array(2004.09,2834.65);break;} // ISO 216, 707 mm x 1000 mm
				case "B2":  {$sizes = array(1417.32,2004.09);break;} // ISO 216, 500 mm x 707 mm
				case "B3":  {$sizes = array(1000.63,1417.32);break;} // ISO 216, 353 mm x 500 mm
				case "B4":  {$sizes = array( 708.66,1000.63);break;} // ISO 216, 250 mm x 353 mm
				case "B5":  {$sizes = array( 498.90, 708.66);break;} // ISO 216, 176 mm x 250 mm
				case "B6":  {$sizes = array( 354.33, 498.90);break;} // ISO 216, 125 mm x 176 mm
				case "B7":  {$sizes = array( 249.45, 354.33);break;} // ISO 216, 88 mm x 125 mm
				case "B8":  {$sizes = array( 175.75, 249.45);break;} // ISO 216, 62 mm x 88 mm
				case "B9":  {$sizes = array( 124.72, 175.75);break;} // ISO 216, 44 mm x 62 mm
				case "B10": {$sizes = array(  87.87, 124.72);break;} // ISO 216, 31 mm x 44 mm
				// ISO C series, Envelope
				case "C0":  {$sizes = array(2599.37,3676.54);break;} // ISO 269, 917 mm x 1297 mm, For flat A0 sheet
				case "C1":  {$sizes = array(1836.85,2599.37);break;} // ISO 269, 648 mm x 917 mm, For flat A1 sheet
				case "C2":  {$sizes = array(1298.27,1836.85);break;} // ISO 269, 458 mm x 648 mm, For flat A2 sheet, A1 folded in half
				case "C3":  {$sizes = array( 918.43,1298.27);break;} // ISO 269, 324 mm x 458 mm, For flat A3 sheet, A2 folded in half
				case "C4":  {$sizes = array( 649.13, 918.43);break;} // ISO 269, 229 mm x 324 mm, For flat A4 sheet, A3 folded in half
				case "C5":  {$sizes = array( 459.21, 649.13);break;} // ISO 269, 162 mm x 229 mm, For flat A5 sheet, A4 folded in half
				case "C6/5":{$sizes = array( 323.15, 649.13);break;} // ISO 269, 114 mm x 229 mm. A5 folded twice = 1/3 A4. Alternative for the DL envelope
				case "C6":  {$sizes = array( 323.15, 459.21);break;} // ISO 269, 114 mm x 162 mm, For A5 folded in half
				case "C7/6":{$sizes = array( 229.61, 459.21);break;} // ISO 269, 81 mm x 162 mm, For A5 sheet folded in thirds
				case "C7":  {$sizes = array( 229.61, 323.15);break;} // ISO 269, 81 mm x 114 mm, For A5 folded in quarters
				case "C8":  {$sizes = array( 161.57, 229.61);break;} // ISO 269, 57 mm x 81 mm
				case "C9":  {$sizes = array( 113.39, 161.57);break;} // ISO 269, 40 mm x 57 mm
				case "C10": {$sizes = array(  79.37, 113.39);break;} // ISO 269, 28 mm x 40 mm
				case "DL":  {$sizes = array( 311.81, 623.62);break;} // Original DIN 678 but ISO 269 now has this C6/5 , 110 mm x 220 mm, For A4 sheet folded in thirds, A5 in half
				// Untrimmed stock sizes for the ISO-A Series - ISO primary range
				case "RA0": {$sizes = array(2437.80,3458.27);break;} // ISO 478, 860 mm x 1220 mm
				case "RA1": {$sizes = array(1729.13,2437.80);break;} // ISO 478, 610 mm x 860 mm
				case "RA2": {$sizes = array(1218.90,1729.13);break;} // ISO 478, 430 mm x 610 mm
				case "RA3": {$sizes = array( 864.57,1218.90);break;} // ISO 478, 305 mm x 430 mm
				case "RA4": {$sizes = array( 609.45, 864.57);break;} // ISO 478, 215 mm x 305 mm
				// Untrimmed stock sizes for the ISO-A Series - ISO supplementary range
				case "SRA0": {$sizes = array(2551.18,3628.35);break;} // ISO 593, 900 mm x 1280 mm
				case "SRA1": {$sizes = array(1814.17,2551.18);break;} // ISO 593, 640 mm x 900 mm
				case "SRA2": {$sizes = array(1275.59,1814.17);break;} // ISO 593, 450 mm x 640 mm
				case "SRA3": {$sizes = array( 907.09,1275.59);break;} // ISO 593, 320 mm x 450 mm
				case "SRA4": {$sizes = array( 637.80, 907.09);break;} // ISO 593, 225 mm x 320 mm
				// ISO size variations
				case "A2EXTRA":  {$sizes = array(1261.42,1754.65);break;} // ISO 216, 445 mm x 619 mm
				case "A2SUPER":  {$sizes = array( 864.57,1440.00);break;} // ISO 216, 305 mm x 508 mm
				case "A3EXTRA":  {$sizes = array( 912.76,1261.42);break;} // ISO 216, 322 mm x 445 mm
				case "SUPERA3":  {$sizes = array( 864.57,1380.47);break;} // ISO 216, 305 mm x 487 mm
				case "A4EXTRA":  {$sizes = array( 666.14, 912.76);break;} // ISO 216, 235 mm x 322 mm
				case "A4LONG":   {$sizes = array( 595.28, 986.46);break;} // ISO 216, 210 mm x 348 mm
				case "A4SUPER":  {$sizes = array( 649.13, 912.76);break;} // ISO 216, 229 mm x 322 mm
				case "SUPERA4":  {$sizes = array( 643.46,1009.13);break;} // ISO 216, 227 mm x 356 mm
				case "A5EXTRA":  {$sizes = array( 490.39, 666.14);break;} // ISO 216, 173 mm x 235 mm
				case "SOB5EXTRA":{$sizes = array( 572.60, 782.36);break;} // ISO 216, 202 mm x 276 mm
				// Japanese version of the ISO 216 B series
				case "JB0": {$sizes = array(2919.69,4127.24);break;} // JIS P 0138-61, 1030 mm x 1456 mm
				case "JB1": {$sizes = array(2063.62,2919.69);break;} // JIS P 0138-61, 728 mm x 1030 mm
				case "JB2": {$sizes = array(1459.84,2063.62);break;} // JIS P 0138-61, 515 mm x 728 mm
				case "JB3": {$sizes = array(1031.81,1459.84);break;} // JIS P 0138-61, 364 mm x 515 mm
				case "JB4": {$sizes = array( 728.50,1031.81);break;} // JIS P 0138-61, 257 mm x 364 mm
				case "JB5": {$sizes = array( 515.91, 728.50);break;} // JIS P 0138-61, 182 mm x 257 mm
				case "JB6": {$sizes = array( 362.83, 515.91);break;} // JIS P 0138-61, 128 mm x 182 mm
				case "JB7": {$sizes = array( 257.95, 362.83);break;} // JIS P 0138-61, 91 mm x 128 mm
				case "JB8": {$sizes = array( 181.42, 257.95);break;} // JIS P 0138-61, 64 mm x 91 mm
				case "JB9": {$sizes = array( 127.56, 181.42);break;} // JIS P 0138-61, 45 mm x 64 mm
				case "JB10":{$sizes = array(  90.71, 127.56);break;} // JIS P 0138-61, 32 mm x 45 mm
				// US pages
				case "EXECUTIVE": {$sizes = array(522.00, 756.00); break;} // 7.25 in x 10.5 in
				case "FOLIO":     {$sizes = array(612.00, 936.00); break;} // 8.5 in x 13 in
				case "FOOLSCAP":  {$sizes = array(972.00,1224.00); break;} // 13.5 in x 17 in
				case "LEDGER":    {$sizes = array(792.00,1224.00); break;} // 11 in x 17 in
				case "LEGAL":     {$sizes = array(612.00,1008.00); break;} // 8.5 in x 14 in
				case "LETTER":    {$sizes = array(612.00, 792.00); break;} // 8.5 in x 11 in
				case "QUARTO":    {$sizes = array(609.12, 777.50); break;} // 8.46 in x 10.8 in
				case "STATEMENT": {$sizes = array(396.00, 612.00); break;} // 5.5 in x 8.5 in
				case "USGOVT":    {$sizes = array(576.00, 792.00); break;} // 8 in x 11 in
			}
			$this->pagew = $sizes[0];
			$this->pageh = $sizes[1];
		}
		else {
			if ($this->pagew < 10) {
				die("<strong>REPORT ERROR WT_Report_Base::setup(): </strong>For custom size pages you must set \"customwidth\" larger then this in the XML file");
			}
			if ($this->pageh < 10) {
				die("<strong>REPORT ERROR WT_Report_Base::setup(): </strong>For custom size pages you must set \"customheight\" larger then this in the XML file");
			}
		}
		return 0;
	}

	/**
	* Process the Header , Page header, Body or Footer - WT_Report_Base
	*
	* @param string $p Header (H), Page header (PH), Body (B) or Footer (F)
	*/
	function setProcessing($p) {
		$this->processing = $p;
		return 0;
	}

	/**
	* Add the Title when raw character data is used in Title - WT_Report_Base
	*
	* @param string $data
	*/
	function addTitle($data) {
		$this->title .= $data;
		return 0;
	}

	/**
	* Add the Description when raw character data is used in Description - WT_Report_Base
	*
	* @param string $data
	*/
	function addDescription($data) {
		$this->rsubject .= $data;
		return 0;
	}

	/**
	* Add Style to Styles array - WT_Report_Base
	*
	* @see StyleSHandler()
	* @param array $style
	*/
	function addStyle($style) {
		$this->Styles[$style['name']] = $style;
		return 0;
	}

	/**
	* Get a style from the Styles array - WT_Report_Base
	*
	* @param string $s Style name
	* @return array
	*/
	function getStyle($s) {
		if (!isset($this->Styles[$s])) {
			return current($this->Styles);
		}
		return $this->Styles[$s];
	}
}

/**
 * Main WT Report Element class that all other page elements are extended from
 *
 * @package webtrees
 * @subpackage Reports
 */
class Element {
	/**
	* @var string
	*/
	public $text = "";

	/**
	* Element renderer
	* @param &$renderer
	*/
	function render(&$renderer) {
		//print "Nothing rendered.  Something bad happened";
		//debug_print_backtrace();
		//-- to be implemented in inherited classes
		return 0;
	}

	function getHeight(&$renderer) {
		return 0;
	}

	function getWidth(&$renderer) {
		return 0;
	}

	function addText($t) {
		global $embed_fonts, $SpecialOrds, $wt_report, $reportTitle, $reportDescription;

		foreach ($SpecialOrds as $ord) {
			if (strpos($t, chr($ord))!==false) {
				$embed_fonts = true;
			}
		}
		$t = trim($t, "\r\n\t");
		$t = str_replace(array("<br>", "&nbsp;"), array("\n", " "), $t);
		if (!WT_RNEW) {
			$t = strip_tags($t);
			$t = htmlspecialchars_decode($t);
		}
		$this->text .= $t;

		// Adding the title and description to the Document Properties
		if ($reportTitle) {
			$wt_report->addTitle($t);
		} elseif ($reportDescription) {
			$wt_report->addDescription($t);
		}
		return 0;
	}

	function addNewline() {
		$this->text .= "\n";
		return 0;
	}

	function getValue() {
		return $this->text;
	}

	function setWrapWidth($wrapwidth, $cellwidth) {
		return 0;
	}

	function renderFootnote(&$renderer) {
		return false;
		//-- to be implemented in inherited classes
	}

	/**
	* Get the Class name type
	*
	* @return string ElementBase
	*/
	function get_type() {
		return "ElementBase";
	}

	function setText($text) {
		$this->text = $text;
		return 0;
	}

} //-- END Element

/**
* HTML element class
*
* @package webtrees
* @subpackage Reports
* @todo add info
*/
class Html extends Element {
	public $tag;
	public $attrs;
	public $elements = array();

	function Html($tag, $attrs) {
		$this->tag = $tag;
		$this->attrs = $attrs;
		return 0;
	}

	function getStart() {
		$str = "<".$this->tag." ";
		foreach ($this->attrs as $key=>$value) {
			$str .= $key."=\"".$value."\" ";
		}
		$str .= ">";
		return $str;
	}

	function getEnd() {
		return "</".$this->tag.">";
	}

	function addElement($element) {
		$this->elements[] = $element;
		return 0;
	}

	/**
	* Get the class type
	* @return string Html
	*/
	function get_type() {
		return "Html";
	}
}

/**
 * Cell element class
*
* @package webtrees
* @subpackage Reports
*/
class Cell extends Element {
	/**
	* Allows to center or align the text. Possible values are:<ul><li>left or empty string: left align</li><li>center: center align</li><li>right: right align</li><li>justify: justification (default value when $ishtml=false)</li></ul>
	* @var string
	*/
	public $align = "";
	/**
	* Whether or not a border should be printed around this box. 0 = no border, 1 = border. Default is 0.
	* Or a string containing some or all of the following characters (in any order):<ul><li>L: left</li><li>T: top</li><li>R: right</li><li>B: bottom</li></ul>
	* @var mixed
	*/
	public $border;
	/**
	* Border color in HTML code
	* @var string
	*/
	public $bocolor;
	/**
	* The HTML color code to fill the background of this cell.
	* @var string
	*/
	public $bgcolor;
	/**
	* Indicates if the cell background must be painted (1) or transparent (0). Default value: 1.
	* If no background color is set then it will not be painted
	* @var int
	*/
	public $fill;
	/**
	* Cell height DEFAULT 0 (expressed in points)
	* The starting height of this cell. If the text wraps the height will automatically be adjusted.
	* @var int
	*/
	public $height;
	/**
	* Left position in user units (X-position). Default is the current position
	* @var mixed
	*/
	public $left;
	/**
	* Indicates where the current position should go after the call.  Possible values are:<ul><li>0: to the right [DEFAULT]</li><li>1: to the beginning of the next line</li><li>2: below</li></ul>
	* @var int
	*/
	public $newline;
	/**
	* The name of the Style that should be used to render the text.
	* @var string
	*/
	public $styleName;
	/**
	* Stretch carachter mode: <ul><li>0 = disabled (default)</li><li>1 = horizontal scaling only if necessary</li><li>2 = forced horizontal scaling</li><li>3 = character spacing only if necessary</li><li>4 = forced character spacing</li></ul>
	* @var int
	*/
	public $stretch;
	/**
	* Text color in HTML code
	* @var string
	*/
	public $tcolor;
	/**
	* Top position in user units (Y-position). Default is the current position
	* @var mixed
	*/
	public $top;
	/**
	* URL address
	* @var string
	*/
	public $url;
	/**
	* Cell width DEFAULT 0 (expressed in points)
	* Setting the width to 0 will make it the width from the current location to the right margin.
	* @var int
	*/
	public $width;

	public $reseth;

	/**
	* CELL - Element
	*
	* @param int $width cell width (expressed in points)
	* @param int $height cell height (expressed in points)
	* @param mixed $border Border style
	* @param string $align Text alignement
	* @param string $bgcolor Background color code
	* @param string $style The name of the text style
	* @param int $ln Indicates where the current position should go after the call
	* @param mixed $top Y-position
	* @param mixed $left X-position
	* @param int $fill Indicates if the cell background must be painted (1) or transparent (0). Default value: 0.
	* @param int $stretch Stretch carachter mode
	* @param string $bocolor Border color
	* @param string $tcolor Text color
	*/
	function Cell($width, $height, $border, $align, $bgcolor, $style, $ln, $top, $left, $fill, $stretch, $bocolor, $tcolor, $reseth) {
		$this->align = $align;
		$this->border = $border;
		$this->bgcolor = $bgcolor;
		$this->bocolor = $bocolor;
		$this->fill = $fill;
		$this->height = $height;
		$this->left = $left;
		$this->newline = $ln;
		$this->styleName = $style;
		$this->text = "";
		$this->tcolor = $tcolor;
		$this->top = $top;
		$this->url = "";
		$this->stretch = $stretch;
		$this->width = $width;
		$this->reseth = $reseth;
		return 0;
	}
	/**
	* Get the cell height
	* @todo add param
	* @return float
	*/
	function getHeight(&$renderer) {
		return $this->height;
	}
	/**
	* Sets the current cells URL
	* @param string $url The URL address to save
	*/
	function setUrl($url) {
		$this->url = $url;
		return 0;
	}
	/**
	* Get the cell width
	* @todo add param
	* @return  float
	*/
	function getWidth(&$renderer) {
		return $this->width;
	}
	/**
	* Get the class type
	* @return string Cell
	*/
	function get_type() {
		return "Cell";
	}
}

/**
 * TextBox element class
*
* @package webtrees
* @subpackage Reports
* @todo add info
*/
class TextBox extends Element {
	/**
	* Array of elements in the TextBox
	* @var array
	*/
	public $elements = array();

	/**
	*  Background color in HTML code
	* @var string
	*/
	public $bgcolor;
	/**
	* Whether or not paint the background
	* @var boolean
	*/
	public $fill;

	/**
	* Position the left corner of this box on the page(expressed in points). The default is the current position.
	* @var mix
	*/
	public $left;
	/**
	* Position the top corner of this box on the page(expressed in points). the default is the current position
	* @var mix
	*/
	public $top;
	/**
	* After this box is finished rendering, should the next section of text start immediately after the this box or should it start on a new line under this box. 0 = no new line, 1 = force new line. Default is 0
	* @var boolean
	*/
	public $newline;

	/**
	* @var boolean
	*/
	public $pagecheck;

	/**
	* Whether or not a border should be printed around this box. 0 = no border, 1 = border. Default is 0
	* @var boolean
	*/
	public $border;
	/**
	* Style of rendering
	*
	* <ul>
	* <li>D or empty string: Draw (default).</li>
	* <li>F: Fill.</li>
	* <li>DF or FD: Draw and fill.</li>
	* <li>CNZ: Clipping mode (using the even-odd rule to determine which regions lie inside the clipping path).</li>
	*<li>CEO: Clipping mode (using the nonzero winding number rule to determine which regions lie inside the clipping path).</li>
	* </ul>
	* @var string
	*/
	public $style;

	/**
	* @var array $borderstyle Border style of rectangle. Array with keys among the following:
	* <ul>
	* <li>all: Line style of all borders. Array like for {@link SetLineStyle SetLineStyle}.</li>
	* <li>L, T, R, B or combinations: Line style of left, top, right or bottom border. Array like for {@link SetLineStyle SetLineStyle}.</li>
	* </ul>
	* Not yet in use
	var $borderstyle;
	*/

	/**
	* The starting height of this cell. If the text wraps the height will automatically be adjusted
	* @var float
	*/
	public $height;
	/**
	* Setting the width to 0 will make it the width from the current location to the right margin
	* @var float
	*/
	public $width;
	/**
	* Use cell padding or not
	* @var boolean $padding
	*/
	public $padding;
	/**
	* Resets this box last height after it's done
	*/
	public $reseth;

	/**
	* TextBox - Element - Base
	*
	* @param float $width Text box width
	* @param float $height Text box height
	* @param boolean $border
	* @param string $bgcolor Background color code in HTML
	* @param boolean $newline
	* @param mixed $left
	* @param mixed $top
	* @param boolean $pagecheck
	* @param string $style
	* @param boolean $fill
	* @param boolean $padding
	* @param boolean $reseth
	*/
	function TextBox($width, $height, $border, $bgcolor, $newline, $left, $top, $pagecheck, $style, $fill, $padding, $reseth) {
		$this->border = $border;
		$this->bgcolor = $bgcolor;
		$this->fill= $fill;
		$this->height = $height;
		$this->left = $left;
		$this->newline = $newline;
		$this->pagecheck = $pagecheck;
		$this->style = $style;
		$this->top = $top;
		$this->width = $width;
		$this->padding = $padding;
		$this->reseth = $reseth;
		return 0;
	}

	/**
	* Add an element to the TextBox
	* @param object|string &$element
	*/
	function addElement($element) {
		$this->elements[] = $element;
		return 0;
	}

	/**
	* Get the class type
	* @return string TextBox
	*/
	function get_type() {
		return "TextBox";
	}
}

/**
 * Text element class
*
* @package webtrees
* @subpackage Reports
* @todo add info
*/
class Text extends Element {
	/**
	* Text color in HTML code
	* @var string
	*/
	public $color;
	/**
	* Style name
	* @var string
	*/
	public $styleName;
	/**
	* Remaining width of a cel
	* @var int User unit (points)
	*/
	public $wrapWidthRemaining;
	/**
	* Original width of a cell
	* @var int User unit (points)
	*/
	public $wrapWidthCell;

	/**
	* Create a Text class - Base
	*
	* @param string $style The name of the text style
	* @param string $color HTML color code
	*/
	function Text($style, $color) {
		$this->text = "";
		$this->color = $color;
		$this->wrapWidthRemaining = 0;
		$this->styleName = $style;
		return 0;
	}

	function setWrapWidth($wrapwidth, $cellwidth) {
		$this->wrapWidthCell = $cellwidth;
		if (strpos($this->text, "\n")!==false) {
			$this->wrapWidthRemaining = $cellwidth;
		} else {
			$this->wrapWidthRemaining = $wrapwidth;
		}
		return $this->wrapWidthRemaining;
	}

	function getStyleName() {
		return $this->styleName;
	}

	/**
	* Get the class type
	* @return string Text
	*/
	function get_type() {
		return "Text";
	}
}

/**
 * Footnote element class
*
* @package webtrees
* @subpackage Reports
* @todo add info
*/
class Footnote extends Element {
	/**
	* The name of the style for this element
	* @var string
	*/
	public $styleName = "";
	/**
	* Numbers for the links
	* @var int
	*/
	public $num;
	/**
	* The text that will be printed with the number
	* @var string
	*/
	public $numText = "";
	/**
	* Remaining width of a cell
	* @var float User unit (points)
	*/
	public $wrapWidthRemaining;
	/**
	* Original width of a cell
	* @var float User unit (points)
	*/
	public $wrapWidthCell;
	public $addlink;

	function Footnote($style="") {
		$this->text = "";
		if (!empty($style)) {
			$this->styleName = $style;
		} else {
			$this->styleName="footnote";
		}
		return 0;
	}

	function rerender($renderer) {
		return false;
	}

	function addText($t) {
		global $embed_fonts, $SpecialOrds;

		foreach ($SpecialOrds as $ord) {
			if (strpos($t, chr($ord))!==false) {
				$embed_fonts = true;
			}
		}
		$t = trim($t, "\r\n\t");
		$t = str_replace(array("<br>", "&nbsp;"), array("\n", " "), $t);
		if (!WT_RNEW) {
			$t = strip_tags($t);
			$t = htmlspecialchars_decode($t);
		}
		$this->text .= $t;
		return 0;
	}

	function setWrapWidth($wrapwidth, $cellwidth) {
		$this->wrapWidthCell = $cellwidth;
		if (strpos($this->numText, "\n")!==false) {
			$this->wrapWidthRemaining = $cellwidth;
		} else {
			$this->wrapWidthRemaining = $wrapwidth;
		}
		return $this->wrapWidthRemaining;
	}

	function setNum($n) {
		$this->num = $n;
		$this->numText = "$n ";
		return 0;
	}

	function setAddlink($a) {
		$this->addlink = $a;
		return 0;
	}

	/**
	* Get the class type
	* @return string Footnote
	*/
	function get_type() {
		return "Footnote";
	}
}

/**
 * PageHeader element class
*
* @package webtrees
* @subpackage Reports
* @todo add info
*/
class PageHeader extends Element {
	public $elements = array();

	function TextBox() {
		$this->elements = array();
		return 0;
	}

	function PageHeader() {
		$this->elements = array();
		return 0;
	}

	/**
	* Add element - PageHeader
	* @param $element
	*/
	function addElement($element) {
		$this->elements[] = $element;
		return 0;
	}

	/**
	* Get the class type
	* @return string PageHeader
	*/
	function get_type() {
		return "PageHeader";
	}
}

/**
 * Image element class
*
* @package webtrees
* @subpackage Reports
* @todo add info
*/
class Image extends Element {
	/**
	* Filename of the image
	* @var string
	*/
	public $file;
	/**
	* Height of the image
	* @var float
	*/
	public $height;
	/**
	* Width of the image
	* @var float
	*/
	public $width;
	/**
	* X-position (left) of the image
	* @var float
	*/
	public $x;
	/**
	* Y-position (top) of the image
	* @var float
	*/
	public $y;
	/**
	* Placement fo the image. L: left, C:center, R:right
	* @var string
	*/
	public $align = "";
	/**
	* T:same line, N:next line
	* @var string
	*/
	public $line = "";

	/**
	* Image class function - Base
	*
	* @param string $file Filename of the image
	* @param float $x X-position (left) of the image
	* @param float $y Y-position (top) of the image
	* @param float $w Width of the image
	* @param float $h Height of the image
	* @param string $align Placement of the image. L: left, C:center, R:right
	* @param string $ln T:same line, N:next line
	*/
	function Image($file, $x, $y, $w, $h, $align, $ln) {
		$this->file = $file;
		$this->width = $w;
		$this->height = $h;
		$this->x = $x;
		$this->y = $y;
		$this->align = $align;
		$this->line = $ln;
		return 0;
	}

	function getHeight(&$renderer) {
		return $this->height;
	}

	function getWidth(&$renderer) {
		return $this->width;
	}

	/**
	* Get the class type
	* @return string Image
	*/
	function get_type() {
		return "Image";
	}
}

/**
 * Line element class
*
* @package webtrees
* @subpackage Reports
* @todo add info
*/
class Line extends Element {
	/**
	* Start horizontal position, current position (default)
	* @var mixed
	*/
	public $x1 = ".";
	/**
	* Start vertical position, current position (default)
	* @var mixed
	*/
	public $y1 = ".";
	/**
	* End horizontal position, maximum width (default)
	* @var mixed
	*/
	public $x2 = ".";
	/**
	* End vertical position
	* @var mixed
	*/
	public $y2 = ".";

	/**
	* Create a line class - Base
	* @param mixed $x1
	* @param mixed $y1
	* @param mixed $x2
	* @param mixed $y2
	*/
	function Line($x1, $y1, $x2, $y2) {
		$this->x1 = $x1;
		$this->y1 = $y1;
		$this->x2 = $x2;
		$this->y2 = $y2;
		return 0;
	}

	function getHeight(&$renderer) {
		return abs($this->y2 - $this->y1);
	}

	function getWidth(&$renderer) {
		return abs($this->x2 - $this->x1);
	}

	/**
	* Get the class type
	* @return string Line
	*/
	function get_type() {
		return "Line";
	}
}

/**
 *XML start element handler
 *
 * This function is called whenever a starting element is reached
 * The element handler will be called if found, otherwise it must be HTML
 *
 * @param resource $parser the resource handler for the XML parser
 * @param string $name the name of the XML element parsed
 * @param array $attrs an array of key value pairs for the attributes
 * @see endElement()
 */
function startElement($parser, $name, $attrs) {
	global $elementHandler, $processIfs, $processGedcoms, $processRepeats, $vars;
	global $processFootnote;

	$newattrs = array();
	$match = array();

	foreach ($attrs as $key=>$value) {
		if (preg_match("/^\\$(\w+)$/", $value, $match)) {
			if ((isset($vars[$match[1]]['id']))&&(!isset($vars[$match[1]]['gedcom']))) {
				$value = $vars[$match[1]]['id'];
			}
		}
		$newattrs[$key] = $value;
	}
	$attrs = $newattrs;
	if (($processFootnote)&&($processIfs==0 || $name=="if")&&($processGedcoms==0 || $name=="Gedcom")&&($processRepeats==0 || $name=="Facts" || $name=="RepeatTag")) {
		if (isset($elementHandler[$name]['start'])) {
			if ($elementHandler[$name]['start'] != "") {
				call_user_func($elementHandler[$name]['start'], $attrs);
			}
		} elseif (!isset($elementHandler[$name]['end'])) {
			HTMLSHandler($name, $attrs);
		}
	}
}

/**
 * XML end element handler
 *
 * This function is called whenever an ending element is reached
 * The element handler will be called if found, otherwise it must be HTML
 *
 * @param resource $parser the resource handler for the XML parser
 * @param string $name the name of the XML element parsed
 * @see startElement()
 */
function endElement($parser, $name) {
	global $elementHandler, $processIfs, $processGedcoms, $processRepeats;
	global $processFootnote;

	if (($processFootnote || $name=="Footnote")&&($processIfs==0 || $name=="if")&&($processGedcoms==0 || $name=="Gedcom")&&($processRepeats==0 || $name=="Facts" || $name=="RepeatTag" || $name=="List" || $name=="Relatives")) {
		if (isset($elementHandler[$name]['end'])) {
			if ($elementHandler[$name]['end']!="") {
				call_user_func($elementHandler[$name]['end']);
			}
		} elseif (!isset($elementHandler[$name]['start'])) {
			HTMLEHandler($name);
		}
	}
}

/**
 * XML character data handler
 *
 * This function is called whenever raw character data is reached
 * just print it to the screen
 * @param resource $parser the resource handler for the XML parser
 * @param string $data the name of the XML element parsed
 * @todo check this
 */
function characterData($parser, $data) {
	global $printData, $currentElement, $processGedcoms, $processIfs, $processRepeats, $reportTitle, $wt_report, $reportDescription;

	if ($printData && ($processGedcoms==0) && ($processIfs==0)&&($processRepeats==0)) {
		$currentElement->addText($data);
	} elseif ($reportTitle) {
		$wt_report->addTitle($data);
	} elseif ($reportDescription) {
		$wt_report->addDescription($data);
	}
}

/**
* XML <StyleSHandler /> element handler
*
* @param array $attrs an array of key value pairs for the attributes
* @see WT_Report_Base::$defaultFont
* @see WT_Report_Base::$defaultFontSize
* @see WT_Report_Base::addStyle()
* @todo add info - update wiki
*/
function StyleSHandler($attrs) {
	global $wt_report;

	if (empty($attrs['name'])) {
		die("<strong>REPORT ERROR Style: </strong> The \"name\" of the style is missing or not set in the XML file.");
	}

	// array Style that will be passed on
	$s = array();

	// string Name af the style
	$s['name'] = $attrs['name'];

	// string Name of the DEFAULT font
	$s['font'] = $wt_report->defaultFont;
	if (!empty($attrs['font'])) $s['font'] = $attrs['font'];

	// int The size of the font in points
	$s['size'] = $wt_report->defaultFontSize;
	if (!empty($attrs['size'])) $s['size'] = (int)$attrs['size']; // Get it as int to ignore all decimal points or text (if any text then int(0))

	// string B: bold, I: italic, U: underline, D: line trough, The default value is regular.
	$s['style'] = "";
	if (!empty($attrs['style'])) $s['style'] = $attrs['style'];

	$wt_report->addStyle($s);
}

/**
* XML <Doc> start element handler
*
* Sets up the basics of the document proparties
* @param array $attrs an array of key value pairs for the attributes
* @see DocEHandler()
* @see WT_Report_Base::setup()
* @todo add showGeneratedBy, height, width param to wiki and update the defaults
*/
function DocSHandler($attrs) {
	global $parser, $xml_parser, $wt_report;

	$parser = $xml_parser;

	// Custom page width
	if (!empty($attrs['customwidth'])) $wt_report->pagew = (int)$attrs['customwidth']; // Get it as int to ignore all decimal points or text (if any text then int(0))
	// Custom Page height
	if (!empty($attrs['customheight'])) $wt_report->pageh = (int)$attrs['customheight']; // Get it as int to ignore all decimal points or text (if any text then int(0))

	// Left Margin
	if (isset($attrs['leftmargin'])) {
		if ($attrs['leftmargin'] === "0") $wt_report->leftmargin = 0;
		elseif (!empty($attrs['leftmargin'])) {
			$wt_report->leftmargin = (int)$attrs['leftmargin']; // Get it as int to ignore all decimal points or text (if any text then int(0))
		}
	}
	// Right Margin
	if (isset($attrs['rightmargin'])) {
		if ($attrs['rightmargin'] === "0") $wt_report->rightmargin = 0;
		elseif (!empty($attrs['rightmargin'])) {
			$wt_report->rightmargin = (int)$attrs['rightmargin']; // Get it as int to ignore all decimal points or text (if any text then int(0))
		}
	}
	// Top Margin
	if (isset($attrs['topmargin'])) {
		if ($attrs['topmargin'] === "0") $wt_report->topmargin = 0;
		elseif (!empty($attrs['topmargin'])) {
			$wt_report->topmargin = (int)$attrs['topmargin']; // Get it as int to ignore all decimal points or text (if any text then int(0))
		}
	}
	// Bottom Margin
	if (isset($attrs['bottommargin'])) {
		if ($attrs['bottommargin'] === "0") $wt_report->bottommargin = 0;
		elseif (!empty($attrs['bottommargin'])) {
			$wt_report->bottommargin = (int)$attrs['bottommargin']; // Get it as int to ignore all decimal points or text (if any text then int(0))
		}
	}
	// Header Margin
	if (isset($attrs['headermargin'])) {
		if ($attrs['headermargin'] === "0") $wt_report->headermargin = 0;
		elseif (!empty($attrs['headermargin'])) {
			$wt_report->headermargin = (int)$attrs['headermargin']; // Get it as int to ignore all decimal points or text (if any text then int(0))
		}
	}
	// Footer Margin
	if (isset($attrs['footermargin'])) {
		if ($attrs['footermargin'] === "0") $wt_report->footermargin = 0;
		elseif (!empty($attrs['footermargin'])) {
			$wt_report->footermargin = (int)$attrs['footermargin']; // Get it as int to ignore all decimal points or text (if any text then int(0))
		}
	}

	// Page Orientation
	if (!empty($attrs['orientation'])) {
		if ($attrs['orientation'] == "landscape") $wt_report->orientation = "landscape";
		elseif ($attrs['orientation'] == "portrait") {
			$wt_report->orientation = "portrait";
		}
	}
	// Page Size
	if (!empty($attrs['pageSize'])) $wt_report->pageFormat = strtoupper($attrs['pageSize']);

	// Show Generated By...
	if (isset($attrs['showGeneratedBy'])) {
		if ($attrs['showGeneratedBy'] === "0") $wt_report->showGenText = false;
		elseif ($attrs['showGeneratedBy'] === "1") {
			$wt_report->showGenText = true;
		}
	}

	$wt_report->setup();
}

/**
* XML </Doc> end element handler
*
* @see DocSHandler()
*/
function DocEHandler() {
	global $wt_report;
	$wt_report->run();
}

/**
* XML <Header> start element handler
*
* @see WT_Report_Base::setProcessing()
*/
function HeaderSHandler() {
	global $wt_report;

	// Clear the Header before any new elements are added
	$wt_report->clearHeader();
	$wt_report->setProcessing("H");
}

/**
* XML <PageHeader> start element handler
*
* @param array $attrs an array of key value pairs for the attributes
* @see PageHeaderEHandler()
*/
function PageHeaderSHandler($attrs) {
	global $printDataStack, $printData, $wt_reportStack, $wt_report, $ReportRoot;

	array_push($printDataStack, $printData);
	$printData = false;
	array_push($wt_reportStack, $wt_report);
	$wt_report = $ReportRoot->createPageHeader();
}

/**
* XML <PageHeaderEHandler> end element handler
*
* @see PageHeaderSHandler()
*/
function PageHeaderEHandler() {
	global $printData, $printDataStack, $wt_report, $currentElement, $wt_reportStack;

	$printData = array_pop($printDataStack);
	$currentElement = $wt_report;
	$wt_report = array_pop($wt_reportStack);
	$wt_report->addElement($currentElement);
}

/**
* XML <BodySHandler> start element handler
*/
function BodySHandler() {
	global $wt_report;
	$wt_report->setProcessing("B");
}

/**
* XML <FooterSHandler> start element handler
*/
function FooterSHandler() {
	global $wt_report;
	$wt_report->setProcessing("F");
}

/**
* XML <Cell> start element handler
*
* @param array $attrs an array of key value pairs for the attributes
* @see CellEHandler()
* @see Cell
* @todo defaults to wiki
*/
function CellSHandler($attrs) {
	global $printData, $printDataStack, $currentElement, $ReportRoot, $wt_report;

	// string The text alignment of the text in this box.
	$align= "";
	if (!empty($attrs['align'])) {
		$align = $attrs['align'];
		// RTL supported left/right alignment
		if ($align == "rightrtl") {
			if ($wt_report->rtl) {
				$align = "left";
			} else {
				$align = "right";
			}
		} elseif ($align == "leftrtl") {
			if ($wt_report->rtl) {
				$align = "right";
			} else {
				$align = "left";
			}
		}
	}

	// string The color to fill the background of this cell
	$bgcolor = "";
	if (!empty($attrs['bgcolor'])) $bgcolor = $attrs['bgcolor'];

	// int Whether or not the background should be painted
	$fill = 1;
	if (isset($attrs['fill'])) {
		if ($attrs['fill'] === "0") {
			$fill = 0;
		} elseif ($attrs['fill'] === "1") {
			$fill = 1;
		}
	}

	$reseth = true;
	// boolean   if true reset the last cell height (default true)
	if (isset($attrs['reseth'])) {
		if ($attrs['reseth'] === "0") {
			$reseth = false;
		} elseif ($attrs['reseth'] === "1") {
			$reseth = true;
		}
	}

	// mixed Whether or not a border should be printed around this box
	$border = 0;
	if (!empty($attrs['border'])) $border = $attrs['border'];
	// @test Print all borders for testing
	// $border = 1;
	// string Border color in HTML code
	$bocolor = "";
	if (!empty($attrs['bocolor'])) $bocolor = $attrs['bocolor'];

	// int Cell height (expressed in points) The starting height of this cell. If the text wraps the height will automatically be adjusted.
	$height= 0;
	if (!empty($attrs['height'])) $height = (int)$attrs['height'];
	// int Cell width (expressed in points) Setting the width to 0 will make it the width from the current location to the right margin.
	$width = 0;
	if (!empty($attrs['width'])) $width = (int)$attrs['width'];

	// int Stretch carachter mode
	$stretch= 0;
	if (!empty($attrs['stretch'])) $stretch = (int)$attrs['stretch'];

	// mixed Position the left corner of this box on the page. The default is the current position.
	$left = ".";
	if (isset($attrs['left'])) {
		if ($attrs['left'] === ".") {
			$left = ".";
		} elseif (!empty($attrs['left'])) {
			$left = (int)$attrs['left'];
		} elseif ($attrs['left'] === "0") {
			$left = 0;
		}
	}
	// mixed Position the top corner of this box on the page. the default is the current position
	$top = ".";
	if (isset($attrs['top'])) {
		if ($attrs['top'] === ".") {
			$top = ".";
		} elseif (!empty($attrs['top'])) {
			$top = (int)$attrs['top'];
		} elseif ($attrs['top'] === "0") {
			$top = 0;
		}
	}

	// string The name of the Style that should be used to render the text.
	$style = "";
	if (!empty($attrs['style'])) $style = $attrs['style'];

	// string Text color in html code
	$tcolor = "";
	if (!empty($attrs['tcolor'])) $tcolor = $attrs['tcolor'];

	// int Indicates where the current position should go after the call.
	$ln = 0;
	if (isset($attrs['newline'])) {
		if (!empty($attrs['newline'])) {
			$ln = (int)$attrs['newline'];
		} elseif ($attrs['newline'] === "0") {
			$ln = 0;
		}
	}

	if ($align=="left") {
		$align="L";
	} elseif ($align=="right") {
		$align="R";
	} elseif ($align=="center") {
		$align="C";
	} elseif ($align=="justify") {
		$align="J";
	}

	array_push($printDataStack, $printData);
	$printData = true;

	$currentElement = $ReportRoot->createCell($width, $height, $border, $align, $bgcolor, $style, $ln, $top, $left, $fill, $stretch, $bocolor, $tcolor, $reseth);
}

/**
* XML </Cell> end element handler
*
* @see CellSHandler()
* @final
*/
function CellEHandler() {
	global $printData, $printDataStack, $currentElement, $wt_report;

	$printData = array_pop($printDataStack);
	$wt_report->addElement($currentElement);
}

/**
* XML <Now /> element handler
*
* @see Element::addText()
* @final
*/
function NowSHandler() {
	global $currentElement;

	$g = timestamp_to_gedcom_date(WT_CLIENT_TIMESTAMP);
	$currentElement->addText($g->Display());
}

/**
* XML <PageNum /> element handler
*
* @see Element::addText()
* @final
*/
function PageNumSHandler() {
	global $currentElement;
	$currentElement->addText("#PAGENUM#");
}

/**
* XML <TotalPages /> element handler
*
* @see Element::addText()
* @final
*/
function TotalPagesSHandler() {
	global $currentElement;
	$currentElement->addText("{{:ptp:}}");
}

/**
* @see GedcomEHandler()
* @todo add info
* @param array $attrs an array of key value pairs for the attributes
*/
function GedcomSHandler($attrs) {
	global $vars, $gedrec, $gedrecStack, $processGedcoms, $fact, $desc, $ged_level;

	if ($processGedcoms>0) {
		$processGedcoms++;
		return;
	}

	$id = "";
	$match = array();
	if (preg_match("/0 @(.+)@/", $gedrec, $match)) {
		$id = $match[1];
	}
	$tag = $attrs['id'];
	$tag = str_replace("@fact", $fact, $tag);
	$tags = explode(":", $tag);
	$newgedrec = "";
	if (count($tags)<2) {
		$tmp=WT_GedcomRecord::getInstance($attrs['id']);
		$newgedrec=$tmp ? $tmp->getGedcom() : '';
	}
	if (empty($newgedrec)) {
		$tgedrec = $gedrec;
		$newgedrec = "";
		foreach ($tags as $tag) {
			if (preg_match("/\\$(.+)/", $tag, $match)) {
				if (isset($vars[$match[1]]['gedcom'])) {
					$newgedrec = $vars[$match[1]]['gedcom'];
				} else {
					$tmp=WT_GedcomRecord::getInstance($match[1]);
					$newgedrec=$tmp ? $tmp->getGedcom() : '';
				}
			} else {
				if (preg_match("/@(.+)/", $tag, $match)) {
					$gmatch = array();
					if (preg_match("/\d $match[1] @([^@]+)@/", $tgedrec, $gmatch)) {
						$tmp=WT_GedcomRecord::getInstance($gmatch[1]);
						$newgedrec=$tmp ? $tmp->getGedcom() : '';
						$tgedrec = $newgedrec;
					} else {
						$newgedrec = "";
						break;
					}
				} else {
					$temp = explode(" ", trim($tgedrec));
					$level = $temp[0] + 1;
					$newgedrec = get_sub_record($level, "$level $tag", $tgedrec);
					$tgedrec = $newgedrec;
				}
			}
		}
	}
	if (!empty($newgedrec)) {
		array_push($gedrecStack, array($gedrec, $fact, $desc));
		$gedrec = $newgedrec;
		if (preg_match("/(\d+) (_?[A-Z0-9]+) (.*)/", $gedrec, $match)) {
			$ged_level = $match[1];
			$fact = $match[2];
			$desc = trim($match[3]);
		}
	} else {
		$processGedcoms++;
	}
}

/**
* @see GedcomSHandler()
* @todo add info
*/
function GedcomEHandler() {
	global $gedrec, $gedrecStack, $processGedcoms, $fact, $desc;

	if ($processGedcoms>0) {
		$processGedcoms--;
	} else {
		$temp = array_pop($gedrecStack);
		$gedrec = $temp[0];
		$fact = $temp[1];
		$desc = $temp[2];
	}
}

/**
* XML <TextBoxSHandler> start element handler
*
* @param array $attrs an array of key value pairs for the attributes
* @see TextBoxEHandler()
* @todo defaults to wiki
*/
function TextBoxSHandler($attrs) {
	global $printData, $printDataStack, $wt_report, $currentElement, $wt_reportStack, $ReportRoot;

	// string Background color code
	$bgcolor = "";
	if (!empty($attrs['bgcolor'])) $bgcolor = $attrs['bgcolor'];

	// boolean Wether or not fill the background color
	$fill = true;
	if (isset($attrs['fill'])) {
		if ($attrs['fill'] === "0") {
			$fill = false;
		} elseif ($attrs['fill'] === "1") {
			$fill = true;
		}
	}

	// var boolean Whether or not a border should be printed around this box. 0 = no border, 1 = border. Default is 0
	$border = false;
	if (isset($attrs['border'])) {
		if ($attrs['border'] === "1") {
			$border = true;
		} elseif ($attrs['border'] === "0") {
			$border = false;
		}
	}
	// @test Print all borders for testing
	// $border = true;

	/**
	* Border style of rectangle. Array with keys among the following
	* <ul><li>L, T, R, B or combinations: Line style of left, top, right or bottom border.</li></ul>
	* @var string
	*/
	/** not yet in use
	$borderstyle = "";
	if (!empty($attrs['borderstyle'])) $borderstyle = $attrs['borderstyle'];
	*/

	// int The starting height of this cell. If the text wraps the height will automatically be adjusted
	$height = 0;
	if (!empty($attrs['height'])) $height = (int)$attrs['height'];
	// int Setting the width to 0 will make it the width from the current location to the margin
	$width = 0;
	if (!empty($attrs['width'])) $width = (int)$attrs['width'];

	// mixed Position the left corner of this box on the page. The default is the current position.
	$left = ".";
	if (isset($attrs['left'])) {
		if ($attrs['left'] === ".") {
			$left = ".";
		} elseif (!empty($attrs['left'])) {
			$left = (int)$attrs['left'];
		} elseif ($attrs['left'] === "0") {
			$left = 0;
		}
	}
	// mixed Position the top corner of this box on the page. the default is the current position
	$top = ".";
	if (isset($attrs['top'])) {
		if ($attrs['top'] === ".") {
			$top = ".";
		} elseif (!empty($attrs['top'])) {
			$top = (int)$attrs['top'];
		} elseif ($attrs['top'] === "0") {
			$top = 0;
		}
	}
	// boolean After this box is finished rendering, should the next section of text start immediately after the this box or should it start on a new line under this box. 0 = no new line, 1 = force new line. Default is 0
	$newline = false;
	if (isset($attrs['newline'])) {
		if ($attrs['newline'] === "1") {
			$newline = true;
		} elseif ($attrs['newline'] === "0") {
			$newline = false;
		}
	}
	// boolean
	$pagecheck = true;
	if (isset($attrs['pagecheck'])) {
		if ($attrs['pagecheck'] === "0") {
			$pagecheck = false;
		} elseif ($attrs['pagecheck'] === "1") {
			$pagecheck = true;
		}
	}
	// boolean Cell padding
	$padding = true;
	if (isset($attrs['padding'])) {
		if ($attrs['padding'] === "0") {
			$padding = false;
		} elseif ($attrs['padding'] === "1") {
			$padding = true;
		}
	}
	// boolean Reset this box Height
	$reseth = false;
	if (isset($attrs['reseth'])) {
		if ($attrs['reseth'] === "1") {
			$reseth = true;
		} elseif ($attrs['reseth'] === "0") {
			$reseth = false;
		}
	}

	// string Style of rendering
	$style = "";
	// fill and border is enought for now for user input
	//if (!empty($attrs['style'])) $style = $attrs['style'];

	array_push($printDataStack, $printData);
	$printData = false;

	array_push($wt_reportStack, $wt_report);
	$wt_report = $ReportRoot->createTextBox($width, $height, $border, $bgcolor, $newline, $left, $top, $pagecheck, $style, $fill, $padding, $reseth);
}

/**
* XML <TextBoxEHandler> end element handler
*
* @see TextBoxSHandler()
*/
function TextBoxEHandler() {
	global $printData, $printDataStack, $wt_report, $currentElement, $wt_reportStack;

	$printData = array_pop($printDataStack);
	$currentElement = $wt_report;
	$wt_report = array_pop($wt_reportStack);
	$wt_report->addElement($currentElement);
}

/**
* @see TextEHandler()
* @todo add info to wiki about "color"
* @todo more variables in Text class, check it out
* @param array $attrs an array of key value pairs for the attributes
*/
function TextSHandler($attrs) {
	global $printData, $printDataStack, $currentElement, $ReportRoot;

	array_push($printDataStack, $printData);
	$printData = true;

	// string The name of the Style that should be used to render the text.
	$style = "";
	if (!empty($attrs['style'])) $style = $attrs['style'];

	// string  The color of the text - Keep the black color as default
	$color = "";
	if (!empty($attrs['color'])) $color = $attrs['color'];

	$currentElement = $ReportRoot->createText($style, $color);
}

/**
* @see TextSHandler()
*/
function TextEHandler() {
	global $printData, $printDataStack, $wt_report, $currentElement;

	$printData = array_pop($printDataStack);
	$wt_report->addElement($currentElement);
}

/**
* XML <GetPersonName> start element handler
* Get the name
* 1. id is empty - current GEDCOM record
* 2. id is set with a record id
*
* @param array $attrs an array of key value pairs for the attributes
*/
function GetPersonNameSHandler($attrs) {
	// @deprecated
	global $currentElement, $vars, $gedrec;

	$id = "";
	$match = array();
	if (empty($attrs['id'])) {
		if (preg_match("/0 @(.+)@/", $gedrec, $match)) {
			$id = $match[1];
		}
	} else {
		if (preg_match("/\\$(.+)/", $attrs['id'], $match)) {
			if (isset($vars[$match[1]]['id'])) {
				$id = $vars[$match[1]]['id'];
			}
		} else {
			if (preg_match("/@(.+)/", $attrs['id'], $match)) {
				$gmatch = array();
				if (preg_match("/\d $match[1] @([^@]+)@/", $gedrec, $gmatch)) {
					$id = $gmatch[1];
				}
			} else {
				$id = $attrs['id'];
			}
		}
	}
	if (!empty($id)) {
		$record = WT_GedcomRecord::getInstance($id);
		if (is_null($record)) {
			return;
		}
		if (!$record->canShowName()) {
			$currentElement->addText(WT_I18N::translate('Private'));
		} else {
			$name = $record->getFullName();
/*
echo "<br>";
for ($ii=0; $ii<=strlen($name); $ii++)
echo substr($name, $ii, 1)." ";
*/
			$name = preg_replace(array('/<span class="starredname">/','/<\/span><\/span>/','/<\/span>/'), array('«','','»'), $name);
			if (!WT_RNEW) {
				$name = strip_tags($name);
			}
			if (!empty($attrs['truncate'])) {
				//short-circuit with the faster strlen
				if (strlen($name)>$attrs['truncate'] && utf8_strlen($name)>$attrs['truncate']) {
					$name = preg_replace("/\(.*\) ?/", "", $name); //removes () and text inbetween - what about ", [ and { etc?
					$words = preg_split('/[, -]+/', $name); // names separated with space, comma or hyphen - any others?
					$name = $words[count($words)-1];
					for ($i=count($words)-2; $i>=0; $i--) {
						$len = utf8_strlen($name);
						for ($j=count($words)-3; $j>=0; $j--) {
							$len += utf8_strlen($words[$j]);
						}
						if ($len>$attrs['truncate']) {
							$first_letter = utf8_substr($words[$i], 0, 1);
							//do not show " of nick-names
							if ($first_letter != "\"") $name = utf8_substr($words[$i], 0, 1).". ".$name;
						} else {
							$name = $words[$i]." ".$name;
						}
					}
				}
			} else {
				$addname = $record->getAddName();
/*
echo "<br>".$addname."<br>";
for ($ii=0; $ii<=strlen($addname); $ii++)
echo substr($addname, $ii, 1)." ";
*/
				$addname = preg_replace(array('/<span class="starredname">/','/<\/span><\/span>/','/<\/span>/'), array('«','','»'), $addname);						
				if (!WT_RNEW) {
					$addname = strip_tags($addname); //@@ unknown printed in other alignment with ... on wrong side
				}
				if (!empty($addname)) {
					$name .= " ".$addname;
				}
			}
			$currentElement->addText(trim($name));
		}
	}
}

/**
* XML <GedcomValue> start element handler
*
* @param array $attrs an array of key value pairs for the attributes
*/
function GedcomValueSHandler($attrs) {
	// @deprecated
	global $currentElement, $gedrec, $fact, $desc;

	$id = "";
	$match = array();
	if (preg_match("/0 @(.+)@/", $gedrec, $match)) {
		$id = $match[1];
	}

	if (isset($attrs['newline']) && $attrs['newline']=="1") {
		$useBreak = "1";
	} else {
		$useBreak = "0";
	}

	$tag = $attrs['tag'];
	if (!empty($tag)) {
		if ($tag=="@desc") {
			$value = $desc;
			$value = trim($value);
			$currentElement->addText($value);
		}
		if ($tag=="@id") {
			$currentElement->addText($id);
		} else {
			$tag = str_replace("@fact", $fact, $tag);
			if (empty($attrs['level'])) {
				$temp = explode(" ", trim($gedrec));
				$level = $temp[0];
				if ($level==0) {
					$level++;
				}
			} else {
				$level = $attrs['level'];
			}
			$truncate = "";
			if (isset($attrs['truncate'])) {
				$truncate=$attrs['truncate'];
			}
			$tags = preg_split('/[: ]/', $tag);
			$value = get_gedcom_value($tag, $level, $gedrec, $truncate);
			switch (end($tags)) {
			case 'DATE':
				$tmp=new WT_Date($value);
				$value=$tmp->Display();
				break;
			case 'PLAC':
				$tmp=new WT_Place($value, WT_GED_ID);
				$value=$tmp->getShortName();
				break;
			}
			if ($useBreak == "1") {
				// Insert <br> when multiple dates exist.
				// This works around a TCPDF bug that incorrectly wraps RTL dates on LTR pages
				$value = str_replace('(', '<br>(', $value);
				$value = str_replace('<span dir="ltr"><br>', '<br><span dir="ltr">', $value);
				$value = str_replace('<span dir="rtl"><br>', '<br><span dir="rtl">', $value);
				if (substr($value, 0, 6) == '<br>') {
					$value = substr($value, 6);
				}
			}
			$currentElement->addText($value);
		}
	}
}

/**
* XML <RepeatTag> start element handler
*
* @see RepeatTagEHandler()
* @param array $attrs an array of key value pairs for the attributes
*/
function RepeatTagSHandler($attrs) {
	// @deprecated
	global $repeats, $repeatsStack, $gedrec, $repeatBytes, $parser, $processRepeats, $fact, $desc;

	$processRepeats++;
	if ($processRepeats>1) return;

	array_push($repeatsStack, array($repeats, $repeatBytes));
	$repeats = array();
	$repeatBytes = xml_get_current_line_number($parser);

	$id = "";
	$match = array();
	if (preg_match("/0 @(.+)@/", $gedrec, $match)) {
		$id = $match[1];
	}

	$tag = "";
	if (isset($attrs['tag'])) {
		$tag = $attrs['tag'];
	}
	if (!empty($tag)) {
		if ($tag=="@desc") {
			$value = $desc;
			$value = trim($value);
			$currentElement->addText($value);
		} else {
			$tag = str_replace("@fact", $fact, $tag);
			$tags = explode(":", $tag);
			$temp = explode(" ", trim($gedrec));
			$level = $temp[0];
			if ($level == 0) {
				$level++;
			}
			$subrec = $gedrec;
			$t = $tag;
			$count = count($tags);
			$i = 0;
			while ($i < $count) {
				$t = $tags[$i];
				if (!empty($t)) {
					if ($i < ($count-1)) {
						$subrec = get_sub_record($level, "$level $t", $subrec);
						if (empty($subrec)) {
							$level--;
							$subrec = get_sub_record($level, "@ $t", $gedrec);
							if (empty($subrec)) {
								return;
							}
						}
					}
					$level++;
				}
				$i++;
			}
			$level--;
			$count = preg_match_all("/$level $t(.*)/", $subrec, $match, PREG_SET_ORDER);
			$i = 0;
			while ($i < $count) {
				$repeats[] = get_sub_record($level, "$level $t", $subrec, $i + 1);;
				$i++;
			}
		}
	}
}

/**
* XML </ RepeatTag> end element handler
*
* @see RepeatTagSHandler()
*/
function RepeatTagEHandler() {
	global $processRepeats, $repeats, $repeatsStack, $repeatBytes;

	$processRepeats--;
	if ($processRepeats>0) {
		return;
	}

	// Check if there is anything to repeat
	if (count($repeats)>0) {
		// No need to load them if not used...
		global $parser, $parserStack, $report, $gedrec;
		// @deprecated
		//$line = xml_get_current_line_number($parser)-1;
		$lineoffset = 0;
		foreach ($repeatsStack as $rep) {
			$lineoffset += $rep[1];
		}
		//-- read the xml from the file
		$lines = file($report);
		while (strpos($lines[$lineoffset + $repeatBytes], "<RepeatTag")===false) {
			$lineoffset--;
		}
		$lineoffset++;
		$reportxml = "<tempdoc>\n";
		$line_nr = $lineoffset + $repeatBytes;
		// RepeatTag Level counter
		$count = 1;
		while (0 < $count) {
			if (strstr($lines[$line_nr], "<RepeatTag")!==false) {
				$count++;
			} elseif (strstr($lines[$line_nr], "</RepeatTag")!==false) {
				$count--;
			}
			if (0 < $count) {
				$reportxml .= $lines[$line_nr];
			}
			$line_nr++;
		}
		// No need to drag this
		unset($lines);
		$reportxml .= "</tempdoc>\n";
		// Save original values
		array_push($parserStack, $parser);
		$oldgedrec = $gedrec;
		foreach ($repeats as $gedrec) {
			//-- start the sax parser
			$repeat_parser = xml_parser_create();
			$parser = $repeat_parser;
			//-- make sure everything is case sensitive
			xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false);
			//-- set the main element handler functions
			xml_set_element_handler($repeat_parser, "startElement", "endElement");
			//-- set the character data handler
			xml_set_character_data_handler($repeat_parser, "characterData");
			if (!xml_parse($repeat_parser, $reportxml, true)) {
				printf($reportxml."\nRepeatTagEHandler XML error: %s at line %d", xml_error_string(xml_get_error_code($repeat_parser)), xml_get_current_line_number($repeat_parser));
				print_r($repeatsStack);
				debug_print_backtrace();
				exit;
			}
			xml_parser_free($repeat_parser);
		}
		// Restore original values
		$gedrec = $oldgedrec;
		$parser = array_pop($parserStack);
	}
	$temp = array_pop($repeatsStack);
	$repeats = $temp[0];
	$repeatBytes = $temp[1];
}

/**
* Variable lookup
*
* Retrieve predefined variables :
* @ desc GEDCOM fact description, example:
*        1 EVEN This is a description
* @ fact GEDCOM fact tag, such as BIRT, DEAT etc.
* $ WT_I18N::translate('....')
* $ language_settings[]
*
*
* Or retrieve variables preset with <SetVar> element
*
* If the variable is a date and 'date="1"' attribute is set then the date will be reformated
* from Sep to September
*
* @param array $attrs an array of key value pairs for the attributes
* @see SetVarSHandler()
*/
function varSHandler($attrs) {
	// @deprecated
	global $currentElement, $type, $parser;
	// Retrievable variables
	global $desc, $fact, $language_settings, $vars;

	if (empty($attrs['var'])) {
		die("<strong>REPORT ERROR var: </strong> The attribute \"var=\" is missing or not set in the XML file on line: ".xml_get_current_line_number($parser));
	}

	$var = $attrs['var'];
	// SetVar element preset variables
	if (!empty($vars[$var]['id'])) {
		$var = $vars[$var]['id'];
	} else {
		$tfact = $fact;
		if (($fact == "EVEN" or $fact == "FACT") and $type != " ") {
			// Use :
			// n TYPE This text if string
			$tfact = $type;
		}
		$var = str_replace(array("@fact", "@desc"), array(WT_Gedcom_Tag::getLabel($tfact), $desc), $var);
		if (substr($var, 0, 18) == 'WT_I18N::translate' || substr($var, 0, 15) == 'WT_I18N::number') {
			eval("\$var=$var;");
		}
	}
	// Check if variable is set as a date and reformat the date
	if (isset($attrs['date'])) {
		if ($attrs['date'] === "1") {
			$g = new WT_Date($var);
			$var = $g->Display();
		}
	}
	$currentElement->addText($var);
}

/**
* @todo add info
* @param array $attrs an array of key value pairs for the attributes
* @see FactsEHandler()
*/
function FactsSHandler($attrs) {
	// @deprecated
	global $repeats, $repeatsStack, $gedrec, $parser, $repeatBytes, $processRepeats, $vars;

	$processRepeats++;
	if ($processRepeats>1) return;

	// @todo Why is this here when its not used?

	$families = 1;
	if (isset($attrs['families'])) {
		$families = $attrs['families'];
	}

	array_push($repeatsStack, array($repeats, $repeatBytes));
	$repeats = array();
	$repeatBytes = xml_get_current_line_number($parser);

	$id = "";
	$match = array();
	if (preg_match("/0 @(.+)@/", $gedrec, $match)) {
		$id = $match[1];
	}
	$tag = "";
	if (isset($attrs['ignore'])) {
		$tag .= $attrs['ignore'];
	}
	if (preg_match("/\\$(.+)/", $tag, $match)) {
		$tag = $vars[$match[1]]['id'];
	}

	$record = WT_GedcomRecord::getInstance($id);
	if (empty($attrs['diff']) && !empty($id)) {
		$facts = $record->getFacts();
		sort_facts($facts);
		$repeats = array();
		$nonfacts=explode(',', $tag);
		foreach ($facts as $event) {
			if (!in_array($event->getTag(), $nonfacts)) {
				$repeats[]=$event->getGedcom();
			}
		}
	} else {
		foreach ($record->getFacts() as $fact) {
			if ($fact->isNew() && $fact->getTag()<>'CHAN') {
				$repeats[]=$fact->getGedcom();
			}
		}
	}
}

/**
* XML </ Facts> end element handler
*
* @see FactsSHandler()
*/
function FactsEHandler() {
	global $repeats, $repeatsStack, $repeatBytes, $parser, $parserStack, $report, $gedrec, $fact, $desc, $type, $processRepeats;

	$processRepeats--;
	if ($processRepeats>0) {
		return;
	}

	// Check if there is anything to repeat
	if (count($repeats) > 0) {

		$line = xml_get_current_line_number($parser)-1;
		$lineoffset = 0;
		foreach ($repeatsStack as $rep) {
			$lineoffset += $rep[1];
		}

		//-- read the xml from the file
		$lines = file($report);
		while (($lineoffset + $repeatBytes > 0) and (strpos($lines[$lineoffset + $repeatBytes], "<Facts ")) === false) {
			$lineoffset--;
		}
		$lineoffset++;
		$reportxml = "<tempdoc>\n";
		$i = $line + $lineoffset;
		$line_nr = $repeatBytes + $lineoffset;
		while ($line_nr < $i) {
			$reportxml .= $lines[$line_nr];
			$line_nr++;
		}
		// No need to drag this
		unset($lines);
		$reportxml .= "</tempdoc>\n";
		// Save original values
		array_push($parserStack, $parser);
		$oldgedrec = $gedrec;
		$count = count($repeats);
		$i = 0;
		$match = array();
		while ($i < $count) {
			$gedrec = $repeats[$i];
			$fact = "";
			$desc = "";
			if (preg_match("/1 (\w+)(.*)/", $gedrec, $match)) {
				$fact = $match[1];
				if ($fact=="EVEN" or $fact=="FACT") {
					$tmatch = array();
					if (preg_match("/2 TYPE (.+)/", $gedrec, $tmatch)) {
						$type = trim($tmatch[1]);
					} else {
						$type = " ";
					}
				}
				$desc = trim($match[2]);
				$desc .= get_cont(2, $gedrec);
			}
			//-- start the sax parser
			$repeat_parser = xml_parser_create();
			$parser = $repeat_parser;
			//-- make sure everything is case sensitive
			xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false);
			//-- set the main element handler functions
			xml_set_element_handler($repeat_parser, "startElement", "endElement");
			//-- set the character data handler
			xml_set_character_data_handler($repeat_parser, "characterData");
			if (!xml_parse($repeat_parser, $reportxml, true)) {
				die(sprintf($reportxml."\nFactsEHandler XML error: %s at line %d", xml_error_string(xml_get_error_code($repeat_parser)), xml_get_current_line_number($repeat_parser)));
			}
			xml_parser_free($repeat_parser);
			$i++;
		}
		// Restore original values
		$parser = array_pop($parserStack);
		$gedrec = $oldgedrec;
	}
	$temp = array_pop($repeatsStack);
	$repeats = $temp[0];
	$repeatBytes = $temp[1];
}

/**
* Setting upp or changing variables in the XML
* The XML variable name and value is stored in the global variable $vars
* @param array $attrs an array of key value pairs for the attributes
*/
function SetVarSHandler($attrs) {
	global $vars, $gedrec, $fact, $desc, $type, $generation;

	if (empty($attrs['name'])) {
		die("<strong>REPORT ERROR var: </strong> The attribute \"name=\" is missing or not set in the XML file");
	}

	$name = $attrs['name'];
	$value = $attrs['value'];
	$match = array();
	// Current GEDCOM record strings
	if ($value == "@ID") {
		if (preg_match("/0 @(.+)@/", $gedrec, $match)) {
			$value = $match[1];
		}
	} elseif ($value == "@fact") {
		$value = $fact;
	} elseif ($value == "@desc") {
		$value = $desc;
	} elseif ($value == "@generation") {
		$value = $generation;
	} elseif (preg_match("/@(\w+)/", $value, $match)) {
		$gmatch = array();
		if (preg_match("/\d $match[1] (.+)/", $gedrec, $gmatch)) {
			$value = str_replace("@", "", trim($gmatch[1]));
		}
	}
	if (preg_match("/\\$(\w+)/", $name, $match)) {
		$name = $vars["'".$match[1]."'"]['id'];
	}
	$count = preg_match_all("/\\$(\w+)/", $value, $match, PREG_SET_ORDER);
	$i=0;
	while ($i<$count) {
		$t = $vars[$match[$i][1]]['id'];
		$value = preg_replace("/\\$".$match[$i][1]."/", $t, $value, 1);
		$i++;
	}
	if (substr($value, 0, 18) == 'WT_I18N::translate' || substr($value, 0, 15) == 'WT_I18N::number') {
		eval("\$value = $value;");
	}
	// Arithmetic functions
	if (preg_match("/(\d+)\s*([\-\+\*\/])\s*(\d+)/", $value, $match)) {
		switch($match[2]) {
			case "+":
				$t = $match[1] + $match[3];
				$value = preg_replace("/".$match[1]."\s*([\-\+\*\/])\s*".$match[3]."/", $t, $value);
				break;
			case "-":
				$t = $match[1] - $match[3];
				$value = preg_replace("/".$match[1]."\s*([\-\+\*\/])\s*".$match[3]."/", $t, $value);
				break;
			case "*":
				$t = $match[1] * $match[3];
				$value = preg_replace("/".$match[1]."\s*([\-\+\*\/])\s*".$match[3]."/", $t, $value);
				break;
			case "/":
				$t = $match[1] / $match[3];
				$value = preg_replace("/".$match[1]."\s*([\-\+\*\/])\s*".$match[3]."/", $t, $value);
				break;
		}
	}
	if (strpos($value, "@")!==false) {
		$value="";
	}
	$vars[$name]['id']=$value;
}

/**
* XML <if > start element
* @see ifEHandler()
* @param array $attrs an array of key value pairs for the attributes
*/
function ifSHandler($attrs) {
	global $vars, $gedrec, $processIfs, $fact, $desc, $generation;

	if ($processIfs>0) {
		$processIfs++;
		return;
	}

	$condition = $attrs['condition'];
	$condition = preg_replace("/\\$(\w+)/", "\$vars[\"$1\"][\"id\"]", $condition);
	$condition = str_replace(array(" LT ", " GT "), array("<", ">"), $condition);
	// Replace the first accurance only once of @fact:DATE or in any other combinations to the current fact, such as BIRT
	$condition = str_replace("@fact", $fact, $condition);
	$match = array();
	$count = preg_match_all("/@([\w:\.]+)/", $condition, $match, PREG_SET_ORDER);
	$i = 0;
	while ( $i < $count ) {
		$id = $match[$i][1];
		$value="\"\"";
		if ($id=="ID") {
			if (preg_match("/0 @(.+)@/", $gedrec, $match)) {
				$value = "'".$match[1]."'";
			}
		} elseif ($id=="fact") {
			$value = "\"$fact\"";
		} elseif ($id=="desc") {
			$value = "\"".addslashes($desc)."\"";
		} elseif ($id=="generation") {
			$value = "\"$generation\"";
		} else {

			$temp = explode(" ", trim($gedrec));
			$level = $temp[0];
			if ($level==0) {
				$level++;
			}
			$value = get_gedcom_value($id, $level, $gedrec);
			if (empty($value)) {
				$level++;
				$value = get_gedcom_value($id, $level, $gedrec);
			}
			$value = "\"".addslashes($value)."\"";
		}
		$condition = str_replace("@$id", $value, $condition);
		$i++;
	}
	$condition = "if ($condition) return true; else return false;";
	$ret = @eval($condition);
	if (!$ret) {
		$processIfs++;
	}
}

/**
* XML <if /> end element
* @see ifSHandler()
*/
function ifEHandler() {
	global $processIfs;
	if ($processIfs>0) $processIfs--;
}

/**
* XML <Footnote > start element
* Collect the Footnote links
* GEDCOM Records that are protected by Privacy setting will be ignore
*
* @param array $attrs an array of key value pairs for the attributes
* @see FootnoteEHandler()
*/
function FootnoteSHandler($attrs) {
	global $printData, $printDataStack, $currentElement, $footnoteElement, $processFootnote, $gedrec, $ReportRoot;

	$match = array();
	$id="";
	$tag="";
	if (preg_match("/[0-9] (.+) @(.+)@/", $gedrec, $match)) {
		$tag = $match[1];
		$id = $match[2];
	}
	$record=WT_GedcomRecord::GetInstance($id);
	if ($record && $record->canShow()) {
		array_push($printDataStack, $printData);
		$printData = true;
		$style = "";
		if (!empty($attrs['style'])) {
			$style=$attrs['style'];
		}
		$footnoteElement = $currentElement;
		$currentElement = $ReportRoot->createFootnote($style);
	} else {
		$printData = false;
		$processFootnote = false;
	}
}

/**
* XML <Footnote /> end element
* Print the collected Footnote data
*
* @see FootnoteSHandler()
*/
function FootnoteEHandler() {
	// @deprecated
	global $printData, $printDataStack, $currentElement, $footnoteElement, $processFootnote, $wt_report;

	if ($processFootnote) {
		$printData = array_pop($printDataStack);
		$temp = trim($currentElement->getValue());
		if (strlen($temp)>3) {
			$wt_report->addElement($currentElement);
		}
		$currentElement = $footnoteElement;
	} else {
		$processFootnote = true;
	}
}

/**
* XML <FootnoteTexts /> element
*
* @param array $attrs an array of key value pairs for the attributes
*/
function FootnoteTextsSHandler() {
	global $wt_report;

	$temp = "footnotetexts";
	$wt_report->addElement($temp);
}

/**
* XML <AgeAtDeath /> element handler
*
* @see Element::addText()
* @final
*/
function AgeAtDeathSHandler() {
	// TODO: This duplicates functionality in format_fact_date()
	global $currentElement, $gedrec, $fact, $desc;

	$id = "";
	$match = array();
	if (preg_match("/0 @(.+)@/", $gedrec, $match)) {
		$person=WT_Individual::getInstance($match[1]);
		// Recorded age
		if (preg_match('/\n2 AGE (.+)/', $factrec, $match)) {
			$fact_age = $match[1];
		} else {
			$fact_age = '';
		}
		if (preg_match('/\n2 HUSB\n3 AGE (.+)/', $factrec, $match)) {
			$husb_age = $match[1];
		} else {
			$husb_age = '';
		}
		if (preg_match('/\n2 WIFE\n3 AGE (.+)/', $factrec, $match)) {
			$wife_age = $match[1];
		} else {
			$wife_age = '';
		}

		// Calculated age
		$birth_date=$person->getBirthDate();
		// Can't use getDeathDate(), as this also gives BURI/CREM events, which
		// wouldn't give the correct "days after death" result for people with
		// no DEAT.
		$death_event=$person->getFirstFact('DEAT');
		if ($death_event) {
			$death_date=$death_event->getDate();
		} else {
			$death_date=new WT_Date('');
		}
		$value = '';
		if (WT_Date::Compare($birth_date, $death_date)<=0 || !$person->isDead()) {
			$age=WT_Date::GetAgeGedcom($birth_date, $death_date);
			// Only show calculated age if it differs from recorded age
			if ($age!='' && $age!="0d") {
				if (
					$fact_age!='' && $fact_age!=$age ||
					$fact_age=='' && $husb_age=='' && $wife_age=='' ||
					$husb_age!='' && $person->getSex()=='M' && $husb_age!=$age ||
					$wife_age!='' && $person->getSex()=='F' && $wife_age!=$age
				) {
					$value = get_age_at_event($age, false);
					$abbrev = substr($value, 0, strpos($value, ' ')+5);
					if ($value !== $abbrev) {
						$value = $abbrev.'.';
					}
				}
			}
		}
		$currentElement->addText($value);
	}
}

/**
* XML element Forced line break handler - HTML code
*
*/
function brSHandler() {
	global $printData, $currentElement, $processGedcoms;
	if ($printData && ($processGedcoms==0)) $currentElement->addText('<br>');
}

/**
* XML <sp />element Forced space handler
*
* @todo add info to wiki - missing function
*/
function spSHandler() {
	global $printData, $currentElement, $processGedcoms;
	if ($printData && ($processGedcoms==0)) $currentElement->addText(' ');
}

/**
* @todo add info
* @param array $attrs an array of key value pairs for the attributes
*/
function HighlightedImageSHandler($attrs) {
	global $gedrec, $wt_report, $ReportRoot;

	$id = '';
	$match = array();
	if (preg_match("/0 @(.+)@/", $gedrec, $match)) {
		$id = $match[1];
	}

	// mixed Position the top corner of this box on the page. the default is the current position
	$top = '.';
	if (isset($attrs['top'])) {
		if ($attrs['top'] === '0') {
			$top = 0;
		} elseif ($attrs['top'] === '.') {
			$top = '.';
		} elseif (!empty($attrs['top'])) {
			$top = (int)$attrs['top'];
		}
	}

	// mixed Position the left corner of this box on the page. the default is the current position
	$left = '.';
	if (isset($attrs['left'])) {
		if ($attrs['left'] === '0') {
			$left = 0;
		} elseif ($attrs['left'] === '.') {
			$left = '.';
		} elseif (!empty($attrs['left'])) {
			$left = (int)$attrs['left'];
		}
	}

	// string Align the image in left, center, right
	$align = '';
	if (!empty($attrs['align'])) $align = $attrs['align'];

	// string Next Line should be T:next to the image, N:next line
	$ln = '';
	if (!empty($attrs['ln'])) $ln = $attrs['ln'];

	$width = 0;
	$height = 0;
	if (!empty($attrs['width'])) $width = (int)$attrs['width'];
	if (!empty($attrs['height'])) $height = (int)$attrs['height'];

	$person=WT_Individual::getInstance($id);
	$mediaobject = $person->findHighlightedMedia();
	if ($mediaobject) {
		$attributes=$mediaobject->getImageAttributes('thumb');
		if (in_array($attributes['ext'], array('GIF','JPG','PNG','SWF','PSD','BMP','TIFF','TIFF','JPC','JP2','JPX','JB2','SWC','IFF','WBMP','XBM')) && $mediaobject->canShow() && $mediaobject->fileExists('thumb')) {
			if (($width>0) and ($height==0)) {
				$perc = $width / $attributes['adjW'];
				$height= round($attributes['adjH']*$perc);
			} elseif (($height>0) and ($width==0)) {
				$perc = $height / $attributes['adjH'];
				$width= round($attributes['adjW']*$perc);
			} else {
				$width = $attributes['adjW'];
				$height = $attributes['adjH'];
			}
			$image = $ReportRoot->createImageFromObject($mediaobject, $left, $top, $width, $height, $align, $ln);
			$wt_report->addElement($image);
		}
	}
}

/**
* @todo add info
* @param array $attrs an array of key value pairs for the attributes
*/
function ImageSHandler($attrs) {
	global $gedrec, $wt_report, $MEDIA_DIRECTORY, $ReportRoot;

	// mixed Position the top corner of this box on the page. the default is the current position
	$top = '.';
	if (isset($attrs['top'])) {
		if ($attrs['top'] === "0") {
			$top = 0;
		} elseif ($attrs['top'] === '.') {
			$top = '.';
		} elseif (!empty($attrs['top'])) {
			$top = (int)$attrs['top'];
		}
	}

	// mixed Position the left corner of this box on the page. the default is the current position
	$left = '.';
	if (isset($attrs['left'])) {
		if ($attrs['left'] === '0') {
			$left = 0;
		} elseif ($attrs['left'] === '.') {
			$left = '.';
		} elseif (!empty($attrs['left'])) {
			$left = (int)$attrs['left'];
		}
	}

	// string Align the image in left, center, right
	$align = '';
	if (!empty($attrs['align'])) $align = $attrs['align'];

	// string Next Line should be T:next to the image, N:next line
	$ln = 'T';
	if (!empty($attrs['ln'])) $ln = $attrs['ln'];

	$width = 0;
	$height = 0;
	if (!empty($attrs['width'])) $width = (int)$attrs['width'];
	if (!empty($attrs['height'])) $height = (int)$attrs['height'];

	$file = '';
	if (!empty($attrs['file'])) $file = $attrs['file'];
	if ($file=="@FILE") {
		$match = array();
		if (preg_match("/\d OBJE @(.+)@/", $gedrec, $match)) {
			$mediaobject=WT_Media::getInstance($match[1], WT_GED_ID);
			$attributes=$mediaobject->getImageAttributes('thumb');
			if (in_array($attributes['ext'], array('GIF','JPG','PNG','SWF','PSD','BMP','TIFF','TIFF','JPC','JP2','JPX','JB2','SWC','IFF','WBMP','XBM')) && $mediaobject->canShow() && $mediaobject->fileExists('thumb')) {
				if (($width>0) and ($height==0)) {
					$perc = $width / $attributes['adjW'];
					$height= round($attributes['adjH']*$perc);
				} elseif (($height>0) and ($width==0)) {
					$perc = $height / $attributes['adjH'];
					$width= round($attributes['adjW']*$perc);
				} else {
					$width = $attributes['adjW'];
					$height = $attributes['adjH'];
				}
				$image = $ReportRoot->createImageFromObject($mediaobject, $left, $top, $width, $height, $align, $ln);
				$wt_report->addElement($image);
			}
		}
	} else {
		if (file_exists($file) && preg_match("/(jpg|jpeg|png|gif)$/i", $file)) {
			$size = getimagesize($file);
			if (($width>0) and ($height==0)) {
				$perc = $width / $size[0];
				$height= round($size[1]*$perc);
			} elseif (($height>0) and ($width==0)) {
				$perc = $height / $size[1];
				$width= round($size[0]*$perc);
			} else {
				$width = $size[0];
				$height = $size[1];
			}
			$image = $ReportRoot->createImage($file, $left, $top, $width, $height, $align, $ln);
			$wt_report->addElement($image);
		}
	}
}

/**
* XML <Line> element handler
*
* @param array $attrs an array of key value pairs for the attributes
*/
function LineSHandler($attrs) {
	global $wt_report, $ReportRoot;

	// Start horizontal position, current position (default)
	$x1 = ".";
	if (isset($attrs['x1'])) {
		if ($attrs['x1'] === "0") {
			$x1 = 0;
		} elseif ($attrs['x1'] === ".") {
			$x1 = ".";
		} elseif (!empty($attrs['x1'])) {
			$x1 = (int)$attrs['x1'];
		}
	}
	// Start vertical position, current position (default)
	$y1 = ".";
	if (isset($attrs['y1'])) {
		if ($attrs['y1'] === "0") {
			$y1 = 0;
		} elseif ($attrs['y1'] === ".") {
			$y1 = ".";
		} elseif (!empty($attrs['y1'])) {
			$y1 = (int)$attrs['y1'];
		}
	}
	// End horizontal position, maximum width (default)
	$x2 = ".";
	if (isset($attrs['x2'])) {
		if ($attrs['x2'] === "0") {
			$x2 = 0;
		} elseif ($attrs['x2'] === ".") {
			$x2 = ".";
		} elseif (!empty($attrs['x2'])) {
			$x2 = (int)$attrs['x2'];
		}
	}
	// End vertical position
	$y2 = ".";
	if (isset($attrs['y2'])) {
		if ($attrs['y2'] === "0") {
			$y2 = 0;
		} elseif ($attrs['y2'] === ".") {
			$y2 = ".";
		} elseif (!empty($attrs['y2'])) {
			$y2 = (int)$attrs['y2'];
		}
	}

	$line = $ReportRoot->createLine($x1, $y1, $x2, $y2);
	$wt_report->addElement($line);
}

/**
* XML <List> start element handler
*
* @see ListEHandler()
* @param array $attrs an array of key value pairs for the attributes
*/
function ListSHandler($attrs) {
	global $gedrec, $repeats, $repeatBytes, $list, $repeatsStack, $processRepeats, $parser, $vars, $sortby;
	global $GEDCOM;

	$processRepeats++;
	if ($processRepeats > 1) return;

	$match = array();
	if (isset($attrs['sortby'])) {
		$sortby = $attrs['sortby'];
		if (preg_match("/\\$(\w+)/", $sortby, $match)) {
			$sortby = $vars[$match[1]]['id'];
			$sortby = trim($sortby);
		}
	} else {
		$sortby = "NAME";
	}

	if (isset($attrs['list'])) {
		$listname=$attrs['list'];
	} else {
		$listname = "individual";
	}
	// Some filters/sorts can be applied using SQL, while others require PHP
	switch ($listname) {
		case "pending":
			$rows=WT_DB::prepare(
				"SELECT xref, gedcom_id, CASE new_gedcom WHEN '' THEN old_gedcom ELSE new_gedcom END AS gedcom".
				" FROM `##change`".
				" WHERE (xref, change_id) IN (".
				"  SELECT xref, MAX(change_id)".
				"   FROM `##change`".
				"   WHERE status='pending' AND gedcom_id=?".
				"   GROUP BY xref".
				" )"
			)->execute(array(WT_GED_ID))->fetchAll();
			$list=array();
			foreach ($rows as $row) {
				$list[] = WT_GedcomRecord::getInstance($row->xref, $row->gedcom_id, $row->gedcom);
			}
			break;
		case "individual":
		case "family":
			$sql_col_prefix=substr($listname, 0, 1)."_"; // i_ for individual, f_ for family, etc.
			$sql_join=array();
			$sql_where=array($sql_col_prefix."file=".WT_GED_ID);
			$sql_order_by=array();
			foreach ($attrs as $attr=>$value) {
				if ((strpos($attr, "filter")===0) && $value) {
					// Substitute global vars
					$value=preg_replace_callback('/\$(\w+)/', function($matches) use ($vars) { return $vars[$matches[1]]['id']; }, $value);
					// Convert the various filters into SQL
					if (preg_match('/^(\w+):DATE (LTE|GTE) (.+)$/', $value, $match)) {
						$sql_join[]="JOIN `##dates` AS {$attr} ON ({$attr}.d_file={$sql_col_prefix}file AND {$attr}.d_gid={$sql_col_prefix}id)";
						$sql_where[]="{$attr}.d_fact='{$match[1]}'";
						$date=new WT_Date($match[3]);
						if ($match[2]=="LTE") {
							$sql_where[]="{$attr}.d_julianday2<=".$date->minJD();
						} else {
							$sql_where[]="{$attr}.d_julianday1>=".$date->minJD();
						}
						if ($sortby==$match[1]) {
							$sortby="";
							$sql_order_by[]="{$attr}.d_julianday1";
						}
						unset($attrs[$attr]); // This filter has been fully processed
					} elseif (($listname=="individual") && (preg_match('/^NAME CONTAINS (.*)$/', $value, $match))) {
						// Do nothing, unless you have to
						if (($match[1] != "") or ($sortby=="NAME")) {
							$sql_join[]="JOIN `##name` AS {$attr} ON (n_file={$sql_col_prefix}file AND n_id={$sql_col_prefix}id)";
							// Search the DB only if there is any name supplied
							if ($match[1] != "") {
								$names = explode(" ", $match[1]);
								foreach ($names as $name) {
									$sql_where[]="{$attr}.n_full LIKE ".WT_DB::quote(utf8_strtoupper("%{$name}%"));
								}
							}
							// Let the DB do the name sorting even when no name was entered
							if ($sortby=="NAME") {
								$sortby="";
								$sql_order_by[]="{$attr}.n_sort";
							}
						}
						unset($attrs[$attr]); // This filter has been fully processed
					} elseif (($listname=="individual") && (preg_match('/^REGEXP \/(.+)\//', $value, $match))) {
						$sql_where[]="i_gedcom REGEXP '".$match[1]."'";
						unset($attrs[$attr]); // This filter has been fully processed
					} elseif (($listname=="family") && (preg_match('/^REGEXP \/(.+)\//', $value, $match))) {
						$sql_where[]="f_gedcom REGEXP '".$match[1]."'";
						unset($attrs[$attr]); // This filter has been fully processed
					} elseif (($listname=="family") && (preg_match('/^NAME CONTAINS (.+)$/', $value, $match))) {
						// Eventually, family "names" will be stored in wt_name.  Until then, an extra is needed....
						$sql_join[]="JOIN `##link` AS {$attr}a ON ({$attr}a.l_file={$sql_col_prefix}file AND {$attr}a.l_from={$sql_col_prefix}id)";
						$sql_join[]="JOIN `##name` AS {$attr}b ON ({$attr}b.n_file={$sql_col_prefix}file AND n_id={$sql_col_prefix}id)";
						$sql_where[]="{$attr}a.l_type=IN ('HUSB, 'WIFE')";
						$sql_where[]="{$attr}.n_full LIKE ".WT_DB::quote(utf8_strtoupper("%{$match[1]}%"));
						if ($sortby=="NAME") {
							$sortby="";
							$sql_order_by[]="{$attr}.n_sort";
						}
						unset($attrs[$attr]); // This filter has been fully processed
					} elseif (preg_match('/^(?:\w+):PLAC CONTAINS (.+)$/', $value, $match)) {
						$sql_join[]="JOIN `##places` AS {$attr}a ON ({$attr}a.p_file={$sql_col_prefix}file)";
						$sql_join[]="JOIN `##placelinks` AS {$attr}b ON ({$attr}a.p_file={$attr}b.pl_file AND {$attr}b.pl_p_id={$attr}a.p_id AND {$attr}b.pl_gid={$sql_col_prefix}id)";
						$sql_where[]="{$attr}a.p_place LIKE ".WT_DB::quote(utf8_strtoupper("%{$match[1]}%"));
						// Don't unset this filter. This is just the first primary PLAC filter to reduce the returned list from the DB
					}
					/**
					* General Purpose DB Filter for Individual and Family Lists
					* Place any other filter before these filters because they will pick up any filters that has not been processed
					* Also, do not unset() these two filters. These are just the first primary filters to reduce the returned list from the DB
					*/
					elseif ($listname=="individual" && preg_match('/^(\w*):*(\w*) CONTAINS (.+)$/', $value, $match)) {
						$query = "";
						// Level 1 tag
						if ($match[1] != "") $query .= "%1 {$match[1]}%";
						// Level 2 tag
						if ($match[2] != "") $query .= "%2 {$match[2]}%";
						// Contains what?
						if ($match[3] != "") $query .= "%{$match[3]}%";
						$sql_where[] = "i_gedcom LIKE ".WT_DB::quote(utf8_strtoupper($query));
					} elseif ($listname=="family" && preg_match('/^(\w*):*(\w*) CONTAINS (.+)$/', $value, $match)) {
						$query = "";
						// Level 1 tag
						if ($match[1] != "") $query .= "%1 {$match[1]}%";
						// Level 2 tag
						if ($match[2] != "") $query .= "%2 {$match[2]}%";
						// Contains what?
						if ($match[3] != "") $query .= "%{$match[3]}%";
						$sql_where[] = "f_gedcom LIKE ".WT_DB::quote(utf8_strtoupper($query));
					} else {
						// TODO: what other filters can we apply in SQL?
					}
				}
			}
			if ($listname=="family") {
				$list=search_fams_custom($sql_join, $sql_where, $sql_order_by);
			} else {
				$list=search_indis_custom($sql_join, $sql_where, $sql_order_by);
			}
			// Clean up the SQL queries - they will not be used again
			unset($sql_join, $sql_where, $sql_order_by);
			break;
		default:
			die("Invalid list name: $listname");
	}

	$filters = array();
	$filters2 = array();
	if ((isset($attrs['filter1'])) and (count($list) > 0)) {
		foreach ($attrs as $key=>$value) {
			if (preg_match("/filter(\d)/", $key)) {
				$condition = $value;
				if (preg_match("/@(\w+)/", $condition, $match)) {
					$id = $match[1];
					$value="''";
					if ($id=="ID") {
						if (preg_match("/0 @(.+)@/", $gedrec, $match)) {
							$value = "'".$match[1]."'";
						}
					} elseif ($id=="fact") {
						$value = "'$fact'";
					} elseif ($id=="desc") {
						$value = "'$desc'";
					} else {
						if (preg_match("/\d $id (.+)/", $gedrec, $match)) {
							$value = "'".str_replace("@", "", trim($match[1]))."'";
						}
					}
					$condition = preg_replace("/@$id/", $value, $condition);
				}
				//-- handle regular expressions
				if (preg_match("/([A-Z:]+)\s*([^\s]+)\s*(.+)/", $condition, $match)) {
					$tag = trim($match[1]);
					$expr = trim($match[2]);
					$val = trim($match[3]);
					if (preg_match("/\\$(\w+)/", $val, $match)) {
						$val = $vars[$match[1]]['id'];
						$val = trim($val);
					}
					if ($val) {
						$searchstr = "";
						$tags = explode(":", $tag);
						//-- only limit to a level number if we are specifically looking at a level
						if (count($tags)>1) {
							$level = 1;
							foreach ($tags as $t) {
								if (!empty($searchstr)) {
									$searchstr.="[^\n]*(\n[2-9][^\n]*)*\n";
								}
								//-- search for both EMAIL and _EMAIL... silly double gedcom standard
								if ($t=="EMAIL" || $t=="_EMAIL") {
									$t="_?EMAIL";
								}
								$searchstr .= $level." ".$t;
								$level++;
							}
						} else {
							if ($tag=="EMAIL" || $tag=="_EMAIL") {
								$tag="_?EMAIL";
							}
							$t = $tag;
							$searchstr = "1 ".$tag;
						}
						switch ($expr) {
							case "CONTAINS":
								if ($t=="PLAC") {
									$searchstr.="[^\n]*[, ]*".$val;
								} else {
									$searchstr.="[^\n]*".$val;
								}
								$filters[] = $searchstr;
								break;
							default:
								$filters2[] = array("tag"=>$tag, "expr"=>$expr, "val"=>$val);
								break;
						}
					}
				}
			}
		}
	}
	//-- apply other filters to the list that could not be added to the search string
	if ($filters) {
		foreach ($list as $key=>$record) {
			foreach ($filters as $filter) {
				if (!preg_match("/".$filter."/i", $record->getGedcom())) {
					unset($list[$key]);
					break;
				}
			}
		}
	}
	if ($filters2) {
		$mylist = array();
		foreach ($list as $indi) {
			$key=$indi->getXref();
			$grec=$indi->getGedcom();
			$keep = true;
			foreach ($filters2 as $filter) {
				if ($keep) {
					$tag = $filter['tag'];
					$expr = $filter['expr'];
					$val = $filter['val'];
					if ($val=="''") {
						$val = "";
					}
					$tags = explode(":", $tag);
					$t = end($tags);
					$v = get_gedcom_value($tag, 1, $grec);
					//-- check for EMAIL and _EMAIL (silly double gedcom standard :P)
					if ($t=="EMAIL" && empty($v)) {
						$tag = str_replace("EMAIL", "_EMAIL", $tag);
						$tags = explode(":", $tag);
						$t = end($tags);
						$v = get_sub_record(1, $tag, $grec);
					}


					$level = count($tags);
					switch ($expr) {
						case "GTE":
								if ($t=="DATE") {
									$date1 = new WT_Date($v);
									$date2 = new WT_Date($val);
									$keep = (WT_Date::Compare($date1, $date2)>=0);
								} elseif ($val >= $v) {
									$keep=true;
								}
							break;
						case "LTE":
								if ($t=="DATE") {
									$date1 = new WT_Date($v);
									$date2 = new WT_Date($val);
									$keep = (WT_Date::Compare($date1, $date2)<=0);
								} elseif ($val >= $v) {
									$keep=true;
								}
							break;
						default:
							if ($v==$val) {
								$keep=true;
							} else {
								$keep = false;
							}
							break;
					}
				}
			}
			if ($keep) $mylist[$key]=$indi;
		}
		$list = $mylist;
	}

	switch ($sortby) {
		case "NAME":
			uasort($list, array("WT_GedcomRecord", "Compare"));
			break;
		case "CHAN":
			uasort($list, function($x, $y) {
				$f1 = $x->getFirstFact('CHAN');
				$f2 = $y->getFirstFact('CHAN');
				if ($f1 && $f2) {
					$d1 = $f1->getDate();
					$d2 = $f2->getDate();
					$cmp = WT_Date::compare($d1, $d2);
					if ($cmp) {
						return $cmp;
					} else {
						// Same date.  Compare times
						preg_match('/\n3 TIME (.+)/', $f1->getGedcom(), $m1);
						preg_match('/\n3 TIME (.+)/', $f2->getGedcom(), $m2);
						return strcmp($m1[1], $m2[1]);
					}
				} else {
					return 0;
				}
			});
			break;
		case "BIRT:DATE":
			uasort($list, array("WT_Individual", "CompareBirtDate"));
			break;
		case "DEAT:DATE":
			uasort($list, array("WT_Individual", "CompareDeatDate"));
			break;
		case "MARR:DATE":
			uasort($list, array("WT_Family", "CompareMarrDate"));
			break;
		default:
			// unsorted or already sorted by SQL
			break;
	}

	array_push($repeatsStack, array($repeats, $repeatBytes));
	$repeatBytes = xml_get_current_line_number($parser)+1;
}

/**
* XML <List> end element handler
* @see ListSHandler()
*/
function ListEHandler() {
	global $list, $repeats, $repeatsStack, $repeatBytes, $parser, $parserStack, $report, $gedrec, $processRepeats, $list_total, $list_private;

	$processRepeats--;
	if ($processRepeats>0) {
		return;
	}

	// Check if there is any list
	if (count($list) > 0) {
		// @deprecated
		//$line = xml_get_current_line_number($parser)-1;
		$lineoffset = 0;
		foreach ($repeatsStack as $rep) {
			$lineoffset += $rep[1];
		}
		//-- read the xml from the file
		$lines = file($report);
		while ((strpos($lines[$lineoffset + $repeatBytes], "<List")===false) && (($lineoffset + $repeatBytes) > 0)) {
			$lineoffset--;
		}
		$lineoffset++;
		$reportxml = "<tempdoc>\n";
		$line_nr = $lineoffset + $repeatBytes;
		// List Level counter
		$count = 1;
		while (0 < $count) {
			if (strpos($lines[$line_nr], "<List")!==false) {
				$count++;
			} elseif (strpos($lines[$line_nr], "</List")!==false) {
				$count--;
			}
			if (0 < $count) {
				$reportxml .= $lines[$line_nr];
			}
			$line_nr++;
		}
		// No need to drag this
		unset($lines);
		$reportxml .= "</tempdoc>";
		// Save original values
		array_push($parserStack, $parser);
		$oldgedrec = $gedrec;

		$list_total = count($list);
		$list_private = 0;
		foreach ($list as $record) {
			if ($record->canShow()) {
				$gedrec = $record->getGedcom();
				//-- start the sax parser
				$repeat_parser = xml_parser_create();
				$parser = $repeat_parser;
				//-- make sure everything is case sensitive
				xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false);
				//-- set the main element handler functions
				xml_set_element_handler($repeat_parser, "startElement", "endElement");
				//-- set the character data handler
				xml_set_character_data_handler($repeat_parser, "characterData");
				if (!xml_parse($repeat_parser, $reportxml, true)) {
					printf($reportxml."\nListEHandler XML error: %s at line %d", xml_error_string(xml_get_error_code($repeat_parser)), xml_get_current_line_number($repeat_parser));
					print_r($repeatsStack);
					debug_print_backtrace();
					exit;
				}
				xml_parser_free($repeat_parser);
			}
			else $list_private++;
		}
		// Clean up the GLOBAL list array
		unset($list);
		$parser = array_pop($parserStack);
		$gedrec = $oldgedrec;
	}
	$temp = array_pop($repeatsStack);
	$repeats = $temp[0];
	$repeatBytes = $temp[1];
}

/**
* XML <ListTotal> element handler
*
* Prints the total number of records in a list
* The total number is collected from
* List and Relatives
* @param array $attrs an array of key value pairs for the attributes
*/
function ListTotalSHandler() {
	global $list_total, $list_private, $currentElement;

	if (empty($list_total)) $list_total = 0;

	if ($list_private==0) {
		$currentElement->addText($list_total);
	} else {
		$currentElement->addText(($list_total - $list_private)." / ".$list_total);
	}
}

/**
* @todo add info
* @param array $attrs an array of key value pairs for the attributes
* @see RelativesEHandler()
*/
function RelativesSHandler($attrs) {
	global $repeats, $repeatBytes, $list, $repeatsStack, $processRepeats, $parser, $vars, $sortby;

	$processRepeats++;
	if ($processRepeats>1) return;

	$sortby = "NAME";
	if (isset($attrs['sortby'])) $sortby = $attrs['sortby'];
	$match = array();
	if (preg_match("/\\$(\w+)/", $sortby, $match)) {
		$sortby = $vars[$match[1]]['id'];
		$sortby = trim($sortby);
	}

	$maxgen = -1;
	if (isset($attrs['maxgen'])) $maxgen = $attrs['maxgen'];
	if ($maxgen=="*") $maxgen = -1;

	$group = "child-family";
	if (isset($attrs['group'])) $group = $attrs['group'];
	if (preg_match("/\\$(\w+)/", $group, $match)) {
		$group = $vars[$match[1]]['id'];
		$group = trim($group);
	}

	$id = "";
	if (isset($attrs['id'])) $id = $attrs['id'];
	if (preg_match("/\\$(\w+)/", $id, $match)) {
		$id = $vars[$match[1]]['id'];
		$id = trim($id);
	}

	$list = array();
	$person = WT_Individual::getInstance($id);
	if (!empty($person)) {
		$list[$id] = $person;
		switch ($group) {
			case "child-family":
				foreach ($person->getChildFamilies() as $family) {
					$husband = $family->getHusband();
					$wife = $family->getWife();
					if (!empty($husband)) {
						$list[$husband->getXref()] = $husband;
					}
					if (!empty($wife)) {
						$list[$wife->getXref()] = $wife;
					}
					$children = $family->getChildren();
					foreach ($children as $child) {
						if (!empty($child)) $list[$child->getXref()] = $child;
					}
				}
				break;
			case "spouse-family":
				foreach ($person->getSpouseFamilies() as $family) {
				$husband = $family->getHusband();
					$wife = $family->getWife();
					if (!empty($husband)) {
						$list[$husband->getXref()] = $husband;
					}
					if (!empty($wife)) {
						$list[$wife->getXref()] = $wife;
					}
					$children = $family->getChildren();
					foreach ($children as $child) {
						if (!empty($child)) $list[$child->getXref()] = $child;
					}
				}
				break;
			case "direct-ancestors":
				add_ancestors($list, $id, false, $maxgen);
				break;
			case "ancestors":
				add_ancestors($list, $id, true, $maxgen);
				break;
			case "descendants":
				$list[$id]->generation = 1;
				add_descendancy($list, $id, false, $maxgen);
				break;
			case "all":
				add_ancestors($list, $id, true, $maxgen);
				add_descendancy($list, $id, true, $maxgen);
				break;
		}
	}

	switch ($sortby) {
		case "NAME":
			uasort($list, array("WT_GedcomRecord", "Compare"));
			break;
		case "BIRT:DATE":
			uasort($list, array("WT_Individual", "CompareBirtDate"));
			break;
		case "DEAT:DATE":
			uasort($list, array("WT_Individual", "CompareDeatDate"));
			break;
		case "generation":
			$newarray = array();
			reset($list);
			$genCounter = 1;
			while (count($newarray) < count($list)) {
				foreach ($list as $key => $value) {
					$generation = $value->generation;
					if ($generation == $genCounter) {
						$newarray[$key] = new stdClass();
						$newarray[$key]->generation=$generation;
					}
				}
				$genCounter++;
			}
			$list = $newarray;
			break;
		default:
			// unsorted
			break;
	}
	array_push($repeatsStack, array($repeats, $repeatBytes));
	$repeatBytes = xml_get_current_line_number($parser)+1;
}

/**
* XML </ Relatives> end element handler
*
* @see RelativesSHandler()
*/
function RelativesEHandler() {
	global $list, $repeats, $repeatsStack, $repeatBytes, $parser, $parserStack, $report, $gedrec, $processRepeats, $list_total, $list_private, $generation;

	$processRepeats--;
	if ($processRepeats>0) {
		return;
	}

	// Check if there is any relatives
	if (count($list) > 0) {

		// @deprecated
		//$line = xml_get_current_line_number($parser)-1;
		$lineoffset = 0;
		foreach ($repeatsStack as $rep) {
			$lineoffset += $rep[1];
		}
		//-- read the xml from the file
		$lines = file($report);
		while ((strpos($lines[$lineoffset + $repeatBytes], "<Relatives")===false) && (($lineoffset + $repeatBytes) > 0)) {
			$lineoffset--;
		}
		$lineoffset++;
		$reportxml = "<tempdoc>\n";
		$line_nr = $lineoffset + $repeatBytes;
		// Relatives Level counter
		$count = 1;
		while (0 < $count) {
			if (strpos($lines[$line_nr], "<Relatives")!==false) {
				$count++;
			} elseif (strpos($lines[$line_nr], "</Relatives")!==false) {
				$count--;
			}
			if (0 < $count) {
				$reportxml .= $lines[$line_nr];
			}
			$line_nr++;
		}
		// No need to drag this
		unset($lines);
		$reportxml .= "</tempdoc>\n";
		// Save original values
		array_push($parserStack, $parser);
		$oldgedrec = $gedrec;

		$list_total = count($list);
		$list_private = 0;
		foreach ($list as $key => $value) {
			if (isset($value->generation)) {
				$generation = $value->generation;
			}
			$tmp=WT_GedcomRecord::getInstance($key);
			$gedrec = $tmp->getGedcom();
			//-- start the sax parser
			$repeat_parser = xml_parser_create();
			$parser = $repeat_parser;
			//-- make sure everything is case sensitive
			xml_parser_set_option($repeat_parser, XML_OPTION_CASE_FOLDING, false);
			//-- set the main element handler functions
			xml_set_element_handler($repeat_parser, "startElement", "endElement");
			//-- set the character data handler
			xml_set_character_data_handler($repeat_parser, "characterData");

			if (!xml_parse($repeat_parser, $reportxml, true)) {
				printf($reportxml."\nRelativesEHandler XML error: %s at line %d", xml_error_string(xml_get_error_code($repeat_parser)), xml_get_current_line_number($repeat_parser));
				print_r($repeatsStack);
				debug_print_backtrace();
				exit;
			}
			xml_parser_free($repeat_parser);
		}
		// Clean up the GLOBAL list array
		unset($list);
		$parser = array_pop($parserStack);
		$gedrec = $oldgedrec;
	}
	$temp = array_pop($repeatsStack);
	$repeats = $temp[0];
	$repeatBytes = $temp[1];
}

/**
* XML <Generation /> element handler
*
* Prints the number of generations
* @todo no info on wiki
* @see Element::addText()
*/
function GenerationSHandler() {
	global $generation, $currentElement;

	if (empty($generation)) $generation = 1;

	$currentElement->addText($generation);
}

/**
* XML <NewPage /> element handler
*
* Has to be placed in an element (header, pageheader, body or footer)
* @final
* @todo update wiki, this element is missing
*/
function NewPageSHandler() {
	global $wt_report;

	$temp = "addpage";
	$wt_report->addElement($temp);
}

/**
* @todo add info
* @todo not on wiki
* @param array $attrs an array of key value pairs for the attributes
* @param string $tag HTML tag name
* @see HTMLEHandler()
* @see WT_Report_Base::createHTML()
*/
function HTMLSHandler($tag, $attrs) {
	global $printData, $printDataStack, $wt_reportStack, $wt_report, $currentElement, $ReportRoot;

	if ($tag=="tempdoc") return;
	array_push($wt_reportStack, $wt_report);
	$wt_report = $ReportRoot->createHTML($tag, $attrs);
	$currentElement = $wt_report;

	array_push($printDataStack, $printData);
	$printData = true;
}

/**
* @todo add info
* @param array $attrs an array of key value pairs for the attributes
* @see HTMLSHandler()
*/
function HTMLEHandler($tag) {
	global $printData, $printDataStack, $wt_report, $currentElement, $wt_reportStack;
	if ($tag=="tempdoc") return;

	$printData = array_pop($printDataStack);
	$currentElement = $wt_report;
	$wt_report = array_pop($wt_reportStack);
	if (!is_null($wt_report)) $wt_report->addElement($currentElement);
	else $wt_report = $currentElement;
}

/**
* XML <TitleSHandler> start element handler
*
* @todo add to wiki
* @see TitleEHandler()
* @final
*/
function TitleSHandler() {
	global $reportTitle;
	$reportTitle = true;
}

/**
* XML </TitleEHandler> end element handler
*
* @see TitleSHandler()
* @final
*/
function TitleEHandler() {
	global $reportTitle;
	$reportTitle = false;
}

/**
* XML <DescriptionSHandler> start element handler
*
* @todo add to wiki
* @see DescriptionEHandler()
* @final
*/
function DescriptionSHandler() {
	global $reportDescription;
	$reportDescription = true;
}

/**
* XML </DescriptionEHandler> end element handler
*
* @see DescriptionSHandler()
* @final
*/
function DescriptionEHandler() {
	global $reportDescription;
	$reportDescription = false;
}

/**
 * get gedcom tag value
 *
 * returns the value of a gedcom tag from the given gedcom record
 * @param string $tag The tag to find, use : to delineate subtags
 * @param int $level The gedcom line level of the first tag to find, setting level to 0 will cause it to use 1+ the level of the incoming record
 * @param string $gedrec The gedcom record to get the value from
 * @param int $truncate Should the value be truncated to a certain number of characters
 * @return string
 */
function get_gedcom_value($tag, $level, $gedrec, $truncate='') {
	global $GEDCOM;
	$ged_id=get_id_from_gedcom($GEDCOM);

	if (empty($gedrec)) {
		return "";
	}
	$tags = explode(':', $tag);
	$origlevel = $level;
	if ($level==0) {
		$level = $gedrec{0} + 1;
	}

	$subrec = $gedrec;
	foreach ($tags as $indexval => $t) {
		$lastsubrec = $subrec;
		$subrec = get_sub_record($level, "$level $t", $subrec);
		if (empty($subrec) && $origlevel==0) {
			$level--;
			$subrec = get_sub_record($level, "$level $t", $lastsubrec);
		}
		if (empty($subrec)) {
			if ($t=="TITL") {
				$subrec = get_sub_record($level, "$level ABBR", $lastsubrec);
				if (!empty($subrec)) {
					$t = "ABBR";
				}
			}
			if (empty($subrec)) {
				if ($level>0) {
					$level--;
				}
				$subrec = get_sub_record($level, "@ $t", $gedrec);
				if (empty($subrec)) {
					return;
				}
			}
		}
		$level++;
	}
	$level--;
	$ct = preg_match("/$level $t(.*)/", $subrec, $match);
	if ($ct==0) {
		$ct = preg_match("/$level @.+@ (.+)/", $subrec, $match);
	}
	if ($ct==0) {
		$ct = preg_match("/@ $t (.+)/", $subrec, $match);
	}
	if ($ct > 0) {
		$value = trim($match[1]);
		if ($t=='NOTE' && preg_match('/^@(.+)@$/', $value, $match)) {
			$note = WT_Note::getInstance($match[1]);
			if ($note) {
				$value = $note->getNote();
			} else {
				//-- set the value to the id without the @
				$value = $match[1];
			}
		}
		if ($level!=0 || $t!="NOTE") {
			$value .= get_cont($level+1, $subrec);
		}
		return $value;
	}
	return "";
}

function add_ancestors(&$list, $pid, $children=false, $generations=-1, $show_empty=false) {
	$total_num_skipped = 0;
	$skipped_gen = 0;
	$num_skipped = 0;
	$genlist = array($pid);
	$list[$pid]->generation = 1;
	while (count($genlist)>0) {
		$id = array_shift($genlist);
		if (strpos($id, "empty")===0) continue; // id can be something like “empty7”
		$person = WT_Individual::getInstance($id);
		$famids = $person->getChildFamilies();
		if (count($famids)>0) {
			$num_skipped = 0;
			foreach ($famids as $famid => $family) {
				$husband = $family->getHusband();
				$wife = $family->getWife();
				if ($husband) {
					$list[$husband->getXref()] = $husband;
					$list[$husband->getXref()]->generation = $list[$id]->generation+1;
				}
				if ($wife) {
					$list[$wife->getXref()] = $wife;
					$list[$wife->getXref()]->generation = $list[$id]->generation+1;
				}
				if ($generations == -1 || $list[$id]->generation+1 < $generations) {
					$skipped_gen = $list[$id]->generation+1;
					if ($husband) {
						array_push($genlist, $husband->getXref());
					}
					if ($wife) {
						array_push($genlist, $wife->getXref());
					}
				}
				$total_num_skipped++;
				if ($children) {
					$childs = $family->getChildren();
					foreach ($childs as $child) {
						$list[$child->getXref()] = $child;
						if (isset($list[$id]->generation))
							$list[$child->getXref()]->generation = $list[$id]->generation;
						else
							$list[$child->getXref()]->generation = 1;
					}
				}
			}
		}
	}
}

function add_descendancy(&$list, $pid, $parents=false, $generations=-1) {
	$person = WT_Individual::getInstance($pid);
	if ($person==null) return;
	if (!isset($list[$pid])) {
		$list[$pid] = $person;
	}
	if (!isset($list[$pid]->generation)) {
		$list[$pid]->generation = 0;
	}
	foreach ($person->getSpouseFamilies() as $family) {
		if ($parents) {
			$husband = $family->getHusband();
			$wife = $family->getWife();
			if ($husband) {
				$list[$husband->getXref()] = $husband;
				if (isset($list[$pid]->generation))
					$list[$husband->getXref()]->generation = $list[$pid]->generation-1;
				else
					$list[$husband->getXref()]->generation = 1;
			}
			if ($wife) {
				$list[$wife->getXref()] = $wife;
				if (isset($list[$pid]->generation))
					$list[$wife->getXref()]->generation = $list[$pid]->generation-1;
				else
					$list[$wife->getXref()]->generation = 1;
			}
		}
		$children = $family->getChildren();
		foreach ($children as $child) {
			if ($child) {
				$list[$child->getXref()] = $child;
				if (isset($list[$pid]->generation))
					$list[$child->getXref()]->generation = $list[$pid]->generation+1;
				else
					$list[$child->getXref()]->generation = 2;
			}
		}
		if ($generations == -1 || $list[$pid]->generation+1 < $generations) {
			foreach ($children as $child) {
				add_descendancy($list, $child->getXref(), $parents, $generations); // recurse on the childs family
			}
		}
	}
}