Proyectos de Subversion Moodle

Rev

| 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
 * Cohort enrolment plugin.
19
 *
20
 * @package    enrol_cohort
21
 * @copyright  2010 Petr Skoda {@link http://skodak.org}
22
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
23
 */
24
 
25
defined('MOODLE_INTERNAL') || die();
26
 
27
/**
28
 * COHORT_CREATEGROUP constant for automatically creating a group for a cohort.
29
 */
30
define('COHORT_CREATE_GROUP', -1);
31
 
32
/**
33
 * COHORT_NOGROUP constant for using no group for a cohort.
34
 */
35
define('COHORT_NOGROUP', 0);
36
 
37
 
38
/**
39
 * Cohort enrolment plugin implementation.
40
 * @author Petr Skoda
41
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
42
 */
43
class enrol_cohort_plugin extends enrol_plugin {
44
 
45
    /**
46
     * Is it possible to delete enrol instance via standard UI?
47
     *
48
     * @param stdClass $instance
49
     * @return bool
50
     */
51
    public function can_delete_instance($instance) {
52
        $context = context_course::instance($instance->courseid);
53
        return has_capability('enrol/cohort:config', $context);
54
    }
55
 
56
    /**
57
     * Returns localised name of enrol instance.
58
     *
59
     * @param stdClass $instance (null is accepted too)
60
     * @return string
61
     */
62
    public function get_instance_name($instance) {
63
        global $DB;
64
 
65
        if (empty($instance)) {
66
            $enrol = $this->get_name();
67
            return get_string('pluginname', 'enrol_'.$enrol);
68
 
69
        } else if (empty($instance->name)) {
70
            $enrol = $this->get_name();
71
            $cohort = $DB->get_record('cohort', array('id'=>$instance->customint1));
72
            if (!$cohort) {
73
                return get_string('pluginname', 'enrol_'.$enrol);
74
            }
75
            $cohortname = format_string($cohort->name, true, array('context'=>context::instance_by_id($cohort->contextid)));
76
            if ($role = $DB->get_record('role', array('id'=>$instance->roleid))) {
77
                $role = role_get_name($role, context_course::instance($instance->courseid, IGNORE_MISSING), ROLENAME_BOTH);
78
                return get_string('pluginname', 'enrol_'.$enrol) . ' (' . $cohortname . ' - ' . $role .')';
79
            } else {
80
                return get_string('pluginname', 'enrol_'.$enrol) . ' (' . $cohortname . ')';
81
            }
82
 
83
        } else {
84
            return format_string($instance->name, true, array('context'=>context_course::instance($instance->courseid)));
85
        }
86
    }
87
 
88
    /**
89
     * Given a courseid this function returns true if the user is able to enrol or configure cohorts.
90
     * AND there are cohorts that the user can view.
91
     *
92
     * @param int $courseid
93
     * @return bool
94
     */
95
    public function can_add_instance($courseid) {
96
        global $CFG;
97
        require_once($CFG->dirroot . '/cohort/lib.php');
98
        $coursecontext = context_course::instance($courseid);
99
        if (!has_capability('moodle/course:enrolconfig', $coursecontext) or !has_capability('enrol/cohort:config', $coursecontext)) {
100
            return false;
101
        }
102
        return cohort_get_available_cohorts($coursecontext, 0, 0, 1) ? true : false;
103
    }
104
 
105
    /**
106
     * Add new instance of enrol plugin.
107
     * @param object $course
108
     * @param array $fields instance fields
109
     * @return int id of new instance, null if can not be created
110
     */
111
    public function add_instance($course, array $fields = null) {
112
        global $CFG;
113
 
114
        // Allows multiple cohorts to be set on creation.
115
        if (!empty($fields['customint1'])) {
116
            $fields2 = $fields;
117
            if (!is_array($fields['customint1'])) {
118
                $fields['customint1'] = array($fields['customint1']);
119
            }
120
            foreach ($fields['customint1'] as $cid) {
121
                $fields2['customint1'] = $cid;
122
                if (!empty($fields['customint2']) && $fields['customint2'] == COHORT_CREATE_GROUP) {
123
                    // Create a new group for the cohort if requested.
124
                    $context = context_course::instance($course->id);
125
                    require_capability('moodle/course:managegroups', $context);
126
                    $groupid = enrol_cohort_create_new_group($course->id, $cid);
127
                    $fields2['customint2'] = $groupid;
128
                }
129
                $result = parent::add_instance($course, $fields2);
130
            }
131
        } else {
132
            $result = parent::add_instance($course, $fields);
133
        }
134
        require_once("$CFG->dirroot/enrol/cohort/locallib.php");
135
        $trace = new null_progress_trace();
136
        enrol_cohort_sync($trace, $course->id);
137
        $trace->finished();
138
        return $result;
139
    }
140
 
141
    /**
142
     * Update instance of enrol plugin.
143
     * @param stdClass $instance
144
     * @param stdClass $data modified instance fields
145
     * @return boolean
146
     */
147
    public function update_instance($instance, $data) {
148
        global $CFG;
149
 
150
        // NOTE: no cohort changes here!!!
151
        $context = context_course::instance($instance->courseid);
152
        if ($data->roleid != $instance->roleid) {
153
            // The sync script can only add roles, for perf reasons it does not modify them.
154
            $params = array(
155
                'contextid' => $context->id,
156
                'roleid' => $instance->roleid,
157
                'component' => 'enrol_cohort',
158
                'itemid' => $instance->id
159
            );
160
            role_unassign_all($params);
161
        }
162
        // Create a new group for the cohort if requested.
163
        if ($data->customint2 == COHORT_CREATE_GROUP) {
164
            require_capability('moodle/course:managegroups', $context);
165
            $groupid = enrol_cohort_create_new_group($instance->courseid, $data->customint1);
166
            $data->customint2 = $groupid;
167
        }
168
 
169
        $result = parent::update_instance($instance, $data);
170
 
171
        require_once("$CFG->dirroot/enrol/cohort/locallib.php");
172
        $trace = new null_progress_trace();
173
        enrol_cohort_sync($trace, $instance->courseid);
174
        $trace->finished();
175
 
176
        return $result;
177
    }
178
 
179
    /**
180
     * Called after updating/inserting course.
181
     *
182
     * @param bool $inserted true if course just inserted
183
     * @param stdClass $course
184
     * @param stdClass $data form data
185
     * @return void
186
     */
187
    public function course_updated($inserted, $course, $data) {
188
        // It turns out there is no need for cohorts to deal with this hook, see MDL-34870.
189
    }
190
 
191
    /**
192
     * Update instance status
193
     *
194
     * @param stdClass $instance
195
     * @param int $newstatus ENROL_INSTANCE_ENABLED, ENROL_INSTANCE_DISABLED
196
     * @return void
197
     */
198
    public function update_status($instance, $newstatus) {
199
        global $CFG;
200
 
201
        parent::update_status($instance, $newstatus);
202
 
203
        require_once("$CFG->dirroot/enrol/cohort/locallib.php");
204
        $trace = new null_progress_trace();
205
        enrol_cohort_sync($trace, $instance->courseid);
206
        $trace->finished();
207
    }
208
 
209
    /**
210
     * Does this plugin allow manual unenrolment of a specific user?
211
     * Yes, but only if user suspended...
212
     *
213
     * @param stdClass $instance course enrol instance
214
     * @param stdClass $ue record from user_enrolments table
215
     *
216
     * @return bool - true means user with 'enrol/xxx:unenrol' may unenrol this user, false means nobody may touch this user enrolment
217
     */
218
    public function allow_unenrol_user(stdClass $instance, stdClass $ue) {
219
        if ($ue->status == ENROL_USER_SUSPENDED) {
220
            return true;
221
        }
222
 
223
        return false;
224
    }
225
 
226
    /**
227
     * Restore instance and map settings.
228
     *
229
     * @param restore_enrolments_structure_step $step
230
     * @param stdClass $data
231
     * @param stdClass $course
232
     * @param int $oldid
233
     */
234
    public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
235
        global $DB, $CFG;
236
 
237
        if (!$step->get_task()->is_samesite()) {
238
            // No cohort restore from other sites.
239
            $step->set_mapping('enrol', $oldid, 0);
240
            return;
241
        }
242
 
243
        if (!empty($data->customint2)) {
244
            $data->customint2 = $step->get_mappingid('group', $data->customint2);
245
        }
246
 
247
        if ($data->roleid and $DB->record_exists('cohort', array('id'=>$data->customint1))) {
248
            $instance = $DB->get_record('enrol', array('roleid'=>$data->roleid, 'customint1'=>$data->customint1, 'courseid'=>$course->id, 'enrol'=>$this->get_name()));
249
            if ($instance) {
250
                $instanceid = $instance->id;
251
            } else {
252
                $instanceid = $this->add_instance($course, (array)$data);
253
            }
254
            $step->set_mapping('enrol', $oldid, $instanceid);
255
 
256
            require_once("$CFG->dirroot/enrol/cohort/locallib.php");
257
            $trace = new null_progress_trace();
258
            enrol_cohort_sync($trace, $course->id);
259
            $trace->finished();
260
 
261
        } else if ($this->get_config('unenrolaction') == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
262
            $data->customint1 = 0;
263
            $instance = $DB->get_record('enrol', array('roleid'=>$data->roleid, 'customint1'=>$data->customint1, 'courseid'=>$course->id, 'enrol'=>$this->get_name()));
264
 
265
            if ($instance) {
266
                $instanceid = $instance->id;
267
            } else {
268
                $data->status = ENROL_INSTANCE_DISABLED;
269
                $instanceid = $this->add_instance($course, (array)$data);
270
            }
271
            $step->set_mapping('enrol', $oldid, $instanceid);
272
 
273
            require_once("$CFG->dirroot/enrol/cohort/locallib.php");
274
            $trace = new null_progress_trace();
275
            enrol_cohort_sync($trace, $course->id);
276
            $trace->finished();
277
 
278
        } else {
279
            $step->set_mapping('enrol', $oldid, 0);
280
        }
281
    }
282
 
283
    /**
284
     * Restore user enrolment.
285
     *
286
     * @param restore_enrolments_structure_step $step
287
     * @param stdClass $data
288
     * @param stdClass $instance
289
     * @param int $oldinstancestatus
290
     * @param int $userid
291
     */
292
    public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
293
        global $DB;
294
 
295
        if ($this->get_config('unenrolaction') != ENROL_EXT_REMOVED_SUSPENDNOROLES) {
296
            // Enrolments were already synchronised in restore_instance(), we do not want any suspended leftovers.
297
            return;
298
        }
299
 
300
        // ENROL_EXT_REMOVED_SUSPENDNOROLES means all previous enrolments are restored
301
        // but without roles and suspended.
302
 
303
        if (!$DB->record_exists('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid))) {
304
            $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, ENROL_USER_SUSPENDED);
305
        }
306
    }
