Search moodle.org's
Developer Documentation

  • Bug fixes for general core bugs in 3.6.x will end 11 November 2019 (12 months).
  • Bug fixes for security issues in 3.6.x will end 11 May 2020 (18 months) - Support has ended.
  • minimum PHP 7.0.0 Note: minimum PHP version has increased since Moodle 3.3. PHP 7.1.x and 7.2.x are supported too. PHP 7.3.x support is being implemented (@ MDL-63420) and not ready for production with this release.
  • /lib/ -> moodlelib.php (source)

    Differences Between: [Versions 35 and 36] [Versions 36 and 310] [Versions 36 and 311] [Versions 36 and 37] [Versions 36 and 38] [Versions 36 and 39]

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