Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * This file contains the moodle hooks for the assign module.
19
 *
20
 * It delegates most functions to the assignment class.
21
 *
22
 * @package   mod_assign
23
 * @copyright 2012 NetSpot {@link http://www.netspot.com.au}
24
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
25
 */
26
defined('MOODLE_INTERNAL') || die();
27
 
28
/**
29
 * Adds an assignment instance
30
 *
31
 * This is done by calling the add_instance() method of the assignment type class
32
 * @param stdClass $data
33
 * @param mod_assign_mod_form $form
34
 * @return int The instance id of the new assignment
35
 */
1441 ariadna 36
function assign_add_instance(stdClass $data, ?mod_assign_mod_form $form = null) {
1 efrain 37
    global $CFG;
38
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
39
 
40
    $assignment = new assign(context_module::instance($data->coursemodule), null, null);
41
    return $assignment->add_instance($data, true);
42
}
43
 
44
/**
45
 * delete an assignment instance
46
 * @param int $id
47
 * @return bool
48
 */
49
function assign_delete_instance($id) {
50
    global $CFG;
51
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
52
    $cm = get_coursemodule_from_instance('assign', $id, 0, false, MUST_EXIST);
53
    $context = context_module::instance($cm->id);
54
 
55
    $assignment = new assign($context, null, null);
56
    return $assignment->delete_instance();
57
}
58
 
59
/**
60
 * This function is used by the reset_course_userdata function in moodlelib.
61
 * This function will remove all assignment submissions and feedbacks in the database
62
 * and clean up any related data.
63
 *
64
 * @param stdClass $data the data submitted from the reset course.
65
 * @return array
66
 */
67
function assign_reset_userdata($data) {
68
    global $CFG, $DB;
69
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
70
 
1441 ariadna 71
    $status = [];
72
    $params = ['courseid' => $data->courseid];
1 efrain 73
    $sql = "SELECT a.id FROM {assign} a WHERE a.course=:courseid";
1441 ariadna 74
    $course = $DB->get_record('course', ['id' => $data->courseid], '*', MUST_EXIST);
1 efrain 75
    if ($assigns = $DB->get_records_sql($sql, $params)) {
76
        foreach ($assigns as $assign) {
1441 ariadna 77
            $cm = get_coursemodule_from_instance(
78
                'assign',
79
                $assign->id,
80
                $data->courseid,
81
                false,
82
                MUST_EXIST,
83
            );
1 efrain 84
            $context = context_module::instance($cm->id);
85
            $assignment = new assign($context, $cm, $course);
86
            $status = array_merge($status, $assignment->reset_userdata($data));
87
        }
88
    }
1441 ariadna 89
 
1 efrain 90
    return $status;
91
}
92
 
93
/**
94
 * This standard function will check all instances of this module
95
 * and make sure there are up-to-date events created for each of them.
96
 * If courseid = 0, then every assignment event in the site is checked, else
97
 * only assignment events belonging to the course specified are checked.
98
 *
99
 * @param int $courseid
100
 * @param int|stdClass $instance Assign module instance or ID.
101
 * @param int|stdClass $cm Course module object or ID (not used in this module).
102
 * @return bool
103
 */
104
function assign_refresh_events($courseid = 0, $instance = null, $cm = null) {
105
    global $CFG, $DB;
106
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
107
 
108
    // If we have instance information then we can just update the one event instead of updating all events.
109
    if (isset($instance)) {
110
        if (!is_object($instance)) {
111
            $instance = $DB->get_record('assign', array('id' => $instance), '*', MUST_EXIST);
112
        }
113
        if (isset($cm)) {
114
            if (!is_object($cm)) {
115
                assign_prepare_update_events($instance);
116
                return true;
117
            } else {
118
                $course = get_course($instance->course);
119
                assign_prepare_update_events($instance, $course, $cm);
120
                return true;
121
            }
122
        }
123
    }
124
 
125
    if ($courseid) {
126
        // Make sure that the course id is numeric.
127
        if (!is_numeric($courseid)) {
128
            return false;
129
        }
130
        if (!$assigns = $DB->get_records('assign', array('course' => $courseid))) {
131
            return false;
132
        }
133
        // Get course from courseid parameter.
134
        if (!$course = $DB->get_record('course', array('id' => $courseid), '*')) {
135
            return false;
136
        }
137
    } else {
138
        if (!$assigns = $DB->get_records('assign')) {
139
            return false;
140
        }
141
    }
142
    foreach ($assigns as $assign) {
143
        assign_prepare_update_events($assign);
144
    }
145
 
146
    return true;
147
}
148
 
149
/**
150
 * This actually updates the normal and completion calendar events.
151
 *
152
 * @param  stdClass $assign Assignment object (from DB).
153
 * @param  stdClass $course Course object.
154
 * @param  stdClass $cm Course module object.
155
 */
156
function assign_prepare_update_events($assign, $course = null, $cm = null) {
157
    global $DB;
158
    if (!isset($course)) {
159
        // Get course and course module for the assignment.
160
        list($course, $cm) = get_course_and_cm_from_instance($assign->id, 'assign', $assign->course);
161
    }
162
    // Refresh the assignment's calendar events.
163
    $context = context_module::instance($cm->id);
164
    $assignment = new assign($context, $cm, $course);
165
    $assignment->update_calendar($cm->id);
166
    // Refresh the calendar events also for the assignment overrides.
167
    $overrides = $DB->get_records('assign_overrides', ['assignid' => $assign->id], '',
168
                                  'id, groupid, userid, duedate, sortorder, timelimit');
169
    foreach ($overrides as $override) {
170
        if (empty($override->userid)) {
171
            unset($override->userid);
172
        }
173
        if (empty($override->groupid)) {
174
            unset($override->groupid);
175
        }
176
        assign_update_events($assignment, $override);
177
    }
178
}
179
 
180
/**
181
 * Removes all grades from gradebook
182
 *
183
 * @param int $courseid The ID of the course to reset
184
 * @param string $type Optional type of assignment to limit the reset to a particular assignment type
185
 */
186
function assign_reset_gradebook($courseid, $type='') {
187
    global $CFG, $DB;
188
 
189
    $params = array('moduletype'=>'assign', 'courseid'=>$courseid);
190
    $sql = 'SELECT a.*, cm.idnumber as cmidnumber, a.course as courseid
191
            FROM {assign} a, {course_modules} cm, {modules} m
192
            WHERE m.name=:moduletype AND m.id=cm.module AND cm.instance=a.id AND a.course=:courseid';
193
 
194
    if ($assignments = $DB->get_records_sql($sql, $params)) {
195
        foreach ($assignments as $assignment) {
196
            assign_grade_item_update($assignment, 'reset');
197
        }
198
    }
199
}
200
 
201
/**
202
 * Implementation of the function for printing the form elements that control
203
 * whether the course reset functionality affects the assignment.
204
 * @param MoodleQuickForm $mform form passed by reference
205
 */
206
function assign_reset_course_form_definition(&$mform) {
207
    $mform->addElement('header', 'assignheader', get_string('modulenameplural', 'assign'));
1441 ariadna 208
    $mform->addElement('static', 'assigndelete', get_string('delete'));
1 efrain 209
    $name = get_string('deleteallsubmissions', 'assign');
210
    $mform->addElement('advcheckbox', 'reset_assign_submissions', $name);
211
    $mform->addElement('advcheckbox', 'reset_assign_user_overrides',
212
        get_string('removealluseroverrides', 'assign'));
213
    $mform->addElement('advcheckbox', 'reset_assign_group_overrides',
214
        get_string('removeallgroupoverrides', 'assign'));
215
}
216
 
217
/**
218
 * Course reset form defaults.
219
 * @param  object $course
220
 * @return array
221
 */
222
function assign_reset_course_form_defaults($course) {
223
    return array('reset_assign_submissions' => 1,
224
            'reset_assign_group_overrides' => 1,
225
            'reset_assign_user_overrides' => 1);
226
}
227
 
228
/**
229
 * Update an assignment instance
230
 *
231
 * This is done by calling the update_instance() method of the assignment type class
232
 * @param stdClass $data
233
 * @param stdClass $form - unused
234
 * @return object
235
 */
236
function assign_update_instance(stdClass $data, $form) {
237
    global $CFG;
238
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
239
    $context = context_module::instance($data->coursemodule);
240
    $assignment = new assign($context, null, null);
241
    return $assignment->update_instance($data);
242
}
243
 
244
/**
245
 * This function updates the events associated to the assign.
246
 * If $override is non-zero, then it updates only the events
247
 * associated with the specified override.
248
 *
249
 * @param assign $assign the assign object.
250
 * @param object $override (optional) limit to a specific override
251
 */
252
function assign_update_events($assign, $override = null) {
253
    global $CFG, $DB;
254
 
255
    require_once($CFG->dirroot . '/calendar/lib.php');
256
 
257
    $assigninstance = $assign->get_instance();
258
 
259
    // Load the old events relating to this assign.
260
    $conds = array('modulename' => 'assign', 'instance' => $assigninstance->id);
261
    if (!empty($override)) {
262
        // Only load events for this override.
263
        if (isset($override->userid)) {
264
            $conds['userid'] = $override->userid;
265
        } else if (isset($override->groupid)) {
266
            $conds['groupid'] = $override->groupid;
267
        } else {
268
            // This is not a valid override, it may have been left from a bad import or restore.
269
            $conds['groupid'] = $conds['userid'] = 0;
270
        }
271
    }
272
    $oldevents = $DB->get_records('event', $conds, 'id ASC');
273
 
274
    // Now make a to-do list of all that needs to be updated.
275
    if (empty($override)) {
276
        // We are updating the primary settings for the assignment, so we need to add all the overrides.
277
        $overrides = $DB->get_records('assign_overrides', array('assignid' => $assigninstance->id), 'id ASC');
278
        // It is necessary to add an empty stdClass to the beginning of the array as the $oldevents
279
        // list contains the original (non-override) event for the module. If this is not included
280
        // the logic below will end up updating the wrong row when we try to reconcile this $overrides
281
        // list against the $oldevents list.
282
        array_unshift($overrides, new stdClass());
283
    } else {
284
        // Just do the one override.
285
        $overrides = array($override);
286
    }
287
 
288
    if (!empty($assign->get_course_module())) {
289
        $cmid = $assign->get_course_module()->id;
290
    } else {
291
        $cmid = get_coursemodule_from_instance('assign', $assigninstance->id, $assigninstance->course)->id;
292
    }
293
 
294
    foreach ($overrides as $current) {
295
        $groupid   = isset($current->groupid) ? $current->groupid : 0;
296
        $userid    = isset($current->userid) ? $current->userid : 0;
297
        $duedate = isset($current->duedate) ? $current->duedate : $assigninstance->duedate;
298
        $timelimit = isset($current->timelimit) ? $current->timelimit : 0;
299
 
300
        // Only add 'due' events for an override if they differ from the assign default.
301
        $addclose = empty($current->id) || !empty($current->duedate);
302
 
303
        $event = new stdClass();
304
        $event->type = CALENDAR_EVENT_TYPE_ACTION;
305
        $event->description = format_module_intro('assign', $assigninstance, $cmid, false);
306
        $event->format = FORMAT_HTML;
307
        // Events module won't show user events when the courseid is nonzero.
308
        $event->courseid    = ($userid) ? 0 : $assigninstance->course;
309
        $event->groupid     = $groupid;
310
        $event->userid      = $userid;
311
        $event->modulename  = 'assign';
312
        $event->instance    = $assigninstance->id;
313
        $event->timestart   = $duedate;
314
        $event->timeduration = $timelimit;
315
        $event->timesort    = $event->timestart + $event->timeduration;
316
        $event->visible     = instance_is_visible('assign', $assigninstance);
317
        $event->eventtype   = ASSIGN_EVENT_TYPE_DUE;
318
        $event->priority    = null;
319
 
320
        // Determine the event name and priority.
321
        if ($groupid) {
322
            // Group override event.
323
            $params = new stdClass();
324
            $params->assign = $assigninstance->name;
325
            $params->group = groups_get_group_name($groupid);
326
            if ($params->group === false) {
327
                // Group doesn't exist, just skip it.
328
                continue;
329
            }
330
            $eventname = get_string('overridegroupeventname', 'assign', $params);
331
            // Set group override priority.
332
            if (isset($current->sortorder)) {
333
                $event->priority = $current->sortorder;
334
            }
335
        } else if ($userid) {
336
            // User override event.
337
            $params = new stdClass();
338
            $params->assign = $assigninstance->name;
339
            $eventname = get_string('overrideusereventname', 'assign', $params);
340
            // Set user override priority.
341
            $event->priority = CALENDAR_EVENT_USER_OVERRIDE_PRIORITY;
342
        } else {
343
            // The parent event.
344
            $eventname = $assigninstance->name;
345
        }
346
 
347
        if ($duedate && $addclose) {
348
            if ($oldevent = array_shift($oldevents)) {
349
                $event->id = $oldevent->id;
350
            } else {
351
                unset($event->id);
352
            }
353
            $event->name      = $eventname.' ('.get_string('duedate', 'assign').')';
354
            calendar_event::create($event, false);
355
        }
356
    }
357
 
358
    // Delete any leftover events.
359
    foreach ($oldevents as $badevent) {
360
        $badevent = calendar_event::load($badevent);
361
        $badevent->delete();
362
    }
363
}
364
 
365
/**
366
 * Return the list if Moodle features this module supports
367
 *
368
 * @param string $feature FEATURE_xx constant for requested feature
369
 * @return mixed True if module supports feature, false if not, null if doesn't know or string for the module purpose.
370
 */
371
function assign_supports($feature) {
372
    switch($feature) {
373
        case FEATURE_GROUPS:
374
            return true;
375
        case FEATURE_GROUPINGS:
376
            return true;
377
        case FEATURE_MOD_INTRO:
378
            return true;
379
        case FEATURE_COMPLETION_TRACKS_VIEWS:
380
            return true;
381
        case FEATURE_COMPLETION_HAS_RULES:
382
            return true;
383
        case FEATURE_GRADE_HAS_GRADE:
384
            return true;
1441 ariadna 385
        case FEATURE_GRADE_HAS_PENALTY:
386
            return true;
1 efrain 387
        case FEATURE_GRADE_OUTCOMES:
388
            return true;
389
        case FEATURE_BACKUP_MOODLE2:
390
            return true;
391
        case FEATURE_SHOW_DESCRIPTION:
392
            return true;
393
        case FEATURE_ADVANCED_GRADING:
394
            return true;
395
        case FEATURE_PLAGIARISM:
396
            return true;
397
        case FEATURE_COMMENT:
398
            return true;
399
        case FEATURE_MOD_PURPOSE:
400
            return MOD_PURPOSE_ASSESSMENT;
401
 
402
        default:
403
            return null;
404
    }
405
}
406
 
407
/**
408
 * extend an assigment navigation settings
409
 *
410
 * @param settings_navigation $settings
411
 * @param navigation_node $navref
412
 * @return void
413
 */
414
function assign_extend_settings_navigation(settings_navigation $settings, navigation_node $navref) {
1441 ariadna 415
    global $DB, $CFG;
1 efrain 416
 
1441 ariadna 417
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
418
 
1 efrain 419
    // We want to add these new nodes after the Edit settings node, and before the
420
    // Locally assigned roles node. Of course, both of those are controlled by capabilities.
421
    $keys = $navref->get_children_key_list();
422
    $beforekey = null;
423
    $i = array_search('modedit', $keys);
424
    if ($i === false and array_key_exists(0, $keys)) {
425
        $beforekey = $keys[0];
426
    } else if (array_key_exists($i + 1, $keys)) {
427
        $beforekey = $keys[$i + 1];
428
    }
429
 
430
    $cm = $settings->get_page()->cm;
431
    if (!$cm) {
432
        return;
433
    }
434
 
435
    $context = $cm->context;
436
    $course = $settings->get_page()->course;
437
 
438
    if (!$course) {
439
        return;
440
    }
441
 
442
    if (has_capability('mod/assign:manageoverrides', $settings->get_page()->cm->context)) {
443
        $url = new moodle_url('/mod/assign/overrides.php', ['cmid' => $settings->get_page()->cm->id, 'mode' => 'user']);
444
 
445
        $node = navigation_node::create(get_string('overrides', 'assign'),
446
            $url,
447
            navigation_node::TYPE_SETTING, null, 'mod_assign_useroverrides');
448
        $navref->add_node($node, $beforekey);
449
    }
450
 
451
    if (has_capability('mod/assign:revealidentities', $context)) {
452
        $dbparams = array('id'=>$cm->instance);
453
        $assignment = $DB->get_record('assign', $dbparams, 'blindmarking, revealidentities');
454
 
455
        if ($assignment && $assignment->blindmarking && !$assignment->revealidentities) {
456
            $urlparams = array('id' => $cm->id, 'action'=>'revealidentities');
457
            $url = new moodle_url('/mod/assign/view.php', $urlparams);
458
            $linkname = get_string('revealidentities', 'assign');
459
            $node = $navref->add($linkname, $url, navigation_node::TYPE_SETTING);
460
        }
461
    }
1441 ariadna 462
 
463
    $assign = new assign($context, null, null);
464
    // If the current user can view grades, include the 'Submissions' navigation node.
465
    if ($assign->can_view_grades()) {
466
        $url = new moodle_url('/mod/assign/view.php', ['id' => $settings->get_page()->cm->id, 'action' => 'grading']);
467
        $navref->add(
468
            text: get_string('gradeitem:submissions', 'assign'),
469
            action: $url,
470
            type: navigation_node::TYPE_SETTING,
471
            key: 'mod_assign_submissions'
472
        );
473
    }
474
 
475
    // Allow changing grade penalty settings at course module level, on assignment module.
476
    // Other modules can choose to allow this change or not.
477
    if (\mod_assign\penalty\helper::is_penalty_enabled($cm->instance)) {
478
        \core_grades\penalty_manager::extend_navigation_module($settings, $navref);
479
    }
1 efrain 480
}
481
 
482
/**
483
 * Add a get_coursemodule_info function in case any assignment type wants to add 'extra' information
484
 * for the course (see resource).
485
 *
486
 * Given a course_module object, this function returns any "extra" information that may be needed
487
 * when printing this activity in a course listing.  See get_array_of_activities() in course/lib.php.
488
 *
489
 * @param stdClass $coursemodule The coursemodule object (record).
490
 * @return cached_cm_info An object on information that the courses
491
 *                        will know about (most noticeably, an icon).
492
 */
493
function assign_get_coursemodule_info($coursemodule) {
494
    global $DB;
495
 
496
    $dbparams = array('id'=>$coursemodule->instance);
497
    $fields = 'id, name, alwaysshowdescription, allowsubmissionsfromdate, intro, introformat, completionsubmit,
498
        duedate, cutoffdate, allowsubmissionsfromdate';
499
    if (! $assignment = $DB->get_record('assign', $dbparams, $fields)) {
500
        return false;
501
    }
502
 
503
    $result = new cached_cm_info();
504
    $result->name = $assignment->name;
505
    if ($coursemodule->showdescription) {
506
        if ($assignment->alwaysshowdescription || time() > $assignment->allowsubmissionsfromdate) {
507
            // Convert intro to html. Do not filter cached version, filters run at display time.
508
            $result->content = format_module_intro('assign', $assignment, $coursemodule->id, false);
509
        }
510
    }
511
 
512
    // Populate the custom completion rules as key => value pairs, but only if the completion mode is 'automatic'.
513
    if ($coursemodule->completion == COMPLETION_TRACKING_AUTOMATIC) {
514
        $result->customdata['customcompletionrules']['completionsubmit'] = $assignment->completionsubmit;
515
    }
516
 
517
    // Populate some other values that can be used in calendar or on dashboard.
518
    if ($assignment->duedate) {
519
        $result->customdata['duedate'] = $assignment->duedate;
520
    }
521
    if ($assignment->cutoffdate) {
522
        $result->customdata['cutoffdate'] = $assignment->cutoffdate;
523
    }
524
    if ($assignment->allowsubmissionsfromdate) {
525
        $result->customdata['allowsubmissionsfromdate'] = $assignment->allowsubmissionsfromdate;
526
    }
527
 
528
    return $result;
529
}
530
 
531
/**
532
 * Sets dynamic information about a course module
533
 *
534
 * This function is called from cm_info when displaying the module
535
 *
536
 * @param cm_info $cm
537
 */
538
function mod_assign_cm_info_dynamic(cm_info $cm) {
539
    global $USER;
540
 
541
    $cache = cache::make('mod_assign', 'overrides');
542
    $override = $cache->get("{$cm->instance}_u_{$USER->id}");
543
 
544
    if (!$override) {
545
        $override = (object) [
546
            'allowsubmissionsfromdate' => null,
547
            'duedate' => null,
548
            'cutoffdate' => null,
549
        ];
550
    }
551
 
552
    // No need to look for group overrides if there are user overrides for all allowsubmissionsfromdate, duedate and cutoffdate.
553
    if (is_null($override->allowsubmissionsfromdate) || is_null($override->duedate) || is_null($override->cutoffdate)) {
554
        $selectedgroupoverride = (object) [
555
            'allowsubmissionsfromdate' => null,
556
            'duedate' => null,
557
            'cutoffdate' => null,
558
            'sortorder' => PHP_INT_MAX, // So that every sortorder read from DB is less than this.
559
        ];
560
        $groupings = groups_get_user_groups($cm->course, $USER->id);
561
        foreach ($groupings[0] as $groupid) {
562
            $groupoverride = $cache->get("{$cm->instance}_g_{$groupid}");
563
            if ($groupoverride) {
564
                if ($groupoverride->sortorder < $selectedgroupoverride->sortorder) {
565
                    $selectedgroupoverride = $groupoverride;
566
                }
567
            }
568
        }
569
        // If there is a user override for a setting, ignore the group override.
570
        if (is_null($override->allowsubmissionsfromdate)) {
571
            $override->allowsubmissionsfromdate = $selectedgroupoverride->allowsubmissionsfromdate;
572
        }
573
        if (is_null($override->duedate)) {
574
            $override->duedate = $selectedgroupoverride->duedate;
575
        }
576
        if (is_null($override->cutoffdate)) {
577
            $override->cutoffdate = $selectedgroupoverride->cutoffdate;
578
        }
579
    }
580
 
581
    // Calculate relative dates. The assignment module calculates relative date only for duedate.
582
    // A user or group override always has higher priority over any relative date calculation.
583
    if (empty($override->duedate) && !empty($cm->customdata['duedate'])) {
584
        $course = get_course($cm->course);
585
        $usercoursedates = course_get_course_dates_for_user_id($course, $USER->id);
586
        if ($usercoursedates['start']) {
587
            $override->duedate = $cm->customdata['duedate'] + $usercoursedates['startoffset'];
588
        }
589
    }
590
 
591
    // Populate some other values that can be used in calendar or on dashboard.
592
    if (!is_null($override->allowsubmissionsfromdate)) {
593
        $cm->override_customdata('allowsubmissionsfromdate', $override->allowsubmissionsfromdate);
594
    }
595
    if (!is_null($override->duedate)) {
596
        $cm->override_customdata('duedate', $override->duedate);
597
    }
598
    if (!is_null($override->cutoffdate)) {
599
        $cm->override_customdata('cutoffdate', $override->cutoffdate);
600
    }
601
}
602
 
603
/**
604
 * Callback which returns human-readable strings describing the active completion custom rules for the module instance.
605
 *
606
 * @param cm_info|stdClass $cm object with fields ->completion and ->customdata['customcompletionrules']
607
 * @return array $descriptions the array of descriptions for the custom rules.
608
 */
609
function mod_assign_get_completion_active_rule_descriptions($cm) {
610
    // Values will be present in cm_info, and we assume these are up to date.
611
    if (empty($cm->customdata['customcompletionrules'])
612
        || $cm->completion != COMPLETION_TRACKING_AUTOMATIC) {
613
        return [];
614
    }
615
 
616
    $descriptions = [];
617
    foreach ($cm->customdata['customcompletionrules'] as $key => $val) {
618
        switch ($key) {
619
            case 'completionsubmit':
620
                if (!empty($val)) {
621
                    $descriptions[] = get_string('completionsubmit', 'assign');
622
                }
623
                break;
624
            default:
625
                break;
626
        }
627
    }
628
    return $descriptions;
629
}
630
 
631
/**
632
 * Return a list of page types
633
 * @param string $pagetype current page type
634
 * @param stdClass $parentcontext Block's parent context
635
 * @param stdClass $currentcontext Current context of block
636
 */
637
function assign_page_type_list($pagetype, $parentcontext, $currentcontext) {
638
    $modulepagetype = array(
639
        'mod-assign-*' => get_string('page-mod-assign-x', 'assign'),
640
        'mod-assign-view' => get_string('page-mod-assign-view', 'assign'),
641
    );
642
    return $modulepagetype;
643
}
644
 
645
/**
646
 * Print recent activity from all assignments in a given course
647
 *
648
 * This is used by the recent activity block
649
 * @param mixed $course the course to print activity for
650
 * @param bool $viewfullnames boolean to determine whether to show full names or not
651
 * @param int $timestart the time the rendering started
652
 * @return bool true if activity was printed, false otherwise.
653
 */
654
function assign_print_recent_activity($course, $viewfullnames, $timestart) {
655
    global $CFG, $USER, $DB, $OUTPUT;
656
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
657
 
658
    // Do not use log table if possible, it may be huge.
659
 
660
    $dbparams = array($timestart, $course->id, 'assign', ASSIGN_SUBMISSION_STATUS_SUBMITTED);
661
    $userfieldsapi = \core_user\fields::for_userpic();
662
    $namefields = $userfieldsapi->get_sql('u', false, '', 'userid', false)->selects;;
663
    if (!$submissions = $DB->get_records_sql("SELECT asb.id, asb.timemodified, cm.id AS cmid, um.id as recordid,
664
                                                     $namefields
665
                                                FROM {assign_submission} asb
666
                                                     JOIN {assign} a      ON a.id = asb.assignment
667
                                                     JOIN {course_modules} cm ON cm.instance = a.id
668
                                                     JOIN {modules} md        ON md.id = cm.module
669
                                                     JOIN {user} u            ON u.id = asb.userid
670
                                                LEFT JOIN {assign_user_mapping} um ON um.userid = u.id AND um.assignment = a.id
671
                                               WHERE asb.timemodified > ? AND
672
                                                     asb.latest = 1 AND
673
                                                     a.course = ? AND
674
                                                     md.name = ? AND
675
                                                     asb.status = ?
676
                                            ORDER BY asb.timemodified ASC", $dbparams)) {
677
         return false;
678
    }
679
 
680
    $modinfo = get_fast_modinfo($course);
681
    $show    = array();
682
    $grader  = array();
683
 
684
    $showrecentsubmissions = get_config('assign', 'showrecentsubmissions');
685
 
686
    foreach ($submissions as $submission) {
687
        if (!array_key_exists($submission->cmid, $modinfo->get_cms())) {
688
            continue;
689
        }
690
        $cm = $modinfo->get_cm($submission->cmid);
691
        if (!$cm->uservisible) {
692
            continue;
693
        }
694
        if ($submission->userid == $USER->id) {
695
            $show[] = $submission;
696
            continue;
697
        }
698
 
699
        $context = context_module::instance($submission->cmid);
700
        // The act of submitting of assignment may be considered private -
701
        // only graders will see it if specified.
702
        if (empty($showrecentsubmissions)) {
703
            if (!array_key_exists($cm->id, $grader)) {
704
                $grader[$cm->id] = has_capability('moodle/grade:viewall', $context);
705
            }
706
            if (!$grader[$cm->id]) {
707
                continue;
708
            }
709
        }
710
 
711
        $groupmode = groups_get_activity_groupmode($cm, $course);
712
 
713
        if ($groupmode == SEPARATEGROUPS &&
714
                !has_capability('moodle/site:accessallgroups',  $context)) {
715
            if (isguestuser()) {
716
                // Shortcut - guest user does not belong into any group.
717
                continue;
718
            }
719
 
720
            // This will be slow - show only users that share group with me in this cm.
721
            if (!$modinfo->get_groups($cm->groupingid)) {
722
                continue;
723
            }
724
            $usersgroups =  groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
725
            if (is_array($usersgroups)) {
726
                $usersgroups = array_keys($usersgroups);
727
                $intersect = array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid));
728
                if (empty($intersect)) {
729
                    continue;
730
                }
731
            }
732
        }
733
        $show[] = $submission;
734
    }
735
 
736
    if (empty($show)) {
737
        return false;
738
    }
739
 
740
    echo $OUTPUT->heading(get_string('newsubmissions', 'assign') . ':', 6);
741
 
742
    foreach ($show as $submission) {
743
        $cm = $modinfo->get_cm($submission->cmid);
744
        $context = context_module::instance($submission->cmid);
745
        $assign = new assign($context, $cm, $cm->course);
746
        $link = $CFG->wwwroot.'/mod/assign/view.php?id='.$cm->id;
747
        // Obscure first and last name if blind marking enabled.
748
        if ($assign->is_blind_marking()) {
749
            $submission->firstname = get_string('participant', 'mod_assign');
750
            if (empty($submission->recordid)) {
751
                $submission->recordid = $assign->get_uniqueid_for_user($submission->userid);
752
            }
753
            $submission->lastname = $submission->recordid;
754
        }
755
        print_recent_activity_note($submission->timemodified,
756
                                   $submission,
757
                                   $cm->name,
758
                                   $link,
759
                                   false,
760
                                   $viewfullnames);
761
    }
762
 
763
    return true;
764
}
765
 
