File: Artifact.class.php

package info (click to toggle)
fusionforge 5.3.2%2B20141104-3
  • links: PTS, VCS
  • area: main
  • in suites: jessie-kfreebsd
  • size: 60,472 kB
  • sloc: php: 271,846; sql: 36,817; python: 14,575; perl: 6,406; sh: 5,980; xml: 4,294; pascal: 1,411; makefile: 911; cpp: 52; awk: 27
file content (1985 lines) | stat: -rw-r--r-- 59,707 bytes parent folder | download | duplicates (3)
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
<?php
/**
 * FusionForge trackers
 *
 * Copyright 1999-2001, VA Linux Systems, Inc.
 * Copyright 2002-2004, GForge, LLC
 * Copyright 2009, Roland Mas
 * Copyright (C) 2009-2013 Alain Peyrat, Alcatel-Lucent
 * Copyright 2012, Thorsten “mirabilos” Glaser <t.glaser@tarent.de>
 * Copyright 2014, Franck Villaume - TrivialDev
 *
 * This file is part of FusionForge. FusionForge is free software;
 * you can redistribute it and/or modify it under the terms of the
 * GNU General Public License as published by the Free Software
 * Foundation; either version 2 of the Licence, or (at your option)
 * any later version.
 *
 * FusionForge is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along
 * with FusionForge; if not, write to the Free Software Foundation, Inc.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

/*
 * Standard Alcatel-Lucent disclaimer for contributing to open source
 *
 * "The Artifact ("Contribution") has not been tested and/or
 * validated for release as or in products, combinations with products or
 * other commercial use. Any use of the Contribution is entirely made at
 * the user's own responsibility and the user can not rely on any features,
 * functionalities or performances Alcatel-Lucent has attributed to the
 * Contribution.
 *
 * THE CONTRIBUTION BY ALCATEL-LUCENT IS PROVIDED AS IS, WITHOUT WARRANTY
 * OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE
 * WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, COMPLIANCE,
 * NON-INTERFERENCE AND/OR INTERWORKING WITH THE SOFTWARE TO WHICH THE
 * CONTRIBUTION HAS BEEN MADE, TITLE AND NON-INFRINGEMENT. IN NO EVENT SHALL
 * ALCATEL-LUCENT BE LIABLE FOR ANY DAMAGES OR OTHER LIABLITY, WHETHER IN
 * CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 * CONTRIBUTION OR THE USE OR OTHER DEALINGS IN THE CONTRIBUTION, WHETHER
 * TOGETHER WITH THE SOFTWARE TO WHICH THE CONTRIBUTION RELATES OR ON A STAND
 * ALONE BASIS."
 */
require_once $gfcommon.'include/Error.class.php';
require_once $gfcommon.'tracker/ArtifactMessage.class.php';
require_once $gfcommon.'tracker/ArtifactExtraField.class.php';
require_once $gfcommon.'tracker/ArtifactWorkflow.class.php';
require_once $gfcommon.'tracker/ArtifactStorage.class.php';

// This string is used when sending the notification mail for identifying the
// user response
define('ARTIFACT_MAIL_MARKER', '#+#+#+#+#+#+#+#+#+#+#+#+#+#+#+#+#+');

/**
 * Factory method which creates an Artifact from an artifact ID
 *
 * @param	int		$artifact_id	The artifact ID
 * @param	array|bool	$data		The result array, if it's passed in
 * @return	Artifact	Artifact object
 */
function &artifact_get_object($artifact_id,$data=false) {
	global $ARTIFACT_OBJ;
	if (!isset($ARTIFACT_OBJ["_".$artifact_id."_"])) {
		if ($data) {
			//the db result handle was passed in
		} else {
			$res = db_query_params ('SELECT * FROM artifact_vw WHERE artifact_id=$1',
						array ($artifact_id)) ;
			if (db_numrows($res) <1 ) {
				$ARTIFACT_OBJ["_".$artifact_id."_"]=false;
				return false;
			}
			$data = db_fetch_array($res);
		}
		$ArtifactType =& artifactType_get_object($data["group_artifact_id"]);
		$ARTIFACT_OBJ["_".$artifact_id."_"]= new Artifact($ArtifactType,$data);
	}
	return $ARTIFACT_OBJ["_".$artifact_id."_"];
}

class Artifact extends Error {

	/**
	 * Resource ID.
	 *
	 * @var	int	$status_res.
	 */
	var $status_res;

	/**
	 * Artifact Type object.
	 *
	 * @var	object	$ArtifactType.
	 */
	var $ArtifactType;

	/**
	 * Array of artifact data.
	 *
	 * @var	array	$data_array.
	 */
	var $data_array;

	/**
	 * Array of artifact data for extra fields defined by Admin.
	 *
	 * @var	array	$extra_field_data.
	 */
	var $extra_field_data;

	/**
	 * Array of ArtifactFile objects.
	 *
	 * @var	array	$files
	 */
	var $files;

	/**
	 * Database result set of related tasks
	 *
	 * @var	result	$relatedtasks
	 */
	var $relatedtasks;

	/**
	 * cached return value of getVotes
	 * @var	int|bool	$votes
	 */
	var $votes = false;

	/**
	 * Artifact - constructor.
	 *
	 * @param	ArtifactType	$ArtifactType	The ArtifactType object.
	 * @param	int|bool	$data		(primary key from database OR complete assoc array)
	 *						ONLY OPTIONAL WHEN YOU PLAN TO IMMEDIATELY CALL ->create()
	 */
	function __construct(&$ArtifactType, $data=false) {
		$this->Error();

		$this->ArtifactType =& $ArtifactType;

		// Was ArtifactType legit?
		if (!$ArtifactType || !is_object($ArtifactType)) {
			$this->setError(_('Invalid Artifact Type'));
			return;
		}

		// Did ArtifactType have an error?
		if ($ArtifactType->isError()) {
			$this->setError($ArtifactType->getErrorMessage());
			return;
		}

		// Make sure this person has permission to view artifacts
		if (!forge_check_perm ('tracker', $this->ArtifactType->getID(), 'read')) {
			$this->setError(_('Only project members can view private artifact types'));
			return;
		}

		if ($data) {
			if (is_array($data)) {
				$this->data_array =& $data;
			} else {
				$this->fetchData($data);
			}
		}
	}

	/**
	 * create - construct a new Artifact in the database.
	 *
	 * @param	string	$summary	The artifact summary.
	 * @param	string	$details	Details of the artifact.
	 * @param	int	$assigned_to	The ID of the user to which this artifact is to be assigned.
	 * @param	int	$priority	The artifacts priority.
	 * @param	array	$extra_fields	Array of extra fields like: array(15=>'foobar',22=>'1');
	 * @param	array	$importData	Array of data to change submitter and time of submit like:
	 *						array('user' => 127, 'time' => 1234556789)
	 * @return	bool	id on success / false on failure.
	 */
	function create( $summary, $details, $assigned_to=100, $priority=3, $extra_fields=array(), $importData = array()) {
		//
		//	make sure this person has permission to add artifacts
		//

		//
		//	get the user_id
		//
		if(array_key_exists('user', $importData)){
				$user = $importData['user'];
		} else {
			if (!forge_check_perm ('tracker',$this->ArtifactType->getID(),'submit')) {
					$this->setError(_('You are not currently allowed to submit items to this tracker.'));
					return false;
			}

			if (session_loggedin()) {
				$user=user_getid();
			} else {
				$user=100;
			}
		}

		//
		//	data validation
		//
		if (!$summary) {
			$this->setError(_('Message Summary Is Required'));
			return false;
		}
		if (!$details) {
			$this->setError(_('Message Body Is Required'));
			return false;
		}
		if (!$assigned_to) {
			$assigned_to=100;
		}
		if (!$priority) {
			$priority=3;
		}
//		if (!$status_id) {
			$status_id=1;		// on creation, status is set to "open"
//		}
		//
		//	They may be using an extra field "status" box so we have to remap
		//	the status_id based on the extra field - this keeps the counters
		//	accurate
		//
		$status_id = $this->ArtifactType->remapStatus($status_id,$extra_fields);
		if (!$status_id) {
			$this->setError(_('Error remapping status'));
			return false;
		}

		db_begin();
		if (array_key_exists('time',$importData)){
			$time = $importData['time'];
		} else {
			$time = time();
		}
		$res = db_query_params ('INSERT INTO artifact
			(group_artifact_id,status_id,priority,
			submitted_by,assigned_to,open_date,summary,details)
			VALUES ($1,$2,$3,$4,$5,$6,$7,$8)',
					array ($this->ArtifactType->getID(),
					       $status_id,
					       $priority,
					       $user,
					       $assigned_to,
					       $time,
					       htmlspecialchars($summary),
					       htmlspecialchars($details))) ;
		if (!$res) {
			$this->setError(db_error());
			db_rollback();
			return false;
		}

		$artifact_id=db_insertid($res,'artifact','artifact_id');

		if (!$res || !$artifact_id) {
			$this->setError(db_error());
			db_rollback();
			return false;
		} else {
			//
			//	Now set up our internal data structures
			//
			if (!$this->fetchData($artifact_id)) {
				db_rollback();
				return false;
			} else {
				// the changes to the extra fields will be logged in this array.
				// (we won't use it however)
				$extra_field_changes = array();
				if (!$this->updateExtraFields($extra_fields,$extra_field_changes)) {
					db_rollback();
					return false;
				}
			}
			//
			//	now send an email if appropriate
			//
			$this->mailFollowupEx(0, 1);
			db_commit();

			return $artifact_id;
		}
	}

