Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 1
<?php
2
// This file is part of Moodle - http://moodle.org/
3
//
4
// Moodle is free software: you can redistribute it and/or modify
5
// it under the terms of the GNU General Public License as published by
6
// the Free Software Foundation, either version 3 of the License, or
7
// (at your option) any later version.
8
//
9
// Moodle is distributed in the hope that it will be useful,
10
// but WITHOUT ANY WARRANTY; without even the implied warranty of
11
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12
// GNU General Public License for more details.
13
//
14
// You should have received a copy of the GNU General Public License
15
// along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
16
 
17
/**
18
 * Library of functions for database manipulation.
19
 *
20
 * Other main libraries:
21
 * - weblib.php - functions that produce web output
22
 * - moodlelib.php - general-purpose Moodle functions
23
 *
24
 * @package    core
25
 * @copyright  1999 onwards Martin Dougiamas  {@link http://moodle.com}
26
 * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27
 */
28
 
29
defined('MOODLE_INTERNAL') || die();
30
 
31
/**
32
 * The maximum courses in a category
33
 * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
34
 */
35
define('MAX_COURSES_IN_CATEGORY', 10000);
36
 
37
/**
38
  * The maximum number of course categories
39
  * MAX_COURSES_IN_CATEGORY * MAX_COURSE_CATEGORIES must not be more than max integer!
40
  */
41
define('MAX_COURSE_CATEGORIES', 10000);
42
 
43
/**
44
 * Number of seconds to wait before updating lastaccess information in DB.
45
 *
46
 * We allow overwrites from config.php, useful to ensure coherence in performance
47
 * tests results.
48
 *
49
 * Note: For web service requests in the external_tokens field, we use a different constant
50
 * webservice::TOKEN_LASTACCESS_UPDATE_SECS.
51
 */
52
if (!defined('LASTACCESS_UPDATE_SECS')) {
53
    define('LASTACCESS_UPDATE_SECS', 60);
54
}
55
/**
56
 * The constant value when we use the search option.
57
 */
58
define('USER_SEARCH_STARTS_WITH', 0);
59
define('USER_SEARCH_CONTAINS', 1);
60
define('USER_SEARCH_EXACT_MATCH', 2);
61
 
62
/**
63
 * Returns $user object of the main admin user
64
 *
65
 * @static stdClass $mainadmin
66
 * @return stdClass|false {user} record from DB, false if not found
67
 */
68
function get_admin() {
69
    global $CFG, $DB;
70
 
71
    static $mainadmin = null;
72
    static $prevadmins = null;
73
 
74
    if (empty($CFG->siteadmins)) {
75
        // Should not happen on an ordinary site.
76
        // It does however happen during unit tests.
77
        return false;
78
    }
79
 
80
    if (isset($mainadmin) and $prevadmins === $CFG->siteadmins) {
81
        return clone($mainadmin);
82
    }
83
 
84
    $mainadmin = null;
85
 
86
    foreach (explode(',', $CFG->siteadmins) as $id) {
87
        if ($user = $DB->get_record('user', array('id'=>$id, 'deleted'=>0))) {
88
            $mainadmin = $user;
89
            break;
90
        }
91
    }
92
 
93
    if ($mainadmin) {
94
        $prevadmins = $CFG->siteadmins;
95
        return clone($mainadmin);
96
    } else {
97
        // this should not happen
98
        return false;
99
    }
100
}
101
 
102
/**
103
 * Returns list of all admins, using 1 DB query
104
 *
105
 * @return array
106
 */
107
function get_admins() {
108
    global $DB, $CFG;
109
 
110
    if (empty($CFG->siteadmins)) {  // Should not happen on an ordinary site
111
        return array();
112
    }
113
 
114
    $sql = "SELECT u.*
115
              FROM {user} u
116
             WHERE u.deleted = 0 AND u.id IN ($CFG->siteadmins)";
117
 
118
    // We want the same order as in $CFG->siteadmins.
119
    $records = $DB->get_records_sql($sql);
120
    $admins = array();
121
    foreach (explode(',', $CFG->siteadmins) as $id) {
122
        $id = (int)$id;
123
        if (!isset($records[$id])) {
124
            // User does not exist, this should not happen.
125
            continue;
126
        }
127
        $admins[$records[$id]->id] = $records[$id];
128
    }
129
 
130
    return $admins;
131
}
132
 
133
/**
134
 * Search through course users
135
 *
136
 * If $coursid specifies the site course then this function searches
137
 * through all undeleted and confirmed users
138
 *
139
 * @global object
140
 * @uses SITEID
141
 * @uses SQL_PARAMS_NAMED
142
 * @uses CONTEXT_COURSE
143
 * @param int $courseid The course in question.
144
 * @param int $groupid The group in question.
145
 * @param string $searchtext The string to search for
146
 * @param string $sort A field to sort by
147
 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
148
 * @return array
149
 */
1441 ariadna 150
function search_users($courseid, $groupid, $searchtext, $sort='', ?array $exceptions=null) {
1 efrain 151
    global $DB;
152
 
153
    $fullname  = $DB->sql_fullname('u.firstname', 'u.lastname');
154
 
155
    if (!empty($exceptions)) {
156
        list($exceptions, $params) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex', false);
157
        $except = "AND u.id $exceptions";
158
    } else {
159
        $except = "";
160
        $params = array();
161
    }
162
 
163
    if (!empty($sort)) {
164
        $order = "ORDER BY $sort";
165
    } else {
166
        $order = "";
167
    }
168
 
169
    $select = "u.deleted = 0 AND u.confirmed = 1 AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('u.email', ':search2', false).")";
170
    $params['search1'] = "%$searchtext%";
171
    $params['search2'] = "%$searchtext%";
172
 
173
    if (!$courseid or $courseid == SITEID) {
174
        $sql = "SELECT u.id, u.firstname, u.lastname, u.email
175
                  FROM {user} u
176
                 WHERE $select
177
                       $except
178
                $order";
179
        return $DB->get_records_sql($sql, $params);
180
 
181
    } else {
182
        if ($groupid) {
183
            $sql = "SELECT u.id, u.firstname, u.lastname, u.email
184
                      FROM {user} u
185
                      JOIN {groups_members} gm ON gm.userid = u.id
186
                     WHERE $select AND gm.groupid = :groupid
187
                           $except
188
                     $order";
189
            $params['groupid'] = $groupid;
190
            return $DB->get_records_sql($sql, $params);
191
 
192
        } else {
193
            $context = context_course::instance($courseid);
194
 
195
            // We want to query both the current context and parent contexts.
196
            list($relatedctxsql, $relatedctxparams) = $DB->get_in_or_equal($context->get_parent_context_ids(true), SQL_PARAMS_NAMED, 'relatedctx');
197
 
198
            $sql = "SELECT u.id, u.firstname, u.lastname, u.email
199
                      FROM {user} u
200
                      JOIN {role_assignments} ra ON ra.userid = u.id
201
                     WHERE $select AND ra.contextid $relatedctxsql
202
                           $except
203
                    $order";
204
            $params = array_merge($params, $relatedctxparams);
205
            return $DB->get_records_sql($sql, $params);
206
        }
207
    }
208
}
209
 
210
/**
211
 * Returns SQL used to search through user table to find users (in a query
212
 * which may also join and apply other conditions).
213
 *
214
 * You can combine this SQL with an existing query by adding 'AND $sql' to the
215
 * WHERE clause of your query (where $sql is the first element in the array
216
 * returned by this function), and merging in the $params array to the parameters
217
 * of your query (where $params is the second element). Your query should use
218
 * named parameters such as :param, rather than the question mark style.
219
 *
220
 * There are examples of basic usage in the unit test for this function.
221
 *
222
 * @param string $search the text to search for (empty string = find all)
223
 * @param string $u the table alias for the user table in the query being
224
 *     built. May be ''.
225
 * @param int $searchtype If 0(default): searches at start, 1: searches in the middle of names
226
 *      2: search exact match.
227
 * @param array $extrafields Array of extra user fields to include in search, must be prefixed with table alias if they are not in
228
 *     the user table.
229
 * @param array $exclude Array of user ids to exclude (empty = don't exclude)
230
 * @param array $includeonly If specified, only returns users that have ids
231
 *     incldued in this array (empty = don't restrict)
232
 * @return array an array with two elements, a fragment of SQL to go in the
233
 *     where clause the query, and an associative array containing any required
234
 *     parameters (using named placeholders).
235
 */
236
function users_search_sql(string $search, string $u = 'u', int $searchtype = USER_SEARCH_STARTS_WITH, array $extrafields = [],
1441 ariadna 237
        ?array $exclude = null, ?array $includeonly = null): array {
1 efrain 238
    global $DB, $CFG;
239
    $params = array();
240
    $tests = array();
241
 
242
    if ($u) {
243
        $u .= '.';
244
    }
245
 
246
    if ($search) {
247
        $conditions = array(
248
            $DB->sql_fullname($u . 'firstname', $u . 'lastname'),
249
            $conditions[] = $u . 'lastname'
250
        );
251
        foreach ($extrafields as $field) {
252
            // Add the table alias for the user table if the field doesn't already have an alias.
253
            $conditions[] = strpos($field, '.') !== false ? $field : $u . $field;
254
        }
255
        switch ($searchtype) {
256
            case USER_SEARCH_STARTS_WITH:
257
                // Put a field LIKE 'search%' condition on each field.
258
                $searchparam = $search . '%';
259
                break;
260
            case USER_SEARCH_CONTAINS:
261
                // Put a field LIKE '$search%' condition on each field.
262
                $searchparam = '%' . $search . '%';
263
                break;
264
            case USER_SEARCH_EXACT_MATCH:
265
                // Match exact the $search string.
266
                $searchparam = $search;
267
                break;
268
        }
269
        $i = 0;
270
        foreach ($conditions as $key => $condition) {
271
            $conditions[$key] = $DB->sql_like($condition, ":con{$i}00", false, false);
272
            if ($searchtype === USER_SEARCH_EXACT_MATCH) {
273
                $conditions[$key] = "$condition = :con{$i}00";
274
            }
275
            $params["con{$i}00"] = $searchparam;
276
            $i++;
277
        }
278
        $tests[] = '(' . implode(' OR ', $conditions) . ')';
279
    }
280
 
281
    // Add some additional sensible conditions.
282
    $tests[] = $u . "id <> :guestid";
283
    $params['guestid'] = $CFG->siteguest;
284
    $tests[] = $u . 'deleted = 0';
285
    $tests[] = $u . 'confirmed = 1';
286
 
287
    // If we are being asked to exclude any users, do that.
288
    if (!empty($exclude)) {
289
        list($usertest, $userparams) = $DB->get_in_or_equal($exclude, SQL_PARAMS_NAMED, 'ex', false);
290
        $tests[] = $u . 'id ' . $usertest;
291
        $params = array_merge($params, $userparams);
292
    }
293
 
294
    // If we are validating a set list of userids, add an id IN (...) test.
295
    if (!empty($includeonly)) {
296
        list($usertest, $userparams) = $DB->get_in_or_equal($includeonly, SQL_PARAMS_NAMED, 'val');
297
        $tests[] = $u . 'id ' . $usertest;
298
        $params = array_merge($params, $userparams);
299
    }
300
 
301
    // In case there are no tests, add one result (this makes it easier to combine
302
    // this with an existing query as you can always add AND $sql).
303
    if (empty($tests)) {
304
        $tests[] = '1 = 1';
305
    }
306
 
307
    // Combing the conditions and return.
308
    return array(implode(' AND ', $tests), $params);
309
}
310
 
311
 
