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
 * Manual enrolment plugin main library file.
19
 *
20
 * @package    enrol_manual
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
class enrol_manual_plugin extends enrol_plugin {
28
 
29
    protected $lasternoller = null;
30
    protected $lasternollerinstanceid = 0;
31
 
32
    public function roles_protected() {
33
        // Users may tweak the roles later.
34
        return false;
35
    }
36
 
37
    public function allow_enrol(stdClass $instance) {
38
        // Users with enrol cap may unenrol other users manually manually.
39
        return true;
40
    }
41
 
42
    public function allow_unenrol(stdClass $instance) {
43
        // Users with unenrol cap may unenrol other users manually manually.
44
        return true;
45
    }
46
 
47
    public function allow_manage(stdClass $instance) {
48
        // Users with manage cap may tweak period and status.
49
        return true;
50
    }
51
 
52
    /**
53
     * Returns link to manual enrol UI if exists.
54
     * Does the access control tests automatically.
55
     *
56
     * @param stdClass $instance
57
     * @return moodle_url
58
     */
59
    public function get_manual_enrol_link($instance) {
60
        $name = $this->get_name();
61
        if ($instance->enrol !== $name) {
62
            throw new coding_exception('invalid enrol instance!');
63
        }
64
 
65
        if (!enrol_is_enabled($name)) {
66
            return NULL;
67
        }
68
 
69
        $context = context_course::instance($instance->courseid, MUST_EXIST);
70
 
71
        if (!has_capability('enrol/manual:enrol', $context)) {
72
            // Note: manage capability not used here because it is used for editing
73
            // of existing enrolments which is not possible here.
74
            return NULL;
75
        }
76
 
77
        return new moodle_url('/enrol/manual/manage.php', array('enrolid'=>$instance->id, 'id'=>$instance->courseid));
78
    }
79
 
80
    /**
81
     * Return true if we can add a new instance to this course.
82
     *
83
     * @param int $courseid
84
     * @return boolean
85
     */
86
    public function can_add_instance($courseid) {
87
        global $DB;
88
 
89
        $context = context_course::instance($courseid, MUST_EXIST);
90
        if (!has_capability('moodle/course:enrolconfig', $context) or !has_capability('enrol/manual:config', $context)) {
91
            return false;
92
        }
93
 
94
        if ($DB->record_exists('enrol', array('courseid'=>$courseid, 'enrol'=>'manual'))) {
95
            // Multiple instances not supported.
96
            return false;
97
        }
98
 
99
        return true;
100
    }
101
 
102
    /**
103
     * Returns edit icons for the page with list of instances.
104
     * @param stdClass $instance
105
     * @return array
106
     */
107
    public function get_action_icons(stdClass $instance) {
108
        global $OUTPUT;
109
 
110
        $context = context_course::instance($instance->courseid);
111
 
112
        $icons = array();
113
        if (has_capability('enrol/manual:enrol', $context) or has_capability('enrol/manual:unenrol', $context)) {
114
            $managelink = new moodle_url("/enrol/manual/manage.php", array('enrolid'=>$instance->id));
115
            $icons[] = $OUTPUT->action_icon($managelink, new pix_icon('t/enrolusers', get_string('enrolusers', 'enrol_manual'), 'core', array('class'=>'iconsmall')));
116
        }
117
 
1441 ariadna 118
        if (has_any_capability(['enrol/manual:config', 'moodle/course:editcoursewelcomemessage'], $context)) {
119
            $linkparams = [
120
                'courseid' => $instance->courseid,
121
                'id' => $instance->id,
122
                'type' => $instance->enrol,
123
            ];
124
            $editlink = new moodle_url('/enrol/editinstance.php', $linkparams);
125
            $icon = new pix_icon('t/edit', get_string('edit'), 'core', ['class' => 'iconsmall']);
126
            $icons[] = $OUTPUT->action_icon($editlink, $icon);
127
        }
128
 
1 efrain 129
        return $icons;
130
    }
131
 
132
    /**
133
     * Add new instance of enrol plugin with default settings.
134
     * @param stdClass $course
135
     * @return int id of new instance, null if can not be created
136
     */
137
    public function add_default_instance($course) {
138
        $expirynotify = $this->get_config('expirynotify', 0);
139
 
140
        $fields = array(
141
            'status'          => $this->get_config('status'),
142
            'roleid'          => $this->get_config('roleid', 0),
143
            'enrolperiod'     => $this->get_config('enrolperiod', 0),
144
            'expirynotify'    => $expirynotify,
145
            'notifyall'       => $expirynotify == 2 ? 1 : 0,
146
            'expirythreshold' => $this->get_config('expirythreshold', 86400),
147
            'customint1' => $this->get_config('sendcoursewelcomemessage'),
148
        );
149
        return $this->add_instance($course, $fields);
150
    }
151
 
152
    /**
153
     * Add new instance of enrol plugin.
154
     * @param stdClass $course
155
     * @param array instance fields
156
     * @return int id of new instance, null if can not be created
157
     */
1441 ariadna 158
    public function add_instance($course, ?array $fields = NULL) {
1 efrain 159
        global $DB;
160
 
161
        if ($DB->record_exists('enrol', array('courseid'=>$course->id, 'enrol'=>'manual'))) {
162
            // only one instance allowed, sorry
163
            return NULL;
164
        }
165
 
166
        return parent::add_instance($course, $fields);
167
    }
168
 
169
    /**
170
     * Update instance of enrol plugin.
171
     * @param stdClass $instance
172
     * @param stdClass $data modified instance fields
173
     * @return boolean
174
     */
175
    public function update_instance($instance, $data) {
176
        global $DB;
177
 
178
        // Delete all other instances, leaving only one.
179
        if ($instances = $DB->get_records('enrol', array('courseid' => $instance->courseid, 'enrol' => 'manual'), 'id ASC')) {
180
            foreach ($instances as $anotherinstance) {
181
                if ($anotherinstance->id != $instance->id) {
182
                    $this->delete_instance($anotherinstance);
183
                }
184
            }
185
        }
186
 
1441 ariadna 187
        // This method is used when configuring the enrolment method, and when only updating the welcome message.
188
        // The 'expirynotify' property won't be set when updating the welcome message.
189
        if (isset($data->expirynotify)) {
190
            $data->notifyall = $data->expirynotify == 2 ? 1 : 0;
191
        }
1 efrain 192
 
193
        return parent::update_instance($instance, $data);
194
    }
195
 
196
    /**
197
     * Returns a button to manually enrol users through the manual enrolment plugin.
198
     *
199
     * By default the first manual enrolment plugin instance available in the course is used.
200
     * If no manual enrolment instances exist within the course then false is returned.
201
     *
202
     * This function also adds a quickenrolment JS ui to the page so that users can be enrolled
203
     * via AJAX.
204
     *
205
     * @param course_enrolment_manager $manager
206
     * @return enrol_user_button
207
     */
208
    public function get_manual_enrol_button(course_enrolment_manager $manager) {
209
        global $CFG, $PAGE;
210
        require_once($CFG->dirroot.'/cohort/lib.php');
211
 
212
        static $called = false;
213
 
214
        $instance = null;
215
        foreach ($manager->get_enrolment_instances() as $tempinstance) {
216
            if ($tempinstance->enrol == 'manual') {
217
                if ($instance === null) {
218
                    $instance = $tempinstance;
219
                }
220
            }
221
        }
222
        if (empty($instance)) {
223
            return false;
224
        }
225
 
226
        $link = $this->get_manual_enrol_link($instance);
227
        if (!$link) {
228
            return false;
229
        }
230
 
231
        $button = new enrol_user_button($link, get_string('enrolusers', 'enrol_manual'), 'get');
232
        $button->class .= ' enrol_manual_plugin';
233
        $button->type = single_button::BUTTON_PRIMARY;
234
 
235
        $context = context_course::instance($instance->courseid);
236
        $arguments = array('contextid' => $context->id);
237
 
238
        if (!$called) {
239
            $called = true;
240
            // Calling the following more than once will cause unexpected results.
241
            $PAGE->requires->js_call_amd('enrol_manual/quickenrolment', 'init', array($arguments));
242
        }
243
 
244
        return $button;
245
    }
246
 
247
    /**
248
     * Sync all meta course links.
249
     *
250
     * @param progress_trace $trace
251
     * @param int $courseid one course, empty mean all
252
     * @return int 0 means ok, 1 means error, 2 means plugin disabled
253
     */
254
    public function sync(progress_trace $trace, $courseid = null) {
255
        global $DB;
256
 
257
        if (!enrol_is_enabled('manual')) {
258
            $trace->finished();
259
            return 2;
260
        }
261
 
262
        // Unfortunately this may take a long time, execution can be interrupted safely here.
263
        core_php_time_limit::raise();
264
        raise_memory_limit(MEMORY_HUGE);
265
 
266
        $trace->output('Verifying manual enrolment expiration...');
267
 
268
        $params = array('now'=>time(), 'useractive'=>ENROL_USER_ACTIVE, 'courselevel'=>CONTEXT_COURSE);
269
        $coursesql = "";
270
        if ($courseid) {
271
            $coursesql = "AND e.courseid = :courseid";
272
            $params['courseid'] = $courseid;
273
        }
274
 
275
        // Deal with expired accounts.
276
        $action = $this->get_config('expiredaction', ENROL_EXT_REMOVED_KEEP);
277
 
278
        if ($action == ENROL_EXT_REMOVED_UNENROL) {
279
            $instances = array();
280
            $sql = "SELECT ue.*, e.courseid, c.id AS contextid
281
                      FROM {user_enrolments} ue
282
                      JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'manual')
283
                      JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
284
                     WHERE ue.timeend > 0 AND ue.timeend < :now
285
                           $coursesql";
286
            $rs = $DB->get_recordset_sql($sql, $params);
287
            foreach ($rs as $ue) {
288
                if (empty($instances[$ue->enrolid])) {
289
                    $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
290
                }
291
                $instance = $instances[$ue->enrolid];
292
                // Always remove all manually assigned roles here, this may break enrol_self roles but we do not want hardcoded hacks here.
293
                role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0), true);
294
                $this->unenrol_user($instance, $ue->userid);
295
                $trace->output("unenrolling expired user $ue->userid from course $instance->courseid", 1);
296
            }
