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