766
/**
767
 * Returns all assignments since a given time.
768
 *
769
 * @param array $activities The activity information is returned in this array
770
 * @param int $index The current index in the activities array
771
 * @param int $timestart The earliest activity to show
772
 * @param int $courseid Limit the search to this course
773
 * @param int $cmid The course module id
774
 * @param int $userid Optional user id
775
 * @param int $groupid Optional group id
776
 * @return void
777
 */
778
function assign_get_recent_mod_activity(&$activities,
779
                                        &$index,
780
                                        $timestart,
781
                                        $courseid,
782
                                        $cmid,
783
                                        $userid=0,
784
                                        $groupid=0) {
785
    global $CFG, $COURSE, $USER, $DB;
786
 
787
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
788
 
789
    if ($COURSE->id == $courseid) {
790
        $course = $COURSE;
791
    } else {
792
        $course = $DB->get_record('course', array('id'=>$courseid));
793
    }
794
 
795
    $modinfo = get_fast_modinfo($course);
796
 
797
    $cm = $modinfo->get_cm($cmid);
798
    $params = array();
799
    if ($userid) {
800
        $userselect = 'AND u.id = :userid';
801
        $params['userid'] = $userid;
802
    } else {
803
        $userselect = '';
804
    }
805
 
806
    if ($groupid) {
807
        $groupselect = 'AND gm.groupid = :groupid';
808
        $groupjoin   = 'JOIN {groups_members} gm ON  gm.userid=u.id';
809
        $params['groupid'] = $groupid;
810
    } else {
811
        $groupselect = '';
812
        $groupjoin   = '';
813
    }
814
 
815
    $params['cminstance'] = $cm->instance;
816
    $params['timestart'] = $timestart;
817
    $params['submitted'] = ASSIGN_SUBMISSION_STATUS_SUBMITTED;
818
 
819
    $userfieldsapi = \core_user\fields::for_userpic();
820
    $userfields = $userfieldsapi->get_sql('u', false, '', 'userid', false)->selects;
821
 
822
    if (!$submissions = $DB->get_records_sql('SELECT asb.id, asb.timemodified, ' .
823
                                                     $userfields .
824
                                             '  FROM {assign_submission} asb
825
                                                JOIN {assign} a ON a.id = asb.assignment
826
                                                JOIN {user} u ON u.id = asb.userid ' .
827
                                          $groupjoin .
828
                                            '  WHERE asb.timemodified > :timestart AND
829
                                                     asb.status = :submitted AND
830
                                                     a.id = :cminstance
831
                                                     ' . $userselect . ' ' . $groupselect .
832
                                            ' ORDER BY asb.timemodified ASC', $params)) {
833
         return;
834
    }
835
 
836
    $groupmode       = groups_get_activity_groupmode($cm, $course);
837
    $cmcontext      = context_module::instance($cm->id);
838
    $grader          = has_capability('moodle/grade:viewall', $cmcontext);
839
    $accessallgroups = has_capability('moodle/site:accessallgroups', $cmcontext);
840
    $viewfullnames   = has_capability('moodle/site:viewfullnames', $cmcontext);
841
 
842
 
843
    $showrecentsubmissions = get_config('assign', 'showrecentsubmissions');
844
    $show = array();
845
    foreach ($submissions as $submission) {
846
        if ($submission->userid == $USER->id) {
847
            $show[] = $submission;
848
            continue;
849
        }
850
        // The act of submitting of assignment may be considered private -
851
        // only graders will see it if specified.
852
        if (empty($showrecentsubmissions)) {
853
            if (!$grader) {
854
                continue;
855
            }
856
        }
857
 
858
        if ($groupmode == SEPARATEGROUPS and !$accessallgroups) {
859
            if (isguestuser()) {
860
                // Shortcut - guest user does not belong into any group.
861
                continue;
862
            }
863
 
864
            // This will be slow - show only users that share group with me in this cm.
865
            if (!$modinfo->get_groups($cm->groupingid)) {
866
                continue;
867
            }
868
            $usersgroups =  groups_get_all_groups($course->id, $submission->userid, $cm->groupingid);
869
            if (is_array($usersgroups)) {
870
                $usersgroups = array_keys($usersgroups);
871
                $intersect = array_intersect($usersgroups, $modinfo->get_groups($cm->groupingid));
872
                if (empty($intersect)) {
873
                    continue;
874
                }
875
            }
876
        }
877
        $show[] = $submission;
878
    }
879
 
880
    if (empty($show)) {
881
        return;
882
    }
883
 
884
    if ($grader) {
885
        require_once($CFG->libdir.'/gradelib.php');
886
        $userids = array();
887
        foreach ($show as $id => $submission) {
888
            $userids[] = $submission->userid;
889
        }
890
        $grades = grade_get_grades($courseid, 'mod', 'assign', $cm->instance, $userids);
891
    }
892
 
893
    $aname = format_string($cm->name, true);
894
    foreach ($show as $submission) {
895
        $activity = new stdClass();
896
 
897
        $activity->type         = 'assign';
898
        $activity->cmid         = $cm->id;
899
        $activity->name         = $aname;
900
        $activity->sectionnum   = $cm->sectionnum;
901
        $activity->timestamp    = $submission->timemodified;
902
        $activity->user         = new stdClass();
903
        if ($grader) {
904
            $activity->grade = $grades->items[0]->grades[$submission->userid]->str_long_grade;
905
        }
906
 
907
        $userfields = explode(',', implode(',', \core_user\fields::get_picture_fields()));
908
        foreach ($userfields as $userfield) {
909
            if ($userfield == 'id') {
910
                // Aliased in SQL above.
911
                $activity->user->{$userfield} = $submission->userid;
912
            } else {
913
                $activity->user->{$userfield} = $submission->{$userfield};
914
            }
915
        }
916
        $activity->user->fullname = fullname($submission, $viewfullnames);
917
 
918
        $activities[$index++] = $activity;
919
    }
920
 
921
    return;
922
}
923
 