297
            $rs->close();
298
            unset($instances);
299
 
300
        } else if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES or $action == ENROL_EXT_REMOVED_SUSPEND) {
301
            $instances = array();
302
            $sql = "SELECT ue.*, e.courseid, c.id AS contextid
303
                      FROM {user_enrolments} ue
304
                      JOIN {enrol} e ON (e.id = ue.enrolid AND e.enrol = 'manual')
305
                      JOIN {context} c ON (c.instanceid = e.courseid AND c.contextlevel = :courselevel)
306
                     WHERE ue.timeend > 0 AND ue.timeend < :now
307
                           AND ue.status = :useractive
308
                           $coursesql";
309
            $rs = $DB->get_recordset_sql($sql, $params);
310
            foreach ($rs as $ue) {
311
                if (empty($instances[$ue->enrolid])) {
312
                    $instances[$ue->enrolid] = $DB->get_record('enrol', array('id'=>$ue->enrolid));
313
                }
314
                $instance = $instances[$ue->enrolid];
315
                if ($action == ENROL_EXT_REMOVED_SUSPENDNOROLES) {
316
                    // Remove all manually assigned roles here, this may break enrol_self roles but we do not want hardcoded hacks here.
317
                    role_unassign_all(array('userid'=>$ue->userid, 'contextid'=>$ue->contextid, 'component'=>'', 'itemid'=>0), true);
318
                    $this->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
319
                    $trace->output("suspending expired user $ue->userid in course $instance->courseid, roles unassigned", 1);
320
                } else {
321
                    $this->update_user_enrol($instance, $ue->userid, ENROL_USER_SUSPENDED);
322
                    $trace->output("suspending expired user $ue->userid in course $instance->courseid, roles kept", 1);
323
                }
324
            }
325
            $rs->close();
326
            unset($instances);
327
 
328
        } else {
329
            // ENROL_EXT_REMOVED_KEEP means no changes.
330
        }
