MDL-61502 questions: add filter tests to gapselect question type.
[moodle.git] / lib / setuplib.php
blobed7775ba680875ba0dce5350da308b7c00ea388a
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 {
67 /**
68 * Constructor.
70 public function __construct() {
71 debugging("'object' class has been deprecated, please use stdClass instead.", DEBUG_DEVELOPER);
75 /**
76 * Base Moodle Exception class
78 * Although this class is defined here, you cannot throw a moodle_exception until
79 * after moodlelib.php has been included (which will happen very soon).
81 * @package core
82 * @subpackage lib
83 * @copyright 2008 Petr Skoda {@link http://skodak.org}
84 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
86 class moodle_exception extends Exception {
88 /**
89 * @var string The name of the string from error.php to print
91 public $errorcode;
93 /**
94 * @var string The name of module
96 public $module;
98 /**
99 * @var mixed Extra words and phrases that might be required in the error string
101 public $a;
104 * @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.
106 public $link;
109 * @var string Optional information to aid the debugging process
111 public $debuginfo;
114 * Constructor
115 * @param string $errorcode The name of the string from error.php to print
116 * @param string $module name of module
117 * @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.
118 * @param mixed $a Extra words and phrases that might be required in the error string
119 * @param string $debuginfo optional debugging information
121 function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
122 if (empty($module) || $module == 'moodle' || $module == 'core') {
123 $module = 'error';
126 $this->errorcode = $errorcode;
127 $this->module = $module;
128 $this->link = $link;
129 $this->a = $a;
130 $this->debuginfo = is_null($debuginfo) ? null : (string)$debuginfo;
132 if (get_string_manager()->string_exists($errorcode, $module)) {
133 $message = get_string($errorcode, $module, $a);
134 $haserrorstring = true;
135 } else {
136 $message = $module . '/' . $errorcode;
137 $haserrorstring = false;
140 if (defined('PHPUNIT_TEST') and PHPUNIT_TEST and $debuginfo) {
141 $message = "$message ($debuginfo)";
144 if (!$haserrorstring and defined('PHPUNIT_TEST') and PHPUNIT_TEST) {
145 // Append the contents of $a to $debuginfo so helpful information isn't lost.
146 // This emulates what {@link get_exception_info()} does. Unfortunately that
147 // function is not used by phpunit.
148 $message .= PHP_EOL.'$a contents: '.print_r($a, true);
151 parent::__construct($message, 0);
156 * Course/activity access exception.
158 * This exception is thrown from require_login()
160 * @package core_access
161 * @copyright 2010 Petr Skoda {@link http://skodak.org}
162 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
164 class require_login_exception extends moodle_exception {
166 * Constructor
167 * @param string $debuginfo Information to aid the debugging process
169 function __construct($debuginfo) {
170 parent::__construct('requireloginerror', 'error', '', NULL, $debuginfo);
175 * Session timeout exception.
177 * This exception is thrown from require_login()
179 * @package core_access
180 * @copyright 2015 Andrew Nicols <andrew@nicols.co.uk>
181 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
183 class require_login_session_timeout_exception extends require_login_exception {
185 * Constructor
187 public function __construct() {
188 moodle_exception::__construct('sessionerroruser', 'error');
193 * Web service parameter exception class
194 * @deprecated since Moodle 2.2 - use moodle exception instead
195 * This exception must be thrown to the web service client when a web service parameter is invalid
196 * The error string is gotten from webservice.php
198 class webservice_parameter_exception extends moodle_exception {
200 * Constructor
201 * @param string $errorcode The name of the string from webservice.php to print
202 * @param string $a The name of the parameter
203 * @param string $debuginfo Optional information to aid debugging
205 function __construct($errorcode=null, $a = '', $debuginfo = null) {
206 parent::__construct($errorcode, 'webservice', '', $a, $debuginfo);
211 * Exceptions indicating user does not have permissions to do something
212 * and the execution can not continue.
214 * @package core_access
215 * @copyright 2009 Petr Skoda {@link http://skodak.org}
216 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
218 class required_capability_exception extends moodle_exception {
220 * Constructor
221 * @param context $context The context used for the capability check
222 * @param string $capability The required capability
223 * @param string $errormessage The error message to show the user
224 * @param string $stringfile
226 function __construct($context, $capability, $errormessage, $stringfile) {
227 $capabilityname = get_capability_string($capability);
228 if ($context->contextlevel == CONTEXT_MODULE and preg_match('/:view$/', $capability)) {
229 // 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
230 $parentcontext = $context->get_parent_context();
231 $link = $parentcontext->get_url();
232 } else {
233 $link = $context->get_url();
235 parent::__construct($errormessage, $stringfile, $link, $capabilityname);
240 * Exception indicating programming error, must be fixed by a programer. For example
241 * a core API might throw this type of exception if a plugin calls it incorrectly.
243 * @package core
244 * @subpackage lib
245 * @copyright 2008 Petr Skoda {@link http://skodak.org}
246 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
248 class coding_exception extends moodle_exception {
250 * Constructor
251 * @param string $hint short description of problem
252 * @param string $debuginfo detailed information how to fix problem
254 function __construct($hint, $debuginfo=null) {
255 parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
260 * Exception indicating malformed parameter problem.
261 * This exception is not supposed to be thrown when processing
262 * user submitted data in forms. It is more suitable
263 * for WS and other low level stuff.
265 * @package core
266 * @subpackage lib
267 * @copyright 2009 Petr Skoda {@link http://skodak.org}
268 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
270 class invalid_parameter_exception extends moodle_exception {
272 * Constructor
273 * @param string $debuginfo some detailed information
275 function __construct($debuginfo=null) {
276 parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
281 * Exception indicating malformed response problem.
282 * This exception is not supposed to be thrown when processing
283 * user submitted data in forms. It is more suitable
284 * for WS and other low level stuff.
286 class invalid_response_exception extends moodle_exception {
288 * Constructor
289 * @param string $debuginfo some detailed information
291 function __construct($debuginfo=null) {
292 parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
297 * An exception that indicates something really weird happened. For example,
298 * if you do switch ($context->contextlevel), and have one case for each
299 * CONTEXT_... constant. You might throw an invalid_state_exception in the
300 * default case, to just in case something really weird is going on, and
301 * $context->contextlevel is invalid - rather than ignoring this possibility.
303 * @package core
304 * @subpackage lib
305 * @copyright 2009 onwards Martin Dougiamas {@link http://moodle.com}
306 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
308 class invalid_state_exception extends moodle_exception {
310 * Constructor
311 * @param string $hint short description of problem
312 * @param string $debuginfo optional more detailed information
314 function __construct($hint, $debuginfo=null) {
315 parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
320 * An exception that indicates incorrect permissions in $CFG->dataroot
322 * @package core
323 * @subpackage lib
324 * @copyright 2010 Petr Skoda {@link http://skodak.org}
325 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
327 class invalid_dataroot_permissions extends moodle_exception {
329 * Constructor
330 * @param string $debuginfo optional more detailed information
332 function __construct($debuginfo = NULL) {
333 parent::__construct('invaliddatarootpermissions', 'error', '', NULL, $debuginfo);
338 * An exception that indicates that file can not be served
340 * @package core
341 * @subpackage lib
342 * @copyright 2010 Petr Skoda {@link http://skodak.org}
343 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
345 class file_serving_exception extends moodle_exception {
347 * Constructor
348 * @param string $debuginfo optional more detailed information
350 function __construct($debuginfo = NULL) {
351 parent::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
356 * Default exception handler.
358 * @param Exception $ex
359 * @return void -does not return. Terminates execution!
361 function default_exception_handler($ex) {
362 global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION, $PAGE;
364 // detect active db transactions, rollback and log as error
365 abort_all_db_transactions();
367 if (($ex instanceof required_capability_exception) && !CLI_SCRIPT && !AJAX_SCRIPT && !empty($CFG->autologinguests) && !empty($USER->autologinguest)) {
368 $SESSION->wantsurl = qualified_me();
369 redirect(get_login_url());
372 $info = get_exception_info($ex);
374 if (debugging('', DEBUG_MINIMAL)) {
375 $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
376 error_log($logerrmsg);
379 if (is_early_init($info->backtrace)) {
380 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
381 } else {
382 try {
383 if ($DB) {
384 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
385 $DB->set_debug(0);
387 if (AJAX_SCRIPT) {
388 // If we are in an AJAX script we don't want to use PREFERRED_RENDERER_TARGET.
389 // Because we know we will want to use ajax format.
390 $renderer = new core_renderer_ajax($PAGE, 'ajax');
391 } else {
392 $renderer = $OUTPUT;
394 echo $renderer->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo,
395 $info->errorcode);
396 } catch (Exception $e) {
397 $out_ex = $e;
398 } catch (Throwable $e) {
399 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
400 $out_ex = $e;
403 if (isset($out_ex)) {
404 // default exception handler MUST not throw any exceptions!!
405 // 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
406 // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
407 if (CLI_SCRIPT or AJAX_SCRIPT) {
408 // just ignore the error and send something back using the safest method
409 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
410 } else {
411 echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
412 $outinfo = get_exception_info($out_ex);
413 echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
418 exit(1); // General error code
422 * Default error handler, prevents some white screens.
423 * @param int $errno
424 * @param string $errstr
425 * @param string $errfile
426 * @param int $errline
427 * @param array $errcontext
428 * @return bool false means use default error handler
430 function default_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
431 if ($errno == 4096) {
432 //fatal catchable error
433 throw new coding_exception('PHP catchable fatal error', $errstr);
435 return false;
439 * Unconditionally abort all database transactions, this function
440 * should be called from exception handlers only.
441 * @return void
443 function abort_all_db_transactions() {
444 global $CFG, $DB, $SCRIPT;
446 // default exception handler MUST not throw any exceptions!!
448 if ($DB && $DB->is_transaction_started()) {
449 error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
450 // note: transaction blocks should never change current $_SESSION
451 $DB->force_transaction_rollback();
456 * This function encapsulates the tests for whether an exception was thrown in
457 * early init -- either during setup.php or during init of $OUTPUT.
459 * If another exception is thrown then, and if we do not take special measures,
460 * we would just get a very cryptic message "Exception thrown without a stack
461 * frame in Unknown on line 0". That makes debugging very hard, so we do take
462 * special measures in default_exception_handler, with the help of this function.
464 * @param array $backtrace the stack trace to analyse.
465 * @return boolean whether the stack trace is somewhere in output initialisation.
467 function is_early_init($backtrace) {
468 $dangerouscode = array(
469 array('function' => 'header', 'type' => '->'),
470 array('class' => 'bootstrap_renderer'),
471 array('file' => __DIR__.'/setup.php'),
473 foreach ($backtrace as $stackframe) {
474 foreach ($dangerouscode as $pattern) {
475 $matches = true;
476 foreach ($pattern as $property => $value) {
477 if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
478 $matches = false;
481 if ($matches) {
482 return true;
486 return false;
490 * Abort execution by throwing of a general exception,
491 * default exception handler displays the error message in most cases.
493 * @param string $errorcode The name of the language string containing the error message.
494 * Normally this should be in the error.php lang file.
495 * @param string $module The language file to get the error message from.
496 * @param string $link The url where the user will be prompted to continue.
497 * If no url is provided the user will be directed to the site index page.
498 * @param object $a Extra words and phrases that might be required in the error string
499 * @param string $debuginfo optional debugging information
500 * @return void, always throws exception!
502 function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
503 throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
507 * Returns detailed information about specified exception.
508 * @param exception $ex
509 * @return object
511 function get_exception_info($ex) {
512 global $CFG, $DB, $SESSION;
514 if ($ex instanceof moodle_exception) {
515 $errorcode = $ex->errorcode;
516 $module = $ex->module;
517 $a = $ex->a;
518 $link = $ex->link;
519 $debuginfo = $ex->debuginfo;
520 } else {
521 $errorcode = 'generalexceptionmessage';
522 $module = 'error';
523 $a = $ex->getMessage();
524 $link = '';
525 $debuginfo = '';
528 // Append the error code to the debug info to make grepping and googling easier
529 $debuginfo .= PHP_EOL."Error code: $errorcode";
531 $backtrace = $ex->getTrace();
532 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
533 array_unshift($backtrace, $place);
535 // Be careful, no guarantee moodlelib.php is loaded.
536 if (empty($module) || $module == 'moodle' || $module == 'core') {
537 $module = 'error';
539 // Search for the $errorcode's associated string
540 // If not found, append the contents of $a to $debuginfo so helpful information isn't lost
541 if (function_exists('get_string_manager')) {
542 if (get_string_manager()->string_exists($errorcode, $module)) {
543 $message = get_string($errorcode, $module, $a);
544 } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
545 // Search in moodle file if error specified - needed for backwards compatibility
546 $message = get_string($errorcode, 'moodle', $a);
547 } else {
548 $message = $module . '/' . $errorcode;
549 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
551 } else {
552 $message = $module . '/' . $errorcode;
553 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
556 // Remove some absolute paths from message and debugging info.
557 $searches = array();
558 $replaces = array();
559 $cfgnames = array('tempdir', 'cachedir', 'localcachedir', 'themedir', 'dataroot', 'dirroot');
560 foreach ($cfgnames as $cfgname) {
561 if (property_exists($CFG, $cfgname)) {
562 $searches[] = $CFG->$cfgname;
563 $replaces[] = "[$cfgname]";
566 if (!empty($searches)) {
567 $message = str_replace($searches, $replaces, $message);
568 $debuginfo = str_replace($searches, $replaces, $debuginfo);
571 // Be careful, no guarantee weblib.php is loaded.
572 if (function_exists('clean_text')) {
573 $message = clean_text($message);
574 } else {
575 $message = htmlspecialchars($message);
578 if (!empty($CFG->errordocroot)) {
579 $errordoclink = $CFG->errordocroot . '/en/';
580 } else {
581 $errordoclink = get_docs_url();
584 if ($module === 'error') {
585 $modulelink = 'moodle';
586 } else {
587 $modulelink = $module;
589 $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
591 if (empty($link)) {
592 if (!empty($SESSION->fromurl)) {
593 $link = $SESSION->fromurl;
594 unset($SESSION->fromurl);
595 } else {
596 $link = $CFG->wwwroot .'/';
600 // When printing an error the continue button should never link offsite.
601 // We cannot use clean_param() here as it is not guaranteed that it has been loaded yet.
602 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
603 if (stripos($link, $CFG->wwwroot) === 0) {
604 // Internal HTTP, all good.
605 } else if (!empty($CFG->loginhttps) && stripos($link, $httpswwwroot) === 0) {
606 // Internal HTTPS, all good.
607 } else {
608 // External link spotted!
609 $link = $CFG->wwwroot . '/';
612 $info = new stdClass();
613 $info->message = $message;
614 $info->errorcode = $errorcode;
615 $info->backtrace = $backtrace;
616 $info->link = $link;
617 $info->moreinfourl = $moreinfourl;
618 $info->a = $a;
619 $info->debuginfo = $debuginfo;
621 return $info;
625 * Generate a uuid.
627 * Unique is hard. Very hard. Attempt to use the PECL UUID functions if available, and if not then revert to
628 * constructing the uuid using mt_rand.
630 * It is important that this token is not solely based on time as this could lead
631 * to duplicates in a clustered environment (especially on VMs due to poor time precision).
633 * @return string The uuid.
635 function generate_uuid() {
636 $uuid = '';
638 if (function_exists("uuid_create")) {
639 $context = null;
640 uuid_create($context);
642 uuid_make($context, UUID_MAKE_V4);
643 uuid_export($context, UUID_FMT_STR, $uuid);
644 } else {
645 // Fallback uuid generation based on:
646 // "http://www.php.net/manual/en/function.uniqid.php#94959".
647 $uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
649 // 32 bits for "time_low".
650 mt_rand(0, 0xffff), mt_rand(0, 0xffff),
652 // 16 bits for "time_mid".
653 mt_rand(0, 0xffff),
655 // 16 bits for "time_hi_and_version",
656 // four most significant bits holds version number 4.
657 mt_rand(0, 0x0fff) | 0x4000,
659 // 16 bits, 8 bits for "clk_seq_hi_res",
660 // 8 bits for "clk_seq_low",
661 // two most significant bits holds zero and one for variant DCE1.1.
662 mt_rand(0, 0x3fff) | 0x8000,
664 // 48 bits for "node".
665 mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
667 return trim($uuid);
671 * Returns the Moodle Docs URL in the users language for a given 'More help' link.
673 * There are three cases:
675 * 1. In the normal case, $path will be a short relative path 'component/thing',
676 * like 'mod/folder/view' 'group/import'. This gets turned into an link to
677 * MoodleDocs in the user's language, and for the appropriate Moodle version.
678 * E.g. 'group/import' may become 'http://docs.moodle.org/2x/en/group/import'.
679 * The 'http://docs.moodle.org' bit comes from $CFG->docroot.
681 * This is the only option that should be used in standard Moodle code. The other
682 * two options have been implemented because they are useful for third-party plugins.
684 * 2. $path may be an absolute URL, starting http:// or https://. In this case,
685 * the link is used as is.
687 * 3. $path may start %%WWWROOT%%, in which case that is replaced by
688 * $CFG->wwwroot to make the link.
690 * @param string $path the place to link to. See above for details.
691 * @return string The MoodleDocs URL in the user's language. for example @link http://docs.moodle.org/2x/en/$path}
693 function get_docs_url($path = null) {
694 global $CFG;
696 // Absolute URLs are used unmodified.
697 if (substr($path, 0, 7) === 'http://' || substr($path, 0, 8) === 'https://') {
698 return $path;
701 // Paths starting %%WWWROOT%% have that replaced by $CFG->wwwroot.
702 if (substr($path, 0, 11) === '%%WWWROOT%%') {
703 return $CFG->wwwroot . substr($path, 11);
706 // Otherwise we do the normal case, and construct a MoodleDocs URL relative to $CFG->docroot.
708 // Check that $CFG->branch has been set up, during installation it won't be.
709 if (empty($CFG->branch)) {
710 // It's not there yet so look at version.php.
711 include($CFG->dirroot.'/version.php');
712 } else {
713 // We can use $CFG->branch and avoid having to include version.php.
714 $branch = $CFG->branch;
716 // ensure branch is valid.
717 if (!$branch) {
718 // We should never get here but in case we do lets set $branch to .
719 // the smart one's will know that this is the current directory
720 // and the smarter ones will know that there is some smart matching
721 // that will ensure people end up at the latest version of the docs.
722 $branch = '.';
724 if (empty($CFG->doclang)) {
725 $lang = current_language();
726 } else {
727 $lang = $CFG->doclang;
729 $end = '/' . $branch . '/' . $lang . '/' . $path;
730 if (empty($CFG->docroot)) {
731 return 'http://docs.moodle.org'. $end;
732 } else {
733 return $CFG->docroot . $end ;
738 * Formats a backtrace ready for output.
740 * This function does not include function arguments because they could contain sensitive information
741 * not suitable to be exposed in a response.
743 * @param array $callers backtrace array, as returned by debug_backtrace().
744 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
745 * @return string formatted backtrace, ready for output.
747 function format_backtrace($callers, $plaintext = false) {
748 // do not use $CFG->dirroot because it might not be available in destructors
749 $dirroot = dirname(__DIR__);
751 if (empty($callers)) {
752 return '';
755 $from = $plaintext ? '' : '<ul style="text-align: left" data-rel="backtrace">';
756 foreach ($callers as $caller) {
757 if (!isset($caller['line'])) {
758 $caller['line'] = '?'; // probably call_user_func()
760 if (!isset($caller['file'])) {
761 $caller['file'] = 'unknownfile'; // probably call_user_func()
763 $from .= $plaintext ? '* ' : '<li>';
764 $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
765 if (isset($caller['function'])) {
766 $from .= ': call to ';
767 if (isset($caller['class'])) {
768 $from .= $caller['class'] . $caller['type'];
770 $from .= $caller['function'] . '()';
771 } else if (isset($caller['exception'])) {
772 $from .= ': '.$caller['exception'].' thrown';
774 $from .= $plaintext ? "\n" : '</li>';
776 $from .= $plaintext ? '' : '</ul>';
778 return $from;
782 * This function makes the return value of ini_get consistent if you are
783 * setting server directives through the .htaccess file in apache.
785 * Current behavior for value set from php.ini On = 1, Off = [blank]
786 * Current behavior for value set from .htaccess On = On, Off = Off
787 * Contributed by jdell @ unr.edu
789 * @param string $ini_get_arg The argument to get
790 * @return bool True for on false for not
792 function ini_get_bool($ini_get_arg) {
793 $temp = ini_get($ini_get_arg);
795 if ($temp == '1' or strtolower($temp) == 'on') {
796 return true;
798 return false;
802 * This function verifies the sanity of PHP configuration
803 * and stops execution if anything critical found.
805 function setup_validate_php_configuration() {
806 // this must be very fast - no slow checks here!!!
808 if (ini_get_bool('session.auto_start')) {
809 print_error('sessionautostartwarning', 'admin');
814 * Initialise global $CFG variable.
815 * @private to be used only from lib/setup.php
817 function initialise_cfg() {
818 global $CFG, $DB;
820 if (!$DB) {
821 // This should not happen.
822 return;
825 try {
826 $localcfg = get_config('core');
827 } catch (dml_exception $e) {
828 // Most probably empty db, going to install soon.
829 return;
832 foreach ($localcfg as $name => $value) {
833 // Note that get_config() keeps forced settings
834 // and normalises values to string if possible.
835 $CFG->{$name} = $value;
840 * Initialises $FULLME and friends. Private function. Should only be called from
841 * setup.php.
843 function initialise_fullme() {
844 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
846 // Detect common config error.
847 if (substr($CFG->wwwroot, -1) == '/') {
848 print_error('wwwrootslash', 'error');
851 if (CLI_SCRIPT) {
852 initialise_fullme_cli();
853 return;
856 $rurl = setup_get_remote_url();
857 $wwwroot = parse_url($CFG->wwwroot.'/');
859 if (empty($rurl['host'])) {
860 // missing host in request header, probably not a real browser, let's ignore them
862 } else if (!empty($CFG->reverseproxy)) {
863 // $CFG->reverseproxy specifies if reverse proxy server used
864 // Used in load balancing scenarios.
865 // Do not abuse this to try to solve lan/wan access problems!!!!!
867 } else {
868 if (($rurl['host'] !== $wwwroot['host']) or
869 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port']) or
870 (strpos($rurl['path'], $wwwroot['path']) !== 0)) {
872 // Explain the problem and redirect them to the right URL
873 if (!defined('NO_MOODLE_COOKIES')) {
874 define('NO_MOODLE_COOKIES', true);
876 // The login/token.php script should call the correct url/port.
877 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
878 $wwwrootport = empty($wwwroot['port'])?'':$wwwroot['port'];
879 $calledurl = $rurl['host'];
880 if (!empty($rurl['port'])) {
881 $calledurl .= ':'. $rurl['port'];
883 $correcturl = $wwwroot['host'];
884 if (!empty($wwwrootport)) {
885 $correcturl .= ':'. $wwwrootport;
887 throw new moodle_exception('requirecorrectaccess', 'error', '', null,
888 'You called ' . $calledurl .', you should have called ' . $correcturl);
890 redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
894 // Check that URL is under $CFG->wwwroot.
895 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
896 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
897 } else {
898 // Probably some weird external script
899 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
900 return;
903 // $CFG->sslproxy specifies if external SSL appliance is used
904 // (That is, the Moodle server uses http, with an external box translating everything to https).
905 if (empty($CFG->sslproxy)) {
906 if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
907 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
908 print_error('sslonlyaccess', 'error');
909 } else {
910 redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
913 } else {
914 if ($wwwroot['scheme'] !== 'https') {
915 throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
917 $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
918 $_SERVER['HTTPS'] = 'on'; // Override $_SERVER to help external libraries with their HTTPS detection.
919 $_SERVER['SERVER_PORT'] = 443; // Assume default ssl port for the proxy.
922 // hopefully this will stop all those "clever" admins trying to set up moodle
923 // with two different addresses in intranet and Internet
924 if (!empty($CFG->reverseproxy) && $rurl['host'] === $wwwroot['host']) {
925 print_error('reverseproxyabused', 'error');
928 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
929 if (!empty($wwwroot['port'])) {
930 $hostandport .= ':'.$wwwroot['port'];
933 $FULLSCRIPT = $hostandport . $rurl['path'];
934 $FULLME = $hostandport . $rurl['fullpath'];
935 $ME = $rurl['fullpath'];
939 * Initialises $FULLME and friends for command line scripts.
940 * This is a private method for use by initialise_fullme.
942 function initialise_fullme_cli() {
943 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
945 // Urls do not make much sense in CLI scripts
946 $backtrace = debug_backtrace();
947 $topfile = array_pop($backtrace);
948 $topfile = realpath($topfile['file']);
949 $dirroot = realpath($CFG->dirroot);
951 if (strpos($topfile, $dirroot) !== 0) {
952 // Probably some weird external script
953 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
954 } else {
955 $relativefile = substr($topfile, strlen($dirroot));
956 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
957 $SCRIPT = $FULLSCRIPT = $relativefile;
958 $FULLME = $ME = null;
963 * Get the URL that PHP/the web server thinks it is serving. Private function
964 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
965 * @return array in the same format that parse_url returns, with the addition of
966 * a 'fullpath' element, which includes any slasharguments path.
968 function setup_get_remote_url() {
969 $rurl = array();
970 if (isset($_SERVER['HTTP_HOST'])) {
971 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
972 } else {
973 $rurl['host'] = null;
975 $rurl['port'] = $_SERVER['SERVER_PORT'];
976 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
977 $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ? 'http' : 'https';
979 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
980 //Apache server
981 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
983 // Fixing a known issue with:
984 // - Apache versions lesser than 2.4.11
985 // - PHP deployed in Apache as PHP-FPM via mod_proxy_fcgi
986 // - PHP versions lesser than 5.6.3 and 5.5.18.
987 if (isset($_SERVER['PATH_INFO']) && (php_sapi_name() === 'fpm-fcgi') && isset($_SERVER['SCRIPT_NAME'])) {
988 $pathinfodec = rawurldecode($_SERVER['PATH_INFO']);
989 $lenneedle = strlen($pathinfodec);
990 // Checks whether SCRIPT_NAME ends with PATH_INFO, URL-decoded.
991 if (substr($_SERVER['SCRIPT_NAME'], -$lenneedle) === $pathinfodec) {
992 // This is the "Apache 2.4.10- running PHP-FPM via mod_proxy_fcgi" fingerprint,
993 // 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)
994 // => SCRIPT_NAME contains 'slash arguments' data too, which is wrongly exposed via PATH_INFO as URL-encoded.
995 // Fix both $_SERVER['PATH_INFO'] and $_SERVER['SCRIPT_NAME'].
996 $lenhaystack = strlen($_SERVER['SCRIPT_NAME']);
997 $pos = $lenhaystack - $lenneedle;
998 // Here $pos is greater than 0 but let's double check it.
999 if ($pos > 0) {
1000 $_SERVER['PATH_INFO'] = $pathinfodec;
1001 $_SERVER['SCRIPT_NAME'] = substr($_SERVER['SCRIPT_NAME'], 0, $pos);
1006 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
1007 //IIS - needs a lot of tweaking to make it work
1008 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
1010 // NOTE: we should ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS.
1011 // Since 2.0, we rely on IIS rewrite extensions like Helicon ISAPI_rewrite
1012 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
1013 // OR
1014 // we rely on a proper IIS 6.0+ configuration: the 'FastCGIUtf8ServerVariables' registry key.
1015 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
1016 // Check that PATH_INFO works == must not contain the script name.
1017 if (strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === false) {
1018 $rurl['fullpath'] .= clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
1022 if (isset($_SERVER['QUERY_STRING']) and $_SERVER['QUERY_STRING'] !== '') {
1023 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
1025 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
1027 /* NOTE: following servers are not fully tested! */
1029 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
1030 //lighttpd - not officially supported
1031 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1033 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
1034 //nginx - not officially supported
1035 if (!isset($_SERVER['SCRIPT_NAME'])) {
1036 die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
1038 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1040 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
1041 //cherokee - not officially supported
1042 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1044 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
1045 //zeus - not officially supported
1046 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1048 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
1049 //LiteSpeed - not officially supported
1050 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1052 } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
1053 //obscure name found on some servers - this is definitely not supported
1054 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1056 } else if (strpos($_SERVER['SERVER_SOFTWARE'], 'PHP') === 0) {
1057 // built-in PHP Development Server
1058 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
1060 } else {
1061 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
1064 // sanitize the url a bit more, the encoding style may be different in vars above
1065 $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
1066 $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);
1068 return $rurl;
1072 * Try to work around the 'max_input_vars' restriction if necessary.
1074 function workaround_max_input_vars() {
1075 // Make sure this gets executed only once from lib/setup.php!
1076 static $executed = false;
1077 if ($executed) {
1078 debugging('workaround_max_input_vars() must be called only once!');
1079 return;
1081 $executed = true;
1083 if (!isset($_SERVER["CONTENT_TYPE"]) or strpos($_SERVER["CONTENT_TYPE"], 'multipart/form-data') !== false) {
1084 // Not a post or 'multipart/form-data' which is not compatible with "php://input" reading.
1085 return;
1088 if (!isloggedin() or isguestuser()) {
1089 // Only real users post huge forms.
1090 return;
1093 $max = (int)ini_get('max_input_vars');
1095 if ($max <= 0) {
1096 // Most probably PHP < 5.3.9 that does not implement this limit.
1097 return;
1100 if ($max >= 200000) {
1101 // This value should be ok for all our forms, by setting it in php.ini
1102 // admins may prevent any unexpected regressions caused by this hack.
1104 // Note there is no need to worry about DDoS caused by making this limit very high
1105 // because there are very many easier ways to DDoS any Moodle server.
1106 return;
1109 // Worst case is advanced checkboxes which use up to two max_input_vars
1110 // slots for each entry in $_POST, because of sending two fields with the
1111 // same name. So count everything twice just in case.
1112 if (count($_POST, COUNT_RECURSIVE) * 2 < $max) {
1113 return;
1116 // Large POST request with enctype supported by php://input.
1117 // Parse php://input in chunks to bypass max_input_vars limit, which also applies to parse_str().
1118 $str = file_get_contents("php://input");
1119 if ($str === false or $str === '') {
1120 // Some weird error.
1121 return;
1124 $delim = '&';
1125 $fun = create_function('$p', 'return implode("'.$delim.'", $p);');
1126 $chunks = array_map($fun, array_chunk(explode($delim, $str), $max));
1128 // Clear everything from existing $_POST array, otherwise it might be included
1129 // twice (this affects array params primarily).
1130 foreach ($_POST as $key => $value) {
1131 unset($_POST[$key]);
1132 // Also clear from request array - but only the things that are in $_POST,
1133 // that way it will leave the things from a get request if any.
1134 unset($_REQUEST[$key]);
1137 foreach ($chunks as $chunk) {
1138 $values = array();
1139 parse_str($chunk, $values);
1141 merge_query_params($_POST, $values);
1142 merge_query_params($_REQUEST, $values);
1147 * Merge parsed POST chunks.
1149 * NOTE: this is not perfect, but it should work in most cases hopefully.
1151 * @param array $target
1152 * @param array $values
1154 function merge_query_params(array &$target, array $values) {
1155 if (isset($values[0]) and isset($target[0])) {
1156 // This looks like a split [] array, lets verify the keys are continuous starting with 0.
1157 $keys1 = array_keys($values);
1158 $keys2 = array_keys($target);
1159 if ($keys1 === array_keys($keys1) and $keys2 === array_keys($keys2)) {
1160 foreach ($values as $v) {
1161 $target[] = $v;
1163 return;
1166 foreach ($values as $k => $v) {
1167 if (!isset($target[$k])) {
1168 $target[$k] = $v;
1169 continue;
1171 if (is_array($target[$k]) and is_array($v)) {
1172 merge_query_params($target[$k], $v);
1173 continue;
1175 // We should not get here unless there are duplicates in params.
1176 $target[$k] = $v;
1181 * Initializes our performance info early.
1183 * Pairs up with get_performance_info() which is actually
1184 * in moodlelib.php. This function is here so that we can
1185 * call it before all the libs are pulled in.
1187 * @uses $PERF
1189 function init_performance_info() {
1191 global $PERF, $CFG, $USER;
1193 $PERF = new stdClass();
1194 $PERF->logwrites = 0;
1195 if (function_exists('microtime')) {
1196 $PERF->starttime = microtime();
1198 if (function_exists('memory_get_usage')) {
1199 $PERF->startmemory = memory_get_usage();
1201 if (function_exists('posix_times')) {
1202 $PERF->startposixtimes = posix_times();
1207 * Indicates whether we are in the middle of the initial Moodle install.
1209 * Very occasionally it is necessary avoid running certain bits of code before the
1210 * Moodle installation has completed. The installed flag is set in admin/index.php
1211 * after Moodle core and all the plugins have been installed, but just before
1212 * the person doing the initial install is asked to choose the admin password.
1214 * @return boolean true if the initial install is not complete.
1216 function during_initial_install() {
1217 global $CFG;
1218 return empty($CFG->rolesactive);
1222 * Function to raise the memory limit to a new value.
1223 * Will respect the memory limit if it is higher, thus allowing
1224 * settings in php.ini, apache conf or command line switches
1225 * to override it.
1227 * The memory limit should be expressed with a constant
1228 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
1229 * It is possible to use strings or integers too (eg:'128M').
1231 * @param mixed $newlimit the new memory limit
1232 * @return bool success
1234 function raise_memory_limit($newlimit) {
1235 global $CFG;
1237 if ($newlimit == MEMORY_UNLIMITED) {
1238 ini_set('memory_limit', -1);
1239 return true;
1241 } else if ($newlimit == MEMORY_STANDARD) {
1242 if (PHP_INT_SIZE > 4) {
1243 $newlimit = get_real_size('128M'); // 64bit needs more memory
1244 } else {
1245 $newlimit = get_real_size('96M');
1248 } else if ($newlimit == MEMORY_EXTRA) {
1249 if (PHP_INT_SIZE > 4) {
1250 $newlimit = get_real_size('384M'); // 64bit needs more memory
1251 } else {
1252 $newlimit = get_real_size('256M');
1254 if (!empty($CFG->extramemorylimit)) {
1255 $extra = get_real_size($CFG->extramemorylimit);
1256 if ($extra > $newlimit) {
1257 $newlimit = $extra;
1261 } else if ($newlimit == MEMORY_HUGE) {
1262 // MEMORY_HUGE uses 2G or MEMORY_EXTRA, whichever is bigger.
1263 $newlimit = get_real_size('2G');
1264 if (!empty($CFG->extramemorylimit)) {
1265 $extra = get_real_size($CFG->extramemorylimit);
1266 if ($extra > $newlimit) {
1267 $newlimit = $extra;
1271 } else {
1272 $newlimit = get_real_size($newlimit);
1275 if ($newlimit <= 0) {
1276 debugging('Invalid memory limit specified.');
1277 return false;
1280 $cur = ini_get('memory_limit');
1281 if (empty($cur)) {
1282 // if php is compiled without --enable-memory-limits
1283 // apparently memory_limit is set to ''
1284 $cur = 0;
1285 } else {
1286 if ($cur == -1){
1287 return true; // unlimited mem!
1289 $cur = get_real_size($cur);
1292 if ($newlimit > $cur) {
1293 ini_set('memory_limit', $newlimit);
1294 return true;
1296 return false;
1300 * Function to reduce the memory limit to a new value.
1301 * Will respect the memory limit if it is lower, thus allowing
1302 * settings in php.ini, apache conf or command line switches
1303 * to override it
1305 * The memory limit should be expressed with a string (eg:'64M')
1307 * @param string $newlimit the new memory limit
1308 * @return bool
1310 function reduce_memory_limit($newlimit) {
1311 if (empty($newlimit)) {
1312 return false;
1314 $cur = ini_get('memory_limit');
1315 if (empty($cur)) {
1316 // if php is compiled without --enable-memory-limits
1317 // apparently memory_limit is set to ''
1318 $cur = 0;
1319 } else {
1320 if ($cur == -1){
1321 return true; // unlimited mem!
1323 $cur = get_real_size($cur);
1326 $new = get_real_size($newlimit);
1327 // -1 is smaller, but it means unlimited
1328 if ($new < $cur && $new != -1) {
1329 ini_set('memory_limit', $newlimit);
1330 return true;
1332 return false;
1336 * Converts numbers like 10M into bytes.
1338 * @param string $size The size to be converted
1339 * @return int
1341 function get_real_size($size = 0) {
1342 if (!$size) {
1343 return 0;
1346 static $binaryprefixes = array(
1347 'K' => 1024,
1348 'k' => 1024,
1349 'M' => 1048576,
1350 'm' => 1048576,
1351 'G' => 1073741824,
1352 'g' => 1073741824,
1353 'T' => 1099511627776,
1354 't' => 1099511627776,
1357 if (preg_match('/^([0-9]+)([KMGT])/i', $size, $matches)) {
1358 return $matches[1] * $binaryprefixes[$matches[2]];
1361 return (int) $size;
1365 * Try to disable all output buffering and purge
1366 * all headers.
1368 * @access private to be called only from lib/setup.php !
1369 * @return void
1371 function disable_output_buffering() {
1372 $olddebug = error_reporting(0);
1374 // disable compression, it would prevent closing of buffers
1375 if (ini_get_bool('zlib.output_compression')) {
1376 ini_set('zlib.output_compression', 'Off');
1379 // try to flush everything all the time
1380 ob_implicit_flush(true);
1382 // close all buffers if possible and discard any existing output
1383 // this can actually work around some whitespace problems in config.php
1384 while(ob_get_level()) {
1385 if (!ob_end_clean()) {
1386 // prevent infinite loop when buffer can not be closed
1387 break;
1391 // disable any other output handlers
1392 ini_set('output_handler', '');
1394 error_reporting($olddebug);
1396 // Disable buffering in nginx.
1397 header('X-Accel-Buffering: no');
1402 * Check whether a major upgrade is needed.
1404 * That is defined as an upgrade that changes something really fundamental
1405 * in the database, so nothing can possibly work until the database has
1406 * been updated, and that is defined by the hard-coded version number in
1407 * this function.
1409 * @return bool
1411 function is_major_upgrade_required() {
1412 global $CFG;
1413 $lastmajordbchanges = 2017040403.00;
1415 $required = empty($CFG->version);
1416 $required = $required || (float)$CFG->version < $lastmajordbchanges;
1417 $required = $required || during_initial_install();
1418 $required = $required || !empty($CFG->adminsetuppending);
1420 return $required;
1424 * Redirect to the Notifications page if a major upgrade is required, and
1425 * terminate the current user session.
1427 function redirect_if_major_upgrade_required() {
1428 global $CFG;
1429 if (is_major_upgrade_required()) {
1430 try {
1431 @\core\session\manager::terminate_current();
1432 } catch (Exception $e) {
1433 // Ignore any errors, redirect to upgrade anyway.
1435 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
1436 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1437 @header('Location: ' . $url);
1438 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
1439 exit;
1444 * Makes sure that upgrade process is not running
1446 * To be inserted in the core functions that can not be called by pluigns during upgrade.
1447 * Core upgrade should not use any API functions at all.
1448 * See {@link http://docs.moodle.org/dev/Upgrade_API#Upgrade_code_restrictions}
1450 * @throws moodle_exception if executed from inside of upgrade script and $warningonly is false
1451 * @param bool $warningonly if true displays a warning instead of throwing an exception
1452 * @return bool true if executed from outside of upgrade process, false if from inside upgrade process and function is used for warning only
1454 function upgrade_ensure_not_running($warningonly = false) {
1455 global $CFG;
1456 if (!empty($CFG->upgraderunning)) {
1457 if (!$warningonly) {
1458 throw new moodle_exception('cannotexecduringupgrade');
1459 } else {
1460 debugging(get_string('cannotexecduringupgrade', 'error'), DEBUG_DEVELOPER);
1461 return false;
1464 return true;
1468 * Function to check if a directory exists and by default create it if not exists.
1470 * Previously this was accepting paths only from dataroot, but we now allow
1471 * files outside of dataroot if you supply custom paths for some settings in config.php.
1472 * This function does not verify that the directory is writable.
1474 * NOTE: this function uses current file stat cache,
1475 * please use clearstatcache() before this if you expect that the
1476 * directories may have been removed recently from a different request.
1478 * @param string $dir absolute directory path
1479 * @param boolean $create directory if does not exist
1480 * @param boolean $recursive create directory recursively
1481 * @return boolean true if directory exists or created, false otherwise
1483 function check_dir_exists($dir, $create = true, $recursive = true) {
1484 global $CFG;
1486 umask($CFG->umaskpermissions);
1488 if (is_dir($dir)) {
1489 return true;
1492 if (!$create) {
1493 return false;
1496 return mkdir($dir, $CFG->directorypermissions, $recursive);
1500 * Create a new unique directory within the specified directory.
1502 * @param string $basedir The directory to create your new unique directory within.
1503 * @param bool $exceptiononerror throw exception if error encountered
1504 * @return string The created directory
1505 * @throws invalid_dataroot_permissions
1507 function make_unique_writable_directory($basedir, $exceptiononerror = true) {
1508 if (!is_dir($basedir) || !is_writable($basedir)) {
1509 // The basedir is not writable. We will not be able to create the child directory.
1510 if ($exceptiononerror) {
1511 throw new invalid_dataroot_permissions($basedir . ' is not writable. Unable to create a unique directory within it.');
1512 } else {
1513 return false;
1517 do {
1518 // Generate a new (hopefully unique) directory name.
1519 $uniquedir = $basedir . DIRECTORY_SEPARATOR . generate_uuid();
1520 } while (
1521 // Ensure that basedir is still writable - if we do not check, we could get stuck in a loop here.
1522 is_writable($basedir) &&
1524 // Make the new unique directory. If the directory already exists, it will return false.
1525 !make_writable_directory($uniquedir, $exceptiononerror) &&
1527 // Ensure that the directory now exists
1528 file_exists($uniquedir) && is_dir($uniquedir)
1531 // Check that the directory was correctly created.
1532 if (!file_exists($uniquedir) || !is_dir($uniquedir) || !is_writable($uniquedir)) {
1533 if ($exceptiononerror) {
1534 throw new invalid_dataroot_permissions('Unique directory creation failed.');
1535 } else {
1536 return false;
1540 return $uniquedir;
1544 * Create a directory and make sure it is writable.
1546 * @private
1547 * @param string $dir the full path of the directory to be created
1548 * @param bool $exceptiononerror throw exception if error encountered
1549 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1551 function make_writable_directory($dir, $exceptiononerror = true) {
1552 global $CFG;
1554 if (file_exists($dir) and !is_dir($dir)) {
1555 if ($exceptiononerror) {
1556 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1557 } else {
1558 return false;
1562 umask($CFG->umaskpermissions);
1564 if (!file_exists($dir)) {
1565 if (!@mkdir($dir, $CFG->directorypermissions, true)) {
1566 clearstatcache();
1567 // There might be a race condition when creating directory.
1568 if (!is_dir($dir)) {
1569 if ($exceptiononerror) {
1570 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1571 } else {
1572 debugging('Can not create directory: '.$dir, DEBUG_DEVELOPER);
1573 return false;
1579 if (!is_writable($dir)) {
1580 if ($exceptiononerror) {
1581 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1582 } else {
1583 return false;
1587 return $dir;
1591 * Protect a directory from web access.
1592 * Could be extended in the future to support other mechanisms (e.g. other webservers).
1594 * @private
1595 * @param string $dir the full path of the directory to be protected
1597 function protect_directory($dir) {
1598 global $CFG;
1599 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1600 if (!file_exists("$dir/.htaccess")) {
1601 if ($handle = fopen("$dir/.htaccess", 'w')) { // For safety
1602 @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");
1603 @fclose($handle);
1604 @chmod("$dir/.htaccess", $CFG->filepermissions);
1610 * Create a directory under dataroot and make sure it is writable.
1611 * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
1613 * @param string $directory the full path of the directory to be created under $CFG->dataroot
1614 * @param bool $exceptiononerror throw exception if error encountered
1615 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1617 function make_upload_directory($directory, $exceptiononerror = true) {
1618 global $CFG;
1620 if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1621 debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1623 } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
1624 debugging('Use make_cache_directory() for creation of cache directory and $CFG->cachedir to get the location.');
1626 } else if (strpos($directory, 'localcache/') === 0 or $directory === 'localcache') {
1627 debugging('Use make_localcache_directory() for creation of local cache directory and $CFG->localcachedir to get the location.');
1630 protect_directory($CFG->dataroot);
1631 return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1635 * Get a per-request storage directory in the tempdir.
1637 * The directory is automatically cleaned up during the shutdown handler.
1639 * @param bool $exceptiononerror throw exception if error encountered
1640 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1642 function get_request_storage_directory($exceptiononerror = true) {
1643 global $CFG;
1645 static $requestdir = null;
1647 if (!$requestdir || !file_exists($requestdir) || !is_dir($requestdir) || !is_writable($requestdir)) {
1648 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1649 check_dir_exists($CFG->localcachedir, true, true);
1650 protect_directory($CFG->localcachedir);
1651 } else {
1652 protect_directory($CFG->dataroot);
1655 if ($requestdir = make_unique_writable_directory($CFG->localcachedir, $exceptiononerror)) {
1656 // Register a shutdown handler to remove the directory.
1657 \core_shutdown_manager::register_function('remove_dir', array($requestdir));
1661 return $requestdir;
1665 * Create a per-request directory and make sure it is writable.
1666 * This can only be used during the current request and will be tidied away
1667 * automatically afterwards.
1669 * A new, unique directory is always created within the current request directory.
1671 * @param bool $exceptiononerror throw exception if error encountered
1672 * @return string full path to directory if successful, false if not; may throw exception
1674 function make_request_directory($exceptiononerror = true) {
1675 $basedir = get_request_storage_directory($exceptiononerror);
1676 return make_unique_writable_directory($basedir, $exceptiononerror);
1680 * Create a directory under tempdir and make sure it is writable.
1682 * Where possible, please use make_request_directory() and limit the scope
1683 * of your data to the current HTTP request.
1685 * Do not use for storing cache files - see make_cache_directory(), and
1686 * make_localcache_directory() instead for this purpose.
1688 * Temporary files must be on a shared storage, and heavy usage is
1689 * discouraged due to the performance impact upon clustered environments.
1691 * @param string $directory the full path of the directory to be created under $CFG->tempdir
1692 * @param bool $exceptiononerror throw exception if error encountered
1693 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1695 function make_temp_directory($directory, $exceptiononerror = true) {
1696 global $CFG;
1697 if ($CFG->tempdir !== "$CFG->dataroot/temp") {
1698 check_dir_exists($CFG->tempdir, true, true);
1699 protect_directory($CFG->tempdir);
1700 } else {
1701 protect_directory($CFG->dataroot);
1703 return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1707 * Create a directory under cachedir and make sure it is writable.
1709 * Note: this cache directory is shared by all cluster nodes.
1711 * @param string $directory the full path of the directory to be created under $CFG->cachedir
1712 * @param bool $exceptiononerror throw exception if error encountered
1713 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1715 function make_cache_directory($directory, $exceptiononerror = true) {
1716 global $CFG;
1717 if ($CFG->cachedir !== "$CFG->dataroot/cache") {
1718 check_dir_exists($CFG->cachedir, true, true);
1719 protect_directory($CFG->cachedir);
1720 } else {
1721 protect_directory($CFG->dataroot);
1723 return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1727 * Create a directory under localcachedir and make sure it is writable.
1728 * The files in this directory MUST NOT change, use revisions or content hashes to
1729 * work around this limitation - this means you can only add new files here.
1731 * The content of this directory gets purged automatically on all cluster nodes
1732 * after calling purge_all_caches() before new data is written to this directory.
1734 * Note: this local cache directory does not need to be shared by cluster nodes.
1736 * @param string $directory the relative path of the directory to be created under $CFG->localcachedir
1737 * @param bool $exceptiononerror throw exception if error encountered
1738 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1740 function make_localcache_directory($directory, $exceptiononerror = true) {
1741 global $CFG;
1743 make_writable_directory($CFG->localcachedir, $exceptiononerror);
1745 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1746 protect_directory($CFG->localcachedir);
1747 } else {
1748 protect_directory($CFG->dataroot);
1751 if (!isset($CFG->localcachedirpurged)) {
1752 $CFG->localcachedirpurged = 0;
1754 $timestampfile = "$CFG->localcachedir/.lastpurged";
1756 if (!file_exists($timestampfile)) {
1757 touch($timestampfile);
1758 @chmod($timestampfile, $CFG->filepermissions);
1760 } else if (filemtime($timestampfile) < $CFG->localcachedirpurged) {
1761 // This means our local cached dir was not purged yet.
1762 remove_dir($CFG->localcachedir, true);
1763 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1764 protect_directory($CFG->localcachedir);
1766 touch($timestampfile);
1767 @chmod($timestampfile, $CFG->filepermissions);
1768 clearstatcache();
1771 if ($directory === '') {
1772 return $CFG->localcachedir;
1775 return make_writable_directory("$CFG->localcachedir/$directory", $exceptiononerror);
1779 * This class solves the problem of how to initialise $OUTPUT.
1781 * The problem is caused be two factors
1782 * <ol>
1783 * <li>On the one hand, we cannot be sure when output will start. In particular,
1784 * an error, which needs to be displayed, could be thrown at any time.</li>
1785 * <li>On the other hand, we cannot be sure when we will have all the information
1786 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1787 * (potentially) depends on the current course, course categories, and logged in user.
1788 * It also depends on whether the current page requires HTTPS.</li>
1789 * </ol>
1791 * So, it is hard to find a single natural place during Moodle script execution,
1792 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1793 * adopt the following strategy
1794 * <ol>
1795 * <li>We will initialise $OUTPUT the first time it is used.</li>
1796 * <li>If, after $OUTPUT has been initialised, the script tries to change something
1797 * that $OUTPUT depends on, we throw an exception making it clear that the script
1798 * did something wrong.
1799 * </ol>
1801 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1802 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1803 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1804 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1806 * Note that this class is used before lib/outputlib.php has been loaded, so we
1807 * must be careful referring to classes/functions from there, they may not be
1808 * defined yet, and we must avoid fatal errors.
1810 * @copyright 2009 Tim Hunt
1811 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1812 * @since Moodle 2.0
1814 class bootstrap_renderer {
1816 * Handles re-entrancy. Without this, errors or debugging output that occur
1817 * during the initialisation of $OUTPUT, cause infinite recursion.
1818 * @var boolean
1820 protected $initialising = false;
1823 * Have we started output yet?
1824 * @return boolean true if the header has been printed.
1826 public function has_started() {
1827 return false;
1831 * Constructor - to be used by core code only.
1832 * @param string $method The method to call
1833 * @param array $arguments Arguments to pass to the method being called
1834 * @return string
1836 public function __call($method, $arguments) {
1837 global $OUTPUT, $PAGE;
1839 $recursing = false;
1840 if ($method == 'notification') {
1841 // Catch infinite recursion caused by debugging output during print_header.
1842 $backtrace = debug_backtrace();
1843 array_shift($backtrace);
1844 array_shift($backtrace);
1845 $recursing = is_early_init($backtrace);
1848 $earlymethods = array(
1849 'fatal_error' => 'early_error',
1850 'notification' => 'early_notification',
1853 // If lib/outputlib.php has been loaded, call it.
1854 if (!empty($PAGE) && !$recursing) {
1855 if (array_key_exists($method, $earlymethods)) {
1856 //prevent PAGE->context warnings - exceptions might appear before we set any context
1857 $PAGE->set_context(null);
1859 $PAGE->initialise_theme_and_output();
1860 return call_user_func_array(array($OUTPUT, $method), $arguments);
1863 $this->initialising = true;
1865 // Too soon to initialise $OUTPUT, provide a couple of key methods.
1866 if (array_key_exists($method, $earlymethods)) {
1867 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1870 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1874 * Returns nicely formatted error message in a div box.
1875 * @static
1876 * @param string $message error message
1877 * @param string $moreinfourl (ignored in early errors)
1878 * @param string $link (ignored in early errors)
1879 * @param array $backtrace
1880 * @param string $debuginfo
1881 * @return string
1883 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1884 global $CFG;
1886 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1887 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1888 width: 80%; -moz-border-radius: 20px; padding: 15px">
1889 ' . $message . '
1890 </div>';
1891 // Check whether debug is set.
1892 $debug = (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER);
1893 // Also check we have it set in the config file. This occurs if the method to read the config table from the
1894 // database fails, reading from the config table is the first database interaction we have.
1895 $debug = $debug || (!empty($CFG->config_php_settings['debug']) && $CFG->config_php_settings['debug'] >= DEBUG_DEVELOPER );
1896 if ($debug) {
1897 if (!empty($debuginfo)) {
1898 $debuginfo = s($debuginfo); // removes all nasty JS
1899 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1900 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
1902 if (!empty($backtrace)) {
1903 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1907 return $content;
1911 * This function should only be called by this class, or from exception handlers
1912 * @static
1913 * @param string $message error message
1914 * @param string $moreinfourl (ignored in early errors)
1915 * @param string $link (ignored in early errors)
1916 * @param array $backtrace
1917 * @param string $debuginfo extra information for developers
1918 * @return string
1920 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = null) {
1921 global $CFG;
1923 if (CLI_SCRIPT) {
1924 echo "!!! $message !!!\n";
1925 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1926 if (!empty($debuginfo)) {
1927 echo "\nDebug info: $debuginfo";
1929 if (!empty($backtrace)) {
1930 echo "\nStack trace: " . format_backtrace($backtrace, true);
1933 return;
1935 } else if (AJAX_SCRIPT) {
1936 $e = new stdClass();
1937 $e->error = $message;
1938 $e->stacktrace = NULL;
1939 $e->debuginfo = NULL;
1940 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1941 if (!empty($debuginfo)) {
1942 $e->debuginfo = $debuginfo;
1944 if (!empty($backtrace)) {
1945 $e->stacktrace = format_backtrace($backtrace, true);
1948 $e->errorcode = $errorcode;
1949 @header('Content-Type: application/json; charset=utf-8');
1950 echo json_encode($e);
1951 return;
1954 // In the name of protocol correctness, monitoring and performance
1955 // profiling, set the appropriate error headers for machine consumption.
1956 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
1957 @header($protocol . ' 503 Service Unavailable');
1959 // better disable any caching
1960 @header('Content-Type: text/html; charset=utf-8');
1961 @header('X-UA-Compatible: IE=edge');
1962 @header('Cache-Control: no-store, no-cache, must-revalidate');
1963 @header('Cache-Control: post-check=0, pre-check=0', false);
1964 @header('Pragma: no-cache');
1965 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1966 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1968 if (function_exists('get_string')) {
1969 $strerror = get_string('error');
1970 } else {
1971 $strerror = 'Error';
1974 $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
1976 return self::plain_page($strerror, $content);
1980 * Early notification message
1981 * @static
1982 * @param string $message
1983 * @param string $classes usually notifyproblem or notifysuccess
1984 * @return string
1986 public static function early_notification($message, $classes = 'notifyproblem') {
1987 return '<div class="' . $classes . '">' . $message . '</div>';
1991 * Page should redirect message.
1992 * @static
1993 * @param string $encodedurl redirect url
1994 * @return string
1996 public static function plain_redirect_message($encodedurl) {
1997 $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
1998 $encodedurl .'">'. get_string('continue') .'</a></div>';
1999 return self::plain_page(get_string('redirect'), $message);
2003 * Early redirection page, used before full init of $PAGE global
2004 * @static
2005 * @param string $encodedurl redirect url
2006 * @param string $message redirect message
2007 * @param int $delay time in seconds
2008 * @return string redirect page
2010 public static function early_redirect_message($encodedurl, $message, $delay) {
2011 $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
2012 $content = self::early_error_content($message, null, null, null);
2013 $content .= self::plain_redirect_message($encodedurl);
2015 return self::plain_page(get_string('redirect'), $content, $meta);
2019 * Output basic html page.
2020 * @static
2021 * @param string $title page title
2022 * @param string $content page content
2023 * @param string $meta meta tag
2024 * @return string html page
2026 public static function plain_page($title, $content, $meta = '') {
2027 if (function_exists('get_string') && function_exists('get_html_lang')) {
2028 $htmllang = get_html_lang();
2029 } else {
2030 $htmllang = '';
2033 $footer = '';
2034 if (MDL_PERF_TEST) {
2035 $perfinfo = get_performance_info();
2036 $footer = '<footer>' . $perfinfo['html'] . '</footer>';
2039 return '<!DOCTYPE html>
2040 <html ' . $htmllang . '>
2041 <head>
2042 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
2043 '.$meta.'
2044 <title>' . $title . '</title>
2045 </head><body>' . $content . $footer . '</body></html>';