312
/**
313
 * This function generates the standard ORDER BY clause for use when generating
314
 * lists of users. If you don't have a reason to use a different order, then
315
 * you should use this method to generate the order when displaying lists of users.
316
 *
317
 * If the optional $search parameter is passed, then exact matches to the search
318
 * will be sorted first. For example, suppose you have two users 'Al Zebra' and
319
 * 'Alan Aardvark'. The default sort is Alan, then Al. If, however, you search for
320
 * 'Al', then Al will be listed first. (With two users, this is not a big deal,
321
 * but with thousands of users, it is essential.)
322
 *
323
 * The list of fields scanned for exact matches are:
324
 *  - firstname
325
 *  - lastname
326
 *  - $DB->sql_fullname
327
 *  - those returned by \core_user\fields::get_identity_fields or those included in $customfieldmappings
328
 *
329
 * If named parameters are used (which is the default, and highly recommended),
330
 * then the parameter names are like :usersortexactN, where N is an int.
331
 *
332
 * The simplest possible example use is:
333
 * list($sort, $params) = users_order_by_sql();
334
 * $sql = 'SELECT * FROM {users} ORDER BY ' . $sort;
335
 *
336
 * A more complex example, showing that this sort can be combined with other sorts:
337
 * list($sort, $sortparams) = users_order_by_sql('u');
338
 * $sql = "SELECT g.id AS groupid, gg.groupingid, u.id AS userid, u.firstname, u.lastname, u.idnumber, u.username
339
 *           FROM {groups} g
340
 *      LEFT JOIN {groupings_groups} gg ON g.id = gg.groupid
341
 *      LEFT JOIN {groups_members} gm ON g.id = gm.groupid
342
 *      LEFT JOIN {user} u ON gm.userid = u.id
343
 *          WHERE g.courseid = :courseid $groupwhere $groupingwhere
344
 *       ORDER BY g.name, $sort";
345
 * $params += $sortparams;
346
 *
347
 * An example showing the use of $search:
348
 * list($sort, $sortparams) = users_order_by_sql('u', $search, $this->get_context());
349
 * $order = ' ORDER BY ' . $sort;
350
 * $params += $sortparams;
351
 * $availableusers = $DB->get_records_sql($fields . $sql . $order, $params, $page*$perpage, $perpage);
352
 *
353
 * @param string $usertablealias (optional) any table prefix for the {users} table. E.g. 'u'.
354
 * @param string $search (optional) a current search string. If given,
355
 *      any exact matches to this string will be sorted first.
356
 * @param context|null $context the context we are in. Used by \core_user\fields::get_identity_fields.
357
 *      Defaults to $PAGE->context.
358
 * @param array $customfieldmappings associative array of mappings for custom fields returned by \core_user\fields::get_sql.
359
 * @return array with two elements:
360
 *      string SQL fragment to use in the ORDER BY clause. For example, "firstname, lastname".
361
 *      array of parameters used in the SQL fragment. If $search is not given, this is guaranteed to be an empty array.
362
 */
1441 ariadna 363
function users_order_by_sql(string $usertablealias = '', ?string $search = null, ?context $context = null,
1 efrain 364
        array $customfieldmappings = []) {
365
    global $DB, $PAGE;
366
 
367
    if ($usertablealias) {
368
        $tableprefix = $usertablealias . '.';
369
    } else {
370
        $tableprefix = '';
371
    }
372
 
373
    $sort = "{$tableprefix}lastname, {$tableprefix}firstname, {$tableprefix}id";
374
    $params = array();
375
 
376
    if (!$search) {
377
        return array($sort, $params);
378
    }
379
 
380
    if (!$context) {
381
        $context = $PAGE->context;
382
    }
383
 
384
    $exactconditions = array();
385
 
386
    $exactconditions[] = $DB->sql_fullname($tableprefix . 'firstname', $tableprefix  . 'lastname') .
1441 ariadna 387
            ' = :usersortexact';
388
    $params['usersortexact'] = $search;
1 efrain 389
 
390
    if ($customfieldmappings) {
391
        $fieldstocheck = array_merge([$tableprefix . 'firstname', $tableprefix . 'lastname'], array_values($customfieldmappings));
392
    } else {
393
        $fieldstocheck = array_merge(['firstname', 'lastname'], \core_user\fields::get_identity_fields($context, false));
394
        $fieldstocheck = array_map(function($field) use ($tableprefix) {
395
            return $tableprefix . $field;
396
        }, $fieldstocheck);
397
    }
398
 
399
    foreach ($fieldstocheck as $key => $field) {
1441 ariadna 400
        $exactconditions[] = 'LOWER(' . $field . ') = LOWER(:usersortfield' . $key . ')';
401
        $params['usersortfield' . $key] = $search;
1 efrain 402
    }
403
 
404
    $sort = 'CASE WHEN ' . implode(' OR ', $exactconditions) .
405
            ' THEN 0 ELSE 1 END, ' . $sort;
406
 
407
    return array($sort, $params);
408
}
409
 
410
/**
411
 * Returns a subset of users
412
 *
413
 * @global object
414
 * @uses DEBUG_DEVELOPER
415
 * @uses SQL_PARAMS_NAMED
416
 * @param bool $get If false then only a count of the records is returned
417
 * @param string $search A simple string to search for
418
 * @param bool $confirmed A switch to allow/disallow unconfirmed users
419
 * @param array $exceptions A list of IDs to ignore, eg 2,4,5,8,9,10
420
 * @param string $sort A SQL snippet for the sorting criteria to use
421
 * @param string $firstinitial Users whose first name starts with $firstinitial
422
 * @param string $lastinitial Users whose last name starts with $lastinitial
423
 * @param string $page The page or records to return
424
 * @param string $recordsperpage The number of records to return per page
425
 * @param string $fields A comma separated list of fields to be returned from the chosen table.
426
 * @return array|int|bool  {@link $USER} records unless get is false in which case the integer count of the records found is returned.
427
 *                        False is returned if an error is encountered.
428
 */
1441 ariadna 429
function get_users($get=true, $search='', $confirmed=false, ?array $exceptions=null, $sort='firstname ASC',
430
                   $firstinitial='', $lastinitial='', $page='', $recordsperpage='', $fields='*', $extraselect='', ?array $extraparams=null) {
1 efrain 431
    global $DB, $CFG;
432
 
433
    if ($get && !$recordsperpage) {
434
        debugging('Call to get_users with $get = true no $recordsperpage limit. ' .
435
                'On large installations, this will probably cause an out of memory error. ' .
436
                'Please think again and change your code so that it does not try to ' .
437
                'load so much data into memory.', DEBUG_DEVELOPER);
438
    }
439
 
440
    $fullname  = $DB->sql_fullname();
441
 
442
    $select = " id <> :guestid AND deleted = 0";
443
    $params = array('guestid'=>$CFG->siteguest);
444
 
445
    if (!empty($search)){
446
        $search = trim($search);
447
        $select .= " AND (".$DB->sql_like($fullname, ':search1', false)." OR ".$DB->sql_like('email', ':search2', false)." OR username = :search3)";
448
        $params['search1'] = "%$search%";
449
        $params['search2'] = "%$search%";
450
        $params['search3'] = "$search";
451
    }
452
 
453
    if ($confirmed) {
454
        $select .= " AND confirmed = 1";
455
    }
456
 
457
    if ($exceptions) {
458
        list($exceptions, $eparams) = $DB->get_in_or_equal($exceptions, SQL_PARAMS_NAMED, 'ex', false);
459
        $params = $params + $eparams;
460
        $select .= " AND id $exceptions";
461
    }
462
 
463
    if ($firstinitial) {
464
        $select .= " AND ".$DB->sql_like('firstname', ':fni', false, false);
465
        $params['fni'] = "$firstinitial%";
466
    }
467
    if ($lastinitial) {
468
        $select .= " AND ".$DB->sql_like('lastname', ':lni', false, false);
469
        $params['lni'] = "$lastinitial%";
470
    }
471
 
472
    if ($extraselect) {
473
        $select .= " AND $extraselect";
474
        $params = $params + (array)$extraparams;
475
    }
476
 
477
    if ($get) {
478
        return $DB->get_records_select('user', $select, $params, $sort, $fields, $page, $recordsperpage);
479
    } else {
480
        return $DB->count_records_select('user', $select, $params);
481
    }
482
}
483
 
484
 
485
/**
486
 * Return filtered (if provided) list of users in site, except guest and deleted users.
487
 *
488
 * @param string $sort An SQL field to sort by
489
 * @param string $dir The sort direction ASC|DESC
490
 * @param int $page The page or records to return
491
 * @param int $recordsperpage The number of records to return per page
492
 * @param string $search A simple string to search for
493
 * @param string $firstinitial Users whose first name starts with $firstinitial
494
 * @param string $lastinitial Users whose last name starts with $lastinitial
495
 * @param string $extraselect An additional SQL select statement to append to the query
496
 * @param array $extraparams Additional parameters to use for the above $extraselect
497
 * @param stdClass $extracontext If specified, will include user 'extra fields'
498
 *   as appropriate for current user and given context
499
 * @return array Array of {@link $USER} records
500
 */
