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
 * This file contains the course_enrolment_manager class which is used to interface
19
 * with the functions that exist in enrollib.php in relation to a single course.
20
 *
21
 * @package    core_enrol
22
 * @copyright  2010 Sam Hemelryk
23
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
24
 */
25
 
26
use core_user\fields;
27
 
28
defined('MOODLE_INTERNAL') || die();
29
 
30
/**
31
 * This class provides a targeted tied together means of interfacing the enrolment
32
 * tasks together with a course.
33
 *
34
 * It is provided as a convenience more than anything else.
35
 *
36
 * @copyright 2010 Sam Hemelryk
37
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
38
 */
39
class course_enrolment_manager {
40
 
41
    /**
42
     * The course context
43
     * @var context
44
     */
45
    protected $context;
46
    /**
47
     * The course we are managing enrolments for
48
     * @var stdClass
49
     */
50
    protected $course = null;
51
    /**
52
     * Limits the focus of the manager to one enrolment plugin instance
53
     * @var string
54
     */
55
    protected $instancefilter = null;
56
    /**
57
     * Limits the focus of the manager to users with specified role
58
     * @var int
59
     */
60
    protected $rolefilter = 0;
61
    /**
62
     * Limits the focus of the manager to users who match search string
63
     * @var string
64
     */
65
    protected $searchfilter = '';
66
    /**
67
     * Limits the focus of the manager to users in specified group
68
     * @var int
69
     */
70
    protected $groupfilter = 0;
71
    /**
72
     * Limits the focus of the manager to users who match status active/inactive
73
     * @var int
74
     */
75
    protected $statusfilter = -1;
76
 
77
    /**
78
     * The total number of users enrolled in the course
79
     * Populated by course_enrolment_manager::get_total_users
80
     * @var int
81
     */
82
    protected $totalusers = null;
83
    /**
84
     * An array of users currently enrolled in the course
85
     * Populated by course_enrolment_manager::get_users
86
     * @var array
87
     */
88
    protected $users = array();
89
 
90
    /**
91
     * An array of users who have roles within this course but who have not
92
     * been enrolled in the course
93
     * @var array
94
     */
95
    protected $otherusers = array();
96
 
97
    /**
98
     * The total number of users who hold a role within the course but who
99
     * arn't enrolled.
100
     * @var int
101
     */
102
    protected $totalotherusers = null;
103
 
104
    /**
105
     * The current moodle_page object
106
     * @var moodle_page
107
     */
108
    protected $moodlepage = null;
109
 
110
    /**#@+
111
     * These variables are used to cache the information this class uses
112
     * please never use these directly instead use their get_ counterparts.
113
     * @access private
114
     * @var array
115
     */
116
    private $_instancessql = null;
117
    private $_instances = null;
118
    private $_inames = null;
119
    private $_plugins = null;
120
    private $_allplugins = null;
121
    private $_roles = null;
122
    private $_visibleroles = null;
123
    private $_assignableroles = null;
124
    private $_assignablerolesothers = null;
125
    private $_groups = null;
126
    /**#@-*/
127
 
128
    /**
129
     * Constructs the course enrolment manager
130
     *
131
     * @param moodle_page $moodlepage
132
     * @param stdClass $course
133
     * @param string $instancefilter
134
     * @param int $rolefilter If non-zero, filters to users with specified role
135
     * @param string $searchfilter If non-blank, filters to users with search text
136
     * @param int $groupfilter if non-zero, filter users with specified group
137
     * @param int $statusfilter if not -1, filter users with active/inactive enrollment.
138
     */
139
    public function __construct(moodle_page $moodlepage, $course, $instancefilter = null,
140
            $rolefilter = 0, $searchfilter = '', $groupfilter = 0, $statusfilter = -1) {
141
        $this->moodlepage = $moodlepage;
142
        $this->context = context_course::instance($course->id);
143
        $this->course = $course;
144
        $this->instancefilter = $instancefilter;
145
        $this->rolefilter = $rolefilter;
146
        $this->searchfilter = $searchfilter;
147
        $this->groupfilter = $groupfilter;
148
        $this->statusfilter = $statusfilter;
149
    }
150
 
151
    /**
152
     * Returns the current moodle page
153
     * @return moodle_page
154
     */
155
    public function get_moodlepage() {
156
        return $this->moodlepage;
157
    }
158
 
159
    /**
160
     * Returns the total number of enrolled users in the course.
161
     *
162
     * If a filter was specificed this will be the total number of users enrolled
163
     * in this course by means of that instance.
164
     *
165
     * @global moodle_database $DB
166
     * @return int
167
     */
168
    public function get_total_users() {
169
        global $DB;
170
        if ($this->totalusers === null) {
171
            list($instancessql, $params, $filter) = $this->get_instance_sql();
172
            list($filtersql, $moreparams) = $this->get_filter_sql();
173
            $params += $moreparams;
174
            $sqltotal = "SELECT COUNT(DISTINCT u.id)
175
                           FROM {user} u
176
                           JOIN {user_enrolments} ue ON (ue.userid = u.id  AND ue.enrolid $instancessql)
177
                           JOIN {enrol} e ON (e.id = ue.enrolid)";
178
            if ($this->groupfilter) {
179
                $sqltotal .= " LEFT JOIN ({groups_members} gm JOIN {groups} g ON (g.id = gm.groupid))
180
                                         ON (u.id = gm.userid AND g.courseid = e.courseid)";
181
            }
182
            $sqltotal .= "WHERE $filtersql";
183
            $this->totalusers = (int)$DB->count_records_sql($sqltotal, $params);
184
        }
185
        return $this->totalusers;
186
    }
187
 
188
    /**
189
     * Returns the total number of enrolled users in the course.
190
     *
191
     * If a filter was specificed this will be the total number of users enrolled
192
     * in this course by means of that instance.
193
     *
194
     * @global moodle_database $DB
195
     * @return int
196
     */
197
    public function get_total_other_users() {
198
        global $DB;
199
        if ($this->totalotherusers === null) {
200
            list($ctxcondition, $params) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'ctx');
201
            $params['courseid'] = $this->course->id;
202
            $sql = "SELECT COUNT(DISTINCT u.id)
203
                      FROM {role_assignments} ra
204
                      JOIN {user} u ON u.id = ra.userid
205
                      JOIN {context} ctx ON ra.contextid = ctx.id
206
                 LEFT JOIN (
207
                           SELECT ue.id, ue.userid
208
                             FROM {user_enrolments} ue
209
                        LEFT JOIN {enrol} e ON e.id=ue.enrolid
210
                            WHERE e.courseid = :courseid
211
                         ) ue ON ue.userid=u.id
212
                     WHERE ctx.id $ctxcondition AND
213
                           ue.id IS NULL";
214
            $this->totalotherusers = (int)$DB->count_records_sql($sql, $params);
215
        }
216
        return $this->totalotherusers;
217
    }
218
 
219
    /**
220
     * Gets all of the users enrolled in this course.
221
     *
222
     * If a filter was specified this will be the users who were enrolled
223
     * in this course by means of that instance. If role or search filters were
224
     * specified then these will also be applied.
225
     *
226
     * @global moodle_database $DB
227
     * @param string $sort
228
     * @param string $direction ASC or DESC
229
     * @param int $page First page should be 0
230
     * @param int $perpage Defaults to 25
231
     * @return array
232
     */