	/**
	 * fetchData - re-fetch the data for this Artifact from the database.
	 *
	 * @param	int	$artifact_id	The artifact ID.
	 * @return	boolean	success.
	 */
	function fetchData($artifact_id) {
		$this->votes = false;
		$res = db_query_params ('SELECT * FROM artifact_vw WHERE artifact_id=$1 AND group_artifact_id=$2',
					array ($artifact_id,
					       $this->ArtifactType->getID())) ;
		if (!$res || db_numrows($res) < 1) {
			$this->setError(_('Invalid Artifact ID'));
			return false;
		}
		$this->data_array = db_fetch_array($res);
		db_free_result($res);
		return true;
	}

	/**
	 * getArtifactType - get the ArtifactType Object this Artifact is associated with.
	 *
	 * @return	object	ArtifactType.
	 */
	function &getArtifactType() {
		return $this->ArtifactType;
	}

	/**
	 * getID - get this ArtifactID.
	 *
	 * @return	int	The artifact_id #.
	 */
	function getID() {
		return $this->data_array['artifact_id'];
	}

	/**
	 * getStringID - get a string display for this ArtifactID.
	 *
	 * @return	string	The artifact_id #.
	 */
	function getStringID() {
		return '[#'.$this->data_array['artifact_id'].']';
	}

	/**
	 * getStatusID - get open/closed/deleted flag.
	 *
	 * @return	int	Status: (1) Open, (2) Closed, (3) Deleted.
	 */
	function getStatusID() {
		return $this->data_array['status_id'];
	}

	/**
	 * getStatusName - get open/closed/deleted text.
	 *
	 * @return	string	The status name.
	 */
	function getStatusName() {
		return $this->data_array['status_name'];
	}

	/**
	 * getCustomStatusName - get custom status value text.
	 *
	 * @return	string	The custom status name.
	 */
	function getCustomStatusName() {
		$custom_status_id = $this->ArtifactType->getCustomStatusField();
		if ($custom_status_id) {
			$result = db_query_params ('SELECT element_name FROM artifact_extra_field_elements aefe, artifact_extra_field_data aefd
										WHERE artifact_id=$1 AND aefd.extra_field_id=$2 AND CAST(aefd.field_data AS INTEGER)=aefe.element_id',
								array ($this->getID(), $custom_status_id)) ;
			if ($result) {
				return db_result($result, 0, 'element_name');
			}
		}
		return $this->data_array['status_name'];
	}

	/**
	 * getPriority - get priority flag.
	 *
	 * @return	int	priority.
	 */
	function getPriority() {
		return $this->data_array['priority'];
	}

	/**
	 * getSubmittedBy - get ID of submitter.
	 *
	 * @return	int	user_id of submitter.
	 */
	function getSubmittedBy() {
		return $this->data_array['submitted_by'];
	}

	/**
	 * getSubmittedEmail - get email of submitter.
	 *
	 * @return	string	The email of submitter.
	 */
	function getSubmittedEmail() {
		return $this->data_array['submitted_email'];
	}

	/**
	 * getSubmittedRealName - get real name of submitter.
	 *
	 * @return	string	The real name of submitter.
	 */
	function getSubmittedRealName() {
		return $this->data_array['submitted_realname'];
	}

	/**
	 * getSubmittedUnixName - get login name of submitter.
	 *
	 * @return	string	The unix name of submitter.
	 */
	function getSubmittedUnixName() {
		return $this->data_array['submitted_unixname'];
	}

	/**
	 * getAssignedTo - get ID of assignee.
	 *
	 * @return	int	user_id of assignee.
	 */
	function getAssignedTo() {
		return $this->data_array['assigned_to'];
	}

	/**
	 * getAssignedEmail - get email of assignee.
	 *
	 * @return	string	The email of assignee.
	 */
	function getAssignedEmail() {
		return $this->data_array['assigned_email'];
	}

	/**
	 * getAssignedRealName - get real name of assignee.
	 *
	 * @return	string	The real name of assignee.
	 */
	function getAssignedRealName() {
		return $this->data_array['assigned_realname'];
	}

	/**
	 * getAssignedUnixName - get login name of assignee.
	 *
	 * @return	string	The unix name of assignee.
	 */
	function getAssignedUnixName() {
		return $this->data_array['assigned_unixname'];
	}

	/**
	 * getOpenDate - get unix time of creation.
	 *
	 * @return	int	unix time.
	 */
	function getOpenDate() {
		return $this->data_array['open_date'];
	}

	/**
	 * getCloseDate - get unix time of closure.
	 *
	 * @return	int	unix time.
	 */
	function getCloseDate() {
		return $this->data_array['close_date'];
	}

	/**
	 * getLastModifiedDate - the last_modified_date of this task.
	 *
	 * @return	int	 the last_modified_date.
	 */
	function getLastModifiedDate() {
		return $this->data_array['last_modified_date'];
	}

	/**
	 * getSummary - get text summary of artifact.
	 *
	 * @return	string	The summary (subject).
	 */
	function getSummary() {
		return $this->data_array['summary'];
	}

	/**
	 * getDetails - get text body (message) of artifact.
	 *
	 * @return	string	The body (message).
	 */
	function getDetails() {
		return $this->data_array['details'];
	}

	/**
	 * delete - delete this tracker and all its related data.
	 *
	 * @param	bool	$sure I'm Sure.
	 * @return	bool	true/false;
	 */
	function delete($sure) {
		if (!$sure) {
			$this->setMissingParamsError(_('Please tick all checkboxes.'));
			return false;
		}
		if (!forge_check_perm ('tracker_admin', $this->ArtifactType->Group->getID())) {
			$this->setPermissionDeniedError();
			return false;
		}
		db_begin();
		$res = db_query_params ('DELETE FROM artifact_extra_field_data WHERE artifact_id=$1',
					array ($this->getID())) ;
		if (!$res) {
			$this->setError(_('Error deleting extra field data: ').db_error());
			db_rollback();
			return false;
		}

		ArtifactStorage::instance()->deleteFromQuery('SELECT id FROM artifact_file WHERE artifact_id=$1',
					array ($this->getID())) ;

		$res = db_query_params ('DELETE FROM artifact_file WHERE artifact_id=$1',
					array ($this->getID())) ;
		if (!$res) {
			$this->setError(_('Error deleting file from db: ').db_error());
			db_rollback();
			ArtifactStorage::instance()->rollback();
			return false;
		}
		$res = db_query_params ('DELETE FROM artifact_message WHERE artifact_id=$1',
					array ($this->getID())) ;
		if (!$res) {
			$this->setError(_('Error deleting message: ').db_error());
			db_rollback();
			ArtifactStorage::instance()->rollback();
			return false;
		}
		$res = db_query_params ('DELETE FROM artifact_history WHERE artifact_id=$1',
					array ($this->getID())) ;
		if (!$res) {
			$this->setError(_('Error deleting history: ').db_error());
			db_rollback();
			ArtifactStorage::instance()->rollback();
			return false;
		}
		$res = db_query_params ('DELETE FROM artifact_monitor WHERE artifact_id=$1',
					array ($this->getID())) ;
		if (!$res) {
			$this->setError(_('Error deleting monitor: ').db_error());
			db_rollback();
			ArtifactStorage::instance()->rollback();
			return false;
		}
		$res = db_query_params ('DELETE FROM artifact WHERE artifact_id=$1',
					array ($this->getID())) ;
		if (!$res) {
			$this->setError(_('Error deleting artifact: ').db_error());
			db_rollback();
			ArtifactStorage::instance()->rollback();
			return false;
		}

		if ($this->getStatusID() == 1) {
			$res = db_query_params ('UPDATE artifact_counts_agg SET count=count-1,open_count=open_count-1
				WHERE group_artifact_id=$1',
						array ($this->getID())) ;
			if (!$res) {
				$this->setError(_('Error updating artifact counts: ').db_error());
				db_rollback();
				ArtifactStorage::instance()->rollback();
				return false;
			}
		} elseif ($this->getStatusID() == 2) {
			$res = db_query_params ('UPDATE artifact_counts_agg SET count=count-1
				WHERE group_artifact_id=$1',
						array ($this->getID())) ;
			if (!$res) {
				$this->setError(_('Error updating artifact counts: ').db_error());
				db_rollback();
				ArtifactStorage::instance()->rollback();
				return false;
			}
		}

		db_commit();
		ArtifactStorage::instance()->commit();
		return true;
	}

