Merge branch 'MDL-70789-311' of git://github.com/paulholden/moodle into MOODLE_311_STABLE
[moodle.git] / lib / setuplib.php
blob9dd220ffa517f9f59f52498f58e6e8eb6a4342ad
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.
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/>.
17 /**
18 * These functions are required very early in the Moodle
19 * setup process, before any of the main libraries are
20 * loaded.
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
28 defined('MOODLE_INTERNAL') || die();
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);
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.
50 define('MEMORY_EXTRA', -3);
51 /** Extremely large memory limit - not recommended for standard scripts */
52 define('MEMORY_HUGE', -4);
54 /**
55 * Base Moodle Exception class
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).
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
65 class moodle_exception extends Exception {
67 /**
68 * @var string The name of the string from error.php to print
70 public $errorcode;
72 /**
73 * @var string The name of module
75 public $module;
77 /**
78 * @var mixed Extra words and phrases that might be required in the error string
80 public $a;
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.
85 public $link;
87 /**
88 * @var string Optional information to aid the debugging process
90 public $debuginfo;
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
100 function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
101 global $CFG;
103 if (empty($module) || $module == 'moodle' || $module == 'core') {
104 $module = 'error';
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;
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;
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
129 if ($debuginfo) {
130 if ($isinphpunittest || $hasdebugdeveloper) {
131 $message = "$message ($debuginfo)";
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);
142 parent::__construct($message, 0);
147 * Course/activity access exception.
149 * This exception is thrown from require_login()
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
155 class require_login_exception extends moodle_exception {
157 * Constructor
158 * @param string $debuginfo Information to aid the debugging process
160 function __construct($debuginfo) {
161 parent::__construct('requireloginerror', 'error', '', NULL, $debuginfo);
166 * Session timeout exception.
168 * This exception is thrown from require_login()
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
174 class require_login_session_timeout_exception extends require_login_exception {
176 * Constructor
178 public function __construct() {
179 moodle_exception::__construct('sessionerroruser', 'error');
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
189 class webservice_parameter_exception extends moodle_exception {
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
196 function __construct($errorcode=null, $a = '', $debuginfo = null) {
197 parent::__construct($errorcode, 'webservice', '', $a, $debuginfo);
202 * Exceptions indicating user does not have permissions to do something
203 * and the execution can not continue.
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
209 class required_capability_exception extends moodle_exception {
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
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();
226 parent::__construct($errormessage, $stringfile, $link, $capabilityname);
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.
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
239 class coding_exception extends moodle_exception {
241 * Constructor
242 * @param string $hint short description of problem
243 * @param string $debuginfo detailed information how to fix problem
245 function __construct($hint, $debuginfo=null) {
246 parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
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.
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
261 class invalid_parameter_exception extends moodle_exception {
263 * Constructor
264 * @param string $debuginfo some detailed information
266 function __construct($debuginfo=null) {
267 parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
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.
277 class invalid_response_exception extends moodle_exception {
279 * Constructor
280 * @param string $debuginfo some detailed information
282 function __construct($debuginfo=null) {
283 parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
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.
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
299 class invalid_state_exception extends moodle_exception {
301 * Constructor
302 * @param string $hint short description of problem
303 * @param string $debuginfo optional more detailed information
305 function __construct($hint, $debuginfo=null) {
306 parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
311 * An exception that indicates incorrect permissions in $CFG->dataroot
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
318 class invalid_dataroot_permissions extends moodle_exception {
320 * Constructor
321 * @param string $debuginfo optional more detailed information
323 function __construct($debuginfo = NULL) {
324 parent::__construct('invaliddatarootpermissions', 'error', '', NULL, $debuginfo);
329 * An exception that indicates that file can not be served
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
336 class file_serving_exception extends moodle_exception {
338 * Constructor
339 * @param string $debuginfo optional more detailed information
341 function __construct($debuginfo = NULL) {
342 parent::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
347 * Default exception handler.
349 * @param Exception $ex
350 * @return void -does not return. Terminates execution!
352 function default_exception_handler($ex) {
353 global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION, $PAGE;
355 // detect active db transactions, rollback and log as error
356 abort_all_db_transactions();
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());
363 $info = get_exception_info($ex);
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');
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);
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);
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;
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;
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);
413 exit(1); // General error code
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
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);
429 return false;
433 * Unconditionally abort all database transactions, this function
434 * should be called from exception handlers only.
435 * @return void
437 function abort_all_db_transactions() {
438 global $CFG, $DB, $SCRIPT;
440 // default exception handler MUST not throw any exceptions!!
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();
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.
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.
458 * @param array $backtrace the stack trace to analyse.
459 * @return boolean whether the stack trace is somewhere in output initialisation.
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'),
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;
475 if ($matches) {
476 return true;
480 return false;
484 * Abort execution by throwing of a general exception,
485 * default exception handler displays the error message in most cases.
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!
496 function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
497 throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
501 * Returns detailed information about specified exception.
502 * @param exception $ex
503 * @return object
505 function get_exception_info($ex) {
506 global $CFG, $DB, $SESSION;
508 if ($ex instanceof moodle_exception) {
509 $errorcode = $ex->errorcode;
510 $module = $ex->module;
511 $a = $ex->a;
512 $link = $ex->link;
513 $debuginfo = $ex->debuginfo;
514 } else {
515 $errorcode = 'generalexceptionmessage';
516 $module = 'error';
517 $a = $ex->getMessage();
518 $link = '';
519 $debuginfo = '';
522 // Append the error code to the debug info to make grepping and googling easier
523 $debuginfo .= PHP_EOL."Error code: $errorcode";
525 $backtrace = $ex->getTrace();
526 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
527 array_unshift($backtrace, $place);
529 // Be careful, no guarantee moodlelib.php is loaded.
530 if (empty($module) || $module == 'moodle' || $module == 'core') {
531 $module = 'error';
533 // Search for the $errorcode's associated string
534 // If not found, append the contents of $a to $debuginfo so helpful information isn't lost
535 if (function_exists('get_string_manager')) {
536 if (get_string_manager()->string_exists($errorcode, $module)) {
537 $message = get_string($errorcode, $module, $a);
538 } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
539 // Search in moodle file if error specified - needed for backwards compatibility
540 $message = get_string($errorcode, 'moodle', $a);
541 } else {
542 $message = $module . '/' . $errorcode;
543 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
545 } else {
546 $message = $module . '/' . $errorcode;
547 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
550 // Remove some absolute paths from message and debugging info.
551 $searches = array();
552 $replaces = array();
553 $cfgnames = array('backuptempdir', 'tempdir', 'cachedir', 'localcachedir', 'themedir', 'dataroot', 'dirroot');
554 foreach ($cfgnames as $cfgname) {
555 if (property_exists($CFG, $cfgname)) {
556 $searches[] = $CFG->$cfgname;
557 $replaces[] = "[$cfgname]";
560 if (!empty($searches)) {
561 $message = str_replace($searches, $replaces, $message);
562 $debuginfo = str_replace($searches, $replaces, $debuginfo);
565 // Be careful, no guarantee weblib.php is loaded.
566 if (function_exists('clean_text')) {
567 $message = clean_text($message);
568 } else {
569 $message = htmlspecialchars($message);
572 if (!empty($CFG->errordocroot)) {
573 $errordoclink = $CFG->errordocroot . '/en/';
574 } else {
575 // Only if the function is available. May be not for early errors.
576 if (function_exists('current_language')) {
577 $errordoclink = get_docs_url();
578 } else {
579 $errordoclink = 'https://docs.moodle.org/en/';
583 if ($module === 'error') {
584 $modulelink = 'moodle';
585 } else {
586 $modulelink = $module;
588 $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
590 if (empty($link)) {
591 if (!empty($SESSION->fromurl)) {
592 $link = $SESSION->fromurl;
593 unset($SESSION->fromurl);
594 } else {
595 $link = $CFG->wwwroot .'/';
599 // When printing an error the continue button should never link offsite.
600 // We cannot use clean_param() here as it is not guaranteed that it has been loaded yet.
601 if (stripos($link, $CFG->wwwroot) === 0) {
602 // Internal HTTP, all good.
603 } else {
604 // External link spotted!
605 $link = $CFG->wwwroot . '/';
608 $info = new stdClass();
609 $info->message = $message;
610 $info->errorcode = $errorcode;
611 $info->backtrace = $backtrace;
612 $info->link = $link;
613 $info->moreinfourl = $moreinfourl;
614 $info->a = $a;
615 $info->debuginfo = $debuginfo;
617 return $info;
621 * Generate a V4 UUID.
623 * Unique is hard. Very hard. Attempt to use the PECL UUID function if available, and if not then revert to
624 * constructing the uuid using mt_rand.
626 * It is important that this token is not solely based on time as this could lead
627 * to duplicates in a clustered environment (especially on VMs due to poor time precision).
629 * @see https://tools.ietf.org/html/rfc4122
631 * @deprecated since Moodle 3.8 MDL-61038 - please do not use this function any more.
632 * @see \core\uuid::generate()
634 * @return string The uuid.
636 function generate_uuid() {
637 debugging('generate_uuid() is deprecated. Please use \core\uuid::generate() instead.', DEBUG_DEVELOPER);
638 return \core\uuid::generate();
642 * Returns the Moodle Docs URL in the users language for a given 'More help' link.
644 * There are three cases:
646 * 1. In the normal case, $path will be a short relative path 'component/thing',
647 * like 'mod/folder/view' 'group/import'. This gets turned into an link to
648 * MoodleDocs in the user's language, and for the appropriate Moodle version.
649 * E.g. 'group/import' may become 'http://docs.moodle.org/2x/en/group/import'.
650 * The 'http://docs.moodle.org' bit comes from $CFG->docroot.
652 * This is the only option that should be used in standard Moodle code. The other
653 * two options have been implemented because they are useful for third-party plugins.
655 * 2. $path may be an absolute URL, starting http:// or https://. In this case,
656 * the link is used as is.
658 * 3. $path may start %%WWWROOT%%, in which case that is replaced by
659 * $CFG->wwwroot to make the link.
661 * @param string $path the place to link to. See above for details.
662 * @return string The MoodleDocs URL in the user's language. for example @link http://docs.moodle.org/2x/en/$path}
664 function get_docs_url($path = null) {
665 global $CFG;
667 // Absolute URLs are used unmodified.
668 if (substr($path, 0, 7) === 'http://' || substr($path, 0, 8) === 'https://') {
669 return $path;
672 // Paths starting %%WWWROOT%% have that replaced by $CFG->wwwroot.
673 if (substr($path, 0, 11) === '%%WWWROOT%%') {
674 return $CFG->wwwroot . substr($path, 11);
677 // Otherwise we do the normal case, and construct a MoodleDocs URL relative to $CFG->docroot.
679 // Check that $CFG->branch has been set up, during installation it won't be.
680 if (empty($CFG->branch)) {
681 // It's not there yet so look at version.php.
682 include($CFG->dirroot.'/version.php');
683 } else {
684 // We can use $CFG->branch and avoid having to include version.php.
685 $branch = $CFG->branch;
687 // ensure branch is valid.
688 if (!$branch) {
689 // We should never get here but in case we do lets set $branch to .
690 // the smart one's will know that this is the current directory
691 // and the smarter ones will know that there is some smart matching
692 // that will ensure people end up at the latest version of the docs.
693 $branch = '.';
695 if (empty($CFG->doclang)) {
696 $lang = current_language();
697 } else {
698 $lang = $CFG->doclang;
700 $end = '/' . $branch . '/' . $lang . '/' . $path;
701 if (empty($CFG->docroot)) {
702 return 'http://docs.moodle.org'. $end;
703 } else {
704 return $CFG->docroot . $end ;
709 * Formats a backtrace ready for output.
711 * This function does not include function arguments because they could contain sensitive information
712 * not suitable to be exposed in a response.
714 * @param array $callers backtrace array, as returned by debug_backtrace().
715 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
716 * @return string formatted backtrace, ready for output.
718 function format_backtrace($callers, $plaintext = false) {
719 // do not use $CFG->dirroot because it might not be available in destructors
720 $dirroot = dirname(__DIR__);
722 if (empty($callers)) {
723 return '';
726 $from = $plaintext ? '' : '<ul style="text-align: left" data-rel="backtrace">';
727 foreach ($callers as $caller) {
728 if (!isset($caller['line'])) {
729 $caller['line'] = '?'; // probably call_user_func()
731 if (!isset($caller['file'])) {
732 $caller['file'] = 'unknownfile'; // probably call_user_func()
734 $from .= $plaintext ? '* ' : '<li>';
735 $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
736 if (isset($caller['function'])) {
737 $from .= ': call to ';
738 if (isset($caller['class'])) {
739 $from .= $caller['class'] . $caller['type'];
741 $from .= $caller['function'] . '()';
742 } else if (isset($caller['exception'])) {
743 $from .= ': '.$caller['exception'].' thrown';
745 $from .= $plaintext ? "\n" : '</li>';
747 $from .= $plaintext ? '' : '</ul>';
749 return $from;
753 * This function makes the return value of ini_get consistent if you are
754 * setting server directives through the .htaccess file in apache.
756 * Current behavior for value set from php.ini On = 1, Off = [blank]
757 * Current behavior for value set from .htaccess On = On, Off = Off
758 * Contributed by jdell @ unr.edu
760 * @param string $ini_get_arg The argument to get
761 * @return bool True for on false for not
763 function ini_get_bool($ini_get_arg) {
764 $temp = ini_get($ini_get_arg);
766 if ($temp == '1' or strtolower($temp) == 'on') {
767 return true;
769 return false;
773 * This function verifies the sanity of PHP configuration
774 * and stops execution if anything critical found.
776 function setup_validate_php_configuration() {
777 // this must be very fast - no slow checks here!!!
779 if (ini_get_bool('session.auto_start')) {
780 print_error('sessionautostartwarning', 'admin');
785 * Initialise global $CFG variable.
786 * @private to be used only from lib/setup.php
788 function initialise_cfg() {
789 global $CFG, $DB;
791 if (!$DB) {
792 // This should not happen.
793 return;
796 try {
797 $localcfg = get_config('core');
798 } catch (dml_exception $e) {
799 // Most probably empty db, going to install soon.
800 return;
803 foreach ($localcfg as $name => $value) {
804 // Note that get_config() keeps forced settings
805 // and normalises values to string if possible.
806 $CFG->{$name} = $value;
811 * Initialises $FULLME and friends. Private function. Should only be called from
812 * setup.php.
814 function initialise_fullme() {
815 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
817 // Detect common config error.
818 if (substr($CFG->wwwroot, -1) == '/') {
819 print_error('wwwrootslash', 'error');
822 if (CLI_SCRIPT) {
823 initialise_fullme_cli();
824 return;
826 if (!empty($CFG->overridetossl)) {
827 if (strpos($CFG->wwwroot, 'http://') === 0) {
828 $CFG->wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
829 } else {
830 unset_config('overridetossl');
834 $rurl = setup_get_remote_url();
835 $wwwroot = parse_url($CFG->wwwroot.'/');
837 if (empty($rurl['host'])) {
838 // missing host in request header, probably not a real browser, let's ignore them
840 } else if (!empty($CFG->reverseproxy)) {
841 // $CFG->reverseproxy specifies if reverse proxy server used
842 // Used in load balancing scenarios.
843 // Do not abuse this to try to solve lan/wan access problems!!!!!
845 } else {
846 if (($rurl['host'] !== $wwwroot['host']) or
847 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port']) or
848 (strpos($rurl['path'], $wwwroot['path']) !== 0)) {
850 // Explain the problem and redirect them to the right URL
851 if (!defined('NO_MOODLE_COOKIES')) {
852 define('NO_MOODLE_COOKIES', true);
854 // The login/token.php script should call the correct url/port.
855 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
856 $wwwrootport = empty($wwwroot['port'])?'':$wwwroot['port'];
857 $calledurl = $rurl['host'];
858 if (!empty($rurl['port'])) {
859 $calledurl .= ':'. $rurl['port'];
861 $correcturl = $wwwroot['host'];
862 if (!empty($wwwrootport)) {
863 $correcturl .= ':'. $wwwrootport;
865 throw new moodle_exception('requirecorrectaccess', 'error', '', null,
866 'You called ' . $calledurl .', you should have called ' . $correcturl);
868 redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
872 // Check that URL is under $CFG->wwwroot.
873 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
874 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
875 } else {
876 // Probably some weird external script
877 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
878 return;
881 // $CFG->sslproxy specifies if external SSL appliance is used
882 // (That is, the Moodle server uses http, with an external box translating everything to https).
883 if (empty($CFG->sslproxy)) {
884 if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
885 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
886 print_error('sslonlyaccess', 'error');
887 } else {
888 redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
891 } else {
892 if ($wwwroot['scheme'] !== 'https') {
893 throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
895 $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
896 $_SERVER['HTTPS'] = 'on'; // Override $_SERVER to help external libraries with their HTTPS detection.
897 $_SERVER['SERVER_PORT'] = 443; // Assume default ssl port for the proxy.
900 // hopefully this will stop all those "clever" admins trying to set up moodle
901 // with two different addresses in intranet and Internet
902 if (!empty($CFG->reverseproxy) && $rurl['host'] === $wwwroot['host']) {
903 print_error('reverseproxyabused', 'error');
906 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
907 if (!empty($wwwroot['port'])) {
908 $hostandport .= ':'.$wwwroot['port'];
911 $FULLSCRIPT = $hostandport . $rurl['path'];
912 $FULLME = $hostandport . $rurl['fullpath'];
913 $ME = $rurl['fullpath'];
917 * Initialises $FULLME and friends for command line scripts.
918 * This is a private method for use by initialise_fullme.
920 function initialise_fullme_cli() {
921 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
923 // Urls do not make much sense in CLI scripts
924 $backtrace = debug_backtrace();
925 $topfile = array_pop($backtrace);
926 $topfile = realpath($topfile['file']);
927 $dirroot = realpath($CFG->dirroot);
929 if (strpos($topfile, $dirroot) !== 0) {
930 // Probably some weird external script
931 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
932 } else {
933 $relativefile = substr($topfile, strlen($dirroot));
934 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
935 $SCRIPT = $FULLSCRIPT = $relativefile;
936 $FULLME = $ME = null;
941 * Get the URL that PHP/the web server thinks it is serving. Private function
942 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
943 * @return array in the same format that parse_url returns, with the addition of
944 * a 'fullpath' element, which includes any slasharguments path.
946 function setup_get_remote_url() {
947 $rurl = array();
948 if (isset($_SERVER['HTTP_HOST'])) {
949 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
950 } else {
951 $rurl['host'] = null;
953 $rurl['port'] = $_SERVER['SERVER_PORT'];
954 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
955 $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ? 'http' : 'https';
957 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
958 //Apache server
959 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
961 // Fixing a known issue with:
962 // - Apache versions lesser than 2.4.11
963 // - PHP deployed in Apache as PHP-FPM via mod_proxy_fcgi
964 // - PHP versions lesser than 5.6.3 and 5.5.18.
965 if (isset($_SERVER['PATH_INFO']) && (php_sapi_name() === 'fpm-fcgi') && isset($_SERVER['SCRIPT_NAME'])) {
966 $pathinfodec = rawurldecode($_SERVER['PATH_INFO']);
967 $lenneedle = strlen($pathinfodec);
968 // Checks whether SCRIPT_NAME ends with PATH_INFO, URL-decoded.
969 if (substr($_SERVER['SCRIPT_NAME'], -$lenneedle) === $pathinfodec) {
970 // This is the "Apache 2.4.10- running PHP-FPM via mod_proxy_fcgi" fingerprint,
971 // 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)
972 // => SCRIPT_NAME contains 'slash arguments' data too, which is wrongly exposed via PATH_INFO as URL-encoded.
973 // Fix both $_SERVER['PATH_INFO'] and $_SERVER['SCRIPT_NAME'].
974 $lenhaystack = strlen($_SERVER['SCRIPT_NAME']);
975 $pos = $lenhaystack - $lenneedle;
976 // Here $pos is greater than 0 but let's double check it.
977 if ($pos > 0) {
978 $_SERVER['PATH_INFO'] = $pathinfodec;
979 $_SERVER['SCRIPT_NAME'] = substr($_SERVER['SCRIPT_NAME'], 0, $pos);
984 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
985 //IIS - needs a lot of tweaking to make it work
986 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
988 // NOTE: we should ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS.
989 // Since 2.0, we rely on IIS rewrite extensions like Helicon ISAPI_rewrite
990 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
991 // OR
992 // we rely on a proper IIS 6.0+ configuration: the 'FastCGIUtf8ServerVariables' registry key.
993 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
994 // Check that PATH_INFO works == must not contain the script name.
995 if (strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === false) {
996 $rurl['fullpath'] .= clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
1000 if (isset($_SERVER['QUERY_STRING']) and $_SERVER['QUERY_STRING'] !== '') {
1001 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
1003 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
1005 /* NOTE: following servers are not fully tested! */
1007 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
1008 //lighttpd - not officially supported
1009 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1011 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
1012 //nginx - not officially supported
1013 if (!isset($_SERVER['SCRIPT_NAME'])) {
1014 die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
1016 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1018 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
1019 //cherokee - not officially supported
1020 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1022 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
1023 //zeus - not officially supported
1024 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1026 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
1027 //LiteSpeed - not officially supported
1028 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1030 } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
1031 //obscure name found on some servers - this is definitely not supported
1032 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1034 } else if (strpos($_SERVER['SERVER_SOFTWARE'], 'PHP') === 0) {
1035 // built-in PHP Development Server
1036 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
1038 } else {
1039 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
1042 // sanitize the url a bit more, the encoding style may be different in vars above
1043 $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
1044 $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);
1046 return $rurl;
1050 * Try to work around the 'max_input_vars' restriction if necessary.
1052 function workaround_max_input_vars() {
1053 // Make sure this gets executed only once from lib/setup.php!
1054 static $executed = false;
1055 if ($executed) {
1056 debugging('workaround_max_input_vars() must be called only once!');
1057 return;
1059 $executed = true;
1061 if (!isset($_SERVER["CONTENT_TYPE"]) or strpos($_SERVER["CONTENT_TYPE"], 'multipart/form-data') !== false) {
1062 // Not a post or 'multipart/form-data' which is not compatible with "php://input" reading.
1063 return;
1066 if (!isloggedin() or isguestuser()) {
1067 // Only real users post huge forms.
1068 return;
1071 $max = (int)ini_get('max_input_vars');
1073 if ($max <= 0) {
1074 // Most probably PHP < 5.3.9 that does not implement this limit.
1075 return;
1078 if ($max >= 200000) {
1079 // This value should be ok for all our forms, by setting it in php.ini
1080 // admins may prevent any unexpected regressions caused by this hack.
1082 // Note there is no need to worry about DDoS caused by making this limit very high
1083 // because there are very many easier ways to DDoS any Moodle server.
1084 return;
1087 // Worst case is advanced checkboxes which use up to two max_input_vars
1088 // slots for each entry in $_POST, because of sending two fields with the
1089 // same name. So count everything twice just in case.
1090 if (count($_POST, COUNT_RECURSIVE) * 2 < $max) {
1091 return;
1094 // Large POST request with enctype supported by php://input.
1095 // Parse php://input in chunks to bypass max_input_vars limit, which also applies to parse_str().
1096 $str = file_get_contents("php://input");
1097 if ($str === false or $str === '') {
1098 // Some weird error.
1099 return;
1102 $delim = '&';
1103 $fun = function($p) use ($delim) {
1104 return implode($delim, $p);
1106 $chunks = array_map($fun, array_chunk(explode($delim, $str), $max));
1108 // Clear everything from existing $_POST array, otherwise it might be included
1109 // twice (this affects array params primarily).
1110 foreach ($_POST as $key => $value) {
1111 unset($_POST[$key]);
1112 // Also clear from request array - but only the things that are in $_POST,
1113 // that way it will leave the things from a get request if any.
1114 unset($_REQUEST[$key]);
1117 foreach ($chunks as $chunk) {
1118 $values = array();
1119 parse_str($chunk, $values);
1121 merge_query_params($_POST, $values);
1122 merge_query_params($_REQUEST, $values);
1127 * Merge parsed POST chunks.
1129 * NOTE: this is not perfect, but it should work in most cases hopefully.
1131 * @param array $target
1132 * @param array $values
1134 function merge_query_params(array &$target, array $values) {
1135 if (isset($values[0]) and isset($target[0])) {
1136 // This looks like a split [] array, lets verify the keys are continuous starting with 0.
1137 $keys1 = array_keys($values);
1138 $keys2 = array_keys($target);
1139 if ($keys1 === array_keys($keys1) and $keys2 === array_keys($keys2)) {
1140 foreach ($values as $v) {
1141 $target[] = $v;
1143 return;
1146 foreach ($values as $k => $v) {
1147 if (!isset($target[$k])) {
1148 $target[$k] = $v;
1149 continue;
1151 if (is_array($target[$k]) and is_array($v)) {
1152 merge_query_params($target[$k], $v);
1153 continue;
1155 // We should not get here unless there are duplicates in params.
1156 $target[$k] = $v;
1161 * Initializes our performance info early.
1163 * Pairs up with get_performance_info() which is actually
1164 * in moodlelib.php. This function is here so that we can
1165 * call it before all the libs are pulled in.
1167 * @uses $PERF
1169 function init_performance_info() {
1171 global $PERF, $CFG, $USER;
1173 $PERF = new stdClass();
1174 $PERF->logwrites = 0;
1175 if (function_exists('microtime')) {
1176 $PERF->starttime = microtime();
1178 if (function_exists('memory_get_usage')) {
1179 $PERF->startmemory = memory_get_usage();
1181 if (function_exists('posix_times')) {
1182 $PERF->startposixtimes = posix_times();
1187 * Indicates whether we are in the middle of the initial Moodle install.
1189 * Very occasionally it is necessary avoid running certain bits of code before the
1190 * Moodle installation has completed. The installed flag is set in admin/index.php
1191 * after Moodle core and all the plugins have been installed, but just before
1192 * the person doing the initial install is asked to choose the admin password.
1194 * @return boolean true if the initial install is not complete.
1196 function during_initial_install() {
1197 global $CFG;
1198 return empty($CFG->rolesactive);
1202 * Function to raise the memory limit to a new value.
1203 * Will respect the memory limit if it is higher, thus allowing
1204 * settings in php.ini, apache conf or command line switches
1205 * to override it.
1207 * The memory limit should be expressed with a constant
1208 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
1209 * It is possible to use strings or integers too (eg:'128M').
1211 * @param mixed $newlimit the new memory limit
1212 * @return bool success
1214 function raise_memory_limit($newlimit) {
1215 global $CFG;
1217 if ($newlimit == MEMORY_UNLIMITED) {
1218 ini_set('memory_limit', -1);
1219 return true;
1221 } else if ($newlimit == MEMORY_STANDARD) {
1222 if (PHP_INT_SIZE > 4) {
1223 $newlimit = get_real_size('128M'); // 64bit needs more memory
1224 } else {
1225 $newlimit = get_real_size('96M');
1228 } else if ($newlimit == MEMORY_EXTRA) {
1229 if (PHP_INT_SIZE > 4) {
1230 $newlimit = get_real_size('384M'); // 64bit needs more memory
1231 } else {
1232 $newlimit = get_real_size('256M');
1234 if (!empty($CFG->extramemorylimit)) {
1235 $extra = get_real_size($CFG->extramemorylimit);
1236 if ($extra > $newlimit) {
1237 $newlimit = $extra;
1241 } else if ($newlimit == MEMORY_HUGE) {
1242 // MEMORY_HUGE uses 2G or MEMORY_EXTRA, whichever is bigger.
1243 $newlimit = get_real_size('2G');
1244 if (!empty($CFG->extramemorylimit)) {
1245 $extra = get_real_size($CFG->extramemorylimit);
1246 if ($extra > $newlimit) {
1247 $newlimit = $extra;
1251 } else {
1252 $newlimit = get_real_size($newlimit);
1255 if ($newlimit <= 0) {
1256 debugging('Invalid memory limit specified.');
1257 return false;
1260 $cur = ini_get('memory_limit');
1261 if (empty($cur)) {
1262 // if php is compiled without --enable-memory-limits
1263 // apparently memory_limit is set to ''
1264 $cur = 0;
1265 } else {
1266 if ($cur == -1){
1267 return true; // unlimited mem!
1269 $cur = get_real_size($cur);
1272 if ($newlimit > $cur) {
1273 ini_set('memory_limit', $newlimit);
1274 return true;
1276 return false;
1280 * Function to reduce the memory limit to a new value.
1281 * Will respect the memory limit if it is lower, thus allowing
1282 * settings in php.ini, apache conf or command line switches
1283 * to override it
1285 * The memory limit should be expressed with a string (eg:'64M')
1287 * @param string $newlimit the new memory limit
1288 * @return bool
1290 function reduce_memory_limit($newlimit) {
1291 if (empty($newlimit)) {
1292 return false;
1294 $cur = ini_get('memory_limit');
1295 if (empty($cur)) {
1296 // if php is compiled without --enable-memory-limits
1297 // apparently memory_limit is set to ''
1298 $cur = 0;
1299 } else {
1300 if ($cur == -1){
1301 return true; // unlimited mem!
1303 $cur = get_real_size($cur);
1306 $new = get_real_size($newlimit);
1307 // -1 is smaller, but it means unlimited
1308 if ($new < $cur && $new != -1) {
1309 ini_set('memory_limit', $newlimit);
1310 return true;
1312 return false;
1316 * Converts numbers like 10M into bytes.
1318 * @param string $size The size to be converted
1319 * @return int
1321 function get_real_size($size = 0) {
1322 if (!$size) {
1323 return 0;
1326 static $binaryprefixes = array(
1327 'K' => 1024 ** 1,
1328 'k' => 1024 ** 1,
1329 'M' => 1024 ** 2,
1330 'm' => 1024 ** 2,
1331 'G' => 1024 ** 3,
1332 'g' => 1024 ** 3,
1333 'T' => 1024 ** 4,
1334 't' => 1024 ** 4,
1335 'P' => 1024 ** 5,
1336 'p' => 1024 ** 5,
1339 if (preg_match('/^([0-9]+)([KMGTP])/i', $size, $matches)) {
1340 return $matches[1] * $binaryprefixes[$matches[2]];
1343 return (int) $size;
1347 * Try to disable all output buffering and purge
1348 * all headers.
1350 * @access private to be called only from lib/setup.php !
1351 * @return void
1353 function disable_output_buffering() {
1354 $olddebug = error_reporting(0);
1356 // disable compression, it would prevent closing of buffers
1357 if (ini_get_bool('zlib.output_compression')) {
1358 ini_set('zlib.output_compression', 'Off');
1361 // try to flush everything all the time
1362 ob_implicit_flush(true);
1364 // close all buffers if possible and discard any existing output
1365 // this can actually work around some whitespace problems in config.php
1366 while(ob_get_level()) {
1367 if (!ob_end_clean()) {
1368 // prevent infinite loop when buffer can not be closed
1369 break;
1373 // disable any other output handlers
1374 ini_set('output_handler', '');
1376 error_reporting($olddebug);
1378 // Disable buffering in nginx.
1379 header('X-Accel-Buffering: no');
1384 * Check whether a major upgrade is needed.
1386 * That is defined as an upgrade that changes something really fundamental
1387 * in the database, so nothing can possibly work until the database has
1388 * been updated, and that is defined by the hard-coded version number in
1389 * this function.
1391 * @return bool
1393 function is_major_upgrade_required() {
1394 global $CFG;
1395 $lastmajordbchanges = 2019050100.01;
1397 $required = empty($CFG->version);
1398 $required = $required || (float)$CFG->version < $lastmajordbchanges;
1399 $required = $required || during_initial_install();
1400 $required = $required || !empty($CFG->adminsetuppending);
1402 return $required;
1406 * Redirect to the Notifications page if a major upgrade is required, and
1407 * terminate the current user session.
1409 function redirect_if_major_upgrade_required() {
1410 global $CFG;
1411 if (is_major_upgrade_required()) {
1412 try {
1413 @\core\session\manager::terminate_current();
1414 } catch (Exception $e) {
1415 // Ignore any errors, redirect to upgrade anyway.
1417 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
1418 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1419 @header('Location: ' . $url);
1420 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
1421 exit;
1426 * Makes sure that upgrade process is not running
1428 * To be inserted in the core functions that can not be called by pluigns during upgrade.
1429 * Core upgrade should not use any API functions at all.
1430 * See {@link http://docs.moodle.org/dev/Upgrade_API#Upgrade_code_restrictions}
1432 * @throws moodle_exception if executed from inside of upgrade script and $warningonly is false
1433 * @param bool $warningonly if true displays a warning instead of throwing an exception
1434 * @return bool true if executed from outside of upgrade process, false if from inside upgrade process and function is used for warning only
1436 function upgrade_ensure_not_running($warningonly = false) {
1437 global $CFG;
1438 if (!empty($CFG->upgraderunning)) {
1439 if (!$warningonly) {
1440 throw new moodle_exception('cannotexecduringupgrade');
1441 } else {
1442 debugging(get_string('cannotexecduringupgrade', 'error'), DEBUG_DEVELOPER);
1443 return false;
1446 return true;
1450 * Function to check if a directory exists and by default create it if not exists.
1452 * Previously this was accepting paths only from dataroot, but we now allow
1453 * files outside of dataroot if you supply custom paths for some settings in config.php.
1454 * This function does not verify that the directory is writable.
1456 * NOTE: this function uses current file stat cache,
1457 * please use clearstatcache() before this if you expect that the
1458 * directories may have been removed recently from a different request.
1460 * @param string $dir absolute directory path
1461 * @param boolean $create directory if does not exist
1462 * @param boolean $recursive create directory recursively
1463 * @return boolean true if directory exists or created, false otherwise
1465 function check_dir_exists($dir, $create = true, $recursive = true) {
1466 global $CFG;
1468 umask($CFG->umaskpermissions);
1470 if (is_dir($dir)) {
1471 return true;
1474 if (!$create) {
1475 return false;
1478 return mkdir($dir, $CFG->directorypermissions, $recursive);
1482 * Create a new unique directory within the specified directory.
1484 * @param string $basedir The directory to create your new unique directory within.
1485 * @param bool $exceptiononerror throw exception if error encountered
1486 * @return string The created directory
1487 * @throws invalid_dataroot_permissions
1489 function make_unique_writable_directory($basedir, $exceptiononerror = true) {
1490 if (!is_dir($basedir) || !is_writable($basedir)) {
1491 // The basedir is not writable. We will not be able to create the child directory.
1492 if ($exceptiononerror) {
1493 throw new invalid_dataroot_permissions($basedir . ' is not writable. Unable to create a unique directory within it.');
1494 } else {
1495 return false;
1499 do {
1500 // Let's use uniqid() because it's "unique enough" (microtime based). The loop does handle repetitions.
1501 // Windows and old PHP don't like very long paths, so try to keep this shorter. See MDL-69975.
1502 $uniquedir = $basedir . DIRECTORY_SEPARATOR . uniqid();
1503 } while (
1504 // Ensure that basedir is still writable - if we do not check, we could get stuck in a loop here.
1505 is_writable($basedir) &&
1507 // Make the new unique directory. If the directory already exists, it will return false.
1508 !make_writable_directory($uniquedir, $exceptiononerror) &&
1510 // Ensure that the directory now exists
1511 file_exists($uniquedir) && is_dir($uniquedir)
1514 // Check that the directory was correctly created.
1515 if (!file_exists($uniquedir) || !is_dir($uniquedir) || !is_writable($uniquedir)) {
1516 if ($exceptiononerror) {
1517 throw new invalid_dataroot_permissions('Unique directory creation failed.');
1518 } else {
1519 return false;
1523 return $uniquedir;
1527 * Create a directory and make sure it is writable.
1529 * @private
1530 * @param string $dir the full path of the directory to be created
1531 * @param bool $exceptiononerror throw exception if error encountered
1532 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1534 function make_writable_directory($dir, $exceptiononerror = true) {
1535 global $CFG;
1537 if (file_exists($dir) and !is_dir($dir)) {
1538 if ($exceptiononerror) {
1539 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1540 } else {
1541 return false;
1545 umask($CFG->umaskpermissions);
1547 if (!file_exists($dir)) {
1548 if (!@mkdir($dir, $CFG->directorypermissions, true)) {
1549 clearstatcache();
1550 // There might be a race condition when creating directory.
1551 if (!is_dir($dir)) {
1552 if ($exceptiononerror) {
1553 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1554 } else {
1555 debugging('Can not create directory: '.$dir, DEBUG_DEVELOPER);
1556 return false;
1562 if (!is_writable($dir)) {
1563 if ($exceptiononerror) {
1564 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1565 } else {
1566 return false;
1570 return $dir;
1574 * Protect a directory from web access.
1575 * Could be extended in the future to support other mechanisms (e.g. other webservers).
1577 * @private
1578 * @param string $dir the full path of the directory to be protected
1580 function protect_directory($dir) {
1581 global $CFG;
1582 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1583 if (!file_exists("$dir/.htaccess")) {
1584 if ($handle = fopen("$dir/.htaccess", 'w')) { // For safety
1585 @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");
1586 @fclose($handle);
1587 @chmod("$dir/.htaccess", $CFG->filepermissions);
1593 * Create a directory under dataroot and make sure it is writable.
1594 * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
1596 * @param string $directory the full path of the directory to be created under $CFG->dataroot
1597 * @param bool $exceptiononerror throw exception if error encountered
1598 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1600 function make_upload_directory($directory, $exceptiononerror = true) {
1601 global $CFG;
1603 if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1604 debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1606 } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
1607 debugging('Use make_cache_directory() for creation of cache directory and $CFG->cachedir to get the location.');
1609 } else if (strpos($directory, 'localcache/') === 0 or $directory === 'localcache') {
1610 debugging('Use make_localcache_directory() for creation of local cache directory and $CFG->localcachedir to get the location.');
1613 protect_directory($CFG->dataroot);
1614 return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1618 * Get a per-request storage directory in the tempdir.
1620 * The directory is automatically cleaned up during the shutdown handler.
1622 * @param bool $exceptiononerror throw exception if error encountered
1623 * @param bool $forcecreate Force creation of a new parent directory
1624 * @return string Returns full path to directory if successful, false if not; may throw exception
1626 function get_request_storage_directory($exceptiononerror = true, bool $forcecreate = false) {
1627 global $CFG;
1629 static $requestdir = null;
1631 $writabledirectoryexists = (null !== $requestdir);
1632 $writabledirectoryexists = $writabledirectoryexists && file_exists($requestdir);
1633 $writabledirectoryexists = $writabledirectoryexists && is_dir($requestdir);
1634 $writabledirectoryexists = $writabledirectoryexists && is_writable($requestdir);
1635 $createnewdirectory = $forcecreate || !$writabledirectoryexists;
1637 if ($createnewdirectory) {
1639 // Let's add the first chars of siteidentifier only. This is to help separate
1640 // paths on systems which host multiple moodles. We don't use the full id
1641 // as Windows and old PHP don't like very long paths. See MDL-69975.
1642 $basedir = $CFG->localrequestdir . '/' . substr($CFG->siteidentifier, 0, 4);
1644 make_writable_directory($basedir);
1645 protect_directory($basedir);
1647 if ($dir = make_unique_writable_directory($basedir, $exceptiononerror)) {
1648 // Register a shutdown handler to remove the directory.
1649 \core_shutdown_manager::register_function('remove_dir', [$dir]);
1652 $requestdir = $dir;
1655 return $requestdir;
1659 * Create a per-request directory and make sure it is writable.
1660 * This can only be used during the current request and will be tidied away
1661 * automatically afterwards.
1663 * A new, unique directory is always created within a shared base request directory.
1665 * In some exceptional cases an alternative base directory may be required. This can be accomplished using the
1666 * $forcecreate parameter. Typically this will only be requried where the file may be required during a shutdown handler
1667 * which may or may not be registered after a previous request directory has been created.
1669 * @param bool $exceptiononerror throw exception if error encountered
1670 * @param bool $forcecreate Force creation of a new parent directory
1671 * @return string The full path to directory if successful, false if not; may throw exception
1673 function make_request_directory($exceptiononerror = true, bool $forcecreate = false) {
1674 $basedir = get_request_storage_directory($exceptiononerror, $forcecreate);
1675 return make_unique_writable_directory($basedir, $exceptiononerror);
1679 * Get the full path of a directory under $CFG->backuptempdir.
1681 * @param string $directory the relative path of the directory under $CFG->backuptempdir
1682 * @return string|false Returns full path to directory given a valid string; otherwise, false.
1684 function get_backup_temp_directory($directory) {
1685 global $CFG;
1686 if (($directory === null) || ($directory === false)) {
1687 return false;
1689 return "$CFG->backuptempdir/$directory";
1693 * Create a directory under $CFG->backuptempdir and make sure it is writable.
1695 * Do not use for storing generic temp files - see make_temp_directory() instead for this purpose.
1697 * Backup temporary files must be on a shared storage.
1699 * @param string $directory the relative path of the directory to be created under $CFG->backuptempdir
1700 * @param bool $exceptiononerror throw exception if error encountered
1701 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1703 function make_backup_temp_directory($directory, $exceptiononerror = true) {
1704 global $CFG;
1705 if ($CFG->backuptempdir !== "$CFG->tempdir/backup") {
1706 check_dir_exists($CFG->backuptempdir, true, true);
1707 protect_directory($CFG->backuptempdir);
1708 } else {
1709 protect_directory($CFG->tempdir);
1711 return make_writable_directory("$CFG->backuptempdir/$directory", $exceptiononerror);
1715 * Create a directory under tempdir and make sure it is writable.
1717 * Where possible, please use make_request_directory() and limit the scope
1718 * of your data to the current HTTP request.
1720 * Do not use for storing cache files - see make_cache_directory(), and
1721 * make_localcache_directory() instead for this purpose.
1723 * Temporary files must be on a shared storage, and heavy usage is
1724 * discouraged due to the performance impact upon clustered environments.
1726 * @param string $directory the full path of the directory to be created under $CFG->tempdir
1727 * @param bool $exceptiononerror throw exception if error encountered
1728 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1730 function make_temp_directory($directory, $exceptiononerror = true) {
1731 global $CFG;
1732 if ($CFG->tempdir !== "$CFG->dataroot/temp") {
1733 check_dir_exists($CFG->tempdir, true, true);
1734 protect_directory($CFG->tempdir);
1735 } else {
1736 protect_directory($CFG->dataroot);
1738 return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1742 * Create a directory under cachedir and make sure it is writable.
1744 * Note: this cache directory is shared by all cluster nodes.
1746 * @param string $directory the full path of the directory to be created under $CFG->cachedir
1747 * @param bool $exceptiononerror throw exception if error encountered
1748 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1750 function make_cache_directory($directory, $exceptiononerror = true) {
1751 global $CFG;
1752 if ($CFG->cachedir !== "$CFG->dataroot/cache") {
1753 check_dir_exists($CFG->cachedir, true, true);
1754 protect_directory($CFG->cachedir);
1755 } else {
1756 protect_directory($CFG->dataroot);
1758 return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1762 * Create a directory under localcachedir and make sure it is writable.
1763 * The files in this directory MUST NOT change, use revisions or content hashes to
1764 * work around this limitation - this means you can only add new files here.
1766 * The content of this directory gets purged automatically on all cluster nodes
1767 * after calling purge_all_caches() before new data is written to this directory.
1769 * Note: this local cache directory does not need to be shared by cluster nodes.
1771 * @param string $directory the relative path of the directory to be created under $CFG->localcachedir
1772 * @param bool $exceptiononerror throw exception if error encountered
1773 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1775 function make_localcache_directory($directory, $exceptiononerror = true) {
1776 global $CFG;
1778 make_writable_directory($CFG->localcachedir, $exceptiononerror);
1780 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1781 protect_directory($CFG->localcachedir);
1782 } else {
1783 protect_directory($CFG->dataroot);
1786 if (!isset($CFG->localcachedirpurged)) {
1787 $CFG->localcachedirpurged = 0;
1789 $timestampfile = "$CFG->localcachedir/.lastpurged";
1791 if (!file_exists($timestampfile)) {
1792 touch($timestampfile);
1793 @chmod($timestampfile, $CFG->filepermissions);
1795 } else if (filemtime($timestampfile) < $CFG->localcachedirpurged) {
1796 // This means our local cached dir was not purged yet.
1797 remove_dir($CFG->localcachedir, true);
1798 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1799 protect_directory($CFG->localcachedir);
1801 touch($timestampfile);
1802 @chmod($timestampfile, $CFG->filepermissions);
1803 clearstatcache();
1806 if ($directory === '') {
1807 return $CFG->localcachedir;
1810 return make_writable_directory("$CFG->localcachedir/$directory", $exceptiononerror);
1814 * Webserver access user logging
1816 function set_access_log_user() {
1817 global $USER, $CFG;
1818 if ($USER && isset($USER->username)) {
1819 $logmethod = '';
1820 $logvalue = 0;
1821 if (!empty($CFG->apacheloguser) && function_exists('apache_note')) {
1822 $logmethod = 'apache';
1823 $logvalue = $CFG->apacheloguser;
1825 if (!empty($CFG->headerloguser)) {
1826 $logmethod = 'header';
1827 $logvalue = $CFG->headerloguser;
1829 if (!empty($logmethod)) {
1830 $loguserid = $USER->id;
1831 $logusername = clean_filename($USER->username);
1832 $logname = '';
1833 if (isset($USER->firstname)) {
1834 // We can assume both will be set
1835 // - even if to empty.
1836 $logname = clean_filename($USER->firstname . " " . $USER->lastname);
1838 if (\core\session\manager::is_loggedinas()) {
1839 $realuser = \core\session\manager::get_realuser();
1840 $logusername = clean_filename($realuser->username." as ".$logusername);
1841 $logname = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$logname);
1842 $loguserid = clean_filename($realuser->id." as ".$loguserid);
1844 switch ($logvalue) {
1845 case 3:
1846 $logname = $logusername;
1847 break;
1848 case 2:
1849 $logname = $logname;
1850 break;
1851 case 1:
1852 default:
1853 $logname = $loguserid;
1854 break;
1856 if ($logmethod == 'apache') {
1857 apache_note('MOODLEUSER', $logname);
1860 if ($logmethod == 'header') {
1861 header("X-MOODLEUSER: $logname");
1868 * This class solves the problem of how to initialise $OUTPUT.
1870 * The problem is caused be two factors
1871 * <ol>
1872 * <li>On the one hand, we cannot be sure when output will start. In particular,
1873 * an error, which needs to be displayed, could be thrown at any time.</li>
1874 * <li>On the other hand, we cannot be sure when we will have all the information
1875 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1876 * (potentially) depends on the current course, course categories, and logged in user.
1877 * It also depends on whether the current page requires HTTPS.</li>
1878 * </ol>
1880 * So, it is hard to find a single natural place during Moodle script execution,
1881 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1882 * adopt the following strategy
1883 * <ol>
1884 * <li>We will initialise $OUTPUT the first time it is used.</li>
1885 * <li>If, after $OUTPUT has been initialised, the script tries to change something
1886 * that $OUTPUT depends on, we throw an exception making it clear that the script
1887 * did something wrong.
1888 * </ol>
1890 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1891 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1892 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1893 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1895 * Note that this class is used before lib/outputlib.php has been loaded, so we
1896 * must be careful referring to classes/functions from there, they may not be
1897 * defined yet, and we must avoid fatal errors.
1899 * @copyright 2009 Tim Hunt
1900 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1901 * @since Moodle 2.0
1903 class bootstrap_renderer {
1905 * Handles re-entrancy. Without this, errors or debugging output that occur
1906 * during the initialisation of $OUTPUT, cause infinite recursion.
1907 * @var boolean
1909 protected $initialising = false;
1912 * Have we started output yet?
1913 * @return boolean true if the header has been printed.
1915 public function has_started() {
1916 return false;
1920 * Constructor - to be used by core code only.
1921 * @param string $method The method to call
1922 * @param array $arguments Arguments to pass to the method being called
1923 * @return string
1925 public function __call($method, $arguments) {
1926 global $OUTPUT, $PAGE;
1928 $recursing = false;
1929 if ($method == 'notification') {
1930 // Catch infinite recursion caused by debugging output during print_header.
1931 $backtrace = debug_backtrace();
1932 array_shift($backtrace);
1933 array_shift($backtrace);
1934 $recursing = is_early_init($backtrace);
1937 $earlymethods = array(
1938 'fatal_error' => 'early_error',
1939 'notification' => 'early_notification',
1942 // If lib/outputlib.php has been loaded, call it.
1943 if (!empty($PAGE) && !$recursing) {
1944 if (array_key_exists($method, $earlymethods)) {
1945 //prevent PAGE->context warnings - exceptions might appear before we set any context
1946 $PAGE->set_context(null);
1948 $PAGE->initialise_theme_and_output();
1949 return call_user_func_array(array($OUTPUT, $method), $arguments);
1952 $this->initialising = true;
1954 // Too soon to initialise $OUTPUT, provide a couple of key methods.
1955 if (array_key_exists($method, $earlymethods)) {
1956 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1959 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1963 * Returns nicely formatted error message in a div box.
1964 * @static
1965 * @param string $message error message
1966 * @param string $moreinfourl (ignored in early errors)
1967 * @param string $link (ignored in early errors)
1968 * @param array $backtrace
1969 * @param string $debuginfo
1970 * @return string
1972 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1973 global $CFG;
1975 $content = "<div class='alert-danger'>$message</div>";
1976 // Check whether debug is set.
1977 $debug = (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER);
1978 // Also check we have it set in the config file. This occurs if the method to read the config table from the
1979 // database fails, reading from the config table is the first database interaction we have.
1980 $debug = $debug || (!empty($CFG->config_php_settings['debug']) && $CFG->config_php_settings['debug'] >= DEBUG_DEVELOPER );
1981 if ($debug) {
1982 if (!empty($debuginfo)) {
1983 // Remove all nasty JS.
1984 if (function_exists('s')) { // Function may be not available for some early errors.
1985 $debuginfo = s($debuginfo);
1986 } else {
1987 // Because weblib is not available for these early errors, we
1988 // just duplicate s() code here to be safe.
1989 $debuginfo = preg_replace('/&amp;#(\d+|x[0-9a-f]+);/i', '&#$1;',
1990 htmlspecialchars($debuginfo, ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE));
1992 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1993 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
1995 if (!empty($backtrace)) {
1996 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
2000 return $content;
2004 * This function should only be called by this class, or from exception handlers
2005 * @static
2006 * @param string $message error message
2007 * @param string $moreinfourl (ignored in early errors)
2008 * @param string $link (ignored in early errors)
2009 * @param array $backtrace
2010 * @param string $debuginfo extra information for developers
2011 * @return string
2013 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = null) {
2014 global $CFG;
2016 if (CLI_SCRIPT) {
2017 echo "!!! $message !!!\n";
2018 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
2019 if (!empty($debuginfo)) {
2020 echo "\nDebug info: $debuginfo";
2022 if (!empty($backtrace)) {
2023 echo "\nStack trace: " . format_backtrace($backtrace, true);
2026 return;
2028 } else if (AJAX_SCRIPT) {
2029 $e = new stdClass();
2030 $e->error = $message;
2031 $e->stacktrace = NULL;
2032 $e->debuginfo = NULL;
2033 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
2034 if (!empty($debuginfo)) {
2035 $e->debuginfo = $debuginfo;
2037 if (!empty($backtrace)) {
2038 $e->stacktrace = format_backtrace($backtrace, true);
2041 $e->errorcode = $errorcode;
2042 @header('Content-Type: application/json; charset=utf-8');
2043 echo json_encode($e);
2044 return;
2047 // In the name of protocol correctness, monitoring and performance
2048 // profiling, set the appropriate error headers for machine consumption.
2049 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2050 @header($protocol . ' 503 Service Unavailable');
2052 // better disable any caching
2053 @header('Content-Type: text/html; charset=utf-8');
2054 @header('X-UA-Compatible: IE=edge');
2055 @header('Cache-Control: no-store, no-cache, must-revalidate');
2056 @header('Cache-Control: post-check=0, pre-check=0', false);
2057 @header('Pragma: no-cache');
2058 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2059 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2061 if (function_exists('get_string')) {
2062 $strerror = get_string('error');
2063 } else {
2064 $strerror = 'Error';
2067 $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
2069 return self::plain_page($strerror, $content);
2073 * Early notification message
2074 * @static
2075 * @param string $message
2076 * @param string $classes usually notifyproblem or notifysuccess
2077 * @return string
2079 public static function early_notification($message, $classes = 'notifyproblem') {
2080 return '<div class="' . $classes . '">' . $message . '</div>';
2084 * Page should redirect message.
2085 * @static
2086 * @param string $encodedurl redirect url
2087 * @return string
2089 public static function plain_redirect_message($encodedurl) {
2090 $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
2091 $encodedurl .'">'. get_string('continue') .'</a></div>';
2092 return self::plain_page(get_string('redirect'), $message);
2096 * Early redirection page, used before full init of $PAGE global
2097 * @static
2098 * @param string $encodedurl redirect url
2099 * @param string $message redirect message
2100 * @param int $delay time in seconds
2101 * @return string redirect page
2103 public static function early_redirect_message($encodedurl, $message, $delay) {
2104 $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
2105 $content = self::early_error_content($message, null, null, null);
2106 $content .= self::plain_redirect_message($encodedurl);
2108 return self::plain_page(get_string('redirect'), $content, $meta);
2112 * Output basic html page.
2113 * @static
2114 * @param string $title page title
2115 * @param string $content page content
2116 * @param string $meta meta tag
2117 * @return string html page
2119 public static function plain_page($title, $content, $meta = '') {
2120 global $CFG;
2122 if (function_exists('get_string') && function_exists('get_html_lang')) {
2123 $htmllang = get_html_lang();
2124 } else {
2125 $htmllang = '';
2128 $footer = '';
2129 if (function_exists('get_performance_info')) { // Function may be not available for some early errors.
2130 if (MDL_PERF_TEST) {
2131 $perfinfo = get_performance_info();
2132 $footer = '<footer>' . $perfinfo['html'] . '</footer>';
2136 ob_start();
2137 include($CFG->dirroot . '/error/plainpage.php');
2138 $html = ob_get_contents();
2139 ob_end_clean();
2141 return $html;