MDL-4667, MDL-4112 switching order of columns in course-userid log table index in...
[moodle.git] / mod / assignment / lib.php
CommitLineData
5c6b657a 1<?PHP // $Id$
b0f2597e 2/**
3 * assignment_base is the base class for assignment types
4 *
5 * This class provides all the functionality for an assignment
6 */
04eba58f 7
1884f2a6 8DEFINE ('ASSIGNMENT_COUNT_WORDS', 1);
9DEFINE ('ASSIGNMENT_COUNT_LETTERS', 2);
d699cd1e 10
7af1e882 11/**
b0f2597e 12 * Standard base class for all assignment submodules (assignment types).
b0f2597e 13 */
14class assignment_base {
15
16 var $cm;
17 var $course;
18 var $assignment;
7af1e882 19 var $strassignment;
20 var $strassignments;
21 var $strsubmissions;
22 var $strlastmodified;
7af1e882 23 var $pagetitle;
7af1e882 24 var $usehtmleditor;
25 var $defaultformat;
55b4d096 26 var $context;
0b5a80a1 27 var $type;
b0f2597e 28
29 /**
30 * Constructor for the base assignment class
31 *
32 * Constructor for the base assignment class.
33 * If cmid is set create the cm, course, assignment objects.
7af1e882 34 * If the assignment is hidden and the user is not a teacher then
35 * this prints a page header and notice.
b0f2597e 36 *
37 * @param cmid integer, the current course module id - not set for new assignments
73097f07 38 * @param assignment object, usually null, but if we have it we pass it to save db access
7af1e882 39 * @param cm object, usually null, but if we have it we pass it to save db access
40 * @param course object, usually null, but if we have it we pass it to save db access
b0f2597e 41 */
7bddd4b7 42 function assignment_base($cmid='staticonly', $assignment=NULL, $cm=NULL, $course=NULL) {
dd97c328 43 global $COURSE;
44
7bddd4b7 45 if ($cmid == 'staticonly') {
46 //use static functions only!
47 return;
48 }
b0f2597e 49
50 global $CFG;
51
7bddd4b7 52 if ($cm) {
53 $this->cm = $cm;
54 } else if (! $this->cm = get_coursemodule_from_id('assignment', $cmid)) {
7bddd4b7 55 error('Course Module ID was incorrect');
56 }
04eba58f 57
dd97c328 58 $this->context = get_context_instance(CONTEXT_MODULE, $this->cm->id);
55b4d096 59
7bddd4b7 60 if ($course) {
61 $this->course = $course;
dd97c328 62 } else if ($this->cm->course == $COURSE->id) {
63 $this->course = $COURSE;
7bddd4b7 64 } else if (! $this->course = get_record('course', 'id', $this->cm->course)) {
65 error('Course is misconfigured');
66 }
04eba58f 67
7bddd4b7 68 if ($assignment) {
69 $this->assignment = $assignment;
70 } else if (! $this->assignment = get_record('assignment', 'id', $this->cm->instance)) {
71 error('assignment ID was incorrect');
72 }
73
b5ebd096 74 $this->assignment->cmidnumber = $this->cm->id; // compatibility with modedit assignment obj
75 $this->assignment->courseid = $this->course->id; // compatibility with modedit assignment obj
e6a4906b 76
7bddd4b7 77 $this->strassignment = get_string('modulename', 'assignment');
78 $this->strassignments = get_string('modulenameplural', 'assignment');
79 $this->strsubmissions = get_string('submissions', 'assignment');
80 $this->strlastmodified = get_string('lastmodified');
7bddd4b7 81 $this->pagetitle = strip_tags($this->course->shortname.': '.$this->strassignment.': '.format_string($this->assignment->name,true));
82
f36cbf1d 83 // visibility handled by require_login() with $cm parameter
84 // get current group only when really needed
e6a4906b 85
73097f07 86 /// Set up things for a HTML editor if it's needed
87 if ($this->usehtmleditor = can_use_html_editor()) {
88 $this->defaultformat = FORMAT_HTML;
89 } else {
90 $this->defaultformat = FORMAT_MOODLE;
e6a4906b 91 }
92 }
93
7af1e882 94 /**
95 * Display the assignment, used by view.php
96 *
97 * This in turn calls the methods producing individual parts of the page
b0f2597e 98 */
b0f2597e 99 function view() {
45fa3412 100
dabfd0ed 101 $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
0468976c 102 require_capability('mod/assignment:view', $context);
45fa3412 103
104 add_to_log($this->course->id, "assignment", "view", "view.php?id={$this->cm->id}",
b0f2597e 105 $this->assignment->id, $this->cm->id);
04eba58f 106
73097f07 107 $this->view_header();
04eba58f 108
f77cfb73 109 $this->view_intro();
04eba58f 110
f77cfb73 111 $this->view_dates();
04eba58f 112
b0f2597e 113 $this->view_feedback();
114
f77cfb73 115 $this->view_footer();
36eb856f 116 }
117
7af1e882 118 /**
119 * Display the header and top of a page
120 *
121 * (this doesn't change much for assignment types)
122 * This is used by the view() method to print the header of view.php but
123 * it can be used on other pages in which case the string to denote the
124 * page in the navigation trail should be passed as an argument
125 *
126 * @param $subpage string Description of subpage to be used in navigation trail
73097f07 127 */
128 function view_header($subpage='') {
129
130 global $CFG;
131
45fa3412 132
73097f07 133 if ($subpage) {
38e179a4 134 $navigation = build_navigation($subpage, $this->cm);
73097f07 135 } else {
38e179a4 136 $navigation = build_navigation('', $this->cm);
73097f07 137 }
45fa3412 138
45fa3412 139 print_header($this->pagetitle, $this->course->fullname, $navigation, '', '',
140 true, update_module_button($this->cm->id, $this->course->id, $this->strassignment),
73097f07 141 navmenu($this->course, $this->cm));
142
ba3dc7b4 143 groups_print_activity_menu($this->cm, 'view.php?id=' . $this->cm->id);
45fa3412 144
73097f07 145 echo '<div class="reportlink">'.$this->submittedlink().'</div>';
7bddd4b7 146 echo '<div class="clearer"></div>';
73097f07 147 }
148
149
7af1e882 150 /**
f77cfb73 151 * Display the assignment intro
7af1e882 152 *
153 * This will most likely be extended by assignment type plug-ins
154 * The default implementation prints the assignment description in a box
f77cfb73 155 */
156 function view_intro() {
32776fef 157 print_simple_box_start('center', '', '', 0, 'generalbox', 'intro');
1e4343a0 158 $formatoptions = new stdClass;
159 $formatoptions->noclean = true;
160 echo format_text($this->assignment->description, $this->assignment->format, $formatoptions);
f77cfb73 161 print_simple_box_end();
162 }
163
7af1e882 164 /**
f77cfb73 165 * Display the assignment dates
7af1e882 166 *
167 * Prints the assignment start and end dates in a box.
168 * This will be suitable for most assignment types
f77cfb73 169 */
170 function view_dates() {
171 if (!$this->assignment->timeavailable && !$this->assignment->timedue) {
172 return;
173 }
174
32776fef 175 print_simple_box_start('center', '', '', 0, 'generalbox', 'dates');
f77cfb73 176 echo '<table>';
177 if ($this->assignment->timeavailable) {
178 echo '<tr><td class="c0">'.get_string('availabledate','assignment').':</td>';
179 echo ' <td class="c1">'.userdate($this->assignment->timeavailable).'</td></tr>';
180 }
181 if ($this->assignment->timedue) {
182 echo '<tr><td class="c0">'.get_string('duedate','assignment').':</td>';
183 echo ' <td class="c1">'.userdate($this->assignment->timedue).'</td></tr>';
184 }
185 echo '</table>';
186 print_simple_box_end();
187 }
188
189
7af1e882 190 /**
191 * Display the bottom and footer of a page
192 *
193 * This default method just prints the footer.
194 * This will be suitable for most assignment types
73097f07 195 */
196 function view_footer() {
197 print_footer($this->course);
198 }
199
7af1e882 200 /**
201 * Display the feedback to the student
202 *
203 * This default method prints the teacher picture and name, date when marked,
ea6432fe 204 * grade and teacher submissioncomment.
7af1e882 205 *
206 * @param $submission object The submission object or NULL in which case it will be loaded
207 */
73097f07 208 function view_feedback($submission=NULL) {
5978010d 209 global $USER, $CFG;
210 require_once($CFG->libdir.'/gradelib.php');
211
212 if (!has_capability('mod/assignment:submit', $this->context, $USER->id, false)) {
213 // can not submit assignments -> no feedback
214 return;
215 }
e6a4906b 216
73097f07 217 if (!$submission) { /// Get submission for this assignment
218 $submission = $this->get_submission($USER->id);
70b2c772 219 }
220
5978010d 221 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $USER->id);
222 $item = $grading_info->items[0];
223 $grade = $item->grades[$USER->id];
224
225 if ($grade->hidden or $grade->grade === false) { // hidden or error
226 return;
227 }
228
30d61820 229 if ($grade->grade === null and empty($grade->str_feedback)) { /// Nothing to show yet
70b2c772 230 return;
9c48354d 231 }
e6a4906b 232
ced5ee59 233 $graded_date = $grade->dategraded;
dc6cb74e 234 $graded_by = $grade->usermodified;
e6a4906b 235
5978010d 236 /// We need the teacher info
237 $teacher = get_record('user', 'id', $graded_by);
238
b0f2597e 239 /// Print the feedback
5978010d 240 print_heading(get_string('feedbackfromteacher', 'assignment', $this->course->teacher)); // TODO: fix teacher string
6d4ecaec 241
b0f2597e 242 echo '<table cellspacing="0" class="feedback">';
243
244 echo '<tr>';
245 echo '<td class="left picture">';
5978010d 246 if ($teacher) {
ad1e3409 247 print_user_picture($teacher, $this->course->id, $teacher->picture);
5978010d 248 }
b0f2597e 249 echo '</td>';
6d4ecaec 250 echo '<td class="topic">';
70b2c772 251 echo '<div class="from">';
5978010d 252 if ($teacher) {
253 echo '<div class="fullname">'.fullname($teacher).'</div>';
254 }
255 echo '<div class="time">'.userdate($graded_date).'</div>';
70b2c772 256 echo '</div>';
b0f2597e 257 echo '</td>';
258 echo '</tr>';
259
260 echo '<tr>';
261 echo '<td class="left side">&nbsp;</td>';
6d4ecaec 262 echo '<td class="content">';
5978010d 263 echo '<div class="grade">';
49292fa0 264 echo get_string("grade").': '.$grade->str_long_grade;
5978010d 265 echo '</div>';
266 echo '<div class="clearer"></div>';
dcd338ff 267
6d4ecaec 268 echo '<div class="comment">';
5978010d 269 echo $grade->str_feedback;
6d4ecaec 270 echo '</div>';
b0f2597e 271 echo '</tr>';
272
273 echo '</table>';
e6a4906b 274 }
e6a4906b 275
45fa3412 276 /**
ba16713f 277 * Returns a link with info about the state of the assignment submissions
7af1e882 278 *
279 * This is used by view_header to put this link at the top right of the page.
280 * For teachers it gives the number of submitted assignments with a link
281 * For students it gives the time of their submission.
282 * This will be suitable for most assignment types.
dd97c328 283 * @param bool $allgroup print all groups info if user can access all groups, suitable for index.php
7af1e882 284 * @return string
ba16713f 285 */
dd97c328 286 function submittedlink($allgroups=false) {
ba16713f 287 global $USER;
288
289 $submitted = '';
290
bbbf2d40 291 $context = get_context_instance(CONTEXT_MODULE,$this->cm->id);
1648afb2 292 if (has_capability('mod/assignment:grade', $context)) {
dd97c328 293 if ($allgroups and has_capability('moodle/site:accessallgroups', $context)) {
294 $group = 0;
ba16713f 295 } else {
f36cbf1d 296 $group = groups_get_activity_group($this->cm);
dd97c328 297 }
298 if ($count = $this->count_real_submissions($group)) {
299 $submitted = '<a href="submissions.php?id='.$this->cm->id.'">'.
300 get_string('viewsubmissions', 'assignment', $count).'</a>';
301 } else {
302 $submitted = '<a href="submissions.php?id='.$this->cm->id.'">'.
303 get_string('noattempts', 'assignment').'</a>';
ba16713f 304 }
ba16713f 305 } else {
86a1ba04 306 if (!empty($USER->id)) {
ba16713f 307 if ($submission = $this->get_submission($USER->id)) {
308 if ($submission->timemodified) {
1e4343a0 309 if ($submission->timemodified <= $this->assignment->timedue || empty($this->assignment->timedue)) {
ba16713f 310 $submitted = '<span class="early">'.userdate($submission->timemodified).'</span>';
311 } else {
312 $submitted = '<span class="late">'.userdate($submission->timemodified).'</span>';
313 }
314 }
315 }
316 }
317 }
318
319 return $submitted;
320 }
321
322
436cfa9f 323 function setup_elements(&$mform) {
45fa3412 324
436cfa9f 325 }
326
7af1e882 327 /**
328 * Create a new assignment activity
329 *
330 * Given an object containing all the necessary data,
331 * (defined by the form in mod.html) this function
332 * will create a new instance and return the id number
333 * of the new instance.
334 * The due data is added to the calendar
335 * This is common to all assignment types.
336 *
337 * @param $assignment object The data from the form on mod.html
338 * @return int The id of the assignment
339 */
b0f2597e 340 function add_instance($assignment) {
7bddd4b7 341 global $COURSE;
b0f2597e 342
343 $assignment->timemodified = time();
7bddd4b7 344 $assignment->courseid = $assignment->course;
38147229 345
736f191c 346 if ($returnid = insert_record("assignment", $assignment)) {
7bddd4b7 347 $assignment->id = $returnid;
736f191c 348
1e4343a0 349 if ($assignment->timedue) {
7bddd4b7 350 $event = new object();
1e4343a0 351 $event->name = $assignment->name;
352 $event->description = $assignment->description;
353 $event->courseid = $assignment->course;
354 $event->groupid = 0;
355 $event->userid = 0;
356 $event->modulename = 'assignment';
357 $event->instance = $returnid;
358 $event->eventtype = 'due';
359 $event->timestart = $assignment->timedue;
360 $event->timeduration = 0;
736f191c 361
1e4343a0 362 add_event($event);
363 }
7bddd4b7 364
365 $assignment = stripslashes_recursive($assignment);
612607bd 366 assignment_grade_item_update($assignment);
7bddd4b7 367
736f191c 368 }
369
7bddd4b7 370
736f191c 371 return $returnid;
b0f2597e 372 }
d699cd1e 373
7af1e882 374 /**
375 * Deletes an assignment activity
376 *
1f8c6549 377 * Deletes all database records, files and calendar events for this assignment.
7af1e882 378 * @param $assignment object The assignment to be deleted
379 * @return boolean False indicates error
380 */
b0f2597e 381 function delete_instance($assignment) {
1f8c6549 382 global $CFG;
383
ada917d5 384 $assignment->courseid = $assignment->course;
385
736f191c 386 $result = true;
387
388 if (! delete_records('assignment_submissions', 'assignment', $assignment->id)) {
389 $result = false;
390 }
391
392 if (! delete_records('assignment', 'id', $assignment->id)) {
393 $result = false;
394 }
395
396 if (! delete_records('event', 'modulename', 'assignment', 'instance', $assignment->id)) {
397 $result = false;
398 }
45fa3412 399
1f8c6549 400 // delete file area with all attachments - ignore errors
401 require_once($CFG->libdir.'/filelib.php');
402 fulldelete($CFG->dataroot.'/'.$assignment->course.'/'.$CFG->moddata.'/assignment/'.$assignment->id);
403
45fa3412 404 assignment_grade_item_delete($assignment);
ada917d5 405
736f191c 406 return $result;
b0f2597e 407 }
d699cd1e 408
7af1e882 409 /**
410 * Updates a new assignment activity
411 *
412 * Given an object containing all the necessary data,
413 * (defined by the form in mod.html) this function
414 * will update the assignment instance and return the id number
415 * The due date is updated in the calendar
416 * This is common to all assignment types.
417 *
418 * @param $assignment object The data from the form on mod.html
419 * @return int The assignment id
420 */
b0f2597e 421 function update_instance($assignment) {
7bddd4b7 422 global $COURSE;
b0f2597e 423
38147229 424 $assignment->timemodified = time();
38147229 425
b0f2597e 426 $assignment->id = $assignment->instance;
7bddd4b7 427 $assignment->courseid = $assignment->course;
736f191c 428
7bddd4b7 429 if (!update_record('assignment', $assignment)) {
430 return false;
431 }
736f191c 432
7bddd4b7 433 if ($assignment->timedue) {
434 $event = new object();
736f191c 435
7bddd4b7 436 if ($event->id = get_field('event', 'id', 'modulename', 'assignment', 'instance', $assignment->id)) {
736f191c 437
7bddd4b7 438 $event->name = $assignment->name;
439 $event->description = $assignment->description;
440 $event->timestart = $assignment->timedue;
736f191c 441
7bddd4b7 442 update_event($event);
47263937 443 } else {
7bddd4b7 444 $event = new object();
445 $event->name = $assignment->name;
446 $event->description = $assignment->description;
447 $event->courseid = $assignment->course;
448 $event->groupid = 0;
449 $event->userid = 0;
450 $event->modulename = 'assignment';
451 $event->instance = $assignment->id;
452 $event->eventtype = 'due';
453 $event->timestart = $assignment->timedue;
454 $event->timeduration = 0;
455
456 add_event($event);
736f191c 457 }
7bddd4b7 458 } else {
459 delete_records('event', 'modulename', 'assignment', 'instance', $assignment->id);
736f191c 460 }
461
7bddd4b7 462 // get existing grade item
463 $assignment = stripslashes_recursive($assignment);
de420c11 464
45fa3412 465 assignment_grade_item_update($assignment);
7bddd4b7 466
467 return true;
468 }
469
470 /**
45fa3412 471 * Update grade item for this submission.
7bddd4b7 472 */
45fa3412 473 function update_grade($submission) {
612607bd 474 assignment_update_grades($this->assignment, $submission->userid);
b0f2597e 475 }
476
7af1e882 477 /**
b0f2597e 478 * Top-level function for handling of submissions called by submissions.php
7af1e882 479 *
480 * This is for handling the teacher interaction with the grading interface
481 * This should be suitable for most assignment types.
482 *
483 * @param $mode string Specifies the kind of teacher interaction taking place
b0f2597e 484 */
485 function submissions($mode) {
9bf660b3 486 ///The main switch is changed to facilitate
487 ///1) Batch fast grading
488 ///2) Skip to the next one on the popup
489 ///3) Save and Skip to the next one on the popup
45fa3412 490
9bf660b3 491 //make user global so we can use the id
492 global $USER;
45fa3412 493
b0f2597e 494 switch ($mode) {
495 case 'grade': // We are in a popup window grading
496 if ($submission = $this->process_feedback()) {
5a36be8c 497 //IE needs proper header with encoding
498 print_header(get_string('feedback', 'assignment').':'.format_string($this->assignment->name));
b0f2597e 499 print_heading(get_string('changessaved'));
73963212 500 print $this->update_main_listing($submission);
b0f2597e 501 }
989a0a52 502 close_window();
b0f2597e 503 break;
9cc9b7c1 504
b0f2597e 505 case 'single': // We are in a popup window displaying submission
506 $this->display_submission();
507 break;
a56d79cd 508
1648afb2 509 case 'all': // Main window, display everything
b0f2597e 510 $this->display_submissions();
511 break;
082215e6 512
9bf660b3 513 case 'fastgrade':
082215e6 514 ///do the fast grading stuff - this process should work for all 3 subclasses
39e11905 515 $grading = false;
16907e53 516 $commenting = false;
39e11905 517 $col = false;
ea6432fe 518 if (isset($_POST['submissioncomment'])) {
519 $col = 'submissioncomment';
16907e53 520 $commenting = true;
521 }
522 if (isset($_POST['menu'])) {
39e11905 523 $col = 'menu';
16907e53 524 $grading = true;
525 }
39e11905 526 if (!$col) {
ea6432fe 527 //both submissioncomment and grade columns collapsed..
45fa3412 528 $this->display_submissions();
16907e53 529 break;
530 }
39e11905 531 foreach ($_POST[$col] as $id => $unusedvalue){
77f4b17b 532
533 $id = (int)$id; //clean parameter name
cc03871b 534
535 $this->process_outcomes($id);
536
39e11905 537 if (!$submission = $this->get_submission($id)) {
538 $submission = $this->prepare_new_submission($id);
539 $newsubmission = true;
540 } else {
541 $newsubmission = false;
542 }
543 unset($submission->data1); // Don't need to update this.
544 unset($submission->data2); // Don't need to update this.
16907e53 545
9bf660b3 546 //for fast grade, we need to check if any changes take place
16907e53 547 $updatedb = false;
548
549 if ($grading) {
550 $grade = $_POST['menu'][$id];
39e11905 551 $updatedb = $updatedb || ($submission->grade != $grade);
552 $submission->grade = $grade;
16907e53 553 } else {
39e11905 554 if (!$newsubmission) {
555 unset($submission->grade); // Don't need to update this.
556 }
16907e53 557 }
558 if ($commenting) {
ea6432fe 559 $commentvalue = trim($_POST['submissioncomment'][$id]);
560 $updatedb = $updatedb || ($submission->submissioncomment != stripslashes($commentvalue));
561 $submission->submissioncomment = $commentvalue;
16907e53 562 } else {
ea6432fe 563 unset($submission->submissioncomment); // Don't need to update this.
9bf660b3 564 }
565
39e11905 566 $submission->teacher = $USER->id;
567 $submission->mailed = $updatedb?0:$submission->mailed;//only change if it's an update
568 $submission->timemarked = time();
569
570 //if it is not an update, we don't change the last modified time etc.
ea6432fe 571 //this will also not write into database if no submissioncomment and grade is entered.
39e11905 572
16907e53 573 if ($updatedb){
39e11905 574 if ($newsubmission) {
7bddd4b7 575 if (!$sid = insert_record('assignment_submissions', $submission)) {
39e11905 576 return false;
577 }
7bddd4b7 578 $submission->id = $sid;
39e11905 579 } else {
580 if (!update_record('assignment_submissions', $submission)) {
581 return false;
582 }
7bddd4b7 583 }
584
585 // triger grade event
45fa3412 586 $this->update_grade($submission);
7bddd4b7 587
39e11905 588 //add to log only if updating
45fa3412 589 add_to_log($this->course->id, 'assignment', 'update grades',
590 'submissions.php?id='.$this->assignment->id.'&user='.$submission->userid,
591 $submission->userid, $this->cm->id);
9bf660b3 592 }
45fa3412 593
594 }
cc03871b 595
fb81abe1 596 $message = notify(get_string('changessaved'), 'notifysuccess', 'center', true);
597
598 $this->display_submissions($message);
9bf660b3 599 break;
39e11905 600
601
9bf660b3 602 case 'next':
603 /// We are currently in pop up, but we want to skip to next one without saving.
604 /// This turns out to be similar to a single case
605 /// The URL used is for the next submission.
45fa3412 606
9bf660b3 607 $this->display_submission();
608 break;
45fa3412 609
9bf660b3 610 case 'saveandnext':
611 ///We are in pop up. save the current one and go to the next one.
612 //first we save the current changes
613 if ($submission = $this->process_feedback()) {
614 //print_heading(get_string('changessaved'));
73963212 615 $extra_javascript = $this->update_main_listing($submission);
9bf660b3 616 }
45fa3412 617
9bf660b3 618 //then we display the next submission
73963212 619 $this->display_submission($extra_javascript);
9bf660b3 620 break;
45fa3412 621
9bf660b3 622 default:
623 echo "something seriously is wrong!!";
45fa3412 624 break;
a56d79cd 625 }
b0f2597e 626 }
45fa3412 627
7af1e882 628 /**
629 * Helper method updating the listing on the main script from popup using javascript
630 *
631 * @param $submission object The submission whose data is to be updated on the main page
632 */
be86672d 633 function update_main_listing($submission) {
fbaa56b2 634 global $SESSION, $CFG;
45fa3412 635
73963212 636 $output = '';
637
9bf660b3 638 $perpage = get_user_preferences('assignment_perpage', 10);
be86672d 639
9bf660b3 640 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
45fa3412 641
be86672d 642 /// Run some Javascript to try and update the parent page
73963212 643 $output .= '<script type="text/javascript">'."\n<!--\n";
ea6432fe 644 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['submissioncomment'])) {
9bf660b3 645 if ($quickgrade){
16fc2088 646 $output.= 'opener.document.getElementById("submissioncomment'.$submission->userid.'").value="'
ea6432fe 647 .trim($submission->submissioncomment).'";'."\n";
9bf660b3 648 } else {
73963212 649 $output.= 'opener.document.getElementById("com'.$submission->userid.
ea6432fe 650 '").innerHTML="'.shorten_text(trim(strip_tags($submission->submissioncomment)), 15)."\";\n";
9bf660b3 651 }
be86672d 652 }
9bf660b3 653
654 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['grade'])) {
655 //echo optional_param('menuindex');
656 if ($quickgrade){
16fc2088 657 $output.= 'opener.document.getElementById("menumenu'.$submission->userid.
658 '").selectedIndex="'.optional_param('menuindex', 0, PARAM_INT).'";'."\n";
9bf660b3 659 } else {
73963212 660 $output.= 'opener.document.getElementById("g'.$submission->userid.'").innerHTML="'.
9bf660b3 661 $this->display_grade($submission->grade)."\";\n";
45fa3412 662 }
663 }
9bf660b3 664 //need to add student's assignments in there too.
73097f07 665 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemodified']) &&
666 $submission->timemodified) {
73963212 667 $output.= 'opener.document.getElementById("ts'.$submission->userid.
3a935caf 668 '").innerHTML="'.addslashes_js($this->print_student_answer($submission->userid)).userdate($submission->timemodified)."\";\n";
be86672d 669 }
45fa3412 670
73097f07 671 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['timemarked']) &&
672 $submission->timemarked) {
73963212 673 $output.= 'opener.document.getElementById("tt'.$submission->userid.
be86672d 674 '").innerHTML="'.userdate($submission->timemarked)."\";\n";
675 }
45fa3412 676
be86672d 677 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['status'])) {
73963212 678 $output.= 'opener.document.getElementById("up'.$submission->userid.'").className="s1";';
9bf660b3 679 $buttontext = get_string('update');
45fa3412 680 $button = link_to_popup_window ('/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;userid='.$submission->userid.'&amp;mode=single'.'&amp;offset='.(optional_param('offset', '', PARAM_INT)-1),
9bf660b3 681 'grade'.$submission->userid, $buttontext, 450, 700, $buttontext, 'none', true, 'button'.$submission->userid);
3a935caf 682 $output.= 'opener.document.getElementById("up'.$submission->userid.'").innerHTML="'.addslashes_js($button).'";';
45fa3412 683 }
f1af7aaa 684
5978010d 685 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $submission->userid);
686
687 if (empty($SESSION->flextable['mod-assignment-submissions']->collapse['finalgrade'])) {
688 $output.= 'opener.document.getElementById("finalgrade_'.$submission->userid.
689 '").innerHTML="'.$grading_info->items[0]->grades[$submission->userid]->str_grade.'";'."\n";
690 }
691
692 if (!empty($CFG->enableoutcomes) and empty($SESSION->flextable['mod-assignment-submissions']->collapse['outcome'])) {
fcac8e51 693
694 if (!empty($grading_info->outcomes)) {
d886a7ea 695 foreach($grading_info->outcomes as $n=>$outcome) {
696 if ($outcome->grades[$submission->userid]->locked) {
697 continue;
698 }
cc03871b 699
d886a7ea 700 if ($quickgrade){
701 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.
702 '").selectedIndex="'.$outcome->grades[$submission->userid]->grade.'";'."\n";
703
704 } else {
705 $options = make_grades_menu(-$outcome->scaleid);
706 $options[0] = get_string('nooutcome', 'grades');
707 $output.= 'opener.document.getElementById("outcome_'.$n.'_'.$submission->userid.'").innerHTML="'.$options[$outcome->grades[$submission->userid]->grade]."\";\n";
708 }
cc03871b 709
710 }
711 }
712 }
713
73963212 714 $output .= "\n-->\n</script>";
715 return $output;
be86672d 716 }
d699cd1e 717
7af1e882 718 /**
719 * Return a grade in user-friendly form, whether it's a scale or not
45fa3412 720 *
7af1e882 721 * @param $grade
722 * @return string User-friendly representation of grade
d59269cf 723 */
724 function display_grade($grade) {
725
c86aa2a4 726 static $scalegrades = array(); // Cache scales for each assignment - they might have different scales!!
d59269cf 727
728 if ($this->assignment->grade >= 0) { // Normal number
082215e6 729 if ($grade == -1) {
730 return '-';
731 } else {
732 return $grade.' / '.$this->assignment->grade;
733 }
d59269cf 734
735 } else { // Scale
c86aa2a4 736 if (empty($scalegrades[$this->assignment->id])) {
d59269cf 737 if ($scale = get_record('scale', 'id', -($this->assignment->grade))) {
c86aa2a4 738 $scalegrades[$this->assignment->id] = make_menu_from_list($scale->scale);
d59269cf 739 } else {
740 return '-';
741 }
742 }
c86aa2a4 743 if (isset($scalegrades[$this->assignment->id][$grade])) {
744 return $scalegrades[$this->assignment->id][$grade];
0f7d4e5e 745 }
39e11905 746 return '-';
d59269cf 747 }
748 }
749
7af1e882 750 /**
b0f2597e 751 * Display a single submission, ready for grading on a popup window
7af1e882 752 *
ea6432fe 753 * This default method prints the teacher info and submissioncomment box at the top and
7af1e882 754 * the student info and submission at the bottom.
755 * This method also fetches the necessary data in order to be able to
756 * provide a "Next submission" button.
757 * Calls preprocess_submission() to give assignment type plug-ins a chance
758 * to process submissions before they are graded
759 * This method gets its arguments from the page parameters userid and offset
b0f2597e 760 */
73963212 761 function display_submission($extra_javascript = '') {
45fa3412 762
082215e6 763 global $CFG;
cc03871b 764 require_once($CFG->libdir.'/gradelib.php');
dd97c328 765 require_once($CFG->libdir.'/tablelib.php');
45fa3412 766
4fdabdc3 767 $userid = required_param('userid', PARAM_INT);
768 $offset = required_param('offset', PARAM_INT);//offset for where to start looking for student.
d699cd1e 769
b0f2597e 770 if (!$user = get_record('user', 'id', $userid)) {
771 error('No such user!');
772 }
d699cd1e 773
39e11905 774 if (!$submission = $this->get_submission($user->id)) {
775 $submission = $this->prepare_new_submission($userid);
b0f2597e 776 }
b0f2597e 777 if ($submission->timemodified > $submission->timemarked) {
778 $subtype = 'assignmentnew';
779 } else {
780 $subtype = 'assignmentold';
781 }
d699cd1e 782
5978010d 783 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array($user->id));
784 $disabled = $grading_info->items[0]->grades[$userid]->locked || $grading_info->items[0]->grades[$userid]->overridden;
785
0cfafdc7 786 /// construct SQL, using current offset to find the data of the next student
9bf660b3 787 $course = $this->course;
788 $assignment = $this->assignment;
789 $cm = $this->cm;
16fc2088 790 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
d699cd1e 791
7bddd4b7 792 /// Get all ppl that can submit assignments
0cfafdc7 793
ba3dc7b4 794 $currentgroup = groups_get_activity_group($cm);
dd97c328 795 if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
796 $users = array_keys($users);
797 }
0cfafdc7 798
dd97c328 799 // if groupmembersonly used, remove users who are not in any group
800 if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
801 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
802 $users = array_intersect($users, array_keys($groupingusers));
803 }
02828119 804 }
805
082215e6 806 $nextid = 0;
dd97c328 807
808 if ($users) {
ad1e3409 809 $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
dd97c328 810 s.id AS submissionid, s.grade, s.submissioncomment,
811 s.timemodified, s.timemarked,
812 COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
813 $sql = 'FROM '.$CFG->prefix.'user u '.
814 'LEFT JOIN '.$CFG->prefix.'assignment_submissions s ON u.id = s.userid
815 AND s.assignment = '.$this->assignment->id.' '.
816 'WHERE u.id IN ('.implode(',', $users).') ';
817
818 if ($sort = flexible_table::get_sql_sort('mod-assignment-submissions')) {
819 $sort = 'ORDER BY '.$sort.' ';
820 }
821
822 if (($auser = get_records_sql($select.$sql.$sort, $offset+1, 1)) !== false) {
823 $nextuser = array_shift($auser);
824 /// Calculate user status
825 $nextuser->status = ($nextuser->timemarked > 0) && ($nextuser->timemarked >= $nextuser->timemodified);
826 $nextid = $nextuser->id;
827 }
9bf660b3 828 }
81532b92 829
9bf660b3 830 print_header(get_string('feedback', 'assignment').':'.fullname($user, true).':'.format_string($this->assignment->name));
d699cd1e 831
73963212 832 /// Print any extra javascript needed for saveandnext
833 echo $extra_javascript;
834
9bf660b3 835 ///SOme javascript to help with setting up >.>
45fa3412 836
c9977d05 837 echo '<script type="text/javascript">'."\n";
9bf660b3 838 echo 'function setNext(){'."\n";
16fc2088 839 echo 'document.getElementById(\'submitform\').mode.value=\'next\';'."\n";
840 echo 'document.getElementById(\'submitform\').userid.value="'.$nextid.'";'."\n";
9bf660b3 841 echo '}'."\n";
45fa3412 842
9bf660b3 843 echo 'function saveNext(){'."\n";
16fc2088 844 echo 'document.getElementById(\'submitform\').mode.value=\'saveandnext\';'."\n";
845 echo 'document.getElementById(\'submitform\').userid.value="'.$nextid.'";'."\n";
846 echo 'document.getElementById(\'submitform\').saveuserid.value="'.$userid.'";'."\n";
847 echo 'document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex;'."\n";
9bf660b3 848 echo '}'."\n";
45fa3412 849
9bf660b3 850 echo '</script>'."\n";
52436fe1 851 echo '<table cellspacing="0" class="feedback '.$subtype.'" >';
d699cd1e 852
9bf660b3 853 ///Start of teacher info row
c69cb506 854
b0f2597e 855 echo '<tr>';
141a922c 856 echo '<td class="picture teacher">';
b0f2597e 857 if ($submission->teacher) {
858 $teacher = get_record('user', 'id', $submission->teacher);
859 } else {
860 global $USER;
861 $teacher = $USER;
862 }
ad1e3409 863 print_user_picture($teacher, $this->course->id, $teacher->picture);
b0f2597e 864 echo '</td>';
865 echo '<td class="content">';
b7dc2256 866 echo '<form id="submitform" action="submissions.php" method="post">';
39bb937a 867 echo '<div>'; // xhtml compatibility - invisiblefieldset was breaking layout here
16fc2088 868 echo '<input type="hidden" name="offset" value="'.($offset+1).'" />';
c9977d05 869 echo '<input type="hidden" name="userid" value="'.$userid.'" />';
870 echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
871 echo '<input type="hidden" name="mode" value="grade" />';
872 echo '<input type="hidden" name="menuindex" value="0" />';//selected menu index
45fa3412 873
9bf660b3 874 //new hidden field, initialized to -1.
c9977d05 875 echo '<input type="hidden" name="saveuserid" value="-1" />';
1a35ee51 876
52436fe1 877 if ($submission->timemarked) {
878 echo '<div class="from">';
879 echo '<div class="fullname">'.fullname($teacher, true).'</div>';
880 echo '<div class="time">'.userdate($submission->timemarked).'</div>';
881 echo '</div>';
882 }
1a35ee51 883 echo '<div class="grade"><label for="menugrade">'.get_string('grade').'</label> ';
5978010d 884 choose_from_menu(make_grades_menu($this->assignment->grade), 'grade', $submission->grade, get_string('nograde'), '', -1, false, $disabled);
52436fe1 885 echo '</div>';
3a5ae660 886
5978010d 887 echo '<div class="clearer"></div>';
888 echo '<div class="finalgrade">'.get_string('finalgrade', 'grades').': '.$grading_info->items[0]->grades[$userid]->str_grade.'</div>';
38f4c3fc 889 echo '<div class="clearer"></div>';
890
fcac8e51 891 if (!empty($CFG->enableoutcomes)) {
d886a7ea 892 foreach($grading_info->outcomes as $n=>$outcome) {
893 echo '<div class="outcome"><label for="menuoutcome_'.$n.'">'.$outcome->name.'</label> ';
894 $options = make_grades_menu(-$outcome->scaleid);
895 if ($outcome->grades[$submission->userid]->locked) {
896 $options[0] = get_string('nooutcome', 'grades');
897 echo $options[$outcome->grades[$submission->userid]->grade];
898 } else {
899 choose_from_menu($options, 'outcome_'.$n.'['.$userid.']', $outcome->grades[$submission->userid]->grade, get_string('nooutcome', 'grades'), '', 0, false, false, 0, 'menuoutcome_'.$n);
3a5ae660 900 }
d886a7ea 901 echo '</div>';
902 echo '<div class="clearer"></div>';
3a5ae660 903 }
3a5ae660 904 }
905
b0f2597e 906
01e2fdfe 907 $this->preprocess_submission($submission);
908
5978010d 909 if ($disabled) {
910 echo '<div class="disabledfeedback">'.$grading_info->items[0]->grades[$userid]->str_feedback.'</div>';
ff8f7015 911
ff8f7015 912 } else {
5978010d 913 print_textarea($this->usehtmleditor, 14, 58, 0, 0, 'submissioncomment', $submission->submissioncomment, $this->course->id);
914 if ($this->usehtmleditor) {
915 echo '<input type="hidden" name="format" value="'.FORMAT_HTML.'" />';
916 } else {
917 echo '<div class="format">';
918 choose_from_menu(format_text_menu(), "format", $submission->format, "");
919 helpbutton("textformat", get_string("helpformatting"));
920 echo '</div>';
921 }
ff8f7015 922 }
b0f2597e 923
9bf660b3 924 ///Print Buttons in Single View
141a922c 925 echo '<div class="buttons">';
16fc2088 926 echo '<input type="submit" name="submit" value="'.get_string('savechanges').'" onclick = "document.getElementById(\'submitform\').menuindex.value = document.getElementById(\'submitform\').grade.selectedIndex" />';
b0f2597e 927 echo '<input type="submit" name="cancel" value="'.get_string('cancel').'" />';
9bf660b3 928 //if there are more to be graded.
082215e6 929 if ($nextid) {
5b48244f 930 echo '<input type="submit" name="saveandnext" value="'.get_string('saveandnext').'" onclick="saveNext()" />';
931 echo '<input type="submit" name="next" value="'.get_string('next').'" onclick="setNext();" />';
9bf660b3 932 }
73097f07 933 echo '</div>';
39bb937a 934 echo '</div></form>';
55b4d096 935
936 $customfeedback = $this->custom_feedbackform($submission, true);
937 if (!empty($customfeedback)) {
45fa3412 938 echo $customfeedback;
55b4d096 939 }
940
73097f07 941 echo '</td></tr>';
45fa3412 942
9bf660b3 943 ///End of teacher info row, Start of student info row
944 echo '<tr>';
141a922c 945 echo '<td class="picture user">';
ad1e3409 946 print_user_picture($user, $this->course->id, $user->picture);
9bf660b3 947 echo '</td>';
948 echo '<td class="topic">';
949 echo '<div class="from">';
950 echo '<div class="fullname">'.fullname($user, true).'</div>';
951 if ($submission->timemodified) {
952 echo '<div class="time">'.userdate($submission->timemodified).
953 $this->display_lateness($submission->timemodified).'</div>';
954 }
955 echo '</div>';
956 $this->print_user_files($user->id);
957 echo '</td>';
958 echo '</tr>';
45fa3412 959
9bf660b3 960 ///End of student info row
45fa3412 961
73097f07 962 echo '</table>';
963
5978010d 964 if (!$disabled and $this->usehtmleditor) {
73097f07 965 use_html_editor();
966 }
967
b0f2597e 968 print_footer('none');
d699cd1e 969 }
970
7af1e882 971 /**
01e2fdfe 972 * Preprocess submission before grading
7af1e882 973 *
974 * Called by display_submission()
975 * The default type does nothing here.
976 * @param $submission object The submission object
01e2fdfe 977 */
978 function preprocess_submission(&$submission) {
979 }
d699cd1e 980
7af1e882 981 /**
b0f2597e 982 * Display all the submissions ready for grading
983 */
fb81abe1 984 function display_submissions($message='') {
9bf660b3 985 global $CFG, $db, $USER;
cc03871b 986 require_once($CFG->libdir.'/gradelib.php');
3446205d 987
9bf660b3 988 /* first we check to see if the form has just been submitted
989 * to request user_preference updates
990 */
45fa3412 991
9bf660b3 992 if (isset($_POST['updatepref'])){
16907e53 993 $perpage = optional_param('perpage', 10, PARAM_INT);
9bf660b3 994 $perpage = ($perpage <= 0) ? 10 : $perpage ;
995 set_user_preference('assignment_perpage', $perpage);
16907e53 996 set_user_preference('assignment_quickgrade', optional_param('quickgrade',0, PARAM_BOOL));
9bf660b3 997 }
1b5910c4 998
45fa3412 999 /* next we get perpage and quickgrade (allow quick grade) params
9bf660b3 1000 * from database
1001 */
1002 $perpage = get_user_preferences('assignment_perpage', 10);
34e67f76 1003
fcac8e51 1004 $quickgrade = get_user_preferences('assignment_quickgrade', 0);
1005
1006 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id);
45fa3412 1007
fcac8e51 1008 if (!empty($CFG->enableoutcomes) and !empty($grading_info->outcomes)) {
e46f4d11 1009 $uses_outcomes = true;
1010 } else {
1011 $uses_outcomes = false;
1012 }
1013
16907e53 1014 $page = optional_param('page', 0, PARAM_INT);
b0f2597e 1015 $strsaveallfeedback = get_string('saveallfeedback', 'assignment');
d0ac6bc2 1016
b0f2597e 1017 /// Some shortcuts to make the code read better
45fa3412 1018
b0f2597e 1019 $course = $this->course;
1020 $assignment = $this->assignment;
1021 $cm = $this->cm;
45fa3412 1022
9bf660b3 1023 $tabindex = 1; //tabindex for quick grading tabbing; Not working for dropdowns yet
91719320 1024
b0f2597e 1025 add_to_log($course->id, 'assignment', 'view submission', 'submissions.php?id='.$this->assignment->id, $this->assignment->id, $this->cm->id);
206ab184 1026
6dac764d 1027 $navigation = build_navigation($this->strsubmissions, $this->cm);
206ab184 1028 print_header_simple(format_string($this->assignment->name,true), "", $navigation,
1029 '', '', true, update_module_button($cm->id, $course->id, $this->strassignment), navmenu($course, $cm));
fb739b77 1030
1031 $course_context = get_context_instance(CONTEXT_COURSE, $course->id);
1032 if (has_capability('gradereport/grader:view', $course_context) && has_capability('moodle/grade:viewall', $course_context)) {
1033 echo '<a class="allcoursegrades" href="' . $CFG->wwwroot . '/grade/report/grader/index.php?id=' . $course->id . '">'
1034 . get_string('seeallcoursegrades', 'grades') . '</a>';
1035 }
7bddd4b7 1036
fb81abe1 1037 if (!empty($message)) {
1038 echo $message; // display messages here if any
1039 }
1040
2d7617c6 1041 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
7bddd4b7 1042
dd97c328 1043 /// Check to see if groups are being used in this assignment
1044
7bddd4b7 1045 /// find out current groups mode
ba3dc7b4 1046 $groupmode = groups_get_activity_groupmode($cm);
1047 $currentgroup = groups_get_activity_group($cm, true);
1048 groups_print_activity_menu($cm, 'submissions.php?id=' . $this->cm->id);
7bddd4b7 1049
1050 /// Get all ppl that are allowed to submit assignments
dd97c328 1051 if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $currentgroup, '', false)) {
33150205 1052 $users = array_keys($users);
1053 }
ba3dc7b4 1054
dd97c328 1055 // if groupmembersonly used, remove users who are not in any group
1056 if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
1057 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
1058 $users = array_intersect($users, array_keys($groupingusers));
1059 }
ba3dc7b4 1060 }
91719320 1061
5978010d 1062 $tablecolumns = array('picture', 'fullname', 'grade', 'submissioncomment', 'timemodified', 'timemarked', 'status', 'finalgrade');
e46f4d11 1063 if ($uses_outcomes) {
5978010d 1064 $tablecolumns[] = 'outcome'; // no sorting based on outcomes column
fbaa56b2 1065 }
1066
206ab184 1067 $tableheaders = array('',
1068 get_string('fullname'),
1069 get_string('grade'),
1070 get_string('comment', 'assignment'),
1071 get_string('lastmodified').' ('.$course->student.')',
1072 get_string('lastmodified').' ('.$course->teacher.')',
5978010d 1073 get_string('status'),
1074 get_string('finalgrade', 'grades'));
e46f4d11 1075 if ($uses_outcomes) {
5978010d 1076 $tableheaders[] = get_string('outcome', 'grades');
fbaa56b2 1077 }
91719320 1078
b0f2597e 1079 require_once($CFG->libdir.'/tablelib.php');
1080 $table = new flexible_table('mod-assignment-submissions');
45fa3412 1081
b0f2597e 1082 $table->define_columns($tablecolumns);
1083 $table->define_headers($tableheaders);
fa22fd5f 1084 $table->define_baseurl($CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id.'&amp;currentgroup='.$currentgroup);
45fa3412 1085
246444b9 1086 $table->sortable(true, 'lastname');//sorted by lastname by default
b0f2597e 1087 $table->collapsible(true);
1088 $table->initialbars(true);
45fa3412 1089
b0f2597e 1090 $table->column_suppress('picture');
1091 $table->column_suppress('fullname');
45fa3412 1092
b0f2597e 1093 $table->column_class('picture', 'picture');
9437c854 1094 $table->column_class('fullname', 'fullname');
1095 $table->column_class('grade', 'grade');
ea6432fe 1096 $table->column_class('submissioncomment', 'comment');
9437c854 1097 $table->column_class('timemodified', 'timemodified');
1098 $table->column_class('timemarked', 'timemarked');
1099 $table->column_class('status', 'status');
5978010d 1100 $table->column_class('finalgrade', 'finalgrade');
e46f4d11 1101 if ($uses_outcomes) {
5978010d 1102 $table->column_class('outcome', 'outcome');
fbaa56b2 1103 }
45fa3412 1104
b0f2597e 1105 $table->set_attribute('cellspacing', '0');
1106 $table->set_attribute('id', 'attempts');
9437c854 1107 $table->set_attribute('class', 'submissions');
b0f2597e 1108 $table->set_attribute('width', '90%');
d9cb14b8 1109 //$table->set_attribute('align', 'center');
45fa3412 1110
5978010d 1111 $table->no_sorting('finalgrade');
1112 $table->no_sorting('outcome');
1113
b0f2597e 1114 // Start working -- this is necessary as soon as the niceties are over
1115 $table->setup();
1116
b0f2597e 1117 if (empty($users)) {
dd97c328 1118 print_heading(get_string('nosubmitusers','assignment'));
b0f2597e 1119 return true;
1120 }
0f1a97c2 1121
b0f2597e 1122 /// Construct the SQL
0f1a97c2 1123
b0f2597e 1124 if ($where = $table->get_sql_where()) {
b0f2597e 1125 $where .= ' AND ';
1126 }
0f1a97c2 1127
b0f2597e 1128 if ($sort = $table->get_sql_sort()) {
86f65395 1129 $sort = ' ORDER BY '.$sort;
b0f2597e 1130 }
9fa49e22 1131
d4ba9ef7 1132 $select = 'SELECT u.id, u.firstname, u.lastname, u.picture, u.imagealt,
45fa3412 1133 s.id AS submissionid, s.grade, s.submissioncomment,
c9265600 1134 s.timemodified, s.timemarked,
1135 COALESCE(SIGN(SIGN(s.timemarked) + SIGN(s.timemarked - s.timemodified)), 0) AS status ';
b0f2597e 1136 $sql = 'FROM '.$CFG->prefix.'user u '.
45fa3412 1137 'LEFT JOIN '.$CFG->prefix.'assignment_submissions s ON u.id = s.userid
9ad5c91f 1138 AND s.assignment = '.$this->assignment->id.' '.
ba3dc7b4 1139 'WHERE '.$where.'u.id IN ('.implode(',',$users).') ';
45fa3412 1140
c5d36203 1141 $table->pagesize($perpage, count($users));
45fa3412 1142
9bf660b3 1143 ///offset used to calculate index of student in that particular query, needed for the pop up to know who's next
1144 $offset = $page * $perpage;
45fa3412 1145
b0f2597e 1146 $strupdate = get_string('update');
9437c854 1147 $strgrade = get_string('grade');
b0f2597e 1148 $grademenu = make_grades_menu($this->assignment->grade);
1149
422770d8 1150 if (($ausers = get_records_sql($select.$sql.$sort, $table->get_page_start(), $table->get_page_size())) !== false) {
fcac8e51 1151 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, array_keys($ausers));
d59269cf 1152 foreach ($ausers as $auser) {
5978010d 1153 $final_grade = $grading_info->items[0]->grades[$auser->id];
9ad5c91f 1154 /// Calculate user status
2ff44114 1155 $auser->status = ($auser->timemarked > 0) && ($auser->timemarked >= $auser->timemodified);
d4ba9ef7 1156 $picture = print_user_picture($auser, $course->id, $auser->picture, false, true);
45fa3412 1157
39e11905 1158 if (empty($auser->submissionid)) {
1159 $auser->grade = -1; //no submission yet
9bf660b3 1160 }
45fa3412 1161
d59269cf 1162 if (!empty($auser->submissionid)) {
9bf660b3 1163 ///Prints student answer and student modified date
1164 ///attach file or print link to student answer, depending on the type of the assignment.
45fa3412 1165 ///Refer to print_student_answer in inherited classes.
1166 if ($auser->timemodified > 0) {
206ab184 1167 $studentmodified = '<div id="ts'.$auser->id.'">'.$this->print_student_answer($auser->id)
1168 . userdate($auser->timemodified).'</div>';
d59269cf 1169 } else {
9437c854 1170 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
d59269cf 1171 }
9bf660b3 1172 ///Print grade, dropdown or text
d59269cf 1173 if ($auser->timemarked > 0) {
1174 $teachermodified = '<div id="tt'.$auser->id.'">'.userdate($auser->timemarked).'</div>';
45fa3412 1175
5978010d 1176 if ($final_grade->locked or $final_grade->overridden) {
1177 $grade = '<div id="g'.$auser->id.'">'.$final_grade->str_grade.'</div>';
1178 } else if ($quickgrade) {
206ab184 1179 $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1180 'menu['.$auser->id.']', $auser->grade,
1181 get_string('nograde'),'',-1,true,false,$tabindex++);
1182 $grade = '<div id="g'.$auser->id.'">'. $menu .'</div>';
9bf660b3 1183 } else {
1184 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1185 }
1186
b0f2597e 1187 } else {
9437c854 1188 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
5978010d 1189 if ($final_grade->locked or $final_grade->overridden) {
1190 $grade = '<div id="g'.$auser->id.'">'.$final_grade->str_grade.'</div>';
1191 } else if ($quickgrade) {
206ab184 1192 $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1193 'menu['.$auser->id.']', $auser->grade,
1194 get_string('nograde'),'',-1,true,false,$tabindex++);
1195 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
9bf660b3 1196 } else {
1197 $grade = '<div id="g'.$auser->id.'">'.$this->display_grade($auser->grade).'</div>';
1198 }
1199 }
1200 ///Print Comment
5978010d 1201 if ($final_grade->locked or $final_grade->overridden) {
1202 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($final_grade->str_feedback),15).'</div>';
1203
1204 } else if ($quickgrade) {
206ab184 1205 $comment = '<div id="com'.$auser->id.'">'
1206 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1207 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
9bf660b3 1208 } else {
ea6432fe 1209 $comment = '<div id="com'.$auser->id.'">'.shorten_text(strip_tags($auser->submissioncomment),15).'</div>';
b0f2597e 1210 }
1211 } else {
9437c854 1212 $studentmodified = '<div id="ts'.$auser->id.'">&nbsp;</div>';
1213 $teachermodified = '<div id="tt'.$auser->id.'">&nbsp;</div>';
9bf660b3 1214 $status = '<div id="st'.$auser->id.'">&nbsp;</div>';
206ab184 1215
5978010d 1216 if ($final_grade->locked or $final_grade->overridden) {
1217 $grade = '<div id="g'.$auser->id.'">'.$final_grade->str_grade.'</div>';
1218 } else if ($quickgrade) { // allow editing
206ab184 1219 $menu = choose_from_menu(make_grades_menu($this->assignment->grade),
1220 'menu['.$auser->id.']', $auser->grade,
1221 get_string('nograde'),'',-1,true,false,$tabindex++);
1222 $grade = '<div id="g'.$auser->id.'">'.$menu.'</div>';
9bf660b3 1223 } else {
39e11905 1224 $grade = '<div id="g'.$auser->id.'">-</div>';
9bf660b3 1225 }
206ab184 1226
5978010d 1227 if ($final_grade->locked or $final_grade->overridden) {
1228 $comment = '<div id="com'.$auser->id.'">'.$final_grade->str_feedback.'</div>';
1229 } else if ($quickgrade) {
206ab184 1230 $comment = '<div id="com'.$auser->id.'">'
1231 . '<textarea tabindex="'.$tabindex++.'" name="submissioncomment['.$auser->id.']" id="submissioncomment'
1232 . $auser->id.'" rows="2" cols="20">'.($auser->submissioncomment).'</textarea></div>';
9bf660b3 1233 } else {
1234 $comment = '<div id="com'.$auser->id.'">&nbsp;</div>';
1235 }
b0f2597e 1236 }
9fa49e22 1237
9ad5c91f 1238 if (empty($auser->status)) { /// Confirm we have exclusively 0 or 1
0f7d4e5e 1239 $auser->status = 0;
9ad5c91f 1240 } else {
1241 $auser->status = 1;
0f7d4e5e 1242 }
1243
9437c854 1244 $buttontext = ($auser->status == 1) ? $strupdate : $strgrade;
45fa3412 1245
fcac8e51 1246 ///No more buttons, we use popups ;-).
1247 $popup_url = '/mod/assignment/submissions.php?id='.$this->cm->id
1248 . '&amp;userid='.$auser->id.'&amp;mode=single'.'&amp;offset='.$offset++;
1249 $button = link_to_popup_window ($popup_url, 'grade'.$auser->id, $buttontext, 600, 780,
1250 $buttontext, 'none', true, 'button'.$auser->id);
206ab184 1251
fcac8e51 1252 $status = '<div id="up'.$auser->id.'" class="s'.$auser->status.'">'.$button.'</div>';
cc03871b 1253
5978010d 1254 $finalgrade = '<span id="finalgrade_'.$auser->id.'">'.$final_grade->str_grade.'</span>';
1255
cc03871b 1256 $outcomes = '';
206ab184 1257
fcac8e51 1258 if ($uses_outcomes) {
206ab184 1259
d886a7ea 1260 foreach($grading_info->outcomes as $n=>$outcome) {
1261 $outcomes .= '<div class="outcome"><label>'.$outcome->name.'</label>';
1262 $options = make_grades_menu(-$outcome->scaleid);
1263
1264 if ($outcome->grades[$auser->id]->locked or !$quickgrade) {
1265 $options[0] = get_string('nooutcome', 'grades');
1266 $outcomes .= ': <span id="outcome_'.$n.'_'.$auser->id.'">'.$options[$outcome->grades[$auser->id]->grade].'</span>';
1267 } else {
1268 $outcomes .= ' ';
1269 $outcomes .= choose_from_menu($options, 'outcome_'.$n.'['.$auser->id.']',
1270 $outcome->grades[$auser->id]->grade, get_string('nooutcome', 'grades'), '', 0, true, false, 0, 'outcome_'.$n.'_'.$auser->id);
cc03871b 1271 }
d886a7ea 1272 $outcomes .= '</div>';
cc03871b 1273 }
1274 }
1275
e2f51ac6 1276 $userlink = '<a href="' . $CFG->wwwroot . '/user/view.php?id=' . $auser->id . '&amp;course=' . $course->id . '">' . fullname($auser) . '</a>';
1277 $row = array($picture, $userlink, $grade, $comment, $studentmodified, $teachermodified, $status, $finalgrade);
e46f4d11 1278 if ($uses_outcomes) {
fbaa56b2 1279 $row[] = $outcomes;
1280 }
1281
d59269cf 1282 $table->add_data($row);
1283 }
b0f2597e 1284 }
45fa3412 1285
082215e6 1286 /// Print quickgrade form around the table
1287 if ($quickgrade){
b7dc2256 1288 echo '<form action="submissions.php" id="fastg" method="post">';
a1b5dd2b 1289 echo '<div>';
820aff13 1290 echo '<input type="hidden" name="id" value="'.$this->cm->id.'" />';
1291 echo '<input type="hidden" name="mode" value="fastgrade" />';
1292 echo '<input type="hidden" name="page" value="'.$page.'" />';
a1b5dd2b 1293 echo '</div>';
fb81abe1 1294 //echo '<div style="text-align:center"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
082215e6 1295 }
1296
1297 $table->print_html(); /// Print the whole table
1298
9bf660b3 1299 if ($quickgrade){
d9cb14b8 1300 echo '<div style="text-align:center"><input type="submit" name="fastg" value="'.get_string('saveallfeedback', 'assignment').'" /></div>';
082215e6 1301 echo '</form>';
9bf660b3 1302 }
082215e6 1303 /// End of fast grading form
45fa3412 1304
082215e6 1305 /// Mini form for setting user preference
9bf660b3 1306 echo '<br />';
b7dc2256 1307 echo '<form id="options" action="submissions.php?id='.$this->cm->id.'" method="post">';
ee8652f3 1308 echo '<div>';
c9977d05 1309 echo '<input type="hidden" id="updatepref" name="updatepref" value="1" />';
ee8652f3 1310 echo '<table id="optiontable" align="right">';
9bf660b3 1311 echo '<tr align="right"><td>';
1312 echo '<label for="perpage">'.get_string('pagesize','assignment').'</label>';
1313 echo ':</td>';
ee8652f3 1314 echo '<td>';
9bf660b3 1315 echo '<input type="text" id="perpage" name="perpage" size="1" value="'.$perpage.'" />';
1316 helpbutton('pagesize', get_string('pagesize','assignment'), 'assignment');
1317 echo '</td></tr>';
fcac8e51 1318 echo '<tr align="right">';
1319 echo '<td>';
1320 print_string('quickgrade','assignment');
1321 echo ':</td>';
ee8652f3 1322 echo '<td>';
fcac8e51 1323 if ($quickgrade){
1324 echo '<input type="checkbox" name="quickgrade" value="1" checked="checked" />';
1325 } else {
1326 echo '<input type="checkbox" name="quickgrade" value="1" />';
9bf660b3 1327 }
fcac8e51 1328 helpbutton('quickgrade', get_string('quickgrade', 'assignment'), 'assignment').'</p></div>';
1329 echo '</td></tr>';
9bf660b3 1330 echo '<tr>';
1331 echo '<td colspan="2" align="right">';
1332 echo '<input type="submit" value="'.get_string('savepreferences').'" />';
1333 echo '</td></tr></table>';
ee8652f3 1334 echo '</div>';
9bf660b3 1335 echo '</form>';
1336 ///End of mini form
b0f2597e 1337 print_footer($this->course);
8e340cb0 1338 }
d699cd1e 1339
7af1e882 1340 /**
1341 * Process teacher feedback submission
1342 *
1343 * This is called by submissions() when a grading even has taken place.
1344 * It gets its data from the submitted form.
1345 * @return object The updated submission object
b0f2597e 1346 */
1347 function process_feedback() {
5978010d 1348 global $CFG, $USER;
1349 require_once($CFG->libdir.'/gradelib.php');
d699cd1e 1350
9894b824 1351 if (!$feedback = data_submitted()) { // No incoming data?
b0f2597e 1352 return false;
d699cd1e 1353 }
b7b42874 1354
9bf660b3 1355 ///For save and next, we need to know the userid to save, and the userid to go
1356 ///We use a new hidden field in the form, and set it to -1. If it's set, we use this
1357 ///as the userid to store
1358 if ((int)$feedback->saveuserid !== -1){
1359 $feedback->userid = $feedback->saveuserid;
1360 }
1361
b0f2597e 1362 if (!empty($feedback->cancel)) { // User hit cancel button
1363 return false;
1364 }
d699cd1e 1365
5978010d 1366 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $feedback->userid);
1367
cc03871b 1368 // store outcomes if needed
1369 $this->process_outcomes($feedback->userid);
1370
7af1e882 1371 $submission = $this->get_submission($feedback->userid, true); // Get or make one
d699cd1e 1372
5978010d 1373 if (!$grading_info->items[0]->grades[$feedback->userid]->locked and
1374 !$grading_info->items[0]->grades[$feedback->userid]->overridden) {
d699cd1e 1375
5978010d 1376 $submission->grade = $feedback->grade;
1377 $submission->submissioncomment = $feedback->submissioncomment;
1378 $submission->format = $feedback->format;
1379 $submission->teacher = $USER->id;
1380 $submission->mailed = 0; // Make sure mail goes out (again, even)
1381 $submission->timemarked = time();
d4156e80 1382
5978010d 1383 unset($submission->data1); // Don't need to update this.
1384 unset($submission->data2); // Don't need to update this.
d699cd1e 1385
5978010d 1386 if (empty($submission->timemodified)) { // eg for offline assignments
1387 // $submission->timemodified = time();
1388 }
d699cd1e 1389
5978010d 1390 if (! update_record('assignment_submissions', $submission)) {
1391 return false;
1392 }
7bddd4b7 1393
5978010d 1394 // triger grade event
1395 $this->update_grade($submission);
1396
1397 add_to_log($this->course->id, 'assignment', 'update grades',
1398 'submissions.php?id='.$this->assignment->id.'&user='.$feedback->userid, $feedback->userid, $this->cm->id);
1399 }
45fa3412 1400
7af1e882 1401 return $submission;
d699cd1e 1402
d699cd1e 1403 }
d699cd1e 1404
cc03871b 1405 function process_outcomes($userid) {
1406 global $CFG, $USER;
fbaa56b2 1407
1408 if (empty($CFG->enableoutcomes)) {
1409 return;
1410 }
1411
cc03871b 1412 require_once($CFG->libdir.'/gradelib.php');
1413
1414 if (!$formdata = data_submitted()) {
1415 return;
1416 }
1417
1418 $data = array();
fcac8e51 1419 $grading_info = grade_get_grades($this->course->id, 'mod', 'assignment', $this->assignment->id, $userid);
1420
1421 if (!empty($grading_info->outcomes)) {
d886a7ea 1422 foreach($grading_info->outcomes as $n=>$old) {
1423 $name = 'outcome_'.$n;
1424 if (isset($formdata->{$name}[$userid]) and $old->grades[$userid]->grade != $formdata->{$name}[$userid]) {
1425 $data[$n] = $formdata->{$name}[$userid];
cc03871b 1426 }
1427 }
1428 }
1429 if (count($data) > 0) {
1430 grade_update_outcomes('mod/assignment', $this->course->id, 'mod', 'assignment', $this->assignment->id, $userid, $data);
1431 }
1432
1433 }
1434
7af1e882 1435 /**
1436 * Load the submission object for a particular user
1437 *
1438 * @param $userid int The id of the user whose submission we want or 0 in which case USER->id is used
1439 * @param $createnew boolean optional Defaults to false. If set to true a new submission object will be created in the database
1440 * @return object The submission
1441 */
f77cfb73 1442 function get_submission($userid=0, $createnew=false) {
1443 global $USER;
1444
1445 if (empty($userid)) {
1446 $userid = $USER->id;
1447 }
1448
b0f2597e 1449 $submission = get_record('assignment_submissions', 'assignment', $this->assignment->id, 'userid', $userid);
d699cd1e 1450
b0f2597e 1451 if ($submission || !$createnew) {
1452 return $submission;
1453 }
39e11905 1454 $newsubmission = $this->prepare_new_submission($userid);
b0f2597e 1455 if (!insert_record("assignment_submissions", $newsubmission)) {
1456 error("Could not insert a new empty submission");
1457 }
d699cd1e 1458
b0f2597e 1459 return get_record('assignment_submissions', 'assignment', $this->assignment->id, 'userid', $userid);
1460 }
d699cd1e 1461
7af1e882 1462 /**
1463 * Instantiates a new submission object for a given user
1464 *
1465 * Sets the assignment, userid and times, everything else is set to default values.
1466 * @param $userid int The userid for which we want a submission object
1467 * @return object The submission
1468 */
39e11905 1469 function prepare_new_submission($userid) {
45fa3412 1470 $submission = new Object;
39e11905 1471 $submission->assignment = $this->assignment->id;
1472 $submission->userid = $userid;
45fa3412 1473 //$submission->timecreated = time();
16fc2088 1474 $submission->timecreated = '';
1475 // teachers should not be modifying modified date, except offline assignments
39e11905 1476 $submission->timemodified = $submission->timecreated;
1477 $submission->numfiles = 0;
1478 $submission->data1 = '';
1479 $submission->data2 = '';
1480 $submission->grade = -1;
ea6432fe 1481 $submission->submissioncomment = '';
39e11905 1482 $submission->format = 0;
1483 $submission->teacher = 0;
1484 $submission->timemarked = 0;
1485 $submission->mailed = 0;
1486 return $submission;
1487 }
1488
7af1e882 1489 /**
1490 * Return all assignment submissions by ENROLLED students (even empty)
1491 *
1492 * @param $sort string optional field names for the ORDER BY in the sql query
1493 * @param $dir string optional specifying the sort direction, defaults to DESC
1494 * @return array The submission objects indexed by id
1495 */
b0f2597e 1496 function get_submissions($sort='', $dir='DESC') {
7af1e882 1497 return assignment_get_all_submissions($this->assignment, $sort, $dir);
b0f2597e 1498 }
1499
7af1e882 1500 /**
1501 * Counts all real assignment submissions by ENROLLED students (not empty ones)
1502 *
1503 * @param $groupid int optional If nonzero then count is restricted to this group
1504 * @return int The number of submissions
1505 */
b0f2597e 1506 function count_real_submissions($groupid=0) {
dd97c328 1507 return assignment_count_real_submissions($this->cm, $groupid);
d59269cf 1508 }
d699cd1e 1509
7af1e882 1510 /**
1511 * Alerts teachers by email of new or changed assignments that need grading
1512 *
1513 * First checks whether the option to email teachers is set for this assignment.
1514 * Sends an email to ALL teachers in the course (or in the group if using separate groups).
1515 * Uses the methods email_teachers_text() and email_teachers_html() to construct the content.
1516 * @param $submission object The submission that has changed
1517 */
73097f07 1518 function email_teachers($submission) {
73097f07 1519 global $CFG;
1520
d8199f1d 1521 if (empty($this->assignment->emailteachers)) { // No need to do anything
73097f07 1522 return;
1523 }
1524
1525 $user = get_record('user', 'id', $submission->userid);
1526
413efd22 1527 if ($teachers = $this->get_graders($user)) {
73097f07 1528
1529 $strassignments = get_string('modulenameplural', 'assignment');
1530 $strassignment = get_string('modulename', 'assignment');
1531 $strsubmitted = get_string('submitted', 'assignment');
1532
1533 foreach ($teachers as $teacher) {
98be6ed8 1534 $info = new object();
413efd22 1535 $info->username = fullname($user, true);
d8199f1d 1536 $info->assignment = format_string($this->assignment->name,true);
1537 $info->url = $CFG->wwwroot.'/mod/assignment/submissions.php?id='.$this->cm->id;
1538
1539 $postsubject = $strsubmitted.': '.$info->username.' -> '.$this->assignment->name;
1540 $posttext = $this->email_teachers_text($info);
1541 $posthtml = ($teacher->mailformat == 1) ? $this->email_teachers_html($info) : '';
73097f07 1542
1543 @email_to_user($teacher, $user, $postsubject, $posttext, $posthtml); // If it fails, oh well, too bad.
1544 }
1545 }
1546 }
1547
413efd22 1548 /**
1549 * Returns a list of teachers that should be grading given submission
1550 */
1551 function get_graders($user) {
1552 //potential graders
7bddd4b7 1553 $potgraders = get_users_by_capability($this->context, 'mod/assignment:grade', '', '', '', '', '', '', false, false);
1554
413efd22 1555 $graders = array();
ba3dc7b4 1556 if (groups_get_activity_groupmode($this->cm) == SEPARATEGROUPS) { // Separate groups are being used
2c386f82 1557 if ($groups = groups_get_all_groups($this->course->id, $user->id)) { // Try to find all groups
413efd22 1558 foreach ($groups as $group) {
1559 foreach ($potgraders as $t) {
1560 if ($t->id == $user->id) {
1561 continue; // do not send self
1562 }
1563 if (groups_is_member($group->id, $t->id)) {
1564 $graders[$t->id] = $t;
1565 }
1566 }
1567 }
1568 } else {
1569 // user not in group, try to find graders without group
1570 foreach ($potgraders as $t) {
1571 if ($t->id == $user->id) {
1572 continue; // do not send self
1573 }
2c386f82 1574 if (!groups_get_all_groups($this->course->id, $t->id)) { //ugly hack
413efd22 1575 $graders[$t->id] = $t;
1576 }
1577 }
1578 }
1579 } else {
1580 foreach ($potgraders as $t) {
1581 if ($t->id == $user->id) {
1582 continue; // do not send self
1583 }
1584 $graders[$t->id] = $t;
1585 }
1586 }
1587 return $graders;
1588 }
1589
7af1e882 1590 /**
1591 * Creates the text content for emails to teachers
1592 *
1593 * @param $info object The info used by the 'emailteachermail' language string
1594 * @return string
1595 */
d8199f1d 1596 function email_teachers_text($info) {
413efd22 1597 $posttext = format_string($this->course->shortname).' -> '.$this->strassignments.' -> '.
1598 format_string($this->assignment->name)."\n";
d8199f1d 1599 $posttext .= '---------------------------------------------------------------------'."\n";
1600 $posttext .= get_string("emailteachermail", "assignment", $info)."\n";
73963212 1601 $posttext .= "\n---------------------------------------------------------------------\n";
d8199f1d 1602 return $posttext;
1603 }
1604
7af1e882 1605 /**
1606 * Creates the html content for emails to teachers
1607 *
1608 * @param $info object The info used by the 'emailteachermailhtml' language string
1609 * @return string
1610 */
d8199f1d 1611 function email_teachers_html($info) {
3554b5c2 1612 global $CFG;
d8199f1d 1613 $posthtml = '<p><font face="sans-serif">'.
413efd22 1614 '<a href="'.$CFG->wwwroot.'/course/view.php?id='.$this->course->id.'">'.format_string($this->course->shortname).'</a> ->'.
d8199f1d 1615 '<a href="'.$CFG->wwwroot.'/mod/assignment/index.php?id='.$this->course->id.'">'.$this->strassignments.'</a> ->'.
413efd22 1616 '<a href="'.$CFG->wwwroot.'/mod/assignment/view.php?id='.$this->cm->id.'">'.format_string($this->assignment->name).'</a></font></p>';
d8199f1d 1617 $posthtml .= '<hr /><font face="sans-serif">';
1618 $posthtml .= '<p>'.get_string('emailteachermailhtml', 'assignment', $info).'</p>';
1619 $posthtml .= '</font><hr />';
815b5ca6 1620 return $posthtml;
d8199f1d 1621 }
1622
7af1e882 1623 /**
1624 * Produces a list of links to the files uploaded by a user
1625 *
1626 * @param $userid int optional id of the user. If 0 then $USER->id is used.
1627 * @param $return boolean optional defaults to false. If true the list is returned rather than printed
1628 * @return string optional
1629 */
d8199f1d 1630 function print_user_files($userid=0, $return=false) {
d8199f1d 1631 global $CFG, $USER;
45fa3412 1632
d8199f1d 1633 if (!$userid) {
1634 if (!isloggedin()) {
1635 return '';
1636 }
1637 $userid = $USER->id;
1638 }
45fa3412 1639
70b2c772 1640 $filearea = $this->file_area_name($userid);
73097f07 1641
1642 $output = '';
45fa3412 1643
70b2c772 1644 if ($basedir = $this->file_area($userid)) {
73097f07 1645 if ($files = get_directory_list($basedir)) {
1ef048ae 1646 require_once($CFG->libdir.'/filelib.php');
73097f07 1647 foreach ($files as $key => $file) {
45fa3412 1648
73097f07 1649 $icon = mimeinfo('icon', $file);
45fa3412 1650
73097f07 1651 if ($CFG->slasharguments) {
d4156e80 1652 $ffurl = "$CFG->wwwroot/file.php/$filearea/$file";
73097f07 1653 } else {
d4156e80 1654 $ffurl = "$CFG->wwwroot/file.php?file=/$filearea/$file";
73097f07 1655 }
45fa3412 1656
0d905d9f 1657 $output .= '<img align="middle" src="'.$CFG->pixpath.'/f/'.$icon.'" class="icon" alt="'.$icon.'" />'.
9bf660b3 1658 '<a href="'.$ffurl.'" >'.$file.'</a><br />';
73097f07 1659 }
1660 }
1661 }
1662
1663 $output = '<div class="files">'.$output.'</div>';
1664
1665 if ($return) {
1666 return $output;
1667 }
1668 echo $output;
1669 }
1670
7af1e882 1671 /**
1672 * Count the files uploaded by a given user
1673 *
1674 * @param $userid int The user id
1675 * @return int
1676 */
70b2c772 1677 function count_user_files($userid) {
1678 global $CFG;
1679
1680 $filearea = $this->file_area_name($userid);
1681
c853b39f 1682 if ( is_dir($CFG->dataroot.'/'.$filearea) && $basedir = $this->file_area($userid)) {
70b2c772 1683 if ($files = get_directory_list($basedir)) {
1684 return count($files);
1685 }
1686 }
1687 return 0;
1688 }
73097f07 1689
7af1e882 1690 /**
1691 * Creates a directory file name, suitable for make_upload_directory()
1692 *
1693 * @param $userid int The user id
1694 * @return string path to file area
1695 */
70b2c772 1696 function file_area_name($userid) {
73097f07 1697 global $CFG;
45fa3412 1698
70b2c772 1699 return $this->course->id.'/'.$CFG->moddata.'/assignment/'.$this->assignment->id.'/'.$userid;
73097f07 1700 }
7af1e882 1701
1702 /**
1703 * Makes an upload directory
1704 *
1705 * @param $userid int The user id
1706 * @return string path to file area.
1707 */
70b2c772 1708 function file_area($userid) {
1709 return make_upload_directory( $this->file_area_name($userid) );
73097f07 1710 }
1711
7af1e882 1712 /**
1713 * Returns true if the student is allowed to submit
1714 *
1715 * Checks that the assignment has started and, if the option to prevent late
1716 * submissions is set, also checks that the assignment has not yet closed.
1717 * @return boolean
1718 */
f77cfb73 1719 function isopen() {
1720 $time = time();
1e4343a0 1721 if ($this->assignment->preventlate && $this->assignment->timedue) {
f77cfb73 1722 return ($this->assignment->timeavailable <= $time && $time <= $this->assignment->timedue);
1723 } else {
1724 return ($this->assignment->timeavailable <= $time);
1725 }
1726 }
1727
0b5a80a1 1728
1729 /**
dc6cb74e 1730 * Return true if is set description is hidden till available date
1731 *
0b5a80a1 1732 * This is needed by calendar so that hidden descriptions do not
dc6cb74e 1733 * come up in upcoming events.
1734 *
0b5a80a1 1735 * Check that description is hidden till available date
dc6cb74e 1736 * By default return false
1737 * Assignments types should implement this method if needed
1738 * @return boolen
0b5a80a1 1739 */
dc6cb74e 1740 function description_is_hidden() {
1741 return false;
1742 }
1743
7af1e882 1744 /**
1745 * Return an outline of the user's interaction with the assignment
1746 *
1747 * The default method prints the grade and timemodified
1748 * @param $user object
1749 * @return object with properties ->info and ->time
1750 */
73097f07 1751 function user_outline($user) {
1752 if ($submission = $this->get_submission($user->id)) {
39e11905 1753
98be6ed8 1754 $result = new object();
39e11905 1755 $result->info = get_string('grade').': '.$this->display_grade($submission->grade);
73097f07 1756 $result->time = $submission->timemodified;
1757 return $result;
1758 }
1759 return NULL;
1760 }
7af1e882 1761
1762 /**
1763 * Print complete information about the user's interaction with the assignment
1764 *
1765 * @param $user object
1766 */
73097f07 1767 function user_complete($user) {
1768 if ($submission = $this->get_submission($user->id)) {
70b2c772 1769 if ($basedir = $this->file_area($user->id)) {
73097f07 1770 if ($files = get_directory_list($basedir)) {
1771 $countfiles = count($files)." ".get_string("uploadedfiles", "assignment");
1772 foreach ($files as $file) {
1773 $countfiles .= "; $file";
1774 }
1775 }
1776 }
45fa3412 1777
73097f07 1778 print_simple_box_start();
1779 echo get_string("lastmodified").": ";
9bf660b3 1780 echo userdate($submission->timemodified);
1781 echo $this->display_lateness($submission->timemodified);
45fa3412 1782
70b2c772 1783 $this->print_user_files($user->id);
45fa3412 1784
73097f07 1785 echo '<br />';
45fa3412 1786
73097f07 1787 if (empty($submission->timemarked)) {
1788 print_string("notgradedyet", "assignment");
1789 } else {
1790 $this->view_feedback($submission);
1791 }
45fa3412 1792
73097f07 1793 print_simple_box_end();
45fa3412 1794
73097f07 1795 } else {
1796 print_string("notsubmittedyet", "assignment");
1797 }
1798 }
1799
7af1e882 1800 /**
1801 * Return a string indicating how late a submission is
1802 *
45fa3412 1803 * @param $timesubmitted int
7af1e882 1804 * @return string
1805 */
70b2c772 1806 function display_lateness($timesubmitted) {
76a60031 1807 return assignment_display_lateness($timesubmitted, $this->assignment->timedue);
73097f07 1808 }
1809
55b4d096 1810 /**
1811 * Empty method stub for all delete actions.
1812 */
1813 function delete() {
1814 //nothing by default
1815 redirect('view.php?id='.$this->cm->id);
1816 }
1817
1818 /**
1819 * Empty custom feedback grading form.
1820 */
1821 function custom_feedbackform($submission, $return=false) {
1822 //nothing by default
1823 return '';
1824 }
73097f07 1825
09ba8e56 1826 /**
1827 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
1828 * for the course (see resource).
1829 *
206ab184 1830 * Given a course_module object, this function returns any "extra" information that may be needed
09ba8e56 1831 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
206ab184 1832 *
09ba8e56 1833 * @param $coursemodule object The coursemodule object (record).
1834 * @return object An object on information that the coures will know about (most noticeably, an icon).
206ab184 1835 *
09ba8e56 1836 */
1837 function get_coursemodule_info($coursemodule) {
1838 return false;
1839 }
1840
d014b69b 1841 /**
1842 * Plugin cron method - do not use $this here, create new assignment instances if needed.
1843 * @return void
1844 */
1845 function cron() {
1846 //no plugin cron by default - override if needed
1847 }
1848
0b5a80a1 1849 /**
1850 * Reset all submissions
1851 */
1852 function reset_userdata($data) {
1853 global $CFG;
1854 require_once($CFG->libdir.'/filelib.php');
1855
1856 if (!count_records('assignment', 'course', $data->courseid, 'assignmenttype', $this->type)) {
1857 return array(); // no assignments of this type present
1858 }
1859
1860 $componentstr = get_string('modulenameplural', 'assignment');
1861 $status = array();
1862
1863 $typestr = get_string('type'.$this->type, 'assignment');
1864
1865 if (!empty($data->reset_assignment_submissions)) {
1866 $assignmentssql = "SELECT a.id
1867 FROM {$CFG->prefix}assignment a
1868 WHERE a.course={$data->courseid} AND a.assignmenttype='{$this->type}'";
1869
1870 delete_records_select('assignment_submissions', "assignment IN ($assignmentssql)");
1871
1872 if ($assignments = get_records_sql($assignmentssql)) {
1873 foreach ($assignments as $assignmentid=>$unused) {
1874 fulldelete($CFG->dataroot.'/'.$data->courseid.'/moddata/assignment/'.$assignmentid);
1875 }
1876 }
1877
1878 $status[] = array('component'=>$componentstr, 'item'=>get_string('deleteallsubmissions','assignment').': '.$typestr, 'error'=>false);
dd97c328 1879
0b5a80a1 1880 if (empty($data->reset_gradebook_grades)) {
1881 // remove all grades from gradebook
1882 assignment_reset_gradebook($data->courseid, $this->type);
1883 }
1884 }
1885
1886 /// updating dates - shift may be negative too
1887 if ($data->timeshift) {
1888 shift_course_mod_dates('assignment', array('timedue', 'timeavailable'), $data->timeshift, $data->courseid);
1889 $status[] = array('component'=>$componentstr, 'item'=>get_string('datechanged').': '.$typestr, 'error'=>false);
1890 }
1891
1892 return $status;
1893 }
b0f2597e 1894} ////// End of the assignment_base class
d699cd1e 1895
18b8fbfa 1896
04eba58f 1897
b0f2597e 1898/// OTHER STANDARD FUNCTIONS ////////////////////////////////////////////////////////
1899
7af1e882 1900/**
1901 * Deletes an assignment instance
1902 *
1903 * This is done by calling the delete_instance() method of the assignment type class
1904 */
b0f2597e 1905function assignment_delete_instance($id){
26b90e70 1906 global $CFG;
1907
b0f2597e 1908 if (! $assignment = get_record('assignment', 'id', $id)) {
1909 return false;
26b90e70 1910 }
1911
1fc87774 1912 // fall back to base class if plugin missing
1913 $classfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
1914 if (file_exists($classfile)) {
1915 require_once($classfile);
1916 $assignmentclass = "assignment_$assignment->assignmenttype";
1917
1918 } else {
1919 debugging("Missing assignment plug-in: {$assignment->assignmenttype}. Using base class for deleting instead.");
1920 $assignmentclass = "assignment_base";
1921 }
1922
b0f2597e 1923 $ass = new $assignmentclass();
1924 return $ass->delete_instance($assignment);
1925}
f466c9ed 1926
ac21ad39 1927
7af1e882 1928/**
1929 * Updates an assignment instance
1930 *
1931 * This is done by calling the update_instance() method of the assignment type class
1932 */
b0f2597e 1933function assignment_update_instance($assignment){
1934 global $CFG;
26b90e70 1935
200c19fb 1936 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
1937
b0f2597e 1938 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1939 $assignmentclass = "assignment_$assignment->assignmenttype";
1940 $ass = new $assignmentclass();
1941 return $ass->update_instance($assignment);
45fa3412 1942}
26b90e70 1943
26b90e70 1944
7af1e882 1945/**
1946 * Adds an assignment instance
1947 *
1948 * This is done by calling the add_instance() method of the assignment type class
1949 */
b0f2597e 1950function assignment_add_instance($assignment) {
1951 global $CFG;
f466c9ed 1952
200c19fb 1953 $assignment->assignmenttype = clean_param($assignment->assignmenttype, PARAM_SAFEDIR);
1954
b0f2597e 1955 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1956 $assignmentclass = "assignment_$assignment->assignmenttype";
1957 $ass = new $assignmentclass();
1958 return $ass->add_instance($assignment);
1959}
f466c9ed 1960
73097f07 1961
7af1e882 1962/**
1963 * Returns an outline of a user interaction with an assignment
1964 *
1965 * This is done by calling the user_outline() method of the assignment type class
1966 */
73097f07 1967function assignment_user_outline($course, $user, $mod, $assignment) {
1968 global $CFG;
1969
1970 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1971 $assignmentclass = "assignment_$assignment->assignmenttype";
1972 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
1973 return $ass->user_outline($user);
1974}
1975
7af1e882 1976/**
1977 * Prints the complete info about a user's interaction with an assignment
1978 *
1979 * This is done by calling the user_complete() method of the assignment type class
1980 */
73097f07 1981function assignment_user_complete($course, $user, $mod, $assignment) {
1982 global $CFG;
1983
1984 require_once("$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php");
1985 $assignmentclass = "assignment_$assignment->assignmenttype";
1986 $ass = new $assignmentclass($mod->id, $assignment, $mod, $course);
1987 return $ass->user_complete($user);
1988}
1989
7af1e882 1990/**
1991 * Function to be run periodically according to the moodle cron
1992 *
1993 * Finds all assignment notifications that have yet to be mailed out, and mails them
1994 */
73097f07 1995function assignment_cron () {
73097f07 1996
1997 global $CFG, $USER;
1998
d014b69b 1999 /// first execute all crons in plugins
2000 if ($plugins = get_list_of_plugins('mod/assignment/type')) {
2001 foreach ($plugins as $plugin) {
2002 require_once("$CFG->dirroot/mod/assignment/type/$plugin/assignment.class.php");
2003 $assignmentclass = "assignment_$plugin";
2004 $ass = new $assignmentclass();
2005 $ass->cron();
2006 }
2007 }
2008
73097f07 2009 /// Notices older than 1 day will not be mailed. This is to avoid the problem where
2010 /// cron has not been running for a long time, and then suddenly people are flooded
2011 /// with mail from the past few weeks or months
2012
2013 $timenow = time();
2014 $endtime = $timenow - $CFG->maxeditingtime;
2015 $starttime = $endtime - 24 * 3600; /// One day earlier
2016
2017 if ($submissions = assignment_get_unmailed_submissions($starttime, $endtime)) {
2018
98be6ed8 2019 $CFG->enablerecordcache = true; // We want all the caching we can get
2020
2021 $realuser = clone($USER);
2022
73097f07 2023 foreach ($submissions as $key => $submission) {
2024 if (! set_field("assignment_submissions", "mailed", "1", "id", "$submission->id")) {
2025 echo "Could not update the mailed field for id $submission->id. Not mailed.\n";
2026 unset($submissions[$key]);
2027 }
2028 }
2029
2030 $timenow = time();
2031
2032 foreach ($submissions as $submission) {
2033
2034 echo "Processing assignment submission $submission->id\n";
2035
2036 if (! $user = get_record("user", "id", "$submission->userid")) {
2037 echo "Could not find user $post->userid\n";
2038 continue;
2039 }
2040
73097f07 2041 if (! $course = get_record("course", "id", "$submission->course")) {
2042 echo "Could not find course $submission->course\n";
2043 continue;
2044 }
98be6ed8 2045
2046 /// Override the language and timezone of the "current" user, so that
2047 /// mail is customised for the receiver.
2048 $USER = $user;
2049 course_setup($course);
2050
dbbb712e 2051 if (!has_capability('moodle/course:view', get_context_instance(CONTEXT_COURSE, $submission->course), $user->id)) {
6ba65fa0 2052 echo fullname($user)." not an active participant in " . format_string($course->shortname) . "\n";
73097f07 2053 continue;
2054 }
2055
2056 if (! $teacher = get_record("user", "id", "$submission->teacher")) {
2057 echo "Could not find teacher $submission->teacher\n";
2058 continue;
2059 }
2060
2061 if (! $mod = get_coursemodule_from_instance("assignment", $submission->assignment, $course->id)) {
2062 echo "Could not find course module for assignment id $submission->assignment\n";
2063 continue;
2064 }
2065
2066 if (! $mod->visible) { /// Hold mail notification for hidden assignments until later
2067 continue;
2068 }
2069
2070 $strassignments = get_string("modulenameplural", "assignment");
2071 $strassignment = get_string("modulename", "assignment");
2072
98be6ed8 2073 $assignmentinfo = new object();
73097f07 2074 $assignmentinfo->teacher = fullname($teacher);
2075 $assignmentinfo->assignment = format_string($submission->name,true);
2076 $assignmentinfo->url = "$CFG->wwwroot/mod/assignment/view.php?id=$mod->id";
2077
2078 $postsubject = "$course->shortname: $strassignments: ".format_string($submission->name,true);
2079 $posttext = "$course->shortname -> $strassignments -> ".format_string($submission->name,true)."\n";
2080 $posttext .= "---------------------------------------------------------------------\n";
3f19bff3 2081 $posttext .= get_string("assignmentmail", "assignment", $assignmentinfo)."\n";
73097f07 2082 $posttext .= "---------------------------------------------------------------------\n";
2083
2084 if ($user->mailformat == 1) { // HTML
2085 $posthtml = "<p><font face=\"sans-serif\">".
2086 "<a href=\"$CFG->wwwroot/course/view.php?id=$course->id\">$course->shortname</a> ->".
2087 "<a href=\"$CFG->wwwroot/mod/assignment/index.php?id=$course->id\">$strassignments</a> ->".
2088 "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id=$mod->id\">".format_string($submission->name,true)."</a></font></p>";
2089 $posthtml .= "<hr /><font face=\"sans-serif\">";
2090 $posthtml .= "<p>".get_string("assignmentmailhtml", "assignment", $assignmentinfo)."</p>";
2091 $posthtml .= "</font><hr />";
2092 } else {
2093 $posthtml = "";
2094 }
2095
2096 if (! email_to_user($user, $teacher, $postsubject, $posttext, $posthtml)) {
2097 echo "Error: assignment cron: Could not send out mail for id $submission->id to user $user->id ($user->email)\n";
2098 }
2099 }
98be6ed8 2100
2101 $USER = $realuser;
2102 course_setup(SITEID); // reset cron user language, theme and timezone settings
2103
73097f07 2104 }
2105
2106 return true;
2107}
2108
45fa3412 2109/**
2110 * Return grade for given user or all users.
2111 *
2112 * @param int $assignmentid id of assignment
2113 * @param int $userid optional user id, 0 means all users
2114 * @return array array of grades, false if none
2115 */
612607bd 2116function assignment_get_user_grades($assignment, $userid=0) {
45fa3412 2117 global $CFG;
2118
2119 $user = $userid ? "AND u.id = $userid" : "";
2120
ced5ee59 2121 $sql = "SELECT u.id, u.id AS userid, s.grade AS rawgrade, s.submissioncomment AS feedback, s.format AS feedbackformat,
2122 s.teacher AS usermodified, s.timemarked AS dategraded, s.timemodified AS datesubmitted
45fa3412 2123 FROM {$CFG->prefix}user u, {$CFG->prefix}assignment_submissions s
612607bd 2124 WHERE u.id = s.userid AND s.assignment = $assignment->id
4a1be95c 2125 $user";
45fa3412 2126
2127 return get_records_sql($sql);
2128}
2129
2130/**
2131 * Update grades by firing grade_updated event
2132 *
612607bd 2133 * @param object $assignment null means all assignments
45fa3412 2134 * @param int $userid specific user only, 0 mean all
2135 */
612607bd 2136function assignment_update_grades($assignment=null, $userid=0, $nullifnone=true) {
45fa3412 2137 global $CFG;
612607bd 2138 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
2139 require_once($CFG->libdir.'/gradelib.php');
2140 }
45fa3412 2141
612607bd 2142 if ($assignment != null) {
2143 if ($grades = assignment_get_user_grades($assignment, $userid)) {
2144 foreach($grades as $k=>$v) {
ac9b0805 2145 if ($v->rawgrade == -1) {
2146 $grades[$k]->rawgrade = null;
45fa3412 2147 }
45fa3412 2148 }
ced5ee59 2149 assignment_grade_item_update($assignment, $grades);
30923fcd 2150 } else {
eafb9d9e 2151 assignment_grade_item_update($assignment);
45fa3412 2152 }
2153
2154 } else {
4a1be95c 2155 $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
2156 FROM {$CFG->prefix}assignment a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
2157 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id";
45fa3412 2158 if ($rs = get_recordset_sql($sql)) {
03cedd62 2159 while ($assignment = rs_fetch_next_record($rs)) {
0b7870f3 2160 if ($assignment->grade != 0) {
03cedd62 2161 assignment_update_grades($assignment);
ced5ee59 2162 } else {
2163 assignment_grade_item_update($assignment);
45fa3412 2164 }
2165 }
2166 rs_close($rs);
2167 }
2168 }
2169}
2170
2171/**
612607bd 2172 * Create grade item for given assignment
45fa3412 2173 *
8b4fb44e 2174 * @param object $assignment object with extra cmidnumber
0b5a80a1 2175 * @param mixed optional array/object of grade(s); 'reset' means reset grades in gradebook
612607bd 2176 * @return int 0 if ok, error code otherwise
45fa3412 2177 */
ced5ee59 2178function assignment_grade_item_update($assignment, $grades=NULL) {
612607bd 2179 global $CFG;
2180 if (!function_exists('grade_update')) { //workaround for buggy PHP versions
2181 require_once($CFG->libdir.'/gradelib.php');
45fa3412 2182 }
2183
8b4fb44e 2184 if (!isset($assignment->courseid)) {
2185 $assignment->courseid = $assignment->course;
2186 }
2187
612607bd 2188 $params = array('itemname'=>$assignment->name, 'idnumber'=>$assignment->cmidnumber);
45fa3412 2189
2190 if ($assignment->grade > 0) {
2191 $params['gradetype'] = GRADE_TYPE_VALUE;
2192 $params['grademax'] = $assignment->grade;
2193 $params['grademin'] = 0;
2194
2195 } else if ($assignment->grade < 0) {
2196 $params['gradetype'] = GRADE_TYPE_SCALE;
2197 $params['scaleid'] = -$assignment->grade;
2198
2199 } else {
612607bd 2200 $params['gradetype'] = GRADE_TYPE_NONE;
45fa3412 2201 }
2202
0b5a80a1 2203 if ($grades === 'reset') {
2204 $params['reset'] = true;
2205 $grades = NULL;
2206 }
2207
ced5ee59 2208 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, $grades, $params);
45fa3412 2209}
2210
2211/**
2212 * Delete grade item for given assignment
2213 *
8b4fb44e 2214 * @param object $assignment object
612607bd 2215 * @return object assignment
45fa3412 2216 */
2217function assignment_grade_item_delete($assignment) {
612607bd 2218 global $CFG;
2219 require_once($CFG->libdir.'/gradelib.php');
2220
8b4fb44e 2221 if (!isset($assignment->courseid)) {
2222 $assignment->courseid = $assignment->course;
2223 }
2224
b67ec72f 2225 return grade_update('mod/assignment', $assignment->courseid, 'mod', 'assignment', $assignment->id, 0, NULL, array('deleted'=>1));
45fa3412 2226}
2227
7af1e882 2228/**
2229 * Returns the users with data in one assignment (students and teachers)
2230 *
2231 * @param $assignmentid int
2232 * @return array of user objects
2233 */
73097f07 2234function assignment_get_participants($assignmentid) {
73097f07 2235
2236 global $CFG;
2237
2238 //Get students
2239 $students = get_records_sql("SELECT DISTINCT u.id, u.id
2240 FROM {$CFG->prefix}user u,
2241 {$CFG->prefix}assignment_submissions a
2242 WHERE a.assignment = '$assignmentid' and
2243 u.id = a.userid");
2244 //Get teachers
2245 $teachers = get_records_sql("SELECT DISTINCT u.id, u.id
2246 FROM {$CFG->prefix}user u,
2247 {$CFG->prefix}assignment_submissions a
2248 WHERE a.assignment = '$assignmentid' and
2249 u.id = a.teacher");
2250
2251 //Add teachers to students
2252 if ($teachers) {
2253 foreach ($teachers as $teacher) {
2254 $students[$teacher->id] = $teacher;
2255 }
2256 }
2257 //Return students array (it contains an array of unique users)
2258 return ($students);
2259}
2260
7af1e882 2261/**
2262 * Checks if a scale is being used by an assignment
2263 *
2264 * This is used by the backup code to decide whether to back up a scale
2265 * @param $assignmentid int
2266 * @param $scaleid int
2267 * @return boolean True if the scale is used by the assignment
2268 */
85c9ebb9 2269function assignment_scale_used($assignmentid, $scaleid) {
73097f07 2270
2271 $return = false;
2272
2273 $rec = get_record('assignment','id',$assignmentid,'grade',-$scaleid);
2274
2275 if (!empty($rec) && !empty($scaleid)) {
2276 $return = true;
2277 }
2278
2279 return $return;
2280}
2281
85c9ebb9 2282/**
2283 * Checks if scale is being used by any instance of assignment
2284 *
2285 * This is used to find out if scale used anywhere
2286 * @param $scaleid int
2287 * @return boolean True if the scale is used by any assignment
2288 */
2289function assignment_scale_used_anywhere($scaleid) {
2290 if ($scaleid and record_exists('assignment', 'grade', -$scaleid)) {
2291 return true;
2292 } else {
2293 return false;
2294 }
2295}
2296
7af1e882 2297/**
2298 * Make sure up-to-date events are created for all assignment instances
2299 *
2300 * This standard function will check all instances of this module
2301 * and make sure there are up-to-date events created for each of them.
2302 * If courseid = 0, then every assignment event in the site is checked, else
2303 * only assignment events belonging to the course specified are checked.
2304 * This function is used, in its new format, by restore_refresh_events()
2305 *
2306 * @param $courseid int optional If zero then all assignments for all courses are covered
2307 * @return boolean Always returns true
2308 */
73097f07 2309function assignment_refresh_events($courseid = 0) {
73097f07 2310
2311 if ($courseid == 0) {
2312 if (! $assignments = get_records("assignment")) {
2313 return true;
2314 }
2315 } else {
2316 if (! $assignments = get_records("assignment", "course", $courseid)) {
2317 return true;
2318 }
2319 }
2320 $moduleid = get_field('modules', 'id', 'name', 'assignment');
2321
2322 foreach ($assignments as $assignment) {
2323 $event = NULL;
2324 $event->name = addslashes($assignment->name);
2325 $event->description = addslashes($assignment->description);
2326 $event->timestart = $assignment->timedue;
2327
2328 if ($event->id = get_field('event', 'id', 'modulename', 'assignment', 'instance', $assignment->id)) {
2329 update_event($event);
2330
2331 } else {
2332 $event->courseid = $assignment->course;
2333 $event->groupid = 0;
2334 $event->userid = 0;
2335 $event->modulename = 'assignment';
2336 $event->instance = $assignment->id;
2337 $event->eventtype = 'due';
2338 $event->timeduration = 0;
2339 $event->visible = get_field('course_modules', 'visible', 'module', $moduleid, 'instance', $assignment->id);
2340 add_event($event);
2341 }
2342
2343 }
2344 return true;
2345}
2346
7af1e882 2347/**
2348 * Print recent activity from all assignments in a given course
2349 *
2350 * This is used by the recent activity block
2351 */
dd97c328 2352function assignment_print_recent_activity($course, $viewfullnames, $timestart) {
2353 global $CFG, $USER;
73097f07 2354
dd97c328 2355 // do not use log table if possible, it may be huge
73097f07 2356
dd97c328 2357 if (!$submissions = get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, asb.userid,
2358 u.firstname, u.lastname, u.email, u.picture
2359 FROM {$CFG->prefix}assignment_submissions asb
2360 JOIN {$CFG->prefix}assignment a ON a.id = asb.assignment
2361 JOIN {$CFG->prefix}course_modules cm ON cm.instance = a.id
2362 JOIN {$CFG->prefix}modules md ON md.id = cm.module
2363 JOIN {$CFG->prefix}user u ON u.id = asb.userid
2364 WHERE asb.timemodified > $timestart AND
2365 a.course = {$course->id} AND
2366 md.name = 'assignment'
2367 ORDER BY asb.timemodified ASC")) {
2368 return false;
73097f07 2369 }
2370
dd97c328 2371 $modinfo =& get_fast_modinfo($course); // reference needed because we might load the groups
2372 $show = array();
2373 $grader = array();
2374
2375 foreach($submissions as $submission) {
2376 if (!array_key_exists($submission->cmid, $modinfo->cms)) {
2377 continue;
2378 }
2379 $cm = $modinfo->cms[$submission->cmid];
2380 if (!$cm->uservisible) {
2381 continue;
2382 }
2383 if ($submission->userid == $USER->id) {
2384 $show[] = $submission;
2385 continue;
2386 }
2387
2388 // the act of sumitting of assignemnt may be considered private - only graders will see it if specified
2389 if (empty($CFG->assignment_showrecentsubmissions)) {
2390 if (!array_key_exists($cm->id, $grader)) {
2391 $grader[$cm->id] = has_capability('moodle/grade:viewall', get_context_instance(CONTEXT_MODULE, $cm->id));
2392 }
2393 if (!$grader[$cm->id]) {
2394 continue;
70b5660a 2395 }
73097f07 2396 }
73097f07 2397
dd97c328 2398 $groupmode = groups_get_activity_groupmode($cm, $course);
2399
2400 if ($groupmode == SEPARATEGROUPS and !has_capability('moodle/site:accessallgroups', get_context_instance(CONTEXT_MODULE, $cm->id))) {
2401 if (isguestuser()) {
2402 // shortcut - guest user does not belong into any group
2403 continue;
2404 }
2405
2406 if (is_null($modinfo->groups)) {
2407 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2408 }
2409
2410 // this will be slow - show only users that share group with me in this cm
2411 if (empty($modinfo->groups[$cm->id])) {
2412 continue;
2413 }
2414 $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2415 if (is_array($usersgroups)) {
2416 $usersgroups = array_keys($usersgroups);
2417 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2418 if (empty($intersect)) {
2419 continue;
2420 }
2421 }
73097f07 2422 }
dd97c328 2423 $show[] = $submission;
73097f07 2424 }
2425
dd97c328 2426 if (empty($show)) {
2427 return false;
2428 }
2429
2430 print_headline(get_string('newsubmissions', 'assignment').':');
2431
2432 foreach ($show as $submission) {
2433 $cm = $modinfo->cms[$submission->cmid];
2434 $link = $CFG->wwwroot.'/mod/assignment/view.php?id='.$cm->id;
2435 print_recent_activity_note($submission->timemodified, $submission, $cm->name, $link, false, $viewfullnames);
2436 }
2437
2438 return true;
73097f07 2439}
2440
2441
7af1e882 2442/**
dd97c328 2443 * Returns all assignments since a given time in specified forum.
7af1e882 2444 */
dd97c328 2445function assignment_get_recent_mod_activity(&$activities, &$index, $timestart, $courseid, $cmid, $userid=0, $groupid=0) {
73097f07 2446
dd97c328 2447 global $CFG, $COURSE, $USER;
73097f07 2448
dd97c328 2449 if ($COURSE->id == $courseid) {
2450 $course = $COURSE;
73097f07 2451 } else {
dd97c328 2452 $course = get_record('course', 'id', $courseid);
73097f07 2453 }
dd97c328 2454
2455 $modinfo =& get_fast_modinfo($course);
2456
2457 $cm = $modinfo->cms[$cmid];
2458
2459 if ($userid) {
2460 $userselect = "AND u.id = $userid";
73097f07 2461 } else {
2462 $userselect = "";
2463 }
2464
dd97c328 2465 if ($groupid) {
2466 $groupselect = "AND gm.groupid = $groupid";
2467 $groupjoin = "JOIN {$CFG->prefix}groups_members gm ON gm.userid=u.id";
2468 } else {
2469 $groupselect = "";
2470 $groupjoin = "";
2471 }
73097f07 2472
dd97c328 2473 if (!$submissions = get_records_sql("SELECT asb.id, asb.timemodified, asb.userid,
2474 u.firstname, u.lastname, u.email, u.picture
2475 FROM {$CFG->prefix}assignment_submissions asb
2476 JOIN {$CFG->prefix}assignment a ON a.id = asb.assignment
2477 JOIN {$CFG->prefix}user u ON u.id = asb.userid
2478 $groupjoin
2479 WHERE asb.timemodified > $timestart AND a.id = $cm->instance
2480 $userselect $groupselect
2481 ORDER BY asb.timemodified ASC")) {
2482 return;
2483 }
73097f07 2484
dd97c328 2485 $groupmode = groups_get_activity_groupmode($cm, $course);
2486 $cm_context = get_context_instance(CONTEXT_MODULE, $cm->id);
2487 $grader = has_capability('moodle/grade:viewall', $cm_context);
2488 $accessallgroups = has_capability('moodle/site:accessallgroups', $cm_context);
2489 $viewfullnames = has_capability('moodle/site:viewfullnames', $cm_context);
2490
2491 if (is_null($modinfo->groups)) {
2492 $modinfo->groups = groups_get_user_groups($course->id); // load all my groups and cache it in modinfo
2493 }
2494
2495 $show = array();
2496
2497 foreach($submissions as $submission) {
2498 if ($submission->userid == $USER->id) {
2499 $show[] = $submission;
2500 continue;
2501 }
2502
2503 // the act of sumitting of assignemnt may be considered private - only graders will see it if specified
2504 if (!empty($CFG->assignment_limitrecentsubmissions)) {
2505 if (!$grader) {
2506 continue;
2507 }
2508 }
73097f07 2509
dd97c328 2510 if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
2511 if (isguestuser()) {
2512 // shortcut - guest user does not belong into any group
2513 continue;
2514 }
2515
2516 // this will be slow - show only users that share group with me in this cm
2517 if (empty($modinfo->groups[$cm->id])) {
2518 continue;
2519 }
2520 $usersgroups = groups_get_all_groups($course->id, $cm->userid, $cm->groupingid);
2521 if (is_array($usersgroups)) {
2522 $usersgroups = array_keys($usersgroups);
2523 $interset = array_intersect($usersgroups, $modinfo->groups[$cm->id]);
2524 if (empty($intersect)) {
2525 continue;
2526 }
2527 }
2528 }
2529 $show[] = $submission;
2530 }
73097f07 2531
dd97c328 2532 if (empty($show)) {
2533 return;
2534 }
73097f07 2535
dd97c328 2536 if ($grader) {
2537 require_once($CFG->libdir.'/gradelib.php');
2538 $userids = array();
2539 foreach ($show as $id=>$submission) {
2540 $userids[] = $submission->userid;
73097f07 2541
dd97c328 2542 }
2543 $grades = grade_get_grades($courseid, 'mod', 'assignment', $cm->instance, $userids);
2544 }
73097f07 2545
dd97c328 2546 $aname = format_string($cm->name,true);
2547 foreach ($show as $submission) {
2548 $tmpactivity = new object();
73097f07 2549
dd97c328 2550 $tmpactivity->type = 'assignment';
2551 $tmpactivity->cmid = $cm->id;
2552 $tmpactivity->name = $aname;
76cbde41 2553 $tmpactivity->sectionnum = $cm->sectionnum;
dd97c328 2554 $tmpactivity->timestamp = $submission->timemodified;
73097f07 2555
dd97c328 2556 if ($grader) {
2557 $tmpactivity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
73097f07 2558 }
dd97c328 2559
2560 $tmpactivity->user->userid = $submission->userid;
2561 $tmpactivity->user->fullname = fullname($submission, $viewfullnames);
2562 $tmpactivity->user->picture = $submission->picture;
2563
2564 $activities[$index++] = $tmpactivity;
73097f07 2565 }
2566
2567 return;
2568}
2569
7af1e882 2570/**
2571 * Print recent activity from all assignments in a given course
2572 *
2573 * This is used by course/recent.php
2574 */
dd97c328 2575function assignment_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
73097f07 2576 global $CFG;
2577
dd97c328 2578 echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
73097f07 2579
141a922c 2580 echo "<tr><td class=\"userpicture\" valign=\"top\">";
dd97c328 2581 print_user_picture($activity->user->userid, $courseid, $activity->user->picture);
2582 echo "</td><td>";
73097f07 2583
2584 if ($detail) {
dd97c328 2585 $modname = $modnames[$activity->type];
2586 echo '<div class="title">';
2587 echo "<img src=\"$CFG->modpixpath/assignment/icon.gif\" ".
2588 "class=\"icon\" alt=\"$modname\">";
2589 echo "<a href=\"$CFG->wwwroot/mod/assignment/view.php?id={$activity->cmid}\">{$activity->name}</a>";
2590 echo '</div>';
73097f07 2591 }
2592
dd97c328 2593 if (isset($activity->grade)) {
2594 echo '<div class="grade">';
2595 echo get_string('grade').': ';
2596 echo $activity->grade;
2597 echo '</div>';
73097f07 2598 }
73097f07 2599
dd97c328 2600 echo '<div class="user">';
2601 echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->userid}&amp;course=$courseid\">"
2602 ."{$activity->user->fullname}</a> - ".userdate($activity->timestamp);
2603 echo '</div>';
73097f07 2604
dd97c328 2605 echo "</td></tr></table>";
73097f07 2606}
2607
2608/// GENERIC SQL FUNCTIONS
2609
7af1e882 2610/**
2611 * Fetch info from logs
2612 *
2613 * @param $log object with properties ->info (the assignment id) and ->userid
2614 * @return array with assignment name and user firstname and lastname
2615 */
73097f07 2616function assignment_log_info($log) {
2617 global $CFG;
2618 return get_record_sql("SELECT a.name, u.firstname, u.lastname
45fa3412 2619 FROM {$CFG->prefix}assignment a,
73097f07 2620 {$CFG->prefix}user u
45fa3412 2621 WHERE a.id = '$log->info'
73097f07 2622 AND u.id = '$log->userid'");
2623}
2624
7af1e882 2625/**
2626 * Return list of marked submissions that have not been mailed out for currently enrolled students
2627 *
2628 * @return array
2629 */
73097f07 2630function assignment_get_unmailed_submissions($starttime, $endtime) {
7af1e882 2631
73097f07 2632 global $CFG;
45fa3412 2633
73097f07 2634 return get_records_sql("SELECT s.*, a.course, a.name
45fa3412 2635 FROM {$CFG->prefix}assignment_submissions s,
4be6bced 2636 {$CFG->prefix}assignment a
45fa3412 2637 WHERE s.mailed = 0
2638 AND s.timemarked <= $endtime
ea8158c1 2639 AND s.timemarked >= $starttime
4be6bced 2640 AND s.assignment = a.id");
ea8158c1 2641
2642 /* return get_records_sql("SELECT s.*, a.course, a.name
45fa3412 2643 FROM {$CFG->prefix}assignment_submissions s,
73097f07 2644 {$CFG->prefix}assignment a,
2645 {$CFG->prefix}user_students us
45fa3412 2646 WHERE s.mailed = 0
2647 AND s.timemarked <= $endtime
73097f07 2648 AND s.timemarked >= $starttime
2649 AND s.assignment = a.id
2650 AND s.userid = us.userid
2651 AND a.course = us.course");
ea8158c1 2652 */
73097f07 2653}
2654
7af1e882 2655/**
2656 * Counts all real assignment submissions by ENROLLED students (not empty ones)
2657 *
2658 * There are also assignment type methods count_real_submissions() wich in the default
2659 * implementation simply call this function.
2660 * @param $groupid int optional If nonzero then count is restricted to this group
2661 * @return int The number of submissions
2662 */
dd97c328 2663function assignment_count_real_submissions($cm, $groupid=0) {
73097f07 2664 global $CFG;
2665
dd97c328 2666 $context = get_context_instance(CONTEXT_MODULE, $cm->id);
01194b77 2667
dd97c328 2668 // this is all the users with this capability set, in this context or higher
2669 if ($users = get_users_by_capability($context, 'mod/assignment:submit', 'u.id', '', '', '', $groupid, '', false)) {
2670 $users = array_keys($users);
2671 }
01194b77 2672
dd97c328 2673 // if groupmembersonly used, remove users who are not in any group
2674 if ($users and !empty($CFG->enablegroupings) and $cm->groupmembersonly) {
2675 if ($groupingusers = groups_get_grouping_members($cm->groupingid, 'u.id', 'u.id')) {
2676 $users = array_intersect($users, array_keys($groupingusers));
73097f07 2677 }
73097f07 2678 }
dd97c328 2679
2680 if (empty($users)) {
2681 return 0;
2682 }
2683
2684 $userlists = implode(',', $users);
2685
2686 return count_records_sql("SELECT COUNT('x')
2687 FROM {$CFG->prefix}assignment_submissions
2688 WHERE assignment = $cm->instance AND
2689 timemodified > 0 AND
2690 userid IN ($userlists)");
73097f07 2691}
2692
7af1e882 2693
2694/**
2695 * Return all assignment submissions by ENROLLED students (even empty)
2696 *
2697 * There are also assignment type methods get_submissions() wich in the default
2698 * implementation simply call this function.
2699 * @param $sort string optional field names for the ORDER BY in the sql query
2700 * @param $dir string optional specifying the sort direction, defaults to DESC
2701 * @return array The submission objects indexed by id
2702 */
73097f07 2703function assignment_get_all_submissions($assignment, $sort="", $dir="DESC") {
2704/// Return all assignment submissions by ENROLLED students (even empty)
2705 global $CFG;
2706
2707 if ($sort == "lastname" or $sort == "firstname") {
2708 $sort = "u.$sort $dir";
2709 } else if (empty($sort)) {
2710 $sort = "a.timemodified DESC";
2711 } else {
2712 $sort = "a.$sort $dir";
2713 }
2714
ea8158c1 2715 /* not sure this is needed at all since assignmenet already has a course define, so this join?
73097f07 2716 $select = "s.course = '$assignment->course' AND";
2717 if ($assignment->course == SITEID) {
2718 $select = '';
ea8158c1 2719 }*/
45fa3412 2720
2721 return get_records_sql("SELECT a.*
2722 FROM {$CFG->prefix}assignment_submissions a,
ea8158c1 2723 {$CFG->prefix}user u
2724 WHERE u.id = a.userid
45fa3412 2725 AND a.assignment = '$assignment->id'
ea8158c1 2726 ORDER BY $sort");
45fa3412 2727
2728 /* return get_records_sql("SELECT a.*
2729 FROM {$CFG->prefix}assignment_submissions a,
73097f07 2730 {$CFG->prefix}user_students s,
2731 {$CFG->prefix}user u
2732 WHERE a.userid = s.userid
2733 AND u.id = a.userid
45fa3412 2734 AND $select a.assignment = '$assignment->id'
73097f07 2735 ORDER BY $sort");
ea8158c1 2736 */
73097f07 2737}
2738
09ba8e56 2739/**
2740 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
2741 * for the course (see resource).
2742 *
206ab184 2743 * Given a course_module object, this function returns any "extra" information that may be needed
09ba8e56 2744 * when printing this activity in a course listing. See get_array_of_activities() in course/lib.php.
206ab184 2745 *
09ba8e56 2746 * @param $coursemodule object The coursemodule object (record).
2747 * @return object An object on information that the coures will know about (most noticeably, an icon).
206ab184 2748 *
09ba8e56 2749 */
2750function assignment_get_coursemodule_info($coursemodule) {
2751 global $CFG;
2752
1ea543df 2753 if (! $assignment = get_record('assignment', 'id', $coursemodule->instance, '', '', '', '', 'id, assignmenttype, name')) {
09ba8e56 2754 return false;
2755 }
2756
1ea543df 2757 $libfile = "$CFG->dirroot/mod/assignment/type/$assignment->assignmenttype/assignment.class.php";
09ba8e56 2758
f36cbf1d 2759 if (file_exists($libfile)) {
2760 require_once($libfile);
1ea543df 2761 $assignmentclass = "assignment_$assignment->assignmenttype";
f36cbf1d 2762 $ass = new $assignmentclass('staticonly');
1ea543df 2763 if ($result = $ass->get_coursemodule_info($coursemodule)) {
2764 return $result;
2765 } else {
2766 $info = new object();
2767 $info->name = $assignment->name;
2768 return $info;
2769 }
f36cbf1d 2770
2771 } else {
1ea543df 2772 debugging('Incorrect assignment type: '.$assignment->assignmenttype);
f36cbf1d 2773 return false;
2774 }
09ba8e56 2775}
73097f07 2776
2777
2778
2779/// OTHER GENERAL FUNCTIONS FOR ASSIGNMENTS ///////////////////////////////////////
2780
7af1e882 2781/**
2782 * Returns an array of installed assignment types indexed and sorted by name
2783 *
2784 * @return array The index is the name of the assignment type, the value its full name from the language strings
2785 */
b0f2597e 2786function assignment_types() {
2787 $types = array();
2788 $names = get_list_of_plugins('mod/assignment/type');
2789 foreach ($names as $name) {
2790 $types[$name] = get_string('type'.$name, 'assignment');
ffeca120 2791 }
b0f2597e 2792 asort($types);
2793 return $types;
f466c9ed 2794}
2795
7af1e882 2796/**
2797 * Executes upgrade scripts for assignment types when necessary
2798 */
b0f2597e 2799function assignment_upgrade_submodules() {
a86a538f 2800
e9d46b81 2801 global $CFG;
59c005b7 2802
e9d46b81 2803/// Install/upgrade assignment types (it uses, simply, the standard plugin architecture)
2804 upgrade_plugins('assignment_type', 'mod/assignment/type', "$CFG->wwwroot/$CFG->admin/index.php");
59c005b7 2805
59c005b7 2806}
2807
84fa8f5f 2808function assignment_print_overview($courses, &$htmlarray) {
afe35ec4 2809
84fa8f5f 2810 global $USER, $CFG;
2811
2812 if (empty($courses) || !is_array($courses) || count($courses) == 0) {
2813 return array();
2814 }
2815
2816 if (!$assignments = get_all_instances_in_courses('assignment',$courses)) {
2817 return;
2818 }
2819
2820 // Do assignment_base::isopen() here without loading the whole thing for speed
2821 foreach ($assignments as $key => $assignment) {
2822 $time = time();
d6da4a1a 2823 if ($assignment->timedue) {
2824 if ($assignment->preventlate) {
2825 $isopen = ($assignment->timeavailable <= $time && $time <= $assignment->timedue);
2826 } else {
2827 $isopen = ($assignment->timeavailable <= $time);
2828 }
84fa8f5f 2829 }
d6da4a1a 2830 if (empty($isopen) || empty($assignment->timedue)) {
84fa8f5f 2831 unset($assignments[$key]);
2832 }
2833 }
2834
2835 $strduedate = get_string('duedate', 'assignment');
8f643c81 2836 $strduedateno = get_string('duedateno', 'assignment');
84fa8f5f 2837 $strgraded = get_string('graded', 'assignment');
2838 $strnotgradedyet = get_string('notgradedyet', 'assignment');
2839 $strnotsubmittedyet = get_string('notsubmittedyet', 'assignment');
2840 $strsubmitted = get_string('submitted', 'assignment');
76a60031 2841 $strassignment = get_string('modulename', 'assignment');
c664a036 2842 $strreviewed = get_string('reviewed','assignment');
84fa8f5f 2843
2844 foreach ($assignments as $assignment) {
a2a37336 2845 $str = '<div class="assignment overview"><div class="name">'.$strassignment. ': '.
a7a74d77 2846 '<a '.($assignment->visible ? '':' class="dimmed"').
76a60031 2847 'title="'.$strassignment.'" href="'.$CFG->wwwroot.
a7a74d77 2848 '/mod/assignment/view.php?id='.$assignment->coursemodule.'">'.
5d45c04f 2849 $assignment->name.'</a></div>';
8f643c81 2850 if ($assignment->timedue) {
2851 $str .= '<div class="info">'.$strduedate.': '.userdate($assignment->timedue).'</div>';
2852 } else {
2853 $str .= '<div class="info">'.$strduedateno.'</div>';
2854 }
793a8c3a 2855 $context = get_context_instance(CONTEXT_MODULE, $assignment->coursemodule);
0468976c 2856 if (has_capability('mod/assignment:grade', $context)) {
45fa3412 2857
ea8158c1 2858 // count how many people can submit
2859 $submissions = 0; // init
7bddd4b7 2860 if ($students = get_users_by_capability($context, 'mod/assignment:submit', '', '', '', '', 0, '', false)) {
2861 foreach ($students as $student) {
2c3d5755 2862 if (record_exists_sql("SELECT id FROM {$CFG->prefix}assignment_submissions
2863 WHERE assignment = $assignment->id AND
afe35ec4 2864 userid = $student->id AND
2865 teacher = 0 AND
2866 timemarked = 0")) {
45fa3412 2867 $submissions++;
c2adcc90 2868 }
ea8158c1 2869 }
2870 }
45fa3412 2871
84fa8f5f 2872 if ($submissions) {
2873 $str .= get_string('submissionsnotgraded', 'assignment', $submissions);
2874 }
2875 } else {
2876 $sql = "SELECT *
2877 FROM {$CFG->prefix}assignment_submissions
b3d4840d 2878 WHERE userid = '$USER->id'
2879 AND assignment = '{$assignment->id}'";
84fa8f5f 2880 if ($submission = get_record_sql($sql)) {
2881 if ($submission->teacher == 0 && $submission->timemarked == 0) {
2882 $str .= $strsubmitted . ', ' . $strnotgradedyet;
c664a036 2883 } else if ($submission->grade <= 0) {
2884 $str .= $strsubmitted . ', ' . $strreviewed;
84fa8f5f 2885 } else {
2886 $str .= $strsubmitted . ', ' . $strgraded;
2887 }
2888 } else {
76a60031 2889 $str .= $strnotsubmittedyet . ' ' . assignment_display_lateness(time(), $assignment->timedue);
84fa8f5f 2890 }
2891 }
a7a74d77 2892 $str .= '</div>';
76a60031 2893 if (empty($htmlarray[$assignment->course]['assignment'])) {
2894 $htmlarray[$assignment->course]['assignment'] = $str;
2895 } else {
2896 $htmlarray[$assignment->course]['assignment'] .= $str;
2897 }
2898 }
2899}
2900
2901function assignment_display_lateness($timesubmitted, $timedue) {
2902 if (!$timedue) {
2903 return '';
2904 }
2905 $time = $timedue - $timesubmitted;
2906 if ($time < 0) {
2907 $timetext = get_string('late', 'assignment', format_time($time));
2908 return ' (<span class="late">'.$timetext.'</span>)';
2909 } else {
2910 $timetext = get_string('early', 'assignment', format_time($time));
2911 return ' (<span class="early">'.$timetext.'</span>)';
84fa8f5f 2912 }
2913}
2914
ac15a2d5 2915function assignment_get_view_actions() {
2916 return array('view');
2917}
2918
2919function assignment_get_post_actions() {
2920 return array('upload');
2921}
2922
89bfeee0 2923function assignment_get_types() {
0ac1cfc3 2924 global $CFG;
89bfeee0 2925 $types = array();
2926
2927 $type = new object();
2928 $type->modclass = MOD_CLASS_ACTIVITY;
2929 $type->type = "assignment_group_start";
2930 $type->typestr = '--'.get_string('modulenameplural', 'assignment');
2931 $types[] = $type;
2932
2933 $standardassignments = array('upload','online','uploadsingle','offline');
2934 foreach ($standardassignments as $assignmenttype) {
2935 $type = new object();
2936 $type->modclass = MOD_CLASS_ACTIVITY;
2937 $type->type = "assignment&amp;type=$assignmenttype";
2938 $type->typestr = get_string("type$assignmenttype", 'assignment');
2939 $types[] = $type;
2940 }
2941
2942 /// Drop-in extra assignment types
2943 $assignmenttypes = get_list_of_plugins('mod/assignment/type');
2944 foreach ($assignmenttypes as $assignmenttype) {
2945 if (!empty($CFG->{'assignment_hide_'.$assignmenttype})) { // Not wanted
2946 continue;
2947 }
2948 if (!in_array($assignmenttype, $standardassignments)) {
2949 $type = new object();
2950 $type->modclass = MOD_CLASS_ACTIVITY;
2951 $type->type = "assignment&amp;type=$assignmenttype";
2952 $type->typestr = get_string("type$assignmenttype", 'assignment');
2953 $types[] = $type;
2954 }
2955 }
2956
2957 $type = new object();
2958 $type->modclass = MOD_CLASS_ACTIVITY;
2959 $type->type = "assignment_group_end";
2960 $type->typestr = '--';
2961 $types[] = $type;
2962
2963 return $types;
2964}
2965
0b5a80a1 2966/**
2967 * Removes all grades from gradebook
2968 * @param int $courseid
2969 * @param string optional type
2970 */
2971function assignment_reset_gradebook($courseid, $type='') {
2972 global $CFG;
2973
2974 $type = $type ? "AND a.assignmenttype='$type'" : '';
2975
2976 $sql = "SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
2977 FROM {$CFG->prefix}assignment a, {$CFG->prefix}course_modules cm, {$CFG->prefix}modules m
2978 WHERE m.name='assignment' AND m.id=cm.module AND cm.instance=a.id AND a.course=$courseid $type";
2979
2980 if ($assignments = get_records_sql($sql)) {
2981 foreach ($assignments as $assignment) {
2982 assignment_grade_item_update($assignment, 'reset');
2983 }
2984 }
2985}
2986
2987/**
2988 * This function is used by the reset_course_userdata function in moodlelib.
2989 * This function will remove all posts from the specified assignment
2990 * and clean up any related data.
2991 * @param $data the data submitted from the reset course.
2992 * @return array status array
2993 */
2994function assignment_reset_userdata($data) {
2995 global $CFG;
2996
2997 $status = array();
2998
2999 foreach (get_list_of_plugins('mod/assignment/type') as $type) {
3000 require_once("$CFG->dirroot/mod/assignment/type/$type/assignment.class.php");
3001 $assignmentclass = "assignment_$type";
3002 $ass = new $assignmentclass();
3003 $status = array_merge($status, $ass->reset_userdata($data));
3004 }
3005
3006 return $status;
3007}
3008
3009/**
3010 * Implementation of the function for printing the form elements that control
3011 * whether the course reset functionality affects the assignment.
3012 * @param $mform form passed by reference
3013 */
3014function assignment_reset_course_form_definition(&$mform) {
3015 $mform->addElement('header', 'assignmentheader', get_string('modulenameplural', 'assignment'));
3016 $mform->addElement('advcheckbox', 'reset_assignment_submissions', get_string('deleteallsubmissions','assignment'));
3017}
3018
3019/**
3020 * Course reset form defaults.
3021 */
3022function assignment_reset_course_form_defaults($course) {
3023 return array('reset_assignment_submissions'=>1);
3024}
3025
76a60031 3026?>