testlink1.9.6 /lib/functions/cfield_mgr.class.php

Language PHP Lines 2484
MD5 Hash e97915df1f3c9decff1eda939b21c97b Estimated Cost $33,864 (why?)
Repository https://bitbucket.org/pfernandez/testlink1.9.6 View Raw File
   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
<?php
/** 
 * TestLink Open Source Project - http://testlink.sourceforge.net/
 * This script is distributed under the GNU General Public License 2 or later. 
 *
 * @package 	TestLink
 * @author 		franciscom
 * @copyright 	2005-2009, TestLink community
 * @copyright 	Mantis BT team (some parts of code was reuse from the Mantis project) 
 * @version    	CVS: $Id: cfield_mgr.class.php,v 1.82 2010/08/29 09:26:16 franciscom Exp $
 * @link 		http://www.teamst.org/index.php
 *
 * @internal Revisions:
 * 
 * 20100829 - franciscom - BUGID 3707,3708 usability issue + browser different behaviour
 * 20100825 - eloff - BUGID 3713 - add platform_name to output of get_linked_cfields_at_execution()
 * 20100726 - amitkhullar - BUGID 3555 - sort order while displaying custom fields.
 * 20100701 - asimon - BUGID 3414: removed a single space character in string_custom_field_input() 
 *                     because of an error that was caused by it 
 * 20100218 - franciscom - string_custom_field_input() changes on checkbox management
 * 20100204 - franciscom - getByLinkID() - new method
 * 20090823 - franciscom - added logic to remove 255 size limit
 * 20090718 - franciscom - buildLocationMap()
 * 20090717 - franciscom - get_linked_cfields_at_design() - added filter by location
 *                         get_linked_cfields_at_execution() - location argument
 *                         
 * 20090607 - franciscom - refactoring to manage table prefix
 * 20090530 - franciscom - execution_values_to_db() added logic to manage insert or update.
 * 20090523 - franciscom - changes on show_on, enable_on logics
 * 20090426 - franciscom - new method getSizeLimit()
 * 20090420 - amitkhullar- BUGID-2410 - get_linked_cfields_at_testplan_design() - added logic to get data
 * 					                    for custom field values stores at test plan level.
 * 20090420 - franciscom - BUGID 2158 - get_linked_cfields_at_design() added filter on custom field id 
 *
 * 20090408 - franciscom - BUGID 2352 - added new method remove_all_scopes_values();
 *                                      changes in delete()
 *
 * 20090321 - franciscom - fixed bug due to missing code on get_linked_cfields_at_design()
 * 20090321 - franciscom - exportValueAsXML()
 * 20090303 - franciscom - get_linked_cfields_at_execution() - fixed bugs on query
 *                         and added logic to change fetch method.
 *
 * 20090223 - franciscom - get_linked_cfields_at_execution() - added logic
 *                         to use this method on report created by:
 *                         Amit Khullar - amkhullar@gmail.com
 *
 * 20080817 - franciscom - added logic give default logic to manage 
 *                         new custom field types that have no specific code.
 *
 * 20080816 - franciscom - new feature: user defined Custom Fields.
 *                         Important: 
 *                         solution is a mix of own ideas and Mantis 1.2.0a1 approach.
 *                         string_custom_field_input(), _build_cfield()
 *
 *                         added radio type, datetime type.
 *
 *
 * 20080810 - franciscom - documentation improvements
 *                         BUGID 1650 (REQ)
 *                         get_linked_cfields_at_design() - interface changes
 *
 * 20080304 - franciscom - prepare_string() before insert
 * 20080216 - franciscom - added testproject name to logAudit recorded information
 * 20071102 - franciscom - BUGID - Feature
 *            addition and refactoring of contributed code
 *
 * 20071027 - franciscom - using Mantis (a php based bugtracking system)
 *                         logic, to improve custom field management
 *                         adding support for url on string custom fields.
 *
 *
 * 20070617 - franciscom - BUGID     insert_id() problems for Postgres and Oracle?
 * 20070501 - franciscom - limiting length of values while writting to db.
 * 20070429 - franciscom - added text area custom field
 *                         code contributed by Seweryn Plywaczyk
 *
 * 20070227 - franciscom - BUGID 677
 * 20070110 - franciscom - solved bug set_active()
 *
 * 20070105 - franciscom -
 * 1. solved bugs on design_values_to_db()
 * 2. refactoring - design_values_to_db()
 *                  execution_values_to_db()
 *
**/

/** load conversion functions */
require_once(dirname(__FILE__) . '/date_api.php');
require_once(dirname(__FILE__) . '/string_api.php');

// Copied from mantis, allow load of user custom implementations
// some sort of poor's man plugin
$cf_files=glob( TL_ABS_PATH . "custom/cf_*.php");
if( count($cf_files) > 0 )
{
    foreach($cf_files as $inc)
    {
        require_once($inc);  
    }   
}


/**
 * class is responsible for logic and store Custom Fields functionality 
 * @package 	TestLink
 */
class cfield_mgr extends tlObject
{
    const DEFAULT_INPUT_SIZE = 50;
    const MULTISELECTIONLIST_WINDOW_SIZE = 5;
    const TEXTAREA_MAX_SIZE = 255;

    // EDIT HERE IF YOU CUSTOMIZE YOUR DB
    /** for text area custom field  40 x 6 -> 240 chars <= 255 chars table field size */
    const TEXTAREA_DEFAULT_COLS = 70;
    const TEXTAREA_DEFAULT_ROWS = 4;

    const CF_ENABLED = 1;
    const ENABLED = 1;
    const DISABLED = 0;
    
	/** @var resource the database handler */
	var $db;

	/** @var object tree class */
	var $tree_manager;

    /**
     *  @var array $application_areas
     * Holds string keys used on this object and pages that manages CF,
     * identifying in what areas/features something will be done
     * 'execution' => mainly on test execution pages,
     *                identifies TL features/pages to record test results
     * 'design'    => test suites, test cases creation
     *                identifies TL features/pages to create test specification
     * 'testplan_design' => link test cases to test plan (assign testcase option)
     * 
     * IMPORTANT: this values are used as access keys in several properties of this object.
     *            then if you add one here, remember to update other properties.
     */
    var $application_areas = array('execution','design','testplan_design');

	/**
	 * @var array Define type of custom fields managed.
	 * Values will be displayed in "Custom Field Type" combo box when
	 * users create custom fields. No localization is applied
	 */ 
    // 20080809 - franciscom
    // Added specific type for test automation related custom fields.
    // Start at code 500
    var $custom_field_types = array(0=>'string',
                                    1=>'numeric',
                                    2=>'float',
                                    4=>'email',
                                    5=>'checkbox',
                                    6=>'list',
                                    7=>'multiselection list',
                                    8=>'date',
                                    9=>'radio',
                                    10=>'datetime',
		  					        20=>'text area',
							        500=>'script',
							        501=>'server');

    /** 
     * @var array Configures for what type of CF "POSSIBLE_VALUES" field need to be manage at GUI level
     * Keys of this map must be the values present in:
     * <code>$this->custom_field_types</code>
     */ 
    var $possible_values_cfg = array('string' => 0,
                                     'numeric'=> 0,
                                     'float'=> 0,
                                     'email'=> 0,
                                     'checkbox' => 1,
                                     'list' => 1,
                                     'multiselection list' => 1,
                                     'date' => 0,
                                     'radio' => 1,
                                     'datetime' =>0,
                                     'text area' => 0,
    							     'script'=> 0,
    							     'server' => 0);
    
    /**  @var array only the types listed here can have custom fields */
    var $node_types = array('testsuite','testplan','testcase','requirement_spec','requirement');

   /**
     *  @var map of maps $locations
     *  
     *  Location is place on page where to display custom field.
     *  This concept has been created to implement a user contribution, that allows for
     *  test cases, display custom fields in a different location (standard location is after
     *  all test case definition), to implemente Prerequisites using CF.
     *
     *  First map key: node type: 'testcase','testsuite', etc.
     *  Each element will be a map with following structure:
     *  key:Holds string keys used on this object and pages that manages CF.
     *      current options: 1 -> standard location, i.e. work as done before this implementation.
     *                       2 -> before steps and results, => between summary and steps/results.
     *
     *  value: used to get translated label to use on User Interface.
     * 
     * IMPORTANT: if you add a new key, this values are used as access keys in several properties of this object.
     *            then if you add one here, remember to update other properties.
     */
    var $locations = array( 'testcase' => 
                            array( 1 => 'standard_location', 2 => 'before_steps_results'));

    // 20090523 - changes in configuration
    //
    // Needed to manage user interface, when creating Custom Fields.
    // When user choose a item type (test case, etc), a javascript logic
    // uses this information to hide/show enable_on, and show_on combos.
    //
    // 0 => combo will not displayed
    //
    // BUGID 3707,3708
    // May be need a review, because after the changes, seems a little bit silly.
    var $enable_on_cfg = array(	'execution' => array('testsuite' => 0,
                                                    'testplan'  => 0,
                                                    'testcase'  => 1,
                                                    'requirement_spec' => 0,
                                                    'requirement' => 0),
								'design' => array('testsuite' => 0,	 //	
                                                  'testplan'  => 0,  //
                                                  'testcase'  => 1,
                                                  'requirement_spec' => 0,
                                                  'requirement' => 0),
                             	'testplan_design' => array('testsuite' => 0,
                                                          'testplan'  => 0,
                                                          'testcase'  => 1,
                                                          'requirement_spec' => 0,
                                                          'requirement' => 0));

  // 0 => combo will not displayed
  var $show_on_cfg=array('execution'=>array('testsuite' => 1,
	                                          'testplan'  => 1,
	                                          'testcase'  => 1,
	                                          'requirement_spec' => 0,
	                                          'requirement' => 0 ),
                         'design' => array('testsuite' => 1,
	                                         'testplan'  => 1,
	                                         'testcase'  => 1,
	                                         'requirement_spec' => 0,
	                                         'requirement' => 0 ),
                         'testplan_design' => array('testsuite' => 1,
	                                         'testplan'  => 1,
	                                         'testcase'  => 1,
	                                         'requirement_spec' => 0,
	                                         'requirement' => 0 )
	                                         );

