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