File: modify.php

package info (click to toggle)
flyspray 0.9.8-10
  • links: PTS
  • area: main
  • in suites: etch-m68k
  • size: 2,444 kB
  • ctags: 3,031
  • sloc: php: 17,634; sh: 301; makefile: 12
file content (2414 lines) | stat: -rw-r--r-- 96,551 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
<?php
/*
   This script performs all database modifications/
*/

$fs->get_language_pack($lang, 'modify');


// Include the notifications class
include_once ( "$basedir/includes/notify.inc.php" );
$notify = new Notifications;


// FIXME: only temporary workaround
if (isset($_POST['default_cat_owner']) && !empty($_POST['default_cat_owner']) )
   $_POST['default_cat_owner'] = $db->emptyToZero($_POST['default_cat_owner']);

if (isset($_POST['category_owner']) && !empty($_POST['category_owner']) )
   $_POST['category_owner'] = $db->emptyToZero($_POST['category_owner']);

if (isset($_POST['list_type']) && !empty($_POST['list_type']) )
{
   $list_table_name = "{$dbprefix}list_".addslashes($_POST['list_type']);
   $list_column_name = addslashes($_POST['list_type'])."_name";
   $list_id = addslashes($_POST['list_type'])."_id";
}

$now = date('U');

if ( !empty($_REQUEST['task_id']) )
   $old_details = $fs->GetTaskDetails($_REQUEST['task_id']);


////////////////////////////////
// Start of adding a new task //
////////////////////////////////