    // the name of html input will have the following format
    // <name_prefix>_<custom_field_type_id>_<progressive>
    //
    var $name_prefix='custom_field_';
    var $sizes = null;
    
    // must be equal to the lenght of:
    // value column on cfield_*_values tables
    // default_value column on custom_fields table
    // 0 -> no limit
    // Is used on text area types
    var $max_length_value;
    
    // must be equal to the lenght of:
    // possible_values column on custom_fields table
    // 0 -> no limit
    var $max_length_possible_values;
    
    
	/**
	 * Class constructor
	 * 
	 * @param resource &$db reference to the database handler
	 */
	function __construct(&$db)
	{
   		parent::__construct();

		$this->db = &$db;
		$this->tree_manager = new tree($this->db);

		$cfConfig = config_get('custom_fields');
		$this->sizes = $cfConfig->sizes;
		
        if( property_exists($cfConfig,'types') && 
		    !is_null($cfConfig->types) )
		{
		    $this->custom_field_types +=$cfConfig->types;
		    ksort($this->custom_field_types);
		}
    
        if( property_exists($cfConfig,'possible_values_cfg') && 
		    !is_null($cfConfig->possible_values_cfg) )
		{
		    $this->possible_values_cfg +=$cfConfig->possible_values_cfg;
		}
        $this->object_table=$this->tables["custom_fields"];

        $this->max_length_value = $cfConfig->max_length;
        $this->max_length_possible_values = $this->max_length_value;
	}

    function getSizeLimit()
    {
        return $this->max_length_value;    
    }

	function get_application_areas()
	{
        return($this->application_areas);
    }

    /**
	 * @return hash with available locatipons
	 * 
	 * 
     */
	function getLocations()
	{
        return($this->locations);
    }


	/**
	 * @return hash with custom field available types
	 *       key: numeric id
	 *       value: short description
	 */
	function get_available_types()
	{
		return($this->custom_field_types);
	}

	/** 
	 * @return string 
	 */
	function get_name_prefix()
	{
		return($this->name_prefix);
	}

	/**
	 * @return hash with node types id, that can have custom fields.
	 *       key:   short description (node_types.description)
	 *       value: node_type_id      (node_types.id)
	 */ 
	function get_allowed_nodes()
	{
		$allowed_nodes=array();
		$tl_node_types=$this->tree_manager->get_available_node_types();
		foreach($this->node_types as $verbose_type )
		{
			$allowed_nodes[$verbose_type]=$tl_node_types[$verbose_type];
		}
		return($allowed_nodes);
	}

	/**
	 * @return hash with node types id, that can have custom fields with enabled_on_$ui_mode.
	 *       key  : node_type_id      (node_types.id)
	 *       value: 1 -> enable on exec can be configured by user
	 */
	function get_enable_on_cfg($ui_mode)
	{
		$mgmt_cfg=array();
		$mgmt_cfg=$this->_get_ui_mgtm_cfg_for_node_type($this->enable_on_cfg[$ui_mode]);
		return($mgmt_cfg);
	}


	function get_show_on_cfg($ui_mode)
	{
		$mgmt_cfg=array();
		$mgmt_cfg=$this->_get_ui_mgtm_cfg_for_node_type($this->show_on_cfg[$ui_mode]);
		return($mgmt_cfg);
	}


  /*
    function: _get_ui_mgtm_cfg_for_node_type
              utility method

    returns: hash with node types id.
             key  : node_type_id      (node_types.id)
             value: 1 -> enable on exec can be configured by user


  */
function _get_ui_mgtm_cfg_for_node_type($map_node_id_cfg)
{
    $enabled_mgmt=array();
    $tl_node_types=$this->tree_manager->get_available_node_types();
    foreach($this->node_types as $verbose_type)
    {
        $type_id=$tl_node_types[$verbose_type];
        if( isset($map_node_id_cfg[$verbose_type]) )
        {
          $enabled_mgmt[$type_id]=$map_node_id_cfg[$verbose_type];
        }
    }
    return($enabled_mgmt);
}



  /*
    function: get_possible_values_cfg

    returns: hash
             key  : cf_type_id      (see $custom_field_types)
             value: 1 -> possible values can be managed on UI.


  */
  function get_possible_values_cfg()
	{
    $pv_cfg=array();
    $custom_field_types_id=array_flip($this->custom_field_types);

    foreach($this->possible_values_cfg as $verbose_cf_type => $use_on_ui)
    {
      $cf_type_id=$custom_field_types_id[$verbose_cf_type];
      $pv_cfg[$cf_type_id]=$use_on_ui;
    }
    return($pv_cfg);
  }




  /*
    function: get_linked_cfields_at_design
              returns information about custom fields that can be used
              at least at design time, with the value assigned (is any has been assigned).


    $tproject_id: needed because is possible to associate/link
                  a different set of custom field for every test project

    $enabled    : 1 -> get custom fields that are has been configured
                       to be shown during specification design AND are enabled.

                       Remember that also exist custom fields
                       that can be only used during TEST CASE EXECUTION.

    [$filters]:default: null
               map with keys:
               [show_on_execution]: 1 -> filter on field show_on_execution=1
                                     0 or null or not exists -> don't filter

               [show_on_testplan_design]: 1 -> filter on field show_on_execution=1
                                           0 or null or not exists -> don't filter

			   [cfield_id]: if exists use it's value to filter on custom field id
                              null or not exists -> don't filter

			   [location]: new concept used to define on what location on screen
			                 custom field will be designed.
			                 Initally used with CF available for Test cases, to
			                 implement pre-requisites.
                             null => no filtering

    [$node_type]: default: null
                  verbose id ('testcase', 'testsuite', etc) of a node type.
                  custom fields are linked also to different node types.
                  Example:
                  I can define a custom field "Aspect" with values
                  Performace, Usability and wnat use it only for test suites.

    [$node_id]: default: null
                identification of a node/element on node hierarchy.
                Needed when I want to get the value of custom fields
                linked to a node.
                Example:
                Have two test cases (ID:9999, ID:89800), and want to get
                the value assigned to custom field "Operating System".
                I will do two calls to this method.

    [$access_key]: default id, field name to use as access key in returned hash
    
    returns: hash
             key: custom field id


    rev :

		  20090420 - franciscom
          added new key cfield_id on filters

          20080811 - franciscom
          interface changes $show_on_execution -> $filters
         
          
          20070526 - franciscom
          changed order by clause

          20070101 - franciscom
          1. added filter on cfield_testprojects.active=1
          2. added new argument $show_on_execution


  */
  function get_linked_cfields_at_design($tproject_id,$enabled,$filters=null,
                                        $node_type=null,$node_id=null,$access_key='id')
  {
    $additional_join="";
    $additional_values="";
    $additional_filter="";

    if( !is_null($node_type) )
    {
        $hash_descr_id = $this->tree_manager->get_available_node_types();
        $node_type_id=$hash_descr_id[$node_type];

        $additional_join  .= " JOIN {$this->tables['cfield_node_types']} CFNT ON CFNT.field_id=CF.id " .
                             " AND CFNT.node_type_id={$node_type_id} ";
    }
    if( !is_null($node_id) )
    {
      $additional_values .= ",CFDV.value AS value,CFDV.node_id AS node_id";
      $additional_join .= " LEFT OUTER JOIN {$this->tables['cfield_design_values']} CFDV ON CFDV.field_id=CF.id " .
                          " AND CFDV.node_id={$node_id} ";
    }

    // 20080811 - franciscom - refactoring for BUGID 1650 (REQ)
    if( !is_null($filters) )
    {
        if( isset($filters['show_on_execution']) && !is_null($filters['show_on_execution']) )
        {
            $additional_filter .= " AND CF.show_on_execution=1 ";
        }   
        
        // 20090523 - franciscom
        // Probably this piece need to be changed to act on enable_on_ attribute
        // due to CF display logic refactoring
        // if( isset($filters['show_on_testplan_design']) && !is_null($filters['show_on_testplan_design']) )
        // {
        //     $additional_filter .= " AND CF.show_on_testplan_design=1 ";
        // }   
        if( isset($filters['show_on_testplan_design']) && !is_null($filters['show_on_testplan_design']) )
        {
            $additional_filter .= " AND CF.enable_on_testplan_design=1 ";
        }   
           
        if( isset($filters['cfield_id']) && !is_null($filters['cfield_id']) )
        {
            $additional_filter .= " AND CF.id={$filters['cfield_id']} ";
        }
        
        // 20090717 - franciscom
        $filterKey='location';
        if( isset($filters[$filterKey]) && !is_null($filters[$filterKey]) )
        {
            $additional_filter .= " AND CFTP.$filterKey={$filters[$filterKey]} ";
        }
    }

    $sql="SELECT CF.*,CFTP.display_order,CFTP.location" .
         $additional_values .
         " FROM {$this->object_table} CF " .
         " JOIN {$this->tables['cfield_testprojects']} CFTP ON CFTP.field_id=CF.id " .
         $additional_join .
         " WHERE CFTP.testproject_id={$tproject_id} " .
         " AND   CFTP.active=1     " .
         " AND   CF.show_on_design=1     " .
         " AND   CF.enable_on_design={$enabled} " .
         $additional_filter .
         " ORDER BY display_order,CF.id ";


    $map = $this->db->fetchRowsIntoMap($sql,$access_key);
    return($map);
  }