	/**
	 * setMonitor - user can monitor this artifact.
	 *
	 * @return	bool	Always false - always use the getErrorMessage() for feedback
	 */
	function setMonitor() {
		if (session_loggedin()) {
			$user_id=user_getid();
		} else {
			$this->setError(_('Valid Email Address Required'));
			return false;
		}

		$res = db_query_params ('SELECT * FROM artifact_monitor WHERE artifact_id=$1 AND user_id=$2',
					array ($this->getID(),
					       $user_id)) ;

		if (!$res || db_numrows($res) < 1) {
			//not yet monitoring
			$res = db_query_params ('INSERT INTO artifact_monitor (artifact_id,user_id) VALUES ($1,$2)',
						array ($this->getID(),
						       $user_id)) ;
			if (!$res) {
				$this->setError(db_error());
				return false;
			} else {
				$this->setError(_('Monitoring Started'));
				return false;
			}
		} else {
			//already monitoring - remove their monitor
			db_query_params ('DELETE FROM artifact_monitor
				WHERE artifact_id=$1
				AND user_id=$2',
					 array ($this->getID(),
						$user_id)) ;
			$this->setError(_('Monitoring Stopped'));
			return false;
		}
	}

	function isMonitoring() {
		if (!session_loggedin()) {
			return false;
		}
		$result = db_query_params ('SELECT count(*) AS count FROM artifact_monitor WHERE user_id=$1 AND artifact_id=$2',
					   array (user_getid(),
						  $this->getID())) ;
		$row_count = db_fetch_array($result);
		return $result && $row_count['count'] > 0;
	}

	/**
	 * getMonitorIds - array of email addresses monitoring this Artifact.
	 *
	 * @return	array of email addresses monitoring this Artifact.
	 */
	function getMonitorIds() {
		$res = db_query_params ('SELECT user_id	FROM artifact_monitor WHERE artifact_id=$1',
					array ($this->getID())) ;
		return array_unique(array_merge($this->ArtifactType->getMonitorIds(),util_result_column_to_array($res)));
	}

	/**
	 * getHistory - returns a result set of audit trail for this support request.
	 *
	 * @return	resource result set.
	 */
	function getHistory() {
		return db_query_params ('SELECT * FROM artifact_history_user_vw WHERE artifact_id=$1 ORDER BY entrydate DESC, id ASC',
					array ($this->getID())) ;
	}

	/**
	 * getMessages - get the list of messages attached to this artifact.
	 *
	 * @param	string		$order
	 * @return	resource	result set.
	 */
	function getMessages($ascending='up') {
		/*
		 * This is necessary because someone committed a change
		 * to this method in FusionForge trunk that accepts 'up'
		 * as default (luckily, it’s the same!) and 'down' as
		 * alternative probability, whereas FusionForge 5.2 has
		 * false as default and true for ascending order, so we
		 * need to check this out and use === to be sure ☹
		 */
		if ($ascending === 'up') {
			$order = 'DESC';
		} elseif ($ascending === true) {
			$order = 'ASC';
		} elseif ($ascending === false) {
			$order = 'DESC';
		} else {
			$order = 'ASC';
		}
		return db_query_params('SELECT * FROM artifact_message_user_vw WHERE artifact_id=$1 ORDER BY adddate ' . $order . ', id ASC',
		    array($this->getID()));
	}

	/**
	 * getMessage - get a message attached to this artifact.
	 *
	 * @param	int		$msg_id id of the message.
	 * @access	public
	 * @return	resource	database result set.
	 */
	function getMessage($msg_id) {
		if (!$msg_id) {
			return false;
		}
		return db_query_params ('SELECT * FROM artifact_message_user_vw WHERE id=$1',
			array($msg_id));
	}

	/**
	 * getMessageObjects - get an array of message objects.
	 *
	 * @return	array Of ArtifactMessage objects.
	 */
	function &getMessageObjects() {
		$res=$this->getMessages();
		$return = array();
		while ($arr = db_fetch_array($res)) {
			//$return[]=new ArtifactMessage($arr['artifact_id'],$arr);
			$return[] = new ArtifactMessage($this, $arr);
		}
		return $return;
	}

	/**
	 * getFiles - get array of ArtifactFile's.
	 *
	 * @return	array of ArtifactFile's.
	 */
	function &getFiles() {
		if (!isset($this->files)) {
			$res = db_query_params ('SELECT id,artifact_id,description,filename,filesize,' .
					'filetype,adddate,submitted_by,user_name,realname
					 FROM artifact_file_user_vw WHERE artifact_id=$1',
						array ($this->getID())) ;
			$rows=db_numrows($res);
			if ($rows > 0) {
				for ($i=0; $i < $rows; $i++) {
					$this->files[$i]=new ArtifactFile($this,db_fetch_array($res));
				}
			} else {
				$this->files=array();
			}
		}
		return $this->files;
	}

	/**
	 * getRelatedTasks - get array of related tasks
	 *
	 * @return	resource	Database result set
	 */
	function getRelatedTasks() {
		if (!$this->relatedtasks) {
			$this->relatedtasks = db_query_params ('SELECT pt.group_project_id,pt.project_task_id,pt.summary,pt.start_date,pt.end_date,pgl.group_id,pt.status_id,pt.percent_complete,ps.status_name
			FROM project_task pt, project_group_list pgl, project_status ps
			WHERE pt.group_project_id = pgl.group_project_id
                        AND ps.status_id = pt.status_id
                        AND EXISTS (SELECT project_task_id FROM project_task_artifact
				WHERE project_task_id=pt.project_task_id
				AND artifact_id = $1)',
							       array ($this->getID())) ;
		}
		return $this->relatedtasks;
	}

	/**
	 * addMessage - attach a text message to this Artifact.
	 *
	 * @param	string	$body		The $string message being attached.
	 * @param	bool	$by		Email $string address of message creator.
	 * @param	bool	$send_followup	Whether $bool to email out a followup.
	 * @return	bool	success.
	 */
	function addMessage($body,$by=false,$send_followup=false) {
		if (!$body) {
			$this->setMissingParamsError();
			return false;
		}
		if (!forge_check_perm ('tracker',$this->ArtifactType->getID(),'submit')) {
			$this->setError(_('You are not currently allowed to submit items to this tracker.'));
			return false;
		}
		if (session_loggedin()) {
			$user_id=user_getid();
			$user = user_get_object($user_id);
			if (!$user || !is_object($user)) {
				$this->setError('Error: Logged In User But Could Not Get User Object');
				return false;
			}
			//	we'll store this email even though it will likely never be used -
			//	since we have their correct user_id, we can join the USERS table to get email
			$by=$user->getEmail();
		} else {
			$user_id=100;
			if (!$by || !validate_email($by)) {
				$this->setMissingParamsError();
				return false;
			}
		}

		$now = time();
		$res = db_query_params ('INSERT INTO artifact_message (artifact_id,submitted_by,from_email,adddate,body) VALUES ($1,$2,$3,$4,$5)',
					array ($this->getID(),
					       $user_id,
					       $by,
					       $now,
					       htmlspecialchars($body))) ;

		$this->updateLastModifiedDate();

		if ($send_followup) {
			$this->mailFollowupEx($now, 2, false);
		}
		return $res;
	}