233
    public function get_users($sort, $direction='ASC', $page=0, $perpage=25) {
234
        global $DB;
235
        if ($direction !== 'ASC') {
236
            $direction = 'DESC';
237
        }
238
        $key = md5("$sort-$direction-$page-$perpage");
239
        if (!array_key_exists($key, $this->users)) {
240
            list($instancessql, $params, $filter) = $this->get_instance_sql();
241
            list($filtersql, $moreparams) = $this->get_filter_sql();
242
            $params += $moreparams;
243
            $userfields = fields::for_identity($this->get_context())->with_userpic()->excluding('lastaccess');
244
            ['selects' => $fieldselect, 'joins' => $fieldjoin, 'params' => $fieldjoinparams] =
245
                    (array)$userfields->get_sql('u', true, '', '', false);
246
            $params += $fieldjoinparams;
247
            $sql = "SELECT DISTINCT $fieldselect, COALESCE(ul.timeaccess, 0) AS lastcourseaccess
248
                      FROM {user} u
249
                      JOIN {user_enrolments} ue ON (ue.userid = u.id  AND ue.enrolid $instancessql)
250
                      JOIN {enrol} e ON (e.id = ue.enrolid)
251
                           $fieldjoin
252
                 LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = u.id)";
253
            if ($this->groupfilter) {
254
                $sql .= " LEFT JOIN ({groups_members} gm JOIN {groups} g ON (g.id = gm.groupid))
255
                                    ON (u.id = gm.userid AND g.courseid = e.courseid)";
256
            }
257
            $sql .= "WHERE $filtersql
258
                  ORDER BY $sort $direction";
259
            $this->users[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
260
        }
261
        return $this->users[$key];
262
    }
263
 
264
    /**
265
     * Obtains WHERE clause to filter results by defined search and role filter
266
     * (instance filter is handled separately in JOIN clause, see
267
     * get_instance_sql).
268
     *
269
     * @return array Two-element array with SQL and params for WHERE clause
270
     */
271
    protected function get_filter_sql() {
272
        global $DB;
273
 
274
        // Search condition.
275
        // TODO Does not support custom user profile fields (MDL-70456).
276
        $extrafields = fields::get_identity_fields($this->get_context(), false);
277
        list($sql, $params) = users_search_sql($this->searchfilter, 'u', USER_SEARCH_CONTAINS, $extrafields);
278
 
279
        // Role condition.
280
        if ($this->rolefilter) {
281
            // Get context SQL.
282
            $contextids = $this->context->get_parent_context_ids();
283
            $contextids[] = $this->context->id;
284
            list($contextsql, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED);
285
            $params += $contextparams;
286
 
287
            // Role check condition.
288
            $sql .= " AND (SELECT COUNT(1) FROM {role_assignments} ra WHERE ra.userid = u.id " .
289
                    "AND ra.roleid = :roleid AND ra.contextid $contextsql) > 0";
290
            $params['roleid'] = $this->rolefilter;
291
        }
292
 
293
        // Group condition.
294
        if ($this->groupfilter) {
295
            if ($this->groupfilter < 0) {
296
                // Show users who are not in any group.
297
                $sql .= " AND gm.groupid IS NULL";
298
            } else {
299
                $sql .= " AND gm.groupid = :groupid";
300
                $params['groupid'] = $this->groupfilter;
301
            }
302
        }
303
 
304
        // Status condition.
305
        if ($this->statusfilter === ENROL_USER_ACTIVE) {
306
            $sql .= " AND ue.status = :active AND e.status = :enabled AND ue.timestart < :now1
307
                    AND (ue.timeend = 0 OR ue.timeend > :now2)";
308
            $now = round(time(), -2); // rounding helps caching in DB
309
            $params += array('enabled' => ENROL_INSTANCE_ENABLED,
310
                             'active' => ENROL_USER_ACTIVE,
311
                             'now1' => $now,
312
                             'now2' => $now);
313
        } else if ($this->statusfilter === ENROL_USER_SUSPENDED) {
314
            $sql .= " AND (ue.status = :inactive OR e.status = :disabled OR ue.timestart > :now1
315
                    OR (ue.timeend <> 0 AND ue.timeend < :now2))";
316
            $now = round(time(), -2); // rounding helps caching in DB
317
            $params += array('disabled' => ENROL_INSTANCE_DISABLED,
318
                             'inactive' => ENROL_USER_SUSPENDED,
319
                             'now1' => $now,
320
                             'now2' => $now);
321
        }
322
 
323
        return array($sql, $params);
324
    }
325
 
326
    /**
327
     * Gets and array of other users.
328
     *
329
     * Other users are users who have been assigned roles or inherited roles
330
     * within this course but who have not been enrolled in the course
331
     *
332
     * @global moodle_database $DB
333
     * @param string $sort
334
     * @param string $direction
335
     * @param int $page
336
     * @param int $perpage
337
     * @return array
338
     */
339
    public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
340
        global $DB;
341
        if ($direction !== 'ASC') {
342
            $direction = 'DESC';
343
        }
344
        $key = md5("$sort-$direction-$page-$perpage");
345
        if (!array_key_exists($key, $this->otherusers)) {
346
            list($ctxcondition, $params) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'ctx');
347
            $params['courseid'] = $this->course->id;
348
            $params['cid'] = $this->course->id;
349
            $userfields = fields::for_identity($this->get_context())->with_userpic();
350
            ['selects' => $fieldselect, 'joins' => $fieldjoin, 'params' => $fieldjoinparams] =
351
                    (array)$userfields->get_sql('u', true);
352
            $params += $fieldjoinparams;
353
            $sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid,
354
                           coalesce(u.lastaccess,0) AS lastaccess
355
                           $fieldselect
356
                      FROM {role_assignments} ra
357
                      JOIN {user} u ON u.id = ra.userid
358
                      JOIN {context} ctx ON ra.contextid = ctx.id
359
                           $fieldjoin
360
                 LEFT JOIN (
361
                       SELECT ue.id, ue.userid
362
                         FROM {user_enrolments} ue
363
                         JOIN {enrol} e ON e.id = ue.enrolid
364
                        WHERE e.courseid = :courseid
365
                       ) ue ON ue.userid=u.id
366
                     WHERE ctx.id $ctxcondition AND
367
                           ue.id IS NULL
368
                  ORDER BY $sort $direction, ctx.depth DESC";
369
            $this->otherusers[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
370
        }
371
        return $this->otherusers[$key];
372
    }
373
 
374
    /**
375
     * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
376
     *
377
     * @param string $search the search term, if any.
378
     * @param bool $searchanywhere Can the search term be anywhere, or must it be at the start.
379
     * @return array with three elements:
380
     *     string list of fields to SELECT,
381
     *     string possible database joins for user fields
382
     *     string contents of SQL WHERE clause,
383
     *     array query params. Note that the SQL snippets use named parameters.
384
     */
385
    protected function get_basic_search_conditions($search, $searchanywhere) {
386
        global $DB, $CFG;
387
 
388
        // Get custom user field SQL used for querying all the fields we need (identity, name, and
389
        // user picture).
390
        $userfields = fields::for_identity($this->context)->with_name()->with_userpic()
391
                ->excluding('username', 'lastaccess', 'maildisplay');
392
        ['selects' => $fieldselects, 'joins' => $fieldjoins, 'params' => $params, 'mappings' => $mappings] =
393
                (array)$userfields->get_sql('u', true, '', '', false);
394
 
395
        // Searchable fields are only the identity and name ones (not userpic, and without exclusions).
396
        $searchablefields = fields::for_identity($this->context)->with_name();
397
        $searchable = array_fill_keys($searchablefields->get_required_fields(), true);
398
        if (array_key_exists('username', $searchable)) {
399
            // Add the username into the mappings list from the other query, because it was excluded.
400
            $mappings['username'] = 'u.username';
401
        }
402
 
403
        // Add some additional sensible conditions
404
        $tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
405
        $params['guestid'] = $CFG->siteguest;
406
        if (!empty($search)) {
407
            // Include identity and name fields as conditions.
408
            foreach ($mappings as $fieldname => $fieldsql) {
409
                if (array_key_exists($fieldname, $searchable)) {
410
                    $conditions[] = $fieldsql;
411
                }
412
            }
413
            $conditions[] = $DB->sql_fullname('u.firstname', 'u.lastname');
414
            if ($searchanywhere) {
415
                $searchparam = '%' . $search . '%';
416
            } else {
417
                $searchparam = $search . '%';
418
            }
419
            $i = 0;
420
            foreach ($conditions as $key => $condition) {
421
                $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
422
                $params["con{$i}00"] = $searchparam;
423
                $i++;
424
            }
425
            $tests[] = '(' . implode(' OR ', $conditions) . ')';
426
        }
427
        $wherecondition = implode(' AND ', $tests);
428
 
429
        $selects = $fieldselects . ', u.username, u.lastaccess, u.maildisplay';
430
        return [$selects, $fieldjoins, $params, $wherecondition];
431
    }