	/*
	  ====================================================================
    ** Very Imporant ** 
    This code is based on Mantis code.
    Initial development was based on 1.x.x versions.
    file:custom_field_api.php - function:print_custom_field_input()
    
    20080815: some changes are done to add more flexibility, and idea
              was compared with 1.2.0a1 Mantis implementation.
    ====================================================================          

    function: string_custom_field_input
              returns an string with the html needed to display the custom field.
   
              If no specific code is found to manage a custom field type,
              it will be used code that manage string type.

    args: $p_field_def: contains the definition of the custom field
                        (including it's field id)

          [$name_suffix]: if used must start with _.
                          example _TCID017

    returns: html string

    rev :
         20080816 - franciscom
         added code to manange user defined (and code developed) Custom Fields.
         Important: solution is a mix of own ideas and Mantis 1.2.0a1 approach

         20071006 - francisco.mancardi@gruppotesi.com
         Added field_size argument

         20070104 - franciscom - added 'multiselection list'

  */
	function string_custom_field_input($p_field_def,$name_suffix='',$field_size=0)
	{

		$str_out='';
		$t_id = $p_field_def['id'];
		$t_type = $p_field_def['type'];

	  	$t_custom_field_value = $p_field_def['default_value'];
	  	if( isset($p_field_def['value']) )
		{
		  $t_custom_field_value = $p_field_def['value'];
		}


    	$verbose_type=trim($this->custom_field_types[$t_type]);
  		$t_custom_field_value = htmlspecialchars( $t_custom_field_value );
    	
    	$input_name="{$this->name_prefix}{$t_type}_{$t_id}{$name_suffix}";
    	$size = isset($this->sizes[$verbose_type]) ? intval($this->sizes[$verbose_type]) : 0;
    	
    	if( $field_size > 0)
    	{
    	  $size=$field_size;
    	}

        
		switch ($verbose_type)
		{
  		case 'list':
  		case 'multiselection list':
   			$t_values = explode( '|', $p_field_def['possible_values']);
        	if( $verbose_type == 'list' )
        	{
        	   $t_multiple=' ';
        	   $t_list_size = intval($size) > 0 ? $size :1;
        	   // 20100701 - asimon - removed single space in next line, 
        	   // it was causing errors in field names on HTML because it somehow gets replaced
        	   // by an underscore somwhere and then the field name doesn't match anymore
        	   //$t_name_suffix=' ';
        	   $t_name_suffix=''; 
        	}
        	else
        	{
        	   $window_size = intval($size) > 1 ? $size : self::MULTISELECTIONLIST_WINDOW_SIZE;
        	   $t_name_suffix='[]';
        	   $t_multiple=' multiple="multiple" ';
        	   $t_list_size = count( $t_values );
        	   if($t_list_size > $window_size)
        	   {
        	    $t_list_size=$window_size;
        	   }
        	}
        	$html_identity=$input_name . $t_name_suffix;
  			$str_out .="<select name=\"{$html_identity}\" id=\"{$input_name}\" {$t_multiple}";
  			$str_out .= ' size="' . $t_list_size . '">';
        	
  			$t_selected_values = explode( '|', $t_custom_field_value );
   			foreach( $t_values as $t_option ) {
  				if( in_array( $t_option, $t_selected_values ) ) {
   					$str_out .='<option value="' . $t_option . '" selected> ' . $t_option . '</option>';
   				} else {
   					$str_out .='<option value="' . $t_option . '">' . $t_option . '</option>';
   				}
   			}
   			$str_out .='</select>';
		break;

		case 'checkbox':
			$t_values = explode( '|', $p_field_def['possible_values']);
        	$t_checked_values = explode( '|', $t_custom_field_value );
			foreach( $t_values as $t_option )
			{
				$str_out .= '<input type="checkbox" name="' . $input_name . '[]"' . " id=\"{$input_name}\"";
				
				// 20100218 - franciscom - added check $t_option != '' to make check box start NOT CHECKED
				if( $t_option != '' && in_array($t_option, $t_checked_values) )
				{
					  $str_out .= ' value="' . $t_option . '" checked="checked">&nbsp;' . $t_option . '&nbsp;&nbsp;';
				}
				else
				{
					  $str_out .= ' value="' . $t_option . '">&nbsp;' . $t_option . '&nbsp;&nbsp;';
				}
				
			}
 	    break;

  		case 'string':
  		case 'email':
  		case 'float':
  		case 'numeric':
			$str_out .= $this->string_input_string($p_field_def,$input_name,$t_custom_field_value,$size);
			break ;

		case 'text area':
			$cols = intval($this->sizes['text area']['cols']);
			$rows = intval($this->sizes['text area']['rows']);
			if($cols <= 0)
			{
				$cols = self::TEXTAREA_DEFAULT_COLS;
			}
			if($rows <= 0)
			{
				$rows = self::TEXTAREA_DEFAULT_ROWS;
			}
			
			if( $this->max_length_value > 0 )
			{
				$counterId = $input_name . '_counter';
				$cf_current_size = $this->max_length_value - tlStringLen($t_custom_field_value);
            	
				// call JS function for check max. size from validate.js
				$js_function = '"textCounter(this.form.' . $input_name . 
				               ',document.getElementById(\''. $counterId.'\'),' . $this->max_length_value .');" ';
			
				$str_out .= '<textarea name="' . $input_name . '" ' . " id=\"{$input_name}\" " .
					    	'onKeyDown=' . $js_function . ' onKeyUp=' . $js_function . 'cols="' .
					        $cols . '" rows="' . $rows . '">' . "{$t_custom_field_value}</textarea>\n";

			    // show character counter
			    $str_out .= '<br><span style="vertical-align: top; padding: 5px;">' .
				    	    sprintf(lang_get('text_counter_feedback'), $this->max_length_value) .
					        ' <span id="' . $counterId .'">'.$cf_current_size.'</span>.</span><br>';
			}		
            else
            {
            	// unlimited
				$str_out .= '<textarea name="' . $input_name . '" ' . " id=\"{$input_name}\" " .
					    	'cols="' . $cols . '" rows="' . $rows . '">' . "{$t_custom_field_value}</textarea>\n";
            		
            }
		break;

		case 'date':
      		$str_out .= create_date_selection_set($input_name,config_get('date_format'),
                                                  $t_custom_field_value, false, true) ;
		break;
      
      case 'datetime':
      $cfg=config_get('gui');
      
      // Important
      // We can do this mix (get date format configuration from standard variable 
      // and time format from an specific custom field config) because string used 
      // for date_format on strftime() has no problem
      // on date() calls (that are used in create_date_selection_set() ).
      $datetime_format=config_get('date_format') . " " .$cfg->custom_fields->time_format;
      $str_out .=create_date_selection_set($input_name,$datetime_format,
                                           $t_custom_field_value, false, true,date( "Y" )-1) ;
      break;
      

      default:
      $dynamic_call='string_input_' . str_replace(' ', '_', $verbose_type);
      if( function_exists($dynamic_call) )
      {
          $str_out .= $dynamic_call($p_field_def, $input_name, $t_custom_field_value);      
      }
      else if( method_exists($this, $dynamic_call) )
      {
          $str_out .= $this->$dynamic_call($p_field_def, $input_name, $t_custom_field_value);
      }
      else
      {
          // treat it as an simple string  
     		  $str_out .= $this->string_input_string($p_field_def,$input_name,$t_custom_field_value,$size);
      }
      break;


  	}
  	return ($str_out);
	} //function end


  /*
    function: design_values_to_db
              write values of custom fields that are used at design time.

    args: $hash: contains info about CF gathered at user interface.
                 (normally $_REQUEST variable)
                 key: custom_field_<field_type_id>_<cfield_id>.
                      Example custom_field_0_67 -> 0=> string field

          $node_id:
          [$cf_map]:  hash -> all the custom fields linked and enabled
                              that are applicable to the node type of $node_id.

                              For the keys not present in $hash, we will write
                              an appropriate value according to custom field
                              type.

                              This is needed because when trying to udpate
                              with hash being $_REQUEST, $_POST or $_GET
                              some kind of custom fields (checkbox, list, multiple list)
                              when has been deselected by user.


    rev:
         20070525 - franciscom - added [hash_type], to reuse this method on
                                 class testcase method copy_cfields_design_values()
         20070501 - franciscom - limiting lenght of value before writting
         20070105 - franciscom - added $cf_map
         20070104 - franciscom - need to manage multiselection in a different way
  */
  function design_values_to_db($hash,$node_id,$cf_map=null,$hash_type=null)
  {
	$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
    if( is_null($hash) && is_null($cf_map) )
    {
       return;
    }
    if( is_null($hash_type) )
    {
      $cfield=$this->_build_cfield($hash,$cf_map);
    }
    else
    {
      $cfield=$hash;
    }
    if( !is_null($cfield) )
    {
      //new dBug($cfield);
      foreach($cfield as $field_id => $type_and_value)
      {
        $value = $type_and_value['cf_value'];

        // do I need to update or insert this value?
        $sql = "/* $debugMsg */ SELECT value FROM {$this->tables['cfield_design_values']} " .
    		   " WHERE field_id={$field_id} AND	node_id={$node_id}";

        $result = $this->db->exec_query($sql);

        // max_length_value = 0 => no limit
        if( $this->max_length_value > 0 && tlStringLen($value) > $this->max_length_value)
        {
           $value = substr($value,0,$this->max_length_value);
        }

        $safe_value=$this->db->prepare_string($value);
        if($this->db->num_rows( $result ) > 0 )
        {

          $sql = "/* $debugMsg */ UPDATE {$this->tables['cfield_design_values']} " .
                 " SET value='{$safe_value}' " .
    	         " WHERE field_id={$field_id} AND	node_id={$node_id}";
        }
        else
        {
          # Remark got from Mantis code:
  		    # Always store the value, even if it's the dafault value
  		    # This is important, as the definitions might change but the
  		    #  values stored with a bug must not change
  		    $sql = "/* $debugMsg */ INSERT INTO {$this->tables['cfield_design_values']} " .
  				   " ( field_id, node_id, value ) " .
  				   " VALUES	( {$field_id}, {$node_id}, '{$safe_value}' )";
  		  }
        $this->db->exec_query($sql);
      } //foreach($cfield
    } //if( !is_null($cfield) )

  } //function end



  /*
    function: remove_all_design_values_from_node
              remove the values of ALL custom fields linked to
              a node. (example test case 5555)

    args: $node_id: single value or array

    returns: -

    rev :
          20070102 - franciscom - $node_id can be an array

  */
  function remove_all_design_values_from_node($node_id)
  {

    $sql="DELETE FROM {$this->tables['cfield_design_values']} ";
    if( is_array($node_id) )
    {

      $sql .= " WHERE node_id IN(" . implode(",",$node_id) . ") ";
    }
    else
    {
      $sql .= " WHERE node_id={$node_id}";
    }
    $this->db->exec_query($sql);
  } //function end