	/**
	 * addHistory - add an entry to audit trail.
	 *
	 * @param	string	$field_name	The name of the field in the database being modified.
	 * @param	string	$old_value	The former value of this field.
	 * @param	array	$importData	Array of data to change submitter and time of submit like:
	 *						array('user' => 127, 'time' => 1234556789)
	 * @access	private
	 * @return	boolean	success.
	 */
	function addHistory($field_name,$old_value, $importData = array()) {
		if (array_key_exists('user', $importData)){
			$user = $importData['user'];
		} else {
			if (!session_loggedin()) {
				$user=100;
			} else {
				$user=user_getid();
			}
		}
		if (array_key_exists('time',$importData)){
			$time = $importData['time'];
		} else {
			$time = time();
		}
		return db_query_params ('INSERT INTO artifact_history(artifact_id,field_name,old_value,mod_by,entrydate) VALUES ($1,$2,$3,$4,$5)',
					array ($this->getID(),
					       $field_name,
					       $old_value,
					       $user,
					       $time)) ;
	}

	/**
	 * setStatus - set the status of this artifact.
	 *
	 * @param	int	The artifact status ID.
	 * @param	int	Closing date if status = 1
	 *
	 * @return	boolean	success.
	 */
	function setStatus($status_id, $closingTime=False) {
		db_begin();
		$qpa = db_construct_qpa (false, 'UPDATE artifact SET status_id=$1', array ($status_id)) ;
		if ($closingTime && $status_id != 1) {
			$time=$closingTime;
			$qpa = db_construct_qpa ($qpa, ', close_date=$1 ', array ($time)) ;
		}
		$qpa = db_construct_qpa ($qpa,
					 'WHERE artifact_id=$1 AND group_artifact_id=$2',
					 array ($this->getID(), $this->ArtifactType->getID())) ;
		$result=db_query_qpa($qpa);

		if (!$result || db_affected_rows($result) < 1) {
			$this->setError('Error - update failed!'.db_error());
			db_rollback();
			return false;
		} else {
			if (!$this->fetchData($this->getID())) {
				db_rollback();
				return false;
			}
		}

		//commiting changes
		db_commit();
		return true;
	}

	/**
	 * update - update the fields in this artifact.
	 *
	 * @param	int	$priority		The artifact priority.
	 * @param	int	$status_id		The artifact status ID.
	 * @param	int	$assigned_to		The person to which this artifact is to be assigned.
	 * @param	string	$summary		The artifact summary.
	 * @param	int	$canned_response	The canned response.
	 * @param	string	$details		Attaching another comment.
	 * @param	int	$new_artifact_type_id	Allows you to move an artifact to another type.
	 * @param	array	$extra_fields		Array of extra fields like: array(15=>'foobar',22=>'1');
	 * @param	string  $description		The description.
	 * @return	boolean	success.
	 */
	function update($priority,$status_id,
		$assigned_to,$summary,$canned_response,$details,$new_artifact_type_id,
		$extra_fields=array(), $description='') {

		/*
			Field-level permission checking
		*/
		if (!forge_check_perm ('tracker', $this->ArtifactType->getID(), 'manager')) {
			// Non-managers cannot modify these fields
			$priority=$this->getPriority();
			$summary=htmlspecialchars_decode($this->getSummary());
			$description=htmlspecialchars_decode($this->getDetails());
			$canned_response=100;
			$new_artifact_type_id=$this->ArtifactType->getID();
			$assigned_to=$this->getAssignedTo();

			if (!forge_check_perm ('tracker', $this->ArtifactType->getID(), 'tech')) {
				$this->setPermissionDeniedError();
				return false;
			}
		}
		//
		//	They may be using an extra field "status" box so we have to remap
		//	the status_id based on the extra field - this keeps the counters
		//	accurate
		//
		if (count($extra_fields) > 0) {
			$status_id=$this->ArtifactType->remapStatus($status_id,$extra_fields);
		}
		if (!$this->getID()) {
			$this->setMissingParamsError('ID');
			return false;
		}
		if (!$assigned_to) {
			$this->setMissingParamsError(_('Assigned to'));
			return false;
		}
		if (!$status_id) {
			$this->setMissingParamsError(_('State'));
			return false;
		}
		if (!$canned_response) {
			$this->setMissingParamsError(_('Canned Response'));
			return false;
		}
		if (!$new_artifact_type_id) {
			$this->setMissingParamsError(_('Data Type'));
			return false;
		}

		// Check that assigned_to is a tech for the tracker
		if ($assigned_to != 100) {
			if (!forge_check_perm_for_user ($assigned_to, 'tracker', $this->ArtifactType->getID(), 'tech')) {
				$this->setError(_("Invalid assigned person: must be a technician"));
				return false;
			}
		}

		// Array to record which properties were changed
		$changes = array();
		$update  = false;

		db_begin();

		//
		//	Get a lock on this row in the database
		//
		db_query_params ('SELECT * FROM artifact WHERE artifact_id=$1 FOR UPDATE', array ($this->getID())) ;
		$artifact_type_id = $this->ArtifactType->getID();
		//
		//	Attempt to move this Artifact to a new ArtifactType
		//	need to instantiate new ArtifactType obj and test perms
		//
		if ($new_artifact_type_id != $artifact_type_id) {
			$newArtifactType= new ArtifactType($this->ArtifactType->getGroup(), $new_artifact_type_id);
			if (!is_object($newArtifactType) || $newArtifactType->isError()) {
				$this->setError(_('Could not move to new Artifact Type'). $newArtifactType->getErrorMessage());
				db_rollback();
				return false;
			}
			//	do they have perms for new ArtifactType?
			if (!forge_check_perm ('tracker', $newArtifactType->getID(), 'manager')) {
				$this->setPermissionDeniedError();
				db_rollback();
				return false;
			}

			// Add a message to explain that the tracker was moved.
			$message = sprintf(_('Moved from %1$s to %2$s'),
                               $this->ArtifactType->getName(),
                               $newArtifactType->getName());
			$this->addHistory('type', $this->ArtifactType->getName());
			$this->addMessage($message,'',0);

			// Fake change to send a mail when moved.
			$changes['Type'] = 1;

			// Try to remap extra_fields values when possible.
			// If there is an extra_field with the same alias
			// and if the value exist in the new one, then recode
			// the value to keep it.
			$new_extra_fields = array();
			$ef = $this->ArtifactType->getExtraFields();
			$ef_new = $newArtifactType->getExtraFields();
			foreach($extra_fields as $extra_id => $value) {
				$alias = preg_replace('/^@/', '', $ef[$extra_id]['alias']);
				$type  = $ef[$extra_id]['field_type'];

				// Search if there is an extra field with the same alias.
				$new_id = 0;
				foreach($ef_new as $id => $arr) {
					if (preg_replace('/^@/', '', $arr['alias']) == $alias) {
						$new_id = $id;
					}
				}

				// If we found one, copy for simple fields or
				// search if there is the same value.
				if ($new_id) {
					if ($type == ARTIFACT_EXTRAFIELDTYPE_TEXT ||
						$type == ARTIFACT_EXTRAFIELDTYPE_INTEGER ||
						$type == ARTIFACT_EXTRAFIELDTYPE_TEXTAREA ||
						$type == ARTIFACT_EXTRAFIELDTYPE_RELATION) {
						$new_extra_fields[$new_id] = $value;
					} else {
						$values = $newArtifactType->getExtraFieldElements($new_id);
						if (is_array($value)) {
							foreach($value as $v) {
								$v = $this->ArtifactType->getElementName($v);
								foreach($values as $ev) {
									if ($ev['element_name'] == $v) {
										$new_extra_fields[$new_id][] = $ev['element_id'];
									}
								}
							}
						} else {
							$value = $this->ArtifactType->getElementName($value);
							foreach($values as $ev) {
								if ($ev['element_name'] == $value) {
									$new_extra_fields[$new_id] = $ev['element_id'];
								}
							}
						}
					}
				}
			}

			// Special case if moving to a tracker with custom status (previous has not).
			$custom_status_id = $newArtifactType->getCustomStatusField();
			if ($custom_status_id && !$new_extra_fields[$custom_status_id]) {
				$atw = new ArtifactWorkflow($newArtifactType, $custom_status_id);
				$nodes = $atw->getNextNodes(100);
				if ($nodes) {
					$new_extra_fields[$custom_status_id] = $nodes[0];
				}
			}

			$extra_fields = $new_extra_fields;

			$res = db_query_params ('DELETE FROM artifact_extra_field_data WHERE artifact_id=$1',
						array ($this->getID()));
			if (!$res) {
				$this->setError(_('Removal of old artifact_extra_field_data failed: ').db_error());
				db_rollback();
				return false;
			}

			// Check that assigned_to is a tech in the new tracker
			if ($assigned_to != 100) {
				if (!forge_check_perm ('tracker', $newArtifactType->getID(), 'tech')) {
					$assigned_to = 100;
				}
			}

			//can't send a canned response when changing ArtifactType
			$canned_response=100;
			$this->ArtifactType =& $newArtifactType;
			$update = true;
		}

		$qpa = db_construct_qpa();
		$qpa = db_construct_qpa($qpa, 'UPDATE artifact SET');

		//
		//	handle audit trail
		//
		$now = time();
		if ($this->getStatusID() != $status_id) {
			$this->addHistory('status_id',$this->getStatusID());
			$qpa = db_construct_qpa($qpa, ' status_id=$1,', array($status_id));
			$changes['status'] = 1;
			$update = true;

			if ($status_id != 1) {
				$qpa = db_construct_qpa($qpa, ' close_date=$1,', array($now));
			} else {
			  $qpa = db_construct_qpa($qpa, ' close_date=$1,', array(0));
			}
			$this->addHistory('close_date', $this->getCloseDate());
		}
		if ($this->getPriority() != $priority) {
			$this->addHistory('priority',$this->getPriority());
			$qpa = db_construct_qpa($qpa, ' priority=$1,', array($priority));
			$changes['priority'] = 1;
			$update = true;
		}

		if ($this->getAssignedTo() != $assigned_to) {
			$this->addHistory('assigned_to',$this->getAssignedTo());
			$qpa = db_construct_qpa($qpa, ' assigned_to=$1,', array($assigned_to));
			$changes['assigned_to'] = 1;
			$update = true;
		}
		if ($summary && ($this->getSummary() != htmlspecialchars($summary))) {
			$this->addHistory('summary', $this->getSummary());
			$qpa = db_construct_qpa($qpa, ' summary=$1,', array(htmlspecialchars($summary)));
			$changes['summary'] = 1;
			$update = true;
		}
 		if ($description && ($this->getDetails() != htmlspecialchars($description))) {
 			$this->addHistory('details', $this->getDetails());
 			$qpa = db_construct_qpa($qpa, ' details=$1,', array(htmlspecialchars($description)));
 			$changes['details'] = 1;
 			$update = true;
  		}
		if ($details) {
			$this->addMessage($details,'',0);
			$changes['details'] = 1;
			$send_message=true;
		}

		/*
			Finally, update the artifact itself
		*/
		if ($update){
		  $qpa = db_construct_qpa($qpa, ' group_artifact_id=$1
				                              WHERE artifact_id=$2 AND group_artifact_id=$3',
                                      array($new_artifact_type_id,
                                            $this->getID(), $artifact_type_id));
		  $result = db_query_qpa($qpa);

			if (!$result || db_affected_rows($result) < 1) {
				$this->setError(_('Update failed').db_error());
				db_rollback();
				return false;
			} else {
				if (!$this->fetchData($this->getID())) {
					db_rollback();
					return false;
				}
			}
		}

		//extra field handling
		$update=true;
		if (!$this->updateExtraFields($extra_fields,$changes)) {
//TODO - see if anything actually did change
			db_rollback();
			return false;
		}

		/*
			handle canned responses

			Instantiate ArtifactCanned and get the body of the message
		*/
		if ($canned_response != 100) {
			//don't care if this response is for this group - could be hacked
			$acr=new ArtifactCanned($this->ArtifactType,$canned_response);
			if (!$acr || !is_object($acr)) {
				$this->setError(_('Could Not Create Canned Response Object'));
			} elseif ($acr->isError()) {
				$this->setError($acr->getErrorMessage());
			} else {
				$body = $acr->getBody();
				if ($body) {
					if (!$this->addMessage(util_unconvert_htmlspecialchars($body),'',0)) {
						db_rollback();
						return false;
					} else {
						$send_message=true;
					}
				} else {
					$this->setError(_('Unable to Use Canned Response'));
					return false;
				}
			}
		}

		if ($update || $send_message){
			if (!empty($changes)) {
				// Send the email with changes
				$this->mailFollowupEx($now, 2, false, $changes);
			}
			db_commit();
			return true;
		} else {
			//nothing changed, so cancel the transaction
			$this->setError(_('Nothing Changed - Update Cancelled'));
			db_rollback();
			return false;
		}

	}