331
 
332
        $trace->output('...manual enrolment updates finished.');
333
        $trace->finished();
334
 
335
        return 0;
336
    }
337
 
338
    /**
339
     * Returns the user who is responsible for manual enrolments in given instance.
340
     *
341
     * Usually it is the first editing teacher - the person with "highest authority"
342
     * as defined by sort_by_roleassignment_authority() having 'enrol/manual:manage'
343
     * capability.
344
     *
345
     * @param int $instanceid enrolment instance id
346
     * @return stdClass user record
347
     */
348
    protected function get_enroller($instanceid) {
349
        global $DB;
350
 
351
        if ($this->lasternollerinstanceid == $instanceid and $this->lasternoller) {
352
            return $this->lasternoller;
353
        }
354
 
355
        $instance = $DB->get_record('enrol', array('id'=>$instanceid, 'enrol'=>$this->get_name()), '*', MUST_EXIST);
356
        $context = context_course::instance($instance->courseid);
357
 
358
        if ($users = get_enrolled_users($context, 'enrol/manual:manage')) {
359
            $users = sort_by_roleassignment_authority($users, $context);
360
            $this->lasternoller = reset($users);
361
            unset($users);
362
        } else {
363
            $this->lasternoller = parent::get_enroller($instanceid);
364
        }
365
 
366
        $this->lasternollerinstanceid = $instanceid;
367
 
368
        return $this->lasternoller;
369
    }