  /*
    function: get_all
              get the definition of all custom field defined in the system,
              or all custom fields with id not included in $id2exclude.

    args: [$id2exclude]: array with custom field ids

    returns: hash:
             key: custom field id

  */
  function get_all($id2exclude=null)
  {
    $not_in_clause="";
    if( !is_null($id2exclude) )
    {
      $not_in_clause=" AND CF.id NOT IN (" .implode(',',$id2exclude) .") ";
    }
    $sql="SELECT CF.*,NT.description AS node_description,NT.id AS node_type_id " .
         " FROM {$this->object_table} CF, " .
         "     {$this->tables['cfield_node_types']} CFNT, " .
         "     {$this->tables['node_types']} NT " .
         " WHERE CF.id=CFNT.field_id " .
         " AND NT.id=CFNT.node_type_id " .
         $not_in_clause .
         " ORDER BY CF.name";
    // $map = $this->db->fetchArrayRowsIntoMap($sql,'id');
    $map = $this->db->fetchRowsIntoMap($sql,'id');
    return($map);
  }

  /*
    function: get_linked_to_testproject
              get definition of all custom fields linked to a test project.


    args: $tproject_id
          [$active]: if not null will add the following filter " AND CFTP.active={$active}"

    returns: hash:
             key: custom field id

    internal revision:
		20090717 - franciscom - added location to result recordset
  */
  function get_linked_to_testproject($tproject_id,$active=null)
  {
    $sql="SELECT CF.*,NT.description AS node_description,NT.id AS node_type_id, " .
         "       CFTP.display_order, CFTP.active, CFTP.location " .
         " FROM {$this->object_table} CF, " .
         "      {$this->tables['cfield_testprojects']} CFTP, " .
         "      {$this->tables['cfield_node_types']} CFNT, " .
         "      {$this->tables['node_types']} NT " .
         " WHERE CF.id=CFNT.field_id " .
         " AND   CF.id=CFTP.field_id " .
         " AND   NT.id=CFNT.node_type_id " .
         " AND   CFTP.testproject_id={$tproject_id} ";

    if( !is_null($active) )
    {
      $sql .= " AND CFTP.active={$active} ";
    }
    //$sql .= " ORDER BY display_order, CF.name";
    // BUGID 3555
   $sql .= " ORDER BY CF.enable_on_design desc, " .
            "CF.enable_on_execution desc, " .
                "CF.enable_on_testplan_design desc,".
                "CFTP.display_order, CF.name";
    $map = $this->db->fetchRowsIntoMap($sql,'id');
    return($map);
  }


  /*
    function: link_to_testproject



    args: $tproject_id
          $cfields_id: array()

    returns: -
  */
	function link_to_testproject($tproject_id,$cfield_ids)
	{
		if(is_null($cfield_ids))
		{
			return;
        }

		$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
    	$tproject_info = $this->tree_manager->get_node_hierarchy_info($tproject_id);
		foreach($cfield_ids as $field_id)
		{
			$sql = "/* $debugMsg */ INSERT INTO {$this->tables['cfield_testprojects']} " .
			   	   " (testproject_id,field_id) " .
			   	   " VALUES({$tproject_id},{$field_id})";

			if ($this->db->exec_query($sql))
			{
				$cf = $this->get_by_id($field_id);
				if ($cf)
				{
					logAuditEvent(TLS("audit_cfield_assigned",$cf[$field_id]['name'],$tproject_info['name']),
								            "ASSIGN",$tproject_id,"testprojects");
			    }					            
			}
		}
	} //function end


  /*
    function: set_active_for_testproject
              set the value of active field


    args: $tproject_id
          $cfields_id: array()
          $active_val: 1/0

    returns: -
  */
	function set_active_for_testproject($tproject_id,$cfield_ids,$active_val)
	{
  		if(is_null($cfield_ids))
  		{
			return;
		}
		
		$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
    	$tproject_info = $this->tree_manager->get_node_hierarchy_info($tproject_id);
		$auditMsg = $active_val ? "audit_cfield_activated" : "audit_cfield_deactivated";
		foreach($cfield_ids as $field_id)
		{
			$sql = "/* $debugMsg */ UPDATE {$this->tables['cfield_testprojects']} " .
				   " SET active={$active_val} " .
				   " WHERE testproject_id={$tproject_id} " .
				   " AND field_id={$field_id}";

			if ($this->db->exec_query($sql))
			{
				$cf = $this->get_by_id($field_id);
				if ($cf)
				{
					logAuditEvent(TLS($auditMsg,$cf[$field_id]['name'],$tproject_info['name']),
								        "SAVE",$tproject_id,"testprojects");
				}								        
			}
		}
	} //function end

 
  /**
   * unlink_from_testproject
   * remove custom field links from target test project
   * N.B.: following Mantis Bugtracking System model,
   *       this operation will NOR remove all values assigned to 
   *       these custom fields .
   *  
   * @param int $tproject_id
   * @param array $cfield_ids 
   *
   */
	function unlink_from_testproject($tproject_id,$cfield_ids)
  	{
	  	if(is_null($cfield_ids))
	  	{
			return;
        }
        
		$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
        // just for audit porpouses
		$tproject_info = $this->tree_manager->get_node_hierarchy_info($tproject_id);
		foreach($cfield_ids as $field_id)
		{
			// BUGID 0000677
			$sql = "/* $debugMsg */ DELETE FROM {$this->tables['cfield_testprojects']} " .
			       " WHERE field_id = {$field_id} AND testproject_id = {$tproject_id} ";
			if ($this->db->exec_query($sql))
			{
				$cf = $this->get_by_id($field_id);
				if ($cf)
				{
					logAuditEvent(TLS("audit_cfield_unassigned",$cf[$field_id]['name'],$tproject_info['name']),
		         					 "ASSIGN",$tproject_id,"testprojects");
		        } 					 
			}
		}
  	} //function end



  /*
    function: get_by_name
              get custom field definition

    args: $name: custom field name

    returns: hash
  */
	function get_by_name($name)
	{
		$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
	  	$my_name=$this->db->prepare_string(trim($name));

	  	$sql="/* $debugMsg */  SELECT CF.*, CFNT.node_type_id,NT.description AS node_type" .
	  	     " FROM {$this->tables['custom_fields']} CF, {$this->tables['cfield_node_types']} CFNT," .
	  	     " {$this->tables['node_types']} NT" .
	  	     " WHERE CF.id=CFNT.field_id " .
	  	     " AND CFNT.node_type_id=NT.id " .
	  	     " AND name='{$my_name}' ";
    	return($this->db->fetchRowsIntoMap($sql,'id'));
  }

  /*
    function: get_by_id
              get custom field definition

    args: $id: custom field id

    returns: hash

  */
	function get_by_id($id)
	{
		$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
	  	$sql="/* $debugMsg */ SELECT CF.*, CFNT.node_type_id" .
	  	     " FROM {$this->tables['custom_fields']}  CF, {$this->tables['cfield_node_types']} CFNT" .
	  	     " WHERE CF.id=CFNT.field_id " .
	  	     " AND   CF.id={$id} ";
    	return($this->db->fetchRowsIntoMap($sql,'id'));
	}

  /*
    function: get_available_item_type
              get information about what item type (testcase,testplan, etc)
              can use this custom field

    args: $id: custom field id

    returns: 

  */
	function get_available_item_type($id)
	{
		$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
	  	$sql="/* $debugMsg */ SELECT CFNT.field_id,CFNT.node_type_id ".
	  	     " FROM {$this->tables['cfield_node_types']} CFNT, " .
	  	     "      {$this->tables['nodes_types']} NT " .
	  	     " WHERE NT.id=CFNT.node_type_id " .
	  	     " CFNt.field_id={$id} ";

    	return($this->db->fetchRowsIntoMap($sql,'field_id'));
	}


  /*
    function: create a custom field

    args: $hash:
          keys   name
                 label
                 type
                 possible_values
                 show_on_design
                 enable_on_design
                 show_on_execute
                 enable_on_execute
                 show_on_testplan_design
                 enable_on_testplan_design
                 node_type_id

    returns: -

    rev: 20080810 - franciscom - BUGID 1650

  */
	function create($cf)
  {
    $ret = array('status_ok' => 0, 'id' => 0, 'msg' => 'ko');

    $my_name=$this->db->prepare_string($cf['name']);
    $my_label=$this->db->prepare_string($cf['label']);
    $my_pvalues=$this->db->prepare_string($cf['possible_values']);


    $sql="INSERT INTO {$this->object_table} " .
         " (name,label,type,possible_values, " .
         "  show_on_design,enable_on_design, " .
         "  show_on_testplan_design,enable_on_testplan_design, " .
         "  show_on_execution,enable_on_execution) " .
         " VALUES('{$my_name}','{$my_label}',{$cf['type']},'{$my_pvalues}', " .
         "        {$cf['show_on_design']},{$cf['enable_on_design']}," .
         "        {$cf['show_on_testplan_design']},{$cf['enable_on_testplan_design']}," .
         "        {$cf['show_on_execution']},{$cf['enable_on_execution']})";
    $result=$this->db->exec_query($sql);

   	if ($result)
  	{
  	  // at least for Postgres DBMS table name is needed.
  	  $field_id=$this->db->insert_id($this->object_table);

      $sql="INSERT INTO {$this->tables['cfield_node_types']} " .
           " (field_id,node_type_id) " .
           " VALUES({$field_id},{$cf['node_type_id']}) ";
      $result=$this->db->exec_query($sql);
    }

    if ($result)
	  {
       $ret = array('status_ok' => 1, 'id' => $field_id, 'msg' => 'ok');
    }
    return($ret);
  } //function end