432
 
433
    /**
434
     * Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
435
     *
436
     * @param string $search the search string, if any.
437
     * @param string $fields the first bit of the SQL when returning some users.
438
     * @param string $countfields fhe first bit of the SQL when counting the users.
439
     * @param string $sql the bulk of the SQL statement.
440
     * @param array $params query parameters.
441
     * @param int $page which page number of the results to show.
442
     * @param int $perpage number of users per page.
443
     * @param int $addedenrollment number of users added to enrollment.
444
     * @param bool $returnexactcount Return the exact total users using count_record or not.
445
     * @return array with two or three elements:
446
     *      int totalusers Number users matching the search. (This element only exist if $returnexactcount was set to true)
447
     *      array users List of user objects returned by the query.
448
     *      boolean moreusers True if there are still more users, otherwise is False.
449
     * @throws dml_exception
450
     */
451
    protected function execute_search_queries($search, $fields, $countfields, $sql, array $params, $page, $perpage,
452
            $addedenrollment = 0, $returnexactcount = false) {
453
        global $DB, $CFG;
454
 
455
        list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
456
        $order = ' ORDER BY ' . $sort;
457
 
458
        $totalusers = 0;
459
        $moreusers = false;
460
        $results = [];
461
 
462
        $availableusers = $DB->get_records_sql($fields . $sql . $order,
463
                array_merge($params, $sortparams), ($page * $perpage) - $addedenrollment, $perpage + 1);
464
        if ($availableusers) {
465
            $totalusers = count($availableusers);
466
            $moreusers = $totalusers > $perpage;
467
 
468
            if ($moreusers) {
469
                // We need to discard the last record.
470
                array_pop($availableusers);
471
            }
472
 
473
            if ($returnexactcount && $moreusers) {
474
                // There is more data. We need to do the exact count.
475
                $totalusers = $DB->count_records_sql($countfields . $sql, $params);
476
            }
477
        }
478
 
479
        $results['users'] = $availableusers;
480
        $results['moreusers'] = $moreusers;
481
 
482
        if ($returnexactcount) {
483
            // Include totalusers in result if $returnexactcount flag is true.
484
            $results['totalusers'] = $totalusers;
485
        }
486
 
487
        return $results;
488
    }
489
 
490
    /**
491
     * Gets an array of the users that can be enrolled in this course.
492
     *
493
     * @global moodle_database $DB
494
     * @param int $enrolid
495
     * @param string $search
496
     * @param bool $searchanywhere
497
     * @param int $page Defaults to 0
498
     * @param int $perpage Defaults to 25
499
     * @param int $addedenrollment Defaults to 0
500
     * @param bool $returnexactcount Return the exact total users using count_record or not.
501
     * @return array with two or three elements:
502
     *      int totalusers Number users matching the search. (This element only exist if $returnexactcount was set to true)
503
     *      array users List of user objects returned by the query.
504
     *      boolean moreusers True if there are still more users, otherwise is False.
505
     * @throws dml_exception
506
     */
507
    public function get_potential_users($enrolid, $search = '', $searchanywhere = false, $page = 0, $perpage = 25,
508
            $addedenrollment = 0, $returnexactcount = false) {
509
        global $DB;
510
 
511
        [$ufields, $joins, $params, $wherecondition] = $this->get_basic_search_conditions($search, $searchanywhere);
512
 
513
        $fields      = 'SELECT '.$ufields;
514
        $countfields = 'SELECT COUNT(1)';
515
        $sql = " FROM {user} u
516
                      $joins
517
            LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
518
                WHERE $wherecondition
519
                      AND ue.id IS NULL";
520
        $params['enrolid'] = $enrolid;
521
 
522
        return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, $addedenrollment,
523
                $returnexactcount);
524
    }
525
 
526
    /**
527
     * Searches other users and returns paginated results
528
     *
529
     * @global moodle_database $DB
530
     * @param string $search
531
     * @param bool $searchanywhere
532
     * @param int $page Starting at 0
533
     * @param int $perpage
534
     * @param bool $returnexactcount Return the exact total users using count_record or not.
535
     * @return array with two or three elements:
536
     *      int totalusers Number users matching the search. (This element only exist if $returnexactcount was set to true)
537
     *      array users List of user objects returned by the query.
538
     *      boolean moreusers True if there are still more users, otherwise is False.
539
     * @throws dml_exception
540
     */
541
    public function search_other_users($search = '', $searchanywhere = false, $page = 0, $perpage = 25, $returnexactcount = false) {
542
        global $DB, $CFG;
543
 
544
        [$ufields, $joins, $params, $wherecondition] = $this->get_basic_search_conditions($search, $searchanywhere);
545
 
546
        $fields      = 'SELECT ' . $ufields;
547
        $countfields = 'SELECT COUNT(u.id)';
548
        $sql   = " FROM {user} u
549
                        $joins
550
              LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid)
551
                  WHERE $wherecondition
552
                    AND ra.id IS NULL";
553
        $params['contextid'] = $this->context->id;
554
 
555
        return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, 0, $returnexactcount);
556
    }
557
 
558
    /**
559
     * Searches through the enrolled users in this course.
560
     *
561
     * @param string $search The search term.
562
     * @param bool $searchanywhere Can the search term be anywhere, or must it be at the start.
563
     * @param int $page Starting at 0.
564
     * @param int $perpage Number of users returned per page.
565
     * @param bool $returnexactcount Return the exact total users using count_record or not.
566
     * @param ?int $contextid Context ID we are in - we might use search on activity level and its group mode can be different from course group mode.
567
     * @return array with two or three elements:
568
     *      int totalusers Number users matching the search. (This element only exist if $returnexactcount was set to true)
569
     *      array users List of user objects returned by the query.
570
     *      boolean moreusers True if there are still more users, otherwise is False.
571
     */
572
    public function search_users(string $search = '', bool $searchanywhere = false, int $page = 0, int $perpage = 25,
573
            bool $returnexactcount = false, ?int $contextid = null) {
574
        global $USER;
575
 
576
        [$ufields, $joins, $params, $wherecondition] = $this->get_basic_search_conditions($search, $searchanywhere);
577
 
578
        if (isset($contextid)) {
579
            // If contextid is set, we need to determine the group mode that should be used (module or course).
580
            [$context, $course, $cm] = get_context_info_array($contextid);
581
            // If cm instance is returned, then use the group mode from the module, otherwise get the course group mode.
582
            $groupmode = $cm ? groups_get_activity_groupmode($cm, $course) : groups_get_course_groupmode($this->course);
583
        } else {
584
            // Otherwise, default to the group mode of the course.
585
            $context = $this->context;
586
            $groupmode = groups_get_course_groupmode($this->course);
587
        }
588
 
589
        if ($groupmode == SEPARATEGROUPS && !has_capability('moodle/site:accessallgroups', $context)) {
590
            $groups = groups_get_all_groups($this->course->id, $USER->id, 0, 'g.id');
591
            $groupids = array_column($groups, 'id');
592
            if (!$groupids) {
593
                return ['totalusers' => 0, 'users' => [], 'moreusers' => false];
594
            }
595
        } else {
596
            $groupids = [];
597
        }
598
 
599
        [$enrolledsql, $enrolledparams] = get_enrolled_sql($context, '', $groupids);
600
 
601
        $fields      = 'SELECT ' . $ufields;
602
        $countfields = 'SELECT COUNT(u.id)';
603
        $sql = " FROM {user} u
604
                      $joins
605
                 JOIN ($enrolledsql) je ON je.id = u.id
606
                WHERE $wherecondition";
607
 
608
        $params = array_merge($params, $enrolledparams);
609
 
610
        return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, 0, $returnexactcount);