370
 
371
    /**
372
     * The manual plugin has several bulk operations that can be performed.
373
     * @param course_enrolment_manager $manager
374
     * @return array
375
     */
376
    public function get_bulk_operations(course_enrolment_manager $manager) {
377
        global $CFG;
378
        require_once($CFG->dirroot.'/enrol/manual/locallib.php');
379
        $context = $manager->get_context();
380
        $bulkoperations = array();
381
        if (has_capability("enrol/manual:manage", $context)) {
382
            $bulkoperations['editselectedusers'] = new enrol_manual_editselectedusers_operation($manager, $this);
383
        }
384
        if (has_capability("enrol/manual:unenrol", $context)) {
385
            $bulkoperations['deleteselectedusers'] = new enrol_manual_deleteselectedusers_operation($manager, $this);
386
        }
387
        return $bulkoperations;
388
    }
389
 
390
    /**
391
     * Restore instance and map settings.
392
     *
393
     * @param restore_enrolments_structure_step $step
394
     * @param stdClass $data
395
     * @param stdClass $course
396
     * @param int $oldid
397
     */
398
    public function restore_instance(restore_enrolments_structure_step $step, stdClass $data, $course, $oldid) {
399
        global $DB;
400
        // There is only I manual enrol instance allowed per course.
401
        if ($instances = $DB->get_records('enrol', array('courseid'=>$data->courseid, 'enrol'=>'manual'), 'id')) {
402
            $instance = reset($instances);
403
            $instanceid = $instance->id;
404
        } else {
405
            $instanceid = $this->add_instance($course, (array)$data);
406
        }
407
        $step->set_mapping('enrol', $oldid, $instanceid);
408
    }
409
 
410
    /**
411
     * Restore user enrolment.
412
     *
413
     * @param restore_enrolments_structure_step $step
414
     * @param stdClass $data
415
     * @param stdClass $instance
416
     * @param int $oldinstancestatus
417
     * @param int $userid
418
     */
419
    public function restore_user_enrolment(restore_enrolments_structure_step $step, $data, $instance, $userid, $oldinstancestatus) {
420
        global $DB;
421
 
422
        // Note: this is a bit tricky because other types may be converted to manual enrolments,
423
        //       and manual is restricted to one enrolment per user.
424
 
425
        $ue = $DB->get_record('user_enrolments', array('enrolid'=>$instance->id, 'userid'=>$userid));
426
        $enrol = false;
427
        if ($ue and $ue->status == ENROL_USER_ACTIVE) {
428
            // We do not want to restrict current active enrolments, let's kind of merge the times only.
429
            // This prevents some teacher lockouts too.
430
            if ($data->status == ENROL_USER_ACTIVE) {
431
                if ($data->timestart > $ue->timestart) {
432
                    $data->timestart = $ue->timestart;
433
                    $enrol = true;
434
                }
435
 
436
                if ($data->timeend == 0) {
437
                    if ($ue->timeend != 0) {
438
                        $enrol = true;
439
                    }
440
                } else if ($ue->timeend == 0) {
441
                    $data->timeend = 0;
442
                } else if ($data->timeend < $ue->timeend) {
443
                    $data->timeend = $ue->timeend;
444
                    $enrol = true;
445
                }
446
            }
447
        } else {
448
            if ($instance->status == ENROL_INSTANCE_ENABLED and $oldinstancestatus != ENROL_INSTANCE_ENABLED) {
449
                // Make sure that user enrolments are not activated accidentally,
450
                // we do it only here because it is not expected that enrolments are migrated to other plugins.
451
                $data->status = ENROL_USER_SUSPENDED;
452
            }
453
            $enrol = true;
454
        }
455
 
456
        if ($enrol) {
457
            $this->enrol_user($instance, $userid, null, $data->timestart, $data->timeend, $data->status);
458
        }
459
    }
460
 
