Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.
/lib/ -> setuplib.php (source)

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

   1  <?php
   2  // This file is part of Moodle - http://moodle.org/
   3  //
   4  // Moodle is free software: you can redistribute it and/or modify
   5  // it under the terms of the GNU General Public License as published by
   6  // the Free Software Foundation, either version 3 of the License, or
   7  // (at your option) any later version.
   8  //
   9  // Moodle is distributed in the hope that it will be useful,
  10  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  12  // GNU General Public License for more details.
  13  //
  14  // You should have received a copy of the GNU General Public License
  15  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  16  
  17  /**
  18   * These functions are required very early in the Moodle
  19   * setup process, before any of the main libraries are
  20   * loaded.
  21   *
  22   * @package    core
  23   * @subpackage lib
  24   * @copyright  1999 onwards Martin Dougiamas  {@link http://moodle.com}
  25   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  26   */
  27  
  28  defined('MOODLE_INTERNAL') || die();
  29  
  30  // Debug levels - always keep the values in ascending order!
  31  /** No warnings and errors at all */
  32  define('DEBUG_NONE', 0);
  33  /** Fatal errors only */
  34  define('DEBUG_MINIMAL', E_ERROR | E_PARSE);
  35  /** Errors, warnings and notices */
  36  define('DEBUG_NORMAL', E_ERROR | E_PARSE | E_WARNING | E_NOTICE);
  37  /** All problems except strict PHP warnings */
  38  define('DEBUG_ALL', E_ALL & ~E_STRICT);
  39  /** DEBUG_ALL with all debug messages and strict warnings */
  40  define('DEBUG_DEVELOPER', E_ALL | E_STRICT);
  41  
  42  /** Remove any memory limits */
  43  define('MEMORY_UNLIMITED', -1);
  44  /** Standard memory limit for given platform */
  45  define('MEMORY_STANDARD', -2);
  46  /**
  47   * Large memory limit for given platform - used in cron, upgrade, and other places that need a lot of memory.
  48   * Can be overridden with $CFG->extramemorylimit setting.
  49   */
  50  define('MEMORY_EXTRA', -3);
  51  /** Extremely large memory limit - not recommended for standard scripts */
  52  define('MEMORY_HUGE', -4);
  53  
  54  /**
  55   * Base Moodle Exception class
  56   *
  57   * Although this class is defined here, you cannot throw a moodle_exception until
  58   * after moodlelib.php has been included (which will happen very soon).
  59   *
  60   * @package    core
  61   * @subpackage lib
  62   * @copyright  2008 Petr Skoda  {@link http://skodak.org}
  63   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  64   */
  65  class moodle_exception extends Exception {
  66  
  67      /**
  68       * @var string The name of the string from error.php to print
  69       */
  70      public $errorcode;
  71  
  72      /**
  73       * @var string The name of module
  74       */
  75      public $module;
  76  
  77      /**
  78       * @var mixed Extra words and phrases that might be required in the error string
  79       */
  80      public $a;
  81  
  82      /**
  83       * @var string The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
  84       */
  85      public $link;
  86  
  87      /**
  88       * @var string Optional information to aid the debugging process
  89       */
  90      public $debuginfo;
  91  
  92      /**
  93       * Constructor
  94       * @param string $errorcode The name of the string from error.php to print
  95       * @param string $module name of module
  96       * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
  97       * @param mixed $a Extra words and phrases that might be required in the error string
  98       * @param string $debuginfo optional debugging information
  99       */
 100      function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
 101          global $CFG;
 102  
 103          if (empty($module) || $module == 'moodle' || $module == 'core') {
 104              $module = 'error';
 105          }
 106  
 107          $this->errorcode = $errorcode;
 108          $this->module    = $module;
 109          $this->link      = $link;
 110          $this->a         = $a;
 111          $this->debuginfo = is_null($debuginfo) ? null : (string)$debuginfo;
 112  
 113          if (get_string_manager()->string_exists($errorcode, $module)) {
 114              $message = get_string($errorcode, $module, $a);
 115              $haserrorstring = true;
 116          } else {
 117              $message = $module . '/' . $errorcode;
 118              $haserrorstring = false;
 119          }
 120  
 121          $isinphpunittest = (defined('PHPUNIT_TEST') && PHPUNIT_TEST);
 122          $hasdebugdeveloper = (
 123              isset($CFG->debugdisplay) &&
 124              isset($CFG->debug) &&
 125              $CFG->debugdisplay &&
 126              $CFG->debug === DEBUG_DEVELOPER
 127          );
 128  
 129          if ($debuginfo) {
 130              if ($isinphpunittest || $hasdebugdeveloper) {
 131                  $message = "$message ($debuginfo)";
 132              }
 133          }
 134  
 135          if (!$haserrorstring and $isinphpunittest) {
 136              // Append the contents of $a to $debuginfo so helpful information isn't lost.
 137              // This emulates what {@link get_exception_info()} does. Unfortunately that
 138              // function is not used by phpunit.
 139              $message .= PHP_EOL.'$a contents: '.print_r($a, true);
 140          }
 141  
 142          parent::__construct($message, 0);
 143      }
 144  }
 145  
 146  /**
 147   * Course/activity access exception.
 148   *
 149   * This exception is thrown from require_login()
 150   *
 151   * @package    core_access
 152   * @copyright  2010 Petr Skoda  {@link http://skodak.org}
 153   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 154   */
 155  class require_login_exception extends moodle_exception {
 156      /**
 157       * Constructor
 158       * @param string $debuginfo Information to aid the debugging process
 159       */
 160      function __construct($debuginfo) {
 161          parent::__construct('requireloginerror', 'error', '', NULL, $debuginfo);
 162      }
 163  }
 164  
 165  /**
 166   * Session timeout exception.
 167   *
 168   * This exception is thrown from require_login()
 169   *
 170   * @package    core_access
 171   * @copyright  2015 Andrew Nicols <andrew@nicols.co.uk>
 172   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 173   */
 174  class require_login_session_timeout_exception extends require_login_exception {
 175      /**
 176       * Constructor
 177       */
 178      public function __construct() {
 179          moodle_exception::__construct('sessionerroruser', 'error');
 180      }
 181  }
 182  
 183  /**
 184   * Web service parameter exception class
 185   * @deprecated since Moodle 2.2 - use moodle exception instead
 186   * This exception must be thrown to the web service client when a web service parameter is invalid
 187   * The error string is gotten from webservice.php
 188   */
 189  class webservice_parameter_exception extends moodle_exception {
 190      /**
 191       * Constructor
 192       * @param string $errorcode The name of the string from webservice.php to print
 193       * @param string $a The name of the parameter
 194       * @param string $debuginfo Optional information to aid debugging
 195       */
 196      function __construct($errorcode=null, $a = '', $debuginfo = null) {
 197          parent::__construct($errorcode, 'webservice', '', $a, $debuginfo);
 198      }
 199  }
 200  
 201  /**
 202   * Exceptions indicating user does not have permissions to do something
 203   * and the execution can not continue.
 204   *
 205   * @package    core_access
 206   * @copyright  2009 Petr Skoda  {@link http://skodak.org}
 207   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 208   */
 209  class required_capability_exception extends moodle_exception {
 210      /**
 211       * Constructor
 212       * @param context $context The context used for the capability check
 213       * @param string $capability The required capability
 214       * @param string $errormessage The error message to show the user
 215       * @param string $stringfile
 216       */
 217      function __construct($context, $capability, $errormessage, $stringfile) {
 218          $capabilityname = get_capability_string($capability);
 219          if ($context->contextlevel == CONTEXT_MODULE and preg_match('/:view$/', $capability)) {
 220              // we can not go to mod/xx/view.php because we most probably do not have cap to view it, let's go to course instead
 221              $parentcontext = $context->get_parent_context();
 222              $link = $parentcontext->get_url();
 223          } else {
 224              $link = $context->get_url();
 225          }
 226          parent::__construct($errormessage, $stringfile, $link, $capabilityname);
 227      }
 228  }
 229  
 230  /**
 231   * Exception indicating programming error, must be fixed by a programer. For example
 232   * a core API might throw this type of exception if a plugin calls it incorrectly.
 233   *
 234   * @package    core
 235   * @subpackage lib
 236   * @copyright  2008 Petr Skoda  {@link http://skodak.org}
 237   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 238   */
 239  class coding_exception extends moodle_exception {
 240      /**
 241       * Constructor
 242       * @param string $hint short description of problem
 243       * @param string $debuginfo detailed information how to fix problem
 244       */
 245      function __construct($hint, $debuginfo=null) {
 246          parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
 247      }
 248  }
 249  
 250  /**
 251   * Exception indicating malformed parameter problem.
 252   * This exception is not supposed to be thrown when processing
 253   * user submitted data in forms. It is more suitable
 254   * for WS and other low level stuff.
 255   *
 256   * @package    core
 257   * @subpackage lib
 258   * @copyright  2009 Petr Skoda  {@link http://skodak.org}
 259   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 260   */
 261  class invalid_parameter_exception extends moodle_exception {
 262      /**
 263       * Constructor
 264       * @param string $debuginfo some detailed information
 265       */
 266      function __construct($debuginfo=null) {
 267          parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
 268      }
 269  }
 270  
 271  /**
 272   * Exception indicating malformed response problem.
 273   * This exception is not supposed to be thrown when processing
 274   * user submitted data in forms. It is more suitable
 275   * for WS and other low level stuff.
 276   */
 277  class invalid_response_exception extends moodle_exception {
 278      /**
 279       * Constructor
 280       * @param string $debuginfo some detailed information
 281       */
 282      function __construct($debuginfo=null) {
 283          parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
 284      }
 285  }
 286  
 287  /**
 288   * An exception that indicates something really weird happened. For example,
 289   * if you do switch ($context->contextlevel), and have one case for each
 290   * CONTEXT_... constant. You might throw an invalid_state_exception in the
 291   * default case, to just in case something really weird is going on, and
 292   * $context->contextlevel is invalid - rather than ignoring this possibility.
 293   *
 294   * @package    core
 295   * @subpackage lib
 296   * @copyright  2009 onwards Martin Dougiamas  {@link http://moodle.com}
 297   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 298   */
 299  class invalid_state_exception extends moodle_exception {
 300      /**
 301       * Constructor
 302       * @param string $hint short description of problem
 303       * @param string $debuginfo optional more detailed information
 304       */
 305      function __construct($hint, $debuginfo=null) {
 306          parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
 307      }
 308  }
 309  
 310  /**
 311   * An exception that indicates incorrect permissions in $CFG->dataroot
 312   *
 313   * @package    core
 314   * @subpackage lib
 315   * @copyright  2010 Petr Skoda {@link http://skodak.org}
 316   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 317   */
 318  class invalid_dataroot_permissions extends moodle_exception {
 319      /**
 320       * Constructor
 321       * @param string $debuginfo optional more detailed information
 322       */
 323      function __construct($debuginfo = NULL) {
 324          parent::__construct('invaliddatarootpermissions', 'error', '', NULL, $debuginfo);
 325      }
 326  }
 327  
 328  /**
 329   * An exception that indicates that file can not be served
 330   *
 331   * @package    core
 332   * @subpackage lib
 333   * @copyright  2010 Petr Skoda {@link http://skodak.org}
 334   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
 335   */
 336  class file_serving_exception extends moodle_exception {
 337      /**
 338       * Constructor
 339       * @param string $debuginfo optional more detailed information
 340       */
 341      function __construct($debuginfo = NULL) {
 342          parent::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
 343      }
 344  }
 345  
 346  /**
 347   * Default exception handler.
 348   *
 349   * @param Exception $ex
 350   * @return void -does not return. Terminates execution!
 351   */
 352  function default_exception_handler($ex) {
 353      global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION, $PAGE;
 354  
 355      // detect active db transactions, rollback and log as error
 356      abort_all_db_transactions();
 357  
 358      if (($ex instanceof required_capability_exception) && !CLI_SCRIPT && !AJAX_SCRIPT && !empty($CFG->autologinguests) && !empty($USER->autologinguest)) {
 359          $SESSION->wantsurl = qualified_me();
 360          redirect(get_login_url());
 361      }
 362  
 363      $info = get_exception_info($ex);
 364  
 365      // If we already tried to send the header remove it, the content length
 366      // should be either empty or the length of the error page.
 367      @header_remove('Content-Length');
 368  
 369      if (is_early_init($info->backtrace)) {
 370          echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
 371      } else {
 372          if (debugging('', DEBUG_MINIMAL)) {
 373              $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
 374              error_log($logerrmsg);
 375          }
 376  
 377          try {
 378              if ($DB) {
 379                  // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
 380                  $DB->set_debug(0);
 381              }
 382              if (AJAX_SCRIPT) {
 383                  // If we are in an AJAX script we don't want to use PREFERRED_RENDERER_TARGET.
 384                  // Because we know we will want to use ajax format.
 385                  $renderer = new core_renderer_ajax($PAGE, 'ajax');
 386              } else {
 387                  $renderer = $OUTPUT;
 388              }
 389              echo $renderer->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo,
 390                  $info->errorcode);
 391          } catch (Exception $e) {
 392              $out_ex = $e;
 393          } catch (Throwable $e) {
 394              // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
 395              $out_ex = $e;
 396          }
 397  
 398          if (isset($out_ex)) {
 399              // default exception handler MUST not throw any exceptions!!
 400              // the problem here is we do not know if page already started or not, we only know that somebody messed up in outputlib or theme
 401              // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
 402              if (CLI_SCRIPT or AJAX_SCRIPT) {
 403                  // just ignore the error and send something back using the safest method
 404                  echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
 405              } else {
 406                  echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
 407                  $outinfo = get_exception_info($out_ex);
 408                  echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
 409              }
 410          }
 411      }
 412  
 413      exit(1); // General error code
 414  }
 415  
 416  /**
 417   * Default error handler, prevents some white screens.
 418   * @param int $errno
 419   * @param string $errstr
 420   * @param string $errfile
 421   * @param int $errline
 422   * @return bool false means use default error handler
 423   */
 424  function default_error_handler($errno, $errstr, $errfile, $errline) {
 425      if ($errno == 4096) {
 426          //fatal catchable error
 427          throw new coding_exception('PHP catchable fatal error', $errstr);
 428      }
 429      return false;
 430  }
 431  
 432  /**
 433   * Unconditionally abort all database transactions, this function
 434   * should be called from exception handlers only.
 435   * @return void
 436   */
 437  function abort_all_db_transactions() {
 438      global $CFG, $DB, $SCRIPT;
 439  
 440      // default exception handler MUST not throw any exceptions!!
 441  
 442      if ($DB && $DB->is_transaction_started()) {
 443          error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
 444          // note: transaction blocks should never change current $_SESSION
 445          $DB->force_transaction_rollback();
 446      }
 447  }
 448  
 449  /**
 450   * This function encapsulates the tests for whether an exception was thrown in
 451   * early init -- either during setup.php or during init of $OUTPUT.
 452   *
 453   * If another exception is thrown then, and if we do not take special measures,
 454   * we would just get a very cryptic message "Exception thrown without a stack
 455   * frame in Unknown on line 0". That makes debugging very hard, so we do take
 456   * special measures in default_exception_handler, with the help of this function.
 457   *
 458   * @param array $backtrace the stack trace to analyse.
 459   * @return boolean whether the stack trace is somewhere in output initialisation.
 460   */
 461  function is_early_init($backtrace) {
 462      $dangerouscode = array(
 463          array('function' => 'header', 'type' => '->'),
 464          array('class' => 'bootstrap_renderer'),
 465          array('file' => __DIR__.'/setup.php'),
 466      );
 467      foreach ($backtrace as $stackframe) {
 468          foreach ($dangerouscode as $pattern) {
 469              $matches = true;
 470              foreach ($pattern as $property => $value) {
 471                  if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
 472                      $matches = false;
 473                  }
 474              }
 475              if ($matches) {
 476                  return true;
 477              }
 478          }
 479      }
 480      return false;
 481  }
 482  
 483  /**
 484   * Abort execution by throwing of a general exception,
 485   * default exception handler displays the error message in most cases.
 486   *
 487   * @param string $errorcode The name of the language string containing the error message.
 488   *      Normally this should be in the error.php lang file.
 489   * @param string $module The language file to get the error message from.
 490   * @param string $link The url where the user will be prompted to continue.
 491   *      If no url is provided the user will be directed to the site index page.
 492   * @param object $a Extra words and phrases that might be required in the error string
 493   * @param string $debuginfo optional debugging information
 494   * @return void, always throws exception!
 495   */
 496  function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
 497      throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
 498  }
 499  
 500  /**
 501   * Returns detailed information about specified exception.
 502   *
 503   * @param Throwable $ex any sort of exception or throwable.
 504   * @return stdClass standardised info to display. Fields are clear if you look at the end of this function.
 505   */
 506  function get_exception_info($ex): stdClass {
 507      global $CFG;
 508  
 509      if ($ex instanceof moodle_exception) {
 510          $errorcode = $ex->errorcode;
 511          $module = $ex->module;
 512          $a = $ex->a;
 513          $link = $ex->link;
 514          $debuginfo = $ex->debuginfo;
 515      } else {
 516          $errorcode = 'generalexceptionmessage';
 517          $module = 'error';
 518          $a = $ex->getMessage();
 519          $link = '';
 520          $debuginfo = '';
 521      }
 522  
 523      // Append the error code to the debug info to make grepping and googling easier
 524      $debuginfo .= PHP_EOL."Error code: $errorcode";
 525  
 526      $backtrace = $ex->getTrace();
 527      $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
 528      array_unshift($backtrace, $place);
 529  
 530      // Be careful, no guarantee moodlelib.php is loaded.
 531      if (empty($module) || $module == 'moodle' || $module == 'core') {
 532          $module = 'error';
 533      }
 534      // Search for the $errorcode's associated string
 535      // If not found, append the contents of $a to $debuginfo so helpful information isn't lost
 536      if (function_exists('get_string_manager')) {
 537          if (get_string_manager()->string_exists($errorcode, $module)) {
 538              $message = get_string($errorcode, $module, $a);
 539          } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
 540              // Search in moodle file if error specified - needed for backwards compatibility
 541              $message = get_string($errorcode, 'moodle', $a);
 542          } else {
 543              $message = $module . '/' . $errorcode;
 544              $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
 545          }
 546      } else {
 547          $message = $module . '/' . $errorcode;
 548          $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
 549      }
 550  
 551      // Remove some absolute paths from message and debugging info.
 552      $searches = array();
 553      $replaces = array();
 554      $cfgnames = array('backuptempdir', 'tempdir', 'cachedir', 'localcachedir', 'themedir', 'dataroot', 'dirroot');
 555      foreach ($cfgnames as $cfgname) {
 556          if (property_exists($CFG, $cfgname)) {
 557              $searches[] = $CFG->$cfgname;
 558              $replaces[] = "[$cfgname]";
 559          }
 560      }
 561      if (!empty($searches)) {
 562          $message   = str_replace($searches, $replaces, $message);
 563          $debuginfo = str_replace($searches, $replaces, $debuginfo);
 564      }
 565  
 566      // Be careful, no guarantee weblib.php is loaded.
 567      if (function_exists('clean_text')) {
 568          $message = clean_text($message);
 569      } else {
 570          $message = htmlspecialchars($message);
 571      }
 572  
 573      if (!empty($CFG->errordocroot)) {
 574          $errordoclink = $CFG->errordocroot . '/en/';
 575      } else {
 576          // Only if the function is available. May be not for early errors.
 577          if (function_exists('current_language')) {
 578              $errordoclink = get_docs_url();
 579          } else {
 580              $errordoclink = 'https://docs.moodle.org/en/';
 581          }
 582      }
 583  
 584      if ($module === 'error') {
 585          $modulelink = 'moodle';
 586      } else {
 587          $modulelink = $module;
 588      }
 589      $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
 590  
 591      if (empty($link)) {
 592          $link = get_local_referer(false) ?: ($CFG->wwwroot . '/');
 593      }
 594  
 595      // When printing an error the continue button should never link offsite.
 596      // We cannot use clean_param() here as it is not guaranteed that it has been loaded yet.
 597      if (stripos($link, $CFG->wwwroot) === 0) {
 598          // Internal HTTP, all good.
 599      } else {
 600          // External link spotted!
 601          $link = $CFG->wwwroot . '/';
 602      }
 603  
 604      $info = new stdClass();
 605      $info->message     = $message;
 606      $info->errorcode   = $errorcode;
 607      $info->backtrace   = $backtrace;
 608      $info->link        = $link;
 609      $info->moreinfourl = $moreinfourl;
 610      $info->a           = $a;
 611      $info->debuginfo   = $debuginfo;
 612  
 613      return $info;
 614  }
 615  
 616  /**
 617   * @deprecated since Moodle 3.8 MDL-61038 - please do not use this function any more.
 618   * @see \core\uuid::generate()
 619   */
 620  function generate_uuid() {
 621      throw new coding_exception('generate_uuid() cannot be used anymore. Please use ' .
 622          '\core\uuid::generate() instead.');
 623  }
 624  
 625  /**
 626   * Returns the Moodle Docs URL in the users language for a given 'More help' link.
 627   *
 628   * There are three cases:
 629   *
 630   * 1. In the normal case, $path will be a short relative path 'component/thing',
 631   * like 'mod/folder/view' 'group/import'. This gets turned into an link to
 632   * MoodleDocs in the user's language, and for the appropriate Moodle version.
 633   * E.g. 'group/import' may become 'http://docs.moodle.org/2x/en/group/import'.
 634   * The 'http://docs.moodle.org' bit comes from $CFG->docroot.
 635   *
 636   * This is the only option that should be used in standard Moodle code. The other
 637   * two options have been implemented because they are useful for third-party plugins.
 638   *
 639   * 2. $path may be an absolute URL, starting http:// or https://. In this case,
 640   * the link is used as is.
 641   *
 642   * 3. $path may start %%WWWROOT%%, in which case that is replaced by
 643   * $CFG->wwwroot to make the link.
 644   *
 645   * @param string $path the place to link to. See above for details.
 646   * @return string The MoodleDocs URL in the user's language. for example @link http://docs.moodle.org/2x/en/$path}
 647   */
 648  function get_docs_url($path = null) {
 649      global $CFG;
 650      if ($path === null) {
 651          $path = '';
 652      }
 653  
 654      // Absolute URLs are used unmodified.
 655      if (substr($path, 0, 7) === 'http://' || substr($path, 0, 8) === 'https://') {
 656          return $path;
 657      }
 658  
 659      // Paths starting %%WWWROOT%% have that replaced by $CFG->wwwroot.
 660      if (substr($path, 0, 11) === '%%WWWROOT%%') {
 661          return $CFG->wwwroot . substr($path, 11);
 662      }
 663  
 664      // Otherwise we do the normal case, and construct a MoodleDocs URL relative to $CFG->docroot.
 665  
 666      // Check that $CFG->branch has been set up, during installation it won't be.
 667      if (empty($CFG->branch)) {
 668          // It's not there yet so look at version.php.
 669          include($CFG->dirroot.'/version.php');
 670      } else {
 671          // We can use $CFG->branch and avoid having to include version.php.
 672          $branch = $CFG->branch;
 673      }
 674      // ensure branch is valid.
 675      if (!$branch) {
 676          // We should never get here but in case we do lets set $branch to .
 677          // the smart one's will know that this is the current directory
 678          // and the smarter ones will know that there is some smart matching
 679          // that will ensure people end up at the latest version of the docs.
 680          $branch = '.';
 681      }
 682      if (empty($CFG->doclang)) {
 683          $lang = current_language();
 684      } else {
 685          $lang = $CFG->doclang;
 686      }
 687      $end = '/' . $branch . '/' . $lang . '/' . $path;
 688      if (empty($CFG->docroot)) {
 689          return 'http://docs.moodle.org'. $end;
 690      } else {
 691          return $CFG->docroot . $end ;
 692      }
 693  }
 694  
 695  /**
 696   * Formats a backtrace ready for output.
 697   *
 698   * This function does not include function arguments because they could contain sensitive information
 699   * not suitable to be exposed in a response.
 700   *
 701   * @param array $callers backtrace array, as returned by debug_backtrace().
 702   * @param boolean $plaintext if false, generates HTML, if true generates plain text.
 703   * @return string formatted backtrace, ready for output.
 704   */
 705  function format_backtrace($callers, $plaintext = false) {
 706      // do not use $CFG->dirroot because it might not be available in destructors
 707      $dirroot = dirname(__DIR__);
 708  
 709      if (empty($callers)) {
 710          return '';
 711      }
 712  
 713      $from = $plaintext ? '' : '<ul style="text-align: left" data-rel="backtrace">';
 714      foreach ($callers as $caller) {
 715          if (!isset($caller['line'])) {
 716              $caller['line'] = '?'; // probably call_user_func()
 717          }
 718          if (!isset($caller['file'])) {
 719              $caller['file'] = 'unknownfile'; // probably call_user_func()
 720          }
 721          $line = $plaintext ? '* ' : '<li>';
 722          $line .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
 723          if (isset($caller['function'])) {
 724              $line .= ': call to ';
 725              if (isset($caller['class'])) {
 726                  $line .= $caller['class'] . $caller['type'];
 727              }
 728              $line .= $caller['function'] . '()';
 729          } else if (isset($caller['exception'])) {
 730              $line .= ': '.$caller['exception'].' thrown';
 731          }
 732  
 733          // Remove any non printable chars.
 734          $line = preg_replace('/[[:^print:]]/', '', $line);
 735  
 736          $line .= $plaintext ? "\n" : '</li>';
 737          $from .= $line;
 738      }
 739      $from .= $plaintext ? '' : '</ul>';
 740  
 741      return $from;
 742  }
 743  
 744  /**
 745   * This function makes the return value of ini_get consistent if you are
 746   * setting server directives through the .htaccess file in apache.
 747   *
 748   * Current behavior for value set from php.ini On = 1, Off = [blank]
 749   * Current behavior for value set from .htaccess On = On, Off = Off
 750   * Contributed by jdell @ unr.edu
 751   *
 752   * @param string $ini_get_arg The argument to get
 753   * @return bool True for on false for not
 754   */
 755  function ini_get_bool($ini_get_arg) {
 756      $temp = ini_get($ini_get_arg);
 757  
 758      if ($temp == '1' or strtolower($temp) == 'on') {
 759          return true;
 760      }
 761      return false;
 762  }
 763  
 764  /**
 765   * This function verifies the sanity of PHP configuration
 766   * and stops execution if anything critical found.
 767   */
 768  function setup_validate_php_configuration() {
 769     // this must be very fast - no slow checks here!!!
 770  
 771     if (ini_get_bool('session.auto_start')) {
 772         print_error('sessionautostartwarning', 'admin');
 773     }
 774  }
 775  
 776  /**
 777   * Initialise global $CFG variable.
 778   * @private to be used only from lib/setup.php
 779   */
 780  function initialise_cfg() {
 781      global $CFG, $DB;
 782  
 783      if (!$DB) {
 784          // This should not happen.
 785          return;
 786      }
 787  
 788      try {
 789          $localcfg = get_config('core');
 790      } catch (dml_exception $e) {
 791          // Most probably empty db, going to install soon.
 792          return;
 793      }
 794  
 795      foreach ($localcfg as $name => $value) {
 796          // Note that get_config() keeps forced settings
 797          // and normalises values to string if possible.
 798          $CFG->{$name} = $value;
 799      }
 800  }
 801  
 802  /**
 803   * Cache any immutable config locally to avoid constant DB lookups.
 804   *
 805   * Only to be used only from lib/setup.php
 806   */
 807  function initialise_local_config_cache() {
 808      global $CFG;
 809  
 810      $bootstrapcachefile = $CFG->localcachedir . '/bootstrap.php';
 811  
 812      if (!empty($CFG->siteidentifier) && !file_exists($bootstrapcachefile)) {
 813          $contents = "<?php
 814  // ********** This file is generated DO NOT EDIT **********
 815  \$CFG->siteidentifier = " . var_export($CFG->siteidentifier, true) . ";
 816  \$CFG->bootstraphash = " . var_export(hash_local_config_cache(), true) . ";
 817  // Only if the file is not stale and has not been defined.
 818  if (\$CFG->bootstraphash === hash_local_config_cache() && !defined('SYSCONTEXTID')) {
 819      define('SYSCONTEXTID', ".SYSCONTEXTID.");
 820  }
 821  ";
 822  
 823          $temp = $bootstrapcachefile . '.tmp' . uniqid();
 824          file_put_contents($temp, $contents);
 825          @chmod($temp, $CFG->filepermissions);
 826          rename($temp, $bootstrapcachefile);
 827      }
 828  }
 829  
 830  /**
 831   * Calculate a proper hash to be able to invalidate stale cached configs.
 832   *
 833   * Only to be used to verify bootstrap.php status.
 834   *
 835   * @return string md5 hash of all the sensible bits deciding if cached config is stale or no.
 836   */
 837  function hash_local_config_cache() {
 838      global $CFG;
 839  
 840      // This is pretty much {@see moodle_database::get_settings_hash()} that is used
 841      // as identifier for the database meta information MUC cache. Should be enough to
 842      // react against any of the normal changes (new prefix, change of DB type) while
 843      // *incorrectly* keeping the old dataroot directory unmodified with stale data.
 844      // This may need more stuff to be considered if it's discovered that there are
 845      // more variables making the file stale.
 846      return md5($CFG->dbtype . $CFG->dbhost . $CFG->dbuser . $CFG->dbname . $CFG->prefix);
 847  }
 848  
 849  /**
 850   * Initialises $FULLME and friends. Private function. Should only be called from
 851   * setup.php.
 852   */
 853  function initialise_fullme() {
 854      global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
 855  
 856      // Detect common config error.
 857      if (substr($CFG->wwwroot, -1) == '/') {
 858          print_error('wwwrootslash', 'error');
 859      }
 860  
 861      if (CLI_SCRIPT) {
 862          initialise_fullme_cli();
 863          return;
 864      }
 865      if (!empty($CFG->overridetossl)) {
 866          if (strpos($CFG->wwwroot, 'http://') === 0) {
 867              $CFG->wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
 868          } else {
 869              unset_config('overridetossl');
 870          }
 871      }
 872  
 873      $rurl = setup_get_remote_url();
 874      $wwwroot = parse_url($CFG->wwwroot.'/');
 875  
 876      if (empty($rurl['host'])) {
 877          // missing host in request header, probably not a real browser, let's ignore them
 878  
 879      } else if (!empty($CFG->reverseproxy)) {
 880          // $CFG->reverseproxy specifies if reverse proxy server used
 881          // Used in load balancing scenarios.
 882          // Do not abuse this to try to solve lan/wan access problems!!!!!
 883  
 884      } else {
 885          if (($rurl['host'] !== $wwwroot['host']) or
 886                  (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port']) or
 887                  (strpos($rurl['path'], $wwwroot['path']) !== 0)) {
 888  
 889              // Explain the problem and redirect them to the right URL
 890              if (!defined('NO_MOODLE_COOKIES')) {
 891                  define('NO_MOODLE_COOKIES', true);
 892              }
 893              // The login/token.php script should call the correct url/port.
 894              if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
 895                  $wwwrootport = empty($wwwroot['port'])?'':$wwwroot['port'];
 896                  $calledurl = $rurl['host'];
 897                  if (!empty($rurl['port'])) {
 898                      $calledurl .=  ':'. $rurl['port'];
 899                  }
 900                  $correcturl = $wwwroot['host'];
 901                  if (!empty($wwwrootport)) {
 902                      $correcturl .=  ':'. $wwwrootport;
 903                  }
 904                  throw new moodle_exception('requirecorrectaccess', 'error', '', null,
 905                      'You called ' . $calledurl .', you should have called ' . $correcturl);
 906              }
 907              redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
 908          }
 909      }
 910  
 911      // Check that URL is under $CFG->wwwroot.
 912      if (strpos($rurl['path'], $wwwroot['path']) === 0) {
 913          $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
 914      } else {
 915          // Probably some weird external script
 916          $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
 917          return;
 918      }
 919  
 920      // $CFG->sslproxy specifies if external SSL appliance is used
 921      // (That is, the Moodle server uses http, with an external box translating everything to https).
 922      if (empty($CFG->sslproxy)) {
 923          if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
 924              if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
 925                  print_error('sslonlyaccess', 'error');
 926              } else {
 927                  redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
 928              }
 929          }
 930      } else {
 931          if ($wwwroot['scheme'] !== 'https') {
 932              throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
 933          }
 934          $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
 935          $_SERVER['HTTPS'] = 'on'; // Override $_SERVER to help external libraries with their HTTPS detection.
 936          $_SERVER['SERVER_PORT'] = 443; // Assume default ssl port for the proxy.
 937      }
 938  
 939      // Hopefully this will stop all those "clever" admins trying to set up moodle
 940      // with two different addresses in intranet and Internet.
 941      // Port forwarding is still allowed!
 942      if (!empty($CFG->reverseproxy) && $rurl['host'] === $wwwroot['host'] && (empty($wwwroot['port']) || $rurl['port'] === $wwwroot['port'])) {
 943          print_error('reverseproxyabused', 'error');
 944      }
 945  
 946      $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
 947      if (!empty($wwwroot['port'])) {
 948          $hostandport .= ':'.$wwwroot['port'];
 949      }
 950  
 951      $FULLSCRIPT = $hostandport . $rurl['path'];
 952      $FULLME = $hostandport . $rurl['fullpath'];
 953      $ME = $rurl['fullpath'];
 954  }
 955  
 956  /**
 957   * Initialises $FULLME and friends for command line scripts.
 958   * This is a private method for use by initialise_fullme.
 959   */
 960  function initialise_fullme_cli() {
 961      global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
 962  
 963      // Urls do not make much sense in CLI scripts
 964      $backtrace = debug_backtrace();
 965      $topfile = array_pop($backtrace);
 966      $topfile = realpath($topfile['file']);
 967      $dirroot = realpath($CFG->dirroot);
 968  
 969      if (strpos($topfile, $dirroot) !== 0) {
 970          // Probably some weird external script
 971          $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
 972      } else {
 973          $relativefile = substr($topfile, strlen($dirroot));
 974          $relativefile = str_replace('\\', '/', $relativefile); // Win fix
 975          $SCRIPT = $FULLSCRIPT = $relativefile;
 976          $FULLME = $ME = null;
 977      }
 978  }
 979  
 980  /**
 981   * Get the URL that PHP/the web server thinks it is serving. Private function
 982   * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
 983   * @return array in the same format that parse_url returns, with the addition of
 984   *      a 'fullpath' element, which includes any slasharguments path.
 985   */
 986  function setup_get_remote_url() {
 987      $rurl = array();
 988      if (isset($_SERVER['HTTP_HOST'])) {
 989          list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
 990      } else {
 991          $rurl['host'] = null;
 992      }
 993      $rurl['port'] = (int)$_SERVER['SERVER_PORT'];
 994      $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
 995      $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ? 'http' : 'https';
 996  
 997      if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
 998          //Apache server
 999          $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
1000  
1001          // Fixing a known issue with:
1002          // - Apache versions lesser than 2.4.11
1003          // - PHP deployed in Apache as PHP-FPM via mod_proxy_fcgi
1004          // - PHP versions lesser than 5.6.3 and 5.5.18.
1005          if (isset($_SERVER['PATH_INFO']) && (php_sapi_name() === 'fpm-fcgi') && isset($_SERVER['SCRIPT_NAME'])) {
1006              $pathinfodec = rawurldecode($_SERVER['PATH_INFO']);
1007              $lenneedle = strlen($pathinfodec);
1008              // Checks whether SCRIPT_NAME ends with PATH_INFO, URL-decoded.
1009              if (substr($_SERVER['SCRIPT_NAME'], -$lenneedle) === $pathinfodec) {
1010                  // This is the "Apache 2.4.10- running PHP-FPM via mod_proxy_fcgi" fingerprint,
1011                  // at least on CentOS 7 (Apache/2.4.6 PHP/5.4.16) and Ubuntu 14.04 (Apache/2.4.7 PHP/5.5.9)
1012                  // => SCRIPT_NAME contains 'slash arguments' data too, which is wrongly exposed via PATH_INFO as URL-encoded.
1013                  // Fix both $_SERVER['PATH_INFO'] and $_SERVER['SCRIPT_NAME'].
1014                  $lenhaystack = strlen($_SERVER['SCRIPT_NAME']);
1015                  $pos = $lenhaystack - $lenneedle;
1016                  // Here $pos is greater than 0 but let's double check it.
1017                  if ($pos > 0) {
1018                      $_SERVER['PATH_INFO'] = $pathinfodec;
1019                      $_SERVER['SCRIPT_NAME'] = substr($_SERVER['SCRIPT_NAME'], 0, $pos);
1020                  }
1021              }
1022          }
1023  
1024      } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
1025          //IIS - needs a lot of tweaking to make it work
1026          $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
1027  
1028          // NOTE: we should ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS.
1029          //       Since 2.0, we rely on IIS rewrite extensions like Helicon ISAPI_rewrite
1030          //         example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
1031          //       OR
1032          //       we rely on a proper IIS 6.0+ configuration: the 'FastCGIUtf8ServerVariables' registry key.
1033          if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
1034              // Check that PATH_INFO works == must not contain the script name.
1035              if (strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === false) {
1036                  $rurl['fullpath'] .= clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
1037              }
1038          }
1039  
1040          if (isset($_SERVER['QUERY_STRING']) and $_SERVER['QUERY_STRING'] !== '') {
1041              $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
1042          }
1043          $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
1044  
1045  /* NOTE: following servers are not fully tested! */
1046  
1047      } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
1048          //lighttpd - not officially supported
1049          $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1050  
1051      } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
1052          //nginx - not officially supported
1053          if (!isset($_SERVER['SCRIPT_NAME'])) {
1054              die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
1055          }
1056          $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1057  
1058       } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
1059           //cherokee - not officially supported
1060           $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1061  
1062       } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
1063           //zeus - not officially supported
1064           $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1065  
1066      } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
1067          //LiteSpeed - not officially supported
1068          $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1069  
1070      } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
1071          //obscure name found on some servers - this is definitely not supported
1072          $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1073  
1074      } else if (strpos($_SERVER['SERVER_SOFTWARE'], 'PHP') === 0) {
1075          // built-in PHP Development Server
1076          $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
1077  
1078      } else {
1079          throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
1080      }
1081  
1082      // sanitize the url a bit more, the encoding style may be different in vars above
1083      $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
1084      $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);
1085  
1086      return $rurl;
1087  }
1088  
1089  /**
1090   * Try to work around the 'max_input_vars' restriction if necessary.
1091   */
1092  function workaround_max_input_vars() {
1093      // Make sure this gets executed only once from lib/setup.php!
1094      static $executed = false;
1095      if ($executed) {
1096          debugging('workaround_max_input_vars() must be called only once!');
1097          return;
1098      }
1099      $executed = true;
1100  
1101      if (!isset($_SERVER["CONTENT_TYPE"]) or strpos($_SERVER["CONTENT_TYPE"], 'multipart/form-data') !== false) {
1102          // Not a post or 'multipart/form-data' which is not compatible with "php://input" reading.
1103          return;
1104      }
1105  
1106      if (!isloggedin() or isguestuser()) {
1107          // Only real users post huge forms.
1108          return;
1109      }
1110  
1111      $max = (int)ini_get('max_input_vars');
1112  
1113      if ($max <= 0) {
1114          // Most probably PHP < 5.3.9 that does not implement this limit.
1115          return;
1116      }
1117  
1118      if ($max >= 200000) {
1119          // This value should be ok for all our forms, by setting it in php.ini
1120          // admins may prevent any unexpected regressions caused by this hack.
1121  
1122          // Note there is no need to worry about DDoS caused by making this limit very high
1123          // because there are very many easier ways to DDoS any Moodle server.
1124          return;
1125      }
1126  
1127      // Worst case is advanced checkboxes which use up to two max_input_vars
1128      // slots for each entry in $_POST, because of sending two fields with the
1129      // same name. So count everything twice just in case.
1130      if (count($_POST, COUNT_RECURSIVE) * 2 < $max) {
1131          return;
1132      }
1133  
1134      // Large POST request with enctype supported by php://input.
1135      // Parse php://input in chunks to bypass max_input_vars limit, which also applies to parse_str().
1136      $str = file_get_contents("php://input");
1137      if ($str === false or $str === '') {
1138          // Some weird error.
1139          return;
1140      }
1141  
1142      $delim = '&';
1143      $fun = function($p) use ($delim) {
1144          return implode($delim, $p);
1145      };
1146      $chunks = array_map($fun, array_chunk(explode($delim, $str), $max));
1147  
1148      // Clear everything from existing $_POST array, otherwise it might be included
1149      // twice (this affects array params primarily).
1150      foreach ($_POST as $key => $value) {
1151          unset($_POST[$key]);
1152          // Also clear from request array - but only the things that are in $_POST,
1153          // that way it will leave the things from a get request if any.
1154          unset($_REQUEST[$key]);
1155      }
1156  
1157      foreach ($chunks as $chunk) {
1158          $values = array();
1159          parse_str($chunk, $values);
1160  
1161          merge_query_params($_POST, $values);
1162          merge_query_params($_REQUEST, $values);
1163      }
1164  }
1165  
1166  /**
1167   * Merge parsed POST chunks.
1168   *
1169   * NOTE: this is not perfect, but it should work in most cases hopefully.
1170   *
1171   * @param array $target
1172   * @param array $values
1173   */
1174  function merge_query_params(array &$target, array $values) {
1175      if (isset($values[0]) and isset($target[0])) {
1176          // This looks like a split [] array, lets verify the keys are continuous starting with 0.
1177          $keys1 = array_keys($values);
1178          $keys2 = array_keys($target);
1179          if ($keys1 === array_keys($keys1) and $keys2 === array_keys($keys2)) {
1180              foreach ($values as $v) {
1181                  $target[] = $v;
1182              }
1183              return;
1184          }
1185      }
1186      foreach ($values as $k => $v) {
1187          if (!isset($target[$k])) {
1188              $target[$k] = $v;
1189              continue;
1190          }
1191          if (is_array($target[$k]) and is_array($v)) {
1192              merge_query_params($target[$k], $v);
1193              continue;
1194          }
1195          // We should not get here unless there are duplicates in params.
1196          $target[$k] = $v;
1197      }
1198  }
1199  
1200  /**
1201   * Initializes our performance info early.
1202   *
1203   * Pairs up with get_performance_info() which is actually
1204   * in moodlelib.php. This function is here so that we can
1205   * call it before all the libs are pulled in.
1206   *
1207   * @uses $PERF
1208   */
1209  function init_performance_info() {
1210  
1211      global $PERF, $CFG, $USER;
1212  
1213      $PERF = new stdClass();
1214      $PERF->logwrites = 0;
1215      if (function_exists('microtime')) {
1216          $PERF->starttime = microtime();
1217      }
1218      if (function_exists('memory_get_usage')) {
1219          $PERF->startmemory = memory_get_usage();
1220      }
1221      if (function_exists('posix_times')) {
1222          $PERF->startposixtimes = posix_times();
1223      }
1224  }
1225  
1226  /**
1227   * Indicates whether we are in the middle of the initial Moodle install.
1228   *
1229   * Very occasionally it is necessary avoid running certain bits of code before the
1230   * Moodle installation has completed. The installed flag is set in admin/index.php
1231   * after Moodle core and all the plugins have been installed, but just before
1232   * the person doing the initial install is asked to choose the admin password.
1233   *
1234   * @return boolean true if the initial install is not complete.
1235   */
1236  function during_initial_install() {
1237      global $CFG;
1238      return empty($CFG->rolesactive);
1239  }
1240  
1241  /**
1242   * Function to raise the memory limit to a new value.
1243   * Will respect the memory limit if it is higher, thus allowing
1244   * settings in php.ini, apache conf or command line switches
1245   * to override it.
1246   *
1247   * The memory limit should be expressed with a constant
1248   * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
1249   * It is possible to use strings or integers too (eg:'128M').
1250   *
1251   * @param mixed $newlimit the new memory limit
1252   * @return bool success
1253   */
1254  function raise_memory_limit($newlimit) {
1255      global $CFG;
1256  
1257      if ($newlimit == MEMORY_UNLIMITED) {
1258          ini_set('memory_limit', -1);
1259          return true;
1260  
1261      } else if ($newlimit == MEMORY_STANDARD) {
1262          if (PHP_INT_SIZE > 4) {
1263              $newlimit = get_real_size('128M'); // 64bit needs more memory
1264          } else {
1265              $newlimit = get_real_size('96M');
1266          }
1267  
1268      } else if ($newlimit == MEMORY_EXTRA) {
1269          if (PHP_INT_SIZE > 4) {
1270              $newlimit = get_real_size('384M'); // 64bit needs more memory
1271          } else {
1272              $newlimit = get_real_size('256M');
1273          }
1274          if (!empty($CFG->extramemorylimit)) {
1275              $extra = get_real_size($CFG->extramemorylimit);
1276              if ($extra > $newlimit) {
1277                  $newlimit = $extra;
1278              }
1279          }
1280  
1281      } else if ($newlimit == MEMORY_HUGE) {
1282          // MEMORY_HUGE uses 2G or MEMORY_EXTRA, whichever is bigger.
1283          $newlimit = get_real_size('2G');
1284          if (!empty($CFG->extramemorylimit)) {
1285              $extra = get_real_size($CFG->extramemorylimit);
1286              if ($extra > $newlimit) {
1287                  $newlimit = $extra;
1288              }
1289          }
1290  
1291      } else {
1292          $newlimit = get_real_size($newlimit);
1293      }
1294  
1295      if ($newlimit <= 0) {
1296          debugging('Invalid memory limit specified.');
1297          return false;
1298      }
1299  
1300      $cur = ini_get('memory_limit');
1301      if (empty($cur)) {
1302          // if php is compiled without --enable-memory-limits
1303          // apparently memory_limit is set to ''
1304          $cur = 0;
1305      } else {
1306          if ($cur == -1){
1307              return true; // unlimited mem!
1308          }
1309          $cur = get_real_size($cur);
1310      }
1311  
1312      if ($newlimit > $cur) {
1313          ini_set('memory_limit', $newlimit);
1314          return true;
1315      }
1316      return false;
1317  }
1318  
1319  /**
1320   * Function to reduce the memory limit to a new value.
1321   * Will respect the memory limit if it is lower, thus allowing
1322   * settings in php.ini, apache conf or command line switches
1323   * to override it
1324   *
1325   * The memory limit should be expressed with a string (eg:'64M')
1326   *
1327   * @param string $newlimit the new memory limit
1328   * @return bool
1329   */
1330  function reduce_memory_limit($newlimit) {
1331      if (empty($newlimit)) {
1332          return false;
1333      }
1334      $cur = ini_get('memory_limit');
1335      if (empty($cur)) {
1336          // if php is compiled without --enable-memory-limits
1337          // apparently memory_limit is set to ''
1338          $cur = 0;
1339      } else {
1340          if ($cur == -1){
1341              return true; // unlimited mem!
1342          }
1343          $cur = get_real_size($cur);
1344      }
1345  
1346      $new = get_real_size($newlimit);
1347      // -1 is smaller, but it means unlimited
1348      if ($new < $cur && $new != -1) {
1349          ini_set('memory_limit', $newlimit);
1350          return true;
1351      }
1352      return false;
1353  }
1354  
1355  /**
1356   * Converts numbers like 10M into bytes.
1357   *
1358   * @param string $size The size to be converted
1359   * @return int
1360   */
1361  function get_real_size($size = 0) {
1362      if (!$size) {
1363          return 0;
1364      }
1365  
1366      static $binaryprefixes = array(
1367          'K' => 1024 ** 1,
1368          'k' => 1024 ** 1,
1369          'M' => 1024 ** 2,
1370          'm' => 1024 ** 2,
1371          'G' => 1024 ** 3,
1372          'g' => 1024 ** 3,
1373          'T' => 1024 ** 4,
1374          't' => 1024 ** 4,
1375          'P' => 1024 ** 5,
1376          'p' => 1024 ** 5,
1377      );
1378  
1379      if (preg_match('/^([0-9]+)([KMGTP])/i', $size, $matches)) {
1380          return $matches[1] * $binaryprefixes[$matches[2]];
1381      }
1382  
1383      return (int) $size;
1384  }
1385  
1386  /**
1387   * Try to disable all output buffering and purge
1388   * all headers.
1389   *
1390   * @access private to be called only from lib/setup.php !
1391   * @return void
1392   */
1393  function disable_output_buffering() {
1394      $olddebug = error_reporting(0);
1395  
1396      // disable compression, it would prevent closing of buffers
1397      if (ini_get_bool('zlib.output_compression')) {
1398          ini_set('zlib.output_compression', 'Off');
1399      }
1400  
1401      // try to flush everything all the time
1402      ob_implicit_flush(true);
1403  
1404      // close all buffers if possible and discard any existing output
1405      // this can actually work around some whitespace problems in config.php
1406      while(ob_get_level()) {
1407          if (!ob_end_clean()) {
1408              // prevent infinite loop when buffer can not be closed
1409              break;
1410          }
1411      }
1412  
1413      // disable any other output handlers
1414      ini_set('output_handler', '');
1415  
1416      error_reporting($olddebug);
1417  
1418      // Disable buffering in nginx.
1419      header('X-Accel-Buffering: no');
1420  
1421  }
1422  
1423  /**
1424   * Check whether a major upgrade is needed.
1425   *
1426   * That is defined as an upgrade that changes something really fundamental
1427   * in the database, so nothing can possibly work until the database has
1428   * been updated, and that is defined by the hard-coded version number in
1429   * this function.
1430   *
1431   * @return bool
1432   */
1433  function is_major_upgrade_required() {
1434      global $CFG;
1435      $lastmajordbchanges = 2022022200.00;
1436  
1437      $required = empty($CFG->version);
1438      $required = $required || (float)$CFG->version < $lastmajordbchanges;
1439      $required = $required || during_initial_install();
1440      $required = $required || !empty($CFG->adminsetuppending);
1441  
1442      return $required;
1443  }
1444  
1445  /**
1446   * Redirect to the Notifications page if a major upgrade is required, and
1447   * terminate the current user session.
1448   */
1449  function redirect_if_major_upgrade_required() {
1450      global $CFG;
1451      if (is_major_upgrade_required()) {
1452          try {
1453              @\core\session\manager::terminate_current();
1454          } catch (Exception $e) {
1455              // Ignore any errors, redirect to upgrade anyway.
1456          }
1457          $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
1458          @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1459          @header('Location: ' . $url);
1460          echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
1461          exit;
1462      }
1463  }
1464  
1465  /**
1466   * Makes sure that upgrade process is not running
1467   *
1468   * To be inserted in the core functions that can not be called by pluigns during upgrade.
1469   * Core upgrade should not use any API functions at all.
1470   * See {@link http://docs.moodle.org/dev/Upgrade_API#Upgrade_code_restrictions}
1471   *
1472   * @throws moodle_exception if executed from inside of upgrade script and $warningonly is false
1473   * @param bool $warningonly if true displays a warning instead of throwing an exception
1474   * @return bool true if executed from outside of upgrade process, false if from inside upgrade process and function is used for warning only
1475   */
1476  function upgrade_ensure_not_running($warningonly = false) {
1477      global $CFG;
1478      if (!empty($CFG->upgraderunning)) {
1479          if (!$warningonly) {
1480              throw new moodle_exception('cannotexecduringupgrade');
1481          } else {
1482              debugging(get_string('cannotexecduringupgrade', 'error'), DEBUG_DEVELOPER);
1483              return false;
1484          }
1485      }
1486      return true;
1487  }
1488  
1489  /**
1490   * Function to check if a directory exists and by default create it if not exists.
1491   *
1492   * Previously this was accepting paths only from dataroot, but we now allow
1493   * files outside of dataroot if you supply custom paths for some settings in config.php.
1494   * This function does not verify that the directory is writable.
1495   *
1496   * NOTE: this function uses current file stat cache,
1497   *       please use clearstatcache() before this if you expect that the
1498   *       directories may have been removed recently from a different request.
1499   *
1500   * @param string $dir absolute directory path
1501   * @param boolean $create directory if does not exist
1502   * @param boolean $recursive create directory recursively
1503   * @return boolean true if directory exists or created, false otherwise
1504   */
1505  function check_dir_exists($dir, $create = true, $recursive = true) {
1506      global $CFG;
1507  
1508      umask($CFG->umaskpermissions);
1509  
1510      if (is_dir($dir)) {
1511          return true;
1512      }
1513  
1514      if (!$create) {
1515          return false;
1516      }
1517  
1518      return mkdir($dir, $CFG->directorypermissions, $recursive);
1519  }
1520  
1521  /**
1522   * Create a new unique directory within the specified directory.
1523   *
1524   * @param string $basedir The directory to create your new unique directory within.
1525   * @param bool $exceptiononerror throw exception if error encountered
1526   * @return string The created directory
1527   * @throws invalid_dataroot_permissions
1528   */
1529  function make_unique_writable_directory($basedir, $exceptiononerror = true) {
1530      if (!is_dir($basedir) || !is_writable($basedir)) {
1531          // The basedir is not writable. We will not be able to create the child directory.
1532          if ($exceptiononerror) {
1533              throw new invalid_dataroot_permissions($basedir . ' is not writable. Unable to create a unique directory within it.');
1534          } else {
1535              return false;
1536          }
1537      }
1538  
1539      do {
1540          // Let's use uniqid() because it's "unique enough" (microtime based). The loop does handle repetitions.
1541          // Windows and old PHP don't like very long paths, so try to keep this shorter. See MDL-69975.
1542          $uniquedir = $basedir . DIRECTORY_SEPARATOR . uniqid();
1543      } while (
1544              // Ensure that basedir is still writable - if we do not check, we could get stuck in a loop here.
1545              is_writable($basedir) &&
1546  
1547              // Make the new unique directory. If the directory already exists, it will return false.
1548              !make_writable_directory($uniquedir, $exceptiononerror) &&
1549  
1550              // Ensure that the directory now exists
1551              file_exists($uniquedir) && is_dir($uniquedir)
1552          );
1553  
1554      // Check that the directory was correctly created.
1555      if (!file_exists($uniquedir) || !is_dir($uniquedir) || !is_writable($uniquedir)) {
1556          if ($exceptiononerror) {
1557              throw new invalid_dataroot_permissions('Unique directory creation failed.');
1558          } else {
1559              return false;
1560          }
1561      }
1562  
1563      return $uniquedir;
1564  }
1565  
1566  /**
1567   * Create a directory and make sure it is writable.
1568   *
1569   * @private
1570   * @param string $dir  the full path of the directory to be created
1571   * @param bool $exceptiononerror throw exception if error encountered
1572   * @return string|false Returns full path to directory if successful, false if not; may throw exception
1573   */
1574  function make_writable_directory($dir, $exceptiononerror = true) {
1575      global $CFG;
1576  
1577      if (file_exists($dir) and !is_dir($dir)) {
1578          if ($exceptiononerror) {
1579              throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1580          } else {
1581              return false;
1582          }
1583      }
1584  
1585      umask($CFG->umaskpermissions);
1586  
1587      if (!file_exists($dir)) {
1588          if (!@mkdir($dir, $CFG->directorypermissions, true)) {
1589              clearstatcache();
1590              // There might be a race condition when creating directory.
1591              if (!is_dir($dir)) {
1592                  if ($exceptiononerror) {
1593                      throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1594                  } else {
1595                      debugging('Can not create directory: '.$dir, DEBUG_DEVELOPER);
1596                      return false;
1597                  }
1598              }
1599          }
1600      }
1601  
1602      if (!is_writable($dir)) {
1603          if ($exceptiononerror) {
1604              throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1605          } else {
1606              return false;
1607          }
1608      }
1609  
1610      return $dir;
1611  }
1612  
1613  /**
1614   * Protect a directory from web access.
1615   * Could be extended in the future to support other mechanisms (e.g. other webservers).
1616   *
1617   * @private
1618   * @param string $dir  the full path of the directory to be protected
1619   */
1620  function protect_directory($dir) {
1621      global $CFG;
1622      // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1623      if (!file_exists("$dir/.htaccess")) {
1624          if ($handle = fopen("$dir/.htaccess", 'w')) {   // For safety
1625              @fwrite($handle, "deny from all\r\nAllowOverride None\r\nNote: this file is broken intentionally, we do not want anybody to undo it in subdirectory!\r\n");
1626              @fclose($handle);
1627              @chmod("$dir/.htaccess", $CFG->filepermissions);
1628          }
1629      }
1630  }
1631  
1632  /**
1633   * Create a directory under dataroot and make sure it is writable.
1634   * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
1635   *
1636   * @param string $directory  the full path of the directory to be created under $CFG->dataroot
1637   * @param bool $exceptiononerror throw exception if error encountered
1638   * @return string|false Returns full path to directory if successful, false if not; may throw exception
1639   */
1640  function make_upload_directory($directory, $exceptiononerror = true) {
1641      global $CFG;
1642  
1643      if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1644          debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1645  
1646      } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
1647          debugging('Use make_cache_directory() for creation of cache directory and $CFG->cachedir to get the location.');
1648  
1649      } else if (strpos($directory, 'localcache/') === 0 or $directory === 'localcache') {
1650          debugging('Use make_localcache_directory() for creation of local cache directory and $CFG->localcachedir to get the location.');
1651      }
1652  
1653      protect_directory($CFG->dataroot);
1654      return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1655  }
1656  
1657  /**
1658   * Get a per-request storage directory in the tempdir.
1659   *
1660   * The directory is automatically cleaned up during the shutdown handler.
1661   *
1662   * @param   bool    $exceptiononerror throw exception if error encountered
1663   * @param   bool    $forcecreate Force creation of a new parent directory
1664   * @return  string  Returns full path to directory if successful, false if not; may throw exception
1665   */
1666  function get_request_storage_directory($exceptiononerror = true, bool $forcecreate = false) {
1667      global $CFG;
1668  
1669      static $requestdir = null;
1670  
1671      $writabledirectoryexists = (null !== $requestdir);
1672      $writabledirectoryexists = $writabledirectoryexists && file_exists($requestdir);
1673      $writabledirectoryexists = $writabledirectoryexists && is_dir($requestdir);
1674      $writabledirectoryexists = $writabledirectoryexists && is_writable($requestdir);
1675      $createnewdirectory = $forcecreate || !$writabledirectoryexists;
1676  
1677      if ($createnewdirectory) {
1678  
1679          // Let's add the first chars of siteidentifier only. This is to help separate
1680          // paths on systems which host multiple moodles. We don't use the full id
1681          // as Windows and old PHP don't like very long paths. See MDL-69975.
1682          $basedir = $CFG->localrequestdir . '/' . substr($CFG->siteidentifier, 0, 4);
1683  
1684          make_writable_directory($basedir);
1685          protect_directory($basedir);
1686  
1687          if ($dir = make_unique_writable_directory($basedir, $exceptiononerror)) {
1688              // Register a shutdown handler to remove the directory.
1689              \core_shutdown_manager::register_function('remove_dir', [$dir]);
1690          }
1691  
1692          $requestdir = $dir;
1693      }
1694  
1695      return $requestdir;
1696  }
1697  
1698  /**
1699   * Create a per-request directory and make sure it is writable.
1700   * This can only be used during the current request and will be tidied away
1701   * automatically afterwards.
1702   *
1703   * A new, unique directory is always created within a shared base request directory.
1704   *
1705   * In some exceptional cases an alternative base directory may be required. This can be accomplished using the
1706   * $forcecreate parameter. Typically this will only be requried where the file may be required during a shutdown handler
1707   * which may or may not be registered after a previous request directory has been created.
1708   *
1709   * @param   bool    $exceptiononerror throw exception if error encountered
1710   * @param   bool    $forcecreate Force creation of a new parent directory
1711   * @return  string  The full path to directory if successful, false if not; may throw exception
1712   */
1713  function make_request_directory(bool $exceptiononerror = true, bool $forcecreate = false) {
1714      $basedir = get_request_storage_directory($exceptiononerror, $forcecreate);
1715      return make_unique_writable_directory($basedir, $exceptiononerror);
1716  }
1717  
1718  /**
1719   * Get the full path of a directory under $CFG->backuptempdir.
1720   *
1721   * @param string $directory  the relative path of the directory under $CFG->backuptempdir
1722   * @return string|false Returns full path to directory given a valid string; otherwise, false.
1723   */
1724  function get_backup_temp_directory($directory) {
1725      global $CFG;
1726      if (($directory === null) || ($directory === false)) {
1727          return false;
1728      }
1729      return "$CFG->backuptempdir/$directory";
1730  }
1731  
1732  /**
1733   * Create a directory under $CFG->backuptempdir and make sure it is writable.
1734   *
1735   * Do not use for storing generic temp files - see make_temp_directory() instead for this purpose.
1736   *
1737   * Backup temporary files must be on a shared storage.
1738   *
1739   * @param string $directory  the relative path of the directory to be created under $CFG->backuptempdir
1740   * @param bool $exceptiononerror throw exception if error encountered
1741   * @return string|false Returns full path to directory if successful, false if not; may throw exception
1742   */
1743  function make_backup_temp_directory($directory, $exceptiononerror = true) {
1744      global $CFG;
1745      if ($CFG->backuptempdir !== "$CFG->tempdir/backup") {
1746          check_dir_exists($CFG->backuptempdir, true, true);
1747          protect_directory($CFG->backuptempdir);
1748      } else {
1749          protect_directory($CFG->tempdir);
1750      }
1751      return make_writable_directory("$CFG->backuptempdir/$directory", $exceptiononerror);
1752  }
1753  
1754  /**
1755   * Create a directory under tempdir and make sure it is writable.
1756   *
1757   * Where possible, please use make_request_directory() and limit the scope
1758   * of your data to the current HTTP request.
1759   *
1760   * Do not use for storing cache files - see make_cache_directory(), and
1761   * make_localcache_directory() instead for this purpose.
1762   *
1763   * Temporary files must be on a shared storage, and heavy usage is
1764   * discouraged due to the performance impact upon clustered environments.
1765   *
1766   * @param string $directory  the full path of the directory to be created under $CFG->tempdir
1767   * @param bool $exceptiononerror throw exception if error encountered
1768   * @return string|false Returns full path to directory if successful, false if not; may throw exception
1769   */
1770  function make_temp_directory($directory, $exceptiononerror = true) {
1771      global $CFG;
1772      if ($CFG->tempdir !== "$CFG->dataroot/temp") {
1773          check_dir_exists($CFG->tempdir, true, true);
1774          protect_directory($CFG->tempdir);
1775      } else {
1776          protect_directory($CFG->dataroot);
1777      }
1778      return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1779  }
1780  
1781  /**
1782   * Create a directory under cachedir and make sure it is writable.
1783   *
1784   * Note: this cache directory is shared by all cluster nodes.
1785   *
1786   * @param string $directory  the full path of the directory to be created under $CFG->cachedir
1787   * @param bool $exceptiononerror throw exception if error encountered
1788   * @return string|false Returns full path to directory if successful, false if not; may throw exception
1789   */
1790  function make_cache_directory($directory, $exceptiononerror = true) {
1791      global $CFG;
1792      if ($CFG->cachedir !== "$CFG->dataroot/cache") {
1793          check_dir_exists($CFG->cachedir, true, true);
1794          protect_directory($CFG->cachedir);
1795      } else {
1796          protect_directory($CFG->dataroot);
1797      }
1798      return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1799  }
1800  
1801  /**
1802   * Create a directory under localcachedir and make sure it is writable.
1803   * The files in this directory MUST NOT change, use revisions or content hashes to
1804   * work around this limitation - this means you can only add new files here.
1805   *
1806   * The content of this directory gets purged automatically on all cluster nodes
1807   * after calling purge_all_caches() before new data is written to this directory.
1808   *
1809   * Note: this local cache directory does not need to be shared by cluster nodes.
1810   *
1811   * @param string $directory the relative path of the directory to be created under $CFG->localcachedir
1812   * @param bool $exceptiononerror throw exception if error encountered
1813   * @return string|false Returns full path to directory if successful, false if not; may throw exception
1814   */
1815  function make_localcache_directory($directory, $exceptiononerror = true) {
1816      global $CFG;
1817  
1818      make_writable_directory($CFG->localcachedir, $exceptiononerror);
1819  
1820      if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1821          protect_directory($CFG->localcachedir);
1822      } else {
1823          protect_directory($CFG->dataroot);
1824      }
1825  
1826      if (!isset($CFG->localcachedirpurged)) {
1827          $CFG->localcachedirpurged = 0;
1828      }
1829      $timestampfile = "$CFG->localcachedir/.lastpurged";
1830  
1831      if (!file_exists($timestampfile)) {
1832          touch($timestampfile);
1833          @chmod($timestampfile, $CFG->filepermissions);
1834  
1835      } else if (filemtime($timestampfile) <  $CFG->localcachedirpurged) {
1836          // This means our local cached dir was not purged yet.
1837          remove_dir($CFG->localcachedir, true);
1838          if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1839              protect_directory($CFG->localcachedir);
1840          }
1841          touch($timestampfile);
1842          @chmod($timestampfile, $CFG->filepermissions);
1843          clearstatcache();
1844      }
1845  
1846      if ($directory === '') {
1847          return $CFG->localcachedir;
1848      }
1849  
1850      return make_writable_directory("$CFG->localcachedir/$directory", $exceptiononerror);
1851  }
1852  
1853  /**
1854   * Webserver access user logging
1855   */
1856  function set_access_log_user() {
1857      global $USER, $CFG;
1858      if ($USER && isset($USER->username)) {
1859          $logmethod = '';
1860          $logvalue = 0;
1861          if (!empty($CFG->apacheloguser) && function_exists('apache_note')) {
1862              $logmethod = 'apache';
1863              $logvalue = $CFG->apacheloguser;
1864          }
1865          if (!empty($CFG->headerloguser)) {
1866              $logmethod = 'header';
1867              $logvalue = $CFG->headerloguser;
1868          }
1869          if (!empty($logmethod)) {
1870              $loguserid = $USER->id;
1871              $logusername = clean_filename($USER->username);
1872              $logname = '';
1873              if (isset($USER->firstname)) {
1874                  // We can assume both will be set
1875                  // - even if to empty.
1876                  $logname = clean_filename($USER->firstname . " " . $USER->lastname);
1877              }
1878              if (\core\session\manager::is_loggedinas()) {
1879                  $realuser = \core\session\manager::get_realuser();
1880                  $logusername = clean_filename($realuser->username." as ".$logusername);
1881                  $logname = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$logname);
1882                  $loguserid = clean_filename($realuser->id." as ".$loguserid);
1883              }
1884              switch ($logvalue) {
1885                  case 3:
1886                      $logname = $logusername;
1887                      break;
1888                  case 2:
1889                      $logname = $logname;
1890                      break;
1891                  case 1:
1892                  default:
1893                      $logname = $loguserid;
1894                      break;
1895              }
1896              if ($logmethod == 'apache') {
1897                  apache_note('MOODLEUSER', $logname);
1898              }
1899  
1900              if ($logmethod == 'header' && !headers_sent()) {
1901                  header("X-MOODLEUSER: $logname");
1902              }
1903          }
1904      }
1905  }
1906  
1907  /**
1908   * This class solves the problem of how to initialise $OUTPUT.
1909   *
1910   * The problem is caused be two factors
1911   * <ol>
1912   * <li>On the one hand, we cannot be sure when output will start. In particular,
1913   * an error, which needs to be displayed, could be thrown at any time.</li>
1914   * <li>On the other hand, we cannot be sure when we will have all the information
1915   * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1916   * (potentially) depends on the current course, course categories, and logged in user.
1917   * It also depends on whether the current page requires HTTPS.</li>
1918   * </ol>
1919   *
1920   * So, it is hard to find a single natural place during Moodle script execution,
1921   * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1922   * adopt the following strategy
1923   * <ol>
1924   * <li>We will initialise $OUTPUT the first time it is used.</li>
1925   * <li>If, after $OUTPUT has been initialised, the script tries to change something
1926   * that $OUTPUT depends on, we throw an exception making it clear that the script
1927   * did something wrong.
1928   * </ol>
1929   *
1930   * The only problem with that is, how do we initialise $OUTPUT on first use if,
1931   * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1932   * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1933   * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1934   *
1935   * Note that this class is used before lib/outputlib.php has been loaded, so we
1936   * must be careful referring to classes/functions from there, they may not be
1937   * defined yet, and we must avoid fatal errors.
1938   *
1939   * @copyright 2009 Tim Hunt
1940   * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1941   * @since     Moodle 2.0
1942   */
1943  class bootstrap_renderer {
1944      /**
1945       * Handles re-entrancy. Without this, errors or debugging output that occur
1946       * during the initialisation of $OUTPUT, cause infinite recursion.
1947       * @var boolean
1948       */
1949      protected $initialising = false;
1950  
1951      /**
1952       * Have we started output yet?
1953       * @return boolean true if the header has been printed.
1954       */
1955      public function has_started() {
1956          return false;
1957      }
1958  
1959      /**
1960       * Constructor - to be used by core code only.
1961       * @param string $method The method to call
1962       * @param array $arguments Arguments to pass to the method being called
1963       * @return string
1964       */
1965      public function __call($method, $arguments) {
1966          global $OUTPUT, $PAGE;
1967  
1968          $recursing = false;
1969          if ($method == 'notification') {
1970              // Catch infinite recursion caused by debugging output during print_header.
1971              $backtrace = debug_backtrace();
1972              array_shift($backtrace);
1973              array_shift($backtrace);
1974              $recursing = is_early_init($backtrace);
1975          }
1976  
1977          $earlymethods = array(
1978              'fatal_error' => 'early_error',
1979              'notification' => 'early_notification',
1980          );
1981  
1982          // If lib/outputlib.php has been loaded, call it.
1983          if (!empty($PAGE) && !$recursing) {
1984              if (array_key_exists($method, $earlymethods)) {
1985                  //prevent PAGE->context warnings - exceptions might appear before we set any context
1986                  $PAGE->set_context(null);
1987              }
1988              $PAGE->initialise_theme_and_output();
1989              return call_user_func_array(array($OUTPUT, $method), $arguments);
1990          }
1991  
1992          $this->initialising = true;
1993  
1994          // Too soon to initialise $OUTPUT, provide a couple of key methods.
1995          if (array_key_exists($method, $earlymethods)) {
1996              return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1997          }
1998  
1999          throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
2000      }
2001  
2002      /**
2003       * Returns nicely formatted error message in a div box.
2004       * @static
2005       * @param string $message error message
2006       * @param string $moreinfourl (ignored in early errors)
2007       * @param string $link (ignored in early errors)
2008       * @param array $backtrace
2009       * @param string $debuginfo
2010       * @return string
2011       */
2012      public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
2013          global $CFG;
2014  
2015          $content = "<div class='alert-danger'>$message</div>";
2016          // Check whether debug is set.
2017          $debug = (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER);
2018          // Also check we have it set in the config file. This occurs if the method to read the config table from the
2019          // database fails, reading from the config table is the first database interaction we have.
2020          $debug = $debug || (!empty($CFG->config_php_settings['debug'])  && $CFG->config_php_settings['debug'] >= DEBUG_DEVELOPER );
2021          if ($debug) {
2022              if (!empty($debuginfo)) {
2023                  // Remove all nasty JS.
2024                  if (function_exists('s')) { // Function may be not available for some early errors.
2025                      $debuginfo = s($debuginfo);
2026                  } else {
2027                      // Because weblib is not available for these early errors, we
2028                      // just duplicate s() code here to be safe.
2029                      $debuginfo = preg_replace('/&amp;#(\d+|x[0-9a-f]+);/i', '&#$1;',
2030                      htmlspecialchars($debuginfo, ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE));
2031                  }
2032                  $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
2033                  $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
2034              }
2035              if (!empty($backtrace)) {
2036                  $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
2037              }
2038          }
2039  
2040          return $content;
2041      }
2042  
2043      /**
2044       * This function should only be called by this class, or from exception handlers
2045       * @static
2046       * @param string $message error message
2047       * @param string $moreinfourl (ignored in early errors)
2048       * @param string $link (ignored in early errors)
2049       * @param array $backtrace
2050       * @param string $debuginfo extra information for developers
2051       * @return string
2052       */
2053      public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = null) {
2054          global $CFG;
2055  
2056          if (CLI_SCRIPT) {
2057              echo "!!! $message !!!\n";
2058              if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
2059                  if (!empty($debuginfo)) {
2060                      echo "\nDebug info: $debuginfo";
2061                  }
2062                  if (!empty($backtrace)) {
2063                      echo "\nStack trace: " . format_backtrace($backtrace, true);
2064                  }
2065              }
2066              return;
2067  
2068          } else if (AJAX_SCRIPT) {
2069              $e = new stdClass();
2070              $e->error      = $message;
2071              $e->stacktrace = NULL;
2072              $e->debuginfo  = NULL;
2073              if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
2074                  if (!empty($debuginfo)) {
2075                      $e->debuginfo = $debuginfo;
2076                  }
2077                  if (!empty($backtrace)) {
2078                      $e->stacktrace = format_backtrace($backtrace, true);
2079                  }
2080              }
2081              $e->errorcode  = $errorcode;
2082              @header('Content-Type: application/json; charset=utf-8');
2083              echo json_encode($e);
2084              return;
2085          }
2086  
2087          // In the name of protocol correctness, monitoring and performance
2088          // profiling, set the appropriate error headers for machine consumption.
2089          $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2090          @header($protocol . ' 500 Internal Server Error');
2091  
2092          // better disable any caching
2093          @header('Content-Type: text/html; charset=utf-8');
2094          @header('X-UA-Compatible: IE=edge');
2095          @header('Cache-Control: no-store, no-cache, must-revalidate');
2096          @header('Cache-Control: post-check=0, pre-check=0', false);
2097          @header('Pragma: no-cache');
2098          @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2099          @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2100  
2101          if (function_exists('get_string')) {
2102              $strerror = get_string('error');
2103          } else {
2104              $strerror = 'Error';
2105          }
2106  
2107          $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
2108  
2109          return self::plain_page($strerror, $content);
2110      }
2111  
2112      /**
2113       * Early notification message
2114       * @static
2115       * @param string $message
2116       * @param string $classes usually notifyproblem or notifysuccess
2117       * @return string
2118       */
2119      public static function early_notification($message, $classes = 'notifyproblem') {
2120          return '<div class="' . $classes . '">' . $message . '</div>';
2121      }
2122  
2123      /**
2124       * Page should redirect message.
2125       * @static
2126       * @param string $encodedurl redirect url
2127       * @return string
2128       */
2129      public static function plain_redirect_message($encodedurl) {
2130          $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
2131                  $encodedurl .'">'. get_string('continue') .'</a></div>';
2132          return self::plain_page(get_string('redirect'), $message);
2133      }
2134  
2135      /**
2136       * Early redirection page, used before full init of $PAGE global
2137       * @static
2138       * @param string $encodedurl redirect url
2139       * @param string $message redirect message
2140       * @param int $delay time in seconds
2141       * @return string redirect page
2142       */
2143      public static function early_redirect_message($encodedurl, $message, $delay) {
2144          $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
2145          $content = self::early_error_content($message, null, null, null);
2146          $content .= self::plain_redirect_message($encodedurl);
2147  
2148          return self::plain_page(get_string('redirect'), $content, $meta);
2149      }
2150  
2151      /**
2152       * Output basic html page.
2153       * @static
2154       * @param string $title page title
2155       * @param string $content page content
2156       * @param string $meta meta tag
2157       * @return string html page
2158       */
2159      public static function plain_page($title, $content, $meta = '') {
2160          global $CFG;
2161  
2162          if (function_exists('get_string') && function_exists('get_html_lang')) {
2163              $htmllang = get_html_lang();
2164          } else {
2165              $htmllang = '';
2166          }
2167  
2168          $footer = '';
2169          if (function_exists('get_performance_info')) { // Function may be not available for some early errors.
2170              if (MDL_PERF_TEST) {
2171                  $perfinfo = get_performance_info();
2172                  $footer = '<footer>' . $perfinfo['html'] . '</footer>';
2173              }
2174          }
2175  
2176          ob_start();
2177          include($CFG->dirroot . '/error/plainpage.php');
2178          $html = ob_get_contents();
2179          ob_end_clean();
2180  
2181          return $html;
2182      }
2183  }