  /*
    function: update a custom field

    args: $hash:
          keys   name
                 label
                 type
                 possible_values
                 show_on_design
                 enable_on_design
                 show_on_execute
                 enable_on_execute
                 show_on_testplan_design
                 enable_on_testplan_design
                 node_type_id

    returns: -
  */
	function update($cf)
	{
		$my_name = $this->db->prepare_string($cf['name']);
		$my_label = $this->db->prepare_string($cf['label']);
		$my_pvalues = $this->db->prepare_string($cf['possible_values']);

		$sql ="UPDATE {$this->tables['custom_fields']}  " .
			 " SET name='{$my_name}',label='{$my_label}'," .
			 "     type={$cf['type']},possible_values='{$my_pvalues}'," .
			 "     show_on_design={$cf['show_on_design']}," .
			 "     enable_on_design={$cf['enable_on_design']}," .
			 "     show_on_testplan_design={$cf['show_on_testplan_design']}," .
			 "     enable_on_testplan_design={$cf['enable_on_testplan_design']}," .
			 "     show_on_execution={$cf['show_on_execution']}," .
			 "     enable_on_execution={$cf['enable_on_execution']}" .
			 " WHERE id={$cf['id']}";
		$result = $this->db->exec_query($sql);

		if ($result)
		{
			$sql = "UPDATE {$this->tables['cfield_node_types']} " .
				" SET node_type_id={$cf['node_type_id']}" .
				" WHERE field_id={$cf['id']}";
			$result = $this->db->exec_query($sql);
		}
		return $result ? 1 : 0;
  } //function end


  /**
   * delete()
   * Will delete custom field definition and also ALL assigned values
   * If custom field is linked to test projects, these links must be removed
   *
   */
	function delete($id)
	{
        // Before deleting definition I need to remove values
        if( $this->is_used($id) )
        {
            $this->remove_all_scopes_values($id);
		}
		$linked_tprojects = $this->get_linked_testprojects($id);
		if( !is_null($linked_tprojects) && count($linked_tprojects) > 0 )
		{
		    $target=array_keys($linked_tprojects);
		    foreach($target as $tproject_id)
		    {
                $this->unlink_from_testproject($tproject_id,(array)$id);
		    }
		}
		
		$sql="DELETE FROM {$this->tables['cfield_node_types']} WHERE field_id={$id}";
		$result=$this->db->exec_query($sql);
		if($result)
		{
			$sql="DELETE FROM {$this->tables['custom_fields']} WHERE id={$id}";
			$result=$this->db->exec_query($sql);
		}
		return $result ? 1 : 0;
	}


  /*
    function: is_used

    args: $id: custom field id

    returns: 1/0
    
    rev: 20080810 - franciscom - BUGID 1650
  */
	function is_used($id)
	{
	  $sql="SELECT field_id FROM {$this->tables['cfield_design_values']} " .
	       "WHERE  field_id={$id} " .
	       "UNION " .
	       "SELECT field_id FROM {$this->tables['cfield_testplan_design_values']} " .
	       "WHERE  field_id={$id} " .
	       "UNION " .
	       "SELECT field_id FROM {$this->tables['cfield_execution_values']} " .
	       "WHERE  field_id={$id} ";
	  $result=$this->db->exec_query($sql);
	  return($this->db->num_rows( $result ) > 0 ? 1 : 0);
	} //function end

  /*
    function: whoIsUsingMe

    args: $id: custom field id

    returns:
  */
	function whoIsUsingMe($id)
	{
	  $sql=" SELECT field_id,name ".
	       " FROM {$this->tables['cfield_design_values']} CFDV, ".
	       "      {$this->tables['cfield_node_types']} CFNT, " .
	       "      {$this->tables['nodes_hierarchy']} NH " .
	       " WHERE CFDV.field_id=CFNT.field_id " .
	       " AND NH.id=CFDV.node_id " .
	       " CFDV.field_id={$id} ";
	} //function end




/*
    function: name_is_unique

    args: $id
          $name

    returns: 1 => name is unique
*/
function name_is_unique($id,$name)
{
    $cf=$this->get_by_name($name);
    $status=0;
    if( is_null($cf) || isset($cf[$id]) )
    {
       $status=1;
    }
    return($status);
} //function end



  # --------------------
	# Adapted from Mantis code
	# Prepare a string containing a custom field value for display
	# $p_field_def 		  definition of the custom field
	# $p_node_id	bug id to display the custom field value for
	#
	# [$p_value_field]: field id, to point to the field value in $p_field_def
	function string_custom_field_value( $p_field_def, $p_node_id,$p_value_field='value')
	{

		$t_custom_field_value=htmlspecialchars($p_field_def[$p_value_field]);

		switch ($this->custom_field_types[$p_field_def['type']])
  	{
			case 'email':
				return "<a href=\"mailto:$t_custom_field_value\">$t_custom_field_value</a>";
				break;

			case 'enum':
			case 'list':
			case 'multiselection list':
			case 'checkbox':
				return str_replace( '|', ', ', $t_custom_field_value );
				break;

			case 'date':
				if ($t_custom_field_value != null)
				{
				  // must remove %
				  $t_date_format=str_replace("%","",config_get( 'date_format'));
				  $xdate=date( $t_date_format, $t_custom_field_value);
					return  $xdate;
				}
				break ;

			case 'datetime':
				if ($t_custom_field_value != null)
				{
				    // must remove %
				    // $t_date_format=str_replace("%","",config_get( 'timestamp_format'));
                    // $datetime_format=$t_date_format;
                    $t_date_format=str_replace("%","",config_get( 'date_format'));
                    $cfg=config_get('gui');
                    $datetime_format=$t_date_format . " " .$cfg->custom_fields->time_format;
                    $xdate=date( $datetime_format, $t_custom_field_value);
					return  $xdate;
				}
				break ;


		  case 'text area':
                if ($t_custom_field_value != null)
			    {
					return nl2br($t_custom_field_value);
                }
        break;

			default:
			  // 20071027 - franciscom
			  // This code manages URLs
				return string_display_links( $t_custom_field_value );

				// return($t_custom_field_value);
		}
	}



  /*
    function: get_linked_cfields_at_execution
              returns information about custom fields that can be used
              at least at executed, with the value assigned (is any has been assigned).


    $tproject_id: needed because is possible to associate/link
                  a different set of custom field for every test project

    $enabled    : 1 -> get custom fields that are has been configured
                       to be shown during test case execution AND are enabled.

    [$node_type]: default: null
                  verbose id ('testcase', 'testsuite', etc) of a node type.
                  custom fields are linked also to different node types.
                  Example:
                  I can define a custom field "Aspect" with values
                  Performace, Usability and wnat use it only for test suites.

    [$node_id]: default: null
                identification of a node/element on node hierarchy.
                Needed when I want to get the value of custom fields
                linked to a node.
                Example:
                Have two test cases (ID:9999, ID:89800), and want to get
                the value assigned to custom field "Operating System".
                I will do two calls to this method.


    [execution_id]
    [testplan_id]
    [access_key]
    [location]

    returns: hash
             key: custom field id


    @internal Revisions:
        20100825 - eloff - added platform name to output
        20090717 - franciscom - added location argument
        20070526 - franciscom - changed order by clause

  */
  function get_linked_cfields_at_execution($tproject_id,$enabled,
                                           $node_type=null,$node_id=null,
                                           $execution_id=null,$testplan_id=null,
                                           $access_key='id',$location=null)
  {
    $base_values="CF.*,";
    $additional_join="";
    $additional_values="";
    $additional_filter="";
    $order_clause=" ORDER BY display_order,CF.id ";

    $fetchMethod='fetchRowsIntoMap';

    if( !is_null($node_type) )
    {
   		$hash_descr_id = $this->tree_manager->get_available_node_types();
        $node_type_id=$hash_descr_id[$node_type];

        $additional_join  .= " JOIN {$this->tables['cfield_node_types']} CFNT ON CFNT.field_id=CF.id " .
                               " AND CFNT.node_type_id={$node_type_id} ";
    }
    
    if( !is_null($node_id) && !is_null($execution_id) && !is_null($testplan_id) )
    {
        $additional_values .= ",CFEV.value AS value,CFEV.tcversion_id AS node_id";
        $additional_join .= " LEFT OUTER JOIN {$this->tables['cfield_execution_values']} CFEV ON CFEV.field_id=CF.id " .
                            " AND CFEV.tcversion_id={$node_id} " .
                            " AND CFEV.execution_id={$execution_id} " .
                            " AND CFEV.testplan_id={$testplan_id} ";
    }
    else
    {
        // This piece is useful for report implementation done by: Amit Khullar - amkhullar@gmail.com
        if( !is_null($testplan_id) )
        {
            $base_values ='';
            $additional_values .= ",CF.name,CF.label,CF.id,CFEV.value AS value,CFEV.tcversion_id AS node_id," .
                                  "EXEC.id AS exec_id, EXEC.tcversion_id,EXEC.tcversion_number," .
                                  "EXEC.execution_ts,EXEC.status AS exec_status,EXEC.notes AS exec_notes, " .
                                  "NHB.id AS tcase_id, NHB.name AS tcase_name, TCV.tc_external_id, " .
                                  "B.id AS builds_id,B.name AS build_name, U.login AS tester, " .
                                  "PLAT.name AS platform_name";
            
            $additional_join .= " JOIN {$this->tables['cfield_execution_values']} CFEV ON CFEV.field_id=CF.id " .
                                " AND CFEV.testplan_id={$testplan_id} " .
                                " JOIN {$this->tables['executions']} EXEC ON CFEV.tcversion_id = EXEC.tcversion_id " .
                                " AND CFEV.execution_id = EXEC.id " ;
            
            $additional_join .= " JOIN {$this->tables['builds']} B ON B.id = EXEC.build_id " .
                                " AND B.testplan_id = EXEC.testplan_id " ;

            $additional_join .= " JOIN {$this->tables['tcversions']} TCV ON TCV.version = EXEC.tcversion_number " .
			                          " AND TCV.id = EXEC.tcversion_id " ;
            
            $additional_join .= " JOIN {$this->tables['users']} U ON  U.id = EXEC.tester_id " .
                                " JOIN {$this->tables['nodes_hierarchy']} NHA ON NHA.id = EXEC.tcversion_id " .
                                " JOIN {$this->tables['nodes_hierarchy']} NHB ON NHB.id = NHA.parent_id  " ;

            // Use left join, if platforms is not used platform_name will become null
            $additional_join .= " LEFT JOIN {$this->tables['platforms']} PLAT ON EXEC.platform_id = PLAT.id";
            $order_clause="ORDER BY EXEC.tcversion_id,exec_status,exec_id";
            
            $fetchMethod='fetchArrayRowsIntoMap';
    
        }
    }

    if( !is_null($location) )
    {
    	$additional_filter .= " AND CF.id= " . intval($location) . " ";
    }

    $sql = "SELECT {$base_values} CFTP.display_order,CFTP.location" .
           $additional_values .
           " FROM {$this->tables['custom_fields']} CF " .
           " JOIN {$this->tables['cfield_testprojects']} CFTP ON CFTP.field_id=CF.id " .
           $additional_join .
           " WHERE CFTP.testproject_id={$tproject_id} " .
           " AND CFTP.active=1 " .
           " AND CF.enable_on_execution={$enabled} " .
           " AND CF.show_on_execution=1 {$additional_filter} {$order_clause} ";
   
    $map = $this->db->$fetchMethod($sql,$access_key);
    return $map;
  }