461
    /**
462
     * Restore role assignment.
463
     *
464
     * @param stdClass $instance
465
     * @param int $roleid
466
     * @param int $userid
467
     * @param int $contextid
468
     */
469
    public function restore_role_assignment($instance, $roleid, $userid, $contextid) {
470
        // This is necessary only because we may migrate other types to this instance,
471
        // we do not use component in manual or self enrol.
472
        role_assign($roleid, $userid, $contextid, '', 0);
473
    }
474
 
475
    /**
476
     * Restore user group membership.
477
     * @param stdClass $instance
478
     * @param int $groupid
479
     * @param int $userid
480
     */
481
    public function restore_group_member($instance, $groupid, $userid) {
482
        global $CFG;
483
        require_once("$CFG->dirroot/group/lib.php");
484
 
485
        // This might be called when forcing restore as manual enrolments.
486
 
487
        groups_add_member($groupid, $userid);
488
    }
489
 
490
    /**
491
     * Is it possible to delete enrol instance via standard UI?
492
     *
493
     * @param object $instance
494
     * @return bool
495
     */
496
    public function can_delete_instance($instance) {
497
        $context = context_course::instance($instance->courseid);
498
        return has_capability('enrol/manual:config', $context);
499
    }
500
 
501
    /**
502
     * Is it possible to hide/show enrol instance via standard UI?
503
     *
504
     * @param stdClass $instance
505
     * @return bool
506
     */
507
    public function can_hide_show_instance($instance) {
508
        $context = context_course::instance($instance->courseid);
509
        return has_capability('enrol/manual:config', $context);
510
    }
511
 
512
    /**
513
     * Enrol all not enrolled cohort members into course via enrol instance.
514
     *
515
     * @param stdClass $instance
516
     * @param int $cohortid
517
     * @param int $roleid optional role id
518
     * @param int $timestart 0 means unknown
519
     * @param int $timeend 0 means forever
520
     * @param int $status default to ENROL_USER_ACTIVE for new enrolments, no change by default in updates
521
     * @param bool $recovergrades restore grade history
522
     * @return int The number of enrolled cohort users
523
     */
524
    public function enrol_cohort(stdClass $instance, $cohortid, $roleid = null, $timestart = 0, $timeend = 0, $status = null, $recovergrades = null) {
525
        global $DB;
526
        $context = context_course::instance($instance->courseid);
527
        list($esql, $params) = get_enrolled_sql($context);
528
        $sql = "SELECT cm.userid FROM {cohort_members} cm LEFT JOIN ($esql) u ON u.id = cm.userid ".
529
            "WHERE cm.cohortid = :cohortid AND u.id IS NULL";
530
        $params['cohortid'] = $cohortid;
531
        $members = $DB->get_fieldset_sql($sql, $params);
532
        foreach ($members as $userid) {
533
            $this->enrol_user($instance, $userid, $roleid, $timestart, $timeend, $status, $recovergrades);
534
        }
535
        return count($members);
536
    }
537
 
538
    /**
539
     * We are a good plugin and don't invent our own UI/validation code path.
540
     *
541
     * @return boolean
542
     */
543
    public function use_standard_editing_ui() {
544
        return true;
545
    }
546
 
547
    /**
548
     * Return an array of valid options for the status.
549
     *
550
     * @return array
551
     */
552
    protected function get_status_options() {
553
        $options = array(ENROL_INSTANCE_ENABLED  => get_string('yes'),
554
                         ENROL_INSTANCE_DISABLED => get_string('no'));
555
        return $options;
556
    }
557
 
558
    /**
559
     * Return an array of valid options for the roleid.
560
     *
561
     * @param stdClass $instance
562
     * @param context $context
563
     * @return array
564
     */
565
    protected function get_roleid_options($instance, $context) {
566
        if ($instance->id) {
567
            $roles = get_default_enrol_roles($context, $instance->roleid);
568
        } else {
569
            $roles = get_default_enrol_roles($context, $this->get_config('roleid'));
570
        }
571
        return $roles;
572
    }
573
 
574
    /**
575
     * Return an array of valid options for the expirynotify.
576
     *
577
     * @return array
578
     */
579
    protected function get_expirynotify_options() {
580
        $options = array(
581
 
582
            1 => get_string('expirynotifyenroller', 'core_enrol'),
583
            2 => get_string('expirynotifyall', 'core_enrol')
584
        );
585
        return $options;
586
    }
587
 
