forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
datalib.php
2435 lines (2137 loc) · 83.1 KB
/
datalib.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/>.
/**
* Library of functions for database manipulation.
*
* Other main libraries:
* - weblib.php - functions that produce web output
* - moodlelib.php - general-purpose Moodle functions
*
* @package moodlecore
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
/**
* The maximum courses in a category
* MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
*/
define('MAX_COURSES_IN_CATEGORY', 10000);
/**
* The maximum number of course categories
* MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
*/
define('MAX_COURSE_CATEGORIES', 10000);
/**
* Number of seconds to wait before updating lastaccess information in DB.
*/
define('LASTACCESS_UPDATE_SECS', 60);
/**
* Returns $user object of the main admin user
* primary admin = admin with lowest role_assignment id among admins
*
* @global object
* @static object $myadmin
* @return object An associative array representing the admin user.
*/
function get_admin () {
static $myadmin;
if (! isset($admin)) {
if (! $admins = get_admins()) {
return false;
}
$admin = reset($admins);//reset returns first element
}
return $admin;
}
/**
* Returns list of all admins, using 1 DB query. It depends on DB schema v1.7
* but does not depend on the v1.9 datastructures (context.path, etc).
*
* @global object
* @return array
*/
function get_admins() {
global $DB;
$sql = "SELECT ra.userid, SUM(rc.permission) AS permission, MIN(ra.id) AS adminid
FROM {role_capabilities} rc
JOIN {context} ctx ON ctx.id=rc.contextid
JOIN {role_assignments} ra ON ra.roleid=rc.roleid AND ra.contextid=ctx.id
WHERE ctx.contextlevel=10 AND rc.capability IN (?, ?, ?)
GROUP BY ra.userid
HAVING SUM(rc.permission) > 0";
$params = array('moodle/site:config', 'moodle/legacy:admin', 'moodle/site:doanything');
$sql = "SELECT u.*, ra.adminid
FROM {user} u
JOIN ($sql) ra
ON u.id=ra.userid
ORDER BY ra.adminid ASC";
return $DB->get_records_sql($sql, $params);
}
/**
* Get all of the courses in a given meta course
*
* @global object
* @param int $metacourseid The metacourse id
* @return array
*/
function get_courses_in_metacourse($metacourseid) {
global $DB;
$sql = "SELECT c.id, c.shortname, c.fullname
FROM {course} c, {course_meta} mc
WHERE mc.parent_course = ? AND mc.child_course = c.id
ORDER BY c.shortname";
$params = array($metacourseid);
return $DB->get_records_sql($sql, $params);
}
/**
* @todo Document this function
*
* @global object
* @uses SITEID
* @param int $metacourseid
* @return array
*/
function get_courses_notin_metacourse($metacourseid) {
global $DB;
if ($alreadycourses = get_courses_in_metacourse($metacourseid)) {
$alreadycourses = implode(',',array_keys($alreadycourses));
$alreadycourses = "AND c.id NOT IN ($alreadycourses)";
} else {
$alreadycourses = "";
}
$sql = "SELECT c.id,c.shortname,c.fullname
FROM {course} c
WHERE c.id != ? and c.id != ".SITEID." and c.metacourse != 1
$alreadycourses
ORDER BY c.shortname";
$params = array($metacourseid);
return $DB->get_records_sql($sql, $params);
}
/**
* @todo Document this function
*
* This function is nearly identical to {@link get_courses_notin_metacourse()}
*
* @global object
* @uses SITEID
* @param int $metacourseid
* @return int The count
*/
function count_courses_notin_metacourse($metacourseid) {
global $DB;
if ($alreadycourses = get_courses_in_metacourse($metacourseid)) {
$alreadycourses = implode(',',array_keys($alreadycourses));
$alreadycourses = "AND c.id NOT IN ($alreadycourses)";
} else {
$alreadycourses = "";
}
$sql = "SELECT COUNT(c.id)
FROM {course} c
WHERE c.id != ? and c.id != ".SITEID." and c.metacourse != 1
$alreadycourses";
$params = array($metacourseid);
return $DB->count_records_sql($sql, $params);
}
/**
* Search through course users
*
* If $coursid specifies the site course then this function searches
* through all undeleted and confirmed users
*
* @global object
* @uses SITEID
* @uses SQL_PARAMS_NAMED
* @uses CONTEXT_COURSE
* @param int $courseid The course in question.
* @param int $groupid The group in question.
* @param string $searchtext The string to search for
* @param string $sort A field to sort by
* @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
* @return array
*/
function search_users($courseid, $groupid, $searchtext, $sort='', array $exceptions=null) {
global $DB;
$LIKE = $DB->sql_ilike();
$fullname = $DB->sql_fullname('u.firstname', 'u.lastname');
if (!empty($exceptions)) {
list($exceptions, $params) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex0000', false);
$except = "AND u.id $exceptions";
} else {
$except = "";
$params = array();
}
if (!empty($sort)) {
$order = "ORDER BY $sort";
} else {
$order = "";
}
$select = "u.deleted = 0 AND u.confirmed = 1 AND ($fullname $LIKE :search1 OR u.email $LIKE :search2)";
$params['search1'] = "%$searchtext%";
$params['search2'] = "%$searchtext%";
if (!$courseid or $courseid == SITEID) {
$sql = "SELECT u.id, u.firstname, u.lastname, u.email
FROM {user} u
WHERE $select
$except
$order";
return $DB->get_records_sql($sql, $params);
} else {
if ($groupid) {
$sql = "SELECT u.id, u.firstname, u.lastname, u.email
FROM {user} u
JOIN {groups_members} gm ON gm.userid = u.id
WHERE $select AND gm.groupid = :groupid
$except
$order";
$params['groupid'] = $groupid;
return $DB->get_records_sql($sql, $params);
} else {
$context = get_context_instance(CONTEXT_COURSE, $courseid);
$contextlists = get_related_contexts_string($context);
$sql = "SELECT u.id, u.firstname, u.lastname, u.email
FROM {user} u
JOIN {role_assignments} ra ON ra.userid = u.id
WHERE $select AND ra.contextid $contextlists
$except
$order";
return $DB->get_records_sql($sql, $params);
}
}
}
/**
* Returns a subset of users
*
* @global object
* @uses DEBUG_DEVELOPER
* @uses SQL_PARAMS_NAMED
* @param bool $get If false then only a count of the records is returned
* @param string $search A simple string to search for
* @param bool $confirmed A switch to allow/disallow unconfirmed users
* @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
* @param string $sort A SQL snippet for the sorting criteria to use
* @param string $firstinitial Users whose first name starts with $firstinitial
* @param string $lastinitial Users whose last name starts with $lastinitial
* @param string $page The page or records to return
* @param string $recordsperpage The number of records to return per page
* @param string $fields A comma separated list of fields to be returned from the chosen table.
* @return array|int|bool {@link $USER} records unless get is false in which case the integer count of the records found is returned.
* False is returned if an error is encountered.
*/
function get_users($get=true, $search='', $confirmed=false, array $exceptions=null, $sort='firstname ASC',
$firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*', $extraselect='', array $extraparams=null) {
global $DB;
if ($get && !$recordsperpage) {
debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
'On large installations, this will probably cause an out of memory error. ' .
'Please think again and change your code so that it does not try to ' .
'load so much data into memory.', DEBUG_DEVELOPER);
}
$LIKE = $DB->sql_ilike();
$fullname = $DB->sql_fullname();
$select = " username <> :guest AND deleted = 0";
$params = array('guest'=>'guest');
if (!empty($search)){
$search = trim($search);
$select .= " AND ($fullname $LIKE :search1 OR email $LIKE :search2 OR username = :search3)";
$params['search1'] = "%$search%";
$params['search2'] = "%$search%";
$params['search3'] = "$search";
}
if ($confirmed) {
$select .= " AND confirmed = 1";
}
if ($exceptions) {
list($exceptions, $eparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex0000', false);
$params = $params + $eparams;
$except = " AND id $exceptions";
}
if ($firstinitial) {
$select .= " AND firstname $LIKE :fni";
$params['fni'] = "$firstinitial%";
}
if ($lastinitial) {
$select .= " AND lastname $LIKE :lni";
$params['lni'] = "$lastinitial%";
}
if ($extraselect) {
$select .= " AND $extraselect";
$params = $params + (array)$extraparams;
}
if ($get) {
return $DB->get_records_select('user', $select, $params, $sort, $fields, $page, $recordsperpage);
} else {
return $DB->count_records_select('user', $select, $params);
}
}
/**
* @todo Finish documenting this function
*
* @param string $sort An SQL field to sort by
* @param string $dir The sort direction ASC|DESC
* @param int $page The page or records to return
* @param int $recordsperpage The number of records to return per page
* @param string $search A simple string to search for
* @param string $firstinitial Users whose first name starts with $firstinitial
* @param string $lastinitial Users whose last name starts with $lastinitial
* @param string $extraselect An additional SQL select statement to append to the query
* @param array $extraparams Additional parameters to use for the above $extraselect
* @return array Array of {@link $USER} records
*/
function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
$search='', $firstinitial='', $lastinitial='', $extraselect='', array $extraparams=null) {
global $DB;
$LIKE = $DB->sql_ilike();
$fullname = $DB->sql_fullname();
$select = "deleted <> 1";
$params = array();
if (!empty($search)) {
$search = trim($search);
$select .= " AND ($fullname $LIKE :search1 OR email $LIKE :search2 OR username = :search3)";
$params['search1'] = "%$search%";
$params['search2'] = "%$search%";
$params['search3'] = "$search";
}
if ($firstinitial) {
$select .= " AND firstname $LIKE :fni";
$params['fni'] = "$firstinitial%";
}
if ($lastinitial) {
$select .= " AND lastname $LIKE :lni";
$params['lni'] = "$lastinitial%";
}
if ($extraselect) {
$select .= " AND $extraselect";
$params = $params + (array)$extraparams;
}
if ($sort) {
$sort = " ORDER BY $sort $dir";
}
/// warning: will return UNCONFIRMED USERS
return $DB->get_records_sql("SELECT id, username, email, firstname, lastname, city, country, lastaccess, confirmed, mnethostid
FROM {user}
WHERE $select
$sort", $params, $page, $recordsperpage);
}
/**
* Full list of users that have confirmed their accounts.
*
* @global object
* @return array of unconfirmed users
*/
function get_users_confirmed() {
global $DB;
return $DB->get_records_sql("SELECT *
FROM {user}
WHERE confirmed = 1 AND deleted = 0 AND username <> ?", array('guest'));
}
/// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
/**
* Returns $course object of the top-level site.
*
* @return object A {@link $COURSE} object for the site, exception if not found
*/
function get_site() {
global $SITE, $DB;
if (!empty($SITE->id)) { // We already have a global to use, so return that
return $SITE;
}
if ($course = $DB->get_record('course', array('category'=>0))) {
return $course;
} else {
// course table exists, but the site is not there,
// unfortunately there is no automatic way to recover
throw new moodle_exception('nosite', 'error');
}
}
/**
* Returns list of courses, for whole site, or category
*
* Returns list of courses, for whole site, or category
* Important: Using c.* for fields is extremely expensive because
* we are using distinct. You almost _NEVER_ need all the fields
* in such a large SELECT
*
* @global object
* @global object
* @global object
* @uses CONTEXT_COURSE
* @param string|int $categoryid Either a category id or 'all' for everything
* @param string $sort A field and direction to sort by
* @param string $fields The additional fields to return
* @return array Array of courses
*/
function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
global $USER, $CFG, $DB;
$params = array();
if ($categoryid !== "all" && is_numeric($categoryid)) {
$categoryselect = "WHERE c.category = :catid";
$params['catid'] = $categoryid;
} else {
$categoryselect = "";
}
if (empty($sort)) {
$sortstatement = "";
} else {
$sortstatement = "ORDER BY $sort";
}
$visiblecourses = array();
$sql = "SELECT $fields,
ctx.id AS ctxid, ctx.path AS ctxpath,
ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
FROM {course} c
JOIN {context} ctx
ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
$categoryselect
$sortstatement";
// pull out all course matching the cat
if ($courses = $DB->get_records_sql($sql, $params)) {
// loop throught them
foreach ($courses as $course) {
$course = make_context_subobj($course);
if (isset($course->visible) && $course->visible <= 0) {
// for hidden courses, require visibility check
if (has_capability('moodle/course:viewhiddencourses', $course->context)) {
$visiblecourses [$course->id] = $course;
}
} else {
$visiblecourses [$course->id] = $course;
}
}
}
return $visiblecourses;
}
/**
* Returns list of courses, for whole site, or category
*
* Similar to get_courses, but allows paging
* Important: Using c.* for fields is extremely expensive because
* we are using distinct. You almost _NEVER_ need all the fields
* in such a large SELECT
*
* @global object
* @global object
* @global object
* @uses CONTEXT_COURSE
* @param string|int $categoryid Either a category id or 'all' for everything
* @param string $sort A field and direction to sort by
* @param string $fields The additional fields to return
* @param int $totalcount Reference for the number of courses
* @param string $limitfrom The course to start from
* @param string $limitnum The number of courses to limit to
* @return array Array of courses
*/
function get_courses_page($categoryid="all", $sort="c.sortorder ASC", $fields="c.*",
&$totalcount, $limitfrom="", $limitnum="") {
global $USER, $CFG, $DB;
$params = array();
$categoryselect = "";
if ($categoryid != "all" && is_numeric($categoryid)) {
$categoryselect = "WHERE c.category = :catid";
$params['catid'] = $categoryid;
} else {
$categoryselect = "";
}
$sql = "SELECT $fields,
ctx.id AS ctxid, ctx.path AS ctxpath,
ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
FROM {course} c
JOIN {context} ctx
ON (c.id = ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
$categoryselect
ORDER BY $sort";
// pull out all course matching the cat
if (!$rs = $DB->get_recordset_sql($sql, $params)) {
return array();
}
$totalcount = 0;
if (!$limitfrom) {
$limitfrom = 0;
}
// iteration will have to be done inside loop to keep track of the limitfrom and limitnum
$visiblecourses = array();
foreach($rs as $course) {
$course = make_context_subobj($course);
if ($course->visible <= 0) {
// for hidden courses, require visibility check
if (has_capability('moodle/course:viewhiddencourses', $course->context)) {
$totalcount++;
if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
$visiblecourses [$course->id] = $course;
}
}
} else {
$totalcount++;
if ($totalcount > $limitfrom && (!$limitnum or count($visiblecourses) < $limitnum)) {
$visiblecourses [$course->id] = $course;
}
}
}
$rs->close();
return $visiblecourses;
}
/**
* Retrieve course records with the course managers and other related records
* that we need for print_course(). This allows print_courses() to do its job
* in a constant number of DB queries, regardless of the number of courses,
* role assignments, etc.
*
* The returned array is indexed on c.id, and each course will have
* - $course->context - a context obj
* - $course->managers - array containing RA objects that include a $user obj
* with the minimal fields needed for fullname()
*
* @global object
* @global object
* @global object
* @uses CONTEXT_COURSE
* @uses CONTEXT_SYSTEM
* @uses CONTEXT_COURSECAT
* @uses SITEID
* @param int|string $categoryid Either the categoryid for the courses or 'all'
* @param string $sort A SQL sort field and direction
* @param array $fields An array of additional fields to fetch
* @return array
*/
function get_courses_wmanagers($categoryid=0, $sort="c.sortorder ASC", $fields=array()) {
/*
* The plan is to
*
* - Grab the courses JOINed w/context
*
* - Grab the interesting course-manager RAs
* JOINed with a base user obj and add them to each course
*
* So as to do all the work in 2 DB queries. The RA+user JOIN
* ends up being pretty expensive if it happens over _all_
* courses on a large site. (Are we surprised!?)
*
* So this should _never_ get called with 'all' on a large site.
*
*/
global $USER, $CFG, $DB;
$params = array();
$allcats = false; // bool flag
if ($categoryid === 'all') {
$categoryclause = '';
$allcats = true;
} elseif (is_numeric($categoryid)) {
$categoryclause = "c.category = :catid";
$params['catid'] = $categoryid;
} else {
debugging("Could not recognise categoryid = $categoryid");
$categoryclause = '';
}
$basefields = array('id', 'category', 'sortorder',
'shortname', 'fullname', 'idnumber',
'guest', 'startdate', 'visible',
'newsitems', 'cost', 'enrol',
'groupmode', 'groupmodeforce');
if (!is_null($fields) && is_string($fields)) {
if (empty($fields)) {
$fields = $basefields;
} else {
// turn the fields from a string to an array that
// get_user_courses_bycap() will like...
$fields = explode(',',$fields);
$fields = array_map('trim', $fields);
$fields = array_unique(array_merge($basefields, $fields));
}
} elseif (is_array($fields)) {
$fields = array_merge($basefields,$fields);
}
$coursefields = 'c.' .join(',c.', $fields);
if (empty($sort)) {
$sortstatement = "";
} else {
$sortstatement = "ORDER BY $sort";
}
$where = 'WHERE c.id != ' . SITEID;
if ($categoryclause !== ''){
$where = "$where AND $categoryclause";
}
// pull out all courses matching the cat
$sql = "SELECT $coursefields,
ctx.id AS ctxid, ctx.path AS ctxpath,
ctx.depth AS ctxdepth, ctx.contextlevel AS ctxlevel
FROM {course} c
JOIN {context} ctx
ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
$where
$sortstatement";
$catpaths = array();
$catpath = NULL;
if ($courses = $DB->get_records_sql($sql, $params)) {
// loop on courses materialising
// the context, and prepping data to fetch the
// managers efficiently later...
foreach ($courses as $k => $course) {
$courses[$k] = make_context_subobj($courses[$k]);
$courses[$k]->managers = array();
if ($allcats === false) {
// single cat, so take just the first one...
if ($catpath === NULL) {
$catpath = preg_replace(':/\d+$:', '',$courses[$k]->context->path);
}
} else {
// chop off the contextid of the course itself
// like dirname() does...
$catpaths[] = preg_replace(':/\d+$:', '',$courses[$k]->context->path);
}
}
} else {
return array(); // no courses!
}
$CFG->coursemanager = trim($CFG->coursemanager);
if (empty($CFG->coursemanager)) {
return $courses;
}
$managerroles = split(',', $CFG->coursemanager);
$catctxids = '';
if (count($managerroles)) {
if ($allcats === true) {
$catpaths = array_unique($catpaths);
$ctxids = array();
foreach ($catpaths as $cpath) {
$ctxids = array_merge($ctxids, explode('/',substr($cpath,1)));
}
$ctxids = array_unique($ctxids);
$catctxids = implode( ',' , $ctxids);
unset($catpaths);
unset($cpath);
} else {
// take the ctx path from the first course
// as all categories will be the same...
$catpath = substr($catpath,1);
$catpath = preg_replace(':/\d+$:','',$catpath);
$catctxids = str_replace('/',',',$catpath);
}
if ($categoryclause !== '') {
$categoryclause = "AND $categoryclause";
}
/*
* Note: Here we use a LEFT OUTER JOIN that can
* "optionally" match to avoid passing a ton of context
* ids in an IN() clause. Perhaps a subselect is faster.
*
* In any case, this SQL is not-so-nice over large sets of
* courses with no $categoryclause.
*
*/
$sql = "SELECT ctx.path, ctx.instanceid, ctx.contextlevel,
ra.hidden,
r.id AS roleid, r.name as rolename,
u.id AS userid, u.firstname, u.lastname
FROM {role_assignments} ra
JOIN {context} ctx ON ra.contextid = ctx.id
JOIN {user} u ON ra.userid = u.id
JOIN {role} r ON ra.roleid = r.id
LEFT OUTER JOIN {course} c
ON (ctx.instanceid=c.id AND ctx.contextlevel=".CONTEXT_COURSE.")
WHERE ( c.id IS NOT NULL";
// under certain conditions, $catctxids is NULL
if($catctxids == NULL){
$sql .= ") ";
}else{
$sql .= " OR ra.contextid IN ($catctxids) )";
}
$sql .= "AND ra.roleid IN ({$CFG->coursemanager})
$categoryclause
ORDER BY r.sortorder ASC, ctx.contextlevel ASC, ra.sortorder ASC";
$rs = $DB->get_recordset_sql($sql, $params);
// This loop is fairly stupid as it stands - might get better
// results doing an initial pass clustering RAs by path.
foreach($rs as $ra) {
$user = new StdClass;
$user->id = $ra->userid; unset($ra->userid);
$user->firstname = $ra->firstname; unset($ra->firstname);
$user->lastname = $ra->lastname; unset($ra->lastname);
$ra->user = $user;
if ($ra->contextlevel == CONTEXT_SYSTEM) {
foreach ($courses as $k => $course) {
$courses[$k]->managers[] = $ra;
}
} elseif ($ra->contextlevel == CONTEXT_COURSECAT) {
if ($allcats === false) {
// It always applies
foreach ($courses as $k => $course) {
$courses[$k]->managers[] = $ra;
}
} else {
foreach ($courses as $k => $course) {
// Note that strpos() returns 0 as "matched at pos 0"
if (strpos($course->context->path, $ra->path.'/')===0) {
// Only add it to subpaths
$courses[$k]->managers[] = $ra;
}
}
}
} else { // course-level
if(!array_key_exists($ra->instanceid, $courses)) {
//this course is not in a list, probably a frontpage course
continue;
}
$courses[$ra->instanceid]->managers[] = $ra;
}
}
$rs->close();
}
return $courses;
}
/**
* Convenience function - lists courses that a user has access to view.
*
* For admins and others with access to "every" course in the system, we should
* try to get courses with explicit RAs.
*
* NOTE: this function is heavily geared towards the perspective of the user
* passed in $userid. So it will hide courses that the user cannot see
* (for any reason) even if called from cron or from another $USER's
* perspective.
*
* If you really want to know what courses are assigned to the user,
* without any hiding or scheming, call the lower-level
* get_user_courses_bycap().
*
*
* Notes inherited from get_user_courses_bycap():
*
* - $fields is an array of fieldnames to ADD
* so name the fields you really need, which will
* be added and uniq'd
*
* - the course records have $c->context which is a fully
* valid context object. Saves you a query per course!
*
* @global object
* @global object
* @global object
* @uses CONTEXT_SYSTEM
* @uses CONTEXT_COURSE
* @uses CONTEXT_COURSECAT
* @param int $userid The user of interest
* @param string $sort the sortorder in the course table
* @param array $fields names of _additional_ fields to return (also accepts a string)
* @param bool $doanything True if using the doanything flag
* @param int $limit Maximum number of records to return, or 0 for unlimited
* @return array Array of {@link $COURSE} of course objects
*/
function get_my_courses($userid, $sort='visible DESC,sortorder ASC', $fields=NULL, $doanything=false,$limit=0) {
global $CFG, $USER, $DB;
// Guest's do not have any courses
$sitecontext = get_context_instance(CONTEXT_SYSTEM);
if (has_capability('moodle/legacy:guest', $sitecontext, $userid, false)) {
return(array());
}
$basefields = array('id', 'category', 'sortorder',
'shortname', 'fullname', 'idnumber',
'guest', 'startdate', 'visible',
'newsitems', 'cost', 'enrol',
'groupmode', 'groupmodeforce');
if (!is_null($fields) && is_string($fields)) {
if (empty($fields)) {
$fields = $basefields;
} else {
// turn the fields from a string to an array that
// get_user_courses_bycap() will like...
$fields = explode(',',$fields);
$fields = array_map('trim', $fields);
$fields = array_unique(array_merge($basefields, $fields));
}
} elseif (is_array($fields)) {
$fields = array_unique(array_merge($basefields, $fields));
} else {
$fields = $basefields;
}
$orderby = '';
$sort = trim($sort);
if (!empty($sort)) {
$rawsorts = explode(',', $sort);
$sorts = array();
foreach ($rawsorts as $rawsort) {
$rawsort = trim($rawsort);
if (strpos($rawsort, 'c.') === 0) {
$rawsort = substr($rawsort, 2);
}
$sorts[] = trim($rawsort);
}
$sort = 'c.'.implode(',c.', $sorts);
$orderby = "ORDER BY $sort";
}
//
// Logged-in user - Check cached courses
//
// NOTE! it's a _string_ because
// - it's all we'll ever use
// - it serialises much more compact than an array
// this a big concern here - cost of serialise
// and unserialise gets huge as the session grows
//
// If the courses are too many - it won't be set
// for large numbers of courses, caching in the session
// has marginal benefits (costs too much, not
// worthwhile...) and we may hit SQL parser limits
// because we use IN()
//
if ($userid === $USER->id) {
if (isset($USER->loginascontext)
&& $USER->loginascontext->contextlevel == CONTEXT_COURSE) {
// list _only_ this course
// anything else is asking for trouble...
$courseids = $USER->loginascontext->instanceid;
} elseif (isset($USER->mycourses)
&& is_string($USER->mycourses)) {
if ($USER->mycourses === '') {
// empty str means: user has no courses
// ... so do the easy thing...
return array();
} else {
$courseids = $USER->mycourses;
}
}
if (isset($courseids)) {
// The data massaging here MUST be kept in sync with
// get_user_courses_bycap() so we return
// the same...
// (but here we don't need to check has_cap)
$coursefields = 'c.' .join(',c.', $fields);
$sql = "SELECT $coursefields,
ctx.id AS ctxid, ctx.path AS ctxpath,
ctx.depth as ctxdepth, ctx.contextlevel AS ctxlevel,
cc.path AS categorypath
FROM {course} c
JOIN {course_categories} cc ON c.category=cc.id
JOIN {context} ctx
ON (c.id=ctx.instanceid AND ctx.contextlevel=".CONTEXT_COURSE.")
WHERE c.id IN ($courseids)
$orderby";
$rs = $DB->get_recordset_sql($sql);
$courses = array();
$cc = 0; // keep count
foreach ($rs as $c) {
// build the context obj
$c = make_context_subobj($c);
if ($limit > 0 && $cc >= $limit) {
break;
}
$courses[$c->id] = $c;
$cc++;
}
$rs->close();
return $courses;
}
}
// Non-cached - get accessinfo
if ($userid === $USER->id && isset($USER->access)) {
$accessinfo = $USER->access;
} else {
$accessinfo = get_user_access_sitewide($userid);
}
$courses = get_user_courses_bycap($userid, 'moodle/course:view', $accessinfo,
$doanything, $sort, $fields,
$limit);
$cats = NULL;
// If we have to walk category visibility
// to eval course visibility, get the categories
if (empty($CFG->allowvisiblecoursesinhiddencategories)) {
$sql = "SELECT cc.id, cc.path, cc.visible,
ctx.id AS ctxid, ctx.path AS ctxpath,
ctx.depth as ctxdepth, ctx.contextlevel AS ctxlevel
FROM {course_categories} cc
JOIN {context} ctx ON (cc.id = ctx.instanceid)
WHERE ctx.contextlevel = ".CONTEXT_COURSECAT."
ORDER BY cc.id";
$rs = $DB->get_recordset_sql($sql);
// Using a temporary array instead of $cats here, to avoid a "true" result when isnull($cats) further down
$categories = array();
foreach($rs as $course_cat) {
// build the context obj
$course_cat = make_context_subobj($course_cat);
$categories[$course_cat->id] = $course_cat;
}
$rs->close();
if (!empty($categories)) {
$cats = $categories;
}
unset($course_cat);
}
//
// Strangely, get_my_courses() is expected to return the
// array keyed on id, which messes up the sorting
// So do that, and also cache the ids in the session if appropriate
//
$kcourses = array();
$courses_count = count($courses);
$cacheids = NULL;
$vcatpaths = array();
if ($userid === $USER->id && $courses_count < 500) {
$cacheids = array();
}
for ($n=0; $n<$courses_count; $n++) {
//
// Check whether $USER (not $userid) can _actually_ see them
// Easy if $CFG->allowvisiblecoursesinhiddencategories
// is set, and we don't have to care about categories.
// Lots of work otherwise... (all in mem though!)
//
$cansee = false;
if (is_null($cats)) { // easy rules!
if ($courses[$n]->visible == true) {
$cansee = true;
} elseif (has_capability('moodle/course:viewhiddencourses',
$courses[$n]->context, $USER->id)) {
$cansee = true;