924
/**
925
 * Print recent activity from all assignments in a given course
926
 *
927
 * This is used by course/recent.php
928
 * @param stdClass $activity
929
 * @param int $courseid
930
 * @param bool $detail
931
 * @param array $modnames
932
 */
933
function assign_print_recent_mod_activity($activity, $courseid, $detail, $modnames) {
934
    global $CFG, $OUTPUT;
935
 
936
    echo '<table border="0" cellpadding="3" cellspacing="0" class="assignment-recent">';
937
 
938
    echo '<tr><td class="userpicture" valign="top">';
939
    echo $OUTPUT->user_picture($activity->user);
940
    echo '</td><td>';
941
 
942
    if ($detail) {
943
        $modname = $modnames[$activity->type];
944
        echo '<div class="title">';
945
        echo $OUTPUT->image_icon('monologo', $modname, 'assign');
946
        echo '<a href="' . $CFG->wwwroot . '/mod/assign/view.php?id=' . $activity->cmid . '">';
947
        echo $activity->name;
948
        echo '</a>';
949
        echo '</div>';
950
    }
951
 
952
    if (isset($activity->grade)) {
953
        echo '<div class="grade">';
954
        echo get_string('gradenoun') . ': ';
955
        echo $activity->grade;
956
        echo '</div>';
957
    }
958
 
959
    echo '<div class="user">';
960
    echo "<a href=\"$CFG->wwwroot/user/view.php?id={$activity->user->id}&amp;course=$courseid\">";
961
    echo "{$activity->user->fullname}</a>  - " . userdate($activity->timestamp);
962
    echo '</div>';
963
 
964
    echo '</td></tr></table>';
965
}
966
 