611
    }
612
 
613
    /**
614
     * Gets an array containing some SQL to user for when selecting, params for
615
     * that SQL, and the filter that was used in constructing the sql.
616
     *
617
     * @global moodle_database $DB
618
     * @return array
619
     */
620
    protected function get_instance_sql() {
621
        global $DB;
622
        if ($this->_instancessql === null) {
623
            $instances = $this->get_enrolment_instances();
624
            $filter = $this->get_enrolment_filter();
625
            if ($filter && array_key_exists($filter, $instances)) {
626
                $sql = " = :ifilter";
627
                $params = array('ifilter'=>$filter);
628
            } else {
629
                $filter = 0;
630
                if ($instances) {
631
                    list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED);
632
                } else {
633
                    // no enabled instances, oops, we should probably say something
634
                    $sql = "= :never";
635
                    $params = array('never'=>-1);
636
                }
637
            }
638
            $this->instancefilter = $filter;
639
            $this->_instancessql = array($sql, $params, $filter);
640
        }
641
        return $this->_instancessql;
642
    }
643
 
644
    /**
645
     * Returns all of the enrolment instances for this course.
646
     *
647
     * @param bool $onlyenabled Whether to return data from enabled enrolment instance names only.
648
     * @return array
649
     */
650
    public function get_enrolment_instances($onlyenabled = false) {
651
        if ($this->_instances === null) {
652
            $this->_instances = enrol_get_instances($this->course->id, $onlyenabled);
653
        }
654
        return $this->_instances;
655
    }
656
 
657
    /**
658
     * Returns the names for all of the enrolment instances for this course.
659
     *
660
     * @param bool $onlyenabled Whether to return data from enabled enrolment instance names only.
661
     * @return array
662
     */
663
    public function get_enrolment_instance_names($onlyenabled = false) {
664
        if ($this->_inames === null) {
665
            $instances = $this->get_enrolment_instances($onlyenabled);
666
            $plugins = $this->get_enrolment_plugins(false);
667
            foreach ($instances as $key=>$instance) {
668
                if (!isset($plugins[$instance->enrol])) {
669
                    // weird, some broken stuff in plugin
670
                    unset($instances[$key]);
671
                    continue;
672
                }
673
                $this->_inames[$key] = $plugins[$instance->enrol]->get_instance_name($instance);
674
            }
675
        }
676
        return $this->_inames;
677
    }
678
 
679
    /**
680
     * Gets all of the enrolment plugins that are available for this course.
681
     *
682
     * @param bool $onlyenabled return only enabled enrol plugins
683
     * @return array
684
     */
685
    public function get_enrolment_plugins($onlyenabled = true) {
686
        if ($this->_plugins === null) {
687
            $this->_plugins = enrol_get_plugins(true);
688
        }
689
 
690
        if ($onlyenabled) {
691
            return $this->_plugins;
692
        }
693
 
694
        if ($this->_allplugins === null) {
695
            // Make sure we have the same objects in _allplugins and _plugins.
696
            $this->_allplugins = $this->_plugins;
697
            foreach (enrol_get_plugins(false) as $name=>$plugin) {
698
                if (!isset($this->_allplugins[$name])) {
699
                    $this->_allplugins[$name] = $plugin;
700
                }
701
            }
702
        }
703
 
704
        return $this->_allplugins;
705
    }
706
 
707
    /**
708
     * Gets all of the roles this course can contain.
709
     *
710
     * @return array
711
     */
712
    public function get_all_roles() {
713
        if ($this->_roles === null) {
714
            $this->_roles = role_fix_names(get_all_roles($this->context), $this->context);
715
        }
716
        return $this->_roles;
717
    }
718
 
719
    /**
720
     * Gets all of the roles this course can contain.
721
     *
722
     * @return array
723
     */
724
    public function get_viewable_roles() {
725
        if ($this->_visibleroles === null) {
726
            $this->_visibleroles = get_viewable_roles($this->context);
727
        }
728
        return $this->_visibleroles;
729
    }
730
 
731
    /**
732
     * Gets all of the assignable roles for this course.
733
     *
734
     * @return array
735
     */
736
    public function get_assignable_roles($otherusers = false) {
737
        if ($this->_assignableroles === null) {
738
            $this->_assignableroles = get_assignable_roles($this->context, ROLENAME_ALIAS, false); // verifies unassign access control too
739
        }
740
 
741
        if ($otherusers) {
742
            if (!is_array($this->_assignablerolesothers)) {
743
                $this->_assignablerolesothers = array();
744
                list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context, 'moodle/course:view');
745
                foreach ($this->_assignableroles as $roleid=>$role) {
746
                    if (isset($courseviewroles[$roleid])) {
747
                        $this->_assignablerolesothers[$roleid] = $role;
748
                    }
749
                }
750
            }
751
            return $this->_assignablerolesothers;
752
        } else {
753
            return $this->_assignableroles;
754
        }
755
    }
756
 
757
    /**
758
     * Gets all of the assignable roles for this course, wrapped in an array to ensure
759
     * role sort order is not lost during json deserialisation.
760
     *
761
     * @param boolean $otherusers whether to include the assignable roles for other users
762
     * @return array
763
     */
764
    public function get_assignable_roles_for_json($otherusers = false) {
765
        $rolesarray = array();
766
        $assignable = $this->get_assignable_roles($otherusers);
767
        foreach ($assignable as $id => $role) {
768
            $rolesarray[] = array('id' => $id, 'name' => $role);
769
        }
770
        return $rolesarray;
771
    }
772
 
773
    /**
774
     * Gets all of the groups for this course.
775
     *
776
     * @return array
777
     */
778
    public function get_all_groups() {
779
        if ($this->_groups === null) {
780
            $this->_groups = groups_get_all_groups($this->course->id);
781
            foreach ($this->_groups as $gid=>$group) {
782
                $this->_groups[$gid]->name = format_string($group->name);
783
            }
784
        }
785
        return $this->_groups;
786
    }
787
 
788
    /**
789
     * Unenrols a user from the course given the users ue entry
790
     *
791
     * @global moodle_database $DB
792
     * @param stdClass $ue
793
     * @return bool
794
     */
795
    public function unenrol_user($ue) {
796
        global $DB;
797
        list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
798
        if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context)) {
799
            $plugin->unenrol_user($instance, $ue->userid);
800
            return true;
801
        }
802
        return false;
803
    }
804
 
805
    /**
806
     * Given a user enrolment record this method returns the plugin and enrolment
807
     * instance that relate to it.
808
     *
809
     * @param stdClass|int $userenrolment
810
     * @return array array($instance, $plugin)
811
     */
812
    public function get_user_enrolment_components($userenrolment) {
813
        global $DB;
814
        if (is_numeric($userenrolment)) {
815
            $userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
816
        }
817
        $instances = $this->get_enrolment_instances();
818
        $plugins = $this->get_enrolment_plugins(false);
819
        if (!$userenrolment || !isset($instances[$userenrolment->enrolid])) {
820
            return array(false, false);
821
        }
822
        $instance = $instances[$userenrolment->enrolid];
823
        $plugin = $plugins[$instance->enrol];
824
        return array($instance, $plugin);
825
    }