307
 
308
    /**
309
     * Restore user group membership.
310
     * @param stdClass $instance
311
     * @param int $groupid
312
     * @param int $userid
313
     */
314
    public function restore_group_member($instance, $groupid, $userid) {
315
        // Nothing to do here, the group members are added in $this->restore_group_restored()
316
        return;
317
    }
318
 
319
    /**
320
     * Is it possible to hide/show enrol instance via standard UI?
321
     *
322
     * @param stdClass $instance
323
     * @return bool
324
     */
325
    public function can_hide_show_instance($instance) {
326
        $context = context_course::instance($instance->courseid);
327
        return has_capability('enrol/cohort:config', $context);
328
    }
329
 
330
    /**
331
     * Return an array of valid options for the status.
332
     *
333
     * @return array
334
     */
335
    protected function get_status_options() {
336
        $options = array(ENROL_INSTANCE_ENABLED  => get_string('yes'),
337
                         ENROL_INSTANCE_DISABLED => get_string('no'));
338
        return $options;
339
    }
340
 
341
    /**
342
     * Return an array of valid options for the cohorts.
343
     *
344
     * @param stdClass $instance
345
     * @param context $context
346
     * @return array
347
     */
348
    protected function get_cohort_options($instance, $context) {
349
        global $DB, $CFG;
350
 
351
        require_once($CFG->dirroot . '/cohort/lib.php');
352
 
353
        $cohorts = array();
354
 
355
        if ($instance->id) {
356
            if ($cohort = $DB->get_record('cohort', array('id' => $instance->customint1))) {
357
                $name = format_string($cohort->name, true, array('context' => context::instance_by_id($cohort->contextid)));
358
                $cohorts = array($instance->customint1 => $name);
359
            } else {
360
                $cohorts = array($instance->customint1 => get_string('error'));
361
            }
362
        } else {
363
            $cohorts = array('' => get_string('choosedots'));
364
            $allcohorts = cohort_get_available_cohorts($context, 0, 0, 0);
365
            foreach ($allcohorts as $c) {
366
                $cohorts[$c->id] = format_string($c->name);
367
            }
368
        }
369
        return $cohorts;
370
    }
