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

Language PHP Lines 2089
MD5 Hash ea40fd2ca7d96919ade961a7e77b93fc Estimated Cost $31,145 (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
<?php
/**
 * TestLink Open Source Project - http://testlink.sourceforge.net/
 * This script is distributed under the GNU General Public License 2 or later.
 *
 * Filename $RCSfile: requirement_mgr.class.php,v $
 *
 * @version $Revision: 1.85 $
 * @modified $Date: 2010/06/24 17:25:53 $ by $Author: asimon83 $
 * @author Francisco Mancardi
 *
 * Manager for requirements.
 * Requirements are children of a requirement specification (requirements container)
 *
 * rev:
 *	20100520 - franciscom - BUGID 2169 - customFieldValuesAsXML() new method_exists
 *	20100511 - franciscom - createFromXML() new method
 *	20100509 - franciscom - update() interface changes.
 *  20100324 - asimon - BUGID 1748 - Moved init_relation_type_select here from reqView.php
 *                                   as it is now used from multiple files.
 *  20100323 - asimon - BUGID 1748 - added count_relations()
 *  20100319 - asimon - BUGID 1748 - added functions for requirement relations: 
 *	                    get_relations(), get_all_relation_labels(), delete_relation(),
 *	                    add_relation(), check_if_relation_exists(), delete_all_relations()
 *                      modified delete() to also delete all relations with req
 *	20100309 - franciscom - get_by_id() removed useless code pointed by BUGID 3254
 *	20100124 - franciscom - BUGID 0003089: Req versions new attributes - active and open 
 *							new methods updateActive(),updateOpen()
 *  20091228 - franciscom - exportReqToXML() - added expected_coverage
 *                          refactoring for feature req versioning
 *  20091227 - franciscom - delete() now manage version_id 
 * 	20091225 - franciscom - new method - generateDocID()
 *  20091216 - franciscom - create_tc_from_requirement() interface changes
 *  20091215 - asimon     - added new method getByDocID()  
 *  20091209 - asimon     - contrib for testcase creation, BUGID 2996
 *  20091208 - franciscom - contrib by julian - BUGID 2995
 *  20091207 - franciscom - create() added node_order
 *	20091202 - franciscom - create(), update() 
 *                          added contribution by asimon83/mx-julian that creates
 *                          links inside scope field.
 *	20091125 - franciscom - expected_coverage management 
 *  20090525 - franciscom - avoid getDisplayName() crash due to deleted user 
 *  20090514 - franciscom - BUGID 2491
 *  20090506 - franciscom - refactoring continued
 *  20090505 - franciscom - refactoring started.
 *                          removed use of REQ.node_order and title.
 *                          this fields must be managed on NH table
 *  
 *  20090401 - franciscom - BUGID 2316
 *  20090315 - franciscom - added require_once '/attachments.inc.php' to avoid autoload() bug
 *                          delete() - fixed delete order due to FK.
 *  20090222 - franciscom - exportReqToXML() - (will be available for TL 1.9)
 *  20081129 - franciscom - BUGID 1852 - bulk_assignment() 
 */

// Needed to use extends tlObjectWithAttachments, If not present autoload fails.
require_once( dirname(__FILE__) . '/attachments.inc.php');
class requirement_mgr extends tlObjectWithAttachments
{
	var $db;
	var $cfield_mgr;
	var $my_node_type;
	var $tree_mgr;
	var $node_types_descr_id;
    var $node_types_id_descr;
	var $attachmentTableName;


	// 20100220 - franciscom - I'm will work only on XML
	// then remove other formats till other dev do refactor
	var $import_file_types = array("csv" => "CSV",
	                               "csv_doors" => "CSV (Doors)",
	                               "XML" => "XML",
							       "DocBook" => "DocBook");

	var $export_file_types = array("XML" => "XML");

	
    const AUTOMATIC_ID=0;
    const ALL_VERSIONS=0;
    const LATEST_VERSION=-1;


  /*
    function: requirement_mgr
              contructor

    args: db: reference to db object

    returns: instance of requirement_mgr

  */
	function __construct(&$db)
	{
		$this->db = &$db;
		$this->cfield_mgr=new cfield_mgr($this->db);
		$this->tree_mgr =  new tree($this->db);

        $this->attachmentTableName = 'requirements';
		tlObjectWithAttachments::__construct($this->db,$this->attachmentTableName);

		$this->node_types_descr_id= $this->tree_mgr->get_available_node_types();
		$this->node_types_id_descr=array_flip($this->node_types_descr_id);
		$this->my_node_type=$this->node_types_descr_id['requirement'];
	    $this->object_table=$this->tables['requirements'];


	}

	/*
	  function: get_export_file_types
	            getter
	
	  args: -
	
	  returns: map
	           key: export file type code
	           value: export file type verbose description
	
	*/
	function get_export_file_types()
	{
    	return $this->export_file_types;
  	}

	/*
	  function: get_impor_file_types
	            getter
	
	  args: -
	
	  returns: map
	           key: import file type code
	           value: import file type verbose description
	
	*/
	function get_import_file_types()
	{
     	return $this->import_file_types;
  	}





/*
  function: get_by_id


  args: id: requirement id (can be an array)
	    [version_id]: requirement version id (can be an array)
	    [version_number]: 
	    [options]
	    

  returns: null if query fails
           map with requirement info

*/
function get_by_id($id,$version_id=self::ALL_VERSIONS,$version_number=1,$options=null,$filters=null)
{
	$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
	$my['options'] = array('order_by' => " ORDER BY REQV.version DESC ");
    $my['options'] = array_merge($my['options'], (array)$options);

    // null => do not filter
	$my['filters'] = array('status' => null, 'type' => null);
    $my['filters'] = array_merge($my['filters'], (array)$filters);

	$filter_clause = '';
    $dummy[]='';  // trick to make implode() work
    foreach( $my['filters'] as $field2filter => $value)
    {
    	if( !is_null($value) )
    	{
    		$dummy[] = " {$field2filter} = '{$value}' ";
    	}
    }
    if( count($dummy) > 1)
    {
    	$filter_clause = implode(" AND ",$dummy);
    }

	$where_clause = " WHERE NH_REQV.parent_id ";
	if( ($id_is_array=is_array($id)) )
	{
		$where_clause .= "IN (" . implode(",",$id) . ") ";
	}
	else
	{
		$where_clause .= " = {$id} ";
	}
	
	if(is_array($version_id))
	{
	    $versionid_list = implode(",",$version_id);
	    $where_clause .= " AND REQV.id IN ({$versionid_list}) ";
	}
	else
	{
		if( is_null($version_id) )
		{
		    // search by "human" version number
		    $where_clause .= " AND REQV.version = {$version_number} ";
		}
		else 
		{
		    if($version_id != self::ALL_VERSIONS && $version_id != self::LATEST_VERSION)
		    {
		    	$where_clause .= " AND REQV.id = {$version_id} ";
		    }
		}
    }
  
	$sql = " /* $debugMsg */ SELECT REQ.id,REQ.srs_id,REQ.req_doc_id," . 
		   " REQV.scope,REQV.status,REQV.type,REQV.active," . 
           " REQV.is_open,REQV.author_id,REQV.version,REQV.id AS version_id," .
           " REQV.expected_coverage,REQV.creation_ts,REQV.modifier_id," .
           " REQV.modification_ts,NH_REQ.name AS title, REQ_SPEC.testproject_id, " .
	       " NH_RSPEC.name AS req_spec_title, REQ_SPEC.doc_id AS req_spec_doc_id, NH_REQ.node_order " .
	       " FROM {$this->object_table} REQ " .
	       " JOIN {$this->tables['nodes_hierarchy']} NH_REQ ON NH_REQ.id = REQ.id " .
	       " JOIN {$this->tables['nodes_hierarchy']} NH_REQV ON NH_REQV.parent_id = NH_REQ.id ".
	       " JOIN  {$this->tables['req_versions']} REQV ON REQV.id = NH_REQV.id " .  
	       " JOIN {$this->tables['req_specs']} REQ_SPEC ON REQ_SPEC.id = REQ.srs_id " .
	       " JOIN {$this->tables['nodes_hierarchy']} NH_RSPEC ON NH_RSPEC.id = REQ_SPEC.id " .
           $where_clause . $filter_clause . $my['options']['order_by'];


	if ($version_id != self::LATEST_VERSION)
	{
		$recordset = $this->db->get_recordset($sql);
	}
	else
	{
	    // 20090413 - franciscom - 
	    // But, how performance wise can be do this, instead of using MAX(version)
	    // and a group by? 
	    //           
	    // 20100309 - franciscom - 
	    // if $id was a list then this will return something USELESS
	    //           
	    if( !$id_is_array )
	    {         
			$recordset = array($this->db->fetchFirstRow($sql));
		}	
		else
		{
			// Write to event viewer ???
		}
	}

  	$rs = null;
  	$userCache = null;  // key: user id, value: display name
  	if(!is_null($recordset))
  	{
  	    // Decode users
  	    $rs = $recordset;
  	    $key2loop = array_keys($recordset);
  	    $labels['undefined'] = lang_get('undefined');
  	    $user_keys = array('author' => 'author_id', 'modifier' => 'modifier_id');
  	    foreach( $key2loop as $key )
  	    {
  	    	foreach( $user_keys as $ukey => $userid_field)
  	    	{
  	    		$rs[$key][$ukey] = '';
  	    		if(trim($rs[$key][$userid_field]) != "")
  	    		{
  	    			if( !isset($userCache[$rs[$key][$userid_field]]) )
  	    			{
  	    				$user = tlUser::getByID($this->db,$rs[$key][$userid_field]);
  	    				$rs[$key][$ukey] = $user ? $user->getDisplayName() : $labels['undefined'];
  	    				$userCache[$rs[$key][$userid_field]] = $rs[$key][$ukey];
  	    			}
  	    			else
  	    			{
  	    				$rs[$key][$ukey] = $userCache[$rs[$key][$userid_field]];
  	    			}
  	    		}
  	    	}	
  	    }
  	}  	
	return $rs;
}

  /*
    function: create

    args: srs_id: req spec id, parent of requirement to be created
          reqdoc_id
          title
          scope
          user_id: author
          [status]
          [type]
          [expected_coverage]
          [node_order]

    returns: map with following keys:
             status_ok -> 1/0
             msg -> some simple message, useful when status_ok ==0
             id -> id of new requirement.

	@internal revision
	20091202 - franciscom -  added contribution by asimon83/mx-julian 

  */
function create($srs_id,$reqdoc_id,$title, $scope, $user_id,
                $status = TL_REQ_STATUS_VALID, $type = TL_REQ_TYPE_INFO,
                $expected_coverage=1,$node_order=0)
{
    $result = array( 'id' => 0, 'status_ok' => 0, 'msg' => 'ko');
	$field_size = config_get('field_size');

	$reqdoc_id = trim_and_limit($reqdoc_id,$field_size->req_docid);
	$title = trim_and_limit($title,$field_size->req_title);
	$tproject_id = $this->tree_mgr->getTreeRoot($srs_id);

	$op = $this->check_basic_data($srs_id,$tproject_id,$title,$reqdoc_id);
	$result['msg'] = $op['status_ok'] ? $result['msg'] : $op['msg'];
	if( $op['status_ok'] )
	{
		$result = $this->create_req_only($srs_id,$reqdoc_id,$title,$user_id,$node_order);
		if($result["status_ok"])
		{

			if (config_get('internal_links')->enable )
			{
				$scope = req_link_replace($this->db, $scope, $tproject_id);
			}

			$version_number = 1;
			$op = $this->create_version($result['id'],$version_number,$scope,$user_id,
			                            $status,$type,intval($expected_coverage));
			$result['msg'] = $op['status_ok'] ? $result['msg'] : $op['msg'];
		}	
	}
	return $result;
	
} // function end


  /*
    function: update


    args: id: requirement id
          version_id
          reqdoc_id
          title
          scope
          user_id: author
          status
          type
          $expected_coverage
          [skip_controls]


    returns: map: keys : status_ok, msg

	@internal revision
	20091202 - franciscom - 
	
  */

function update($id,$version_id,$reqdoc_id,$title, $scope, $user_id, $status, $type,
                $expected_coverage,$node_order=null,$tproject_id=null,$skip_controls=0)
{
	$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
    
    $result['status_ok'] = 1;
    $result['msg'] = 'ok';
    
    $db_now = $this->db->db_now();
    $field_size=config_get('field_size');
    
    // get SRSid, needed to do controls
    $rs=$this->get_by_id($id,$version_id);
    $req = $rs[0];
    $srs_id=$req['srs_id'];
    
    // try to avoid function calls when data is available on caller
	$tproject_id = is_null($tproject_id) ? $this->tree_mgr->getTreeRoot($srs_id): $tproject_id;

    /* contribution by asimon83/mx-julian */
	if (config_get('internal_links')->enable ) 
	{
		$scope = req_link_replace($this->db, $scope, $tproject_id);
	}
	/* end contribution by asimon83/mx-julian */
    
	$reqdoc_id=trim_and_limit($reqdoc_id,$field_size->req_docid);
	$title=trim_and_limit($title,$field_size->req_title);
    $chk=$this->check_basic_data($srs_id,$tproject_id,$title,$reqdoc_id,$id);

    if($chk['status_ok'] || $skip_controls)
	{
 		$sql = array();

  		$q = "/* $debugMsg */ UPDATE {$this->tables['nodes_hierarchy']} " .
  		  	 " SET name='" . $this->db->prepare_string($title) . "'";
	  	if( !is_null($node_order) )
	  	{
  			$q .= ', node_order= ' . abs(intval($node_order));  	     
	  	}
 	  	$sql[] = $q . " WHERE id={$id}";

	  	$sql[] = "/* $debugMsg */ UPDATE {$this->tables['requirements']} " .
	  	         " SET req_doc_id='" . $this->db->prepare_string($reqdoc_id) . "'" .
	  	         " WHERE id={$id}";
	  	
	  	$sql[] = "/* $debugMsg */ UPDATE {$this->tables['req_versions']} " .
	  			 " SET scope='" . $this->db->prepare_string($scope) . "', " .
	  	         " status='" . $this->db->prepare_string($status) . "', " .
	  	         " type='" . $this->db->prepare_string($type) . "', " .
	  	         " modifier_id={$user_id}, modification_ts={$db_now}, " . 
	  	         " expected_coverage={$expected_coverage} " . 
	  	         " WHERE id={$version_id}";

		foreach($sql as $stm)
		{
		    $qres = $this->db->exec_query($stm);
		    if( !$qres )
		    {
		  	  	$result['status_ok'] = 0;
		  	  	$result['msg'] = $this->db->error_msg;
		  	  	$result['sql'] = $stm;
		      	break;
		    }
		}

    } // 	  if($chk['status_ok'] || $skip_controls)
    else
	{
	    $result['status_ok']=$chk['status_ok'];
	    $result['msg']=$chk['msg'];
	}
    return $result;
  } //function end



  /*
    function: delete
              Requirement
              Requirement link to testcases
              Requirement relations
              Requirement custom fields values
              Attachments


    args: id: can be one id, or an array of id

    returns:

  */
	function delete($id,$version_id = self::ALL_VERSIONS)
 	{
 		$children = null;
		$where_clause_coverage = '';
	  	$where_clause_this = '';
		$deleteAll = false;
	    $result = null;
	    $doIt = true;
	    
	  	if(is_array($id))
	  	{
		
			$id_list = implode(',',$id);
	    	$where_clause_coverage = " WHERE req_id IN ({$id_list})";
			$where_clause_this = " WHERE id IN ({$id_list})";
	  	}
	    else
	    {
	    	$where_clause_coverage = " WHERE req_id = {$id}";
			$where_clause_this = " WHERE id = {$id}";
	    }
		
		// When deleting only one version, we need to check if we need to delete 
		// requirement also.
		$children[] = $version_id;
	  	if( $version_id == self::ALL_VERSIONS)
	  	{
 			$deleteAll = true;
			// I'm trying to speedup the next deletes
	    	$sql="SELECT NH.id FROM {$this->tables['nodes_hierarchy']} NH WHERE NH.parent_id ";
	    	if( is_array($id) )
	    	{
	      		$sql .=  " IN (" .implode(',',$id) . ") ";
	    	}
	    	else
	    	{
	      		$sql .= "  = {$id} ";
	    	}
	
	    	$children_rs=$this->db->fetchRowsIntoMap($sql,'id');
            $children = array_keys($children_rs); 

	    	// Delete Custom fields
	    	$this->cfield_mgr->remove_all_design_values_from_node($id);
	  		
	  		// delete dependencies with test specification
	  		$sql = "DELETE FROM {$this->tables['req_coverage']} " . $where_clause_coverage;
	  		$result = $this->db->exec_query($sql);

			if ($result)
	  		{
	  			$doIt = true;
	  			$the_ids = is_array($id) ? $id : array($id);
				foreach($the_ids as $key => $value)
				{
					$result = $this->attachmentRepository->deleteAttachmentsFor($value,$this->attachmentTableName);
				}
	    	}
	  	}        

        // Delete version info
	  	if( $doIt )
	  	{
	  			$where_clause_children = " WHERE id IN (" .implode(',',$children) . ") ";
	  			$sql = "DELETE FROM {$this->tables['req_versions']} " . $where_clause_children;
	  			$result = $this->db->exec_query($sql);

	  			$sql = "DELETE FROM {$this->tables['nodes_hierarchy']} " . $where_clause_children;
	  			$result = $this->db->exec_query($sql);
		} 

		if( $deleteAll && $result)
		{
	  		$sql = "DELETE FROM {$this->object_table} " . $where_clause_this;
	  		$result = $this->db->exec_query($sql);

	  		$sql = "DELETE FROM {$this->tables['nodes_hierarchy']} " . $where_clause_this;
	  		$result = $this->db->exec_query($sql);
	  		
	  		//also delete relations to other requirements
	  		$this->delete_all_relations($id);
		}
	
	    $result = (!$result) ? lang_get('error_deleting_req') : 'ok';
	  	return $result;
	}


/** collect coverage of Requirement
 * @param string $req_id ID of req.
 * @return assoc_array list of test cases [id, title]
 *
 * rev: 20080226 - franciscom - get test case external id
 */
function get_coverage($id)
{
	$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
    $sql = "/* $debugMsg */ SELECT DISTINCT NHA.id,NHA.name,TCV.tc_external_id " .
  	       " FROM {$this->tables['nodes_hierarchy']} NHA, " .
  	       " {$this->tables['nodes_hierarchy']} NHB, " .
  	       " {$this->tables['tcversions']} TCV, " .
  	       " {$this->tables['req_coverage']} RC " .
           " WHERE RC.testcase_id = NHA.id " .
  		   " AND NHB.parent_id=NHA.id " .
           " AND TCV.id=NHB.id " .
  		   " AND RC.req_id={$id}";
  	return $this->db->get_recordset($sql);
}


  /*
    function: check_basic_data
              do checks on title and reqdoc id, for a requirement

    args: srs_id: req spec id (req parent)
          title
          reqdoc_id
          [id]: default null


    returns: map
             keys: status_ok
                   msg

  */
  function check_basic_data($srs_id,$tproject_id,$title,$reqdoc_id,$id = null)
  {

  	$req_cfg = config_get('req_cfg');

  	$my_srs_id=$srs_id;

  	$ret['status_ok'] = 1;
  	$ret['msg'] = '';

  	if ($title == "")
  	{
  		$ret['status_ok'] = 0;
  		$ret['msg'] = lang_get("warning_empty_req_title");
  	}

  	if ($reqdoc_id == "")
  	{
  		$ret['status_ok'] = 0;
  		$ret['msg'] .=  " " . lang_get("warning_empty_reqdoc_id");
  	}

  	if($ret['status_ok'])
  	{
  		$ret['msg'] = 'ok';
  		$rs = $this->getByDocID($reqdoc_id,$tproject_id);
 		if(!is_null($rs) && (is_null($id) || !isset($rs[$id])))
  		{
  			$ret['msg'] = sprintf(lang_get("warning_duplicate_reqdoc_id"),$reqdoc_id);
  			$ret['status_ok'] = 0;
  		}
  	}

  	return $ret;
  }


  /*
    function: create_tc_from_requirement
              create testcases using requirements as input


    args:

    returns:

  */
function create_tc_from_requirement($mixIdReq,$srs_id, $user_id, $tproject_id = null, $tc_count=null)
{
	$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
    $tcase_mgr = new testcase($this->db);
   	$tsuite_mgr = new testsuite($this->db);

  	$req_cfg = config_get('req_cfg');
  	$field_size = config_get('field_size');
 	
  	$auto_testsuite_name = $req_cfg->default_testsuite_name;
    $node_descr_type=$this->tree_mgr->get_available_node_types();
    $empty_steps = null;
    $empty_preconditions = ''; // fix for BUGID 2995
    
    $labels['tc_created'] = lang_get('tc_created');

  	$output = null;
  	$reqSet = is_array($mixIdReq) ? $mixIdReq : array($mixIdReq);
  	
  	/* contribution BUGID 2996, testcase creation */
    if( is_null($tproject_id) || $tproject_id == 0 )
    {
  		$tproject_id = $this->tree_mgr->getTreeRoot($srs_id);
  	}
  	
  	if ( $req_cfg->use_req_spec_as_testsuite_name ) 
  	{
 		$full_path = $this->tree_mgr->get_path($srs_id);
  		$addition = " (" . lang_get("testsuite_title_addition") . ")";
  		$truncate_limit = $field_size->testsuite_name - strlen($addition);

  		// REQ_SPEC_A
  		//           |-- REQ_SPEC_A1 
  		//                          |-- REQ_SPEC_A2
  		//                                         |- REQ100
  		//                                         |- REQ101
  		//
  		// We will try to check if a test suite has already been created for
  		// top REQ_SPEC_A  (we do search using automatic generated name as search criteria).
  		// If not => we need to create all path till leaves (REQ100 and REQ200)
  		//
  		//
  		// First search: we use test project
  		$parent_id = $tproject_id;
  		$deep_create = false;
  		foreach($full_path as $key => $node) 
  		{
  			// follow hierarchy of test suites to create
  			$tsuiteInfo = null;
  			$testsuite_name = substr($node['name'],0,$truncate_limit). $addition;
  			if( !$deep_create )
  			{
  				// child test suite with this name, already exists on current parent ?
  				// At first a failure we will not check anymore an proceed with deep create
  				$sql="/* $debugMsg */ SELECT id,name FROM {$this->tables['nodes_hierarchy']} NH " .
  	     			 " WHERE name='" . $this->db->prepare_string($testsuite_name) . "' " .
  	     			 " AND node_type_id=" . $node_descr_type['testsuite'] . 
  	     			 " AND parent_id = {$parent_id} ";
            	
            	// If returns more that one record use ALWAYS first
  				$tsuiteInfo = $this->db->fetchRowsIntoMap($sql,'id');
 			}
 			
 			if( is_null($tsuiteInfo) )
 			{
  				$tsuiteInfo = $tsuite_mgr->create($parent_id,$testsuite_name,$req_cfg->testsuite_details);
  				$output[] = sprintf(lang_get('testsuite_name_created'), $testsuite_name);
  				$deep_create = true;
 			}
 			else
 			{
 				$tsuiteInfo = current($tsuiteInfo);
 				$tsuite_id = $tsuiteInfo['id'];
 			}
			$tsuite_id = $tsuiteInfo['id'];  // last value here will be used as parent for test cases
 			$parent_id = $tsuite_id;
  		}
  		$output[]=sprintf(lang_get('created_on_testsuite'), $testsuite_name);
  	} 
  	else 
  	{
  		// don't use req_spec as testsuite name
  		// Warning:
  		// We are not maintaining hierarchy !!!
  		$sql=" SELECT id FROM {$this->tables['nodes_hierarchy']} NH " .
  		     " WHERE name='" . $this->db->prepare_string($auto_testsuite_name) . "' " .
  		     " AND parent_id=" . $testproject_id . " " .
  	    	 " AND node_type_id=" . $node_descr_type['testsuite'];
  
  		$result = $this->db->exec_query($sql);
    	if ($this->db->num_rows($result) == 1) {
    		$row = $this->db->fetch_array($result);
    		$tsuite_id = $row['id'];
    		$label = lang_get('created_on_testsuite');
    	} else {
    		// not found -> create
	    	tLog('test suite:' . $auto_testsuite_name . ' was not found.');
	    	$new_tsuite=$tsuite_mgr->create($testproject_id,$auto_testsuite_name,$req_cfg->testsuite_details);
	    	$tsuite_id=$new_tsuite['id'];
	    	$label = lang_get('testsuite_name_created');
	   	}
    	$output[]=sprintf($label, $auto_testsuite_name);
	   	
  	}
  	/* end contribution */

  	// create TC
    $createOptions = array();
    $createOptions['check_names_for_duplicates'] = config_get('check_names_for_duplicates');
    $createOptions['action_on_duplicate_name'] = config_get('action_on_duplicate_name');

    $testcase_importance_default = config_get('testcase_importance_default');

  	// compute test case order
  	$testcase_order = config_get('treemenu_default_testcase_order');
   	$nt2exclude=array('testplan' => 'exclude_me','requirement_spec'=> 'exclude_me','requirement'=> 'exclude_me');
    $siblings = $this->tree_mgr->get_children($tsuite_id,$nt2exclude);
    if( !is_null($siblings) )
    {
    	$dummy = end($siblings);
    	$testcase_order = $dummy['node_order'];
    }
    
  	foreach ($reqSet as $reqID)
  	{
        $reqData = $this->get_by_id($reqID,requirement_mgr::LATEST_VERSION);
        $count = (!is_null($tc_count)) ? $tc_count[$reqID] : 1;
        $reqData = $reqData[0];
        
        // Generate name with progessive
        $instance=1;
     	$getOptions = array('check_criteria' => 'like','access_key' => 'name');
        $itemSet = $tcase_mgr->getDuplicatesByName($reqData['title'],$tsuite_id,$getOptions);	
        $nameSet = null;
        if( !is_null($itemSet) )
        {
        	$nameSet = array_flip(array_keys($itemSet));
        }
        for ($idx = 0; $idx < $count; $idx++) 
        {
	        $testcase_order++;
            	
            // We have a little problem to work on:
            // suppose you have created:
            // TC [1]
            // TC [2]
            // TC [3]
            // If we delete TC [2]
            // When I got siblings  il will got 2, if I create new progressive using next,
            // it will be 3 => I will get duplicated name.
            //
            // Seems better option can be:
            // Get all siblings names, put on array, create name an check if exists, if true 
            // generate a new name.
            // This may be at performance level is better than create name then check on db,
            // because this approach will need more queries to DB     	
            //
            $tcase_name = $reqData['title'] . " [{$instance}]"; 
            if( !is_null($nameSet) )
            {
            	while( isset($nameSet[$tcase_name]) )
            	{
            		$instance++;
            		$tcase_name = $reqData['title'] . " [{$instance}]"; 
            	}
            }        
            $nameSet[$tcase_name]=$tcase_name;
            
            // 20100106 - franciscom - multiple test case steps feature - removed expected_results
	        // Julian - BUGID 2995
	  	    $tcase = $tcase_mgr->create($tsuite_id,$tcase_name,$req_cfg->testcase_summary_prefix . $reqData['scope'] ,
						                $empty_preconditions, $empty_steps,$user_id,null,
						                $testcase_order,testcase::AUTOMATIC_ID,TESTCASE_EXECUTION_TYPE_MANUAL,
						                $testcase_importance_default,$createOptions);
	        
	        $tcase_name = $tcase['new_name'] == '' ? $tcase_name : $tcase['new_name'];
	        $output[]=sprintf($labels['tc_created'], $tcase_name);

	  		// create coverage dependency
	  		if (!$this->assign_to_tcase($reqData['id'],$tcase['id']) ) 
	  		{
	  			$output[] = 'Test case: ' . $tcase_name . " was not created";
	  		}
        }
  	}
  	return $output;
  }


  /*
    function: assign_to_tcase
              assign requirement(s) to test case

    args: req_id: can be an array of requirement id
          testcase_id

    returns: 1/0
    
    rev:  20090401 - franciscom - BUGID 2316 - refactored

  */
  function assign_to_tcase($req_id,$testcase_id)
  {
	$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;

  	$output = 0;
    if($testcase_id && $req_id)
    {
        $items = (array)$req_id;
  	    $in_clause = implode(",",$items);
    	$sql = " /* $debugMsg */ SELECT req_id,testcase_id FROM {$this->tables['req_coverage']} " .
  		       " WHERE req_id IN ({$in_clause}) AND testcase_id = {$testcase_id}";
 	    $coverage = $this->db->fetchRowsIntoMap($sql,'req_id');
   	    
  	    $loop2do=count($items);
   	    for($idx=0; $idx < $loop2do; $idx++)
   	    {
   	        if( is_null($coverage) || !isset($coverage[$items[$idx]]) )
   	        {
   	            $sql = "INSERT INTO {$this->tables['req_coverage']} (req_id,testcase_id) " .
         	           "VALUES ({$items[$idx]},{$testcase_id})";
           	    $result = $this->db->exec_query($sql);
         	    if ($this->db->affected_rows() == 1)
         	    {
        	        $output = 1;
         	        $tcInfo = $this->tree_mgr->get_node_hierarchy_info($testcase_id);
        	        $reqInfo = $this->tree_mgr->get_node_hierarchy_info($items[$idx]);
        	        if($tcInfo && $reqInfo)
        	        {
        	    	    logAuditEvent(TLS("audit_req_assigned_tc",$reqInfo['name'],$tcInfo['name']),
        	    	                  "ASSIGN",$this->object_table);
        	    	}                  
         	    }
   	        }    
            else
            {
                $output = 1;
            }    
   	    }
  	}
  	return $output;
  }




  /*
    function: unassign_from_tcase

    args: req_id
          testcase_id

    returns:

  */
	function unassign_from_tcase($req_id,$testcase_id)
	{
		$output = 0;
		$sql = " DELETE FROM {$this->tables['req_coverage']} " .
		     " WHERE req_id={$req_id} " .
		     " AND testcase_id={$testcase_id}";
	
		$result = $this->db->exec_query($sql);
	
		if ($result && $this->db->affected_rows() == 1)
		{
			$tcInfo = $this->tree_mgr->get_node_hierarchy_info($testcase_id);
			$reqInfo = $this->tree_mgr->get_node_hierarchy_info($req_id);
			if($tcInfo && $reqInfo)
			{
				logAuditEvent(TLS("audit_req_assignment_removed_tc",$reqInfo['name'],
				                  $tcInfo['name']),"ASSIGN",$this->object_table);
			}
			$output = 1;
		}
		return $output;
	}

  /*
    function: bulk_assignment
              assign N requirements to M test cases
              Do not write audit info              

    args: req_id: can be an array
          testcase_id: can be an array

    returns: number of assignments done


  */
  function bulk_assignment($req_id,$testcase_id)
  {
	$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;

    $insertCounter=0;  // just for debug
  	$requirementSet=$req_id;
  	$tcaseSet=$testcase_id;
  	
    if( !is_array($req_id) )
    {
       $requirementSet=array($req_id);  
    }
    if( !is_array($testcase_id) )
    {
       $tcaseSet=array($testcase_id);  
    }

    $req_list=implode(",",$requirementSet);
    $tcase_list=implode(",",$tcaseSet);
    
    // Get coverage for this set of requirements and testcase, to be used
    // to understand if insert if needed
    $sql = " /* $debugMsg */ SELECT req_id,testcase_id FROM {$this->tables['req_coverage']} " .
  		   " WHERE req_id IN ({$req_list}) AND testcase_id IN ({$tcase_list})";
    $coverage = $this->db->fetchMapRowsIntoMap($sql,'req_id','testcase_id');
   
   
  	$insert_sql = "INSERT INTO {$this->tables['req_coverage']} (req_id,testcase_id) ";
  	foreach($tcaseSet as $tcid)
  	{
  	    foreach($requirementSet as $reqid)
  	    {
            if( !isset($coverage[$reqid][$tcid]) )
            {
                $insertCounter++;
  	            $sql = $insert_sql . "VALUES ({$reqid},{$tcid})";
                $this->db->exec_query($sql);
            }    
  	    }
  	}
  	return $insertCounter;
  }


  /*
    function: get_relationships

    args :

    returns:

  */
  function get_relationships($req_id)
  {
	$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;

  	$sql = " /* $debugMsg */ SELECT nodes_hierarchy.id,nodes_hierarchy.name " .
  	       " FROM {$this->tables['nodes_hierarchy']} nodes_hierarchy, " .
  	       "      {$this->tables['req_coverage']} req_coverage " .
		   " WHERE req_coverage.testcase_id = nodes_hierarchy.id " .
  		   " AND  req_coverage.req_id={$req_id}";

  	return ($this->db->get_recordset($sql));
  }


  /*
    function: get_all_for_tcase
              get all requirements assigned to a test case
              A filter can be applied to do search on all req spec,
              or only on one.


    args: testcase_id
          [srs_id]: default 'all'

    returns:
    
    

  */
function get_all_for_tcase($testcase_id, $srs_id = 'all')
{                         
	$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
    
  	$sql = " /* $debugMsg */ SELECT REQ.id,REQ.req_doc_id,NHA.name AS title, " .
  	       " NHB.name AS req_spec_title,REQ_COVERAGE.testcase_id " .
  	       " FROM {$this->object_table} REQ, " .
  	       "      {$this->tables['req_coverage']} REQ_COVERAGE," .
  	       "      {$this->tables['nodes_hierarchy']} NHA," .
  	       "      {$this->tables['nodes_hierarchy']} NHB," .
  	       "      {$this->tables['req_specs']} RSPEC " ;
  	
  	$idList = implode(",",(array)$testcase_id);
  	$sql .= " WHERE REQ_COVERAGE.testcase_id  IN (" . $idList . ")";
	$sql .= " AND REQ.srs_id=RSPEC.id  AND REQ_COVERAGE.req_id=REQ.id " .
	        " AND NHA.id=REQ.id AND NHB.id=RSPEC.id " ;

  	// if only for one specification is required
  	if ($srs_id != 'all') 
  	{
  		$sql .= " AND REQ.srs_id=" . $srs_id;
  	}
	if (is_array($testcase_id))
	{
  		return $this->db->fetchRowsIntoMap($sql,'testcase_id',true);
  	}
  	else
  	{
  		return $this->db->get_recordset($sql);
  	}	
}




  /*
    function:

    args :

    returns:

  */
	function check_title($title)
	{
		$ret = array('status_ok' => 1, 'msg' => 'ok');
	
		if ($title == "")
		{
			$ret['status_ok'] = 0;
	  		$ret['msg'] = lang_get("warning_empty_req_title");
	    }
	
	 	return $ret;
	}

/*
  function:

  args :
          $nodes: array with req_id in order
  returns:

*/
function set_order($map_id_order)
{
  $this->tree_mgr->change_order_bulk($map_id_order);
}


/**
 * exportReqToXML
 *
 * @param  int $id requirement id
 * @param  int $tproject_id: optional default null.
 *         useful to get custom fields (when this feature will be developed).
 *
 * @return  string with XML code
 *
 */
function exportReqToXML($id,$tproject_id=null)
{            
	// BUGID 2169
	$cfXML = $this->customFieldValuesAsXML($id,$tproject_id);

 	$rootElem = "{{XMLCODE}}";
	$elemTpl = "\t" .   "<requirement>" .
	           "\n\t\t" . "<docid><![CDATA[||DOCID||]]></docid>" .
	           "\n\t\t" . "<title><![CDATA[||TITLE||]]></title>" .
	           "\n\t\t" . "<node_order><![CDATA[||NODE_ORDER||]]></node_order>".
			   "\n\t\t" . "<description><![CDATA[\n||DESCRIPTION||\n]]></description>".
			   "\n\t\t" . "<status><![CDATA[||STATUS||]]></status>" .
			   "\n\t\t" . "<type><![CDATA[||TYPE||]]></type>" .
			   "\n\t\t" . "<expected_coverage><![CDATA[||EXPECTED_COVERAGE||]]></expected_coverage>" .			   
			   "\n\t\t" . $cfXML . 
			   "\n\t" . "</requirement>" . "\n";
					   
	$info = array (	"||DOCID||" => "req_doc_id",
							    "||TITLE||" => "title",
							    "||DESCRIPTION||" => "scope",
							    "||STATUS||" => "status",
							    "||TYPE||" => "type",
							    "||NODE_ORDER||" => "node_order",
							    "||EXPECTED_COVERAGE||" => "expected_coverage",
							    );
	
	$req = $this->get_by_id($id,requirement_mgr::LATEST_VERSION);
	$reqData[] = $req[0]; 
	
	
	$xmlStr = exportDataToXML($reqData,$rootElem,$elemTpl,$info,true);						    
	return $xmlStr;
}


/**
 * xmlToMapRequirement
 *
 */
function xmlToMapRequirement($xml_item)
{
    // Attention: following PHP Manual SimpleXML documentation, Please remember to cast
    //            before using data from $xml,
    if( is_null($xml_item) )
    {
        return null;      
    }
        
	$dummy=array();
	foreach($xml_item->attributes() as $key => $value)
	{
	   $dummy[$key] = (string)$value;  // See PHP Manual SimpleXML documentation.
	}    
	
	$dummy['node_order'] = (int)$xml_item->node_order;
	$dummy['title'] = (string)$xml_item->title;
    $dummy['docid'] = (string)$xml_item->docid;
    $dummy['description'] = (string)$xml_item->description;
    $dummy['status'] = (string)$xml_item->status;
    $dummy['type'] = (string)$xml_item->type;
    $dummy['expected_coverage'] = (int)$xml_item->expected_coverage;

    if( property_exists($xml_item,'custom_fields') )	              
    {
	      $dummy['custom_fields']=array();
	      foreach($xml_item->custom_fields->children() as $key)
	      {
	         $dummy['custom_fields'][(string)$key->name]= (string)$key->value;
	      }    
	}
	return $dummy;
}


/**
 * createFromXML
 *
 */
function createFromXML($xml,$tproject_id,$parent_id,$author_id,$filters = null,$options=null)
{
	$user_feedback = null;
	$req = $this->xmlToMapRequirement($xml);

    $copy_req = null;
	$getOptions = array('output' => 'minimun');
    $has_filters = !is_null($filters);
	$my['options'] = array( 'actionOnDuplicate' => "update");
	$my['options'] = array_merge($my['options'], (array)$options);

	$labels = array('import_req_created' => '','import_req_skipped' =>'', 'import_req_updated' => '');
	foreach($labels as $key => $dummy)
	{
		$labels[$key] = lang_get($key);
	}

    // Check:
    // If item with SAME DOCID exists inside container
	// If there is a hit
	//	   We will follow user option: update,create new version
	//
	// If do not exist check must be repeated, but on WHOLE test project
	// 	If there is a hit -> we can not create
	//		else => create
	// 
	$getOptions = array('output' => 'minimun');
	$msgID = 'import_req_skipped';
	$check_in_reqspec = $this->getByDocID($req['docid'],$tproject_id,$parent_id,$getOptions);
	if(is_null($check_in_reqspec))
	{
		$check_in_tproject = $this->getByDocID($req['docid'],$tproject_id,null,$getOptions);
		if(is_null($check_in_tproject))
		{
			$this->create($parent_id,$req['docid'],$req['title'],$req['description'],
		    		         $author_id,$req['status'],$req['type'],$req['expected_coverage'],
		    		         $req['node_order']);
			$msgID = 'import_req_created';
		}             		 
        else
        {
			// Can not have req with same req doc id on another branch => BLOCK
			// What to do if is Frozen ??? -> now ignore and update anyway
			$msgID = 'import_req_skipped';

        }               		 
	}
    else
    {
		// Need to get Last Version no matter active or not.
		// What to do if is Frozen ??? -> now ignore and update anyway
		$reqID = key($check_in_reqspec);
		$last_version = $this->get_last_version_info($reqID);
		$result = $this->update($reqID,$last_version['id'],$req['docid'],$req['title'],$req['description'],
								$author_id,$req['status'],$req['type'],$req['expected_coverage'],
								$req['node_order']);
		$msgID = 'import_req_updated';
    }               		 
    $user_feedback = array('doc_id' => $req['docid'],'title' => $req['title'], 
    				 	   'import_status' => sprintf($labels[$msgID],$req['docid']));
	
	
	return $user_feedback;
}




// ---------------------------------------------------------------------------------------
// Custom field related functions
// ---------------------------------------------------------------------------------------

/*
  function: get_linked_cfields
            Get all linked custom fields.
            Remember that custom fields are defined at system wide level, and
            has to be linked to a testproject, in order to be used.


  args: id: requirement id
        [parent_id]:
                     this information is vital, to get the linked custom fields.
                     null -> use requirement_id as starting point.
                     !is_null -> use this value as testproject id


  returns: map/hash
           key: custom field id
           value: map with custom field definition and value assigned for choosen requirement,
                  with following keys:

            			id: custom field id
            			name
            			label
            			type: custom field type
            			possible_values: for custom field
            			default_value
            			valid_regexp
            			length_min
            			length_max
            			show_on_design
            			enable_on_design
            			show_on_execution
            			enable_on_execution
            			display_order
            			value: value assigned to custom field for this requirement
            			       null if for this requirement custom field was never edited.

            			node_id: requirement id
            			         null if for this requirement, custom field was never edited.


  rev :
       20070302 - check for $id not null, is not enough, need to check is > 0

*/
function get_linked_cfields($id,$parent_id=null)
{
	$enabled = 1;
	if (!is_null($id) && $id > 0)
	{
    	$req_info = $this->get_by_id($id);
    	$req_info = $req_info[0];
	  	$tproject_id = $req_info['testproject_id'];
	}
	else
	{
	  	$tproject_id = $parent_id;
	}
	$cf_map = $this->cfield_mgr->get_linked_cfields_at_design($tproject_id,$enabled,null,
	                                                          'requirement',$id);

	return $cf_map;
}


/*
  function: html_table_of_custom_field_inputs
            Return html code, implementing a table with custom fields labels
            and html inputs, for choosen requirement.
            Used to manage user actions on custom fields values.


  args: $id
        [parent_id]: need to undertad to which testproject the requirement belongs.
                     this information is vital, to get the linked custom fields.
                     null -> use requirement_id as starting point.
                     !is_null -> use this value as starting point.


        [$name_suffix]: must start with '_' (underscore).
                        Used when we display in a page several items
                        (example during test case execution, several test cases)
                        that have the same custom fields.
                        In this kind of situation we can use the item id as name suffix.


  returns: html string

*/
function html_table_of_custom_field_inputs($id,$parent_id=null,$name_suffix='')
{
    $NO_WARNING_IF_MISSING=true;
    $cf_smarty = '';
    $cf_map = $this->get_linked_cfields($id,$parent_id);
    
    if(!is_null($cf_map))
    {
    	$cf_smarty = "<table>";
    	foreach($cf_map as $cf_id => $cf_info)
    	{
            $label=str_replace(TL_LOCALIZE_TAG,'',
                               lang_get($cf_info['label'],null,$NO_WARNING_IF_MISSING));
    
    		$cf_smarty .= '<tr><td class="labelHolder">' . htmlspecialchars($label) . ":</td><td>" .
    			          $this->cfield_mgr->string_custom_field_input($cf_info,$name_suffix) .
    					  "</td></tr>\n";
    	}
    	$cf_smarty .= "</table>";
    }
    return $cf_smarty;
}


/*
  function: html_table_of_custom_field_values
            Return html code, implementing a table with custom fields labels
            and custom fields values, for choosen requirement.
            You can think of this function as some sort of read only version
            of html_table_of_custom_field_inputs.


  args: $id

  returns: html string

*/
function html_table_of_custom_field_values($id)
{
    $NO_WARNING_IF_MISSING=true;
	$PID_NO_NEEDED = null;
	$cf_smarty = '';

	$cf_map = $this->get_linked_cfields($id,$PID_NO_NEEDED);

	if(!is_null($cf_map))
	{
		foreach($cf_map as $cf_id => $cf_info)
		{
			// if user has assigned a value, then node_id is not null
			if($cf_info['node_id'])
			{
				$label = str_replace(TL_LOCALIZE_TAG,'',
	                                 lang_get($cf_info['label'],null,$NO_WARNING_IF_MISSING));

				$cf_smarty .= '<tr><td class="labelHolder">' .
								htmlspecialchars($label) . ":</td><td>" .
								$this->cfield_mgr->string_custom_field_value($cf_info,$id) .
								"</td></tr>\n";
			}
		}

		if(trim($cf_smarty) != "")
		{
			$cf_smarty = "<table>" . $cf_smarty . "</table>";
		}
	}
	return $cf_smarty;
} // function end


  /*
    function: values_to_db
              write values of custom fields.

    args: $hash:
          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:
  */
  function values_to_db($hash,$node_id,$cf_map=null,$hash_type=null)
  {
    $this->cfield_mgr->design_values_to_db($hash,$node_id,$cf_map,$hash_type);
  }


 /**
  * customFieldValuesAsXML
  *
  * @param $id: requirement spec id
  * @param $tproject_id: test project id
  *
  *
  */
 function customFieldValuesAsXML($id,$tproject_id)
 {
    $xml = null;
    $cfMap=$this->get_linked_cfields($id,$tproject_id);
	if( !is_null($cfMap) && count($cfMap) > 0 )
	{
        $xml = $this->cfield_mgr->exportValueAsXML($cfMap);
    }
    return $xml;
 }





  /*
   function: getByDocID
   get req information using document ID as access key.

   args : doc_id:
   [tproject_id]
   [parent_id] -> req spec parent of requirement searched
   default 0 -> case sensivite search

   returns: map.
   key: req spec id
   value: req info, map with following keys:
   id
   doc_id
   testproject_id
   title
   scope
   */
	function getByDocID($doc_id,$tproject_id=null,$parent_id=null, $options = null)
  	{
		$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;

	    $my['options'] = array( 'check_criteria' => '=', 'access_key' => 'id', 
	                            'case' => 'sensitive', 'output' => 'standard');
	    $my['options'] = array_merge($my['options'], (array)$options);
    	
    	   
  		$output=null;
  		$the_doc_id = $this->db->prepare_string(trim($doc_id));
	    switch($my['options']['check_criteria'])
	    {
	    	case '=':
	    	default:
	    		$check_criteria = " = '{$the_doc_id}' ";
	    	break;
	    	
	    	case 'like':
	    		$check_criteria = " LIKE '{$the_doc_id}%' ";
	    	break;
	    }
  		
		$sql = " /* $debugMsg */ SELECT ";
		switch($my['options']['output'])
		{
			case 'standard':
				 $sql .= " REQ.id,REQ.srs_id,REQ.req_doc_id,NH_REQ.name AS title, REQ_SPEC.testproject_id, " .
		       			 " NH_RSPEC.name AS req_spec_title, REQ_SPEC.doc_id AS req_spec_doc_id, NH_REQ.node_order ";
		    break;
		       			 
			case 'minimun':
				 $sql .= " REQ.id,REQ.srs_id,REQ.req_doc_id,NH_REQ.name AS title, REQ_SPEC.testproject_id";
		    break;
			
		}
		$sql .= " FROM {$this->object_table} REQ " .
		       	" /* Get Req info from NH */ " .
		       	" JOIN {$this->tables['nodes_hierarchy']} NH_REQ ON NH_REQ.id = REQ.id " .
		       	" JOIN {$this->tables['req_specs']} REQ_SPEC ON REQ_SPEC.id = REQ.srs_id " .
		       	" JOIN {$this->tables['nodes_hierarchy']} NH_RSPEC ON NH_RSPEC.id = REQ_SPEC.id " .
				" WHERE REQ.req_doc_id {$check_criteria} ";
  		
  		if( !is_null($tproject_id) )
  		{
  			$sql .= " AND REQ_SPEC.testproject_ID={$tproject_id}";
  		}
    	
  		if( !is_null($parent_id) )
  		{
  			$sql .= " AND REQ.srs_id={$parent_id}";
  		}

  		$output = $this->db->fetchRowsIntoMap($sql,$my['options']['access_key']);
  		
  		return $output;
  	}

	/**
	 * Copy a requirement to a new requirement specification
	 * requirement DOC ID will be changed because must be unique inside
	 * MASTER CONTAINER (test project)
	 * 
	 * @param integer $id: requirement ID
	 * @param integer $parent_id: target req spec id (where we want to copy)
	 * @param integer $user_id: who is requesting copy
	 * @param integer $tproject_id: optional, is null will be computed here
	 * @param array $options: map
	 *
	 */
	function copy_to($id,$parent_id,$user_id,$tproject_id=null,$options=null)
	{
	    $new_item = array('id' => -1, 'status_ok' => 0, 'msg' => 'ok', 'mappings' => null);
		$my['options'] = array('copy_also' => null);
	    $my['options'] = array_merge($my['options'], (array)$options);
    
   	    if( is_null($my['options']['copy_also']) )
	    {
	        $my['options']['copy_also'] = array('testcase_assignment' => true);   
	    }

		$root = $tproject_id;
		if( !is_null($root) )
		{
			$reqSpecMgr = new requirement_spec_mgr($this->db);
			$target = $reqSpecMgr->get_by_id($parent_id);
			$root = $target['testproject_id'];
		}
        $target_doc = $this->generateDocID($id,$root);		

		$item_versions = $this->get_by_id($id);
		if($item_versions)
		{
			$new_item = $this->create_req_only($parent_id,$target_doc,$item_versions[0]['title'],
			                                   $item_versions[0]['author_id'],$item_versions[0]['node_order']);
			if ($new_item['status_ok'])
			{
		        $ret['status_ok']=1;
   		        $new_item['mappings'][$id] = $new_item['id'];
		        
	 			foreach($item_versions as $req_version)
				{
					$op = $this->create_version($new_item['id'],$req_version['version'],
					                            $req_version['scope'],$req_version['author_id'],
					                            $req_version['status'],$req_version['type'],
					                            $req_version['expected_coverage']);

	    			$new_item['mappings'][$req_version['id']] = $op['id'];
				}
				
				$this->copy_cfields($id,$new_item['id']);
	        	$this->copy_attachments($id,$new_item['id']);
		    	if( isset($my['options']['copy_also']['testcase_assignment']) &&
		    	    $my['options']['copy_also']['testcase_assignment'] )
				{
	        		$linked_items = $this->get_coverage($id);
            		if( !is_null($linked_items) )
            		{
            			foreach($linked_items as $value)
            			{
            				$this->assign_to_tcase($new_item['id'],$value['id']);
            			}
            		}	            
				}
			}
		}

		return($new_item);
	}


    /**
     * 
     *
     */
	function copy_attachments($source_id,$target_id)
	{
		$this->attachmentRepository->copyAttachments($source_id,$target_id,$this->attachmentTableName);
	}


	/*
	  function: copy_cfields
	            Get all cfields linked to any testcase of this testproject
	            with the values presents for $from_id, testcase we are using as
	            source for our copy.
	
	  args: from_id: source item id
	        to_id: target item id
	
	  returns: -
	
	*/
	function copy_cfields($from_id,$to_id)
	{
	  $cfmap_from=$this->get_linked_cfields($from_id);
	  $cfield=null;
	  if( !is_null($cfmap_from) )
	  {
	    foreach($cfmap_from as $key => $value)
	    {
	      $cfield[$key]=array("type_id"  => $value['type'], "cf_value" => $value['value']);
	    }
	  }
	  $this->cfield_mgr->design_values_to_db($cfield,$to_id,null,'tcase_copy_cfields');
	}



    /**
	 * 
 	 *
 	 */
	function generateDocID($id, $tproject_id)
	{
		$field_size = config_get('field_size');
		$item_info = $this->get_by_id($id);
        $item_info = $item_info[0]; 

		// Check if another req with same DOC ID exists on test project (MASTER CONTAINER),
		// If yes generate a new DOC ID
		$getOptions = array('check_criteria' => 'like', 'access_key' => 'req_doc_id');
		$itemSet = $this->getByDocID($item_info['req_doc_id'],$tproject_id,null,$getOptions);
        
		$target_doc = $item_info['req_doc_id'];
		$instance = 1;
		if( !is_null($itemSet) )
		{
			// req_doc_id has limited size then we need to be sure that generated id will
			// not exceed DB size
    	    $nameSet = array_flip(array_keys($itemSet));
		    // 6 magic from " [xxx]"
		    $prefix = trim_and_limit($item_info['req_doc_id'],$field_size->req_docid-6);
    	    $target_doc = $prefix . " [{$instance}]"; 
    		while( isset($nameSet[$target_doc]) )
    		{
    			$instance++;
    	    	$target_doc = $prefix . " [{$instance}]"; 
    		}
		}
     	return $target_doc;
	}

    /**
 	 * 
     *
     */
	function create_req_only($srs_id,$reqdoc_id,$title,$user_id,$node_order=0)
	{
		$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
		$result = array( 'id' => -1, 'status_ok' => 0, 'msg' => 'ok');
		$req_id = $this->tree_mgr->new_node($srs_id,$this->node_types_descr_id['requirement'],
		                                    $title,$node_order);
		$db_now = $this->db->db_now();
		$sql = "/* $debugMsg */ INSERT INTO {$this->object_table} " .
		       " (id, srs_id, req_doc_id)" .
    	       " VALUES ({$req_id}, {$srs_id},'" . $this->db->prepare_string($reqdoc_id) . "')";
		  	   
    	if (!$this->db->exec_query($sql))
    	{
		 	  $result['msg'] = lang_get('error_inserting_req');
		}
		else
		{
			$result = array( 'id' => $req_id, 'status_ok' => 1, 'msg' => 'ok');
		}
    	return $result;
    }

	/*
	  function: create_version
	
	  args:
	
	  returns:
	
	  rev: 20080113 - franciscom - interface changes added tc_ext_id
	
	*/
	function create_version($id,$version,$scope, $user_id, $status = TL_REQ_STATUS_VALID, 
	                        $type = TL_REQ_TYPE_INFO, $expected_coverage=1)
	{
		$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
		$item_id = $this->tree_mgr->new_node($id,$this->node_types_descr_id['requirement_version']);
	    
		$sql = "/* $debugMsg */ INSERT INTO {$this->tables['req_versions']} " .
		       " (id,version,scope,status,type,expected_coverage,author_id,creation_ts) " . 
	  	       " VALUES({$item_id},{$version},'" . $this->db->prepare_string($scope) . "','" . 
	  	       $this->db->prepare_string($status) . "','" . $this->db->prepare_string($type) . "'," .
	  	       "{$expected_coverage},{$user_id}," . $this->db->db_now() . ")";
	  	       
		$result = $this->db->exec_query($sql);
		$ret = array( 'msg' => 'ok', 'id' => $item_id, 'status_ok' => 1);
		if (!$result)
		{
			$ret['msg'] = $this->db->error_msg();
		  	$ret['status_ok']=0;
		  	$ret['id']=-1;
		}
		return $ret;
	}
	
	/*
	  function: create_new_version()
	            create a new version, doing a copy of last version.
	
	  args : $id: requirement id
	         $user_id: who is doing this operation.
	
	  returns:
	          map:  id: node id of created tcversion
	                version: version number (i.e. 5)
	                msg
	
	  rev: 
	*/
	function create_new_version($id,$user_id)
	{
	  // get a new id
	  $version_id = $this->tree_mgr->new_node($id,$this->node_types_descr_id['requirement_version']);
	  $last_version_info =  $this->get_last_version_info($id);
	  $this->copy_version($last_version_info['id'],$version_id,$last_version_info['version']+1,$user_id);
	
	  $ret['id'] = $version_id;
	  $ret['version'] = $last_version_info['version']+1;
	  $ret['msg'] = 'ok';
	  return $ret;
	}


    /**
	 * 
 	 *
     */
	function get_last_version_info($id)
	{
		$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
		$info = null;
	
		$sql = " /* $debugMsg */ SELECT MAX(version) AS version " .
		       " FROM {$this->tables['req_versions']} REQV," .
		       " {$this->tables['nodes_hierarchy']} NH WHERE ".
		       " NH.id = REQV.id ".
		       " AND NH.parent_id = {$id} ";
	
		$max_version = $this->db->fetchFirstRowSingleColumn($sql,'version');
		if ($max_version)
		{
			$sql = "/* $debugMsg */ SELECT REQV.* FROM {$this->tables['req_versions']} REQV," .
			       " {$this->tables['nodes_hierarchy']} NH ".
			       " WHERE version = {$max_version} AND NH.id = REQV.id AND NH.parent_id = {$id}";
	
			$info = $this->db->fetchFirstRow($sql);
		}
		return $info;
	}

    /**
	 * 
 	 *
     */
	function copy_version($from_version_id,$to_version_id,$as_version_number,$user_id)
	{
		
		$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
	    $now = $this->db->db_now();
	    $sql="/* $debugMsg */ INSERT INTO {$this->tables['req_versions']} " .
	         " (id,version,author_id,creation_ts,scope,status,type,expected_coverage) " .
	         " SELECT {$to_version_id} AS id, {$as_version_number} AS version, " .
	         "        {$user_id} AS author_id, {$now} AS creation_ts," .
	         "        scope,status,type,expected_coverage " .
	         " FROM {$this->tables['req_versions']} " .
	         " WHERE id={$from_version_id} ";
	    $result = $this->db->exec_query($sql);
	}

    /**
	 * 
 	 *
     */
	function updateOpen($reqVersionID,$value)
	{
		$this->updateBoolean($reqVersionID,'is_open',$value);
	}	

    /**
	 * 
 	 *
     */
	function updateActive($reqVersionID,$value)
	{
		$this->updateBoolean($reqVersionID,'active',$value);
	}	

    /**
	 * 
 	 *
     */
	private function updateBoolean($reqVersionID,$field,$value)
	{
		$booleanValue = $value;
	    if( is_bool($booleanValue) )
	    {
	    	$booleanValue = $booleanValue ? 1 : 0;
	    }
		else if( !is_numeric($booleanValue) || is_null($booleanValue))
		{
			$booleanValue = 1;
		}
		$booleanValue = $booleanValue > 0 ? 1 : 0;
		$debugMsg = 'Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__;
		$sql = "/* $debugMsg */ UPDATE {$this->tables['req_versions']} " .
  		       " SET {$field}={$booleanValue} WHERE id={$reqVersionID}";
	
	    $result = $this->db->exec_query($sql);
	   
	}	


	/**
	 * get relations for a given requirement ID
	 * 
	 * @author Andreas Simon
	 * 
	 * @param int $id Requirement ID
	 * 
	 * @return array $relations in which this req is either source or destination
	 */
	public function get_relations($id) 
	{
		
		$debugMsg = '/* Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__ . ' */';
		$relations = array();
		$relations['num_relations'] = 0;
	    $relations['req'] = current($this->get_by_id($id));
		$relations['relations'] = array();

		$tproject_mgr = new testproject($this->db);
		$interproject_linking = config_get('req_cfg')->relations->interproject_linking;

		$sql = " $debugMsg SELECT id, source_id, destination_id, relation_type, author_id, creation_ts " . 
			   " FROM {$this->tables['req_relations']} " .
			   " WHERE source_id=$id OR destination_id=$id " .
			   " ORDER BY id ASC ";
   
    	$relations['relations']= $this->db->get_recordset($sql);  
    	
    	if( !is_null($relations['relations']) && count($relations['relations']) > 0 )
    	{
    		$labels = $this->get_all_relation_labels();
			$label_keys = array_keys($labels);
    		foreach($relations['relations'] as $key => $rel) {
        	
    			// is this relation type is configured?
    			if( ($relTypeAllowed = in_array($rel['relation_type'],$label_keys)) ) 
    			{ 
	    			$relations['relations'][$key]['source_localized'] = $labels[$rel['relation_type']]['source'];
	    			$relations['relations'][$key]['destination_localized'] = $labels[$rel['relation_type']]['destination'];
	    			
	    			if ($id == $rel['source_id']) {
	    				$type_localized = 'source_localized';
	    				$other_key = 'destination_id';
	    			} else {
	    				$type_localized = 'destination_localized';
	    				$other_key = 'source_id';
	    			}
	    			$relations['relations'][$key]['type_localized'] = $relations['relations'][$key][$type_localized];
	    			$other_req = $this->get_by_id($rel[$other_key]);
			    		    		
	    			// only add it, if either interproject linking is on or if it is in the same project
	    			$relTypeAllowed = false;
	    			if ($interproject_linking || ($other_req[0]['testproject_id'] == $relations['req']['testproject_id'])) {
	    			
	    				$relTypeAllowed = true;
			    		$relations['relations'][$key]['related_req'] = $other_req[0];
			    		$other_tproject = $tproject_mgr->get_by_id($other_req[0]['testproject_id']);
			    		$relations['relations'][$key]['related_req']['testproject_name'] = $other_tproject['name'];
			    		
			    		$user = tlUser::getByID($this->db,$rel['author_id']);
			    		$relations['relations'][$key]['author'] = $user->getDisplayName();
	    			} 
    			} 
    			
    			if( !$relTypeAllowed )
    			{
    				unset($relations['relations'][$key]);
    			}
    			   		
    		} // end foreach
    		
    		$relations['num_relations'] = count($relations['relations']);
		}
		return $relations;
	}
	
	
	/**
	 * checks if there is a relation of a given type between two requirements
	 * 
	 * @author Andreas Simon
	 * 
	 * @param integer $first_id requirement ID to check
	 * @param integer $second_id another requirement ID to check
	 * @param integer $rel_type_id relation type ID to check
	 * 
	 * @return true, if relation already exists, false if not
	 */
	public function check_if_relation_exists($first_id, $second_id, $rel_type_id) {
		
		$debugMsg = '/* Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__ . ' */';
		$sql = " $debugMsg SELECT COUNT(0) AS qty " .
			   " FROM {$this->tables['req_relations']} " .
			   " WHERE ((source_id=$first_id AND destination_id=$second_id) " . 
			   " OR (source_id=$second_id AND destination_id=$first_id)) " . 
			   " AND relation_type=$rel_type_id";
		$rs = $this->db->get_recordset($sql);
    	return($rs[0]['qty'] > 0);
	}
	
	
	/**
	 * Get count of all relations for a requirement, no matter if it is source or destination
	 * or what type of relation it is.
	 * 
	 * @author Andreas Simon
	 * 
	 * @param integer $id requirement ID to check
	 * 
	 * @return integer $count
	 */
	public function count_relations($id) {
		
		$debugMsg = '/* Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__ . ' */';
		$sql = " $debugMsg SELECT COUNT(*) AS qty " .
			   " FROM {$this->tables['req_relations']} " .
			   " WHERE source_id=$id OR destination_id=$id ";
		$rs = $this->db->get_recordset($sql);
    	return($rs[0]['qty']);
	}
	
	
	/**
	 * add a relation of a given type between two requirements
	 * 
	 * @author Andreas Simon
	 * 
	 * @param integer $source_id ID of source requirement
	 * @param integer $destination_id ID of destination requirement
	 * @param integer $type_id relation type ID to set
	 * @param integer $author_id user's ID
	 */
	public function add_relation($source_id, $destination_id, $type_id, $author_id) {
		
		$debugMsg = '/* Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__ . ' */';
		$time = $this->db->db_now();
		$sql = " $debugMsg INSERT INTO {$this->tables['req_relations']} "	. 
			   " (source_id, destination_id, relation_type, author_id, creation_ts) " .
			   " values ($source_id, $destination_id, $type_id, $author_id, $time)";
		$this->db->exec_query($sql);
	}
	
	
	/**
	 * delete an existing relation with between two requirements
	 * 
	 * @author Andreas Simon
	 * 
	 * @param int $id requirement relation id
	 */
	public function delete_relation($id) {
		
		$debugMsg = '/* Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__ . ' */';
		$sql = " $debugMsg DELETE FROM {$this->tables['req_relations']} WHERE id=$id ";
		$this->db->exec_query($sql);
	}
	
	
	/**
	 * delete all existing relations for (from or to) a given req id, no matter which project
	 * they belong to or which other requirement they are related to
	 * 
	 * @author Andreas Simon
	 * 
	 * @param int $id requirement ID (can be array of IDs)
	 */
	public function delete_all_relations($id) {
		
		$debugMsg = '/* Class:' . __CLASS__ . ' - Method: ' . __FUNCTION__ . ' */';
		$id_list = implode(",", (array)$id);
		$sql = " $debugMsg DELETE FROM {$this->tables['req_relations']} " . 
			   " WHERE source_id IN ($id_list) OR destination_id IN ($id_list) ";
		$this->db->exec_query($sql);
	}
	
	
	/**
	 * initialize the requirement relation labels
	 * 
	 * @author Andreas Simon
	 * 
	 * @return array $labels a map with all labels in following form:
	 *		Array
	 *		(
	 *			    [1] => Array
	 *			        (
	 *			            [source] => parent of
	 *			            [destination] => child of
	 *			        )
	 *			    [2] => Array
	 *			        (
	 *			            [source] => blocks
	 *			            [destination] => depends on
	 *			        )
	 *			    [3] => Array
	 *			        (
	 *			            [source] => related to
	 *			            [destination] => related to
	 *			        )
	 *			)
	 */
	public static function get_all_relation_labels() {
		
		$labels = config_get('req_cfg')->rel_type_labels;
		
		foreach ($labels as $key => $label) {
			$labels[$key] = init_labels($label);
		}
		
		return $labels;
	}
	
	
	/**
	 * Initializes the select field for the localized requirement relation types.
	 * 
	 * @author Andreas Simon
	 * 
	 * @return array $htmlSelect info needed to create select box on multiple templates
	 */
	function init_relation_type_select() {
		
		$htmlSelect = array('items' => array(), 'selected' => null, 'equal_relations' => array());
		$labels = $this->get_all_relation_labels();
		
		foreach ($labels as $key => $lab) {
			$htmlSelect['items'][$key . "_source"] = $lab['source'];
			if ($lab['source'] != $lab['destination']) {
				// relation is not equal as labels for source and dest are different
				$htmlSelect['items'][$key . "_destination"] = $lab['destination']; 
			} else {
				// mark this as equal relation - no parent/child, makes searching simpler
				$htmlSelect['equal_relations'][] = $key . "_source"; 
			}
		}
		
		// set "related to" as default preselected value in forms
		if (defined('TL_REQ_REL_TYPE_RELATED') && isset($htmlSelect[TL_REQ_REL_TYPE_RELATED . "_source"])) {
			$selected_key = TL_REQ_REL_TYPE_RELATED . "_source";
		} else {
			// "related to" is not configured, so take last element as selected one
			$keys = array_keys($htmlSelect['items']);
			$selected_key = end($keys);
		}
		$htmlSelect['selected'] = $selected_key;
		
		return $htmlSelect;
	}
} // class end
?>
Back to Top