826
 
827
    /**
828
     * Removes an assigned role from a user.
829
     *
830
     * @global moodle_database $DB
831
     * @param int $userid
832
     * @param int $roleid
833
     * @return bool
834
     */
835
    public function unassign_role_from_user($userid, $roleid) {
836
        global $DB;
837
        // Admins may unassign any role, others only those they could assign.
838
        if (!is_siteadmin() and !array_key_exists($roleid, $this->get_assignable_roles())) {
839
            if (defined('AJAX_SCRIPT')) {
840
                throw new moodle_exception('invalidrole');
841
            }
842
            return false;
843
        }
844
        $user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
845
        $ras = $DB->get_records('role_assignments', array('contextid'=>$this->context->id, 'userid'=>$user->id, 'roleid'=>$roleid));
846
        foreach ($ras as $ra) {
847
            if ($ra->component) {
848
                if (strpos($ra->component, 'enrol_') !== 0) {
849
                    continue;
850
                }
851
                if (!$plugin = enrol_get_plugin(substr($ra->component, 6))) {
852
                    continue;
853
                }
854
                if ($plugin->roles_protected()) {
855
                    continue;
856
                }
857
            }
858
            role_unassign($ra->roleid, $ra->userid, $ra->contextid, $ra->component, $ra->itemid);
859
        }
860
        return true;
861
    }
862
 
863
    /**
864
     * Assigns a role to a user.
865
     *
866
     * @param int $roleid
867
     * @param int $userid
868
     * @return int|false
869
     */
870
    public function assign_role_to_user($roleid, $userid) {
871
        require_capability('moodle/role:assign', $this->context);
872
        if (!array_key_exists($roleid, $this->get_assignable_roles())) {
873
            if (defined('AJAX_SCRIPT')) {
874
                throw new moodle_exception('invalidrole');
875
            }
876
            return false;
877
        }
878
        return role_assign($roleid, $userid, $this->context->id, '', NULL);
879
    }
880
 
881
    /**
882
     * Adds a user to a group
883
     *
884
     * @param stdClass $user
885
     * @param int $groupid
886
     * @return bool
887
     */
888
    public function add_user_to_group($user, $groupid) {
889
        require_capability('moodle/course:managegroups', $this->context);
890
        $group = $this->get_group($groupid);
891
        if (!$group) {
892
            return false;
893
        }
894
        return groups_add_member($group->id, $user->id);
895
    }
896
 
897
    /**
898
     * Removes a user from a group
899
     *
900
     * @global moodle_database $DB
901
     * @param StdClass $user
902
     * @param int $groupid
903
     * @return bool
904
     */
905
    public function remove_user_from_group($user, $groupid) {
906
        global $DB;
907
        require_capability('moodle/course:managegroups', $this->context);
908
        $group = $this->get_group($groupid);
909
        if (!groups_remove_member_allowed($group, $user)) {
910
            return false;
911
        }
912
        if (!$group) {
913
            return false;
914
        }
915
        return groups_remove_member($group, $user);
916
    }
917
 
918
    /**
919
     * Gets the requested group
920
     *
921
     * @param int $groupid
922
     * @return stdClass|int
923
     */
924
    public function get_group($groupid) {
925
        $groups = $this->get_all_groups();
926
        if (!array_key_exists($groupid, $groups)) {
927
            return false;
928
        }
929
        return $groups[$groupid];
930
    }
931
 
932
    /**
933
     * Edits an enrolment
934
     *
935
     * @param stdClass $userenrolment
936
     * @param stdClass $data
937
     * @return bool
938
     */
939
    public function edit_enrolment($userenrolment, $data) {
940
        //Only allow editing if the user has the appropriate capability
941
        //Already checked in /user/index.php but checking again in case this function is called from elsewhere
942
        list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
943
        if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context)) {
944
            if (!isset($data->status)) {
945
                $data->status = $userenrolment->status;
946
            }
947
            $plugin->update_user_enrol($instance, $userenrolment->userid, $data->status, $data->timestart, $data->timeend);
948
            return true;
949
        }
950
        return false;
951
    }
952
 
953
    /**
954
     * Returns the current enrolment filter that is being applied by this class
955
     * @return string
956
     */
957
    public function get_enrolment_filter() {
958
        return $this->instancefilter;
959
    }
960
 
961
    /**
962
     * Gets the roles assigned to this user that are applicable for this course.
963
     *
964
     * @param int $userid
965
     * @return array
966
     */
967
    public function get_user_roles($userid) {
968
        $roles = array();
969
        $ras = get_user_roles($this->context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
970
        $plugins = $this->get_enrolment_plugins(false);
971
        foreach ($ras as $ra) {
972
            if ($ra->contextid != $this->context->id) {
973
                if (!array_key_exists($ra->roleid, $roles)) {
974
                    $roles[$ra->roleid] = null;
975
                }
976
                // higher ras, course always takes precedence
977
                continue;
978
            }
979
            if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) {
980
                continue;
981
            }
982
            $changeable = true;
983
            if ($ra->component) {
984
                $changeable = false;
985
                if (strpos($ra->component, 'enrol_') === 0) {
986
                    $plugin = substr($ra->component, 6);
987
                    if (isset($plugins[$plugin])) {
988
                        $changeable = !$plugins[$plugin]->roles_protected();
989
                    }
990
                }
991
            }
992
 
993
            $roles[$ra->roleid] = $changeable;
994
        }
995
        return $roles;
996
    }
997
 
998
    /**
999
     * Gets the enrolments this user has in the course - including all suspended plugins and instances.
1000
     *
1001
     * @global moodle_database $DB
1002
     * @param int $userid
1003
     * @return array
1004
     */
1005
    public function get_user_enrolments($userid) {
1006
        global $DB;
1007
        list($instancessql, $params, $filter) = $this->get_instance_sql();
1008
        $params['userid'] = $userid;
1009
        $userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
1010
        $instances = $this->get_enrolment_instances();
1011
        $plugins = $this->get_enrolment_plugins(false);
1012
        $inames = $this->get_enrolment_instance_names();
1013
        foreach ($userenrolments as &$ue) {
1014
            $ue->enrolmentinstance     = $instances[$ue->enrolid];
1015
            $ue->enrolmentplugin       = $plugins[$ue->enrolmentinstance->enrol];
1016
            $ue->enrolmentinstancename = $inames[$ue->enrolmentinstance->id];
1017
        }
1018
        return $userenrolments;
1019
    }
1020
 
1021
    /**
1022
     * Gets the groups this user belongs to
1023
     *
1024
     * @param int $userid
1025
     * @return array
1026
     */
1027
    public function get_user_groups($userid) {
1028
        return groups_get_all_groups($this->course->id, $userid, 0, 'g.id');
1029
    }
1030
 
1031
    /**
1032
     * Retursn an array of params that would go into the URL to return to this
1033
     * exact page.
1034
     *
1035
     * @return array
1036
     */
1037
    public function get_url_params() {
1038
        $args = array(
1039
            'id' => $this->course->id
1040
        );
1041
        if (!empty($this->instancefilter)) {
1042
            $args['ifilter'] = $this->instancefilter;
1043
        }
1044
        if (!empty($this->rolefilter)) {
1045
            $args['role'] = $this->rolefilter;
1046
        }
1047
        if ($this->searchfilter !== '') {
1048
            $args['search'] = $this->searchfilter;
1049
        }
1050
        if (!empty($this->groupfilter)) {
1051
            $args['filtergroup'] = $this->groupfilter;
1052
        }
1053
        if ($this->statusfilter !== -1) {
1054
            $args['status'] = $this->statusfilter;
1055
        }
1056
        return $args;
1057
    }
1058
 