501
function get_users_listing($sort='lastaccess', $dir='ASC', $page=0, $recordsperpage=0,
502
                           $search='', $firstinitial='', $lastinitial='', $extraselect='',
1441 ariadna 503
                           ?array $extraparams=null, $extracontext = null) {
1 efrain 504
    global $DB, $CFG;
505
 
506
    $fullname  = $DB->sql_fullname();
507
 
508
    $select = "deleted <> 1 AND u.id <> :guestid";
509
    $params = array('guestid' => $CFG->siteguest);
510
 
511
    if (!empty($search)) {
512
        $search = trim($search);
513
        $select .= " AND (". $DB->sql_like($fullname, ':search1', false, false).
514
                   " OR ". $DB->sql_like('email', ':search2', false, false).
515
                   " OR username = :search3)";
516
        $params['search1'] = "%$search%";
517
        $params['search2'] = "%$search%";
518
        $params['search3'] = "$search";
519
    }
520
 
521
    if ($firstinitial) {
522
        $select .= " AND ". $DB->sql_like('firstname', ':fni', false, false);
523
        $params['fni'] = "$firstinitial%";
524
    }
525
    if ($lastinitial) {
526
        $select .= " AND ". $DB->sql_like('lastname', ':lni', false, false);
527
        $params['lni'] = "$lastinitial%";
528
    }
529
 
530
    if ($extraselect) {
531
        // The extra WHERE clause may refer to the 'id' column which can now be ambiguous because we
532
        // changed the query to include joins, so replace any 'id' that is on its own (no alias)
533
        // with 'u.id'.
534
        $extraselect = preg_replace('~([ =]|^)id([ =]|$)~', '$1u.id$2', $extraselect);
535
        $select .= " AND $extraselect";
536
        $params = $params + (array)$extraparams;
537
    }
538
 
539
    // If a context is specified, get extra user fields that the current user
540
    // is supposed to see, otherwise just get the name fields.
541
    $userfields = \core_user\fields::for_name();
542
    if ($extracontext) {
543
        $userfields->with_identity($extracontext, true);
544
    }
545
 
546
    $userfields->excluding('id');
547
    $userfields->including('username', 'email', 'city', 'country', 'lastaccess', 'confirmed', 'mnethostid', 'suspended');
548
    ['selects' => $selects, 'joins' => $joins, 'params' => $joinparams, 'mappings' => $mappings] =
549
            (array)$userfields->get_sql('u', true);
550
 
551
    if ($sort) {
552
        $orderbymap = $mappings;
553
        $orderbymap['default'] = 'lastaccess';
554
        $sort = get_safe_orderby($orderbymap, $sort, $dir);
555
    }
556
 
557
    // warning: will return UNCONFIRMED USERS
558
    return $DB->get_records_sql("SELECT u.id $selects
559
                                   FROM {user} u
560
                                        $joins
561
                                  WHERE $select
562
                                  $sort", array_merge($params, $joinparams), $page, $recordsperpage);
563
 
564
}
565
 
566
 
567
/**
568
 * Full list of users that have confirmed their accounts.
569
 *
570
 * @global object
571
 * @return array of unconfirmed users
572
 */
573
function get_users_confirmed() {
574
    global $DB, $CFG;
575
    return $DB->get_records_sql("SELECT *
576
                                   FROM {user}
577
                                  WHERE confirmed = 1 AND deleted = 0 AND id <> ?", array($CFG->siteguest));
578
}
579
 
580
 
581
/// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
582
 
583
 
584
/**
585
 * Returns $course object of the top-level site.
586
 *
587
 * @return object A {@link $COURSE} object for the site, exception if not found
588
 */
589
function get_site() {
590
    global $SITE, $DB;
591
 
592
    if (!empty($SITE->id)) {   // We already have a global to use, so return that
593
        return $SITE;
594
    }
595
 
596
    if ($course = $DB->get_record('course', array('category'=>0))) {
597
        return $course;
598
    } else {
599
        // course table exists, but the site is not there,
600
        // unfortunately there is no automatic way to recover
601
        throw new moodle_exception('nosite', 'error');
602
    }
603
}
604
 
605
/**
606
 * Gets a course object from database. If the course id corresponds to an
607
 * already-loaded $COURSE or $SITE object, then the loaded object will be used,
608
 * saving a database query.
609
 *
610
 * If it reuses an existing object, by default the object will be cloned. This
611
 * means you can modify the object safely without affecting other code.
612
 *
613
 * @param int $courseid Course id
614
 * @param bool $clone If true (default), makes a clone of the record
615
 * @return stdClass A course object
616
 * @throws dml_exception If not found in database
617
 */
618
function get_course($courseid, $clone = true) {
619
    global $DB, $COURSE, $SITE;
620
    if (!empty($COURSE->id) && $COURSE->id == $courseid) {
621
        return $clone ? clone($COURSE) : $COURSE;
622
    } else if (!empty($SITE->id) && $SITE->id == $courseid) {
623
        return $clone ? clone($SITE) : $SITE;
624
    } else {
625
        return $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
626
    }
627
}
628
 
629
/**
630
 * Returns list of courses, for whole site, or category
631
 *
632
 * Returns list of courses, for whole site, or category
633
 * Important: Using c.* for fields is extremely expensive because
634
 *            we are using distinct. You almost _NEVER_ need all the fields
635
 *            in such a large SELECT
636
 *
637
 * Consider using core_course_category::get_courses()
638
 * or core_course_category::search_courses() instead since they use caching.
639
 *
640
 * @global object
641
 * @global object
642
 * @global object
643
 * @uses CONTEXT_COURSE
644
 * @param string|int $categoryid Either a category id or 'all' for everything
645
 * @param string $sort A field and direction to sort by
646
 * @param string $fields The additional fields to return (note that "id, category, visible" are always present)
647
 * @return array Array of courses
648
 */
649
function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
650
 
651
    global $USER, $CFG, $DB;
652
 
653
    $params = array();
654
 
655
    if ($categoryid !== "all" && is_numeric($categoryid)) {
656
        $categoryselect = "WHERE c.category = :catid";
657
        $params['catid'] = $categoryid;
658
    } else {
659
        $categoryselect = "";
660
    }
661
 
662
    if (empty($sort)) {
663
        $sortstatement = "";
664
    } else {
665
        $sortstatement = "ORDER BY $sort";
666
    }
667
 
668
    $visiblecourses = array();
669
 
670
    $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
671
    $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
672
    $params['contextlevel'] = CONTEXT_COURSE;
673
 
674
    // The fields "id, category, visible" are required in the subsequent loop and must always be present.
675
    if ($fields !== 'c.*') {
676
        $fieldarray = array_merge(
677
            // Split fields on comma + zero or more whitespace, merge with required fields.
678
            preg_split('/,\s*/', $fields), [
679
                'c.id',
680
                'c.category',
681
                'c.visible',
682
            ]
683
        );
684
        $fields = implode(',', array_unique($fieldarray));
685
    }
686
 
687
    $sql = "SELECT $fields $ccselect
688
              FROM {course} c
689
           $ccjoin
690
              $categoryselect
691
              $sortstatement";
692
 
693
    // pull out all course matching the cat
694
    if ($courses = $DB->get_records_sql($sql, $params)) {
695
 
696
        // loop throught them
697
        foreach ($courses as $course) {
698
            context_helper::preload_from_record($course);
699
            if (core_course_category::can_view_course_info($course)) {
700
                $visiblecourses [$course->id] = $course;
701
            }
702
        }
703
    }
704
    return $visiblecourses;
705
}
706
 
707
/**
708
 * A list of courses that match a search
709
 *
710
 * @global object
711
 * @global object
712
 * @param array $searchterms An array of search criteria
713
 * @param string $sort A field and direction to sort by
714
 * @param int $page The page number to get
715
 * @param int $recordsperpage The number of records per page
716
 * @param int $totalcount Passed in by reference.
717
 * @param array $requiredcapabilities Extra list of capabilities used to filter courses
718
 * @param array $searchcond additional search conditions, for example ['c.enablecompletion = :p1']
719
 * @param array $params named parameters for additional search conditions, for example ['p1' => 1]
720
 * @return stdClass[] {@link $COURSE} records
721
 */
722
function get_courses_search($searchterms, $sort, $page, $recordsperpage, &$totalcount,
723
                            $requiredcapabilities = array(), $searchcond = [], $params = []) {
724
    global $CFG, $DB;
725
 
726
    if ($DB->sql_regex_supported()) {
727
        $REGEXP    = $DB->sql_regex(true);
728
        $NOTREGEXP = $DB->sql_regex(false);
729
    }
730
 
731
    $i = 0;
732
 
1441 ariadna 733
    $concat = $DB->sql_concat("COALESCE(c.summary, '')", "' '", 'c.fullname', "' '", 'c.idnumber', "' '", 'c.shortname');
1 efrain 734
 
735
    foreach ($searchterms as $searchterm) {
736
        $i++;
737
 
1441 ariadna 738
        // Initially we aren't going to perform NOT LIKE searches, only MSSQL
739
        // will use it to simulate the "-" operator with LIKE clause.
740
        $NOT = false;
1 efrain 741
 
1441 ariadna 742
        // Under MSSQL, trim the + and - operators and perform
743
        // simpler LIKE (or NOT LIKE) queries.
1 efrain 744
        if (!$DB->sql_regex_supported()) {
745
            if (substr($searchterm, 0, 1) == '-') {
746
                $NOT = true;
747
            }
748
            $searchterm = trim($searchterm, '+-');
749
        }
750
 
751
        // TODO: +- may not work for non latin languages
752
 
753
        if (substr($searchterm,0,1) == '+') {
754
            $searchterm = trim($searchterm, '+-');
755
            $searchterm = preg_quote($searchterm, '|');
756
            $searchcond[] = "$concat $REGEXP :ss$i";
757
            $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
758
 
759
        } else if ((substr($searchterm,0,1) == "-") && (core_text::strlen($searchterm) > 1)) {
760
            $searchterm = trim($searchterm, '+-');
761
            $searchterm = preg_quote($searchterm, '|');
762
            $searchcond[] = "$concat $NOTREGEXP :ss$i";
763
            $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
764
 
765
        } else {
766
            $searchcond[] = $DB->sql_like($concat,":ss$i", false, true, $NOT);
767
            $params['ss'.$i] = "%$searchterm%";
768
        }
769
    }
770
 
771
    if (empty($searchcond)) {
772
        $searchcond = array('1 = 1');
773
    }
774
 
775
    $searchcond = implode(" AND ", $searchcond);
776
 
777
    $courses = array();
778
    $c = 0; // counts how many visible courses we've seen
779
 
780
    // Tiki pagination
781
    $limitfrom = $page * $recordsperpage;
782
    $limitto   = $limitfrom + $recordsperpage;
783
 
784
    $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
785
    $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
786
    $params['contextlevel'] = CONTEXT_COURSE;
787
 
788
    $sql = "SELECT c.* $ccselect
789
              FROM {course} c
790
           $ccjoin
791
             WHERE $searchcond AND c.id <> ".SITEID."
792
          ORDER BY $sort";
793
 
794
    $mycourses = enrol_get_my_courses();
795
    $rs = $DB->get_recordset_sql($sql, $params);
796
    foreach($rs as $course) {
797
        // Preload contexts only for hidden courses or courses we need to return.
798
        context_helper::preload_from_record($course);
799
        $coursecontext = context_course::instance($course->id);
800
        if (!array_key_exists($course->id, $mycourses) && !core_course_category::can_view_course_info($course)) {
801
            continue;
802
        }
803
        if (!empty($requiredcapabilities)) {
804
            if (!has_all_capabilities($requiredcapabilities, $coursecontext)) {
805
                continue;
806
            }
807
        }
808
        // Don't exit this loop till the end
809
        // we need to count all the visible courses
810
        // to update $totalcount
811
        if ($c >= $limitfrom && $c < $limitto) {
812
            $courses[$course->id] = $course;
813
        }
814
        $c++;
815
    }
816
    $rs->close();
817
 
818
    // our caller expects 2 bits of data - our return
819
    // array, and an updated $totalcount
820
    $totalcount = $c;
821
    return $courses;
822
}
823
 
824
/**
825
 * Fixes course category and course sortorder, also verifies category and course parents and paths.
826
 * (circular references are not fixed)
827
 *
828
 * @global object
829
 * @global object
830
 * @uses MAX_COURSE_CATEGORIES
831
 * @uses SITEID
832
 * @uses CONTEXT_COURSE
833
 * @return void
834
 */
835
function fix_course_sortorder() {
836
    global $DB, $SITE;
837
 
838
    //WARNING: this is PHP5 only code!
839
 
840
    // if there are any changes made to courses or categories we will trigger
841
    // the cache events to purge all cached courses/categories data
842
    $cacheevents = array();
843
 
844
    if ($unsorted = $DB->get_records('course_categories', array('sortorder'=>0))) {
845
        //move all categories that are not sorted yet to the end
846
        $DB->set_field('course_categories', 'sortorder',
847
            get_max_courses_in_category() * MAX_COURSE_CATEGORIES, array('sortorder' => 0));
848
        $cacheevents['changesincoursecat'] = true;
849
    }
850
 
851
    $allcats = $DB->get_records('course_categories', null, 'sortorder, id', 'id, sortorder, parent, depth, path');
852
    $topcats    = array();
853
    $brokencats = array();
854
    foreach ($allcats as $cat) {
855
        $sortorder = (int)$cat->sortorder;
856
        if (!$cat->parent) {
857
            while(isset($topcats[$sortorder])) {
858
                $sortorder++;
859
            }
860
            $topcats[$sortorder] = $cat;
861
            continue;
862
        }
863
        if (!isset($allcats[$cat->parent])) {
864
            $brokencats[] = $cat;
865
            continue;
866
        }
867
        if (!isset($allcats[$cat->parent]->children)) {
868
            $allcats[$cat->parent]->children = array();
869
        }
870
        while(isset($allcats[$cat->parent]->children[$sortorder])) {
871
            $sortorder++;
872
        }
873
        $allcats[$cat->parent]->children[$sortorder] = $cat;
874
    }
875
    unset($allcats);
876
 
877
    // add broken cats to category tree
878
    if ($brokencats) {
879
        $defaultcat = reset($topcats);
880
        foreach ($brokencats as $cat) {
881
            $topcats[] = $cat;
882
        }
883
    }
884
 
885
    // now walk recursively the tree and fix any problems found
886
    $sortorder = 0;
887
    $fixcontexts = array();
888
    if (_fix_course_cats($topcats, $sortorder, 0, 0, '', $fixcontexts)) {
889
        $cacheevents['changesincoursecat'] = true;
890
    }
891
 
892
    // detect if there are "multiple" frontpage courses and fix them if needed
893
    $frontcourses = $DB->get_records('course', array('category'=>0), 'id');
894
    if (count($frontcourses) > 1) {
895
        if (isset($frontcourses[SITEID])) {
896
            $frontcourse = $frontcourses[SITEID];
897
            unset($frontcourses[SITEID]);
898
        } else {
899
            $frontcourse = array_shift($frontcourses);
900
        }
901
        $defaultcat = reset($topcats);
902
        foreach ($frontcourses as $course) {
903
            $DB->set_field('course', 'category', $defaultcat->id, array('id'=>$course->id));
904
            $context = context_course::instance($course->id);
905
            $fixcontexts[$context->id] = $context;
906
            $cacheevents['changesincourse'] = true;
907
        }
908
        unset($frontcourses);
909
    } else {
910
        $frontcourse = reset($frontcourses);
911
    }
912
 
913
    // now fix the paths and depths in context table if needed
914
    if ($fixcontexts) {
915
        foreach ($fixcontexts as $fixcontext) {
916
            $fixcontext->reset_paths(false);
917
        }
918
        context_helper::build_all_paths(false);
919
        unset($fixcontexts);
920
        $cacheevents['changesincourse'] = true;
921
        $cacheevents['changesincoursecat'] = true;
922
    }
923
 
924
    // release memory
925
    unset($topcats);
926
    unset($brokencats);
927
    unset($fixcontexts);
928
 
929
    // fix frontpage course sortorder
930
    if ($frontcourse->sortorder != 1) {
931
        $DB->set_field('course', 'sortorder', 1, array('id'=>$frontcourse->id));
932
        $cacheevents['changesincourse'] = true;
933
    }
934
 
935
    // now fix the course counts in category records if needed
936
    $sql = "SELECT cc.id, cc.coursecount, COUNT(c.id) AS newcount
937
              FROM {course_categories} cc
938
              LEFT JOIN {course} c ON c.category = cc.id
939
          GROUP BY cc.id, cc.coursecount
940
            HAVING cc.coursecount <> COUNT(c.id)";
941
 
942
    if ($updatecounts = $DB->get_records_sql($sql)) {
943
        // categories with more courses than MAX_COURSES_IN_CATEGORY
944
        $categories = array();
945
        foreach ($updatecounts as $cat) {
946
            $cat->coursecount = $cat->newcount;
947
            if ($cat->coursecount >= get_max_courses_in_category()) {
948
                $categories[] = $cat->id;
949
            }
950
            unset($cat->newcount);
951
            $DB->update_record_raw('course_categories', $cat, true);
952
        }
953
        if (!empty($categories)) {
954
            $str = implode(', ', $categories);
955
            debugging("The number of courses (category id: $str) has reached max number of courses " .
956
                "in a category (" . get_max_courses_in_category() . "). It will cause a sorting performance issue. " .
957
                "Please set higher value for \$CFG->maxcoursesincategory in config.php. " .
958
                "Please also make sure \$CFG->maxcoursesincategory * MAX_COURSE_CATEGORIES less than max integer. " .
959
                "See tracker issues: MDL-25669 and MDL-69573", DEBUG_DEVELOPER);
960
        }
961
        $cacheevents['changesincoursecat'] = true;
962
    }
963
 
964
    // now make sure that sortorders in course table are withing the category sortorder ranges
965
    $sql = "SELECT DISTINCT cc.id, cc.sortorder
966
              FROM {course_categories} cc
967
              JOIN {course} c ON c.category = cc.id
968
             WHERE c.sortorder < cc.sortorder OR c.sortorder > cc.sortorder + " . get_max_courses_in_category();
969
 
970
    if ($fixcategories = $DB->get_records_sql($sql)) {
971
        //fix the course sortorder ranges
972
        foreach ($fixcategories as $cat) {
973
            $sql = "UPDATE {course}
974
                       SET sortorder = ".$DB->sql_modulo('sortorder', get_max_courses_in_category())." + ?
975
                     WHERE category = ?";
976
            $DB->execute($sql, array($cat->sortorder, $cat->id));
977
        }
978
        $cacheevents['changesincoursecat'] = true;
979
    }
980
    unset($fixcategories);
981
 
982
    // categories having courses with sortorder duplicates or having gaps in sortorder
983
    $sql = "SELECT DISTINCT c1.category AS id , cc.sortorder
984
              FROM {course} c1
985
              JOIN {course} c2 ON c1.sortorder = c2.sortorder
986
              JOIN {course_categories} cc ON (c1.category = cc.id)
987
             WHERE c1.id <> c2.id";
988
    $fixcategories = $DB->get_records_sql($sql);
989
 
990
    $sql = "SELECT cc.id, cc.sortorder, cc.coursecount, MAX(c.sortorder) AS maxsort, MIN(c.sortorder) AS minsort
991
              FROM {course_categories} cc
992
              JOIN {course} c ON c.category = cc.id
993
          GROUP BY cc.id, cc.sortorder, cc.coursecount
994
            HAVING (MAX(c.sortorder) <>  cc.sortorder + cc.coursecount) OR (MIN(c.sortorder) <>  cc.sortorder + 1)";
995
    $gapcategories = $DB->get_records_sql($sql);
996
 
997
    foreach ($gapcategories as $cat) {
998
        if (isset($fixcategories[$cat->id])) {
999
            // duplicates detected already
1000
 
1001
        } else if ($cat->minsort == $cat->sortorder and $cat->maxsort == $cat->sortorder + $cat->coursecount - 1) {
1002
            // easy - new course inserted with sortorder 0, the rest is ok
1003
            $sql = "UPDATE {course}
1004
                       SET sortorder = sortorder + 1
1005
                     WHERE category = ?";
1006
            $DB->execute($sql, array($cat->id));
1007
 
1008
        } else {
1009
            // it needs full resorting
1010
            $fixcategories[$cat->id] = $cat;
1011
        }
1012
        $cacheevents['changesincourse'] = true;
1013
    }
1014
    unset($gapcategories);
1015
 
1016
    // fix course sortorders in problematic categories only
1017
    foreach ($fixcategories as $cat) {
1018
        $i = 1;
1019
        $courses = $DB->get_records('course', array('category'=>$cat->id), 'sortorder ASC, id DESC', 'id, sortorder');
1020
        foreach ($courses as $course) {
1021
            if ($course->sortorder != $cat->sortorder + $i) {
1022
                $course->sortorder = $cat->sortorder + $i;
1023
                $DB->update_record_raw('course', $course, true);
1024
                $cacheevents['changesincourse'] = true;
1025
            }
1026
            $i++;
1027
        }
1028
    }
1029
 
1030
    // advise all caches that need to be rebuilt
1031
    foreach (array_keys($cacheevents) as $event) {
1032
        cache_helper::purge_by_event($event);
1033
    }
1034
}
1035
 
1036
/**
1037
 * Internal recursive category verification function, do not use directly!
1038
 *
1039
 * @todo Document the arguments of this function better
1040
 *
1041
 * @global object
1042
 * @uses CONTEXT_COURSECAT
1043
 * @param array $children
1044
 * @param int $sortorder
1045
 * @param string $parent
1046
 * @param int $depth
1047
 * @param string $path
1048
 * @param array $fixcontexts
1049
 * @return bool if changes were made
1050
 */
1051
function _fix_course_cats($children, &$sortorder, $parent, $depth, $path, &$fixcontexts) {
1052
    global $DB;
1053
 
1054
    $depth++;
1055
    $changesmade = false;
1056
 
1057
    foreach ($children as $cat) {
1058
        $sortorder = $sortorder + get_max_courses_in_category();
1059
        $update = false;
1060
        if ($parent != $cat->parent or $depth != $cat->depth or $path.'/'.$cat->id != $cat->path) {
1061
            $cat->parent = $parent;
1062
            $cat->depth  = $depth;
1063
            $cat->path   = $path.'/'.$cat->id;
1064
            $update = true;
1065
 
1066
            // make sure context caches are rebuild and dirty contexts marked
1067
            $context = context_coursecat::instance($cat->id);
1068
            $fixcontexts[$context->id] = $context;
1069
        }
1070
        if ($cat->sortorder != $sortorder) {
1071
            $cat->sortorder = $sortorder;
1072
            $update = true;
1073
        }
1074
        if ($update) {
1075
            $DB->update_record('course_categories', $cat, true);
1076
            $changesmade = true;
1077
        }
1078
        if (isset($cat->children)) {
1079
            if (_fix_course_cats($cat->children, $sortorder, $cat->id, $cat->depth, $cat->path, $fixcontexts)) {
1080
                $changesmade = true;
1081
            }
1082
        }
1083
    }
1084
    return $changesmade;
1085
}
1086
 
1087
/**
1088
 * List of remote courses that a user has access to via MNET.
1089
 * Works only on the IDP
1090
 *
1091
 * @global object
1092
 * @global object
1093
 * @param int @userid The user id to get remote courses for
1094
 * @return array Array of {@link $COURSE} of course objects
1095
 */
1096
function get_my_remotecourses($userid=0) {
1097
    global $DB, $USER;
1098
 
1099
    if (empty($userid)) {
1100
        $userid = $USER->id;
1101
    }
1102
 
1441 ariadna 1103
    // We can not use SELECT DISTINCT + text field (summary) because of MS SQL, subselect used therefore.
1 efrain 1104
    $sql = "SELECT c.id, c.remoteid, c.shortname, c.fullname,
1105
                   c.hostid, c.summary, c.summaryformat, c.categoryname AS cat_name,
1106
                   h.name AS hostname
1107
              FROM {mnetservice_enrol_courses} c
1108
              JOIN (SELECT DISTINCT hostid, remotecourseid
1109
                      FROM {mnetservice_enrol_enrolments}
1110
                     WHERE userid = ?
1111
                   ) e ON (e.hostid = c.hostid AND e.remotecourseid = c.remoteid)
1112
              JOIN {mnet_host} h ON h.id = c.hostid";
1113
 
1114
    return $DB->get_records_sql($sql, array($userid));
1115
}
1116
 
1117
/**
1118
 * List of remote hosts that a user has access to via MNET.
1119
 * Works on the SP
1120
 *
1121
 * @global object
1122
 * @global object
1123
 * @return array|bool Array of host objects or false
1124
 */
1125
function get_my_remotehosts() {
1126
    global $CFG, $USER;
1127
 
1128
    if ($USER->mnethostid == $CFG->mnet_localhost_id) {
1129
        return false; // Return nothing on the IDP
1130
    }
1131
    if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) {
1132
        return $USER->mnet_foreign_host_array;
1133
    }
1134
    return false;
1135
}
1136
 