967
/**
1441 ariadna 968
 * Checks if scale is being used by any instance of assignment or is the default scale used for assignments.
1 efrain 969
 *
970
 * This is used to find out if scale used anywhere
971
 * @param int $scaleid
1441 ariadna 972
 * @return boolean True if the scale is used by any assignment or is the default scale used for assignments.
1 efrain 973
 */
974
function assign_scale_used_anywhere($scaleid) {
975
    global $DB;
976
 
1441 ariadna 977
    return $scaleid && (
978
        $DB->record_exists('assign', ['grade' => -(int)$scaleid]) ||
979
        (int)get_config('mod_assign', 'defaultgradescale') === (int)$scaleid
980
    );
1 efrain 981
}
982
 
983
/**
984
 * List the actions that correspond to a view of this module.
985
 * This is used by the participation report.
986
 *
987
 * Note: This is not used by new logging system. Event with
988
 *       crud = 'r' and edulevel = LEVEL_PARTICIPATING will
989
 *       be considered as view action.
990
 *
991
 * @return array
992
 */
993
function assign_get_view_actions() {
994
    return array('view submission', 'view feedback');
995
}
996
 
997
/**
998
 * List the actions that correspond to a post of this module.
999
 * This is used by the participation report.
1000
 *
1001
 * Note: This is not used by new logging system. Event with
1002
 *       crud = ('c' || 'u' || 'd') and edulevel = LEVEL_PARTICIPATING
1003
 *       will be considered as post action.
1004
 *
1005
 * @return array
1006
 */
