forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
datalib.php
1970 lines (1707 loc) · 67.3 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 core
* @subpackage lib
* @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
* @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
*/
defined('MOODLE_INTERNAL') || die();
/**
* 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
*
* @static stdClass $mainadmin
* @return stdClass {@link $USER} record from DB, false if not found
*/
function get_admin() {
static $mainadmin = null;
if (!isset($mainadmin)) {
if (! $admins = get_admins()) {
return false;
}
//TODO: add some admin setting for specifying of THE main admin
// for now return the first assigned admin
$mainadmin = reset($admins);
}
// we must clone this otherwise code outside can break the static var
return clone($mainadmin);
}
/**
* Returns list of all admins, using 1 DB query
*
* @return array
*/
function get_admins() {
global $DB, $CFG;
if (empty($CFG->siteadmins)) { // Should not happen on an ordinary site
return array();
}
$sql = "SELECT u.*
FROM {user} u
WHERE u.deleted = 0 AND u.id IN ($CFG->siteadmins)";
return $DB->get_records_sql($sql);
}
/**
* 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;
$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 (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('u.email', ':search2', false).")";
$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, $CFG;
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);
}
$fullname = $DB->sql_fullname();
$select = " id <> :guestid AND deleted = 0";
$params = array('guestid'=>$CFG->siteguest);
if (!empty($search)){
$search = trim($search);
$select .= " AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('email', ':search2', false)." 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 ".$DB->sql_like('firstname', ':fni', false, false);
$params['fni'] = "$firstinitial%";
}
if ($lastinitial) {
$select .= " AND ".$DB->sql_like('lastname', ':lni', false, false);
$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;
$fullname = $DB->sql_fullname();
$select = "deleted <> 1";
$params = array();
if (!empty($search)) {
$search = trim($search);
$select .= " AND (". $DB->sql_like($fullname, ':search1', false, false).
" OR ". $DB->sql_like('email', ':search2', false, false).
" OR username = :search3)";
$params['search1'] = "%$search%";
$params['search2'] = "%$search%";
$params['search3'] = "$search";
}
if ($firstinitial) {
$select .= " AND ". $DB->sql_like('firstname', ':fni', false, false);
$params['fni'] = "$firstinitial%";
}
if ($lastinitial) {
$select .= " AND ". $DB->sql_like('lastname', ':lni', false, false);
$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, $CFG;
return $DB->get_records_sql("SELECT *
FROM {user}
WHERE confirmed = 1 AND deleted = 0 AND id <> ?", array($CFG->siteguest));
}
/// 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();
list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
$sql = "SELECT $fields $ccselect
FROM {course} c
$ccjoin
$categoryselect
$sortstatement";
// pull out all course matching the cat
if ($courses = $DB->get_records_sql($sql, $params)) {
// loop throught them
foreach ($courses as $course) {
context_instance_preload($course);
if (isset($course->visible) && $course->visible <= 0) {
// for hidden courses, require visibility check
if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
$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 = "";
}
list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
$totalcount = 0;
if (!$limitfrom) {
$limitfrom = 0;
}
$visiblecourses = array();
$sql = "SELECT $fields $ccselect
FROM {course} c
$ccjoin
$categoryselect
ORDER BY $sort";
// pull out all course matching the cat
$rs = $DB->get_recordset_sql($sql, $params);
// iteration will have to be done inside loop to keep track of the limitfrom and limitnum
foreach($rs as $course) {
context_instance_preload($course);
if ($course->visible <= 0) {
// for hidden courses, require visibility check
if (has_capability('moodle/course:viewhiddencourses', get_context_instance(CONTEXT_COURSE, $course->id))) {
$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->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',
'startdate', 'visible',
'newsitems', '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
list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
$sql = "SELECT $coursefields $ccselect
FROM {course} c
$ccjoin
$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) {
context_instance_preload($course);
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
$courses[$k] = $course;
$courses[$k]->managers = array();
if ($allcats === false) {
// single cat, so take just the first one...
if ($catpath === NULL) {
$catpath = preg_replace(':/\d+$:', '', $coursecontext->path);
}
} else {
// chop off the contextid of the course itself
// like dirname() does...
$catpaths[] = preg_replace(':/\d+$:', '', $coursecontext->path);
}
}
} else {
return array(); // no courses!
}
$CFG->coursecontact = trim($CFG->coursecontact);
if (empty($CFG->coursecontact)) {
return $courses;
}
$managerroles = explode(',', $CFG->coursecontact);
$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,
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->coursecontact})
$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;
}
} else if ($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) {
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
// Note that strpos() returns 0 as "matched at pos 0"
if (strpos($coursecontext->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;
}
/**
* A list of courses that match a search
*
* @global object
* @global object
* @param array $searchterms An array of search criteria
* @param string $sort A field and direction to sort by
* @param int $page The page number to get
* @param int $recordsperpage The number of records per page
* @param int $totalcount Passed in by reference.
* @return object {@link $COURSE} records
*/
function get_courses_search($searchterms, $sort='fullname ASC', $page=0, $recordsperpage=50, &$totalcount) {
global $CFG, $DB;
if ($DB->sql_regex_supported()) {
$REGEXP = $DB->sql_regex(true);
$NOTREGEXP = $DB->sql_regex(false);
}
$searchcond = array();
$params = array();
$i = 0;
$concat = $DB->sql_concat('c.summary', "' '", 'c.fullname');
foreach ($searchterms as $searchterm) {
$i++;
$NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
/// will use it to simulate the "-" operator with LIKE clause
/// Under Oracle and MSSQL, trim the + and - operators and perform
/// simpler LIKE (or NOT LIKE) queries
if (!$DB->sql_regex_supported()) {
if (substr($searchterm, 0, 1) == '-') {
$NOT = true;
}
$searchterm = trim($searchterm, '+-');
}
// TODO: +- may not work for non latin languages
if (substr($searchterm,0,1) == '+') {
$searchterm = trim($searchterm, '+-');
$searchterm = preg_quote($searchterm, '|');
$searchcond[] = "$concat $REGEXP :ss$i";
$params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
} else if (substr($searchterm,0,1) == "-") {
$searchterm = trim($searchterm, '+-');
$searchterm = preg_quote($searchterm, '|');
$searchcond[] = "$concat $NOTREGEXP :ss$i";
$params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
} else {
$searchcond[] = $DB->sql_like($concat,":ss$i", false, true, $NOT);
$params['ss'.$i] = "%$searchterm%";
}
}
if (empty($searchcond)) {
$totalcount = 0;
return array();
}
$searchcond = implode(" AND ", $searchcond);
$courses = array();
$c = 0; // counts how many visible courses we've seen
// Tiki pagination
$limitfrom = $page * $recordsperpage;
$limitto = $limitfrom + $recordsperpage;
list($ccselect, $ccjoin) = context_instance_preload_sql('c.id', CONTEXT_COURSE, 'ctx');
$sql = "SELECT c.* $ccselect
FROM {course} c
$ccjoin
WHERE $searchcond AND c.id <> ".SITEID."
ORDER BY $sort";
$rs = $DB->get_recordset_sql($sql, $params);
foreach($rs as $course) {
context_instance_preload($course);
$coursecontext = get_context_instance(CONTEXT_COURSE, $course->id);
if ($course->visible || has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
// Don't exit this loop till the end
// we need to count all the visible courses
// to update $totalcount
if ($c >= $limitfrom && $c < $limitto) {
$courses[$course->id] = $course;
}
$c++;
}
}
$rs->close();
// our caller expects 2 bits of data - our return
// array, and an updated $totalcount
$totalcount = $c;
return $courses;
}
/**
* Returns a sorted list of categories. Each category object has a context
* property that is a context object.
*
* When asking for $parent='none' it will return all the categories, regardless
* of depth. Wheen asking for a specific parent, the default is to return
* a "shallow" resultset. Pass false to $shallow and it will return all
* the child categories as well.
*
* @global object
* @uses CONTEXT_COURSECAT
* @param string $parent The parent category if any
* @param string $sort the sortorder
* @param bool $shallow - set to false to get the children too
* @return array of categories
*/
function get_categories($parent='none', $sort=NULL, $shallow=true) {
global $DB;
if ($sort === NULL) {
$sort = 'ORDER BY cc.sortorder ASC';
} elseif ($sort ==='') {
// leave it as empty
} else {
$sort = "ORDER BY $sort";
}
list($ccselect, $ccjoin) = context_instance_preload_sql('cc.id', CONTEXT_COURSECAT, 'ctx');
if ($parent === 'none') {
$sql = "SELECT cc.* $ccselect
FROM {course_categories} cc
$ccjoin
$sort";
$params = array();
} elseif ($shallow) {
$sql = "SELECT cc.* $ccselect
FROM {course_categories} cc
$ccjoin
WHERE cc.parent=?
$sort";
$params = array($parent);
} else {
$sql = "SELECT cc.* $ccselect
FROM {course_categories} cc
$ccjoin
JOIN {course_categories} ccp
ON (cc.path LIKE ".$DB->sql_concat('ccp.path',"'%'").")
WHERE ccp.id=?
$sort";
$params = array($parent);
}
$categories = array();
$rs = $DB->get_recordset_sql($sql, $params);
foreach($rs as $cat) {
context_instance_preload($cat);
$catcontext = get_context_instance(CONTEXT_COURSECAT, $cat->id);
if ($cat->visible || has_capability('moodle/category:viewhiddencategories', $catcontext)) {
$categories[$cat->id] = $cat;
}
}
$rs->close();
return $categories;
}
/**
* Returns an array of category ids of all the subcategories for a given
* category.
*
* @global object
* @param int $catid - The id of the category whose subcategories we want to find.
* @return array of category ids.
*/
function get_all_subcategories($catid) {
global $DB;
$subcats = array();
if ($categories = $DB->get_records('course_categories', array('parent'=>$catid))) {
foreach ($categories as $cat) {
array_push($subcats, $cat->id);
$subcats = array_merge($subcats, get_all_subcategories($cat->id));
}
}
return $subcats;
}
/**
* Return specified category, default if given does not exist
*
* @global object
* @uses MAX_COURSES_IN_CATEGORY
* @uses CONTEXT_COURSECAT
* @uses SYSCONTEXTID
* @param int $catid course category id
* @return object caregory
*/
function get_course_category($catid=0) {
global $DB;
$category = false;
if (!empty($catid)) {
$category = $DB->get_record('course_categories', array('id'=>$catid));
}
if (!$category) {
// the first category is considered default for now
if ($category = $DB->get_records('course_categories', null, 'sortorder', '*', 0, 1)) {
$category = reset($category);
} else {
$cat = new stdClass();
$cat->name = get_string('miscellaneous');
$cat->depth = 1;
$cat->sortorder = MAX_COURSES_IN_CATEGORY;
$cat->timemodified = time();
$catid = $DB->insert_record('course_categories', $cat);
// make sure category context exists
get_context_instance(CONTEXT_COURSECAT, $catid);
mark_context_dirty('/'.SYSCONTEXTID);
fix_course_sortorder(); // Required to build course_categories.depth and .path.
$category = $DB->get_record('course_categories', array('id'=>$catid));
}
}
return $category;
}
/**
* Fixes course category and course sortorder, also verifies category and course parents and paths.
* (circular references are not fixed)
*
* @global object
* @global object
* @uses MAX_COURSES_IN_CATEGORY
* @uses MAX_COURSE_CATEGORIES
* @uses SITEID
* @uses CONTEXT_COURSE
* @return void
*/
function fix_course_sortorder() {
global $DB, $SITE;
//WARNING: this is PHP5 only code!
if ($unsorted = $DB->get_records('course_categories', array('sortorder'=>0))) {
//move all categories that are not sorted yet to the end
$DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('sortorder'=>0));
}
$allcats = $DB->get_records('course_categories', null, 'sortorder, id', 'id, sortorder, parent, depth, path');
$topcats = array();
$brokencats = array();
foreach ($allcats as $cat) {
$sortorder = (int)$cat->sortorder;
if (!$cat->parent) {
while(isset($topcats[$sortorder])) {
$sortorder++;
}
$topcats[$sortorder] = $cat;
continue;
}
if (!isset($allcats[$cat->parent])) {
$brokencats[] = $cat;
continue;
}
if (!isset($allcats[$cat->parent]->children)) {
$allcats[$cat->parent]->children = array();
}
while(isset($allcats[$cat->parent]->children[$sortorder])) {
$sortorder++;
}
$allcats[$cat->parent]->children[$sortorder] = $cat;
}
unset($allcats);
// add broken cats to category tree
if ($brokencats) {
$defaultcat = reset($topcats);
foreach ($brokencats as $cat) {
$topcats[] = $cat;
}
}
// now walk recursively the tree and fix any problems found
$sortorder = 0;
$fixcontexts = array();
_fix_course_cats($topcats, $sortorder, 0, 0, '', $fixcontexts);
// detect if there are "multiple" frontpage courses and fix them if needed
$frontcourses = $DB->get_records('course', array('category'=>0), 'id');
if (count($frontcourses) > 1) {
if (isset($frontcourses[SITEID])) {
$frontcourse = $frontcourses[SITEID];
unset($frontcourses[SITEID]);