	/**
	 * updateLastModifiedDate - update the last_modified_date attribute of this artifact.
	 *
	 * @return	bool	true on success / false on failure
	 */
	function updateLastModifiedDate() {
		$res = db_query_params ('UPDATE artifact SET last_modified_date=EXTRACT(EPOCH FROM now())::integer WHERE artifact_id=$1',
			array ($this->getID()));
		return (!$res);
	}

	/**
	 * assignToMe - assigns this artifact to current user
	 *
	 * @return	bool	true on success / false on failure
	 */
	function assignToMe() {
		if (!session_loggedin() || !($this->ArtifactType->userIsAdmin() || $this->ArtifactType->userIsTechnician())) {
			$this->setPermissionDeniedError();
			return false;
		}

		$user_id = user_getid();
		$res = db_query_params ('UPDATE artifact SET assigned_to=$1 WHERE artifact_id=$2',
								array ($user_id, $this->getID())) ;
		if (!$res) {
			$this->setError(_('Error updating assigned_to in artifact: ').db_error());
			return false;
		}
		$this->fetchData($this->getID());

		return true;
	}

	/**
	 * updateExtraFields - updates the extra data elements for this artifact
	 * e.g. the extra fields created and defined by the admin.
	 *
	 * @param	array	Array of extra fields like: array(15=>'foobar',22=>'1');
	 * @param	array	Array where changes to the extra fields should be logged
	 * @return	bool	true on success / false on failure
	 */
	function updateExtraFields($extra_fields,&$changes){
/*
	This is extremely complex code - we have take the passed array
	and see if we need to insert it into the db, and may have to
	add history rows for the audit trail

	start by getting all the available extra fields from ArtifactType
		For each field from ArtifacType, check the passed array -
			This prevents someone from passing bogus extra field entries - they will be ignored
			if the passed entry is blank, may have to force a default value
			if the passed array is different from the existing data in db,
				delete old entry and insert new entries, along with possible audit trail
			else
				skip it and continue to next item

*/
		$update = false;

		//get a list of extra fields for this artifact_type
		$ef = $this->ArtifactType->getExtraFields();
		$efk=array_keys($ef);

		if (empty($extra_fields) && empty($ef)) {
			return true;
		}

		// If there is a status field, then check against the workflow.
		// Unless if we change type.
		if (! isset($changes['Type']) || !$changes['Type']) {
			for ($i=0; $i<count($efk); $i++) {
				$efid=$efk[$i];
				$type=$ef[$efid]['field_type'];
				if ($type == ARTIFACT_EXTRAFIELDTYPE_STATUS) {
					// Get previous value.
					$res = db_query_params ('SELECT field_data FROM artifact_extra_field_data
							WHERE artifact_id=$1 AND extra_field_id=$2',
						array($this->getID(),
							$efid));
					$old = (db_numrows($res)>0) ? db_result($res,0,'field_data') : 100;
					if ($old != $extra_fields[$efid]) {
						$atw = new ArtifactWorkflow($this->ArtifactType, $efid);
						if (!$atw->checkEvent($old, $extra_fields[$efid])) {
							$this->setError('Workflow error: You are not authorized to change the Status ('.$old.' => '.$extra_fields[$efid].')');
							return false;
						}
					}
				}
			}
		}

		//now we'll update this artifact for each extra field
		for ($i=0; $i<count($efk); $i++) {
			$efid=$efk[$i];
			$type=$ef[$efid]['field_type'];

			// check required fields
			if ($ef[$efid]['is_required']) {
				if (!array_key_exists($efid, $extra_fields)) {
					if ($type == ARTIFACT_EXTRAFIELDTYPE_STATUS) {
						$this->setError(_('Status Custom Field Must Be Set'));
					}
					else {
						$this->setMissingParamsError($ef[$efid]['field_name']);
					}
					return false;
				}
				else {
					if ($extra_fields[$efid] === '') {
						if ($type == ARTIFACT_EXTRAFIELDTYPE_STATUS) {
							$this->setError(_('Status Custom Field Must Be Set'));
						}
						else {
							$this->setMissingParamsError($ef[$efid]['field_name']);
						}
						return false;
					}
					else {
						if (($type == ARTIFACT_EXTRAFIELDTYPE_SELECT || $type == ARTIFACT_EXTRAFIELDTYPE_RADIO) &&
							$extra_fields[$efid] == '100') {
								$this->setMissingParamsError($ef[$efid]['field_name']);
								return false;
						}
						elseif (($type == ARTIFACT_EXTRAFIELDTYPE_MULTISELECT || $type == ARTIFACT_EXTRAFIELDTYPE_CHECKBOX) &&
								(count($extra_fields[$efid]) == 1 && $extra_fields[$efid][0] == '100')) {
							$this->setMissingParamsError($ef[$efid]['field_name']);
							return false;
						}
					}
				}
			}
//
//	Force each field to have some value if it is a numeric field
//	text fields will just be purged and skipped
//
			if (!array_key_exists($efid, $extra_fields) || $extra_fields[$efid] === '') {
				if (($type == ARTIFACT_EXTRAFIELDTYPE_SELECT) || ($type == ARTIFACT_EXTRAFIELDTYPE_RADIO)) {
					$extra_fields[$efid]='100';
				} elseif (($type == ARTIFACT_EXTRAFIELDTYPE_MULTISELECT) || ($type == ARTIFACT_EXTRAFIELDTYPE_CHECKBOX)) {
					$extra_fields[$efid]=array('100');
				} else {
					db_query_params ('DELETE FROM artifact_extra_field_data WHERE artifact_id=$1 AND extra_field_id=$2',
								   array ($this->getID(),
									  $efid)) ;
					continue;
				}
			}

			//
			//	get the old rows of data
			//
			$resd = db_query_params ('SELECT * FROM artifact_extra_field_data WHERE artifact_id=$1 AND extra_field_id=$2',
						 array ($this->getID(),
							$efid)) ;
			$rows=db_numrows($resd);
			if ($resd && $rows) {
//
//POTENTIAL PROBLEM - no entry was there before, but adding one now - may need history
//
				//
				//	Compare for history purposes
				//

				// these types have arrays associated to them, so they need
				// special handling to check for differences
				if ($type == ARTIFACT_EXTRAFIELDTYPE_MULTISELECT || $type == ARTIFACT_EXTRAFIELDTYPE_CHECKBOX) {
					// check the differences between the old values and the new values
					$old_values = util_result_column_to_array($resd,"field_data");

					$added_values = array_diff($extra_fields[$efid], $old_values);
					$deleted_values = array_diff($old_values, $extra_fields[$efid]);

					if (!empty($added_values) || !empty($deleted_values))	{	// there are differences...
						$field_name = $ef[$efid]['field_name'];
						if (!preg_match('/^@/', $ef[$efid]['alias'])) {
							$changes["extra_fields"][$efid] = 1;
						}

						$this->addHistory($field_name, $this->ArtifactType->getElementName(array_reverse($old_values)));
						$update = true;

						db_query_params ('DELETE FROM artifact_extra_field_data WHERE	artifact_id=$1 AND extra_field_id=$2',
									   array ($this->getID(),
										  $efid)) ;
					} else {
						continue;
					}
				} elseif (db_result($resd,0,'field_data') == htmlspecialchars($extra_fields[$efid])) {
					//element did not change
					continue;
				} else {
					//element DID change - do a history entry
					$field_name = $ef[$efid]['field_name'];
					if (!preg_match('/^@/', $ef[$efid]['alias'])) {
						$changes["extra_fields"][$efid] = 1;
					}
					db_query_params ('DELETE FROM artifact_extra_field_data WHERE	artifact_id=$1 AND extra_field_id=$2',
								   array ($this->getID(),
									  $efid)) ;

					// Adding history with previous value.
					if (($type == ARTIFACT_EXTRAFIELDTYPE_SELECT) || ($type == ARTIFACT_EXTRAFIELDTYPE_RADIO) || ($type == ARTIFACT_EXTRAFIELDTYPE_STATUS)) {
						$this->addHistory($field_name,$this->ArtifactType->getElementName(db_result($resd,0,'field_data')));
					} else {
						$this->addHistory($field_name, db_result($resd,0,'field_data'));
					}
					$update = true;
				}
			} else {

//no history for this extra field exists

			}

			//
			// Some rewrite & consistency checks on the relation type field.
			//
			// 1) Convert syntax [#NNN] to NNN
			// 2) Allow multiple spaces as separator.
			// 3) Ensure that only integers are given.
			// 4) Ensure that id corresponds to valid tracker id.
			//
			if ($type == ARTIFACT_EXTRAFIELDTYPE_RELATION) {
				$value = preg_replace('/\[\#(\d+)\]/', "\\1", trim($extra_fields[$efid]));
				$value = preg_replace('/\\s+/', ' ', $value);
				$new = '';
				foreach (explode(' ',$value) as $id) {
					if (preg_match('/^(\d+)$/', $id)) {
						// Control that the id is present in the db

						$res = db_query_params ('SELECT artifact_id FROM artifact WHERE artifact_id=$1',
			array($id));
						if (db_numrows($res) == 1) {
							$new .= $id.' ';
						} else {
							$this->setError('Illegal id '.$id.', it\'s not a valid tracker id for field: '.$ef[$efid]['field_name'].'.'); // @todo: lang
							return false;
						}
					} else {
						$this->setError('Illegal value '.$id.', only trackers id are allowed for field: '.$ef[$efid]['field_name'].'.'); // @todo: lang
						return false;
					}
				}
				$extra_fields[$efid] = trim($new);
			}

			// Ensure that only integer are allowed for type ARTIFACT_EXTRAFIELDTYPE_INTEGER
			if ($type == ARTIFACT_EXTRAFIELDTYPE_INTEGER) {
				$extra_fields[$efid] = trim($extra_fields[$efid]);
				if (!preg_match('/^[-+]?(\d+)$/', $extra_fields[$efid])) {
					$this->setError('Illegal value '.$extra_fields[$efid].' for field '.$ef[$efid]['field_name'].': Only integer is allowed.');
					return false;
				}
				if ($extra_fields[$efid] < -2147483648 || $extra_fields[$efid] > 2147483647) {
					$this->setError('Illegal value '.$extra_fields[$efid].' for field '.$ef[$efid]['field_name'].': Integer out of range (-2147483648 to +2147483647).');
					return false;
				}
				$extra_fields[$efid] = intval($extra_fields[$efid]);
			}

			//
			//	See if anything was even passed for this extra_field_id
			//
			if ($extra_fields[$efid] === '') {
				//nothing in field to update - text fields may be blank
			} else {
				//determine the type of field and whether it should have multiple rows supporting it
				$type=$ef[$efid]['field_type'];
				if (($type == ARTIFACT_EXTRAFIELDTYPE_CHECKBOX) || ($type==ARTIFACT_EXTRAFIELDTYPE_MULTISELECT)) {
					$multi_rows=true;
					$count=count($extra_fields[$efid]);
					for ($fin=0; $fin<$count; $fin++) {
						$res = db_query_params ('INSERT INTO artifact_extra_field_data (artifact_id,extra_field_id,field_data) VALUES ($1,$2,$3)',
									array ($this->getID(),
									       $efid,
									       $extra_fields[$efid][$fin])) ;
						if (!$res) {
							$this->setError(db_error());
							return false;
						}
					}
				} else {
					$multi_rows=false;
					$count=1;
					$res = db_query_params ('INSERT INTO artifact_extra_field_data (artifact_id,extra_field_id,field_data) VALUES ($1,$2,$3)',
								array ($this->getID(),
								       $efid,
								       htmlspecialchars($extra_fields[$efid]))) ;
					if (!$res) {
						$this->setError(db_error());
						return false;
					}
					$update = true;
				}
			}
		}
		unset($this->extra_field_data);

		if ($update)
			$this->updateLastModifiedDate();

		return true;
	}