  /*
    function: execution_values_to_db
              write values of custom fields that are used at execution time.
              if record exists => UPDATE

    args: $hash: contains info about CF gathered at user interface.
                 (normally $_REQUEST variable)
                 key: custom_field_<field_type_id>_<cfield_id>.
                      Example custom_field_0_67 -> 0=> string field

          $node_id:
          $execution_id:
          $testplan_id:

          [$cf_map]:  hash -> all the custom fields linked and enabled
                              that are applicable to the node type of $node_id.

                            For the keys not present in $hash, we will write
                            an appropriate value according to custom field
                            type.

                            This is needed because when trying to udpate
                            with hash being $_REQUEST, $_POST or $_GET
                            some kind of custom fields (checkbox, list, multiple list)
                            when has been deselected by user.


          [hash_type]: default null, string that can be used to change how hash
                       is processed.
                       
    rev:
        20090727 - franciscom - added [hash_type], to reuse this method on API
        20070501 - franciscom - limiting lenght of value before writting
  */
  function execution_values_to_db($hash,$node_id,$execution_id,$testplan_id,
                                  $cf_map=null,$hash_type=null)
  {
    if( is_null($hash) && is_null($cf_map) )
    {
       return;
    }

    if( is_null($hash_type) )
    {
      $cfield=$this->_build_cfield($hash,$cf_map);
    }
    else
    {
      $cfield=$hash;
    }

    if( !is_null($cfield) )
    {
      foreach($cfield as $field_id => $type_and_value)
      {
        $value = $type_and_value['cf_value'];

        $where_clause = " WHERE field_id={$field_id} AND tcversion_id={$node_id} " .
 			            " AND execution_id={$execution_id} AND testplan_id={$testplan_id}" ;


        // do I need to update or insert this value?
        $sql = " SELECT value,field_id,execution_id " .
               " FROM {$this->tables['cfield_execution_values']} " . $where_clause;
        // file_put_contents('c:\sql.txt',$sql);

        $rs = $this->db->get_recordset($sql); 			   
        // file_put_contents('c:\sql-dd.txt',serialize($rs));

        // max_length_value = 0 => no limit
        if( $this->max_length_value > 0 && tlStringLen($value) > $this->max_length_value)
        {
           $value = substr($value,0,$this->max_length_value);
        }
        $safe_value=$this->db->prepare_string($value);

        // file_put_contents('c:\sql-count.txt',$this->db->num_rows( $result ));
        if( count($rs) > 0 )   //$this->db->num_rows($result) > 0 )
        {
          $sql = "UPDATE {$this->tables['cfield_execution_values']} " .
                 " SET value='{$safe_value}' " .
    	         $where_clause;
    	    // file_put_contents('c:\update.txt',$sql);         
        }
        else
        {

          # Remark got from Mantis code:
  		  # Always store the value, even if it's the default value
  		  # This is important, as the definitions might change but the
  		  #  values stored with a bug must not change
  		  $sql = "INSERT INTO {$this->tables['cfield_execution_values']} " .
  				 " ( field_id, tcversion_id, execution_id,testplan_id,value ) " .
  			     " VALUES	( {$field_id}, {$node_id}, {$execution_id}, {$testplan_id}, '{$safe_value}' )";
          // file_put_contents('c:\insert.txt',$sql);  
        
        }
                               
        $this->db->exec_query($sql);
      } //foreach($cfield
    } //if( !is_null($cfield) )
          // file_put_contents('c:\bye.txt','bye');

  } //function end



  /*
    function: _build_cfield
              support function useful for method used to write CF values to db:
              - design_values_to_db()
              - execution_values_to_db()
              - testplan_design_values_to_db()

    args: $hash:
           key: custom_field_<field_type_id>_<cfield_id>[_<name_suffix>][_<date_part>].
                Example custom_field_0_67 -> 0=> string field
                
                In certain situation we can get:
                custom_field_0_67_234
                0 => string field
                234 => item owner of CF.
                       this happens when you can have multiple times same CF on a page, as happens
                       on execution page if configure TL to work on all test cases in test suite,
                       or when you use CF on testplan_design.
                                                
                To understand [<_date_part>] read below on "Notes on DATE PART - _build_cfield"

           value: can be an array, or a string depending the <field_type_id>

           $cf_map: hash
           key: cfield_id
           value: custom field definition data


    returns: hash or null.

             key: cfield_id
             value: hash ('type_id'  => field_type_id,
                          'cf_value' => value)

    rev: 20080816 - franciscom
         - added code to manange user defined (and code developed) Custom Fields.
           Important: solution is a mix of own ideas and Mantis 1.2.0a1 approach
         - added logic to manage datetime custom field type.  
  */
  function _build_cfield($hash,$cf_map)
  {
    // carved in the stone
    $html_date_input_suffix = array('day' => true,
                                    'month' => true,
                                    'year' => true,
                                    'hour' => true,
                                    'minute' => true,
                                    'second' => true);

    $cf_prefix=$this->name_prefix;
    $len_cfp = tlStringLen($cf_prefix);
    $cftype_pos=2;
    $cfid_pos=3;
    $cfield=null;

    // -------------------------------------------------------------------------
    if( !is_null($cf_map) )
    {
      foreach($cf_map as $key => $value)
      {
        $cfield[$key]=array("type_id"  => $value['type'],
                            "cf_value" => '');
      }
    }
    // -------------------------------------------------------------------------

    // -------------------------------------------------------------------------
    // Overwrite with values if custom field id exist
    if( !is_null($hash) )
    {
      foreach($hash as $key => $value)
      {
        if( strncmp($key,$cf_prefix,$len_cfp) == 0 )
        {
          // Notes on DATE PART - _build_cfield
          // 
          // When using Custom Fields on Test Spec:
          // key has this format (for every type except date )
          // custom_field_0_10 for every type except for type date.
          //
          // For date custom fields:
          // custom_field_8_10_day, custom_field_8_10_month, custom_field_8_10_year
          //
          // After explode()
          // Position 2: CF type
          // Position 3: CF id
          // Position 4: only available for date CF, is date part indicator
          //
          // When using Custom Fields on Execution
          // another piece is added (TC id) then for a date CF, 
          // date part indicator is Position 5, instead of 4
          //
          // When using Custom Fields on Testplan Design 
          // another piece is added (testplan_tcversion.id) then for a date CF, 
          // date part indicator is Position 5, instead of 4
          //
          $dummy=explode('_',$key);
          $last_idx=count($dummy)-1;
          $the_value=$value;
          if( isset($html_date_input_suffix[$dummy[$last_idx]]) )
          {
            $the_value=array();
            if( isset($cfield[$dummy[$cfid_pos]]) )
            {
              $the_value=$cfield[$dummy[$cfid_pos]]['cf_value'];
            }
            $the_value[$dummy[$last_idx]]=$value;
          }
          $cfield[$dummy[$cfid_pos]]=array("type_id"  => $dummy[$cftype_pos],
                                           "cf_value" => $the_value);
        }
      }
    } //if( !is_null($hash) )

    if( !is_null($cfield) )
    {
      foreach($cfield as $field_id => $type_and_value)
      {
        $value = $type_and_value['cf_value'];
        $verbose_type=trim($this->custom_field_types[$type_and_value['type_id']]);

        switch ($verbose_type)
        {
          case 'multiselection list':
          case 'checkbox':
            if( count($value) > 1)
            {
              $value=implode('|',$value);
            }
            else
            {
              $value=is_array($value) ? $value[0] :$value;
            }
            $cfield[$field_id]['cf_value']=$value;
          break;

          case 'date':
            if (($value['year'] == 0) || ($value['month'] == 0) || ($value['day'] == 0))
            {
              $cfield[$field_id]['cf_value']='';
            }
            else
            {
              $cfield[$field_id]['cf_value']=strtotime($value['year'] . "-" .
                                                       $value['month'] . "-" . $value['day']);
            }
          break;
          
          case 'datetime':
            if (($value['year'] == 0) || ($value['month'] == 0) || ($value['day'] == 0))
            {
              $cfield[$field_id]['cf_value']='';
            }
            else
            {
              // mktime(int hour, int minute, int second, int month, int day, int year); 
              // to avoid problems with date formats on strtotime().
              // I've used this PHP manual user's note:
              // thalesjacobi at thalesjacobi dot net (06-Nov-2007 09:50)
              // strtotime() reads the timestamp in en_US format if you want to change 
              // the date format with this number, you should previously know the format 
              // of the date you are trying to parse. Let's say you want to do this :
              // strftime("%Y-%m-%d",strtotime("05/11/2007"));
              // It will understand the date as 11th of may 2007, and not 5th of november 2007. 
              // In this case I would use: 
              // $date = explode("/","05/11/2007");
              // strftime("%Y-%m-%d",mktime(0,0,0,$date[1],$date[0],$date[2]));
              // Much reliable but you must know the date format before. 
              $cfield[$field_id]['cf_value']=mktime($value['hour'],$value['minute'],$value['second'],
                                                    $value['month'],$value['day'],$value['year']);
            }
          break;
         

          default:
            $dynamic_call='build_cfield_' . str_replace(' ', '_', $verbose_type);
            if( function_exists($dynamic_call) )
            {
                $cfield[$field_id]['cf_value']=$dynamic_call($value);      
            }
            else if( method_exists($this,$dynamic_call) )
            {
                $cfield[$field_id]['cf_value']=$this->$dynamic_call($value);      
            }
            else
            {
                $cfield[$field_id]['cf_value']=$value;
            }    
          break;

        }
      } // foreach
    }

    return($cfield);
 } // function end






