File: lib.php

package info (click to toggle)
moodle 1.6.3-2%2Betch3
  • links: PTS
  • area: main
  • in suites: etch
  • size: 37,172 kB
  • ctags: 51,688
  • sloc: php: 231,916; sql: 5,631; xml: 2,688; sh: 1,185; perl: 638; makefile: 48; pascal: 36
file content (1858 lines) | stat: -rw-r--r-- 86,296 bytes parent folder | download | duplicates (2)
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
<?php  // $Id: lib.php,v 1.89 2005/10/15 10:40:36 stronk7 Exp $

// workshop constants and standard Moodle functions plus the workshop functions 
// called by the standard functions

// see also locallib.php for other non-standard workshop functions

require_once($CFG->libdir.'/filelib.php');

/*** Constants **********************************/


$WORKSHOP_EWEIGHTS = array(  0 => -4.0, 1 => -2.0, 2 => -1.5, 3 => -1.0, 4 => -0.75, 5 => -0.5,  6 => -0.25, 
                             7 => 0.0, 8 => 0.25, 9 => 0.5, 10 => 0.75, 11=> 1.0, 12 => 1.5, 13=> 2.0, 
                             14 => 4.0); 

$WORKSHOP_FWEIGHTS = array(  0 => 0, 1 => 0.1, 2 => 0.25, 3 => 0.5, 4 => 0.75, 5 => 1.0,  6 => 1.5, 
                             7 => 2.0, 8 => 3.0, 9 => 5.0, 10 => 7.5, 11=> 10.0, 12=>50.0); 


$WORKSHOP_ASSESSMENT_COMPS = array (
                          0 => array('name' => get_string('verylax', 'workshop'), 'value' => 1),
                          1 => array('name' => get_string('lax', 'workshop'), 'value' => 0.6),
                          2 => array('name' => get_string('fair', 'workshop'), 'value' => 0.4),
                          3 => array('name' => get_string('strict', 'workshop'), 'value' => 0.33),
                          4 => array('name' => get_string('verystrict', 'workshop'), 'value' => 0.2) );



/*** Standard Moodle functions ******************
workshop_add_instance($workshop) 
workshop_check_dates($workshop)
workshop_cron () 
workshop_delete_instance($id) 
workshop_grades($workshopid) 
workshop_print_recent_activity(&$logs, $isteacher=false) 
workshop_refresh_events($workshop) 
workshop_update_instance($workshop) 
workshop_user_complete($course, $user, $mod, $workshop) 
workshop_user_outline($course, $user, $mod, $workshop) 
**********************************************/

///////////////////////////////////////////////////////////////////////////////
function workshop_add_instance($workshop) {
// Given an object containing all the necessary data, 
// (defined by the form in mod.html) this function 
// will create a new instance and return the id number 
// of the new instance.

    $workshop->timemodified = time();

    $workshop->submissionstart = make_timestamp($workshop->submissionstartyear, 
            $workshop->submissionstartmonth, $workshop->submissionstartday, $workshop->submissionstarthour, 
            $workshop->submissionstartminute);

    $workshop->assessmentstart = make_timestamp($workshop->assessmentstartyear, 
            $workshop->assessmentstartmonth, $workshop->assessmentstartday, $workshop->assessmentstarthour, 
            $workshop->assessmentstartminute);

    $workshop->submissionend = make_timestamp($workshop->submissionendyear, 
            $workshop->submissionendmonth, $workshop->submissionendday, $workshop->submissionendhour, 
            $workshop->submissionendminute);

    $workshop->assessmentend = make_timestamp($workshop->assessmentendyear, 
            $workshop->assessmentendmonth, $workshop->assessmentendday, $workshop->assessmentendhour, 
            $workshop->assessmentendminute);

    $workshop->releasegrades = make_timestamp($workshop->releaseyear, 
            $workshop->releasemonth, $workshop->releaseday, $workshop->releasehour, 
            $workshop->releaseminute);
    
    if (!workshop_check_dates($workshop)) {
        return get_string('invaliddates', 'workshop');
    }

    if ($returnid = insert_record("workshop", $workshop)) {

        $event = NULL;
        $event->name        = get_string('submissionstartevent','workshop', $workshop->name);
        $event->description = $workshop->description;
        $event->courseid    = $workshop->course;
        $event->groupid     = 0;
        $event->userid      = 0;
        $event->modulename  = 'workshop';
        $event->instance    = $returnid;
        $event->eventtype   = 'submissionstart';
        $event->timestart   = $workshop->submissionstart;
        $event->timeduration = 0;
        add_event($event);

        $event->name        = get_string('submissionendevent','workshop', $workshop->name);
        $event->eventtype   = 'submissionend';
        $event->timestart   = $workshop->submissionend;
        add_event($event);

        $event->name        = get_string('assessmentstartevent','workshop', $workshop->name);
        $event->eventtype   = 'assessmentstart';
        $event->timestart   = $workshop->assessmentstart;
        add_event($event);

        $event->name        = get_string('assessmentendevent','workshop', $workshop->name);
        $event->eventtype   = 'assessmentend';
        $event->timestart   = $workshop->assessmentend;
        add_event($event);
    }

    return $returnid;
}

///////////////////////////////////////////////////////////////////////////////
// returns true if the dates are valid, false otherwise
function workshop_check_dates($workshop) {
    // allow submission and assessment to start on the same date and to end on the same date
    // but enforce non-empty submission period and non-empty assessment period.
    return ($workshop->submissionstart < $workshop->submissionend and
            $workshop->submissionstart <= $workshop->assessmentstart and
            $workshop->assessmentstart < $workshop->assessmentend and
            $workshop->submissionend <= $workshop->assessmentend);
}


