Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 3.11.x will end 14 Nov 2022 (12 months plus 6 months extension).
  • Bug fixes for security issues in 3.11.x will end 13 Nov 2023 (18 months plus 12 months extension).
  • PHP version: minimum PHP 7.3.0 Note: minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is supported too.
/lib/ -> moodlelib.php (source)

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

   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   * moodlelib.php - Moodle main library
  19   *
  20   * Main library file of miscellaneous general-purpose Moodle functions.
  21   * Other main libraries:
  22   *  - weblib.php      - functions that produce web output
  23   *  - datalib.php     - functions that access the database
  24   *
  25   * @package    core
  26   * @subpackage lib
  27   * @copyright  1999 onwards Martin Dougiamas  http://dougiamas.com
  28   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  29   */
  30  
  31  defined('MOODLE_INTERNAL') || die();
  32  
  33  // CONSTANTS (Encased in phpdoc proper comments).
  34  
  35  // Date and time constants.
  36  /**
  37   * Time constant - the number of seconds in a year
  38   */
  39  define('YEARSECS', 31536000);
  40  
  41  /**
  42   * Time constant - the number of seconds in a week
  43   */
  44  define('WEEKSECS', 604800);
  45  
  46  /**
  47   * Time constant - the number of seconds in a day
  48   */
  49  define('DAYSECS', 86400);
  50  
  51  /**
  52   * Time constant - the number of seconds in an hour
  53   */
  54  define('HOURSECS', 3600);
  55  
  56  /**
  57   * Time constant - the number of seconds in a minute
  58   */
  59  define('MINSECS', 60);
  60  
  61  /**
  62   * Time constant - the number of minutes in a day
  63   */
  64  define('DAYMINS', 1440);
  65  
  66  /**
  67   * Time constant - the number of minutes in an hour
  68   */
  69  define('HOURMINS', 60);
  70  
  71  // Parameter constants - every call to optional_param(), required_param()
  72  // or clean_param() should have a specified type of parameter.
  73  
  74  /**
  75   * PARAM_ALPHA - contains only English ascii letters [a-zA-Z].
  76   */
  77  define('PARAM_ALPHA',    'alpha');
  78  
  79  /**
  80   * PARAM_ALPHAEXT the same contents as PARAM_ALPHA (English ascii letters [a-zA-Z]) plus the chars in quotes: "_-" allowed
  81   * NOTE: originally this allowed "/" too, please use PARAM_SAFEPATH if "/" needed
  82   */
  83  define('PARAM_ALPHAEXT', 'alphaext');
  84  
  85  /**
  86   * PARAM_ALPHANUM - expected numbers 0-9 and English ascii letters [a-zA-Z] only.
  87   */
  88  define('PARAM_ALPHANUM', 'alphanum');
  89  
  90  /**
  91   * PARAM_ALPHANUMEXT - expected numbers 0-9, letters (English ascii letters [a-zA-Z]) and _- only.
  92   */
  93  define('PARAM_ALPHANUMEXT', 'alphanumext');
  94  
  95  /**
  96   * PARAM_AUTH - actually checks to make sure the string is a valid auth plugin
  97   */
  98  define('PARAM_AUTH',  'auth');
  99  
 100  /**
 101   * PARAM_BASE64 - Base 64 encoded format
 102   */
 103  define('PARAM_BASE64',   'base64');
 104  
 105  /**
 106   * PARAM_BOOL - converts input into 0 or 1, use for switches in forms and urls.
 107   */
 108  define('PARAM_BOOL',     'bool');
 109  
 110  /**
 111   * PARAM_CAPABILITY - A capability name, like 'moodle/role:manage'. Actually
 112   * checked against the list of capabilities in the database.
 113   */
 114  define('PARAM_CAPABILITY',   'capability');
 115  
 116  /**
 117   * PARAM_CLEANHTML - cleans submitted HTML code. Note that you almost never want
 118   * to use this. The normal mode of operation is to use PARAM_RAW when receiving
 119   * the input (required/optional_param or formslib) and then sanitise the HTML
 120   * using format_text on output. This is for the rare cases when you want to
 121   * sanitise the HTML on input. This cleaning may also fix xhtml strictness.
 122   */
 123  define('PARAM_CLEANHTML', 'cleanhtml');
 124  
 125  /**
 126   * PARAM_EMAIL - an email address following the RFC
 127   */
 128  define('PARAM_EMAIL',   'email');
 129  
 130  /**
 131   * PARAM_FILE - safe file name, all dangerous chars are stripped, protects against XSS, SQL injections and directory traversals
 132   */
 133  define('PARAM_FILE',   'file');
 134  
 135  /**
 136   * PARAM_FLOAT - a real/floating point number.
 137   *
 138   * Note that you should not use PARAM_FLOAT for numbers typed in by the user.
 139   * It does not work for languages that use , as a decimal separator.
 140   * Use PARAM_LOCALISEDFLOAT instead.
 141   */
 142  define('PARAM_FLOAT',  'float');
 143  
 144  /**
 145   * PARAM_LOCALISEDFLOAT - a localised real/floating point number.
 146   * This is preferred over PARAM_FLOAT for numbers typed in by the user.
 147   * Cleans localised numbers to computer readable numbers; false for invalid numbers.
 148   */
 149  define('PARAM_LOCALISEDFLOAT',  'localisedfloat');
 150  
 151  /**
 152   * PARAM_HOST - expected fully qualified domain name (FQDN) or an IPv4 dotted quad (IP address)
 153   */
 154  define('PARAM_HOST',     'host');
 155  
 156  /**
 157   * PARAM_INT - integers only, use when expecting only numbers.
 158   */
 159  define('PARAM_INT',      'int');
 160  
 161  /**
 162   * PARAM_LANG - checks to see if the string is a valid installed language in the current site.
 163   */
 164  define('PARAM_LANG',  'lang');
 165  
 166  /**
 167   * PARAM_LOCALURL - expected properly formatted URL as well as one that refers to the local server itself. (NOT orthogonal to the
 168   * others! Implies PARAM_URL!)
 169   */
 170  define('PARAM_LOCALURL', 'localurl');
 171  
 172  /**
 173   * PARAM_NOTAGS - all html tags are stripped from the text. Do not abuse this type.
 174   */
 175  define('PARAM_NOTAGS',   'notags');
 176  
 177  /**
 178   * PARAM_PATH - safe relative path name, all dangerous chars are stripped, protects against XSS, SQL injections and directory
 179   * traversals note: the leading slash is not removed, window drive letter is not allowed
 180   */
 181  define('PARAM_PATH',     'path');
 182  
 183  /**
 184   * PARAM_PEM - Privacy Enhanced Mail format
 185   */
 186  define('PARAM_PEM',      'pem');
 187  
 188  /**
 189   * PARAM_PERMISSION - A permission, one of CAP_INHERIT, CAP_ALLOW, CAP_PREVENT or CAP_PROHIBIT.
 190   */
 191  define('PARAM_PERMISSION',   'permission');
 192  
 193  /**
 194   * PARAM_RAW specifies a parameter that is not cleaned/processed in any way except the discarding of the invalid utf-8 characters
 195   */
 196  define('PARAM_RAW', 'raw');
 197  
 198  /**
 199   * PARAM_RAW_TRIMMED like PARAM_RAW but leading and trailing whitespace is stripped.
 200   */
 201  define('PARAM_RAW_TRIMMED', 'raw_trimmed');
 202  
 203  /**
 204   * PARAM_SAFEDIR - safe directory name, suitable for include() and require()
 205   */
 206  define('PARAM_SAFEDIR',  'safedir');
 207  
 208  /**
 209   * PARAM_SAFEPATH - several PARAM_SAFEDIR joined by "/", suitable for include() and require(), plugin paths
 210   * and other references to Moodle code files.
 211   *
 212   * This is NOT intended to be used for absolute paths or any user uploaded files.
 213   */
 214  define('PARAM_SAFEPATH',  'safepath');
 215  
 216  /**
 217   * PARAM_SEQUENCE - expects a sequence of numbers like 8 to 1,5,6,4,6,8,9.  Numbers and comma only.
 218   */
 219  define('PARAM_SEQUENCE',  'sequence');
 220  
 221  /**
 222   * PARAM_TAG - one tag (interests, blogs, etc.) - mostly international characters and space, <> not supported
 223   */
 224  define('PARAM_TAG',   'tag');
 225  
 226  /**
 227   * PARAM_TAGLIST - list of tags separated by commas (interests, blogs, etc.)
 228   */
 229  define('PARAM_TAGLIST',   'taglist');
 230  
 231  /**
 232   * PARAM_TEXT - general plain text compatible with multilang filter, no other html tags. Please note '<', or '>' are allowed here.
 233   */
 234  define('PARAM_TEXT',  'text');
 235  
 236  /**
 237   * PARAM_THEME - Checks to see if the string is a valid theme name in the current site
 238   */
 239  define('PARAM_THEME',  'theme');
 240  
 241  /**
 242   * PARAM_URL - expected properly formatted URL. Please note that domain part is required, http://localhost/ is not accepted but
 243   * http://localhost.localdomain/ is ok.
 244   */
 245  define('PARAM_URL',      'url');
 246  
 247  /**
 248   * PARAM_USERNAME - Clean username to only contains allowed characters. This is to be used ONLY when manually creating user
 249   * accounts, do NOT use when syncing with external systems!!
 250   */
 251  define('PARAM_USERNAME',    'username');
 252  
 253  /**
 254   * PARAM_STRINGID - used to check if the given string is valid string identifier for get_string()
 255   */
 256  define('PARAM_STRINGID',    'stringid');
 257  
 258  // DEPRECATED PARAM TYPES OR ALIASES - DO NOT USE FOR NEW CODE.
 259  /**
 260   * PARAM_CLEAN - obsoleted, please use a more specific type of parameter.
 261   * It was one of the first types, that is why it is abused so much ;-)
 262   * @deprecated since 2.0
 263   */
 264  define('PARAM_CLEAN',    'clean');
 265  
 266  /**
 267   * PARAM_INTEGER - deprecated alias for PARAM_INT
 268   * @deprecated since 2.0
 269   */
 270  define('PARAM_INTEGER',  'int');
 271  
 272  /**
 273   * PARAM_NUMBER - deprecated alias of PARAM_FLOAT
 274   * @deprecated since 2.0
 275   */
 276  define('PARAM_NUMBER',  'float');
 277  
 278  /**
 279   * PARAM_ACTION - deprecated alias for PARAM_ALPHANUMEXT, use for various actions in forms and urls
 280   * NOTE: originally alias for PARAM_APLHA
 281   * @deprecated since 2.0
 282   */
 283  define('PARAM_ACTION',   'alphanumext');
 284  
 285  /**
 286   * PARAM_FORMAT - deprecated alias for PARAM_ALPHANUMEXT, use for names of plugins, formats, etc.
 287   * NOTE: originally alias for PARAM_APLHA
 288   * @deprecated since 2.0
 289   */
 290  define('PARAM_FORMAT',   'alphanumext');
 291  
 292  /**
 293   * PARAM_MULTILANG - deprecated alias of PARAM_TEXT.
 294   * @deprecated since 2.0
 295   */
 296  define('PARAM_MULTILANG',  'text');
 297  
 298  /**
 299   * PARAM_TIMEZONE - expected timezone. Timezone can be int +-(0-13) or float +-(0.5-12.5) or
 300   * string separated by '/' and can have '-' &/ '_' (eg. America/North_Dakota/New_Salem
 301   * America/Port-au-Prince)
 302   */
 303  define('PARAM_TIMEZONE', 'timezone');
 304  
 305  /**
 306   * PARAM_CLEANFILE - deprecated alias of PARAM_FILE; originally was removing regional chars too
 307   */
 308  define('PARAM_CLEANFILE', 'file');
 309  
 310  /**
 311   * PARAM_COMPONENT is used for full component names (aka frankenstyle) such as 'mod_forum', 'core_rating', 'auth_ldap'.
 312   * Short legacy subsystem names and module names are accepted too ex: 'forum', 'rating', 'user'.
 313   * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
 314   * NOTE: numbers and underscores are strongly discouraged in plugin names!
 315   */
 316  define('PARAM_COMPONENT', 'component');
 317  
 318  /**
 319   * PARAM_AREA is a name of area used when addressing files, comments, ratings, etc.
 320   * It is usually used together with context id and component.
 321   * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
 322   */
 323  define('PARAM_AREA', 'area');
 324  
 325  /**
 326   * PARAM_PLUGIN is used for plugin names such as 'forum', 'glossary', 'ldap', 'paypal', 'completionstatus'.
 327   * Only lowercase ascii letters, numbers and underscores are allowed, it has to start with a letter.
 328   * NOTE: numbers and underscores are strongly discouraged in plugin names! Underscores are forbidden in module names.
 329   */
 330  define('PARAM_PLUGIN', 'plugin');
 331  
 332  
 333  // Web Services.
 334  
 335  /**
 336   * VALUE_REQUIRED - if the parameter is not supplied, there is an error
 337   */
 338  define('VALUE_REQUIRED', 1);
 339  
 340  /**
 341   * VALUE_OPTIONAL - if the parameter is not supplied, then the param has no value
 342   */
 343  define('VALUE_OPTIONAL', 2);
 344  
 345  /**
 346   * VALUE_DEFAULT - if the parameter is not supplied, then the default value is used
 347   */
 348  define('VALUE_DEFAULT', 0);
 349  
 350  /**
 351   * NULL_NOT_ALLOWED - the parameter can not be set to null in the database
 352   */
 353  define('NULL_NOT_ALLOWED', false);
 354  
 355  /**
 356   * NULL_ALLOWED - the parameter can be set to null in the database
 357   */
 358  define('NULL_ALLOWED', true);
 359  
 360  // Page types.
 361  
 362  /**
 363   * PAGE_COURSE_VIEW is a definition of a page type. For more information on the page class see moodle/lib/pagelib.php.
 364   */
 365  define('PAGE_COURSE_VIEW', 'course-view');
 366  
 367  /** Get remote addr constant */
 368  define('GETREMOTEADDR_SKIP_HTTP_CLIENT_IP', '1');
 369  /** Get remote addr constant */
 370  define('GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR', '2');
 371  /**
 372   * GETREMOTEADDR_SKIP_DEFAULT defines the default behavior remote IP address validation.
 373   */
 374  define('GETREMOTEADDR_SKIP_DEFAULT', GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR|GETREMOTEADDR_SKIP_HTTP_CLIENT_IP);
 375  
 376  // Blog access level constant declaration.
 377  define ('BLOG_USER_LEVEL', 1);
 378  define ('BLOG_GROUP_LEVEL', 2);
 379  define ('BLOG_COURSE_LEVEL', 3);
 380  define ('BLOG_SITE_LEVEL', 4);
 381  define ('BLOG_GLOBAL_LEVEL', 5);
 382  
 383  
 384  // Tag constants.
 385  /**
 386   * To prevent problems with multibytes strings,Flag updating in nav not working on the review page. this should not exceed the
 387   * length of "varchar(255) / 3 (bytes / utf-8 character) = 85".
 388   * TODO: this is not correct, varchar(255) are 255 unicode chars ;-)
 389   *
 390   * @todo define(TAG_MAX_LENGTH) this is not correct, varchar(255) are 255 unicode chars ;-)
 391   */
 392  define('TAG_MAX_LENGTH', 50);
 393  
 394  // Password policy constants.
 395  define ('PASSWORD_LOWER', 'abcdefghijklmnopqrstuvwxyz');
 396  define ('PASSWORD_UPPER', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ');
 397  define ('PASSWORD_DIGITS', '0123456789');
 398  define ('PASSWORD_NONALPHANUM', '.,;:!?_-+/*@#&$');
 399  
 400  // Feature constants.
 401  // Used for plugin_supports() to report features that are, or are not, supported by a module.
 402  
 403  /** True if module can provide a grade */
 404  define('FEATURE_GRADE_HAS_GRADE', 'grade_has_grade');
 405  /** True if module supports outcomes */
 406  define('FEATURE_GRADE_OUTCOMES', 'outcomes');
 407  /** True if module supports advanced grading methods */
 408  define('FEATURE_ADVANCED_GRADING', 'grade_advanced_grading');
 409  /** True if module controls the grade visibility over the gradebook */
 410  define('FEATURE_CONTROLS_GRADE_VISIBILITY', 'controlsgradevisbility');
 411  /** True if module supports plagiarism plugins */
 412  define('FEATURE_PLAGIARISM', 'plagiarism');
 413  
 414  /** True if module has code to track whether somebody viewed it */
 415  define('FEATURE_COMPLETION_TRACKS_VIEWS', 'completion_tracks_views');
 416  /** True if module has custom completion rules */
 417  define('FEATURE_COMPLETION_HAS_RULES', 'completion_has_rules');
 418  
 419  /** True if module has no 'view' page (like label) */
 420  define('FEATURE_NO_VIEW_LINK', 'viewlink');
 421  /** True (which is default) if the module wants support for setting the ID number for grade calculation purposes. */
 422  define('FEATURE_IDNUMBER', 'idnumber');
 423  /** True if module supports groups */
 424  define('FEATURE_GROUPS', 'groups');
 425  /** True if module supports groupings */
 426  define('FEATURE_GROUPINGS', 'groupings');
 427  /**
 428   * True if module supports groupmembersonly (which no longer exists)
 429   * @deprecated Since Moodle 2.8
 430   */
 431  define('FEATURE_GROUPMEMBERSONLY', 'groupmembersonly');
 432  
 433  /** Type of module */
 434  define('FEATURE_MOD_ARCHETYPE', 'mod_archetype');
 435  /** True if module supports intro editor */
 436  define('FEATURE_MOD_INTRO', 'mod_intro');
 437  /** True if module has default completion */
 438  define('FEATURE_MODEDIT_DEFAULT_COMPLETION', 'modedit_default_completion');
 439  
 440  define('FEATURE_COMMENT', 'comment');
 441  
 442  define('FEATURE_RATE', 'rate');
 443  /** True if module supports backup/restore of moodle2 format */
 444  define('FEATURE_BACKUP_MOODLE2', 'backup_moodle2');
 445  
 446  /** True if module can show description on course main page */
 447  define('FEATURE_SHOW_DESCRIPTION', 'showdescription');
 448  
 449  /** True if module uses the question bank */
 450  define('FEATURE_USES_QUESTIONS', 'usesquestions');
 451  
 452  /**
 453   * Maximum filename char size
 454   */
 455  define('MAX_FILENAME_SIZE', 100);
 456  
 457  /** Unspecified module archetype */
 458  define('MOD_ARCHETYPE_OTHER', 0);
 459  /** Resource-like type module */
 460  define('MOD_ARCHETYPE_RESOURCE', 1);
 461  /** Assignment module archetype */
 462  define('MOD_ARCHETYPE_ASSIGNMENT', 2);
 463  /** System (not user-addable) module archetype */
 464  define('MOD_ARCHETYPE_SYSTEM', 3);
 465  
 466  /**
 467   * Security token used for allowing access
 468   * from external application such as web services.
 469   * Scripts do not use any session, performance is relatively
 470   * low because we need to load access info in each request.
 471   * Scripts are executed in parallel.
 472   */
 473  define('EXTERNAL_TOKEN_PERMANENT', 0);
 474  
 475  /**
 476   * Security token used for allowing access
 477   * of embedded applications, the code is executed in the
 478   * active user session. Token is invalidated after user logs out.
 479   * Scripts are executed serially - normal session locking is used.
 480   */
 481  define('EXTERNAL_TOKEN_EMBEDDED', 1);
 482  
 483  /**
 484   * The home page should be the site home
 485   */
 486  define('HOMEPAGE_SITE', 0);
 487  /**
 488   * The home page should be the users my page
 489   */
 490  define('HOMEPAGE_MY', 1);
 491  /**
 492   * The home page can be chosen by the user
 493   */
 494  define('HOMEPAGE_USER', 2);
 495  
 496  /**
 497   * URL of the Moodle sites registration portal.
 498   */
 499  defined('HUB_MOODLEORGHUBURL') || define('HUB_MOODLEORGHUBURL', 'https://stats.moodle.org');
 500  
 501  /**
 502   * URL of the statistic server public key.
 503   */
 504  defined('HUB_STATSPUBLICKEY') || define('HUB_STATSPUBLICKEY', 'https://moodle.org/static/statspubkey.pem');
 505  
 506  /**
 507   * Moodle mobile app service name
 508   */
 509  define('MOODLE_OFFICIAL_MOBILE_SERVICE', 'moodle_mobile_app');
 510  
 511  /**
 512   * Indicates the user has the capabilities required to ignore activity and course file size restrictions
 513   */
 514  define('USER_CAN_IGNORE_FILE_SIZE_LIMITS', -1);
 515  
 516  /**
 517   * Course display settings: display all sections on one page.
 518   */
 519  define('COURSE_DISPLAY_SINGLEPAGE', 0);
 520  /**
 521   * Course display settings: split pages into a page per section.
 522   */
 523  define('COURSE_DISPLAY_MULTIPAGE', 1);
 524  
 525  /**
 526   * Authentication constant: String used in password field when password is not stored.
 527   */
 528  define('AUTH_PASSWORD_NOT_CACHED', 'not cached');
 529  
 530  /**
 531   * Email from header to never include via information.
 532   */
 533  define('EMAIL_VIA_NEVER', 0);
 534  
 535  /**
 536   * Email from header to always include via information.
 537   */
 538  define('EMAIL_VIA_ALWAYS', 1);
 539  
 540  /**
 541   * Email from header to only include via information if the address is no-reply.
 542   */
 543  define('EMAIL_VIA_NO_REPLY_ONLY', 2);
 544  
 545  // PARAMETER HANDLING.
 546  
 547  /**
 548   * Returns a particular value for the named variable, taken from
 549   * POST or GET.  If the parameter doesn't exist then an error is
 550   * thrown because we require this variable.
 551   *
 552   * This function should be used to initialise all required values
 553   * in a script that are based on parameters.  Usually it will be
 554   * used like this:
 555   *    $id = required_param('id', PARAM_INT);
 556   *
 557   * Please note the $type parameter is now required and the value can not be array.
 558   *
 559   * @param string $parname the name of the page parameter we want
 560   * @param string $type expected type of parameter
 561   * @return mixed
 562   * @throws coding_exception
 563   */
 564  function required_param($parname, $type) {
 565      if (func_num_args() != 2 or empty($parname) or empty($type)) {
 566          throw new coding_exception('required_param() requires $parname and $type to be specified (parameter: '.$parname.')');
 567      }
 568      // POST has precedence.
 569      if (isset($_POST[$parname])) {
 570          $param = $_POST[$parname];
 571      } else if (isset($_GET[$parname])) {
 572          $param = $_GET[$parname];
 573      } else {
 574          print_error('missingparam', '', '', $parname);
 575      }
 576  
 577      if (is_array($param)) {
 578          debugging('Invalid array parameter detected in required_param(): '.$parname);
 579          // TODO: switch to fatal error in Moodle 2.3.
 580          return required_param_array($parname, $type);
 581      }
 582  
 583      return clean_param($param, $type);
 584  }
 585  
 586  /**
 587   * Returns a particular array value for the named variable, taken from
 588   * POST or GET.  If the parameter doesn't exist then an error is
 589   * thrown because we require this variable.
 590   *
 591   * This function should be used to initialise all required values
 592   * in a script that are based on parameters.  Usually it will be
 593   * used like this:
 594   *    $ids = required_param_array('ids', PARAM_INT);
 595   *
 596   *  Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
 597   *
 598   * @param string $parname the name of the page parameter we want
 599   * @param string $type expected type of parameter
 600   * @return array
 601   * @throws coding_exception
 602   */
 603  function required_param_array($parname, $type) {
 604      if (func_num_args() != 2 or empty($parname) or empty($type)) {
 605          throw new coding_exception('required_param_array() requires $parname and $type to be specified (parameter: '.$parname.')');
 606      }
 607      // POST has precedence.
 608      if (isset($_POST[$parname])) {
 609          $param = $_POST[$parname];
 610      } else if (isset($_GET[$parname])) {
 611          $param = $_GET[$parname];
 612      } else {
 613          print_error('missingparam', '', '', $parname);
 614      }
 615      if (!is_array($param)) {
 616          print_error('missingparam', '', '', $parname);
 617      }
 618  
 619      $result = array();
 620      foreach ($param as $key => $value) {
 621          if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
 622              debugging('Invalid key name in required_param_array() detected: '.$key.', parameter: '.$parname);
 623              continue;
 624          }
 625          $result[$key] = clean_param($value, $type);
 626      }
 627  
 628      return $result;
 629  }
 630  
 631  /**
 632   * Returns a particular value for the named variable, taken from
 633   * POST or GET, otherwise returning a given default.
 634   *
 635   * This function should be used to initialise all optional values
 636   * in a script that are based on parameters.  Usually it will be
 637   * used like this:
 638   *    $name = optional_param('name', 'Fred', PARAM_TEXT);
 639   *
 640   * Please note the $type parameter is now required and the value can not be array.
 641   *
 642   * @param string $parname the name of the page parameter we want
 643   * @param mixed  $default the default value to return if nothing is found
 644   * @param string $type expected type of parameter
 645   * @return mixed
 646   * @throws coding_exception
 647   */
 648  function optional_param($parname, $default, $type) {
 649      if (func_num_args() != 3 or empty($parname) or empty($type)) {
 650          throw new coding_exception('optional_param requires $parname, $default + $type to be specified (parameter: '.$parname.')');
 651      }
 652  
 653      // POST has precedence.
 654      if (isset($_POST[$parname])) {
 655          $param = $_POST[$parname];
 656      } else if (isset($_GET[$parname])) {
 657          $param = $_GET[$parname];
 658      } else {
 659          return $default;
 660      }
 661  
 662      if (is_array($param)) {
 663          debugging('Invalid array parameter detected in required_param(): '.$parname);
 664          // TODO: switch to $default in Moodle 2.3.
 665          return optional_param_array($parname, $default, $type);
 666      }
 667  
 668      return clean_param($param, $type);
 669  }
 670  
 671  /**
 672   * Returns a particular array value for the named variable, taken from
 673   * POST or GET, otherwise returning a given default.
 674   *
 675   * This function should be used to initialise all optional values
 676   * in a script that are based on parameters.  Usually it will be
 677   * used like this:
 678   *    $ids = optional_param('id', array(), PARAM_INT);
 679   *
 680   * Note: arrays of arrays are not supported, only alphanumeric keys with _ and - are supported
 681   *
 682   * @param string $parname the name of the page parameter we want
 683   * @param mixed $default the default value to return if nothing is found
 684   * @param string $type expected type of parameter
 685   * @return array
 686   * @throws coding_exception
 687   */
 688  function optional_param_array($parname, $default, $type) {
 689      if (func_num_args() != 3 or empty($parname) or empty($type)) {
 690          throw new coding_exception('optional_param_array requires $parname, $default + $type to be specified (parameter: '.$parname.')');
 691      }
 692  
 693      // POST has precedence.
 694      if (isset($_POST[$parname])) {
 695          $param = $_POST[$parname];
 696      } else if (isset($_GET[$parname])) {
 697          $param = $_GET[$parname];
 698      } else {
 699          return $default;
 700      }
 701      if (!is_array($param)) {
 702          debugging('optional_param_array() expects array parameters only: '.$parname);
 703          return $default;
 704      }
 705  
 706      $result = array();
 707      foreach ($param as $key => $value) {
 708          if (!preg_match('/^[a-z0-9_-]+$/i', $key)) {
 709              debugging('Invalid key name in optional_param_array() detected: '.$key.', parameter: '.$parname);
 710              continue;
 711          }
 712          $result[$key] = clean_param($value, $type);
 713      }
 714  
 715      return $result;
 716  }
 717  
 718  /**
 719   * Strict validation of parameter values, the values are only converted
 720   * to requested PHP type. Internally it is using clean_param, the values
 721   * before and after cleaning must be equal - otherwise
 722   * an invalid_parameter_exception is thrown.
 723   * Objects and classes are not accepted.
 724   *
 725   * @param mixed $param
 726   * @param string $type PARAM_ constant
 727   * @param bool $allownull are nulls valid value?
 728   * @param string $debuginfo optional debug information
 729   * @return mixed the $param value converted to PHP type
 730   * @throws invalid_parameter_exception if $param is not of given type
 731   */
 732  function validate_param($param, $type, $allownull=NULL_NOT_ALLOWED, $debuginfo='') {
 733      if (is_null($param)) {
 734          if ($allownull == NULL_ALLOWED) {
 735              return null;
 736          } else {
 737              throw new invalid_parameter_exception($debuginfo);
 738          }
 739      }
 740      if (is_array($param) or is_object($param)) {
 741          throw new invalid_parameter_exception($debuginfo);
 742      }
 743  
 744      $cleaned = clean_param($param, $type);
 745  
 746      if ($type == PARAM_FLOAT) {
 747          // Do not detect precision loss here.
 748          if (is_float($param) or is_int($param)) {
 749              // These always fit.
 750          } else if (!is_numeric($param) or !preg_match('/^[\+-]?[0-9]*\.?[0-9]*(e[-+]?[0-9]+)?$/i', (string)$param)) {
 751              throw new invalid_parameter_exception($debuginfo);
 752          }
 753      } else if ((string)$param !== (string)$cleaned) {
 754          // Conversion to string is usually lossless.
 755          throw new invalid_parameter_exception($debuginfo);
 756      }
 757  
 758      return $cleaned;
 759  }
 760  
 761  /**
 762   * Makes sure array contains only the allowed types, this function does not validate array key names!
 763   *
 764   * <code>
 765   * $options = clean_param($options, PARAM_INT);
 766   * </code>
 767   *
 768   * @param array|null $param the variable array we are cleaning
 769   * @param string $type expected format of param after cleaning.
 770   * @param bool $recursive clean recursive arrays
 771   * @return array
 772   * @throws coding_exception
 773   */
 774  function clean_param_array(?array $param, $type, $recursive = false) {
 775      // Convert null to empty array.
 776      $param = (array)$param;
 777      foreach ($param as $key => $value) {
 778          if (is_array($value)) {
 779              if ($recursive) {
 780                  $param[$key] = clean_param_array($value, $type, true);
 781              } else {
 782                  throw new coding_exception('clean_param_array can not process multidimensional arrays when $recursive is false.');
 783              }
 784          } else {
 785              $param[$key] = clean_param($value, $type);
 786          }
 787      }
 788      return $param;
 789  }
 790  
 791  /**
 792   * Used by {@link optional_param()} and {@link required_param()} to
 793   * clean the variables and/or cast to specific types, based on
 794   * an options field.
 795   * <code>
 796   * $course->format = clean_param($course->format, PARAM_ALPHA);
 797   * $selectedgradeitem = clean_param($selectedgradeitem, PARAM_INT);
 798   * </code>
 799   *
 800   * @param mixed $param the variable we are cleaning
 801   * @param string $type expected format of param after cleaning.
 802   * @return mixed
 803   * @throws coding_exception
 804   */
 805  function clean_param($param, $type) {
 806      global $CFG;
 807  
 808      if (is_array($param)) {
 809          throw new coding_exception('clean_param() can not process arrays, please use clean_param_array() instead.');
 810      } else if (is_object($param)) {
 811          if (method_exists($param, '__toString')) {
 812              $param = $param->__toString();
 813          } else {
 814              throw new coding_exception('clean_param() can not process objects, please use clean_param_array() instead.');
 815          }
 816      }
 817  
 818      switch ($type) {
 819          case PARAM_RAW:
 820              // No cleaning at all.
 821              $param = fix_utf8($param);
 822              return $param;
 823  
 824          case PARAM_RAW_TRIMMED:
 825              // No cleaning, but strip leading and trailing whitespace.
 826              $param = fix_utf8($param);
 827              return trim($param);
 828  
 829          case PARAM_CLEAN:
 830              // General HTML cleaning, try to use more specific type if possible this is deprecated!
 831              // Please use more specific type instead.
 832              if (is_numeric($param)) {
 833                  return $param;
 834              }
 835              $param = fix_utf8($param);
 836              // Sweep for scripts, etc.
 837              return clean_text($param);
 838  
 839          case PARAM_CLEANHTML:
 840              // Clean html fragment.
 841              $param = fix_utf8($param);
 842              // Sweep for scripts, etc.
 843              $param = clean_text($param, FORMAT_HTML);
 844              return trim($param);
 845  
 846          case PARAM_INT:
 847              // Convert to integer.
 848              return (int)$param;
 849  
 850          case PARAM_FLOAT:
 851              // Convert to float.
 852              return (float)$param;
 853  
 854          case PARAM_LOCALISEDFLOAT:
 855              // Convert to float.
 856              return unformat_float($param, true);
 857  
 858          case PARAM_ALPHA:
 859              // Remove everything not `a-z`.
 860              return preg_replace('/[^a-zA-Z]/i', '', $param);
 861  
 862          case PARAM_ALPHAEXT:
 863              // Remove everything not `a-zA-Z_-` (originally allowed "/" too).
 864              return preg_replace('/[^a-zA-Z_-]/i', '', $param);
 865  
 866          case PARAM_ALPHANUM:
 867              // Remove everything not `a-zA-Z0-9`.
 868              return preg_replace('/[^A-Za-z0-9]/i', '', $param);
 869  
 870          case PARAM_ALPHANUMEXT:
 871              // Remove everything not `a-zA-Z0-9_-`.
 872              return preg_replace('/[^A-Za-z0-9_-]/i', '', $param);
 873  
 874          case PARAM_SEQUENCE:
 875              // Remove everything not `0-9,`.
 876              return preg_replace('/[^0-9,]/i', '', $param);
 877  
 878          case PARAM_BOOL:
 879              // Convert to 1 or 0.
 880              $tempstr = strtolower($param);
 881              if ($tempstr === 'on' or $tempstr === 'yes' or $tempstr === 'true') {
 882                  $param = 1;
 883              } else if ($tempstr === 'off' or $tempstr === 'no'  or $tempstr === 'false') {
 884                  $param = 0;
 885              } else {
 886                  $param = empty($param) ? 0 : 1;
 887              }
 888              return $param;
 889  
 890          case PARAM_NOTAGS:
 891              // Strip all tags.
 892              $param = fix_utf8($param);
 893              return strip_tags($param);
 894  
 895          case PARAM_TEXT:
 896              // Leave only tags needed for multilang.
 897              $param = fix_utf8($param);
 898              // If the multilang syntax is not correct we strip all tags because it would break xhtml strict which is required
 899              // for accessibility standards please note this cleaning does not strip unbalanced '>' for BC compatibility reasons.
 900              do {
 901                  if (strpos($param, '</lang>') !== false) {
 902                      // Old and future mutilang syntax.
 903                      $param = strip_tags($param, '<lang>');
 904                      if (!preg_match_all('/<.*>/suU', $param, $matches)) {
 905                          break;
 906                      }
 907                      $open = false;
 908                      foreach ($matches[0] as $match) {
 909                          if ($match === '</lang>') {
 910                              if ($open) {
 911                                  $open = false;
 912                                  continue;
 913                              } else {
 914                                  break 2;
 915                              }
 916                          }
 917                          if (!preg_match('/^<lang lang="[a-zA-Z0-9_-]+"\s*>$/u', $match)) {
 918                              break 2;
 919                          } else {
 920                              $open = true;
 921                          }
 922                      }
 923                      if ($open) {
 924                          break;
 925                      }
 926                      return $param;
 927  
 928                  } else if (strpos($param, '</span>') !== false) {
 929                      // Current problematic multilang syntax.
 930                      $param = strip_tags($param, '<span>');
 931                      if (!preg_match_all('/<.*>/suU', $param, $matches)) {
 932                          break;
 933                      }
 934                      $open = false;
 935                      foreach ($matches[0] as $match) {
 936                          if ($match === '</span>') {
 937                              if ($open) {
 938                                  $open = false;
 939                                  continue;
 940                              } else {
 941                                  break 2;
 942                              }
 943                          }
 944                          if (!preg_match('/^<span(\s+lang="[a-zA-Z0-9_-]+"|\s+class="multilang"){2}\s*>$/u', $match)) {
 945                              break 2;
 946                          } else {
 947                              $open = true;
 948                          }
 949                      }
 950                      if ($open) {
 951                          break;
 952                      }
 953                      return $param;
 954                  }
 955              } while (false);
 956              // Easy, just strip all tags, if we ever want to fix orphaned '&' we have to do that in format_string().
 957              return strip_tags($param);
 958  
 959          case PARAM_COMPONENT:
 960              // We do not want any guessing here, either the name is correct or not
 961              // please note only normalised component names are accepted.
 962              if (!preg_match('/^[a-z][a-z0-9]*(_[a-z][a-z0-9_]*)?[a-z0-9]+$/', $param)) {
 963                  return '';
 964              }
 965              if (strpos($param, '__') !== false) {
 966                  return '';
 967              }
 968              if (strpos($param, 'mod_') === 0) {
 969                  // Module names must not contain underscores because we need to differentiate them from invalid plugin types.
 970                  if (substr_count($param, '_') != 1) {
 971                      return '';
 972                  }
 973              }
 974              return $param;
 975  
 976          case PARAM_PLUGIN:
 977          case PARAM_AREA:
 978              // We do not want any guessing here, either the name is correct or not.
 979              if (!is_valid_plugin_name($param)) {
 980                  return '';
 981              }
 982              return $param;
 983  
 984          case PARAM_SAFEDIR:
 985              // Remove everything not a-zA-Z0-9_- .
 986              return preg_replace('/[^a-zA-Z0-9_-]/i', '', $param);
 987  
 988          case PARAM_SAFEPATH:
 989              // Remove everything not a-zA-Z0-9/_- .
 990              return preg_replace('/[^a-zA-Z0-9\/_-]/i', '', $param);
 991  
 992          case PARAM_FILE:
 993              // Strip all suspicious characters from filename.
 994              $param = fix_utf8($param);
 995              $param = preg_replace('~[[:cntrl:]]|[&<>"`\|\':\\\\/]~u', '', $param);
 996              if ($param === '.' || $param === '..') {
 997                  $param = '';
 998              }
 999              return $param;
1000  
1001          case PARAM_PATH:
1002              // Strip all suspicious characters from file path.
1003              $param = fix_utf8($param);
1004              $param = str_replace('\\', '/', $param);
1005  
1006              // Explode the path and clean each element using the PARAM_FILE rules.
1007              $breadcrumb = explode('/', $param);
1008              foreach ($breadcrumb as $key => $crumb) {
1009                  if ($crumb === '.' && $key === 0) {
1010                      // Special condition to allow for relative current path such as ./currentdirfile.txt.
1011                  } else {
1012                      $crumb = clean_param($crumb, PARAM_FILE);
1013                  }
1014                  $breadcrumb[$key] = $crumb;
1015              }
1016              $param = implode('/', $breadcrumb);
1017  
1018              // Remove multiple current path (./././) and multiple slashes (///).
1019              $param = preg_replace('~//+~', '/', $param);
1020              $param = preg_replace('~/(\./)+~', '/', $param);
1021              return $param;
1022  
1023          case PARAM_HOST:
1024              // Allow FQDN or IPv4 dotted quad.
1025              $param = preg_replace('/[^\.\d\w-]/', '', $param );
1026              // Match ipv4 dotted quad.
1027              if (preg_match('/(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})/', $param, $match)) {
1028                  // Confirm values are ok.
1029                  if ( $match[0] > 255
1030                       || $match[1] > 255
1031                       || $match[3] > 255
1032                       || $match[4] > 255 ) {
1033                      // Hmmm, what kind of dotted quad is this?
1034                      $param = '';
1035                  }
1036              } else if ( preg_match('/^[\w\d\.-]+$/', $param) // Dots, hyphens, numbers.
1037                         && !preg_match('/^[\.-]/',  $param) // No leading dots/hyphens.
1038                         && !preg_match('/[\.-]$/',  $param) // No trailing dots/hyphens.
1039                         ) {
1040                  // All is ok - $param is respected.
1041              } else {
1042                  // All is not ok...
1043                  $param='';
1044              }
1045              return $param;
1046  
1047          case PARAM_URL:
1048              // Allow safe urls.
1049              $param = fix_utf8($param);
1050              include_once($CFG->dirroot . '/lib/validateurlsyntax.php');
1051              if (!empty($param) && validateUrlSyntax($param, 's?H?S?F?E-u-P-a?I?p?f?q?r?')) {
1052                  // All is ok, param is respected.
1053              } else {
1054                  // Not really ok.
1055                  $param ='';
1056              }
1057              return $param;
1058  
1059          case PARAM_LOCALURL:
1060              // Allow http absolute, root relative and relative URLs within wwwroot.
1061              $param = clean_param($param, PARAM_URL);
1062              if (!empty($param)) {
1063  
1064                  if ($param === $CFG->wwwroot) {
1065                      // Exact match;
1066                  } else if (preg_match(':^/:', $param)) {
1067                      // Root-relative, ok!
1068                  } else if (preg_match('/^' . preg_quote($CFG->wwwroot . '/', '/') . '/i', $param)) {
1069                      // Absolute, and matches our wwwroot.
1070                  } else {
1071  
1072                      // Relative - let's make sure there are no tricks.
1073                      if (validateUrlSyntax('/' . $param, 's-u-P-a-p-f+q?r?') && !preg_match('/javascript:/i', $param)) {
1074                          // Looks ok.
1075                      } else {
1076                          $param = '';
1077                      }
1078                  }
1079              }
1080              return $param;
1081  
1082          case PARAM_PEM:
1083              $param = trim($param);
1084              // PEM formatted strings may contain letters/numbers and the symbols:
1085              //   forward slash: /
1086              //   plus sign:     +
1087              //   equal sign:    =
1088              //   , surrounded by BEGIN and END CERTIFICATE prefix and suffixes.
1089              if (preg_match('/^-----BEGIN CERTIFICATE-----([\s\w\/\+=]+)-----END CERTIFICATE-----$/', trim($param), $matches)) {
1090                  list($wholething, $body) = $matches;
1091                  unset($wholething, $matches);
1092                  $b64 = clean_param($body, PARAM_BASE64);
1093                  if (!empty($b64)) {
1094                      return "-----BEGIN CERTIFICATE-----\n$b64\n-----END CERTIFICATE-----\n";
1095                  } else {
1096                      return '';
1097                  }
1098              }
1099              return '';
1100  
1101          case PARAM_BASE64:
1102              if (!empty($param)) {
1103                  // PEM formatted strings may contain letters/numbers and the symbols
1104                  //   forward slash: /
1105                  //   plus sign:     +
1106                  //   equal sign:    =.
1107                  if (0 >= preg_match('/^([\s\w\/\+=]+)$/', trim($param))) {
1108                      return '';
1109                  }
1110                  $lines = preg_split('/[\s]+/', $param, -1, PREG_SPLIT_NO_EMPTY);
1111                  // Each line of base64 encoded data must be 64 characters in length, except for the last line which may be less
1112                  // than (or equal to) 64 characters long.
1113                  for ($i=0, $j=count($lines); $i < $j; $i++) {
1114                      if ($i + 1 == $j) {
1115                          if (64 < strlen($lines[$i])) {
1116                              return '';
1117                          }
1118                          continue;
1119                      }
1120  
1121                      if (64 != strlen($lines[$i])) {
1122                          return '';
1123                      }
1124                  }
1125                  return implode("\n", $lines);
1126              } else {
1127                  return '';
1128              }
1129  
1130          case PARAM_TAG:
1131              $param = fix_utf8($param);
1132              // Please note it is not safe to use the tag name directly anywhere,
1133              // it must be processed with s(), urlencode() before embedding anywhere.
1134              // Remove some nasties.
1135              $param = preg_replace('~[[:cntrl:]]|[<>`]~u', '', $param);
1136              // Convert many whitespace chars into one.
1137              $param = preg_replace('/\s+/u', ' ', $param);
1138              $param = core_text::substr(trim($param), 0, TAG_MAX_LENGTH);
1139              return $param;
1140  
1141          case PARAM_TAGLIST:
1142              $param = fix_utf8($param);
1143              $tags = explode(',', $param);
1144              $result = array();
1145              foreach ($tags as $tag) {
1146                  $res = clean_param($tag, PARAM_TAG);
1147                  if ($res !== '') {
1148                      $result[] = $res;
1149                  }
1150              }
1151              if ($result) {
1152                  return implode(',', $result);
1153              } else {
1154                  return '';
1155              }
1156  
1157          case PARAM_CAPABILITY:
1158              if (get_capability_info($param)) {
1159                  return $param;
1160              } else {
1161                  return '';
1162              }
1163  
1164          case PARAM_PERMISSION:
1165              $param = (int)$param;
1166              if (in_array($param, array(CAP_INHERIT, CAP_ALLOW, CAP_PREVENT, CAP_PROHIBIT))) {
1167                  return $param;
1168              } else {
1169                  return CAP_INHERIT;
1170              }
1171  
1172          case PARAM_AUTH:
1173              $param = clean_param($param, PARAM_PLUGIN);
1174              if (empty($param)) {
1175                  return '';
1176              } else if (exists_auth_plugin($param)) {
1177                  return $param;
1178              } else {
1179                  return '';
1180              }
1181  
1182          case PARAM_LANG:
1183              $param = clean_param($param, PARAM_SAFEDIR);
1184              if (get_string_manager()->translation_exists($param)) {
1185                  return $param;
1186              } else {
1187                  // Specified language is not installed or param malformed.
1188                  return '';
1189              }
1190  
1191          case PARAM_THEME:
1192              $param = clean_param($param, PARAM_PLUGIN);
1193              if (empty($param)) {
1194                  return '';
1195              } else if (file_exists("$CFG->dirroot/theme/$param/config.php")) {
1196                  return $param;
1197              } else if (!empty($CFG->themedir) and file_exists("$CFG->themedir/$param/config.php")) {
1198                  return $param;
1199              } else {
1200                  // Specified theme is not installed.
1201                  return '';
1202              }
1203  
1204          case PARAM_USERNAME:
1205              $param = fix_utf8($param);
1206              $param = trim($param);
1207              // Convert uppercase to lowercase MDL-16919.
1208              $param = core_text::strtolower($param);
1209              if (empty($CFG->extendedusernamechars)) {
1210                  $param = str_replace(" " , "", $param);
1211                  // Regular expression, eliminate all chars EXCEPT:
1212                  // alphanum, dash (-), underscore (_), at sign (@) and period (.) characters.
1213                  $param = preg_replace('/[^-\.@_a-z0-9]/', '', $param);
1214              }
1215              return $param;
1216  
1217          case PARAM_EMAIL:
1218              $param = fix_utf8($param);
1219              if (validate_email($param)) {
1220                  return $param;
1221              } else {
1222                  return '';
1223              }
1224  
1225          case PARAM_STRINGID:
1226              if (preg_match('|^[a-zA-Z][a-zA-Z0-9\.:/_-]*$|', $param)) {
1227                  return $param;
1228              } else {
1229                  return '';
1230              }
1231  
1232          case PARAM_TIMEZONE:
1233              // Can be int, float(with .5 or .0) or string seperated by '/' and can have '-_'.
1234              $param = fix_utf8($param);
1235              $timezonepattern = '/^(([+-]?(0?[0-9](\.[5|0])?|1[0-3](\.0)?|1[0-2]\.5))|(99)|[[:alnum:]]+(\/?[[:alpha:]_-])+)$/';
1236              if (preg_match($timezonepattern, $param)) {
1237                  return $param;
1238              } else {
1239                  return '';
1240              }
1241  
1242          default:
1243              // Doh! throw error, switched parameters in optional_param or another serious problem.
1244              print_error("unknownparamtype", '', '', $type);
1245      }
1246  }
1247  
1248  /**
1249   * Whether the PARAM_* type is compatible in RTL.
1250   *
1251   * Being compatible with RTL means that the data they contain can flow
1252   * from right-to-left or left-to-right without compromising the user experience.
1253   *
1254   * Take URLs for example, they are not RTL compatible as they should always
1255   * flow from the left to the right. This also applies to numbers, email addresses,
1256   * configuration snippets, base64 strings, etc...
1257   *
1258   * This function tries to best guess which parameters can contain localised strings.
1259   *
1260   * @param string $paramtype Constant PARAM_*.
1261   * @return bool
1262   */
1263  function is_rtl_compatible($paramtype) {
1264      return $paramtype == PARAM_TEXT || $paramtype == PARAM_NOTAGS;
1265  }
1266  
1267  /**
1268   * Makes sure the data is using valid utf8, invalid characters are discarded.
1269   *
1270   * Note: this function is not intended for full objects with methods and private properties.
1271   *
1272   * @param mixed $value
1273   * @return mixed with proper utf-8 encoding
1274   */
1275  function fix_utf8($value) {
1276      if (is_null($value) or $value === '') {
1277          return $value;
1278  
1279      } else if (is_string($value)) {
1280          if ((string)(int)$value === $value) {
1281              // Shortcut.
1282              return $value;
1283          }
1284          // No null bytes expected in our data, so let's remove it.
1285          $value = str_replace("\0", '', $value);
1286  
1287          // Note: this duplicates min_fix_utf8() intentionally.
1288          static $buggyiconv = null;
1289          if ($buggyiconv === null) {
1290              $buggyiconv = (!function_exists('iconv') or @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
1291          }
1292  
1293          if ($buggyiconv) {
1294              if (function_exists('mb_convert_encoding')) {
1295                  $subst = mb_substitute_character();
1296                  mb_substitute_character('none');
1297                  $result = mb_convert_encoding($value, 'utf-8', 'utf-8');
1298                  mb_substitute_character($subst);
1299  
1300              } else {
1301                  // Warn admins on admin/index.php page.
1302                  $result = $value;
1303              }
1304  
1305          } else {
1306              $result = @iconv('UTF-8', 'UTF-8//IGNORE', $value);
1307          }
1308  
1309          return $result;
1310  
1311      } else if (is_array($value)) {
1312          foreach ($value as $k => $v) {
1313              $value[$k] = fix_utf8($v);
1314          }
1315          return $value;
1316  
1317      } else if (is_object($value)) {
1318          // Do not modify original.
1319          $value = clone($value);
1320          foreach ($value as $k => $v) {
1321              $value->$k = fix_utf8($v);
1322          }
1323          return $value;
1324  
1325      } else {
1326          // This is some other type, no utf-8 here.
1327          return $value;
1328      }
1329  }
1330  
1331  /**
1332   * Return true if given value is integer or string with integer value
1333   *
1334   * @param mixed $value String or Int
1335   * @return bool true if number, false if not
1336   */
1337  function is_number($value) {
1338      if (is_int($value)) {
1339          return true;
1340      } else if (is_string($value)) {
1341          return ((string)(int)$value) === $value;
1342      } else {
1343          return false;
1344      }
1345  }
1346  
1347  /**
1348   * Returns host part from url.
1349   *
1350   * @param string $url full url
1351   * @return string host, null if not found
1352   */
1353  function get_host_from_url($url) {
1354      preg_match('|^[a-z]+://([a-zA-Z0-9-.]+)|i', $url, $matches);
1355      if ($matches) {
1356          return $matches[1];
1357      }
1358      return null;
1359  }
1360  
1361  /**
1362   * Tests whether anything was returned by text editor
1363   *
1364   * This function is useful for testing whether something you got back from
1365   * the HTML editor actually contains anything. Sometimes the HTML editor
1366   * appear to be empty, but actually you get back a <br> tag or something.
1367   *
1368   * @param string $string a string containing HTML.
1369   * @return boolean does the string contain any actual content - that is text,
1370   * images, objects, etc.
1371   */
1372  function html_is_blank($string) {
1373      return trim(strip_tags($string, '<img><object><applet><input><select><textarea><hr>')) == '';
1374  }
1375  
1376  /**
1377   * Set a key in global configuration
1378   *
1379   * Set a key/value pair in both this session's {@link $CFG} global variable
1380   * and in the 'config' database table for future sessions.
1381   *
1382   * Can also be used to update keys for plugin-scoped configs in config_plugin table.
1383   * In that case it doesn't affect $CFG.
1384   *
1385   * A NULL value will delete the entry.
1386   *
1387   * NOTE: this function is called from lib/db/upgrade.php
1388   *
1389   * @param string $name the key to set
1390   * @param string $value the value to set (without magic quotes)
1391   * @param string $plugin (optional) the plugin scope, default null
1392   * @return bool true or exception
1393   */
1394  function set_config($name, $value, $plugin=null) {
1395      global $CFG, $DB;
1396  
1397      if (empty($plugin)) {
1398          if (!array_key_exists($name, $CFG->config_php_settings)) {
1399              // So it's defined for this invocation at least.
1400              if (is_null($value)) {
1401                  unset($CFG->$name);
1402              } else {
1403                  // Settings from db are always strings.
1404                  $CFG->$name = (string)$value;
1405              }
1406          }
1407  
1408          if ($DB->get_field('config', 'name', array('name' => $name))) {
1409              if ($value === null) {
1410                  $DB->delete_records('config', array('name' => $name));
1411              } else {
1412                  $DB->set_field('config', 'value', $value, array('name' => $name));
1413              }
1414          } else {
1415              if ($value !== null) {
1416                  $config = new stdClass();
1417                  $config->name  = $name;
1418                  $config->value = $value;
1419                  $DB->insert_record('config', $config, false);
1420              }
1421              // When setting config during a Behat test (in the CLI script, not in the web browser
1422              // requests), remember which ones are set so that we can clear them later.
1423              if (defined('BEHAT_TEST')) {
1424                  if (!property_exists($CFG, 'behat_cli_added_config')) {
1425                      $CFG->behat_cli_added_config = [];
1426                  }
1427                  $CFG->behat_cli_added_config[$name] = true;
1428              }
1429          }
1430          if ($name === 'siteidentifier') {
1431              cache_helper::update_site_identifier($value);
1432          }
1433          cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1434      } else {
1435          // Plugin scope.
1436          if ($id = $DB->get_field('config_plugins', 'id', array('name' => $name, 'plugin' => $plugin))) {
1437              if ($value===null) {
1438                  $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1439              } else {
1440                  $DB->set_field('config_plugins', 'value', $value, array('id' => $id));
1441              }
1442          } else {
1443              if ($value !== null) {
1444                  $config = new stdClass();
1445                  $config->plugin = $plugin;
1446                  $config->name   = $name;
1447                  $config->value  = $value;
1448                  $DB->insert_record('config_plugins', $config, false);
1449              }
1450          }
1451          cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1452      }
1453  
1454      return true;
1455  }
1456  
1457  /**
1458   * Get configuration values from the global config table
1459   * or the config_plugins table.
1460   *
1461   * If called with one parameter, it will load all the config
1462   * variables for one plugin, and return them as an object.
1463   *
1464   * If called with 2 parameters it will return a string single
1465   * value or false if the value is not found.
1466   *
1467   * NOTE: this function is called from lib/db/upgrade.php
1468   *
1469   * @static string|false $siteidentifier The site identifier is not cached. We use this static cache so
1470   *     that we need only fetch it once per request.
1471   * @param string $plugin full component name
1472   * @param string $name default null
1473   * @return mixed hash-like object or single value, return false no config found
1474   * @throws dml_exception
1475   */
1476  function get_config($plugin, $name = null) {
1477      global $CFG, $DB;
1478  
1479      static $siteidentifier = null;
1480  
1481      if ($plugin === 'moodle' || $plugin === 'core' || empty($plugin)) {
1482          $forced =& $CFG->config_php_settings;
1483          $iscore = true;
1484          $plugin = 'core';
1485      } else {
1486          if (array_key_exists($plugin, $CFG->forced_plugin_settings)) {
1487              $forced =& $CFG->forced_plugin_settings[$plugin];
1488          } else {
1489              $forced = array();
1490          }
1491          $iscore = false;
1492      }
1493  
1494      if ($siteidentifier === null) {
1495          try {
1496              // This may fail during installation.
1497              // If you have a look at {@link initialise_cfg()} you will see that this is how we detect the need to
1498              // install the database.
1499              $siteidentifier = $DB->get_field('config', 'value', array('name' => 'siteidentifier'));
1500          } catch (dml_exception $ex) {
1501              // Set siteidentifier to false. We don't want to trip this continually.
1502              $siteidentifier = false;
1503              throw $ex;
1504          }
1505      }
1506  
1507      if (!empty($name)) {
1508          if (array_key_exists($name, $forced)) {
1509              return (string)$forced[$name];
1510          } else if ($name === 'siteidentifier' && $plugin == 'core') {
1511              return $siteidentifier;
1512          }
1513      }
1514  
1515      $cache = cache::make('core', 'config');
1516      $result = $cache->get($plugin);
1517      if ($result === false) {
1518          // The user is after a recordset.
1519          if (!$iscore) {
1520              $result = $DB->get_records_menu('config_plugins', array('plugin' => $plugin), '', 'name,value');
1521          } else {
1522              // This part is not really used any more, but anyway...
1523              $result = $DB->get_records_menu('config', array(), '', 'name,value');;
1524          }
1525          $cache->set($plugin, $result);
1526      }
1527  
1528      if (!empty($name)) {
1529          if (array_key_exists($name, $result)) {
1530              return $result[$name];
1531          }
1532          return false;
1533      }
1534  
1535      if ($plugin === 'core') {
1536          $result['siteidentifier'] = $siteidentifier;
1537      }
1538  
1539      foreach ($forced as $key => $value) {
1540          if (is_null($value) or is_array($value) or is_object($value)) {
1541              // We do not want any extra mess here, just real settings that could be saved in db.
1542              unset($result[$key]);
1543          } else {
1544              // Convert to string as if it went through the DB.
1545              $result[$key] = (string)$value;
1546          }
1547      }
1548  
1549      return (object)$result;
1550  }
1551  
1552  /**
1553   * Removes a key from global configuration.
1554   *
1555   * NOTE: this function is called from lib/db/upgrade.php
1556   *
1557   * @param string $name the key to set
1558   * @param string $plugin (optional) the plugin scope
1559   * @return boolean whether the operation succeeded.
1560   */
1561  function unset_config($name, $plugin=null) {
1562      global $CFG, $DB;
1563  
1564      if (empty($plugin)) {
1565          unset($CFG->$name);
1566          $DB->delete_records('config', array('name' => $name));
1567          cache_helper::invalidate_by_definition('core', 'config', array(), 'core');
1568      } else {
1569          $DB->delete_records('config_plugins', array('name' => $name, 'plugin' => $plugin));
1570          cache_helper::invalidate_by_definition('core', 'config', array(), $plugin);
1571      }
1572  
1573      return true;
1574  }
1575  
1576  /**
1577   * Remove all the config variables for a given plugin.
1578   *
1579   * NOTE: this function is called from lib/db/upgrade.php
1580   *
1581   * @param string $plugin a plugin, for example 'quiz' or 'qtype_multichoice';
1582   * @return boolean whether the operation succeeded.
1583   */
1584  function unset_all_config_for_plugin($plugin) {
1585      global $DB;
1586      // Delete from the obvious config_plugins first.
1587      $DB->delete_records('config_plugins', array('plugin' => $plugin));
1588      // Next delete any suspect settings from config.
1589      $like = $DB->sql_like('name', '?', true, true, false, '|');
1590      $params = array($DB->sql_like_escape($plugin.'_', '|') . '%');
1591      $DB->delete_records_select('config', $like, $params);
1592      // Finally clear both the plugin cache and the core cache (suspect settings now removed from core).
1593      cache_helper::invalidate_by_definition('core', 'config', array(), array('core', $plugin));
1594  
1595      return true;
1596  }
1597  
1598  /**
1599   * Use this function to get a list of users from a config setting of type admin_setting_users_with_capability.
1600   *
1601   * All users are verified if they still have the necessary capability.
1602   *
1603   * @param string $value the value of the config setting.
1604   * @param string $capability the capability - must match the one passed to the admin_setting_users_with_capability constructor.
1605   * @param bool $includeadmins include administrators.
1606   * @return array of user objects.
1607   */
1608  function get_users_from_config($value, $capability, $includeadmins = true) {
1609      if (empty($value) or $value === '$@NONE@$') {
1610          return array();
1611      }
1612  
1613      // We have to make sure that users still have the necessary capability,
1614      // it should be faster to fetch them all first and then test if they are present
1615      // instead of validating them one-by-one.
1616      $users = get_users_by_capability(context_system::instance(), $capability);
1617      if ($includeadmins) {
1618          $admins = get_admins();
1619          foreach ($admins as $admin) {
1620              $users[$admin->id] = $admin;
1621          }
1622      }
1623  
1624      if ($value === '$@ALL@$') {
1625          return $users;
1626      }
1627  
1628      $result = array(); // Result in correct order.
1629      $allowed = explode(',', $value);
1630      foreach ($allowed as $uid) {
1631          if (isset($users[$uid])) {
1632              $user = $users[$uid];
1633              $result[$user->id] = $user;
1634          }
1635      }
1636  
1637      return $result;
1638  }
1639  
1640  
1641  /**
1642   * Invalidates browser caches and cached data in temp.
1643   *
1644   * @return void
1645   */
1646  function purge_all_caches() {
1647      purge_caches();
1648  }
1649  
1650  /**
1651   * Selectively invalidate different types of cache.
1652   *
1653   * Purges the cache areas specified.  By default, this will purge all caches but can selectively purge specific
1654   * areas alone or in combination.
1655   *
1656   * @param bool[] $options Specific parts of the cache to purge. Valid options are:
1657   *        'muc'    Purge MUC caches?
1658   *        'theme'  Purge theme cache?
1659   *        'lang'   Purge language string cache?
1660   *        'js'     Purge javascript cache?
1661   *        'filter' Purge text filter cache?
1662   *        'other'  Purge all other caches?
1663   */
1664  function purge_caches($options = []) {
1665      $defaults = array_fill_keys(['muc', 'theme', 'lang', 'js', 'template', 'filter', 'other'], false);
1666      if (empty(array_filter($options))) {
1667          $options = array_fill_keys(array_keys($defaults), true); // Set all options to true.
1668      } else {
1669          $options = array_merge($defaults, array_intersect_key($options, $defaults)); // Override defaults with specified options.
1670      }
1671      if ($options['muc']) {
1672          cache_helper::purge_all();
1673      }
1674      if ($options['theme']) {
1675          theme_reset_all_caches();
1676      }
1677      if ($options['lang']) {
1678          get_string_manager()->reset_caches();
1679      }
1680      if ($options['js']) {
1681          js_reset_all_caches();
1682      }
1683      if ($options['template']) {
1684          template_reset_all_caches();
1685      }
1686      if ($options['filter']) {
1687          reset_text_filters_cache();
1688      }
1689      if ($options['other']) {
1690          purge_other_caches();
1691      }
1692  }
1693  
1694  /**
1695   * Purge all non-MUC caches not otherwise purged in purge_caches.
1696   *
1697   * IMPORTANT - If you are adding anything here to do with the cache directory you should also have a look at
1698   * {@link phpunit_util::reset_dataroot()}
1699   */
1700  function purge_other_caches() {
1701      global $DB, $CFG;
1702      core_text::reset_caches();
1703      if (class_exists('core_plugin_manager')) {
1704          core_plugin_manager::reset_caches();
1705      }
1706  
1707      // Bump up cacherev field for all courses.
1708      try {
1709          increment_revision_number('course', 'cacherev', '');
1710      } catch (moodle_exception $e) {
1711          // Ignore exception since this function is also called before upgrade script when field course.cacherev does not exist yet.
1712      }
1713  
1714      $DB->reset_caches();
1715  
1716      // Purge all other caches: rss, simplepie, etc.
1717      clearstatcache();
1718      remove_dir($CFG->cachedir.'', true);
1719  
1720      // Make sure cache dir is writable, throws exception if not.
1721      make_cache_directory('');
1722  
1723      // This is the only place where we purge local caches, we are only adding files there.
1724      // The $CFG->localcachedirpurged flag forces local directories to be purged on cluster nodes.
1725      remove_dir($CFG->localcachedir, true);
1726      set_config('localcachedirpurged', time());
1727      make_localcache_directory('', true);
1728      \core\task\manager::clear_static_caches();
1729  }
1730  
1731  /**
1732   * Get volatile flags
1733   *
1734   * @param string $type
1735   * @param int $changedsince default null
1736   * @return array records array
1737   */
1738  function get_cache_flags($type, $changedsince = null) {
1739      global $DB;
1740  
1741      $params = array('type' => $type, 'expiry' => time());
1742      $sqlwhere = "flagtype = :type AND expiry >= :expiry";
1743      if ($changedsince !== null) {
1744          $params['changedsince'] = $changedsince;
1745          $sqlwhere .= " AND timemodified > :changedsince";
1746      }
1747      $cf = array();
1748      if ($flags = $DB->get_records_select('cache_flags', $sqlwhere, $params, '', 'name,value')) {
1749          foreach ($flags as $flag) {
1750              $cf[$flag->name] = $flag->value;
1751          }
1752      }
1753      return $cf;
1754  }
1755  
1756  /**
1757   * Get volatile flags
1758   *
1759   * @param string $type
1760   * @param string $name
1761   * @param int $changedsince default null
1762   * @return string|false The cache flag value or false
1763   */
1764  function get_cache_flag($type, $name, $changedsince=null) {
1765      global $DB;
1766  
1767      $params = array('type' => $type, 'name' => $name, 'expiry' => time());
1768  
1769      $sqlwhere = "flagtype = :type AND name = :name AND expiry >= :expiry";
1770      if ($changedsince !== null) {
1771          $params['changedsince'] = $changedsince;
1772          $sqlwhere .= " AND timemodified > :changedsince";
1773      }
1774  
1775      return $DB->get_field_select('cache_flags', 'value', $sqlwhere, $params);
1776  }
1777  
1778  /**
1779   * Set a volatile flag
1780   *
1781   * @param string $type the "type" namespace for the key
1782   * @param string $name the key to set
1783   * @param string $value the value to set (without magic quotes) - null will remove the flag
1784   * @param int $expiry (optional) epoch indicating expiry - defaults to now()+ 24hs
1785   * @return bool Always returns true
1786   */
1787  function set_cache_flag($type, $name, $value, $expiry = null) {
1788      global $DB;
1789  
1790      $timemodified = time();
1791      if ($expiry === null || $expiry < $timemodified) {
1792          $expiry = $timemodified + 24 * 60 * 60;
1793      } else {
1794          $expiry = (int)$expiry;
1795      }
1796  
1797      if ($value === null) {
1798          unset_cache_flag($type, $name);
1799          return true;
1800      }
1801  
1802      if ($f = $DB->get_record('cache_flags', array('name' => $name, 'flagtype' => $type), '*', IGNORE_MULTIPLE)) {
1803          // This is a potential problem in DEBUG_DEVELOPER.
1804          if ($f->value == $value and $f->expiry == $expiry and $f->timemodified == $timemodified) {
1805              return true; // No need to update.
1806          }
1807          $f->value        = $value;
1808          $f->expiry       = $expiry;
1809          $f->timemodified = $timemodified;
1810          $DB->update_record('cache_flags', $f);
1811      } else {
1812          $f = new stdClass();
1813          $f->flagtype     = $type;
1814          $f->name         = $name;
1815          $f->value        = $value;
1816          $f->expiry       = $expiry;
1817          $f->timemodified = $timemodified;
1818          $DB->insert_record('cache_flags', $f);
1819      }
1820      return true;
1821  }
1822  
1823  /**
1824   * Removes a single volatile flag
1825   *
1826   * @param string $type the "type" namespace for the key
1827   * @param string $name the key to set
1828   * @return bool
1829   */
1830  function unset_cache_flag($type, $name) {
1831      global $DB;
1832      $DB->delete_records('cache_flags', array('name' => $name, 'flagtype' => $type));
1833      return true;
1834  }
1835  
1836  /**
1837   * Garbage-collect volatile flags
1838   *
1839   * @return bool Always returns true
1840   */
1841  function gc_cache_flags() {
1842      global $DB;
1843      $DB->delete_records_select('cache_flags', 'expiry < ?', array(time()));
1844      return true;
1845  }
1846  
1847  // USER PREFERENCE API.
1848  
1849  /**
1850   * Refresh user preference cache. This is used most often for $USER
1851   * object that is stored in session, but it also helps with performance in cron script.
1852   *
1853   * Preferences for each user are loaded on first use on every page, then again after the timeout expires.
1854   *
1855   * @package  core
1856   * @category preference
1857   * @access   public
1858   * @param    stdClass         $user          User object. Preferences are preloaded into 'preference' property
1859   * @param    int              $cachelifetime Cache life time on the current page (in seconds)
1860   * @throws   coding_exception
1861   * @return   null
1862   */
1863  function check_user_preferences_loaded(stdClass $user, $cachelifetime = 120) {
1864      global $DB;
1865      // Static cache, we need to check on each page load, not only every 2 minutes.
1866      static $loadedusers = array();
1867  
1868      if (!isset($user->id)) {
1869          throw new coding_exception('Invalid $user parameter in check_user_preferences_loaded() call, missing id field');
1870      }
1871  
1872      if (empty($user->id) or isguestuser($user->id)) {
1873          // No permanent storage for not-logged-in users and guest.
1874          if (!isset($user->preference)) {
1875              $user->preference = array();
1876          }
1877          return;
1878      }
1879  
1880      $timenow = time();
1881  
1882      if (isset($loadedusers[$user->id]) and isset($user->preference) and isset($user->preference['_lastloaded'])) {
1883          // Already loaded at least once on this page. Are we up to date?
1884          if ($user->preference['_lastloaded'] + $cachelifetime > $timenow) {
1885              // No need to reload - we are on the same page and we loaded prefs just a moment ago.
1886              return;
1887  
1888          } else if (!get_cache_flag('userpreferenceschanged', $user->id, $user->preference['_lastloaded'])) {
1889              // No change since the lastcheck on this page.
1890              $user->preference['_lastloaded'] = $timenow;
1891              return;
1892          }
1893      }
1894  
1895      // OK, so we have to reload all preferences.
1896      $loadedusers[$user->id] = true;
1897      $user->preference = $DB->get_records_menu('user_preferences', array('userid' => $user->id), '', 'name,value'); // All values.
1898      $user->preference['_lastloaded'] = $timenow;
1899  }
1900  
1901  /**
1902   * Called from set/unset_user_preferences, so that the prefs can be correctly reloaded in different sessions.
1903   *
1904   * NOTE: internal function, do not call from other code.
1905   *
1906   * @package core
1907   * @access private
1908   * @param integer $userid the user whose prefs were changed.
1909   */
1910  function mark_user_preferences_changed($userid) {
1911      global $CFG;
1912  
1913      if (empty($userid) or isguestuser($userid)) {
1914          // No cache flags for guest and not-logged-in users.
1915          return;
1916      }
1917  
1918      set_cache_flag('userpreferenceschanged', $userid, 1, time() + $CFG->sessiontimeout);
1919  }
1920  
1921  /**
1922   * Sets a preference for the specified user.
1923   *
1924   * If a $user object is submitted it's 'preference' property is used for the preferences cache.
1925   *
1926   * When additional validation/permission check is needed it is better to use {@see useredit_update_user_preference()}
1927   *
1928   * @package  core
1929   * @category preference
1930   * @access   public
1931   * @param    string            $name  The key to set as preference for the specified user
1932   * @param    string            $value The value to set for the $name key in the specified user's
1933   *                                    record, null means delete current value.
1934   * @param    stdClass|int|null $user  A moodle user object or id, null means current user
1935   * @throws   coding_exception
1936   * @return   bool                     Always true or exception
1937   */
1938  function set_user_preference($name, $value, $user = null) {
1939      global $USER, $DB;
1940  
1941      if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
1942          throw new coding_exception('Invalid preference name in set_user_preference() call');
1943      }
1944  
1945      if (is_null($value)) {
1946          // Null means delete current.
1947          return unset_user_preference($name, $user);
1948      } else if (is_object($value)) {
1949          throw new coding_exception('Invalid value in set_user_preference() call, objects are not allowed');
1950      } else if (is_array($value)) {
1951          throw new coding_exception('Invalid value in set_user_preference() call, arrays are not allowed');
1952      }
1953      // Value column maximum length is 1333 characters.
1954      $value = (string)$value;
1955      if (core_text::strlen($value) > 1333) {
1956          throw new coding_exception('Invalid value in set_user_preference() call, value is is too long for the value column');
1957      }
1958  
1959      if (is_null($user)) {
1960          $user = $USER;
1961      } else if (isset($user->id)) {
1962          // It is a valid object.
1963      } else if (is_numeric($user)) {
1964          $user = (object)array('id' => (int)$user);
1965      } else {
1966          throw new coding_exception('Invalid $user parameter in set_user_preference() call');
1967      }
1968  
1969      check_user_preferences_loaded($user);
1970  
1971      if (empty($user->id) or isguestuser($user->id)) {
1972          // No permanent storage for not-logged-in users and guest.
1973          $user->preference[$name] = $value;
1974          return true;
1975      }
1976  
1977      if ($preference = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => $name))) {
1978          if ($preference->value === $value and isset($user->preference[$name]) and $user->preference[$name] === $value) {
1979              // Preference already set to this value.
1980              return true;
1981          }
1982          $DB->set_field('user_preferences', 'value', $value, array('id' => $preference->id));
1983  
1984      } else {
1985          $preference = new stdClass();
1986          $preference->userid = $user->id;
1987          $preference->name   = $name;
1988          $preference->value  = $value;
1989          $DB->insert_record('user_preferences', $preference);
1990      }
1991  
1992      // Update value in cache.
1993      $user->preference[$name] = $value;
1994      // Update the $USER in case where we've not a direct reference to $USER.
1995      if ($user !== $USER && $user->id == $USER->id) {
1996          $USER->preference[$name] = $value;
1997      }
1998  
1999      // Set reload flag for other sessions.
2000      mark_user_preferences_changed($user->id);
2001  
2002      return true;
2003  }
2004  
2005  /**
2006   * Sets a whole array of preferences for the current user
2007   *
2008   * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2009   *
2010   * @package  core
2011   * @category preference
2012   * @access   public
2013   * @param    array             $prefarray An array of key/value pairs to be set
2014   * @param    stdClass|int|null $user      A moodle user object or id, null means current user
2015   * @return   bool                         Always true or exception
2016   */
2017  function set_user_preferences(array $prefarray, $user = null) {
2018      foreach ($prefarray as $name => $value) {
2019          set_user_preference($name, $value, $user);
2020      }
2021      return true;
2022  }
2023  
2024  /**
2025   * Unsets a preference completely by deleting it from the database
2026   *
2027   * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2028   *
2029   * @package  core
2030   * @category preference
2031   * @access   public
2032   * @param    string            $name The key to unset as preference for the specified user
2033   * @param    stdClass|int|null $user A moodle user object or id, null means current user
2034   * @throws   coding_exception
2035   * @return   bool                    Always true or exception
2036   */
2037  function unset_user_preference($name, $user = null) {
2038      global $USER, $DB;
2039  
2040      if (empty($name) or is_numeric($name) or $name === '_lastloaded') {
2041          throw new coding_exception('Invalid preference name in unset_user_preference() call');
2042      }
2043  
2044      if (is_null($user)) {
2045          $user = $USER;
2046      } else if (isset($user->id)) {
2047          // It is a valid object.
2048      } else if (is_numeric($user)) {
2049          $user = (object)array('id' => (int)$user);
2050      } else {
2051          throw new coding_exception('Invalid $user parameter in unset_user_preference() call');
2052      }
2053  
2054      check_user_preferences_loaded($user);
2055  
2056      if (empty($user->id) or isguestuser($user->id)) {
2057          // No permanent storage for not-logged-in user and guest.
2058          unset($user->preference[$name]);
2059          return true;
2060      }
2061  
2062      // Delete from DB.
2063      $DB->delete_records('user_preferences', array('userid' => $user->id, 'name' => $name));
2064  
2065      // Delete the preference from cache.
2066      unset($user->preference[$name]);
2067      // Update the $USER in case where we've not a direct reference to $USER.
2068      if ($user !== $USER && $user->id == $USER->id) {
2069          unset($USER->preference[$name]);
2070      }
2071  
2072      // Set reload flag for other sessions.
2073      mark_user_preferences_changed($user->id);
2074  
2075      return true;
2076  }
2077  
2078  /**
2079   * Used to fetch user preference(s)
2080   *
2081   * If no arguments are supplied this function will return
2082   * all of the current user preferences as an array.
2083   *
2084   * If a name is specified then this function
2085   * attempts to return that particular preference value.  If
2086   * none is found, then the optional value $default is returned,
2087   * otherwise null.
2088   *
2089   * If a $user object is submitted it's 'preference' property is used for the preferences cache.
2090   *
2091   * @package  core
2092   * @category preference
2093   * @access   public
2094   * @param    string            $name    Name of the key to use in finding a preference value
2095   * @param    mixed|null        $default Value to be returned if the $name key is not set in the user preferences
2096   * @param    stdClass|int|null $user    A moodle user object or id, null means current user
2097   * @throws   coding_exception
2098   * @return   string|mixed|null          A string containing the value of a single preference. An
2099   *                                      array with all of the preferences or null
2100   */
2101  function get_user_preferences($name = null, $default = null, $user = null) {
2102      global $USER;
2103  
2104      if (is_null($name)) {
2105          // All prefs.
2106      } else if (is_numeric($name) or $name === '_lastloaded') {
2107          throw new coding_exception('Invalid preference name in get_user_preferences() call');
2108      }
2109  
2110      if (is_null($user)) {
2111          $user = $USER;
2112      } else if (isset($user->id)) {
2113          // Is a valid object.
2114      } else if (is_numeric($user)) {
2115          if ($USER->id == $user) {
2116              $user = $USER;
2117          } else {
2118              $user = (object)array('id' => (int)$user);
2119          }
2120      } else {
2121          throw new coding_exception('Invalid $user parameter in get_user_preferences() call');
2122      }
2123  
2124      check_user_preferences_loaded($user);
2125  
2126      if (empty($name)) {
2127          // All values.
2128          return $user->preference;
2129      } else if (isset($user->preference[$name])) {
2130          // The single string value.
2131          return $user->preference[$name];
2132      } else {
2133          // Default value (null if not specified).
2134          return $default;
2135      }
2136  }
2137  
2138  // FUNCTIONS FOR HANDLING TIME.
2139  
2140  /**
2141   * Given Gregorian date parts in user time produce a GMT timestamp.
2142   *
2143   * @package core
2144   * @category time
2145   * @param int $year The year part to create timestamp of
2146   * @param int $month The month part to create timestamp of
2147   * @param int $day The day part to create timestamp of
2148   * @param int $hour The hour part to create timestamp of
2149   * @param int $minute The minute part to create timestamp of
2150   * @param int $second The second part to create timestamp of
2151   * @param int|float|string $timezone Timezone modifier, used to calculate GMT time offset.
2152   *             if 99 then default user's timezone is used {@link http://docs.moodle.org/dev/Time_API#Timezone}
2153   * @param bool $applydst Toggle Daylight Saving Time, default true, will be
2154   *             applied only if timezone is 99 or string.
2155   * @return int GMT timestamp
2156   */
2157  function make_timestamp($year, $month=1, $day=1, $hour=0, $minute=0, $second=0, $timezone=99, $applydst=true) {
2158      $date = new DateTime('now', core_date::get_user_timezone_object($timezone));
2159      $date->setDate((int)$year, (int)$month, (int)$day);
2160      $date->setTime((int)$hour, (int)$minute, (int)$second);
2161  
2162      $time = $date->getTimestamp();
2163  
2164      if ($time === false) {
2165          throw new coding_exception('getTimestamp() returned false, please ensure you have passed correct values.'.
2166              ' This can fail if year is more than 2038 and OS is 32 bit windows');
2167      }
2168  
2169      // Moodle BC DST stuff.
2170      if (!$applydst) {
2171          $time += dst_offset_on($time, $timezone);
2172      }
2173  
2174      return $time;
2175  
2176  }
2177  
2178  /**
2179   * Format a date/time (seconds) as weeks, days, hours etc as needed
2180   *
2181   * Given an amount of time in seconds, returns string
2182   * formatted nicely as years, days, hours etc as needed
2183   *
2184   * @package core
2185   * @category time
2186   * @uses MINSECS
2187   * @uses HOURSECS
2188   * @uses DAYSECS
2189   * @uses YEARSECS
2190   * @param int $totalsecs Time in seconds
2191   * @param stdClass $str Should be a time object
2192   * @return string A nicely formatted date/time string
2193   */
2194  function format_time($totalsecs, $str = null) {
2195  
2196      $totalsecs = abs($totalsecs);
2197  
2198      if (!$str) {
2199          // Create the str structure the slow way.
2200          $str = new stdClass();
2201          $str->day   = get_string('day');
2202          $str->days  = get_string('days');
2203          $str->hour  = get_string('hour');
2204          $str->hours = get_string('hours');
2205          $str->min   = get_string('min');
2206          $str->mins  = get_string('mins');
2207          $str->sec   = get_string('sec');
2208          $str->secs  = get_string('secs');
2209          $str->year  = get_string('year');
2210          $str->years = get_string('years');
2211      }
2212  
2213      $years     = floor($totalsecs/YEARSECS);
2214      $remainder = $totalsecs - ($years*YEARSECS);
2215      $days      = floor($remainder/DAYSECS);
2216      $remainder = $totalsecs - ($days*DAYSECS);
2217      $hours     = floor($remainder/HOURSECS);
2218      $remainder = $remainder - ($hours*HOURSECS);
2219      $mins      = floor($remainder/MINSECS);
2220      $secs      = $remainder - ($mins*MINSECS);
2221  
2222      $ss = ($secs == 1)  ? $str->sec  : $str->secs;
2223      $sm = ($mins == 1)  ? $str->min  : $str->mins;
2224      $sh = ($hours == 1) ? $str->hour : $str->hours;
2225      $sd = ($days == 1)  ? $str->day  : $str->days;
2226      $sy = ($years == 1)  ? $str->year  : $str->years;
2227  
2228      $oyears = '';
2229      $odays = '';
2230      $ohours = '';
2231      $omins = '';
2232      $osecs = '';
2233  
2234      if ($years) {
2235          $oyears  = $years .' '. $sy;
2236      }
2237      if ($days) {
2238          $odays  = $days .' '. $sd;
2239      }
2240      if ($hours) {
2241          $ohours = $hours .' '. $sh;
2242      }
2243      if ($mins) {
2244          $omins  = $mins .' '. $sm;
2245      }
2246      if ($secs) {
2247          $osecs  = $secs .' '. $ss;
2248      }
2249  
2250      if ($years) {
2251          return trim($oyears .' '. $odays);
2252      }
2253      if ($days) {
2254          return trim($odays .' '. $ohours);
2255      }
2256      if ($hours) {
2257          return trim($ohours .' '. $omins);
2258      }
2259      if ($mins) {
2260          return trim($omins .' '. $osecs);
2261      }
2262      if ($secs) {
2263          return $osecs;
2264      }
2265      return get_string('now');
2266  }
2267  
2268  /**
2269   * Returns a formatted string that represents a date in user time.
2270   *
2271   * @package core
2272   * @category time
2273   * @param int $date the timestamp in UTC, as obtained from the database.
2274   * @param string $format strftime format. You should probably get this using
2275   *        get_string('strftime...', 'langconfig');
2276   * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2277   *        not 99 then daylight saving will not be added.
2278   *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2279   * @param bool $fixday If true (default) then the leading zero from %d is removed.
2280   *        If false then the leading zero is maintained.
2281   * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2282   * @return string the formatted date/time.
2283   */
2284  function userdate($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2285      $calendartype = \core_calendar\type_factory::get_calendar_instance();
2286      return $calendartype->timestamp_to_date_string($date, $format, $timezone, $fixday, $fixhour);
2287  }
2288  
2289  /**
2290   * Returns a html "time" tag with both the exact user date with timezone information
2291   * as a datetime attribute in the W3C format, and the user readable date and time as text.
2292   *
2293   * @package core
2294   * @category time
2295   * @param int $date the timestamp in UTC, as obtained from the database.
2296   * @param string $format strftime format. You should probably get this using
2297   *        get_string('strftime...', 'langconfig');
2298   * @param int|float|string $timezone by default, uses the user's time zone. if numeric and
2299   *        not 99 then daylight saving will not be added.
2300   *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2301   * @param bool $fixday If true (default) then the leading zero from %d is removed.
2302   *        If false then the leading zero is maintained.
2303   * @param bool $fixhour If true (default) then the leading zero from %I is removed.
2304   * @return string the formatted date/time.
2305   */
2306  function userdate_htmltime($date, $format = '', $timezone = 99, $fixday = true, $fixhour = true) {
2307      $userdatestr = userdate($date, $format, $timezone, $fixday, $fixhour);
2308      if (CLI_SCRIPT && !PHPUNIT_TEST) {
2309          return $userdatestr;
2310      }
2311      $machinedate = new DateTime();
2312      $machinedate->setTimestamp(intval($date));
2313      $machinedate->setTimezone(core_date::get_user_timezone_object());
2314  
2315      return html_writer::tag('time', $userdatestr, ['datetime' => $machinedate->format(DateTime::W3C)]);
2316  }
2317  
2318  /**
2319   * Returns a formatted date ensuring it is UTF-8.
2320   *
2321   * If we are running under Windows convert to Windows encoding and then back to UTF-8
2322   * (because it's impossible to specify UTF-8 to fetch locale info in Win32).
2323   *
2324   * @param int $date the timestamp - since Moodle 2.9 this is a real UTC timestamp
2325   * @param string $format strftime format.
2326   * @param int|float|string $tz the user timezone
2327   * @return string the formatted date/time.
2328   * @since Moodle 2.3.3
2329   */
2330  function date_format_string($date, $format, $tz = 99) {
2331      global $CFG;
2332  
2333      $localewincharset = null;
2334      // Get the calendar type user is using.
2335      if ($CFG->ostype == 'WINDOWS') {
2336          $calendartype = \core_calendar\type_factory::get_calendar_instance();
2337          $localewincharset = $calendartype->locale_win_charset();
2338      }
2339  
2340      if ($localewincharset) {
2341          $format = core_text::convert($format, 'utf-8', $localewincharset);
2342      }
2343  
2344      date_default_timezone_set(core_date::get_user_timezone($tz));
2345  
2346      if (strftime('%p', 0) === strftime('%p', HOURSECS * 18)) {
2347          $datearray = getdate($date);
2348          $format = str_replace([
2349              '%P',
2350              '%p',
2351          ], [
2352              $datearray['hours'] < 12 ? get_string('am', 'langconfig') : get_string('pm', 'langconfig'),
2353              $datearray['hours'] < 12 ? get_string('amcaps', 'langconfig') : get_string('pmcaps', 'langconfig'),
2354          ], $format);
2355      }
2356  
2357      $datestring = strftime($format, $date);
2358      core_date::set_default_server_timezone();
2359  
2360      if ($localewincharset) {
2361          $datestring = core_text::convert($datestring, $localewincharset, 'utf-8');
2362      }
2363  
2364      return $datestring;
2365  }
2366  
2367  /**
2368   * Given a $time timestamp in GMT (seconds since epoch),
2369   * returns an array that represents the Gregorian date in user time
2370   *
2371   * @package core
2372   * @category time
2373   * @param int $time Timestamp in GMT
2374   * @param float|int|string $timezone user timezone
2375   * @return array An array that represents the date in user time
2376   */
2377  function usergetdate($time, $timezone=99) {
2378      if ($time === null) {
2379          // PHP8 and PHP7 return different results when getdate(null) is called.
2380          // Display warning and cast to 0 to make sure the usergetdate() behaves consistently on all versions of PHP.
2381          // In the future versions of Moodle we may consider adding a strict typehint.
2382          debugging('usergetdate() expects parameter $time to be int, null given', DEBUG_DEVELOPER);
2383          $time = 0;
2384      }
2385  
2386      date_default_timezone_set(core_date::get_user_timezone($timezone));
2387      $result = getdate($time);
2388      core_date::set_default_server_timezone();
2389  
2390      return $result;
2391  }
2392  
2393  /**
2394   * Given a GMT timestamp (seconds since epoch), offsets it by
2395   * the timezone.  eg 3pm in India is 3pm GMT - 7 * 3600 seconds
2396   *
2397   * NOTE: this function does not include DST properly,
2398   *       you should use the PHP date stuff instead!
2399   *
2400   * @package core
2401   * @category time
2402   * @param int $date Timestamp in GMT
2403   * @param float|int|string $timezone user timezone
2404   * @return int
2405   */
2406  function usertime($date, $timezone=99) {
2407      $userdate = new DateTime('@' . $date);
2408      $userdate->setTimezone(core_date::get_user_timezone_object($timezone));
2409      $dst = dst_offset_on($date, $timezone);
2410  
2411      return $date - $userdate->getOffset() + $dst;
2412  }
2413  
2414  /**
2415   * Get a formatted string representation of an interval between two unix timestamps.
2416   *
2417   * E.g.
2418   * $intervalstring = get_time_interval_string(12345600, 12345660);
2419   * Will produce the string:
2420   * '0d 0h 1m'
2421   *
2422   * @param int $time1 unix timestamp
2423   * @param int $time2 unix timestamp
2424   * @param string $format string (can be lang string) containing format chars: https://www.php.net/manual/en/dateinterval.format.php.
2425   * @return string the formatted string describing the time difference, e.g. '10d 11h 45m'.
2426   */
2427  function get_time_interval_string(int $time1, int $time2, string $format = ''): string {
2428      $dtdate = new DateTime();
2429      $dtdate->setTimeStamp($time1);
2430      $dtdate2 = new DateTime();
2431      $dtdate2->setTimeStamp($time2);
2432      $interval = $dtdate2->diff($dtdate);
2433      $format = empty($format) ? get_string('dateintervaldayshoursmins', 'langconfig') : $format;
2434      return $interval->format($format);
2435  }
2436  
2437  /**
2438   * Given a time, return the GMT timestamp of the most recent midnight
2439   * for the current user.
2440   *
2441   * @package core
2442   * @category time
2443   * @param int $date Timestamp in GMT
2444   * @param float|int|string $timezone user timezone
2445   * @return int Returns a GMT timestamp
2446   */
2447  function usergetmidnight($date, $timezone=99) {
2448  
2449      $userdate = usergetdate($date, $timezone);
2450  
2451      // Time of midnight of this user's day, in GMT.
2452      return make_timestamp($userdate['year'], $userdate['mon'], $userdate['mday'], 0, 0, 0, $timezone);
2453  
2454  }
2455  
2456  /**
2457   * Returns a string that prints the user's timezone
2458   *
2459   * @package core
2460   * @category time
2461   * @param float|int|string $timezone user timezone
2462   * @return string
2463   */
2464  function usertimezone($timezone=99) {
2465      $tz = core_date::get_user_timezone($timezone);
2466      return core_date::get_localised_timezone($tz);
2467  }
2468  
2469  /**
2470   * Returns a float or a string which denotes the user's timezone
2471   * A float value means that a simple offset from GMT is used, while a string (it will be the name of a timezone in the database)
2472   * means that for this timezone there are also DST rules to be taken into account
2473   * Checks various settings and picks the most dominant of those which have a value
2474   *
2475   * @package core
2476   * @category time
2477   * @param float|int|string $tz timezone to calculate GMT time offset before
2478   *        calculating user timezone, 99 is default user timezone
2479   *        {@link http://docs.moodle.org/dev/Time_API#Timezone}
2480   * @return float|string
2481   */
2482  function get_user_timezone($tz = 99) {
2483      global $USER, $CFG;
2484  
2485      $timezones = array(
2486          $tz,
2487          isset($CFG->forcetimezone) ? $CFG->forcetimezone : 99,
2488          isset($USER->timezone) ? $USER->timezone : 99,
2489          isset($CFG->timezone) ? $CFG->timezone : 99,
2490          );
2491  
2492      $tz = 99;
2493  
2494      // Loop while $tz is, empty but not zero, or 99, and there is another timezone is the array.
2495      foreach ($timezones as $nextvalue) {
2496          if ((empty($tz) && !is_numeric($tz)) || $tz == 99) {
2497              $tz = $nextvalue;
2498          }
2499      }
2500      return is_numeric($tz) ? (float) $tz : $tz;
2501  }
2502  
2503  /**
2504   * Calculates the Daylight Saving Offset for a given date/time (timestamp)
2505   * - Note: Daylight saving only works for string timezones and not for float.
2506   *
2507   * @package core
2508   * @category time
2509   * @param int $time must NOT be compensated at all, it has to be a pure timestamp
2510   * @param int|float|string $strtimezone user timezone
2511   * @return int
2512   */
2513  function dst_offset_on($time, $strtimezone = null) {
2514      $tz = core_date::get_user_timezone($strtimezone);
2515      $date = new DateTime('@' . $time);
2516      $date->setTimezone(new DateTimeZone($tz));
2517      if ($date->format('I') == '1') {
2518          if ($tz === 'Australia/Lord_Howe') {
2519              return 1800;
2520          }
2521          return 3600;
2522      }
2523      return 0;
2524  }
2525  
2526  /**
2527   * Calculates when the day appears in specific month
2528   *
2529   * @package core
2530   * @category time
2531   * @param int $startday starting day of the month
2532   * @param int $weekday The day when week starts (normally taken from user preferences)
2533   * @param int $month The month whose day is sought
2534   * @param int $year The year of the month whose day is sought
2535   * @return int
2536   */
2537  function find_day_in_month($startday, $weekday, $month, $year) {
2538      $calendartype = \core_calendar\type_factory::get_calendar_instance();
2539  
2540      $daysinmonth = days_in_month($month, $year);
2541      $daysinweek = count($calendartype->get_weekdays());
2542  
2543      if ($weekday == -1) {
2544          // Don't care about weekday, so return:
2545          //    abs($startday) if $startday != -1
2546          //    $daysinmonth otherwise.
2547          return ($startday == -1) ? $daysinmonth : abs($startday);
2548      }
2549  
2550      // From now on we 're looking for a specific weekday.
2551      // Give "end of month" its actual value, since we know it.
2552      if ($startday == -1) {
2553          $startday = -1 * $daysinmonth;
2554      }
2555  
2556      // Starting from day $startday, the sign is the direction.
2557      if ($startday < 1) {
2558          $startday = abs($startday);
2559          $lastmonthweekday = dayofweek($daysinmonth, $month, $year);
2560  
2561          // This is the last such weekday of the month.
2562          $lastinmonth = $daysinmonth + $weekday - $lastmonthweekday;
2563          if ($lastinmonth > $daysinmonth) {
2564              $lastinmonth -= $daysinweek;
2565          }
2566  
2567          // Find the first such weekday <= $startday.
2568          while ($lastinmonth > $startday) {
2569              $lastinmonth -= $daysinweek;
2570          }
2571  
2572          return $lastinmonth;
2573      } else {
2574          $indexweekday = dayofweek($startday, $month, $year);
2575  
2576          $diff = $weekday - $indexweekday;
2577          if ($diff < 0) {
2578              $diff += $daysinweek;
2579          }
2580  
2581          // This is the first such weekday of the month equal to or after $startday.
2582          $firstfromindex = $startday + $diff;
2583  
2584          return $firstfromindex;
2585      }
2586  }
2587  
2588  /**
2589   * Calculate the number of days in a given month
2590   *
2591   * @package core
2592   * @category time
2593   * @param int $month The month whose day count is sought
2594   * @param int $year The year of the month whose day count is sought
2595   * @return int
2596   */
2597  function days_in_month($month, $year) {
2598      $calendartype = \core_calendar\type_factory::get_calendar_instance();
2599      return $calendartype->get_num_days_in_month($year, $month);
2600  }
2601  
2602  /**
2603   * Calculate the position in the week of a specific calendar day
2604   *
2605   * @package core
2606   * @category time
2607   * @param int $day The day of the date whose position in the week is sought
2608   * @param int $month The month of the date whose position in the week is sought
2609   * @param int $year The year of the date whose position in the week is sought
2610   * @return int
2611   */
2612  function dayofweek($day, $month, $year) {
2613      $calendartype = \core_calendar\type_factory::get_calendar_instance();
2614      return $calendartype->get_weekday($year, $month, $day);
2615  }
2616  
2617  // USER AUTHENTICATION AND LOGIN.
2618  
2619  /**
2620   * Returns full login url.
2621   *
2622   * Any form submissions for authentication to this URL must include username,
2623   * password as well as a logintoken generated by \core\session\manager::get_login_token().
2624   *
2625   * @return string login url
2626   */
2627  function get_login_url() {
2628      global $CFG;
2629  
2630      return "$CFG->wwwroot/login/index.php";
2631  }
2632  
2633  /**
2634   * This function checks that the current user is logged in and has the
2635   * required privileges
2636   *
2637   * This function checks that the current user is logged in, and optionally
2638   * whether they are allowed to be in a particular course and view a particular
2639   * course module.
2640   * If they are not logged in, then it redirects them to the site login unless
2641   * $autologinguest is set and {@link $CFG}->autologinguests is set to 1 in which
2642   * case they are automatically logged in as guests.
2643   * If $courseid is given and the user is not enrolled in that course then the
2644   * user is redirected to the course enrolment page.
2645   * If $cm is given and the course module is hidden and the user is not a teacher
2646   * in the course then the user is redirected to the course home page.
2647   *
2648   * When $cm parameter specified, this function sets page layout to 'module'.
2649   * You need to change it manually later if some other layout needed.
2650   *
2651   * @package    core_access
2652   * @category   access
2653   *
2654   * @param mixed $courseorid id of the course or course object
2655   * @param bool $autologinguest default true
2656   * @param object $cm course module object
2657   * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
2658   *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
2659   *             in order to keep redirects working properly. MDL-14495
2660   * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
2661   * @return mixed Void, exit, and die depending on path
2662   * @throws coding_exception
2663   * @throws require_login_exception
2664   * @throws moodle_exception
2665   */
2666  function require_login($courseorid = null, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
2667      global $CFG, $SESSION, $USER, $PAGE, $SITE, $DB, $OUTPUT;
2668  
2669      // Must not redirect when byteserving already started.
2670      if (!empty($_SERVER['HTTP_RANGE'])) {
2671          $preventredirect = true;
2672      }
2673  
2674      if (AJAX_SCRIPT) {
2675          // We cannot redirect for AJAX scripts either.
2676          $preventredirect = true;
2677      }
2678  
2679      // Setup global $COURSE, themes, language and locale.
2680      if (!empty($courseorid)) {
2681          if (is_object($courseorid)) {
2682              $course = $courseorid;
2683          } else if ($courseorid == SITEID) {
2684              $course = clone($SITE);
2685          } else {
2686              $course = $DB->get_record('course', array('id' => $courseorid), '*', MUST_EXIST);
2687          }
2688          if ($cm) {
2689              if ($cm->course != $course->id) {
2690                  throw new coding_exception('course and cm parameters in require_login() call do not match!!');
2691              }
2692              // Make sure we have a $cm from get_fast_modinfo as this contains activity access details.
2693              if (!($cm instanceof cm_info)) {
2694                  // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
2695                  // db queries so this is not really a performance concern, however it is obviously
2696                  // better if you use get_fast_modinfo to get the cm before calling this.
2697                  $modinfo = get_fast_modinfo($course);
2698                  $cm = $modinfo->get_cm($cm->id);
2699              }
2700          }
2701      } else {
2702          // Do not touch global $COURSE via $PAGE->set_course(),
2703          // the reasons is we need to be able to call require_login() at any time!!
2704          $course = $SITE;
2705          if ($cm) {
2706              throw new coding_exception('cm parameter in require_login() requires valid course parameter!');
2707          }
2708      }
2709  
2710      // If this is an AJAX request and $setwantsurltome is true then we need to override it and set it to false.
2711      // Otherwise the AJAX request URL will be set to $SESSION->wantsurl and events such as self enrolment in the future
2712      // risk leading the user back to the AJAX request URL.
2713      if ($setwantsurltome && defined('AJAX_SCRIPT') && AJAX_SCRIPT) {
2714          $setwantsurltome = false;
2715      }
2716  
2717      // Redirect to the login page if session has expired, only with dbsessions enabled (MDL-35029) to maintain current behaviour.
2718      if ((!isloggedin() or isguestuser()) && !empty($SESSION->has_timed_out) && !empty($CFG->dbsessions)) {
2719          if ($preventredirect) {
2720              throw new require_login_session_timeout_exception();
2721          } else {
2722              if ($setwantsurltome) {
2723                  $SESSION->wantsurl = qualified_me();
2724              }
2725              redirect(get_login_url());
2726          }
2727      }
2728  
2729      // If the user is not even logged in yet then make sure they are.
2730      if (!isloggedin()) {
2731          if ($autologinguest and !empty($CFG->guestloginbutton) and !empty($CFG->autologinguests)) {
2732              if (!$guest = get_complete_user_data('id', $CFG->siteguest)) {
2733                  // Misconfigured site guest, just redirect to login page.
2734                  redirect(get_login_url());
2735                  exit; // Never reached.
2736              }
2737              $lang = isset($SESSION->lang) ? $SESSION->lang : $CFG->lang;
2738              complete_user_login($guest);
2739              $USER->autologinguest = true;
2740              $SESSION->lang = $lang;
2741          } else {
2742              // NOTE: $USER->site check was obsoleted by session test cookie, $USER->confirmed test is in login/index.php.
2743              if ($preventredirect) {
2744                  throw new require_login_exception('You are not logged in');
2745              }
2746  
2747              if ($setwantsurltome) {
2748                  $SESSION->wantsurl = qualified_me();
2749              }
2750  
2751              // Give auth plugins an opportunity to authenticate or redirect to an external login page
2752              $authsequence = get_enabled_auth_plugins(); // Auths, in sequence.
2753              foreach($authsequence as $authname) {
2754                  $authplugin = get_auth_plugin($authname);
2755                  $authplugin->pre_loginpage_hook();
2756                  if (isloggedin()) {
2757                      if ($cm) {
2758                          $modinfo = get_fast_modinfo($course);
2759                          $cm = $modinfo->get_cm($cm->id);
2760                      }
2761                      set_access_log_user();
2762                      break;
2763                  }
2764              }
2765  
2766              // If we're still not logged in then go to the login page
2767              if (!isloggedin()) {
2768                  redirect(get_login_url());
2769                  exit; // Never reached.
2770              }
2771          }
2772      }
2773  
2774      // Loginas as redirection if needed.
2775      if ($course->id != SITEID and \core\session\manager::is_loggedinas()) {
2776          if ($USER->loginascontext->contextlevel == CONTEXT_COURSE) {
2777              if ($USER->loginascontext->instanceid != $course->id) {
2778                  print_error('loginasonecourse', '', $CFG->wwwroot.'/course/view.php?id='.$USER->loginascontext->instanceid);
2779              }
2780          }
2781      }
2782  
2783      // Check whether the user should be changing password (but only if it is REALLY them).
2784      if (get_user_preferences('auth_forcepasswordchange') && !\core\session\manager::is_loggedinas()) {
2785          $userauth = get_auth_plugin($USER->auth);
2786          if ($userauth->can_change_password() and !$preventredirect) {
2787              if ($setwantsurltome) {
2788                  $SESSION->wantsurl = qualified_me();
2789              }
2790              if ($changeurl = $userauth->change_password_url()) {
2791                  // Use plugin custom url.
2792                  redirect($changeurl);
2793              } else {
2794                  // Use moodle internal method.
2795                  redirect($CFG->wwwroot .'/login/change_password.php');
2796              }
2797          } else if ($userauth->can_change_password()) {
2798              throw new moodle_exception('forcepasswordchangenotice');
2799          } else {
2800              throw new moodle_exception('nopasswordchangeforced', 'auth');
2801          }
2802      }
2803  
2804      // Check that the user account is properly set up. If we can't redirect to
2805      // edit their profile and this is not a WS request, perform just the lax check.
2806      // It will allow them to use filepicker on the profile edit page.
2807  
2808      if ($preventredirect && !WS_SERVER) {
2809          $usernotfullysetup = user_not_fully_set_up($USER, false);
2810      } else {
2811          $usernotfullysetup = user_not_fully_set_up($USER, true);
2812      }
2813  
2814      if ($usernotfullysetup) {
2815          if ($preventredirect) {
2816              throw new moodle_exception('usernotfullysetup');
2817          }
2818          if ($setwantsurltome) {
2819              $SESSION->wantsurl = qualified_me();
2820          }
2821          redirect($CFG->wwwroot .'/user/edit.php?id='. $USER->id .'&amp;course='. SITEID);
2822      }
2823  
2824      // Make sure the USER has a sesskey set up. Used for CSRF protection.
2825      sesskey();
2826  
2827      if (\core\session\manager::is_loggedinas()) {
2828          // During a "logged in as" session we should force all content to be cleaned because the
2829          // logged in user will be viewing potentially malicious user generated content.
2830          // See MDL-63786 for more details.
2831          $CFG->forceclean = true;
2832      }
2833  
2834      $afterlogins = get_plugins_with_function('after_require_login', 'lib.php');
2835  
2836      // Do not bother admins with any formalities, except for activities pending deletion.
2837      if (is_siteadmin() && !($cm && $cm->deletioninprogress)) {
2838          // Set the global $COURSE.
2839          if ($cm) {
2840              $PAGE->set_cm($cm, $course);
2841              $PAGE->set_pagelayout('incourse');
2842          } else if (!empty($courseorid)) {
2843              $PAGE->set_course($course);
2844          }
2845          // Set accesstime or the user will appear offline which messes up messaging.
2846          // Do not update access time for webservice or ajax requests.
2847          if (!WS_SERVER && !AJAX_SCRIPT) {
2848              user_accesstime_log($course->id);
2849          }
2850  
2851          foreach ($afterlogins as $plugintype => $plugins) {
2852              foreach ($plugins as $pluginfunction) {
2853                  $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
2854              }
2855          }
2856          return;
2857      }
2858  
2859      // Scripts have a chance to declare that $USER->policyagreed should not be checked.
2860      // This is mostly for places where users are actually accepting the policies, to avoid the redirect loop.
2861      if (!defined('NO_SITEPOLICY_CHECK')) {
2862          define('NO_SITEPOLICY_CHECK', false);
2863      }
2864  
2865      // Check that the user has agreed to a site policy if there is one - do not test in case of admins.
2866      // Do not test if the script explicitly asked for skipping the site policies check.
2867      if (!$USER->policyagreed && !is_siteadmin() && !NO_SITEPOLICY_CHECK) {
2868          $manager = new \core_privacy\local\sitepolicy\manager();
2869          if ($policyurl = $manager->get_redirect_url(isguestuser())) {
2870              if ($preventredirect) {
2871                  throw new moodle_exception('sitepolicynotagreed', 'error', '', $policyurl->out());
2872              }
2873              if ($setwantsurltome) {
2874                  $SESSION->wantsurl = qualified_me();
2875              }
2876              redirect($policyurl);
2877          }
2878      }
2879  
2880      // Fetch the system context, the course context, and prefetch its child contexts.
2881      $sysctx = context_system::instance();
2882      $coursecontext = context_course::instance($course->id, MUST_EXIST);
2883      if ($cm) {
2884          $cmcontext = context_module::instance($cm->id, MUST_EXIST);
2885      } else {
2886          $cmcontext = null;
2887      }
2888  
2889      // If the site is currently under maintenance, then print a message.
2890      if (!empty($CFG->maintenance_enabled) and !has_capability('moodle/site:maintenanceaccess', $sysctx)) {
2891          if ($preventredirect) {
2892              throw new require_login_exception('Maintenance in progress');
2893          }
2894          $PAGE->set_context(null);
2895          print_maintenance_message();
2896      }
2897  
2898      // Make sure the course itself is not hidden.
2899      if ($course->id == SITEID) {
2900          // Frontpage can not be hidden.
2901      } else {
2902          if (is_role_switched($course->id)) {
2903              // When switching roles ignore the hidden flag - user had to be in course to do the switch.
2904          } else {
2905              if (!$course->visible and !has_capability('moodle/course:viewhiddencourses', $coursecontext)) {
2906                  // Originally there was also test of parent category visibility, BUT is was very slow in complex queries
2907                  // involving "my courses" now it is also possible to simply hide all courses user is not enrolled in :-).
2908                  if ($preventredirect) {
2909                      throw new require_login_exception('Course is hidden');
2910                  }
2911                  $PAGE->set_context(null);
2912                  // We need to override the navigation URL as the course won't have been added to the navigation and thus
2913                  // the navigation will mess up when trying to find it.
2914                  navigation_node::override_active_url(new moodle_url('/'));
2915                  notice(get_string('coursehidden'), $CFG->wwwroot .'/');
2916              }
2917          }
2918      }
2919  
2920      // Is the user enrolled?
2921      if ($course->id == SITEID) {
2922          // Everybody is enrolled on the frontpage.
2923      } else {
2924          if (\core\session\manager::is_loggedinas()) {
2925              // Make sure the REAL person can access this course first.
2926              $realuser = \core\session\manager::get_realuser();
2927              if (!is_enrolled($coursecontext, $realuser->id, '', true) and
2928                  !is_viewing($coursecontext, $realuser->id) and !is_siteadmin($realuser->id)) {
2929                  if ($preventredirect) {
2930                      throw new require_login_exception('Invalid course login-as access');
2931                  }
2932                  $PAGE->set_context(null);
2933                  echo $OUTPUT->header();
2934                  notice(get_string('studentnotallowed', '', fullname($USER, true)), $CFG->wwwroot .'/');
2935              }
2936          }
2937  
2938          $access = false;
2939  
2940          if (is_role_switched($course->id)) {
2941              // Ok, user had to be inside this course before the switch.
2942              $access = true;
2943  
2944          } else if (is_viewing($coursecontext, $USER)) {
2945              // Ok, no need to mess with enrol.
2946              $access = true;
2947  
2948          } else {
2949              if (isset($USER->enrol['enrolled'][$course->id])) {
2950                  if ($USER->enrol['enrolled'][$course->id] > time()) {
2951                      $access = true;
2952                      if (isset($USER->enrol['tempguest'][$course->id])) {
2953                          unset($USER->enrol['tempguest'][$course->id]);
2954                          remove_temp_course_roles($coursecontext);
2955                      }
2956                  } else {
2957                      // Expired.
2958                      unset($USER->enrol['enrolled'][$course->id]);
2959                  }
2960              }
2961              if (isset($USER->enrol['tempguest'][$course->id])) {
2962                  if ($USER->enrol['tempguest'][$course->id] == 0) {
2963                      $access = true;
2964                  } else if ($USER->enrol['tempguest'][$course->id] > time()) {
2965                      $access = true;
2966                  } else {
2967                      // Expired.
2968                      unset($USER->enrol['tempguest'][$course->id]);
2969                      remove_temp_course_roles($coursecontext);
2970                  }
2971              }
2972  
2973              if (!$access) {
2974                  // Cache not ok.
2975                  $until = enrol_get_enrolment_end($coursecontext->instanceid, $USER->id);
2976                  if ($until !== false) {
2977                      // Active participants may always access, a timestamp in the future, 0 (always) or false.
2978                      if ($until == 0) {
2979                          $until = ENROL_MAX_TIMESTAMP;
2980                      }
2981                      $USER->enrol['enrolled'][$course->id] = $until;
2982                      $access = true;
2983  
2984                  } else if (core_course_category::can_view_course_info($course)) {
2985                      $params = array('courseid' => $course->id, 'status' => ENROL_INSTANCE_ENABLED);
2986                      $instances = $DB->get_records('enrol', $params, 'sortorder, id ASC');
2987                      $enrols = enrol_get_plugins(true);
2988                      // First ask all enabled enrol instances in course if they want to auto enrol user.
2989                      foreach ($instances as $instance) {
2990                          if (!isset($enrols[$instance->enrol])) {
2991                              continue;
2992                          }
2993                          // Get a duration for the enrolment, a timestamp in the future, 0 (always) or false.
2994                          $until = $enrols[$instance->enrol]->try_autoenrol($instance);
2995                          if ($until !== false) {
2996                              if ($until == 0) {
2997                                  $until = ENROL_MAX_TIMESTAMP;
2998                              }
2999                              $USER->enrol['enrolled'][$course->id] = $until;
3000                              $access = true;
3001                              break;
3002                          }
3003                      }
3004                      // If not enrolled yet try to gain temporary guest access.
3005                      if (!$access) {
3006                          foreach ($instances as $instance) {
3007                              if (!isset($enrols[$instance->enrol])) {
3008                                  continue;
3009                              }
3010                              // Get a duration for the guest access, a timestamp in the future or false.
3011                              $until = $enrols[$instance->enrol]->try_guestaccess($instance);
3012                              if ($until !== false and $until > time()) {
3013                                  $USER->enrol['tempguest'][$course->id] = $until;
3014                                  $access = true;
3015                                  break;
3016                              }
3017                          }
3018                      }
3019                  } else {
3020                      // User is not enrolled and is not allowed to browse courses here.
3021                      if ($preventredirect) {
3022                          throw new require_login_exception('Course is not available');
3023                      }
3024                      $PAGE->set_context(null);
3025                      // We need to override the navigation URL as the course won't have been added to the navigation and thus
3026                      // the navigation will mess up when trying to find it.
3027                      navigation_node::override_active_url(new moodle_url('/'));
3028                      notice(get_string('coursehidden'), $CFG->wwwroot .'/');
3029                  }
3030              }
3031          }
3032  
3033          if (!$access) {
3034              if ($preventredirect) {
3035                  throw new require_login_exception('Not enrolled');
3036              }
3037              if ($setwantsurltome) {
3038                  $SESSION->wantsurl = qualified_me();
3039              }
3040              redirect($CFG->wwwroot .'/enrol/index.php?id='. $course->id);
3041          }
3042      }
3043  
3044      // Check whether the activity has been scheduled for deletion. If so, then deny access, even for admins.
3045      if ($cm && $cm->deletioninprogress) {
3046          if ($preventredirect) {
3047              throw new moodle_exception('activityisscheduledfordeletion');
3048          }
3049          require_once($CFG->dirroot . '/course/lib.php');
3050          redirect(course_get_url($course), get_string('activityisscheduledfordeletion', 'error'));
3051      }
3052  
3053      // Check visibility of activity to current user; includes visible flag, conditional availability, etc.
3054      if ($cm && !$cm->uservisible) {
3055          if ($preventredirect) {
3056              throw new require_login_exception('Activity is hidden');
3057          }
3058          // Get the error message that activity is not available and why (if explanation can be shown to the user).
3059          $PAGE->set_course($course);
3060          $renderer = $PAGE->get_renderer('course');
3061          $message = $renderer->course_section_cm_unavailable_error_message($cm);
3062          redirect(course_get_url($course), $message, null, \core\output\notification::NOTIFY_ERROR);
3063      }
3064  
3065      // Set the global $COURSE.
3066      if ($cm) {
3067          $PAGE->set_cm($cm, $course);
3068          $PAGE->set_pagelayout('incourse');
3069      } else if (!empty($courseorid)) {
3070          $PAGE->set_course($course);
3071      }
3072  
3073      foreach ($afterlogins as $plugintype => $plugins) {
3074          foreach ($plugins as $pluginfunction) {
3075              $pluginfunction($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3076          }
3077      }
3078  
3079      // Finally access granted, update lastaccess times.
3080      // Do not update access time for webservice or ajax requests.
3081      if (!WS_SERVER && !AJAX_SCRIPT) {
3082          user_accesstime_log($course->id);
3083      }
3084  }
3085  
3086  /**
3087   * A convenience function for where we must be logged in as admin
3088   * @return void
3089   */
3090  function require_admin() {
3091      require_login(null, false);
3092      require_capability('moodle/site:config', context_system::instance());
3093  }
3094  
3095  /**
3096   * This function just makes sure a user is logged out.
3097   *
3098   * @package    core_access
3099   * @category   access
3100   */
3101  function require_logout() {
3102      global $USER, $DB;
3103  
3104      if (!isloggedin()) {
3105          // This should not happen often, no need for hooks or events here.
3106          \core\session\manager::terminate_current();
3107          return;
3108      }
3109  
3110      // Execute hooks before action.
3111      $authplugins = array();
3112      $authsequence = get_enabled_auth_plugins();
3113      foreach ($authsequence as $authname) {
3114          $authplugins[$authname] = get_auth_plugin($authname);
3115          $authplugins[$authname]->prelogout_hook();
3116      }
3117  
3118      // Store info that gets removed during logout.
3119      $sid = session_id();
3120      $event = \core\event\user_loggedout::create(
3121          array(
3122              'userid' => $USER->id,
3123              'objectid' => $USER->id,
3124              'other' => array('sessionid' => $sid),
3125          )
3126      );
3127      if ($session = $DB->get_record('sessions', array('sid'=>$sid))) {
3128          $event->add_record_snapshot('sessions', $session);
3129      }
3130  
3131      // Clone of $USER object to be used by auth plugins.
3132      $user = fullclone($USER);
3133  
3134      // Delete session record and drop $_SESSION content.
3135      \core\session\manager::terminate_current();
3136  
3137      // Trigger event AFTER action.
3138      $event->trigger();
3139  
3140      // Hook to execute auth plugins redirection after event trigger.
3141      foreach ($authplugins as $authplugin) {
3142          $authplugin->postlogout_hook($user);
3143      }
3144  }
3145  
3146  /**
3147   * Weaker version of require_login()
3148   *
3149   * This is a weaker version of {@link require_login()} which only requires login
3150   * when called from within a course rather than the site page, unless
3151   * the forcelogin option is turned on.
3152   * @see require_login()
3153   *
3154   * @package    core_access
3155   * @category   access
3156   *
3157   * @param mixed $courseorid The course object or id in question
3158   * @param bool $autologinguest Allow autologin guests if that is wanted
3159   * @param object $cm Course activity module if known
3160   * @param bool $setwantsurltome Define if we want to set $SESSION->wantsurl, defaults to
3161   *             true. Used to avoid (=false) some scripts (file.php...) to set that variable,
3162   *             in order to keep redirects working properly. MDL-14495
3163   * @param bool $preventredirect set to true in scripts that can not redirect (CLI, rss feeds, etc.), throws exceptions
3164   * @return void
3165   * @throws coding_exception
3166   */
3167  function require_course_login($courseorid, $autologinguest = true, $cm = null, $setwantsurltome = true, $preventredirect = false) {
3168      global $CFG, $PAGE, $SITE;
3169      $issite = ((is_object($courseorid) and $courseorid->id == SITEID)
3170            or (!is_object($courseorid) and $courseorid == SITEID));
3171      if ($issite && !empty($cm) && !($cm instanceof cm_info)) {
3172          // Note: nearly all pages call get_fast_modinfo anyway and it does not make any
3173          // db queries so this is not really a performance concern, however it is obviously
3174          // better if you use get_fast_modinfo to get the cm before calling this.
3175          if (is_object($courseorid)) {
3176              $course = $courseorid;
3177          } else {
3178              $course = clone($SITE);
3179          }
3180          $modinfo = get_fast_modinfo($course);
3181          $cm = $modinfo->get_cm($cm->id);
3182      }
3183      if (!empty($CFG->forcelogin)) {
3184          // Login required for both SITE and courses.
3185          require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3186  
3187      } else if ($issite && !empty($cm) and !$cm->uservisible) {
3188          // Always login for hidden activities.
3189          require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3190  
3191      } else if (isloggedin() && !isguestuser()) {
3192          // User is already logged in. Make sure the login is complete (user is fully setup, policies agreed).
3193          require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3194  
3195      } else if ($issite) {
3196          // Login for SITE not required.
3197          // We still need to instatiate PAGE vars properly so that things that rely on it like navigation function correctly.
3198          if (!empty($courseorid)) {
3199              if (is_object($courseorid)) {
3200                  $course = $courseorid;
3201              } else {
3202                  $course = clone $SITE;
3203              }
3204              if ($cm) {
3205                  if ($cm->course != $course->id) {
3206                      throw new coding_exception('course and cm parameters in require_course_login() call do not match!!');
3207                  }
3208                  $PAGE->set_cm($cm, $course);
3209                  $PAGE->set_pagelayout('incourse');
3210              } else {
3211                  $PAGE->set_course($course);
3212              }
3213          } else {
3214              // If $PAGE->course, and hence $PAGE->context, have not already been set up properly, set them up now.
3215              $PAGE->set_course($PAGE->course);
3216          }
3217          // Do not update access time for webservice or ajax requests.
3218          if (!WS_SERVER && !AJAX_SCRIPT) {
3219              user_accesstime_log(SITEID);
3220          }
3221          return;
3222  
3223      } else {
3224          // Course login always required.
3225          require_login($courseorid, $autologinguest, $cm, $setwantsurltome, $preventredirect);
3226      }
3227  }
3228  
3229  /**
3230   * Validates a user key, checking if the key exists, is not expired and the remote ip is correct.
3231   *
3232   * @param  string $keyvalue the key value
3233   * @param  string $script   unique script identifier
3234   * @param  int $instance    instance id
3235   * @return stdClass the key entry in the user_private_key table
3236   * @since Moodle 3.2
3237   * @throws moodle_exception
3238   */
3239  function validate_user_key($keyvalue, $script, $instance) {
3240      global $DB;
3241  
3242      if (!$key = $DB->get_record('user_private_key', array('script' => $script, 'value' => $keyvalue, 'instance' => $instance))) {
3243          print_error('invalidkey');
3244      }
3245  
3246      if (!empty($key->validuntil) and $key->validuntil < time()) {
3247          print_error('expiredkey');
3248      }
3249  
3250      if ($key->iprestriction) {
3251          $remoteaddr = getremoteaddr(null);
3252          if (empty($remoteaddr) or !address_in_subnet($remoteaddr, $key->iprestriction)) {
3253              print_error('ipmismatch');
3254          }
3255      }
3256      return $key;
3257  }
3258  
3259  /**
3260   * Require key login. Function terminates with error if key not found or incorrect.
3261   *
3262   * @uses NO_MOODLE_COOKIES
3263   * @uses PARAM_ALPHANUM
3264   * @param string $script unique script identifier
3265   * @param int $instance optional instance id
3266   * @param string $keyvalue The key. If not supplied, this will be fetched from the current session.
3267   * @return int Instance ID
3268   */
3269  function require_user_key_login($script, $instance = null, $keyvalue = null) {
3270      global $DB;
3271  
3272      if (!NO_MOODLE_COOKIES) {
3273          print_error('sessioncookiesdisable');
3274      }
3275  
3276      // Extra safety.
3277      \core\session\manager::write_close();
3278  
3279      if (null === $keyvalue) {
3280          $keyvalue = required_param('key', PARAM_ALPHANUM);
3281      }
3282  
3283      $key = validate_user_key($keyvalue, $script, $instance);
3284  
3285      if (!$user = $DB->get_record('user', array('id' => $key->userid))) {
3286          print_error('invaliduserid');
3287      }
3288  
3289      core_user::require_active_user($user, true, true);
3290  
3291      // Emulate normal session.
3292      enrol_check_plugins($user);
3293      \core\session\manager::set_user($user);
3294  
3295      // Note we are not using normal login.
3296      if (!defined('USER_KEY_LOGIN')) {
3297          define('USER_KEY_LOGIN', true);
3298      }
3299  
3300      // Return instance id - it might be empty.
3301      return $key->instance;
3302  }
3303  
3304  /**
3305   * Creates a new private user access key.
3306   *
3307   * @param string $script unique target identifier
3308   * @param int $userid
3309   * @param int $instance optional instance id
3310   * @param string $iprestriction optional ip restricted access
3311   * @param int $validuntil key valid only until given data
3312   * @return string access key value
3313   */
3314  function create_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3315      global $DB;
3316  
3317      $key = new stdClass();
3318      $key->script        = $script;
3319      $key->userid        = $userid;
3320      $key->instance      = $instance;
3321      $key->iprestriction = $iprestriction;
3322      $key->validuntil    = $validuntil;
3323      $key->timecreated   = time();
3324  
3325      // Something long and unique.
3326      $key->value         = md5($userid.'_'.time().random_string(40));
3327      while ($DB->record_exists('user_private_key', array('value' => $key->value))) {
3328          // Must be unique.
3329          $key->value     = md5($userid.'_'.time().random_string(40));
3330      }
3331      $DB->insert_record('user_private_key', $key);
3332      return $key->value;
3333  }
3334  
3335  /**
3336   * Delete the user's new private user access keys for a particular script.
3337   *
3338   * @param string $script unique target identifier
3339   * @param int $userid
3340   * @return void
3341   */
3342  function delete_user_key($script, $userid) {
3343      global $DB;
3344      $DB->delete_records('user_private_key', array('script' => $script, 'userid' => $userid));
3345  }
3346  
3347  /**
3348   * Gets a private user access key (and creates one if one doesn't exist).
3349   *
3350   * @param string $script unique target identifier
3351   * @param int $userid
3352   * @param int $instance optional instance id
3353   * @param string $iprestriction optional ip restricted access
3354   * @param int $validuntil key valid only until given date
3355   * @return string access key value
3356   */
3357  function get_user_key($script, $userid, $instance=null, $iprestriction=null, $validuntil=null) {
3358      global $DB;
3359  
3360      if ($key = $DB->get_record('user_private_key', array('script' => $script, 'userid' => $userid,
3361                                                           'instance' => $instance, 'iprestriction' => $iprestriction,
3362                                                           'validuntil' => $validuntil))) {
3363          return $key->value;
3364      } else {
3365          return create_user_key($script, $userid, $instance, $iprestriction, $validuntil);
3366      }
3367  }
3368  
3369  
3370  /**
3371   * Modify the user table by setting the currently logged in user's last login to now.
3372   *
3373   * @return bool Always returns true
3374   */
3375  function update_user_login_times() {
3376      global $USER, $DB;
3377  
3378      if (isguestuser()) {
3379          // Do not update guest access times/ips for performance.
3380          return true;
3381      }
3382  
3383      if (defined('USER_KEY_LOGIN') && USER_KEY_LOGIN === true) {
3384          // Do not update user login time when using user key login.
3385          return true;
3386      }
3387  
3388      $now = time();
3389  
3390      $user = new stdClass();
3391      $user->id = $USER->id;
3392  
3393      // Make sure all users that logged in have some firstaccess.
3394      if ($USER->firstaccess == 0) {
3395          $USER->firstaccess = $user->firstaccess = $now;
3396      }
3397  
3398      // Store the previous current as lastlogin.
3399      $USER->lastlogin = $user->lastlogin = $USER->currentlogin;
3400  
3401      $USER->currentlogin = $user->currentlogin = $now;
3402  
3403      // Function user_accesstime_log() may not update immediately, better do it here.
3404      $USER->lastaccess = $user->lastaccess = $now;
3405      $USER->lastip = $user->lastip = getremoteaddr();
3406  
3407      // Note: do not call user_update_user() here because this is part of the login process,
3408      //       the login event means that these fields were updated.
3409      $DB->update_record('user', $user);
3410      return true;
3411  }
3412  
3413  /**
3414   * Determines if a user has completed setting up their account.
3415   *
3416   * The lax mode (with $strict = false) has been introduced for special cases
3417   * only where we want to skip certain checks intentionally. This is valid in
3418   * certain mnet or ajax scenarios when the user cannot / should not be
3419   * redirected to edit their profile. In most cases, you should perform the
3420   * strict check.
3421   *
3422   * @param stdClass $user A {@link $USER} object to test for the existence of a valid name and email
3423   * @param bool $strict Be more strict and assert id and custom profile fields set, too
3424   * @return bool
3425   */
3426  function user_not_fully_set_up($user, $strict = true) {
3427      global $CFG;
3428      require_once($CFG->dirroot.'/user/profile/lib.php');
3429  
3430      if (isguestuser($user)) {
3431          return false;
3432      }
3433  
3434      if (empty($user->firstname) or empty($user->lastname) or empty($user->email) or over_bounce_threshold($user)) {
3435          return true;
3436      }
3437  
3438      if ($strict) {
3439          if (empty($user->id)) {
3440              // Strict mode can be used with existing accounts only.
3441              return true;
3442          }
3443          if (!profile_has_required_custom_fields_set($user->id)) {
3444              return true;
3445          }
3446      }
3447  
3448      return false;
3449  }
3450  
3451  /**
3452   * Check whether the user has exceeded the bounce threshold
3453   *
3454   * @param stdClass $user A {@link $USER} object
3455   * @return bool true => User has exceeded bounce threshold
3456   */
3457  function over_bounce_threshold($user) {
3458      global $CFG, $DB;
3459  
3460      if (empty($CFG->handlebounces)) {
3461          return false;
3462      }
3463  
3464      if (empty($user->id)) {
3465          // No real (DB) user, nothing to do here.
3466          return false;
3467      }
3468  
3469      // Set sensible defaults.
3470      if (empty($CFG->minbounces)) {
3471          $CFG->minbounces = 10;
3472      }
3473      if (empty($CFG->bounceratio)) {
3474          $CFG->bounceratio = .20;
3475      }
3476      $bouncecount = 0;
3477      $sendcount = 0;
3478      if ($bounce = $DB->get_record('user_preferences', array ('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3479          $bouncecount = $bounce->value;
3480      }
3481      if ($send = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3482          $sendcount = $send->value;
3483      }
3484      return ($bouncecount >= $CFG->minbounces && $bouncecount/$sendcount >= $CFG->bounceratio);
3485  }
3486  
3487  /**
3488   * Used to increment or reset email sent count
3489   *
3490   * @param stdClass $user object containing an id
3491   * @param bool $reset will reset the count to 0
3492   * @return void
3493   */
3494  function set_send_count($user, $reset=false) {
3495      global $DB;
3496  
3497      if (empty($user->id)) {
3498          // No real (DB) user, nothing to do here.
3499          return;
3500      }
3501  
3502      if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_send_count'))) {
3503          $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3504          $DB->update_record('user_preferences', $pref);
3505      } else if (!empty($reset)) {
3506          // If it's not there and we're resetting, don't bother. Make a new one.
3507          $pref = new stdClass();
3508          $pref->name   = 'email_send_count';
3509          $pref->value  = 1;
3510          $pref->userid = $user->id;
3511          $DB->insert_record('user_preferences', $pref, false);
3512      }
3513  }
3514  
3515  /**
3516   * Increment or reset user's email bounce count
3517   *
3518   * @param stdClass $user object containing an id
3519   * @param bool $reset will reset the count to 0
3520   */
3521  function set_bounce_count($user, $reset=false) {
3522      global $DB;
3523  
3524      if ($pref = $DB->get_record('user_preferences', array('userid' => $user->id, 'name' => 'email_bounce_count'))) {
3525          $pref->value = (!empty($reset)) ? 0 : $pref->value+1;
3526          $DB->update_record('user_preferences', $pref);
3527      } else if (!empty($reset)) {
3528          // If it's not there and we're resetting, don't bother. Make a new one.
3529          $pref = new stdClass();
3530          $pref->name   = 'email_bounce_count';
3531          $pref->value  = 1;
3532          $pref->userid = $user->id;
3533          $DB->insert_record('user_preferences', $pref, false);
3534      }
3535  }
3536  
3537  /**
3538   * Determines if the logged in user is currently moving an activity
3539   *
3540   * @param int $courseid The id of the course being tested
3541   * @return bool
3542   */
3543  function ismoving($courseid) {
3544      global $USER;
3545  
3546      if (!empty($USER->activitycopy)) {
3547          return ($USER->activitycopycourse == $courseid);
3548      }
3549      return false;
3550  }
3551  
3552  /**
3553   * Returns a persons full name
3554   *
3555   * Given an object containing all of the users name values, this function returns a string with the full name of the person.
3556   * The result may depend on system settings or language. 'override' will force the alternativefullnameformat to be used. In
3557   * English, fullname as well as alternativefullnameformat is set to 'firstname lastname' by default. But you could have
3558   * fullname set to 'firstname lastname' and alternativefullnameformat set to 'firstname middlename alternatename lastname'.
3559   *
3560   * @param stdClass $user A {@link $USER} object to get full name of.
3561   * @param bool $override If true then the alternativefullnameformat format rather than fullnamedisplay format will be used.
3562   * @return string
3563   */
3564  function fullname($user, $override=false) {
3565      global $CFG, $SESSION;
3566  
3567      if (!isset($user->firstname) and !isset($user->lastname)) {
3568          return '';
3569      }
3570  
3571      // Get all of the name fields.
3572      $allnames = \core_user\fields::get_name_fields();
3573      if ($CFG->debugdeveloper) {
3574          foreach ($allnames as $allname) {
3575              if (!property_exists($user, $allname)) {
3576                  // If all the user name fields are not set in the user object, then notify the programmer that it needs to be fixed.
3577                  debugging('You need to update your sql to include additional name fields in the user object.', DEBUG_DEVELOPER);
3578                  // Message has been sent, no point in sending the message multiple times.
3579                  break;
3580              }
3581          }
3582      }
3583  
3584      if (!$override) {
3585          if (!empty($CFG->forcefirstname)) {
3586              $user->firstname = $CFG->forcefirstname;
3587          }
3588          if (!empty($CFG->forcelastname)) {
3589              $user->lastname = $CFG->forcelastname;
3590          }
3591      }
3592  
3593      if (!empty($SESSION->fullnamedisplay)) {
3594          $CFG->fullnamedisplay = $SESSION->fullnamedisplay;
3595      }
3596  
3597      $template = null;
3598      // If the fullnamedisplay setting is available, set the template to that.
3599      if (isset($CFG->fullnamedisplay)) {
3600          $template = $CFG->fullnamedisplay;
3601      }
3602      // If the template is empty, or set to language, return the language string.
3603      if ((empty($template) || $template == 'language') && !$override) {
3604          return get_string('fullnamedisplay', null, $user);
3605      }
3606  
3607      // Check to see if we are displaying according to the alternative full name format.
3608      if ($override) {
3609          if (empty($CFG->alternativefullnameformat) || $CFG->alternativefullnameformat == 'language') {
3610              // Default to show just the user names according to the fullnamedisplay string.
3611              return get_string('fullnamedisplay', null, $user);
3612          } else {
3613              // If the override is true, then change the template to use the complete name.
3614              $template = $CFG->alternativefullnameformat;
3615          }
3616      }
3617  
3618      $requirednames = array();
3619      // With each name, see if it is in the display name template, and add it to the required names array if it is.
3620      foreach ($allnames as $allname) {
3621          if (strpos($template, $allname) !== false) {
3622              $requirednames[] = $allname;
3623          }
3624      }
3625  
3626      $displayname = $template;
3627      // Switch in the actual data into the template.
3628      foreach ($requirednames as $altname) {
3629          if (isset($user->$altname)) {
3630              // Using empty() on the below if statement causes breakages.
3631              if ((string)$user->$altname == '') {
3632                  $displayname = str_replace($altname, 'EMPTY', $displayname);
3633              } else {
3634                  $displayname = str_replace($altname, $user->$altname, $displayname);
3635              }
3636          } else {
3637              $displayname = str_replace($altname, 'EMPTY', $displayname);
3638          }
3639      }
3640      // Tidy up any misc. characters (Not perfect, but gets most characters).
3641      // Don't remove the "u" at the end of the first expression unless you want garbled characters when combining hiragana or
3642      // katakana and parenthesis.
3643      $patterns = array();
3644      // This regular expression replacement is to fix problems such as 'James () Kirk' Where 'Tiberius' (middlename) has not been
3645      // filled in by a user.
3646      // The special characters are Japanese brackets that are common enough to make allowances for them (not covered by :punct:).
3647      $patterns[] = '/[[:punct:]「」]*EMPTY[[:punct:]「」]*/u';
3648      // This regular expression is to remove any double spaces in the display name.
3649      $patterns[] = '/\s{2,}/u';
3650      foreach ($patterns as $pattern) {
3651          $displayname = preg_replace($pattern, ' ', $displayname);
3652      }
3653  
3654      // Trimming $displayname will help the next check to ensure that we don't have a display name with spaces.
3655      $displayname = trim($displayname);
3656      if (empty($displayname)) {
3657          // Going with just the first name if no alternate fields are filled out. May be changed later depending on what
3658          // people in general feel is a good setting to fall back on.
3659          $displayname = $user->firstname;
3660      }
3661      return $displayname;
3662  }
3663  
3664  /**
3665   * Reduces lines of duplicated code for getting user name fields.
3666   *
3667   * See also {@link user_picture::unalias()}
3668   *
3669   * @param object $addtoobject Object to add user name fields to.
3670   * @param object $secondobject Object that contains user name field information.
3671   * @param string $prefix prefix to be added to all fields (including $additionalfields) e.g. authorfirstname.
3672   * @param array $additionalfields Additional fields to be matched with data in the second object.
3673   * The key can be set to the user table field name.
3674   * @return object User name fields.
3675   */
3676  function username_load_fields_from_object($addtoobject, $secondobject, $prefix = null, $additionalfields = null) {
3677      $fields = [];
3678      foreach (\core_user\fields::get_name_fields() as $field) {
3679          $fields[$field] = $prefix . $field;
3680      }
3681      if ($additionalfields) {
3682          // Additional fields can specify their own 'alias' such as 'id' => 'userid'. This checks to see if
3683          // the key is a number and then sets the key to the array value.
3684          foreach ($additionalfields as $key => $value) {
3685              if (is_numeric($key)) {
3686                  $additionalfields[$value] = $prefix . $value;
3687                  unset($additionalfields[$key]);
3688              } else {
3689                  $additionalfields[$key] = $prefix . $value;
3690              }
3691          }
3692          $fields = array_merge($fields, $additionalfields);
3693      }
3694      foreach ($fields as $key => $field) {
3695          // Important that we have all of the user name fields present in the object that we are sending back.
3696          $addtoobject->$key = '';
3697          if (isset($secondobject->$field)) {
3698              $addtoobject->$key = $secondobject->$field;
3699          }
3700      }
3701      return $addtoobject;
3702  }
3703  
3704  /**
3705   * Returns an array of values in order of occurance in a provided string.
3706   * The key in the result is the character postion in the string.
3707   *
3708   * @param array $values Values to be found in the string format
3709   * @param string $stringformat The string which may contain values being searched for.
3710   * @return array An array of values in order according to placement in the string format.
3711   */
3712  function order_in_string($values, $stringformat) {
3713      $valuearray = array();
3714      foreach ($values as $value) {
3715          $pattern = "/$value\b/";
3716          // Using preg_match as strpos() may match values that are similar e.g. firstname and firstnamephonetic.
3717          if (preg_match($pattern, $stringformat)) {
3718              $replacement = "thing";
3719              // Replace the value with something more unique to ensure we get the right position when using strpos().
3720              $newformat = preg_replace($pattern, $replacement, $stringformat);
3721              $position = strpos($newformat, $replacement);
3722              $valuearray[$position] = $value;
3723          }
3724      }
3725      ksort($valuearray);
3726      return $valuearray;
3727  }
3728  
3729  /**
3730   * Returns whether a given authentication plugin exists.
3731   *
3732   * @param string $auth Form of authentication to check for. Defaults to the global setting in {@link $CFG}.
3733   * @return boolean Whether the plugin is available.
3734   */
3735  function exists_auth_plugin($auth) {
3736      global $CFG;
3737  
3738      if (file_exists("{$CFG->dirroot}/auth/$auth/auth.php")) {
3739          return is_readable("{$CFG->dirroot}/auth/$auth/auth.php");
3740      }
3741      return false;
3742  }
3743  
3744  /**
3745   * Checks if a given plugin is in the list of enabled authentication plugins.
3746   *
3747   * @param string $auth Authentication plugin.
3748   * @return boolean Whether the plugin is enabled.
3749   */
3750  function is_enabled_auth($auth) {
3751      if (empty($auth)) {
3752          return false;
3753      }
3754  
3755      $enabled = get_enabled_auth_plugins();
3756  
3757      return in_array($auth, $enabled);
3758  }
3759  
3760  /**
3761   * Returns an authentication plugin instance.
3762   *
3763   * @param string $auth name of authentication plugin
3764   * @return auth_plugin_base An instance of the required authentication plugin.
3765   */
3766  function get_auth_plugin($auth) {
3767      global $CFG;
3768  
3769      // Check the plugin exists first.
3770      if (! exists_auth_plugin($auth)) {
3771          print_error('authpluginnotfound', 'debug', '', $auth);
3772      }
3773  
3774      // Return auth plugin instance.
3775      require_once("{$CFG->dirroot}/auth/$auth/auth.php");
3776      $class = "auth_plugin_$auth";
3777      return new $class;
3778  }
3779  
3780  /**
3781   * Returns array of active auth plugins.
3782   *
3783   * @param bool $fix fix $CFG->auth if needed. Only set if logged in as admin.
3784   * @return array
3785   */
3786  function get_enabled_auth_plugins($fix=false) {
3787      global $CFG;
3788  
3789      $default = array('manual', 'nologin');
3790  
3791      if (empty($CFG->auth)) {
3792          $auths = array();
3793      } else {
3794          $auths = explode(',', $CFG->auth);
3795      }
3796  
3797      $auths = array_unique($auths);
3798      $oldauthconfig = implode(',', $auths);
3799      foreach ($auths as $k => $authname) {
3800          if (in_array($authname, $default)) {
3801              // The manual and nologin plugin never need to be stored.
3802              unset($auths[$k]);
3803          } else if (!exists_auth_plugin($authname)) {
3804              debugging(get_string('authpluginnotfound', 'debug', $authname));
3805              unset($auths[$k]);
3806          }
3807      }
3808  
3809      // Ideally only explicit interaction from a human admin should trigger a
3810      // change in auth config, see MDL-70424 for details.
3811      if ($fix) {
3812          $newconfig = implode(',', $auths);
3813          if (!isset($CFG->auth) or $newconfig != $CFG->auth) {
3814              add_to_config_log('auth', $oldauthconfig, $newconfig, 'core');
3815              set_config('auth', $newconfig);
3816          }
3817      }
3818  
3819      return (array_merge($default, $auths));
3820  }
3821  
3822  /**
3823   * Returns true if an internal authentication method is being used.
3824   * if method not specified then, global default is assumed
3825   *
3826   * @param string $auth Form of authentication required
3827   * @return bool
3828   */
3829  function is_internal_auth($auth) {
3830      // Throws error if bad $auth.
3831      $authplugin = get_auth_plugin($auth);
3832      return $authplugin->is_internal();
3833  }
3834  
3835  /**
3836   * Returns true if the user is a 'restored' one.
3837   *
3838   * Used in the login process to inform the user and allow him/her to reset the password
3839   *
3840   * @param string $username username to be checked
3841   * @return bool
3842   */
3843  function is_restored_user($username) {
3844      global $CFG, $DB;
3845  
3846      return $DB->record_exists('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id, 'password' => 'restored'));
3847  }
3848  
3849  /**
3850   * Returns an array of user fields
3851   *
3852   * @return array User field/column names
3853   */
3854  function get_user_fieldnames() {
3855      global $DB;
3856  
3857      $fieldarray = $DB->get_columns('user');
3858      unset($fieldarray['id']);
3859      $fieldarray = array_keys($fieldarray);
3860  
3861      return $fieldarray;
3862  }
3863  
3864  /**
3865   * Returns the string of the language for the new user.
3866   *
3867   * @return string language for the new user
3868   */
3869  function get_newuser_language() {
3870      global $CFG, $SESSION;
3871      return (!empty($CFG->autolangusercreation) && !empty($SESSION->lang)) ? $SESSION->lang : $CFG->lang;
3872  }
3873  
3874  /**
3875   * Creates a bare-bones user record
3876   *
3877   * @todo Outline auth types and provide code example
3878   *
3879   * @param string $username New user's username to add to record
3880   * @param string $password New user's password to add to record
3881   * @param string $auth Form of authentication required
3882   * @return stdClass A complete user object
3883   */
3884  function create_user_record($username, $password, $auth = 'manual') {
3885      global $CFG, $DB, $SESSION;
3886      require_once($CFG->dirroot.'/user/profile/lib.php');
3887      require_once($CFG->dirroot.'/user/lib.php');
3888  
3889      // Just in case check text case.
3890      $username = trim(core_text::strtolower($username));
3891  
3892      $authplugin = get_auth_plugin($auth);
3893      $customfields = $authplugin->get_custom_user_profile_fields();
3894      $newuser = new stdClass();
3895      if ($newinfo = $authplugin->get_userinfo($username)) {
3896          $newinfo = truncate_userinfo($newinfo);
3897          foreach ($newinfo as $key => $value) {
3898              if (in_array($key, $authplugin->userfields) || (in_array($key, $customfields))) {
3899                  $newuser->$key = $value;
3900              }
3901          }
3902      }
3903  
3904      if (!empty($newuser->email)) {
3905          if (email_is_not_allowed($newuser->email)) {
3906              unset($newuser->email);
3907          }
3908      }
3909  
3910      $newuser->auth = $auth;
3911      $newuser->username = $username;
3912  
3913      // Fix for MDL-8480
3914      // user CFG lang for user if $newuser->lang is empty
3915      // or $user->lang is not an installed language.
3916      if (empty($newuser->lang) || !get_string_manager()->translation_exists($newuser->lang)) {
3917          $newuser->lang = get_newuser_language();
3918      }
3919      $newuser->confirmed = 1;
3920      $newuser->lastip = getremoteaddr();
3921      $newuser->timecreated = time();
3922      $newuser->timemodified = $newuser->timecreated;
3923      $newuser->mnethostid = $CFG->mnet_localhost_id;
3924  
3925      $newuser->id = user_create_user($newuser, false, false);
3926  
3927      // Save user profile data.
3928      profile_save_data($newuser);
3929  
3930      $user = get_complete_user_data('id', $newuser->id);
3931      if (!empty($CFG->{'auth_'.$newuser->auth.'_forcechangepassword'})) {
3932          set_user_preference('auth_forcepasswordchange', 1, $user);
3933      }
3934      // Set the password.
3935      update_internal_user_password($user, $password);
3936  
3937      // Trigger event.
3938      \core\event\user_created::create_from_userid($newuser->id)->trigger();
3939  
3940      return $user;
3941  }
3942  
3943  /**
3944   * Will update a local user record from an external source (MNET users can not be updated using this method!).
3945   *
3946   * @param string $username user's username to update the record
3947   * @return stdClass A complete user object
3948   */
3949  function update_user_record($username) {
3950      global $DB, $CFG;
3951      // Just in case check text case.
3952      $username = trim(core_text::strtolower($username));
3953  
3954      $oldinfo = $DB->get_record('user', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id), '*', MUST_EXIST);
3955      return update_user_record_by_id($oldinfo->id);
3956  }
3957  
3958  /**
3959   * Will update a local user record from an external source (MNET users can not be updated using this method!).
3960   *
3961   * @param int $id user id
3962   * @return stdClass A complete user object
3963   */
3964  function update_user_record_by_id($id) {
3965      global $DB, $CFG;
3966      require_once($CFG->dirroot."/user/profile/lib.php");
3967      require_once($CFG->dirroot.'/user/lib.php');
3968  
3969      $params = array('mnethostid' => $CFG->mnet_localhost_id, 'id' => $id, 'deleted' => 0);
3970      $oldinfo = $DB->get_record('user', $params, '*', MUST_EXIST);
3971  
3972      $newuser = array();
3973      $userauth = get_auth_plugin($oldinfo->auth);
3974  
3975      if ($newinfo = $userauth->get_userinfo($oldinfo->username)) {
3976          $newinfo = truncate_userinfo($newinfo);
3977          $customfields = $userauth->get_custom_user_profile_fields();
3978  
3979          foreach ($newinfo as $key => $value) {
3980              $iscustom = in_array($key, $customfields);
3981              if (!$iscustom) {
3982                  $key = strtolower($key);
3983              }
3984              if ((!property_exists($oldinfo, $key) && !$iscustom) or $key === 'username' or $key === 'id'
3985                      or $key === 'auth' or $key === 'mnethostid' or $key === 'deleted') {
3986                  // Unknown or must not be changed.
3987                  continue;
3988              }
3989              if (empty($userauth->config->{'field_updatelocal_' . $key}) || empty($userauth->config->{'field_lock_' . $key})) {
3990                  continue;
3991              }
3992              $confval = $userauth->config->{'field_updatelocal_' . $key};
3993              $lockval = $userauth->config->{'field_lock_' . $key};
3994              if ($confval === 'onlogin') {
3995                  // MDL-4207 Don't overwrite modified user profile values with
3996                  // empty LDAP values when 'unlocked if empty' is set. The purpose
3997                  // of the setting 'unlocked if empty' is to allow the user to fill
3998                  // in a value for the selected field _if LDAP is giving
3999                  // nothing_ for this field. Thus it makes sense to let this value
4000                  // stand in until LDAP is giving a value for this field.
4001                  if (!(empty($value) && $lockval === 'unlockedifempty')) {
4002                      if ($iscustom || (in_array($key, $userauth->userfields) &&
4003                              ((string)$oldinfo->$key !== (string)$value))) {
4004                          $newuser[$key] = (string)$value;
4005                      }
4006                  }
4007              }
4008          }
4009          if ($newuser) {
4010              $newuser['id'] = $oldinfo->id;
4011              $newuser['timemodified'] = time();
4012              user_update_user((object) $newuser, false, false);
4013  
4014              // Save user profile data.
4015              profile_save_data((object) $newuser);
4016  
4017              // Trigger event.
4018              \core\event\user_updated::create_from_userid($newuser['id'])->trigger();
4019          }
4020      }
4021  
4022      return get_complete_user_data('id', $oldinfo->id);
4023  }
4024  
4025  /**
4026   * Will truncate userinfo as it comes from auth_get_userinfo (from external auth) which may have large fields.
4027   *
4028   * @param array $info Array of user properties to truncate if needed
4029   * @return array The now truncated information that was passed in
4030   */
4031  function truncate_userinfo(array $info) {
4032      // Define the limits.
4033      $limit = array(
4034          'username'    => 100,
4035          'idnumber'    => 255,
4036          'firstname'   => 100,
4037          'lastname'    => 100,
4038          'email'       => 100,
4039          'phone1'      =>  20,
4040          'phone2'      =>  20,
4041          'institution' => 255,
4042          'department'  => 255,
4043          'address'     => 255,
4044          'city'        => 120,
4045          'country'     =>   2,
4046      );
4047  
4048      // Apply where needed.
4049      foreach (array_keys($info) as $key) {
4050          if (!empty($limit[$key])) {
4051              $info[$key] = trim(core_text::substr($info[$key], 0, $limit[$key]));
4052          }
4053      }
4054  
4055      return $info;
4056  }
4057  
4058  /**
4059   * Marks user deleted in internal user database and notifies the auth plugin.
4060   * Also unenrols user from all roles and does other cleanup.
4061   *
4062   * Any plugin that needs to purge user data should register the 'user_deleted' event.
4063   *
4064   * @param stdClass $user full user object before delete
4065   * @return boolean success
4066   * @throws coding_exception if invalid $user parameter detected
4067   */
4068  function delete_user(stdClass $user) {
4069      global $CFG, $DB, $SESSION;
4070      require_once($CFG->libdir.'/grouplib.php');
4071      require_once($CFG->libdir.'/gradelib.php');
4072      require_once($CFG->dirroot.'/message/lib.php');
4073      require_once($CFG->dirroot.'/user/lib.php');
4074  
4075      // Make sure nobody sends bogus record type as parameter.
4076      if (!property_exists($user, 'id') or !property_exists($user, 'username')) {
4077          throw new coding_exception('Invalid $user parameter in delete_user() detected');
4078      }
4079  
4080      // Better not trust the parameter and fetch the latest info this will be very expensive anyway.
4081      if (!$user = $DB->get_record('user', array('id' => $user->id))) {
4082          debugging('Attempt to delete unknown user account.');
4083          return false;
4084      }
4085  
4086      // There must be always exactly one guest record, originally the guest account was identified by username only,
4087      // now we use $CFG->siteguest for performance reasons.
4088      if ($user->username === 'guest' or isguestuser($user)) {
4089          debugging('Guest user account can not be deleted.');
4090          return false;
4091      }
4092  
4093      // Admin can be theoretically from different auth plugin, but we want to prevent deletion of internal accoutns only,
4094      // if anything goes wrong ppl may force somebody to be admin via config.php setting $CFG->siteadmins.
4095      if ($user->auth === 'manual' and is_siteadmin($user)) {
4096          debugging('Local administrator accounts can not be deleted.');
4097          return false;
4098      }
4099  
4100      // Allow plugins to use this user object before we completely delete it.
4101      if ($pluginsfunction = get_plugins_with_function('pre_user_delete')) {
4102          foreach ($pluginsfunction as $plugintype => $plugins) {
4103              foreach ($plugins as $pluginfunction) {
4104                  $pluginfunction($user);
4105              }
4106          }
4107      }
4108  
4109      // Keep user record before updating it, as we have to pass this to user_deleted event.
4110      $olduser = clone $user;
4111  
4112      // Keep a copy of user context, we need it for event.
4113      $usercontext = context_user::instance($user->id);
4114  
4115      // Delete all grades - backup is kept in grade_grades_history table.
4116      grade_user_delete($user->id);
4117  
4118      // TODO: remove from cohorts using standard API here.
4119  
4120      // Remove user tags.
4121      core_tag_tag::remove_all_item_tags('core', 'user', $user->id);
4122  
4123      // Unconditionally unenrol from all courses.
4124      enrol_user_delete($user);
4125  
4126      // Unenrol from all roles in all contexts.
4127      // This might be slow but it is really needed - modules might do some extra cleanup!
4128      role_unassign_all(array('userid' => $user->id));
4129  
4130      // Notify the competency subsystem.
4131      \core_competency\api::hook_user_deleted($user->id);
4132  
4133      // Now do a brute force cleanup.
4134  
4135      // Delete all user events and subscription events.
4136      $DB->delete_records_select('event', 'userid = :userid AND subscriptionid IS NOT NULL', ['userid' => $user->id]);
4137  
4138      // Now, delete all calendar subscription from the user.
4139      $DB->delete_records('event_subscriptions', ['userid' => $user->id]);
4140  
4141      // Remove from all cohorts.
4142      $DB->delete_records('cohort_members', array('userid' => $user->id));
4143  
4144      // Remove from all groups.
4145      $DB->delete_records('groups_members', array('userid' => $user->id));
4146  
4147      // Brute force unenrol from all courses.
4148      $DB->delete_records('user_enrolments', array('userid' => $user->id));
4149  
4150      // Purge user preferences.
4151      $DB->delete_records('user_preferences', array('userid' => $user->id));
4152  
4153      // Purge user extra profile info.
4154      $DB->delete_records('user_info_data', array('userid' => $user->id));
4155  
4156      // Purge log of previous password hashes.
4157      $DB->delete_records('user_password_history', array('userid' => $user->id));
4158  
4159      // Last course access not necessary either.
4160      $DB->delete_records('user_lastaccess', array('userid' => $user->id));
4161      // Remove all user tokens.
4162      $DB->delete_records('external_tokens', array('userid' => $user->id));
4163  
4164      // Unauthorise the user for all services.
4165      $DB->delete_records('external_services_users', array('userid' => $user->id));
4166  
4167      // Remove users private keys.
4168      $DB->delete_records('user_private_key', array('userid' => $user->id));
4169  
4170      // Remove users customised pages.
4171      $DB->delete_records('my_pages', array('userid' => $user->id, 'private' => 1));
4172  
4173      // Remove user's oauth2 refresh tokens, if present.
4174      $DB->delete_records('oauth2_refresh_token', array('userid' => $user->id));
4175  
4176      // Delete user from $SESSION->bulk_users.
4177      if (isset($SESSION->bulk_users[$user->id])) {
4178          unset($SESSION->bulk_users[$user->id]);
4179      }
4180  
4181      // Force logout - may fail if file based sessions used, sorry.
4182      \core\session\manager::kill_user_sessions($user->id);
4183  
4184      // Generate username from email address, or a fake email.
4185      $delemail = !empty($user->email) ? $user->email : $user->username . '.' . $user->id . '@unknownemail.invalid';
4186  
4187      $deltime = time();
4188      $deltimelength = core_text::strlen((string) $deltime);
4189  
4190      // Max username length is 100 chars. Select up to limit - (length of current time + 1 [period character]) from users email.
4191      $delname = clean_param($delemail, PARAM_USERNAME);
4192      $delname = core_text::substr($delname, 0, 100 - ($deltimelength + 1)) . ".{$deltime}";
4193  
4194      // Workaround for bulk deletes of users with the same email address.
4195      while ($DB->record_exists('user', array('username' => $delname))) { // No need to use mnethostid here.
4196          $delname++;
4197      }
4198  
4199      // Mark internal user record as "deleted".
4200      $updateuser = new stdClass();
4201      $updateuser->id           = $user->id;
4202      $updateuser->deleted      = 1;
4203      $updateuser->username     = $delname;            // Remember it just in case.
4204      $updateuser->email        = md5($user->username);// Store hash of username, useful importing/restoring users.
4205      $updateuser->idnumber     = '';                  // Clear this field to free it up.
4206      $updateuser->picture      = 0;
4207      $updateuser->timemodified = $deltime;
4208  
4209      // Don't trigger update event, as user is being deleted.
4210      user_update_user($updateuser, false, false);
4211  
4212      // Delete all content associated with the user context, but not the context itself.
4213      $usercontext->delete_content();
4214  
4215      // Delete any search data.
4216      \core_search\manager::context_deleted($usercontext);
4217  
4218      // Any plugin that needs to cleanup should register this event.
4219      // Trigger event.
4220      $event = \core\event\user_deleted::create(
4221              array(
4222                  'objectid' => $user->id,
4223                  'relateduserid' => $user->id,
4224                  'context' => $usercontext,
4225                  'other' => array(
4226                      'username' => $user->username,
4227                      'email' => $user->email,
4228                      'idnumber' => $user->idnumber,
4229                      'picture' => $user->picture,
4230                      'mnethostid' => $user->mnethostid
4231                      )
4232                  )
4233              );
4234      $event->add_record_snapshot('user', $olduser);
4235      $event->trigger();
4236  
4237      // We will update the user's timemodified, as it will be passed to the user_deleted event, which
4238      // should know about this updated property persisted to the user's table.
4239      $user->timemodified = $updateuser->timemodified;
4240  
4241      // Notify auth plugin - do not block the delete even when plugin fails.
4242      $authplugin = get_auth_plugin($user->auth);
4243      $authplugin->user_delete($user);
4244  
4245      return true;
4246  }
4247  
4248  /**
4249   * Retrieve the guest user object.
4250   *
4251   * @return stdClass A {@link $USER} object
4252   */
4253  function guest_user() {
4254      global $CFG, $DB;
4255  
4256      if ($newuser = $DB->get_record('user', array('id' => $CFG->siteguest))) {
4257          $newuser->confirmed = 1;
4258          $newuser->lang = get_newuser_language();
4259          $newuser->lastip = getremoteaddr();
4260      }
4261  
4262      return $newuser;
4263  }
4264  
4265  /**
4266   * Authenticates a user against the chosen authentication mechanism
4267   *
4268   * Given a username and password, this function looks them
4269   * up using the currently selected authentication mechanism,
4270   * and if the authentication is successful, it returns a
4271   * valid $user object from the 'user' table.
4272   *
4273   * Uses auth_ functions from the currently active auth module
4274   *
4275   * After authenticate_user_login() returns success, you will need to
4276   * log that the user has logged in, and call complete_user_login() to set
4277   * the session up.
4278   *
4279   * Note: this function works only with non-mnet accounts!
4280   *
4281   * @param string $username  User's username (or also email if $CFG->authloginviaemail enabled)
4282   * @param string $password  User's password
4283   * @param bool $ignorelockout useful when guessing is prevented by other mechanism such as captcha or SSO
4284   * @param int $failurereason login failure reason, can be used in renderers (it may disclose if account exists)
4285   * @param mixed logintoken If this is set to a string it is validated against the login token for the session.
4286   * @return stdClass|false A {@link $USER} object or false if error
4287   */
4288  function authenticate_user_login($username, $password, $ignorelockout=false, &$failurereason=null, $logintoken=false) {
4289      global $CFG, $DB, $PAGE;
4290      require_once("$CFG->libdir/authlib.php");
4291  
4292      if ($user = get_complete_user_data('username', $username, $CFG->mnet_localhost_id)) {
4293          // we have found the user
4294  
4295      } else if (!empty($CFG->authloginviaemail)) {
4296          if ($email = clean_param($username, PARAM_EMAIL)) {
4297              $select = "mnethostid = :mnethostid AND LOWER(email) = LOWER(:email) AND deleted = 0";
4298              $params = array('mnethostid' => $CFG->mnet_localhost_id, 'email' => $email);
4299              $users = $DB->get_records_select('user', $select, $params, 'id', 'id', 0, 2);
4300              if (count($users) === 1) {
4301                  // Use email for login only if unique.
4302                  $user = reset($users);
4303                  $user = get_complete_user_data('id', $user->id);
4304                  $username = $user->username;
4305              }
4306              unset($users);
4307          }
4308      }
4309  
4310      // Make sure this request came from the login form.
4311      if (!\core\session\manager::validate_login_token($logintoken)) {
4312          $failurereason = AUTH_LOGIN_FAILED;
4313  
4314          // Trigger login failed event (specifying the ID of the found user, if available).
4315          \core\event\user_login_failed::create([
4316              'userid' => ($user->id ?? 0),
4317              'other' => [
4318                  'username' => $username,
4319                  'reason' => $failurereason,
4320              ],
4321          ])->trigger();
4322  
4323          error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Invalid Login Token:  $username  ".$_SERVER['HTTP_USER_AGENT']);
4324          return false;
4325      }
4326  
4327      $authsenabled = get_enabled_auth_plugins();
4328  
4329      if ($user) {
4330          // Use manual if auth not set.
4331          $auth = empty($user->auth) ? 'manual' : $user->auth;
4332  
4333          if (in_array($user->auth, $authsenabled)) {
4334              $authplugin = get_auth_plugin($user->auth);
4335              $authplugin->pre_user_login_hook($user);
4336          }
4337  
4338          if (!empty($user->suspended)) {
4339              $failurereason = AUTH_LOGIN_SUSPENDED;
4340  
4341              // Trigger login failed event.
4342              $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4343                      'other' => array('username' => $username, 'reason' => $failurereason)));
4344              $event->trigger();
4345              error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Suspended Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
4346              return false;
4347          }
4348          if ($auth=='nologin' or !is_enabled_auth($auth)) {
4349              // Legacy way to suspend user.
4350              $failurereason = AUTH_LOGIN_SUSPENDED;
4351  
4352              // Trigger login failed event.
4353              $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4354                      'other' => array('username' => $username, 'reason' => $failurereason)));
4355              $event->trigger();
4356              error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Disabled Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
4357              return false;
4358          }
4359          $auths = array($auth);
4360  
4361      } else {
4362          // Check if there's a deleted record (cheaply), this should not happen because we mangle usernames in delete_user().
4363          if ($DB->get_field('user', 'id', array('username' => $username, 'mnethostid' => $CFG->mnet_localhost_id,  'deleted' => 1))) {
4364              $failurereason = AUTH_LOGIN_NOUSER;
4365  
4366              // Trigger login failed event.
4367              $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4368                      'reason' => $failurereason)));
4369              $event->trigger();
4370              error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Deleted Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
4371              return false;
4372          }
4373  
4374          // User does not exist.
4375          $auths = $authsenabled;
4376          $user = new stdClass();
4377          $user->id = 0;
4378      }