	/**
	 * getExtraFieldData - get an array of data for the extra fields associated with this artifact
	 *
	 * @return	array	array of data
	 */
	function &getExtraFieldData() {
		if (!isset($this->extra_field_data)) {
			$this->extra_field_data = array();
			$res = db_query_params ('SELECT * FROM artifact_extra_field_data WHERE artifact_id=$1 ORDER BY extra_field_id',
						array ($this->getID())) ;
			$ef = $this->ArtifactType->getExtraFields();
			while ($arr = db_fetch_array($res)) {
				$type=$ef[$arr['extra_field_id']]['field_type'];
				if (($type == ARTIFACT_EXTRAFIELDTYPE_CHECKBOX) || ($type==ARTIFACT_EXTRAFIELDTYPE_MULTISELECT)) {
					//accumulate a sub-array of values in cases where you may have multiple rows
					if (!array_key_exists($arr['extra_field_id'], $this->extra_field_data) || !is_array($this->extra_field_data[$arr['extra_field_id']])) {
						$this->extra_field_data[$arr['extra_field_id']] = array();
					}
					$this->extra_field_data[$arr['extra_field_id']][]=$arr['field_data'];
				} else {
					$this->extra_field_data[$arr['extra_field_id']]=$arr['field_data'];
				}
			}
		}
		return $this->extra_field_data;
	}