1137
 
1138
/**
1139
 * Returns a menu of all available scales from the site as well as the given course
1140
 *
1141
 * @global object
1142
 * @param int $courseid The id of the course as found in the 'course' table.
1143
 * @return array
1144
 */
1145
function get_scales_menu($courseid=0) {
1146
    global $DB;
1147
 
1148
    $sql = "SELECT id, name, courseid
1149
              FROM {scale}
1150
             WHERE courseid = 0 or courseid = ?
1151
          ORDER BY courseid ASC, name ASC";
1152
    $params = array($courseid);
1153
    $scales = array();
1154
    $results = $DB->get_records_sql($sql, $params);
1155
    foreach ($results as $index => $record) {
1156
        $context = empty($record->courseid) ? context_system::instance() : context_course::instance($record->courseid);
1157
        $scales[$index] = format_string($record->name, false, ["context" => $context]);
1158
    }
1159
    // Format: [id => 'scale name'].
1160
    return $scales;
1161
}
1162
 
1163
/**
1164
 * Increment standard revision field.
1165
 *
1166
 * The revision are based on current time and are incrementing.
1167
 * There is a protection for runaway revisions, it may not go further than
1168
 * one hour into future.
1169
 *
1170
 * The field has to be XMLDB_TYPE_INTEGER with size 10.
1171
 *
1172
 * @param string $table
1173
 * @param string $field name of the field containing revision
1174
 * @param string $select use empty string when updating all records
1175
 * @param array $params optional select parameters
1176
 */