371
 
372
    /**
373
     * Return an array of valid options for the roles.
374
     *
375
     * @param stdClass $instance
376
     * @param context $coursecontext
377
     * @return array
378
     */
379
    protected function get_role_options($instance, $coursecontext) {
380
        global $DB;
381
 
382
        $roles = get_assignable_roles($coursecontext, ROLENAME_BOTH);
383
        $roles[0] = get_string('none');
384
        $roles = array_reverse($roles, true); // Descending default sortorder.
385
 
386
        // If the instance is already configured, but the configured role is no longer assignable in the course then add it back.
387
        if ($instance->id and !isset($roles[$instance->roleid])) {
388
            if ($role = $DB->get_record('role', array('id' => $instance->roleid))) {
389
                $roles[$instance->roleid] = role_get_name($role, $coursecontext, ROLENAME_BOTH);
390
            } else {
391
                $roles[$instance->roleid] = get_string('error');
392
            }
393
        }
394
 
395
        return $roles;
396
    }
397
 
398
    /**
399
     * Return an array of valid options for the groups.
400
     *
401
     * @param context $coursecontext
402
     * @return array
403
     */
404
    protected function get_group_options($coursecontext) {
405
        $groups = array(0 => get_string('none'));
406
        if (has_capability('moodle/course:managegroups', $coursecontext)) {
407
            $groups[COHORT_CREATE_GROUP] = get_string('creategroup', 'enrol_cohort');
408
        }
409
 
410
        foreach (groups_get_all_groups($coursecontext->instanceid) as $group) {
411
            $groups[$group->id] = format_string($group->name, true, array('context' => $coursecontext));
412
        }
413
 
414
        return $groups;
415
    }
