MDL-54934 workshop: ensure "Current phase" is always separated
[moodle.git] / lib / setuplib.php
blob16810cddc99fb43dcad36240c538c28514686d7c
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);
55 /**
56 * Simple class. It is usually used instead of stdClass because it looks
57 * more familiar to Java developers ;-) Do not use for type checking of
58 * function parameters. Please use stdClass instead.
60 * @package core
61 * @subpackage lib
62 * @copyright 2009 Petr Skoda {@link http://skodak.org}
63 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
64 * @deprecated since 2.0
66 class object extends stdClass {};
68 /**
69 * Base Moodle Exception class
71 * Although this class is defined here, you cannot throw a moodle_exception until
72 * after moodlelib.php has been included (which will happen very soon).
74 * @package core
75 * @subpackage lib
76 * @copyright 2008 Petr Skoda {@link http://skodak.org}
77 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
79 class moodle_exception extends Exception {
81 /**
82 * @var string The name of the string from error.php to print
84 public $errorcode;
86 /**
87 * @var string The name of module
89 public $module;
91 /**
92 * @var mixed Extra words and phrases that might be required in the error string
94 public $a;
96 /**
97 * @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.
99 public $link;
102 * @var string Optional information to aid the debugging process
104 public $debuginfo;
107 * Constructor
108 * @param string $errorcode The name of the string from error.php to print
109 * @param string $module name of module
110 * @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.
111 * @param mixed $a Extra words and phrases that might be required in the error string
112 * @param string $debuginfo optional debugging information
114 function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
115 if (empty($module) || $module == 'moodle' || $module == 'core') {
116 $module = 'error';
119 $this->errorcode = $errorcode;
120 $this->module = $module;
121 $this->link = $link;
122 $this->a = $a;
123 $this->debuginfo = is_null($debuginfo) ? null : (string)$debuginfo;
125 if (get_string_manager()->string_exists($errorcode, $module)) {
126 $message = get_string($errorcode, $module, $a);
127 $haserrorstring = true;
128 } else {
129 $message = $module . '/' . $errorcode;
130 $haserrorstring = false;
133 if (defined('PHPUNIT_TEST') and PHPUNIT_TEST and $debuginfo) {
134 $message = "$message ($debuginfo)";
137 if (!$haserrorstring and defined('PHPUNIT_TEST') and PHPUNIT_TEST) {
138 // Append the contents of $a to $debuginfo so helpful information isn't lost.
139 // This emulates what {@link get_exception_info()} does. Unfortunately that
140 // function is not used by phpunit.
141 $message .= PHP_EOL.'$a contents: '.print_r($a, true);
144 parent::__construct($message, 0);
149 * Course/activity access exception.
151 * This exception is thrown from require_login()
153 * @package core_access
154 * @copyright 2010 Petr Skoda {@link http://skodak.org}
155 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
157 class require_login_exception extends moodle_exception {
159 * Constructor
160 * @param string $debuginfo Information to aid the debugging process
162 function __construct($debuginfo) {
163 parent::__construct('requireloginerror', 'error', '', NULL, $debuginfo);
168 * Session timeout exception.
170 * This exception is thrown from require_login()
172 * @package core_access
173 * @copyright 2015 Andrew Nicols <andrew@nicols.co.uk>
174 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
176 class require_login_session_timeout_exception extends require_login_exception {
178 * Constructor
180 public function __construct() {
181 moodle_exception::__construct('sessionerroruser', 'error');
186 * Web service parameter exception class
187 * @deprecated since Moodle 2.2 - use moodle exception instead
188 * This exception must be thrown to the web service client when a web service parameter is invalid
189 * The error string is gotten from webservice.php
191 class webservice_parameter_exception extends moodle_exception {
193 * Constructor
194 * @param string $errorcode The name of the string from webservice.php to print
195 * @param string $a The name of the parameter
196 * @param string $debuginfo Optional information to aid debugging
198 function __construct($errorcode=null, $a = '', $debuginfo = null) {
199 parent::__construct($errorcode, 'webservice', '', $a, $debuginfo);
204 * Exceptions indicating user does not have permissions to do something
205 * and the execution can not continue.
207 * @package core_access
208 * @copyright 2009 Petr Skoda {@link http://skodak.org}
209 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
211 class required_capability_exception extends moodle_exception {
213 * Constructor
214 * @param context $context The context used for the capability check
215 * @param string $capability The required capability
216 * @param string $errormessage The error message to show the user
217 * @param string $stringfile
219 function __construct($context, $capability, $errormessage, $stringfile) {
220 $capabilityname = get_capability_string($capability);
221 if ($context->contextlevel == CONTEXT_MODULE and preg_match('/:view$/', $capability)) {
222 // 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
223 $parentcontext = $context->get_parent_context();
224 $link = $parentcontext->get_url();
225 } else {
226 $link = $context->get_url();
228 parent::__construct($errormessage, $stringfile, $link, $capabilityname);
233 * Exception indicating programming error, must be fixed by a programer. For example
234 * a core API might throw this type of exception if a plugin calls it incorrectly.
236 * @package core
237 * @subpackage lib
238 * @copyright 2008 Petr Skoda {@link http://skodak.org}
239 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
241 class coding_exception extends moodle_exception {
243 * Constructor
244 * @param string $hint short description of problem
245 * @param string $debuginfo detailed information how to fix problem
247 function __construct($hint, $debuginfo=null) {
248 parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
253 * Exception indicating malformed parameter problem.
254 * This exception is not supposed to be thrown when processing
255 * user submitted data in forms. It is more suitable
256 * for WS and other low level stuff.
258 * @package core
259 * @subpackage lib
260 * @copyright 2009 Petr Skoda {@link http://skodak.org}
261 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
263 class invalid_parameter_exception extends moodle_exception {
265 * Constructor
266 * @param string $debuginfo some detailed information
268 function __construct($debuginfo=null) {
269 parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
274 * Exception indicating malformed response problem.
275 * This exception is not supposed to be thrown when processing
276 * user submitted data in forms. It is more suitable
277 * for WS and other low level stuff.
279 class invalid_response_exception extends moodle_exception {
281 * Constructor
282 * @param string $debuginfo some detailed information
284 function __construct($debuginfo=null) {
285 parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
290 * An exception that indicates something really weird happened. For example,
291 * if you do switch ($context->contextlevel), and have one case for each
292 * CONTEXT_... constant. You might throw an invalid_state_exception in the
293 * default case, to just in case something really weird is going on, and
294 * $context->contextlevel is invalid - rather than ignoring this possibility.
296 * @package core
297 * @subpackage lib
298 * @copyright 2009 onwards Martin Dougiamas {@link http://moodle.com}
299 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
301 class invalid_state_exception extends moodle_exception {
303 * Constructor
304 * @param string $hint short description of problem
305 * @param string $debuginfo optional more detailed information
307 function __construct($hint, $debuginfo=null) {
308 parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
313 * An exception that indicates incorrect permissions in $CFG->dataroot
315 * @package core
316 * @subpackage lib
317 * @copyright 2010 Petr Skoda {@link http://skodak.org}
318 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
320 class invalid_dataroot_permissions extends moodle_exception {
322 * Constructor
323 * @param string $debuginfo optional more detailed information
325 function __construct($debuginfo = NULL) {
326 parent::__construct('invaliddatarootpermissions', 'error', '', NULL, $debuginfo);
331 * An exception that indicates that file can not be served
333 * @package core
334 * @subpackage lib
335 * @copyright 2010 Petr Skoda {@link http://skodak.org}
336 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
338 class file_serving_exception extends moodle_exception {
340 * Constructor
341 * @param string $debuginfo optional more detailed information
343 function __construct($debuginfo = NULL) {
344 parent::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
349 * Default exception handler.
351 * @param Exception $ex
352 * @return void -does not return. Terminates execution!
354 function default_exception_handler($ex) {
355 global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION, $PAGE;
357 // detect active db transactions, rollback and log as error
358 abort_all_db_transactions();
360 if (($ex instanceof required_capability_exception) && !CLI_SCRIPT && !AJAX_SCRIPT && !empty($CFG->autologinguests) && !empty($USER->autologinguest)) {
361 $SESSION->wantsurl = qualified_me();
362 redirect(get_login_url());
365 $info = get_exception_info($ex);
367 if (debugging('', DEBUG_MINIMAL)) {
368 $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
369 error_log($logerrmsg);
372 if (is_early_init($info->backtrace)) {
373 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
374 } else {
375 try {
376 if ($DB) {
377 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
378 $DB->set_debug(0);
380 echo $OUTPUT->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
381 } catch (Exception $e) {
382 $out_ex = $e;
383 } catch (Throwable $e) {
384 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
385 $out_ex = $e;
388 if (isset($out_ex)) {
389 // default exception handler MUST not throw any exceptions!!
390 // 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
391 // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
392 if (CLI_SCRIPT or AJAX_SCRIPT) {
393 // just ignore the error and send something back using the safest method
394 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
395 } else {
396 echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
397 $outinfo = get_exception_info($out_ex);
398 echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
403 exit(1); // General error code
407 * Default error handler, prevents some white screens.
408 * @param int $errno
409 * @param string $errstr
410 * @param string $errfile
411 * @param int $errline
412 * @param array $errcontext
413 * @return bool false means use default error handler
415 function default_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
416 if ($errno == 4096) {
417 //fatal catchable error
418 throw new coding_exception('PHP catchable fatal error', $errstr);
420 return false;
424 * Unconditionally abort all database transactions, this function
425 * should be called from exception handlers only.
426 * @return void
428 function abort_all_db_transactions() {
429 global $CFG, $DB, $SCRIPT;
431 // default exception handler MUST not throw any exceptions!!
433 if ($DB && $DB->is_transaction_started()) {
434 error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
435 // note: transaction blocks should never change current $_SESSION
436 $DB->force_transaction_rollback();
441 * This function encapsulates the tests for whether an exception was thrown in
442 * early init -- either during setup.php or during init of $OUTPUT.
444 * If another exception is thrown then, and if we do not take special measures,
445 * we would just get a very cryptic message "Exception thrown without a stack
446 * frame in Unknown on line 0". That makes debugging very hard, so we do take
447 * special measures in default_exception_handler, with the help of this function.
449 * @param array $backtrace the stack trace to analyse.
450 * @return boolean whether the stack trace is somewhere in output initialisation.
452 function is_early_init($backtrace) {
453 $dangerouscode = array(
454 array('function' => 'header', 'type' => '->'),
455 array('class' => 'bootstrap_renderer'),
456 array('file' => dirname(__FILE__).'/setup.php'),
458 foreach ($backtrace as $stackframe) {
459 foreach ($dangerouscode as $pattern) {
460 $matches = true;
461 foreach ($pattern as $property => $value) {
462 if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
463 $matches = false;
466 if ($matches) {
467 return true;
471 return false;
475 * Abort execution by throwing of a general exception,
476 * default exception handler displays the error message in most cases.
478 * @param string $errorcode The name of the language string containing the error message.
479 * Normally this should be in the error.php lang file.
480 * @param string $module The language file to get the error message from.
481 * @param string $link The url where the user will be prompted to continue.
482 * If no url is provided the user will be directed to the site index page.
483 * @param object $a Extra words and phrases that might be required in the error string
484 * @param string $debuginfo optional debugging information
485 * @return void, always throws exception!
487 function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
488 throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
492 * Returns detailed information about specified exception.
493 * @param exception $ex
494 * @return object
496 function get_exception_info($ex) {
497 global $CFG, $DB, $SESSION;
499 if ($ex instanceof moodle_exception) {
500 $errorcode = $ex->errorcode;
501 $module = $ex->module;
502 $a = $ex->a;
503 $link = $ex->link;
504 $debuginfo = $ex->debuginfo;
505 } else {
506 $errorcode = 'generalexceptionmessage';
507 $module = 'error';
508 $a = $ex->getMessage();
509 $link = '';
510 $debuginfo = '';
513 // Append the error code to the debug info to make grepping and googling easier
514 $debuginfo .= PHP_EOL."Error code: $errorcode";
516 $backtrace = $ex->getTrace();
517 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
518 array_unshift($backtrace, $place);
520 // Be careful, no guarantee moodlelib.php is loaded.
521 if (empty($module) || $module == 'moodle' || $module == 'core') {
522 $module = 'error';
524 // Search for the $errorcode's associated string
525 // If not found, append the contents of $a to $debuginfo so helpful information isn't lost
526 if (function_exists('get_string_manager')) {
527 if (get_string_manager()->string_exists($errorcode, $module)) {
528 $message = get_string($errorcode, $module, $a);
529 } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
530 // Search in moodle file if error specified - needed for backwards compatibility
531 $message = get_string($errorcode, 'moodle', $a);
532 } else {
533 $message = $module . '/' . $errorcode;
534 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
536 } else {
537 $message = $module . '/' . $errorcode;
538 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
541 // Remove some absolute paths from message and debugging info.
542 $searches = array();
543 $replaces = array();
544 $cfgnames = array('tempdir', 'cachedir', 'localcachedir', 'themedir', 'dataroot', 'dirroot');
545 foreach ($cfgnames as $cfgname) {
546 if (property_exists($CFG, $cfgname)) {
547 $searches[] = $CFG->$cfgname;
548 $replaces[] = "[$cfgname]";
551 if (!empty($searches)) {
552 $message = str_replace($searches, $replaces, $message);
553 $debuginfo = str_replace($searches, $replaces, $debuginfo);
556 // Be careful, no guarantee weblib.php is loaded.
557 if (function_exists('clean_text')) {
558 $message = clean_text($message);
559 } else {
560 $message = htmlspecialchars($message);
563 if (!empty($CFG->errordocroot)) {
564 $errordoclink = $CFG->errordocroot . '/en/';
565 } else {
566 $errordoclink = get_docs_url();
569 if ($module === 'error') {
570 $modulelink = 'moodle';
571 } else {
572 $modulelink = $module;
574 $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
576 if (empty($link)) {
577 if (!empty($SESSION->fromurl)) {
578 $link = $SESSION->fromurl;
579 unset($SESSION->fromurl);
580 } else {
581 $link = $CFG->wwwroot .'/';
585 // When printing an error the continue button should never link offsite.
586 // We cannot use clean_param() here as it is not guaranteed that it has been loaded yet.
587 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
588 if (stripos($link, $CFG->wwwroot) === 0) {
589 // Internal HTTP, all good.
590 } else if (!empty($CFG->loginhttps) && stripos($link, $httpswwwroot) === 0) {
591 // Internal HTTPS, all good.
592 } else {
593 // External link spotted!
594 $link = $CFG->wwwroot . '/';
597 $info = new stdClass();
598 $info->message = $message;
599 $info->errorcode = $errorcode;
600 $info->backtrace = $backtrace;
601 $info->link = $link;
602 $info->moreinfourl = $moreinfourl;
603 $info->a = $a;
604 $info->debuginfo = $debuginfo;
606 return $info;
610 * Generate a uuid.
612 * Unique is hard. Very hard. Attempt to use the PECL UUID functions if available, and if not then revert to
613 * constructing the uuid using mt_rand.
615 * It is important that this token is not solely based on time as this could lead
616 * to duplicates in a clustered environment (especially on VMs due to poor time precision).
618 * @return string The uuid.
620 function generate_uuid() {
621 $uuid = '';
623 if (function_exists("uuid_create")) {
624 $context = null;
625 uuid_create($context);
627 uuid_make($context, UUID_MAKE_V4);
628 uuid_export($context, UUID_FMT_STR, $uuid);
629 } else {
630 // Fallback uuid generation based on:
631 // "http://www.php.net/manual/en/function.uniqid.php#94959".
632 $uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
634 // 32 bits for "time_low".
635 mt_rand(0, 0xffff), mt_rand(0, 0xffff),
637 // 16 bits for "time_mid".
638 mt_rand(0, 0xffff),
640 // 16 bits for "time_hi_and_version",
641 // four most significant bits holds version number 4.
642 mt_rand(0, 0x0fff) | 0x4000,
644 // 16 bits, 8 bits for "clk_seq_hi_res",
645 // 8 bits for "clk_seq_low",
646 // two most significant bits holds zero and one for variant DCE1.1.
647 mt_rand(0, 0x3fff) | 0x8000,
649 // 48 bits for "node".
650 mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
652 return trim($uuid);
656 * Returns the Moodle Docs URL in the users language for a given 'More help' link.
658 * There are three cases:
660 * 1. In the normal case, $path will be a short relative path 'component/thing',
661 * like 'mod/folder/view' 'group/import'. This gets turned into an link to
662 * MoodleDocs in the user's language, and for the appropriate Moodle version.
663 * E.g. 'group/import' may become 'http://docs.moodle.org/2x/en/group/import'.
664 * The 'http://docs.moodle.org' bit comes from $CFG->docroot.
666 * This is the only option that should be used in standard Moodle code. The other
667 * two options have been implemented because they are useful for third-party plugins.
669 * 2. $path may be an absolute URL, starting http:// or https://. In this case,
670 * the link is used as is.
672 * 3. $path may start %%WWWROOT%%, in which case that is replaced by
673 * $CFG->wwwroot to make the link.
675 * @param string $path the place to link to. See above for details.
676 * @return string The MoodleDocs URL in the user's language. for example @link http://docs.moodle.org/2x/en/$path}
678 function get_docs_url($path = null) {
679 global $CFG;
681 // Absolute URLs are used unmodified.
682 if (substr($path, 0, 7) === 'http://' || substr($path, 0, 8) === 'https://') {
683 return $path;
686 // Paths starting %%WWWROOT%% have that replaced by $CFG->wwwroot.
687 if (substr($path, 0, 11) === '%%WWWROOT%%') {
688 return $CFG->wwwroot . substr($path, 11);
691 // Otherwise we do the normal case, and construct a MoodleDocs URL relative to $CFG->docroot.
693 // Check that $CFG->branch has been set up, during installation it won't be.
694 if (empty($CFG->branch)) {
695 // It's not there yet so look at version.php.
696 include($CFG->dirroot.'/version.php');
697 } else {
698 // We can use $CFG->branch and avoid having to include version.php.
699 $branch = $CFG->branch;
701 // ensure branch is valid.
702 if (!$branch) {
703 // We should never get here but in case we do lets set $branch to .
704 // the smart one's will know that this is the current directory
705 // and the smarter ones will know that there is some smart matching
706 // that will ensure people end up at the latest version of the docs.
707 $branch = '.';
709 if (empty($CFG->doclang)) {
710 $lang = current_language();
711 } else {
712 $lang = $CFG->doclang;
714 $end = '/' . $branch . '/' . $lang . '/' . $path;
715 if (empty($CFG->docroot)) {
716 return 'http://docs.moodle.org'. $end;
717 } else {
718 return $CFG->docroot . $end ;
723 * Formats a backtrace ready for output.
725 * @param array $callers backtrace array, as returned by debug_backtrace().
726 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
727 * @return string formatted backtrace, ready for output.
729 function format_backtrace($callers, $plaintext = false) {
730 // do not use $CFG->dirroot because it might not be available in destructors
731 $dirroot = dirname(dirname(__FILE__));
733 if (empty($callers)) {
734 return '';
737 $from = $plaintext ? '' : '<ul style="text-align: left" data-rel="backtrace">';
738 foreach ($callers as $caller) {
739 if (!isset($caller['line'])) {
740 $caller['line'] = '?'; // probably call_user_func()
742 if (!isset($caller['file'])) {
743 $caller['file'] = 'unknownfile'; // probably call_user_func()
745 $from .= $plaintext ? '* ' : '<li>';
746 $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
747 if (isset($caller['function'])) {
748 $from .= ': call to ';
749 if (isset($caller['class'])) {
750 $from .= $caller['class'] . $caller['type'];
752 $from .= $caller['function'] . '()';
753 } else if (isset($caller['exception'])) {
754 $from .= ': '.$caller['exception'].' thrown';
756 $from .= $plaintext ? "\n" : '</li>';
758 $from .= $plaintext ? '' : '</ul>';
760 return $from;
764 * This function makes the return value of ini_get consistent if you are
765 * setting server directives through the .htaccess file in apache.
767 * Current behavior for value set from php.ini On = 1, Off = [blank]
768 * Current behavior for value set from .htaccess On = On, Off = Off
769 * Contributed by jdell @ unr.edu
771 * @param string $ini_get_arg The argument to get
772 * @return bool True for on false for not
774 function ini_get_bool($ini_get_arg) {
775 $temp = ini_get($ini_get_arg);
777 if ($temp == '1' or strtolower($temp) == 'on') {
778 return true;
780 return false;
784 * This function verifies the sanity of PHP configuration
785 * and stops execution if anything critical found.
787 function setup_validate_php_configuration() {
788 // this must be very fast - no slow checks here!!!
790 if (ini_get_bool('session.auto_start')) {
791 print_error('sessionautostartwarning', 'admin');
796 * Initialise global $CFG variable.
797 * @private to be used only from lib/setup.php
799 function initialise_cfg() {
800 global $CFG, $DB;
802 if (!$DB) {
803 // This should not happen.
804 return;
807 try {
808 $localcfg = get_config('core');
809 } catch (dml_exception $e) {
810 // Most probably empty db, going to install soon.
811 return;
814 foreach ($localcfg as $name => $value) {
815 // Note that get_config() keeps forced settings
816 // and normalises values to string if possible.
817 $CFG->{$name} = $value;
822 * Initialises $FULLME and friends. Private function. Should only be called from
823 * setup.php.
825 function initialise_fullme() {
826 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
828 // Detect common config error.
829 if (substr($CFG->wwwroot, -1) == '/') {
830 print_error('wwwrootslash', 'error');
833 if (CLI_SCRIPT) {
834 initialise_fullme_cli();
835 return;
838 $rurl = setup_get_remote_url();
839 $wwwroot = parse_url($CFG->wwwroot.'/');
841 if (empty($rurl['host'])) {
842 // missing host in request header, probably not a real browser, let's ignore them
844 } else if (!empty($CFG->reverseproxy)) {
845 // $CFG->reverseproxy specifies if reverse proxy server used
846 // Used in load balancing scenarios.
847 // Do not abuse this to try to solve lan/wan access problems!!!!!
849 } else {
850 if (($rurl['host'] !== $wwwroot['host']) or
851 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port']) or
852 (strpos($rurl['path'], $wwwroot['path']) !== 0)) {
854 // Explain the problem and redirect them to the right URL
855 if (!defined('NO_MOODLE_COOKIES')) {
856 define('NO_MOODLE_COOKIES', true);
858 // The login/token.php script should call the correct url/port.
859 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
860 $wwwrootport = empty($wwwroot['port'])?'':$wwwroot['port'];
861 $calledurl = $rurl['host'];
862 if (!empty($rurl['port'])) {
863 $calledurl .= ':'. $rurl['port'];
865 $correcturl = $wwwroot['host'];
866 if (!empty($wwwrootport)) {
867 $correcturl .= ':'. $wwwrootport;
869 throw new moodle_exception('requirecorrectaccess', 'error', '', null,
870 'You called ' . $calledurl .', you should have called ' . $correcturl);
872 redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
876 // Check that URL is under $CFG->wwwroot.
877 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
878 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
879 } else {
880 // Probably some weird external script
881 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
882 return;
885 // $CFG->sslproxy specifies if external SSL appliance is used
886 // (That is, the Moodle server uses http, with an external box translating everything to https).
887 if (empty($CFG->sslproxy)) {
888 if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
889 print_error('sslonlyaccess', 'error');
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 = create_function('$p', 'return implode("'.$delim.'", $p);');
1104 $chunks = array_map($fun, array_chunk(explode($delim, $str), $max));
1106 // Clear everything from existing $_POST array, otherwise it might be included
1107 // twice (this affects array params primarily).
1108 foreach ($_POST as $key => $value) {
1109 unset($_POST[$key]);
1110 // Also clear from request array - but only the things that are in $_POST,
1111 // that way it will leave the things from a get request if any.
1112 unset($_REQUEST[$key]);
1115 foreach ($chunks as $chunk) {
1116 $values = array();
1117 parse_str($chunk, $values);
1119 merge_query_params($_POST, $values);
1120 merge_query_params($_REQUEST, $values);
1125 * Merge parsed POST chunks.
1127 * NOTE: this is not perfect, but it should work in most cases hopefully.
1129 * @param array $target
1130 * @param array $values
1132 function merge_query_params(array &$target, array $values) {
1133 if (isset($values[0]) and isset($target[0])) {
1134 // This looks like a split [] array, lets verify the keys are continuous starting with 0.
1135 $keys1 = array_keys($values);
1136 $keys2 = array_keys($target);
1137 if ($keys1 === array_keys($keys1) and $keys2 === array_keys($keys2)) {
1138 foreach ($values as $v) {
1139 $target[] = $v;
1141 return;
1144 foreach ($values as $k => $v) {
1145 if (!isset($target[$k])) {
1146 $target[$k] = $v;
1147 continue;
1149 if (is_array($target[$k]) and is_array($v)) {
1150 merge_query_params($target[$k], $v);
1151 continue;
1153 // We should not get here unless there are duplicates in params.
1154 $target[$k] = $v;
1159 * Initializes our performance info early.
1161 * Pairs up with get_performance_info() which is actually
1162 * in moodlelib.php. This function is here so that we can
1163 * call it before all the libs are pulled in.
1165 * @uses $PERF
1167 function init_performance_info() {
1169 global $PERF, $CFG, $USER;
1171 $PERF = new stdClass();
1172 $PERF->logwrites = 0;
1173 if (function_exists('microtime')) {
1174 $PERF->starttime = microtime();
1176 if (function_exists('memory_get_usage')) {
1177 $PERF->startmemory = memory_get_usage();
1179 if (function_exists('posix_times')) {
1180 $PERF->startposixtimes = posix_times();
1185 * Indicates whether we are in the middle of the initial Moodle install.
1187 * Very occasionally it is necessary avoid running certain bits of code before the
1188 * Moodle installation has completed. The installed flag is set in admin/index.php
1189 * after Moodle core and all the plugins have been installed, but just before
1190 * the person doing the initial install is asked to choose the admin password.
1192 * @return boolean true if the initial install is not complete.
1194 function during_initial_install() {
1195 global $CFG;
1196 return empty($CFG->rolesactive);
1200 * Function to raise the memory limit to a new value.
1201 * Will respect the memory limit if it is higher, thus allowing
1202 * settings in php.ini, apache conf or command line switches
1203 * to override it.
1205 * The memory limit should be expressed with a constant
1206 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
1207 * It is possible to use strings or integers too (eg:'128M').
1209 * @param mixed $newlimit the new memory limit
1210 * @return bool success
1212 function raise_memory_limit($newlimit) {
1213 global $CFG;
1215 if ($newlimit == MEMORY_UNLIMITED) {
1216 ini_set('memory_limit', -1);
1217 return true;
1219 } else if ($newlimit == MEMORY_STANDARD) {
1220 if (PHP_INT_SIZE > 4) {
1221 $newlimit = get_real_size('128M'); // 64bit needs more memory
1222 } else {
1223 $newlimit = get_real_size('96M');
1226 } else if ($newlimit == MEMORY_EXTRA) {
1227 if (PHP_INT_SIZE > 4) {
1228 $newlimit = get_real_size('384M'); // 64bit needs more memory
1229 } else {
1230 $newlimit = get_real_size('256M');
1232 if (!empty($CFG->extramemorylimit)) {
1233 $extra = get_real_size($CFG->extramemorylimit);
1234 if ($extra > $newlimit) {
1235 $newlimit = $extra;
1239 } else if ($newlimit == MEMORY_HUGE) {
1240 // MEMORY_HUGE uses 2G or MEMORY_EXTRA, whichever is bigger.
1241 $newlimit = get_real_size('2G');
1242 if (!empty($CFG->extramemorylimit)) {
1243 $extra = get_real_size($CFG->extramemorylimit);
1244 if ($extra > $newlimit) {
1245 $newlimit = $extra;
1249 } else {
1250 $newlimit = get_real_size($newlimit);
1253 if ($newlimit <= 0) {
1254 debugging('Invalid memory limit specified.');
1255 return false;
1258 $cur = ini_get('memory_limit');
1259 if (empty($cur)) {
1260 // if php is compiled without --enable-memory-limits
1261 // apparently memory_limit is set to ''
1262 $cur = 0;
1263 } else {
1264 if ($cur == -1){
1265 return true; // unlimited mem!
1267 $cur = get_real_size($cur);
1270 if ($newlimit > $cur) {
1271 ini_set('memory_limit', $newlimit);
1272 return true;
1274 return false;
1278 * Function to reduce the memory limit to a new value.
1279 * Will respect the memory limit if it is lower, thus allowing
1280 * settings in php.ini, apache conf or command line switches
1281 * to override it
1283 * The memory limit should be expressed with a string (eg:'64M')
1285 * @param string $newlimit the new memory limit
1286 * @return bool
1288 function reduce_memory_limit($newlimit) {
1289 if (empty($newlimit)) {
1290 return false;
1292 $cur = ini_get('memory_limit');
1293 if (empty($cur)) {
1294 // if php is compiled without --enable-memory-limits
1295 // apparently memory_limit is set to ''
1296 $cur = 0;
1297 } else {
1298 if ($cur == -1){
1299 return true; // unlimited mem!
1301 $cur = get_real_size($cur);
1304 $new = get_real_size($newlimit);
1305 // -1 is smaller, but it means unlimited
1306 if ($new < $cur && $new != -1) {
1307 ini_set('memory_limit', $newlimit);
1308 return true;
1310 return false;
1314 * Converts numbers like 10M into bytes.
1316 * @param string $size The size to be converted
1317 * @return int
1319 function get_real_size($size = 0) {
1320 if (!$size) {
1321 return 0;
1323 $scan = array();
1324 $scan['GB'] = 1073741824;
1325 $scan['Gb'] = 1073741824;
1326 $scan['G'] = 1073741824;
1327 $scan['MB'] = 1048576;
1328 $scan['Mb'] = 1048576;
1329 $scan['M'] = 1048576;
1330 $scan['m'] = 1048576;
1331 $scan['KB'] = 1024;
1332 $scan['Kb'] = 1024;
1333 $scan['K'] = 1024;
1334 $scan['k'] = 1024;
1336 while (list($key) = each($scan)) {
1337 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
1338 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
1339 break;
1342 return $size;
1346 * Try to disable all output buffering and purge
1347 * all headers.
1349 * @access private to be called only from lib/setup.php !
1350 * @return void
1352 function disable_output_buffering() {
1353 $olddebug = error_reporting(0);
1355 // disable compression, it would prevent closing of buffers
1356 if (ini_get_bool('zlib.output_compression')) {
1357 ini_set('zlib.output_compression', 'Off');
1360 // try to flush everything all the time
1361 ob_implicit_flush(true);
1363 // close all buffers if possible and discard any existing output
1364 // this can actually work around some whitespace problems in config.php
1365 while(ob_get_level()) {
1366 if (!ob_end_clean()) {
1367 // prevent infinite loop when buffer can not be closed
1368 break;
1372 // disable any other output handlers
1373 ini_set('output_handler', '');
1375 error_reporting($olddebug);
1379 * Check whether a major upgrade is needed. That is defined as an upgrade that
1380 * changes something really fundamental in the database, so nothing can possibly
1381 * work until the database has been updated, and that is defined by the hard-coded
1382 * version number in this function.
1384 function redirect_if_major_upgrade_required() {
1385 global $CFG;
1386 $lastmajordbchanges = 2014093001.00;
1387 if (empty($CFG->version) or (float)$CFG->version < $lastmajordbchanges or
1388 during_initial_install() or !empty($CFG->adminsetuppending)) {
1389 try {
1390 @\core\session\manager::terminate_current();
1391 } catch (Exception $e) {
1392 // Ignore any errors, redirect to upgrade anyway.
1394 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
1395 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1396 @header('Location: ' . $url);
1397 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
1398 exit;
1403 * Makes sure that upgrade process is not running
1405 * To be inserted in the core functions that can not be called by pluigns during upgrade.
1406 * Core upgrade should not use any API functions at all.
1407 * See {@link http://docs.moodle.org/dev/Upgrade_API#Upgrade_code_restrictions}
1409 * @throws moodle_exception if executed from inside of upgrade script and $warningonly is false
1410 * @param bool $warningonly if true displays a warning instead of throwing an exception
1411 * @return bool true if executed from outside of upgrade process, false if from inside upgrade process and function is used for warning only
1413 function upgrade_ensure_not_running($warningonly = false) {
1414 global $CFG;
1415 if (!empty($CFG->upgraderunning)) {
1416 if (!$warningonly) {
1417 throw new moodle_exception('cannotexecduringupgrade');
1418 } else {
1419 debugging(get_string('cannotexecduringupgrade', 'error'), DEBUG_DEVELOPER);
1420 return false;
1423 return true;
1427 * Function to check if a directory exists and by default create it if not exists.
1429 * Previously this was accepting paths only from dataroot, but we now allow
1430 * files outside of dataroot if you supply custom paths for some settings in config.php.
1431 * This function does not verify that the directory is writable.
1433 * NOTE: this function uses current file stat cache,
1434 * please use clearstatcache() before this if you expect that the
1435 * directories may have been removed recently from a different request.
1437 * @param string $dir absolute directory path
1438 * @param boolean $create directory if does not exist
1439 * @param boolean $recursive create directory recursively
1440 * @return boolean true if directory exists or created, false otherwise
1442 function check_dir_exists($dir, $create = true, $recursive = true) {
1443 global $CFG;
1445 umask($CFG->umaskpermissions);
1447 if (is_dir($dir)) {
1448 return true;
1451 if (!$create) {
1452 return false;
1455 return mkdir($dir, $CFG->directorypermissions, $recursive);
1459 * Create a new unique directory within the specified directory.
1461 * @param string $basedir The directory to create your new unique directory within.
1462 * @param bool $exceptiononerror throw exception if error encountered
1463 * @return string The created directory
1464 * @throws invalid_dataroot_permissions
1466 function make_unique_writable_directory($basedir, $exceptiononerror = true) {
1467 if (!is_dir($basedir) || !is_writable($basedir)) {
1468 // The basedir is not writable. We will not be able to create the child directory.
1469 if ($exceptiononerror) {
1470 throw new invalid_dataroot_permissions($basedir . ' is not writable. Unable to create a unique directory within it.');
1471 } else {
1472 return false;
1476 do {
1477 // Generate a new (hopefully unique) directory name.
1478 $uniquedir = $basedir . DIRECTORY_SEPARATOR . generate_uuid();
1479 } while (
1480 // Ensure that basedir is still writable - if we do not check, we could get stuck in a loop here.
1481 is_writable($basedir) &&
1483 // Make the new unique directory. If the directory already exists, it will return false.
1484 !make_writable_directory($uniquedir, $exceptiononerror) &&
1486 // Ensure that the directory now exists
1487 file_exists($uniquedir) && is_dir($uniquedir)
1490 // Check that the directory was correctly created.
1491 if (!file_exists($uniquedir) || !is_dir($uniquedir) || !is_writable($uniquedir)) {
1492 if ($exceptiononerror) {
1493 throw new invalid_dataroot_permissions('Unique directory creation failed.');
1494 } else {
1495 return false;
1499 return $uniquedir;
1503 * Create a directory and make sure it is writable.
1505 * @private
1506 * @param string $dir the full path of the directory to be created
1507 * @param bool $exceptiononerror throw exception if error encountered
1508 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1510 function make_writable_directory($dir, $exceptiononerror = true) {
1511 global $CFG;
1513 if (file_exists($dir) and !is_dir($dir)) {
1514 if ($exceptiononerror) {
1515 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1516 } else {
1517 return false;
1521 umask($CFG->umaskpermissions);
1523 if (!file_exists($dir)) {
1524 if (!@mkdir($dir, $CFG->directorypermissions, true)) {
1525 clearstatcache();
1526 // There might be a race condition when creating directory.
1527 if (!is_dir($dir)) {
1528 if ($exceptiononerror) {
1529 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1530 } else {
1531 debugging('Can not create directory: '.$dir, DEBUG_DEVELOPER);
1532 return false;
1538 if (!is_writable($dir)) {
1539 if ($exceptiononerror) {
1540 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1541 } else {
1542 return false;
1546 return $dir;
1550 * Protect a directory from web access.
1551 * Could be extended in the future to support other mechanisms (e.g. other webservers).
1553 * @private
1554 * @param string $dir the full path of the directory to be protected
1556 function protect_directory($dir) {
1557 global $CFG;
1558 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1559 if (!file_exists("$dir/.htaccess")) {
1560 if ($handle = fopen("$dir/.htaccess", 'w')) { // For safety
1561 @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");
1562 @fclose($handle);
1563 @chmod("$dir/.htaccess", $CFG->filepermissions);
1569 * Create a directory under dataroot and make sure it is writable.
1570 * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
1572 * @param string $directory the full path of the directory to be created under $CFG->dataroot
1573 * @param bool $exceptiononerror throw exception if error encountered
1574 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1576 function make_upload_directory($directory, $exceptiononerror = true) {
1577 global $CFG;
1579 if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1580 debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1582 } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
1583 debugging('Use make_cache_directory() for creation of cache directory and $CFG->cachedir to get the location.');
1585 } else if (strpos($directory, 'localcache/') === 0 or $directory === 'localcache') {
1586 debugging('Use make_localcache_directory() for creation of local cache directory and $CFG->localcachedir to get the location.');
1589 protect_directory($CFG->dataroot);
1590 return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1594 * Get a per-request storage directory in the tempdir.
1596 * The directory is automatically cleaned up during the shutdown handler.
1598 * @param bool $exceptiononerror throw exception if error encountered
1599 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1601 function get_request_storage_directory($exceptiononerror = true) {
1602 global $CFG;
1604 static $requestdir = null;
1606 if (!$requestdir || !file_exists($requestdir) || !is_dir($requestdir) || !is_writable($requestdir)) {
1607 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1608 check_dir_exists($CFG->localcachedir, true, true);
1609 protect_directory($CFG->localcachedir);
1610 } else {
1611 protect_directory($CFG->dataroot);
1614 if ($requestdir = make_unique_writable_directory($CFG->localcachedir, $exceptiononerror)) {
1615 // Register a shutdown handler to remove the directory.
1616 \core_shutdown_manager::register_function('remove_dir', array($requestdir));
1620 return $requestdir;
1624 * Create a per-request directory and make sure it is writable.
1625 * This can only be used during the current request and will be tidied away
1626 * automatically afterwards.
1628 * A new, unique directory is always created within the current request directory.
1630 * @param bool $exceptiononerror throw exception if error encountered
1631 * @return string full path to directory if successful, false if not; may throw exception
1633 function make_request_directory($exceptiononerror = true) {
1634 $basedir = get_request_storage_directory($exceptiononerror);
1635 return make_unique_writable_directory($basedir, $exceptiononerror);
1639 * Create a directory under tempdir and make sure it is writable.
1641 * Where possible, please use make_request_directory() and limit the scope
1642 * of your data to the current HTTP request.
1644 * Do not use for storing cache files - see make_cache_directory(), and
1645 * make_localcache_directory() instead for this purpose.
1647 * Temporary files must be on a shared storage, and heavy usage is
1648 * discouraged due to the performance impact upon clustered environments.
1650 * @param string $directory the full path of the directory to be created under $CFG->tempdir
1651 * @param bool $exceptiononerror throw exception if error encountered
1652 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1654 function make_temp_directory($directory, $exceptiononerror = true) {
1655 global $CFG;
1656 if ($CFG->tempdir !== "$CFG->dataroot/temp") {
1657 check_dir_exists($CFG->tempdir, true, true);
1658 protect_directory($CFG->tempdir);
1659 } else {
1660 protect_directory($CFG->dataroot);
1662 return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1666 * Create a directory under cachedir and make sure it is writable.
1668 * Note: this cache directory is shared by all cluster nodes.
1670 * @param string $directory the full path of the directory to be created under $CFG->cachedir
1671 * @param bool $exceptiononerror throw exception if error encountered
1672 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1674 function make_cache_directory($directory, $exceptiononerror = true) {
1675 global $CFG;
1676 if ($CFG->cachedir !== "$CFG->dataroot/cache") {
1677 check_dir_exists($CFG->cachedir, true, true);
1678 protect_directory($CFG->cachedir);
1679 } else {
1680 protect_directory($CFG->dataroot);
1682 return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1686 * Create a directory under localcachedir and make sure it is writable.
1687 * The files in this directory MUST NOT change, use revisions or content hashes to
1688 * work around this limitation - this means you can only add new files here.
1690 * The content of this directory gets purged automatically on all cluster nodes
1691 * after calling purge_all_caches() before new data is written to this directory.
1693 * Note: this local cache directory does not need to be shared by cluster nodes.
1695 * @param string $directory the relative path of the directory to be created under $CFG->localcachedir
1696 * @param bool $exceptiononerror throw exception if error encountered
1697 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1699 function make_localcache_directory($directory, $exceptiononerror = true) {
1700 global $CFG;
1702 make_writable_directory($CFG->localcachedir, $exceptiononerror);
1704 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1705 protect_directory($CFG->localcachedir);
1706 } else {
1707 protect_directory($CFG->dataroot);
1710 if (!isset($CFG->localcachedirpurged)) {
1711 $CFG->localcachedirpurged = 0;
1713 $timestampfile = "$CFG->localcachedir/.lastpurged";
1715 if (!file_exists($timestampfile)) {
1716 touch($timestampfile);
1717 @chmod($timestampfile, $CFG->filepermissions);
1719 } else if (filemtime($timestampfile) < $CFG->localcachedirpurged) {
1720 // This means our local cached dir was not purged yet.
1721 remove_dir($CFG->localcachedir, true);
1722 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1723 protect_directory($CFG->localcachedir);
1725 touch($timestampfile);
1726 @chmod($timestampfile, $CFG->filepermissions);
1727 clearstatcache();
1730 if ($directory === '') {
1731 return $CFG->localcachedir;
1734 return make_writable_directory("$CFG->localcachedir/$directory", $exceptiononerror);
1738 * This class solves the problem of how to initialise $OUTPUT.
1740 * The problem is caused be two factors
1741 * <ol>
1742 * <li>On the one hand, we cannot be sure when output will start. In particular,
1743 * an error, which needs to be displayed, could be thrown at any time.</li>
1744 * <li>On the other hand, we cannot be sure when we will have all the information
1745 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1746 * (potentially) depends on the current course, course categories, and logged in user.
1747 * It also depends on whether the current page requires HTTPS.</li>
1748 * </ol>
1750 * So, it is hard to find a single natural place during Moodle script execution,
1751 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1752 * adopt the following strategy
1753 * <ol>
1754 * <li>We will initialise $OUTPUT the first time it is used.</li>
1755 * <li>If, after $OUTPUT has been initialised, the script tries to change something
1756 * that $OUTPUT depends on, we throw an exception making it clear that the script
1757 * did something wrong.
1758 * </ol>
1760 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1761 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1762 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1763 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1765 * Note that this class is used before lib/outputlib.php has been loaded, so we
1766 * must be careful referring to classes/functions from there, they may not be
1767 * defined yet, and we must avoid fatal errors.
1769 * @copyright 2009 Tim Hunt
1770 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1771 * @since Moodle 2.0
1773 class bootstrap_renderer {
1775 * Handles re-entrancy. Without this, errors or debugging output that occur
1776 * during the initialisation of $OUTPUT, cause infinite recursion.
1777 * @var boolean
1779 protected $initialising = false;
1782 * Have we started output yet?
1783 * @return boolean true if the header has been printed.
1785 public function has_started() {
1786 return false;
1790 * Constructor - to be used by core code only.
1791 * @param string $method The method to call
1792 * @param array $arguments Arguments to pass to the method being called
1793 * @return string
1795 public function __call($method, $arguments) {
1796 global $OUTPUT, $PAGE;
1798 $recursing = false;
1799 if ($method == 'notification') {
1800 // Catch infinite recursion caused by debugging output during print_header.
1801 $backtrace = debug_backtrace();
1802 array_shift($backtrace);
1803 array_shift($backtrace);
1804 $recursing = is_early_init($backtrace);
1807 $earlymethods = array(
1808 'fatal_error' => 'early_error',
1809 'notification' => 'early_notification',
1812 // If lib/outputlib.php has been loaded, call it.
1813 if (!empty($PAGE) && !$recursing) {
1814 if (array_key_exists($method, $earlymethods)) {
1815 //prevent PAGE->context warnings - exceptions might appear before we set any context
1816 $PAGE->set_context(null);
1818 $PAGE->initialise_theme_and_output();
1819 return call_user_func_array(array($OUTPUT, $method), $arguments);
1822 $this->initialising = true;
1824 // Too soon to initialise $OUTPUT, provide a couple of key methods.
1825 if (array_key_exists($method, $earlymethods)) {
1826 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1829 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1833 * Returns nicely formatted error message in a div box.
1834 * @static
1835 * @param string $message error message
1836 * @param string $moreinfourl (ignored in early errors)
1837 * @param string $link (ignored in early errors)
1838 * @param array $backtrace
1839 * @param string $debuginfo
1840 * @return string
1842 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1843 global $CFG;
1845 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1846 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1847 width: 80%; -moz-border-radius: 20px; padding: 15px">
1848 ' . $message . '
1849 </div>';
1850 // Check whether debug is set.
1851 $debug = (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER);
1852 // Also check we have it set in the config file. This occurs if the method to read the config table from the
1853 // database fails, reading from the config table is the first database interaction we have.
1854 $debug = $debug || (!empty($CFG->config_php_settings['debug']) && $CFG->config_php_settings['debug'] >= DEBUG_DEVELOPER );
1855 if ($debug) {
1856 if (!empty($debuginfo)) {
1857 $debuginfo = s($debuginfo); // removes all nasty JS
1858 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1859 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
1861 if (!empty($backtrace)) {
1862 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1866 return $content;
1870 * This function should only be called by this class, or from exception handlers
1871 * @static
1872 * @param string $message error message
1873 * @param string $moreinfourl (ignored in early errors)
1874 * @param string $link (ignored in early errors)
1875 * @param array $backtrace
1876 * @param string $debuginfo extra information for developers
1877 * @return string
1879 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = null) {
1880 global $CFG;
1882 if (CLI_SCRIPT) {
1883 echo "!!! $message !!!\n";
1884 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1885 if (!empty($debuginfo)) {
1886 echo "\nDebug info: $debuginfo";
1888 if (!empty($backtrace)) {
1889 echo "\nStack trace: " . format_backtrace($backtrace, true);
1892 return;
1894 } else if (AJAX_SCRIPT) {
1895 $e = new stdClass();
1896 $e->error = $message;
1897 $e->stacktrace = NULL;
1898 $e->debuginfo = NULL;
1899 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1900 if (!empty($debuginfo)) {
1901 $e->debuginfo = $debuginfo;
1903 if (!empty($backtrace)) {
1904 $e->stacktrace = format_backtrace($backtrace, true);
1907 $e->errorcode = $errorcode;
1908 @header('Content-Type: application/json; charset=utf-8');
1909 echo json_encode($e);
1910 return;
1913 // In the name of protocol correctness, monitoring and performance
1914 // profiling, set the appropriate error headers for machine consumption.
1915 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
1916 @header($protocol . ' 503 Service Unavailable');
1918 // better disable any caching
1919 @header('Content-Type: text/html; charset=utf-8');
1920 @header('X-UA-Compatible: IE=edge');
1921 @header('Cache-Control: no-store, no-cache, must-revalidate');
1922 @header('Cache-Control: post-check=0, pre-check=0', false);
1923 @header('Pragma: no-cache');
1924 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1925 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1927 if (function_exists('get_string')) {
1928 $strerror = get_string('error');
1929 } else {
1930 $strerror = 'Error';
1933 $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
1935 return self::plain_page($strerror, $content);
1939 * Early notification message
1940 * @static
1941 * @param string $message
1942 * @param string $classes usually notifyproblem or notifysuccess
1943 * @return string
1945 public static function early_notification($message, $classes = 'notifyproblem') {
1946 return '<div class="' . $classes . '">' . $message . '</div>';
1950 * Page should redirect message.
1951 * @static
1952 * @param string $encodedurl redirect url
1953 * @return string
1955 public static function plain_redirect_message($encodedurl) {
1956 $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
1957 $encodedurl .'">'. get_string('continue') .'</a></div>';
1958 return self::plain_page(get_string('redirect'), $message);
1962 * Early redirection page, used before full init of $PAGE global
1963 * @static
1964 * @param string $encodedurl redirect url
1965 * @param string $message redirect message
1966 * @param int $delay time in seconds
1967 * @return string redirect page
1969 public static function early_redirect_message($encodedurl, $message, $delay) {
1970 $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
1971 $content = self::early_error_content($message, null, null, null);
1972 $content .= self::plain_redirect_message($encodedurl);
1974 return self::plain_page(get_string('redirect'), $content, $meta);
1978 * Output basic html page.
1979 * @static
1980 * @param string $title page title
1981 * @param string $content page content
1982 * @param string $meta meta tag
1983 * @return string html page
1985 public static function plain_page($title, $content, $meta = '') {
1986 if (function_exists('get_string') && function_exists('get_html_lang')) {
1987 $htmllang = get_html_lang();
1988 } else {
1989 $htmllang = '';
1992 $footer = '';
1993 if (MDL_PERF_TEST) {
1994 $perfinfo = get_performance_info();
1995 $footer = '<footer>' . $perfinfo['html'] . '</footer>';
1998 return '<!DOCTYPE html>
1999 <html ' . $htmllang . '>
2000 <head>
2001 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
2002 '.$meta.'
2003 <title>' . $title . '</title>
2004 </head><body>' . $content . $footer . '</body></html>';