1007
function assign_get_post_actions() {
1008
    return array('upload', 'submit', 'submit for grading');
1009
}
1010
 
1011
/**
1012
 * Returns all other capabilities used by this module.
1013
 * @return array Array of capability strings
1014
 */
1015
function assign_get_extra_capabilities() {
1016
    return ['gradereport/grader:view', 'moodle/grade:viewall'];
1017
}
1018
 
1019
/**
1020
 * Create grade item for given assignment.
1021
 *
1022
 * @param stdClass $assign record with extra cmidnumber
1023
 * @param array $grades optional array/object of grade(s); 'reset' means reset grades in gradebook
1024
 * @return int 0 if ok, error code otherwise
1025
 */
1026
function assign_grade_item_update($assign, $grades=null) {
1027
    global $CFG;
1028
    require_once($CFG->libdir.'/gradelib.php');
1029
 
1030
    if (!isset($assign->courseid)) {
1031
        $assign->courseid = $assign->course;
1032
    }
1033
 
1034
    $params = array('itemname'=>$assign->name, 'idnumber'=>$assign->cmidnumber);
1035
 
1036
    // Check if feedback plugin for gradebook is enabled, if yes then
1037
    // gradetype = GRADE_TYPE_TEXT else GRADE_TYPE_NONE.
1038
    $gradefeedbackenabled = false;
1039
 
1040
    if (isset($assign->gradefeedbackenabled)) {
1041
        $gradefeedbackenabled = $assign->gradefeedbackenabled;
1042
    } else if ($assign->grade == 0) { // Grade feedback is needed only when grade == 0.
1043
        require_once($CFG->dirroot . '/mod/assign/locallib.php');
1044
        $mod = get_coursemodule_from_instance('assign', $assign->id, $assign->courseid);
1045
        $cm = context_module::instance($mod->id);
1046
        $assignment = new assign($cm, null, null);
1047
        $gradefeedbackenabled = $assignment->is_gradebook_feedback_enabled();
1048
    }
1049
 
1050
    if ($assign->grade > 0) {
1051
        $params['gradetype'] = GRADE_TYPE_VALUE;
1052
        $params['grademax']  = $assign->grade;
1053
        $params['grademin']  = 0;
1054
 
1055
    } else if ($assign->grade < 0) {
1056
        $params['gradetype'] = GRADE_TYPE_SCALE;
1057
        $params['scaleid']   = -$assign->grade;
1058
 
1059
    } else if ($gradefeedbackenabled) {
1060
        // $assign->grade == 0 and feedback enabled.
1061
        $params['gradetype'] = GRADE_TYPE_TEXT;
1062
    } else {
1063
        // $assign->grade == 0 and no feedback enabled.
1064
        $params['gradetype'] = GRADE_TYPE_NONE;
1065
    }
1066
 
1067
    if ($grades  === 'reset') {
1068
        $params['reset'] = true;
1069
        $grades = null;
1070
    }
1071
 
1441 ariadna 1072
    $result = grade_update('mod/assign',
1 efrain 1073
                        $assign->courseid,
1074
                        'mod',
1075
                        'assign',
1076
                        $assign->id,
1077
                        0,
1078
                        $grades,
1079
                        $params);
1441 ariadna 1080
 
1081
    // Get lists of users whose grades are updated.
1082
    $userids = [];
1083
    if (is_array($grades)) {
1084
        // The $grades is array/object of grade(s).
1085
        // We are checking if it is single user (array with simple values such as userid and rawgrade).
1086
        // Or it is array of grade objects, for multiple users.
1087
        if (isset($grades['userid']) && isset($grades['rawgrade'])) {
1088
            // Single user grade update.
1089
            $userids = [$grades['userid']];
1090
        } else {
1091
            // Multiple user grade update.
1092
            foreach ($grades as $grade) {
1093
                if (is_object($grade) && isset($grade->userid) && isset($grade->rawgrade)) {
1094
                    $userids[] = $grade->userid;
1095
                }
1096
            }
1097
        }
1098
    }
1099
    // Apply penalty to each user.
1100
    foreach ($userids as $userid) {
1101
        \mod_assign\penalty\helper::apply_penalty_to_user($assign->id, $userid);
1102
    }
1103
 
1104
    return $result;
1 efrain 1105
}
1106
 
1107
/**
1108
 * Return grade for given user or all users.
1109
 *
1110
 * @param stdClass $assign record of assign with an additional cmidnumber
1111
 * @param int $userid optional user id, 0 means all users
1112
 * @return array array of grades, false if none
1113
 */
1114
function assign_get_user_grades($assign, $userid=0) {
1115
    global $CFG;
1116
 
1117
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
1118
 
1119
    $cm = get_coursemodule_from_instance('assign', $assign->id, 0, false, MUST_EXIST);
1120
    $context = context_module::instance($cm->id);
1121
    $assignment = new assign($context, null, null);
1122
    $assignment->set_instance($assign);
1123
    return $assignment->get_user_grades_for_gradebook($userid);
1124
}
1125
 
1126
/**
1127
 * Update activity grades.
1128
 *
1129
 * @param stdClass $assign database record
1130
 * @param int $userid specific user only, 0 means all
1131
 * @param bool $nullifnone - not used
1132
 */
1133
function assign_update_grades($assign, $userid=0, $nullifnone=true) {
1134
    global $CFG;
1135
    require_once($CFG->libdir.'/gradelib.php');
1136
 
1137
    if ($assign->grade == 0) {
1138
        assign_grade_item_update($assign);
1139
 
1140
    } else if ($grades = assign_get_user_grades($assign, $userid)) {
1141
        foreach ($grades as $k => $v) {
1142
            if ($v->rawgrade == -1) {
1143
                $grades[$k]->rawgrade = null;
1144
            }
1145
        }
1146
        assign_grade_item_update($assign, $grades);
1147
 
1148
    } else {
1149
        assign_grade_item_update($assign);
1150
    }
1151
}
1152
 
1153
/**
1154
 * List the file areas that can be browsed.
1155
 *
1156
 * @param stdClass $course
1157
 * @param stdClass $cm
1158
 * @param stdClass $context
1159
 * @return array
1160
 */
1161
function assign_get_file_areas($course, $cm, $context) {
1162
    global $CFG;
1163
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
1164
 
1165
    $areas = array(
1166
        ASSIGN_INTROATTACHMENT_FILEAREA => get_string('introattachments', 'mod_assign'),
1167
        ASSIGN_ACTIVITYATTACHMENT_FILEAREA => get_string('activityattachments', 'mod_assign'),
1168
    );
1169
 
1170
    $assignment = new assign($context, $cm, $course);
1171
    foreach ($assignment->get_submission_plugins() as $plugin) {
1172
        if ($plugin->is_visible()) {
1173
            $pluginareas = $plugin->get_file_areas();
1174
 
1175
            if ($pluginareas) {
1176
                $areas = array_merge($areas, $pluginareas);
1177
            }
1178
        }
1179
    }
1180
    foreach ($assignment->get_feedback_plugins() as $plugin) {
1181
        if ($plugin->is_visible()) {
1182
            $pluginareas = $plugin->get_file_areas();
1183
 
1184
            if ($pluginareas) {
1185
                $areas = array_merge($areas, $pluginareas);
1186
            }
1187
        }
1188
    }
1189
 
1190
    return $areas;
1191
}
1192
 