588
    /**
589
     * Add elements to the edit instance form.
590
     *
591
     * @param stdClass $instance
592
     * @param MoodleQuickForm $mform
593
     * @param context $context
594
     * @return bool
595
     */
596
    public function edit_instance_form($instance, MoodleQuickForm $mform, $context) {
597
 
1441 ariadna 598
        // Main fields.
599
        if (has_capability('enrol/manual:config', $context)) {
600
            $options = $this->get_status_options();
601
            $mform->addElement('select', 'status', get_string('status', 'enrol_manual'), $options);
602
            $mform->addHelpButton('status', 'status', 'enrol_manual');
603
            $mform->setDefault('status', $this->get_config('status'));
1 efrain 604
 
1441 ariadna 605
            $roles = $this->get_roleid_options($instance, $context);
606
            $mform->addElement('select', 'roleid', get_string('defaultrole', 'role'), $roles);
607
            $mform->setDefault('roleid', $this->get_config('roleid'));
1 efrain 608
 
1441 ariadna 609
            $options = ['optional' => true, 'defaultunit' => 86400];
610
            $mform->addElement('duration', 'enrolperiod', get_string('defaultperiod', 'enrol_manual'), $options);
611
            $mform->setDefault('enrolperiod', $this->get_config('enrolperiod'));
612
            $mform->addHelpButton('enrolperiod', 'defaultperiod', 'enrol_manual');
1 efrain 613
 
1441 ariadna 614
            $options = $this->get_expirynotify_options();
615
            $mform->addElement('select', 'expirynotify', get_string('expirynotify', 'core_enrol'), $options);
616
            $mform->addHelpButton('expirynotify', 'expirynotify', 'core_enrol');
1 efrain 617
 
1441 ariadna 618
            $options = ['optional' => false, 'defaultunit' => 86400];
619
            $mform->addElement('duration', 'expirythreshold', get_string('expirythreshold', 'core_enrol'), $options);
620
            $mform->addHelpButton('expirythreshold', 'expirythreshold', 'core_enrol');
621
            $mform->disabledIf('expirythreshold', 'expirynotify', 'eq', 0);
622
        }
1 efrain 623
 
624
        // Course welcome message.
1441 ariadna 625
        if (has_any_capability(['enrol/manual:config', 'moodle/course:editcoursewelcomemessage'], $context)) {
626
            $mform->addElement(
627
                'select',
628
                'customint1',
629
                get_string(
630
                    identifier: 'sendcoursewelcomemessage',
631
                    component: 'core_enrol',
632
                ),
633
                enrol_send_welcome_email_options(),
634
            );
635
            $mform->addHelpButton(
636
                elementname: 'customint1',
1 efrain 637
                identifier: 'sendcoursewelcomemessage',
638
                component: 'core_enrol',
1441 ariadna 639
            );
1 efrain 640
 
1441 ariadna 641
            $options = [
642
                'cols' => '60',
643
                'rows' => '8',
644
            ];
645
            $mform->addElement(
646
                'textarea',
647
                'customtext1',
648
                get_string(
649
                    identifier: 'customwelcomemessage',
650
                    component: 'core_enrol',
651
                ),
652
                $options,
653
            );
654
            $mform->setDefault('customtext1', get_string('customwelcomemessageplaceholder', 'core_enrol'));
655
            $mform->hideIf(
656
                elementname: 'customtext1',
657
                dependenton: 'customint1',
658
                condition: 'eq',
659
                value: ENROL_DO_NOT_SEND_EMAIL,
660
            );
1 efrain 661
 
1441 ariadna 662
            // Static form elements cannot be hidden by hideIf() so we need to add a dummy group.
663
            // See: https://tracker.moodle.org/browse/MDL-66251.
664
            $group[] = $mform->createElement(
665
                'static',
666
                'customwelcomemessage_extra_help',
667
                null,
668
                get_string(
669
                    identifier: 'customwelcomemessage_help',
670
                    component: 'core_enrol',
671
                ),
672
            );
673
            $mform->addGroup($group, 'group_customwelcomemessage_extra_help', '', ' ', false);
674
            $mform->hideIf(
675
                elementname: 'group_customwelcomemessage_extra_help',
676
                dependenton: 'customint1',
677
                condition: 'eq',
678
                value: ENROL_DO_NOT_SEND_EMAIL,
679
            );
680
        }
1 efrain 681
 
1441 ariadna 682
        // Enrolment changes warning.
683
        if (has_capability('enrol/manual:config', $context) && enrol_accessing_via_instance($instance)) {
1 efrain 684
            $warntext = get_string('instanceeditselfwarningtext', 'core_enrol');
685
            $mform->addElement('static', 'selfwarn', get_string('instanceeditselfwarning', 'core_enrol'), $warntext);
686
        }
687
    }