1059
    /**
1060
     * Returns the course this object is managing enrolments for
1061
     *
1062
     * @return stdClass
1063
     */
1064
    public function get_course() {
1065
        return $this->course;
1066
    }
1067
 
1068
    /**
1069
     * Returns the course context
1070
     *
1071
     * @return context
1072
     */
1073
    public function get_context() {
1074
        return $this->context;
1075
    }
1076
 
1077
    /**
1078
     * Gets an array of other users in this course ready for display.
1079
     *
1080
     * Other users are users who have been assigned or inherited roles within this
1081
     * course but have not been enrolled.
1082
     *
1083
     * @param core_enrol_renderer $renderer
1084
     * @param moodle_url $pageurl
1085
     * @param string $sort
1086
     * @param string $direction ASC | DESC
1087
     * @param int $page Starting from 0
1088
     * @param int $perpage
1089
     * @return array
1090
     */
1091
    public function get_other_users_for_display(core_enrol_renderer $renderer, moodle_url $pageurl, $sort, $direction, $page, $perpage) {
1092
 
1093
        $userroles = $this->get_other_users($sort, $direction, $page, $perpage);
1094
        $roles = $this->get_all_roles();
1095
        $plugins = $this->get_enrolment_plugins(false);
1096
 
1097
        $context    = $this->get_context();
1098
        $now = time();
1099
        // TODO Does not support custom user profile fields (MDL-70456).
1100
        $extrafields = fields::get_identity_fields($context, false);
1101
 
1102
        $users = array();
1103
        foreach ($userroles as $userrole) {
1104
            $contextid = $userrole->contextid;
1105
            unset($userrole->contextid); // This would collide with user avatar.
1106
            if (!array_key_exists($userrole->id, $users)) {
1107
                $users[$userrole->id] = $this->prepare_user_for_display($userrole, $extrafields, $now);
1108
            }
1109
            $a = new stdClass;
1110
            $a->role = $roles[$userrole->roleid]->localname;
1111
            if ($contextid == $this->context->id) {
1112
                $changeable = true;
1113
                if ($userrole->component) {
1114
                    $changeable = false;
1115
                    if (strpos($userrole->component, 'enrol_') === 0) {
1116
                        $plugin = substr($userrole->component, 6);
1117
                        if (isset($plugins[$plugin])) {
1118
                            $changeable = !$plugins[$plugin]->roles_protected();
1119
                        }
1120
                    }
1121
                }
1122
                $roletext = get_string('rolefromthiscourse', 'enrol', $a);
1123
            } else {
1124
                $changeable = false;
1125
                switch ($userrole->contextlevel) {
1126
                    case CONTEXT_COURSE :
1127
                        // Meta course
1128
                        $roletext = get_string('rolefrommetacourse', 'enrol', $a);
1129
                        break;
1130
                    case CONTEXT_COURSECAT :
1131
                        $roletext = get_string('rolefromcategory', 'enrol', $a);
1132
                        break;
1133
                    case CONTEXT_SYSTEM:
1134
                    default:
1135
                        $roletext = get_string('rolefromsystem', 'enrol', $a);
1136
                        break;
1137
                }
1138
            }
1139
            if (!isset($users[$userrole->id]['roles'])) {
1140
                $users[$userrole->id]['roles'] = array();
1141
            }
1142
            $users[$userrole->id]['roles'][$userrole->roleid] = array(
1143
                'text' => $roletext,
1144
                'unchangeable' => !$changeable
1145
            );
1146
        }
1147
        return $users;
1148
    }
1149
 
1150
    /**
1151
     * Gets an array of users for display, this includes minimal user information
1152
     * as well as minimal information on the users roles, groups, and enrolments.
1153
     *
1154
     * @param core_enrol_renderer $renderer
1155
     * @param moodle_url $pageurl
1156
     * @param int $sort
1157
     * @param string $direction ASC or DESC
1158
     * @param int $page
1159
     * @param int $perpage
1160
     * @return array
1161
     */
1162
    public function get_users_for_display(course_enrolment_manager $manager, $sort, $direction, $page, $perpage) {
1163
        $pageurl = $manager->get_moodlepage()->url;
1164
        $users = $this->get_users($sort, $direction, $page, $perpage);
1165
 
1166
        $now = time();
1167
        $straddgroup = get_string('addgroup', 'group');
1168
        $strunenrol = get_string('unenrol', 'enrol');
1169
        $stredit = get_string('edit');
1170
 
1171
        $visibleroles   = $this->get_viewable_roles();
1172
        $assignable = $this->get_assignable_roles();
1173
        $allgroups  = $this->get_all_groups();
1174
        $context    = $this->get_context();
1175
        $canmanagegroups = has_capability('moodle/course:managegroups', $context);
1176
 
1177
        $url = new moodle_url($pageurl, $this->get_url_params());
1178
        // TODO Does not support custom user profile fields (MDL-70456).
1179
        $extrafields = fields::get_identity_fields($context, false);
1180
 
1181
        $enabledplugins = $this->get_enrolment_plugins(true);
1182
 
1183
        $userdetails = array();
1184
        foreach ($users as $user) {
1185
            $details = $this->prepare_user_for_display($user, $extrafields, $now);
1186
 
1187
            // Roles
1188
            $details['roles'] = array();
1189
            foreach ($this->get_user_roles($user->id) as $rid=>$rassignable) {
1190
                $unchangeable = !$rassignable;
1191
                if (!is_siteadmin() and !isset($assignable[$rid])) {
1192
                    $unchangeable = true;
1193
                }
1194
 
1195
                if (isset($visibleroles[$rid])) {
1196
                    $label = $visibleroles[$rid];
1197
                } else {
1198
                    $label = get_string('novisibleroles', 'role');
1199
                    $unchangeable = true;
1200
                }
1201
 
1202
                $details['roles'][$rid] = array('text' => $label, 'unchangeable' => $unchangeable);
1203
            }
1204
 
1205
            // Users
1206
            $usergroups = $this->get_user_groups($user->id);
1207
            $details['groups'] = array();
1208
            foreach($usergroups as $gid=>$unused) {
1209
                $details['groups'][$gid] = $allgroups[$gid]->name;
1210
            }
1211
 
1212
            // Enrolments
1213
            $details['enrolments'] = array();
1214
            foreach ($this->get_user_enrolments($user->id) as $ue) {
1215
                if (!isset($enabledplugins[$ue->enrolmentinstance->enrol])) {
1216
                    $details['enrolments'][$ue->id] = array(
1217
                        'text' => $ue->enrolmentinstancename,
1218
                        'period' => null,
1219
                        'dimmed' =>  true,
1220
                        'actions' => array()
1221
                    );
1222
                    continue;
1223
                } else if ($ue->timestart and $ue->timeend) {
1224
                    $period = get_string('periodstartend', 'enrol', array('start'=>userdate($ue->timestart), 'end'=>userdate($ue->timeend)));
1225
                    $periodoutside = ($ue->timestart && $ue->timeend && ($now < $ue->timestart || $now > $ue->timeend));
1226
                } else if ($ue->timestart) {
1227
                    $period = get_string('periodstart', 'enrol', userdate($ue->timestart));
1228
                    $periodoutside = ($ue->timestart && $now < $ue->timestart);
1229
                } else if ($ue->timeend) {
1230
                    $period = get_string('periodend', 'enrol', userdate($ue->timeend));
1231
                    $periodoutside = ($ue->timeend && $now > $ue->timeend);
1232
                } else {
1233
                    // If there is no start or end show when user was enrolled.
1234
                    $period = get_string('periodnone', 'enrol', userdate($ue->timecreated));
1235
                    $periodoutside = false;
1236
                }
1237
                $details['enrolments'][$ue->id] = array(
1238
                    'text' => $ue->enrolmentinstancename,
1239
                    'period' => $period,
1240
                    'dimmed' =>  ($periodoutside or $ue->status != ENROL_USER_ACTIVE or $ue->enrolmentinstance->status != ENROL_INSTANCE_ENABLED),
1241
                    'actions' => $ue->enrolmentplugin->get_user_enrolment_actions($manager, $ue)
1242
                );
1243
            }
1244
            $userdetails[$user->id] = $details;
1245
        }
1246
        return $userdetails;
1247
    }
