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