688
 
689
    /**
690
     * Perform custom validation of the data used to edit the instance.
691
     *
692
     * @param array $data array of ("fieldname"=>value) of submitted data
693
     * @param array $files array of uploaded files "element_name"=>tmp_file_path
694
     * @param object $instance The instance loaded from the DB
695
     * @param context $context The context of the instance we are editing
696
     * @return array of "element_name"=>"error_description" if there are errors,
697
     *         or an empty array if everything is OK.
698
     * @return void
699
     */
700
    public function edit_instance_validation($data, $files, $instance, $context) {
701
        $errors = array();
702
 
1441 ariadna 703
        // This method is used when configuring the enrolment method, and when only updating the welcome message.
704
        // The 'expirynotify' key won't be set when updating the welcome message.
705
        if (isset($data['expirynotify']) && $data['expirynotify'] > 0 && $data['expirythreshold'] < DAYSECS) {
1 efrain 706
            $errors['expirythreshold'] = get_string('errorthresholdlow', 'core_enrol');
707
        }
708
 
709
        $validstatus = array_keys($this->get_status_options());
710
        $validroles = array_keys($this->get_roleid_options($instance, $context));
711
        $validexpirynotify = array_keys($this->get_expirynotify_options());
712
 
713
        $tovalidate = array(
714
            'status' => $validstatus,
715
            'roleid' => $validroles,
716
            'enrolperiod' => PARAM_INT,
717
            'expirynotify' => $validexpirynotify,
718
            'expirythreshold' => PARAM_INT
719
        );
720
 
721
        $typeerrors = $this->validate_param_types($data, $tovalidate);
722
        $errors = array_merge($errors, $typeerrors);
723
 
724
        return $errors;
725
    }
726
 
727
    /**
728
     * Check if enrolment plugin is supported in csv course upload.
729
     *
730
     * @return bool
731
     */
732
    public function is_csv_upload_supported(): bool {
733
        return true;
734
    }
735
 
736
    /**
737
     * Finds matching instances for a given course.
738
     *
739
     * @param array $enrolmentdata enrolment data.
740
     * @param int $courseid Course ID.
741
     * @return stdClass|null Matching instance
742
     */
743
    public function find_instance(array $enrolmentdata, int $courseid): ?stdClass {
744
 
745
        $instances = enrol_get_instances($courseid, false);
746
        $instance = null;
747
        foreach ($instances as $i) {
748
            if ($i->enrol == 'manual') {
749
                // There can be only one manual enrol instance so find first available.
750
                $instance = $i;
751
                break;
752
            }
753
        }
754
        return $instance;
755
    }
756
 
757
    /**
758
     * Fill custom fields data for a given enrolment plugin.
759
     *
760
     * @param array $enrolmentdata enrolment data.
761
     * @param int $courseid Course ID.
762
     * @return array Updated enrolment data with custom fields info.
763
     */
764
    public function fill_enrol_custom_fields(array $enrolmentdata, int $courseid): array {
765
        return $enrolmentdata + [
766
            'expirynotify' => 0,
767
            'expirythreshold' => 0,
768
        ];
769
    }
770
 
771
    /**
772
     * Returns defaults for new instances.
773
     *
774
     * @return array
775
     */
776
    public function get_instance_defaults(): array {
777
        $fields['customint1'] = $this->get_config('sendcoursewelcomemessage');
778
        return $fields;
779
    }
780
}
781
 
782
/**
783
 * Serve the manual enrol users form as a fragment.
784
 *
785
 * @param array $args List of named arguments for the fragment loader.
786
 * @return string
787
 */
788
function enrol_manual_output_fragment_enrol_users_form($args) {
789
    $args = (object) $args;
790
    $context = $args->context;
791
    $o = '';
792
 
793
    require_capability('enrol/manual:enrol', $context);
794
    $mform = new enrol_manual_enrol_users_form(null, $args);
795
 
796
    ob_start();
797
    $mform->display();
798
    $o .= ob_get_contents();
799
    ob_end_clean();
800
 
801
    return $o;
802
}