416
 
417
    /**
418
     * We are a good plugin and don't invent our own UI/validation code path.
419
     *
420
     * @return boolean
421
     */
422
    public function use_standard_editing_ui() {
423
        return true;
424
    }
425
 
426
    /**
427
     * Add elements to the edit instance form.
428
     *
429
     * @param stdClass $instance
430
     * @param MoodleQuickForm $mform
431
     * @param context $coursecontext
432
     * @return bool
433
     */
434
    public function edit_instance_form($instance, MoodleQuickForm $mform, $coursecontext) {
435
 
436
        $options = $this->get_status_options();
437
        $mform->addElement('select', 'status', get_string('status', 'enrol_cohort'), $options);
438
 
439
        $options = ['contextid' => $coursecontext->id, 'multiple' => true];
440
        $mform->addElement('cohort', 'customint1', get_string('cohort', 'cohort'), $options);
441
 
442
        if ($instance->id) {
443
            $mform->setConstant('customint1', $instance->customint1);
444
            $mform->hardFreeze('customint1', $instance->customint1);
445
        } else {
446
            $mform->addRule('customint1', get_string('required'), 'required', null, 'client');
447
        }
448
 
449
        $roles = $this->get_role_options($instance, $coursecontext);
450
        $mform->addElement('select', 'roleid', get_string('assignrole', 'enrol_cohort'), $roles);
451
        $mform->setDefault('roleid', $this->get_config('roleid'));
452
        $groups = $this->get_group_options($coursecontext);
453
        $mform->addElement('select', 'customint2', get_string('addgroup', 'enrol_cohort'), $groups);
454
    }