1248
 
1249
    /**
1250
     * Prepare a user record for display
1251
     *
1252
     * This function is called by both {@link get_users_for_display} and {@link get_other_users_for_display} to correctly
1253
     * prepare user fields for display
1254
     *
1255
     * Please note that this function does not check capability for moodle/coures:viewhiddenuserfields
1256
     *
1257
     * @param object $user The user record
1258
     * @param array $extrafields The list of fields as returned from \core_user\fields::get_identity_fields used to determine which
1259
     * additional fields may be displayed
1260
     * @param int $now The time used for lastaccess calculation
1261
     * @return array The fields to be displayed including userid, courseid, picture, firstname, lastcourseaccess, lastaccess and any
1262
     * additional fields from $extrafields
1263
     */
1264
    private function prepare_user_for_display($user, $extrafields, $now) {
1265
        $details = array(
1266
            'userid'              => $user->id,
1267
            'courseid'            => $this->get_course()->id,
1268
            'picture'             => new user_picture($user),
1269
            'userfullnamedisplay' => fullname($user, has_capability('moodle/site:viewfullnames', $this->get_context())),
1270
            'lastaccess'          => get_string('never'),
1271
            'lastcourseaccess'    => get_string('never'),
1272
        );
1273
 
1274
        foreach ($extrafields as $field) {
1275
            $details[$field] = s($user->{$field});
1276
        }
1277
 
1278
        // Last time user has accessed the site.
1279
        if (!empty($user->lastaccess)) {
1280
            $details['lastaccess'] = format_time($now - $user->lastaccess);
1281
        }
1282
 
1283
        // Last time user has accessed the course.
1284
        if (!empty($user->lastcourseaccess)) {
1285
            $details['lastcourseaccess'] = format_time($now - $user->lastcourseaccess);
1286
        }
1287
        return $details;
1288
    }
1289
 
1290
    public function get_manual_enrol_buttons() {
1291
        $plugins = $this->get_enrolment_plugins(true); // Skip disabled plugins.
1292
        $buttons = array();
1293
        foreach ($plugins as $plugin) {
1294
            $newbutton = $plugin->get_manual_enrol_button($this);
1295
            if (is_array($newbutton)) {
1296
                $buttons += $newbutton;
1297
            } else if ($newbutton instanceof enrol_user_button) {
1298
                $buttons[] = $newbutton;
1299
            }
1300
        }
1301
        return $buttons;
1302
    }
1303
 
1304
    public function has_instance($enrolpluginname) {
1305
        // Make sure manual enrolments instance exists
1306
        foreach ($this->get_enrolment_instances() as $instance) {
1307
            if ($instance->enrol == $enrolpluginname) {
1308
                return true;
1309
            }
1310
        }
1311
        return false;
1312
    }
1313
 
1314
    /**
1315
     * Returns the enrolment plugin that the course manager was being filtered to.
1316
     *
1317
     * If no filter was being applied then this function returns false.
1318
     *
1319
     * @return enrol_plugin
1320
     */
1321
    public function get_filtered_enrolment_plugin() {
1322
        $instances = $this->get_enrolment_instances();
1323
        $plugins = $this->get_enrolment_plugins(false);
1324
 
1325
        if (empty($this->instancefilter) || !array_key_exists($this->instancefilter, $instances)) {
1326
            return false;
1327
        }
1328
 
1329
        $instance = $instances[$this->instancefilter];
1330
        return $plugins[$instance->enrol];
1331
    }
1332
 
1333
    /**
1334
     * Returns and array of users + enrolment details.
1335
     *
1336
     * Given an array of user id's this function returns and array of user enrolments for those users
1337
     * as well as enough user information to display the users name and picture for each enrolment.
1338
     *
1339
     * @global moodle_database $DB
1340
     * @param array $userids
1341
     * @return array
1342
     */
1343
    public function get_users_enrolments(array $userids) {
1344
        global $DB;
1345
 
1346
        $instances = $this->get_enrolment_instances();
1347
        $plugins = $this->get_enrolment_plugins(false);
1348
 
1349
        if  (!empty($this->instancefilter)) {
1350
            $instancesql = ' = :instanceid';
1351
            $instanceparams = array('instanceid' => $this->instancefilter);
1352
        } else {
1353
            list($instancesql, $instanceparams) = $DB->get_in_or_equal(array_keys($instances), SQL_PARAMS_NAMED, 'instanceid0000');
1354
        }
1355
 
1356
        $userfieldsapi = \core_user\fields::for_userpic();
1357
        $userfields = $userfieldsapi->get_sql('u', false, '', '', false)->selects;
1358
        list($idsql, $idparams) = $DB->get_in_or_equal($userids, SQL_PARAMS_NAMED, 'userid0000');
1359
 
1360
        list($sort, $sortparams) = users_order_by_sql('u');
1361
 
1362
        $sql = "SELECT ue.id AS ueid, ue.status, ue.enrolid, ue.userid, ue.timestart, ue.timeend, ue.modifierid, ue.timecreated, ue.timemodified, $userfields
1363
                  FROM {user_enrolments} ue
1364
             LEFT JOIN {user} u ON u.id = ue.userid
1365
                 WHERE ue.enrolid $instancesql AND
1366
                       u.id $idsql
1367
              ORDER BY $sort";
1368
 
1369
        $rs = $DB->get_recordset_sql($sql, $idparams + $instanceparams + $sortparams);
1370
        $users = array();
1371
        foreach ($rs as $ue) {
1372
            $user = user_picture::unalias($ue);
1373
            $ue->id = $ue->ueid;
1374
            unset($ue->ueid);
1375
            if (!array_key_exists($user->id, $users)) {
1376
                $user->enrolments = array();
1377
                $users[$user->id] = $user;
1378
            }
1379
            $ue->enrolmentinstance = $instances[$ue->enrolid];
1380
            $ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
1381
            $users[$user->id]->enrolments[$ue->id] = $ue;
1382
        }
1383
        $rs->close();
1384
        return $users;
1385
    }
1386
}
1387
 
1388
/**
1389
 * A button that is used to enrol users in a course
1390
 *
1391
 * @copyright 2010 Sam Hemelryk
1392
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1393
 */