///////////////////////////////////////////////////////////////////////////////
function workshop_cron () {
// Function to be run periodically according to the moodle cron

    global $CFG, $USER;
    
    // if there any ungraded assessments run the grading routine
    if ($workshops = get_records("workshop")) {
        foreach ($workshops as $workshop) {
            // automatically grade assessments if workshop has examples and/or peer assessments
            if ($workshop->gradingstrategy and ($workshop->ntassessments or $workshop->nsassessments)) {
                workshop_grade_assessments($workshop);
            }
        }
    }
    $timenow = time();
    
    // Find all workshop notifications that have yet to be mailed out, and mails them
    $cutofftime = $timenow - $CFG->maxeditingtime;

    // look for new assessments
    if ($assessments = workshop_get_unmailed_assessments($cutofftime)) {
        foreach ($assessments as $assessment) {

            echo "Processing workshop assessment $assessment->id\n";
            
            // only process the entry once
            if (! set_field("workshop_assessments", "mailed", "1", "id", "$assessment->id")) {
                echo "Could not update the mailed field for id $assessment->id\n";
            }
            
            if (! $submission = get_record("workshop_submissions", "id", "$assessment->submissionid")) {
                echo "Could not find submission $assessment->submissionid\n";
                continue;
            }
            if (! $workshop = get_record("workshop", "id", $submission->workshopid)) {
                echo "Could not find workshop id $submission->workshopid\n";
                continue;
            }
            if (! $course = get_record("course", "id", $workshop->course)) {
                error("Could not find course id $workshop->course");
                continue;
            }
            if (! $cm = get_coursemodule_from_instance("workshop", $workshop->id, $course->id)) {
                error("Course Module ID was incorrect");
                continue;
            }
            if (! $submissionowner = get_record("user", "id", "$submission->userid")) {
                echo "Could not find user $submission->userid\n";
                continue;
            }
            if (! $assessmentowner = get_record("user", "id", "$assessment->userid")) {
                echo "Could not find user $assessment->userid\n";
                continue;
            }
            if (! isstudent($course->id, $submissionowner->id) and !isteacher($course->id, 
                        $submissionowner->id)) {
                continue;  // Not an active participant
            }
            if (! isstudent($course->id, $assessmentowner->id) and !isteacher($course->id, 
                        $assessmentowner->id)) {
                continue;  // Not an active participant
            }
            // don't sent self assessment
            if ($submissionowner->id == $assessmentowner->id) {
                continue;
            }
            $strworkshops = get_string("modulenameplural", "workshop");
            $strworkshop  = get_string("modulename", "workshop");
    
            // it's an assessment, tell the submission owner
            $USER->lang = $submissionowner->lang;
            $sendto = $submissionowner;
            // "Your assignment \"$submission->title\" has been assessed by"
            if (isstudent($course->id, $assessmentowner->id)) {
                $msg = get_string("mail1", "workshop", $submission->title)." a $course->student.\n";
            }
            else {
                $msg = get_string("mail1", "workshop", $submission->title).
                    " ".fullname($assessmentowner)."\n";
            }
            // "The comments and grade can be seen in the workshop assignment '$workshop->name'
            // I have taken the following line out because the info is repeated below.
            // $msg .= get_string("mail2", "workshop", $workshop->name)."\n\n";
    
            $postsubject = "$course->shortname: $strworkshops: ".format_string($workshop->name,true);
            $posttext  = "$course->shortname -> $strworkshops -> ".format_string($workshop->name,true)."\n";
            $posttext .= "---------------------------------------------------------------------\n";
            $posttext .= $msg;
            // "The comments and grade can be seen in ..."
            $posttext .= get_string("mail2", "workshop", 
                format_string($workshop->name,true).",   $CFG->wwwroot/mod/workshop/view.php?id=$cm->id")."\n";
            $posttext .= "---------------------------------------------------------------------\n";
            if ($sendto->mailformat == 1) {  // HTML
                $posthtml = "<p><font face=\"sans-serif\">".
                    "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
                    "<a href=\"$CFG->wwwroot/mod/workshop/index.php?id=$course->id\">$strworkshops</a> ->".
                    "<a href=\"$CFG->wwwroot/mod/workshop/view.php?id=$cm->id\">".format_string($workshop->name,true)."</a></font></p>";
                $posthtml .= "<hr><font face=\"sans-serif\">";
                $posthtml .= "<p>$msg</p>";
                $posthtml .= "<p>".get_string("mail2", "workshop",
                    " <a href=\"$CFG->wwwroot/mod/workshop/view.php?id=$cm->id\">".format_string($workshop->name,true)."</a>")."</p></font><hr>";
            } else {
                $posthtml = "";
            }
    
            if (!$teacher = get_teacher($course->id)) {
                echo "Error: can not find teacher for course $course->id!\n";
            }
                
            if (! email_to_user($sendto, $teacher, $postsubject, $posttext, $posthtml)) {
                echo "Error: workshop cron: Could not send out mail for id $submission->id to 
                    user $sendto->id ($sendto->email)\n";
            }
        }
    }
        
    // look for new assessments of resubmissions
    if ($assessments = workshop_get_unmailed_resubmissions($cutofftime)) {
        $timenow = time();

        foreach ($assessments as $assessment) {

            echo "Processing workshop assessment $assessment->id\n";
            
            // only process the entry once
            if (! set_field("workshop_assessments", "mailed", "1", "id", "$assessment->id")) {
                echo "Could not update the mailed field for id $assessment->id\n";
            }
            
            if (! $submission = get_record("workshop_submissions", "id", "$assessment->submissionid")) {
                echo "Could not find submission $assessment->submissionid\n";
                continue;
            }
            if (! $workshop = get_record("workshop", "id", $submission->workshopid)) {
                echo "Could not find workshop id $submission->workshopid\n";
                continue;
            }
            if (! $course = get_record("course", "id", $workshop->course)) {
                error("Could not find course id $workshop->course");
                continue;
            }
            if (! $cm = get_coursemodule_from_instance("workshop", $workshop->id, $course->id)) {
                error("Course Module ID was incorrect");
                continue;
            }
            if (! $submissionowner = get_record("user", "id", "$submission->userid")) {
                echo "Could not find user $submission->userid\n";
                continue;
            }
            if (! $assessmentowner = get_record("user", "id", "$assessment->userid")) {
                echo "Could not find user $assessment->userid\n";
                continue;
            }
            if (! isstudent($course->id, $submissionowner->id) and !isteacher($course->id, 
                        $submissionowner->id)) {
                continue;  // Not an active participant
            }
            if (! isstudent($course->id, $assessmentowner->id) and !isteacher($course->id, 
                        $assessmentowner->id)) {
                continue;  // Not an active participant
            }
    
            $strworkshops = get_string("modulenameplural", "workshop");
            $strworkshop  = get_string("modulename", "workshop");
    
            // it's a resubission assessment, tell the assessment owner to (re)assess
            $USER->lang = $assessmentowner->lang;
            $sendto = $assessmentowner;
            // "The assignment \"$submission->title\" is a revised piece of work. "
            $msg = get_string("mail8", "workshop", $submission->title)."\n";
            // "Please assess it in the workshop assignment '$workshop->name'
            // $msg .= get_string("mail9", "workshop", $workshop->name)."\n\n";
    
            $postsubject = "$course->shortname: $strworkshops: ".format_string($workshop->name,true);
            $posttext  = "$course->shortname -> $strworkshops -> ".format_string($workshop->name,true)."\n";
            $posttext .= "---------------------------------------------------------------------\n";
            $posttext .= $msg;
            // "Please assess it in ..."
            $posttext .= get_string("mail9", "workshop", 
                           format_string($workshop->name,true).", $CFG->wwwroot/mod/workshop/view.php?id=$cm->id")."\n";
            $posttext .= "---------------------------------------------------------------------\n";
            if ($sendto->mailformat == 1) {  // HTML
                $posthtml = "<p><font face=\"sans-serif\">".
                  "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
                  "<a href=\"$CFG->wwwroot/mod/workshop/index.php?id=$course->id\">$strworkshops</a> ->".
                  "<a href=\"$CFG->wwwroot/mod/workshop/view.php?id=$cm->id\">".format_string($workshop->name,true)."</a></font></p>";
                $posthtml .= "<hr><font face=\"sans-serif\">";
                $posthtml .= "<p>$msg</p>";
                $posthtml .= "<p>".get_string("mail9", "workshop",
                  " <a href=\"$CFG->wwwroot/mod/workshop/view.php?id=$cm->id\">".format_string($workshop->name,true)."</a>").'</p></font><hr>';
            } 
            else {
              $posthtml = "";
            }
    
            if (!$teacher = get_teacher($course->id)) {
                echo "Error: can not find teacher for course $course->id!\n";
            }
                
            if (! email_to_user($sendto, $teacher, $postsubject, $posttext, $posthtml)) {
                echo "Error: workshop cron: Could not send out mail for id $submission->id to 
                    user $sendto->id ($sendto->email)\n";
            }
        }
    }
    
    // look for new comments
    if ($comments = workshop_get_unmailed_comments($cutofftime)) {
        $timenow = time();

        foreach ($comments as $comment) {

            echo "Processing workshop comment $comment->id\n";
            
            // only process the entry once
            if (! set_field("workshop_comments", "mailed", "1", "id", "$comment->id")) {
                echo "Could not update the mailed field for comment id $comment->id\n";
            }
            
            if (! $assessment = get_record("workshop_assessments", "id", "$comment->assessmentid")) {
                echo "Could not find assessment $comment->assessmentid\n";
                continue;
            }
            if (! $submission = get_record("workshop_submissions", "id", "$assessment->submissionid")) {
                echo "Could not find submission $assessment->submissionid\n";
                continue;
            }
            if (! $workshop = get_record("workshop", "id", $submission->workshopid)) {
                echo "Could not find workshop id $submission->workshopid\n";
                continue;
            }
            if (! $course = get_record("course", "id", $workshop->course)) {
                error("Could not find course id $workshop->course");
                continue;
            }
            if (! $cm = get_coursemodule_from_instance("workshop", $workshop->id, $course->id)) {
                error("Course Module ID was incorrect");
                continue;
            }
            if (! $submissionowner = get_record("user", "id", "$submission->userid")) {
                echo "Could not find user $submission->userid\n";
                continue;
            }
            if (! $assessmentowner = get_record("user", "id", "$assessment->userid")) {
                echo "Could not find user $assessment->userid\n";
                continue;
            }
            if (! isstudent($course->id, $submissionowner->id) and !isteacher($course->id, 
                        $submissionowner->id)) {
                continue;  // Not an active participant
            }
            if (! isstudent($course->id, $assessmentowner->id) and !isteacher($course->id, 
                        $assessmentowner->id)) {
                continue;  // Not an active participant
            }
    
            $strworkshops = get_string("modulenameplural", "workshop");
            $strworkshop  = get_string("modulename", "workshop");
    
            // see if the submission owner needs to be told
            if ($comment->userid != $submission->userid) {
                $USER->lang = $submissionowner->lang;
                $sendto = $submissionowner;
                // "A comment has been added to the assignment \"$submission->title\" by
                if (isstudent($course->id, $assessmentowner->id)) {
                    $msg = get_string("mail4", "workshop", $submission->title)." a $course->student.\n";
                }
                else {
                    $msg = get_string("mail4", "workshop", $submission->title)." ".fullname($assessmentowner)."\n";
                }
                // "The new comment can be seen in the workshop assignment '$workshop->name'
                // $msg .= get_string("mail5", "workshop", $workshop->name)."\n\n";
    
                $postsubject = "$course->shortname: $strworkshops: ".format_string($workshop->name,true);
                $posttext  = "$course->shortname -> $strworkshops -> ".format_string($workshop->name,true)."\n";
                $posttext .= "---------------------------------------------------------------------\n";
                $posttext .= $msg;
                // "The new comment can be seen in ..."
                $posttext .= get_string("mail5", "workshop",
                    format_string($workshop->name,true).",   $CFG->wwwroot/mod/workshop/view.php?id=$cm->id")."\n";
                $posttext .= "---------------------------------------------------------------------\n";
                if ($sendto->mailformat == 1) {  // HTML
                    $posthtml = "<p><font face=\"sans-serif\">".
                    "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
                    "<a href=\"$CFG->wwwroot/mod/workshop/index.php?id=$course->id\">$strworkshops</a> ->".
                    "<a href=\"$CFG->wwwroot/mod/workshop/view.php?id=$cm->id\">".format_string($workshop->name,true)."</a></font></p>";
                    $posthtml .= "<hr><font face=\"sans-serif\">";
                    $posthtml .= "<p>$msg</p>";
                    $posthtml .= "<p>".get_string("mail5", "workshop",
                        " <a href=\"$CFG->wwwroot/mod/workshop/view.php?id=$cm->id\">".format_string($workshop->name,true)."</a>")
                        ."</p></font><hr>";
                } 
                else {
                    $posthtml = "";
                }
    
                if (!$teacher = get_teacher($course->id)) {
                    echo "Error: can not find teacher for course $course->id!\n";
                }
                    
                if (! email_to_user($sendto, $teacher, $postsubject, $posttext, $posthtml)) {
                    echo "Error: workshop cron: Could not send out mail for id $submission->id to user 
                        $sendto->id ($sendto->email)\n";
                }
            }
            // see if the assessor needs to to told
            if ($comment->userid != $assessment->userid) {
                $USER->lang = $assessmentowner->lang;
                $sendto = $assessmentowner;
                // "A comment has been added to the assignment \"$submission->title\" by
                if (isstudent($course->id, $submissionowner->id)) {
                    $msg = get_string("mail4", "workshop", $submission->title)." a $course->student.\n";
                }
                else {
                    $msg = get_string("mail4", "workshop", $submission->title).
                        " ".fullname($submissionowner)."\n";
                }
                // "The new comment can be seen in the workshop assignment '$workshop->name'
                // $msg .= get_string("mail5", "workshop", $workshop->name)."\n\n";
    
                $postsubject = "$course->shortname: $strworkshops: ".format_string($workshop->name,true);
                $posttext  = "$course->shortname -> $strworkshops -> ".format_string($workshop->name,true)."\n";
                $posttext .= "---------------------------------------------------------------------\n";
                $posttext .= $msg;
                // "The new comment can be seen in ..."
                $posttext .= get_string("mail5", "workshop",
                    format_string($workshop->name,true).",  $CFG->wwwroot/mod/workshop/view.php?id=$cm->id")."\n";
                $posttext .= "---------------------------------------------------------------------\n";
                if ($sendto->mailformat == 1) {  // HTML
                    $posthtml = "<p><font face=\"sans-serif\">".
                    "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
                    "<a href=\"$CFG->wwwroot/mod/workshop/index.php?id=$course->id\">$strworkshops</a> ->".
                    "<a href=\"$CFG->wwwroot/mod/workshop/view.php?id=$cm->id\">".format_string($workshop->name,true)."</a></font></p>";
                    $posthtml .= "<hr><font face=\"sans-serif\">";
                    $posthtml .= "<p>$msg</p>";
                    $posthtml .= "<p>".get_string("mail5", "workshop",
                        " <a href=\"$CFG->wwwroot/mod/workshop/view.php?id=$cm->id\">".format_string($workshop->name,true)."</a>")
                        ."</p></font><hr>";
                } 
                else {
                    $posthtml = "";
                }
    
                if (!$teacher = get_teacher($course->id)) {
                    echo "Error: can not find teacher for course $course->id!\n";
                }
                    
                if (! email_to_user($sendto, $teacher, $postsubject, $posttext, $posthtml)) {
                    echo "Error: workshop cron: Could not send out mail for id $submission->id to user 
                        $sendto->id ($sendto->email)\n";
                }
                if (! set_field("workshop_comments", "mailed", "1", "id", "$comment->id")) {
                    echo "Could not update the mailed field for comment id $comment->id\n";
                }
            }
        }
    }
    return true;
}