455
 
456
    /**
457
     * Perform custom validation of the data used to edit the instance.
458
     *
459
     * @param array $data array of ("fieldname" => value) of submitted data
460
     * @param array $files array of uploaded files "element_name" => tmp_file_path
461
     * @param object $instance The instance loaded from the DB
462
     * @param context $context The context of the instance we are editing
463
     * @return array of "element_name" => "error_description" if there are errors,
464
     *         or an empty array if everything is OK.
465
     * @return void
466
     */
467
    public function edit_instance_validation($data, $files, $instance, $context) {
468
        global $DB;
469
        $errors = array();
470
        // Allows multiple cohorts to be selected.
471
        list($sql1, $params1) = $DB->get_in_or_equal($data['customint1'], SQL_PARAMS_NAMED);
472
        $params = array(
473
            'roleid' => $data['roleid'],
474
            'courseid' => $data['courseid'],
475
            'id' => $data['id']
476
        );
477
        $params = array_merge($params, $params1);
478
        $sql = "roleid = :roleid AND customint1 $sql1 AND courseid = :courseid AND enrol = 'cohort' AND id <> :id";
479
        if ($DB->record_exists_select('enrol', $sql, $params)) {
480
            $errors['customint1'] = get_string('instanceexists', 'enrol_cohort');
481
        }
482
        $validstatus = array_keys($this->get_status_options());
483
        $validcohorts = array_keys($this->get_cohort_options($instance, $context));
484
        $validroles = array_keys($this->get_role_options($instance, $context));
485
        $validgroups = array_keys($this->get_group_options($context));
486
        $tovalidate = array(
487
            'status' => $validstatus,
488
            'roleid' => $validroles,
489
            'customint2' => $validgroups
490
        );
491
        $typeerrors = $this->validate_param_types($data, $tovalidate);
492
        // When creating a new cohort enrolment, we allow multiple cohorts in just one go.
493
        // When editing an existing enrolment, changing the cohort is no allowed, so cohort is a single value.
494
        if (is_array($data['customint1'])) {
495
            $cohorts = $data['customint1'];
496
        } else {
497
            $cohorts = [$data['customint1']];
498
        }
499
 
500
        $errors = array_merge($errors, $typeerrors);
501
        // Check that the cohorts passed are valid.
502
        if (!empty(array_diff($cohorts, $validcohorts))) {
503
            $errors['customint1'] = get_string('invaliddata', 'error');
504
        }
505
        return $errors;
506
    }
507
 
508
    /**
509
     * Check if data is valid for a given enrolment plugin
510
     *
511
     * @param array $enrolmentdata enrolment data to validate.
512
     * @param int|null $courseid Course ID.
513
     * @return array Errors
514
     */