1193
/**
1194
 * File browsing support for assign module.
1195
 *
1196
 * @param file_browser $browser
1197
 * @param object $areas
1198
 * @param object $course
1199
 * @param object $cm
1200
 * @param object $context
1201
 * @param string $filearea
1202
 * @param int $itemid
1203
 * @param string $filepath
1204
 * @param string $filename
1205
 * @return object file_info instance or null if not found
1206
 */
1207
function assign_get_file_info($browser,
1208
                              $areas,
1209
                              $course,
1210
                              $cm,
1211
                              $context,
1212
                              $filearea,
1213
                              $itemid,
1214
                              $filepath,
1215
                              $filename) {
1216
    global $CFG;
1217
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
1218
 
1219
    if ($context->contextlevel != CONTEXT_MODULE) {
1220
        return null;
1221
    }
1222
 
1223
    $urlbase = $CFG->wwwroot.'/pluginfile.php';
1224
    $fs = get_file_storage();
1225
    $filepath = is_null($filepath) ? '/' : $filepath;
1226
    $filename = is_null($filename) ? '.' : $filename;
1227
 
1228
    // Need to find where this belongs to.
1229
    $assignment = new assign($context, $cm, $course);
1230
    if ($filearea === ASSIGN_INTROATTACHMENT_FILEAREA || $filearea === ASSIGN_ACTIVITYATTACHMENT_FILEAREA) {
1231
        if (!has_capability('moodle/course:managefiles', $context)) {
1232
            // Students can not peak here!
1233
            return null;
1234
        }
1235
        if (!($storedfile = $fs->get_file($assignment->get_context()->id,
1236
                                          'mod_assign', $filearea, 0, $filepath, $filename))) {
1237
            return null;
1238
        }
1239
        return new file_info_stored($browser,
1240
                        $assignment->get_context(),
1241
                        $storedfile,
1242
                        $urlbase,
1243
                        $filearea,
1244
                        $itemid,
1245
                        true,
1246
                        true,
1247
                        false);
1248
    }
1249
 
1250
    $pluginowner = null;
1251
    foreach ($assignment->get_submission_plugins() as $plugin) {
1252
        if ($plugin->is_visible()) {
1253
            $pluginareas = $plugin->get_file_areas();
1254
 
1255
            if (array_key_exists($filearea, $pluginareas)) {
1256
                $pluginowner = $plugin;
1257
                break;
1258
            }
1259
        }
1260
    }
1261
    if (!$pluginowner) {
1262
        foreach ($assignment->get_feedback_plugins() as $plugin) {
1263
            if ($plugin->is_visible()) {
1264
                $pluginareas = $plugin->get_file_areas();
1265
 
1266
                if (array_key_exists($filearea, $pluginareas)) {
1267
                    $pluginowner = $plugin;
1268
                    break;
1269
                }
1270
            }
1271
        }
1272
    }
1273
 
1274
    if (!$pluginowner) {
1275
        return null;
1276
    }
1277
 
1278
    $result = $pluginowner->get_file_info($browser, $filearea, $itemid, $filepath, $filename);
1279
    return $result;
1280
}
1281
 
1282
/**
1283
 * Prints the complete info about a user's interaction with an assignment.
1284
 *
1285
 * @param stdClass $course
1286
 * @param stdClass $user
1287
 * @param stdClass $coursemodule
1288
 * @param stdClass $assign the database assign record
1289
 *
1290
 * This prints the submission summary and feedback summary for this student.
1291
 */
1292
function assign_user_complete($course, $user, $coursemodule, $assign) {
1293
    global $CFG;
1294
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
1295
 
1296
    $context = context_module::instance($coursemodule->id);
1297
 
1298
    $assignment = new assign($context, $coursemodule, $course);
1299
 
1300
    echo $assignment->view_student_summary($user, false);
1301
}
1302
 
1303
/**
1304
 * Rescale all grades for this activity and push the new grades to the gradebook.
1305
 *
1306
 * @param stdClass $course Course db record
1307
 * @param stdClass $cm Course module db record
1308
 * @param float $oldmin
1309
 * @param float $oldmax
1310
 * @param float $newmin
1311
 * @param float $newmax
1312
 */
1313
function assign_rescale_activity_grades($course, $cm, $oldmin, $oldmax, $newmin, $newmax) {
1314
    global $DB;
1315
 
1316
    if ($oldmax <= $oldmin) {
1317
        // Grades cannot be scaled.
1318
        return false;
1319
    }
1320
    $scale = ($newmax - $newmin) / ($oldmax - $oldmin);
1321
    if (($newmax - $newmin) <= 1) {
1322
        // We would lose too much precision, lets bail.
1323
        return false;
1324
    }
1325
 
1326
    $params = array(
1327
        'p1' => $oldmin,
1328
        'p2' => $scale,
1329
        'p3' => $newmin,
1330
        'a' => $cm->instance
1331
    );
1332
 
1333
    // Only rescale grades that are greater than or equal to 0. Anything else is a special value.
1334
    $sql = 'UPDATE {assign_grades} set grade = (((grade - :p1) * :p2) + :p3) where assignment = :a and grade >= 0';
1335
    $dbupdate = $DB->execute($sql, $params);
1336
    if (!$dbupdate) {
1337
        return false;
1338
    }
1339
 
1340
    // Now re-push all grades to the gradebook.
1341
    $dbparams = array('id' => $cm->instance);
1342
    $assign = $DB->get_record('assign', $dbparams);
1343
    $assign->cmidnumber = $cm->idnumber;
1344
 
1345
    assign_update_grades($assign);
1346
 
1347
    return true;
1348
}
1349
 
1350
/**
1351
 * Print the grade information for the assignment for this user.
1352
 *
1353
 * @param stdClass $course
1354
 * @param stdClass $user
1355
 * @param stdClass $coursemodule
1356
 * @param stdClass $assignment
1357
 */
1358
function assign_user_outline($course, $user, $coursemodule, $assignment) {
1359
    global $CFG;
1360
    require_once($CFG->libdir.'/gradelib.php');
1361
    require_once($CFG->dirroot.'/grade/grading/lib.php');
1362
 
1363
    $gradinginfo = grade_get_grades($course->id,
1364
                                        'mod',
1365
                                        'assign',
1366
                                        $assignment->id,
1367
                                        $user->id);
1368
 
1369
    $gradingitem = $gradinginfo->items[0];
1370
    $gradebookgrade = $gradingitem->grades[$user->id];
1371
 
1372
    if (empty($gradebookgrade->str_long_grade)) {
1373
        return null;
1374
    }
1375
    $result = new stdClass();
1376
    if (!$gradingitem->hidden || has_capability('moodle/grade:viewhidden', context_course::instance($course->id))) {
1377
        $result->info = get_string('outlinegrade', 'assign', $gradebookgrade->str_long_grade);
1378
    } else {
1379
        $result->info = get_string('gradenoun') . ': ' . get_string('hidden', 'grades');
1380
    }
1381
    $result->time = $gradebookgrade->dategraded;
1382
 
1383
    return $result;
1384
}
1385
 
1386
/**
1387
 * Serves intro attachment files.
1388
 *
1389
 * @param mixed $course course or id of the course
1390
 * @param mixed $cm course module or id of the course module
1391
 * @param context $context
1392
 * @param string $filearea
1393
 * @param array $args
1394
 * @param bool $forcedownload
1395
 * @param array $options additional options affecting the file serving
1396
 * @return bool false if file not found, does not return if found - just send the file
1397
 */
1398
function assign_pluginfile($course,
1399
                $cm,
1400
                context $context,
1401
                $filearea,
1402
                $args,
1403
                $forcedownload,
1404
                array $options=array()) {
1405
    global $CFG;
1406
 
1407
    if ($context->contextlevel != CONTEXT_MODULE) {
1408
        return false;
1409
    }
1410
 
1411
    require_login($course, false, $cm);
1412
    if (!has_capability('mod/assign:view', $context)) {
1413
        return false;
1414
    }
1415
 
1416
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
1417
    $assign = new assign($context, $cm, $course);
1418
 
1419
    if ($filearea !== ASSIGN_INTROATTACHMENT_FILEAREA && $filearea !== ASSIGN_ACTIVITYATTACHMENT_FILEAREA) {
1420
        return false;
1421
    }
1422
    if (!$assign->show_intro()) {
1423
        return false;
1424
    }
1425
 
1426
    $itemid = (int)array_shift($args);
1427
    if ($itemid != 0) {
1428
        return false;
1429
    }
1430
 
1431
    $relativepath = implode('/', $args);
1432
 
1433
    $fullpath = "/{$context->id}/mod_assign/$filearea/$itemid/$relativepath";
1434
 
1435
    $fs = get_file_storage();
1436
    if (!$file = $fs->get_file_by_hash(sha1($fullpath)) or $file->is_directory()) {
1437
        return false;
1438
    }
1439
    send_stored_file($file, 0, 0, $forcedownload, $options);
1440
}
1441
 
