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      }
4379  
4380      if ($ignorelockout) {
4381          // Some other mechanism protects against brute force password guessing, for example login form might include reCAPTCHA
4382          // or this function is called from a SSO script.
4383      } else if ($user->id) {
4384          // Verify login lockout after other ways that may prevent user login.
4385          if (login_is_lockedout($user)) {
4386              $failurereason = AUTH_LOGIN_LOCKOUT;
4387  
4388              // Trigger login failed event.
4389              $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4390                      'other' => array('username' => $username, 'reason' => $failurereason)));
4391              $event->trigger();
4392  
4393              error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Login lockout:  $username  ".$_SERVER['HTTP_USER_AGENT']);
4394              return false;
4395          }
4396      } else {
4397          // We can not lockout non-existing accounts.
4398      }
4399  
4400      foreach ($auths as $auth) {
4401          $authplugin = get_auth_plugin($auth);
4402  
4403          // On auth fail fall through to the next plugin.
4404          if (!$authplugin->user_login($username, $password)) {
4405              continue;
4406          }
4407  
4408          // Before performing login actions, check if user still passes password policy, if admin setting is enabled.
4409          if (!empty($CFG->passwordpolicycheckonlogin)) {
4410              $errmsg = '';
4411              $passed = check_password_policy($password, $errmsg, $user);
4412              if (!$passed) {
4413                  // First trigger event for failure.
4414                  $failedevent = \core\event\user_password_policy_failed::create_from_user($user);
4415                  $failedevent->trigger();
4416  
4417                  // If able to change password, set flag and move on.
4418                  if ($authplugin->can_change_password()) {
4419                      // Check if we are on internal change password page, or service is external, don't show notification.
4420                      $internalchangeurl = new moodle_url('/login/change_password.php');
4421                      if (!($PAGE->has_set_url() && $internalchangeurl->compare($PAGE->url)) && $authplugin->is_internal()) {
4422                          \core\notification::error(get_string('passwordpolicynomatch', '', $errmsg));
4423                      }
4424                      set_user_preference('auth_forcepasswordchange', 1, $user);
4425                  } else if ($authplugin->can_reset_password()) {
4426                      // Else force a reset if possible.
4427                      \core\notification::error(get_string('forcepasswordresetnotice', '', $errmsg));
4428                      redirect(new moodle_url('/login/forgot_password.php'));
4429                  } else {
4430                      $notifymsg = get_string('forcepasswordresetfailurenotice', '', $errmsg);
4431                      // If support page is set, add link for help.
4432                      if (!empty($CFG->supportpage)) {
4433                          $link = \html_writer::link($CFG->supportpage, $CFG->supportpage);
4434                          $link = \html_writer::tag('p', $link);
4435                          $notifymsg .= $link;
4436                      }
4437  
4438                      // If no change or reset is possible, add a notification for user.
4439                      \core\notification::error($notifymsg);
4440                  }
4441              }
4442          }
4443  
4444          // Successful authentication.
4445          if ($user->id) {
4446              // User already exists in database.
4447              if (empty($user->auth)) {
4448                  // For some reason auth isn't set yet.
4449                  $DB->set_field('user', 'auth', $auth, array('id' => $user->id));
4450                  $user->auth = $auth;
4451              }
4452  
4453              // If the existing hash is using an out-of-date algorithm (or the legacy md5 algorithm), then we should update to
4454              // the current hash algorithm while we have access to the user's password.
4455              update_internal_user_password($user, $password);
4456  
4457              if ($authplugin->is_synchronised_with_external()) {
4458                  // Update user record from external DB.
4459                  $user = update_user_record_by_id($user->id);
4460              }
4461          } else {
4462              // The user is authenticated but user creation may be disabled.
4463              if (!empty($CFG->authpreventaccountcreation)) {
4464                  $failurereason = AUTH_LOGIN_UNAUTHORISED;
4465  
4466                  // Trigger login failed event.
4467                  $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4468                          'reason' => $failurereason)));
4469                  $event->trigger();
4470  
4471                  error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Unknown user, can not create new accounts:  $username  ".
4472                          $_SERVER['HTTP_USER_AGENT']);
4473                  return false;
4474              } else {
4475                  $user = create_user_record($username, $password, $auth);
4476              }
4477          }
4478  
4479          $authplugin->sync_roles($user);
4480  
4481          foreach ($authsenabled as $hau) {
4482              $hauth = get_auth_plugin($hau);
4483              $hauth->user_authenticated_hook($user, $username, $password);
4484          }
4485  
4486          if (empty($user->id)) {
4487              $failurereason = AUTH_LOGIN_NOUSER;
4488              // Trigger login failed event.
4489              $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4490                      'reason' => $failurereason)));
4491              $event->trigger();
4492              return false;
4493          }
4494  
4495          if (!empty($user->suspended)) {
4496              // Just in case some auth plugin suspended account.
4497              $failurereason = AUTH_LOGIN_SUSPENDED;
4498              // Trigger login failed event.
4499              $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4500                      'other' => array('username' => $username, 'reason' => $failurereason)));
4501              $event->trigger();
4502              error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Suspended Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
4503              return false;
4504          }
4505  
4506          login_attempt_valid($user);
4507          $failurereason = AUTH_LOGIN_OK;
4508          return $user;
4509      }
4510  
4511      // Failed if all the plugins have failed.
4512      if (debugging('', DEBUG_ALL)) {
4513          error_log('[client '.getremoteaddr()."]  $CFG->wwwroot  Failed Login:  $username  ".$_SERVER['HTTP_USER_AGENT']);
4514      }
4515  
4516      if ($user->id) {
4517          login_attempt_failed($user);
4518          $failurereason = AUTH_LOGIN_FAILED;
4519          // Trigger login failed event.
4520          $event = \core\event\user_login_failed::create(array('userid' => $user->id,
4521                  'other' => array('username' => $username, 'reason' => $failurereason)));
4522          $event->trigger();
4523      } else {
4524          $failurereason = AUTH_LOGIN_NOUSER;
4525          // Trigger login failed event.
4526          $event = \core\event\user_login_failed::create(array('other' => array('username' => $username,
4527                  'reason' => $failurereason)));
4528          $event->trigger();
4529      }
4530  
4531      return false;
4532  }
4533  
4534  /**
4535   * Call to complete the user login process after authenticate_user_login()
4536   * has succeeded. It will setup the $USER variable and other required bits
4537   * and pieces.
4538   *
4539   * NOTE:
4540   * - It will NOT log anything -- up to the caller to decide what to log.
4541   * - this function does not set any cookies any more!
4542   *
4543   * @param stdClass $user
4544   * @return stdClass A {@link $USER} object - BC only, do not use
4545   */
4546  function complete_user_login($user) {
4547      global $CFG, $DB, $USER, $SESSION;
4548  
4549      \core\session\manager::login_user($user);
4550  
4551      // Reload preferences from DB.
4552      unset($USER->preference);
4553      check_user_preferences_loaded($USER);
4554  
4555      // Update login times.
4556      update_user_login_times();
4557  
4558      // Extra session prefs init.
4559      set_login_session_preferences();
4560  
4561      // Trigger login event.
4562      $event = \core\event\user_loggedin::create(
4563          array(
4564              'userid' => $USER->id,
4565              'objectid' => $USER->id,
4566              'other' => array('username' => $USER->username),
4567          )
4568      );
4569      $event->trigger();
4570  
4571      // Queue migrating the messaging data, if we need to.
4572      if (!get_user_preferences('core_message_migrate_data', false, $USER->id)) {
4573          // Check if there are any legacy messages to migrate.
4574          if (\core_message\helper::legacy_messages_exist($USER->id)) {
4575              \core_message\task\migrate_message_data::queue_task($USER->id);
4576          } else {
4577              set_user_preference('core_message_migrate_data', true, $USER->id);
4578          }
4579      }
4580  
4581      if (isguestuser()) {
4582          // No need to continue when user is THE guest.
4583          return $USER;
4584      }
4585  
4586      if (CLI_SCRIPT) {
4587          // We can redirect to password change URL only in browser.
4588          return $USER;
4589      }
4590  
4591      // Select password change url.
4592      $userauth = get_auth_plugin($USER->auth);
4593  
4594      // Check whether the user should be changing password.
4595      if (get_user_preferences('auth_forcepasswordchange', false)) {
4596          if ($userauth->can_change_password()) {
4597              if ($changeurl = $userauth->change_password_url()) {
4598                  redirect($changeurl);
4599              } else {
4600                  require_once($CFG->dirroot . '/login/lib.php');
4601                  $SESSION->wantsurl = core_login_get_return_url();
4602                  redirect($CFG->wwwroot.'/login/change_password.php');
4603              }
4604          } else {
4605              print_error('nopasswordchangeforced', 'auth');
4606          }
4607      }
4608      return $USER;
4609  }
4610  
4611  /**
4612   * Check a password hash to see if it was hashed using the legacy hash algorithm (md5).
4613   *
4614   * @param string $password String to check.
4615   * @return boolean True if the $password matches the format of an md5 sum.
4616   */
4617  function password_is_legacy_hash($password) {
4618      return (bool) preg_match('/^[0-9a-f]{32}$/', $password);
4619  }
4620  
4621  /**
4622   * Compare password against hash stored in user object to determine if it is valid.
4623   *
4624   * If necessary it also updates the stored hash to the current format.
4625   *
4626   * @param stdClass $user (Password property may be updated).
4627   * @param string $password Plain text password.
4628   * @return bool True if password is valid.
4629   */
4630  function validate_internal_user_password($user, $password) {
4631      global $CFG;
4632  
4633      if ($user->password === AUTH_PASSWORD_NOT_CACHED) {
4634          // Internal password is not used at all, it can not validate.
4635          return false;
4636      }
4637  
4638      // If hash isn't a legacy (md5) hash, validate using the library function.
4639      if (!password_is_legacy_hash($user->password)) {
4640          return password_verify($password, $user->password);
4641      }
4642  
4643      // Otherwise we need to check for a legacy (md5) hash instead. If the hash
4644      // is valid we can then update it to the new algorithm.
4645  
4646      $sitesalt = isset($CFG->passwordsaltmain) ? $CFG->passwordsaltmain : '';
4647      $validated = false;
4648  
4649      if ($user->password === md5($password.$sitesalt)
4650              or $user->password === md5($password)
4651              or $user->password === md5(addslashes($password).$sitesalt)
4652              or $user->password === md5(addslashes($password))) {
4653          // Note: we are intentionally using the addslashes() here because we
4654          //       need to accept old password hashes of passwords with magic quotes.
4655          $validated = true;
4656  
4657      } else {
4658          for ($i=1; $i<=20; $i++) { // 20 alternative salts should be enough, right?
4659              $alt = 'passwordsaltalt'.$i;
4660              if (!empty($CFG->$alt)) {
4661                  if ($user->password === md5($password.$CFG->$alt) or $user->password === md5(addslashes($password).$CFG->$alt)) {
4662                      $validated = true;
4663                      break;
4664                  }
4665              }
4666          }
4667      }
4668  
4669      if ($validated) {
4670          // If the password matches the existing md5 hash, update to the
4671          // current hash algorithm while we have access to the user's password.
4672          update_internal_user_password($user, $password);
4673      }
4674  
4675      return $validated;
4676  }
4677  
4678  /**
4679   * Calculate hash for a plain text password.
4680   *
4681   * @param string $password Plain text password to be hashed.
4682   * @param bool $fasthash If true, use a low cost factor when generating the hash
4683   *                       This is much faster to generate but makes the hash
4684   *                       less secure. It is used when lots of hashes need to
4685   *                       be generated quickly.
4686   * @return string The hashed password.
4687   *
4688   * @throws moodle_exception If a problem occurs while generating the hash.
4689   */
4690  function hash_internal_user_password($password, $fasthash = false) {
4691      global $CFG;
4692  
4693      // Set the cost factor to 4 for fast hashing, otherwise use default cost.
4694      $options = ($fasthash) ? array('cost' => 4) : array();
4695  
4696      $generatedhash = password_hash($password, PASSWORD_DEFAULT, $options);
4697  
4698      if ($generatedhash === false || $generatedhash === null) {
4699          throw new moodle_exception('Failed to generate password hash.');
4700      }
4701  
4702      return $generatedhash;
4703  }
4704  
4705  /**
4706   * Update password hash in user object (if necessary).
4707   *
4708   * The password is updated if:
4709   * 1. The password has changed (the hash of $user->password is different
4710   *    to the hash of $password).
4711   * 2. The existing hash is using an out-of-date algorithm (or the legacy
4712   *    md5 algorithm).
4713   *
4714   * Updating the password will modify the $user object and the database
4715   * record to use the current hashing algorithm.
4716   * It will remove Web Services user tokens too.
4717   *
4718   * @param stdClass $user User object (password property may be updated).
4719   * @param string $password Plain text password.
4720   * @param bool $fasthash If true, use a low cost factor when generating the hash
4721   *                       This is much faster to generate but makes the hash
4722   *                       less secure. It is used when lots of hashes need to
4723   *                       be generated quickly.
4724   * @return bool Always returns true.
4725   */
4726  function update_internal_user_password($user, $password, $fasthash = false) {
4727      global $CFG, $DB;
4728  
4729      // Figure out what the hashed password should be.
4730      if (!isset($user->auth)) {
4731          debugging('User record in update_internal_user_password() must include field auth',
4732                  DEBUG_DEVELOPER);
4733          $user->auth = $DB->get_field('user', 'auth', array('id' => $user->id));
4734      }
4735      $authplugin = get_auth_plugin($user->auth);
4736      if ($authplugin->prevent_local_passwords()) {
4737          $hashedpassword = AUTH_PASSWORD_NOT_CACHED;
4738      } else {
4739          $hashedpassword = hash_internal_user_password($password, $fasthash);
4740      }
4741  
4742      $algorithmchanged = false;
4743  
4744      if ($hashedpassword === AUTH_PASSWORD_NOT_CACHED) {
4745          // Password is not cached, update it if not set to AUTH_PASSWORD_NOT_CACHED.
4746          $passwordchanged = ($user->password !== $hashedpassword);
4747  
4748      } else if (isset($user->password)) {
4749          // If verification fails then it means the password has changed.
4750          $passwordchanged = !password_verify($password, $user->password);
4751          $algorithmchanged = password_needs_rehash($user->password, PASSWORD_DEFAULT);
4752      } else {
4753          // While creating new user, password in unset in $user object, to avoid
4754          // saving it with user_create()
4755          $passwordchanged = true;
4756      }
4757  
4758      if ($passwordchanged || $algorithmchanged) {
4759          $DB->set_field('user', 'password',  $hashedpassword, array('id' => $user->id));
4760          $user->password = $hashedpassword;
4761  
4762          // Trigger event.
4763          $user = $DB->get_record('user', array('id' => $user->id));
4764          \core\event\user_password_updated::create_from_user($user)->trigger();
4765  
4766          // Remove WS user tokens.
4767          if (!empty($CFG->passwordchangetokendeletion)) {
4768              require_once($CFG->dirroot.'/webservice/lib.php');
4769              webservice::delete_user_ws_tokens($user->id);
4770          }
4771      }
4772  
4773      return true;
4774  }
4775  
4776  /**
4777   * Get a complete user record, which includes all the info in the user record.
4778   *
4779   * Intended for setting as $USER session variable
4780   *
4781   * @param string $field The user field to be checked for a given value.
4782   * @param string $value The value to match for $field.
4783   * @param int $mnethostid
4784   * @param bool $throwexception If true, it will throw an exception when there's no record found or when there are multiple records
4785   *                              found. Otherwise, it will just return false.
4786   * @return mixed False, or A {@link $USER} object.
4787   */
4788  function get_complete_user_data($field, $value, $mnethostid = null, $throwexception = false) {
4789      global $CFG, $DB;
4790  
4791      if (!$field || !$value) {
4792          return false;
4793      }
4794  
4795      // Change the field to lowercase.
4796      $field = core_text::strtolower($field);
4797  
4798      // List of case insensitive fields.
4799      $caseinsensitivefields = ['email'];
4800  
4801      // Username input is forced to lowercase and should be case sensitive.
4802      if ($field == 'username') {
4803          $value = core_text::strtolower($value);
4804      }
4805  
4806      // Build the WHERE clause for an SQL query.
4807      $params = array('fieldval' => $value);
4808  
4809      // Do a case-insensitive query, if necessary. These are generally very expensive. The performance can be improved on some DBs
4810      // such as MySQL by pre-filtering users with accent-insensitive subselect.
4811      if (in_array($field, $caseinsensitivefields)) {
4812          $fieldselect = $DB->sql_equal($field, ':fieldval', false);
4813          $idsubselect = $DB->sql_equal($field, ':fieldval2', false, false);
4814          $params['fieldval2'] = $value;
4815      } else {
4816          $fieldselect = "$field = :fieldval";
4817          $idsubselect = '';
4818      }
4819      $constraints = "$fieldselect AND deleted <> 1";
4820  
4821      // If we are loading user data based on anything other than id,
4822      // we must also restrict our search based on mnet host.
4823      if ($field != 'id') {
4824          if (empty($mnethostid)) {
4825              // If empty, we restrict to local users.
4826              $mnethostid = $CFG->mnet_localhost_id;
4827          }
4828      }
4829      if (!empty($mnethostid)) {
4830          $params['mnethostid'] = $mnethostid;
4831          $constraints .= " AND mnethostid = :mnethostid";
4832      }
4833  
4834      if ($idsubselect) {
4835          $constraints .= " AND id IN (SELECT id FROM {user} WHERE {$idsubselect})";
4836      }
4837  
4838      // Get all the basic user data.
4839      try {
4840          // Make sure that there's only a single record that matches our query.
4841          // For example, when fetching by email, multiple records might match the query as there's no guarantee that email addresses
4842          // are unique. Therefore we can't reliably tell whether the user profile data that we're fetching is the correct one.
4843          $user = $DB->get_record_select('user', $constraints, $params, '*', MUST_EXIST);
4844      } catch (dml_exception $exception) {
4845          if ($throwexception) {
4846              throw $exception;
4847          } else {
4848              // Return false when no records or multiple records were found.
4849              return false;
4850          }
4851      }
4852  
4853      // Get various settings and preferences.
4854  
4855      // Preload preference cache.
4856      check_user_preferences_loaded($user);
4857  
4858      // Load course enrolment related stuff.
4859      $user->lastcourseaccess    = array(); // During last session.
4860      $user->currentcourseaccess = array(); // During current session.
4861      if ($lastaccesses = $DB->get_records('user_lastaccess', array('userid' => $user->id))) {
4862          foreach ($lastaccesses as $lastaccess) {
4863              $user->lastcourseaccess[$lastaccess->courseid] = $lastaccess->timeaccess;
4864          }
4865      }
4866  
4867      $sql = "SELECT g.id, g.courseid
4868                FROM {groups} g, {groups_members} gm
4869               WHERE gm.groupid=g.id AND gm.userid=?";
4870  
4871      // This is a special hack to speedup calendar display.
4872      $user->groupmember = array();
4873      if (!isguestuser($user)) {
4874          if ($groups = $DB->get_records_sql($sql, array($user->id))) {
4875              foreach ($groups as $group) {
4876                  if (!array_key_exists($group->courseid, $user->groupmember)) {
4877                      $user->groupmember[$group->courseid] = array();
4878                  }
4879                  $user->groupmember[$group->courseid][$group->id] = $group->id;
4880              }
4881          }
4882      }
4883  
4884      // Add cohort theme.
4885      if (!empty($CFG->allowcohortthemes)) {
4886          require_once($CFG->dirroot . '/cohort/lib.php');
4887          if ($cohorttheme = cohort_get_user_cohort_theme($user->id)) {
4888              $user->cohorttheme = $cohorttheme;
4889          }
4890      }
4891  
4892      // Add the custom profile fields to the user record.
4893      $user->profile = array();
4894      if (!isguestuser($user)) {
4895          require_once($CFG->dirroot.'/user/profile/lib.php');
4896          profile_load_custom_fields($user);
4897      }
4898  
4899      // Rewrite some variables if necessary.
4900      if (!empty($user->description)) {
4901          // No need to cart all of it around.
4902          $user->description = true;
4903      }
4904      if (isguestuser($user)) {
4905          // Guest language always same as site.
4906          $user->lang = get_newuser_language();
4907          // Name always in current language.
4908          $user->firstname = get_string('guestuser');
4909          $user->lastname = ' ';
4910      }
4911  
4912      return $user;
4913  }
4914  
4915  /**
4916   * Validate a password against the configured password policy
4917   *
4918   * @param string $password the password to be checked against the password policy
4919   * @param string $errmsg the error message to display when the password doesn't comply with the policy.
4920   * @param stdClass $user the user object to perform password validation against. Defaults to null if not provided.
4921   *
4922   * @return bool true if the password is valid according to the policy. false otherwise.
4923   */
4924  function check_password_policy($password, &$errmsg, $user = null) {
4925      global $CFG;
4926  
4927      if (!empty($CFG->passwordpolicy)) {
4928          $errmsg = '';
4929          if (core_text::strlen($password) < $CFG->minpasswordlength) {
4930              $errmsg .= '<div>'. get_string('errorminpasswordlength', 'auth', $CFG->minpasswordlength) .'</div>';
4931          }
4932          if (preg_match_all('/[[:digit:]]/u', $password, $matches) < $CFG->minpassworddigits) {
4933              $errmsg .= '<div>'. get_string('errorminpassworddigits', 'auth', $CFG->minpassworddigits) .'</div>';
4934          }
4935          if (preg_match_all('/[[:lower:]]/u', $password, $matches) < $CFG->minpasswordlower) {
4936              $errmsg .= '<div>'. get_string('errorminpasswordlower', 'auth', $CFG->minpasswordlower) .'</div>';
4937          }
4938          if (preg_match_all('/[[:upper:]]/u', $password, $matches) < $CFG->minpasswordupper) {
4939              $errmsg .= '<div>'. get_string('errorminpasswordupper', 'auth', $CFG->minpasswordupper) .'</div>';
4940          }
4941          if (preg_match_all('/[^[:upper:][:lower:][:digit:]]/u', $password, $matches) < $CFG->minpasswordnonalphanum) {
4942              $errmsg .= '<div>'. get_string('errorminpasswordnonalphanum', 'auth', $CFG->minpasswordnonalphanum) .'</div>';
4943          }
4944          if (!check_consecutive_identical_characters($password, $CFG->maxconsecutiveidentchars)) {
4945              $errmsg .= '<div>'. get_string('errormaxconsecutiveidentchars', 'auth', $CFG->maxconsecutiveidentchars) .'</div>';
4946          }
4947  
4948          // Fire any additional password policy functions from plugins.
4949          // Plugin functions should output an error message string or empty string for success.
4950          $pluginsfunction = get_plugins_with_function('check_password_policy');
4951          foreach ($pluginsfunction as $plugintype => $plugins) {
4952              foreach ($plugins as $pluginfunction) {
4953                  $pluginerr = $pluginfunction($password, $user);
4954                  if ($pluginerr) {
4955                      $errmsg .= '<div>'. $pluginerr .'</div>';
4956                  }
4957              }
4958          }
4959      }
4960  
4961      if ($errmsg == '') {
4962          return true;
4963      } else {
4964          return false;
4965      }
4966  }
4967  
4968  
4969  /**
4970   * When logging in, this function is run to set certain preferences for the current SESSION.
4971   */
4972  function set_login_session_preferences() {
4973      global $SESSION;
4974  
4975      $SESSION->justloggedin = true;
4976  
4977      unset($SESSION->lang);
4978      unset($SESSION->forcelang);
4979      unset($SESSION->load_navigation_admin);
4980  }
4981  
4982  
4983  /**
4984   * Delete a course, including all related data from the database, and any associated files.
4985   *
4986   * @param mixed $courseorid The id of the course or course object to delete.
4987   * @param bool $showfeedback Whether to display notifications of each action the function performs.
4988   * @return bool true if all the removals succeeded. false if there were any failures. If this
4989   *             method returns false, some of the removals will probably have succeeded, and others
4990   *             failed, but you have no way of knowing which.
4991   */
4992  function delete_course($courseorid, $showfeedback = true) {
4993      global $DB;
4994  
4995      if (is_object($courseorid)) {
4996          $courseid = $courseorid->id;
4997          $course   = $courseorid;
4998      } else {
4999          $courseid = $courseorid;
5000          if (!$course = $DB->get_record('course', array('id' => $courseid))) {
5001              return false;
5002          }
5003      }
5004      $context = context_course::instance($courseid);
5005  
5006      // Frontpage course can not be deleted!!
5007      if ($courseid == SITEID) {
5008          return false;
5009      }
5010  
5011      // Allow plugins to use this course before we completely delete it.
5012      if ($pluginsfunction = get_plugins_with_function('pre_course_delete')) {
5013          foreach ($pluginsfunction as $plugintype => $plugins) {
5014              foreach ($plugins as $pluginfunction) {
5015                  $pluginfunction($course);
5016              }
5017          }
5018      }
5019  
5020      // Tell the search manager we are about to delete a course. This prevents us sending updates
5021      // for each individual context being deleted.
5022      \core_search\manager::course_deleting_start($courseid);
5023  
5024      $handler = core_course\customfield\course_handler::create();
5025      $handler->delete_instance($courseid);
5026  
5027      // Make the course completely empty.
5028      remove_course_contents($courseid, $showfeedback);
5029  
5030      // Delete the course and related context instance.
5031      context_helper::delete_instance(CONTEXT_COURSE, $courseid);
5032  
5033      $DB->delete_records("course", array("id" => $courseid));
5034      $DB->delete_records("course_format_options", array("courseid" => $courseid));
5035  
5036      // Reset all course related caches here.
5037      if (class_exists('format_base', false)) {
5038          format_base::reset_course_cache($courseid);
5039      }
5040  
5041      // Tell search that we have deleted the course so it can delete course data from the index.
5042      \core_search\manager::course_deleting_finish($courseid);
5043  
5044      // Trigger a course deleted event.
5045      $event = \core\event\course_deleted::create(array(
5046          'objectid' => $course->id,
5047          'context' => $context,
5048          'other' => array(
5049              'shortname' => $course->shortname,
5050              'fullname' => $course->fullname,
5051              'idnumber' => $course->idnumber
5052              )
5053      ));
5054      $event->add_record_snapshot('course', $course);
5055      $event->trigger();
5056  
5057      return true;
5058  }
5059  
5060  /**
5061   * Clear a course out completely, deleting all content but don't delete the course itself.
5062   *
5063   * This function does not verify any permissions.
5064   *
5065   * Please note this function also deletes all user enrolments,
5066   * enrolment instances and role assignments by default.
5067   *
5068   * $options:
5069   *  - 'keep_roles_and_enrolments' - false by default
5070   *  - 'keep_groups_and_groupings' - false by default
5071   *
5072   * @param int $courseid The id of the course that is being deleted
5073   * @param bool $showfeedback Whether to display notifications of each action the function performs.
5074   * @param array $options extra options
5075   * @return bool true if all the removals succeeded. false if there were any failures. If this
5076   *             method returns false, some of the removals will probably have succeeded, and others
5077   *             failed, but you have no way of knowing which.
5078   */
5079  function remove_course_contents($courseid, $showfeedback = true, array $options = null) {
5080      global $CFG, $DB, $OUTPUT;
5081  
5082      require_once($CFG->libdir.'/badgeslib.php');
5083      require_once($CFG->libdir.'/completionlib.php');
5084      require_once($CFG->libdir.'/questionlib.php');
5085      require_once($CFG->libdir.'/gradelib.php');
5086      require_once($CFG->dirroot.'/group/lib.php');
5087      require_once($CFG->dirroot.'/comment/lib.php');
5088      require_once($CFG->dirroot.'/rating/lib.php');
5089      require_once($CFG->dirroot.'/notes/lib.php');
5090  
5091      // Handle course badges.
5092      badges_handle_course_deletion($courseid);
5093  
5094      // NOTE: these concatenated strings are suboptimal, but it is just extra info...
5095      $strdeleted = get_string('deleted').' - ';
5096  
5097      // Some crazy wishlist of stuff we should skip during purging of course content.
5098      $options = (array)$options;
5099  
5100      $course = $DB->get_record('course', array('id' => $courseid), '*', MUST_EXIST);
5101      $coursecontext = context_course::instance($courseid);
5102      $fs = get_file_storage();
5103  
5104      // Delete course completion information, this has to be done before grades and enrols.
5105      $cc = new completion_info($course);
5106      $cc->clear_criteria();
5107      if ($showfeedback) {
5108          echo $OUTPUT->notification($strdeleted.get_string('completion', 'completion'), 'notifysuccess');
5109      }
5110  
5111      // Remove all data from gradebook - this needs to be done before course modules
5112      // because while deleting this information, the system may need to reference
5113      // the course modules that own the grades.
5114      remove_course_grades($courseid, $showfeedback);
5115      remove_grade_letters($coursecontext, $showfeedback);
5116  
5117      // Delete course blocks in any all child contexts,
5118      // they may depend on modules so delete them first.
5119      $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5120      foreach ($childcontexts as $childcontext) {
5121          blocks_delete_all_for_context($childcontext->id);
5122      }
5123      unset($childcontexts);
5124      blocks_delete_all_for_context($coursecontext->id);
5125      if ($showfeedback) {
5126          echo $OUTPUT->notification($strdeleted.get_string('type_block_plural', 'plugin'), 'notifysuccess');
5127      }
5128  
5129      $DB->set_field('course_modules', 'deletioninprogress', '1', ['course' => $courseid]);
5130      rebuild_course_cache($courseid, true);
5131  
5132      // Get the list of all modules that are properly installed.
5133      $allmodules = $DB->get_records_menu('modules', array(), '', 'name, id');
5134  
5135      // Delete every instance of every module,
5136      // this has to be done before deleting of course level stuff.
5137      $locations = core_component::get_plugin_list('mod');
5138      foreach ($locations as $modname => $moddir) {
5139          if ($modname === 'NEWMODULE') {
5140              continue;
5141          }
5142          if (array_key_exists($modname, $allmodules)) {
5143              $sql = "SELECT cm.*, m.id AS modinstance, m.name, '$modname' AS modname
5144                FROM {".$modname."} m
5145                     LEFT JOIN {course_modules} cm ON cm.instance = m.id AND cm.module = :moduleid
5146               WHERE m.course = :courseid";
5147              $instances = $DB->get_records_sql($sql, array('courseid' => $course->id,
5148                  'modulename' => $modname, 'moduleid' => $allmodules[$modname]));
5149  
5150              include_once("$moddir/lib.php");                 // Shows php warning only if plugin defective.
5151              $moddelete = $modname .'_delete_instance';       // Delete everything connected to an instance.
5152  
5153              if ($instances) {
5154                  foreach ($instances as $cm) {
5155                      if ($cm->id) {
5156                          // Delete activity context questions and question categories.
5157                          question_delete_activity($cm);
5158                          // Notify the competency subsystem.
5159                          \core_competency\api::hook_course_module_deleted($cm);
5160  
5161                          // Delete all tag instances associated with the instance of this module.
5162                          core_tag_tag::delete_instances("mod_{$modname}", null, context_module::instance($cm->id)->id);
5163                          core_tag_tag::remove_all_item_tags('core', 'course_modules', $cm->id);
5164                      }
5165                      if (function_exists($moddelete)) {
5166                          // This purges all module data in related tables, extra user prefs, settings, etc.
5167                          $moddelete($cm->modinstance);
5168                      } else {
5169                          // NOTE: we should not allow installation of modules with missing delete support!
5170                          debugging("Defective module '$modname' detected when deleting course contents: missing function $moddelete()!");
5171                          $DB->delete_records($modname, array('id' => $cm->modinstance));
5172                      }
5173  
5174                      if ($cm->id) {
5175                          // Delete cm and its context - orphaned contexts are purged in cron in case of any race condition.
5176                          context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5177                          $DB->delete_records('course_modules_completion', ['coursemoduleid' => $cm->id]);
5178                          $DB->delete_records('course_modules', array('id' => $cm->id));
5179                          rebuild_course_cache($cm->course, true);
5180                      }
5181                  }
5182              }
5183              if ($instances and $showfeedback) {
5184                  echo $OUTPUT->notification($strdeleted.get_string('pluginname', $modname), 'notifysuccess');
5185              }
5186          } else {
5187              // Ooops, this module is not properly installed, force-delete it in the next block.
5188          }
5189      }
5190  
5191      // We have tried to delete everything the nice way - now let's force-delete any remaining module data.
5192  
5193      // Delete completion defaults.
5194      $DB->delete_records("course_completion_defaults", array("course" => $courseid));
5195  
5196      // Remove all data from availability and completion tables that is associated
5197      // with course-modules belonging to this course. Note this is done even if the
5198      // features are not enabled now, in case they were enabled previously.
5199      $DB->delete_records_subquery('course_modules_completion', 'coursemoduleid', 'id',
5200              'SELECT id from {course_modules} WHERE course = ?', [$courseid]);
5201  
5202      // Remove course-module data that has not been removed in modules' _delete_instance callbacks.
5203      $cms = $DB->get_records('course_modules', array('course' => $course->id));
5204      $allmodulesbyid = array_flip($allmodules);
5205      foreach ($cms as $cm) {
5206          if (array_key_exists($cm->module, $allmodulesbyid)) {
5207              try {
5208                  $DB->delete_records($allmodulesbyid[$cm->module], array('id' => $cm->instance));
5209              } catch (Exception $e) {
5210                  // Ignore weird or missing table problems.
5211              }
5212          }
5213          context_helper::delete_instance(CONTEXT_MODULE, $cm->id);
5214          $DB->delete_records('course_modules', array('id' => $cm->id));
5215          rebuild_course_cache($cm->course, true);
5216      }
5217  
5218      if ($showfeedback) {
5219          echo $OUTPUT->notification($strdeleted.get_string('type_mod_plural', 'plugin'), 'notifysuccess');
5220      }
5221  
5222      // Delete questions and question categories.
5223      question_delete_course($course);
5224      if ($showfeedback) {
5225          echo $OUTPUT->notification($strdeleted.get_string('questions', 'question'), 'notifysuccess');
5226      }
5227  
5228      // Delete content bank contents.
5229      $cb = new \core_contentbank\contentbank();
5230      $cbdeleted = $cb->delete_contents($coursecontext);
5231      if ($showfeedback && $cbdeleted) {
5232          echo $OUTPUT->notification($strdeleted.get_string('contentbank', 'contentbank'), 'notifysuccess');
5233      }
5234  
5235      // Make sure there are no subcontexts left - all valid blocks and modules should be already gone.
5236      $childcontexts = $coursecontext->get_child_contexts(); // Returns all subcontexts since 2.2.
5237      foreach ($childcontexts as $childcontext) {
5238          $childcontext->delete();
5239      }
5240      unset($childcontexts);
5241  
5242      // Remove roles and enrolments by default.
5243      if (empty($options['keep_roles_and_enrolments'])) {
5244          // This hack is used in restore when deleting contents of existing course.
5245          // During restore, we should remove only enrolment related data that the user performing the restore has a
5246          // permission to remove.
5247          $userid = $options['userid'] ?? null;
5248          enrol_course_delete($course, $userid);
5249          role_unassign_all(array('contextid' => $coursecontext->id, 'component' => ''), true);
5250          if ($showfeedback) {
5251              echo $OUTPUT->notification($strdeleted.get_string('type_enrol_plural', 'plugin'), 'notifysuccess');
5252          }
5253      }
5254  
5255      // Delete any groups, removing members and grouping/course links first.
5256      if (empty($options['keep_groups_and_groupings'])) {
5257          groups_delete_groupings($course->id, $showfeedback);
5258          groups_delete_groups($course->id, $showfeedback);
5259      }
5260  
5261      // Filters be gone!
5262      filter_delete_all_for_context($coursecontext->id);
5263  
5264      // Notes, you shall not pass!
5265      note_delete_all($course->id);
5266  
5267      // Die comments!
5268      comment::delete_comments($coursecontext->id);
5269  
5270      // Ratings are history too.
5271      $delopt = new stdclass();
5272      $delopt->contextid = $coursecontext->id;
5273      $rm = new rating_manager();
5274      $rm->delete_ratings($delopt);
5275  
5276      // Delete course tags.
5277      core_tag_tag::remove_all_item_tags('core', 'course', $course->id);
5278  
5279      // Notify the competency subsystem.
5280      \core_competency\api::hook_course_deleted($course);
5281  
5282      // Delete calendar events.
5283      $DB->delete_records('event', array('courseid' => $course->id));
5284      $fs->delete_area_files($coursecontext->id, 'calendar');
5285  
5286      // Delete all related records in other core tables that may have a courseid
5287      // This array stores the tables that need to be cleared, as
5288      // table_name => column_name that contains the course id.
5289      $tablestoclear = array(
5290          'backup_courses' => 'courseid',  // Scheduled backup stuff.
5291          'user_lastaccess' => 'courseid', // User access info.
5292      );
5293      foreach ($tablestoclear as $table => $col) {
5294          $DB->delete_records($table, array($col => $course->id));
5295      }
5296  
5297      // Delete all course backup files.
5298      $fs->delete_area_files($coursecontext->id, 'backup');
5299  
5300      // Cleanup course record - remove links to deleted stuff.
5301      $oldcourse = new stdClass();
5302      $oldcourse->id               = $course->id;
5303      $oldcourse->summary          = '';
5304      $oldcourse->cacherev         = 0;
5305      $oldcourse->legacyfiles      = 0;
5306      if (!empty($options['keep_groups_and_groupings'])) {
5307          $oldcourse->defaultgroupingid = 0;
5308      }
5309      $DB->update_record('course', $oldcourse);
5310  
5311      // Delete course sections.
5312      $DB->delete_records('course_sections', array('course' => $course->id));
5313  
5314      // Delete legacy, section and any other course files.
5315      $fs->delete_area_files($coursecontext->id, 'course'); // Files from summary and section.
5316  
5317      // Delete all remaining stuff linked to context such as files, comments, ratings, etc.
5318      if (empty($options['keep_roles_and_enrolments']) and empty($options['keep_groups_and_groupings'])) {
5319          // Easy, do not delete the context itself...
5320          $coursecontext->delete_content();
5321      } else {
5322          // Hack alert!!!!
5323          // We can not drop all context stuff because it would bork enrolments and roles,
5324          // there might be also files used by enrol plugins...
5325      }
5326  
5327      // Delete legacy files - just in case some files are still left there after conversion to new file api,
5328      // also some non-standard unsupported plugins may try to store something there.
5329      fulldelete($CFG->dataroot.'/'.$course->id);
5330  
5331      // Delete from cache to reduce the cache size especially makes sense in case of bulk course deletion.
5332      course_modinfo::purge_course_cache($courseid);
5333  
5334      // Trigger a course content deleted event.
5335      $event = \core\event\course_content_deleted::create(array(
5336          'objectid' => $course->id,
5337          'context' => $coursecontext,
5338          'other' => array('shortname' => $course->shortname,
5339                           'fullname' => $course->fullname,
5340                           'options' => $options) // Passing this for legacy reasons.
5341      ));
5342      $event->add_record_snapshot('course', $course);
5343      $event->trigger();
5344  
5345      return true;
5346  }
5347  
5348  /**
5349   * Change dates in module - used from course reset.
5350   *
5351   * @param string $modname forum, assignment, etc
5352   * @param array $fields array of date fields from mod table
5353   * @param int $timeshift time difference
5354   * @param int $courseid
5355   * @param int $modid (Optional) passed if specific mod instance in course needs to be updated.
5356   * @return bool success
5357   */
5358  function shift_course_mod_dates($modname, $fields, $timeshift, $courseid, $modid = 0) {
5359      global $CFG, $DB;
5360      include_once($CFG->dirroot.'/mod/'.$modname.'/lib.php');
5361  
5362      $return = true;
5363      $params = array($timeshift, $courseid);
5364      foreach ($fields as $field) {
5365          $updatesql = "UPDATE {".$modname."}
5366                            SET $field = $field + ?
5367                          WHERE course=? AND $field<>0";
5368          if ($modid) {
5369              $updatesql .= ' AND id=?';
5370              $params[] = $modid;
5371          }
5372          $return = $DB->execute($updatesql, $params) && $return;
5373      }
5374  
5375      return $return;
5376  }
5377  
5378  /**
5379   * This function will empty a course of user data.
5380   * It will retain the activities and the structure of the course.
5381   *
5382   * @param object $data an object containing all the settings including courseid (without magic quotes)
5383   * @return array status array of array component, item, error
5384   */
5385  function reset_course_userdata($data) {
5386      global $CFG, $DB;
5387      require_once($CFG->libdir.'/gradelib.php');
5388      require_once($CFG->libdir.'/completionlib.php');
5389      require_once($CFG->dirroot.'/completion/criteria/completion_criteria_date.php');
5390      require_once($CFG->dirroot.'/group/lib.php');
5391  
5392      $data->courseid = $data->id;
5393      $context = context_course::instance($data->courseid);
5394  
5395      $eventparams = array(
5396          'context' => $context,
5397          'courseid' => $data->id,
5398          'other' => array(
5399              'reset_options' => (array) $data
5400          )
5401      );
5402      $event = \core\event\course_reset_started::create($eventparams);
5403      $event->trigger();
5404  
5405      // Calculate the time shift of dates.
5406      if (!empty($data->reset_start_date)) {
5407          // Time part of course startdate should be zero.
5408          $data->timeshift = $data->reset_start_date - usergetmidnight($data->reset_start_date_old);
5409      } else {
5410          $data->timeshift = 0;
5411      }
5412  
5413      // Result array: component, item, error.
5414      $status = array();
5415  
5416      // Start the resetting.
5417      $componentstr = get_string('general');
5418  
5419      // Move the course start time.
5420      if (!empty($data->reset_start_date) and $data->timeshift) {
5421          // Change course start data.
5422          $DB->set_field('course', 'startdate', $data->reset_start_date, array('id' => $data->courseid));
5423          // Update all course and group events - do not move activity events.
5424          $updatesql = "UPDATE {event}
5425                           SET timestart = timestart + ?
5426                         WHERE courseid=? AND instance=0";
5427          $DB->execute($updatesql, array($data->timeshift, $data->courseid));
5428  
5429          // Update any date activity restrictions.
5430          if ($CFG->enableavailability) {
5431              \availability_date\condition::update_all_dates($data->courseid, $data->timeshift);
5432          }
5433  
5434          // Update completion expected dates.
5435          if ($CFG->enablecompletion) {
5436              $modinfo = get_fast_modinfo($data->courseid);
5437              $changed = false;
5438              foreach ($modinfo->get_cms() as $cm) {
5439                  if ($cm->completion && !empty($cm->completionexpected)) {
5440                      $DB->set_field('course_modules', 'completionexpected', $cm->completionexpected + $data->timeshift,
5441                          array('id' => $cm->id));
5442                      $changed = true;
5443                  }
5444              }
5445  
5446              // Clear course cache if changes made.
5447              if ($changed) {
5448                  rebuild_course_cache($data->courseid, true);
5449              }
5450  
5451              // Update course date completion criteria.
5452              \completion_criteria_date::update_date($data->courseid, $data->timeshift);
5453          }
5454  
5455          $status[] = array('component' => $componentstr, 'item' => get_string('datechanged'), 'error' => false);
5456      }
5457  
5458      if (!empty($data->reset_end_date)) {
5459          // If the user set a end date value respect it.
5460          $DB->set_field('course', 'enddate', $data->reset_end_date, array('id' => $data->courseid));
5461      } else if ($data->timeshift > 0 && $data->reset_end_date_old) {
5462          // If there is a time shift apply it to the end date as well.
5463          $enddate = $data->reset_end_date_old + $data->timeshift;
5464          $DB->set_field('course', 'enddate', $enddate, array('id' => $data->courseid));
5465      }
5466  
5467      if (!empty($data->reset_events)) {
5468          $DB->delete_records('event', array('courseid' => $data->courseid));
5469          $status[] = array('component' => $componentstr, 'item' => get_string('deleteevents', 'calendar'), 'error' => false);
5470      }
5471  
5472      if (!empty($data->reset_notes)) {
5473          require_once($CFG->dirroot.'/notes/lib.php');
5474          note_delete_all($data->courseid);
5475          $status[] = array('component' => $componentstr, 'item' => get_string('deletenotes', 'notes'), 'error' => false);
5476      }
5477  
5478      if (!empty($data->delete_blog_associations)) {
5479          require_once($CFG->dirroot.'/blog/lib.php');
5480          blog_remove_associations_for_course($data->courseid);
5481          $status[] = array('component' => $componentstr, 'item' => get_string('deleteblogassociations', 'blog'), 'error' => false);
5482      }
5483  
5484      if (!empty($data->reset_completion)) {
5485          // Delete course and activity completion information.
5486          $course = $DB->get_record('course', array('id' => $data->courseid));
5487          $cc = new completion_info($course);
5488          $cc->delete_all_completion_data();
5489          $status[] = array('component' => $componentstr,
5490                  'item' => get_string('deletecompletiondata', 'completion'), 'error' => false);
5491      }
5492  
5493      if (!empty($data->reset_competency_ratings)) {
5494          \core_competency\api::hook_course_reset_competency_ratings($data->courseid);
5495          $status[] = array('component' => $componentstr,
5496              'item' => get_string('deletecompetencyratings', 'core_competency'), 'error' => false);
5497      }
5498  
5499      $componentstr = get_string('roles');
5500  
5501      if (!empty($data->reset_roles_overrides)) {
5502          $children = $context->get_child_contexts();
5503          foreach ($children as $child) {
5504              $child->delete_capabilities();
5505          }
5506          $context->delete_capabilities();
5507          $status[] = array('component' => $componentstr, 'item' => get_string('deletecourseoverrides', 'role'), 'error' => false);
5508      }
5509  
5510      if (!empty($data->reset_roles_local)) {
5511          $children = $context->get_child_contexts();
5512          foreach ($children as $child) {
5513              role_unassign_all(array('contextid' => $child->id));
5514          }
5515          $status[] = array('component' => $componentstr, 'item' => get_string('deletelocalroles', 'role'), 'error' => false);
5516      }
5517  
5518      // First unenrol users - this cleans some of related user data too, such as forum subscriptions, tracking, etc.
5519      $data->unenrolled = array();
5520      if (!empty($data->unenrol_users)) {
5521          $plugins = enrol_get_plugins(true);
5522          $instances = enrol_get_instances($data->courseid, true);
5523          foreach ($instances as $key => $instance) {
5524              if (!isset($plugins[$instance->enrol])) {
5525                  unset($instances[$key]);
5526                  continue;
5527              }
5528          }
5529  
5530          $usersroles = enrol_get_course_users_roles($data->courseid);
5531          foreach ($data->unenrol_users as $withroleid) {
5532              if ($withroleid) {
5533                  $sql = "SELECT ue.*
5534                            FROM {user_enrolments} ue
5535                            JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5536                            JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5537                            JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.roleid = :roleid AND ra.userid = ue.userid)";
5538                  $params = array('courseid' => $data->courseid, 'roleid' => $withroleid, 'courselevel' => CONTEXT_COURSE);
5539  
5540              } else {
5541                  // Without any role assigned at course context.
5542                  $sql = "SELECT ue.*
5543                            FROM {user_enrolments} ue
5544                            JOIN {enrol} e ON (e.id = ue.enrolid AND e.courseid = :courseid)
5545                            JOIN {context} c ON (c.contextlevel = :courselevel AND c.instanceid = e.courseid)
5546                       LEFT JOIN {role_assignments} ra ON (ra.contextid = c.id AND ra.userid = ue.userid)
5547                           WHERE ra.id IS null";
5548                  $params = array('courseid' => $data->courseid, 'courselevel' => CONTEXT_COURSE);
5549              }
5550  
5551              $rs = $DB->get_recordset_sql($sql, $params);
5552              foreach ($rs as $ue) {
5553                  if (!isset($instances[$ue->enrolid])) {
5554                      continue;
5555                  }
5556                  $instance = $instances[$ue->enrolid];
5557                  $plugin = $plugins[$instance->enrol];
5558                  if (!$plugin->allow_unenrol($instance) and !$plugin->allow_unenrol_user($instance, $ue)) {
5559                      continue;
5560                  }
5561  
5562                  if ($withroleid && count($usersroles[$ue->userid]) > 1) {
5563                      // If we don't remove all roles and user has more than one role, just remove this role.
5564                      role_unassign($withroleid, $ue->userid, $context->id);
5565  
5566                      unset($usersroles[$ue->userid][$withroleid]);
5567                  } else {
5568                      // If we remove all roles or user has only one role, unenrol user from course.
5569                      $plugin->unenrol_user($instance, $ue->userid);
5570                  }
5571                  $data->unenrolled[$ue->userid] = $ue->userid;
5572              }
5573              $rs->close();
5574          }
5575      }
5576      if (!empty($data->unenrolled)) {
5577          $status[] = array(
5578              'component' => $componentstr,
5579              'item' => get_string('unenrol', 'enrol').' ('.count($data->unenrolled).')',
5580              'error' => false
5581          );
5582      }
5583  
5584      $componentstr = get_string('groups');
5585  
5586      // Remove all group members.
5587      if (!empty($data->reset_groups_members)) {
5588          groups_delete_group_members($data->courseid);
5589          $status[] = array('component' => $componentstr, 'item' => get_string('removegroupsmembers', 'group'), 'error' => false);
5590      }
5591  
5592      // Remove all groups.
5593      if (!empty($data->reset_groups_remove)) {
5594          groups_delete_groups($data->courseid, false);
5595          $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroups', 'group'), 'error' => false);
5596      }
5597  
5598      // Remove all grouping members.
5599      if (!empty($data->reset_groupings_members)) {
5600          groups_delete_groupings_groups($data->courseid, false);
5601          $status[] = array('component' => $componentstr, 'item' => get_string('removegroupingsmembers', 'group'), 'error' => false);
5602      }
5603  
5604      // Remove all groupings.
5605      if (!empty($data->reset_groupings_remove)) {
5606          groups_delete_groupings($data->courseid, false);
5607          $status[] = array('component' => $componentstr, 'item' => get_string('deleteallgroupings', 'group'), 'error' => false);
5608      }
5609  
5610      // Look in every instance of every module for data to delete.
5611      $unsupportedmods = array();
5612      if ($allmods = $DB->get_records('modules') ) {
5613          foreach ($allmods as $mod) {
5614              $modname = $mod->name;
5615              $modfile = $CFG->dirroot.'/mod/'. $modname.'/lib.php';
5616              $moddeleteuserdata = $modname.'_reset_userdata';   // Function to delete user data.
5617              if (file_exists($modfile)) {
5618                  if (!$DB->count_records($modname, array('course' => $data->courseid))) {
5619                      continue; // Skip mods with no instances.
5620                  }
5621                  include_once($modfile);
5622                  if (function_exists($moddeleteuserdata)) {
5623                      $modstatus = $moddeleteuserdata($data);
5624                      if (is_array($modstatus)) {
5625                          $status = array_merge($status, $modstatus);
5626                      } else {
5627                          debugging('Module '.$modname.' returned incorrect staus - must be an array!');
5628                      }
5629                  } else {
5630                      $unsupportedmods[] = $mod;
5631                  }
5632              } else {
5633                  debugging('Missing lib.php in '.$modname.' module!');
5634              }
5635              // Update calendar events for all modules.
5636              course_module_bulk_update_calendar_events($modname, $data->courseid);
5637          }
5638      }
5639  
5640      // Mention unsupported mods.
5641      if (!empty($unsupportedmods)) {
5642          foreach ($unsupportedmods as $mod) {
5643              $status[] = array(
5644                  'component' => get_string('modulenameplural', $mod->name),
5645                  'item' => '',
5646                  'error' => get_string('resetnotimplemented')
5647              );
5648          }
5649      }
5650  
5651      $componentstr = get_string('gradebook', 'grades');
5652      // Reset gradebook,.
5653      if (!empty($data->reset_gradebook_items)) {
5654          remove_course_grades($data->courseid, false);
5655          grade_grab_course_grades($data->courseid);
5656          grade_regrade_final_grades($data->courseid);
5657          $status[] = array('component' => $componentstr, 'item' => get_string('removeallcourseitems', 'grades'), 'error' => false);
5658  
5659      } else if (!empty($data->reset_gradebook_grades)) {
5660          grade_course_reset($data->courseid);
5661          $status[] = array('component' => $componentstr, 'item' => get_string('removeallcoursegrades', 'grades'), 'error' => false);
5662      }
5663      // Reset comments.
5664      if (!empty($data->reset_comments)) {
5665          require_once($CFG->dirroot.'/comment/lib.php');
5666          comment::reset_course_page_comments($context);
5667      }
5668  
5669      $event = \core\event\course_reset_ended::create($eventparams);
5670      $event->trigger();
5671  
5672      return $status;
5673  }
5674  
5675  /**
5676   * Generate an email processing address.
5677   *
5678   * @param int $modid
5679   * @param string $modargs
5680   * @return string Returns email processing address
5681   */
5682  function generate_email_processing_address($modid, $modargs) {
5683      global $CFG;
5684  
5685      $header = $CFG->mailprefix . substr(base64_encode(pack('C', $modid)), 0, 2).$modargs;
5686      return $header . substr(md5($header.get_site_identifier()), 0, 16).'@'.$CFG->maildomain;
5687  }
5688  
5689  /**
5690   * ?
5691   *
5692   * @todo Finish documenting this function
5693   *
5694   * @param string $modargs
5695   * @param string $body Currently unused
5696   */
5697  function moodle_process_email($modargs, $body) {
5698      global $DB;
5699  
5700      // The first char should be an unencoded letter. We'll take this as an action.
5701      switch ($modargs[0]) {
5702          case 'B': { // Bounce.
5703              list(, $userid) = unpack('V', base64_decode(substr($modargs, 1, 8)));
5704              if ($user = $DB->get_record("user", array('id' => $userid), "id,email")) {
5705                  // Check the half md5 of their email.
5706                  $md5check = substr(md5($user->email), 0, 16);
5707                  if ($md5check == substr($modargs, -16)) {
5708                      set_bounce_count($user);
5709                  }
5710                  // Else maybe they've already changed it?
5711              }
5712          }
5713          break;
5714          // Maybe more later?
5715      }
5716  }
5717  
5718  // CORRESPONDENCE.
5719  
5720  /**
5721   * Get mailer instance, enable buffering, flush buffer or disable buffering.
5722   *
5723   * @param string $action 'get', 'buffer', 'close' or 'flush'
5724   * @return moodle_phpmailer|null mailer instance if 'get' used or nothing
5725   */
5726  function get_mailer($action='get') {
5727      global $CFG;
5728  
5729      /** @var moodle_phpmailer $mailer */
5730      static $mailer  = null;
5731      static $counter = 0;
5732  
5733      if (!isset($CFG->smtpmaxbulk)) {
5734          $CFG->smtpmaxbulk = 1;
5735      }
5736  
5737      if ($action == 'get') {
5738          $prevkeepalive = false;
5739  
5740          if (isset($mailer) and $mailer->Mailer == 'smtp') {
5741              if ($counter < $CFG->smtpmaxbulk and !$mailer->isError()) {
5742                  $counter++;
5743                  // Reset the mailer.
5744                  $mailer->Priority         = 3;
5745                  $mailer->CharSet          = 'UTF-8'; // Our default.
5746                  $mailer->ContentType      = "text/plain";
5747                  $mailer->Encoding         = "8bit";
5748                  $mailer->From             = "root@localhost";
5749                  $mailer->FromName         = "Root User";
5750                  $mailer->Sender           = "";
5751                  $mailer->Subject          = "";
5752                  $mailer->Body             = "";
5753                  $mailer->AltBody          = "";
5754                  $mailer->ConfirmReadingTo = "";
5755  
5756                  $mailer->clearAllRecipients();
5757                  $mailer->clearReplyTos();
5758                  $mailer->clearAttachments();
5759                  $mailer->clearCustomHeaders();
5760                  return $mailer;
5761              }
5762  
5763              $prevkeepalive = $mailer->SMTPKeepAlive;
5764              get_mailer('flush');
5765          }
5766  
5767          require_once($CFG->libdir.'/phpmailer/moodle_phpmailer.php');
5768          $mailer = new moodle_phpmailer();
5769  
5770          $counter = 1;
5771  
5772          if ($CFG->smtphosts == 'qmail') {
5773              // Use Qmail system.
5774              $mailer->isQmail();
5775  
5776          } else if (empty($CFG->smtphosts)) {
5777              // Use PHP mail() = sendmail.
5778              $mailer->isMail();
5779  
5780          } else {
5781              // Use SMTP directly.
5782              $mailer->isSMTP();
5783              if (!empty($CFG->debugsmtp) && (!empty($CFG->debugdeveloper))) {
5784                  $mailer->SMTPDebug = 3;
5785              }
5786              // Specify main and backup servers.
5787              $mailer->Host          = $CFG->smtphosts;
5788              // Specify secure connection protocol.
5789              $mailer->SMTPSecure    = $CFG->smtpsecure;
5790              // Use previous keepalive.
5791              $mailer->SMTPKeepAlive = $prevkeepalive;
5792  
5793              if ($CFG->smtpuser) {
5794                  // Use SMTP authentication.
5795                  $mailer->SMTPAuth = true;
5796                  $mailer->Username = $CFG->smtpuser;
5797                  $mailer->Password = $CFG->smtppass;
5798              }
5799          }
5800  
5801          return $mailer;
5802      }
5803  
5804      $nothing = null;
5805  
5806      // Keep smtp session open after sending.
5807      if ($action == 'buffer') {
5808          if (!empty($CFG->smtpmaxbulk)) {
5809              get_mailer('flush');
5810              $m = get_mailer();
5811              if ($m->Mailer == 'smtp') {
5812                  $m->SMTPKeepAlive = true;
5813              }
5814          }
5815          return $nothing;
5816      }
5817  
5818      // Close smtp session, but continue buffering.
5819      if ($action == 'flush') {
5820          if (isset($mailer) and $mailer->Mailer == 'smtp') {
5821              if (!empty($mailer->SMTPDebug)) {
5822                  echo '<pre>'."\n";
5823              }
5824              $mailer->SmtpClose();
5825              if (!empty($mailer->SMTPDebug)) {
5826                  echo '</pre>';
5827              }
5828          }
5829          return $nothing;
5830      }
5831  
5832      // Close smtp session, do not buffer anymore.
5833      if ($action == 'close') {
5834          if (isset($mailer) and $mailer->Mailer == 'smtp') {
5835              get_mailer('flush');
5836              $mailer->SMTPKeepAlive = false;
5837          }
5838          $mailer = null; // Better force new instance.
5839          return $nothing;
5840      }
5841  }
5842  
5843  /**
5844   * A helper function to test for email diversion
5845   *
5846   * @param string $email
5847   * @return bool Returns true if the email should be diverted
5848   */
5849  function email_should_be_diverted($email) {
5850      global $CFG;
5851  
5852      if (empty($CFG->divertallemailsto)) {
5853          return false;
5854      }
5855  
5856      if (empty($CFG->divertallemailsexcept)) {
5857          return true;
5858      }
5859  
5860      $patterns = array_map('trim', preg_split("/[\s,]+/", $CFG->divertallemailsexcept, -1, PREG_SPLIT_NO_EMPTY));
5861      foreach ($patterns as $pattern) {
5862          if (preg_match("/$pattern/", $email)) {
5863              return false;
5864          }
5865      }
5866  
5867      return true;
5868  }
5869  
5870  /**
5871   * Generate a unique email Message-ID using the moodle domain and install path
5872   *
5873   * @param string $localpart An optional unique message id prefix.
5874   * @return string The formatted ID ready for appending to the email headers.
5875   */
5876  function generate_email_messageid($localpart = null) {
5877      global $CFG;
5878  
5879      $urlinfo = parse_url($CFG->wwwroot);
5880      $base = '@' . $urlinfo['host'];
5881  
5882      // If multiple moodles are on the same domain we want to tell them
5883      // apart so we add the install path to the local part. This means
5884      // that the id local part should never contain a / character so
5885      // we can correctly parse the id to reassemble the wwwroot.
5886      if (isset($urlinfo['path'])) {
5887          $base = $urlinfo['path'] . $base;
5888      }
5889  
5890      if (empty($localpart)) {
5891          $localpart = uniqid('', true);
5892      }
5893  
5894      // Because we may have an option /installpath suffix to the local part
5895      // of the id we need to escape any / chars which are in the $localpart.
5896      $localpart = str_replace('/', '%2F', $localpart);
5897  
5898      return '<' . $localpart . $base . '>';
5899  }
5900  
5901  /**
5902   * Send an email to a specified user
5903   *
5904   * @param stdClass $user  A {@link $USER} object
5905   * @param stdClass $from A {@link $USER} object
5906   * @param string $subject plain text subject line of the email
5907   * @param string $messagetext plain text version of the message
5908   * @param string $messagehtml complete html version of the message (optional)
5909   * @param string $attachment a file on the filesystem, either relative to $CFG->dataroot or a full path to a file in one of
5910   *          the following directories: $CFG->cachedir, $CFG->dataroot, $CFG->dirroot, $CFG->localcachedir, $CFG->tempdir
5911   * @param string $attachname the name of the file (extension indicates MIME)
5912   * @param bool $usetrueaddress determines whether $from email address should
5913   *          be sent out. Will be overruled by user profile setting for maildisplay
5914   * @param string $replyto Email address to reply to
5915   * @param string $replytoname Name of reply to recipient
5916   * @param int $wordwrapwidth custom word wrap width, default 79
5917   * @return bool Returns true if mail was sent OK and false if there was an error.
5918   */
5919  function email_to_user($user, $from, $subject, $messagetext, $messagehtml = '', $attachment = '', $attachname = '',
5920                         $usetrueaddress = true, $replyto = '', $replytoname = '', $wordwrapwidth = 79) {
5921  
5922      global $CFG, $PAGE, $SITE;
5923  
5924      if (empty($user) or empty($user->id)) {
5925          debugging('Can not send email to null user', DEBUG_DEVELOPER);
5926          return false;
5927      }
5928  
5929      if (empty($user->email)) {
5930          debugging('Can not send email to user without email: '.$user->id, DEBUG_DEVELOPER);
5931          return false;
5932      }
5933  
5934      if (!empty($user->deleted)) {
5935          debugging('Can not send email to deleted user: '.$user->id, DEBUG_DEVELOPER);
5936          return false;
5937      }
5938  
5939      if (defined('BEHAT_SITE_RUNNING')) {
5940          // Fake email sending in behat.
5941          return true;
5942      }
5943  
5944      if (!empty($CFG->noemailever)) {
5945          // Hidden setting for development sites, set in config.php if needed.
5946          debugging('Not sending email due to $CFG->noemailever config setting', DEBUG_NORMAL);
5947          return true;
5948      }
5949  
5950      if (email_should_be_diverted($user->email)) {
5951          $subject = "[DIVERTED {$user->email}] $subject";
5952          $user = clone($user);
5953          $user->email = $CFG->divertallemailsto;
5954      }
5955  
5956      // Skip mail to suspended users.
5957      if ((isset($user->auth) && $user->auth=='nologin') or (isset($user->suspended) && $user->suspended)) {
5958          return true;
5959      }
5960  
5961      if (!validate_email($user->email)) {
5962          // We can not send emails to invalid addresses - it might create security issue or confuse the mailer.
5963          debugging("email_to_user: User $user->id (".fullname($user).") email ($user->email) is invalid! Not sending.");
5964          return false;
5965      }
5966  
5967      if (over_bounce_threshold($user)) {
5968          debugging("email_to_user: User $user->id (".fullname($user).") is over bounce threshold! Not sending.");
5969          return false;
5970      }
5971  
5972      // TLD .invalid  is specifically reserved for invalid domain names.
5973      // For More information, see {@link http://tools.ietf.org/html/rfc2606#section-2}.
5974      if (substr($user->email, -8) == '.invalid') {
5975          debugging("email_to_user: User $user->id (".fullname($user).") email domain ($user->email) is invalid! Not sending.");
5976          return true; // This is not an error.
5977      }
5978  
5979      // If the user is a remote mnet user, parse the email text for URL to the
5980      // wwwroot and modify the url to direct the user's browser to login at their
5981      // home site (identity provider - idp) before hitting the link itself.
5982      if (is_mnet_remote_user($user)) {
5983          require_once($CFG->dirroot.'/mnet/lib.php');
5984  
5985          $jumpurl = mnet_get_idp_jump_url($user);
5986          $callback = partial('mnet_sso_apply_indirection', $jumpurl);
5987  
5988          $messagetext = preg_replace_callback("%($CFG->wwwroot[^[:space:]]*)%",
5989                  $callback,
5990                  $messagetext);
5991          $messagehtml = preg_replace_callback("%href=[\"'`]($CFG->wwwroot[\w_:\?=#&@/;.~-]*)[\"'`]%",
5992                  $callback,
5993                  $messagehtml);
5994      }
5995      $mail = get_mailer();
5996  
5997      if (!empty($mail->SMTPDebug)) {
5998          echo '<pre>' . "\n";
5999      }
6000  
6001      $temprecipients = array();
6002      $tempreplyto = array();
6003  
6004      // Make sure that we fall back onto some reasonable no-reply address.
6005      $noreplyaddressdefault = 'noreply@' . get_host_from_url($CFG->wwwroot);
6006      $noreplyaddress = empty($CFG->noreplyaddress) ? $noreplyaddressdefault : $CFG->noreplyaddress;
6007  
6008      if (!validate_email($noreplyaddress)) {
6009          debugging('email_to_user: Invalid noreply-email '.s($noreplyaddress));
6010          $noreplyaddress = $noreplyaddressdefault;
6011      }
6012  
6013      // Make up an email address for handling bounces.
6014      if (!empty($CFG->handlebounces)) {
6015          $modargs = 'B'.base64_encode(pack('V', $user->id)).substr(md5($user->email), 0, 16);
6016          $mail->Sender = generate_email_processing_address(0, $modargs);
6017      } else {
6018          $mail->Sender = $noreplyaddress;
6019      }
6020  
6021      // Make sure that the explicit replyto is valid, fall back to the implicit one.
6022      if (!empty($replyto) && !validate_email($replyto)) {
6023          debugging('email_to_user: Invalid replyto-email '.s($replyto));
6024          $replyto = $noreplyaddress;
6025      }
6026  
6027      if (is_string($from)) { // So we can pass whatever we want if there is need.
6028          $mail->From     = $noreplyaddress;
6029          $mail->FromName = $from;
6030      // Check if using the true address is true, and the email is in the list of allowed domains for sending email,
6031      // and that the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6032      // in a course with the sender.
6033      } else if ($usetrueaddress && can_send_from_real_email_address($from, $user)) {
6034          if (!validate_email($from->email)) {
6035              debugging('email_to_user: Invalid from-email '.s($from->email).' - not sending');
6036              // Better not to use $noreplyaddress in this case.
6037              return false;
6038          }
6039          $mail->From = $from->email;
6040          $fromdetails = new stdClass();
6041          $fromdetails->name = fullname($from);
6042          $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6043          $fromdetails->siteshortname = format_string($SITE->shortname);
6044          $fromstring = $fromdetails->name;
6045          if ($CFG->emailfromvia == EMAIL_VIA_ALWAYS) {
6046              $fromstring = get_string('emailvia', 'core', $fromdetails);
6047          }
6048          $mail->FromName = $fromstring;
6049          if (empty($replyto)) {
6050              $tempreplyto[] = array($from->email, fullname($from));
6051          }
6052      } else {
6053          $mail->From = $noreplyaddress;
6054          $fromdetails = new stdClass();
6055          $fromdetails->name = fullname($from);
6056          $fromdetails->url = preg_replace('#^https?://#', '', $CFG->wwwroot);
6057          $fromdetails->siteshortname = format_string($SITE->shortname);
6058          $fromstring = $fromdetails->name;
6059          if ($CFG->emailfromvia != EMAIL_VIA_NEVER) {
6060              $fromstring = get_string('emailvia', 'core', $fromdetails);
6061          }
6062          $mail->FromName = $fromstring;
6063          if (empty($replyto)) {
6064              $tempreplyto[] = array($noreplyaddress, get_string('noreplyname'));
6065          }
6066      }
6067  
6068      if (!empty($replyto)) {
6069          $tempreplyto[] = array($replyto, $replytoname);
6070      }
6071  
6072      $temprecipients[] = array($user->email, fullname($user));
6073  
6074      // Set word wrap.
6075      $mail->WordWrap = $wordwrapwidth;
6076  
6077      if (!empty($from->customheaders)) {
6078          // Add custom headers.
6079          if (is_array($from->customheaders)) {
6080              foreach ($from->customheaders as $customheader) {
6081                  $mail->addCustomHeader($customheader);
6082              }
6083          } else {
6084              $mail->addCustomHeader($from->customheaders);
6085          }
6086      }
6087  
6088      // If the X-PHP-Originating-Script email header is on then also add an additional
6089      // header with details of where exactly in moodle the email was triggered from,
6090      // either a call to message_send() or to email_to_user().
6091      if (ini_get('mail.add_x_header')) {
6092  
6093          $stack = debug_backtrace(false);
6094          $origin = $stack[0];
6095  
6096          foreach ($stack as $depth => $call) {
6097              if ($call['function'] == 'message_send') {
6098                  $origin = $call;
6099              }
6100          }
6101  
6102          $originheader = $CFG->wwwroot . ' => ' . gethostname() . ':'
6103               . str_replace($CFG->dirroot . '/', '', $origin['file']) . ':' . $origin['line'];
6104          $mail->addCustomHeader('X-Moodle-Originating-Script: ' . $originheader);
6105      }
6106  
6107      if (!empty($CFG->emailheaders)) {
6108          $headers = array_map('trim', explode("\n", $CFG->emailheaders));
6109          foreach ($headers as $header) {
6110              if (!empty($header)) {
6111                  $mail->addCustomHeader($header);
6112              }
6113          }
6114      }
6115  
6116      if (!empty($from->priority)) {
6117          $mail->Priority = $from->priority;
6118      }
6119  
6120      $renderer = $PAGE->get_renderer('core');
6121      $context = array(
6122          'sitefullname' => $SITE->fullname,
6123          'siteshortname' => $SITE->shortname,
6124          'sitewwwroot' => $CFG->wwwroot,
6125          'subject' => $subject,
6126          'prefix' => $CFG->emailsubjectprefix,
6127          'to' => $user->email,
6128          'toname' => fullname($user),
6129          'from' => $mail->From,
6130          'fromname' => $mail->FromName,
6131      );
6132      if (!empty($tempreplyto[0])) {
6133          $context['replyto'] = $tempreplyto[0][0];
6134          $context['replytoname'] = $tempreplyto[0][1];
6135      }
6136      if ($user->id > 0) {
6137          $context['touserid'] = $user->id;
6138          $context['tousername'] = $user->username;
6139      }
6140  
6141      if (!empty($user->mailformat) && $user->mailformat == 1) {
6142          // Only process html templates if the user preferences allow html email.
6143  
6144          if (!$messagehtml) {
6145              // If no html has been given, BUT there is an html wrapping template then
6146              // auto convert the text to html and then wrap it.
6147              $messagehtml = trim(text_to_html($messagetext));
6148          }
6149          $context['body'] = $messagehtml;
6150          $messagehtml = $renderer->render_from_template('core/email_html', $context);
6151      }
6152  
6153      $context['body'] = html_to_text(nl2br($messagetext));
6154      $mail->Subject = $renderer->render_from_template('core/email_subject', $context);
6155      $mail->FromName = $renderer->render_from_template('core/email_fromname', $context);
6156      $messagetext = $renderer->render_from_template('core/email_text', $context);
6157  
6158      // Autogenerate a MessageID if it's missing.
6159      if (empty($mail->MessageID)) {
6160          $mail->MessageID = generate_email_messageid();
6161      }
6162  
6163      if ($messagehtml && !empty($user->mailformat) && $user->mailformat == 1) {
6164          // Don't ever send HTML to users who don't want it.
6165          $mail->isHTML(true);
6166          $mail->Encoding = 'quoted-printable';
6167          $mail->Body    =  $messagehtml;
6168          $mail->AltBody =  "\n$messagetext\n";
6169      } else {
6170          $mail->IsHTML(false);
6171          $mail->Body =  "\n$messagetext\n";
6172      }
6173  
6174      if ($attachment && $attachname) {
6175          if (preg_match( "~\\.\\.~" , $attachment )) {
6176              // Security check for ".." in dir path.
6177              $supportuser = core_user::get_support_user();
6178              $temprecipients[] = array($supportuser->email, fullname($supportuser, true));
6179              $mail->addStringAttachment('Error in attachment.  User attempted to attach a filename with a unsafe name.', 'error.txt', '8bit', 'text/plain');
6180          } else {
6181              require_once($CFG->libdir.'/filelib.php');
6182              $mimetype = mimeinfo('type', $attachname);
6183  
6184              // Before doing the comparison, make sure that the paths are correct (Windows uses slashes in the other direction).
6185              // The absolute (real) path is also fetched to ensure that comparisons to allowed paths are compared equally.
6186              $attachpath = str_replace('\\', '/', realpath($attachment));
6187  
6188              // Build an array of all filepaths from which attachments can be added (normalised slashes, absolute/real path).
6189              $allowedpaths = array_map(function(string $path): string {
6190                  return str_replace('\\', '/', realpath($path));
6191              }, [
6192                  $CFG->cachedir,
6193                  $CFG->dataroot,
6194                  $CFG->dirroot,
6195                  $CFG->localcachedir,
6196                  $CFG->tempdir,
6197                  $CFG->localrequestdir,
6198              ]);
6199  
6200              // Set addpath to true.
6201              $addpath = true;
6202  
6203              // Check if attachment includes one of the allowed paths.
6204              foreach (array_filter($allowedpaths) as $allowedpath) {
6205                  // Set addpath to false if the attachment includes one of the allowed paths.
6206                  if (strpos($attachpath, $allowedpath) === 0) {
6207                      $addpath = false;
6208                      break;
6209                  }
6210              }
6211  
6212              // If the attachment is a full path to a file in the multiple allowed paths, use it as is,
6213              // otherwise assume it is a relative path from the dataroot (for backwards compatibility reasons).
6214              if ($addpath == true) {
6215                  $attachment = $CFG->dataroot . '/' . $attachment;
6216              }
6217  
6218              $mail->addAttachment($attachment, $attachname, 'base64', $mimetype);
6219          }
6220      }
6221  
6222      // Check if the email should be sent in an other charset then the default UTF-8.
6223      if ((!empty($CFG->sitemailcharset) || !empty($CFG->allowusermailcharset))) {
6224  
6225          // Use the defined site mail charset or eventually the one preferred by the recipient.
6226          $charset = $CFG->sitemailcharset;
6227          if (!empty($CFG->allowusermailcharset)) {
6228              if ($useremailcharset = get_user_preferences('mailcharset', '0', $user->id)) {
6229                  $charset = $useremailcharset;
6230              }
6231          }
6232  
6233          // Convert all the necessary strings if the charset is supported.
6234          $charsets = get_list_of_charsets();
6235          unset($charsets['UTF-8']);
6236          if (in_array($charset, $charsets)) {
6237              $mail->CharSet  = $charset;
6238              $mail->FromName = core_text::convert($mail->FromName, 'utf-8', strtolower($charset));
6239              $mail->Subject  = core_text::convert($mail->Subject, 'utf-8', strtolower($charset));
6240              $mail->Body     = core_text::convert($mail->Body, 'utf-8', strtolower($charset));
6241              $mail->AltBody  = core_text::convert($mail->AltBody, 'utf-8', strtolower($charset));
6242  
6243              foreach ($temprecipients as $key => $values) {
6244                  $temprecipients[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6245              }
6246              foreach ($tempreplyto as $key => $values) {
6247                  $tempreplyto[$key][1] = core_text::convert($values[1], 'utf-8', strtolower($charset));
6248              }
6249          }
6250      }
6251  
6252      foreach ($temprecipients as $values) {
6253          $mail->addAddress($values[0], $values[1]);
6254      }
6255      foreach ($tempreplyto as $values) {
6256          $mail->addReplyTo($values[0], $values[1]);
6257      }
6258  
6259      if (!empty($CFG->emaildkimselector)) {
6260          $domain = substr(strrchr($mail->From, "@"), 1);
6261          $pempath = "{$CFG->dataroot}/dkim/{$domain}/{$CFG->emaildkimselector}.private";
6262          if (file_exists($pempath)) {
6263              $mail->DKIM_domain      = $domain;
6264              $mail->DKIM_private     = $pempath;
6265              $mail->DKIM_selector    = $CFG->emaildkimselector;
6266              $mail->DKIM_identity    = $mail->From;
6267          } else {
6268              debugging("Email DKIM selector chosen due to {$mail->From} but no certificate found at $pempath", DEBUG_DEVELOPER);
6269          }
6270      }
6271  
6272      if ($mail->send()) {
6273          set_send_count($user);
6274          if (!empty($mail->SMTPDebug)) {
6275              echo '</pre>';
6276          }
6277          return true;
6278      } else {
6279          // Trigger event for failing to send email.
6280          $event = \core\event\email_failed::create(array(
6281              'context' => context_system::instance(),
6282              'userid' => $from->id,
6283              'relateduserid' => $user->id,
6284              'other' => array(
6285                  'subject' => $subject,
6286                  'message' => $messagetext,
6287                  'errorinfo' => $mail->ErrorInfo
6288              )
6289          ));
6290          $event->trigger();
6291          if (CLI_SCRIPT) {
6292              mtrace('Error: lib/moodlelib.php email_to_user(): '.$mail->ErrorInfo);
6293          }
6294          if (!empty($mail->SMTPDebug)) {
6295              echo '</pre>';
6296          }
6297          return false;
6298      }
6299  }
6300  
6301  /**
6302   * Check to see if a user's real email address should be used for the "From" field.
6303   *
6304   * @param  object $from The user object for the user we are sending the email from.
6305   * @param  object $user The user object that we are sending the email to.
6306   * @param  array $unused No longer used.
6307   * @return bool Returns true if we can use the from user's email adress in the "From" field.
6308   */
6309  function can_send_from_real_email_address($from, $user, $unused = null) {
6310      global $CFG;
6311      if (!isset($CFG->allowedemaildomains) || empty(trim($CFG->allowedemaildomains))) {
6312          return false;
6313      }
6314      $alloweddomains = array_map('trim', explode("\n", $CFG->allowedemaildomains));
6315      // Email is in the list of allowed domains for sending email,
6316      // and the senders email setting is either displayed to everyone, or display to only other users that are enrolled
6317      // in a course with the sender.
6318      if (\core\ip_utils::is_domain_in_allowed_list(substr($from->email, strpos($from->email, '@') + 1), $alloweddomains)
6319                  && ($from->maildisplay == core_user::MAILDISPLAY_EVERYONE
6320                  || ($from->maildisplay == core_user::MAILDISPLAY_COURSE_MEMBERS_ONLY
6321                  && enrol_get_shared_courses($user, $from, false, true)))) {
6322          return true;
6323      }
6324      return false;
6325  }
6326  
6327  /**
6328   * Generate a signoff for emails based on support settings
6329   *
6330   * @return string
6331   */
6332  function generate_email_signoff() {
6333      global $CFG;
6334  
6335      $signoff = "\n";
6336      if (!empty($CFG->supportname)) {
6337          $signoff .= $CFG->supportname."\n";
6338      }
6339      if (!empty($CFG->supportemail)) {
6340          $signoff .= $CFG->supportemail."\n";
6341      }
6342      if (!empty($CFG->supportpage)) {
6343          $signoff .= $CFG->supportpage."\n";
6344      }
6345      return $signoff;
6346  }
6347  
6348  /**
6349   * Sets specified user's password and send the new password to the user via email.
6350   *
6351   * @param stdClass $user A {@link $USER} object
6352   * @param bool $fasthash If true, use a low cost factor when generating the hash for speed.
6353   * @return bool|string Returns "true" if mail was sent OK and "false" if there was an error
6354   */
6355  function setnew_password_and_mail($user, $fasthash = false) {
6356      global $CFG, $DB;
6357  
6358      // We try to send the mail in language the user understands,
6359      // unfortunately the filter_string() does not support alternative langs yet
6360      // so multilang will not work properly for site->fullname.
6361      $lang = empty($user->lang) ? get_newuser_language() : $user->lang;
6362  
6363      $site  = get_site();
6364  
6365      $supportuser = core_user::get_support_user();
6366  
6367      $newpassword = generate_password();
6368  
6369      update_internal_user_password($user, $newpassword, $fasthash);
6370  
6371      $a = new stdClass();
6372      $a->firstname   = fullname($user, true);
6373      $a->sitename    = format_string($site->fullname);
6374      $a->username    = $user->username;
6375      $a->newpassword = $newpassword;
6376      $a->link        = $CFG->wwwroot .'/login/?lang='.$lang;
6377      $a->signoff     = generate_email_signoff();
6378  
6379      $message = (string)new lang_string('newusernewpasswordtext', '', $a, $lang);
6380  
6381      $subject = format_string($site->fullname) .': '. (string)new lang_string('newusernewpasswordsubj', '', $a, $lang);
6382  
6383      // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6384      return email_to_user($user, $supportuser, $subject, $message);
6385  
6386  }
6387  
6388  /**
6389   * Resets specified user's password and send the new password to the user via email.
6390   *
6391   * @param stdClass $user A {@link $USER} object
6392   * @return bool Returns true if mail was sent OK and false if there was an error.
6393   */
6394  function reset_password_and_mail($user) {
6395      global $CFG;
6396  
6397      $site  = get_site();
6398      $supportuser = core_user::get_support_user();
6399  
6400      $userauth = get_auth_plugin($user->auth);
6401      if (!$userauth->can_reset_password() or !is_enabled_auth($user->auth)) {
6402          trigger_error("Attempt to reset user password for user $user->username with Auth $user->auth.");
6403          return false;
6404      }
6405  
6406      $newpassword = generate_password();
6407  
6408      if (!$userauth->user_update_password($user, $newpassword)) {
6409          print_error("cannotsetpassword");
6410      }
6411  
6412      $a = new stdClass();
6413      $a->firstname   = $user->firstname;
6414      $a->lastname    = $user->lastname;
6415      $a->sitename    = format_string($site->fullname);
6416      $a->username    = $user->username;
6417      $a->newpassword = $newpassword;
6418      $a->link        = $CFG->wwwroot .'/login/change_password.php';
6419      $a->signoff     = generate_email_signoff();
6420  
6421      $message = get_string('newpasswordtext', '', $a);
6422  
6423      $subject  = format_string($site->fullname) .': '. get_string('changedpassword');
6424  
6425      unset_user_preference('create_password', $user); // Prevent cron from generating the password.
6426  
6427      // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6428      return email_to_user($user, $supportuser, $subject, $message);
6429  }
6430  
6431  /**
6432   * Send email to specified user with confirmation text and activation link.
6433   *
6434   * @param stdClass $user A {@link $USER} object
6435   * @param string $confirmationurl user confirmation URL
6436   * @return bool Returns true if mail was sent OK and false if there was an error.
6437   */
6438  function send_confirmation_email($user, $confirmationurl = null) {
6439      global $CFG;
6440  
6441      $site = get_site();
6442      $supportuser = core_user::get_support_user();
6443  
6444      $data = new stdClass();
6445      $data->sitename  = format_string($site->fullname);
6446      $data->admin     = generate_email_signoff();
6447  
6448      $subject = get_string('emailconfirmationsubject', '', format_string($site->fullname));
6449  
6450      if (empty($confirmationurl)) {
6451          $confirmationurl = '/login/confirm.php';
6452      }
6453  
6454      $confirmationurl = new moodle_url($confirmationurl);
6455      // Remove data parameter just in case it was included in the confirmation so we can add it manually later.
6456      $confirmationurl->remove_params('data');
6457      $confirmationpath = $confirmationurl->out(false);
6458  
6459      // We need to custom encode the username to include trailing dots in the link.
6460      // Because of this custom encoding we can't use moodle_url directly.
6461      // Determine if a query string is present in the confirmation url.
6462      $hasquerystring = strpos($confirmationpath, '?') !== false;
6463      // Perform normal url encoding of the username first.
6464      $username = urlencode($user->username);
6465      // Prevent problems with trailing dots not being included as part of link in some mail clients.
6466      $username = str_replace('.', '%2E', $username);
6467  
6468      $data->link = $confirmationpath . ( $hasquerystring ? '&' : '?') . 'data='. $user->secret .'/'. $username;
6469  
6470      $message     = get_string('emailconfirmation', '', $data);
6471      $messagehtml = text_to_html(get_string('emailconfirmation', '', $data), false, false, true);
6472  
6473      // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6474      return email_to_user($user, $supportuser, $subject, $message, $messagehtml);
6475  }
6476  
6477  /**
6478   * Sends a password change confirmation email.
6479   *
6480   * @param stdClass $user A {@link $USER} object
6481   * @param stdClass $resetrecord An object tracking metadata regarding password reset request
6482   * @return bool Returns true if mail was sent OK and false if there was an error.
6483   */
6484  function send_password_change_confirmation_email($user, $resetrecord) {
6485      global $CFG;
6486  
6487      $site = get_site();
6488      $supportuser = core_user::get_support_user();
6489      $pwresetmins = isset($CFG->pwresettime) ? floor($CFG->pwresettime / MINSECS) : 30;
6490  
6491      $data = new stdClass();
6492      $data->firstname = $user->firstname;
6493      $data->lastname  = $user->lastname;
6494      $data->username  = $user->username;
6495      $data->sitename  = format_string($site->fullname);
6496      $data->link      = $CFG->wwwroot .'/login/forgot_password.php?token='. $resetrecord->token;
6497      $data->admin     = generate_email_signoff();
6498      $data->resetminutes = $pwresetmins;
6499  
6500      $message = get_string('emailresetconfirmation', '', $data);
6501      $subject = get_string('emailresetconfirmationsubject', '', format_string($site->fullname));
6502  
6503      // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6504      return email_to_user($user, $supportuser, $subject, $message);
6505  
6506  }
6507  
6508  /**
6509   * Sends an email containing information on how to change your password.
6510   *
6511   * @param stdClass $user A {@link $USER} object
6512   * @return bool Returns true if mail was sent OK and false if there was an error.
6513   */
6514  function send_password_change_info($user) {
6515      $site = get_site();
6516      $supportuser = core_user::get_support_user();
6517  
6518      $data = new stdClass();
6519      $data->firstname = $user->firstname;
6520      $data->lastname  = $user->lastname;
6521      $data->username  = $user->username;
6522      $data->sitename  = format_string($site->fullname);
6523      $data->admin     = generate_email_signoff();
6524  
6525      if (!is_enabled_auth($user->auth)) {
6526          $message = get_string('emailpasswordchangeinfodisabled', '', $data);
6527          $subject = get_string('emailpasswordchangeinfosubject', '', format_string($site->fullname));
6528          // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6529          return email_to_user($user, $supportuser, $subject, $message);
6530      }
6531  
6532      $userauth = get_auth_plugin($user->auth);
6533      ['subject' => $subject, 'message' => $message] = $userauth->get_password_change_info($user);
6534  
6535      // Directly email rather than using the messaging system to ensure its not routed to a popup or jabber.
6536      return email_to_user($user, $supportuser, $subject, $message);
6537  }
6538  
6539  /**
6540   * Check that an email is allowed.  It returns an error message if there was a problem.
6541   *
6542   * @param string $email Content of email
6543   * @return string|false
6544   */
6545  function email_is_not_allowed($email) {
6546      global $CFG;
6547  
6548      // Comparing lowercase domains.
6549      $email = strtolower($email);
6550      if (!empty($CFG->allowemailaddresses)) {
6551          $allowed = explode(' ', strtolower($CFG->allowemailaddresses));
6552          foreach ($allowed as $allowedpattern) {
6553              $allowedpattern = trim($allowedpattern);
6554              if (!$allowedpattern) {
6555                  continue;
6556              }
6557              if (strpos($allowedpattern, '.') === 0) {
6558                  if (strpos(strrev($email), strrev($allowedpattern)) === 0) {
6559                      // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6560                      return false;
6561                  }
6562  
6563              } else if (strpos(strrev($email), strrev('@'.$allowedpattern)) === 0) {
6564                  return false;
6565              }
6566          }
6567          return get_string('emailonlyallowed', '', $CFG->allowemailaddresses);
6568  
6569      } else if (!empty($CFG->denyemailaddresses)) {
6570          $denied = explode(' ', strtolower($CFG->denyemailaddresses));
6571          foreach ($denied as $deniedpattern) {
6572              $deniedpattern = trim($deniedpattern);
6573              if (!$deniedpattern) {
6574                  continue;
6575              }
6576              if (strpos($deniedpattern, '.') === 0) {
6577                  if (strpos(strrev($email), strrev($deniedpattern)) === 0) {
6578                      // Subdomains are in a form ".example.com" - matches "xxx@anything.example.com".
6579                      return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6580                  }
6581  
6582              } else if (strpos(strrev($email), strrev('@'.$deniedpattern)) === 0) {
6583                  return get_string('emailnotallowed', '', $CFG->denyemailaddresses);
6584              }
6585          }
6586      }
6587  
6588      return false;
6589  }
6590  
6591  // FILE HANDLING.
6592  
6593  /**
6594   * Returns local file storage instance
6595   *
6596   * @return file_storage
6597   */
6598  function get_file_storage($reset = false) {
6599      global $CFG;
6600  
6601      static $fs = null;
6602  
6603      if ($reset) {
6604          $fs = null;
6605          return;
6606      }
6607  
6608      if ($fs) {
6609          return $fs;
6610      }
6611  
6612      require_once("$CFG->libdir/filelib.php");
6613  
6614      $fs = new file_storage();
6615  
6616      return $fs;
6617  }
6618  
6619  /**
6620   * Returns local file storage instance
6621   *
6622   * @return file_browser
6623   */
6624  function get_file_browser() {
6625      global $CFG;
6626  
6627      static $fb = null;
6628  
6629      if ($fb) {
6630          return $fb;
6631      }
6632  
6633      require_once("$CFG->libdir/filelib.php");
6634  
6635      $fb = new file_browser();
6636  
6637      return $fb;
6638  }
6639  
6640  /**
6641   * Returns file packer
6642   *
6643   * @param string $mimetype default application/zip
6644   * @return file_packer
6645   */
6646  function get_file_packer($mimetype='application/zip') {
6647      global $CFG;
6648  
6649      static $fp = array();
6650  
6651      if (isset($fp[$mimetype])) {
6652          return $fp[$mimetype];
6653      }
6654  
6655      switch ($mimetype) {
6656          case 'application/zip':
6657          case 'application/vnd.moodle.profiling':
6658              $classname = 'zip_packer';
6659              break;
6660  
6661          case 'application/x-gzip' :
6662              $classname = 'tgz_packer';
6663              break;
6664  
6665          case 'application/vnd.moodle.backup':
6666              $classname = 'mbz_packer';
6667              break;
6668  
6669          default:
6670              return false;
6671      }
6672  
6673      require_once("$CFG->libdir/filestorage/$classname.php");
6674      $fp[$mimetype] = new $classname();
6675  
6676      return $fp[$mimetype];
6677  }
6678  
6679  /**
6680   * Returns current name of file on disk if it exists.
6681   *
6682   * @param string $newfile File to be verified
6683   * @return string Current name of file on disk if true
6684   */
6685  function valid_uploaded_file($newfile) {
6686      if (empty($newfile)) {
6687          return '';
6688      }
6689      if (is_uploaded_file($newfile['tmp_name']) and $newfile['size'] > 0) {
6690          return $newfile['tmp_name'];
6691      } else {
6692          return '';
6693      }
6694  }
6695  
6696  /**
6697   * Returns the maximum size for uploading files.
6698   *
6699   * There are seven possible upload limits:
6700   * 1. in Apache using LimitRequestBody (no way of checking or changing this)
6701   * 2. in php.ini for 'upload_max_filesize' (can not be changed inside PHP)
6702   * 3. in .htaccess for 'upload_max_filesize' (can not be changed inside PHP)
6703   * 4. in php.ini for 'post_max_size' (can not be changed inside PHP)
6704   * 5. by the Moodle admin in $CFG->maxbytes
6705   * 6. by the teacher in the current course $course->maxbytes
6706   * 7. by the teacher for the current module, eg $assignment->maxbytes
6707   *
6708   * These last two are passed to this function as arguments (in bytes).
6709   * Anything defined as 0 is ignored.
6710   * The smallest of all the non-zero numbers is returned.
6711   *
6712   * @todo Finish documenting this function
6713   *
6714   * @param int $sitebytes Set maximum size
6715   * @param int $coursebytes Current course $course->maxbytes (in bytes)
6716   * @param int $modulebytes Current module ->maxbytes (in bytes)
6717   * @param bool $unused This parameter has been deprecated and is not used any more.
6718   * @return int The maximum size for uploading files.
6719   */
6720  function get_max_upload_file_size($sitebytes=0, $coursebytes=0, $modulebytes=0, $unused = false) {
6721  
6722      if (! $filesize = ini_get('upload_max_filesize')) {
6723          $filesize = '5M';
6724      }
6725      $minimumsize = get_real_size($filesize);
6726  
6727      if ($postsize = ini_get('post_max_size')) {
6728          $postsize = get_real_size($postsize);
6729          if ($postsize < $minimumsize) {
6730              $minimumsize = $postsize;
6731          }
6732      }
6733  
6734      if (($sitebytes > 0) and ($sitebytes < $minimumsize)) {
6735          $minimumsize = $sitebytes;
6736      }
6737  
6738      if (($coursebytes > 0) and ($coursebytes < $minimumsize)) {
6739          $minimumsize = $coursebytes;
6740      }
6741  
6742      if (($modulebytes > 0) and ($modulebytes < $minimumsize)) {
6743          $minimumsize = $modulebytes;
6744      }
6745  
6746      return $minimumsize;
6747  }
6748  
6749  /**
6750   * Returns the maximum size for uploading files for the current user
6751   *
6752   * This function takes in account {@link get_max_upload_file_size()} the user's capabilities
6753   *
6754   * @param context $context The context in which to check user capabilities
6755   * @param int $sitebytes Set maximum size
6756   * @param int $coursebytes Current course $course->maxbytes (in bytes)
6757   * @param int $modulebytes Current module ->maxbytes (in bytes)
6758   * @param stdClass $user The user
6759   * @param bool $unused This parameter has been deprecated and is not used any more.
6760   * @return int The maximum size for uploading files.
6761   */
6762  function get_user_max_upload_file_size($context, $sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $user = null,
6763          $unused = false) {
6764      global $USER;
6765  
6766      if (empty($user)) {
6767          $user = $USER;
6768      }
6769  
6770      if (has_capability('moodle/course:ignorefilesizelimits', $context, $user)) {
6771          return USER_CAN_IGNORE_FILE_SIZE_LIMITS;
6772      }
6773  
6774      return get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes);
6775  }
6776  
6777  /**
6778   * Returns an array of possible sizes in local language
6779   *
6780   * Related to {@link get_max_upload_file_size()} - this function returns an
6781   * array of possible sizes in an array, translated to the
6782   * local language.
6783   *
6784   * The list of options will go up to the minimum of $sitebytes, $coursebytes or $modulebytes.
6785   *
6786   * If $coursebytes or $sitebytes is not 0, an option will be included for "Course/Site upload limit (X)"
6787   * with the value set to 0. This option will be the first in the list.
6788   *
6789   * @uses SORT_NUMERIC
6790   * @param int $sitebytes Set maximum size
6791   * @param int $coursebytes Current course $course->maxbytes (in bytes)
6792   * @param int $modulebytes Current module ->maxbytes (in bytes)
6793   * @param int|array $custombytes custom upload size/s which will be added to list,
6794   *        Only value/s smaller then maxsize will be added to list.
6795   * @return array
6796   */
6797  function get_max_upload_sizes($sitebytes = 0, $coursebytes = 0, $modulebytes = 0, $custombytes = null) {
6798      global $CFG;
6799  
6800      if (!$maxsize = get_max_upload_file_size($sitebytes, $coursebytes, $modulebytes)) {
6801          return array();
6802      }
6803  
6804      if ($sitebytes == 0) {
6805          // Will get the minimum of upload_max_filesize or post_max_size.
6806          $sitebytes = get_max_upload_file_size();
6807      }
6808  
6809      $filesize = array();
6810      $sizelist = array(10240, 51200, 102400, 512000, 1048576, 2097152,
6811                        5242880, 10485760, 20971520, 52428800, 104857600,
6812                        262144000, 524288000, 786432000, 1073741824,
6813                        2147483648, 4294967296, 8589934592);
6814  
6815      // If custombytes is given and is valid then add it to the list.
6816      if (is_number($custombytes) and $custombytes > 0) {
6817          $custombytes = (int)$custombytes;
6818          if (!in_array($custombytes, $sizelist)) {
6819              $sizelist[] = $custombytes;
6820          }
6821      } else if (is_array($custombytes)) {
6822          $sizelist = array_unique(array_merge($sizelist, $custombytes));
6823      }
6824  
6825      // Allow maxbytes to be selected if it falls outside the above boundaries.
6826      if (isset($CFG->maxbytes) && !in_array(get_real_size($CFG->maxbytes), $sizelist)) {
6827          // Note: get_real_size() is used in order to prevent problems with invalid values.
6828          $sizelist[] = get_real_size($CFG->maxbytes);
6829      }
6830  
6831      foreach ($sizelist as $sizebytes) {
6832          if ($sizebytes < $maxsize && $sizebytes > 0) {
6833              $filesize[(string)intval($sizebytes)] = display_size($sizebytes);
6834          }
6835      }
6836  
6837      $limitlevel = '';
6838      $displaysize = '';
6839      if ($modulebytes &&
6840          (($modulebytes < $coursebytes || $coursebytes == 0) &&
6841           ($modulebytes < $sitebytes || $sitebytes == 0))) {
6842          $limitlevel = get_string('activity', 'core');
6843          $displaysize = display_size($modulebytes);
6844          $filesize[$modulebytes] = $displaysize; // Make sure the limit is also included in the list.
6845  
6846      } else if ($coursebytes && ($coursebytes < $sitebytes || $sitebytes == 0)) {
6847          $limitlevel = get_string('course', 'core');
6848          $displaysize = display_size($coursebytes);
6849          $filesize[$coursebytes] = $displaysize; // Make sure the limit is also included in the list.
6850  
6851      } else if ($sitebytes) {
6852          $limitlevel = get_string('site', 'core');
6853          $displaysize = display_size($sitebytes);
6854          $filesize[$sitebytes] = $displaysize; // Make sure the limit is also included in the list.
6855      }
6856  
6857      krsort($filesize, SORT_NUMERIC);
6858      if ($limitlevel) {
6859          $params = (object) array('contextname' => $limitlevel, 'displaysize' => $displaysize);
6860          $filesize  = array('0' => get_string('uploadlimitwithsize', 'core', $params)) + $filesize;
6861      }
6862  
6863      return $filesize;
6864  }
6865  
6866  /**
6867   * Returns an array with all the filenames in all subdirectories, relative to the given rootdir.
6868   *
6869   * If excludefiles is defined, then that file/directory is ignored
6870   * If getdirs is true, then (sub)directories are included in the output
6871   * If getfiles is true, then files are included in the output
6872   * (at least one of these must be true!)
6873   *
6874   * @todo Finish documenting this function. Add examples of $excludefile usage.
6875   *
6876   * @param string $rootdir A given root directory to start from
6877   * @param string|array $excludefiles If defined then the specified file/directory is ignored
6878   * @param bool $descend If true then subdirectories are recursed as well
6879   * @param bool $getdirs If true then (sub)directories are included in the output
6880   * @param bool $getfiles  If true then files are included in the output
6881   * @return array An array with all the filenames in all subdirectories, relative to the given rootdir
6882   */
6883  function get_directory_list($rootdir, $excludefiles='', $descend=true, $getdirs=false, $getfiles=true) {
6884  
6885      $dirs = array();
6886  
6887      if (!$getdirs and !$getfiles) {   // Nothing to show.
6888          return $dirs;
6889      }
6890  
6891      if (!is_dir($rootdir)) {          // Must be a directory.
6892          return $dirs;
6893      }
6894  
6895      if (!$dir = opendir($rootdir)) {  // Can't open it for some reason.
6896          return $dirs;
6897      }
6898  
6899      if (!is_array($excludefiles)) {
6900          $excludefiles = array($excludefiles);
6901      }
6902  
6903      while (false !== ($file = readdir($dir))) {
6904          $firstchar = substr($file, 0, 1);
6905          if ($firstchar == '.' or $file == 'CVS' or in_array($file, $excludefiles)) {
6906              continue;
6907          }
6908          $fullfile = $rootdir .'/'. $file;
6909          if (filetype($fullfile) == 'dir') {
6910              if ($getdirs) {
6911                  $dirs[] = $file;
6912              }
6913              if ($descend) {
6914                  $subdirs = get_directory_list($fullfile, $excludefiles, $descend, $getdirs, $getfiles);
6915                  foreach ($subdirs as $subdir) {
6916                      $dirs[] = $file .'/'. $subdir;
6917                  }
6918              }
6919          } else if ($getfiles) {
6920              $dirs[] = $file;
6921          }
6922      }
6923      closedir($dir);
6924  
6925      asort($dirs);
6926  
6927      return $dirs;
6928  }
6929  
6930  
6931  /**
6932   * Adds up all the files in a directory and works out the size.
6933   *
6934   * @param string $rootdir  The directory to start from
6935   * @param string $excludefile A file to exclude when summing directory size
6936   * @return int The summed size of all files and subfiles within the root directory
6937   */
6938  function get_directory_size($rootdir, $excludefile='') {
6939      global $CFG;
6940  
6941      // Do it this way if we can, it's much faster.
6942      if (!empty($CFG->pathtodu) && is_executable(trim($CFG->pathtodu))) {
6943          $command = trim($CFG->pathtodu).' -sk '.escapeshellarg($rootdir);
6944          $output = null;
6945          $return = null;
6946          exec($command, $output, $return);
6947          if (is_array($output)) {
6948              // We told it to return k.
6949              return get_real_size(intval($output[0]).'k');
6950          }
6951      }
6952  
6953      if (!is_dir($rootdir)) {
6954          // Must be a directory.
6955          return 0;
6956      }
6957  
6958      if (!$dir = @opendir($rootdir)) {
6959          // Can't open it for some reason.
6960          return 0;
6961      }
6962  
6963      $size = 0;
6964  
6965      while (false !== ($file = readdir($dir))) {
6966          $firstchar = substr($file, 0, 1);
6967          if ($firstchar == '.' or $file == 'CVS' or $file == $excludefile) {
6968              continue;
6969          }
6970          $fullfile = $rootdir .'/'. $file;
6971          if (filetype($fullfile) == 'dir') {
6972              $size += get_directory_size($fullfile, $excludefile);
6973          } else {
6974              $size += filesize($fullfile);
6975          }
6976      }
6977      closedir($dir);
6978  
6979      return $size;
6980  }
6981  
6982  /**
6983   * Converts bytes into display form
6984   *
6985   * @static string $gb Localized string for size in gigabytes
6986   * @static string $mb Localized string for size in megabytes
6987   * @static string $kb Localized string for size in kilobytes
6988   * @static string $b Localized string for size in bytes
6989   * @param int $size  The size to convert to human readable form
6990   * @return string
6991   */
6992  function display_size($size) {
6993  
6994      static $units;
6995  
6996      if ($size === USER_CAN_IGNORE_FILE_SIZE_LIMITS) {
6997          return get_string('unlimited');
6998      }
6999  
7000      if (empty($units)) {
7001          $units[] = get_string('sizeb');
7002          $units[] = get_string('sizekb');
7003          $units[] = get_string('sizemb');
7004          $units[] = get_string('sizegb');
7005          $units[] = get_string('sizetb');
7006          $units[] = get_string('sizepb');
7007      }
7008  
7009      if ($size >= 1024 ** 5) {
7010          $size = round($size / 1024 ** 5 * 10) / 10 . $units[5];
7011      } else if ($size >= 1024 ** 4) {
7012          $size = round($size / 1024 ** 4 * 10) / 10 . $units[4];
7013      } else if ($size >= 1024 ** 3) {
7014          $size = round($size / 1024 ** 3 * 10) / 10 . $units[3];
7015      } else if ($size >= 1024 ** 2) {
7016          $size = round($size / 1024 ** 2 * 10) / 10 . $units[2];
7017      } else if ($size >= 1024 ** 1) {
7018          $size = round($size / 1024 ** 1 * 10) / 10 . $units[1];
7019      } else {
7020          $size = intval($size) .' '. $units[0]; // File sizes over 2GB can not work in 32bit PHP anyway.
7021      }
7022      return $size;
7023  }
7024  
7025  /**
7026   * Cleans a given filename by removing suspicious or troublesome characters
7027   *
7028   * @see clean_param()
7029   * @param string $string file name
7030   * @return string cleaned file name
7031   */
7032  function clean_filename($string) {
7033      return clean_param($string, PARAM_FILE);
7034  }
7035  
7036  // STRING TRANSLATION.
7037  
7038  /**
7039   * Returns the code for the current language
7040   *
7041   * @category string
7042   * @return string
7043   */
7044  function current_language() {
7045      global $CFG, $USER, $SESSION, $COURSE;
7046  
7047      if (!empty($SESSION->forcelang)) {
7048          // Allows overriding course-forced language (useful for admins to check
7049          // issues in courses whose language they don't understand).
7050          // Also used by some code to temporarily get language-related information in a
7051          // specific language (see force_current_language()).
7052          $return = $SESSION->forcelang;
7053  
7054      } else if (!empty($COURSE->id) and $COURSE->id != SITEID and !empty($COURSE->lang)) {
7055          // Course language can override all other settings for this page.
7056          $return = $COURSE->lang;
7057  
7058      } else if (!empty($SESSION->lang)) {
7059          // Session language can override other settings.
7060          $return = $SESSION->lang;
7061  
7062      } else if (!empty($USER->lang)) {
7063          $return = $USER->lang;
7064  
7065      } else if (isset($CFG->lang)) {
7066          $return = $CFG->lang;
7067  
7068      } else {
7069          $return = 'en';
7070      }
7071  
7072      // Just in case this slipped in from somewhere by accident.
7073      $return = str_replace('_utf8', '', $return);
7074  
7075      return $return;
7076  }
7077  
7078  /**
7079   * Fix the current language to the given language code.
7080   *
7081   * @param string $lang The language code to use.
7082   * @return void
7083   */
7084  function fix_current_language(string $lang): void {
7085      global $CFG, $COURSE, $SESSION, $USER;
7086  
7087      if (!get_string_manager()->translation_exists($lang)) {
7088          throw new coding_exception("The language pack for $lang is not available");
7089      }
7090  
7091      $fixglobal = '';
7092      $fixlang = 'lang';
7093      if (!empty($SESSION->forcelang)) {
7094          $fixglobal = $SESSION;
7095          $fixlang = 'forcelang';
7096      } else if (!empty($COURSE->id) && $COURSE->id != SITEID && !empty($COURSE->lang)) {
7097          $fixglobal = $COURSE;
7098      } else if (!empty($SESSION->lang)) {
7099          $fixglobal = $SESSION;
7100      } else if (!empty($USER->lang)) {
7101          $fixglobal = $USER;
7102      } else if (isset($CFG->lang)) {
7103          set_config('lang', $lang);
7104      }
7105  
7106      if ($fixglobal) {
7107          $fixglobal->$fixlang = $lang;
7108      }
7109  }
7110  
7111  /**
7112   * Returns parent language of current active language if defined
7113   *
7114   * @category string
7115   * @param string $lang null means current language
7116   * @return string
7117   */
7118  function get_parent_language($lang=null) {
7119  
7120      $parentlang = get_string_manager()->get_string('parentlanguage', 'langconfig', null, $lang);
7121  
7122      if ($parentlang === 'en') {
7123          $parentlang = '';
7124      }
7125  
7126      return $parentlang;
7127  }
7128  
7129  /**
7130   * Force the current language to get strings and dates localised in the given language.
7131   *
7132   * After calling this function, all strings will be provided in the given language
7133   * until this function is called again, or equivalent code is run.
7134   *
7135   * @param string $language
7136   * @return string previous $SESSION->forcelang value
7137   */
7138  function force_current_language($language) {
7139      global $SESSION;
7140      $sessionforcelang = isset($SESSION->forcelang) ? $SESSION->forcelang : '';
7141      if ($language !== $sessionforcelang) {
7142          // Seting forcelang to null or an empty string disables it's effect.
7143          if (empty($language) || get_string_manager()->translation_exists($language, false)) {
7144              $SESSION->forcelang = $language;
7145              moodle_setlocale();
7146          }
7147      }
7148      return $sessionforcelang;
7149  }
7150  
7151  /**
7152   * Returns current string_manager instance.
7153   *
7154   * The param $forcereload is needed for CLI installer only where the string_manager instance
7155   * must be replaced during the install.php script life time.
7156   *
7157   * @category string
7158   * @param bool $forcereload shall the singleton be released and new instance created instead?
7159   * @return core_string_manager
7160   */
7161  function get_string_manager($forcereload=false) {
7162      global $CFG;
7163  
7164      static $singleton = null;
7165  
7166      if ($forcereload) {
7167          $singleton = null;
7168      }
7169      if ($singleton === null) {
7170          if (empty($CFG->early_install_lang)) {
7171  
7172              $transaliases = array();
7173              if (empty($CFG->langlist)) {
7174                   $translist = array();
7175              } else {
7176                  $translist = explode(',', $CFG->langlist);
7177                  $translist = array_map('trim', $translist);
7178                  // Each language in the $CFG->langlist can has an "alias" that would substitute the default language name.
7179                  foreach ($translist as $i => $value) {
7180                      $parts = preg_split('/\s*\|\s*/', $value, 2);
7181                      if (count($parts) == 2) {
7182                          $transaliases[$parts[0]] = $parts[1];
7183                          $translist[$i] = $parts[0];
7184                      }
7185                  }
7186              }
7187  
7188              if (!empty($CFG->config_php_settings['customstringmanager'])) {
7189                  $classname = $CFG->config_php_settings['customstringmanager'];
7190  
7191                  if (class_exists($classname)) {
7192                      $implements = class_implements($classname);
7193  
7194                      if (isset($implements['core_string_manager'])) {
7195                          $singleton = new $classname($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7196                          return $singleton;
7197  
7198                      } else {
7199                          debugging('Unable to instantiate custom string manager: class '.$classname.
7200                              ' does not implement the core_string_manager interface.');
7201                      }
7202  
7203                  } else {
7204                      debugging('Unable to instantiate custom string manager: class '.$classname.' can not be found.');
7205                  }
7206              }
7207  
7208              $singleton = new core_string_manager_standard($CFG->langotherroot, $CFG->langlocalroot, $translist, $transaliases);
7209  
7210          } else {
7211              $singleton = new core_string_manager_install();
7212          }
7213      }
7214  
7215      return $singleton;
7216  }
7217  
7218  /**
7219   * Returns a localized string.
7220   *
7221   * Returns the translated string specified by $identifier as
7222   * for $module.  Uses the same format files as STphp.
7223   * $a is an object, string or number that can be used
7224   * within translation strings
7225   *
7226   * eg 'hello {$a->firstname} {$a->lastname}'
7227   * or 'hello {$a}'
7228   *
7229   * If you would like to directly echo the localized string use
7230   * the function {@link print_string()}
7231   *
7232   * Example usage of this function involves finding the string you would
7233   * like a local equivalent of and using its identifier and module information
7234   * to retrieve it.<br/>
7235   * If you open moodle/lang/en/moodle.php and look near line 278
7236   * you will find a string to prompt a user for their word for 'course'
7237   * <code>
7238   * $string['course'] = 'Course';
7239   * </code>
7240   * So if you want to display the string 'Course'
7241   * in any language that supports it on your site
7242   * you just need to use the identifier 'course'
7243   * <code>
7244   * $mystring = '<strong>'. get_string('course') .'</strong>';
7245   * or
7246   * </code>
7247   * If the string you want is in another file you'd take a slightly
7248   * different approach. Looking in moodle/lang/en/calendar.php you find
7249   * around line 75:
7250   * <code>
7251   * $string['typecourse'] = 'Course event';
7252   * </code>
7253   * If you want to display the string "Course event" in any language
7254   * supported you would use the identifier 'typecourse' and the module 'calendar'
7255   * (because it is in the file calendar.php):
7256   * <code>
7257   * $mystring = '<h1>'. get_string('typecourse', 'calendar') .'</h1>';
7258   * </code>
7259   *
7260   * As a last resort, should the identifier fail to map to a string
7261   * the returned string will be [[ $identifier ]]
7262   *
7263   * In Moodle 2.3 there is a new argument to this function $lazyload.
7264   * Setting $lazyload to true causes get_string to return a lang_string object
7265   * rather than the string itself. The fetching of the string is then put off until
7266   * the string object is first used. The object can be used by calling it's out
7267   * method or by casting the object to a string, either directly e.g.
7268   *     (string)$stringobject
7269   * or indirectly by using the string within another string or echoing it out e.g.
7270   *     echo $stringobject
7271   *     return "<p>{$stringobject}</p>";
7272   * It is worth noting that using $lazyload and attempting to use the string as an
7273   * array key will cause a fatal error as objects cannot be used as array keys.
7274   * But you should never do that anyway!
7275   * For more information {@link lang_string}
7276   *
7277   * @category string
7278   * @param string $identifier The key identifier for the localized string
7279   * @param string $component The module where the key identifier is stored,
7280   *      usually expressed as the filename in the language pack without the
7281   *      .php on the end but can also be written as mod/forum or grade/export/xls.
7282   *      If none is specified then moodle.php is used.
7283   * @param string|object|array $a An object, string or number that can be used
7284   *      within translation strings
7285   * @param bool $lazyload If set to true a string object is returned instead of
7286   *      the string itself. The string then isn't calculated until it is first used.
7287   * @return string The localized string.
7288   * @throws coding_exception
7289   */
7290  function get_string($identifier, $component = '', $a = null, $lazyload = false) {
7291      global $CFG;
7292  
7293      // If the lazy load argument has been supplied return a lang_string object
7294      // instead.
7295      // We need to make sure it is true (and a bool) as you will see below there
7296      // used to be a forth argument at one point.
7297      if ($lazyload === true) {
7298          return new lang_string($identifier, $component, $a);
7299      }
7300  
7301      if ($CFG->debugdeveloper && clean_param($identifier, PARAM_STRINGID) === '') {
7302          throw new coding_exception('Invalid string identifier. The identifier cannot be empty. Please fix your get_string() call.', DEBUG_DEVELOPER);
7303      }
7304  
7305      // There is now a forth argument again, this time it is a boolean however so
7306      // we can still check for the old extralocations parameter.
7307      if (!is_bool($lazyload) && !empty($lazyload)) {
7308          debugging('extralocations parameter in get_string() is not supported any more, please use standard lang locations only.');
7309      }
7310  
7311      if (strpos($component, '/') !== false) {
7312          debugging('The module name you passed to get_string is the deprecated format ' .
7313                  'like mod/mymod or block/myblock. The correct form looks like mymod, or block_myblock.' , DEBUG_DEVELOPER);
7314          $componentpath = explode('/', $component);
7315  
7316          switch ($componentpath[0]) {
7317              case 'mod':
7318                  $component = $componentpath[1];
7319                  break;
7320              case 'blocks':
7321              case 'block':
7322                  $component = 'block_'.$componentpath[1];
7323                  break;
7324              case 'enrol':
7325                  $component = 'enrol_'.$componentpath[1];
7326                  break;
7327              case 'format':
7328                  $component = 'format_'.$componentpath[1];
7329                  break;
7330              case 'grade':
7331                  $component = 'grade'.$componentpath[1].'_'.$componentpath[2];
7332                  break;
7333          }
7334      }
7335  
7336      $result = get_string_manager()->get_string($identifier, $component, $a);
7337  
7338      // Debugging feature lets you display string identifier and component.
7339      if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
7340          $result .= ' {' . $identifier . '/' . $component . '}';
7341      }
7342      return $result;
7343  }
7344  
7345  /**
7346   * Converts an array of strings to their localized value.
7347   *
7348   * @param array $array An array of strings
7349   * @param string $component The language module that these strings can be found in.
7350   * @return stdClass translated strings.
7351   */
7352  function get_strings($array, $component = '') {
7353      $string = new stdClass;
7354      foreach ($array as $item) {
7355          $string->$item = get_string($item, $component);
7356      }
7357      return $string;
7358  }
7359  
7360  /**
7361   * Prints out a translated string.
7362   *
7363   * Prints out a translated string using the return value from the {@link get_string()} function.
7364   *
7365   * Example usage of this function when the string is in the moodle.php file:<br/>
7366   * <code>
7367   * echo '<strong>';
7368   * print_string('course');
7369   * echo '</strong>';
7370   * </code>
7371   *
7372   * Example usage of this function when the string is not in the moodle.php file:<br/>
7373   * <code>
7374   * echo '<h1>';
7375   * print_string('typecourse', 'calendar');
7376   * echo '</h1>';
7377   * </code>
7378   *
7379   * @category string
7380   * @param string $identifier The key identifier for the localized string
7381   * @param string $component The module where the key identifier is stored. If none is specified then moodle.php is used.
7382   * @param string|object|array $a An object, string or number that can be used within translation strings
7383   */
7384  function print_string($identifier, $component = '', $a = null) {
7385      echo get_string($identifier, $component, $a);
7386  }
7387  
7388  /**
7389   * Returns a list of charset codes
7390   *
7391   * Returns a list of charset codes. It's hardcoded, so they should be added manually
7392   * (checking that such charset is supported by the texlib library!)
7393   *
7394   * @return array And associative array with contents in the form of charset => charset
7395   */
7396  function get_list_of_charsets() {
7397  
7398      $charsets = array(
7399          'EUC-JP'     => 'EUC-JP',
7400          'ISO-2022-JP'=> 'ISO-2022-JP',
7401          'ISO-8859-1' => 'ISO-8859-1',
7402          'SHIFT-JIS'  => 'SHIFT-JIS',
7403          'GB2312'     => 'GB2312',
7404          'GB18030'    => 'GB18030', // GB18030 not supported by typo and mbstring.
7405          'UTF-8'      => 'UTF-8');
7406  
7407      asort($charsets);
7408  
7409      return $charsets;
7410  }
7411  
7412  /**
7413   * Returns a list of valid and compatible themes
7414   *
7415   * @return array
7416   */
7417  function get_list_of_themes() {
7418      global $CFG;
7419  
7420      $themes = array();
7421  
7422      if (!empty($CFG->themelist)) {       // Use admin's list of themes.
7423          $themelist = explode(',', $CFG->themelist);
7424      } else {
7425          $themelist = array_keys(core_component::get_plugin_list("theme"));
7426      }
7427  
7428      foreach ($themelist as $key => $themename) {
7429          $theme = theme_config::load($themename);
7430          $themes[$themename] = $theme;
7431      }
7432  
7433      core_collator::asort_objects_by_method($themes, 'get_theme_name');
7434  
7435      return $themes;
7436  }
7437  
7438  /**
7439   * Factory function for emoticon_manager
7440   *
7441   * @return emoticon_manager singleton
7442   */
7443  function get_emoticon_manager() {
7444      static $singleton = null;
7445  
7446      if (is_null($singleton)) {
7447          $singleton = new emoticon_manager();
7448      }
7449  
7450      return $singleton;
7451  }
7452  
7453  /**
7454   * Provides core support for plugins that have to deal with emoticons (like HTML editor or emoticon filter).
7455   *
7456   * Whenever this manager mentiones 'emoticon object', the following data
7457   * structure is expected: stdClass with properties text, imagename, imagecomponent,
7458   * altidentifier and altcomponent
7459   *
7460   * @see admin_setting_emoticons
7461   *
7462   * @copyright 2010 David Mudrak
7463   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
7464   */
7465  class emoticon_manager {
7466  
7467      /**
7468       * Returns the currently enabled emoticons
7469       *
7470       * @param boolean $selectable - If true, only return emoticons that should be selectable from a list.
7471       * @return array of emoticon objects
7472       */
7473      public function get_emoticons($selectable = false) {
7474          global $CFG;
7475          $notselectable = ['martin', 'egg'];
7476  
7477          if (empty($CFG->emoticons)) {
7478              return array();
7479          }
7480  
7481          $emoticons = $this->decode_stored_config($CFG->emoticons);
7482  
7483          if (!is_array($emoticons)) {
7484              // Something is wrong with the format of stored setting.
7485              debugging('Invalid format of emoticons setting, please resave the emoticons settings form', DEBUG_NORMAL);
7486              return array();
7487          }
7488          if ($selectable) {
7489              foreach ($emoticons as $index => $emote) {
7490                  if (in_array($emote->altidentifier, $notselectable)) {
7491                      // Skip this one.
7492                      unset($emoticons[$index]);
7493                  }
7494              }
7495          }
7496  
7497          return $emoticons;
7498      }
7499  
7500      /**
7501       * Converts emoticon object into renderable pix_emoticon object
7502       *
7503       * @param stdClass $emoticon emoticon object
7504       * @param array $attributes explicit HTML attributes to set
7505       * @return pix_emoticon
7506       */
7507      public function prepare_renderable_emoticon(stdClass $emoticon, array $attributes = array()) {
7508          $stringmanager = get_string_manager();
7509          if ($stringmanager->string_exists($emoticon->altidentifier, $emoticon->altcomponent)) {
7510              $alt = get_string($emoticon->altidentifier, $emoticon->altcomponent);
7511          } else {
7512              $alt = s($emoticon->text);
7513          }
7514          return new pix_emoticon($emoticon->imagename, $alt, $emoticon->imagecomponent, $attributes);
7515      }
7516  
7517      /**
7518       * Encodes the array of emoticon objects into a string storable in config table
7519       *
7520       * @see self::decode_stored_config()
7521       * @param array $emoticons array of emtocion objects
7522       * @return string
7523       */
7524      public function encode_stored_config(array $emoticons) {
7525          return json_encode($emoticons);
7526      }
7527  
7528      /**
7529       * Decodes the string into an array of emoticon objects
7530       *
7531       * @see self::encode_stored_config()
7532       * @param string $encoded
7533       * @return string|null
7534       */
7535      public function decode_stored_config($encoded) {
7536          $decoded = json_decode($encoded);
7537          if (!is_array($decoded)) {
7538              return null;
7539          }
7540          return $decoded;
7541      }
7542  
7543      /**
7544       * Returns default set of emoticons supported by Moodle
7545       *
7546       * @return array of sdtClasses
7547       */
7548      public function default_emoticons() {
7549          return array(
7550              $this->prepare_emoticon_object(":-)", 's/smiley', 'smiley'),
7551              $this->prepare_emoticon_object(":)", 's/smiley', 'smiley'),
7552              $this->prepare_emoticon_object(":-D", 's/biggrin', 'biggrin'),
7553              $this->prepare_emoticon_object(";-)", 's/wink', 'wink'),
7554              $this->prepare_emoticon_object(":-/", 's/mixed', 'mixed'),
7555              $this->prepare_emoticon_object("V-.", 's/thoughtful', 'thoughtful'),
7556              $this->prepare_emoticon_object(":-P", 's/tongueout', 'tongueout'),
7557              $this->prepare_emoticon_object(":-p", 's/tongueout', 'tongueout'),
7558              $this->prepare_emoticon_object("B-)", 's/cool', 'cool'),
7559              $this->prepare_emoticon_object("^-)", 's/approve', 'approve'),
7560              $this->prepare_emoticon_object("8-)", 's/wideeyes', 'wideeyes'),
7561              $this->prepare_emoticon_object(":o)", 's/clown', 'clown'),
7562              $this->prepare_emoticon_object(":-(", 's/sad', 'sad'),
7563              $this->prepare_emoticon_object(":(", 's/sad', 'sad'),
7564              $this->prepare_emoticon_object("8-.", 's/shy', 'shy'),
7565              $this->prepare_emoticon_object(":-I", 's/blush', 'blush'),
7566              $this->prepare_emoticon_object(":-X", 's/kiss', 'kiss'),
7567              $this->prepare_emoticon_object("8-o", 's/surprise', 'surprise'),
7568              $this->prepare_emoticon_object("P-|", 's/blackeye', 'blackeye'),
7569              $this->prepare_emoticon_object("8-[", 's/angry', 'angry'),
7570              $this->prepare_emoticon_object("(grr)", 's/angry', 'angry'),
7571              $this->prepare_emoticon_object("xx-P", 's/dead', 'dead'),
7572              $this->prepare_emoticon_object("|-.", 's/sleepy', 'sleepy'),
7573              $this->prepare_emoticon_object("}-]", 's/evil', 'evil'),
7574              $this->prepare_emoticon_object("(h)", 's/heart', 'heart'),
7575              $this->prepare_emoticon_object("(heart)", 's/heart', 'heart'),
7576              $this->prepare_emoticon_object("(y)", 's/yes', 'yes', 'core'),
7577              $this->prepare_emoticon_object("(n)", 's/no', 'no', 'core'),
7578              $this->prepare_emoticon_object("(martin)", 's/martin', 'martin'),
7579              $this->prepare_emoticon_object("( )", 's/egg', 'egg'),
7580          );
7581      }
7582  
7583      /**
7584       * Helper method preparing the stdClass with the emoticon properties
7585       *
7586       * @param string|array $text or array of strings
7587       * @param string $imagename to be used by {@link pix_emoticon}
7588       * @param string $altidentifier alternative string identifier, null for no alt
7589       * @param string $altcomponent where the alternative string is defined
7590       * @param string $imagecomponent to be used by {@link pix_emoticon}
7591       * @return stdClass
7592       */
7593      protected function prepare_emoticon_object($text, $imagename, $altidentifier = null,
7594                                                 $altcomponent = 'core_pix', $imagecomponent = 'core') {
7595          return (object)array(
7596              'text'           => $text,
7597              'imagename'      => $imagename,
7598              'imagecomponent' => $imagecomponent,
7599              'altidentifier'  => $altidentifier,
7600              'altcomponent'   => $altcomponent,
7601          );
7602      }
7603  }
7604  
7605  // ENCRYPTION.
7606  
7607  /**
7608   * rc4encrypt
7609   *
7610   * @param string $data        Data to encrypt.
7611   * @return string             The now encrypted data.
7612   */
7613  function rc4encrypt($data) {
7614      return endecrypt(get_site_identifier(), $data, '');
7615  }
7616  
7617  /**
7618   * rc4decrypt
7619   *
7620   * @param string $data        Data to decrypt.
7621   * @return string             The now decrypted data.
7622   */
7623  function rc4decrypt($data) {
7624      return endecrypt(get_site_identifier(), $data, 'de');
7625  }
7626  
7627  /**
7628   * Based on a class by Mukul Sabharwal [mukulsabharwal @ yahoo.com]
7629   *
7630   * @todo Finish documenting this function
7631   *
7632   * @param string $pwd The password to use when encrypting or decrypting
7633   * @param string $data The data to be decrypted/encrypted
7634   * @param string $case Either 'de' for decrypt or '' for encrypt
7635   * @return string
7636   */
7637  function endecrypt ($pwd, $data, $case) {
7638  
7639      if ($case == 'de') {
7640          $data = urldecode($data);
7641      }
7642  
7643      $key[] = '';
7644      $box[] = '';
7645      $pwdlength = strlen($pwd);
7646  
7647      for ($i = 0; $i <= 255; $i++) {
7648          $key[$i] = ord(substr($pwd, ($i % $pwdlength), 1));
7649          $box[$i] = $i;
7650      }
7651  
7652      $x = 0;
7653  
7654      for ($i = 0; $i <= 255; $i++) {
7655          $x = ($x + $box[$i] + $key[$i]) % 256;
7656          $tempswap = $box[$i];
7657          $box[$i] = $box[$x];
7658          $box[$x] = $tempswap;
7659      }
7660  
7661      $cipher = '';
7662  
7663      $a = 0;
7664      $j = 0;
7665  
7666      for ($i = 0; $i < strlen($data); $i++) {
7667          $a = ($a + 1) % 256;
7668          $j = ($j + $box[$a]) % 256;
7669          $temp = $box[$a];
7670          $box[$a] = $box[$j];
7671          $box[$j] = $temp;
7672          $k = $box[(($box[$a] + $box[$j]) % 256)];
7673          $cipherby = ord(substr($data, $i, 1)) ^ $k;
7674          $cipher .= chr($cipherby);
7675      }
7676  
7677      if ($case == 'de') {
7678          $cipher = urldecode(urlencode($cipher));
7679      } else {
7680          $cipher = urlencode($cipher);
7681      }
7682  
7683      return $cipher;
7684  }
7685  
7686  // ENVIRONMENT CHECKING.
7687  
7688  /**
7689   * This method validates a plug name. It is much faster than calling clean_param.
7690   *
7691   * @param string $name a string that might be a plugin name.
7692   * @return bool if this string is a valid plugin name.
7693   */
7694  function is_valid_plugin_name($name) {
7695      // This does not work for 'mod', bad luck, use any other type.
7696      return core_component::is_valid_plugin_name('tool', $name);
7697  }
7698  
7699  /**
7700   * Get a list of all the plugins of a given type that define a certain API function
7701   * in a certain file. The plugin component names and function names are returned.
7702   *
7703   * @param string $plugintype the type of plugin, e.g. 'mod' or 'report'.
7704   * @param string $function the part of the name of the function after the
7705   *      frankenstyle prefix. e.g 'hook' if you are looking for functions with
7706   *      names like report_courselist_hook.
7707   * @param string $file the name of file within the plugin that defines the
7708   *      function. Defaults to lib.php.
7709   * @return array with frankenstyle plugin names as keys (e.g. 'report_courselist', 'mod_forum')
7710   *      and the function names as values (e.g. 'report_courselist_hook', 'forum_hook').
7711   */
7712  function get_plugin_list_with_function($plugintype, $function, $file = 'lib.php') {
7713      global $CFG;
7714  
7715      // We don't include here as all plugin types files would be included.
7716      $plugins = get_plugins_with_function($function, $file, false);
7717  
7718      if (empty($plugins[$plugintype])) {
7719          return array();
7720      }
7721  
7722      $allplugins = core_component::get_plugin_list($plugintype);
7723  
7724      // Reformat the array and include the files.
7725      $pluginfunctions = array();
7726      foreach ($plugins[$plugintype] as $pluginname => $functionname) {
7727  
7728          // Check that it has not been removed and the file is still available.
7729          if (!empty($allplugins[$pluginname])) {
7730  
7731              $filepath = $allplugins[$pluginname] . DIRECTORY_SEPARATOR . $file;
7732              if (file_exists($filepath)) {
7733                  include_once($filepath);
7734  
7735                  // Now that the file is loaded, we must verify the function still exists.
7736                  if (function_exists($functionname)) {
7737                      $pluginfunctions[$plugintype . '_' . $pluginname] = $functionname;
7738                  } else {
7739                      // Invalidate the cache for next run.
7740                      \cache_helper::invalidate_by_definition('core', 'plugin_functions');
7741                  }
7742              }
7743          }
7744      }
7745  
7746      return $pluginfunctions;
7747  }
7748  
7749  /**
7750   * Get a list of all the plugins that define a certain API function in a certain file.
7751   *
7752   * @param string $function the part of the name of the function after the
7753   *      frankenstyle prefix. e.g 'hook' if you are looking for functions with
7754   *      names like report_courselist_hook.
7755   * @param string $file the name of file within the plugin that defines the
7756   *      function. Defaults to lib.php.
7757   * @param bool $include Whether to include the files that contain the functions or not.
7758   * @return array with [plugintype][plugin] = functionname
7759   */
7760  function get_plugins_with_function($function, $file = 'lib.php', $include = true) {
7761      global $CFG;
7762  
7763      if (during_initial_install() || isset($CFG->upgraderunning)) {
7764          // API functions _must not_ be called during an installation or upgrade.
7765          return [];
7766      }
7767  
7768      $cache = \cache::make('core', 'plugin_functions');
7769  
7770      // Including both although I doubt that we will find two functions definitions with the same name.
7771      // Clearning the filename as cache_helper::hash_key only allows a-zA-Z0-9_.
7772      $key = $function . '_' . clean_param($file, PARAM_ALPHA);
7773      $pluginfunctions = $cache->get($key);
7774      $dirty = false;
7775  
7776      // Use the plugin manager to check that plugins are currently installed.
7777      $pluginmanager = \core_plugin_manager::instance();
7778  
7779      if ($pluginfunctions !== false) {
7780  
7781          // Checking that the files are still available.
7782          foreach ($pluginfunctions as $plugintype => $plugins) {
7783  
7784              $allplugins = \core_component::get_plugin_list($plugintype);
7785              $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7786              foreach ($plugins as $plugin => $function) {
7787                  if (!isset($installedplugins[$plugin])) {
7788                      // Plugin code is still present on disk but it is not installed.
7789                      $dirty = true;
7790                      break 2;
7791                  }
7792  
7793                  // Cache might be out of sync with the codebase, skip the plugin if it is not available.
7794                  if (empty($allplugins[$plugin])) {
7795                      $dirty = true;
7796                      break 2;
7797                  }
7798  
7799                  $fileexists = file_exists($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7800                  if ($include && $fileexists) {
7801                      // Include the files if it was requested.
7802                      include_once($allplugins[$plugin] . DIRECTORY_SEPARATOR . $file);
7803                  } else if (!$fileexists) {
7804                      // If the file is not available any more it should not be returned.
7805                      $dirty = true;
7806                      break 2;
7807                  }
7808  
7809                  // Check if the function still exists in the file.
7810                  if ($include && !function_exists($function)) {
7811                      $dirty = true;
7812                      break 2;
7813                  }
7814              }
7815          }
7816  
7817          // If the cache is dirty, we should fall through and let it rebuild.
7818          if (!$dirty) {
7819              return $pluginfunctions;
7820          }
7821      }
7822  
7823      $pluginfunctions = array();
7824  
7825      // To fill the cached. Also, everything should continue working with cache disabled.
7826      $plugintypes = \core_component::get_plugin_types();
7827      foreach ($plugintypes as $plugintype => $unused) {
7828  
7829          // We need to include files here.
7830          $pluginswithfile = \core_component::get_plugin_list_with_file($plugintype, $file, true);
7831          $installedplugins = $pluginmanager->get_installed_plugins($plugintype);
7832          foreach ($pluginswithfile as $plugin => $notused) {
7833  
7834              if (!isset($installedplugins[$plugin])) {
7835                  continue;
7836              }
7837  
7838              $fullfunction = $plugintype . '_' . $plugin . '_' . $function;
7839  
7840              $pluginfunction = false;
7841              if (function_exists($fullfunction)) {
7842                  // Function exists with standard name. Store, indexed by frankenstyle name of plugin.
7843                  $pluginfunction = $fullfunction;
7844  
7845              } else if ($plugintype === 'mod') {
7846                  // For modules, we also allow plugin without full frankenstyle but just starting with the module name.
7847                  $shortfunction = $plugin . '_' . $function;
7848                  if (function_exists($shortfunction)) {
7849                      $pluginfunction = $shortfunction;
7850                  }
7851              }
7852  
7853              if ($pluginfunction) {
7854                  if (empty($pluginfunctions[$plugintype])) {
7855                      $pluginfunctions[$plugintype] = array();
7856                  }
7857                  $pluginfunctions[$plugintype][$plugin] = $pluginfunction;
7858              }
7859  
7860          }
7861      }
7862      $cache->set($key, $pluginfunctions);
7863  
7864      return $pluginfunctions;
7865  
7866  }
7867  
7868  /**
7869   * Lists plugin-like directories within specified directory
7870   *
7871   * This function was originally used for standard Moodle plugins, please use
7872   * new core_component::get_plugin_list() now.
7873   *
7874   * This function is used for general directory listing and backwards compatility.
7875   *
7876   * @param string $directory relative directory from root
7877   * @param string $exclude dir name to exclude from the list (defaults to none)
7878   * @param string $basedir full path to the base dir where $plugin resides (defaults to $CFG->dirroot)
7879   * @return array Sorted array of directory names found under the requested parameters
7880   */
7881  function get_list_of_plugins($directory='mod', $exclude='', $basedir='') {
7882      global $CFG;
7883  
7884      $plugins = array();
7885  
7886      if (empty($basedir)) {
7887          $basedir = $CFG->dirroot .'/'. $directory;
7888  
7889      } else {
7890          $basedir = $basedir .'/'. $directory;
7891      }
7892  
7893      if ($CFG->debugdeveloper and empty($exclude)) {
7894          // Make sure devs do not use this to list normal plugins,
7895          // this is intended for general directories that are not plugins!
7896  
7897          $subtypes = core_component::get_plugin_types();
7898          if (in_array($basedir, $subtypes)) {
7899              debugging('get_list_of_plugins() should not be used to list real plugins, use core_component::get_plugin_list() instead!', DEBUG_DEVELOPER);
7900          }
7901          unset($subtypes);
7902      }
7903  
7904      if (file_exists($basedir) && filetype($basedir) == 'dir') {
7905          if (!$dirhandle = opendir($basedir)) {
7906              debugging("Directory permission error for plugin ({$directory}). Directory exists but cannot be read.", DEBUG_DEVELOPER);
7907              return array();
7908          }
7909          while (false !== ($dir = readdir($dirhandle))) {
7910              // Func: strpos is marginally but reliably faster than substr($dir, 0, 1).
7911              if (strpos($dir, '.') === 0 or $dir === 'CVS' or $dir === '_vti_cnf' or $dir === 'simpletest' or $dir === 'yui' or
7912                  $dir === 'tests' or $dir === 'classes' or $dir === $exclude) {
7913                  continue;
7914              }
7915              if (filetype($basedir .'/'. $dir) != 'dir') {
7916                  continue;
7917              }
7918              $plugins[] = $dir;
7919          }
7920          closedir($dirhandle);
7921      }
7922      if ($plugins) {
7923          asort($plugins);
7924      }
7925      return $plugins;
7926  }
7927  
7928  /**
7929   * Invoke plugin's callback functions
7930   *
7931   * @param string $type plugin type e.g. 'mod'
7932   * @param string $name plugin name
7933   * @param string $feature feature name
7934   * @param string $action feature's action
7935   * @param array $params parameters of callback function, should be an array
7936   * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7937   * @return mixed
7938   *
7939   * @todo Decide about to deprecate and drop plugin_callback() - MDL-30743
7940   */
7941  function plugin_callback($type, $name, $feature, $action, $params = null, $default = null) {
7942      return component_callback($type . '_' . $name, $feature . '_' . $action, (array) $params, $default);
7943  }
7944  
7945  /**
7946   * Invoke component's callback functions
7947   *
7948   * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7949   * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7950   * @param array $params parameters of callback function
7951   * @param mixed $default default value if callback function hasn't been defined, or if it retursn null.
7952   * @return mixed
7953   */
7954  function component_callback($component, $function, array $params = array(), $default = null) {
7955  
7956      $functionname = component_callback_exists($component, $function);
7957  
7958      if ($params && (array_keys($params) !== range(0, count($params) - 1))) {
7959          // PHP 8 allows to have associative arrays in the call_user_func_array() parameters but
7960          // PHP 7 does not. Using associative arrays can result in different behavior in different PHP versions.
7961          // See https://php.watch/versions/8.0/named-parameters#named-params-call_user_func_array
7962          // This check can be removed when minimum PHP version for Moodle is raised to 8.
7963          debugging('Parameters array can not be an associative array while Moodle supports both PHP 7 and PHP 8.',
7964              DEBUG_DEVELOPER);
7965          $params = array_values($params);
7966      }
7967  
7968      if ($functionname) {
7969          // Function exists, so just return function result.
7970          $ret = call_user_func_array($functionname, $params);
7971          if (is_null($ret)) {
7972              return $default;
7973          } else {
7974              return $ret;
7975          }
7976      }
7977      return $default;
7978  }
7979  
7980  /**
7981   * Determine if a component callback exists and return the function name to call. Note that this
7982   * function will include the required library files so that the functioname returned can be
7983   * called directly.
7984   *
7985   * @param string $component frankenstyle component name, e.g. 'mod_quiz'
7986   * @param string $function the rest of the function name, e.g. 'cron' will end up calling 'mod_quiz_cron'
7987   * @return mixed Complete function name to call if the callback exists or false if it doesn't.
7988   * @throws coding_exception if invalid component specfied
7989   */
7990  function component_callback_exists($component, $function) {
7991      global $CFG; // This is needed for the inclusions.
7992  
7993      $cleancomponent = clean_param($component, PARAM_COMPONENT);
7994      if (empty($cleancomponent)) {
7995          throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
7996      }
7997      $component = $cleancomponent;
7998  
7999      list($type, $name) = core_component::normalize_component($component);
8000      $component = $type . '_' . $name;
8001  
8002      $oldfunction = $name.'_'.$function;
8003      $function = $component.'_'.$function;
8004  
8005      $dir = core_component::get_component_directory($component);
8006      if (empty($dir)) {
8007          throw new coding_exception('Invalid component used in plugin/component_callback():' . $component);
8008      }
8009  
8010      // Load library and look for function.
8011      if (file_exists($dir.'/lib.php')) {
8012          require_once($dir.'/lib.php');
8013      }
8014  
8015      if (!function_exists($function) and function_exists($oldfunction)) {
8016          if ($type !== 'mod' and $type !== 'core') {
8017              debugging("Please use new function name $function instead of legacy $oldfunction", DEBUG_DEVELOPER);
8018          }
8019          $function = $oldfunction;
8020      }
8021  
8022      if (function_exists($function)) {
8023          return $function;
8024      }
8025      return false;
8026  }
8027  
8028  /**
8029   * Call the specified callback method on the provided class.
8030   *
8031   * If the callback returns null, then the default value is returned instead.
8032   * If the class does not exist, then the default value is returned.
8033   *
8034   * @param   string      $classname The name of the class to call upon.
8035   * @param   string      $methodname The name of the staticically defined method on the class.
8036   * @param   array       $params The arguments to pass into the method.
8037   * @param   mixed       $default The default value.
8038   * @return  mixed       The return value.
8039   */
8040  function component_class_callback($classname, $methodname, array $params, $default = null) {
8041      if (!class_exists($classname)) {
8042          return $default;
8043      }
8044  
8045      if (!method_exists($classname, $methodname)) {
8046          return $default;
8047      }
8048  
8049      $fullfunction = $classname . '::' . $methodname;
8050      $result = call_user_func_array($fullfunction, $params);
8051  
8052      if (null === $result) {
8053          return $default;
8054      } else {
8055          return $result;
8056      }
8057  }
8058  
8059  /**
8060   * Checks whether a plugin supports a specified feature.
8061   *
8062   * @param string $type Plugin type e.g. 'mod'
8063   * @param string $name Plugin name e.g. 'forum'
8064   * @param string $feature Feature code (FEATURE_xx constant)
8065   * @param mixed $default default value if feature support unknown
8066   * @return mixed Feature result (false if not supported, null if feature is unknown,
8067   *         otherwise usually true but may have other feature-specific value such as array)
8068   * @throws coding_exception
8069   */
8070  function plugin_supports($type, $name, $feature, $default = null) {
8071      global $CFG;
8072  
8073      if ($type === 'mod' and $name === 'NEWMODULE') {
8074          // Somebody forgot to rename the module template.
8075          return false;
8076      }
8077  
8078      $component = clean_param($type . '_' . $name, PARAM_COMPONENT);
8079      if (empty($component)) {
8080          throw new coding_exception('Invalid component used in plugin_supports():' . $type . '_' . $name);
8081      }
8082  
8083      $function = null;
8084  
8085      if ($type === 'mod') {
8086          // We need this special case because we support subplugins in modules,
8087          // otherwise it would end up in infinite loop.
8088          if (file_exists("$CFG->dirroot/mod/$name/lib.php")) {
8089              include_once("$CFG->dirroot/mod/$name/lib.php");
8090              $function = $component.'_supports';
8091              if (!function_exists($function)) {
8092                  // Legacy non-frankenstyle function name.
8093                  $function = $name.'_supports';
8094              }
8095          }
8096  
8097      } else {
8098          if (!$path = core_component::get_plugin_directory($type, $name)) {
8099              // Non existent plugin type.
8100              return false;
8101          }
8102          if (file_exists("$path/lib.php")) {
8103              include_once("$path/lib.php");
8104              $function = $component.'_supports';
8105          }
8106      }
8107  
8108      if ($function and function_exists($function)) {
8109          $supports = $function($feature);
8110          if (is_null($supports)) {
8111              // Plugin does not know - use default.
8112              return $default;
8113          } else {
8114              return $supports;
8115          }
8116      }
8117  
8118      // Plugin does not care, so use default.
8119      return $default;
8120  }
8121  
8122  /**
8123   * Returns true if the current version of PHP is greater that the specified one.
8124   *
8125   * @todo Check PHP version being required here is it too low?
8126   *
8127   * @param string $version The version of php being tested.
8128   * @return bool
8129   */
8130  function check_php_version($version='5.2.4') {
8131      return (version_compare(phpversion(), $version) >= 0);
8132  }
8133  
8134  /**
8135   * Determine if moodle installation requires update.
8136   *
8137   * Checks version numbers of main code and all plugins to see
8138   * if there are any mismatches.
8139   *
8140   * @return bool
8141   */
8142  function moodle_needs_upgrading() {
8143      global $CFG;
8144  
8145      if (empty($CFG->version)) {
8146          return true;
8147      }
8148  
8149      // There is no need to purge plugininfo caches here because
8150      // these caches are not used during upgrade and they are purged after
8151      // every upgrade.
8152  
8153      if (empty($CFG->allversionshash)) {
8154          return true;
8155      }
8156  
8157      $hash = core_component::get_all_versions_hash();
8158  
8159      return ($hash !== $CFG->allversionshash);
8160  }
8161  
8162  /**
8163   * Returns the major version of this site
8164   *
8165   * Moodle version numbers consist of three numbers separated by a dot, for
8166   * example 1.9.11 or 2.0.2. The first two numbers, like 1.9 or 2.0, represent so
8167   * called major version. This function extracts the major version from either
8168   * $CFG->release (default) or eventually from the $release variable defined in
8169   * the main version.php.
8170   *
8171   * @param bool $fromdisk should the version if source code files be used
8172   * @return string|false the major version like '2.3', false if could not be determined
8173   */
8174  function moodle_major_version($fromdisk = false) {
8175      global $CFG;
8176  
8177      if ($fromdisk) {
8178          $release = null;
8179          require($CFG->dirroot.'/version.php');
8180          if (empty($release)) {
8181              return false;
8182          }
8183  
8184      } else {
8185          if (empty($CFG->release)) {
8186              return false;
8187          }
8188          $release = $CFG->release;
8189      }
8190  
8191      if (preg_match('/^[0-9]+\.[0-9]+/', $release, $matches)) {
8192          return $matches[0];
8193      } else {
8194          return false;
8195      }
8196  }
8197  
8198  // MISCELLANEOUS.
8199  
8200  /**
8201   * Gets the system locale
8202   *
8203   * @return string Retuns the current locale.
8204   */
8205  function moodle_getlocale() {
8206      global $CFG;
8207  
8208      // Fetch the correct locale based on ostype.
8209      if ($CFG->ostype == 'WINDOWS') {
8210          $stringtofetch = 'localewin';
8211      } else {
8212          $stringtofetch = 'locale';
8213      }
8214  
8215      if (!empty($CFG->locale)) { // Override locale for all language packs.
8216          return $CFG->locale;
8217      }
8218  
8219      return get_string($stringtofetch, 'langconfig');
8220  }
8221  
8222  /**
8223   * Sets the system locale
8224   *
8225   * @category string
8226   * @param string $locale Can be used to force a locale
8227   */
8228  function moodle_setlocale($locale='') {
8229      global $CFG;
8230  
8231      static $currentlocale = ''; // Last locale caching.
8232  
8233      $oldlocale = $currentlocale;
8234  
8235      // The priority is the same as in get_string() - parameter, config, course, session, user, global language.
8236      if (!empty($locale)) {
8237          $currentlocale = $locale;
8238      } else {
8239          $currentlocale = moodle_getlocale();
8240      }
8241  
8242      // Do nothing if locale already set up.
8243      if ($oldlocale == $currentlocale) {
8244          return;
8245      }
8246  
8247      // Due to some strange BUG we cannot set the LC_TIME directly, so we fetch current values,
8248      // set LC_ALL and then set values again. Just wondering why we cannot set LC_ALL only??? - stronk7
8249      // Some day, numeric, monetary and other categories should be set too, I think. :-/.
8250  
8251      // Get current values.
8252      $monetary= setlocale (LC_MONETARY, 0);
8253      $numeric = setlocale (LC_NUMERIC, 0);
8254      $ctype   = setlocale (LC_CTYPE, 0);
8255      if ($CFG->ostype != 'WINDOWS') {
8256          $messages= setlocale (LC_MESSAGES, 0);
8257      }
8258      // Set locale to all.
8259      $result = setlocale (LC_ALL, $currentlocale);
8260      // If setting of locale fails try the other utf8 or utf-8 variant,
8261      // some operating systems support both (Debian), others just one (OSX).
8262      if ($result === false) {
8263          if (stripos($currentlocale, '.UTF-8') !== false) {
8264              $newlocale = str_ireplace('.UTF-8', '.UTF8', $currentlocale);
8265              setlocale (LC_ALL, $newlocale);
8266          } else if (stripos($currentlocale, '.UTF8') !== false) {
8267              $newlocale = str_ireplace('.UTF8', '.UTF-8', $currentlocale);
8268              setlocale (LC_ALL, $newlocale);
8269          }
8270      }
8271      // Set old values.
8272      setlocale (LC_MONETARY, $monetary);
8273      setlocale (LC_NUMERIC, $numeric);
8274      if ($CFG->ostype != 'WINDOWS') {
8275          setlocale (LC_MESSAGES, $messages);
8276      }
8277      if ($currentlocale == 'tr_TR' or $currentlocale == 'tr_TR.UTF-8') {
8278          // To workaround a well-known PHP problem with Turkish letter Ii.
8279          setlocale (LC_CTYPE, $ctype);
8280      }
8281  }
8282  
8283  /**
8284   * Count words in a string.
8285   *
8286   * Words are defined as things between whitespace.
8287   *
8288   * @category string
8289   * @param string $string The text to be searched for words. May be HTML.
8290   * @return int The count of words in the specified string
8291   */
8292  function count_words($string) {
8293      // Before stripping tags, add a space after the close tag of anything that is not obviously inline.
8294      // Also, br is a special case because it definitely delimits a word, but has no close tag.
8295      $string = preg_replace('~
8296              (                                   # Capture the tag we match.
8297                  </                              # Start of close tag.
8298                  (?!                             # Do not match any of these specific close tag names.
8299                      a> | b> | del> | em> | i> |
8300                      ins> | s> | small> |
8301                      strong> | sub> | sup> | u>
8302                  )
8303                  \w+                             # But, apart from those execptions, match any tag name.
8304                  >                               # End of close tag.
8305              |
8306                  <br> | <br\s*/>                 # Special cases that are not close tags.
8307              )
8308              ~x', '$1 ', $string); // Add a space after the close tag.
8309      // Now remove HTML tags.
8310      $string = strip_tags($string);
8311      // Decode HTML entities.
8312      $string = html_entity_decode($string);
8313  
8314      // Now, the word count is the number of blocks of characters separated
8315      // by any sort of space. That seems to be the definition used by all other systems.
8316      // To be precise about what is considered to separate words:
8317      // * Anything that Unicode considers a 'Separator'
8318      // * Anything that Unicode considers a 'Control character'
8319      // * An em- or en- dash.
8320      return count(preg_split('~[\p{Z}\p{Cc}—–]+~u', $string, -1, PREG_SPLIT_NO_EMPTY));
8321  }
8322  
8323  /**
8324   * Count letters in a string.
8325   *
8326   * Letters are defined as chars not in tags and different from whitespace.
8327   *
8328   * @category string
8329   * @param string $string The text to be searched for letters. May be HTML.
8330   * @return int The count of letters in the specified text.
8331   */
8332  function count_letters($string) {
8333      $string = strip_tags($string); // Tags are out now.
8334      $string = html_entity_decode($string);
8335      $string = preg_replace('/[[:space:]]*/', '', $string); // Whitespace are out now.
8336  
8337      return core_text::strlen($string);
8338  }
8339  
8340  /**
8341   * Generate and return a random string of the specified length.
8342   *
8343   * @param int $length The length of the string to be created.
8344   * @return string
8345   */
8346  function random_string($length=15) {
8347      $randombytes = random_bytes_emulate($length);
8348      $pool  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
8349      $pool .= 'abcdefghijklmnopqrstuvwxyz';
8350      $pool .= '0123456789';
8351      $poollen = strlen($pool);
8352      $string = '';
8353      for ($i = 0; $i < $length; $i++) {
8354          $rand = ord($randombytes[$i]);
8355          $string .= substr($pool, ($rand%($poollen)), 1);
8356      }
8357      return $string;
8358  }
8359  
8360  /**
8361   * Generate a complex random string (useful for md5 salts)
8362   *
8363   * This function is based on the above {@link random_string()} however it uses a
8364   * larger pool of characters and generates a string between 24 and 32 characters
8365   *
8366   * @param int $length Optional if set generates a string to exactly this length
8367   * @return string
8368   */
8369  function complex_random_string($length=null) {
8370      $pool  = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
8371      $pool .= '`~!@#%^&*()_+-=[];,./<>?:{} ';
8372      $poollen = strlen($pool);
8373      if ($length===null) {
8374          $length = floor(rand(24, 32));
8375      }
8376      $randombytes = random_bytes_emulate($length);
8377      $string = '';
8378      for ($i = 0; $i < $length; $i++) {
8379          $rand = ord($randombytes[$i]);
8380          $string .= $pool[($rand%$poollen)];
8381      }
8382      return $string;
8383  }
8384  
8385  /**
8386   * Try to generates cryptographically secure pseudo-random bytes.
8387   *
8388   * Note this is achieved by fallbacking between:
8389   *  - PHP 7 random_bytes().
8390   *  - OpenSSL openssl_random_pseudo_bytes().
8391   *  - In house random generator getting its entropy from various, hard to guess, pseudo-random sources.
8392   *
8393   * @param int $length requested length in bytes
8394   * @return string binary data
8395   */
8396  function random_bytes_emulate($length) {
8397      global $CFG;
8398      if ($length <= 0) {
8399          debugging('Invalid random bytes length', DEBUG_DEVELOPER);
8400          return '';
8401      }
8402      if (function_exists('random_bytes')) {
8403          // Use PHP 7 goodness.
8404          $hash = @random_bytes($length);
8405          if ($hash !== false) {
8406              return $hash;
8407          }
8408      }
8409      if (function_exists('openssl_random_pseudo_bytes')) {
8410          // If you have the openssl extension enabled.
8411          $hash = openssl_random_pseudo_bytes($length);
8412          if ($hash !== false) {
8413              return $hash;
8414          }
8415      }
8416  
8417      // Bad luck, there is no reliable random generator, let's just slowly hash some unique stuff that is hard to guess.
8418      $staticdata = serialize($CFG) . serialize($_SERVER);
8419      $hash = '';
8420      do {
8421          $hash .= sha1($staticdata . microtime(true) . uniqid('', true), true);
8422      } while (strlen($hash) < $length);
8423  
8424      return substr($hash, 0, $length);
8425  }
8426  
8427  /**
8428   * Given some text (which may contain HTML) and an ideal length,
8429   * this function truncates the text neatly on a word boundary if possible
8430   *
8431   * @category string
8432   * @param string $text text to be shortened
8433   * @param int $ideal ideal string length
8434   * @param boolean $exact if false, $text will not be cut mid-word
8435   * @param string $ending The string to append if the passed string is truncated
8436   * @return string $truncate shortened string
8437   */
8438  function shorten_text($text, $ideal=30, $exact = false, $ending='...') {
8439      // If the plain text is shorter than the maximum length, return the whole text.
8440      if (core_text::strlen(preg_replace('/<.*?>/', '', $text)) <= $ideal) {
8441          return $text;
8442      }
8443  
8444      // Splits on HTML tags. Each open/close/empty tag will be the first thing
8445      // and only tag in its 'line'.
8446      preg_match_all('/(<.+?>)?([^<>]*)/s', $text, $lines, PREG_SET_ORDER);
8447  
8448      $totallength = core_text::strlen($ending);
8449      $truncate = '';
8450  
8451      // This array stores information about open and close tags and their position
8452      // in the truncated string. Each item in the array is an object with fields
8453      // ->open (true if open), ->tag (tag name in lower case), and ->pos
8454      // (byte position in truncated text).
8455      $tagdetails = array();
8456  
8457      foreach ($lines as $linematchings) {
8458          // If there is any html-tag in this line, handle it and add it (uncounted) to the output.
8459          if (!empty($linematchings[1])) {
8460              // If it's an "empty element" with or without xhtml-conform closing slash (f.e. <br/>).
8461              if (!preg_match('/^<(\s*.+?\/\s*|\s*(img|br|input|hr|area|base|basefont|col|frame|isindex|link|meta|param)(\s.+?)?)>$/is', $linematchings[1])) {
8462                  if (preg_match('/^<\s*\/([^\s]+?)\s*>$/s', $linematchings[1], $tagmatchings)) {
8463                      // Record closing tag.
8464                      $tagdetails[] = (object) array(
8465                              'open' => false,
8466                              'tag'  => core_text::strtolower($tagmatchings[1]),
8467                              'pos'  => core_text::strlen($truncate),
8468                          );
8469  
8470                  } else if (preg_match('/^<\s*([^\s>!]+).*?>$/s', $linematchings[1], $tagmatchings)) {
8471                      // Record opening tag.
8472                      $tagdetails[] = (object) array(
8473                              'open' => true,
8474                              'tag'  => core_text::strtolower($tagmatchings[1]),
8475                              'pos'  => core_text::strlen($truncate),
8476                          );
8477                  } else if (preg_match('/^<!--\[if\s.*?\]>$/s', $linematchings[1], $tagmatchings)) {
8478                      $tagdetails[] = (object) array(
8479                              'open' => true,
8480                              'tag'  => core_text::strtolower('if'),
8481                              'pos'  => core_text::strlen($truncate),
8482                      );
8483                  } else if (preg_match('/^<!--<!\[endif\]-->$/s', $linematchings[1], $tagmatchings)) {
8484                      $tagdetails[] = (object) array(
8485                              'open' => false,
8486                              'tag'  => core_text::strtolower('if'),
8487                              'pos'  => core_text::strlen($truncate),
8488                      );
8489                  }
8490              }
8491              // Add html-tag to $truncate'd text.
8492              $truncate .= $linematchings[1];
8493          }
8494  
8495          // Calculate the length of the plain text part of the line; handle entities as one character.
8496          $contentlength = core_text::strlen(preg_replace('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', ' ', $linematchings[2]));
8497          if ($totallength + $contentlength > $ideal) {
8498              // The number of characters which are left.
8499              $left = $ideal - $totallength;
8500              $entitieslength = 0;
8501              // Search for html entities.
8502              if (preg_match_all('/&[0-9a-z]{2,8};|&#[0-9]{1,7};|&#x[0-9a-f]{1,6};/i', $linematchings[2], $entities, PREG_OFFSET_CAPTURE)) {
8503                  // Calculate the real length of all entities in the legal range.
8504                  foreach ($entities[0] as $entity) {
8505                      if ($entity[1]+1-$entitieslength <= $left) {
8506                          $left--;
8507                          $entitieslength += core_text::strlen($entity[0]);
8508                      } else {
8509                          // No more characters left.
8510                          break;
8511                      }
8512                  }
8513              }
8514              $breakpos = $left + $entitieslength;
8515  
8516              // If the words shouldn't be cut in the middle...
8517              if (!$exact) {
8518                  // Search the last occurence of a space.
8519                  for (; $breakpos > 0; $breakpos--) {
8520                      if ($char = core_text::substr($linematchings[2], $breakpos, 1)) {
8521                          if ($char === '.' or $char === ' ') {
8522                              $breakpos += 1;
8523                              break;
8524                          } else if (strlen($char) > 2) {
8525                              // Chinese/Japanese/Korean text can be truncated at any UTF-8 character boundary.
8526                              $breakpos += 1;
8527                              break;
8528                          }
8529                      }
8530                  }
8531              }
8532              if ($breakpos == 0) {
8533                  // This deals with the test_shorten_text_no_spaces case.
8534                  $breakpos = $left + $entitieslength;
8535              } else if ($breakpos > $left + $entitieslength) {
8536                  // This deals with the previous for loop breaking on the first char.
8537                  $breakpos = $left + $entitieslength;
8538              }
8539  
8540              $truncate .= core_text::substr($linematchings[2], 0, $breakpos);
8541              // Maximum length is reached, so get off the loop.
8542              break;
8543          } else {
8544              $truncate .= $linematchings[2];
8545              $totallength += $contentlength;
8546          }
8547  
8548          // If the maximum length is reached, get off the loop.
8549          if ($totallength >= $ideal) {
8550              break;
8551          }
8552      }
8553  
8554      // Add the defined ending to the text.
8555      $truncate .= $ending;
8556  
8557      // Now calculate the list of open html tags based on the truncate position.
8558      $opentags = array();
8559      foreach ($tagdetails as $taginfo) {
8560          if ($taginfo->open) {
8561              // Add tag to the beginning of $opentags list.
8562              array_unshift($opentags, $taginfo->tag);
8563          } else {
8564              // Can have multiple exact same open tags, close the last one.
8565              $pos = array_search($taginfo->tag, array_reverse($opentags, true));
8566              if ($pos !== false) {
8567                  unset($opentags[$pos]);
8568              }
8569          }
8570      }
8571  
8572      // Close all unclosed html-tags.
8573      foreach ($opentags as $tag) {
8574          if ($tag === 'if') {
8575              $truncate .= '<!--<![endif]-->';
8576          } else {
8577              $truncate .= '</' . $tag . '>';
8578          }
8579      }
8580  
8581      return $truncate;
8582  }
8583  
8584  /**
8585   * Shortens a given filename by removing characters positioned after the ideal string length.
8586   * When the filename is too long, the file cannot be created on the filesystem due to exceeding max byte size.
8587   * Limiting the filename to a certain size (considering multibyte characters) will prevent this.
8588   *
8589   * @param string $filename file name
8590   * @param int $length ideal string length
8591   * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8592   * @return string $shortened shortened file name
8593   */
8594  function shorten_filename($filename, $length = MAX_FILENAME_SIZE, $includehash = false) {
8595      $shortened = $filename;
8596      // Extract a part of the filename if it's char size exceeds the ideal string length.
8597      if (core_text::strlen($filename) > $length) {
8598          // Exclude extension if present in filename.
8599          $mimetypes = get_mimetypes_array();
8600          $extension = pathinfo($filename, PATHINFO_EXTENSION);
8601          if ($extension && !empty($mimetypes[$extension])) {
8602              $basename = pathinfo($filename, PATHINFO_FILENAME);
8603              $hash = empty($includehash) ? '' : ' - ' . substr(sha1($basename), 0, 10);
8604              $shortened = core_text::substr($basename, 0, $length - strlen($hash)) . $hash;
8605              $shortened .= '.' . $extension;
8606          } else {
8607              $hash = empty($includehash) ? '' : ' - ' . substr(sha1($filename), 0, 10);
8608              $shortened = core_text::substr($filename, 0, $length - strlen($hash)) . $hash;
8609          }
8610      }
8611      return $shortened;
8612  }
8613  
8614  /**
8615   * Shortens a given array of filenames by removing characters positioned after the ideal string length.
8616   *
8617   * @param array $path The paths to reduce the length.
8618   * @param int $length Ideal string length
8619   * @param bool $includehash Whether to include a file hash in the shortened version. This ensures uniqueness.
8620   * @return array $result Shortened paths in array.
8621   */
8622  function shorten_filenames(array $path, $length = MAX_FILENAME_SIZE, $includehash = false) {
8623      $result = null;
8624  
8625      $result = array_reduce($path, function($carry, $singlepath) use ($length, $includehash) {
8626          $carry[] = shorten_filename($singlepath, $length, $includehash);
8627          return $carry;
8628      }, []);
8629  
8630      return $result;
8631  }
8632  
8633  /**
8634   * Given dates in seconds, how many weeks is the date from startdate
8635   * The first week is 1, the second 2 etc ...
8636   *
8637   * @param int $startdate Timestamp for the start date
8638   * @param int $thedate Timestamp for the end date
8639   * @return string
8640   */
8641  function getweek ($startdate, $thedate) {
8642      if ($thedate < $startdate) {
8643          return 0;
8644      }
8645  
8646      return floor(($thedate - $startdate) / WEEKSECS) + 1;
8647  }
8648  
8649  /**
8650   * Returns a randomly generated password of length $maxlen.  inspired by
8651   *
8652   * {@link http://www.phpbuilder.com/columns/jesus19990502.php3} and
8653   * {@link http://es2.php.net/manual/en/function.str-shuffle.php#73254}
8654   *
8655   * @param int $maxlen  The maximum size of the password being generated.
8656   * @return string
8657   */
8658  function generate_password($maxlen=10) {
8659      global $CFG;
8660  
8661      if (empty($CFG->passwordpolicy)) {
8662          $fillers = PASSWORD_DIGITS;
8663          $wordlist = file($CFG->wordlist);
8664          $word1 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8665          $word2 = trim($wordlist[rand(0, count($wordlist) - 1)]);
8666          $filler1 = $fillers[rand(0, strlen($fillers) - 1)];
8667          $password = $word1 . $filler1 . $word2;
8668      } else {
8669          $minlen = !empty($CFG->minpasswordlength) ? $CFG->minpasswordlength : 0;
8670          $digits = $CFG->minpassworddigits;
8671          $lower = $CFG->minpasswordlower;
8672          $upper = $CFG->minpasswordupper;
8673          $nonalphanum = $CFG->minpasswordnonalphanum;
8674          $total = $lower + $upper + $digits + $nonalphanum;
8675          // Var minlength should be the greater one of the two ( $minlen and $total ).
8676          $minlen = $minlen < $total ? $total : $minlen;
8677          // Var maxlen can never be smaller than minlen.
8678          $maxlen = $minlen > $maxlen ? $minlen : $maxlen;
8679          $additional = $maxlen - $total;
8680  
8681          // Make sure we have enough characters to fulfill
8682          // complexity requirements.
8683          $passworddigits = PASSWORD_DIGITS;
8684          while ($digits > strlen($passworddigits)) {
8685              $passworddigits .= PASSWORD_DIGITS;
8686          }
8687          $passwordlower = PASSWORD_LOWER;
8688          while ($lower > strlen($passwordlower)) {
8689              $passwordlower .= PASSWORD_LOWER;
8690          }
8691          $passwordupper = PASSWORD_UPPER;
8692          while ($upper > strlen($passwordupper)) {
8693              $passwordupper .= PASSWORD_UPPER;
8694          }
8695          $passwordnonalphanum = PASSWORD_NONALPHANUM;
8696          while ($nonalphanum > strlen($passwordnonalphanum)) {
8697              $passwordnonalphanum .= PASSWORD_NONALPHANUM;
8698          }
8699  
8700          // Now mix and shuffle it all.
8701          $password = str_shuffle (substr(str_shuffle ($passwordlower), 0, $lower) .
8702                                   substr(str_shuffle ($passwordupper), 0, $upper) .
8703                                   substr(str_shuffle ($passworddigits), 0, $digits) .
8704                                   substr(str_shuffle ($passwordnonalphanum), 0 , $nonalphanum) .
8705                                   substr(str_shuffle ($passwordlower .
8706                                                       $passwordupper .
8707                                                       $passworddigits .
8708                                                       $passwordnonalphanum), 0 , $additional));
8709      }
8710  
8711      return substr ($password, 0, $maxlen);
8712  }
8713  
8714  /**
8715   * Given a float, prints it nicely.
8716   * Localized floats must not be used in calculations!
8717   *
8718   * The stripzeros feature is intended for making numbers look nicer in small
8719   * areas where it is not necessary to indicate the degree of accuracy by showing
8720   * ending zeros. If you turn it on with $decimalpoints set to 3, for example,
8721   * then it will display '5.4' instead of '5.400' or '5' instead of '5.000'.
8722   *
8723   * @param float $float The float to print
8724   * @param int $decimalpoints The number of decimal places to print. -1 is a special value for auto detect (full precision).
8725   * @param bool $localized use localized decimal separator
8726   * @param bool $stripzeros If true, removes final zeros after decimal point. It will be ignored and the trailing zeros after
8727   *                         the decimal point are always striped if $decimalpoints is -1.
8728   * @return string locale float
8729   */
8730  function format_float($float, $decimalpoints=1, $localized=true, $stripzeros=false) {
8731      if (is_null($float)) {
8732          return '';
8733      }
8734      if ($localized) {
8735          $separator = get_string('decsep', 'langconfig');
8736      } else {
8737          $separator = '.';
8738      }
8739      if ($decimalpoints == -1) {
8740          // The following counts the number of decimals.
8741          // It is safe as both floatval() and round() functions have same behaviour when non-numeric values are provided.
8742          $floatval = floatval($float);
8743          for ($decimalpoints = 0; $floatval != round($float, $decimalpoints); $decimalpoints++);
8744      }
8745  
8746      $result = number_format($float, $decimalpoints, $separator, '');
8747      if ($stripzeros && $decimalpoints > 0) {
8748          // Remove zeros and final dot if not needed.
8749          // However, only do this if there is a decimal point!
8750          $result = preg_replace('~(' . preg_quote($separator, '~') . ')?0+$~', '', $result);
8751      }
8752      return $result;
8753  }
8754  
8755  /**
8756   * Converts locale specific floating point/comma number back to standard PHP float value
8757   * Do NOT try to do any math operations before this conversion on any user submitted floats!
8758   *
8759   * @param string $localefloat locale aware float representation
8760   * @param bool $strict If true, then check the input and return false if it is not a valid number.
8761   * @return mixed float|bool - false or the parsed float.
8762   */
8763  function unformat_float($localefloat, $strict = false) {
8764      $localefloat = trim($localefloat);
8765  
8766      if ($localefloat == '') {
8767          return null;
8768      }
8769  
8770      $localefloat = str_replace(' ', '', $localefloat); // No spaces - those might be used as thousand separators.
8771      $localefloat = str_replace(get_string('decsep', 'langconfig'), '.', $localefloat);
8772  
8773      if ($strict && !is_numeric($localefloat)) {
8774          return false;
8775      }
8776  
8777      return (float)$localefloat;
8778  }
8779  
8780  /**
8781   * Given a simple array, this shuffles it up just like shuffle()
8782   * Unlike PHP's shuffle() this function works on any machine.
8783   *
8784   * @param array $array The array to be rearranged
8785   * @return array
8786   */
8787  function swapshuffle($array) {
8788  
8789      $last = count($array) - 1;
8790      for ($i = 0; $i <= $last; $i++) {
8791          $from = rand(0, $last);
8792          $curr = $array[$i];
8793          $array[$i] = $array[$from];
8794          $array[$from] = $curr;
8795      }
8796      return $array;
8797  }
8798  
8799  /**
8800   * Like {@link swapshuffle()}, but works on associative arrays
8801   *
8802   * @param array $array The associative array to be rearranged
8803   * @return array
8804   */
8805  function swapshuffle_assoc($array) {
8806  
8807      $newarray = array();
8808      $newkeys = swapshuffle(array_keys($array));
8809  
8810      foreach ($newkeys as $newkey) {
8811          $newarray[$newkey] = $array[$newkey];
8812      }
8813      return $newarray;
8814  }
8815  
8816  /**
8817   * Given an arbitrary array, and a number of draws,
8818   * this function returns an array with that amount
8819   * of items.  The indexes are retained.
8820   *
8821   * @todo Finish documenting this function
8822   *
8823   * @param array $array
8824   * @param int $draws
8825   * @return array
8826   */
8827  function draw_rand_array($array, $draws) {
8828  
8829      $return = array();
8830  
8831      $last = count($array);
8832  
8833      if ($draws > $last) {
8834          $draws = $last;
8835      }
8836  
8837      while ($draws > 0) {
8838          $last--;
8839  
8840          $keys = array_keys($array);
8841          $rand = rand(0, $last);
8842  
8843          $return[$keys[$rand]] = $array[$keys[$rand]];
8844          unset($array[$keys[$rand]]);
8845  
8846          $draws--;
8847      }
8848  
8849      return $return;
8850  }
8851  
8852  /**
8853   * Calculate the difference between two microtimes
8854   *
8855   * @param string $a The first Microtime
8856   * @param string $b The second Microtime
8857   * @return string
8858   */
8859  function microtime_diff($a, $b) {
8860      list($adec, $asec) = explode(' ', $a);
8861      list($bdec, $bsec) = explode(' ', $b);
8862      return $bsec - $asec + $bdec - $adec;
8863  }
8864  
8865  /**
8866   * Given a list (eg a,b,c,d,e) this function returns
8867   * an array of 1->a, 2->b, 3->c etc
8868   *
8869   * @param string $list The string to explode into array bits
8870   * @param string $separator The separator used within the list string
8871   * @return array The now assembled array
8872   */
8873  function make_menu_from_list($list, $separator=',') {
8874  
8875      $array = array_reverse(explode($separator, $list), true);
8876      foreach ($array as $key => $item) {
8877          $outarray[$key+1] = trim($item);
8878      }
8879      return $outarray;
8880  }
8881  
8882  /**
8883   * Creates an array that represents all the current grades that
8884   * can be chosen using the given grading type.
8885   *
8886   * Negative numbers
8887   * are scales, zero is no grade, and positive numbers are maximum
8888   * grades.
8889   *
8890   * @todo Finish documenting this function or better deprecated this completely!
8891   *
8892   * @param int $gradingtype
8893   * @return array
8894   */
8895  function make_grades_menu($gradingtype) {
8896      global $DB;
8897  
8898      $grades = array();
8899      if ($gradingtype < 0) {
8900          if ($scale = $DB->get_record('scale', array('id'=> (-$gradingtype)))) {
8901              return make_menu_from_list($scale->scale);
8902          }
8903      } else if ($gradingtype > 0) {
8904          for ($i=$gradingtype; $i>=0; $i--) {
8905              $grades[$i] = $i .' / '. $gradingtype;
8906          }
8907          return $grades;
8908      }
8909      return $grades;
8910  }
8911  
8912  /**
8913   * make_unique_id_code
8914   *
8915   * @todo Finish documenting this function
8916   *
8917   * @uses $_SERVER
8918   * @param string $extra Extra string to append to the end of the code
8919   * @return string
8920   */
8921  function make_unique_id_code($extra = '') {
8922  
8923      $hostname = 'unknownhost';
8924      if (!empty($_SERVER['HTTP_HOST'])) {
8925          $hostname = $_SERVER['HTTP_HOST'];
8926      } else if (!empty($_ENV['HTTP_HOST'])) {
8927          $hostname = $_ENV['HTTP_HOST'];
8928      } else if (!empty($_SERVER['SERVER_NAME'])) {
8929          $hostname = $_SERVER['SERVER_NAME'];
8930      } else if (!empty($_ENV['SERVER_NAME'])) {
8931          $hostname = $_ENV['SERVER_NAME'];
8932      }
8933  
8934      $date = gmdate("ymdHis");
8935  
8936      $random =  random_string(6);
8937  
8938      if ($extra) {
8939          return $hostname .'+'. $date .'+'. $random .'+'. $extra;
8940      } else {
8941          return $hostname .'+'. $date .'+'. $random;
8942      }
8943  }
8944  
8945  
8946  /**
8947   * Function to check the passed address is within the passed subnet
8948   *
8949   * The parameter is a comma separated string of subnet definitions.
8950   * Subnet strings can be in one of three formats:
8951   *   1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn          (number of bits in net mask)
8952   *   2: xxx.xxx.xxx.xxx-yyy or  xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy (a range of IP addresses in the last group)
8953   *   3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.                  (incomplete address, a bit non-technical ;-)
8954   * Code for type 1 modified from user posted comments by mediator at
8955   * {@link http://au.php.net/manual/en/function.ip2long.php}
8956   *
8957   * @param string $addr    The address you are checking
8958   * @param string $subnetstr    The string of subnet addresses
8959   * @param bool $checkallzeros    The state to whether check for 0.0.0.0
8960   * @return bool
8961   */
8962  function address_in_subnet($addr, $subnetstr, $checkallzeros = false) {
8963  
8964      if ($addr == '0.0.0.0' && !$checkallzeros) {
8965          return false;
8966      }
8967      $subnets = explode(',', $subnetstr);
8968      $found = false;
8969      $addr = trim($addr);
8970      $addr = cleanremoteaddr($addr, false); // Normalise.
8971      if ($addr === null) {
8972          return false;
8973      }
8974      $addrparts = explode(':', $addr);
8975  
8976      $ipv6 = strpos($addr, ':');
8977  
8978      foreach ($subnets as $subnet) {
8979          $subnet = trim($subnet);
8980          if ($subnet === '') {
8981              continue;
8982          }
8983  
8984          if (strpos($subnet, '/') !== false) {
8985              // 1: xxx.xxx.xxx.xxx/nn or xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx/nnn.
8986              list($ip, $mask) = explode('/', $subnet);
8987              $mask = trim($mask);
8988              if (!is_number($mask)) {
8989                  continue; // Incorect mask number, eh?
8990              }
8991              $ip = cleanremoteaddr($ip, false); // Normalise.
8992              if ($ip === null) {
8993                  continue;
8994              }
8995              if (strpos($ip, ':') !== false) {
8996                  // IPv6.
8997                  if (!$ipv6) {
8998                      continue;
8999                  }
9000                  if ($mask > 128 or $mask < 0) {
9001                      continue; // Nonsense.
9002                  }
9003                  if ($mask == 0) {
9004                      return true; // Any address.
9005                  }
9006                  if ($mask == 128) {
9007                      if ($ip === $addr) {
9008                          return true;
9009                      }
9010                      continue;
9011                  }
9012                  $ipparts = explode(':', $ip);
9013                  $modulo  = $mask % 16;
9014                  $ipnet   = array_slice($ipparts, 0, ($mask-$modulo)/16);
9015                  $addrnet = array_slice($addrparts, 0, ($mask-$modulo)/16);
9016                  if (implode(':', $ipnet) === implode(':', $addrnet)) {
9017                      if ($modulo == 0) {
9018                          return true;
9019                      }
9020                      $pos     = ($mask-$modulo)/16;
9021                      $ipnet   = hexdec($ipparts[$pos]);
9022                      $addrnet = hexdec($addrparts[$pos]);
9023                      $mask    = 0xffff << (16 - $modulo);
9024                      if (($addrnet & $mask) == ($ipnet & $mask)) {
9025                          return true;
9026                      }
9027                  }
9028  
9029              } else {
9030                  // IPv4.
9031                  if ($ipv6) {
9032                      continue;
9033                  }
9034                  if ($mask > 32 or $mask < 0) {
9035                      continue; // Nonsense.
9036                  }
9037                  if ($mask == 0) {
9038                      return true;
9039                  }
9040                  if ($mask == 32) {
9041                      if ($ip === $addr) {
9042                          return true;
9043                      }
9044                      continue;
9045                  }
9046                  $mask = 0xffffffff << (32 - $mask);
9047                  if (((ip2long($addr) & $mask) == (ip2long($ip) & $mask))) {
9048                      return true;
9049                  }
9050              }
9051  
9052          } else if (strpos($subnet, '-') !== false) {
9053              // 2: xxx.xxx.xxx.xxx-yyy or  xxxx:xxxx:xxxx:xxxx:xxxx:xxxx:xxxx::xxxx-yyyy. A range of IP addresses in the last group.
9054              $parts = explode('-', $subnet);
9055              if (count($parts) != 2) {
9056                  continue;
9057              }
9058  
9059              if (strpos($subnet, ':') !== false) {
9060                  // IPv6.
9061                  if (!$ipv6) {
9062                      continue;
9063                  }
9064                  $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9065                  if ($ipstart === null) {
9066                      continue;
9067                  }
9068                  $ipparts = explode(':', $ipstart);
9069                  $start = hexdec(array_pop($ipparts));
9070                  $ipparts[] = trim($parts[1]);
9071                  $ipend = cleanremoteaddr(implode(':', $ipparts), false); // Normalise.
9072                  if ($ipend === null) {
9073                      continue;
9074                  }
9075                  $ipparts[7] = '';
9076                  $ipnet = implode(':', $ipparts);
9077                  if (strpos($addr, $ipnet) !== 0) {
9078                      continue;
9079                  }
9080                  $ipparts = explode(':', $ipend);
9081                  $end = hexdec($ipparts[7]);
9082  
9083                  $addrend = hexdec($addrparts[7]);
9084  
9085                  if (($addrend >= $start) and ($addrend <= $end)) {
9086                      return true;
9087                  }
9088  
9089              } else {
9090                  // IPv4.
9091                  if ($ipv6) {
9092                      continue;
9093                  }
9094                  $ipstart = cleanremoteaddr(trim($parts[0]), false); // Normalise.
9095                  if ($ipstart === null) {
9096                      continue;
9097                  }
9098                  $ipparts = explode('.', $ipstart);
9099                  $ipparts[3] = trim($parts[1]);
9100                  $ipend = cleanremoteaddr(implode('.', $ipparts), false); // Normalise.
9101                  if ($ipend === null) {
9102                      continue;
9103                  }
9104  
9105                  if ((ip2long($addr) >= ip2long($ipstart)) and (ip2long($addr) <= ip2long($ipend))) {
9106                      return true;
9107                  }
9108              }
9109  
9110          } else {
9111              // 3: xxx.xxx or xxx.xxx. or xxx:xxx:xxxx or xxx:xxx:xxxx.
9112              if (strpos($subnet, ':') !== false) {
9113                  // IPv6.
9114                  if (!$ipv6) {
9115                      continue;
9116                  }
9117                  $parts = explode(':', $subnet);
9118                  $count = count($parts);
9119                  if ($parts[$count-1] === '') {
9120                      unset($parts[$count-1]); // Trim trailing :'s.
9121                      $count--;
9122                      $subnet = implode('.', $parts);
9123                  }
9124                  $isip = cleanremoteaddr($subnet, false); // Normalise.
9125                  if ($isip !== null) {
9126                      if ($isip === $addr) {
9127                          return true;
9128                      }
9129                      continue;
9130                  } else if ($count > 8) {
9131                      continue;
9132                  }
9133                  $zeros = array_fill(0, 8-$count, '0');
9134                  $subnet = $subnet.':'.implode(':', $zeros).'/'.($count*16);
9135                  if (address_in_subnet($addr, $subnet)) {
9136                      return true;
9137                  }
9138  
9139              } else {
9140                  // IPv4.
9141                  if ($ipv6) {
9142                      continue;
9143                  }
9144                  $parts = explode('.', $subnet);
9145                  $count = count($parts);
9146                  if ($parts[$count-1] === '') {
9147                      unset($parts[$count-1]); // Trim trailing .
9148                      $count--;
9149                      $subnet = implode('.', $parts);
9150                  }
9151                  if ($count == 4) {
9152                      $subnet = cleanremoteaddr($subnet, false); // Normalise.
9153                      if ($subnet === $addr) {
9154                          return true;
9155                      }
9156                      continue;
9157                  } else if ($count > 4) {
9158                      continue;
9159                  }
9160                  $zeros = array_fill(0, 4-$count, '0');
9161                  $subnet = $subnet.'.'.implode('.', $zeros).'/'.($count*8);
9162                  if (address_in_subnet($addr, $subnet)) {
9163                      return true;
9164                  }
9165              }
9166          }
9167      }
9168  
9169      return false;
9170  }
9171  
9172  /**
9173   * For outputting debugging info
9174   *
9175   * @param string $string The string to write
9176   * @param string $eol The end of line char(s) to use
9177   * @param string $sleep Period to make the application sleep
9178   *                      This ensures any messages have time to display before redirect
9179   */
9180  function mtrace($string, $eol="\n", $sleep=0) {
9181      global $CFG;
9182  
9183      if (isset($CFG->mtrace_wrapper) && function_exists($CFG->mtrace_wrapper)) {
9184          $fn = $CFG->mtrace_wrapper;
9185          $fn($string, $eol);
9186          return;
9187      } else if (defined('STDOUT') && !PHPUNIT_TEST && !defined('BEHAT_TEST')) {
9188          // We must explicitly call the add_line function here.
9189          // Uses of fwrite to STDOUT are not picked up by ob_start.
9190          if ($output = \core\task\logmanager::add_line("{$string}{$eol}")) {
9191              fwrite(STDOUT, $output);
9192          }
9193      } else {
9194          echo $string . $eol;
9195      }
9196  
9197      // Flush again.
9198      flush();
9199  
9200      // Delay to keep message on user's screen in case of subsequent redirect.
9201      if ($sleep) {
9202          sleep($sleep);
9203      }
9204  }
9205  
9206  /**
9207   * Replace 1 or more slashes or backslashes to 1 slash
9208   *
9209   * @param string $path The path to strip
9210   * @return string the path with double slashes removed
9211   */
9212  function cleardoubleslashes ($path) {
9213      return preg_replace('/(\/|\\\){1,}/', '/', $path);
9214  }
9215  
9216  /**
9217   * Is the current ip in a given list?
9218   *
9219   * @param string $list
9220   * @return bool
9221   */
9222  function remoteip_in_list($list) {
9223      $clientip = getremoteaddr(null);
9224  
9225      if (!$clientip) {
9226          // Ensure access on cli.
9227          return true;
9228      }
9229      return \core\ip_utils::is_ip_in_subnet_list($clientip, $list);
9230  }
9231  
9232  /**
9233   * Returns most reliable client address
9234   *
9235   * @param string $default If an address can't be determined, then return this
9236   * @return string The remote IP address
9237   */
9238  function getremoteaddr($default='0.0.0.0') {
9239      global $CFG;
9240  
9241      if (!isset($CFG->getremoteaddrconf)) {
9242          // This will happen, for example, before just after the upgrade, as the
9243          // user is redirected to the admin screen.
9244          $variablestoskip = GETREMOTEADDR_SKIP_DEFAULT;
9245      } else {
9246          $variablestoskip = $CFG->getremoteaddrconf;
9247      }
9248      if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_CLIENT_IP)) {
9249          if (!empty($_SERVER['HTTP_CLIENT_IP'])) {
9250              $address = cleanremoteaddr($_SERVER['HTTP_CLIENT_IP']);
9251              return $address ? $address : $default;
9252          }
9253      }
9254      if (!($variablestoskip & GETREMOTEADDR_SKIP_HTTP_X_FORWARDED_FOR)) {
9255          if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {
9256              $forwardedaddresses = explode(",", $_SERVER['HTTP_X_FORWARDED_FOR']);
9257  
9258              $forwardedaddresses = array_filter($forwardedaddresses, function($ip) {
9259                  global $CFG;
9260                  return !\core\ip_utils::is_ip_in_subnet_list($ip, $CFG->reverseproxyignore ?? '', ',');
9261              });
9262  
9263              // Multiple proxies can append values to this header including an
9264              // untrusted original request header so we must only trust the last ip.
9265              $address = end($forwardedaddresses);
9266  
9267              if (substr_count($address, ":") > 1) {
9268                  // Remove port and brackets from IPv6.
9269                  if (preg_match("/\[(.*)\]:/", $address, $matches)) {
9270                      $address = $matches[1];
9271                  }
9272              } else {
9273                  // Remove port from IPv4.
9274                  if (substr_count($address, ":") == 1) {
9275                      $parts = explode(":", $address);
9276                      $address = $parts[0];
9277                  }
9278              }
9279  
9280              $address = cleanremoteaddr($address);
9281              return $address ? $address : $default;
9282          }
9283      }
9284      if (!empty($_SERVER['REMOTE_ADDR'])) {
9285          $address = cleanremoteaddr($_SERVER['REMOTE_ADDR']);
9286          return $address ? $address : $default;
9287      } else {
9288          return $default;
9289      }
9290  }
9291  
9292  /**
9293   * Cleans an ip address. Internal addresses are now allowed.
9294   * (Originally local addresses were not allowed.)
9295   *
9296   * @param string $addr IPv4 or IPv6 address
9297   * @param bool $compress use IPv6 address compression
9298   * @return string normalised ip address string, null if error
9299   */
9300  function cleanremoteaddr($addr, $compress=false) {
9301      $addr = trim($addr);
9302  
9303      if (strpos($addr, ':') !== false) {
9304          // Can be only IPv6.
9305          $parts = explode(':', $addr);
9306          $count = count($parts);
9307  
9308          if (strpos($parts[$count-1], '.') !== false) {
9309              // Legacy ipv4 notation.
9310              $last = array_pop($parts);
9311              $ipv4 = cleanremoteaddr($last, true);
9312              if ($ipv4 === null) {
9313                  return null;
9314              }
9315              $bits = explode('.', $ipv4);
9316              $parts[] = dechex($bits[0]).dechex($bits[1]);
9317              $parts[] = dechex($bits[2]).dechex($bits[3]);
9318              $count = count($parts);
9319              $addr = implode(':', $parts);
9320          }
9321  
9322          if ($count < 3 or $count > 8) {
9323              return null; // Severly malformed.
9324          }
9325  
9326          if ($count != 8) {
9327              if (strpos($addr, '::') === false) {
9328                  return null; // Malformed.
9329              }
9330              // Uncompress.
9331              $insertat = array_search('', $parts, true);
9332              $missing = array_fill(0, 1 + 8 - $count, '0');
9333              array_splice($parts, $insertat, 1, $missing);
9334              foreach ($parts as $key => $part) {
9335                  if ($part === '') {
9336                      $parts[$key] = '0';
9337                  }
9338              }
9339          }
9340  
9341          $adr = implode(':', $parts);
9342          if (!preg_match('/^([0-9a-f]{1,4})(:[0-9a-f]{1,4})*$/i', $adr)) {
9343              return null; // Incorrect format - sorry.
9344          }
9345  
9346          // Normalise 0s and case.
9347          $parts = array_map('hexdec', $parts);
9348          $parts = array_map('dechex', $parts);
9349  
9350          $result = implode(':', $parts);
9351  
9352          if (!$compress) {
9353              return $result;
9354          }
9355  
9356          if ($result === '0:0:0:0:0:0:0:0') {
9357              return '::'; // All addresses.
9358          }
9359  
9360          $compressed = preg_replace('/(:0)+:0$/', '::', $result, 1);
9361          if ($compressed !== $result) {
9362              return $compressed;
9363          }
9364  
9365          $compressed = preg_replace('/^(0:){2,7}/', '::', $result, 1);
9366          if ($compressed !== $result) {
9367              return $compressed;
9368          }
9369  
9370          $compressed = preg_replace('/(:0){2,6}:/', '::', $result, 1);
9371          if ($compressed !== $result) {
9372              return $compressed;
9373          }
9374  
9375          return $result;
9376      }
9377  
9378      // First get all things that look like IPv4 addresses.
9379      $parts = array();
9380      if (!preg_match('/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $addr, $parts)) {
9381          return null;
9382      }
9383      unset($parts[0]);
9384  
9385      foreach ($parts as $key => $match) {
9386          if ($match > 255) {
9387              return null;
9388          }
9389          $parts[$key] = (int)$match; // Normalise 0s.
9390      }
9391  
9392      return implode('.', $parts);
9393  }
9394  
9395  
9396  /**
9397   * Is IP address a public address?
9398   *
9399   * @param string $ip The ip to check
9400   * @return bool true if the ip is public
9401   */
9402  function ip_is_public($ip) {
9403      return (bool) filter_var($ip, FILTER_VALIDATE_IP, (FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE));
9404  }
9405  
9406  /**
9407   * This function will make a complete copy of anything it's given,
9408   * regardless of whether it's an object or not.
9409   *
9410   * @param mixed $thing Something you want cloned
9411   * @return mixed What ever it is you passed it
9412   */
9413  function fullclone($thing) {
9414      return unserialize(serialize($thing));
9415  }
9416  
9417  /**
9418   * Used to make sure that $min <= $value <= $max
9419   *
9420   * Make sure that value is between min, and max
9421   *
9422   * @param int $min The minimum value
9423   * @param int $value The value to check
9424   * @param int $max The maximum value
9425   * @return int
9426   */
9427  function bounded_number($min, $value, $max) {
9428      if ($value < $min) {
9429          return $min;
9430      }
9431      if ($value > $max) {
9432          return $max;
9433      }
9434      return $value;
9435  }
9436  
9437  /**
9438   * Check if there is a nested array within the passed array
9439   *
9440   * @param array $array
9441   * @return bool true if there is a nested array false otherwise
9442   */
9443  function array_is_nested($array) {
9444      foreach ($array as $value) {
9445          if (is_array($value)) {
9446              return true;
9447          }
9448      }
9449      return false;
9450  }
9451  
9452  /**
9453   * get_performance_info() pairs up with init_performance_info()
9454   * loaded in setup.php. Returns an array with 'html' and 'txt'
9455   * values ready for use, and each of the individual stats provided
9456   * separately as well.
9457   *
9458   * @return array
9459   */
9460  function get_performance_info() {
9461      global $CFG, $PERF, $DB, $PAGE;
9462  
9463      $info = array();
9464      $info['txt']  = me() . ' '; // Holds log-friendly representation.
9465  
9466      $info['html'] = '';
9467      if (!empty($CFG->themedesignermode)) {
9468          // Attempt to avoid devs debugging peformance issues, when its caused by css building and so on.
9469          $info['html'] .= '<p><strong>Warning: Theme designer mode is enabled.</strong></p>';
9470      }
9471      $info['html'] .= '<ul class="list-unstyled row mx-md-0">';         // Holds userfriendly HTML representation.
9472  
9473      $info['realtime'] = microtime_diff($PERF->starttime, microtime());
9474  
9475      $info['html'] .= '<li class="timeused col-sm-4">'.$info['realtime'].' secs</li> ';
9476      $info['txt'] .= 'time: '.$info['realtime'].'s ';
9477  
9478      // GET/POST (or NULL if $_SERVER['REQUEST_METHOD'] is undefined) is useful for txt logged information.
9479      $info['txt'] .= 'method: ' . ($_SERVER['REQUEST_METHOD'] ?? "NULL") . ' ';
9480  
9481      if (function_exists('memory_get_usage')) {
9482          $info['memory_total'] = memory_get_usage();
9483          $info['memory_growth'] = memory_get_usage() - $PERF->startmemory;
9484          $info['html'] .= '<li class="memoryused col-sm-4">RAM: '.display_size($info['memory_total']).'</li> ';
9485          $info['txt']  .= 'memory_total: '.$info['memory_total'].'B (' . display_size($info['memory_total']).') memory_growth: '.
9486              $info['memory_growth'].'B ('.display_size($info['memory_growth']).') ';
9487      }
9488  
9489      if (function_exists('memory_get_peak_usage')) {
9490          $info['memory_peak'] = memory_get_peak_usage();
9491          $info['html'] .= '<li class="memoryused col-sm-4">RAM peak: '.display_size($info['memory_peak']).'</li> ';
9492          $info['txt']  .= 'memory_peak: '.$info['memory_peak'].'B (' . display_size($info['memory_peak']).') ';
9493      }
9494  
9495      $info['html'] .= '</ul><ul class="list-unstyled row mx-md-0">';
9496      $inc = get_included_files();
9497      $info['includecount'] = count($inc);
9498      $info['html'] .= '<li class="included col-sm-4">Included '.$info['includecount'].' files</li> ';
9499      $info['txt']  .= 'includecount: '.$info['includecount'].' ';
9500  
9501      if (!empty($CFG->early_install_lang) or empty($PAGE)) {
9502          // We can not track more performance before installation or before PAGE init, sorry.
9503          return $info;
9504      }
9505  
9506      $filtermanager = filter_manager::instance();
9507      if (method_exists($filtermanager, 'get_performance_summary')) {
9508          list($filterinfo, $nicenames) = $filtermanager->get_performance_summary();
9509          $info = array_merge($filterinfo, $info);
9510          foreach ($filterinfo as $key => $value) {
9511              $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9512              $info['txt'] .= "$key: $value ";
9513          }
9514      }
9515  
9516      $stringmanager = get_string_manager();
9517      if (method_exists($stringmanager, 'get_performance_summary')) {
9518          list($filterinfo, $nicenames) = $stringmanager->get_performance_summary();
9519          $info = array_merge($filterinfo, $info);
9520          foreach ($filterinfo as $key => $value) {
9521              $info['html'] .= "<li class='$key col-sm-4'>$nicenames[$key]: $value </li> ";
9522              $info['txt'] .= "$key: $value ";
9523          }
9524      }
9525  
9526      if (!empty($PERF->logwrites)) {
9527          $info['logwrites'] = $PERF->logwrites;
9528          $info['html'] .= '<li class="logwrites col-sm-4">Log DB writes '.$info['logwrites'].'</li> ';
9529          $info['txt'] .= 'logwrites: '.$info['logwrites'].' ';
9530      }
9531  
9532      $info['dbqueries'] = $DB->perf_get_reads().'/'.($DB->perf_get_writes() - $PERF->logwrites);
9533      $info['html'] .= '<li class="dbqueries col-sm-4">DB reads/writes: '.$info['dbqueries'].'</li> ';
9534      $info['txt'] .= 'db reads/writes: '.$info['dbqueries'].' ';
9535  
9536      if ($DB->want_read_slave()) {
9537          $info['dbreads_slave'] = $DB->perf_get_reads_slave();
9538          $info['html'] .= '<li class="dbqueries col-sm-4">DB reads from slave: '.$info['dbreads_slave'].'</li> ';
9539          $info['txt'] .= 'db reads from slave: '.$info['dbreads_slave'].' ';
9540      }
9541  
9542      $info['dbtime'] = round($DB->perf_get_queries_time(), 5);
9543      $info['html'] .= '<li class="dbtime col-sm-4">DB queries time: '.$info['dbtime'].' secs</li> ';
9544      $info['txt'] .= 'db queries time: ' . $info['dbtime'] . 's ';
9545  
9546      if (function_exists('posix_times')) {
9547          $ptimes = posix_times();
9548          if (is_array($ptimes)) {
9549              foreach ($ptimes as $key => $val) {
9550                  $info[$key] = $ptimes[$key] -  $PERF->startposixtimes[$key];
9551              }
9552              $info['html'] .= "<li class=\"posixtimes col-sm-4\">ticks: $info[ticks] user: $info[utime]";
9553              $info['html'] .= "sys: $info[stime] cuser: $info[cutime] csys: $info[cstime]</li> ";
9554              $info['txt'] .= "ticks: $info[ticks] user: $info[utime] sys: $info[stime] cuser: $info[cutime] csys: $info[cstime] ";
9555          }
9556      }
9557  
9558      // Grab the load average for the last minute.
9559      // /proc will only work under some linux configurations
9560      // while uptime is there under MacOSX/Darwin and other unices.
9561      if (is_readable('/proc/loadavg') && $loadavg = @file('/proc/loadavg')) {
9562          list($serverload) = explode(' ', $loadavg[0]);
9563          unset($loadavg);
9564      } else if ( function_exists('is_executable') && is_executable('/usr/bin/uptime') && $loadavg = `/usr/bin/uptime` ) {
9565          if (preg_match('/load averages?: (\d+[\.,:]\d+)/', $loadavg, $matches)) {
9566              $serverload = $matches[1];
9567          } else {
9568              trigger_error('Could not parse uptime output!');
9569          }
9570      }
9571      if (!empty($serverload)) {
9572          $info['serverload'] = $serverload;
9573          $info['html'] .= '<li class="serverload col-sm-4">Load average: '.$info['serverload'].'</li> ';
9574          $info['txt'] .= "serverload: {$info['serverload']} ";
9575      }
9576  
9577      // Display size of session if session started.
9578      if ($si = \core\session\manager::get_performance_info()) {
9579          $info['sessionsize'] = $si['size'];
9580          $info['html'] .= "<li class=\"serverload col-sm-4\">" . $si['html'] . "</li>";
9581          $info['txt'] .= $si['txt'];
9582      }
9583  
9584      $info['html'] .= '</ul>';
9585      $html = '';
9586      if ($stats = cache_helper::get_stats()) {
9587  
9588          $table = new html_table();
9589          $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9590          $table->head = ['Mode', 'Cache item', 'Static', 'H', 'M', get_string('mappingprimary', 'cache'), 'H', 'M', 'S'];
9591          $table->data = [];
9592          $table->align = ['left', 'left', 'left', 'right', 'right', 'left', 'right', 'right', 'right'];
9593  
9594          $text = 'Caches used (hits/misses/sets): ';
9595          $hits = 0;
9596          $misses = 0;
9597          $sets = 0;
9598          $maxstores = 0;
9599  
9600          // We want to align static caches into their own column.
9601          $hasstatic = false;
9602          foreach ($stats as $definition => $details) {
9603              $numstores = count($details['stores']);
9604              $first = key($details['stores']);
9605              if ($first !== cache_store::STATIC_ACCEL) {
9606                  $numstores++; // Add a blank space for the missing static store.
9607              }
9608              $maxstores = max($maxstores, $numstores);
9609          }
9610  
9611          $storec = 0;
9612  
9613          while ($storec++ < ($maxstores - 2)) {
9614              if ($storec == ($maxstores - 2)) {
9615                  $table->head[] = get_string('mappingfinal', 'cache');
9616              } else {
9617                  $table->head[] = "Store $storec";
9618              }
9619              $table->align[] = 'left';
9620              $table->align[] = 'right';
9621              $table->align[] = 'right';
9622              $table->align[] = 'right';
9623              $table->head[] = 'H';
9624              $table->head[] = 'M';
9625              $table->head[] = 'S';
9626          }
9627  
9628          ksort($stats);
9629  
9630          foreach ($stats as $definition => $details) {
9631              switch ($details['mode']) {
9632                  case cache_store::MODE_APPLICATION:
9633                      $modeclass = 'application';
9634                      $mode = ' <span title="application cache">App</span>';
9635                      break;
9636                  case cache_store::MODE_SESSION:
9637                      $modeclass = 'session';
9638                      $mode = ' <span title="session cache">Ses</span>';
9639                      break;
9640                  case cache_store::MODE_REQUEST:
9641                      $modeclass = 'request';
9642                      $mode = ' <span title="request cache">Req</span>';
9643                      break;
9644              }
9645              $row = [$mode, $definition];
9646  
9647              $text .= "$definition {";
9648  
9649              $storec = 0;
9650              foreach ($details['stores'] as $store => $data) {
9651  
9652                  if ($storec == 0 && $store !== cache_store::STATIC_ACCEL) {
9653                      $row[] = '';
9654                      $row[] = '';
9655                      $row[] = '';
9656                      $storec++;
9657                  }
9658  
9659                  $hits   += $data['hits'];
9660                  $misses += $data['misses'];
9661                  $sets   += $data['sets'];
9662                  if ($data['hits'] == 0 and $data['misses'] > 0) {
9663                      $cachestoreclass = 'nohits bg-danger';
9664                  } else if ($data['hits'] < $data['misses']) {
9665                      $cachestoreclass = 'lowhits bg-warning text-dark';
9666                  } else {
9667                      $cachestoreclass = 'hihits';
9668                  }
9669                  $text .= "$store($data[hits]/$data[misses]/$data[sets]) ";
9670                  $cell = new html_table_cell($store);
9671                  $cell->attributes = ['class' => $cachestoreclass];
9672                  $row[] = $cell;
9673                  $cell = new html_table_cell($data['hits']);
9674                  $cell->attributes = ['class' => $cachestoreclass];
9675                  $row[] = $cell;
9676                  $cell = new html_table_cell($data['misses']);
9677                  $cell->attributes = ['class' => $cachestoreclass];
9678                  $row[] = $cell;
9679  
9680                  if ($store !== cache_store::STATIC_ACCEL) {
9681                      // The static cache is never set.
9682                      $cell = new html_table_cell($data['sets']);
9683                      $cell->attributes = ['class' => $cachestoreclass];
9684                      $row[] = $cell;
9685                  }
9686                  $storec++;
9687              }
9688              while ($storec++ < $maxstores) {
9689                  $row[] = '';
9690                  $row[] = '';
9691                  $row[] = '';
9692                  $row[] = '';
9693              }
9694              $text .= '} ';
9695  
9696              $table->data[] = $row;
9697          }
9698  
9699          $html .= html_writer::table($table);
9700  
9701          // Now lets also show sub totals for each cache store.
9702          $storetotals = [];
9703          $storetotal = ['hits' => 0, 'misses' => 0, 'sets' => 0];
9704          foreach ($stats as $definition => $details) {
9705              foreach ($details['stores'] as $store => $data) {
9706                  if (!array_key_exists($store, $storetotals)) {
9707                      $storetotals[$store] = ['hits' => 0, 'misses' => 0, 'sets' => 0];
9708                  }
9709                  $storetotals[$store]['class']   = $data['class'];
9710                  $storetotals[$store]['hits']   += $data['hits'];
9711                  $storetotals[$store]['misses'] += $data['misses'];
9712                  $storetotals[$store]['sets']   += $data['sets'];
9713                  $storetotal['hits']   += $data['hits'];
9714                  $storetotal['misses'] += $data['misses'];
9715                  $storetotal['sets']   += $data['sets'];
9716              }
9717          }
9718  
9719          $table = new html_table();
9720          $table->attributes['class'] = 'cachesused table table-dark table-sm w-auto table-bordered';
9721          $table->head = [get_string('storename', 'cache'), get_string('type_cachestore', 'plugin'), 'H', 'M', 'S'];
9722          $table->data = [];
9723          $table->align = ['left', 'left', 'right', 'right', 'right'];
9724  
9725          ksort($storetotals);
9726  
9727          foreach ($storetotals as $store => $data) {
9728              $row = [];
9729              if ($data['hits'] == 0 and $data['misses'] > 0) {
9730                  $cachestoreclass = 'nohits bg-danger';
9731              } else if ($data['hits'] < $data['misses']) {
9732                  $cachestoreclass = 'lowhits bg-warning text-dark';
9733              } else {
9734                  $cachestoreclass = 'hihits';
9735              }
9736              $cell = new html_table_cell($store);
9737              $cell->attributes = ['class' => $cachestoreclass];
9738              $row[] = $cell;
9739              $cell = new html_table_cell($data['class']);
9740              $cell->attributes = ['class' => $cachestoreclass];
9741              $row[] = $cell;
9742              $cell = new html_table_cell($data['hits']);
9743              $cell->attributes = ['class' => $cachestoreclass];
9744              $row[] = $cell;
9745              $cell = new html_table_cell($data['misses']);
9746              $cell->attributes = ['class' => $cachestoreclass];
9747              $row[] = $cell;
9748              $cell = new html_table_cell($data['sets']);
9749              $cell->attributes = ['class' => $cachestoreclass];
9750              $row[] = $cell;
9751              $table->data[] = $row;
9752          }
9753          $row = [
9754              get_string('total'),
9755              '',
9756              $storetotal['hits'],
9757              $storetotal['misses'],
9758              $storetotal['sets'],
9759          ];
9760          $table->data[] = $row;
9761  
9762          $html .= html_writer::table($table);
9763  
9764          $info['cachesused'] = "$hits / $misses / $sets";
9765          $info['html'] .= $html;
9766          $info['txt'] .= $text.'. ';
9767      } else {
9768          $info['cachesused'] = '0 / 0 / 0';
9769          $info['html'] .= '<div class="cachesused">Caches used (hits/misses/sets): 0/0/0</div>';
9770          $info['txt'] .= 'Caches used (hits/misses/sets): 0/0/0 ';
9771      }
9772  
9773      $info['html'] = '<div class="performanceinfo siteinfo container-fluid px-md-0 overflow-auto mt-3">'.$info['html'].'</div>';
9774      return $info;
9775  }
9776  
9777  /**
9778   * Renames a file or directory to a unique name within the same directory.
9779   *
9780   * This function is designed to avoid any potential race conditions, and select an unused name.
9781   *
9782   * @param string $filepath Original filepath
9783   * @param string $prefix Prefix to use for the temporary name
9784   * @return string|bool New file path or false if failed
9785   * @since Moodle 3.10
9786   */
9787  function rename_to_unused_name(string $filepath, string $prefix = '_temp_') {
9788      $dir = dirname($filepath);
9789      $basename = $dir . '/' . $prefix;
9790      $limit = 0;
9791      while ($limit < 100) {
9792          // Select a new name based on a random number.
9793          $newfilepath = $basename . md5(mt_rand());
9794  
9795          // Attempt a rename to that new name.
9796          if (@rename($filepath, $newfilepath)) {
9797              return $newfilepath;
9798          }
9799  
9800          // The first time, do some sanity checks, maybe it is failing for a good reason and there
9801          // is no point trying 100 times if so.
9802          if ($limit === 0 && (!file_exists($filepath) || !is_writable($dir))) {
9803              return false;
9804          }
9805          $limit++;
9806      }
9807      return false;
9808  }
9809  
9810  /**
9811   * Delete directory or only its content
9812   *
9813   * @param string $dir directory path
9814   * @param bool $contentonly
9815   * @return bool success, true also if dir does not exist
9816   */
9817  function remove_dir($dir, $contentonly=false) {
9818      if (!is_dir($dir)) {
9819          // Nothing to do.
9820          return true;
9821      }
9822  
9823      if (!$contentonly) {
9824          // Start by renaming the directory; this will guarantee that other processes don't write to it
9825          // while it is in the process of being deleted.
9826          $tempdir = rename_to_unused_name($dir);
9827          if ($tempdir) {
9828              // If the rename was successful then delete the $tempdir instead.
9829              $dir = $tempdir;
9830          }
9831          // If the rename fails, we will continue through and attempt to delete the directory
9832          // without renaming it since that is likely to at least delete most of the files.
9833      }
9834  
9835      if (!$handle = opendir($dir)) {
9836          return false;
9837      }
9838      $result = true;
9839      while (false!==($item = readdir($handle))) {
9840          if ($item != '.' && $item != '..') {
9841              if (is_dir($dir.'/'.$item)) {
9842                  $result = remove_dir($dir.'/'.$item) && $result;
9843              } else {
9844                  $result = unlink($dir.'/'.$item) && $result;
9845              }
9846          }
9847      }
9848      closedir($handle);
9849      if ($contentonly) {
9850          clearstatcache(); // Make sure file stat cache is properly invalidated.
9851          return $result;
9852      }
9853      $result = rmdir($dir); // If anything left the result will be false, no need for && $result.
9854      clearstatcache(); // Make sure file stat cache is properly invalidated.
9855      return $result;
9856  }
9857  
9858  /**
9859   * Detect if an object or a class contains a given property
9860   * will take an actual object or the name of a class
9861   *
9862   * @param mix $obj Name of class or real object to test
9863   * @param string $property name of property to find
9864   * @return bool true if property exists
9865   */
9866  function object_property_exists( $obj, $property ) {
9867      if (is_string( $obj )) {
9868          $properties = get_class_vars( $obj );
9869      } else {
9870          $properties = get_object_vars( $obj );
9871      }
9872      return array_key_exists( $property, $properties );
9873  }
9874  
9875  /**
9876   * Converts an object into an associative array
9877   *
9878   * This function converts an object into an associative array by iterating
9879   * over its public properties. Because this function uses the foreach
9880   * construct, Iterators are respected. It works recursively on arrays of objects.
9881   * Arrays and simple values are returned as is.
9882   *
9883   * If class has magic properties, it can implement IteratorAggregate
9884   * and return all available properties in getIterator()
9885   *
9886   * @param mixed $var
9887   * @return array
9888   */
9889  function convert_to_array($var) {
9890      $result = array();
9891  
9892      // Loop over elements/properties.
9893      foreach ($var as $key => $value) {
9894          // Recursively convert objects.
9895          if (is_object($value) || is_array($value)) {
9896              $result[$key] = convert_to_array($value);
9897          } else {
9898              // Simple values are untouched.
9899              $result[$key] = $value;
9900          }
9901      }
9902      return $result;
9903  }
9904  
9905  /**
9906   * Detect a custom script replacement in the data directory that will
9907   * replace an existing moodle script
9908   *
9909   * @return string|bool full path name if a custom script exists, false if no custom script exists
9910   */
9911  function custom_script_path() {
9912      global $CFG, $SCRIPT;
9913  
9914      if ($SCRIPT === null) {
9915          // Probably some weird external script.
9916          return false;
9917      }
9918  
9919      $scriptpath = $CFG->customscripts . $SCRIPT;
9920  
9921      // Check the custom script exists.
9922      if (file_exists($scriptpath) and is_file($scriptpath)) {
9923          return $scriptpath;
9924      } else {
9925          return false;
9926      }
9927  }
9928  
9929  /**
9930   * Returns whether or not the user object is a remote MNET user. This function
9931   * is in moodlelib because it does not rely on loading any of the MNET code.
9932   *
9933   * @param object $user A valid user object
9934   * @return bool        True if the user is from a remote Moodle.
9935   */
9936  function is_mnet_remote_user($user) {
9937      global $CFG;
9938  
9939      if (!isset($CFG->mnet_localhost_id)) {
9940          include_once($CFG->dirroot . '/mnet/lib.php');
9941          $env = new mnet_environment();
9942          $env->init();
9943          unset($env);
9944      }
9945  
9946      return (!empty($user->mnethostid) && $user->mnethostid != $CFG->mnet_localhost_id);
9947  }
9948  
9949  /**
9950   * This function will search for browser prefereed languages, setting Moodle
9951   * to use the best one available if $SESSION->lang is undefined
9952   */
9953  function setup_lang_from_browser() {
9954      global $CFG, $SESSION, $USER;
9955  
9956      if (!empty($SESSION->lang) or !empty($USER->lang) or empty($CFG->autolang)) {
9957          // Lang is defined in session or user profile, nothing to do.
9958          return;
9959      }
9960  
9961      if (!isset($_SERVER['HTTP_ACCEPT_LANGUAGE'])) { // There isn't list of browser langs, nothing to do.
9962          return;
9963      }
9964  
9965      // Extract and clean langs from headers.
9966      $rawlangs = $_SERVER['HTTP_ACCEPT_LANGUAGE'];
9967      $rawlangs = str_replace('-', '_', $rawlangs);         // We are using underscores.
9968      $rawlangs = explode(',', $rawlangs);                  // Convert to array.
9969      $langs = array();
9970  
9971      $order = 1.0;
9972      foreach ($rawlangs as $lang) {
9973          if (strpos($lang, ';') === false) {
9974              $langs[(string)$order] = $lang;
9975              $order = $order-0.01;
9976          } else {
9977              $parts = explode(';', $lang);
9978              $pos = strpos($parts[1], '=');
9979              $langs[substr($parts[1], $pos+1)] = $parts[0];
9980          }
9981      }
9982      krsort($langs, SORT_NUMERIC);
9983  
9984      // Look for such langs under standard locations.
9985      foreach ($langs as $lang) {
9986          // Clean it properly for include.
9987          $lang = strtolower(clean_param($lang, PARAM_SAFEDIR));
9988          if (get_string_manager()->translation_exists($lang, false)) {
9989              // Lang exists, set it in session.
9990              $SESSION->lang = $lang;
9991              // We have finished. Go out.
9992              break;
9993          }
9994      }
9995      return;
9996  }
9997  
9998  /**
9999   * Check if $url matches anything in proxybypass list
10000   *
10001   * Any errors just result in the proxy being used (least bad)
10002   *
10003   * @param string $url url to check
10004   * @return boolean true if we should bypass the proxy
10005   */
10006  function is_proxybypass( $url ) {
10007      global $CFG;
10008  
10009      // Sanity check.
10010      if (empty($CFG->proxyhost) or empty($CFG->proxybypass)) {
10011          return false;
10012      }
10013  
10014      // Get the host part out of the url.
10015      if (!$host = parse_url( $url, PHP_URL_HOST )) {
10016          return false;
10017      }
10018  
10019      // Get the possible bypass hosts into an array.
10020      $matches = explode( ',', $CFG->proxybypass );
10021  
10022      // Check for a exact match on the IP or in the domains.
10023      $isdomaininallowedlist = \core\ip_utils::is_domain_in_allowed_list($host, $matches);
10024      $isipinsubnetlist = \core\ip_utils::is_ip_in_subnet_list($host, $CFG->proxybypass, ',');
10025  
10026      if ($isdomaininallowedlist || $isipinsubnetlist) {
10027          return true;
10028      }
10029  
10030      // Nothing matched.
10031      return false;
10032  }
10033  
10034  /**
10035   * Check if the passed navigation is of the new style
10036   *
10037   * @param mixed $navigation
10038   * @return bool true for yes false for no
10039   */
10040  function is_newnav($navigation) {
10041      if (is_array($navigation) && !empty($navigation['newnav'])) {
10042          return true;
10043      } else {
10044          return false;
10045      }
10046  }
10047  
10048  /**
10049   * Checks whether the given variable name is defined as a variable within the given object.
10050   *
10051   * This will NOT work with stdClass objects, which have no class variables.
10052   *
10053   * @param string $var The variable name
10054   * @param object $object The object to check
10055   * @return boolean
10056   */
10057  function in_object_vars($var, $object) {
10058      $classvars = get_class_vars(get_class($object));
10059      $classvars = array_keys($classvars);
10060      return in_array($var, $classvars);
10061  }
10062  
10063  /**
10064   * Returns an array without repeated objects.
10065   * This function is similar to array_unique, but for arrays that have objects as values
10066   *
10067   * @param array $array
10068   * @param bool $keepkeyassoc
10069   * @return array
10070   */
10071  function object_array_unique($array, $keepkeyassoc = true) {
10072      $duplicatekeys = array();
10073      $tmp         = array();
10074  
10075      foreach ($array as $key => $val) {
10076          // Convert objects to arrays, in_array() does not support objects.
10077          if (is_object($val)) {
10078              $val = (array)$val;
10079          }
10080  
10081          if (!in_array($val, $tmp)) {
10082              $tmp[] = $val;
10083          } else {
10084              $duplicatekeys[] = $key;
10085          }
10086      }
10087  
10088      foreach ($duplicatekeys as $key) {
10089          unset($array[$key]);
10090      }
10091  
10092      return $keepkeyassoc ? $array : array_values($array);
10093  }
10094  
10095  /**
10096   * Is a userid the primary administrator?
10097   *
10098   * @param int $userid int id of user to check
10099   * @return boolean
10100   */
10101  function is_primary_admin($userid) {
10102      $primaryadmin =  get_admin();
10103  
10104      if ($userid == $primaryadmin->id) {
10105          return true;
10106      } else {
10107          return false;
10108      }
10109  }
10110  
10111  /**
10112   * Returns the site identifier
10113   *
10114   * @return string $CFG->siteidentifier, first making sure it is properly initialised.
10115   */
10116  function get_site_identifier() {
10117      global $CFG;
10118      // Check to see if it is missing. If so, initialise it.
10119      if (empty($CFG->siteidentifier)) {
10120          set_config('siteidentifier', random_string(32) . $_SERVER['HTTP_HOST']);
10121      }
10122      // Return it.
10123      return $CFG->siteidentifier;
10124  }
10125  
10126  /**
10127   * Check whether the given password has no more than the specified
10128   * number of consecutive identical characters.
10129   *
10130   * @param string $password   password to be checked against the password policy
10131   * @param integer $maxchars  maximum number of consecutive identical characters
10132   * @return bool
10133   */
10134  function check_consecutive_identical_characters($password, $maxchars) {
10135  
10136      if ($maxchars < 1) {
10137          return true; // Zero 0 is to disable this check.
10138      }
10139      if (strlen($password) <= $maxchars) {
10140          return true; // Too short to fail this test.
10141      }
10142  
10143      $previouschar = '';
10144      $consecutivecount = 1;
10145      foreach (str_split($password) as $char) {
10146          if ($char != $previouschar) {
10147              $consecutivecount = 1;
10148          } else {
10149              $consecutivecount++;
10150              if ($consecutivecount > $maxchars) {
10151                  return false; // Check failed already.
10152              }
10153          }
10154  
10155          $previouschar = $char;
10156      }
10157  
10158      return true;
10159  }
10160  
10161  /**
10162   * Helper function to do partial function binding.
10163   * so we can use it for preg_replace_callback, for example
10164   * this works with php functions, user functions, static methods and class methods
10165   * it returns you a callback that you can pass on like so:
10166   *
10167   * $callback = partial('somefunction', $arg1, $arg2);
10168   *     or
10169   * $callback = partial(array('someclass', 'somestaticmethod'), $arg1, $arg2);
10170   *     or even
10171   * $obj = new someclass();
10172   * $callback = partial(array($obj, 'somemethod'), $arg1, $arg2);
10173   *
10174   * and then the arguments that are passed through at calltime are appended to the argument list.
10175   *
10176   * @param mixed $function a php callback
10177   * @param mixed $arg1,... $argv arguments to partially bind with
10178   * @return array Array callback
10179   */
10180  function partial() {
10181      if (!class_exists('partial')) {
10182          /**
10183           * Used to manage function binding.
10184           * @copyright  2009 Penny Leach
10185           * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10186           */
10187          class partial{
10188              /** @var array */
10189              public $values = array();
10190              /** @var string The function to call as a callback. */
10191              public $func;
10192              /**
10193               * Constructor
10194               * @param string $func
10195               * @param array $args
10196               */
10197              public function __construct($func, $args) {
10198                  $this->values = $args;
10199                  $this->func = $func;
10200              }
10201              /**
10202               * Calls the callback function.
10203               * @return mixed
10204               */
10205              public function method() {
10206                  $args = func_get_args();
10207                  return call_user_func_array($this->func, array_merge($this->values, $args));
10208              }
10209          }
10210      }
10211      $args = func_get_args();
10212      $func = array_shift($args);
10213      $p = new partial($func, $args);
10214      return array($p, 'method');
10215  }
10216  
10217  /**
10218   * helper function to load up and initialise the mnet environment
10219   * this must be called before you use mnet functions.
10220   *
10221   * @return mnet_environment the equivalent of old $MNET global
10222   */
10223  function get_mnet_environment() {
10224      global $CFG;
10225      require_once($CFG->dirroot . '/mnet/lib.php');
10226      static $instance = null;
10227      if (empty($instance)) {
10228          $instance = new mnet_environment();
10229          $instance->init();
10230      }
10231      return $instance;
10232  }
10233  
10234  /**
10235   * during xmlrpc server code execution, any code wishing to access
10236   * information about the remote peer must use this to get it.
10237   *
10238   * @return mnet_remote_client the equivalent of old $MNETREMOTE_CLIENT global
10239   */
10240  function get_mnet_remote_client() {
10241      if (!defined('MNET_SERVER')) {
10242          debugging(get_string('notinxmlrpcserver', 'mnet'));
10243          return false;
10244      }
10245      global $MNET_REMOTE_CLIENT;
10246      if (isset($MNET_REMOTE_CLIENT)) {
10247          return $MNET_REMOTE_CLIENT;
10248      }
10249      return false;
10250  }
10251  
10252  /**
10253   * during the xmlrpc server code execution, this will be called
10254   * to setup the object returned by {@link get_mnet_remote_client}
10255   *
10256   * @param mnet_remote_client $client the client to set up
10257   * @throws moodle_exception
10258   */
10259  function set_mnet_remote_client($client) {
10260      if (!defined('MNET_SERVER')) {
10261          throw new moodle_exception('notinxmlrpcserver', 'mnet');
10262      }
10263      global $MNET_REMOTE_CLIENT;
10264      $MNET_REMOTE_CLIENT = $client;
10265  }
10266  
10267  /**
10268   * return the jump url for a given remote user
10269   * this is used for rewriting forum post links in emails, etc
10270   *
10271   * @param stdclass $user the user to get the idp url for
10272   */
10273  function mnet_get_idp_jump_url($user) {
10274      global $CFG;
10275  
10276      static $mnetjumps = array();
10277      if (!array_key_exists($user->mnethostid, $mnetjumps)) {
10278          $idp = mnet_get_peer_host($user->mnethostid);
10279          $idpjumppath = mnet_get_app_jumppath($idp->applicationid);
10280          $mnetjumps[$user->mnethostid] = $idp->wwwroot . $idpjumppath . '?hostwwwroot=' . $CFG->wwwroot . '&wantsurl=';
10281      }
10282      return $mnetjumps[$user->mnethostid];
10283  }
10284  
10285  /**
10286   * Gets the homepage to use for the current user
10287   *
10288   * @return int One of HOMEPAGE_*
10289   */
10290  function get_home_page() {
10291      global $CFG;
10292  
10293      if (isloggedin() && !isguestuser() && !empty($CFG->defaulthomepage)) {
10294          if ($CFG->defaulthomepage == HOMEPAGE_MY) {
10295              return HOMEPAGE_MY;
10296          } else {
10297              return (int)get_user_preferences('user_home_page_preference', HOMEPAGE_MY);
10298          }
10299      }
10300      return HOMEPAGE_SITE;
10301  }
10302  
10303  /**
10304   * Gets the name of a course to be displayed when showing a list of courses.
10305   * By default this is just $course->fullname but user can configure it. The
10306   * result of this function should be passed through print_string.
10307   * @param stdClass|core_course_list_element $course Moodle course object
10308   * @return string Display name of course (either fullname or short + fullname)
10309   */
10310  function get_course_display_name_for_list($course) {
10311      global $CFG;
10312      if (!empty($CFG->courselistshortnames)) {
10313          if (!($course instanceof stdClass)) {
10314              $course = (object)convert_to_array($course);
10315          }
10316          return get_string('courseextendednamedisplay', '', $course);
10317      } else {
10318          return $course->fullname;
10319      }
10320  }
10321  
10322  /**
10323   * Safe analogue of unserialize() that can only parse arrays
10324   *
10325   * Arrays may contain only integers or strings as both keys and values. Nested arrays are allowed.
10326   *
10327   * @param string $expression
10328   * @return array|bool either parsed array or false if parsing was impossible.
10329   */
10330  function unserialize_array($expression) {
10331  
10332      // Check the expression is an array.
10333      if (!preg_match('/^a:(\d+):/', $expression)) {
10334          return false;
10335      }
10336  
10337      $values = (array) unserialize_object($expression);
10338  
10339      // Callback that returns true if the given value is an unserialized object, executes recursively.
10340      $invalidvaluecallback = static function($value) use (&$invalidvaluecallback): bool {
10341          if (is_array($value)) {
10342              return (bool) array_filter($value, $invalidvaluecallback);
10343          }
10344          return ($value instanceof stdClass) || ($value instanceof __PHP_Incomplete_Class);
10345      };
10346  
10347      // Iterate over the result to ensure there are no stray objects.
10348      if (array_filter($values, $invalidvaluecallback)) {
10349          return false;
10350      }
10351  
10352      return $values;
10353  }
10354  
10355  /**
10356   * Safe method for unserializing given input that is expected to contain only a serialized instance of an stdClass object
10357   *
10358   * If any class type other than stdClass is included in the input string, it will not be instantiated and will be cast to an
10359   * stdClass object. The initial cast to array, then back to object is to ensure we are always returning the correct type,
10360   * otherwise we would return an instances of {@see __PHP_Incomplete_class} for malformed strings
10361   *
10362   * @param string $input
10363   * @return stdClass
10364   */
10365  function unserialize_object(string $input): stdClass {
10366      $instance = (array) unserialize($input, ['allowed_classes' => [stdClass::class]]);
10367      return (object) $instance;
10368  }
10369  
10370  /**
10371   * The lang_string class
10372   *
10373   * This special class is used to create an object representation of a string request.
10374   * It is special because processing doesn't occur until the object is first used.
10375   * The class was created especially to aid performance in areas where strings were
10376   * required to be generated but were not necessarily used.
10377   * As an example the admin tree when generated uses over 1500 strings, of which
10378   * normally only 1/3 are ever actually printed at any time.
10379   * The performance advantage is achieved by not actually processing strings that
10380   * arn't being used, as such reducing the processing required for the page.
10381   *
10382   * How to use the lang_string class?
10383   *     There are two methods of using the lang_string class, first through the
10384   *     forth argument of the get_string function, and secondly directly.
10385   *     The following are examples of both.
10386   * 1. Through get_string calls e.g.
10387   *     $string = get_string($identifier, $component, $a, true);
10388   *     $string = get_string('yes', 'moodle', null, true);
10389   * 2. Direct instantiation
10390   *     $string = new lang_string($identifier, $component, $a, $lang);
10391   *     $string = new lang_string('yes');
10392   *
10393   * How do I use a lang_string object?
10394   *     The lang_string object makes use of a magic __toString method so that you
10395   *     are able to use the object exactly as you would use a string in most cases.
10396   *     This means you are able to collect it into a variable and then directly
10397   *     echo it, or concatenate it into another string, or similar.
10398   *     The other thing you can do is manually get the string by calling the
10399   *     lang_strings out method e.g.
10400   *         $string = new lang_string('yes');
10401   *         $string->out();
10402   *     Also worth noting is that the out method can take one argument, $lang which
10403   *     allows the developer to change the language on the fly.
10404   *
10405   * When should I use a lang_string object?
10406   *     The lang_string object is designed to be used in any situation where a
10407   *     string may not be needed, but needs to be generated.
10408   *     The admin tree is a good example of where lang_string objects should be
10409   *     used.
10410   *     A more practical example would be any class that requries strings that may
10411   *     not be printed (after all classes get renderer by renderers and who knows
10412   *     what they will do ;))
10413   *
10414   * When should I not use a lang_string object?
10415   *     Don't use lang_strings when you are going to use a string immediately.
10416   *     There is no need as it will be processed immediately and there will be no
10417   *     advantage, and in fact perhaps a negative hit as a class has to be
10418   *     instantiated for a lang_string object, however get_string won't require
10419   *     that.
10420   *
10421   * Limitations:
10422   * 1. You cannot use a lang_string object as an array offset. Doing so will
10423   *     result in PHP throwing an error. (You can use it as an object property!)
10424   *
10425   * @package    core
10426   * @category   string
10427   * @copyright  2011 Sam Hemelryk
10428   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
10429   */
10430  class lang_string {
10431  
10432      /** @var string The strings identifier */
10433      protected $identifier;
10434      /** @var string The strings component. Default '' */
10435      protected $component = '';
10436      /** @var array|stdClass Any arguments required for the string. Default null */
10437      protected $a = null;
10438      /** @var string The language to use when processing the string. Default null */
10439      protected $lang = null;
10440  
10441      /** @var string The processed string (once processed) */
10442      protected $string = null;
10443  
10444      /**
10445       * A special boolean. If set to true then the object has been woken up and
10446       * cannot be regenerated. If this is set then $this->string MUST be used.
10447       * @var bool
10448       */
10449      protected $forcedstring = false;
10450  
10451      /**
10452       * Constructs a lang_string object
10453       *
10454       * This function should do as little processing as possible to ensure the best
10455       * performance for strings that won't be used.
10456       *
10457       * @param string $identifier The strings identifier
10458       * @param string $component The strings component
10459       * @param stdClass|array $a Any arguments the string requires
10460       * @param string $lang The language to use when processing the string.
10461       * @throws coding_exception
10462       */
10463      public function __construct($identifier, $component = '', $a = null, $lang = null) {
10464          if (empty($component)) {
10465              $component = 'moodle';
10466          }
10467  
10468          $this->identifier = $identifier;
10469          $this->component = $component;
10470          $this->lang = $lang;
10471  
10472          // We MUST duplicate $a to ensure that it if it changes by reference those
10473          // changes are not carried across.
10474          // To do this we always ensure $a or its properties/values are strings
10475          // and that any properties/values that arn't convertable are forgotten.
10476          if ($a !== null) {
10477              if (is_scalar($a)) {
10478                  $this->a = $a;
10479              } else if ($a instanceof lang_string) {
10480                  $this->a = $a->out();
10481              } else if (is_object($a) or is_array($a)) {
10482                  $a = (array)$a;
10483                  $this->a = array();
10484                  foreach ($a as $key => $value) {
10485                      // Make sure conversion errors don't get displayed (results in '').
10486                      if (is_array($value)) {
10487                          $this->a[$key] = '';
10488                      } else if (is_object($value)) {
10489                          if (method_exists($value, '__toString')) {
10490                              $this->a[$key] = $value->__toString();
10491                          } else {
10492                              $this->a[$key] = '';
10493                          }
10494                      } else {
10495                          $this->a[$key] = (string)$value;
10496                      }
10497                  }
10498              }
10499          }
10500  
10501          if (debugging(false, DEBUG_DEVELOPER)) {
10502              if (clean_param($this->identifier, PARAM_STRINGID) == '') {
10503                  throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition');
10504              }
10505              if (!empty($this->component) && clean_param($this->component, PARAM_COMPONENT) == '') {
10506                  throw new coding_exception('Invalid string compontent. Please check your string definition');
10507              }
10508              if (!get_string_manager()->string_exists($this->identifier, $this->component)) {
10509                  debugging('String does not exist. Please check your string definition for '.$this->identifier.'/'.$this->component, DEBUG_DEVELOPER);
10510              }
10511          }
10512      }
10513  
10514      /**
10515       * Processes the string.
10516       *
10517       * This function actually processes the string, stores it in the string property
10518       * and then returns it.
10519       * You will notice that this function is VERY similar to the get_string method.
10520       * That is because it is pretty much doing the same thing.
10521       * However as this function is an upgrade it isn't as tolerant to backwards
10522       * compatibility.
10523       *
10524       * @return string
10525       * @throws coding_exception
10526       */
10527      protected function get_string() {
10528          global $CFG;
10529  
10530          // Check if we need to process the string.
10531          if ($this->string === null) {
10532              // Check the quality of the identifier.
10533              if ($CFG->debugdeveloper && clean_param($this->identifier, PARAM_STRINGID) === '') {
10534                  throw new coding_exception('Invalid string identifier. Most probably some illegal character is part of the string identifier. Please check your string definition', DEBUG_DEVELOPER);
10535              }
10536  
10537              // Process the string.
10538              $this->string = get_string_manager()->get_string($this->identifier, $this->component, $this->a, $this->lang);
10539              // Debugging feature lets you display string identifier and component.
10540              if (isset($CFG->debugstringids) && $CFG->debugstringids && optional_param('strings', 0, PARAM_INT)) {
10541                  $this->string .= ' {' . $this->identifier . '/' . $this->component . '}';
10542              }
10543          }
10544          // Return the string.
10545          return $this->string;
10546      }
10547  
10548      /**
10549       * Returns the string
10550       *
10551       * @param string $lang The langauge to use when processing the string
10552       * @return string
10553       */
10554      public function out($lang = null) {
10555          if ($lang !== null && $lang != $this->lang && ($this->lang == null && $lang != current_language())) {
10556              if ($this->forcedstring) {
10557                  debugging('lang_string objects that have been used cannot be printed in another language. ('.$this->lang.' used)', DEBUG_DEVELOPER);
10558                  return $this->get_string();
10559              }
10560              $translatedstring = new lang_string($this->identifier, $this->component, $this->a, $lang);
10561              return $translatedstring->out();
10562          }
10563          return $this->get_string();
10564      }
10565  
10566      /**
10567       * Magic __toString method for printing a string
10568       *
10569       * @return string
10570       */
10571      public function __toString() {
10572          return $this->get_string();
10573      }
10574  
10575      /**
10576       * Magic __set_state method used for var_export
10577       *
10578       * @param array $array
10579       * @return self
10580       */
10581      public static function __set_state(array $array): self {
10582          $tmp = new lang_string($array['identifier'], $array['component'], $array['a'], $array['lang']);
10583          $tmp->string = $array['string'];
10584          $tmp->forcedstring = $array['forcedstring'];
10585          return $tmp;
10586      }
10587  
10588      /**
10589       * Prepares the lang_string for sleep and stores only the forcedstring and
10590       * string properties... the string cannot be regenerated so we need to ensure
10591       * it is generated for this.
10592       *
10593       * @return string
10594       */
10595      public function __sleep() {
10596          $this->get_string();
10597          $this->forcedstring = true;
10598          return array('forcedstring', 'string', 'lang');
10599      }
10600  
10601      /**
10602       * Returns the identifier.
10603       *
10604       * @return string
10605       */
10606      public function get_identifier() {
10607          return $this->identifier;
10608      }
10609  
10610      /**
10611       * Returns the component.
10612       *
10613       * @return string
10614       */
10615      public function get_component() {
10616          return $this->component;
10617      }
10618  }
10619  
10620  /**
10621   * Get human readable name describing the given callable.
10622   *
10623   * This performs syntax check only to see if the given param looks like a valid function, method or closure.
10624   * It does not check if the callable actually exists.
10625   *
10626   * @param callable|string|array $callable
10627   * @return string|bool Human readable name of callable, or false if not a valid callable.
10628   */
10629  function get_callable_name($callable) {
10630  
10631      if (!is_callable($callable, true, $name)) {
10632          return false;
10633  
10634      } else {
10635          return $name;
10636      }
10637  }
10638  
10639  /**
10640   * Tries to guess if $CFG->wwwroot is publicly accessible or not.
10641   * Never put your faith on this function and rely on its accuracy as there might be false positives.
10642   * It just performs some simple checks, and mainly is used for places where we want to hide some options
10643   * such as site registration when $CFG->wwwroot is not publicly accessible.
10644   * Good thing is there is no false negative.
10645   * Note that it's possible to force the result of this check by specifying $CFG->site_is_public in config.php
10646   *
10647   * @return bool
10648   */
10649  function site_is_public() {
10650      global $CFG;
10651  
10652      // Return early if site admin has forced this setting.
10653      if (isset($CFG->site_is_public)) {
10654          return (bool)$CFG->site_is_public;
10655      }
10656  
10657      $host = parse_url($CFG->wwwroot, PHP_URL_HOST);
10658  
10659      if ($host === 'localhost' || preg_match('|^127\.\d+\.\d+\.\d+$|', $host)) {
10660          $ispublic = false;
10661      } else if (\core\ip_utils::is_ip_address($host) && !ip_is_public($host)) {
10662          $ispublic = false;
10663      } else if (($address = \core\ip_utils::get_ip_address($host)) && !ip_is_public($address)) {
10664          $ispublic = false;
10665      } else {
10666          $ispublic = true;
10667      }
10668  
10669      return $ispublic;
10670  }