515
    public function validate_enrol_plugin_data(array $enrolmentdata, ?int $courseid = null): array {
516
        global $DB;
517
 
518
        $errors = parent::validate_enrol_plugin_data($enrolmentdata, $courseid);
519
 
520
        if (isset($enrolmentdata['addtogroup'])) {
521
            $addtogroup = $enrolmentdata['addtogroup'];
522
            if (($addtogroup == - COHORT_CREATE_GROUP) || $addtogroup == COHORT_NOGROUP) {
523
                if (isset($enrolmentdata['groupname'])) {
524
                    $errors['erroraddtogroupgroupname'] =
525
                        new lang_string('erroraddtogroupgroupname', 'group');
526
                }
527
            } else {
528
                $errors['erroraddtogroup'] =
529
                    new lang_string('erroraddtogroup', 'group');
530
            }
531
        }
532
 
533
        if ($courseid) {
534
            $enrolmentdata = $this->fill_enrol_custom_fields($enrolmentdata, $courseid);
535
            $error = $this->validate_plugin_data_context($enrolmentdata, $courseid);
536
            if ($error) {
537
                $errors['contextnotallowed'] = $error;
538
            }
539
 
540
            if (isset($enrolmentdata['groupname']) && $enrolmentdata['groupname']) {
541
                $groupname = $enrolmentdata['groupname'];
542
                if (!groups_get_group_by_name($courseid, $groupname)) {
543
                    $errors['errorinvalidgroup'] =
544
                        new lang_string('errorinvalidgroup', 'group', $groupname);
545
                }
546
            }
547
        }
548
 
549
        if (!isset($enrolmentdata['cohortidnumber'])) {
550
            $missingmandatoryfields = 'cohortidnumber';
551
        } else {
552
            $cohortidnumber = $enrolmentdata['cohortidnumber'];
553
            // Cohort idnumber is unique.
554
            $cohortid = $DB->get_field('cohort', 'id', ['idnumber' => $cohortidnumber]);
555
 
556
            if (!$cohortid) {
557
                $errors['unknowncohort'] =
558
                    new lang_string('unknowncohort', 'cohort', $cohortidnumber);
559
            }
560
        }
561
 
562
        if (!isset($enrolmentdata['role'])) {
563
            // We require role since we need it to identify enrol instance.
564
            if (isset($missingmandatoryfields)) {
565
                $missingmandatoryfields .= ', role';
566
            } else {
567
                $missingmandatoryfields = 'role';
568
            }
569
            $errors['missingmandatoryfields'] =
570
                new lang_string('missingmandatoryfields', 'tool_uploadcourse',
571
                    $missingmandatoryfields);
572
        } else {
573
            $roleid = $DB->get_field('role', 'id', ['shortname' => $enrolmentdata['role']]);
574
            if (!$roleid) {
575
                $errors['unknownrole'] =
576
                    new lang_string('unknownrole', 'error', s($enrolmentdata['role']));
577
            }
578
        }
579
 
580
        return $errors;
581
    }
582
 
583
    /**
584
     * Fill custom fields data for a given enrolment plugin.
585
     *
586
     * @param array $enrolmentdata enrolment data.
587
     * @param int $courseid Course ID.
588
     * @return array Updated enrolment data with custom fields info.
589
     */
590
    public function fill_enrol_custom_fields(array $enrolmentdata, int $courseid): array {
591
        global $DB;
592
 
593
        if (isset($enrolmentdata['cohortidnumber'])) {
594
            // Cohort idnumber is unique.
595
            $enrolmentdata['customint1'] =
596
                $DB->get_field('cohort', 'id', ['idnumber' => $enrolmentdata['cohortidnumber']]);
597
        }
598
 
599
        if (isset($enrolmentdata['addtogroup'])) {
600
            if ($enrolmentdata['addtogroup'] == COHORT_NOGROUP) {
601
                $enrolmentdata['customint2'] = COHORT_NOGROUP;
602
            } else if ($enrolmentdata['addtogroup'] == - COHORT_CREATE_GROUP) {
603
                $enrolmentdata['customint2'] = COHORT_CREATE_GROUP;
604
            }
605
        } else if (isset($enrolmentdata['groupname'])) {
606
            $enrolmentdata['customint2'] = groups_get_group_by_name($courseid, $enrolmentdata['groupname']);
607
        }
608
        return $enrolmentdata;
609
    }
610
 
611
    /**
612
     * Check if plugin custom data is allowed in relevant context.
613
     *
614
     * @param array $enrolmentdata enrolment data to validate.
615
     * @param int|null $courseid Course ID.
616
     * @return lang_string|null Error
617
     */