 /*
   function: set_display_order

   args :  $tproject_id: needed because is possible to associate/link
                         a different set of custom field for every test project
           $map_field_id_display_order



   returns:

 */
 function set_display_order($tproject_id, $map_field_id_display_order)
 {
 	$tproject_info = $this->tree_manager->get_node_hierarchy_info($tproject_id);
    foreach($map_field_id_display_order as $field_id => $display_order)
    {
		$sql = "UPDATE {$this->tables['cfield_testprojects']}  " .
		      " SET display_order=" . intval($display_order) .
		      " WHERE testproject_id={$tproject_id} AND field_id={$field_id} ";
		$this->db->exec_query($sql);
    }
	if ($tproject_info)
	{
		logAuditEvent(TLS("audit_cfield_display_order_changed",$tproject_info['name']),
		                  "SAVE",$tproject_id,"testprojects");
	}	
 } // function end


/**
 * set value of location attribute for one or multiple custom fields.
 *
 * 
 */
 function setDisplayLocation($tproject_id, $field_id_location)
 {
 	$tproject_info = $this->tree_manager->get_node_hierarchy_info($tproject_id);
    foreach($field_id_location as $field_id => $location)
    {
		$sql = "UPDATE {$this->tables['cfield_testprojects']}  " .
		      " SET location=" . intval($location) .
		      " WHERE testproject_id={$tproject_id} AND field_id={$field_id} ";
		$this->db->exec_query($sql);
    }
	if ($tproject_info)
	{
		logAuditEvent(TLS("audit_cfield_location_changed",$tproject_info['name']),
		                  "SAVE",$tproject_id,"testprojects");
	}	
 } // function end


 # code from mantis helper_api.php
 # --------------------
 # returns a tab index value and increments it by one.  This is used to give sequential tab index on
 # a form.
 function helper_get_tab_index_value() {
	 static $tab_index = 0;
	 return ++$tab_index;
 }

 # --------------------
 # returns a tab index and increments internal state by 1.  This is used to give sequential tab index on
 # a form.  For example, this function returns: tabindex="1"
 function helper_get_tab_index() {
	 return 'tabindex="' . helper_get_tab_index_value() . '"';
 }



/**
 * Retrieves the XML Server Parameters specified through custom fields.
 * 
 * @param integer $node_id Accepts current node id from nodes hierarchy level
 * @return mixed An array of config params if found, else returns null
 *
 * @internal rev:
 *     20071102 - franciscom - refactoring
 *     200710 - creation - Swanand
 **/
function getXMLServerParams($node_id)
{
	$srv_cfg = new stdClass();
	
	$node_type=$this->tree_manager->get_available_node_types();
	$node_info=$this->tree_manager->get_node_hierarchy_info($node_id);
	$ret=null;
	
	if( !is_null($node_info) )
	{
		$prefix = "";
		$ret = array( 'xml_server_host' => null,
			'xml_server_port' => null,
			'xml_server_path' => null);
		
		$node_info=$this->tree_manager->get_node_hierarchy_info($node_id);
		
		
		if( $node_info['node_type_id'] == $node_type['testcase'])
		{
			$prefix = "tc_";
		}
		$srv_cfg->host=$prefix . "server_host";
		$srv_cfg->port=$prefix . "server_port";
		$srv_cfg->path=$prefix . "server_path";
		
		$sql = "SELECT cf.name, cfdv.value " .
			"FROM {$this->tables['cfield_design_values']} cfdv," .
			" {$this->tables['custom_fields']}  cf " .
			"WHERE cfdv.field_id = cf.id AND cfdv.node_id = {$node_id}";
		
		$server_info = $this->db->fetchRowsIntoMap($sql,'name');
		$server_cfg_is_ok=0;
		$server_use_host_port=0;
		$server_use_path=0;
		
		if( (isset($server_info[$srv_cfg->host]) && $server_info[$srv_cfg->host] != "") &&
				(isset($server_info[$srv_cfg->port]) && $server_info[$srv_cfg->port] != "") )
		{
			$server_cfg_is_ok=1;
			$ret['xml_server_host'] = $server_info[$srv_cfg->host];
			$ret['xml_server_port'] = $server_info[$srv_cfg->port];
		}
		else if (isset($server_info[$srv_cfg->path]) && $server_info[$srv_cfg->path] != "")
		{
			$server_cfg_is_ok=1;
			$ret['xml_server_path'] = $server_info[$srv_cfg->path];
		}
		else
		{
			if($node_info['parent_id'] != "")
			{
				$ret=$this->getXMLServerParams($node_info['parent_id']);
			}
		}
	} // if( !is_null($node_info) )
	
	return $ret;
} //function end


  /*
    function: testplan_design_values_to_db
              write values of custom fields that are used at testplan design time.

    args: $hash: contains info about CF gathered at user interface.
                 (normally $_REQUEST variable)
                 key: custom_field_<field_type_id>_<cfield_id>.
                      Example custom_field_0_67 -> 0=> string field

          $node_id: Remember that this CF are used to extend information
                    on test cases (tcversions) linked to test plans.
                    Then node_id can not point to other type of node than test case version,
                    then node_id will contain a tcversion_id.
                    
                    I have leave this argument to 
          
          
          
          $link_id: Remember that this CF are used to extend information
                    on test cases (tcversions) linked to test plans.
                    Link information is store in testplan_tcversions table,
                    $link_id points to this link (testplan_tcversions.id field)

          [$cf_map]:  hash -> all the custom fields linked and enabled
                              that are applicable to the node type of $node_id.

                              For the keys not present in $hash, we will write
                              an appropriate value according to custom field
                              type.
                              This is needed because when trying to udpate
                              with hash being $_REQUEST, $_POST or $_GET
                              some kind of custom fields (checkbox, list, multiple list)
                              when has been deselected by user.
                              
          [$hash_type]:  NEED TO BE COMMENTED
                         

    rev:
  */
  function testplan_design_values_to_db($hash,$node_id,$link_id,$cf_map=null,$hash_type=null)
  {
	if( is_null($hash) && is_null($cf_map) )
	{
	   return;
	}

	$cfield = is_null($hash_type) ? $this->_build_cfield($hash,$cf_map) : $hash;
	if( !is_null($cfield) )
	{
	  foreach($cfield as $field_id => $type_and_value)
	  {
	  	// echo "DEBUG: \$field_id:$field_id - \$link_id:$link_id<br>";
	    $value = $type_and_value['cf_value'];

	    // do I need to update or insert this value?
	    $sql = "SELECT value FROM {$this->tables['cfield_testplan_design_values']} " .
			   " WHERE field_id={$field_id} AND	link_id={$link_id}";
	
	    $result = $this->db->exec_query($sql);
	
	    // max_length_value = 0 => no limit
	    if( $this->max_length_value > 0 && tlStringLen($value) > $this->max_length_value)
	    {
	       $value = substr($value,0,$this->max_length_value);
	    }
	
	    $safe_value=$this->db->prepare_string($value);
	    if($this->db->num_rows( $result ) > 0 )
	    {
	
	      $sql = "UPDATE {$this->tables['cfield_testplan_design_values']} " .
	             " SET value='{$safe_value}' " .
			     " WHERE field_id={$field_id} AND	link_id={$link_id}";
	    }
	    else
	    {
	      # Remark got from Mantis code:
		    # Always store the value, even if it's the dafault value
		    # This is important, as the definitions might change but the
		    #  values stored with a bug must not change
		    $sql = "INSERT INTO {$this->tables['cfield_testplan_design_values']} " .
				   " ( field_id, link_id, value ) " .
				   " VALUES	( {$field_id}, {$link_id}, '{$safe_value}' )";
		  }
	    $this->db->exec_query($sql);
	  } //foreach($cfield
	} //if( !is_null($cfield) )

  } //function end


  
  /*
    function: get_linked_cfields_at_testplan_design
              returns information about custom fields that can be used
              at least at testplan design time (test case assignment), 
              with the value assigned (is any has been assigned).


    $tproject_id: needed because is possible to associate/link
                  a different set of custom field for every test project

    $enabled    : 1 -> get custom fields that are has been configured
                       to be shown during test case execution AND are enabled.

    [$node_type]: default: null
                  verbose id ('testcase', 'testsuite', etc) of a node type.
                  custom fields are linked also to different node types.
                  Example:
                  I can define a custom field "Aspect" with values
                  Performace, Usability and wnat use it only for test suites.

    [$node_id]: default: null
                identification of a node/element on node hierarchy.
                Needed when I want to get the value of custom fields
                linked to a node.
                Example:
                Have two test cases (ID:9999, ID:89800), and want to get
                the value assigned to custom field "Operating System".
                I will do two calls to this method.

                IMPORTANT:
                Fot testplan_design Custom Field this will be a TCVERSION_ID,
                not a TESTCASE_ID


    [link_id]: points to testplan_tcversions.id field
    [testplan_id]


    returns: hash
             key: custom field id
             
             

  */
  function get_linked_cfields_at_testplan_design($tproject_id,$enabled,
                                                 $node_type=null,$node_id=null,
                                                 $link_id=null,$testplan_id=null,$access_key = 'id')
  {
    $additional_join="";
    $additional_values="";
    $additional_filter="";
    
    $order_by_clause = " ORDER BY display_order,CF.id ";
    $fetchMethod = 'fetchRowsIntoMap';

    if( !is_null($node_type) )
    {
   		$hash_descr_id = $this->tree_manager->get_available_node_types();
        $node_type_id=$hash_descr_id[$node_type];

        $additional_join  .= " JOIN {$this->tables['cfield_node_types']} CFNT ON CFNT.field_id=CF.id " .
                           " AND CFNT.node_type_id={$node_type_id} ";
    }
    // }
    
    //-amitkhullar - Created this logic to get the linked tcversions for a testplan 
    //                 that have custom field values at test plan level - BUGID 2410
    if( is_null($link_id) && !is_null($testplan_id))
    {
        $additional_values .= ",CFTDV.value AS value, CFTDV.link_id AS node_id, " . 
                              "NHB.id AS tcase_id, NHB.name AS tcase_name, " .
                              "TCV.tc_external_id ";
                               //"TCV.tc_external_id, exec.status ";
                               
        $additional_join .= "JOIN {$this->tables['testplan_tcversions']} TPTC" .
                          " ON TPTC.testplan_id = {$testplan_id}" .
        				  " JOIN {$this->tables['cfield_testplan_design_values']} CFTDV " .
                          " ON CFTDV.field_id=CF.id " .
                          " AND CFTDV.link_id = TPTC.id ";
        
        $additional_join .= " JOIN {$this->tables['tcversions']} TCV ON TCV.id = TPTC.tcversion_id " .
		                    " AND TCV.id = TPTC.tcversion_id " .
         					" JOIN {$this->tables['nodes_hierarchy']} NHA ON NHA.id = TPTC.tcversion_id " .
                            " JOIN {$this->tables['nodes_hierarchy']} NHB ON NHB.id = NHA.parent_id  " ;
        
        //$additional_join .= " JOIN executions EXEC on TPTC.tcversion_id = EXEC.tcversion_id  ";
        
        $order_by_clause = " ORDER BY node_id,display_order,CF.id "; 
        $fetchMethod = 'fetchArrayRowsIntoMap';
        $access_key = 'node_id';
        
    }

    elseif( !is_null($link_id) )
    {
        $additional_values .= ",CFTDV.value AS value, CFTDV.link_id AS node_id";
        $additional_join .= " LEFT OUTER JOIN {$this->tables['cfield_testplan_design_values']} CFTDV " .
                            " ON CFTDV.field_id=CF.id " .
                            " AND CFTDV.link_id={$link_id} ";
    }

    
    
    $sql="SELECT CF.*,CFTP.display_order" .
         $additional_values .
         " FROM {$this->tables['custom_fields']} CF " .
         " JOIN {$this->tables['cfield_testprojects']} CFTP ON CFTP.field_id=CF.id " .
         $additional_join .
         " WHERE CFTP.testproject_id={$tproject_id} " .
         " AND   CFTP.active=1     " .
         " AND   CF.enable_on_testplan_design={$enabled} " .
         
         // 20090523 - franciscom 
         // missing refactoring when changing custom field management
         // " AND   CF.show_on_testplan_design=1 " .
         $order_by_clause;
    $map = $this->db->$fetchMethod($sql,$access_key);
    return($map);
  }

