forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
locallib.php
1544 lines (1417 loc) · 55.1 KB
/
locallib.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<?php
// This file is part of Moodle - http://moodle.org/
//
// Moodle is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// Moodle is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with Moodle. If not, see <http://www.gnu.org/licenses/>.
/**
* This file contains the course_enrolment_manager class which is used to interface
* with the functions that exist in enrollib.php in relation to a single course.
*
* @package core_enrol
* @copyright 2010 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* This class provides a targeted tied together means of interfacing the enrolment
* tasks together with a course.
*
* It is provided as a convenience more than anything else.
*
* @copyright 2010 Sam Hemelryk
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
class course_enrolment_manager {
/**
* The course context
* @var context
*/
protected $context;
/**
* The course we are managing enrolments for
* @var stdClass
*/
protected $course = null;
/**
* Limits the focus of the manager to one enrolment plugin instance
* @var string
*/
protected $instancefilter = null;
/**
* Limits the focus of the manager to users with specified role
* @var int
*/
protected $rolefilter = 0;
/**
* Limits the focus of the manager to users who match search string
* @var string
*/
protected $searchfilter = '';
/**
* Limits the focus of the manager to users in specified group
* @var int
*/
protected $groupfilter = 0;
/**
* Limits the focus of the manager to users who match status active/inactive
* @var int
*/
protected $statusfilter = -1;
/**
* The total number of users enrolled in the course
* Populated by course_enrolment_manager::get_total_users
* @var int
*/
protected $totalusers = null;
/**
* An array of users currently enrolled in the course
* Populated by course_enrolment_manager::get_users
* @var array
*/
protected $users = array();
/**
* An array of users who have roles within this course but who have not
* been enrolled in the course
* @var array
*/
protected $otherusers = array();
/**
* The total number of users who hold a role within the course but who
* arn't enrolled.
* @var int
*/
protected $totalotherusers = null;
/**
* The current moodle_page object
* @var moodle_page
*/
protected $moodlepage = null;
/**#@+
* These variables are used to cache the information this class uses
* please never use these directly instead use their get_ counterparts.
* @access private
* @var array
*/
private $_instancessql = null;
private $_instances = null;
private $_inames = null;
private $_plugins = null;
private $_allplugins = null;
private $_roles = null;
private $_visibleroles = null;
private $_assignableroles = null;
private $_assignablerolesothers = null;
private $_groups = null;
/**#@-*/
/**
* Constructs the course enrolment manager
*
* @param moodle_page $moodlepage
* @param stdClass $course
* @param string $instancefilter
* @param int $rolefilter If non-zero, filters to users with specified role
* @param string $searchfilter If non-blank, filters to users with search text
* @param int $groupfilter if non-zero, filter users with specified group
* @param int $statusfilter if not -1, filter users with active/inactive enrollment.
*/
public function __construct(moodle_page $moodlepage, $course, $instancefilter = null,
$rolefilter = 0, $searchfilter = '', $groupfilter = 0, $statusfilter = -1) {
$this->moodlepage = $moodlepage;
$this->context = context_course::instance($course->id);
$this->course = $course;
$this->instancefilter = $instancefilter;
$this->rolefilter = $rolefilter;
$this->searchfilter = $searchfilter;
$this->groupfilter = $groupfilter;
$this->statusfilter = $statusfilter;
}
/**
* Returns the current moodle page
* @return moodle_page
*/
public function get_moodlepage() {
return $this->moodlepage;
}
/**
* Returns the total number of enrolled users in the course.
*
* If a filter was specificed this will be the total number of users enrolled
* in this course by means of that instance.
*
* @global moodle_database $DB
* @return int
*/
public function get_total_users() {
global $DB;
if ($this->totalusers === null) {
list($instancessql, $params, $filter) = $this->get_instance_sql();
list($filtersql, $moreparams) = $this->get_filter_sql();
$params += $moreparams;
$sqltotal = "SELECT COUNT(DISTINCT u.id)
FROM {user} u
JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
JOIN {enrol} e ON (e.id = ue.enrolid)";
if ($this->groupfilter) {
$sqltotal .= " LEFT JOIN ({groups_members} gm JOIN {groups} g ON (g.id = gm.groupid))
ON (u.id = gm.userid AND g.courseid = e.courseid)";
}
$sqltotal .= "WHERE $filtersql";
$this->totalusers = (int)$DB->count_records_sql($sqltotal, $params);
}
return $this->totalusers;
}
/**
* Returns the total number of enrolled users in the course.
*
* If a filter was specificed this will be the total number of users enrolled
* in this course by means of that instance.
*
* @global moodle_database $DB
* @return int
*/
public function get_total_other_users() {
global $DB;
if ($this->totalotherusers === null) {
list($ctxcondition, $params) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'ctx');
$params['courseid'] = $this->course->id;
$sql = "SELECT COUNT(DISTINCT u.id)
FROM {role_assignments} ra
JOIN {user} u ON u.id = ra.userid
JOIN {context} ctx ON ra.contextid = ctx.id
LEFT JOIN (
SELECT ue.id, ue.userid
FROM {user_enrolments} ue
LEFT JOIN {enrol} e ON e.id=ue.enrolid
WHERE e.courseid = :courseid
) ue ON ue.userid=u.id
WHERE ctx.id $ctxcondition AND
ue.id IS NULL";
$this->totalotherusers = (int)$DB->count_records_sql($sql, $params);
}
return $this->totalotherusers;
}
/**
* Gets all of the users enrolled in this course.
*
* If a filter was specified this will be the users who were enrolled
* in this course by means of that instance. If role or search filters were
* specified then these will also be applied.
*
* @global moodle_database $DB
* @param string $sort
* @param string $direction ASC or DESC
* @param int $page First page should be 0
* @param int $perpage Defaults to 25
* @return array
*/
public function get_users($sort, $direction='ASC', $page=0, $perpage=25) {
global $DB;
if ($direction !== 'ASC') {
$direction = 'DESC';
}
$key = md5("$sort-$direction-$page-$perpage");
if (!array_key_exists($key, $this->users)) {
list($instancessql, $params, $filter) = $this->get_instance_sql();
list($filtersql, $moreparams) = $this->get_filter_sql();
$params += $moreparams;
$extrafields = get_extra_user_fields($this->get_context());
$extrafields[] = 'lastaccess';
$ufields = user_picture::fields('u', $extrafields);
$sql = "SELECT DISTINCT $ufields, COALESCE(ul.timeaccess, 0) AS lastcourseaccess
FROM {user} u
JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid $instancessql)
JOIN {enrol} e ON (e.id = ue.enrolid)
LEFT JOIN {user_lastaccess} ul ON (ul.courseid = e.courseid AND ul.userid = u.id)";
if ($this->groupfilter) {
$sql .= " LEFT JOIN ({groups_members} gm JOIN {groups} g ON (g.id = gm.groupid))
ON (u.id = gm.userid AND g.courseid = e.courseid)";
}
$sql .= "WHERE $filtersql
ORDER BY $sort $direction";
$this->users[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
}
return $this->users[$key];
}
/**
* Obtains WHERE clause to filter results by defined search and role filter
* (instance filter is handled separately in JOIN clause, see
* get_instance_sql).
*
* @return array Two-element array with SQL and params for WHERE clause
*/
protected function get_filter_sql() {
global $DB;
// Search condition.
$extrafields = get_extra_user_fields($this->get_context());
list($sql, $params) = users_search_sql($this->searchfilter, 'u', true, $extrafields);
// Role condition.
if ($this->rolefilter) {
// Get context SQL.
$contextids = $this->context->get_parent_context_ids();
$contextids[] = $this->context->id;
list($contextsql, $contextparams) = $DB->get_in_or_equal($contextids, SQL_PARAMS_NAMED);
$params += $contextparams;
// Role check condition.
$sql .= " AND (SELECT COUNT(1) FROM {role_assignments} ra WHERE ra.userid = u.id " .
"AND ra.roleid = :roleid AND ra.contextid $contextsql) > 0";
$params['roleid'] = $this->rolefilter;
}
// Group condition.
if ($this->groupfilter) {
if ($this->groupfilter < 0) {
// Show users who are not in any group.
$sql .= " AND gm.groupid IS NULL";
} else {
$sql .= " AND gm.groupid = :groupid";
$params['groupid'] = $this->groupfilter;
}
}
// Status condition.
if ($this->statusfilter === ENROL_USER_ACTIVE) {
$sql .= " AND ue.status = :active AND e.status = :enabled AND ue.timestart < :now1
AND (ue.timeend = 0 OR ue.timeend > :now2)";
$now = round(time(), -2); // rounding helps caching in DB
$params += array('enabled' => ENROL_INSTANCE_ENABLED,
'active' => ENROL_USER_ACTIVE,
'now1' => $now,
'now2' => $now);
} else if ($this->statusfilter === ENROL_USER_SUSPENDED) {
$sql .= " AND (ue.status = :inactive OR e.status = :disabled OR ue.timestart > :now1
OR (ue.timeend <> 0 AND ue.timeend < :now2))";
$now = round(time(), -2); // rounding helps caching in DB
$params += array('disabled' => ENROL_INSTANCE_DISABLED,
'inactive' => ENROL_USER_SUSPENDED,
'now1' => $now,
'now2' => $now);
}
return array($sql, $params);
}
/**
* Gets and array of other users.
*
* Other users are users who have been assigned roles or inherited roles
* within this course but who have not been enrolled in the course
*
* @global moodle_database $DB
* @param string $sort
* @param string $direction
* @param int $page
* @param int $perpage
* @return array
*/
public function get_other_users($sort, $direction='ASC', $page=0, $perpage=25) {
global $DB;
if ($direction !== 'ASC') {
$direction = 'DESC';
}
$key = md5("$sort-$direction-$page-$perpage");
if (!array_key_exists($key, $this->otherusers)) {
list($ctxcondition, $params) = $DB->get_in_or_equal($this->context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'ctx');
$params['courseid'] = $this->course->id;
$params['cid'] = $this->course->id;
$extrafields = get_extra_user_fields($this->get_context());
$ufields = user_picture::fields('u', $extrafields);
$sql = "SELECT ra.id as raid, ra.contextid, ra.component, ctx.contextlevel, ra.roleid, $ufields,
coalesce(u.lastaccess,0) AS lastaccess
FROM {role_assignments} ra
JOIN {user} u ON u.id = ra.userid
JOIN {context} ctx ON ra.contextid = ctx.id
LEFT JOIN (
SELECT ue.id, ue.userid
FROM {user_enrolments} ue
JOIN {enrol} e ON e.id = ue.enrolid
WHERE e.courseid = :courseid
) ue ON ue.userid=u.id
WHERE ctx.id $ctxcondition AND
ue.id IS NULL
ORDER BY $sort $direction, ctx.depth DESC";
$this->otherusers[$key] = $DB->get_records_sql($sql, $params, $page*$perpage, $perpage);
}
return $this->otherusers[$key];
}
/**
* Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
*
* @param string $search the search term, if any.
* @param bool $searchanywhere Can the search term be anywhere, or must it be at the start.
* @return array with three elements:
* string list of fields to SELECT,
* string contents of SQL WHERE clause,
* array query params. Note that the SQL snippets use named parameters.
*/
protected function get_basic_search_conditions($search, $searchanywhere) {
global $DB, $CFG;
// Add some additional sensible conditions
$tests = array("u.id <> :guestid", 'u.deleted = 0', 'u.confirmed = 1');
$params = array('guestid' => $CFG->siteguest);
if (!empty($search)) {
$conditions = get_extra_user_fields($this->get_context());
foreach (get_all_user_name_fields() as $field) {
$conditions[] = 'u.'.$field;
}
$conditions[] = $DB->sql_fullname('u.firstname', 'u.lastname');
if ($searchanywhere) {
$searchparam = '%' . $search . '%';
} else {
$searchparam = $search . '%';
}
$i = 0;
foreach ($conditions as $key => $condition) {
$conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false);
$params["con{$i}00"] = $searchparam;
$i++;
}
$tests[] = '(' . implode(' OR ', $conditions) . ')';
}
$wherecondition = implode(' AND ', $tests);
$extrafields = get_extra_user_fields($this->get_context(), array('username', 'lastaccess'));
$extrafields[] = 'username';
$extrafields[] = 'lastaccess';
$extrafields[] = 'maildisplay';
$ufields = user_picture::fields('u', $extrafields);
return array($ufields, $params, $wherecondition);
}
/**
* Helper method used by {@link get_potential_users()} and {@link search_other_users()}.
*
* @param string $search the search string, if any.
* @param string $fields the first bit of the SQL when returning some users.
* @param string $countfields fhe first bit of the SQL when counting the users.
* @param string $sql the bulk of the SQL statement.
* @param array $params query parameters.
* @param int $page which page number of the results to show.
* @param int $perpage number of users per page.
* @param int $addedenrollment number of users added to enrollment.
* @return array with two elememts:
* int total number of users matching the search.
* array of user objects returned by the query.
*/
protected function execute_search_queries($search, $fields, $countfields, $sql, array $params, $page, $perpage, $addedenrollment=0) {
global $DB, $CFG;
list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
$order = ' ORDER BY ' . $sort;
$totalusers = $DB->count_records_sql($countfields . $sql, $params);
$availableusers = $DB->get_records_sql($fields . $sql . $order,
array_merge($params, $sortparams), ($page*$perpage) - $addedenrollment, $perpage);
return array('totalusers' => $totalusers, 'users' => $availableusers);
}
/**
* Gets an array of the users that can be enrolled in this course.
*
* @global moodle_database $DB
* @param int $enrolid
* @param string $search
* @param bool $searchanywhere
* @param int $page Defaults to 0
* @param int $perpage Defaults to 25
* @param int $addedenrollment Defaults to 0
* @return array Array(totalusers => int, users => array)
*/
public function get_potential_users($enrolid, $search='', $searchanywhere=false, $page=0, $perpage=25, $addedenrollment=0) {
global $DB;
list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
$fields = 'SELECT '.$ufields;
$countfields = 'SELECT COUNT(1)';
$sql = " FROM {user} u
LEFT JOIN {user_enrolments} ue ON (ue.userid = u.id AND ue.enrolid = :enrolid)
WHERE $wherecondition
AND ue.id IS NULL";
$params['enrolid'] = $enrolid;
return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage, $addedenrollment);
}
/**
* Searches other users and returns paginated results
*
* @global moodle_database $DB
* @param string $search
* @param bool $searchanywhere
* @param int $page Starting at 0
* @param int $perpage
* @return array
*/
public function search_other_users($search='', $searchanywhere=false, $page=0, $perpage=25) {
global $DB, $CFG;
list($ufields, $params, $wherecondition) = $this->get_basic_search_conditions($search, $searchanywhere);
$fields = 'SELECT ' . $ufields;
$countfields = 'SELECT COUNT(u.id)';
$sql = " FROM {user} u
LEFT JOIN {role_assignments} ra ON (ra.userid = u.id AND ra.contextid = :contextid)
WHERE $wherecondition
AND ra.id IS NULL";
$params['contextid'] = $this->context->id;
return $this->execute_search_queries($search, $fields, $countfields, $sql, $params, $page, $perpage);
}
/**
* Gets an array containing some SQL to user for when selecting, params for
* that SQL, and the filter that was used in constructing the sql.
*
* @global moodle_database $DB
* @return string
*/
protected function get_instance_sql() {
global $DB;
if ($this->_instancessql === null) {
$instances = $this->get_enrolment_instances();
$filter = $this->get_enrolment_filter();
if ($filter && array_key_exists($filter, $instances)) {
$sql = " = :ifilter";
$params = array('ifilter'=>$filter);
} else {
$filter = 0;
if ($instances) {
list($sql, $params) = $DB->get_in_or_equal(array_keys($this->get_enrolment_instances()), SQL_PARAMS_NAMED);
} else {
// no enabled instances, oops, we should probably say something
$sql = "= :never";
$params = array('never'=>-1);
}
}
$this->instancefilter = $filter;
$this->_instancessql = array($sql, $params, $filter);
}
return $this->_instancessql;
}
/**
* Returns all of the enrolment instances for this course.
*
* @param bool $onlyenabled Whether to return data from enabled enrolment instance names only.
* @return array
*/
public function get_enrolment_instances($onlyenabled = false) {
if ($this->_instances === null) {
$this->_instances = enrol_get_instances($this->course->id, $onlyenabled);
}
return $this->_instances;
}
/**
* Returns the names for all of the enrolment instances for this course.
*
* @param bool $onlyenabled Whether to return data from enabled enrolment instance names only.
* @return array
*/
public function get_enrolment_instance_names($onlyenabled = false) {
if ($this->_inames === null) {
$instances = $this->get_enrolment_instances($onlyenabled);
$plugins = $this->get_enrolment_plugins(false);
foreach ($instances as $key=>$instance) {
if (!isset($plugins[$instance->enrol])) {
// weird, some broken stuff in plugin
unset($instances[$key]);
continue;
}
$this->_inames[$key] = $plugins[$instance->enrol]->get_instance_name($instance);
}
}
return $this->_inames;
}
/**
* Gets all of the enrolment plugins that are available for this course.
*
* @param bool $onlyenabled return only enabled enrol plugins
* @return array
*/
public function get_enrolment_plugins($onlyenabled = true) {
if ($this->_plugins === null) {
$this->_plugins = enrol_get_plugins(true);
}
if ($onlyenabled) {
return $this->_plugins;
}
if ($this->_allplugins === null) {
// Make sure we have the same objects in _allplugins and _plugins.
$this->_allplugins = $this->_plugins;
foreach (enrol_get_plugins(false) as $name=>$plugin) {
if (!isset($this->_allplugins[$name])) {
$this->_allplugins[$name] = $plugin;
}
}
}
return $this->_allplugins;
}
/**
* Gets all of the roles this course can contain.
*
* @return array
*/
public function get_all_roles() {
if ($this->_roles === null) {
$this->_roles = role_fix_names(get_all_roles($this->context), $this->context);
}
return $this->_roles;
}
/**
* Gets all of the roles this course can contain.
*
* @return array
*/
public function get_viewable_roles() {
if ($this->_visibleroles === null) {
$this->_visibleroles = get_viewable_roles($this->context);
}
return $this->_visibleroles;
}
/**
* Gets all of the assignable roles for this course.
*
* @return array
*/
public function get_assignable_roles($otherusers = false) {
if ($this->_assignableroles === null) {
$this->_assignableroles = get_assignable_roles($this->context, ROLENAME_ALIAS, false); // verifies unassign access control too
}
if ($otherusers) {
if (!is_array($this->_assignablerolesothers)) {
$this->_assignablerolesothers = array();
list($courseviewroles, $ignored) = get_roles_with_cap_in_context($this->context, 'moodle/course:view');
foreach ($this->_assignableroles as $roleid=>$role) {
if (isset($courseviewroles[$roleid])) {
$this->_assignablerolesothers[$roleid] = $role;
}
}
}
return $this->_assignablerolesothers;
} else {
return $this->_assignableroles;
}
}
/**
* Gets all of the assignable roles for this course, wrapped in an array to ensure
* role sort order is not lost during json deserialisation.
*
* @param boolean $otherusers whether to include the assignable roles for other users
* @return array
*/
public function get_assignable_roles_for_json($otherusers = false) {
$rolesarray = array();
$assignable = $this->get_assignable_roles($otherusers);
foreach ($assignable as $id => $role) {
$rolesarray[] = array('id' => $id, 'name' => $role);
}
return $rolesarray;
}
/**
* Gets all of the groups for this course.
*
* @return array
*/
public function get_all_groups() {
if ($this->_groups === null) {
$this->_groups = groups_get_all_groups($this->course->id);
foreach ($this->_groups as $gid=>$group) {
$this->_groups[$gid]->name = format_string($group->name);
}
}
return $this->_groups;
}
/**
* Unenrols a user from the course given the users ue entry
*
* @global moodle_database $DB
* @param stdClass $ue
* @return bool
*/
public function unenrol_user($ue) {
global $DB;
list ($instance, $plugin) = $this->get_user_enrolment_components($ue);
if ($instance && $plugin && $plugin->allow_unenrol_user($instance, $ue) && has_capability("enrol/$instance->enrol:unenrol", $this->context)) {
$plugin->unenrol_user($instance, $ue->userid);
return true;
}
return false;
}
/**
* Given a user enrolment record this method returns the plugin and enrolment
* instance that relate to it.
*
* @param stdClass|int $userenrolment
* @return array array($instance, $plugin)
*/
public function get_user_enrolment_components($userenrolment) {
global $DB;
if (is_numeric($userenrolment)) {
$userenrolment = $DB->get_record('user_enrolments', array('id'=>(int)$userenrolment));
}
$instances = $this->get_enrolment_instances();
$plugins = $this->get_enrolment_plugins(false);
if (!$userenrolment || !isset($instances[$userenrolment->enrolid])) {
return array(false, false);
}
$instance = $instances[$userenrolment->enrolid];
$plugin = $plugins[$instance->enrol];
return array($instance, $plugin);
}
/**
* Removes an assigned role from a user.
*
* @global moodle_database $DB
* @param int $userid
* @param int $roleid
* @return bool
*/
public function unassign_role_from_user($userid, $roleid) {
global $DB;
// Admins may unassign any role, others only those they could assign.
if (!is_siteadmin() and !array_key_exists($roleid, $this->get_assignable_roles())) {
if (defined('AJAX_SCRIPT')) {
throw new moodle_exception('invalidrole');
}
return false;
}
$user = $DB->get_record('user', array('id'=>$userid), '*', MUST_EXIST);
$ras = $DB->get_records('role_assignments', array('contextid'=>$this->context->id, 'userid'=>$user->id, 'roleid'=>$roleid));
foreach ($ras as $ra) {
if ($ra->component) {
if (strpos($ra->component, 'enrol_') !== 0) {
continue;
}
if (!$plugin = enrol_get_plugin(substr($ra->component, 6))) {
continue;
}
if ($plugin->roles_protected()) {
continue;
}
}
role_unassign($ra->roleid, $ra->userid, $ra->contextid, $ra->component, $ra->itemid);
}
return true;
}
/**
* Assigns a role to a user.
*
* @param int $roleid
* @param int $userid
* @return int|false
*/
public function assign_role_to_user($roleid, $userid) {
require_capability('moodle/role:assign', $this->context);
if (!array_key_exists($roleid, $this->get_assignable_roles())) {
if (defined('AJAX_SCRIPT')) {
throw new moodle_exception('invalidrole');
}
return false;
}
return role_assign($roleid, $userid, $this->context->id, '', NULL);
}
/**
* Adds a user to a group
*
* @param stdClass $user
* @param int $groupid
* @return bool
*/
public function add_user_to_group($user, $groupid) {
require_capability('moodle/course:managegroups', $this->context);
$group = $this->get_group($groupid);
if (!$group) {
return false;
}
return groups_add_member($group->id, $user->id);
}
/**
* Removes a user from a group
*
* @global moodle_database $DB
* @param StdClass $user
* @param int $groupid
* @return bool
*/
public function remove_user_from_group($user, $groupid) {
global $DB;
require_capability('moodle/course:managegroups', $this->context);
$group = $this->get_group($groupid);
if (!groups_remove_member_allowed($group, $user)) {
return false;
}
if (!$group) {
return false;
}
return groups_remove_member($group, $user);
}
/**
* Gets the requested group
*
* @param int $groupid
* @return stdClass|int
*/
public function get_group($groupid) {
$groups = $this->get_all_groups();
if (!array_key_exists($groupid, $groups)) {
return false;
}
return $groups[$groupid];
}
/**
* Edits an enrolment
*
* @param stdClass $userenrolment
* @param stdClass $data
* @return bool
*/
public function edit_enrolment($userenrolment, $data) {
//Only allow editing if the user has the appropriate capability
//Already checked in /user/index.php but checking again in case this function is called from elsewhere
list($instance, $plugin) = $this->get_user_enrolment_components($userenrolment);
if ($instance && $plugin && $plugin->allow_manage($instance) && has_capability("enrol/$instance->enrol:manage", $this->context)) {
if (!isset($data->status)) {
$data->status = $userenrolment->status;
}
$plugin->update_user_enrol($instance, $userenrolment->userid, $data->status, $data->timestart, $data->timeend);
return true;
}
return false;
}
/**
* Returns the current enrolment filter that is being applied by this class
* @return string
*/
public function get_enrolment_filter() {
return $this->instancefilter;
}
/**
* Gets the roles assigned to this user that are applicable for this course.
*
* @param int $userid
* @return array
*/
public function get_user_roles($userid) {
$roles = array();
$ras = get_user_roles($this->context, $userid, true, 'c.contextlevel DESC, r.sortorder ASC');
$plugins = $this->get_enrolment_plugins(false);
foreach ($ras as $ra) {
if ($ra->contextid != $this->context->id) {
if (!array_key_exists($ra->roleid, $roles)) {
$roles[$ra->roleid] = null;
}
// higher ras, course always takes precedence
continue;
}
if (array_key_exists($ra->roleid, $roles) && $roles[$ra->roleid] === false) {
continue;
}
$changeable = true;
if ($ra->component) {
$changeable = false;
if (strpos($ra->component, 'enrol_') === 0) {
$plugin = substr($ra->component, 6);
if (isset($plugins[$plugin])) {
$changeable = !$plugins[$plugin]->roles_protected();
}
}
}
$roles[$ra->roleid] = $changeable;
}
return $roles;
}
/**
* Gets the enrolments this user has in the course - including all suspended plugins and instances.
*
* @global moodle_database $DB
* @param int $userid
* @return array
*/
public function get_user_enrolments($userid) {
global $DB;
list($instancessql, $params, $filter) = $this->get_instance_sql();
$params['userid'] = $userid;
$userenrolments = $DB->get_records_select('user_enrolments', "enrolid $instancessql AND userid = :userid", $params);
$instances = $this->get_enrolment_instances();
$plugins = $this->get_enrolment_plugins(false);
$inames = $this->get_enrolment_instance_names();
foreach ($userenrolments as &$ue) {
$ue->enrolmentinstance = $instances[$ue->enrolid];
$ue->enrolmentplugin = $plugins[$ue->enrolmentinstance->enrol];
$ue->enrolmentinstancename = $inames[$ue->enrolmentinstance->id];
}
return $userenrolments;
}
/**
* Gets the groups this user belongs to
*
* @param int $userid
* @return array
*/
public function get_user_groups($userid) {
return groups_get_all_groups($this->course->id, $userid, 0, 'g.id');
}
/**
* Retursn an array of params that would go into the URL to return to this
* exact page.
*
* @return array
*/
public function get_url_params() {
$args = array(
'id' => $this->course->id
);
if (!empty($this->instancefilter)) {
$args['ifilter'] = $this->instancefilter;
}
if (!empty($this->rolefilter)) {
$args['role'] = $this->rolefilter;
}
if ($this->searchfilter !== '') {
$args['search'] = $this->searchfilter;
}
if (!empty($this->groupfilter)) {
$args['filtergroup'] = $this->groupfilter;
}
if ($this->statusfilter !== -1) {
$args['status'] = $this->statusfilter;
}
return $args;
}
/**
* Returns the course this object is managing enrolments for
*
* @return stdClass
*/
public function get_course() {
return $this->course;
}
/**
* Returns the course context
*
* @return context
*/
public function get_context() {
return $this->context;
}
/**
* Gets an array of other users in this course ready for display.
*
* Other users are users who have been assigned or inherited roles within this
* course but have not been enrolled.
*
* @param core_enrol_renderer $renderer
* @param moodle_url $pageurl
* @param string $sort
* @param string $direction ASC | DESC
* @param int $page Starting from 0
* @param int $perpage
* @return array
*/
public function get_other_users_for_display(core_enrol_renderer $renderer, moodle_url $pageurl, $sort, $direction, $page, $perpage) {
$userroles = $this->get_other_users($sort, $direction, $page, $perpage);
$roles = $this->get_all_roles();
$plugins = $this->get_enrolment_plugins(false);
$context = $this->get_context();
$now = time();
$extrafields = get_extra_user_fields($context);
$users = array();
foreach ($userroles as $userrole) {
$contextid = $userrole->contextid;
unset($userrole->contextid); // This would collide with user avatar.
if (!array_key_exists($userrole->id, $users)) {
$users[$userrole->id] = $this->prepare_user_for_display($userrole, $extrafields, $now);
}
$a = new stdClass;
$a->role = $roles[$userrole->roleid]->localname;
if ($contextid == $this->context->id) {
$changeable = true;
if ($userrole->component) {
$changeable = false;
if (strpos($userrole->component, 'enrol_') === 0) {
$plugin = substr($userrole->component, 6);
if (isset($plugins[$plugin])) {
$changeable = !$plugins[$plugin]->roles_protected();
}
}
}