forked from moodle/moodle
-
Notifications
You must be signed in to change notification settings - Fork 0
/
datalib.php
2016 lines (1752 loc) · 70.9 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
* @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.
*
* We allow overwrites from config.php, useful to ensure coherence in performance
* tests results.
*/
if (!defined('LASTACCESS_UPDATE_SECS')) {
define('LASTACCESS_UPDATE_SECS', 60);
}
/**
* Returns $user object of the main admin user
*
* @static stdClass $mainadmin
* @return stdClass {@link $USER} record from DB, false if not found
*/
function get_admin() {
global $CFG, $DB;
static $mainadmin = null;
static $prevadmins = null;
if (empty($CFG->siteadmins)) {
// Should not happen on an ordinary site.
// It does however happen during unit tests.
return false;
}
if (isset($mainadmin) and $prevadmins === $CFG->siteadmins) {
return clone($mainadmin);
}
$mainadmin = null;
foreach (explode(',', $CFG->siteadmins) as $id) {
if ($user = $DB->get_record('user', array('id'=>$id, 'deleted'=>0))) {
$mainadmin = $user;
break;
}
}
if ($mainadmin) {
$prevadmins = $CFG->siteadmins;
return clone($mainadmin);
} else {
// this should not happen
return false;
}
}
/**
* 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)";
// We want the same order as in $CFG->siteadmins.
$records = $DB->get_records_sql($sql);
$admins = array();
foreach (explode(',', $CFG->siteadmins) as $id) {
$id = (int)$id;
if (!isset($records[$id])) {
// User does not exist, this should not happen.
continue;
}
$admins[$records[$id]->id] = $records[$id];
}
return $admins;
}
/**
* 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, 'ex', 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 = context_course::instance($courseid);
// We want to query both the current context and parent contexts.
list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
$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 $relatedctxsql
$except
$order";
$params = array_merge($params, $relatedctxparams);
return $DB->get_records_sql($sql, $params);
}
}
}
/**
* Returns SQL used to search through user table to find users (in a query
* which may also join and apply other conditions).
*
* You can combine this SQL with an existing query by adding 'AND $sql' to the
* WHERE clause of your query (where $sql is the first element in the array
* returned by this function), and merging in the $params array to the parameters
* of your query (where $params is the second element). Your query should use
* named parameters such as :param, rather than the question mark style.
*
* There are examples of basic usage in the unit test for this function.
*
* @param string $search the text to search for (empty string = find all)
* @param string $u the table alias for the user table in the query being
* built. May be ''.
* @param bool $searchanywhere If true (default), searches in the middle of
* names, otherwise only searches at start
* @param array $extrafields Array of extra user fields to include in search
* @param array $exclude Array of user ids to exclude (empty = don't exclude)
* @param array $includeonly If specified, only returns users that have ids
* incldued in this array (empty = don't restrict)
* @return array an array with two elements, a fragment of SQL to go in the
* where clause the query, and an associative array containing any required
* parameters (using named placeholders).
*/
function users_search_sql($search, $u = 'u', $searchanywhere = true, array $extrafields = array(),
array $exclude = null, array $includeonly = null) {
global $DB, $CFG;
$params = array();
$tests = array();
if ($u) {
$u .= '.';
}
// If we have a $search string, put a field LIKE '$search%' condition on each field.
if ($search) {
$conditions = array(
$DB->sql_fullname($u . 'firstname', $u . 'lastname'),
$conditions[] = $u . 'lastname'
);
foreach ($extrafields as $field) {
$conditions[] = $u . $field;
}
if ($searchanywhere) {
$searchparam = '%' . $search . '%';
} else {
$searchparam = $search . '%';
}
$i = 0;
foreach ($conditions as $key => $condition) {
$conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false, false);
$params["con{$i}00"] = $searchparam;
$i++;
}
$tests[] = '(' . implode(' OR ', $conditions) . ')';
}
// Add some additional sensible conditions.
$tests[] = $u . "id <> :guestid";
$params['guestid'] = $CFG->siteguest;
$tests[] = $u . 'deleted = 0';
$tests[] = $u . 'confirmed = 1';
// If we are being asked to exclude any users, do that.
if (!empty($exclude)) {
list($usertest, $userparams) = $DB->get_in_or_equal($exclude, SQL_PARAMS_NAMED, 'ex', false);
$tests[] = $u . 'id ' . $usertest;
$params = array_merge($params, $userparams);
}
// If we are validating a set list of userids, add an id IN (...) test.
if (!empty($includeonly)) {
list($usertest, $userparams) = $DB->get_in_or_equal($includeonly, SQL_PARAMS_NAMED, 'val');
$tests[] = $u . 'id ' . $usertest;
$params = array_merge($params, $userparams);
}
// In case there are no tests, add one result (this makes it easier to combine
// this with an existing query as you can always add AND $sql).
if (empty($tests)) {
$tests[] = '1 = 1';
}
// Combing the conditions and return.
return array(implode(' AND ', $tests), $params);
}
/**
* This function generates the standard ORDER BY clause for use when generating
* lists of users. If you don't have a reason to use a different order, then
* you should use this method to generate the order when displaying lists of users.
*
* If the optional $search parameter is passed, then exact matches to the search
* will be sorted first. For example, suppose you have two users 'Al Zebra' and
* 'Alan Aardvark'. The default sort is Alan, then Al. If, however, you search for
* 'Al', then Al will be listed first. (With two users, this is not a big deal,
* but with thousands of users, it is essential.)
*
* The list of fields scanned for exact matches are:
* - firstname
* - lastname
* - $DB->sql_fullname
* - those returned by get_extra_user_fields
*
* If named parameters are used (which is the default, and highly recommended),
* then the parameter names are like :usersortexactN, where N is an int.
*
* The simplest possible example use is:
* list($sort, $params) = users_order_by_sql();
* $sql = 'SELECT * FROM {users} ORDER BY ' . $sort;
*
* A more complex example, showing that this sort can be combined with other sorts:
* list($sort, $sortparams) = users_order_by_sql('u');
* $sql = "SELECT g.id AS groupid, gg.groupingid, u.id AS userid, u.firstname, u.lastname, u.idnumber, u.username
* FROM {groups} g
* LEFT JOIN {groupings_groups} gg ON g.id = gg.groupid
* LEFT JOIN {groups_members} gm ON g.id = gm.groupid
* LEFT JOIN {user} u ON gm.userid = u.id
* WHERE g.courseid = :courseid $groupwhere $groupingwhere
* ORDER BY g.name, $sort";
* $params += $sortparams;
*
* An example showing the use of $search:
* list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
* $order = ' ORDER BY ' . $sort;
* $params += $sortparams;
* $availableusers = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);
*
* @param string $usertablealias (optional) any table prefix for the {users} table. E.g. 'u'.
* @param string $search (optional) a current search string. If given,
* any exact matches to this string will be sorted first.
* @param context $context the context we are in. Use by get_extra_user_fields.
* Defaults to $PAGE->context.
* @return array with two elements:
* string SQL fragment to use in the ORDER BY clause. For example, "firstname, lastname".
* array of parameters used in the SQL fragment.
*/
function users_order_by_sql($usertablealias = '', $search = null, context $context = null) {
global $DB, $PAGE;
if ($usertablealias) {
$tableprefix = $usertablealias . '.';
} else {
$tableprefix = '';
}
$sort = "{$tableprefix}lastname, {$tableprefix}firstname, {$tableprefix}id";
$params = array();
if (!$search) {
return array($sort, $params);
}
if (!$context) {
$context = $PAGE->context;
}
$exactconditions = array();
$paramkey = 'usersortexact1';
$exactconditions[] = $DB->sql_fullname($tableprefix . 'firstname', $tableprefix . 'lastname') .
' = :' . $paramkey;
$params[$paramkey] = $search;
$paramkey++;
$fieldstocheck = array_merge(array('firstname', 'lastname'), get_extra_user_fields($context));
foreach ($fieldstocheck as $key => $field) {
$exactconditions[] = 'LOWER(' . $tableprefix . $field . ') = LOWER(:' . $paramkey . ')';
$params[$paramkey] = $search;
$paramkey++;
}
$sort = 'CASE WHEN ' . implode(' OR ', $exactconditions) .
' THEN 0 ELSE 1 END, ' . $sort;
return array($sort, $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, 'ex', false);
$params = $params + $eparams;
$select .= " 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);
}
}
/**
* Return filtered (if provided) list of users in site, except guest and deleted users.
*
* @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
* @param stdClass $extracontext If specified, will include user 'extra fields'
* as appropriate for current user and given context
* @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, $extracontext = null) {
global $DB, $CFG;
$fullname = $DB->sql_fullname();
$select = "deleted <> 1 AND id <> :guestid";
$params = array('guestid' => $CFG->siteguest);
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";
}
// If a context is specified, get extra user fields that the current user
// is supposed to see.
$extrafields = '';
if ($extracontext) {
$extrafields = get_extra_user_fields_sql($extracontext, '', '',
array('id', 'username', 'email', 'firstname', 'lastname', 'city', 'country',
'lastaccess', 'confirmed', 'mnethostid'));
}
$namefields = get_all_user_name_fields(true);
$extrafields = "$extrafields, $namefields";
// warning: will return UNCONFIRMED USERS
return $DB->get_records_sql("SELECT id, username, email, city, country, lastaccess, confirmed, mnethostid, suspended $extrafields
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');
}
}
/**
* Gets a course object from database. If the course id corresponds to an
* already-loaded $COURSE or $SITE object, then the loaded object will be used,
* saving a database query.
*
* If it reuses an existing object, by default the object will be cloned. This
* means you can modify the object safely without affecting other code.
*
* @param int $courseid Course id
* @param bool $clone If true (default), makes a clone of the record
* @return stdClass A course object
* @throws dml_exception If not found in database
*/
function get_course($courseid, $clone = true) {
global $DB, $COURSE, $SITE;
if (!empty($COURSE->id) && $COURSE->id == $courseid) {
return $clone ? clone($COURSE) : $COURSE;
} else if (!empty($SITE->id) && $SITE->id == $courseid) {
return $clone ? clone($SITE) : $SITE;
} else {
return $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
}
}
/**
* 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();
$ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
$ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
$params['contextlevel'] = CONTEXT_COURSE;
$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_helper::preload_from_record($course);
if (isset($course->visible) && $course->visible <= 0) {
// for hidden courses, require visibility check
if (has_capability('moodle/course:viewhiddencourses', context_course::instance($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 = "";
}
$ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
$ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
$params['contextlevel'] = CONTEXT_COURSE;
$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_helper::preload_from_record($course);
if ($course->visible <= 0) {
// for hidden courses, require visibility check
if (has_capability('moodle/course:viewhiddencourses', context_course::instance($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;
}
/**
* 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, $page, $recordsperpage, &$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;
// Thanks Oracle for your non-ansi concat and type limits in coalesce. MDL-29912
if ($DB->get_dbfamily() == 'oracle') {
$concat = "(c.summary|| ' ' || c.fullname || ' ' || c.idnumber || ' ' || c.shortname)";
} else {
$concat = $DB->sql_concat("COALESCE(c.summary, '')", "' '", 'c.fullname', "' '", 'c.idnumber', "' '", 'c.shortname');
}
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;
$ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
$ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
$params['contextlevel'] = CONTEXT_COURSE;
$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) {
if (!$course->visible) {
// preload contexts only for hidden courses or courses we need to return
context_helper::preload_from_record($course);
$coursecontext = context_course::instance($course->id);
if (!has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
continue;
}
}
// 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;
}
/**
* 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 there are any changes made to courses or categories we will trigger
// the cache events to purge all cached courses/categories data
$cacheevents = array();
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));
$cacheevents['changesincoursecat'] = true;
}
$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();
if (_fix_course_cats($topcats, $sortorder, 0, 0, '', $fixcontexts)) {
$cacheevents['changesincoursecat'] = true;
}
// 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]);
} else {
$frontcourse = array_shift($frontcourses);
}
$defaultcat = reset($topcats);
foreach ($frontcourses as $course) {
$DB->set_field('course', 'category', $defaultcat->id, array('id'=>$course->id));
$context = context_course::instance($course->id);
$fixcontexts[$context->id] = $context;
$cacheevents['changesincourse'] = true;
}
unset($frontcourses);
} else {
$frontcourse = reset($frontcourses);
}
// now fix the paths and depths in context table if needed
if ($fixcontexts) {
foreach ($fixcontexts as $fixcontext) {
$fixcontext->reset_paths(false);
}
context_helper::build_all_paths(false);
unset($fixcontexts);
$cacheevents['changesincourse'] = true;
$cacheevents['changesincoursecat'] = true;
}
// release memory
unset($topcats);
unset($brokencats);
unset($fixcontexts);
// fix frontpage course sortorder
if ($frontcourse->sortorder != 1) {
$DB->set_field('course', 'sortorder', 1, array('id'=>$frontcourse->id));
$cacheevents['changesincourse'] = true;
}
// now fix the course counts in category records if needed
$sql = "SELECT cc.id, cc.coursecount, COUNT(c.id) AS newcount
FROM {course_categories} cc
LEFT JOIN {course} c ON c.category = cc.id
GROUP BY cc.id, cc.coursecount
HAVING cc.coursecount <> COUNT(c.id)";
if ($updatecounts = $DB->get_records_sql($sql)) {
// categories with more courses than MAX_COURSES_IN_CATEGORY
$categories = array();
foreach ($updatecounts as $cat) {
$cat->coursecount = $cat->newcount;
if ($cat->coursecount >= MAX_COURSES_IN_CATEGORY) {
$categories[] = $cat->id;
}
unset($cat->newcount);
$DB->update_record_raw('course_categories', $cat, true);
}
if (!empty($categories)) {
$str = implode(', ', $categories);
debugging("The number of courses (category id: $str) has reached MAX_COURSES_IN_CATEGORY (" . MAX_COURSES_IN_CATEGORY . "), it will cause a sorting performance issue, please increase the value of MAX_COURSES_IN_CATEGORY in lib/datalib.php file. See tracker issue: MDL-25669", DEBUG_DEVELOPER);
}
$cacheevents['changesincoursecat'] = true;
}
// now make sure that sortorders in course table are withing the category sortorder ranges
$sql = "SELECT DISTINCT cc.id, cc.sortorder
FROM {course_categories} cc
JOIN {course} c ON c.category = cc.id
WHERE c.sortorder < cc.sortorder OR c.sortorder > cc.sortorder + ".MAX_COURSES_IN_CATEGORY;
if ($fixcategories = $DB->get_records_sql($sql)) {
//fix the course sortorder ranges
foreach ($fixcategories as $cat) {
$sql = "UPDATE {course}
SET sortorder = ".$DB->sql_modulo('sortorder', MAX_COURSES_IN_CATEGORY)." + ?
WHERE category = ?";
$DB->execute($sql, array($cat->sortorder, $cat->id));
}
$cacheevents['changesincoursecat'] = true;