	/**
	 * marker - adds the > symbol to fields that have been modified for the email message
	 *
	 *
	 */
	function marker($prop_name,$changes,$extra_field_id=0) {
		if ($prop_name == 'extra_fields' && isset($changes[$prop_name][$extra_field_id])) {
			return '>';
		} elseif ($prop_name != 'extra_fields' && isset($changes[$prop_name])) {
			return '>';
		} else {
			return '';
		}
	}

	/**
	 * mailFollowupEx - send out an email update for this artifact.
	 *
	 * @param	time_t	Time of the change
	 * @param	int	(1) initial/creation (2) update.
	 * @param	array	Array of additional addresses to mail to.
	 * @param	array	Array of fields changed in this update .
	 * @access	private
	 * @return	boolean	success.
	 */
	function mailFollowupEx($tm, $type, $more_addresses = false, $changes='') {

		$monitor_ids = array();

		if (!$changes) {
			$changes=array();
		}

		$sess = session_get_user();
		$name = util_unconvert_htmlspecialchars($this->ArtifactType->getName());
		$body = $this->ArtifactType->Group->getUnixName() . '-' . $name .' '. $this->getStringID();

		if ($type == 1) {
			$body .= ' was opened at '.date('Y-m-d H:i', $this->getOpenDate());
		} elseif ($type == 3) {
			$body .= ' was deleted at '.date('Y-m-d H:i', time());
		} else {
			$body .= ' was changed at '.date('Y-m-d H:i', $tm);
		}
		if ($sess) {
			$body .= ' by ' . $sess->getRealName();
		}

		if ($type == 1 || $type == 2) {
			$body .= "\nYou can respond by visiting: ".
				"\n".util_make_url ('/tracker/?func=detail&atid='. $this->ArtifactType->getID() .
					    "&aid=". $this->getID() .
					    "&group_id=". $this->ArtifactType->Group->getID()) .
				"\nOr by replying to this e-mail entering your response between the following markers: ".
				"\n".ARTIFACT_MAIL_MARKER.
				"\n(enter your response here, only in plain text format)".
				"\n".ARTIFACT_MAIL_MARKER.
				"\n";
		}

		$body .= "\n".$this->marker('status',$changes).
			 "Status: ". $this->getStatusName() ."\n".
			$this->marker('priority',$changes).
			 "Priority: ". $this->getPriority() ."\n".
			"Submitted By: ". $this->getSubmittedRealName() .
			" (". $this->getSubmittedUnixName(). ")"."\n".
			$this->marker('assigned_to',$changes).
			 "Assigned to: ". $this->getAssignedRealName() .
			 " (". $this->getAssignedUnixName(). ")"."\n".
			$this->marker('summary',$changes).
			 "Summary: ". util_unconvert_htmlspecialchars( $this->getSummary() )." \n";

		// Now display the extra fields
		$efd = $this->getExtraFieldDataText();
		foreach ($efd as $efid => $ef) {
			$body .= $this->marker('extra_fields', $changes, $efid);
			$body .= $ef["name"].": ".$ef["value"]."\n";
		}

		$subject='['. $this->ArtifactType->Group->getUnixName() . '-' . $name . ']' . $this->getStringID() .' '. util_unconvert_htmlspecialchars( $this->getSummary() );

		if ($type > 1) {
			// get all the email addresses that are monitoring this request or the ArtifactType
			$monitor_ids = $this->getMonitorIds();
		} else {
			// initial creation, we just get the users monitoring the ArtifactType
			$monitor_ids = $this->ArtifactType->getMonitorIds();
		}

		$emails = array();
		if ($more_addresses) {
			$emails[] = $more_addresses;
		}
		//we don't email the current user
		if ($this->getAssignedTo() != user_getid()) {
			$monitor_ids[] = $this->getAssignedTo();
		}
		if ($this->getSubmittedBy() != user_getid()) {
			$monitor_ids[] = $this->getSubmittedBy();
		}
		//initial submission
		if ($type==1) {
			//if an email is set for this ArtifactType
			//add that address to the BCC: list
			if ($this->ArtifactType->getEmailAddress()) {
				$emails[] = $this->ArtifactType->getEmailAddress();
			}
		} else {
			//update
			if ($this->ArtifactType->emailAll()) {
				$emails[] = $this->ArtifactType->getEmailAddress();
			}
		}

		$body .= "\n\nInitial Comment:".
			"\n".util_unconvert_htmlspecialchars( $this->getDetails() ) .
			"\n\n----------------------------------------------------------------------";

		if ($type > 1) {
			/*
				Now include the followups
			*/
			$result2=$this->getMessages();

			$rows=db_numrows($result2);

			if ($result2 && $rows > 0) {
				for ($i=0; $i<$rows; $i++) {
					//
					//	for messages posted by non-logged-in users,
					//	we grab the email they gave us
					//
					//	otherwise we use the confirmed one from the users table
					//
					if (db_result($result2,$i,'user_id') == 100) {
						$emails[] = db_result($result2,$i,'from_email');
					} else {
						$monitor_ids[] = db_result($result2,$i,'user_id');
					}

					$body .= "\n\n";
					if ($i == 0) {
						$body .= $this->marker('details',$changes);
					}
					$body .= "Comment By: ". db_result($result2,$i,'realname') . " (".db_result($result2,$i,'user_name').")".
					"\nDate: ". date( _('Y-m-d H:i'),db_result($result2,$i,'adddate') ).
					"\n\nMessage:".
					"\n".util_unconvert_htmlspecialchars( db_result($result2,$i,'body') ).
					"\n\n----------------------------------------------------------------------";
				}
			}

		}

		$body .= "\n\nYou can respond by visiting: ".
			"\n".util_make_url ('/tracker/?func=detail&atid='. $this->ArtifactType->getID() .
					    "&aid=". $this->getID() .
					    "&group_id=". $this->ArtifactType->Group->getID());

		//only send if some recipients were found
		if (count($emails) < 1 && count($monitor_ids) < 1) {
			return true;
		}

		if (count($monitor_ids) < 1) {
			$monitor_ids=array();
		} else {
			$monitor_ids=array_unique($monitor_ids);
		}

		$from = $this->ArtifactType->getReturnEmailAddress();
		$extra_headers = 'Reply-to: '.$from;

		// load the e-mail addresses of the users
		$users = user_get_objects($monitor_ids);
		if (count($users) > 0) {
			foreach ($users as $user) {
				if ($user->getStatus() == "A") { //we are only sending emails to active users
					$emails[] = $user->getEmail();
				}
			}
		}

		//now remove all duplicates from the email list
		if (count($emails) > 0) {
			$BCC=implode(',',array_unique($emails));
			util_send_message('',$subject,$body,$from,$BCC,'',$extra_headers);
		}

		$this->sendSubjectMsg = $subject;
		$this->sendBodyMsg = $body;

		//util_handle_message($monitor_ids,$subject,$body,$BCC);

		return true;
	}