///////////////////////////////////////////////////////////////////////////////
function workshop_delete_instance($id) {
// Given an ID of an instance of this module, 
// this function will permanently delete the instance 
// and any data that depends on it.  

    if (! $workshop = get_record("workshop", "id", "$id")) {
        return false;
    }
    
    // delete all the associated records in the workshop tables, start positive...
    $result = true;

    if (! delete_records("workshop_comments", "workshopid", "$workshop->id")) {
        $result = false;
    }

    if (! delete_records("workshop_stockcomments", "workshopid", "$workshop->id")) {
        $result = false;
    }

    if (! delete_records("workshop_grades", "workshopid", "$workshop->id")) {
        $result = false;
    }

    if (! delete_records("workshop_elements", "workshopid", "$workshop->id")) {
        $result = false;
    }

    if (! delete_records("workshop_assessments", "workshopid", "$workshop->id")) {
        $result = false;
    }

    if (! delete_records("workshop_submissions", "workshopid", "$workshop->id")) {
        $result = false;
    }

    if (! delete_records("workshop", "id", "$workshop->id")) {
        $result = false;
    }

    if (! delete_records('event', 'modulename', 'workshop', 'instance', $workshop->id)) {
        $result = false;    
    }   

    return $result;
}


///////////////////////////////////////////////////////////////////////////////
function workshop_grades($workshopid) {
/// Must return an array of grades, indexed by user, and a max grade.
/// only returns grades once assessment has started
/// returns nothing if workshop is not graded
    global $CFG;

    $return = null;
    if ($workshop = get_record("workshop", "id", $workshopid)) {
        if (($workshop->assessmentstart < time()) and $workshop->gradingstrategy) {
            if ($students = get_course_students($workshop->course)) {
                foreach ($students as $student) {
                    if ($workshop->wtype) {
                        $gradinggrade = workshop_gradinggrade($workshop, $student);
                    } else { // ignore grading grades for simple assignments
                        $gradinggrade = 0;
                    }
                    $bestgrade = 0;
                    if ($submissions = workshop_get_user_submissions($workshop, $student)) {
                        foreach ($submissions as $submission) {
                            if (!$submission->late) {
                                $grade = workshop_submission_grade($workshop, $submission);
                            } else {
                                $grade = 0.01;
                            }
                            if ($grade > $bestgrade) {
                                $bestgrade = $grade;
                            }
                        }
                    }
                    $return->grades[$student->id] = $gradinggrade + $bestgrade;
                }
            }
        }
        // set maximum grade if graded
        if ($workshop->gradingstrategy) {
            if ($workshop->wtype) {
                $return->maxgrade = $workshop->grade + $workshop->gradinggrade;
            } else { // ignore grading grades for simple assignemnts
                $return->maxgrade = $workshop->grade;
            }
        }
    }
    return $return;
}

//////////////////////////////////////////////////////////////////////////////////////
function workshop_is_recent_activity($course, $isteacher, $timestart) {//jlw1 added for adding mark to courses with activity in My Moodle
    global $CFG;

    // have a look for agreed assessments for this user (agree) 
    $agreecontent = false;
    if (!$isteacher) { // teachers only need to see submissions
        if ($logs = workshop_get_agree_logs($course, $timestart)) {
            // got some, see if any belong to a visible module
            foreach ($logs as $log) {
                // Create a temp valid module structure (only need courseid, moduleid)
                $tempmod->course = $course->id;
                $tempmod->id = $log->workshopid;
                //Obtain the visible property from the instance
                if (instance_is_visible("workshop",$tempmod)) {
                    $agreecontent = true;
                    break;
                }
            }
        }
    }
    return false;
}