1442
/**
1443
 * Serve the grading panel as a fragment.
1444
 *
1445
 * @param array $args List of named arguments for the fragment loader.
1446
 * @return string
1447
 */
1448
function mod_assign_output_fragment_gradingpanel($args) {
1449
    global $CFG;
1450
 
1451
    \core\session\manager::write_close(); // No changes to session in this function.
1452
 
1453
    $context = $args['context'];
1454
 
1455
    if ($context->contextlevel != CONTEXT_MODULE) {
1456
        return null;
1457
    }
1458
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
1459
    $assign = new assign($context, null, null);
1460
 
1461
    $userid = clean_param($args['userid'], PARAM_INT);
1462
 
1463
    $participant = $assign->get_participant($userid);
1464
    $isfiltered = $assign->is_userid_filtered($userid);
1465
    if (!$participant || !$isfiltered) {
1466
        // User is not enrolled or filtered out by filters and table preferences.
1467
        return '';
1468
    }
1469
 
1470
    $attemptnumber = clean_param($args['attemptnumber'], PARAM_INT);
1471
    $formdata = array();
1472
    if (!empty($args['jsonformdata'])) {
1473
        $serialiseddata = json_decode($args['jsonformdata']);
1474
        parse_str($serialiseddata, $formdata);
1475
    }
1476
    $viewargs = array(
1477
        'userid' => $userid,
1478
        'attemptnumber' => $attemptnumber,
1479
        'formdata' => $formdata
1480
    );
1481
 
1482
    return $assign->view('gradingpanel', $viewargs);
1483
}
1484
 
1485
/**
1486
 * Check if the module has any update that affects the current user since a given time.
1487
 *
1488
 * @param  cm_info $cm course module data
1489
 * @param  int $from the time to check updates from
1490
 * @param  array $filter  if we need to check only specific updates
1491
 * @return stdClass an object with the different type of areas indicating if they were updated or not
1492
 * @since Moodle 3.2
1493
 */
1494
function assign_check_updates_since(cm_info $cm, $from, $filter = array()) {
1495
    global $DB, $USER, $CFG;
1496
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
1497
 
1498
    $updates = new stdClass();
1499
    $updates = course_check_module_updates_since($cm, $from, array(ASSIGN_INTROATTACHMENT_FILEAREA), $filter);
1500
 
1501
    // Check if there is a new submission by the user or new grades.
1502
    $select = 'assignment = :id AND userid = :userid AND (timecreated > :since1 OR timemodified > :since2)';
1503
    $params = array('id' => $cm->instance, 'userid' => $USER->id, 'since1' => $from, 'since2' => $from);
1504
    $updates->submissions = (object) array('updated' => false);
1505
    $submissions = $DB->get_records_select('assign_submission', $select, $params, '', 'id');
1506
    if (!empty($submissions)) {
1507
        $updates->submissions->updated = true;
1508
        $updates->submissions->itemids = array_keys($submissions);
1509
    }
1510
 
1511
    $updates->grades = (object) array('updated' => false);
1512
    $grades = $DB->get_records_select('assign_grades', $select, $params, '', 'id');
1513
    if (!empty($grades)) {
1514
        $updates->grades->updated = true;
1515
        $updates->grades->itemids = array_keys($grades);
1516
    }
1517
 
1518
    // Now, teachers should see other students updates.
1519
    if (has_capability('mod/assign:viewgrades', $cm->context)) {
1520
        $params = array('id' => $cm->instance, 'since1' => $from, 'since2' => $from);
1521
        $select = 'assignment = :id AND (timecreated > :since1 OR timemodified > :since2)';
1522
 
1523
        if (groups_get_activity_groupmode($cm) == SEPARATEGROUPS) {
1524
            $groupusers = array_keys(groups_get_activity_shared_group_members($cm));
1525
            if (empty($groupusers)) {
1526
                return $updates;
1527
            }
1528
            list($insql, $inparams) = $DB->get_in_or_equal($groupusers, SQL_PARAMS_NAMED);
1529
            $select .= ' AND userid ' . $insql;
1530
            $params = array_merge($params, $inparams);
1531
        }
1532
 
1533
        $updates->usersubmissions = (object) array('updated' => false);
1534
        $submissions = $DB->get_records_select('assign_submission', $select, $params, '', 'id');
1535
        if (!empty($submissions)) {
1536
            $updates->usersubmissions->updated = true;
1537
            $updates->usersubmissions->itemids = array_keys($submissions);
1538
        }
1539
 
1540
        $updates->usergrades = (object) array('updated' => false);
1541
        $grades = $DB->get_records_select('assign_grades', $select, $params, '', 'id');
1542
        if (!empty($grades)) {
1543
            $updates->usergrades->updated = true;
1544
            $updates->usergrades->itemids = array_keys($grades);
1545
        }
1546
    }
1547
 
1548
    return $updates;
1549
}
1550
 
1551
/**
1552
 * Is the event visible?
1553
 *
1554
 * This is used to determine global visibility of an event in all places throughout Moodle. For example,
1555
 * the ASSIGN_EVENT_TYPE_GRADINGDUE event will not be shown to students on their calendar.
1556
 *
1557
 * @param calendar_event $event
1558
 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1559
 * @return bool Returns true if the event is visible to the current user, false otherwise.
1560
 */
1561
function mod_assign_core_calendar_is_event_visible(calendar_event $event, $userid = 0) {
1562
    global $CFG, $USER;
1563
 
1564
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
1565
 
1566
    if (empty($userid)) {
1567
        $userid = $USER->id;
1568
    }
1569
 
1570
    $cm = get_fast_modinfo($event->courseid, $userid)->instances['assign'][$event->instance];
1571
    $context = context_module::instance($cm->id);
1572
 
1573
    $assign = new assign($context, $cm, null);
1574
 
1575
    if ($event->eventtype == ASSIGN_EVENT_TYPE_GRADINGDUE) {
1576
        return $assign->can_grade($userid);
1577
    } else {
1578
        return true;
1579
    }
1580
}
1581
 
1582
/**
1583
 * This function receives a calendar event and returns the action associated with it, or null if there is none.
1584
 *
1585
 * This is used by block_myoverview in order to display the event appropriately. If null is returned then the event
1586
 * is not displayed on the block.
1587
 *
1588
 * @param calendar_event $event
1589
 * @param \core_calendar\action_factory $factory
1590
 * @param int $userid User id to use for all capability checks, etc. Set to 0 for current user (default).
1591
 * @return \core_calendar\local\event\entities\action_interface|null
1592
 */
1593
function mod_assign_core_calendar_provide_event_action(calendar_event $event,
1594
                                                       \core_calendar\action_factory $factory,
1595
                                                       $userid = 0) {
1596
 
1597
    global $CFG, $USER;
1598
 
1599
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
1600
 
1601
    if (empty($userid)) {
1602
        $userid = $USER->id;
1603
    }
1604
 
1605
    $cm = get_fast_modinfo($event->courseid, $userid)->instances['assign'][$event->instance];
1606
    $context = context_module::instance($cm->id);
1607
 
1608
    $completion = new \completion_info($cm->get_course());
1609
 
1610
    $completiondata = $completion->get_data($cm, false, $userid);
1611
 
1612
    if ($completiondata->completionstate != COMPLETION_INCOMPLETE) {
1613
        return null;
1614
    }
1615
 
1616
    $assign = new assign($context, $cm, null);
1617
 
1618
    // Apply overrides.
1619
    $assign->update_effective_access($userid);
1620
 
1621
    if ($event->eventtype == ASSIGN_EVENT_TYPE_GRADINGDUE) {
1622
        $name = get_string('gradeverb');
1623
        $url = new \moodle_url('/mod/assign/view.php', [
1624
            'id' => $cm->id,
1625
            'action' => 'grader'
1626
        ]);
1627
        $actionable = $assign->can_grade($userid) && (time() >= $assign->get_instance()->allowsubmissionsfromdate);
1628
        $itemcount = $actionable ? $assign->count_submissions_need_grading() : 0;
1629
    } else {
1630
        $usersubmission = $assign->get_user_submission($userid, false);
1631
        if ($usersubmission && $usersubmission->status === ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1632
            // The user has already submitted.
1633
            // We do not want to change the text to edit the submission, we want to remove the event from the Dashboard entirely.
1634
            return null;
1635
        }
1636
 
1637
        $instance = $assign->get_instance();
1638
        if ($instance->teamsubmission && !$instance->requireallteammemberssubmit) {
1639
            $groupsubmission = $assign->get_group_submission($userid, 0, false);
1640
            if ($groupsubmission && $groupsubmission->status === ASSIGN_SUBMISSION_STATUS_SUBMITTED) {
1641
                return null;
1642
            }
1643
        }
1644
 
1645
        $participant = $assign->get_participant($userid);
1646
 
1647
        if (!$participant) {
1648
            // If the user is not a participant in the assignment then they have
1649
            // no action to take. This will filter out the events for teachers.
1650
            return null;
1651
        }
1652
 
1653
        // The user has not yet submitted anything. Show the addsubmission link.
1654
        $name = get_string('addsubmission', 'assign');
1655
        $url = new \moodle_url('/mod/assign/view.php', [
1656
            'id' => $cm->id,
1657
            'action' => 'editsubmission'
1658
        ]);
1659
        $itemcount = 1;
1660
        $actionable = $assign->is_any_submission_plugin_enabled() && $assign->can_edit_submission($userid, $userid);
1661
    }
1662
 
1663
    return $factory->create_instance(
1664
        $name,
1665
        $url,
1666
        $itemcount,
1667
        $actionable
1668
    );
1669
}
1670
 
