Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 3.9.x will end* 10 May 2021 (12 months).
  • Bug fixes for security issues in 3.9.x will end* 8 May 2023 (36 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 39 and 310] [Versions 39 and 311] [Versions 39 and 400] [Versions 39 and 401] [Versions 39 and 402] [Versions 39 and 403]

   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 a context is specified, get extra user fields that the current user
 510      // is supposed to see.
 511      $extrafields = '';
 512      $includedfields = ['id', 'username', 'email', 'firstname', 'lastname', 'city', 'country',
 513          'lastaccess', 'confirmed', 'mnethostid', 'suspended'];
 514      if ($extracontext) {
 515          $extrafields = get_extra_user_fields_sql($extracontext, '', '', $includedfields);
 516      }
 517      $namefields = get_all_user_name_fields(true);
 518      $extrafields = "$extrafields, $namefields";
 519  
 520      if ($sort) {
 521          $orderbymap = trim($extrafields, ', ');
 522          $orderbymap = array_merge(explode(',', $orderbymap), $includedfields);
 523          $neworderbymap = ['default' => 'lastaccess'];
 524          foreach($orderbymap as $value) {
 525              $neworderbymap[$value] = $value;
 526          }
 527          $sort = get_safe_orderby($neworderbymap, $sort, $dir);
 528      }
 529  
 530      // warning: will return UNCONFIRMED USERS
 531      return $DB->get_records_sql("SELECT id, username, email, city, country, lastaccess, confirmed, mnethostid, suspended $extrafields
 532                                     FROM {user}
 533                                    WHERE $select
 534                                    $sort", $params, $page, $recordsperpage);
 535  
 536  }
 537  
 538  
 539  /**
 540   * Full list of users that have confirmed their accounts.
 541   *
 542   * @global object
 543   * @return array of unconfirmed users
 544   */
 545  function get_users_confirmed() {
 546      global $DB, $CFG;
 547      return $DB->get_records_sql("SELECT *
 548                                     FROM {user}
 549                                    WHERE confirmed = 1 AND deleted = 0 AND id <> ?", array($CFG->siteguest));
 550  }
 551  
 552  
 553  /// OTHER SITE AND COURSE FUNCTIONS /////////////////////////////////////////////
 554  
 555  
 556  /**
 557   * Returns $course object of the top-level site.
 558   *
 559   * @return object A {@link $COURSE} object for the site, exception if not found
 560   */
 561  function get_site() {
 562      global $SITE, $DB;
 563  
 564      if (!empty($SITE->id)) {   // We already have a global to use, so return that
 565          return $SITE;
 566      }
 567  
 568      if ($course = $DB->get_record('course', array('category'=>0))) {
 569          return $course;
 570      } else {
 571          // course table exists, but the site is not there,
 572          // unfortunately there is no automatic way to recover
 573          throw new moodle_exception('nosite', 'error');
 574      }
 575  }
 576  
 577  /**
 578   * Gets a course object from database. If the course id corresponds to an
 579   * already-loaded $COURSE or $SITE object, then the loaded object will be used,
 580   * saving a database query.
 581   *
 582   * If it reuses an existing object, by default the object will be cloned. This
 583   * means you can modify the object safely without affecting other code.
 584   *
 585   * @param int $courseid Course id
 586   * @param bool $clone If true (default), makes a clone of the record
 587   * @return stdClass A course object
 588   * @throws dml_exception If not found in database
 589   */
 590  function get_course($courseid, $clone = true) {
 591      global $DB, $COURSE, $SITE;
 592      if (!empty($COURSE->id) && $COURSE->id == $courseid) {
 593          return $clone ? clone($COURSE) : $COURSE;
 594      } else if (!empty($SITE->id) && $SITE->id == $courseid) {
 595          return $clone ? clone($SITE) : $SITE;
 596      } else {
 597          return $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
 598      }
 599  }
 600  
 601  /**
 602   * Returns list of courses, for whole site, or category
 603   *
 604   * Returns list of courses, for whole site, or category
 605   * Important: Using c.* for fields is extremely expensive because
 606   *            we are using distinct. You almost _NEVER_ need all the fields
 607   *            in such a large SELECT
 608   *
 609   * Consider using core_course_category::get_courses()
 610   * or core_course_category::search_courses() instead since they use caching.
 611   *
 612   * @global object
 613   * @global object
 614   * @global object
 615   * @uses CONTEXT_COURSE
 616   * @param string|int $categoryid Either a category id or 'all' for everything
 617   * @param string $sort A field and direction to sort by
 618   * @param string $fields The additional fields to return (note that "id, category, visible" are always present)
 619   * @return array Array of courses
 620   */
 621  function get_courses($categoryid="all", $sort="c.sortorder ASC", $fields="c.*") {
 622  
 623      global $USER, $CFG, $DB;
 624  
 625      $params = array();
 626  
 627      if ($categoryid !== "all" && is_numeric($categoryid)) {
 628          $categoryselect = "WHERE c.category = :catid";
 629          $params['catid'] = $categoryid;
 630      } else {
 631          $categoryselect = "";
 632      }
 633  
 634      if (empty($sort)) {
 635          $sortstatement = "";
 636      } else {
 637          $sortstatement = "ORDER BY $sort";
 638      }
 639  
 640      $visiblecourses = array();
 641  
 642      $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
 643      $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
 644      $params['contextlevel'] = CONTEXT_COURSE;
 645  
 646      // The fields "id, category, visible" are required in the subsequent loop and must always be present.
 647      if ($fields !== 'c.*') {
 648          $fieldarray = array_merge(
 649              // Split fields on comma + zero or more whitespace, merge with required fields.
 650              preg_split('/,\s*/', $fields), [
 651                  'c.id',
 652                  'c.category',
 653                  'c.visible',
 654              ]
 655          );
 656          $fields = implode(',', array_unique($fieldarray));
 657      }
 658  
 659      $sql = "SELECT $fields $ccselect
 660                FROM {course} c
 661             $ccjoin
 662                $categoryselect
 663                $sortstatement";
 664  
 665      // pull out all course matching the cat
 666      if ($courses = $DB->get_records_sql($sql, $params)) {
 667  
 668          // loop throught them
 669          foreach ($courses as $course) {
 670              context_helper::preload_from_record($course);
 671              if (core_course_category::can_view_course_info($course)) {
 672                  $visiblecourses [$course->id] = $course;
 673              }
 674          }
 675      }
 676      return $visiblecourses;
 677  }
 678  
 679  /**
 680   * A list of courses that match a search
 681   *
 682   * @global object
 683   * @global object
 684   * @param array $searchterms An array of search criteria
 685   * @param string $sort A field and direction to sort by
 686   * @param int $page The page number to get
 687   * @param int $recordsperpage The number of records per page
 688   * @param int $totalcount Passed in by reference.
 689   * @param array $requiredcapabilities Extra list of capabilities used to filter courses
 690   * @param array $searchcond additional search conditions, for example ['c.enablecompletion = :p1']
 691   * @param array $params named parameters for additional search conditions, for example ['p1' => 1]
 692   * @return stdClass[] {@link $COURSE} records
 693   */
 694  function get_courses_search($searchterms, $sort, $page, $recordsperpage, &$totalcount,
 695                              $requiredcapabilities = array(), $searchcond = [], $params = []) {
 696      global $CFG, $DB;
 697  
 698      if ($DB->sql_regex_supported()) {
 699          $REGEXP    = $DB->sql_regex(true);
 700          $NOTREGEXP = $DB->sql_regex(false);
 701      }
 702  
 703      $i = 0;
 704  
 705      // Thanks Oracle for your non-ansi concat and type limits in coalesce. MDL-29912
 706      if ($DB->get_dbfamily() == 'oracle') {
 707          $concat = "(c.summary|| ' ' || c.fullname || ' ' || c.idnumber || ' ' || c.shortname)";
 708      } else {
 709          $concat = $DB->sql_concat("COALESCE(c.summary, '')", "' '", 'c.fullname', "' '", 'c.idnumber', "' '", 'c.shortname');
 710      }
 711  
 712      foreach ($searchterms as $searchterm) {
 713          $i++;
 714  
 715          $NOT = false; /// Initially we aren't going to perform NOT LIKE searches, only MSSQL and Oracle
 716                     /// will use it to simulate the "-" operator with LIKE clause
 717  
 718      /// Under Oracle and MSSQL, trim the + and - operators and perform
 719      /// simpler LIKE (or NOT LIKE) queries
 720          if (!$DB->sql_regex_supported()) {
 721              if (substr($searchterm, 0, 1) == '-') {
 722                  $NOT = true;
 723              }
 724              $searchterm = trim($searchterm, '+-');
 725          }
 726  
 727          // TODO: +- may not work for non latin languages
 728  
 729          if (substr($searchterm,0,1) == '+') {
 730              $searchterm = trim($searchterm, '+-');
 731              $searchterm = preg_quote($searchterm, '|');
 732              $searchcond[] = "$concat $REGEXP :ss$i";
 733              $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
 734  
 735          } else if ((substr($searchterm,0,1) == "-") && (core_text::strlen($searchterm) > 1)) {
 736              $searchterm = trim($searchterm, '+-');
 737              $searchterm = preg_quote($searchterm, '|');
 738              $searchcond[] = "$concat $NOTREGEXP :ss$i";
 739              $params['ss'.$i] = "(^|[^a-zA-Z0-9])$searchterm([^a-zA-Z0-9]|$)";
 740  
 741          } else {
 742              $searchcond[] = $DB->sql_like($concat,":ss$i", false, true, $NOT);
 743              $params['ss'.$i] = "%$searchterm%";
 744          }
 745      }
 746  
 747      if (empty($searchcond)) {
 748          $searchcond = array('1 = 1');
 749      }
 750  
 751      $searchcond = implode(" AND ", $searchcond);
 752  
 753      $courses = array();
 754      $c = 0; // counts how many visible courses we've seen
 755  
 756      // Tiki pagination
 757      $limitfrom = $page * $recordsperpage;
 758      $limitto   = $limitfrom + $recordsperpage;
 759  
 760      $ccselect = ', ' . context_helper::get_preload_record_columns_sql('ctx');
 761      $ccjoin = "LEFT JOIN {context} ctx ON (ctx.instanceid = c.id AND ctx.contextlevel = :contextlevel)";
 762      $params['contextlevel'] = CONTEXT_COURSE;
 763  
 764      $sql = "SELECT c.* $ccselect
 765                FROM {course} c
 766             $ccjoin
 767               WHERE $searchcond AND c.id <> ".SITEID."
 768            ORDER BY $sort";
 769  
 770      $mycourses = enrol_get_my_courses();
 771      $rs = $DB->get_recordset_sql($sql, $params);
 772      foreach($rs as $course) {
 773          // Preload contexts only for hidden courses or courses we need to return.
 774          context_helper::preload_from_record($course);
 775          $coursecontext = context_course::instance($course->id);
 776          if (!array_key_exists($course->id, $mycourses) && !core_course_category::can_view_course_info($course)) {
 777              continue;
 778          }
 779          if (!empty($requiredcapabilities)) {
 780              if (!has_all_capabilities($requiredcapabilities, $coursecontext)) {
 781                  continue;
 782              }
 783          }
 784          // Don't exit this loop till the end
 785          // we need to count all the visible courses
 786          // to update $totalcount
 787          if ($c >= $limitfrom && $c < $limitto) {
 788              $courses[$course->id] = $course;
 789          }
 790          $c++;
 791      }
 792      $rs->close();
 793  
 794      // our caller expects 2 bits of data - our return
 795      // array, and an updated $totalcount
 796      $totalcount = $c;
 797      return $courses;
 798  }
 799  
 800  /**
 801   * Fixes course category and course sortorder, also verifies category and course parents and paths.
 802   * (circular references are not fixed)
 803   *
 804   * @global object
 805   * @global object
 806   * @uses MAX_COURSES_IN_CATEGORY
 807   * @uses MAX_COURSE_CATEGORIES
 808   * @uses SITEID
 809   * @uses CONTEXT_COURSE
 810   * @return void
 811   */
 812  function fix_course_sortorder() {
 813      global $DB, $SITE;
 814  
 815      //WARNING: this is PHP5 only code!
 816  
 817      // if there are any changes made to courses or categories we will trigger
 818      // the cache events to purge all cached courses/categories data
 819      $cacheevents = array();
 820  
 821      if ($unsorted = $DB->get_records('course_categories', array('sortorder'=>0))) {
 822          //move all categories that are not sorted yet to the end
 823          $DB->set_field('course_categories', 'sortorder', MAX_COURSES_IN_CATEGORY*MAX_COURSE_CATEGORIES, array('sortorder'=>0));
 824          $cacheevents['changesincoursecat'] = true;
 825      }
 826  
 827      $allcats = $DB->get_records('course_categories', null, 'sortorder, id', 'id, sortorder, parent, depth, path');
 828      $topcats    = array();
 829      $brokencats = array();
 830      foreach ($allcats as $cat) {
 831          $sortorder = (int)$cat->sortorder;
 832          if (!$cat->parent) {
 833              while(isset($topcats[$sortorder])) {
 834                  $sortorder++;
 835              }
 836              $topcats[$sortorder] = $cat;
 837              continue;
 838          }
 839          if (!isset($allcats[$cat->parent])) {
 840              $brokencats[] = $cat;
 841              continue;
 842          }
 843          if (!isset($allcats[$cat->parent]->children)) {
 844              $allcats[$cat->parent]->children = array();
 845          }
 846          while(isset($allcats[$cat->parent]->children[$sortorder])) {
 847              $sortorder++;
 848          }
 849          $allcats[$cat->parent]->children[$sortorder] = $cat;
 850      }
 851      unset($allcats);
 852  
 853      // add broken cats to category tree
 854      if ($brokencats) {
 855          $defaultcat = reset($topcats);
 856          foreach ($brokencats as $cat) {
 857              $topcats[] = $cat;
 858          }
 859      }
 860  
 861      // now walk recursively the tree and fix any problems found
 862      $sortorder = 0;
 863      $fixcontexts = array();
 864      if (_fix_course_cats($topcats, $sortorder, 0, 0, '', $fixcontexts)) {
 865          $cacheevents['changesincoursecat'] = true;
 866      }
 867  
 868      // detect if there are "multiple" frontpage courses and fix them if needed
 869      $frontcourses = $DB->get_records('course', array('category'=>0), 'id');
 870      if (count($frontcourses) > 1) {
 871          if (isset($frontcourses[SITEID])) {
 872              $frontcourse = $frontcourses[SITEID];
 873              unset($frontcourses[SITEID]);
 874          } else {
 875              $frontcourse = array_shift($frontcourses);
 876          }
 877          $defaultcat = reset($topcats);
 878          foreach ($frontcourses as $course) {
 879              $DB->set_field('course', 'category', $defaultcat->id, array('id'=>$course->id));
 880              $context = context_course::instance($course->id);
 881              $fixcontexts[$context->id] = $context;
 882              $cacheevents['changesincourse'] = true;
 883          }
 884          unset($frontcourses);
 885      } else {
 886          $frontcourse = reset($frontcourses);
 887      }
 888  
 889      // now fix the paths and depths in context table if needed
 890      if ($fixcontexts) {
 891          foreach ($fixcontexts as $fixcontext) {
 892              $fixcontext->reset_paths(false);
 893          }
 894          context_helper::build_all_paths(false);
 895          unset($fixcontexts);
 896          $cacheevents['changesincourse'] = true;
 897          $cacheevents['changesincoursecat'] = true;
 898      }
 899  
 900      // release memory
 901      unset($topcats);
 902      unset($brokencats);
 903      unset($fixcontexts);
 904  
 905      // fix frontpage course sortorder
 906      if ($frontcourse->sortorder != 1) {
 907          $DB->set_field('course', 'sortorder', 1, array('id'=>$frontcourse->id));
 908          $cacheevents['changesincourse'] = true;
 909      }
 910  
 911      // now fix the course counts in category records if needed
 912      $sql = "SELECT cc.id, cc.coursecount, COUNT(c.id) AS newcount
 913                FROM {course_categories} cc
 914                LEFT JOIN {course} c ON c.category = cc.id
 915            GROUP BY cc.id, cc.coursecount
 916              HAVING cc.coursecount <> COUNT(c.id)";
 917  
 918      if ($updatecounts = $DB->get_records_sql($sql)) {
 919          // categories with more courses than MAX_COURSES_IN_CATEGORY
 920          $categories = array();
 921          foreach ($updatecounts as $cat) {
 922              $cat->coursecount = $cat->newcount;
 923              if ($cat->coursecount >= MAX_COURSES_IN_CATEGORY) {
 924                  $categories[] = $cat->id;
 925              }
 926              unset($cat->newcount);
 927              $DB->update_record_raw('course_categories', $cat, true);
 928          }
 929          if (!empty($categories)) {
 930              $str = implode(', ', $categories);
 931              debugging("The number of courses (category id: $str) has reached MAX_COURSES_IN_CATEGORY (" . MAX_COURSES_IN_CATEGORY . "), it will cause a sorting performance issue, please increase the value of MAX_COURSES_IN_CATEGORY in lib/datalib.php file. See tracker issue: MDL-25669", DEBUG_DEVELOPER);
 932          }
 933          $cacheevents['changesincoursecat'] = true;
 934      }
 935  
 936      // now make sure that sortorders in course table are withing the category sortorder ranges
 937      $sql = "SELECT DISTINCT cc.id, cc.sortorder
 938                FROM {course_categories} cc
 939                JOIN {course} c ON c.category = cc.id
 940               WHERE c.sortorder < cc.sortorder OR c.sortorder > cc.sortorder + ".MAX_COURSES_IN_CATEGORY;
 941  
 942      if ($fixcategories = $DB->get_records_sql($sql)) {
 943          //fix the course sortorder ranges
 944          foreach ($fixcategories as $cat) {
 945              $sql = "UPDATE {course}
 946                         SET sortorder = ".$DB->sql_modulo('sortorder', MAX_COURSES_IN_CATEGORY)." + ?
 947                       WHERE category = ?";
 948              $DB->execute($sql, array($cat->sortorder, $cat->id));
 949          }
 950          $cacheevents['changesincoursecat'] = true;
 951      }
 952      unset($fixcategories);
 953  
 954      // categories having courses with sortorder duplicates or having gaps in sortorder
 955      $sql = "SELECT DISTINCT c1.category AS id , cc.sortorder
 956                FROM {course} c1
 957                JOIN {course} c2 ON c1.sortorder = c2.sortorder
 958                JOIN {course_categories} cc ON (c1.category = cc.id)
 959               WHERE c1.id <> c2.id";
 960      $fixcategories = $DB->get_records_sql($sql);
 961  
 962      $sql = "SELECT cc.id, cc.sortorder, cc.coursecount, MAX(c.sortorder) AS maxsort, MIN(c.sortorder) AS minsort
 963                FROM {course_categories} cc
 964                JOIN {course} c ON c.category = cc.id
 965            GROUP BY cc.id, cc.sortorder, cc.coursecount
 966              HAVING (MAX(c.sortorder) <>  cc.sortorder + cc.coursecount) OR (MIN(c.sortorder) <>  cc.sortorder + 1)";
 967      $gapcategories = $DB->get_records_sql($sql);
 968  
 969      foreach ($gapcategories as $cat) {
 970          if (isset($fixcategories[$cat->id])) {
 971              // duplicates detected already
 972  
 973          } else if ($cat->minsort == $cat->sortorder and $cat->maxsort == $cat->sortorder + $cat->coursecount - 1) {
 974              // easy - new course inserted with sortorder 0, the rest is ok
 975              $sql = "UPDATE {course}
 976                         SET sortorder = sortorder + 1
 977                       WHERE category = ?";
 978              $DB->execute($sql, array($cat->id));
 979  
 980          } else {
 981              // it needs full resorting
 982              $fixcategories[$cat->id] = $cat;
 983          }
 984          $cacheevents['changesincourse'] = true;
 985      }
 986      unset($gapcategories);
 987  
 988      // fix course sortorders in problematic categories only
 989      foreach ($fixcategories as $cat) {
 990          $i = 1;
 991          $courses = $DB->get_records('course', array('category'=>$cat->id), 'sortorder ASC, id DESC', 'id, sortorder');
 992          foreach ($courses as $course) {
 993              if ($course->sortorder != $cat->sortorder + $i) {
 994                  $course->sortorder = $cat->sortorder + $i;
 995                  $DB->update_record_raw('course', $course, true);
 996                  $cacheevents['changesincourse'] = true;
 997              }
 998              $i++;
 999          }
1000      }
1001  
1002      // advise all caches that need to be rebuilt
1003      foreach (array_keys($cacheevents) as $event) {
1004          cache_helper::purge_by_event($event);
1005      }
1006  }
1007  
1008  /**
1009   * Internal recursive category verification function, do not use directly!
1010   *
1011   * @todo Document the arguments of this function better
1012   *
1013   * @global object
1014   * @uses MAX_COURSES_IN_CATEGORY
1015   * @uses CONTEXT_COURSECAT
1016   * @param array $children
1017   * @param int $sortorder
1018   * @param string $parent
1019   * @param int $depth
1020   * @param string $path
1021   * @param array $fixcontexts
1022   * @return bool if changes were made
1023   */
1024  function _fix_course_cats($children, &$sortorder, $parent, $depth, $path, &$fixcontexts) {
1025      global $DB;
1026  
1027      $depth++;
1028      $changesmade = false;
1029  
1030      foreach ($children as $cat) {
1031          $sortorder = $sortorder + MAX_COURSES_IN_CATEGORY;
1032          $update = false;
1033          if ($parent != $cat->parent or $depth != $cat->depth or $path.'/'.$cat->id != $cat->path) {
1034              $cat->parent = $parent;
1035              $cat->depth  = $depth;
1036              $cat->path   = $path.'/'.$cat->id;
1037              $update = true;
1038  
1039              // make sure context caches are rebuild and dirty contexts marked
1040              $context = context_coursecat::instance($cat->id);
1041              $fixcontexts[$context->id] = $context;
1042          }
1043          if ($cat->sortorder != $sortorder) {
1044              $cat->sortorder = $sortorder;
1045              $update = true;
1046          }
1047          if ($update) {
1048              $DB->update_record('course_categories', $cat, true);
1049              $changesmade = true;
1050          }
1051          if (isset($cat->children)) {
1052              if (_fix_course_cats($cat->children, $sortorder, $cat->id, $cat->depth, $cat->path, $fixcontexts)) {
1053                  $changesmade = true;
1054              }
1055          }
1056      }
1057      return $changesmade;
1058  }
1059  
1060  /**
1061   * List of remote courses that a user has access to via MNET.
1062   * Works only on the IDP
1063   *
1064   * @global object
1065   * @global object
1066   * @param int @userid The user id to get remote courses for
1067   * @return array Array of {@link $COURSE} of course objects
1068   */
1069  function get_my_remotecourses($userid=0) {
1070      global $DB, $USER;
1071  
1072      if (empty($userid)) {
1073          $userid = $USER->id;
1074      }
1075  
1076      // we can not use SELECT DISTINCT + text field (summary) because of MS SQL and Oracle, subselect used therefore
1077      $sql = "SELECT c.id, c.remoteid, c.shortname, c.fullname,
1078                     c.hostid, c.summary, c.summaryformat, c.categoryname AS cat_name,
1079                     h.name AS hostname
1080                FROM {mnetservice_enrol_courses} c
1081                JOIN (SELECT DISTINCT hostid, remotecourseid
1082                        FROM {mnetservice_enrol_enrolments}
1083                       WHERE userid = ?
1084                     ) e ON (e.hostid = c.hostid AND e.remotecourseid = c.remoteid)
1085                JOIN {mnet_host} h ON h.id = c.hostid";
1086  
1087      return $DB->get_records_sql($sql, array($userid));
1088  }
1089  
1090  /**
1091   * List of remote hosts that a user has access to via MNET.
1092   * Works on the SP
1093   *
1094   * @global object
1095   * @global object
1096   * @return array|bool Array of host objects or false
1097   */
1098  function get_my_remotehosts() {
1099      global $CFG, $USER;
1100  
1101      if ($USER->mnethostid == $CFG->mnet_localhost_id) {
1102          return false; // Return nothing on the IDP
1103      }
1104      if (!empty($USER->mnet_foreign_host_array) && is_array($USER->mnet_foreign_host_array)) {
1105          return $USER->mnet_foreign_host_array;
1106      }
1107      return false;
1108  }
1109  
1110  
1111  /**
1112   * Returns a menu of all available scales from the site as well as the given course
1113   *
1114   * @global object
1115   * @param int $courseid The id of the course as found in the 'course' table.
1116   * @return array
1117   */
1118  function get_scales_menu($courseid=0) {
1119      global $DB;
1120  
1121      $sql = "SELECT id, name, courseid
1122                FROM {scale}
1123               WHERE courseid = 0 or courseid = ?
1124            ORDER BY courseid ASC, name ASC";
1125      $params = array($courseid);
1126      $scales = array();
1127      $results = $DB->get_records_sql($sql, $params);
1128      foreach ($results as $index => $record) {
1129          $context = empty($record->courseid) ? context_system::instance() : context_course::instance($record->courseid);
1130          $scales[$index] = format_string($record->name, false, ["context" => $context]);
1131      }
1132      // Format: [id => 'scale name'].
1133      return $scales;
1134  }
1135  
1136  /**
1137   * Increment standard revision field.
1138   *
1139   * The revision are based on current time and are incrementing.
1140   * There is a protection for runaway revisions, it may not go further than
1141   * one hour into future.
1142   *
1143   * The field has to be XMLDB_TYPE_INTEGER with size 10.
1144   *
1145   * @param string $table
1146   * @param string $field name of the field containing revision
1147   * @param string $select use empty string when updating all records
1148   * @param array $params optional select parameters
1149   */
1150  function increment_revision_number($table, $field, $select, array $params = null) {
1151      global $DB;
1152  
1153      $now = time();
1154      $sql = "UPDATE {{$table}}
1155                     SET $field = (CASE
1156                         WHEN $field IS NULL THEN $now
1157                         WHEN $field < $now THEN $now
1158                         WHEN $field > $now + 3600 THEN $now
1159                         ELSE $field + 1 END)";
1160      if ($select) {
1161          $sql = $sql . " WHERE $select";
1162      }
1163      $DB->execute($sql, $params);
1164  }
1165  
1166  
1167  /// MODULE FUNCTIONS /////////////////////////////////////////////////
1168  
1169  /**
1170   * Just gets a raw list of all modules in a course
1171   *
1172   * @global object
1173   * @param int $courseid The id of the course as found in the 'course' table.
1174   * @return array
1175   */
1176  function get_course_mods($courseid) {
1177      global $DB;
1178  
1179      if (empty($courseid)) {
1180          return false; // avoid warnings
1181      }
1182  
1183      return $DB->get_records_sql("SELECT cm.*, m.name as modname
1184                                     FROM {modules} m, {course_modules} cm
1185                                    WHERE cm.course = ? AND cm.module = m.id AND m.visible = 1",
1186                                  array($courseid)); // no disabled mods
1187  }
1188  
1189  
1190  /**
1191   * Given an id of a course module, finds the coursemodule description
1192   *
1193   * Please note that this function performs 1-2 DB queries. When possible use cached
1194   * course modinfo. For example get_fast_modinfo($courseorid)->get_cm($cmid)
1195   * See also {@link cm_info::get_course_module_record()}
1196   *
1197   * @global object
1198   * @param string $modulename name of module type, eg. resource, assignment,... (optional, slower and less safe if not specified)
1199   * @param int $cmid course module id (id in course_modules table)
1200   * @param int $courseid optional course id for extra validation
1201   * @param bool $sectionnum include relative section number (0,1,2 ...)
1202   * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1203   *                        IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1204   *                        MUST_EXIST means throw exception if no record or multiple records found
1205   * @return stdClass
1206   */
1207  function get_coursemodule_from_id($modulename, $cmid, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1208      global $DB;
1209  
1210      $params = array('cmid'=>$cmid);
1211  
1212      if (!$modulename) {
1213          if (!$modulename = $DB->get_field_sql("SELECT md.name
1214                                                   FROM {modules} md
1215                                                   JOIN {course_modules} cm ON cm.module = md.id
1216                                                  WHERE cm.id = :cmid", $params, $strictness)) {
1217              return false;
1218          }
1219      } else {
1220          if (!core_component::is_valid_plugin_name('mod', $modulename)) {
1221              throw new coding_exception('Invalid modulename parameter');
1222          }
1223      }
1224  
1225      $params['modulename'] = $modulename;
1226  
1227      $courseselect = "";
1228      $sectionfield = "";
1229      $sectionjoin  = "";
1230  
1231      if ($courseid) {
1232          $courseselect = "AND cm.course = :courseid";
1233          $params['courseid'] = $courseid;
1234      }
1235  
1236      if ($sectionnum) {
1237          $sectionfield = ", cw.section AS sectionnum";
1238          $sectionjoin  = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1239      }
1240  
1241      $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1242                FROM {course_modules} cm
1243                     JOIN {modules} md ON md.id = cm.module
1244                     JOIN {".$modulename."} m ON m.id = cm.instance
1245                     $sectionjoin
1246               WHERE cm.id = :cmid AND md.name = :modulename
1247                     $courseselect";
1248  
1249      return $DB->get_record_sql($sql, $params, $strictness);
1250  }
1251  
1252  /**
1253   * Given an instance number of a module, finds the coursemodule description
1254   *
1255   * Please note that this function performs DB query. When possible use cached course
1256   * modinfo. For example get_fast_modinfo($courseorid)->instances[$modulename][$instance]
1257   * See also {@link cm_info::get_course_module_record()}
1258   *
1259   * @global object
1260   * @param string $modulename name of module type, eg. resource, assignment,...
1261   * @param int $instance module instance number (id in resource, assignment etc. table)
1262   * @param int $courseid optional course id for extra validation
1263   * @param bool $sectionnum include relative section number (0,1,2 ...)
1264   * @param int $strictness IGNORE_MISSING means compatible mode, false returned if record not found, debug message if more found;
1265   *                        IGNORE_MULTIPLE means return first, ignore multiple records found(not recommended);
1266   *                        MUST_EXIST means throw exception if no record or multiple records found
1267   * @return stdClass
1268   */
1269  function get_coursemodule_from_instance($modulename, $instance, $courseid=0, $sectionnum=false, $strictness=IGNORE_MISSING) {
1270      global $DB;
1271  
1272      if (!core_component::is_valid_plugin_name('mod', $modulename)) {
1273          throw new coding_exception('Invalid modulename parameter');
1274      }
1275  
1276      $params = array('instance'=>$instance, 'modulename'=>$modulename);
1277  
1278      $courseselect = "";
1279      $sectionfield = "";
1280      $sectionjoin  = "";
1281  
1282      if ($courseid) {
1283          $courseselect = "AND cm.course = :courseid";
1284          $params['courseid'] = $courseid;
1285      }
1286  
1287      if ($sectionnum) {
1288          $sectionfield = ", cw.section AS sectionnum";
1289          $sectionjoin  = "LEFT JOIN {course_sections} cw ON cw.id = cm.section";
1290      }
1291  
1292      $sql = "SELECT cm.*, m.name, md.name AS modname $sectionfield
1293                FROM {course_modules} cm
1294                     JOIN {modules} md ON md.id = cm.module
1295                     JOIN {".$modulename."} m ON m.id = cm.instance
1296                     $sectionjoin
1297               WHERE m.id = :instance AND md.name = :modulename
1298                     $courseselect";
1299  
1300      return $DB->get_record_sql($sql, $params, $strictness);
1301  }
1302  
1303  /**
1304   * Returns all course modules of given activity in course
1305   *
1306   * @param string $modulename The module name (forum, quiz, etc.)
1307   * @param int $courseid The course id to get modules for
1308   * @param string $extrafields extra fields starting with m.
1309   * @return array Array of results
1310   */
1311  function get_coursemodules_in_course($modulename, $courseid, $extrafields='') {
1312      global $DB;
1313  
1314      if (!core_component::is_valid_plugin_name('mod', $modulename)) {
1315          throw new coding_exception('Invalid modulename parameter');
1316      }
1317  
1318      if (!empty($extrafields)) {
1319          $extrafields = ", $extrafields";
1320      }
1321      $params = array();
1322      $params['courseid'] = $courseid;
1323      $params['modulename'] = $modulename;
1324  
1325  
1326      return $DB->get_records_sql("SELECT cm.*, m.name, md.name as modname $extrafields
1327                                     FROM {course_modules} cm, {modules} md, {".$modulename."} m
1328                                    WHERE cm.course = :courseid AND
1329                                          cm.instance = m.id AND
1330                                          md.name = :modulename AND
1331                                          md.id = cm.module", $params);
1332  }
1333  
1334  /**
1335   * Returns an array of all the active instances of a particular module in given courses, sorted in the order they are defined
1336   *
1337   * Returns an array of all the active instances of a particular
1338   * module in given courses, sorted in the order they are defined
1339   * in the course. Returns an empty array on any errors.
1340   *
1341   * The returned objects includle the columns cw.section, cm.visible,
1342   * cm.groupmode, and cm.groupingid, and are indexed by cm.id.
1343   *
1344   * @global object
1345   * @global object
1346   * @param string $modulename The name of the module to get instances for
1347   * @param array $courses an array of course objects.
1348   * @param int $userid
1349   * @param int $includeinvisible
1350   * @return array of module instance objects, including some extra fields from the course_modules
1351   *          and course_sections tables, or an empty array if an error occurred.
1352   */
1353  function get_all_instances_in_courses($modulename, $courses, $userid=NULL, $includeinvisible=false) {
1354      global $CFG, $DB;
1355  
1356      if (!core_component::is_valid_plugin_name('mod', $modulename)) {
1357          throw new coding_exception('Invalid modulename parameter');
1358      }
1359  
1360      $outputarray = array();
1361  
1362      if (empty($courses) || !is_array($courses) || count($courses) == 0) {
1363          return $outputarray;
1364      }
1365  
1366      list($coursessql, $params) = $DB->get_in_or_equal(array_keys($courses), SQL_PARAMS_NAMED, 'c0');
1367      $params['modulename'] = $modulename;
1368  
1369      if (!$rawmods = $DB->get_records_sql("SELECT cm.id AS coursemodule, m.*, cw.section, cm.visible AS visible,
1370                                                   cm.groupmode, cm.groupingid
1371                                              FROM {course_modules} cm, {course_sections} cw, {modules} md,
1372                                                   {".$modulename."} m
1373                                             WHERE cm.course $coursessql AND
1374                                                   cm.instance = m.id AND
1375                                                   cm.section = cw.id AND
1376                                                   md.name = :modulename AND
1377                                                   md.id = cm.module", $params)) {
1378          return $outputarray;
1379      }
1380  
1381      foreach ($courses as $course) {
1382          $modinfo = get_fast_modinfo($course, $userid);
1383  
1384          if (empty($modinfo->instances[$modulename])) {
1385              continue;
1386          }
1387  
1388          foreach ($modinfo->instances[$modulename] as $cm) {
1389              if (!$includeinvisible and !$cm->uservisible) {
1390                  continue;
1391              }
1392              if (!isset($rawmods[$cm->id])) {
1393                  continue;
1394              }
1395              $instance = $rawmods[$cm->id];
1396              if (!empty($cm->extra)) {
1397                  $instance->extra = $cm->extra;
1398              }
1399              $outputarray[] = $instance;
1400          }
1401      }
1402  
1403      return $outputarray;
1404  }
1405  
1406  /**
1407   * Returns an array of all the active instances of a particular module in a given course,
1408   * sorted in the order they are defined.
1409   *
1410   * Returns an array of all the active instances of a particular
1411   * module in a given course, sorted in the order they are defined
1412   * in the course. Returns an empty array on any errors.
1413   *
1414   * The returned objects includle the columns cw.section, cm.visible,
1415   * cm.groupmode, and cm.groupingid, and are indexed by cm.id.
1416   *
1417   * Simply calls {@link all_instances_in_courses()} with a single provided course
1418   *
1419   * @param string $modulename The name of the module to get instances for
1420   * @param object $course The course obect.
1421   * @return array of module instance objects, including some extra fields from the course_modules
1422   *          and course_sections tables, or an empty array if an error occurred.
1423   * @param int $userid
1424   * @param int $includeinvisible
1425   */
1426  function get_all_instances_in_course($modulename, $course, $userid=NULL, $includeinvisible=false) {
1427      return get_all_instances_in_courses($modulename, array($course->id => $course), $userid, $includeinvisible);
1428  }
1429  
1430  
1431  /**
1432   * Determine whether a module instance is visible within a course
1433   *
1434   * Given a valid module object with info about the id and course,
1435   * and the module's type (eg "forum") returns whether the object
1436   * is visible or not according to the 'eye' icon only.
1437   *
1438   * NOTE: This does NOT take into account visibility to a particular user.
1439   * To get visibility access for a specific user, use get_fast_modinfo, get a
1440   * cm_info object from this, and check the ->uservisible property; or use
1441   * the \core_availability\info_module::is_user_visible() static function.
1442   *
1443   * @global object
1444  
1445   * @param $moduletype Name of the module eg 'forum'
1446   * @param $module Object which is the instance of the module
1447   * @return bool Success
1448   */
1449  function instance_is_visible($moduletype, $module) {
1450      global $DB;
1451  
1452      if (!empty($module->id)) {
1453          $params = array('courseid'=>$module->course, 'moduletype'=>$moduletype, 'moduleid'=>$module->id);
1454          if ($records = $DB->get_records_sql("SELECT cm.instance, cm.visible, cm.groupingid, cm.id, cm.course
1455                                                 FROM {course_modules} cm, {modules} m
1456                                                WHERE cm.course = :courseid AND
1457                                                      cm.module = m.id AND
1458                                                      m.name = :moduletype AND
1459                                                      cm.instance = :moduleid", $params)) {
1460  
1461              foreach ($records as $record) { // there should only be one - use the first one
1462                  return $record->visible;
1463              }
1464          }
1465      }
1466      return true;  // visible by default!
1467  }
1468  
1469  
1470  /// LOG FUNCTIONS /////////////////////////////////////////////////////
1471  
1472  /**
1473   * Get instance of log manager.
1474   *
1475   * @param bool $forcereload
1476   * @return \core\log\manager
1477   */
1478  function get_log_manager($forcereload = false) {
1479      /** @var \core\log\manager $singleton */
1480      static $singleton = null;
1481  
1482      if ($forcereload and isset($singleton)) {
1483          $singleton->dispose();
1484          $singleton = null;
1485      }
1486  
1487      if (isset($singleton)) {
1488          return $singleton;
1489      }
1490  
1491      $classname = '\tool_log\log\manager';
1492      if (defined('LOG_MANAGER_CLASS')) {
1493          $classname = LOG_MANAGER_CLASS;
1494      }
1495  
1496      if (!class_exists($classname)) {
1497          if (!empty($classname)) {
1498              debugging("Cannot find log manager class '$classname'.", DEBUG_DEVELOPER);
1499          }
1500          $classname = '\core\log\dummy_manager';
1501      }
1502  
1503      $singleton = new $classname();
1504      return $singleton;
1505  }
1506  
1507  /**
1508   * Add an entry to the config log table.
1509   *
1510   * These are "action" focussed rather than web server hits,
1511   * and provide a way to easily reconstruct changes to Moodle configuration.
1512   *
1513   * @package core
1514   * @category log
1515   * @global moodle_database $DB
1516   * @global stdClass $USER
1517   * @param    string  $name     The name of the configuration change action
1518                                 For example 'filter_active' when activating or deactivating a filter
1519   * @param    string  $oldvalue The config setting's previous value
1520   * @param    string  $value    The config setting's new value
1521   * @param    string  $plugin   Plugin name, for example a filter name when changing filter configuration
1522   * @return void
1523   */
1524  function add_to_config_log($name, $oldvalue, $value, $plugin) {
1525      global $USER, $DB;
1526  
1527      $log = new stdClass();
1528      // Use 0 as user id during install.
1529      $log->userid       = during_initial_install() ? 0 : $USER->id;
1530      $log->timemodified = time();
1531      $log->name         = $name;
1532      $log->oldvalue  = $oldvalue;
1533      $log->value     = $value;
1534      $log->plugin    = $plugin;
1535  
1536      $id = $DB->insert_record('config_log', $log);
1537  
1538      $event = core\event\config_log_created::create(array(
1539              'objectid' => $id,
1540              'userid' => $log->userid,
1541              'context' => \context_system::instance(),
1542              'other' => array(
1543                  'name' => $log->name,
1544                  'oldvalue' => $log->oldvalue,
1545                  'value' => $log->value,
1546                  'plugin' => $log->plugin
1547              )
1548          ));
1549      $event->trigger();
1550  }
1551  
1552  /**
1553   * Store user last access times - called when use enters a course or site
1554   *
1555   * @package core
1556   * @category log
1557   * @global stdClass $USER
1558   * @global stdClass $CFG
1559   * @global moodle_database $DB
1560   * @uses LASTACCESS_UPDATE_SECS
1561   * @uses SITEID
1562   * @param int $courseid  empty courseid means site
1563   * @return void
1564   */
1565  function user_accesstime_log($courseid=0) {
1566      global $USER, $CFG, $DB;
1567  
1568      if (!isloggedin() or \core\session\manager::is_loggedinas()) {
1569          // no access tracking
1570          return;
1571      }
1572  
1573      if (isguestuser()) {
1574          // Do not update guest access times/ips for performance.
1575          return;
1576      }
1577  
1578      if (empty($courseid)) {
1579          $courseid = SITEID;
1580      }
1581  
1582      $timenow = time();
1583  
1584  /// Store site lastaccess time for the current user
1585      if ($timenow - $USER->lastaccess > LASTACCESS_UPDATE_SECS) {
1586      /// Update $USER->lastaccess for next checks
1587          $USER->lastaccess = $timenow;
1588  
1589          $last = new stdClass();
1590          $last->id         = $USER->id;
1591          $last->lastip     = getremoteaddr();
1592          $last->lastaccess = $timenow;
1593  
1594          $DB->update_record_raw('user', $last);
1595      }
1596  
1597      if ($courseid == SITEID) {
1598      ///  no user_lastaccess for frontpage
1599          return;
1600      }
1601  
1602  /// Store course lastaccess times for the current user
1603      if (empty($USER->currentcourseaccess[$courseid]) or ($timenow - $USER->currentcourseaccess[$courseid] > LASTACCESS_UPDATE_SECS)) {
1604  
1605          $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid'=>$USER->id, 'courseid'=>$courseid));
1606  
1607          if ($lastaccess === false) {
1608              // Update course lastaccess for next checks
1609              $USER->currentcourseaccess[$courseid] = $timenow;
1610  
1611              $last = new stdClass();
1612              $last->userid     = $USER->id;
1613              $last->courseid   = $courseid;
1614              $last->timeaccess = $timenow;
1615              try {
1616                  $DB->insert_record_raw('user_lastaccess', $last, false);
1617              } catch (dml_write_exception $e) {
1618                  // During a race condition we can fail to find the data, then it appears.
1619                  // If we still can't find it, rethrow the exception.
1620                  $lastaccess = $DB->get_field('user_lastaccess', 'timeaccess', array('userid' => $USER->id,
1621                                                                                      'courseid' => $courseid));
1622                  if ($lastaccess === false) {
1623                      throw $e;
1624                  }
1625                  // If we did find it, the race condition was true and another thread has inserted the time for us.
1626                  // We can just continue without having to do anything.
1627              }
1628  
1629          } else if ($timenow - $lastaccess <  LASTACCESS_UPDATE_SECS) {
1630              // no need to update now, it was updated recently in concurrent login ;-)
1631  
1632          } else {
1633              // Update course lastaccess for next checks
1634              $USER->currentcourseaccess[$courseid] = $timenow;
1635  
1636              $DB->set_field('user_lastaccess', 'timeaccess', $timenow, array('userid'=>$USER->id, 'courseid'=>$courseid));
1637          }
1638      }
1639  }
1640  
1641  /// GENERAL HELPFUL THINGS  ///////////////////////////////////
1642  
1643  /**
1644   * Dumps a given object's information for debugging purposes
1645   *
1646   * When used in a CLI script, the object's information is written to the standard
1647   * error output stream. When used in a web script, the object is dumped to a
1648   * pre-formatted block with the "notifytiny" CSS class.
1649   *
1650   * @param mixed $object The data to be printed
1651   * @return void output is echo'd
1652   */
1653  function print_object($object) {
1654  
1655      // we may need a lot of memory here
1656      raise_memory_limit(MEMORY_EXTRA);
1657  
1658      if (CLI_SCRIPT) {
1659          fwrite(STDERR, print_r($object, true));
1660          fwrite(STDERR, PHP_EOL);
1661      } else if (AJAX_SCRIPT) {
1662          foreach (explode("\n", print_r($object, true)) as $line) {
1663              error_log($line);
1664          }
1665      } else {
1666          echo html_writer::tag('pre', s(print_r($object, true)), array('class' => 'notifytiny'));
1667      }
1668  }
1669  
1670  /**
1671   * This function is the official hook inside XMLDB stuff to delegate its debug to one
1672   * external function.
1673   *
1674   * Any script can avoid calls to this function by defining XMLDB_SKIP_DEBUG_HOOK before
1675   * using XMLDB classes. Obviously, also, if this function doesn't exist, it isn't invoked ;-)
1676   *
1677   * @uses DEBUG_DEVELOPER
1678   * @param string $message string contains the error message
1679   * @param object $object object XMLDB object that fired the debug
1680   */
1681  function xmldb_debug($message, $object) {
1682  
1683      debugging($message, DEBUG_DEVELOPER);
1684  }
1685  
1686  /**
1687   * @global object
1688   * @uses CONTEXT_COURSECAT
1689   * @return boolean Whether the user can create courses in any category in the system.
1690   */
1691  function user_can_create_courses() {
1692      global $DB;
1693      $catsrs = $DB->get_recordset('course_categories');
1694      foreach ($catsrs as $cat) {
1695          if (has_capability('moodle/course:create', context_coursecat::instance($cat->id))) {
1696              $catsrs->close();
1697              return true;
1698          }
1699      }
1700      $catsrs->close();
1701      return false;
1702  }
1703  
1704  /**
1705   * This method can update the values in mulitple database rows for a colum with
1706   * a unique index, without violating that constraint.
1707   *
1708   * Suppose we have a table with a unique index on (otherid, sortorder), and
1709   * for a particular value of otherid, we want to change all the sort orders.
1710   * You have to do this carefully or you will violate the unique index at some time.
1711   * This method takes care of the details for you.
1712   *
1713   * Note that, it is the responsibility of the caller to make sure that the
1714   * requested rename is legal. For example, if you ask for [1 => 2, 2 => 2]
1715   * then you will get a unique key violation error from the database.
1716   *
1717   * @param string $table The database table to modify.
1718   * @param string $field the field that contains the values we are going to change.
1719   * @param array $newvalues oldvalue => newvalue how to change the values.
1720   *      E.g. [1 => 4, 2 => 1, 3 => 3, 4 => 2].
1721   * @param array $otherconditions array fieldname => requestedvalue extra WHERE clause
1722   *      conditions to restrict which rows are affected. E.g. array('otherid' => 123).
1723   * @param int $unusedvalue (defaults to -1) a value that is never used in $ordercol.
1724   */
1725  function update_field_with_unique_index($table, $field, array $newvalues,
1726          array $otherconditions, $unusedvalue = -1) {
1727      global $DB;
1728      $safechanges = decompose_update_into_safe_changes($newvalues, $unusedvalue);
1729  
1730      $transaction = $DB->start_delegated_transaction();
1731      foreach ($safechanges as $change) {
1732          list($from, $to) = $change;
1733          $otherconditions[$field] = $from;
1734          $DB->set_field($table, $field, $to, $otherconditions);
1735      }
1736      $transaction->allow_commit();
1737  }
1738  
1739  /**
1740   * Helper used by {@link update_field_with_unique_index()}. Given a desired
1741   * set of changes, break them down into single udpates that can be done one at
1742   * a time without breaking any unique index constraints.
1743   *
1744   * Suppose the input is array(1 => 2, 2 => 1) and -1. Then the output will be
1745   * array (array(1, -1), array(2, 1), array(-1, 2)). This function solves this
1746   * problem in the general case, not just for simple swaps. The unit tests give
1747   * more examples.
1748   *
1749   * Note that, it is the responsibility of the caller to make sure that the
1750   * requested rename is legal. For example, if you ask for something impossible
1751   * like array(1 => 2, 2 => 2) then the results are undefined. (You will probably
1752   * get a unique key violation error from the database later.)
1753   *
1754   * @param array $newvalues The desired re-ordering.
1755   *      E.g. array(1 => 4, 2 => 1, 3 => 3, 4 => 2).
1756   * @param int $unusedvalue A value that is not currently used.
1757   * @return array A safe way to perform the re-order. An array of two-element
1758   *      arrays array($from, $to).
1759   *      E.g. array(array(1, -1), array(2, 1), array(4, 2), array(-1, 4)).
1760   */
1761  function decompose_update_into_safe_changes(array $newvalues, $unusedvalue) {
1762      $nontrivialmap = array();
1763      foreach ($newvalues as $from => $to) {
1764          if ($from == $unusedvalue || $to == $unusedvalue) {
1765              throw new \coding_exception('Supposedly unused value ' . $unusedvalue . ' is actually used!');
1766          }
1767          if ($from != $to) {
1768              $nontrivialmap[$from] = $to;
1769          }
1770      }
1771  
1772      if (empty($nontrivialmap)) {
1773          return array();
1774      }
1775  
1776      // First we deal with all renames that are not part of cycles.
1777      // This bit is O(n^2) and it ought to be possible to do better,
1778      // but it does not seem worth the effort.
1779      $safechanges = array();
1780      $nontrivialmapchanged = true;
1781      while ($nontrivialmapchanged) {
1782          $nontrivialmapchanged = false;
1783  
1784          foreach ($nontrivialmap as $from => $to) {
1785              if (array_key_exists($to, $nontrivialmap)) {
1786                  continue; // Cannot currenly do this rename.
1787              }
1788              // Is safe to do this rename now.
1789              $safechanges[] = array($from, $to);
1790              unset($nontrivialmap[$from]);
1791              $nontrivialmapchanged = true;
1792          }
1793      }
1794  
1795      // Are we done?
1796      if (empty($nontrivialmap)) {
1797          return $safechanges;
1798      }
1799  
1800      // Now what is left in $nontrivialmap must be a permutation,
1801      // which must be a combination of disjoint cycles. We need to break them.
1802      while (!empty($nontrivialmap)) {
1803          // Extract the first cycle.
1804          reset($nontrivialmap);
1805          $current = $cyclestart = key($nontrivialmap);
1806          $cycle = array();
1807          do {
1808              $cycle[] = $current;
1809              $next = $nontrivialmap[$current];
1810              unset($nontrivialmap[$current]);
1811              $current = $next;
1812          } while ($current != $cyclestart);
1813  
1814          // Now convert it to a sequence of safe renames by using a temp.
1815          $safechanges[] = array($cyclestart, $unusedvalue);
1816          $cycle[0] = $unusedvalue;
1817          $to = $cyclestart;
1818          while ($from = array_pop($cycle)) {
1819              $safechanges[] = array($from, $to);
1820              $to = $from;
1821          }
1822      }
1823  
1824      return $safechanges;
1825  }
1826  
1827  /**
1828   * Prepare a safe ORDER BY statement from user interactable requests.
1829   *
1830   * This allows safe user specified sorting (ORDER BY), by abstracting the SQL from the value being requested by the user.
1831   * A standard string (and optional direction) can be specified, which will be mapped to a predefined allow list of SQL ordering.
1832   * The mapping can optionally include a 'default', which will be used if the key provided is invalid.
1833   *
1834   * Example usage:
1835   *      -If $orderbymap = [
1836   *              'courseid' => 'c.id',
1837   *              'somecustomvalue'=> 'c.startdate, c.shortname',
1838   *              'default' => 'c.fullname',
1839   *       ]
1840   *      -A value from the map array's keys can be passed in by a user interaction (eg web service) along with an optional direction.
1841   *      -get_safe_orderby($orderbymap, 'courseid', 'DESC') would return: ORDER BY c.id DESC
1842   *      -get_safe_orderby($orderbymap, 'somecustomvalue') would return: ORDER BY c.startdate, c.shortname
1843   *      -get_safe_orderby($orderbymap, 'invalidblah', 'DESC') would return: ORDER BY c.fullname DESC
1844   *      -If no default key was specified in $orderbymap, the invalidblah example above would return empty string.
1845   *
1846   * @param array $orderbymap An array in the format [keystring => sqlstring]. A default fallback can be set with the key 'default'.
1847   * @param string $orderbykey A string to be mapped to a key in $orderbymap.
1848   * @param string $direction Optional ORDER BY direction (ASC/DESC, case insensitive).
1849   * @param bool $useprefix Whether ORDER BY is prefixed to the output (true by default). This should not be modified in most cases.
1850   *                        It is included to enable get_safe_orderby_multiple() to use this function multiple times.
1851   * @return string The ORDER BY statement, or empty string if $orderbykey is invalid and no default is mapped.
1852   */
1853  function get_safe_orderby(array $orderbymap, string $orderbykey, string $direction = '', bool $useprefix = true): string {
1854      $orderby = $useprefix ? ' ORDER BY ' : '';
1855      $output = '';
1856  
1857      // Only include an order direction if ASC/DESC is explicitly specified (case insensitive).
1858      $direction = strtoupper($direction);
1859      if (!in_array($direction, ['ASC', 'DESC'], true)) {
1860          $direction = '';
1861      } else {
1862          $direction = " {$direction}";
1863      }
1864  
1865      // Prepare the statement if the key maps to a defined sort parameter.
1866      if (isset($orderbymap[$orderbykey])) {
1867          $output = "{$orderby}{$orderbymap[$orderbykey]}{$direction}";
1868      } else if (array_key_exists('default', $orderbymap)) {
1869          // Fall back to use the default if one is specified.
1870          $output = "{$orderby}{$orderbymap['default']}{$direction}";
1871      }
1872  
1873      return $output;
1874  }
1875  
1876  /**
1877   * Prepare a safe ORDER BY statement from user interactable requests using multiple values.
1878   *
1879   * This allows safe user specified sorting (ORDER BY) similar to get_safe_orderby(), but supports multiple keys and directions.
1880   * This is useful in cases where combinations of columns are needed and/or each item requires a specified direction (ASC/DESC).
1881   * The mapping can optionally include a 'default', which will be used if the key provided is invalid.
1882   *
1883   * Example usage:
1884   *      -If $orderbymap = [
1885   *              'courseid' => 'c.id',
1886   *              'fullname'=> 'c.fullname',
1887   *              'default' => 'c.startdate',
1888   *          ]
1889   *      -An array of values from the map's keys can be passed in by a user interaction (eg web service), with optional directions.
1890   *      -get_safe_orderby($orderbymap, ['courseid', 'fullname'], ['DESC', 'ASC']) would return: ORDER BY c.id DESC, c.fullname ASC
1891   *      -get_safe_orderby($orderbymap, ['courseid', 'invalidblah'], ['aaa', 'DESC']) would return: ORDER BY c.id, c.startdate DESC
1892   *      -If no default key was specified in $orderbymap, the invalidblah example above would return: ORDER BY c.id
1893   *
1894   * @param array $orderbymap An array in the format [keystring => sqlstring]. A default fallback can be set with the key 'default'.
1895   * @param array $orderbykeys An array of strings to be mapped to keys in $orderbymap.
1896   * @param array $directions Optional array of ORDER BY direction (ASC/DESC, case insensitive).
1897   *                          The array keys should match array keys in $orderbykeys.
1898   * @return string The ORDER BY statement, or empty string if $orderbykeys contains no valid items and no default is mapped.
1899   */
1900  function get_safe_orderby_multiple(array $orderbymap, array $orderbykeys, array $directions = []): string {
1901      $output = '';
1902  
1903      // Check each key for a valid mapping and add to the ORDER BY statement (invalid entries will be empty strings).
1904      foreach ($orderbykeys as $index => $orderbykey) {
1905          $direction = $directions[$index] ?? '';
1906          $safeorderby = get_safe_orderby($orderbymap, $orderbykey, $direction, false);
1907  
1908          if (!empty($safeorderby)) {
1909              $output .= ", {$safeorderby}";
1910          }
1911      }
1912  
1913      // Prefix with ORDER BY if any valid ordering is specified (and remove comma from the start).
1914      if (!empty($output)) {
1915          $output = ' ORDER BY' . ltrim($output, ',');
1916      }
1917  
1918      return $output;
1919  }