///////////////////////////////////////////////////////////////////////////////
function workshop_print_recent_activity($course, $isteacher, $timestart) {
    global $CFG;

    // have a look for agreed assessments for this user (agree) 
    $agreecontent = false;
    if (!$isteacher) { // teachers only need to see submissions
        if ($logs = workshop_get_agree_logs($course, $timestart)) {
            // got some, see if any belong to a visible module
            foreach ($logs as $log) {
                // Create a temp valid module structure (only need courseid, moduleid)
                $tempmod->course = $course->id;
                $tempmod->id = $log->workshopid;
                //Obtain the visible property from the instance
                if (instance_is_visible("workshop",$tempmod)) {
                    $agreecontent = true;
                    break;
                    }
                }
            // if we got some "live" ones then output them
            if ($agreecontent) {
                print_headline(get_string("workshopagreedassessments", "workshop").":");
                foreach ($logs as $log) {
                    //Create a temp valid module structure (only need courseid, moduleid)
                    $tempmod->course = $course->id;
                    $tempmod->id = $log->workshopid;
                    //Obtain the visible property from the instance
                    if (instance_is_visible("workshop",$tempmod)) {
                        if (!isteacher($course->id, $log->userid)) {  // don't break anonymous rule
                            $log->firstname = $course->student;
                            $log->lastname = '';
                        }
                        print_recent_activity_note($log->time, $log, $isteacher, $log->name,
                                                   $CFG->wwwroot.'/mod/workshop/'.$log->url);
                    }
                }
            }
        }
    }

    // have a look for new assessments for this user (assess) 
    $assesscontent = false;
    if (!$isteacher) { // teachers only need to see submissions
        if ($logs = workshop_get_assess_logs($course, $timestart)) {
            // got some, see if any belong to a visible module
            foreach ($logs as $log) {
                // Create a temp valid module structure (only need courseid, moduleid)
                $tempmod->course = $course->id;
                $tempmod->id = $log->workshopid;
                //Obtain the visible property from the instance
                if (instance_is_visible("workshop",$tempmod)) {
                    $assesscontent = true;
                    break;
                    }
                }
            // if we got some "live" ones then output them
            if ($assesscontent) {
                print_headline(get_string("workshopassessments", "workshop").":");
                foreach ($logs as $log) {
                    //Create a temp valid module structure (only need courseid, moduleid)
                    $tempmod->course = $course->id;
                    $tempmod->id = $log->workshopid;
                    //Obtain the visible property from the instance
                    if (instance_is_visible("workshop",$tempmod)) {
                        if (!isteacher($course->id, $log->userid)) {  // don't break anonymous rule
                            $log->firstname = $course->student;
                            $log->lastname = '';
                        }
                        print_recent_activity_note($log->time, $log, $isteacher, $log->name,
                                                   $CFG->wwwroot.'/mod/workshop/'.$log->url);
                    }
                }
            }
        }
    }
    // have a look for new comments for this user (comment) 
    $commentcontent = false;
    if (!$isteacher) { // teachers only need to see submissions
        if ($logs = workshop_get_comment_logs($course, $timestart)) {
            // got some, see if any belong to a visible module
            foreach ($logs as $log) {
                // Create a temp valid module structure (only need courseid, moduleid)
                $tempmod->course = $course->id;
                $tempmod->id = $log->workshopid;
                //Obtain the visible property from the instance
                if (instance_is_visible("workshop",$tempmod)) {
                    $commentcontent = true;
                    break;
                    }
                }
            // if we got some "live" ones then output them
            if ($commentcontent) {
                print_headline(get_string("workshopcomments", "workshop").":");
                foreach ($logs as $log) {
                    //Create a temp valid module structure (only need courseid, moduleid)
                    $tempmod->course = $course->id;
                    $tempmod->id = $log->workshopid;
                    //Obtain the visible property from the instance
                    if (instance_is_visible("workshop",$tempmod)) {
                        $log->firstname = $course->student;    // Keep anonymous
                        $log->lastname = '';
                        print_recent_activity_note($log->time, $log, $isteacher, $log->name,
                                                   $CFG->wwwroot.'/mod/workshop/'.$log->url);
                    }
                }
            }
        }
    }

    // have a look for new assessment gradings for this user (grade)
    $gradecontent = false;
    if ($logs = workshop_get_grade_logs($course, $timestart)) {
        // got some, see if any belong to a visible module
        foreach ($logs as $log) {
            // Create a temp valid module structure (only need courseid, moduleid)
            $tempmod->course = $course->id;
            $tempmod->id = $log->workshopid;
            //Obtain the visible property from the instance
            if (instance_is_visible("workshop",$tempmod)) {
                $gradecontent = true;
                break;
                }
            }
        // if we got some "live" ones then output them
        if ($gradecontent) {
            print_headline(get_string("workshopfeedback", "workshop").":");
            foreach ($logs as $log) {
                //Create a temp valid module structure (only need courseid, moduleid)
                $tempmod->course = $course->id;
                $tempmod->id = $log->workshopid;
                //Obtain the visible property from the instance
                if (instance_is_visible("workshop",$tempmod)) {
                    $log->firstname = $course->teacher;    // Keep anonymous
                    $log->lastname = '';
                    print_recent_activity_note($log->time, $log, $isteacher, $log->name,
                                               $CFG->wwwroot.'/mod/workshop/'.$log->url);
                }
            }
        }
    }

    // have a look for new submissions (only show to teachers) (submit)
    $submitcontent = false;
    if ($isteacher) {
        if ($logs = workshop_get_submit_logs($course, $timestart)) {
            // got some, see if any belong to a visible module
            foreach ($logs as $log) {
                // Create a temp valid module structure (only need courseid, moduleid)
                $tempmod->course = $course->id;
                $tempmod->id = $log->workshopid;
                //Obtain the visible property from the instance
                if (instance_is_visible("workshop",$tempmod)) {
                    $submitcontent = true;
                    break;
                    }
                }
            // if we got some "live" ones then output them
            if ($submitcontent) {
                print_headline(get_string("workshopsubmissions", "workshop").":");
                foreach ($logs as $log) {
                    //Create a temp valid module structure (only need courseid, moduleid)
                    $tempmod->course = $course->id;
                    $tempmod->id = $log->workshopid;
                    //Obtain the visible property from the instance
                    if (instance_is_visible("workshop",$tempmod)) {
                        print_recent_activity_note($log->time, $log, $isteacher, $log->name,
                                                   $CFG->wwwroot.'/mod/workshop/'.$log->url);
                    }
                }
            }
        }
    }

    return $agreecontent or $assesscontent or $commentcontent or $gradecontent or $submitcontent;
}


///////////////////////////////////////////////////////////////////////////////
function workshop_refresh_events($courseid = 0) {
// This standard function will check all instances of this module
// and make sure there are up-to-date events created for each of them.
// If courseid = 0, then every workshop event in the site is checked, else
// only workshop events belonging to the course specified are checked.
// This function is used, in its new format, by restore_refresh_events()

    if ($courseid == 0) {
        if (! $workshops = get_records("workshop")) {
            return true;        
        }   
    } else {
        if (! $workshops = get_records("workshop", "course", $courseid)) {
            return true;
        }
    }
    $moduleid = get_field('modules', 'id', 'name', 'workshop');
    
    foreach ($workshops as $workshop) {
    
        $dates = array(
            'submissionstart' => $workshop->submissionstart,
            'submissionend' => $workshop->submissionend,
            'assessmentstart' => $workshop->assessmentstart,
            'assessmentend' => $workshop->assessmentend
        );
        
        foreach ($dates as $type => $date) {
        
            if ($date) {
                if ($event = get_record('event', 'modulename', 'workshop', 'instance', $workshop->id, 'eventtype', $type)) {
                    $event->name        = addslashes(get_string($type.'event','workshop', $workshop->name));
                    $event->description = addslashes($workshop->description);
                    $event->eventtype   = $type;
                    $event->timestart   = $date;
                    update_event($event);
                } else {
                    $event->courseid    = $workshop->course;
                    $event->modulename  = 'workshop';
                    $event->instance    = $workshop->id; 
                    $event->name        = addslashes(get_string($type.'event','workshop', $workshop->name));
                    $event->description = addslashes($workshop->description);
                    $event->eventtype   = $type;
                    $event->timestart   = $date;
                    $event->timeduration = 0;
                    $event->visible     = get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $workshop->id); 
                    add_event($event);
                }
            }
        }
    }
    return true;
}   


///////////////////////////////////////////////////////////////////////////////
function workshop_update_instance($workshop) {
// Given an object containing all the necessary data, 
// (defined by the form in mod.html) this function 
// will update an existing instance with new data.
    global $CFG;

    $workshop->timemodified = time();

    $workshop->submissionstart = make_timestamp($workshop->submissionstartyear, 
            $workshop->submissionstartmonth, $workshop->submissionstartday, $workshop->submissionstarthour, 
            $workshop->submissionstartminute);

    $workshop->assessmentstart = make_timestamp($workshop->assessmentstartyear, 
            $workshop->assessmentstartmonth, $workshop->assessmentstartday, $workshop->assessmentstarthour, 
            $workshop->assessmentstartminute);

    $workshop->submissionend = make_timestamp($workshop->submissionendyear, 
            $workshop->submissionendmonth, $workshop->submissionendday, $workshop->submissionendhour, 
            $workshop->submissionendminute);

    $workshop->assessmentend = make_timestamp($workshop->assessmentendyear, 
            $workshop->assessmentendmonth, $workshop->assessmentendday, $workshop->assessmentendhour, 
            $workshop->assessmentendminute);

    $workshop->releasegrades = make_timestamp($workshop->releaseyear, 
            $workshop->releasemonth, $workshop->releaseday, $workshop->releasehour, 
            $workshop->releaseminute);
            
    if (!workshop_check_dates($workshop)) {
        return get_string('invaliddates', 'workshop');
    }

    // set the workshop's type
    $wtype = 0; // 3 phases, no grading grades
    if ($workshop->includeself or $workshop->ntassessments) $wtype = 1; // 3 phases with grading grades
    if ($workshop->nsassessments) $wtype = 2; // 5 phases with grading grades 
    $workshop->wtype = $wtype;
    
    // encode password if necessary
    if (!empty($workshop->password)) {
        $workshop->password = md5($workshop->password);
    } else {
        unset($workshop->password);
    }

    $workshop->id = $workshop->instance;

    if ($returnid = update_record("workshop", $workshop)) {

        $dates = array(
            'submissionstart' => $workshop->submissionstart,
            'submissionend' => $workshop->submissionend,
            'assessmentstart' => $workshop->assessmentstart,
            'assessmentend' => $workshop->assessmentend
        );
        $moduleid = get_field('modules', 'id', 'name', 'workshop');
        
        foreach ($dates as $type => $date) {
            if ($event = get_record('event', 'modulename', 'workshop', 'instance', $workshop->id, 'eventtype', $type)) {
                $event->name        = get_string($type.'event','workshop', $workshop->name);
                $event->description = $workshop->description;
                $event->eventtype   = $type;
                $event->timestart   = $date;
                update_event($event);
            } else if ($date) {
                $event = NULL;
                $event->name        = get_string($type.'event','workshop', $workshop->name);
                $event->description = $workshop->description;
                $event->courseid    = $workshop->course;
                $event->groupid     = 0;
                $event->userid      = 0;
                $event->modulename  = 'workshop';
                $event->instance    = $workshop->instance;
                $event->eventtype   = $type;
                $event->timestart   = $date;
                $event->timeduration = 0;
                $event->visible     = get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $workshop->id); 
                add_event($event);
            }
        }
    }

    if (time() > $workshop->assessmentstart) {
        // regrade all the submissions...
        set_field("workshop_submissions", "nassessments", 0, "workshopid", $workshop->id);
        workshop_grade_assessments($workshop);
    }

    return $returnid;
}