if ($_POST['action'] == 'newtask'
    && (@$permissions['open_new_tasks'] == '1'
    OR $project_prefs['anon_open'] == '1'))
{
   // If they entered something in both the summary and detailed description
   if (!empty($_POST['item_summary']) && !empty($_POST['detailed_desc']))
   {
      $item_summary = $_POST['item_summary'];
      $detailed_desc = $_POST['detailed_desc'];

      $param_names = array('task_type', 'item_status',
        'assigned_to', 'product_category', 'product_version',
        'closedby_version', 'operating_system', 'task_severity',
        'task_priority');

      $sql_values = array($_POST['project_id'], $now, $now, $item_summary,
                $detailed_desc,
                $db->emptyToZero($_COOKIE['flyspray_userid']),
                '0');

      $sql_params = array();
      foreach ($param_names as $param_name)
      {
         if (!empty($_POST[$param_name]))
         {
            array_push($sql_params, $param_name);
            array_push($sql_values, $_POST[$param_name]);
         }
      }

      // Process the due_date
      if (isset($_POST['due_date']) && !empty($_POST['due_date']))
      {
         $due_date = strtotime("{$_POST['due_date']} +23 hours 59 minutes 59 seconds");
      } else
      {
         $due_date = '0';
      }
      array_push($sql_params, 'due_date');
      array_push($sql_values, $due_date);

      $sql_params = join(', ', $sql_params);
      $sql_placeholder = join(', ', array_fill(1, count($sql_values), '?'));

      $add_item = $db->Query("INSERT INTO {$dbprefix}tasks
                              (attached_to_project,
                              date_opened,
                              last_edited_time,
                              item_summary,
                              detailed_desc,
                              opened_by,
                              percent_complete,
                              $sql_params)
                              VALUES ($sql_placeholder)",
                                      $sql_values);

    // Now, let's get the task_id back, so that we can send a direct link
    // URL in the notification message
    $result = $db->Query("SELECT task_id, item_summary, product_category
                                                FROM {$dbprefix}tasks
                                                WHERE item_summary = ?
                                                AND detailed_desc = ?
                                                ORDER BY task_id DESC",
                                                array($item_summary, $detailed_desc), 1);
    $task_details = $db->FetchArray($result);

   // Log that the task was opened
   $fs->logEvent($task_details['task_id'], 1);

      // If the user uploaded one or more files
      if ($permissions['create_attachments'] == '1')
      {
         $files_added = $be->UploadFiles($current_user['user_id'],
                                         $task_details['task_id'],
                                         $_FILES
                                        );
      }

   $result = $db->Query("SELECT * FROM {$dbprefix}list_category
                                              WHERE category_id = ?",
                                              array($_POST['product_category'])
                                 );
   $cat_details = $db->FetchArray($result);

   // We need to figure out who is the category owner for this task
   if (!empty($cat_details['category_owner']))
   {
      $owner = $cat_details['category_owner'];

   } elseif (!empty($cat_details['parent_id']))
   {
      $result = $db->Query("SELECT category_owner
                                                         FROM {$dbprefix}list_category
                                                         WHERE category_id = ?",
                                                         array($cat_details['parent_id'])
                                            );
      $parent_cat_details = $db->FetchArray($result);

      // If there's a parent category owner, send to them
      if (!empty($parent_cat_details['category_owner']))
         $owner = $parent_cat_details['category_owner'];
   }

   // Otherwise send it to the default category owner
   if (empty($owner))
      $owner = $project_prefs['default_cat_owner'];

   if (!empty($owner))
   {
      // Category owners now get auto-added to the notification list for new tasks
      $insert = $db->Query("INSERT INTO {$dbprefix}notifications
                           (task_id, user_id)
                           VALUES(?, ?)",
                           array($task_details['task_id'], $owner)
                          );

      $fs->logEvent($task_details['task_id'], 9, $owner);

      // Create the Notification
      $notify->Create('1', $task_details['task_id']);

   // End of checking if there's a category owner set, and notifying them.
   }

   // If the reporter wanted to be added to the notification list
   if ($_POST['notifyme'] == '1' && ($_COOKIE['flyspray_userid'] != $owner))
      $be->AddToNotifyList($current_user['user_id'], array($task_details['task_id']));

   // Status and redirect
   $_SESSION['SUCCESS'] = $modify_text['newtaskadded'];
   $fs->redirect($fs->CreateURL('details', $task_details['task_id']));

?>

<?php
  // If they didn't fill in both the summary and detailed description, show an error
  } else {
    echo "<div class=\"redirectmessage\"><p>{$modify_text['summaryanddetails']}</p>";
    echo "<p><a href=\"javascript:history.back();\">{$modify_text['goback']}</a></p></div>";
  };

// End of adding a new task.

/////////////////////////////////////////
// Start of modifying an existing task //
/////////////////////////////////////////

} elseif ($_POST['action'] == "update"
          && ($permissions['modify_all_tasks'] == '1'
              OR ($permissions['modify_own_tasks'] == '1'
                  && $current_user['user_id'] == $old_details['assigned_to'])))
{

   // If they entered something in both the summary and detailed description
   if (!empty($_POST['item_summary'])
      && !empty($_POST['detailed_desc']))
   {

   // Check to see if this task has already been modified before we clicked "save"...
   // If so, we need to confirm that the we really wants to save our changes
   if ($_POST['edit_start_time'] < $old_details['last_edited_time'])
   {
      echo $modify_text['alreadyedited'];
      ?>

      <br><br>
      <span>
      <form name="form1" action="index.php" method="post">
         <input type="hidden" name="do" value="modify">
         <input type="hidden" name="action" value="update">
         <input type="hidden" name="task_id" value="<?php echo $_POST['task_id'];?>">
         <input type="hidden" name="edit_start_time" value="999999999999">
         <input type="hidden" name="attached_to_project" value="<?php echo $_POST['attached_to_project'];?>">
         <input type="hidden" name="task_type" value="<?php echo $_POST['task_type'];?>">

         <!-- A bit dodgy, part 1 -->
         <input type="text" style="display:none;" name="item_summary" value="<?php echo htmlspecialchars($_POST['item_summary'],ENT_COMPAT,'utf-8');?>">
         <textarea style="display:none" name="detailed_desc"><?php echo htmlspecialchars($_POST['detailed_desc'],ENT_COMPAT,'utf-8');?></textarea>

         <input type="hidden" name="item_status" value="<?php echo $_POST['item_status'];?>">
         <input type="hidden" name="assigned_to" value="<?php echo $_POST['assigned_to'];?>">
         <input type="hidden" name="product_category" value="<?php echo $_POST['product_category'];?>">
         <input type="hidden" name="closedby_version" value="<?php echo $_POST['closedby_version'];?>">
         <input type="hidden" name="due_date" value="<?php echo $_POST['due_date'];?>">
         <input type="hidden" name="operating_system" value="<?php echo $_POST['operating_system'];?>">
         <input type="hidden" name="task_severity" value="<?php echo $_POST['task_severity'];?>">
         <input type="hidden" name="task_priority" value="<?php echo $_POST['task_priority'];?>">
         <input type="hidden" name="percent_complete" value="<?php echo $_POST['percent_complete'];?>">
         <input type="submit" class="adminbutton" value="<?php echo $modify_text['saveanyway']; ?>">
      </form>
      </span>
      &nbsp;&nbsp;&nbsp;
      <span>
      <form action="index.php" method="get">
         <input type="hidden" name="do" value="details">
         <input type="hidden" name="id" value="<?php echo $_POST['task_id'];?>">
         <input type="submit" class="adminbutton" value="<?php echo $modify_text['cancel'];?>">
      </form>
      </span>

   <?php
   } else {

      $result = $db->Query("SELECT * FROM {$dbprefix}tasks WHERE task_id = ?", array($_POST['task_id']));
      $old_details_history = $db->FetchRow($result);

      $item_summary = $_POST['item_summary'];
      $detailed_desc = $_POST['detailed_desc'];

      // A bit dodgy, part 2.
      if ($_POST['edit_start_time'] == "999999999999")
      {
         $item_summary = stripslashes($_POST['item_summary']);
         $detailed_desc = stripslashes($_POST['detailed_desc']);
      }

      if (!empty($_POST['due_date']))
      {
         $due_date = strtotime("{$_POST['due_date']} +23 hours 59 minutes 59 seconds");
      } else
      {
         $due_date = '0';
      }

      $add_item = $db->Query("UPDATE {$dbprefix}tasks SET
                              attached_to_project = ?,
                              task_type = ?,
                              item_summary = ?,
                              detailed_desc = ?,
                              item_status = ?,
                              assigned_to = ?,
                              product_category = ?,
                              closedby_version = ?,
                              operating_system = ?,
                              task_severity = ?,
                              task_priority = ?,
                              last_edited_by = ?,
                              last_edited_time = ?,
                              due_date = ?,
                              percent_complete = ?

                              WHERE task_id = ?",
                              array($_POST['attached_to_project'], $_POST['task_type'],
                              $item_summary, $detailed_desc, $_POST['item_status'],
                              $_POST['assigned_to'], $_POST['product_category'],
                              $db->emptyToZero($_POST['closedby_version']),
                              $_POST['operating_system'], $_POST['task_severity'],
                              $_POST['task_priority'], $_COOKIE['flyspray_userid'],
                              $now,
                              $due_date,
                              $_POST['percent_complete'],
                              $_POST['task_id'])
                           );

      // Get the details of the task we just updated
      // To generate the changed-task message
      $new_details = $fs->GetTaskDetails($_POST['task_id']);
      $result = $db->Query("SELECT * FROM {$dbprefix}tasks WHERE task_id = ?", array($_POST['task_id']));
      $new_details_history = $db->FetchRow($result);

      // Now we compare old and new, mark the changed fields
      $field = array(
            "{$modify_text['project']}"          =>  'project_title',
            "{$modify_text['summary']}"          =>  'item_summary',
            "{$modify_text['tasktype']}"         =>  'tasktype_name',
            "{$modify_text['category']}"         =>  'category_name',
            "{$modify_text['status']}"           =>  'status_name',
            "{$modify_text['operatingsystem']}"  =>  'os_name',
            "{$modify_text['severity']}"         =>  'severity_name',
            "{$modify_text['priority']}"         =>  'priority_name',
            "{$modify_text['reportedversion']}"  =>  'reported_version_name',
            "{$modify_text['dueinversion']}"     =>  'due_in_version_name',
            "{$modify_text['percentcomplete']}"  =>  'percent_complete',
            "{$modify_text['details']}"          =>  'detailed_desc',
            "{$modify_text['duedate']}"          =>  'due_date',
            "assigned_to"                        =>  'assigned_to',
            );

      while (list($key, $val) = each($field))
      {
         if ($old_details[$val] != $new_details[$val])
            $send_me = 'YES';
      }

      // Log the changed fields in the task history
      while (list($key, $val) = each($old_details_history))
      {
         if ($key != 'last_edited_time' && $key != 'last_edited_by' && $key != 'assigned_to'
             && !is_numeric($key)
             && $old_details_history[$key] != $new_details_history[$key])
         {
            $fs->logEvent($_POST['task_id'], 0, $new_details_history[$key], $old_details_history[$key], $key);
         }
      }


      if ($send_me == 'YES')
      {
         $notify->Create('2', $new_details['task_id']);
      }

      // Check to see if the assignment has changed
      if ($_POST['old_assigned'] != $_POST['assigned_to'])
      {
         // Log to task history
         $fs->logEvent($_POST['task_id'], 14, $_POST['assigned_to'], $_POST['old_assigned']);

         // Notify the new assignee what happened
         if ($new_details['assigned_to'] != $current_user['user_id'])
         {
            $to  = $notify->SpecificAddresses(array($_POST['assigned_to']));
            $msg = $notify->GenerateMsg('14', $_POST['task_id']);
            $mail = $notify->SendEmail($to[0], $msg[0], $msg[1]);
            $jabb = $notify->StoreJabber($to[1], $msg[0], $msg[1]);
         }
      }

      $_SESSION['SUCCESS'] = $modify_text['taskupdated'];
      $fs->redirect($fs->CreateURL('details', $_POST['task_id']));

   // End of checking if this task was modified while we were editing it.
   };

   // If they didn't fill in both the summary and detailed description, show an error
   } else {
      echo "<div class=\"redirectmessage\"><p><em>{$modify_text['summaryanddetails']}</em></p>";
      echo "<p><a href=\"javascript:history.back();\">{$modify_text['goback']}</a></p></div>";
   };

// End of updating an task

/////////////////////////////
// Start of closing a task //
/////////////////////////////

} elseif(isset($_POST['action']) && $_POST['action'] == 'close'
         && ( (@$permissions['close_own_tasks'] == '1'
          && ($old_details['assigned_to'] == $current_user['user_id'])
          OR @$permissions['close_other_tasks'] == '1') ) )
{
   if (!empty($_POST['resolution_reason']))
   {
      $db->Query("UPDATE {$dbprefix}tasks SET
                  date_closed = ?,
                  closed_by = ?,
                  closure_comment = ?,
                  is_closed = '1',
                  resolution_reason = ?
                  WHERE task_id = ?",
                  array($now,
                        $_COOKIE['flyspray_userid'],
                        $db->emptyToZero($_POST['closure_comment']),
                        $_POST['resolution_reason'],
                        $_POST['task_id'])
                );

      if (isset($_POST['mark100']) && $_POST['mark100'] == '1')
      {
         $db->Query("UPDATE {$dbprefix}tasks SET
                     percent_complete = '100'
                     WHERE task_id = ?",
                     array($_POST['task_id'])
                   );

         $fs->logEvent($_POST['task_id'], '0', '100', $old_details['percent_complete'], 'percent_complete');
      }

      // Get the resolution name for the notifications
      $result = $db->Query("SELECT resolution_name FROM {$dbprefix}list_resolution WHERE resolution_id = ?", array($_POST['resolution_reason']));
      $get_res = $db->FetchArray($result);

      // Get the item summary for the notifications
      $result = $db->Query("SELECT item_summary FROM {$dbprefix}tasks WHERE task_id = ?", array($_POST['task_id']));
      list($item_summary) = $db->FetchArray($result);
      $item_summary = stripslashes($item_summary);

      // Create notification
      $notify->Create('3', $_POST['task_id']);

      // Log this to the task's history
      $fs->logEvent($_POST['task_id'], 2, $_POST['resolution_reason'], $_POST['closure_comment']);

      // If there's an admin request related to this, close it
      if ($fs->AdminRequestCheck(1, $_POST['task_id']) == '1') {
         $db->Query("UPDATE {$dbprefix}admin_requests
                    SET resolved_by = ?, time_resolved = ?
                    WHERE task_id = ? AND request_type = ?",
                    array($current_user['user_id'], date('U'), $_POST['task_id'], 1));
      };

      $_SESSION['SUCCESS'] = $modify_text['taskclosed'];
      $fs->redirect($fs->CreateURL('details', $_POST['task_id']));

   // If the user didn't select a closure reason
   } else
   {
      $_SESSION['ERROR'] = $modify_text['noclosereason'];
      $fs->redirect($fs->CreateURL('details', $_POST['task_id']));
   };

// End of closing a task

/////////////////////////////////
// Start of re-opening an task //
/////////////////////////////////

} elseif ( isset($_GET['action']) && $_GET['action'] == "reopen"
          && ( (@$permissions['close_own_tasks'] == '1'
          && ($old_details['assigned_to'] == $current_user['user_id'])
          OR @$permissions['close_other_tasks'] == '1') ) )
{
    $db->Query("UPDATE {$dbprefix}tasks SET
                resolution_reason = '0',
                closure_comment = '0',
                last_edited_time = ?,
                last_edited_by = ?,
                is_closed = '0'
                WHERE task_id = ?",
                array($now, $current_user['user_id'], $_GET['task_id']));

   $notify->Create('4', $_GET['task_id']);

   // If there's an admin request related to this, close it
   if ($fs->AdminRequestCheck(2, $_GET['task_id']) == '1')
   {
      $db->Query("UPDATE {$dbprefix}admin_requests
                  SET resolved_by = ?, time_resolved = ?
                  WHERE task_id = ? AND request_type = ?",
                  array($current_user['user_id'], date('U'), $_GET['task_id'], 2));
   }

   $fs->logEvent($_GET['task_id'], 13);

   $_SESSION['SUCCESS'] = $modify_text['taskreopened'];
   $fs->redirect($fs->CreateURL('details', $_GET['task_id']));

// End of re-opening an task

///////////////////////////////
// Start of adding a comment //
///////////////////////////////

} elseif ($_POST['action'] == 'addcomment'
          && $permissions['add_comments'] == '1')
{

   if (!empty($_POST['comment_text']))
   {
      $comment = $_POST['comment_text'];

      $db->Query("INSERT INTO {$dbprefix}comments
                  (task_id, date_added, user_id, comment_text)
                  VALUES ( ?, ?, ?, ? )",
                  array($_POST['task_id'], $now, $_COOKIE['flyspray_userid'], $comment));

      $result = $db->Query("SELECT comment_id FROM {$dbprefix}comments
                                           WHERE task_id = ?
                                           ORDER BY comment_id DESC",
                                           array($_POST['task_id']), 1
                              );
      $comment = $db->FetchRow($result);

      $fs->logEvent($_POST['task_id'], 4, $comment['comment_id']);

      // If the user wanted to watch this task for changes
      if ( isset($_POST['notifyme']) && $_POST['notifyme'] == '1' )
         $be->AddToNotifyList($current_user['user_id'], array($_POST['task_id']));

      // If the user uploaded one or more files
      if ($permissions['create_attachments'] == '1')
      {
         $files_added = $be->UploadFiles($current_user['user_id'],
                                         $old_details['task_id'],
                                         $_FILES,
                                         $comment['comment_id']
                                        );
      }

      // Send the notification
      if ($files_added == true)
      {
         $notify->Create('7', $_POST['task_id'], 'files');
      } else
      {
         $notify->Create('7', $_POST['task_id']);
      }

      $_SESSION['SUCCESS'] = $modify_text['commentadded'];
      $fs->redirect($fs->CreateURL('details', $_POST['task_id']));

   // If they pressed submit without actually typing anything
   } else
   {
      $_SESSION['ERROR'] = $modify_text['nocommententered'];
      $fs->redirect($fs->CreateURL('details', $_POST['task_id']));
   }


// End of adding a comment


/////////////////////////////////////////////////////
// Start of sending a new user a confirmation code //
/////////////////////////////////////////////////////

} elseif ($_POST['action'] == 'sendcode')
{
   if (!empty($_POST['user_name'])
         && !empty($_POST['real_name'])
         && (($_POST['email_address'] != '' && $_POST['notify_type'] == '1')
               OR ($_POST['jabber_id'] != '' && $_POST['notify_type'] == '2'))
   )
   {


      // Check to see if the username is available
      $check_username = $db->Query("SELECT * FROM {$dbprefix}users WHERE user_name = ?",
                                     array($_POST['user_name']));
      if ($db->CountRows($check_username))
      {
        echo "<p class=\"admin\">{$register_text['usernametaken']}<br>";
        echo "<a href=\"javascript:history.back();\">{$register_text['goback']}</a></p>";
      } else
      {
         // Delete registration codes older than 24 hours
         $now = date('U');
         $yesterday = $now - '86400';
         $remove = $db->Query("DELETE FROM {$dbprefix}registrations WHERE reg_time < ?",
                                array($yesterday));

         // Generate a random bunch of numbers for the confirmation code
         function make_seed()
         {
            list($usec, $sec) = explode(' ', microtime());
            return (float) $sec + ((float) $usec * 100000);
         }
         mt_srand(make_seed());
         $randval = mt_rand();

         // Convert those numbers to a seemingly random string using crypt
         $confirm_code = crypt($randval, $cookiesalt);

         // Generate a looonnnnggg random string to send as an URL to complete this registration
         $magic_url = md5(microtime());

         // Insert everything into the database
         $save_code = $db->Query("INSERT INTO {$dbprefix}registrations
                                  (reg_time,
                                  confirm_code,
                                  user_name,
                                  real_name,
                                  email_address,
                                  jabber_id,
                                  notify_type,
                                  magic_url)
                                  VALUES (?,?,?,?,?,?,?,?)",
                                array($now,
                                      $confirm_code,
                                      $_POST['user_name'],
                                      $_POST['real_name'],
                                      $_POST['email_address'],
                                      $_POST['jabber_id'],
                                      $_POST['notify_type'],
                                      $magic_url
                                      )
                              );

$subject = $modify_text['noticefrom'] . ' Flyspray';

$message = "{$register_text['noticefrom']} {$flyspray_prefs['project_title']}\n
{$modify_text['addressused']}\n
{$conf['general']['baseurl']}index.php?do=register&magic=$magic_url \n
{$modify_text['confirmcodeis']}\n
{$confirm_code}";

      // Check how they want to receive their code
      if ($_POST['notify_type'] == '1')
      {
         $notify->SendEmail($_POST['email_address'], $subject, $message);

      } elseif ($_POST['notify_type'] == '2')
      {
         $notify->StoreJabber(array($_POST['jabber_id']), $subject,
            htmlentities($message),ENT_COMPAT,'utf-8');

      }

      // Let the user know what just happened
      echo "<div class=\"redirectmessage\"><p><em>{$modify_text['codesent']}</em></p></div>";

    // End of checking if the username is available
    }

  // If the form wasn't filled out correctly, show an error
  } else
  {
    // Error!
    echo "<div class=\"redirectmessage\"><p><em>{$modify_text['erroronform']}</em></p>";
    echo "<p><a href=\"javascript:history.back()\">{$modify_text['goback']}</a></p></div>";

  // End of checking that the form was completed correctly
  }


// End of sending a new user a confirmation code


//////////////////////////////////////////////////////////////////
// Start of new user self-registration with a confirmation code //
//////////////////////////////////////////////////////////////////

} elseif ($_POST['action'] == "registeruser" && $flyspray_prefs['anon_reg'] == '1')
{

   // If they filled in all the required fields
   if (!empty($_POST['user_pass'])
      && !empty($_POST['user_pass2'])
      && !empty($_POST['confirmation_code'])
    )
   {

      // If the passwords matched
      if ($_POST['user_pass'] == $_POST['user_pass2'])
      {
         // Check that the user entered the right confirmation code
         $code_check = $db->Query("SELECT * FROM {$dbprefix}registrations WHERE magic_url = ?", array($_POST['magic_url']));
         $reg_details = $db->FetchArray($code_check);

         // If the code is correct
         if ($reg_details['confirm_code'] == $_POST['confirmation_code'])
         {
            // Encrypt their password
            $pass_hash = $fs->cryptPassword($_POST['user_pass']);

            // Add the user to the database
            $add_user = $db->Query("INSERT INTO {$dbprefix}users
                                      (user_name,
                                       user_pass,
                                       real_name,
                                       jabber_id,
                                       email_address,
                                       notify_type,
                                       account_enabled,
                                       tasks_perpage)
                                       VALUES(?, ?, ?, ?, ?, ?, ?, ?)",
                                       array($reg_details['user_name'],
                                             $pass_hash,
                                             $reg_details['real_name'],
                                             $reg_details['jabber_id'],
                                             $reg_details['email_address'],
                                             $reg_details['notify_type'],
                                             '1',
                                             '25')
                                   );


            // Get this user's id for the record
            $result = $db->Query("SELECT * FROM {$dbprefix}users WHERE user_name = ?", array($reg_details['user_name']));
            $user_details = $db->FetchArray($result);

            // Now, create a new record in the users_in_groups table
            $set_global_group = $db->Query("INSERT INTO {$dbprefix}users_in_groups
                                          (user_id,
                                          group_id)
                                          VALUES(?, ?)",
                                          array($user_details['user_id'], $flyspray_prefs['anon_group']));

            // Let the user know what just happened
            echo "<div class=\"redirectmessage\"><p><em>{$modify_text['accountcreated']}</em></p>";
            echo "<p>{$modify_text['loginbelow']}</p>";
            echo "<p>{$modify_text['newuserwarning']}</p></div>";


         // If they didn't enter the right confirmation code
         } else
         {
            echo "<div class=\"redirectmessage\"><p><em>{$modify_text['confirmwrong']}</em></p>";
            echo "<p><a href=\"javascript:history.back();\">{$modify_text['goback']}</a></p></div>";
         };


      // If passwords didn't match
      } else
      {
         echo "<div class=\"redirectmessage\"><p><em>{$modify_text['nomatchpass']}</em></p><p><a href=\"javascript:history.back();\">{$modify_text['goback']}</a></p></div>";
      };

   // If they didn't fill in all the fields
   } else {
      echo "<div class=\"redirectessage\"><p><em>{$modify_text['formnotcomplete']}</em></p><p><a href=\"javascript:history.back();\">{$modify_text['goback']}</a></p></div>";
   };

// End of registering a new user

///////////////////////////////////////////////////////////////
// Start of user self-registration without confirmation code //
// Or, by an admin                                           //
///////////////////////////////////////////////////////////////

} elseif ($_POST['action'] == "newuser"
           && (@$permissions['is_admin'] == '1'
                OR ($flyspray_prefs['anon_reg'] == '1'
                    && $flyspray_prefs['spam_proof'] != '1')))
{

  // If they filled in all the required fields
  if (!empty($_POST['user_name'])
    && !empty($_POST['user_pass'])
    && !empty($_POST['user_pass2'])
    && !empty($_POST['real_name'])
    && (!empty($_POST['email_address']) OR !empty($_POST['jabber_id']))
    ) {

    // Check to see if the username is available
    $check_username = $db->Query("SELECT * FROM {$dbprefix}users WHERE user_name = ?", array($_POST['user_name']));
    if ($db->CountRows($check_username)) {
      echo "<div class=\"redirectmessage\"><p><em>{$modify_text['usernametaken']}</em></p>";
      echo "<p><a href=\"javascript:history.back();\">{$modify_text['goback']}</a></p></div>";
    } else {

      // If the passwords matched, add the user
      if (($_POST['user_pass'] == $_POST['user_pass2']) && $_POST['user_pass'] != '') {

        $pass_hash = $fs->cryptPassword($_POST['user_pass']);

        if (@$permissions['is_admin'] == '1') {
          $group_in = $_POST['group_in'];
        } else {
          $group_in = $flyspray_prefs['anon_group'];
        };

        $add_user = $db->Query("INSERT INTO {$dbprefix}users
                                    (user_name,
                                     user_pass,
                                     real_name,
                                     jabber_id,
                                     email_address,
                                     notify_type,
                                     account_enabled,
                                     tasks_perpage)
                                     VALUES( ?, ?, ?, ?, ?, ?, ?, ?)",
                                    array($_POST['user_name'],
                                          $pass_hash,
                                          $_POST['real_name'],
                                          $_POST['jabber_id'],
                                          $_POST['email_address'],
                                          $_POST['notify_type'],
                                          '1',
                                          '25')
                                 );

        // Get this user's id for the record
        $result = $db->Query("SELECT * FROM {$dbprefix}users WHERE user_name = ?", array($_POST['user_name']));
        $user_details = $db->FetchArray($result);

        // Now, create a new record in the users_in_groups table
        $set_global_group = $db->Query("INSERT INTO {$dbprefix}users_in_groups
                                          (user_id,
                                          group_id)
                                          VALUES( ?, ?)",
                                          array($user_details['user_id'], $group_in));

        if (@$permissions['is_admin'] != '1') {
          echo "<p>{$modify_text['loginbelow']}</p>";
          echo "<p>{$modify_text['newuserwarning']}</p></div>";
        } else
        {
          $_SESSION['SUCCESS'] = $modify_text['newusercreated'];
          $fs->redirect($fs->CreateURL('admin', 'groups'));
        }


      } else
      {
        echo "<div class=\"redirectmessage\"><p><em>{$modify_text['nomatchpass']}</em></p><p><a href=\"javascript:history.back();\">{$modify_text['goback']}</a></p></div>";
      }

    }

  } else
  {
    echo "<div class=\"redirectmessage\"><p><em>{$modify_text['formnotcomplete']}</em></p><p><a href=\"javascript:history.back();\">{$modify_text['goback']}</a></p></div>";
  }

// End of adding a new user by an admin

/////////////////////////////////
// Start of adding a new group //
/////////////////////////////////

} elseif ($_POST['action'] == "newgroup"
          && ((!empty($_POST['belongs_to_project']) && $permissions['manage_project'] == '1')
          OR $permissions['is_admin'] == '1') )
{
   // If they filled in all the required fields
   if (!empty($_POST['group_name']) && !empty($_POST['group_desc']))
   {
      // Check to see if the group name is available
      $check_groupname = $db->Query("SELECT * FROM {$dbprefix}groups
                                     WHERE group_name = ?
                                     AND belongs_to_project = ?",
                                     array($_POST['group_name'],
                                           $_POST['project'])
                                   );

      if ($db->CountRows($check_groupname))
      {
         echo "<div class=\"redirectmessage\"><p><em>{$modify_text['groupnametaken']}</em></p><p><a href=\"javascript:history.back();\">{$modify_text['goback']}</a></p></div>";
      } else
      {
         $db->Query("INSERT INTO {$dbprefix}groups
                     (group_name,
                      group_desc,
                      belongs_to_project,
                      manage_project,
                      view_tasks,
                      open_new_tasks,
                      modify_own_tasks,
                      modify_all_tasks,
                      view_comments,
                      add_comments,
                      edit_comments,
                      delete_comments,
                      create_attachments,
                      delete_attachments,
                      view_history,
                      close_own_tasks,
                      close_other_tasks,
                      assign_to_self,
                      assign_others_to_self,
                      view_reports,
                      group_open)
                      VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                      array($_POST['group_name'], $_POST['group_desc'],
                      $db->emptyToZero($_POST['project']),
                      $db->emptyToZero($_POST['manage_project']),
                      $db->emptyToZero($_POST['view_tasks']),
                      $db->emptyToZero($_POST['open_new_tasks']),
                      $db->emptyToZero($_POST['modify_own_tasks']),
                      $db->emptyToZero($_POST['modify_all_tasks']),
                      $db->emptyToZero($_POST['view_comments']),
                      $db->emptyToZero($_POST['add_comments']),
                      $db->emptyToZero($_POST['edit_comments']),
                      $db->emptyToZero($_POST['delete_comments']),
                      $db->emptyToZero($_POST['create_attachments']),
                      $db->emptyToZero($_POST['delete_attachments']),
                      $db->emptyToZero($_POST['view_history']),
                      $db->emptyToZero($_POST['close_own_tasks']),
                      $db->emptyToZero($_POST['close_other_tasks']),
                      $db->emptyToZero($_POST['assign_to_self']),
                      $db->emptyToZero($_POST['assign_others_to_self']),
                      $db->emptyToZero($_POST['view_reports']),
                      $db->emptyToZero($_POST['group_open']))
                    );

         $_SESSION['SUCCESS'] = $modify_text['newgroupadded'];
         if (empty($_POST['project']) )
         {
            $fs->redirect($fs->CreateURL('admin', 'groups'));
         } else
         {
            $fs->redirect($fs->CreateURL('pm', 'groups', $_POST['project']));
         }
      }

   } else {
      echo "<div class=\"redirectmessage\"><p><em>{$modify_text['formnotcomplete']}</em></p><p><a href=\"javascript:history.back();\">{$modify_text['goback']}</a></p></div>";
   }
// End of adding a new group

///////////////////////////////////////////////
// Update the global application preferences //
///////////////////////////////////////////////

} elseif ($_POST['action'] == "globaloptions"
          && $permissions['is_admin'] == '1')
{
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'jabber_server'", array($_POST['jabber_server']));
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'jabber_port'", array($_POST['jabber_port']));
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'jabber_username'", array($_POST['jabber_username']));
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'jabber_password'", array($_POST['jabber_password']));
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'anon_group'", array($_POST['anon_group']));

   /*$base_url = trim($_POST['base_url']);

   if (substr($base_url,-1,1) != '/')
   {
      $base_url .= '/';
   }

   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'base_url'", array($base_url));
*/
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'user_notify'", array($_POST['user_notify']));
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'admin_email'", array($_POST['admin_email']));
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'lang_code'", array($_POST['lang_code']));
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'spam_proof'", array($_POST['spam_proof']));
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'default_project'", array($_POST['default_project']));
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'dateformat'", array($_POST['dateformat']));
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'dateformat_extended'", array($_POST['dateformat_extended']));
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'anon_reg'", array($_POST['anon_reg']));
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'global_theme'", array($_POST['global_theme']));
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'smtp_server'", array($_POST['smtp_server']));
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'smtp_user'", array($_POST['smtp_user']));
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'smtp_pass'", array($_POST['smtp_pass']));
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'funky_urls'", array($_POST['funky_urls']));
   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'reminder_daemon'", array($_POST['reminder_daemon']));

   // Process the list of groups into a format we can store
   foreach ($_POST['assigned_groups'] as $group_id => $val)
      $assigned_groups .= $group_id . ' ';

   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'assigned_groups'", array($assigned_groups));


   // Process the list of visible columns into format we can store
   foreach ($_POST['visible_columns'] as $column => $val)
      $columnlist .= $column . ' ';

   $update = $db->Query("UPDATE {$dbprefix}prefs SET pref_value = ? WHERE pref_name = 'visible_columns'", array($columnlist));


   $_SESSION['SUCCESS'] = $modify_text['optionssaved'];
   $fs->redirect($fs->CreateURL('admin','prefs'));

// End of updating application preferences

///////////////////////////////////
// Start of adding a new project //
///////////////////////////////////

} elseif ($_POST['action'] == "newproject"
          && $permissions['is_admin'] == '1') {

   if ($_POST['project_title'] != '') {

      // FIXME: Temporary workaround to supress notices
      if (empty($_POST['show_logo']) )
         $_POST['show_logo'] = '0';

      if (empty($_POST['others_view']) )
         $_POST['others_view'] = '0';

      if (empty($_POST['anon_open']) )
         $_POST['anon_open'] = '0';


      $insert = $db->Query("INSERT INTO {$dbprefix}projects
                              (project_title,
                              theme_style,
                              show_logo,
                              intro_message,
                              others_view,
                              anon_open,
                              project_is_active,
                              visible_columns)
                              VALUES (?, ?, ?, ?, ?, ?, ?, ?)",
                            array($_POST['project_title'],
                              $_POST['theme_style'],
                              $db->emptyToZero($_POST['show_logo']),
                              $_POST['intro_message'],
                              $db->emptyToZero($_POST['others_view']),
                              $db->emptyToZero($_POST['anon_open']),
                              '1',
                              'id tasktype severity summary status dueversion progress',
                              ));

    $result = $db->Query("SELECT project_id FROM {$dbprefix}projects ORDER BY project_id DESC", false, 1);
    $newproject = $db->FetchArray($result);

      $add_group = $db->Query("INSERT INTO {$dbprefix}groups
                                      (group_name,
                                      group_desc,
                                      belongs_to_project,
                                      manage_project,
                                      view_tasks,
                                      open_new_tasks,
                                      modify_own_tasks,
                                      modify_all_tasks,
                                      view_comments,
                                      add_comments,
                                      edit_comments,
                                      delete_comments,
                                      create_attachments,
                                      delete_attachments,
                                      view_history,
                                      close_own_tasks,
                                      close_other_tasks,
                                      assign_to_self,
                                      assign_others_to_self,
                                      view_reports,
                                      group_open)
                                      VALUES( ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
                                      array('Project Managers', 'Permission to do anything related to this project.' ,
                                            $db->emptyToZero($newproject['project_id']),
                                            '1',
                                            '1',
                                            '1',
                                            '1',
                                            '1',
                                            '1',
                                            '1',
                                            '1',
                                            '1',
                                            '1',
                                            '1',
                                            '1',
                                            '1',
                                            '1',
                                            '1',
                                            '1',
                                            '1',
                                            '1')
                                     );

    $insert = $db->Query("INSERT INTO {$dbprefix}list_category
                             (project_id, category_name, list_position,
                             show_in_list, category_owner)
                             VALUES ( ?, ?, ?, ?, ?)",
                             array($newproject['project_id'],
                            'Backend / Core', '1', '1', '0'));

    $insert = $db->Query("INSERT INTO {$dbprefix}list_os
                             (project_id, os_name, list_position,
                             show_in_list)
                             VALUES (?,?,?,?)",
                             array($newproject['project_id'], 'All', '1', '1'));

    $insert = $db->Query("INSERT INTO {$dbprefix}list_version
                             (project_id, version_name, list_position,
                             show_in_list, version_tense)
                             VALUES (?, ?, ?, ?, ?)",
                        array($newproject['project_id'], '1.0', '1', '1', '2'));

    echo "<div class=\"redirectmessage\"><p><em>{$modify_text['projectcreated']}";
    echo "<br><br><a href=\"" . $fs->CreateURL('pm', 'prefs', $newproject['project_id']) . "\">{$modify_text['customiseproject']}</a></em></p></div>";

  } else {

    echo "<div class=\"errormessage\"><p><em>{$modify_text['emptytitle']}</em></p></div>";

  };

// End of adding a new project

///////////////////////////////////////////
// Start of updating project preferences //
///////////////////////////////////////////

} elseif ($_POST['action'] == 'updateproject' && $permissions['manage_project'] == '1')
{
   if (!empty($_POST['project_title']))
   {
      $update = $db->Query("UPDATE {$dbprefix}projects SET
                            project_title = ?,
                            theme_style = ?,
                            show_logo = ?,
                            inline_images = ?,
                            default_cat_owner = ?,
                            intro_message = ?,
                            project_is_active = ?,
                            others_view = ?,
                            anon_open = ?,
                            notify_email = ?,
                            notify_email_when = ?,
                            notify_jabber = ?,
                            notify_jabber_when = ?
                            WHERE project_id = ?",
                            array($_POST['project_title'],
                                    $_POST['theme_style'],
                                    $db->emptyToZero($_POST['show_logo']),
                                    $db->emptyToZero($_POST['inline_images']),
                                    $db->emptyToZero($_POST['default_cat_owner']),
                                    $_POST['intro_message'],
                                    $db->emptyToZero($_POST['project_is_active']),
                                    $db->emptyToZero($_POST['others_view']),
                                    $db->emptyToZero($_POST['anon_open']),
                                    $_POST['notify_email'],
                                    $db->emptyToZero($_POST['notify_email_type']),
                                    $_POST['notify_jabber'],
                                    $db->emptyToZero($_POST['notify_jabber_type']),
                                    $_POST['project_id']));

      // Process the list of visible columns into a format we can store
      foreach ($_POST['visible_columns'] as $column => $val)
         $columnlist .= $column . ' ';

      $update = $db->Query("UPDATE {$dbprefix}projects SET visible_columns = ? WHERE project_id = ?", array($columnlist, $_POST['project_id']));


      $_SESSION['SUCCESS'] = $modify_text['projectupdated'];
      $fs->redirect($fs->CreateURL('pm', 'prefs', $project_id));

   } else
   {
      echo "<div class=\"redirectmessage\"><p><em>{$modify_text['emptytitle']}</em></p></div>";
   }


// End of updating project preferences

//////////////////////////////////////
// Start of uploading an attachment //
//////////////////////////////////////

} elseif ($_POST['action'] == "addattachment"
          && $permissions['create_attachments'] == '1')
{
   // This function came from the php function page for mt_srand()
   // seed with microseconds to create a random filename
   function make_seed()
   {
      list($usec, $sec) = explode(' ', microtime());
      return (float) $sec + ((float) $usec * 100000);
   }

   mt_srand(make_seed());
   $randval = mt_rand();
   $file_name = $_POST['task_id']."_$randval";

   // If there is a file attachment to be uploaded, upload it
   if ($_FILES['userfile']['name'])
   {
      // Then move the uploaded file into the attachments directory and remove exe permissions
      @move_uploaded_file($_FILES['userfile']['tmp_name'], "attachments/$file_name");
      @chmod("attachments/$file_name", 0644);

      // Only add the listing to the database if the file was actually uploaded successfully
      if (file_exists("attachments/$file_name"))
      {
         $file_desc = $_POST['file_desc'];
         $add_to_db = $db->Query("INSERT INTO {$dbprefix}attachments
                                  (task_id, orig_name, file_name, file_desc,
                                  file_type, file_size, added_by, date_added)
                                  VALUES ( ?, ?, ?, ?, ?, ?, ?, ?)",
                                  array($_POST['task_id'],
                                       $_FILES['userfile']['name'],
                                       $file_name, $file_desc,
                                       $_FILES['userfile']['type'],
                                       $_FILES['userfile']['size'],
                                       $_COOKIE['flyspray_userid'],
                                       $now)
                                 );

         $notify->Create('8', $_POST['task_id']);

         $result = $db->Query("SELECT attachment_id FROM {$dbprefix}attachments WHERE task_id = ? ORDER BY attachment_id DESC", array($_POST['task_id']), 1);
         $row = $db->FetchRow($result);
         $fs->logEvent($_POST['task_id'], 7, $row['attachment_id']);

         // Success message!
         $_SESSION['SUCCESS'] = $modify_text['fileuploaded'];
         $fs->redirect($fs->CreateURL('details', $_POST['task_id']));

      // If the file didn't actually get saved, better show an error to that effect
      } else
      {
         $_SESSION['ERROR'] = $modify_text['fileerror'];
         $fs->redirect($fs->CreateURL('details', $_POST['task_id']));
      }

   // If there wasn't a file uploaded with a description, show an error
   } else
   {
      $_SESSION['ERROR'] = $modify_text['selectfileerror'];
      $fs->redirect($fs->CreateURL('details', $_POST['task_id']));
   }
// End of uploading an attachment

/////////////////////////////////////
// Start of modifying user details //
/////////////////////////////////////

} elseif ($_POST['action'] == "edituser"
          && ($permissions['is_admin'] == '1'
              OR ($current_user['user_id'] == $_POST['user_id'])))
{
   // If they filled in all the required fields
   if (!empty($_POST['real_name'])
       && (!empty($_POST['email_address'])
          OR !empty($_POST['jabber_id']))
      )
   {
      //If the user entered matching password and confirmation
      //we can change the selected user's password
      $password_problem = false;
      if ($_POST['changepass'] || $_POST['confirmpass'])
      {
         //check that the entered passwords match
         if ($_POST['changepass'] == $_POST['confirmpass'])
         {
            $new_pass = $_POST['changepass'];
            $new_pass_hash = $fs->cryptPassword($new_pass);
            $update_pass = $db->Query("UPDATE {$dbprefix}users SET user_pass = '$new_pass_hash' WHERE user_id = ?", array($_POST['user_id']));

            // If the user is changing their password, better update their cookie hash
            if ($_COOKIE['flyspray_userid'] == $_POST['user_id'])
            {
               setcookie('flyspray_passhash', crypt("$new_pass_hash", $cookiesalt), time()+60*60*24*30, "/");
            }

         } else
         {
            echo "<div class=\"redirectmessage\"><p><em>{$modify_text['passnomatch']}</em></p>";
            echo "<p><a href=\"javascript:history.back();\">{$modify_text['goback']}</a></p></div>";
            $password_problem = true;
         }
      }

      if ($password_problem == false)
      {
         $update = $db->Query("UPDATE {$dbprefix}users SET
                                 real_name = ?,
                                 email_address = ?,
                                 jabber_id = ?,
                                 notify_type = ?,
                                 dateformat = ?,
                                 dateformat_extended = ?,
                                 tasks_perpage = ?
                                 WHERE user_id = ?",
                                 array(
                                       $_POST['real_name'],
                                       $_POST['email_address'],
                                       $_POST['jabber_id'],
                                       $db->emptyToZero($_POST['notify_type']),
                                       $_POST['dateformat'],
                                       $_POST['dateformat_extended'],
                                       $_POST['tasks_perpage'],
                                       $_POST['user_id']
                                      )
                              );

         if ($permissions['is_admin'] == '1' && !empty($_POST['group_in']))
         {
            $update = $db->Query("UPDATE {$dbprefix}users SET
                                  account_enabled = ?
                                  WHERE user_id = ?",
                                  array(
                                        $db->emptyToZero($_POST['account_enabled']),
                                        $_POST['user_id']
                                        )
                                );

            $update = $db->Query("UPDATE {$dbprefix}users_in_groups SET
                                  group_id = ?
                                  WHERE record_id = ?",
                                  array($_POST['group_in'], $_POST['record_id'])
                              );

         }

         $_SESSION['SUCCESS'] = $modify_text['userupdated'];
         $fs->redirect($_POST['prev_page']);
      };

   } else
   {
      $_SESSION['ERROR'] = $modify_text['realandnotify'];
      $fs->redirect($_POST['prev_page']);
   }
   // End of modifying user details

//////////////////////////////////////////
// Start of updating a group definition //
//////////////////////////////////////////

} elseif ($_POST['action'] == "editgroup"
          && ($permissions['is_admin'] == '1'
              OR $permissions['manage_project'] == '1'))
{
   if ($_POST['group_name'] != ''
     && $_POST['group_desc'] != '')
   {
      $update = $db->Query("UPDATE {$dbprefix}groups SET
                             group_name = ?,
                             group_desc = ?,
                             manage_project = ?,
                             view_tasks = ?,
                             open_new_tasks = ?,
                             modify_own_tasks = ?,
                             modify_all_tasks = ?,
                             view_comments = ?,
                             add_comments = ?,
                             edit_comments = ?,
                             delete_comments = ?,
                             view_attachments = ?,
                             create_attachments = ?,
                             delete_attachments = ?,
                             view_history = ?,
                             close_own_tasks = ?,
                             close_other_tasks = ?,
                             assign_to_self = ?,
                             assign_others_to_self = ?,
                             view_reports = ?,
                             group_open = ?
                             WHERE group_id = ?",
                             array($_POST['group_name'], $_POST['group_desc'],
                                   $db->emptyToZero($_POST['manage_project']),
                                   $db->emptyToZero($_POST['view_tasks']),
                                   $db->emptyToZero($_POST['open_new_tasks']),
                                   $db->emptyToZero($_POST['modify_own_tasks']),
                                   $db->emptyToZero($_POST['modify_all_tasks']),
                                   $db->emptyToZero($_POST['view_comments']),
                                   $db->emptyToZero($_POST['add_comments']),
                                   $db->emptyToZero($_POST['edit_comments']),
                                   $db->emptyToZero($_POST['delete_comments']),
                                   $db->emptyToZero($_POST['view_attachments']),
                                   $db->emptyToZero($_POST['create_attachments']),
                                   $db->emptyToZero($_POST['delete_attachments']),
                                   $db->emptyToZero($_POST['view_history']),
                                   $db->emptyToZero($_POST['close_own_tasks']),
                                   $db->emptyToZero($_POST['close_other_tasks']),
                                   $db->emptyToZero($_POST['assign_to_self']),
                                   $db->emptyToZero($_POST['assign_others_to_self']),
                                   $db->emptyToZero($_POST['view_reports']),
                                   $db->emptyToZero($_POST['group_open']),
                                   $_POST['group_id']
                                  )
                            );


      // Get the group definition that this group belongs to
      $result = $db->Query("SELECT * FROM {$dbprefix}groups WHERE group_id = ?", array($_POST['group_id']));
      $group_details = $db->FetchArray($result);

      $_SESSION['SUCCESS'] = $modify_text['groupupdated'];
      $fs->redirect($_POST['prev_page']);

   } else
   {
      echo "<div class=\"redirectmessage\"><p><em>{$modify_text['groupanddesc']}</em></p><p><a href=\"javascript:history.back();\">{$modify_text['goback']}</a></p></div>";
   }
// End of updating group definition

//////////////////////////////
// Start of updating a list //
//////////////////////////////

} elseif ($_POST['action'] == "update_list"
          && ($permissions['is_admin'] == '1'
              OR $permissions['manage_project'] == '1')) {

  $listname = $_POST['list_name'];
  $listposition = $_POST['list_position'];
  $listshow = $_POST['show_in_list'];
  $listdelete = $_POST['delete'];
  $listid = $_POST['id'];

  $redirectmessage = $modify_text['listupdated'];

  for($i = 0; $i < count($listname); $i++) {
      $listname[$i] = stripslashes($listname[$i]);
      if($listname[$i] != ''
          && is_numeric($listposition[$i])
          ) {
          $update = $db->Query("UPDATE $list_table_name SET
                                    $list_column_name = ?,
                                    list_position = ?,
                                    show_in_list = ?
          WHERE $list_id = '{$listid[$i]}'",
          array($listname[$i], $listposition[$i],
                $db->emptyToZero($listshow[$i])
                ));
      }
      else {
          $redirectmessage = $modify_text['listupdated'] . " " . $modify_text['fieldsmissing'];
      };
  };

  if (is_array($listdelete)) {
      $deleteids = "$list_id = " . join(" OR $list_id =", array_keys($listdelete));
      $db->Query("DELETE FROM $list_table_name WHERE $deleteids");
  }

   $_SESSION['SUCCESS'] = $redirectmessage;
   $fs->redirect($_POST['prev_page']);


// End of updating a list

/////////////////////////////////
// Start of adding a list item //
/////////////////////////////////

} elseif ($_POST['action'] == "add_to_list"
   && $permissions['manage_project'] == '1')
{

   if (!empty($_POST['list_name'])
    && !empty($_POST['list_position']) )
   {
      // If the user is requesting a project-level addition
      if (!empty($_POST['project_id']))
      {
         $db->Query("INSERT INTO $list_table_name
                     (project_id, $list_column_name, list_position, show_in_list)
                     VALUES (?, ?, ?, ?)",
                     array($_POST['project_id'], $_POST['list_name'], $_POST['list_position'], '1'));

         // Redirect
         $_SESSION['SUCCESS'] = $modify_text['listitemadded'];
         $fs->redirect($_POST['prev_page']);

      // If the user is requesting a global list addition
      } else
      {
         $db->Query("INSERT INTO $list_table_name
                    ($list_column_name, list_position, show_in_list, project_id)
                    VALUES (?, ?, ?, ?)",
                    array($_POST['list_name'], $_POST['list_position'], '1', '0'));

         // Redirect
         $_SESSION['SUCCESS'] = $modify_text['listitemadded'];
         $fs->redirect($_POST['prev_page']);
      }


   } else
   {
      $_SESSION['ERROR'] = $modify_text['fillallfields'];
      $fs->redirect($_POST['prev_page']);
   }
// End of adding a list item

////////////////////////////////////////
// Start of updating the version list //
////////////////////////////////////////

} elseif ($_POST['action'] == "update_version_list"
 && ($permissions['is_admin'] == '1'
     OR $permissions['manage_project'] == '1'))
{

  $listname = $_POST['list_name'];
  $listposition = $_POST['list_position'];
  $listshow = $_POST['show_in_list'];
  $listtense = $_POST['version_tense'];
  $listdelete = $_POST['delete'];
  $listid = $_POST['id'];

  $redirectmessage = $modify_text['listupdated'];

   for($i = 0; $i < count($listname); $i++)
   {
      $listname[$i] = stripslashes($listname[$i]);
      if($listname[$i] != ''
          && is_numeric($listposition[$i]))
      {
         $update = $db->Query("UPDATE $list_table_name SET
                               $list_column_name = ?,
                               list_position = ?,
                               show_in_list = ?,
                               version_tense = ?
                               WHERE $list_id = '{$listid[$i]}'",
                               array($listname[$i], $listposition[$i],
                               $db->emptyToZero($listshow[$i]),
                               $listtense[$i])
                             );
      } else
      {
          $redirectmessage = $modify_text['listupdated'] . " " . $modify_text['fieldsmissing'];
      }
   }

  if (is_array($listdelete)) {
      $deleteids = "$list_id = " . join(" OR $list_id =", array_keys($listdelete));
      $db->Query("DELETE FROM $list_table_name WHERE $deleteids");
  }

  $_SESSION['SUCCESS'] = $redirectmessage;
  $fs->redirect($_POST['prev_page']);

// End of updating the version list

/////////////////////////////////////////
// Start of adding a version list item //
/////////////////////////////////////////

} elseif ($_POST['action'] == "add_to_version_list"
          && $permissions['manage_project'] == '1')
{
   if ($_POST['list_name'] != ''
    && $_POST['list_position'] != '')
   {
      $update = $db->Query("INSERT INTO $list_table_name
                           (project_id, $list_column_name, list_position, show_in_list, version_tense)
                           VALUES (?, ?, ?, ?, ?)",
                           array($_POST['project_id'], $_POST['list_name'], $_POST['list_position'], '1', $_POST['version_tense']));

      $_SESSION['SUCCESS'] = $modify_text['listitemadded'];
      $fs->redirect($_POST['prev_page']);

   } else
   {
      $_SESSION['ERROR'] = $modify_text['fillallfields'];
      $fs->redirect($_POST['prev_page']);
   }
// End of adding a version list item



////////////////////////////////////////////
// Start of updating the category list    //
// Category lists are slightly different, //
// requiring their own update section     //
////////////////////////////////////////////

} elseif ($_POST['action'] == "update_category"
          && ($permissions['is_admin'] == '1'
              OR $permissions['manage_project'] == '1')) {

  $listname = $_POST['list_name'];
  $listposition = $_POST['list_position'];
  $listshow = $_POST['show_in_list'];
  $listid = $_POST['id'];
  $listowner = $_POST['category_owner'];
  $listdelete = $_POST['delete'];

  $redirectmessage = $modify_text['listupdated'];

  for($i = 0; $i < count($listname); $i++) {
      $listname[$i] = stripslashes($listname[$i]);
      if ($listname[$i] != ''
          && is_numeric($listposition[$i])
          ) {
          $update = $db->Query("UPDATE {$dbprefix}list_category SET
                                    category_name = ?,
                                    list_position = ?,
                                    show_in_list = ?,
                                    category_owner = ?
                              WHERE category_id = ?",
                              array($listname[$i], $listposition[$i],
                              $db->emptyToZero($listshow[$i]),
                              $db->emptyToZero($listowner[$i]),
                              $listid[$i]));
      }
      else {
          $redirectmessage = $modify_text['listupdated'] . " " . $modify_text['fieldsmissing'];
      };
  };

  if (is_array($listdelete)) {
      $deleteids = "$list_id = " . join(" OR $list_id =", array_keys($listdelete));
      $db->Query("DELETE FROM {$dbprefix}list_category WHERE $deleteids");
  }

  $_SESSION['SUCCESS'] = $redirectmessage;
  $fs->redirect($_POST['prev_page']);

// End of updating the category list

//////////////////////////////////////////
// Start of adding a category list item //
//////////////////////////////////////////

} elseif ($_POST['action'] == "add_category"
          && ($permissions['is_admin'] == '1'
              OR $permissions['manage_project'] == '1')) {

  if ($_POST['list_name'] != ''
    && $_POST['list_position'] != ''
    ) {
      $update = $db->Query("INSERT INTO {$dbprefix}list_category
                                (project_id, category_name, list_position,
                                show_in_list, category_owner, parent_id)
                                VALUES (?, ?, ?, ?, ?, ?)",
                        array(
			$db->emptyToZero($_POST['project_id']),
			$_POST['list_name'],
                        $_POST['list_position'],
                        '1',
                        $db->emptyToZero($_POST['category_owner']),
                        $db->emptyToZero($_POST['parent_id'])));

      $_SESSION['SUCCESS'] = $modify_text['listitemadded'];
      $fs->redirect($_POST['prev_page']);

} else {
    $_SESSION['ERROR'] = $modify_text['fillallfields'];
    $fs->redirect($_POST['prev_page']);
};
// End of adding a category list item

//////////////////////////////////////////
// Start of adding a related task entry //
//////////////////////////////////////////

} elseif ($_POST['action'] == 'add_related'
          && ($permissions['modify_all_tasks'] == '1'
               OR ($permissions['modify_own_tasks'] == '1' && $old_details['assigned_to'] == $current_user['user_id']))) {

  if (is_numeric($_POST['related_task'])) {
    $check = $db->Query("SELECT * FROM {$dbprefix}related
        WHERE this_task = ?
        AND related_task = ?",
        array($_POST['this_task'], $_POST['related_task']));
    $check2 = $db->Query("SELECT attached_to_project FROM {$dbprefix}tasks
        WHERE task_id = ?",
        array($_POST['related_task']));

    if ($db->CountRows($check) > 0)
    {
        $_SESSION['ERROR'] = $modify_text['relatederror'];
        $fs->redirect($fs->CreateURL('details', $_POST['this_task'].'#related'));

    } elseif (!$db->CountRows($check2))
    {
        $_SESSION['ERROR'] = $modify_text['relatedinvalid'];
        $fs->redirect($fs->CreateURL('details', $_POST['this_task'].'#related'));
    } else
    {
        list($relatedproject) = $db->FetchRow($check2);
        if ($project_id == $relatedproject || isset($_POST['allprojects'])) {
            $insert = $db->Query("INSERT INTO {$dbprefix}related (this_task, related_task) VALUES(?,?)", array($_POST['this_task'], $_POST['related_task']));

            $fs->logEvent($_POST['this_task'], 11, $_POST['related_task']);
            $fs->logEvent($_POST['related_task'], 15, $_POST['this_task']);

            $notify->Create('9', $_POST['this_task']);


            $_SESSION['SUCCESS'] = $modify_text['relatedadded'];
            $fs->redirect($fs->CreateURL('details', $_POST['this_task'].'#related'));

        } else {
            ?>
            <div class="redirectmessage">
                <p><em><?php echo $modify_text['relatedproject'];?></em></p>
                <form action="index.php" method="post">
                    <input type="hidden" name="do" value="modify">
                    <input type="hidden" name="action" value="add_related">
                    <input type="hidden" name="this_task" value="<?php echo $_POST['this_task'];?>">
                    <input type="hidden" name="related_task" value="<?php echo $_POST['related_task'];?>">
                    <input type="hidden" name="allprojects" value="1">
                    <input class="adminbutton" type="submit" value="<?php echo $modify_text['addanyway'];?>">
                </form>
                <form action="index.php" method="get">
                    <input type="hidden" name="do" value="details">
                    <input type="hidden" name="id" value="<?php echo $_POST['this_task'];?>">
                    <input type="hidden" name="area" value="related">
                    <input class="adminbutton" type="submit" value="<?php echo $modify_text['cancel'];?>">
                </form>
            </div>
            <?php
        };
    };
  } else {
    $_SESSION['ERROR'] = $modify_text['relatedinvalid'];
    $fs->redirect($fs->CreateURL('details', $_POST['this_task'].'#related'));
  };

// End of adding a related task entry

///////////////////////////////////
// Removing a related task entry //
///////////////////////////////////

} elseif ($_POST['action'] == "remove_related"
          && ($permissions['modify_all_jobs'] == '1'
               OR ($permissions['modify_own_tasks'] == '1'))) { // FIX THIS PERMISSION!!

  $remove = $db->Query("DELETE FROM {$dbprefix}related WHERE related_id = ?", array($_POST['related_id']));

  $fs->logEvent($_POST['id'], 12, $_POST['related_task']);
  $fs->logEvent($_POST['related_task'], 16, $_POST['id']);

  $_SESSION['SUCCESS'] = $modify_text['relatedremoved'];
  $fs->redirect($fs->CreateURL('details', $_POST['id']));

// End of removing a related task entry

/////////////////////////////////////////////////////
// Start of adding a user to the notification list //
/////////////////////////////////////////////////////

} elseif ( isset($_REQUEST['action']) && $_REQUEST['action'] == "add_notification" )
{

   if ( isset($_REQUEST['prev_page']) )
   {
      $ids = $_REQUEST['ids'];
      $tasks = array();
      $redirect_url = $_REQUEST['prev_page'];

      if ( is_array($ids) && !empty($ids) )
      {
         foreach ( $ids AS $key => $val )
            array_push($tasks, $key);

         $be->AddToNotifyList($current_user['user_id'], $tasks);
      } else
      {
         $be->AddToNotifyList($_REQUEST['user_id'], array($_REQUEST['ids']));
      }

   } else
   {
      $be->AddToNotifyList($_REQUEST['user_id'], array($_REQUEST['ids']));
      $redirect_url = $fs->CreateURL('details', $_REQUEST['ids']);
   }

   $_SESSION['SUCCESS'] = $modify_text['notifyadded'];
   $fs->redirect($redirect_url.'#notify');

// End of adding a user to the notification list

////////////////////////////////////////////
// Start of removing a notification entry //
////////////////////////////////////////////

} elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == "remove_notification")
{
   if ( isset($_REQUEST['prev_page']) )
   {
      $ids = $_REQUEST['ids'];
      $tasks = array();
      $redirect_url = $_REQUEST['prev_page'];

      if (!empty($ids))
      {
         foreach ($ids AS $key => $val)
            array_push($tasks, $key);

         $be->RemoveFromNotifyList($current_user['user_id'], $tasks);
      }

   } else
   {
      $be->RemoveFromNotifyList($_REQUEST['user_id'], array($_REQUEST['ids']));
      $redirect_url = $fs->CreateURL('details', $_REQUEST['ids']);
   }

   $_SESSION['SUCCESS'] = $modify_text['notifyremoved'];
   $fs->redirect($redirect_url.'#notify');

// End of removing a notification entry

////////////////////////////////
// Start of editing a comment //
////////////////////////////////

} elseif ($_POST['action'] == "editcomment"
          && $permissions['edit_comments'] == '1')
{
   $update = $db->Query("UPDATE {$dbprefix}comments
                         SET comment_text = ?  WHERE comment_id = ?",
                         array($_POST['comment_text'], $_POST['comment_id']));

   $fs->logEvent($_POST['task_id'], 5, $_POST['comment_text'], $_POST['previous_text'], $_POST['comment_id']);

   $_SESSION['SUCCESS'] = $modify_text['editcommentsaved'];
   $fs->Redirect($fs->CreateURL('details', $_REQUEST['task_id']));

// End of editing a comment

/////////////////////////////////
// Start of deleting a comment //
/////////////////////////////////

} elseif ($_GET['action'] == "deletecomment"
&& $permissions['delete_comments'] == '1')
{
   $result = $db->Query("SELECT comment_text, user_id, date_added
                                        FROM {$dbprefix}comments
                                        WHERE comment_id = ?",
                                        array($_GET['comment_id'])
                           );
   $comment = $db->FetchRow($result);

   // Check for files attached to this comment
   $check_attachments = $db->Query("SELECT * FROM {$dbprefix}attachments
                                    WHERE comment_id = ?",
                                    array($_REQUEST['comment_id'])
                                  );

   if($db->CountRows($check_attachments) && $permissions['delete_attachments'] != '1')
   {
      $_SESSION['ERROR'] = $modify_text['commentattachperms'];
      $fs->redirect($fs->CreateURL('details', $_REQUEST['task_id']));

   } else
   {
      $db->Query("DELETE FROM {$dbprefix}comments
                  WHERE comment_id = ?",
                  array($_REQUEST['comment_id'])
                );

      $fs->logEvent($_REQUEST['task_id'], 6, $comment['user_id'], $comment['comment_text'], $comment['date_added']);

      while ($attachment = $db->FetchRow($check_attachments))
      {
         // Delete the attachment
         $db->Query("DELETE from {$dbprefix}attachments
                     WHERE attachment_id = ?",
                     array($attachment['attachment_id'])
                   );

         // Log to task history
         $fs->logEvent($attachment['task_id'], 8, $attachment['orig_name']);
      }

      $_SESSION['SUCCESS'] = $modify_text['commentdeleted'];
      $fs->redirect($fs->CreateURL('details', $_REQUEST['task_id']));

   // End of permission check
   }

// End of deleting a comment

/////////////////////////////////////
// Start of deleting an attachment //
/////////////////////////////////////

} elseif ($_REQUEST['action'] == 'deleteattachment'
          && $permissions['delete_attachments'] == '1')
{
   // if an attachment needs to be deleted do it right now
   $result = $db->Query("SELECT * FROM {$dbprefix}attachments
                         WHERE attachment_id = ?",
                         array($_REQUEST['id'])
                       );
   $row = $db->FetchArray($result);

   @unlink("attachments/" . $row['file_name']);
   $db->Query("DELETE FROM {$dbprefix}attachments
               WHERE attachment_id = ?",
               array($_REQUEST['id'])
             );

  $fs->logEvent($row['task_id'], 8, $row['orig_name']);

  $_SESSION['SUCCESS'] = $modify_text['attachmentdeleted'];
  $fs->redirect($fs->CreateURL('details', $row['task_id']));

// End of deleting an attachment

////////////////////////////////
// Start of adding a reminder //
////////////////////////////////

} elseif ($_POST['action'] == "addreminder"
          && ($permissions['manage_project'] == '1'
              OR $permissions['is_admin'] == '1')) {

  $now = date('U');

  $how_often = $_POST['timeamount1'] * $_POST['timetype1'];
  //echo "how often = $how_often<br>";
  //echo "now = $now<br>";

  $start_time = ($_POST['timeamount2'] * $_POST['timetype2']) + $now;
  //echo "start time = $start_time";

  $insert = $db->Query("INSERT INTO {$dbprefix}reminders (task_id, to_user_id, from_user_id, start_time, how_often, reminder_message) VALUES(?,?,?,?,?,?)", array($_POST['task_id'], $_POST['to_user_id'], $current_user['user_id'], $start_time, $how_often, $_POST['reminder_message']));

  $fs->logEvent($_POST['task_id'], 17, $_POST['to_user_id']);

  $_SESSION['SUCCESS'] = $modify_text['reminderadded'];
  $fs->redirect($fs->CreateURL('details', $_REQUEST['task_id']).'#remind');

// End of adding a reminder

//////////////////////////////////
// Start of removing a reminder //
//////////////////////////////////
} elseif ($_POST['action'] == "deletereminder"
          && ($permissions['manage_project'] == '1'
              OR $permissions['is_admin'] == '1')) {

  $result = $db->Query("SELECT to_user_id FROM {$dbprefix}reminders WHERE reminder_id = ?", array($_POST['reminder_id']));
  $reminder = $db->FetchRow($result);
  $db->Query("DELETE FROM {$dbprefix}reminders WHERE reminder_id = ?",
                    array($_POST['reminder_id']));

  $fs->logEvent($_POST['task_id'], 18, $reminder['to_user_id']);

  $_SESSION['SUCCESS'] = $modify_text['reminderdeleted'];
  $fs->redirect($fs->CreateURL('details', $_REQUEST['task_id']).'#remind');

// End of removing a reminder

/////////////////////////////////////////////////
// Start of adding a bunch of users to a group //
/////////////////////////////////////////////////
} elseif ($_POST['action'] == "addtogroup"
          && ($permissions['manage_project'] == '1'
              OR $permissions['is_admin'] == '1')) {

  // If no users were selected, throw an error
   if (!is_array($_POST['user_list']))
   {
      $_SESSION['ERROR'] = $modify_text['nouserselected'];
      $fs->redirect($_POST['prev_page']);

   // If users were select, keep going
   } else {

      // Cycle through the users passed to us
      //while (list($key, $val) = each($_POST['user_list'])) {
      foreach ($_POST['user_list'] AS $key => $val)
      {
         // Create entries for them that point to the requested group
         $create = $db->Query("INSERT INTO {$dbprefix}users_in_groups
                               (user_id, group_id)
                               VALUES(?, ?)",
                               array($val, $_POST['add_to_group'])
                             );
      }

   $_SESSION['SUCCESS'] = $modify_text['groupswitchupdated'];
   $fs->redirect($_POST['prev_page']);

   }

// End of adding a bunch of users to a group


///////////////////////////////////////////////
// Start of change a bunch of users' groups //
//////////////////////////////////////////////
} elseif ($_POST['action'] == 'movetogroup'
          && ($permissions['manage_project'] == '1'
              OR $permissions['is_admin'] == '1'))
{
   // Cycle through the array of user ids
   foreach ($_POST['users'] AS $user_id => $val)
   {
      // To be removed from a project entirely
      if ($_POST['switch_to_group'] == '0')
      {
         $db->Query("DELETE FROM {$dbprefix}users_in_groups
                     WHERE user_id = ? AND group_id = ?",
                     array($user_id, $_POST['old_group'])
                   );

      // Otherwise moved to another project/global group
      } else
      {
         $db->Query("UPDATE {$dbprefix}users_in_groups
                     SET group_id = ?
                     WHERE user_id = ? AND group_id = ?",
                     array($_POST['switch_to_group'], $user_id, $_POST['old_group']));
      }
   }

  $_SESSION['SUCCESS'] = $modify_text['groupswitchupdated'];
  $fs->redirect($_POST['prev_page']);

  // End of changing a bunch of users' groups

///////////////////////////////
// Start of taking ownership //
///////////////////////////////

} elseif ($_REQUEST['action'] == 'takeownership')
{
   if ( isset($_REQUEST['prev_page']) )
   {
      $ids = $_REQUEST['ids'];
      $tasks = array();
      $redirect_url = $_REQUEST['prev_page'];

      if (!empty($ids))
      {
         foreach ($ids AS $key => $val)
            array_push($tasks, $key);

         $be->AssignToMe($current_user['user_id'], $tasks);
      }

   } else
   {
      $be->AssignToMe($current_user['user_id'], array($_REQUEST['ids']));
      $redirect_url = $redirect_url = $fs->CreateURL('details', $_REQUEST['ids']);
   }

   $_SESSION['SUCCESS'] = $modify_text['takenownership'];
   $fs->redirect($redirect_url);

// End of taking ownership


//////////////////////////////////////
// Start of requesting task closure //
//////////////////////////////////////

} elseif ($_POST['action'] == 'requestclose')
{
   // Retrieve details on the task we want to close
   $task_details = $fs->GetTaskDetails($_POST['task_id']);

   // Log the admin request
   $fs->AdminRequest(1, $task_details['attached_to_project'], $_POST['task_id'], $current_user['user_id'], $_POST['reason_given']);

   // Log this event to the task history
   $fs->logEvent($_POST['task_id'], 20, $_POST['reason_given']);

   // Now, get the project managers' details for this project
   $get_pms = $db->Query("SELECT u.user_id
                          FROM {$dbprefix}users u
                          LEFT JOIN {$dbprefix}users_in_groups uig ON u.user_id = uig.user_id
                          LEFT JOIN {$dbprefix}groups g ON uig.group_id = g.group_id
                          WHERE g.belongs_to_project = ?
                          AND g.manage_project = '1'",
                          array($project_id)
                        );

   $pms = array();

   // Add each PM to the array
   while ($row = $db->FetchArray($get_pms))
   {
      array_push($pms, $row['user_id']);
   }

   // Call the functions to create the address arrays, and send notifications
   $to  = $notify->SpecificAddresses($pms);
   $msg = $notify->GenerateMsg('12', $_POST['task_id']);
   $mail = $notify->SendEmail($to[0], $msg[0], $msg[1]);
   $jabb = $notify->StoreJabber($to[1], $msg[0], $msg[1]);

   $_SESSION['SUCCESS'] = $modify_text['adminrequestmade'];
   $fs->redirect($fs->CreateURL('details', $_REQUEST['task_id']));


// End of requesting task closure

/////////////////////////////////////////
// Start of requesting task re-opening //
/////////////////////////////////////////

} elseif ($_POST['action'] == 'requestreopen')
{
   // Log the admin request
   $fs->AdminRequest(2, $project_id, $_POST['task_id'], $current_user['user_id'], $_POST['reason_given']);

   // Log this event to the task history
   $fs->logEvent($_POST['task_id'], 21, $_POST['reason_given']);

   // Check if the user is on the notification list
   $check_notify = $db->Query("SELECT * FROM {$dbprefix}notifications
                               WHERE task_id = ?
                               AND user_id = ?",
                               array($_POST['task_id'], $current_user['user_id'])
                             );

   if (!$db->CountRows($check_notify))
   {
      // Add the requestor to the task notification list, so that they know when it has been re-opened
      $be->AddToNotifyList($current_user['user_id'], array($_POST['task_id']));

      $fs->logEvent($_POST['task_id'], 9, $current_user['user_id']);
   }

   // Now, get the project managers details for this project
   $get_pms = $db->Query("SELECT u.user_id
                          FROM {$dbprefix}users u
                          LEFT JOIN {$dbprefix}users_in_groups uig ON u.user_id = uig.user_id
                          LEFT JOIN {$dbprefix}groups g ON uig.group_id = g.group_id
                          WHERE g.belongs_to_project = ?
                          AND g.manage_project = '1'",
                          array($project_id)
                        );

   $pms = array();

   // Add each PM to the array
   while ($row = $db->FetchArray($get_pms))
   {
      array_push($pms, $row['user_id']);
   }

   // Call the functions to create the address arrays, and send notifications
   $to  = $notify->SpecificAddresses($pms);
   $msg = $notify->GenerateMsg('12', $_POST['task_id']);
   $mail = $notify->SendEmail($to[0], $msg[0], $msg[1]);
   $jabb = $notify->StoreJabber($to[1], $msg[0], $msg[1]);


   $_SESSION['SUCCESS'] = $modify_text['adminrequestmade'];
   $fs->redirect($fs->CreateURL('details', $_REQUEST['task_id']));

// End of requesting task re-opening


///////////////////////////////////
// Start of denying a PM request //
///////////////////////////////////

} elseif (isset($_REQUEST['action']) && $_REQUEST['action'] == 'denypmreq' && $permissions['manage_project'] == '1')
{
   // Get info on the pm request
   $result = $db->Query("SELECT task_id
                         FROM {$dbprefix}admin_requests
                         WHERE request_id = ?",
                         array($_REQUEST['req_id'])
                        );
   $req_details = $db->FetchArray($result);

   // Mark the PM request as 'resolved'
   $db->Query("UPDATE {$dbprefix}admin_requests
               SET resolved_by = ?, time_resolved = ?, deny_reason = ?
               WHERE request_id = ?",
               array($current_user['user_id'], date('U'), $_REQUEST['deny_reason'], $_REQUEST['req_id']));


   // Log this event to the task's history
   $fs->logEvent($req_details['task_id'], 28, $_REQUEST['deny_reason']);

   // Send notifications
   $notify->Create('13', $req_details['task_id']);

   // Redirect
   $_SESSION['SUCCESS'] = $modify_text['pmreqdenied'];
   $fs->redirect($_REQUEST['prev_page']);

// End of denying a PM request


//////////////////////////////////
// Start of adding a dependency //
//////////////////////////////////

} elseif ($_POST['action'] == 'newdep'
   && (($permissions['modify_own_tasks'] == '1'
   && $old_details['assigned_to'] == $current_user['user_id'])
   OR $permissions['modify_all_tasks'] == '1')
   && !empty($_POST['dep_task_id']))
{
  // First check that the user hasn't tried to add this twice
  $check_dep = $db->Query("SELECT * FROM {$dbprefix}dependencies
                             WHERE task_id = ? AND dep_task_id = ?",
                             array($_POST['task_id'], $_POST['dep_task_id']));

  // or that they are trying to reverse-depend the same task, creating a mutual-block
  $check_dep2 = $db->Query("SELECT * FROM {$dbprefix}dependencies
                             WHERE task_id = ? AND dep_task_id = ?",
                             array($_POST['dep_task_id'], $_POST['task_id']));

  // Check that the dependency actually exists!
  $check_dep3 = $db->Query("SELECT * FROM {$dbprefix}tasks
                              WHERE task_id = ?",
                              array($_POST['dep_task_id'])
                            );

   $notify->Create('5', $_POST['task_id']);

//    $to  = $notify->Address($_POST['task_id']);
//    $msg = $notify->Create('5', $_POST['task_id']);
//    $mail = $notify->SendEmail($to[0], $msg[0], $msg[1]);
//    $jabb = $notify->StoreJabber($to[1], $msg[0], $msg[1]);


   if (!$db->CountRows($check_dep)
       && !$db->CountRows($check_dep2)
       && $db->CountRows($check_dep3)
       // Check that the user hasn't tried to add the same task as a dependency
       && $_POST['task_id'] != $_POST['dep_task_id']) {

    // Log this event to the task history, both ways
    $fs->logEvent($_POST['task_id'], 22, $_POST['dep_task_id']);
    $fs->logEvent($_POST['dep_task_id'], 23, $_POST['task_id']);

    // Add the dependency to the database
    $add_dep = $db->Query("INSERT INTO {$dbprefix}dependencies
                             (task_id, dep_task_id)
                             VALUES(?,?)",
                             array($_POST['task_id'], $_POST['dep_task_id']));




    // Redirect
   $_SESSION['SUCCESS'] = $modify_text['dependadded'];
   $fs->redirect($fs->CreateURL('details', $_REQUEST['task_id']));

  // If the user tried to add the wrong task as a dependency
  } else {

    // If the user tried to add the 'wrong' task as a dependency,
    // show error and redirect
   $_SESSION['ERROR'] = $modify_text['dependaddfailed'];
   $fs->redirect($fs->CreateURL('details', $_REQUEST['task_id']));

  };

// End of adding a dependency


////////////////////////////////////
// Start of removing a dependency //
////////////////////////////////////

} elseif ($_GET['action'] == 'removedep'
          && (($permissions['modify_own_tasks'] == '1'
               && $old_details['assigned_to'] == $current_user['user_id'])
             OR $permissions['modify_all_tasks'] =='1')) {

  // We need some info about this dep for the task history
  $result = $db->Query("SELECT * FROM {$dbprefix}dependencies
                        WHERE depend_id = ?",
                        array($_GET['depend_id']));
  $dep_info = $db->FetchArray($result);

   $notify->Create('6', $dep_info['task_id']);

//    $to  = $notify->Address($dep_info['task_id']);
//    $msg = $notify->Create('6', $dep_info['task_id']);
//    $mail = $notify->SendEmail($to[0], $msg[0], $msg[1]);
//    $jabb = $notify->StoreJabber($to[1], $msg[0], $msg[1]);

   // Log this event to the task's history
   $fs->logEvent($dep_info['task_id'], 24, $dep_info['dep_task_id']);
   $fs->logEvent($dep_info['dep_task_id'], 25, $dep_info['task_id']);

   // Do the removal
   $remove = $db->Query("DELETE FROM {$dbprefix}dependencies
                         WHERE depend_id = ?",
                         array($_GET['depend_id']));

   // Generate status message and redirect
   $_SESSION['SUCCESS'] = $modify_text['depremoved'];
   $fs->redirect($fs->CreateURL('details', $dep_info['task_id']));

// End of removing a dependency


//////////////////////////////////////////////////
// Start of a user requesting a password change //
//////////////////////////////////////////////////

} elseif ($_POST['action'] == 'sendmagic') {

   // Check that the username exists
   $check_details = $db->Query("SELECT * FROM {$dbprefix}users
                                WHERE user_name = ?",
                                array($_POST['user_name']));

   // If the username doesn't exist, throw an error
   if (!$db->CountRows($check_details))
   {
      $_SESSION['ERROR'] = $modify_text['usernotexist'];
      $fs->redirect($fs->CreateURL('lostpw', null));

   // ...otherwise get on with it
   } else
   {
      $user_details = $db->FetchArray($check_details);

      // Generate a looonnnnggg random string to send as an URL
      $magic_url = md5(microtime());

      // Insert the random "magic url" into the user's profile
      $update = $db->Query("UPDATE {$dbprefix}users
                            SET magic_url = ?
                            WHERE user_id = ?",
                            array($magic_url, $user_details['user_id'])
                          );

      // Create notification message
      $subject = $modify_text['noticefrom'] . ' ' . $project_prefs['project_title'];

      $message = "{$modify_text['noticefrom']} {$project_prefs['project_title']} \n
{$modify_text['magicurlmessage']} \n
{$conf['general']['baseurl']}index.php?do=lostpw&amp;magic=$magic_url\n";
      // End of generating a message

      // Send the brief notification message

      $to  = $notify->SpecificAddresses(array($user_details['user_id']));
      $mail = $notify->SendEmail($to[0], $subject, $message);
      $jabb = $notify->StoreJabber($to[1], $subject, $message);

      // Let the user know what just happened
      echo "<div class=\"redirectmessage\"><p><em>{$modify_text['magicurlsent']}</em></p></div>";

  // End of checking if the username exists
  };

// End of a user requesting a password change


////////////////////////////////
// Change the user's password //
////////////////////////////////

} elseif ($_POST['action'] == 'chpass')
{
   // Check that the user submitted both the fields, and they are the same
   if ($_POST['pass1'] != ''
     && $_POST['pass2'] != ''
     && $_POST['magic_url'] != ''
     && $_POST['pass2'] == $_POST['pass2'])
   {
      // Get the user's details from the magic url
      $result = $db->Query("SELECT * FROM {$dbprefix}users
                            WHERE magic_url = ?",
                            array($_POST['magic_url'])
                          );
      $user_details = $db->FetchArray($result);

      // Encrypt the new password
      $new_pass_hash = $fs->cryptPassword($_POST['pass1']);

      // Change the password and clear the magic_url field
      $update = $db->Query("UPDATE {$dbprefix}users SET
                            user_pass = ?,
                            magic_url = ''
                            WHERE magic_url = ?",
                            array($new_pass_hash, $_POST['magic_url'])
                          );

      // Let the user know what just happened
      echo "<div class=\"redirectmessage\"><p><em>{$modify_text['passchanged']}</em></p>";
      echo "<p>{$modify_text['loginbelow']}</p></div>";

   // If the fields were submitted incorrectly, show an error
   } else
   {
      echo "<div class=\"redirectmessage\"><p><em>{$modify_text['erroronform']}</em></p>";
      echo "<p><a href=\"javascript:history.back()\">{$modify_text['goback']}</a></p></div>";

   // End of checking fields were submitted correctly
   }

// End of changing the user's password


////////////////////////////////////
// Start of making a task private //
////////////////////////////////////

} elseif ($_GET['action'] == 'makeprivate'
  && $permissions['manage_project'] == '1')
{
   $update = $db->Query("UPDATE {$dbprefix}tasks
                         SET mark_private = '1'
                         WHERE task_id = ?",
                         array($_GET['id'])
                       );

   // Log to task history
   $fs->logEvent($_GET['id'], 26);

   $_SESSION['SUCCESS'] = $modify_text['taskmadeprivate'];
   $fs->redirect($fs->CreateURL('details', $_REQUEST['id']));

// End of making a task private


///////////////////////////////////
// Start of making a task public //
///////////////////////////////////

} elseif ($_GET['action'] == 'makepublic'
  && $permissions['manage_project'] == '1')
{
   $update = $db->Query("UPDATE {$dbprefix}tasks
                         SET mark_private = '0'
                         WHERE task_id = ?",
                         array($_GET['id'])
                       );

   // Log to task history
   $fs->logEvent($_GET['id'], 27);

   $_SESSION['SUCCESS'] = $modify_text['taskmadepublic'];
   $fs->redirect($fs->CreateURL('details', $_REQUEST['id']));

// End of making a task public


/////////////////////
// End of actions! //
/////////////////////
}

?>