1441 ariadna 1177
function increment_revision_number($table, $field, $select, ?array $params = null) {
1 efrain 1178
    global $DB;
1179
 
1180
    $now = time();
1181
    $sql = "UPDATE {{$table}}
1182
                   SET $field = (CASE
1183
                       WHEN $field IS NULL THEN $now
1184
                       WHEN $field < $now THEN $now
1185
                       WHEN $field > $now + 3600 THEN $now
1186
                       ELSE $field + 1 END)";
1187
    if ($select) {
1188
        $sql = $sql . " WHERE $select";
1189
    }
1190
    $DB->execute($sql, $params);
1191
}
1192
 
1193
 
1194
/// MODULE FUNCTIONS /////////////////////////////////////////////////
1195
 
1196
/**
1197
 * Just gets a raw list of all modules in a course
1198
 *
1199
 * @global object
1200
 * @param int $courseid The id of the course as found in the 'course' table.
1201
 * @return array|false
1202
 */
1203
function get_course_mods($courseid) {
1204
    global $DB;
1205
 
1206
    if (empty($courseid)) {
1207
        return false; // avoid warnings
1208
    }
1209
 
1210
    return $DB->get_records_sql("SELECT cm.*, m.name as modname
1211
                                   FROM {modules} m, {course_modules} cm
1212
                                  WHERE cm.course = ? AND cm.module = m.id AND m.visible = 1",
1213
                                array($courseid)); // no disabled mods
1214
}
1215
 
1216
 
1217
/**
1218
 * Given an id of a course module, finds the coursemodule description
1219
 *
1220
 * Please note that this function performs 1-2 DB queries. When possible use cached
1221
 * course modinfo. For example get_fast_modinfo($courseorid)->get_cm($cmid)
1222
 * See also {@link cm_info::get_course_module_record()}
1223
 *
1224
 * @global object
1225
 * @param string $modulename name of module type, eg. resource, assignment,... (optional, slower and less safe if not specified)
1226
 * @param int $cmid course module id (id in course_modules table)
1227
 * @param int $courseid optional course id for extra validation
1228
 * @param bool $sectionnum include relative section number (0,1,2 ...)
1229
 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1230
 *                        IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1231
 *                        MUST_EXIST means throw exception if no record or multiple records found
1232
 * @return stdClass|false
1233
 */
1234
function get_coursemodule_from_id($modulename, $cmid, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1235
    global $DB;
1236
 
1237
    $params = array('cmid'=>$cmid);
1238
 
1239
    if (!$modulename) {
1240
        if (!$modulename = $DB->get_field_sql("SELECT md.name
1241
                                                 FROM {modules} md
1242
                                                 JOIN {course_modules} cm ON cm.module = md.id
1243
                                                WHERE cm.id = :cmid", $params, $strictness)) {
1244
            return false;
1245
        }
1246
    } else {
1247
        if (!core_component::is_valid_plugin_name('mod', $modulename)) {
1248
            throw new coding_exception('Invalid modulename parameter');
1249
        }
1250
    }
1251
 
1252
    $params['modulename'] = $modulename;
1253
 
1254
    $courseselect = "";
1255
    $sectionfield = "";
1256
    $sectionjoin  = "";
1257
 
1258
    if ($courseid) {
1259
        $courseselect = "AND cm.course = :courseid";
1260
        $params['courseid'] = $courseid;
1261
    }
1262
 
1263
    if ($sectionnum) {
1264
        $sectionfield = ", cw.section AS sectionnum";
1265
        $sectionjoin  = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1266
    }
1267
 
1268
    $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1269
              FROM {course_modules} cm
1270
                   JOIN {modules} md ON md.id = cm.module
1271
                   JOIN {".$modulename."} m ON m.id = cm.instance
1272
                   $sectionjoin
1273
             WHERE cm.id = :cmid AND md.name = :modulename
1274
                   $courseselect";
1275
 
1276
    return $DB->get_record_sql($sql, $params, $strictness);
1277
}
1278
 
1279
/**
1280
 * Given an instance number of a module, finds the coursemodule description
1281
 *
1282
 * Please note that this function performs DB query. When possible use cached course
1283
 * modinfo. For example get_fast_modinfo($courseorid)->instances[$modulename][$instance]
1284
 * See also {@link cm_info::get_course_module_record()}
1285
 *
1286
 * @global object
1287
 * @param string $modulename name of module type, eg. resource, assignment,...
1288
 * @param int $instance module instance number (id in resource, assignment etc. table)
1289
 * @param int $courseid optional course id for extra validation
1290
 * @param bool $sectionnum include relative section number (0,1,2 ...)
1291
 * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1292
 *                        IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1293
 *                        MUST_EXIST means throw exception if no record or multiple records found
1294
 * @return stdClass
1295
 */
1296
function get_coursemodule_from_instance($modulename, $instance, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1297
    global $DB;
1298
 
1299
    if (!core_component::is_valid_plugin_name('mod', $modulename)) {
1300
        throw new coding_exception('Invalid modulename parameter');
1301
    }
1302
 
1303
    $params = array('instance'=>$instance, 'modulename'=>$modulename);
1304
 
1305
    $courseselect = "";
1306
    $sectionfield = "";
1307
    $sectionjoin  = "";
1308
 
1309
    if ($courseid) {
1310
        $courseselect = "AND cm.course = :courseid";
1311
        $params['courseid'] = $courseid;
1312
    }
1313
 
1314
    if ($sectionnum) {
1315
        $sectionfield = ", cw.section AS sectionnum";
1316
        $sectionjoin  = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1317
    }
1318
 
1319
    $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1320
              FROM {course_modules} cm
1321
                   JOIN {modules} md ON md.id = cm.module
1322
                   JOIN {".$modulename."} m ON m.id = cm.instance
1323
                   $sectionjoin
1324
             WHERE m.id = :instance AND md.name = :modulename
1325
                   $courseselect";
1326
 
1327
    return $DB->get_record_sql($sql, $params, $strictness);
1328
}
1329
 
1330
/**
1331
 * Returns all course modules of given activity in course
1332
 *
1333
 * @param string $modulename The module name (forum, quiz, etc.)
1334
 * @param int $courseid The course id to get modules for
1335
 * @param string $extrafields extra fields starting with m.
1336
 * @return array Array of results
1337
 */
1338
function get_coursemodules_in_course($modulename, $courseid, $extrafields='') {
1339
    global $DB;
1340
 
1341
    if (!core_component::is_valid_plugin_name('mod', $modulename)) {
1342
        throw new coding_exception('Invalid modulename parameter');
1343
    }
1344
 
1345
    if (!empty($extrafields)) {
1346
        $extrafields = ", $extrafields";
1347
    }
1348
    $params = array();
1349
    $params['courseid'] = $courseid;
1350
    $params['modulename'] = $modulename;
1351
 
1352
 
1353
    return $DB->get_records_sql("SELECT cm.*, m.name, md.name as modname $extrafields
1354
                                   FROM {course_modules} cm, {modules} md, {".$modulename."} m
1355
                                  WHERE cm.course = :courseid AND
1356
                                        cm.instance = m.id AND
1357
                                        md.name = :modulename AND
1358
                                        md.id = cm.module", $params);
1359
}
1360
 
1361
/**
1362
 * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1363
 *
1364
 * Returns an array of all the active instances of a particular
1365
 * module in given courses, sorted in the order they are defined
1366
 * in the course. Returns an empty array on any errors.
1367
 *
1368
 * The returned objects includle the columns cw.section, cm.visible,
1369
 * cm.groupmode, cm.groupingid and cm.lang and are indexed by cm.id.
1370
 *
1371
 * @global object
1372
 * @global object
1373
 * @param string $modulename The name of the module to get instances for
1374
 * @param array $courses an array of course objects.
1375
 * @param int $userid
1376
 * @param int $includeinvisible
1377
 * @return array of module instance objects, including some extra fields from the course_modules
1378
 *          and course_sections tables, or an empty array if an error occurred.
1379
 */
1380
function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
1381
    global $CFG, $DB;
1382
 
1383
    if (!core_component::is_valid_plugin_name('mod', $modulename)) {
1384
        throw new coding_exception('Invalid modulename parameter');
1385
    }
1386
 
1387
    $outputarray = array();
1388
 
1389
    if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1390
        return $outputarray;
1391
    }
1392
 
1393
    list($coursessql, $params) = $DB->get_in_or_equal(array_keys($courses), SQL_PARAMS_NAMED, 'c0');
1394
    $params['modulename'] = $modulename;
1395
 
1396
    if (!$rawmods = $DB->get_records_sql("SELECT cm.id AS coursemodule, m.*, cw.section, cm.visible AS visible,
1397
                                                 cm.groupmode, cm.groupingid, cm.lang
1398
                                            FROM {course_modules} cm, {course_sections} cw, {modules} md,
1399
                                                 {".$modulename."} m
1400
                                           WHERE cm.course $coursessql AND
1401
                                                 cm.instance = m.id AND
1402
                                                 cm.section = cw.id AND
1403
                                                 md.name = :modulename AND
1404
                                                 md.id = cm.module", $params)) {
1405
        return $outputarray;
1406
    }
1407
 
1408
    foreach ($courses as $course) {
1409
        $modinfo = get_fast_modinfo($course, $userid);
1410
 
1411
        if (empty($modinfo->instances[$modulename])) {
1412
            continue;
1413
        }
1414
 
1415
        foreach ($modinfo->instances[$modulename] as $cm) {
1416
            if (!$includeinvisible and !$cm->uservisible) {
1417
                continue;
1418
            }
1419
            if (!isset($rawmods[$cm->id])) {
1420
                continue;
1421
            }
1422
            $instance = $rawmods[$cm->id];
1423
            if (!empty($cm->extra)) {
1424
                $instance->extra = $cm->extra;
1425
            }
1426
            $outputarray[] = $instance;
1427
        }
1428
    }
1429
 
1430
    return $outputarray;
1431
}
1432
 
1433
/**
1434
 * Returns an array of all the active instances of a particular module in a given course,
1435
 * sorted in the order they are defined.
1436
 *
1437
 * Returns an array of all the active instances of a particular
1438
 * module in a given course, sorted in the order they are defined
1439
 * in the course. Returns an empty array on any errors.
1440
 *
1441
 * The returned objects includle the columns cw.section, cm.visible,
1442
 * cm.groupmode, and cm.groupingid, and are indexed by cm.id.
1443
 *
1444
 * Simply calls {@link all_instances_in_courses()} with a single provided course
1445
 *
1446
 * @param string $modulename The name of the module to get instances for
1447
 * @param object $course The course obect.
1448
 * @return array of module instance objects, including some extra fields from the course_modules
1449
 *          and course_sections tables, or an empty array if an error occurred.
1450
 * @param int $userid
1451
 * @param int $includeinvisible
1452
 */
1453
function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
1454
    return get_all_instances_in_courses($modulename, array($course->id => $course), $userid, $includeinvisible);
1455
}
1456
 