///////////////////////////////////////////////////////////////////////////////
function workshop_user_complete($course, $user, $mod, $workshop) {
    if ($submission = workshop_get_student_submission($workshop, $user)) {
        if ($basedir = workshop_file_area($workshop, $user)) {
            if ($files = get_directory_list($basedir)) {
                $countfiles = count($files).' '.get_string('submissions', 'workshop');
                foreach ($files as $file) {
                    $countfiles .= "; $file";
                }
            }
        }

        print_simple_box_start();

        echo $submission->description.'<br />';

        if (!empty($countfiles)) {
            echo $countfiles,'<br />';
        }
        
        workshop_print_feedback($course, $submission);

        print_simple_box_end();

    } else {
        print_string('notsubmittedyet', 'workshop');
    }
}

//////////////////////////////////////////////////////////////////////////////////////
function workshop_print_feedback($course, $submission) {
    global $CFG, $RATING;

    if (! $feedbacks = get_records('workshop_assessments', 'submissionid', $submission->id)) {
        return;
    }

    $strgrade = get_string('grade');
    $strnograde = get_string('nograde');

    foreach ($feedbacks as $feedback) {
        if (! $user = get_record('user', 'id', $feedback->userid)) {
            /// Weird error but we'll just ignore it and continue with other feedback
            continue;
        }

        echo '<table cellspacing="0" class="workshop_feedbackbox">';

        echo '<tr>';
        echo '<td class="picture left">';
        print_user_picture($user->id, $course->id, $user->picture);
        echo '</td>';
        echo '<td><span class="author">'.fullname($user).'</span>';
        echo '<span class="time">'.userdate($feedback->timegraded).'</span>';
        echo '</tr>';

        echo '<tr><td class="left side">&nbsp;</td>';
        echo '<td class="content">';

        if ($feedback->grade) {
            echo $strgrade.': '.$feedback->grade;
        } else {
            echo $strnograde;
        }

        echo '<span class="comment">'.format_text($feedback->generalcomment).'</span>';
        echo '<span class="teachercomment">'.format_text($feedback->teachercomment).'</span>';
        echo '</td></tr></table>';

    }
}




///////////////////////////////////////////////////////////////////////////////
function workshop_user_outline($course, $user, $mod, $workshop) {
    if ($submissions = workshop_get_user_submissions($workshop, $user)) {
        $result->info = count($submissions)." ".get_string("submissions", "workshop");
        // workshop_get_user_submissions returns the newest one first
        foreach ($submissions as $submission) {
            $result->time = $submission->timecreated;
            break;
            }
        return $result;
    }
    return NULL;
}