  /*
    function: string_input_radio
              returns an string with the html needed to display radio custom field.
              Is normally called by string_custom_field_input()

    args: p_field_def: contains the definition of the custom field
                       (including it's field id)

          p_input_name: html input name
          
          p_custom_field_value: html input value
                                htmlspecialchars() must be applied to this
                                argument by caller.

    returns: html string
  
    rev: 20080816 - franciscom
         based on Mantis 1.2.0a1 code
         
  */
  function string_input_radio($p_field_def, $p_input_name, $p_custom_field_value) 
  {
    $str_out='';
    $t_values = explode( '|', $p_field_def['possible_values']);                                        
    $t_checked_values = explode( '|', $p_custom_field_value );                                         
    foreach( $t_values as $t_option )                                                                  
    {                                                                                                  
      $str_out .= '<input type="radio" name="' . $p_input_name . '[]"';                               
      if( in_array( $t_option, $t_checked_values ) )                                                   
      {                                                                                                
    	  $str_out .= ' value="' . $t_option . '" checked="checked">&nbsp;' . $t_option . '&nbsp;&nbsp;';
      }                                                                                                
      else                                                                                             
      {                                                                                                
    	  $str_out .= ' value="' . $t_option . '">&nbsp;' . $t_option . '&nbsp;&nbsp;';                  
      }                                                                                                
    }
    return $str_out;
  }               

  /*
    function: build_cfield_radio
              support function useful for method used to write radio CF values to db.
              Is normally called by _build_cfield()
              
    args: custom_field_value: value to be converted to be written to db.
    
    returns: value converted
    
    rev: 20080816 - franciscom

  */
  function build_cfield_radio($custom_field_value) 
  {
      if( count($custom_field_value) > 1)
      {
        $value=implode('|',$custom_field_value);
      }
      else
      {
        $value=is_array($custom_field_value) ? $custom_field_value[0] :$custom_field_value;
      }
      return $value;
  }


/*
    function: string_input_string
              returns an string with the html needed to display custom field of type:
              string, email, numeric, float
               
              Is normally called by string_custom_field_input()

    args: p_field_def: contains the definition of the custom field
                       (including it's field id)

          p_input_name: html input name
          
          p_custom_field_value: html input value
                                htmlspecialchars() must be applied to this
                                argument by caller.
          
          p_size: html input size

    returns: html string
  
    rev: 20080817 - franciscom
         
  */
  function string_input_string($p_field_def, $p_input_name, $p_custom_field_value, $p_size) 
  {
  	$str_out='';
    $size = intval($p_size) > 0 ? $p_size : self::DEFAULT_INPUT_SIZE;
  	$str_out .= "<input type=\"text\" name=\"{$p_input_name}\" id=\"{$p_input_name}\" size=\"{$size}\" ";
	if( 0 < $p_field_def['length_max'] )
	{
	  $str_out .= ' maxlength="' . $p_field_def['length_max'] . '"';
	}
	else
	{
	   $str_out .= ' maxlength="255"';
	}
	$str_out .= ' value="' . $p_custom_field_value .'"></input>';
    return $str_out;
  }               



/**
 * exportValueAsXML
 * generate XML with custom field name, and custom field value
 * useful on export to XML method for items that can have custom fields,
 * example: test cases, test suites, req specification, etc.
 *
 * @param map $cfMap: key: custom file ID, value: map with at least keys 'name', 'value'
 *
 */
 function exportValueAsXML($cfMap)
 {
    $cfRootElem = "<custom_fields>{{XMLCODE}}</custom_fields>";
    $cfElemTemplate = "\t" . '<custom_field><name><![CDATA[' . "\n||NAME||\n]]>" . "</name>" .
	                         '<value><![CDATA['."\n||VALUE||\n]]>".'</value></custom_field>'."\n";
    $cfDecode = array ("||NAME||" => "name","||VALUE||" => "value");
	$cfXML = exportDataToXML($cfMap,$cfRootElem,$cfElemTemplate,$cfDecode,true);
  return $cfXML; 
 }


/**
 * remove_all_scopes_values
 * For a given custom field id remove all assigned values in any scope 
 *
 * @param int $id: custom field id
 * 
 * 
 *
 *
 */
function remove_all_scopes_values($id)
{
    // some sort of blind delete
    $sql=array();
    $sql[]="DELETE FROM {$this->tables['cfield_design_values']} WHERE field_id={$id} ";
    $sql[]="DELETE FROM {$this->tables['cfield_execution_values']} WHERE field_id={$id} ";
    $sql[]="DELETE FROM {$this->tables['cfield_testplan_design_values']} WHERE field_id={$id} ";
  
    foreach($sql as $s)
    {
        $this->db->exec_query($s);        
    }
}

/**
 * get_linked_testprojects
 * For a given custom field id return all test projects where is linked.
 *
 * @param int $id: custom field id
 *
 */
function get_linked_testprojects($id)
{
    $sql=" SELECT NH.id, NH.name " .
         " FROM {$this->tables['cfield_testprojects']} CFTP, {$this->tables['nodes_hierarchy']} NH " .
         " WHERE CFTP.testproject_id=NH.id " .
         " AND CFTP.field_id = {$id} ORDER BY NH.name ";

    $rs=$this->db->fetchRowsIntoMap($sql,'id');
    return $rs;
}


/**
 * @param string node type in verbose form. Example 'testcase'
 *
 * returns map with key: verbose location (see custom field class $locations)
 *                  value: array with fixed key 'location'
 *                         value: location code
 *
 */
function buildLocationMap($nodeType)
{
	$locationMap=null;
    $dummy = $this->getLocations();
	$verboseLocationCode = array_flip($dummy[$nodeType]);
	if( !is_null($verboseLocationCode) && count($verboseLocationCode) > 0 )
	{
		foreach($verboseLocationCode as $key => $value)
		{
			$locationMap[$key]['location']=$value;
		}
	}	     
    return $locationMap; 
}


/**
 * @param int linkID: how is used depends on $options['scope']
 *                    $options['scope']=design => node_id
 *                    $options['scope']=testplan_design => feature_id (see testplan_tcversions table)
 *                    $options['scope']=execution => execution_id
 *
 */
function getByLinkID($linkID, $options=null)
{
	$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;

	$my['options'] = array('scope' => 'design', 'output' => 'field_id'); 	
	$my['options'] = array_merge($my['options'], (array)$options);

 	switch($my['options']['output'])
 	{
 		case 'field_id':
			 $sql = "/* debugMsg */ SELECT field_id FROM ";
 		break;

 		case 'full':
			 $sql = "/* debugMsg */ SELECT * FROM ";
 		break;
 		
 	}
 	 
	switch($my['options']['scope'])
	{
		case 'design':
			 $sql .= " {$this->tables['cfield_design_values']} " .
			         " WHERE node_id = {$linkID} ";
		break;
		
		case 'testplan_design':
			 $sql .= " {$this->tables['cfield_testplan_design_values']} " .
			         " WHERE feature_id = {$linkID} ";
		break;
		
		case 'execution':
			 $sql .= " {$this->tables['cfield_execution_values']} " .
			         " WHERE execution_id = {$linkID} ";
		break;
	
	}
	$rs = $this->db->get_recordset($sql);
	
	
    return $rs; 
}



} // end class
?>
Back to Top