1457
 
1458
/**
1459
 * Determine whether a module instance is visible within a course
1460
 *
1461
 * Given a valid module object with info about the id and course,
1462
 * and the module's type (eg "forum") returns whether the object
1463
 * is visible or not according to the 'eye' icon only.
1464
 *
1465
 * NOTE: This does NOT take into account visibility to a particular user.
1466
 * To get visibility access for a specific user, use get_fast_modinfo, get a
1467
 * cm_info object from this, and check the ->uservisible property; or use
1468
 * the \core_availability\info_module::is_user_visible() static function.
1469
 *
1470
 * @global object
1471
 
1472
 * @param $moduletype Name of the module eg 'forum'
1473
 * @param $module Object which is the instance of the module
1474
 * @return bool Success
1475
 */
1476
function instance_is_visible($moduletype, $module) {
1477
    global $DB;
1478
 
1479
    if (!empty($module->id)) {
1480
        $params = array('courseid'=>$module->course, 'moduletype'=>$moduletype, 'moduleid'=>$module->id);
1481
        if ($records = $DB->get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.course
1482
                                               FROM {course_modules} cm, {modules} m
1483
                                              WHERE cm.course = :courseid AND
1484
                                                    cm.module = m.id AND
1485
                                                    m.name = :moduletype AND
1486
                                                    cm.instance = :moduleid", $params)) {
1487
 
1488
            foreach ($records as $record) { // there should only be one - use the first one
1489
                return $record->visible;
1490
            }
1491
        }
1492
    }
1493
    return true;  // visible by default!
1494
}
1495
 
1496
 
1497
/// LOG FUNCTIONS /////////////////////////////////////////////////////
1498
 
1499
/**
1500
 * Get instance of log manager.
1501
 *
1502
 * @param bool $forcereload
1503
 * @return \core\log\manager
1504
 */
1505
function get_log_manager($forcereload = false) {
1506
    /** @var \core\log\manager $singleton */
1507
    static $singleton = null;
1508
 
1509
    if ($forcereload and isset($singleton)) {
1510
        $singleton->dispose();
1511
        $singleton = null;
1512
    }
1513
 
1514
    if (isset($singleton)) {
1515
        return $singleton;
1516
    }
1517
 
1518
    $classname = '\tool_log\log\manager';
1519
    if (defined('LOG_MANAGER_CLASS')) {
1520
        $classname = LOG_MANAGER_CLASS;
1521
    }
1522
 
1523
    if (!class_exists($classname)) {
1524
        if (!empty($classname)) {
1525
            debugging("Cannot find log manager class '$classname'.", DEBUG_DEVELOPER);
1526
        }
1527
        $classname = '\core\log\dummy_manager';
1528
    }
1529
 
1530
    $singleton = new $classname();
1531
    return $singleton;
1532
}
1533
 
1534
/**
1535
 * Add an entry to the config log table.
1536
 *
1537
 * These are "action" focussed rather than web server hits,
1538
 * and provide a way to easily reconstruct changes to Moodle configuration.
1539
 *
1540
 * @package core
1541
 * @category log
1542
 * @global moodle_database $DB
1543
 * @global stdClass $USER
1544
 * @param    string  $name     The name of the configuration change action
1545
                               For example 'filter_active' when activating or deactivating a filter
1546
 * @param    string  $oldvalue The config setting's previous value
1547
 * @param    string  $value    The config setting's new value
1548
 * @param    string  $plugin   Plugin name, for example a filter name when changing filter configuration
1549
 * @return void
1550
 */
1551
function add_to_config_log($name, $oldvalue, $value, $plugin) {
1552
    global $USER, $DB;
1553
 
1554
    $log = new stdClass();
1555
    // Use 0 as user id during install.
1556
    $log->userid       = during_initial_install() ? 0 : $USER->id;
1557
    $log->timemodified = time();
1558
    $log->name         = $name;
1559
    $log->oldvalue  = $oldvalue;
1560
    $log->value     = $value;
1561
    $log->plugin    = $plugin;
1562
 
1563
    $id = $DB->insert_record('config_log', $log);
1564
 
1565
    $event = core\event\config_log_created::create(array(
1566
            'objectid' => $id,
1567
            'userid' => $log->userid,
1568
            'context' => \context_system::instance(),
1569
            'other' => array(
1570
                'name' => $log->name,
1571
                'oldvalue' => $log->oldvalue,
1572
                'value' => $log->value,
1573
                'plugin' => $log->plugin
1574
            )
1575
        ));
1576
    $event->trigger();
1577
}
1578
 
1579
/**
1580
 * Store user last access times - called when use enters a course or site
1581
 *
1582
 * @package core
1583
 * @category log
1584
 * @global stdClass $USER
1585
 * @global stdClass $CFG
1586
 * @global moodle_database $DB
1587
 * @uses LASTACCESS_UPDATE_SECS
1588
 * @uses SITEID
1589
 * @param int $courseid  empty courseid means site
1590
 * @return void
1591
 */
1592
function user_accesstime_log($courseid=0) {
1593
    global $USER, $CFG, $DB;
1594
 
1595
    if (!isloggedin() or \core\session\manager::is_loggedinas()) {
1596
        // no access tracking
1597
        return;
1598
    }
1599
 
1600
    if (isguestuser()) {
1601
        // Do not update guest access times/ips for performance.
1602
        return;
1603
    }
1604
 
1605
    if (defined('USER_KEY_LOGIN') && USER_KEY_LOGIN === true) {
1606
        // Do not update user login time when using user key login.
1607
        return;
1608
    }
1609
 
1610
    if (empty($courseid)) {
1611
        $courseid = SITEID;
1612
    }
1613
 
1614
    $timenow = time();
1615
 
1616
/// Store site lastaccess time for the current user
1617
    if ($timenow - $USER->lastaccess > LASTACCESS_UPDATE_SECS) {
1618
    /// Update $USER->lastaccess for next checks
1619
        $USER->lastaccess = $timenow;
1620
 
1621
        $last = new stdClass();
1622
        $last->id         = $USER->id;
1623
        $last->lastip     = getremoteaddr();
1624
        $last->lastaccess = $timenow;
1625
 
1626
        $DB->update_record_raw('user', $last);
1627
    }
1628
 
1629
    if ($courseid == SITEID) {
1630
    ///  no user_lastaccess for frontpage
1631
        return;
1632
    }
1633
 
1634
/// Store course lastaccess times for the current user
1635
    if (empty($USER->currentcourseaccess[$courseid]) or ($timenow - $USER->currentcourseaccess[$courseid] > LASTACCESS_UPDATE_SECS)) {
1636
 
1637
        $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid'=>$USER->id, 'courseid'=>$courseid));
1638
 
1639
        if ($lastaccess === false) {
1640
            // Update course lastaccess for next checks
1641
            $USER->currentcourseaccess[$courseid] = $timenow;
1642
 
1643
            $last = new stdClass();
1644
            $last->userid     = $USER->id;
1645
            $last->courseid   = $courseid;
1646
            $last->timeaccess = $timenow;
1647
            try {
1648
                $DB->insert_record_raw('user_lastaccess', $last, false);
1649
            } catch (dml_write_exception $e) {
1650
                // During a race condition we can fail to find the data, then it appears.
1651
                // If we still can't find it, rethrow the exception.
1652
                $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid' => $USER->id,
1653
                                                                                    'courseid' => $courseid));
1654
                if ($lastaccess === false) {
1655
                    throw $e;
1656
                }
1657
                // If we did find it, the race condition was true and another thread has inserted the time for us.
1658
                // We can just continue without having to do anything.
1659
            }
1660
 
1661
        } else if ($timenow - $lastaccess <  LASTACCESS_UPDATE_SECS) {
1662
            // no need to update now, it was updated recently in concurrent login ;-)
1663
 
1664
        } else {
1665
            // Update course lastaccess for next checks
1666
            $USER->currentcourseaccess[$courseid] = $timenow;
1667
 
1668
            $DB->set_field('user_lastaccess', 'timeaccess', $timenow, array('userid'=>$USER->id, 'courseid'=>$courseid));
1669
        }
1670
    }
1671
}
1672
 
1673
/// GENERAL HELPFUL THINGS  ///////////////////////////////////
1674
 
1675
/**
1676
 * Dumps a given object's information for debugging purposes. (You can actually use this function
1677
 * to print any type of value such as arrays or simple strings, not just objects.)
1678
 *
1679
 * When used in a web script, the object is dumped in a fancy-formatted div.
1680
 *
1681
 * When used in a CLI script, the object's information is written to the standard error output
1682
 * stream.
1683
 *
1684
 * When used in an AJAX script, the object's information is dumped to the server error log.
1685
 *
1686
 * In text mode, private fields are shown with * and protected with +.
1687
 *
1688
 * In web view, formatting is done with Bootstrap classes. You can hover over some items to see
1689
 * more information, such as value types or access controls, or full field names if the names get
1690
 * cut off.
1691
 *
1692
 * By default, this will recurse to child objects, except where that would result in infinite
1693
 * recursion. To change that, set $expandclasses to an empty array (= do not recurse) or to a list
1694
 * of the class names that you would like to expand. You can also set values in this array to a
1695
 * regular expression beginning with / if you want to match a range of classes.
1696
 *
1697
 * @param mixed $item Object, array, or other item to display
1698
 * @param string[] $expandclasses Optional list of class patterns to recurse to
1699
 * @param bool $textonly If true, outputs text-only (automatically set for CLI and AJAX)
1700
 * @param bool $return For internal use - if true, returns value instead of echoing it
1701
 * @param int $depth For internal use - depth of recursion within print_object call
1702
 * @param \stdClass[] $done For internal use - array listing already-printed objects
1703
 * @return string  HTML code (or text if CLI) to display, if $return is true, otherwise empty string
1704
 */
1705
function print_object($item, array $expandclasses = ['/./'], bool $textonly = false, bool $return = false,
1706
        int $depth = 0, array $done = []): string {
1707
    // We may need a lot of memory here.
1708
    raise_memory_limit(MEMORY_EXTRA);
1709
 
1710
    // Set text (instead of HTML) mode if in CLI or AJAX script.
1711
    if (CLI_SCRIPT || AJAX_SCRIPT) {
1712
        $textonly = true;
1713
    }
1714
 
1715
    /**
1716
     * Gets styling for types of variable.
1717
     *
1718
     * @param mixed $item Arbitrary PHP variable (simple primitive type) to display
1719
     * @return string Bootstrap class for styling the display
1720
     */
1721
    $gettypestyle = function($item): string {
1722
        switch (gettype($item)) {
1723
            case 'NULL':
1724
            case 'boolean':
1441 ariadna 1725
                return 'fst-italic';
1 efrain 1726
            case 'integer':
1727
            case 'double':
1728
                return 'text-primary';
1729
            case 'string' :
1730
                return 'text-success';
1731
            default:
1732
                return '';
1733
        }
1734
    };
1735
 
1736
    /**
1737
     * Formats and escapes the text for the contents of a variable.
1738
     *
1739
     * @param mixed $item Arbitrary PHP variable (simple primitive type) to display
1740
     * @return string Contents as text
1741
     */
1742
    $getobjectstr = function($item) use($textonly): string {
1743
        if (is_null($item)) {
1744
            return 'null';
1745
        }
1746
        $objectstr = (string)$item;
1747
        if (is_string($item)) {
1748
            // Quotes around strings.
1749
            $objectstr = "'$objectstr'";
1750
        } else if (is_bool($item)) {
1751
            // Show true or false for bools.
1752
            $objectstr = $item ? 'true' : 'false';
1753
        } else if (is_float($item)) {
1754
            // Add 'f' for floats.
1755
            $objectstr = $item . 'f';
1756
        }
1757
        if ($textonly) {
1758
            return $objectstr;
1759
        } else {
1760
            return s($objectstr);
1761
        }
1762
    };
1763
 
1764
    if ($textonly) {
1765
        $out = '';
1766
    } else {
1767
        $notype = false;
1768
        $cssclass = $gettypestyle($item);
1769
        if (is_object($item) || is_array($item)) {
1770
            // For object and array, don't show the title on hover - it makes no sense because
1771
            // they're big, plus we already show the word 'array' or the object type.
1772
            $notype = true;
1773
            // Add a fancy box, with alternating colour, around the object and non-empty array.
1774
            if (is_object($item) || count($item) > 0) {
1775
                if (($depth & 1) === 0) {
1776
                    $cssclass .= ' bg-white rounded p-2';
1777
                } else {
1778
                    $cssclass .= ' bg-light rounded p-2';
1779
                }
1780
            }
1781
        }
1782
        if ($depth === 0) {
1783
            // The top-level object being printed has print-object class in case anyone wants to
1784
            // do extra styling.
1785
            $cssclass .= ' print-object';
1786
        }
1787
        $attributes = [];
1788
        if (!$notype) {
1789
            // We show the item type on hover. Note there is no need to include the actual value
1790
            // in the title attribute here, because the full text will be displayed anyway with
1791
            // wrapping if needed..
1792
            $attributes['title'] = gettype($item);
1793
        }
1794
        $out = html_writer::start_div($cssclass, $attributes);
1795
    }
1796
 
1797
    // Depending on the level of nesting, we allocate a slightly different proportion (ranging
1798
    // from 2/12 to 5/12) of the available width for the key names.
1799
    $bsdepth = floor(min(6, $depth) / 2);
1800
    $bootstrapdt = 'col-sm-' . ($bsdepth + 2);
1801
    $bootstrapdd = 'col-sm-' . (12 - ($bsdepth + 2));
1802
 
1803
    // This main code handles objects and arrays.
1804
    if (is_array($item) || is_object($item)) {
1805
        if (is_object($item)) {
1806
            // Object header: class name.
1807
            if ($textonly) {
1808
                $out .= '[' . get_class($item) . ']';
1809
            } else {
1810
                // Objects display the class name as a badge. Content goes within a <dl>.
1811
                $badge = html_writer::span(get_class($item), 'badge bg-primary text-white');
1812
                $out .= html_writer::tag('h5', $badge);
1813
                $out .= html_writer::start_tag('dl', ['class' => 'row']);
1814
                $dl = true;
1815
            }
1816
            // Record that we have output this object already (to prevent circular refs).
1817
            $done[] = $item;
1818
            $object = true;
1819
            // Cast to array so we can loop through all properties.
1820
            $item = (array)$item;
1821
        } else {
1822
            // Array header: 'array' and a count.
1823
            $arrayinfo = 'array (' . count($item) . ')';
1824
            if ($textonly) {
1825
                $out .= $arrayinfo;
1826
            } else {
1827
                // Arrays show the same as objects but the badge is grey.
1828
                $badge = html_writer::span($arrayinfo, 'badge bg-secondary text-dark');
1829
                // Decide if there will be a <dl> tag - only if there is some content.
1830
                $dl = count($item) > 0;
1831
                $attributes = [];
1832
                if (!$dl) {
1833
                    // When there is no content inside the array, don't show bottom margin on heading.
1834
                    $attributes['class'] = 'mb-0';
1835
                }
1836
                $out .= html_writer::tag('h5', $badge, $attributes);
1837
                if ($dl) {
1838
                    $out .= html_writer::start_tag('dl', ['class' => 'row']);
1839
                }
1840
            }
1841
            $object = false;
1842
        }
1843
 
1844
        // Properties.
1845
        foreach ($item as $key => $value) {
1846
            // Detect private and protected variables.
1847
            $matches = [];
1848
            $stringkey = (string)$key;
1849
            if (preg_match('~^\x00(.*)\x00(.*)$~', $stringkey, $matches)) {
1850
                $shortkey = $matches[2];
1851
                $access = $matches[1] == '*' ? 'protected' : 'private';
1852
            } else {
1853
                $shortkey = $stringkey;
1854
                $access = 'public';
1855
            }
1856
            if ($textonly) {
1857
                switch ($access) {
1858
                    case 'protected' :
1859
                        $shortkey = '+' . $shortkey;
1860
                        break;
1861
                    case 'private' :
1862
                        $shortkey = '*' . $shortkey;
1863
                        break;
1864
                }
1865
                $out .= PHP_EOL . '  ' . $shortkey . ' = ';
1866
            } else {
1867
                switch ($access) {
1868
                    case 'protected':
1869
                        // Protected is in normal font.
1441 ariadna 1870
                        $bootstrapstyle = ' fw-normal';
1 efrain 1871
                        break;
1872
                    case 'private':
1873
                        // Private is italic.
1441 ariadna 1874
                        $bootstrapstyle = ' fw-normal fst-italic';
1 efrain 1875
                        break;
1876
                    default:
1877
                        // Public is bold, same for array keys.
1878
                        $bootstrapstyle = '';
1879
                        break;
1880
                }
1881
                $attributes = ['class' => $bootstrapdt . ' text-truncate' . $bootstrapstyle];
1882
                if ($object) {
1883
                    // For an object property, the title is the full text of the key (in case it
1884
                    // gets cut off) and the access modifier.
1885
                    $attributes['title'] = s($shortkey) . ' (' . $access . ')';
1886
                    $objectstr = s($shortkey);
1887
                } else {
1888
                    // For an array key, the title is the full text of the key (in case it gets
1889
                    // cut off) and the type of the key. Array keys can't have an access modifier.
1890
                    $attributes['title'] = s($shortkey) . ' (' . gettype($key) . ')';
1891
                    // Array keys are styled according to the normal styling for that type.
1892
                    $typestyle = $gettypestyle($key);
1893
                    if ($typestyle) {
1894
                        $attributes['class'] .= ' ' . $typestyle;
1895
                    }
1896
                    // Array keys also use a special object string e.g. 'true' for bool, quoted.
1897
                    $objectstr = $getobjectstr($key);
1898
                }
1899
                $out .= html_writer::tag('dt', $objectstr, $attributes);
1900
            }
1901
            // Consider how to display the value for this key.
1902
            $extraclass = '';
1903
            switch (gettype($value)) {
1904
                case 'object' :
1905
                    $objclass = get_class($value);
1906
 
1907
                    // See if we printed it further up the tree in which case
1908
                    // it will definitely not be printed (infinite recursion).
1909
                    if (in_array($value, $done)) {
1910
                        if ($textonly) {
1911
                            $display = '[circular reference: ' . $objclass . ']';
1912
                        } else {
1913
                            $display = '[circular reference: ' . s($objclass) . ']';
1914
                            $extraclass = ' text-danger';
1915
                        }
1916
                        break;
1917
                    }
1918
 
1919
                    // Recurse only to specified types.
1920
                    $recurse = false;
1921
                    foreach ($expandclasses as $pattern) {
1922
                        if (substr($pattern, 0, 1) === '/') {
1923
                            // Allow regular expressions beginning with a / symbol.
1924
                            if (preg_match($pattern, $objclass)) {
1925
                                $recurse = true;
1926
                                break;
1927
                            }
1928
                        } else {
1929
                            // Other strings must be exact match.
1930
                            if ($objclass === $pattern) {
1931
                                $recurse = true;
1932
                                break;
1933
                            }
1934
                        }
1935
                    }
1936
 
1937
                    if ($recurse) {
1938
                        // Recursively display the object.
1939
                        $display = print_object($value, $expandclasses, $textonly, true, $depth + 1, $done);
1940
                        if ($textonly) {
1941
                            // Indent by adding spaces after each LF.
1942
                            $display = str_replace(PHP_EOL, PHP_EOL . '  ', $display);
1943
                        }
1944
                    } else {
1945
                        // Do not display the object, just a marker in square breackets.
1946
                        if ($textonly) {
1947
                            $display = '[object: ' . $objclass . ']';
1948
                        } else {
1949
                            $display = '[object: ' . s($objclass) . ']';
1950
                        }
1951
                    }
1952
                    break;
1953
 
1954
                case 'array' :
1955
                    // Recursively display the array.
1956
                    $display = print_object($value, $expandclasses, $textonly, true, $depth + 1, $done);
1957
                    if ($textonly) {
1958
                        // Indent by adding spaces after each LF.
1959
                        $display = str_replace(PHP_EOL, PHP_EOL . '  ', $display);
1960
                    }
1961
                    break;
1962
 
1963
                default:
1964
                    // Plain value - recurse to display.
1965
                    $display = print_object($value, [], $textonly, true, $depth + 1);
1966
                    break;
1967
            }
1968
            if ($textonly) {
1969
                $out .= $display;
1970
            } else {
1971
                $out .= html_writer::tag('dd', $display, ['class' => $bootstrapdd . $extraclass]);
1972
            }
1973
        }
1974
        if (!$textonly && $dl) {
1975
            $out .= html_writer::end_tag('dl');
1976
        }
1977
    } else {
1978
        // For things which are not objects or arrays, just convert to string for display.
1979
        $out .= $getobjectstr($item);
1980
    }
1981
 
1982
    if (!$textonly) {
1983
        $out .= html_writer::end_div();
1984
    }
1985
 
1986
    // Display or return result.
1987
    if ($return) {
1988
        return $out;
1989
    } else {
1990
        if (CLI_SCRIPT) {
1991
            fwrite(STDERR, $out);
1992
            fwrite(STDERR, PHP_EOL);
1993
        } else if (AJAX_SCRIPT) {
1994
            foreach (explode(PHP_EOL, $out) as $line) {
1995
                error_log($line);
1996
            }
1997
        } else {
1998
            if ($textonly) {
1999
                $out = html_writer::tag('pre', s($out));
2000
            }
2001
            echo $out . "\n";
2002
        }
2003
        return '';
2004
    }
2005
}
2006
 
2007
/**
2008
 * This function is the official hook inside XMLDB stuff to delegate its debug to one
2009
 * external function.
2010
 *
2011
 * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
2012
 * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
2013
 *
2014
 * @uses DEBUG_DEVELOPER
2015
 * @param string $message string contains the error message
2016
 * @param object $object object XMLDB object that fired the debug
2017
 */
2018
function xmldb_debug($message, $object) {
2019
 
2020
    debugging($message, DEBUG_DEVELOPER);
2021
}
2022
 
2023
/**
2024
 * @global object
2025
 * @uses CONTEXT_COURSECAT
2026
 * @return boolean Whether the user can create courses in any category in the system.
2027
 */
2028
function user_can_create_courses() {
2029
    global $DB;
2030
    $catsrs = $DB->get_recordset('course_categories');
2031
    foreach ($catsrs as $cat) {
2032
        if (has_capability('moodle/course:create', context_coursecat::instance($cat->id))) {
2033
            $catsrs->close();
2034
            return true;
2035
        }
2036
    }
2037
    $catsrs->close();
2038
    return false;
2039
}
2040
 
2041
/**
2042
 * This method can update the values in mulitple database rows for a colum with
2043
 * a unique index, without violating that constraint.
2044
 *
2045
 * Suppose we have a table with a unique index on (otherid, sortorder), and
2046
 * for a particular value of otherid, we want to change all the sort orders.
2047
 * You have to do this carefully or you will violate the unique index at some time.
2048
 * This method takes care of the details for you.
2049
 *
2050
 * Note that, it is the responsibility of the caller to make sure that the
2051
 * requested rename is legal. For example, if you ask for [1 => 2, 2 => 2]
2052
 * then you will get a unique key violation error from the database.
2053
 *
2054
 * @param string $table The database table to modify.
2055
 * @param string $field the field that contains the values we are going to change.
2056
 * @param array $newvalues oldvalue => newvalue how to change the values.
2057
 *      E.g. [1 => 4, 2 => 1, 3 => 3, 4 => 2].
2058
 * @param array $otherconditions array fieldname => requestedvalue extra WHERE clause
2059
 *      conditions to restrict which rows are affected. E.g. array('otherid' => 123).
2060
 * @param int $unusedvalue (defaults to -1) a value that is never used in $ordercol.
2061
 */
2062
function update_field_with_unique_index($table, $field, array $newvalues,
2063
        array $otherconditions, $unusedvalue = -1) {
2064
    global $DB;
2065
    $safechanges = decompose_update_into_safe_changes($newvalues, $unusedvalue);
2066
 
2067
    $transaction = $DB->start_delegated_transaction();
2068
    foreach ($safechanges as $change) {
2069
        list($from, $to) = $change;
2070
        $otherconditions[$field] = $from;
2071
        $DB->set_field($table, $field, $to, $otherconditions);
2072
    }
2073
    $transaction->allow_commit();
2074
}
2075
 
2076
/**
2077
 * Helper used by {@link update_field_with_unique_index()}. Given a desired
2078
 * set of changes, break them down into single udpates that can be done one at
2079
 * a time without breaking any unique index constraints.
2080
 *
2081
 * Suppose the input is array(1 => 2, 2 => 1) and -1. Then the output will be
2082
 * array (array(1, -1), array(2, 1), array(-1, 2)). This function solves this
2083
 * problem in the general case, not just for simple swaps. The unit tests give
2084
 * more examples.
2085
 *
2086
 * Note that, it is the responsibility of the caller to make sure that the
2087
 * requested rename is legal. For example, if you ask for something impossible
2088
 * like array(1 => 2, 2 => 2) then the results are undefined. (You will probably
2089
 * get a unique key violation error from the database later.)
2090
 *
2091
 * @param array $newvalues The desired re-ordering.
2092
 *      E.g. array(1 => 4, 2 => 1, 3 => 3, 4 => 2).
2093
 * @param int $unusedvalue A value that is not currently used.
2094
 * @return array A safe way to perform the re-order. An array of two-element
2095
 *      arrays array($from, $to).
2096
 *      E.g. array(array(1, -1), array(2, 1), array(4, 2), array(-1, 4)).
2097
 */
2098
function decompose_update_into_safe_changes(array $newvalues, $unusedvalue) {
2099
    $nontrivialmap = array();
2100
    foreach ($newvalues as $from => $to) {
2101
        if ($from == $unusedvalue || $to == $unusedvalue) {
2102
            throw new \coding_exception('Supposedly unused value ' . $unusedvalue . ' is actually used!');
2103
        }
2104
        if ($from != $to) {
2105
            $nontrivialmap[$from] = $to;
2106
        }
2107
    }
2108
 
2109
    if (empty($nontrivialmap)) {
2110
        return array();
2111
    }
2112
 
2113
    // First we deal with all renames that are not part of cycles.
2114
    // This bit is O(n^2) and it ought to be possible to do better,
2115
    // but it does not seem worth the effort.
2116
    $safechanges = array();
2117
    $nontrivialmapchanged = true;
2118
    while ($nontrivialmapchanged) {
2119
        $nontrivialmapchanged = false;
2120
 
2121
        foreach ($nontrivialmap as $from => $to) {
2122
            if (array_key_exists($to, $nontrivialmap)) {
2123
                continue; // Cannot currenly do this rename.
2124
            }
2125
            // Is safe to do this rename now.
2126
            $safechanges[] = array($from, $to);
2127
            unset($nontrivialmap[$from]);
2128
            $nontrivialmapchanged = true;
2129
        }
2130
    }
2131
 
2132
    // Are we done?
2133
    if (empty($nontrivialmap)) {
2134
        return $safechanges;
2135
    }
2136
 
2137
    // Now what is left in $nontrivialmap must be a permutation,
2138
    // which must be a combination of disjoint cycles. We need to break them.
2139
    while (!empty($nontrivialmap)) {
2140
        // Extract the first cycle.
2141
        reset($nontrivialmap);
2142
        $current = $cyclestart = key($nontrivialmap);
2143
        $cycle = array();
2144
        do {
2145
            $cycle[] = $current;
2146
            $next = $nontrivialmap[$current];
2147
            unset($nontrivialmap[$current]);
2148
            $current = $next;
2149
        } while ($current != $cyclestart);
2150
 
2151
        // Now convert it to a sequence of safe renames by using a temp.
2152
        $safechanges[] = array($cyclestart, $unusedvalue);
2153
        $cycle[0] = $unusedvalue;
2154
        $to = $cyclestart;
2155
        while ($from = array_pop($cycle)) {
2156
            $safechanges[] = array($from, $to);
2157
            $to = $from;
2158
        }
2159
    }
2160
 
2161
    return $safechanges;
2162
}
2163
 
2164
/**
2165
 * Return maximum number of courses in a category
2166
 *
2167
 * @uses MAX_COURSES_IN_CATEGORY
2168
 * @return int number of courses
2169
 */
2170
function get_max_courses_in_category() {
2171
    global $CFG;
2172
    // Use default MAX_COURSES_IN_CATEGORY if $CFG->maxcoursesincategory is not set or invalid.
2173
    if (!isset($CFG->maxcoursesincategory) || clean_param($CFG->maxcoursesincategory, PARAM_INT) == 0) {
2174
        return MAX_COURSES_IN_CATEGORY;
2175
    } else {
2176
        return $CFG->maxcoursesincategory;
2177
    }
2178
}
2179
 
2180
/**
2181
 * Prepare a safe ORDER BY statement from user interactable requests.
2182
 *
2183
 * This allows safe user specified sorting (ORDER BY), by abstracting the SQL from the value being requested by the user.
2184
 * A standard string (and optional direction) can be specified, which will be mapped to a predefined allow list of SQL ordering.
2185
 * The mapping can optionally include a 'default', which will be used if the key provided is invalid.
2186
 *
2187
 * Example usage:
2188
 *      -If $orderbymap = [
2189
 *              'courseid' => 'c.id',
2190
 *              'somecustomvalue'=> 'c.startdate, c.shortname',
2191
 *              'default' => 'c.fullname',
2192
 *       ]
2193
 *      -A value from the map array's keys can be passed in by a user interaction (eg web service) along with an optional direction.
2194
 *      -get_safe_orderby($orderbymap, 'courseid', 'DESC') would return: ORDER BY c.id DESC
2195
 *      -get_safe_orderby($orderbymap, 'somecustomvalue') would return: ORDER BY c.startdate, c.shortname
2196
 *      -get_safe_orderby($orderbymap, 'invalidblah', 'DESC') would return: ORDER BY c.fullname DESC
2197
 *      -If no default key was specified in $orderbymap, the invalidblah example above would return empty string.
2198
 *
2199
 * @param array $orderbymap An array in the format [keystring => sqlstring]. A default fallback can be set with the key 'default'.
2200
 * @param string $orderbykey A string to be mapped to a key in $orderbymap.
2201
 * @param string $direction Optional ORDER BY direction (ASC/DESC, case insensitive).
2202
 * @param bool $useprefix Whether ORDER BY is prefixed to the output (true by default). This should not be modified in most cases.
2203
 *                        It is included to enable get_safe_orderby_multiple() to use this function multiple times.
2204
 * @return string The ORDER BY statement, or empty string if $orderbykey is invalid and no default is mapped.
2205
 */
2206
function get_safe_orderby(array $orderbymap, string $orderbykey, string $direction = '', bool $useprefix = true): string {
2207
    $orderby = $useprefix ? ' ORDER BY ' : '';
2208
    $output = '';
2209
 
2210
    // Only include an order direction if ASC/DESC is explicitly specified (case insensitive).
2211
    $direction = strtoupper($direction);
2212
    if (!in_array($direction, ['ASC', 'DESC'], true)) {
2213
        $direction = '';
2214
    } else {
2215
        $direction = " {$direction}";
2216
    }
2217
 
2218
    // Prepare the statement if the key maps to a defined sort parameter.
2219
    if (isset($orderbymap[$orderbykey])) {
2220
        $output = "{$orderby}{$orderbymap[$orderbykey]}{$direction}";
2221
    } else if (array_key_exists('default', $orderbymap)) {
2222
        // Fall back to use the default if one is specified.
2223
        $output = "{$orderby}{$orderbymap['default']}{$direction}";
2224
    }
2225
 
2226
    return $output;
2227
}
2228
 
2229
/**
2230
 * Prepare a safe ORDER BY statement from user interactable requests using multiple values.
2231
 *
2232
 * This allows safe user specified sorting (ORDER BY) similar to get_safe_orderby(), but supports multiple keys and directions.
2233
 * This is useful in cases where combinations of columns are needed and/or each item requires a specified direction (ASC/DESC).
2234
 * The mapping can optionally include a 'default', which will be used if the key provided is invalid.
2235
 *
2236
 * Example usage:
2237
 *      -If $orderbymap = [
2238
 *              'courseid' => 'c.id',
2239
 *              'fullname'=> 'c.fullname',
2240
 *              'default' => 'c.startdate',
2241
 *          ]
2242
 *      -An array of values from the map's keys can be passed in by a user interaction (eg web service), with optional directions.
2243
 *      -get_safe_orderby($orderbymap, ['courseid', 'fullname'], ['DESC', 'ASC']) would return: ORDER BY c.id DESC, c.fullname ASC
2244
 *      -get_safe_orderby($orderbymap, ['courseid', 'invalidblah'], ['aaa', 'DESC']) would return: ORDER BY c.id, c.startdate DESC
2245
 *      -If no default key was specified in $orderbymap, the invalidblah example above would return: ORDER BY c.id
2246
 *
2247
 * @param array $orderbymap An array in the format [keystring => sqlstring]. A default fallback can be set with the key 'default'.
2248
 * @param array $orderbykeys An array of strings to be mapped to keys in $orderbymap.
2249
 * @param array $directions Optional array of ORDER BY direction (ASC/DESC, case insensitive).
2250
 *                          The array keys should match array keys in $orderbykeys.
2251
 * @return string The ORDER BY statement, or empty string if $orderbykeys contains no valid items and no default is mapped.
2252
 */
2253
function get_safe_orderby_multiple(array $orderbymap, array $orderbykeys, array $directions = []): string {
2254
    $output = '';
2255
 
2256
    // Check each key for a valid mapping and add to the ORDER BY statement (invalid entries will be empty strings).
2257
    foreach ($orderbykeys as $index => $orderbykey) {
2258
        $direction = $directions[$index] ?? '';
2259
        $safeorderby = get_safe_orderby($orderbymap, $orderbykey, $direction, false);
2260
 
2261
        if (!empty($safeorderby)) {
2262
            $output .= ", {$safeorderby}";
2263
        }
2264
    }
2265
 
2266
    // Prefix with ORDER BY if any valid ordering is specified (and remove comma from the start).
2267
    if (!empty($output)) {
2268
        $output = ' ORDER BY' . ltrim($output, ',');
2269
    }
2270
 
2271
    return $output;
2272
}