//////////////////////////////////////////////////////////////////////////////////////
function workshop_get_participants($workshopid) {      
//Returns the users with data in one workshop
//(users with records in workshop_submissions, workshop_assessments and workshop_comments, students)

    global $CFG;

    //Get students from workshop_submissions
    $st_submissions = get_records_sql("SELECT DISTINCT u.id, u.id
                                       FROM {$CFG->prefix}user u,
                                            {$CFG->prefix}workshop_submissions s
                                       WHERE s.workshopid = '$workshopid' and
                                             u.id = s.userid");
    //Get students from workshop_assessments
    $st_assessments = get_records_sql("SELECT DISTINCT u.id, u.id
                                 FROM {$CFG->prefix}user u,
                                      {$CFG->prefix}workshop_assessments a
                                 WHERE a.workshopid = '$workshopid' and
                                       u.id = a.userid");

    //Get students from workshop_comments
    $st_comments = get_records_sql("SELECT DISTINCT u.id, u.id
                                   FROM {$CFG->prefix}user u,
                                        {$CFG->prefix}workshop_comments c
                                   WHERE c.workshopid = '$workshopid' and
                                         u.id = c.userid");

    //Add st_assessments to st_submissions
    if ($st_assessments) {
        foreach ($st_assessments as $st_assessment) {
            $st_submissions[$st_assessment->id] = $st_assessment;
        }
    }
    //Add st_comments to st_submissions
    if ($st_comments) {
        foreach ($st_comments as $st_comment) {
            $st_submissions[$st_comment->id] = $st_comment;
        }
    }
    //Return st_submissions array (it contains an array of unique users)
    return ($st_submissions);
}

//////////////////////////////////////////////////////////////////////////////////////
function workshop_get_recent_mod_activity(&$activities, &$index, $sincetime, $courseid, 
                                           $workshop="0", $user="", $groupid="") {
    // Returns all workshop posts since a given time.  If workshop is specified then
    // this restricts the results

    global $CFG;

    if ($workshop) {
        $workshopselect = " AND cm.id = '$workshop'";
    } else {
        $workshopselect = "";
    }

    if ($user) {
        $userselect = " AND u.id = '$user'";
    } else {
        $userselect = "";
    }

    $posts = get_records_sql("SELECT s.*, u.firstname, u.lastname,
            u.picture, cm.instance, w.name, cm.section
            FROM {$CFG->prefix}workshop_submissions s,
            {$CFG->prefix}user u,
            {$CFG->prefix}course_modules cm,
            {$CFG->prefix}workshop w
            WHERE s.timecreated  > '$sincetime' $workshopselect
            AND s.userid = u.id $userselect
            AND w.course = '$courseid' 
            AND cm.instance = w.id
            AND cm.course = w.course
            AND s.workshopid = w.id
            ORDER BY s.id");


    if (empty($posts)) {
        return;
    }

    foreach ($posts as $post) {

        if (empty($groupid) || ismember($groupid, $post->userid)) {

            $tmpactivity = new Object;

            $tmpactivity->type = "workshop";
            $tmpactivity->defaultindex = $index;
            $tmpactivity->instance = $post->instance;
            $tmpactivity->name = $post->name;
            $tmpactivity->section = $post->section;

            $tmpactivity->content->id = $post->id;
            $tmpactivity->content->title = $post->title;

            $tmpactivity->user->userid = $post->userid;
            $tmpactivity->user->fullname = fullname($post);
            $tmpactivity->user->picture = $post->picture;

            $tmpactivity->timestamp = $post->timecreated;
            $activities[] = $tmpactivity;

            $index++;
        }
    }

    return;
}

//////////////////////////////////////////////////////////////////////////////////////
function workshop_print_recent_mod_activity($activity, $course, $detail=false) {

    global $CFG;

    echo '<table border="0" cellpadding="3" cellspacing="0">';

    if (!empty($activity->content->parent)) {
        $openformat = "<font size=\"2\"><i>";
        $closeformat = "</i></font>";
    } else {
        $openformat = "<b>";
        $closeformat = "</b>";
    }

    echo "<tr><td class=\"workshoppostpicture\" width=\"35\" valign=\"top\">";
    print_user_picture($activity->user->userid, $course, $activity->user->picture);
    echo "</td><td>$openformat";

    if ($detail) {
        echo "<img src=\"$CFG->modpixpath/$activity->type/icon.gif\" ".
            "height=\"16\" width=\"16\" alt=\"".strip_tags(format_string($activity->name,true))."\" />  ";
    }
    echo "<a href=\"$CFG->wwwroot/mod/workshop/view.php?" 
        . "#" . $activity->content->id . "\">".$activity->content->title;

    echo "</a>$closeformat";

    echo "<br /><font size=\"2\">";
    echo "<a href=\"$CFG->wwwroot/user/view.php?id=" . $activity->user->userid . "&amp;course=" . "$course\">"
        . $activity->user->fullname . "</a>";
    echo " - " . userdate($activity->timestamp) . "</font></td></tr>";
    echo "</table>";

    return;

}


//////////////////////////////////////////////////////////////////////////////////////
// Non-standard workshop functions
///////////////////////////////////////////////////////////////////////////////////////////////
function workshop_compare_assessments($workshop, $assessment1, $assessment2) {
    global $WORKSHOP_ASSESSMENT_COMPS, $WORKSHOP_EWEIGHTS;
    // first get the assignment elements for maxscores...
    $elementsraw = get_records("workshop_elements", "workshopid", $workshop->id, "elementno ASC");
    foreach ($elementsraw as $element) {
        $maxscore[] = $element->maxscore;   // to renumber index 0,1,2...
        $weight[] = $WORKSHOP_EWEIGHTS[$element->weight];   // get real value and renumber index 0,1,2...
    }
    for ($i = 0; $i < 2; $i++) {
        if ($i) {
            $rawgrades = get_records("workshop_grades", "assessmentid", $assessment1->id, "elementno ASC");
        } else {
            $rawgrades = get_records("workshop_grades", "assessmentid", $assessment2->id, "elementno ASC");
        }
        foreach ($rawgrades as $grade) {
            $grades[$i][] = $grade->grade;
        }
    }
    $sumdiffs = 0;
    $sumweights = 0;
    switch ($workshop->gradingstrategy) {
        case 1 : // accumulative grading and...
        case 4 : // ...rubic grading
            for ($i=0; $i < $workshop->nelements; $i++) {
                $diff = ($grades[0][$i] - $grades[1][$i]) * $weight[$i] / $maxscore[$i];
                $sumdiffs += $diff * $diff; // use squared distances
                $sumweights += $weight[$i];
                }
            break;
        case 2 :  // error banded grading
            // ignore maxscores here, the grades are either 0 or 1,
            for ($i=0; $i < $workshop->nelements; $i++) {
                $diff = ($grades[0][$i] - $grades[1][$i]) * $weight[$i];
                $sumdiffs += $diff * $diff; // use squared distances
                $sumweights += $weight[$i];
                }
            break;
        case 3 : // criterion grading
            // here we only need to look at the difference between the "zero" grade elements
            $diff = ($grades[0][0] - $grades[1][0]) / (count($elementsraw) - 1);
            $sumdiffs = $diff * $diff;
            $sumweights = 1;
            break;
    }            
    // convert to a sensible grade (always out of 100)
    $COMP = (object)$WORKSHOP_ASSESSMENT_COMPS[$workshop->assessmentcomps];
    $factor = $COMP->value;
    $gradinggrade = (($factor - ($sumdiffs / $sumweights)) / $factor) * 100;
    if ($gradinggrade < 0) {
        $gradinggrade = 0;
    }
    return $gradinggrade;
}


//////////////////////////////////////////////////////////////////////////////////////
function workshop_count_assessments($submission) {
    // Return the (real) assessments for this submission, 
    $timenow = time();
   return count_records_select("workshop_assessments", 
           "submissionid = $submission->id AND timecreated < $timenow");
}


//////////////////////////////////////////////////////////////////////////////////////
function workshop_count_ungraded_assessments($workshop) {
    // function returns the number of ungraded assessments by students
    global $CFG;
    
    $timenow = time();
    $n = 0;
    // get all the cold assessments that have not been graded
    if ($assessments = get_records_select("workshop_assessments", "workshopid = $workshop->id AND 
            (timecreated + $CFG->maxeditingtime) < $timenow AND timegraded = 0")) {
        foreach ($assessments as $assessment) {
            if (isstudent($workshop->course, $assessment->userid)) {
                $n++;
            }
        }
    }
    return $n;
}


//////////////////////////////////////////////////////////////////////////////////////
function workshop_file_area($workshop, $submission) {
    return make_upload_directory( workshop_file_area_name($workshop, $submission) );
}


//////////////////////////////////////////////////////////////////////////////////////
function workshop_file_area_name($workshop, $submission) {
//  Creates a directory file name, suitable for make_upload_directory()
    global $CFG;

    return "$workshop->course/$CFG->moddata/workshop/$submission->id";
}


///////////////////////////////////////////////////////////////////////////////////////////////
function workshop_get_agree_logs($course, $timestart) {
    // get the "agree" entries for this user (the assessment owner) and add the first and last names 
    // the last two probably wont be used...
    global $CFG, $USER;
    if (empty($USER->id)) {
        return false;
    }
    
    $timethen = time() - $CFG->maxeditingtime;
    return get_records_sql("SELECT l.time, l.url, u.firstname, u.lastname, a.workshopid, a.userid, e.name
                             FROM {$CFG->prefix}log l,
                                {$CFG->prefix}workshop e, 
                                {$CFG->prefix}workshop_submissions s, 
                                {$CFG->prefix}workshop_assessments a, 
                                {$CFG->prefix}user u
                            WHERE l.time > $timestart AND l.time < $timethen 
                                AND l.course = $course->id AND l.module = 'workshop' AND l.action = 'agree'
                                AND a.id = l.info AND s.id = a.submissionid AND a.userid = $USER->id
                                AND u.id = s.userid AND e.id = a.workshopid");
}


///////////////////////////////////////////////////////////////////////////////////////////////
function workshop_get_assess_logs($course, $timestart) {
    // get the "assess" entries for this user and add the first and last names...
    global $CFG, $USER;
    if (empty($USER->id)) {
        return false;
    }
    
    $timethen = time() - $CFG->maxeditingtime;
    return get_records_sql("SELECT l.time, l.url, u.firstname, u.lastname, a.workshopid, a.userid, e.name
                             FROM {$CFG->prefix}log l,
                                {$CFG->prefix}workshop e, 
                                {$CFG->prefix}workshop_submissions s, 
                                {$CFG->prefix}workshop_assessments a, 
                                {$CFG->prefix}user u
                            WHERE l.time > $timestart AND l.time < $timethen 
                                AND l.course = $course->id AND l.module = 'workshop' AND l.action = 'assess'
                                AND a.id = l.info AND s.id = a.submissionid AND s.userid = $USER->id
                                AND u.id = a.userid AND e.id = a.workshopid");
}


//////////////////////////////////////////////////////////////////////////////////////
function workshop_get_assessments($submission, $all = '', $order = '') {
    // Return assessments for this submission ordered oldest first, newest last
    // new assessments made within the editing time are NOT returned unless they
    // belong to the user or the second argument is set to ALL
    global $CFG, $USER;

    $timenow = time();
    if (!$order) {
        $order = "timecreated DESC";
    }
    if ($all != 'ALL') {
        return get_records_select("workshop_assessments", "(submissionid = $submission->id) AND 
            ((timecreated < $timenow - $CFG->maxeditingtime) or 
                ((timecreated < $timenow) AND (userid = $USER->id)))", $order);
    } else {
        return get_records_select("workshop_assessments", "submissionid = $submission->id AND 
            (timecreated < $timenow)", $order);
    }
}


///////////////////////////////////////////////////////////////////////////////////////////////
function workshop_get_comment_logs($course, $timestart) {
    // get the "comment" entries for this user and add the first and last names (which may not be used)...
    global $CFG, $USER;
    if (empty($USER->id)) {
        return false;
    }
    
    $timethen = time() - $CFG->maxeditingtime;
    return get_records_sql("SELECT l.time, l.url, u.firstname, u.lastname, a.workshopid, e.name
                             FROM {$CFG->prefix}log l,
                                {$CFG->prefix}workshop e, 
                                {$CFG->prefix}workshop_submissions s, 
                                {$CFG->prefix}workshop_assessments a, 
                                {$CFG->prefix}workshop_comments c, 
                                {$CFG->prefix}user u
                            WHERE l.time > $timestart AND l.time < $timethen 
                                AND l.course = $course->id AND l.module = 'workshop' AND l.action = 'comment'
                                AND c.id = l.info AND c.userid != $USER->id AND a.id = c.assessmentid
                                AND s.id = a.submissionid AND (s.userid = $USER->id OR a.userid = $USER->id)
                                AND u.id = a.userid AND e.id = a.workshopid");
}


///////////////////////////////////////////////////////////////////////////////////////////////
function workshop_get_grade_logs($course, $timestart) {
    // get the "grade" entries for this user and add the first and last names (of submission owner, 
    // better to get name of teacher...
    // ...but not available in assessment record...)
    global $CFG, $USER;
    if (empty($USER->id)) {
        return false;
    }
    
    $timethen = time() - $CFG->maxeditingtime;
    return get_records_sql("SELECT l.time, l.url, u.firstname, u.lastname, a.workshopid, e.name
                             FROM {$CFG->prefix}log l,
                                {$CFG->prefix}workshop e, 
                                {$CFG->prefix}workshop_submissions s, 
                                {$CFG->prefix}workshop_assessments a, 
                                {$CFG->prefix}user u
                            WHERE l.time > $timestart AND l.time < $timethen 
                                AND l.course = $course->id AND l.module = 'workshop'    AND l.action = 'grade'
                                AND a.id = l.info AND s.id = a.submissionid AND a.userid = $USER->id
                                AND u.id = s.userid AND e.id = a.workshopid");
}


//////////////////////////////////////////////////////////////////////////////////////
function workshop_get_student_submission($workshop, $user) {
// Return a submission for a particular user
    global $CFG;

    $submission = get_record("workshop_submissions", "workshopid", $workshop->id, "userid", $user->id);
    if (!empty($submission->timecreated)) {
        return $submission;
    }
    return NULL;
}


//////////////////////////////////////////////////////////////////////////////////////
function workshop_get_student_submissions($workshop, $order = "title") {
// Return all  ENROLLED student submissions
    global $CFG;
    
    if ($order == "title") {
        $order = "s.title";
        }
    if ($order == "name") {
        $order = "a.lastname, a.firstname";
        }
    if ($order == "time") {
        $order = "s.timecreated ASC";
    }
    // make sure it works on the site course
    $select = "u.course = '$workshop->course' AND";
    $site = get_site();
    if ($workshop->course == $site->id) {
        $select = '';
    }

    return get_records_sql("SELECT s.* FROM {$CFG->prefix}workshop_submissions s, 
                            {$CFG->prefix}user_students u, {$CFG->prefix}user a 
                            WHERE $select s.userid = u.userid
                              AND a.id = u.userid
                              AND s.workshopid = $workshop->id
                              AND s.timecreated > 0
                              ORDER BY $order");
}


///////////////////////////////////////////////////////////////////////////////////////////////
function workshop_get_submit_logs($course, $timestart) {
    // get the "submit" entries and add the first and last names...
    global $CFG, $USER;
    
    $timethen = time() - $CFG->maxeditingtime;
    return get_records_sql("SELECT l.time, l.url, u.firstname, u.lastname, l.info as workshopid, e.name
                             FROM {$CFG->prefix}log l,
                                {$CFG->prefix}workshop e, 
                                {$CFG->prefix}user u
                            WHERE l.time > $timestart AND l.time < $timethen 
                                AND l.course = $course->id AND l.module = 'workshop'
                                AND l.action = 'submit'
                                AND e.id = l.info 
                                AND u.id = l.userid");
}


//////////////////////////////////////////////////////////////////////////////////////
function workshop_get_unmailed_assessments($cutofftime) {
    /// Return list of assessments that have not been mailed out
    global $CFG;
    return get_records_sql("SELECT a.*, g.course, g.name
                              FROM {$CFG->prefix}workshop_assessments a, {$CFG->prefix}workshop g
                             WHERE a.mailed = 0 
                               AND a.timecreated < $cutofftime 
                               AND g.id = a.workshopid
                               AND g.releasegrades < $cutofftime");
}


//////////////////////////////////////////////////////////////////////////////////////
function workshop_get_unmailed_comments($cutofftime) {
    /// Return list of comments that have not been mailed out
    global $CFG;
    return get_records_sql("SELECT c.*, g.course, g.name
                              FROM {$CFG->prefix}workshop_comments c, {$CFG->prefix}workshop g
                             WHERE c.mailed = 0 
                               AND c.timecreated < $cutofftime 
                               AND g.id = c.workshopid");
}


//////////////////////////////////////////////////////////////////////////////////////
function workshop_get_unmailed_graded_assessments($cutofftime) {
    /// Return list of graded assessments that have not been mailed out
    global $CFG;
    return get_records_sql("SELECT a.*, g.course, g.name
                              FROM {$CFG->prefix}workshop_assessments a, {$CFG->prefix}workshop g
                             WHERE a.mailed = 0 
                               AND a.timegraded < $cutofftime 
                               AND a.timegraded > 0
                               AND g.id = a.workshopid");
}


//////////////////////////////////////////////////////////////////////////////////////
function workshop_get_unmailed_resubmissions($cutofftime) {
    /// Return list of assessments of resubmissions that have not been mailed out
    global $CFG;
    return get_records_sql("SELECT a.*, w.course, w.name
                              FROM {$CFG->prefix}workshop_assessments a, {$CFG->prefix}workshop w
                             WHERE a.mailed = 0 
                               AND a.resubmission = 1
                               AND w.id = a.workshopid");
}


//////////////////////////////////////////////////////////////////////////////////////
function workshop_get_user_assessments($workshop, $user) {
// Return all the  user's assessments, newest first, oldest last (hot, warm and cold ones)
    return get_records_select("workshop_assessments", "workshopid = $workshop->id AND userid = $user->id", 
                "timecreated DESC");
}


//////////////////////////////////////////////////////////////////////////////////////
function workshop_get_user_submissions($workshop, $user) {
    // return real submissions of user newest first, oldest last. Ignores the dummy submissions
    // which get created to hold the final grades for users that make no submissions
    return get_records_select("workshop_submissions", "workshopid = $workshop->id AND 
        userid = $user->id AND timecreated > 0", "timecreated DESC" );
}


//////////////////////////////////////////////////////////////////////////////////////
function workshop_grade_assessments($workshop, $verbose=false) {
    global $WORKSHOP_EWEIGHTS;
    
    // timeout after 10 minutes
    @set_time_limit(600);

    $timenow = time();
    
    // set minumim value for the variance (of the elements)
    $minvar = 0.05;

    // check when the standard deviations were calculated
    $oldtotalassessments = get_field("workshop_elements", "totalassessments", "workshopid", $workshop->id, 
                "elementno", 0);
    $totalassessments = count_records("workshop_assessments", "workshopid", $workshop->id);
    // calculate the std. devs every 10 assessments for low numbers of assessments, thereafter every 100 new assessments
    if ((($totalassessments < 100) and (($totalassessments - $oldtotalassessments) > 10)) or 
            (($totalassessments - $oldtotalassessments) > 100)) {
        // calculate the means for each submission using just the "good" assessments 
        if ($submissions = get_records("workshop_submissions", "workshopid", $workshop->id)) {
            foreach ($submissions as $submission) {
                $nassessments[$submission->id] = 0;
                if ($assessments = workshop_get_assessments($submission)) {
                    foreach ($assessments as $assessment) {
                        // test if assessment is "good", a teacher assessment always "good", but may be weighted out 
                        if (isteacher($workshop->course, $assessment->userid)) {
                            if (!$workshop->teacherweight) {
                                // drop teacher's assessment as weight is zero
                                continue;
                            }
                        } elseif ((!$assessment->gradinggrade and $assessment->timegraded) or 
                                ($workshop->agreeassessments and !$assessment->timeagreed)) {
                            // it's a duff assessment, or it's not been agreed
                            continue;
                        }
                        if (isset($num[$submission->id])) {
                            if (isteacher($workshop->course, $assessment->userid)) {
                                $num[$submission->id] += $workshop->teacherweight; // weight teacher's assessment
                            } else {
                                $num[$submission->id]++; // number of assessments
                            }
                            $nassessments[$submission->id]++;
                        } else {
                            if (isteacher($workshop->course, $assessment->userid)) {
                                $num[$submission->id] = $workshop->teacherweight;
                            } else {
                                $num[$submission->id] = 1;
                            }
                            $nassessments[$submission->id] = 1;
                        }
                        for ($i = 0; $i < $workshop->nelements; $i++) {
                            $grade =  get_field("workshop_grades", "grade",
                                    "assessmentid", $assessment->id, "elementno", $i);
                            if (isset($sum[$submission->id][$i])) {
                                if (isteacher($workshop->course, $assessment->userid)) {
                                    $sum[$submission->id][$i] += $workshop->teacherweight * $grade; // teacher's grade
                                } else {
                                    $sum[$submission->id][$i] += $grade; // student's grade
                                }
                            } else { 
                                if (isteacher($workshop->course, $assessment->userid)) {
                                    $sum[$submission->id][$i] = $workshop->teacherweight * $grade; // teacher's grade
                                } else {
                                    $sum[$submission->id][$i] = $grade; // students's grade
                                }
                            }
                        }
                    }
                }
            }

            if (!isset($num)) { 
                // no assessments yet
                return;
            }
            reset($num);
            // calculate the means for each submission
            $total = 0;
            foreach ($num as $submissionid => $n) {
                if ($n) { // stop division by zero
                    for ($i = 0; $i < $workshop->nelements; $i++) {
                        $mean[$submissionid][$i] = $sum[$submissionid][$i] / $n;
                        // echo "Submission: $submissionid; Element: $i; Mean: {$mean[$submissionid][$i]}<br />\n";
                    }
                    $total += $n; // weighted total
                }
            }
            if ($verbose) {
                echo "<p align=\"center\">".get_string("numberofsubmissions", "workshop", count($num))."<br />\n";
                echo get_string("numberofassessmentsweighted", "workshop", $total)."</p>\n";
            }

            // now get an estimate of the standard deviation of each element in the assessment
            // this is just a rough measure, all assessments are included and teacher's assesments are not weighted
            $n = 0;
            for ($i = 0; $i < $workshop->nelements; $i++) {
                $var[$i] = 0;
            }
            foreach ($submissions as $submission) {
                if ($assessments = workshop_get_assessments($submission)) {
                    foreach ($assessments as $assessment) {
                        $n++;
                        for ($i = 0; $i < $workshop->nelements; $i++) {
                            $grade =  get_field("workshop_grades", "grade",
                                    "assessmentid", $assessment->id, "elementno", $i);
                            $temp = $mean[$submission->id][$i] - $grade;
                            $var[$i] += $temp * $temp;
                        }
                    }
                }
            }
            for ($i = 0; $i < $workshop->nelements; $i++) {
                if ($n > 1) {
                    $sd[$i] = sqrt($var[$i] / ($n - 1));
                } else {
                    $sd[$i] = 0;
                }
                set_field("workshop_elements", "stddev", $sd[$i], "workshopid", $workshop->id, "elementno", $i);
                set_field("workshop_elements", "totalassessments", $totalassessments, "workshopid", $workshop->id,
                        "elementno", $i);
                if ($verbose) {
                    echo get_string("standarddeviationofelement", "workshop", $i+1)." $sd[$i]<br />";
                    if ($sd[$i] <= $minvar) {
                        print_string("standarddeviationnote", "workshop")."<br />\n";
                    }
                }
            }
        } 
    }

    // this section looks at each submission if the number of assessments made has increased it recalculates the
    // grading grades for those assessments
    // first get the assignment elements for the weights and the stddevs...
    if ($elementsraw = get_records("workshop_elements", "workshopid", $workshop->id, "elementno ASC")) {
        foreach ($elementsraw as $element) {
            $weight[] = $element->weight;   // to renumber index 0,1,2...
            $sd[] = $element->stddev;   // to renumber index 0,1,2...
        }
    }

    unset($num); // may have been used in calculating stddevs
    unset($sum); // ditto
    if ($submissions = get_records("workshop_submissions", "workshopid", $workshop->id)) {
        foreach ($submissions as $submission) {
            // see if the number of assessments has changed
            $nassessments = workshop_count_assessments($submission);
            if ($submission->nassessments <> $nassessments) {
                // ...if there are three or more assessments calculate the variance of each assessment.
                // Use the variance to find the "best" assessment. (When there is only one or two assessments they 
                // are not altered by this routine.)
                if ($verbose) {
                    echo "Processing submission $submission->id ($nassessments asessments)...\n"; 
                }
                if ($nassessments > 2) {
                    $num = 0; // weighted number of assessments
                    for ($i = 0; $i < $workshop->nelements; $i++) {
                        $sum[$i] = 0; // weighted sum of grades
                    }
                    if ($assessments = workshop_get_assessments($submission)) {
                        // first calculate the mean grades for each element
                        foreach ($assessments as $assessment) {
                            // test if assessment is "good", a teacher assessment always "good", but may be weighted out 
                            if (isteacher($workshop->course, $assessment->userid)) {
                                if (!$workshop->teacherweight) {
                                    // drop teacher's assessment as weight is zero
                                    continue;
                                }
                            } else if ((!$assessment->gradinggrade and $assessment->timegraded) or 
                                    ($workshop->agreeassessments and !$assessment->timeagreed)) {
                                // it's a duff assessment, or it's not been agreed
                                continue;
                            }
                            if (isteacher($workshop->course, $assessment->userid)) {
                                $num += $workshop->teacherweight; // weight teacher's assessment
                            } else {
                                $num++; // student assessment just add one
                            }
                            for ($i = 0; $i < $workshop->nelements; $i++) {
                                $grade =  get_field("workshop_grades", "grade",
                                        "assessmentid", $assessment->id, "elementno", $i);
                                if (isteacher($workshop->course, $assessment->userid)) {
                                    $sum[$i] += $workshop->teacherweight * $grade; // teacher's grade
                                } else {
                                    $sum[$i] += $grade; // student's grade
                                }
                            }
                        }
                        if ($num) { // could all the assessments be duff? 
                            for ($i = 0; $i < $workshop->nelements; $i++) {
                                $mean[$i] = $sum[$i] / $num;
                                if ($verbose) echo "Submission: $submission->id; Element: $i; Mean: {$mean[$i]}\n";
                            }
                        } else {
                            continue; // move to the next submission
                        }
                        // run through the assessments again to see which is the "best" one (the one
                        // closest to the mean)
                        $lowest = 10e9;
                        foreach ($assessments as $assessment) {
                            if ($workshop->agreeassessments and !$assessment->timeagreed) {
                                // ignore assessments that have not been agreed
                                continue;
                            }
                            $var = 0;
                            for ($i = 0; $i < $workshop->nelements; $i++) {
                                $grade =  get_field("workshop_grades", "grade",
                                        "assessmentid", $assessment->id, "elementno", $i);
                                if ($sd[$i] > $minvar) {
                                    $temp = ($mean[$i] - $grade) * 
                                        $WORKSHOP_EWEIGHTS[$weight[$i]] / $sd[$i];
                                } else {
                                    $temp = 0;
                                }
                                $var += $temp * $temp;
                            }
                            // find the "best" assessment of this submission
                            if ($lowest > $var) {
                                $lowest = $var;
                                $bestassessmentid = $assessment->id;
                            }
                        }

                        if (!$best = get_record("workshop_assessments", "id", $bestassessmentid)) {
                            notify("Workshop grade assessments: cannot find best assessment");
                            continue;
                        }
                        if ($verbose) {
                            echo "Best assessment is $bestassessmentid;\n";
                        }
                        foreach ($assessments as $assessment) {
                            // don't overwrite teacher's grade
                            if ($assessment->teachergraded) {
                                continue;
                            }
                            if ($assessment->id == $bestassessmentid) { 
                                // it's the best one, set the grading grade to the maximum 
                                set_field("workshop_assessments", "gradinggrade", 100, "id", $assessment->id);
                                set_field("workshop_assessments", "timegraded", $timenow, "id", $assessment->id);
                            } else {
                                // it's one of the pack, compare with the best...
                                $gradinggrade = workshop_compare_assessments($workshop, $best, $assessment);
                                // ...and save the grade for the assessment 
                                set_field("workshop_assessments", "gradinggrade", $gradinggrade, "id", $assessment->id);
                                set_field("workshop_assessments", "timegraded", $timenow, "id", $assessment->id);
                            }
                        }
                    }
                } else {
                    // there are less than 3 assessments for this submission
                    if ($assessments = workshop_get_assessments($submission)) {
                        foreach ($assessments as $assessment) {
                            if (!$assessment->timegraded and !$assessment->teachergraded) {
                                // set the grading grade to the maximum and say it's been graded 
                                set_field("workshop_assessments", "gradinggrade", 100, "id", $assessment->id);
                                set_field("workshop_assessments", "timegraded", $timenow, "id", $assessment->id);
                            }
                        }
                    }
                }       
                // set the number of assessments for this submission
                set_field("workshop_submissions", "nassessments", $nassessments, "id", $submission->id);    
            }
        }
    }
    return;
}


//////////////////////////////////////////////////////////////////////////////////////
function workshop_gradinggrade($workshop, $student) {
    // returns the current (external) grading grade of the based on their (cold) assessments
    // (needed as it's called by grade)
    
    $gradinggrade = 0;
    if ($assessments = workshop_get_user_assessments($workshop, $student)) {
        $n = 0;
        foreach ($assessments as $assessment) {
            $gradinggrade += $assessment->gradinggrade;
            $n++;
        }
        if ($n < ($workshop->ntassessments + $workshop->nsassessments)) { // the minimum students should do
            $n = $workshop->ntassessments + $workshop->nsassessments;
        }
        $gradinggrade = $gradinggrade / $n;
    }
    return number_format($gradinggrade * $workshop->gradinggrade / 100, 1);
}


//////////////////////////////////////////////////////////////////////////////////////
function workshop_submission_grade($workshop, $submission) {
    // returns the current (external) grade of the submission based on the "good" (cold) assessments
    // (needed as it's called by grade)
    
    $grade = 0;
    if ($assessments = workshop_get_assessments($submission)) {
        $n = 0;
        foreach ($assessments as $assessment) {
            if ($workshop->agreeassessments and !$assessment->timeagreed) {
                // ignore assessments which have not been agreed
                continue;
            }
            if ($assessment->gradinggrade or !$assessment->timegraded) { 
                // a good assessment (or one that has not been graded yet)
                if (isteacher($workshop->course, $assessment->userid)) {
                    $timenow = time();
                    if ($timenow > $workshop->releasegrades) {
                        // teacher's grade is available
                        $grade += $workshop->teacherweight * $assessment->grade;
                        $n += $workshop->teacherweight;
                    }
                } else {
                    $grade += $assessment->grade;
                    $n++;
                }
            }
        }
        if ($n) { // stop division by zero
            $grade = $grade / $n;
        }
    }
    return number_format($grade * $workshop->grade / 100, 1);
}


/////////////////////////////////////////////////////////////////////////////
function workshop_fullname($userid, $courseid) {
    global $CFG;
    if (!$user = get_record('user', 'id', $userid)) {
        return '';
    }
    return '<a href="'.$CFG->wwwroot.'/user/view.php?id='.$user->id.'&amp;course='.$courseid.'">'.
        fullname($user).'</a>';
}

function workshop_get_view_actions() {
    return array('view','view all');
}

function workshop_get_post_actions() {
    return array('agree','assess','comment','grade','newattachment','removeattachments','resubmit','submit');
}

?>