	/**
	* getExtraFieldDataText - Return the extra fields' data in a human-readable form.
	*
	* @return	array	Array containing field ID => field name and value associated to it for
	*			this artifact
	*/
	function getExtraFieldDataText() {
		// First we get the list of extra fields and the data
		// associated to the fields
		$efs = $this->ArtifactType->getExtraFields();
		$efd = $this->getExtraFieldData();

		$return = array();

		foreach ($efs as $efid => $ef) {
			$name = $ef["field_name"];
			$type = $ef["field_type"];

			// Get the value according to the type
			switch ($type) {

				// for these types, the associated value comes straight
				case ARTIFACT_EXTRAFIELDTYPE_TEXT:
				case ARTIFACT_EXTRAFIELDTYPE_TEXTAREA:
				case ARTIFACT_EXTRAFIELDTYPE_RELATION:
				case ARTIFACT_EXTRAFIELDTYPE_INTEGER:
					if (isset($efd[$efid])) {
						$value = $efd[$efid];
					} else {
						$value = '';
					}
					break;

				// the other types have and ID or an array of IDs associated to them
				default:
					if (isset($efd[$efid])) {
						$value = $this->ArtifactType->getElementName($efd[$efid]);
					} else {
						$value = 'None';
					}
			}

			$return[$efid] = array("name" => $name, "value" => $value, 'type' => $type);
		}

		return $return;
	}

	/**
	 * castVote - Vote on this tracker item or retract the vote
	 * @param	bool	$value	true to cast, false to retract
	 * @return	bool	success (false sets error message)
	 */
	function castVote($value = true) {
		if (!($uid = user_getid()) || $uid == 100) {
			$this->setMissingParamsError(_('User ID not passed'));
			return false;
		}
		if (!$this->ArtifactType->canVote()) {
			$this->setPermissionDeniedError();
			return false;
		}
		$has_vote = $this->hasVote($uid);
		if ($has_vote == $value) {
			/* nothing changed */
			return true;
		}
		if ($value) {
			$res = db_query_params('INSERT INTO artifact_votes (artifact_id, user_id) VALUES ($1, $2)',
						array($this->getID(), $uid));
		} else {
			$res = db_query_params('DELETE FROM artifact_votes WHERE artifact_id=$1 AND user_id=$2',
						array($this->getID(), $uid));
		}
		if (!$res) {
			$this->setError(db_error());
			return false;
		}
		return true;
	}

	/**
	 * hasVote - Check if a user has voted on this tracker item
	 *
	 * @param	int	$uid	user ID (default: current user)
	 * @return	bool	true if a vote exists
	 */
	function hasVote($uid=false) {
		if (!$uid) {
			$uid = user_getid();
		}
		if (!$uid || $uid == 100) {
			return false;
		}
		$res = db_query_params('SELECT * FROM artifact_votes WHERE artifact_id=$1 AND user_id=$2',
					array($this->getID(), $uid));
		return (db_numrows($res) == 1);
	}

       /**
        * getVotes - get number of valid cast and potential votes
        *
        * @return	array	(votes, voters, percent)
        */
	function getVotes() {
		if ($this->votes !== false) {
			return $this->votes;
		}

		$voters = $this->ArtifactType->getVoters();
		unset($voters[0]);	/* just in case */
		unset($voters[100]);	/* need users */
		if (($numvoters = count($voters)) < 1) {
			$this->votes = array(0, 0, 0);
			return $this->votes;
		}

		$res = db_query_params('SELECT COUNT(*) AS count FROM artifact_votes WHERE artifact_id=$1 AND user_id=ANY($2)',
					array($this->getID(), db_int_array_to_any_clause($voters)));
		$db_count = db_fetch_array($res);
		$numvotes = $db_count['count'];

		/* check for invalid values */
		if ($numvotes < 0 || $numvoters < $numvotes) {
			$this->votes = array(-1, -1, 0);
		} else {
			$this->votes = array($numvotes, $numvoters,
				(int)($numvotes * 100 / $numvoters + 0.5));
		}
		return $this->votes;
	}
}

class ArtifactComparator {
	var $criterion = 'artifact_id' ;
	var $order = 'ASC' ;

	function Compare ($a, $b) {
		if ($this->order == 'DESC') {
			$c = $a ; $a = $b ; $b = $c ;
		}
		switch ($this->criterion) {
		case 'summary':
			$namecmp = strcoll ($a->getSummary(),
					    $b->getSummary()) ;
			if ($namecmp != 0) {
				return $namecmp ;
			}
			break ;
		case 'assigned_to':
			$namecmp = strcoll (user_get_object($a->getAssignedTo())->getRealName(),
					    user_get_object($b->getAssignedTo())->getRealName()) ;
			if ($namecmp != 0) {
				return $namecmp ;
			}
			break ;
		case 'submitted_by':
			$namecmp = strcoll (user_get_object($a->getSubmittedBy())->getRealName(),
					    user_get_object($b->getSubmittedBy())->getRealName()) ;
			if ($namecmp != 0) {
				return $namecmp ;
			}
			break ;
		case 'open_date':
			$a_date = $a->getOpenDate() ;
			$b_date = $b->getOpenDate() ;
			return ($a_date < $b_date) ? -1 : 1;
			break;
		case 'close_date':
			$a_date = $a->getCloseDate() ;
			$b_date = $b->getCloseDate() ;
			return ($a_date < $b_date) ? -1 : 1;
			break;
		case 'last_modified_date':
			$a_date = $a->getLastModifiedDate() ;
			$b_date = $b->getLastModifiedDate() ;
			return ($a_date < $b_date) ? -1 : 1;
			break;
		case 'priority':
			$a_priority = $a->getPriority() ;
			$b_priority = $b->getPriority() ;
			return ($a_priority < $b_priority) ? -1 : 1;
			break;
		case '_votes':
			$a->getVotes();
			$a_votes = $a->votes[0];
			$b->getVotes();
			$b_votes = $b->votes[0];
			return ($a_votes < $b_votes) ? -1 : 1;
			break;
		case '_voters':
			$a->getVotes();
			$a_votes = $a->votes[1];
			$b->getVotes();
			$b_votes = $b->votes[1];
			return ($a_votes < $b_votes) ? -1 : 1;
			break;
		case '_votage':
			$a->getVotes();
			$a_votes = $a->votes[2];
			$b->getVotes();
			$b_votes = $b->votes[2];
			return ($a_votes < $b_votes) ? -1 : 1;
			break;
		default:
			$aa=$a->getExtraFieldDataText();
			$ba=$b->getExtraFieldDataText();
			if(!isset($this->criterion) || empty($this->criterion)) {
                                $criterion = 1;
			}
			else {
                                $criterion = $this->criterion;
			}
                        $af=$aa[$criterion]['value'];
                        $bf=$ba[$criterion]['value'];
			$namecmp = strcoll ($af,$bf) ;
			if ($namecmp != 0) {
				return $namecmp ;
			}
			break ;
		}

		// When in doubt, sort on artifact ID
		$aid = $a->getID() ;
		$bid = $b->getID() ;
		if ($aid == $bid) {
			return 0;
		}
		return ($aid < $bid) ? -1 : 1;
	}
}

function sortArtifactList (&$list, $criterion='name', $order='ASC') {
	$cmp = new ArtifactComparator () ;
	$cmp->criterion = $criterion ;
	$cmp->order = $order ;

	return usort ($list, array ($cmp, 'Compare')) ;
}

// Local Variables:
// mode: php
// c-file-style: "bsd"
// End: