Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.10.x will end 8 November 2021 (12 months).
  • Bug fixes for security issues in 3.10.x will end 9 May 2022 (18 months).
  • PHP version: minimum PHP 7.2.0 Note: minimum PHP version has increased since Moodle 3.8. PHP 7.3.x and 7.4.x are supported too.
/lib/ -> datalib.php (source)

Differences Between: [Versions 310 and 311] [Versions 310 and 400] [Versions 310 and 401] [Versions 310 and 402] [Versions 310 and 403] [Versions 39 and 310]

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