1671
/**
1672
 * Callback function that determines whether an action event should be showing its item count
1673
 * based on the event type and the item count.
1674
 *
1675
 * @param calendar_event $event The calendar event.
1676
 * @param int $itemcount The item count associated with the action event.
1677
 * @return bool
1678
 */
1679
function mod_assign_core_calendar_event_action_shows_item_count(calendar_event $event, $itemcount = 0) {
1680
    // List of event types where the action event's item count should be shown.
1681
    $eventtypesshowingitemcount = [
1682
        ASSIGN_EVENT_TYPE_GRADINGDUE
1683
    ];
1684
    // For mod_assign, item count should be shown if the event type is 'gradingdue' and there is one or more item count.
1685
    return in_array($event->eventtype, $eventtypesshowingitemcount) && $itemcount > 0;
1686
}
1687
 
1688
/**
1689
 * This function calculates the minimum and maximum cutoff values for the timestart of
1690
 * the given event.
1691
 *
1692
 * It will return an array with two values, the first being the minimum cutoff value and
1693
 * the second being the maximum cutoff value. Either or both values can be null, which
1694
 * indicates there is no minimum or maximum, respectively.
1695
 *
1696
 * If a cutoff is required then the function must return an array containing the cutoff
1697
 * timestamp and error string to display to the user if the cutoff value is violated.
1698
 *
1699
 * A minimum and maximum cutoff return value will look like:
1700
 * [
1701
 *     [1505704373, 'The due date must be after the sbumission start date'],
1702
 *     [1506741172, 'The due date must be before the cutoff date']
1703
 * ]
1704
 *
1705
 * If the event does not have a valid timestart range then [false, false] will
1706
 * be returned.
1707
 *
1708
 * @param calendar_event $event The calendar event to get the time range for
1709
 * @param stdClass $instance The module instance to get the range from
1710
 * @return array
1711
 */
1712
function mod_assign_core_calendar_get_valid_event_timestart_range(\calendar_event $event, \stdClass $instance) {
1713
    global $CFG;
1714
 
1715
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
1716
 
1717
    $courseid = $event->courseid;
1718
    $modulename = $event->modulename;
1719
    $instanceid = $event->instance;
1720
    $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
1721
    $context = context_module::instance($coursemodule->id);
1722
    $assign = new assign($context, null, null);
1723
    $assign->set_instance($instance);
1724
 
1725
    return $assign->get_valid_calendar_event_timestart_range($event);
1726
}
1727
 
1728
/**
1729
 * This function will update the assign module according to the
1730
 * event that has been modified.
1731
 *
1732
 * @throws \moodle_exception
1733
 * @param \calendar_event $event
1734
 * @param stdClass $instance The module instance to get the range from
1735
 */
1736
function mod_assign_core_calendar_event_timestart_updated(\calendar_event $event, \stdClass $instance) {
1737
    global $CFG, $DB;
1738
 
1739
    require_once($CFG->dirroot . '/mod/assign/locallib.php');
1740
 
1741
    if (empty($event->instance) || $event->modulename != 'assign') {
1742
        return;
1743
    }
1744
 
1745
    if ($instance->id != $event->instance) {
1746
        return;
1747
    }
1748
 
1749
    if (!in_array($event->eventtype, [ASSIGN_EVENT_TYPE_DUE, ASSIGN_EVENT_TYPE_GRADINGDUE])) {
1750
        return;
1751
    }
1752
 
1753
    $courseid = $event->courseid;
1754
    $modulename = $event->modulename;
1755
    $instanceid = $event->instance;
1756
    $modified = false;
1757
    $coursemodule = get_fast_modinfo($courseid)->instances[$modulename][$instanceid];
1758
    $context = context_module::instance($coursemodule->id);
1759
 
1760
    // The user does not have the capability to modify this activity.
1761
    if (!has_capability('moodle/course:manageactivities', $context)) {
1762
        return;
1763
    }
1764
 
1765
    $assign = new assign($context, $coursemodule, null);
1766
    $assign->set_instance($instance);
1767
 
1768
    if ($event->eventtype == ASSIGN_EVENT_TYPE_DUE) {
1769
        // This check is in here because due date events are currently
1770
        // the only events that can be overridden, so we can save a DB
1771
        // query if we don't bother checking other events.
1772
        if ($assign->is_override_calendar_event($event)) {
1773
            // This is an override event so we should ignore it.
1774
            return;
1775
        }
1776
 
1777
        $newduedate = $event->timestart;
1778
 
1779
        if ($newduedate != $instance->duedate) {
1780
            $instance->duedate = $newduedate;
1781
            $modified = true;
1782
        }
1783
    } else if ($event->eventtype == ASSIGN_EVENT_TYPE_GRADINGDUE) {
1784
        $newduedate = $event->timestart;
1785
 
1786
        if ($newduedate != $instance->gradingduedate) {
1787
            $instance->gradingduedate = $newduedate;
1788
            $modified = true;
1789
        }
1790
    }
1791
 
1792
    if ($modified) {
1793
        $instance->timemodified = time();
1794
        // Persist the assign instance changes.
1795
        $DB->update_record('assign', $instance);
1796
        $assign->update_calendar($coursemodule->id);
1797
        $event = \core\event\course_module_updated::create_from_cm($coursemodule, $context);
1798
        $event->trigger();
1799
    }
1800
}
1801
 
1802
/**
1803
 * Return a list of all the user preferences used by mod_assign.
1804
 *
1805
 * @uses core_user::is_current_user
1806
 *
1807
 * @return array[]
1808
 */
1809
function mod_assign_user_preferences(): array {
1810
    $preferences = array();
1811
    $preferences['assign_filter'] = array(
1812
        'type' => PARAM_ALPHA,
1813
        'null' => NULL_NOT_ALLOWED,
1814
        'default' => '',
1815
        'permissioncallback' => [core_user::class, 'is_current_user'],
1816
    );
1817
    $preferences['assign_workflowfilter'] = array(
1818
        'type' => PARAM_ALPHA,
1819
        'null' => NULL_NOT_ALLOWED,
1820
        'default' => '',
1821
        'permissioncallback' => [core_user::class, 'is_current_user'],
1822
    );
1823
    $preferences['assign_markerfilter'] = array(
1824
        'type' => PARAM_ALPHANUMEXT,
1825
        'null' => NULL_NOT_ALLOWED,
1826
        'default' => '',
1827
        'permissioncallback' => [core_user::class, 'is_current_user'],
1828
    );
1829
 
1830
    return $preferences;
1831
}
1832
 
1833
/**
1834
 * Given an array with a file path, it returns the itemid and the filepath for the defined filearea.
1835
 *
1836
 * @param  string $filearea The filearea.
1837
 * @param  array  $args The path (the part after the filearea and before the filename).
1838
 * @return array The itemid and the filepath inside the $args path, for the defined filearea.
1839
 */
1840
function mod_assign_get_path_from_pluginfile(string $filearea, array $args): array {
1841
    // Assign never has an itemid (the number represents the revision but it's not stored in database).
1842
    array_shift($args);
1843
 
1844
    // Get the filepath.
1845
    if (empty($args)) {
1846
        $filepath = '/';
1847
    } else {
1848
        $filepath = '/' . implode('/', $args) . '/';
1849
    }
1850
 
1851
    return [
1852
        'itemid' => 0,
1853
        'filepath' => $filepath,
1854
    ];
1855
}
1856
 
1857
/**
1858
 * Callback to fetch the activity event type lang string.
1859
 *
1860
 * @param string $eventtype The event type.
1861
 * @return lang_string The event type lang string.
1862
 */
1863
function mod_assign_core_calendar_get_event_action_string(string $eventtype): string {
1864
    $modulename = get_string('modulename', 'assign');
1865
 
1866
    switch ($eventtype) {
1867
        case ASSIGN_EVENT_TYPE_DUE:
1868
            $identifier = 'calendardue';
1869
            break;
1870
        case ASSIGN_EVENT_TYPE_GRADINGDUE:
1871
            $identifier = 'calendargradingdue';
1872
            break;
1873
        default:
1874
            return get_string('requiresaction', 'calendar', $modulename);
1875
    }
1876
 
1877
    return get_string($identifier, 'assign', $modulename);
1878
}
1441 ariadna 1879
 
1880
/**
1881
 * Allow the support for SMS in assignment.
1882
 *
1883
 * @return bool
1884
 */
1885
function mod_assign_supports_sms_notifications(): bool {
1886
    // At the moment, assignment supports sms notifications.
1887
    return true;
1888
}