1394
class enrol_user_button extends single_button {
1395
 
1396
    /**
1397
     * An array containing JS YUI modules required by this button
1398
     * @var array
1399
     */
1400
    protected $jsyuimodules = array();
1401
 
1402
    /**
1403
     * An array containing JS initialisation calls required by this button
1404
     * @var array
1405
     */
1406
    protected $jsinitcalls = array();
1407
 
1408
    /**
1409
     * An array strings required by JS for this button
1410
     * @var array
1411
     */
1412
    protected $jsstrings = array();
1413
 
1414
    /**
1415
     * Initialises the new enrol_user_button
1416
     *
1417
     * @staticvar int $count The number of enrol user buttons already created
1418
     * @param moodle_url $url
1419
     * @param string $label The text to display in the button
1420
     * @param string $method Either post or get
1421
     */
1422
    public function __construct(moodle_url $url, $label, $method = 'post') {
1423
        static $count = 0;
1424
        $count ++;
1425
        parent::__construct($url, $label, $method);
1426
        $this->class = 'singlebutton enrolusersbutton';
1427
        $this->formid = 'enrolusersbutton-'.$count;
1428
    }
1429
 
1430
    /**
1431
     * Adds a YUI module call that will be added to the page when the button is used.
1432
     *
1433
     * @param string|array $modules One or more modules to require
1434
     * @param string $function The JS function to call
1435
     * @param array $arguments An array of arguments to pass to the function
1436
     * @param string $galleryversion Deprecated: The gallery version to use
1437
     * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1438
     */
1439
    public function require_yui_module($modules, $function, array $arguments = null, $galleryversion = null, $ondomready = false) {
1440
        if ($galleryversion != null) {
1441
            debugging('The galleryversion parameter to yui_module has been deprecated since Moodle 2.3.', DEBUG_DEVELOPER);
1442
        }
1443
 
1444
        $js = new stdClass;
1445
        $js->modules = (array)$modules;
1446
        $js->function = $function;
1447
        $js->arguments = $arguments;
1448
        $js->ondomready = $ondomready;
1449
        $this->jsyuimodules[] = $js;
1450
    }
1451
 
1452
    /**
1453
     * Adds a JS initialisation call to the page when the button is used.
1454
     *
1455
     * @param string $function The function to call
1456
     * @param array $extraarguments An array of arguments to pass to the function
1457
     * @param bool $ondomready If true the call is postponed until the DOM is finished loading
1458
     * @param array $module A module definition
1459
     */
1460
    public function require_js_init_call($function, array $extraarguments = null, $ondomready = false, array $module = null) {
1461
        $js = new stdClass;
1462
        $js->function = $function;
1463
        $js->extraarguments = $extraarguments;
1464
        $js->ondomready = $ondomready;
1465
        $js->module = $module;
1466
        $this->jsinitcalls[] = $js;
1467
    }
1468
 
1469
    /**
1470
     * Requires strings for JS that will be loaded when the button is used.
1471
     *
1472
     * @param type $identifiers
1473
     * @param string $component
1474
     * @param mixed $a
1475
     */
1476
    public function strings_for_js($identifiers, $component = 'moodle', $a = null) {
1477
        $string = new stdClass;
1478
        $string->identifiers = (array)$identifiers;
1479
        $string->component = $component;
1480
        $string->a = $a;
1481
        $this->jsstrings[] = $string;
1482
    }
1483
 
1484
    /**
1485
     * Initialises the JS that is required by this button
1486
     *
1487
     * @param moodle_page $page
1488
     */
1489
    public function initialise_js(moodle_page $page) {
1490
        foreach ($this->jsyuimodules as $js) {
1491
            $page->requires->yui_module($js->modules, $js->function, $js->arguments, null, $js->ondomready);
1492
        }
1493
        foreach ($this->jsinitcalls as $js) {
1494
            $page->requires->js_init_call($js->function, $js->extraarguments, $js->ondomready, $js->module);
1495
        }
1496
        foreach ($this->jsstrings as $string) {
1497
            $page->requires->strings_for_js($string->identifiers, $string->component, $string->a);
1498
        }
1499
    }
1500
}
1501
 
1502
/**
1503
 * User enrolment action
1504
 *
1505
 * This class is used to manage a renderable ue action such as editing an user enrolment or deleting
1506
 * a user enrolment.
1507
 *
1508
 * @copyright  2011 Sam Hemelryk
1509
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1510
 */
1511
class user_enrolment_action implements renderable {
1512
 
1513
    /**
1514
     * The icon to display for the action
1515
     * @var pix_icon
1516
     */
1517
    protected $icon;
1518
 
1519
    /**
1520
     * The title for the action
1521
     * @var string
1522
     */
1523
    protected $title;
1524
 
1525
    /**
1526
     * The URL to the action
1527
     * @var moodle_url
1528
     */
1529
    protected $url;
1530
 
1531
    /**
1532
     * An array of HTML attributes
1533
     * @var array
1534
     */
1535
    protected $attributes = array();
1536
 
1537
    /**
1538
     * Constructor
1539
     * @param pix_icon $icon
1540
     * @param string $title
1541
     * @param moodle_url $url
1542
     * @param array $attributes
1543
     */
1544
    public function __construct(pix_icon $icon, $title, $url, array $attributes = null) {
1545
        $this->icon = $icon;
1546
        $this->title = $title;
1547
        $this->url = new moodle_url($url);
1548
        if (!empty($attributes)) {
1549
            $this->attributes = $attributes;
1550
        }
1551
        $this->attributes['title'] = $title;
1552
    }
1553
 
1554
    /**
1555
     * Returns the icon for this action
1556
     * @return pix_icon
1557
     */
1558
    public function get_icon() {
1559
        return $this->icon;
1560
    }
1561
 
1562
    /**
1563
     * Returns the title for this action
1564
     * @return string
1565
     */
1566
    public function get_title() {
1567
        return $this->title;
1568
    }
1569
 
1570
    /**
1571
     * Returns the URL for this action
1572
     * @return moodle_url
1573
     */
1574
    public function get_url() {
1575
        return $this->url;
1576
    }
1577
 
1578
    /**
1579
     * Returns the attributes to use for this action
1580
     * @return array
1581
     */
1582
    public function get_attributes() {
1583
        return $this->attributes;
1584
    }
1585
}
1586
 
1587
class enrol_ajax_exception extends moodle_exception {
1588
    /**
1589
     * Constructor
1590
     * @param string $errorcode The name of the string from error.php to print
1591
     * @param string $module name of module
1592
     * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
1593
     * @param object $a Extra words and phrases that might be required in the error string
1594
     * @param string $debuginfo optional debugging information
1595
     */
1596
    public function __construct($errorcode, $link = '', $a = NULL, $debuginfo = null) {
1597
        parent::__construct($errorcode, 'enrol', $link, $a, $debuginfo);
1598
    }
1599
}
1600
 
1601
/**
1602
 * This class is used to manage a bulk operations for enrolment plugins.
1603
 *
1604
 * @copyright 2011 Sam Hemelryk
1605
 * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1606
 */
1607
abstract class enrol_bulk_enrolment_operation {
1608
 
1609
    /**
1610
     * The course enrolment manager
1611
     * @var course_enrolment_manager
1612
     */
1613
    protected $manager;
1614
 
1615
    /**
1616
     * The enrolment plugin to which this operation belongs
1617
     * @var enrol_plugin
1618
     */
1619
    protected $plugin;
1620
 
1621
    /**
1622
     * Contructor
1623
     * @param course_enrolment_manager $manager
1624
     * @param stdClass $plugin
1625
     */
1626
    public function __construct(course_enrolment_manager $manager, enrol_plugin $plugin = null) {
1627
        $this->manager = $manager;
1628
        $this->plugin = $plugin;
1629
    }
1630
 
1631
    /**
1632
     * Returns a moodleform used for this operation, or false if no form is required and the action
1633
     * should be immediatly processed.
1634
     *
1635
     * @param moodle_url|string $defaultaction
1636
     * @param mixed $defaultcustomdata
1637
     * @return enrol_bulk_enrolment_change_form|moodleform|false
1638
     */
1639
    public function get_form($defaultaction = null, $defaultcustomdata = null) {
1640
        return false;
1641
    }
1642
 
1643
    /**
1644
     * Returns the title to use for this bulk operation
1645
     *
1646
     * @return string
1647
     */
1648
    abstract public function get_title();
1649
 
1650
    /**
1651
     * Returns the identifier for this bulk operation.
1652
     * This should be the same identifier used by the plugins function when returning
1653
     * all of its bulk operations.
1654
     *
1655
     * @return string
1656
     */
1657
    abstract public function get_identifier();
1658
 
1659
    /**
1660
     * Processes the bulk operation on the given users
1661
     *
1662
     * @param course_enrolment_manager $manager
1663
     * @param array $users
1664
     * @param stdClass $properties
1665
     */
1666
    abstract public function process(course_enrolment_manager $manager, array $users, stdClass $properties);
1667
}