618
    public function validate_plugin_data_context(array $enrolmentdata, ?int $courseid = null): ?lang_string {
619
        $error = null;
620
        if (isset($enrolmentdata['customint1'])) {
621
            $cohortid = $enrolmentdata['customint1'];
622
            $coursecontext = \context_course::instance($courseid);
623
            if (!cohort_get_cohort($cohortid, $coursecontext)) {
624
                $error = new lang_string('contextcohortnotallowed', 'cohort', $enrolmentdata['cohortidnumber']);
625
            }
626
        }
627
        return $error;
628
    }
629
 
630
    /**
631
     * Add new instance of enrol plugin with custom settings,
632
     * called when adding new instance manually or when adding new course.
633
     * Used for example on course upload.
634
     *
635
     * Not all plugins support this.
636
     *
637
     * @param stdClass $course Course object
638
     * @param array|null $fields instance fields
639
     * @return int|null id of new instance or null if not supported
640
     */
641
    public function add_custom_instance(stdClass $course, ?array $fields = null): ?int {
642
        return $this->add_instance($course, $fields);
643
    }
644
 
645
 
646
    /**
647
     * Check if enrolment plugin is supported in csv course upload.
648
     *
649
     * @return bool
650
     */
651
    public function is_csv_upload_supported(): bool {
652
        return true;
653
    }
654
 
655
    /**
656
     * Finds matching instances for a given course.
657
     *
658
     * @param array $enrolmentdata enrolment data.
659
     * @param int $courseid Course ID.
660
     * @return stdClass|null Matching instance
661
     */
662
    public function find_instance(array $enrolmentdata, int $courseid): ?stdClass {
663
        global $DB;
664
        $instances = enrol_get_instances($courseid, false);
665
 
666
        $instance = null;
667
        if (isset($enrolmentdata['cohortidnumber']) && isset($enrolmentdata['role'])) {
668
            $cohortid = $DB->get_field('cohort', 'id', ['idnumber' => $enrolmentdata['cohortidnumber']]);
669
            $roleid = $DB->get_field('role', 'id', ['shortname' => $enrolmentdata['role']]);
670
            if ($cohortid && $roleid) {
671
                foreach ($instances as $i) {
672
                    if ($i->enrol == 'cohort' && $i->customint1 == $cohortid && $i->roleid == $roleid) {
673
                        $instance = $i;
674
                        break;
675
                    }
676
                }
677
            }
678
        }
679
        return $instance;
680
    }
681
}
682
 
683
/**
684
 * Prevent removal of enrol roles.
685
 * @param int $itemid
686
 * @param int $groupid
687
 * @param int $userid
688
 * @return bool
689
 */
690
function enrol_cohort_allow_group_member_remove($itemid, $groupid, $userid) {
691
    return false;
692
}
693
 
694
/**
695
 * Create a new group with the cohorts name.
696
 *
697
 * @param int $courseid
698
 * @param int $cohortid
699
 * @return int $groupid Group ID for this cohort.
700
 */
701
function enrol_cohort_create_new_group($courseid, $cohortid) {
702
    global $DB, $CFG;
703
 
704
    require_once($CFG->dirroot . '/group/lib.php');
705
 
706
    $groupname = $DB->get_field('cohort', 'name', array('id' => $cohortid), MUST_EXIST);
707
    $a = new stdClass();
708
    $a->name = $groupname;
709
    $a->increment = '';
710
    $groupname = trim(get_string('defaultgroupnametext', 'enrol_cohort', $a));
711
    $inc = 1;
712
    // Check to see if the cohort group name already exists. Add an incremented number if it does.
713
    while ($DB->record_exists('groups', array('name' => $groupname, 'courseid' => $courseid))) {
714
        $a->increment = '(' . (++$inc) . ')';
715
        $newshortname = trim(get_string('defaultgroupnametext', 'enrol_cohort', $a));
716
        $groupname = $newshortname;
717
    }
718
    // Create a new group for the cohort.
719
    $groupdata = new stdClass();
720
    $groupdata->courseid = $courseid;
721
    $groupdata->name = $groupname;
722
    $groupid = groups_create_group($groupdata);
723
 
724
    return $groupid;
725
}