MDL-51177 core: Ignore built files in stylelint
[moodle.git] / lib / setuplib.php
blob7a07e1d023fbb0418bd6326b3ac6a4fcac4c004d
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * These functions are required very early in the Moodle
19 * setup process, before any of the main libraries are
20 * loaded.
22 * @package core
23 * @subpackage lib
24 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
30 // Debug levels - always keep the values in ascending order!
31 /** No warnings and errors at all */
32 define('DEBUG_NONE', 0);
33 /** Fatal errors only */
34 define('DEBUG_MINIMAL', E_ERROR | E_PARSE);
35 /** Errors, warnings and notices */
36 define('DEBUG_NORMAL', E_ERROR | E_PARSE | E_WARNING | E_NOTICE);
37 /** All problems except strict PHP warnings */
38 define('DEBUG_ALL', E_ALL & ~E_STRICT);
39 /** DEBUG_ALL with all debug messages and strict warnings */
40 define('DEBUG_DEVELOPER', E_ALL | E_STRICT);
42 /** Remove any memory limits */
43 define('MEMORY_UNLIMITED', -1);
44 /** Standard memory limit for given platform */
45 define('MEMORY_STANDARD', -2);
46 /**
47 * Large memory limit for given platform - used in cron, upgrade, and other places that need a lot of memory.
48 * Can be overridden with $CFG->extramemorylimit setting.
50 define('MEMORY_EXTRA', -3);
51 /** Extremely large memory limit - not recommended for standard scripts */
52 define('MEMORY_HUGE', -4);
54 /**
55 * Base Moodle Exception class
57 * Although this class is defined here, you cannot throw a moodle_exception until
58 * after moodlelib.php has been included (which will happen very soon).
60 * @package core
61 * @subpackage lib
62 * @copyright 2008 Petr Skoda {@link http://skodak.org}
63 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
65 class moodle_exception extends Exception {
67 /**
68 * @var string The name of the string from error.php to print
70 public $errorcode;
72 /**
73 * @var string The name of module
75 public $module;
77 /**
78 * @var mixed Extra words and phrases that might be required in the error string
80 public $a;
82 /**
83 * @var string The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
85 public $link;
87 /**
88 * @var string Optional information to aid the debugging process
90 public $debuginfo;
92 /**
93 * Constructor
94 * @param string $errorcode The name of the string from error.php to print
95 * @param string $module name of module
96 * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
97 * @param mixed $a Extra words and phrases that might be required in the error string
98 * @param string $debuginfo optional debugging information
100 function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
101 if (empty($module) || $module == 'moodle' || $module == 'core') {
102 $module = 'error';
105 $this->errorcode = $errorcode;
106 $this->module = $module;
107 $this->link = $link;
108 $this->a = $a;
109 $this->debuginfo = is_null($debuginfo) ? null : (string)$debuginfo;
111 if (get_string_manager()->string_exists($errorcode, $module)) {
112 $message = get_string($errorcode, $module, $a);
113 $haserrorstring = true;
114 } else {
115 $message = $module . '/' . $errorcode;
116 $haserrorstring = false;
119 if (defined('PHPUNIT_TEST') and PHPUNIT_TEST and $debuginfo) {
120 $message = "$message ($debuginfo)";
123 if (!$haserrorstring and defined('PHPUNIT_TEST') and PHPUNIT_TEST) {
124 // Append the contents of $a to $debuginfo so helpful information isn't lost.
125 // This emulates what {@link get_exception_info()} does. Unfortunately that
126 // function is not used by phpunit.
127 $message .= PHP_EOL.'$a contents: '.print_r($a, true);
130 parent::__construct($message, 0);
135 * Course/activity access exception.
137 * This exception is thrown from require_login()
139 * @package core_access
140 * @copyright 2010 Petr Skoda {@link http://skodak.org}
141 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
143 class require_login_exception extends moodle_exception {
145 * Constructor
146 * @param string $debuginfo Information to aid the debugging process
148 function __construct($debuginfo) {
149 parent::__construct('requireloginerror', 'error', '', NULL, $debuginfo);
154 * Session timeout exception.
156 * This exception is thrown from require_login()
158 * @package core_access
159 * @copyright 2015 Andrew Nicols <andrew@nicols.co.uk>
160 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
162 class require_login_session_timeout_exception extends require_login_exception {
164 * Constructor
166 public function __construct() {
167 moodle_exception::__construct('sessionerroruser', 'error');
172 * Web service parameter exception class
173 * @deprecated since Moodle 2.2 - use moodle exception instead
174 * This exception must be thrown to the web service client when a web service parameter is invalid
175 * The error string is gotten from webservice.php
177 class webservice_parameter_exception extends moodle_exception {
179 * Constructor
180 * @param string $errorcode The name of the string from webservice.php to print
181 * @param string $a The name of the parameter
182 * @param string $debuginfo Optional information to aid debugging
184 function __construct($errorcode=null, $a = '', $debuginfo = null) {
185 parent::__construct($errorcode, 'webservice', '', $a, $debuginfo);
190 * Exceptions indicating user does not have permissions to do something
191 * and the execution can not continue.
193 * @package core_access
194 * @copyright 2009 Petr Skoda {@link http://skodak.org}
195 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
197 class required_capability_exception extends moodle_exception {
199 * Constructor
200 * @param context $context The context used for the capability check
201 * @param string $capability The required capability
202 * @param string $errormessage The error message to show the user
203 * @param string $stringfile
205 function __construct($context, $capability, $errormessage, $stringfile) {
206 $capabilityname = get_capability_string($capability);
207 if ($context->contextlevel == CONTEXT_MODULE and preg_match('/:view$/', $capability)) {
208 // 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
209 $parentcontext = $context->get_parent_context();
210 $link = $parentcontext->get_url();
211 } else {
212 $link = $context->get_url();
214 parent::__construct($errormessage, $stringfile, $link, $capabilityname);
219 * Exception indicating programming error, must be fixed by a programer. For example
220 * a core API might throw this type of exception if a plugin calls it incorrectly.
222 * @package core
223 * @subpackage lib
224 * @copyright 2008 Petr Skoda {@link http://skodak.org}
225 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
227 class coding_exception extends moodle_exception {
229 * Constructor
230 * @param string $hint short description of problem
231 * @param string $debuginfo detailed information how to fix problem
233 function __construct($hint, $debuginfo=null) {
234 parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
239 * Exception indicating malformed parameter problem.
240 * This exception is not supposed to be thrown when processing
241 * user submitted data in forms. It is more suitable
242 * for WS and other low level stuff.
244 * @package core
245 * @subpackage lib
246 * @copyright 2009 Petr Skoda {@link http://skodak.org}
247 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
249 class invalid_parameter_exception extends moodle_exception {
251 * Constructor
252 * @param string $debuginfo some detailed information
254 function __construct($debuginfo=null) {
255 parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
260 * Exception indicating malformed response 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 class invalid_response_exception extends moodle_exception {
267 * Constructor
268 * @param string $debuginfo some detailed information
270 function __construct($debuginfo=null) {
271 parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
276 * An exception that indicates something really weird happened. For example,
277 * if you do switch ($context->contextlevel), and have one case for each
278 * CONTEXT_... constant. You might throw an invalid_state_exception in the
279 * default case, to just in case something really weird is going on, and
280 * $context->contextlevel is invalid - rather than ignoring this possibility.
282 * @package core
283 * @subpackage lib
284 * @copyright 2009 onwards Martin Dougiamas {@link http://moodle.com}
285 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
287 class invalid_state_exception extends moodle_exception {
289 * Constructor
290 * @param string $hint short description of problem
291 * @param string $debuginfo optional more detailed information
293 function __construct($hint, $debuginfo=null) {
294 parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
299 * An exception that indicates incorrect permissions in $CFG->dataroot
301 * @package core
302 * @subpackage lib
303 * @copyright 2010 Petr Skoda {@link http://skodak.org}
304 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
306 class invalid_dataroot_permissions extends moodle_exception {
308 * Constructor
309 * @param string $debuginfo optional more detailed information
311 function __construct($debuginfo = NULL) {
312 parent::__construct('invaliddatarootpermissions', 'error', '', NULL, $debuginfo);
317 * An exception that indicates that file can not be served
319 * @package core
320 * @subpackage lib
321 * @copyright 2010 Petr Skoda {@link http://skodak.org}
322 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
324 class file_serving_exception extends moodle_exception {
326 * Constructor
327 * @param string $debuginfo optional more detailed information
329 function __construct($debuginfo = NULL) {
330 parent::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
335 * Default exception handler.
337 * @param Exception $ex
338 * @return void -does not return. Terminates execution!
340 function default_exception_handler($ex) {
341 global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION, $PAGE;
343 // detect active db transactions, rollback and log as error
344 abort_all_db_transactions();
346 if (($ex instanceof required_capability_exception) && !CLI_SCRIPT && !AJAX_SCRIPT && !empty($CFG->autologinguests) && !empty($USER->autologinguest)) {
347 $SESSION->wantsurl = qualified_me();
348 redirect(get_login_url());
351 $info = get_exception_info($ex);
353 if (debugging('', DEBUG_MINIMAL)) {
354 $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
355 error_log($logerrmsg);
358 if (is_early_init($info->backtrace)) {
359 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
360 } else {
361 try {
362 if ($DB) {
363 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
364 $DB->set_debug(0);
366 if (AJAX_SCRIPT) {
367 // If we are in an AJAX script we don't want to use PREFERRED_RENDERER_TARGET.
368 // Because we know we will want to use ajax format.
369 $renderer = new core_renderer_ajax($PAGE, 'ajax');
370 } else {
371 $renderer = $OUTPUT;
373 echo $renderer->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo,
374 $info->errorcode);
375 } catch (Exception $e) {
376 $out_ex = $e;
377 } catch (Throwable $e) {
378 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
379 $out_ex = $e;
382 if (isset($out_ex)) {
383 // default exception handler MUST not throw any exceptions!!
384 // 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
385 // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
386 if (CLI_SCRIPT or AJAX_SCRIPT) {
387 // just ignore the error and send something back using the safest method
388 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
389 } else {
390 echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
391 $outinfo = get_exception_info($out_ex);
392 echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
397 exit(1); // General error code
401 * Default error handler, prevents some white screens.
402 * @param int $errno
403 * @param string $errstr
404 * @param string $errfile
405 * @param int $errline
406 * @param array $errcontext
407 * @return bool false means use default error handler
409 function default_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
410 if ($errno == 4096) {
411 //fatal catchable error
412 throw new coding_exception('PHP catchable fatal error', $errstr);
414 return false;
418 * Unconditionally abort all database transactions, this function
419 * should be called from exception handlers only.
420 * @return void
422 function abort_all_db_transactions() {
423 global $CFG, $DB, $SCRIPT;
425 // default exception handler MUST not throw any exceptions!!
427 if ($DB && $DB->is_transaction_started()) {
428 error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
429 // note: transaction blocks should never change current $_SESSION
430 $DB->force_transaction_rollback();
435 * This function encapsulates the tests for whether an exception was thrown in
436 * early init -- either during setup.php or during init of $OUTPUT.
438 * If another exception is thrown then, and if we do not take special measures,
439 * we would just get a very cryptic message "Exception thrown without a stack
440 * frame in Unknown on line 0". That makes debugging very hard, so we do take
441 * special measures in default_exception_handler, with the help of this function.
443 * @param array $backtrace the stack trace to analyse.
444 * @return boolean whether the stack trace is somewhere in output initialisation.
446 function is_early_init($backtrace) {
447 $dangerouscode = array(
448 array('function' => 'header', 'type' => '->'),
449 array('class' => 'bootstrap_renderer'),
450 array('file' => __DIR__.'/setup.php'),
452 foreach ($backtrace as $stackframe) {
453 foreach ($dangerouscode as $pattern) {
454 $matches = true;
455 foreach ($pattern as $property => $value) {
456 if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
457 $matches = false;
460 if ($matches) {
461 return true;
465 return false;
469 * Abort execution by throwing of a general exception,
470 * default exception handler displays the error message in most cases.
472 * @param string $errorcode The name of the language string containing the error message.
473 * Normally this should be in the error.php lang file.
474 * @param string $module The language file to get the error message from.
475 * @param string $link The url where the user will be prompted to continue.
476 * If no url is provided the user will be directed to the site index page.
477 * @param object $a Extra words and phrases that might be required in the error string
478 * @param string $debuginfo optional debugging information
479 * @return void, always throws exception!
481 function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
482 throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
486 * Returns detailed information about specified exception.
487 * @param exception $ex
488 * @return object
490 function get_exception_info($ex) {
491 global $CFG, $DB, $SESSION;
493 if ($ex instanceof moodle_exception) {
494 $errorcode = $ex->errorcode;
495 $module = $ex->module;
496 $a = $ex->a;
497 $link = $ex->link;
498 $debuginfo = $ex->debuginfo;
499 } else {
500 $errorcode = 'generalexceptionmessage';
501 $module = 'error';
502 $a = $ex->getMessage();
503 $link = '';
504 $debuginfo = '';
507 // Append the error code to the debug info to make grepping and googling easier
508 $debuginfo .= PHP_EOL."Error code: $errorcode";
510 $backtrace = $ex->getTrace();
511 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
512 array_unshift($backtrace, $place);
514 // Be careful, no guarantee moodlelib.php is loaded.
515 if (empty($module) || $module == 'moodle' || $module == 'core') {
516 $module = 'error';
518 // Search for the $errorcode's associated string
519 // If not found, append the contents of $a to $debuginfo so helpful information isn't lost
520 if (function_exists('get_string_manager')) {
521 if (get_string_manager()->string_exists($errorcode, $module)) {
522 $message = get_string($errorcode, $module, $a);
523 } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
524 // Search in moodle file if error specified - needed for backwards compatibility
525 $message = get_string($errorcode, 'moodle', $a);
526 } else {
527 $message = $module . '/' . $errorcode;
528 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
530 } else {
531 $message = $module . '/' . $errorcode;
532 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
535 // Remove some absolute paths from message and debugging info.
536 $searches = array();
537 $replaces = array();
538 $cfgnames = array('tempdir', 'cachedir', 'localcachedir', 'themedir', 'dataroot', 'dirroot');
539 foreach ($cfgnames as $cfgname) {
540 if (property_exists($CFG, $cfgname)) {
541 $searches[] = $CFG->$cfgname;
542 $replaces[] = "[$cfgname]";
545 if (!empty($searches)) {
546 $message = str_replace($searches, $replaces, $message);
547 $debuginfo = str_replace($searches, $replaces, $debuginfo);
550 // Be careful, no guarantee weblib.php is loaded.
551 if (function_exists('clean_text')) {
552 $message = clean_text($message);
553 } else {
554 $message = htmlspecialchars($message);
557 if (!empty($CFG->errordocroot)) {
558 $errordoclink = $CFG->errordocroot . '/en/';
559 } else {
560 $errordoclink = get_docs_url();
563 if ($module === 'error') {
564 $modulelink = 'moodle';
565 } else {
566 $modulelink = $module;
568 $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
570 if (empty($link)) {
571 if (!empty($SESSION->fromurl)) {
572 $link = $SESSION->fromurl;
573 unset($SESSION->fromurl);
574 } else {
575 $link = $CFG->wwwroot .'/';
579 // When printing an error the continue button should never link offsite.
580 // We cannot use clean_param() here as it is not guaranteed that it has been loaded yet.
581 if (stripos($link, $CFG->wwwroot) === 0) {
582 // Internal HTTP, all good.
583 } else {
584 // External link spotted!
585 $link = $CFG->wwwroot . '/';
588 $info = new stdClass();
589 $info->message = $message;
590 $info->errorcode = $errorcode;
591 $info->backtrace = $backtrace;
592 $info->link = $link;
593 $info->moreinfourl = $moreinfourl;
594 $info->a = $a;
595 $info->debuginfo = $debuginfo;
597 return $info;
601 * Generate a uuid.
603 * Unique is hard. Very hard. Attempt to use the PECL UUID functions if available, and if not then revert to
604 * constructing the uuid using mt_rand.
606 * It is important that this token is not solely based on time as this could lead
607 * to duplicates in a clustered environment (especially on VMs due to poor time precision).
609 * @return string The uuid.
611 function generate_uuid() {
612 $uuid = '';
614 if (function_exists("uuid_create")) {
615 $context = null;
616 uuid_create($context);
618 uuid_make($context, UUID_MAKE_V4);
619 uuid_export($context, UUID_FMT_STR, $uuid);
620 } else {
621 // Fallback uuid generation based on:
622 // "http://www.php.net/manual/en/function.uniqid.php#94959".
623 $uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
625 // 32 bits for "time_low".
626 mt_rand(0, 0xffff), mt_rand(0, 0xffff),
628 // 16 bits for "time_mid".
629 mt_rand(0, 0xffff),
631 // 16 bits for "time_hi_and_version",
632 // four most significant bits holds version number 4.
633 mt_rand(0, 0x0fff) | 0x4000,
635 // 16 bits, 8 bits for "clk_seq_hi_res",
636 // 8 bits for "clk_seq_low",
637 // two most significant bits holds zero and one for variant DCE1.1.
638 mt_rand(0, 0x3fff) | 0x8000,
640 // 48 bits for "node".
641 mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
643 return trim($uuid);
647 * Returns the Moodle Docs URL in the users language for a given 'More help' link.
649 * There are three cases:
651 * 1. In the normal case, $path will be a short relative path 'component/thing',
652 * like 'mod/folder/view' 'group/import'. This gets turned into an link to
653 * MoodleDocs in the user's language, and for the appropriate Moodle version.
654 * E.g. 'group/import' may become 'http://docs.moodle.org/2x/en/group/import'.
655 * The 'http://docs.moodle.org' bit comes from $CFG->docroot.
657 * This is the only option that should be used in standard Moodle code. The other
658 * two options have been implemented because they are useful for third-party plugins.
660 * 2. $path may be an absolute URL, starting http:// or https://. In this case,
661 * the link is used as is.
663 * 3. $path may start %%WWWROOT%%, in which case that is replaced by
664 * $CFG->wwwroot to make the link.
666 * @param string $path the place to link to. See above for details.
667 * @return string The MoodleDocs URL in the user's language. for example @link http://docs.moodle.org/2x/en/$path}
669 function get_docs_url($path = null) {
670 global $CFG;
672 // Absolute URLs are used unmodified.
673 if (substr($path, 0, 7) === 'http://' || substr($path, 0, 8) === 'https://') {
674 return $path;
677 // Paths starting %%WWWROOT%% have that replaced by $CFG->wwwroot.
678 if (substr($path, 0, 11) === '%%WWWROOT%%') {
679 return $CFG->wwwroot . substr($path, 11);
682 // Otherwise we do the normal case, and construct a MoodleDocs URL relative to $CFG->docroot.
684 // Check that $CFG->branch has been set up, during installation it won't be.
685 if (empty($CFG->branch)) {
686 // It's not there yet so look at version.php.
687 include($CFG->dirroot.'/version.php');
688 } else {
689 // We can use $CFG->branch and avoid having to include version.php.
690 $branch = $CFG->branch;
692 // ensure branch is valid.
693 if (!$branch) {
694 // We should never get here but in case we do lets set $branch to .
695 // the smart one's will know that this is the current directory
696 // and the smarter ones will know that there is some smart matching
697 // that will ensure people end up at the latest version of the docs.
698 $branch = '.';
700 if (empty($CFG->doclang)) {
701 $lang = current_language();
702 } else {
703 $lang = $CFG->doclang;
705 $end = '/' . $branch . '/' . $lang . '/' . $path;
706 if (empty($CFG->docroot)) {
707 return 'http://docs.moodle.org'. $end;
708 } else {
709 return $CFG->docroot . $end ;
714 * Formats a backtrace ready for output.
716 * This function does not include function arguments because they could contain sensitive information
717 * not suitable to be exposed in a response.
719 * @param array $callers backtrace array, as returned by debug_backtrace().
720 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
721 * @return string formatted backtrace, ready for output.
723 function format_backtrace($callers, $plaintext = false) {
724 // do not use $CFG->dirroot because it might not be available in destructors
725 $dirroot = dirname(__DIR__);
727 if (empty($callers)) {
728 return '';
731 $from = $plaintext ? '' : '<ul style="text-align: left" data-rel="backtrace">';
732 foreach ($callers as $caller) {
733 if (!isset($caller['line'])) {
734 $caller['line'] = '?'; // probably call_user_func()
736 if (!isset($caller['file'])) {
737 $caller['file'] = 'unknownfile'; // probably call_user_func()
739 $from .= $plaintext ? '* ' : '<li>';
740 $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
741 if (isset($caller['function'])) {
742 $from .= ': call to ';
743 if (isset($caller['class'])) {
744 $from .= $caller['class'] . $caller['type'];
746 $from .= $caller['function'] . '()';
747 } else if (isset($caller['exception'])) {
748 $from .= ': '.$caller['exception'].' thrown';
750 $from .= $plaintext ? "\n" : '</li>';
752 $from .= $plaintext ? '' : '</ul>';
754 return $from;
758 * This function makes the return value of ini_get consistent if you are
759 * setting server directives through the .htaccess file in apache.
761 * Current behavior for value set from php.ini On = 1, Off = [blank]
762 * Current behavior for value set from .htaccess On = On, Off = Off
763 * Contributed by jdell @ unr.edu
765 * @param string $ini_get_arg The argument to get
766 * @return bool True for on false for not
768 function ini_get_bool($ini_get_arg) {
769 $temp = ini_get($ini_get_arg);
771 if ($temp == '1' or strtolower($temp) == 'on') {
772 return true;
774 return false;
778 * This function verifies the sanity of PHP configuration
779 * and stops execution if anything critical found.
781 function setup_validate_php_configuration() {
782 // this must be very fast - no slow checks here!!!
784 if (ini_get_bool('session.auto_start')) {
785 print_error('sessionautostartwarning', 'admin');
790 * Initialise global $CFG variable.
791 * @private to be used only from lib/setup.php
793 function initialise_cfg() {
794 global $CFG, $DB;
796 if (!$DB) {
797 // This should not happen.
798 return;
801 try {
802 $localcfg = get_config('core');
803 } catch (dml_exception $e) {
804 // Most probably empty db, going to install soon.
805 return;
808 foreach ($localcfg as $name => $value) {
809 // Note that get_config() keeps forced settings
810 // and normalises values to string if possible.
811 $CFG->{$name} = $value;
816 * Initialises $FULLME and friends. Private function. Should only be called from
817 * setup.php.
819 function initialise_fullme() {
820 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
822 // Detect common config error.
823 if (substr($CFG->wwwroot, -1) == '/') {
824 print_error('wwwrootslash', 'error');
827 if (CLI_SCRIPT) {
828 initialise_fullme_cli();
829 return;
831 if (!empty($CFG->overridetossl)) {
832 if (strpos($CFG->wwwroot, 'http://') === 0) {
833 $CFG->wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
834 } else {
835 unset_config('overridetossl');
839 $rurl = setup_get_remote_url();
840 $wwwroot = parse_url($CFG->wwwroot.'/');
842 if (empty($rurl['host'])) {
843 // missing host in request header, probably not a real browser, let's ignore them
845 } else if (!empty($CFG->reverseproxy)) {
846 // $CFG->reverseproxy specifies if reverse proxy server used
847 // Used in load balancing scenarios.
848 // Do not abuse this to try to solve lan/wan access problems!!!!!
850 } else {
851 if (($rurl['host'] !== $wwwroot['host']) or
852 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port']) or
853 (strpos($rurl['path'], $wwwroot['path']) !== 0)) {
855 // Explain the problem and redirect them to the right URL
856 if (!defined('NO_MOODLE_COOKIES')) {
857 define('NO_MOODLE_COOKIES', true);
859 // The login/token.php script should call the correct url/port.
860 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
861 $wwwrootport = empty($wwwroot['port'])?'':$wwwroot['port'];
862 $calledurl = $rurl['host'];
863 if (!empty($rurl['port'])) {
864 $calledurl .= ':'. $rurl['port'];
866 $correcturl = $wwwroot['host'];
867 if (!empty($wwwrootport)) {
868 $correcturl .= ':'. $wwwrootport;
870 throw new moodle_exception('requirecorrectaccess', 'error', '', null,
871 'You called ' . $calledurl .', you should have called ' . $correcturl);
873 redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
877 // Check that URL is under $CFG->wwwroot.
878 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
879 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
880 } else {
881 // Probably some weird external script
882 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
883 return;
886 // $CFG->sslproxy specifies if external SSL appliance is used
887 // (That is, the Moodle server uses http, with an external box translating everything to https).
888 if (empty($CFG->sslproxy)) {
889 if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
890 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
891 print_error('sslonlyaccess', 'error');
892 } else {
893 redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
896 } else {
897 if ($wwwroot['scheme'] !== 'https') {
898 throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
900 $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
901 $_SERVER['HTTPS'] = 'on'; // Override $_SERVER to help external libraries with their HTTPS detection.
902 $_SERVER['SERVER_PORT'] = 443; // Assume default ssl port for the proxy.
905 // hopefully this will stop all those "clever" admins trying to set up moodle
906 // with two different addresses in intranet and Internet
907 if (!empty($CFG->reverseproxy) && $rurl['host'] === $wwwroot['host']) {
908 print_error('reverseproxyabused', 'error');
911 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
912 if (!empty($wwwroot['port'])) {
913 $hostandport .= ':'.$wwwroot['port'];
916 $FULLSCRIPT = $hostandport . $rurl['path'];
917 $FULLME = $hostandport . $rurl['fullpath'];
918 $ME = $rurl['fullpath'];
922 * Initialises $FULLME and friends for command line scripts.
923 * This is a private method for use by initialise_fullme.
925 function initialise_fullme_cli() {
926 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
928 // Urls do not make much sense in CLI scripts
929 $backtrace = debug_backtrace();
930 $topfile = array_pop($backtrace);
931 $topfile = realpath($topfile['file']);
932 $dirroot = realpath($CFG->dirroot);
934 if (strpos($topfile, $dirroot) !== 0) {
935 // Probably some weird external script
936 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
937 } else {
938 $relativefile = substr($topfile, strlen($dirroot));
939 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
940 $SCRIPT = $FULLSCRIPT = $relativefile;
941 $FULLME = $ME = null;
946 * Get the URL that PHP/the web server thinks it is serving. Private function
947 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
948 * @return array in the same format that parse_url returns, with the addition of
949 * a 'fullpath' element, which includes any slasharguments path.
951 function setup_get_remote_url() {
952 $rurl = array();
953 if (isset($_SERVER['HTTP_HOST'])) {
954 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
955 } else {
956 $rurl['host'] = null;
958 $rurl['port'] = $_SERVER['SERVER_PORT'];
959 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
960 $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ? 'http' : 'https';
962 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
963 //Apache server
964 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
966 // Fixing a known issue with:
967 // - Apache versions lesser than 2.4.11
968 // - PHP deployed in Apache as PHP-FPM via mod_proxy_fcgi
969 // - PHP versions lesser than 5.6.3 and 5.5.18.
970 if (isset($_SERVER['PATH_INFO']) && (php_sapi_name() === 'fpm-fcgi') && isset($_SERVER['SCRIPT_NAME'])) {
971 $pathinfodec = rawurldecode($_SERVER['PATH_INFO']);
972 $lenneedle = strlen($pathinfodec);
973 // Checks whether SCRIPT_NAME ends with PATH_INFO, URL-decoded.
974 if (substr($_SERVER['SCRIPT_NAME'], -$lenneedle) === $pathinfodec) {
975 // This is the "Apache 2.4.10- running PHP-FPM via mod_proxy_fcgi" fingerprint,
976 // 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)
977 // => SCRIPT_NAME contains 'slash arguments' data too, which is wrongly exposed via PATH_INFO as URL-encoded.
978 // Fix both $_SERVER['PATH_INFO'] and $_SERVER['SCRIPT_NAME'].
979 $lenhaystack = strlen($_SERVER['SCRIPT_NAME']);
980 $pos = $lenhaystack - $lenneedle;
981 // Here $pos is greater than 0 but let's double check it.
982 if ($pos > 0) {
983 $_SERVER['PATH_INFO'] = $pathinfodec;
984 $_SERVER['SCRIPT_NAME'] = substr($_SERVER['SCRIPT_NAME'], 0, $pos);
989 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
990 //IIS - needs a lot of tweaking to make it work
991 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
993 // NOTE: we should ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS.
994 // Since 2.0, we rely on IIS rewrite extensions like Helicon ISAPI_rewrite
995 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
996 // OR
997 // we rely on a proper IIS 6.0+ configuration: the 'FastCGIUtf8ServerVariables' registry key.
998 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
999 // Check that PATH_INFO works == must not contain the script name.
1000 if (strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === false) {
1001 $rurl['fullpath'] .= clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
1005 if (isset($_SERVER['QUERY_STRING']) and $_SERVER['QUERY_STRING'] !== '') {
1006 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
1008 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
1010 /* NOTE: following servers are not fully tested! */
1012 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
1013 //lighttpd - not officially supported
1014 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1016 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
1017 //nginx - not officially supported
1018 if (!isset($_SERVER['SCRIPT_NAME'])) {
1019 die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
1021 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1023 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
1024 //cherokee - not officially supported
1025 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1027 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
1028 //zeus - not officially supported
1029 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1031 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
1032 //LiteSpeed - not officially supported
1033 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1035 } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
1036 //obscure name found on some servers - this is definitely not supported
1037 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1039 } else if (strpos($_SERVER['SERVER_SOFTWARE'], 'PHP') === 0) {
1040 // built-in PHP Development Server
1041 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
1043 } else {
1044 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
1047 // sanitize the url a bit more, the encoding style may be different in vars above
1048 $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
1049 $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);
1051 return $rurl;
1055 * Try to work around the 'max_input_vars' restriction if necessary.
1057 function workaround_max_input_vars() {
1058 // Make sure this gets executed only once from lib/setup.php!
1059 static $executed = false;
1060 if ($executed) {
1061 debugging('workaround_max_input_vars() must be called only once!');
1062 return;
1064 $executed = true;
1066 if (!isset($_SERVER["CONTENT_TYPE"]) or strpos($_SERVER["CONTENT_TYPE"], 'multipart/form-data') !== false) {
1067 // Not a post or 'multipart/form-data' which is not compatible with "php://input" reading.
1068 return;
1071 if (!isloggedin() or isguestuser()) {
1072 // Only real users post huge forms.
1073 return;
1076 $max = (int)ini_get('max_input_vars');
1078 if ($max <= 0) {
1079 // Most probably PHP < 5.3.9 that does not implement this limit.
1080 return;
1083 if ($max >= 200000) {
1084 // This value should be ok for all our forms, by setting it in php.ini
1085 // admins may prevent any unexpected regressions caused by this hack.
1087 // Note there is no need to worry about DDoS caused by making this limit very high
1088 // because there are very many easier ways to DDoS any Moodle server.
1089 return;
1092 // Worst case is advanced checkboxes which use up to two max_input_vars
1093 // slots for each entry in $_POST, because of sending two fields with the
1094 // same name. So count everything twice just in case.
1095 if (count($_POST, COUNT_RECURSIVE) * 2 < $max) {
1096 return;
1099 // Large POST request with enctype supported by php://input.
1100 // Parse php://input in chunks to bypass max_input_vars limit, which also applies to parse_str().
1101 $str = file_get_contents("php://input");
1102 if ($str === false or $str === '') {
1103 // Some weird error.
1104 return;
1107 $delim = '&';
1108 $fun = function($p) use ($delim) {
1109 return implode($delim, $p);
1111 $chunks = array_map($fun, array_chunk(explode($delim, $str), $max));
1113 // Clear everything from existing $_POST array, otherwise it might be included
1114 // twice (this affects array params primarily).
1115 foreach ($_POST as $key => $value) {
1116 unset($_POST[$key]);
1117 // Also clear from request array - but only the things that are in $_POST,
1118 // that way it will leave the things from a get request if any.
1119 unset($_REQUEST[$key]);
1122 foreach ($chunks as $chunk) {
1123 $values = array();
1124 parse_str($chunk, $values);
1126 merge_query_params($_POST, $values);
1127 merge_query_params($_REQUEST, $values);
1132 * Merge parsed POST chunks.
1134 * NOTE: this is not perfect, but it should work in most cases hopefully.
1136 * @param array $target
1137 * @param array $values
1139 function merge_query_params(array &$target, array $values) {
1140 if (isset($values[0]) and isset($target[0])) {
1141 // This looks like a split [] array, lets verify the keys are continuous starting with 0.
1142 $keys1 = array_keys($values);
1143 $keys2 = array_keys($target);
1144 if ($keys1 === array_keys($keys1) and $keys2 === array_keys($keys2)) {
1145 foreach ($values as $v) {
1146 $target[] = $v;
1148 return;
1151 foreach ($values as $k => $v) {
1152 if (!isset($target[$k])) {
1153 $target[$k] = $v;
1154 continue;
1156 if (is_array($target[$k]) and is_array($v)) {
1157 merge_query_params($target[$k], $v);
1158 continue;
1160 // We should not get here unless there are duplicates in params.
1161 $target[$k] = $v;
1166 * Initializes our performance info early.
1168 * Pairs up with get_performance_info() which is actually
1169 * in moodlelib.php. This function is here so that we can
1170 * call it before all the libs are pulled in.
1172 * @uses $PERF
1174 function init_performance_info() {
1176 global $PERF, $CFG, $USER;
1178 $PERF = new stdClass();
1179 $PERF->logwrites = 0;
1180 if (function_exists('microtime')) {
1181 $PERF->starttime = microtime();
1183 if (function_exists('memory_get_usage')) {
1184 $PERF->startmemory = memory_get_usage();
1186 if (function_exists('posix_times')) {
1187 $PERF->startposixtimes = posix_times();
1192 * Indicates whether we are in the middle of the initial Moodle install.
1194 * Very occasionally it is necessary avoid running certain bits of code before the
1195 * Moodle installation has completed. The installed flag is set in admin/index.php
1196 * after Moodle core and all the plugins have been installed, but just before
1197 * the person doing the initial install is asked to choose the admin password.
1199 * @return boolean true if the initial install is not complete.
1201 function during_initial_install() {
1202 global $CFG;
1203 return empty($CFG->rolesactive);
1207 * Function to raise the memory limit to a new value.
1208 * Will respect the memory limit if it is higher, thus allowing
1209 * settings in php.ini, apache conf or command line switches
1210 * to override it.
1212 * The memory limit should be expressed with a constant
1213 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
1214 * It is possible to use strings or integers too (eg:'128M').
1216 * @param mixed $newlimit the new memory limit
1217 * @return bool success
1219 function raise_memory_limit($newlimit) {
1220 global $CFG;
1222 if ($newlimit == MEMORY_UNLIMITED) {
1223 ini_set('memory_limit', -1);
1224 return true;
1226 } else if ($newlimit == MEMORY_STANDARD) {
1227 if (PHP_INT_SIZE > 4) {
1228 $newlimit = get_real_size('128M'); // 64bit needs more memory
1229 } else {
1230 $newlimit = get_real_size('96M');
1233 } else if ($newlimit == MEMORY_EXTRA) {
1234 if (PHP_INT_SIZE > 4) {
1235 $newlimit = get_real_size('384M'); // 64bit needs more memory
1236 } else {
1237 $newlimit = get_real_size('256M');
1239 if (!empty($CFG->extramemorylimit)) {
1240 $extra = get_real_size($CFG->extramemorylimit);
1241 if ($extra > $newlimit) {
1242 $newlimit = $extra;
1246 } else if ($newlimit == MEMORY_HUGE) {
1247 // MEMORY_HUGE uses 2G or MEMORY_EXTRA, whichever is bigger.
1248 $newlimit = get_real_size('2G');
1249 if (!empty($CFG->extramemorylimit)) {
1250 $extra = get_real_size($CFG->extramemorylimit);
1251 if ($extra > $newlimit) {
1252 $newlimit = $extra;
1256 } else {
1257 $newlimit = get_real_size($newlimit);
1260 if ($newlimit <= 0) {
1261 debugging('Invalid memory limit specified.');
1262 return false;
1265 $cur = ini_get('memory_limit');
1266 if (empty($cur)) {
1267 // if php is compiled without --enable-memory-limits
1268 // apparently memory_limit is set to ''
1269 $cur = 0;
1270 } else {
1271 if ($cur == -1){
1272 return true; // unlimited mem!
1274 $cur = get_real_size($cur);
1277 if ($newlimit > $cur) {
1278 ini_set('memory_limit', $newlimit);
1279 return true;
1281 return false;
1285 * Function to reduce the memory limit to a new value.
1286 * Will respect the memory limit if it is lower, thus allowing
1287 * settings in php.ini, apache conf or command line switches
1288 * to override it
1290 * The memory limit should be expressed with a string (eg:'64M')
1292 * @param string $newlimit the new memory limit
1293 * @return bool
1295 function reduce_memory_limit($newlimit) {
1296 if (empty($newlimit)) {
1297 return false;
1299 $cur = ini_get('memory_limit');
1300 if (empty($cur)) {
1301 // if php is compiled without --enable-memory-limits
1302 // apparently memory_limit is set to ''
1303 $cur = 0;
1304 } else {
1305 if ($cur == -1){
1306 return true; // unlimited mem!
1308 $cur = get_real_size($cur);
1311 $new = get_real_size($newlimit);
1312 // -1 is smaller, but it means unlimited
1313 if ($new < $cur && $new != -1) {
1314 ini_set('memory_limit', $newlimit);
1315 return true;
1317 return false;
1321 * Converts numbers like 10M into bytes.
1323 * @param string $size The size to be converted
1324 * @return int
1326 function get_real_size($size = 0) {
1327 if (!$size) {
1328 return 0;
1331 static $binaryprefixes = array(
1332 'K' => 1024,
1333 'k' => 1024,
1334 'M' => 1048576,
1335 'm' => 1048576,
1336 'G' => 1073741824,
1337 'g' => 1073741824,
1338 'T' => 1099511627776,
1339 't' => 1099511627776,
1342 if (preg_match('/^([0-9]+)([KMGT])/i', $size, $matches)) {
1343 return $matches[1] * $binaryprefixes[$matches[2]];
1346 return (int) $size;
1350 * Try to disable all output buffering and purge
1351 * all headers.
1353 * @access private to be called only from lib/setup.php !
1354 * @return void
1356 function disable_output_buffering() {
1357 $olddebug = error_reporting(0);
1359 // disable compression, it would prevent closing of buffers
1360 if (ini_get_bool('zlib.output_compression')) {
1361 ini_set('zlib.output_compression', 'Off');
1364 // try to flush everything all the time
1365 ob_implicit_flush(true);
1367 // close all buffers if possible and discard any existing output
1368 // this can actually work around some whitespace problems in config.php
1369 while(ob_get_level()) {
1370 if (!ob_end_clean()) {
1371 // prevent infinite loop when buffer can not be closed
1372 break;
1376 // disable any other output handlers
1377 ini_set('output_handler', '');
1379 error_reporting($olddebug);
1381 // Disable buffering in nginx.
1382 header('X-Accel-Buffering: no');
1387 * Check whether a major upgrade is needed.
1389 * That is defined as an upgrade that changes something really fundamental
1390 * in the database, so nothing can possibly work until the database has
1391 * been updated, and that is defined by the hard-coded version number in
1392 * this function.
1394 * @return bool
1396 function is_major_upgrade_required() {
1397 global $CFG;
1398 $lastmajordbchanges = 2017092900.00;
1400 $required = empty($CFG->version);
1401 $required = $required || (float)$CFG->version < $lastmajordbchanges;
1402 $required = $required || during_initial_install();
1403 $required = $required || !empty($CFG->adminsetuppending);
1405 return $required;
1409 * Redirect to the Notifications page if a major upgrade is required, and
1410 * terminate the current user session.
1412 function redirect_if_major_upgrade_required() {
1413 global $CFG;
1414 if (is_major_upgrade_required()) {
1415 try {
1416 @\core\session\manager::terminate_current();
1417 } catch (Exception $e) {
1418 // Ignore any errors, redirect to upgrade anyway.
1420 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
1421 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1422 @header('Location: ' . $url);
1423 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
1424 exit;
1429 * Makes sure that upgrade process is not running
1431 * To be inserted in the core functions that can not be called by pluigns during upgrade.
1432 * Core upgrade should not use any API functions at all.
1433 * See {@link http://docs.moodle.org/dev/Upgrade_API#Upgrade_code_restrictions}
1435 * @throws moodle_exception if executed from inside of upgrade script and $warningonly is false
1436 * @param bool $warningonly if true displays a warning instead of throwing an exception
1437 * @return bool true if executed from outside of upgrade process, false if from inside upgrade process and function is used for warning only
1439 function upgrade_ensure_not_running($warningonly = false) {
1440 global $CFG;
1441 if (!empty($CFG->upgraderunning)) {
1442 if (!$warningonly) {
1443 throw new moodle_exception('cannotexecduringupgrade');
1444 } else {
1445 debugging(get_string('cannotexecduringupgrade', 'error'), DEBUG_DEVELOPER);
1446 return false;
1449 return true;
1453 * Function to check if a directory exists and by default create it if not exists.
1455 * Previously this was accepting paths only from dataroot, but we now allow
1456 * files outside of dataroot if you supply custom paths for some settings in config.php.
1457 * This function does not verify that the directory is writable.
1459 * NOTE: this function uses current file stat cache,
1460 * please use clearstatcache() before this if you expect that the
1461 * directories may have been removed recently from a different request.
1463 * @param string $dir absolute directory path
1464 * @param boolean $create directory if does not exist
1465 * @param boolean $recursive create directory recursively
1466 * @return boolean true if directory exists or created, false otherwise
1468 function check_dir_exists($dir, $create = true, $recursive = true) {
1469 global $CFG;
1471 umask($CFG->umaskpermissions);
1473 if (is_dir($dir)) {
1474 return true;
1477 if (!$create) {
1478 return false;
1481 return mkdir($dir, $CFG->directorypermissions, $recursive);
1485 * Create a new unique directory within the specified directory.
1487 * @param string $basedir The directory to create your new unique directory within.
1488 * @param bool $exceptiononerror throw exception if error encountered
1489 * @return string The created directory
1490 * @throws invalid_dataroot_permissions
1492 function make_unique_writable_directory($basedir, $exceptiononerror = true) {
1493 if (!is_dir($basedir) || !is_writable($basedir)) {
1494 // The basedir is not writable. We will not be able to create the child directory.
1495 if ($exceptiononerror) {
1496 throw new invalid_dataroot_permissions($basedir . ' is not writable. Unable to create a unique directory within it.');
1497 } else {
1498 return false;
1502 do {
1503 // Generate a new (hopefully unique) directory name.
1504 $uniquedir = $basedir . DIRECTORY_SEPARATOR . generate_uuid();
1505 } while (
1506 // Ensure that basedir is still writable - if we do not check, we could get stuck in a loop here.
1507 is_writable($basedir) &&
1509 // Make the new unique directory. If the directory already exists, it will return false.
1510 !make_writable_directory($uniquedir, $exceptiononerror) &&
1512 // Ensure that the directory now exists
1513 file_exists($uniquedir) && is_dir($uniquedir)
1516 // Check that the directory was correctly created.
1517 if (!file_exists($uniquedir) || !is_dir($uniquedir) || !is_writable($uniquedir)) {
1518 if ($exceptiononerror) {
1519 throw new invalid_dataroot_permissions('Unique directory creation failed.');
1520 } else {
1521 return false;
1525 return $uniquedir;
1529 * Create a directory and make sure it is writable.
1531 * @private
1532 * @param string $dir the full path of the directory to be created
1533 * @param bool $exceptiononerror throw exception if error encountered
1534 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1536 function make_writable_directory($dir, $exceptiononerror = true) {
1537 global $CFG;
1539 if (file_exists($dir) and !is_dir($dir)) {
1540 if ($exceptiononerror) {
1541 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1542 } else {
1543 return false;
1547 umask($CFG->umaskpermissions);
1549 if (!file_exists($dir)) {
1550 if (!@mkdir($dir, $CFG->directorypermissions, true)) {
1551 clearstatcache();
1552 // There might be a race condition when creating directory.
1553 if (!is_dir($dir)) {
1554 if ($exceptiononerror) {
1555 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1556 } else {
1557 debugging('Can not create directory: '.$dir, DEBUG_DEVELOPER);
1558 return false;
1564 if (!is_writable($dir)) {
1565 if ($exceptiononerror) {
1566 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1567 } else {
1568 return false;
1572 return $dir;
1576 * Protect a directory from web access.
1577 * Could be extended in the future to support other mechanisms (e.g. other webservers).
1579 * @private
1580 * @param string $dir the full path of the directory to be protected
1582 function protect_directory($dir) {
1583 global $CFG;
1584 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1585 if (!file_exists("$dir/.htaccess")) {
1586 if ($handle = fopen("$dir/.htaccess", 'w')) { // For safety
1587 @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");
1588 @fclose($handle);
1589 @chmod("$dir/.htaccess", $CFG->filepermissions);
1595 * Create a directory under dataroot and make sure it is writable.
1596 * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
1598 * @param string $directory the full path of the directory to be created under $CFG->dataroot
1599 * @param bool $exceptiononerror throw exception if error encountered
1600 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1602 function make_upload_directory($directory, $exceptiononerror = true) {
1603 global $CFG;
1605 if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1606 debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1608 } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
1609 debugging('Use make_cache_directory() for creation of cache directory and $CFG->cachedir to get the location.');
1611 } else if (strpos($directory, 'localcache/') === 0 or $directory === 'localcache') {
1612 debugging('Use make_localcache_directory() for creation of local cache directory and $CFG->localcachedir to get the location.');
1615 protect_directory($CFG->dataroot);
1616 return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1620 * Get a per-request storage directory in the tempdir.
1622 * The directory is automatically cleaned up during the shutdown handler.
1624 * @param bool $exceptiononerror throw exception if error encountered
1625 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1627 function get_request_storage_directory($exceptiononerror = true) {
1628 global $CFG;
1630 static $requestdir = null;
1632 if (!$requestdir || !file_exists($requestdir) || !is_dir($requestdir) || !is_writable($requestdir)) {
1633 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1634 check_dir_exists($CFG->localcachedir, true, true);
1635 protect_directory($CFG->localcachedir);
1636 } else {
1637 protect_directory($CFG->dataroot);
1640 if ($requestdir = make_unique_writable_directory($CFG->localcachedir, $exceptiononerror)) {
1641 // Register a shutdown handler to remove the directory.
1642 \core_shutdown_manager::register_function('remove_dir', array($requestdir));
1646 return $requestdir;
1650 * Create a per-request directory and make sure it is writable.
1651 * This can only be used during the current request and will be tidied away
1652 * automatically afterwards.
1654 * A new, unique directory is always created within the current request directory.
1656 * @param bool $exceptiononerror throw exception if error encountered
1657 * @return string full path to directory if successful, false if not; may throw exception
1659 function make_request_directory($exceptiononerror = true) {
1660 $basedir = get_request_storage_directory($exceptiononerror);
1661 return make_unique_writable_directory($basedir, $exceptiononerror);
1665 * Get the full path of a directory under $CFG->backuptempdir.
1667 * @param string $directory the relative path of the directory under $CFG->backuptempdir
1668 * @return string|false Returns full path to directory given a valid string; otherwise, false.
1670 function get_backup_temp_directory($directory) {
1671 global $CFG;
1672 if (($directory === null) || ($directory === false)) {
1673 return false;
1675 return "$CFG->backuptempdir/$directory";
1679 * Create a directory under $CFG->backuptempdir and make sure it is writable.
1681 * Do not use for storing generic temp files - see make_temp_directory() instead for this purpose.
1683 * Backup temporary files must be on a shared storage.
1685 * @param string $directory the relative path of the directory to be created under $CFG->backuptempdir
1686 * @param bool $exceptiononerror throw exception if error encountered
1687 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1689 function make_backup_temp_directory($directory, $exceptiononerror = true) {
1690 global $CFG;
1691 if ($CFG->backuptempdir !== "$CFG->tempdir/backup") {
1692 check_dir_exists($CFG->backuptempdir, true, true);
1693 protect_directory($CFG->backuptempdir);
1694 } else {
1695 protect_directory($CFG->tempdir);
1697 return make_writable_directory("$CFG->backuptempdir/$directory", $exceptiononerror);
1701 * Create a directory under tempdir and make sure it is writable.
1703 * Where possible, please use make_request_directory() and limit the scope
1704 * of your data to the current HTTP request.
1706 * Do not use for storing cache files - see make_cache_directory(), and
1707 * make_localcache_directory() instead for this purpose.
1709 * Temporary files must be on a shared storage, and heavy usage is
1710 * discouraged due to the performance impact upon clustered environments.
1712 * @param string $directory the full path of the directory to be created under $CFG->tempdir
1713 * @param bool $exceptiononerror throw exception if error encountered
1714 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1716 function make_temp_directory($directory, $exceptiononerror = true) {
1717 global $CFG;
1718 if ($CFG->tempdir !== "$CFG->dataroot/temp") {
1719 check_dir_exists($CFG->tempdir, true, true);
1720 protect_directory($CFG->tempdir);
1721 } else {
1722 protect_directory($CFG->dataroot);
1724 return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1728 * Create a directory under cachedir and make sure it is writable.
1730 * Note: this cache directory is shared by all cluster nodes.
1732 * @param string $directory the full path of the directory to be created under $CFG->cachedir
1733 * @param bool $exceptiononerror throw exception if error encountered
1734 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1736 function make_cache_directory($directory, $exceptiononerror = true) {
1737 global $CFG;
1738 if ($CFG->cachedir !== "$CFG->dataroot/cache") {
1739 check_dir_exists($CFG->cachedir, true, true);
1740 protect_directory($CFG->cachedir);
1741 } else {
1742 protect_directory($CFG->dataroot);
1744 return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1748 * Create a directory under localcachedir and make sure it is writable.
1749 * The files in this directory MUST NOT change, use revisions or content hashes to
1750 * work around this limitation - this means you can only add new files here.
1752 * The content of this directory gets purged automatically on all cluster nodes
1753 * after calling purge_all_caches() before new data is written to this directory.
1755 * Note: this local cache directory does not need to be shared by cluster nodes.
1757 * @param string $directory the relative path of the directory to be created under $CFG->localcachedir
1758 * @param bool $exceptiononerror throw exception if error encountered
1759 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1761 function make_localcache_directory($directory, $exceptiononerror = true) {
1762 global $CFG;
1764 make_writable_directory($CFG->localcachedir, $exceptiononerror);
1766 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1767 protect_directory($CFG->localcachedir);
1768 } else {
1769 protect_directory($CFG->dataroot);
1772 if (!isset($CFG->localcachedirpurged)) {
1773 $CFG->localcachedirpurged = 0;
1775 $timestampfile = "$CFG->localcachedir/.lastpurged";
1777 if (!file_exists($timestampfile)) {
1778 touch($timestampfile);
1779 @chmod($timestampfile, $CFG->filepermissions);
1781 } else if (filemtime($timestampfile) < $CFG->localcachedirpurged) {
1782 // This means our local cached dir was not purged yet.
1783 remove_dir($CFG->localcachedir, true);
1784 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1785 protect_directory($CFG->localcachedir);
1787 touch($timestampfile);
1788 @chmod($timestampfile, $CFG->filepermissions);
1789 clearstatcache();
1792 if ($directory === '') {
1793 return $CFG->localcachedir;
1796 return make_writable_directory("$CFG->localcachedir/$directory", $exceptiononerror);
1800 * This class solves the problem of how to initialise $OUTPUT.
1802 * The problem is caused be two factors
1803 * <ol>
1804 * <li>On the one hand, we cannot be sure when output will start. In particular,
1805 * an error, which needs to be displayed, could be thrown at any time.</li>
1806 * <li>On the other hand, we cannot be sure when we will have all the information
1807 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1808 * (potentially) depends on the current course, course categories, and logged in user.
1809 * It also depends on whether the current page requires HTTPS.</li>
1810 * </ol>
1812 * So, it is hard to find a single natural place during Moodle script execution,
1813 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1814 * adopt the following strategy
1815 * <ol>
1816 * <li>We will initialise $OUTPUT the first time it is used.</li>
1817 * <li>If, after $OUTPUT has been initialised, the script tries to change something
1818 * that $OUTPUT depends on, we throw an exception making it clear that the script
1819 * did something wrong.
1820 * </ol>
1822 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1823 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1824 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1825 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1827 * Note that this class is used before lib/outputlib.php has been loaded, so we
1828 * must be careful referring to classes/functions from there, they may not be
1829 * defined yet, and we must avoid fatal errors.
1831 * @copyright 2009 Tim Hunt
1832 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1833 * @since Moodle 2.0
1835 class bootstrap_renderer {
1837 * Handles re-entrancy. Without this, errors or debugging output that occur
1838 * during the initialisation of $OUTPUT, cause infinite recursion.
1839 * @var boolean
1841 protected $initialising = false;
1844 * Have we started output yet?
1845 * @return boolean true if the header has been printed.
1847 public function has_started() {
1848 return false;
1852 * Constructor - to be used by core code only.
1853 * @param string $method The method to call
1854 * @param array $arguments Arguments to pass to the method being called
1855 * @return string
1857 public function __call($method, $arguments) {
1858 global $OUTPUT, $PAGE;
1860 $recursing = false;
1861 if ($method == 'notification') {
1862 // Catch infinite recursion caused by debugging output during print_header.
1863 $backtrace = debug_backtrace();
1864 array_shift($backtrace);
1865 array_shift($backtrace);
1866 $recursing = is_early_init($backtrace);
1869 $earlymethods = array(
1870 'fatal_error' => 'early_error',
1871 'notification' => 'early_notification',
1874 // If lib/outputlib.php has been loaded, call it.
1875 if (!empty($PAGE) && !$recursing) {
1876 if (array_key_exists($method, $earlymethods)) {
1877 //prevent PAGE->context warnings - exceptions might appear before we set any context
1878 $PAGE->set_context(null);
1880 $PAGE->initialise_theme_and_output();
1881 return call_user_func_array(array($OUTPUT, $method), $arguments);
1884 $this->initialising = true;
1886 // Too soon to initialise $OUTPUT, provide a couple of key methods.
1887 if (array_key_exists($method, $earlymethods)) {
1888 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1891 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1895 * Returns nicely formatted error message in a div box.
1896 * @static
1897 * @param string $message error message
1898 * @param string $moreinfourl (ignored in early errors)
1899 * @param string $link (ignored in early errors)
1900 * @param array $backtrace
1901 * @param string $debuginfo
1902 * @return string
1904 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1905 global $CFG;
1907 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1908 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1909 width: 80%; -moz-border-radius: 20px; padding: 15px">
1910 ' . $message . '
1911 </div>';
1912 // Check whether debug is set.
1913 $debug = (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER);
1914 // Also check we have it set in the config file. This occurs if the method to read the config table from the
1915 // database fails, reading from the config table is the first database interaction we have.
1916 $debug = $debug || (!empty($CFG->config_php_settings['debug']) && $CFG->config_php_settings['debug'] >= DEBUG_DEVELOPER );
1917 if ($debug) {
1918 if (!empty($debuginfo)) {
1919 $debuginfo = s($debuginfo); // removes all nasty JS
1920 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1921 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
1923 if (!empty($backtrace)) {
1924 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1928 return $content;
1932 * This function should only be called by this class, or from exception handlers
1933 * @static
1934 * @param string $message error message
1935 * @param string $moreinfourl (ignored in early errors)
1936 * @param string $link (ignored in early errors)
1937 * @param array $backtrace
1938 * @param string $debuginfo extra information for developers
1939 * @return string
1941 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = null) {
1942 global $CFG;
1944 if (CLI_SCRIPT) {
1945 echo "!!! $message !!!\n";
1946 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1947 if (!empty($debuginfo)) {
1948 echo "\nDebug info: $debuginfo";
1950 if (!empty($backtrace)) {
1951 echo "\nStack trace: " . format_backtrace($backtrace, true);
1954 return;
1956 } else if (AJAX_SCRIPT) {
1957 $e = new stdClass();
1958 $e->error = $message;
1959 $e->stacktrace = NULL;
1960 $e->debuginfo = NULL;
1961 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1962 if (!empty($debuginfo)) {
1963 $e->debuginfo = $debuginfo;
1965 if (!empty($backtrace)) {
1966 $e->stacktrace = format_backtrace($backtrace, true);
1969 $e->errorcode = $errorcode;
1970 @header('Content-Type: application/json; charset=utf-8');
1971 echo json_encode($e);
1972 return;
1975 // In the name of protocol correctness, monitoring and performance
1976 // profiling, set the appropriate error headers for machine consumption.
1977 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
1978 @header($protocol . ' 503 Service Unavailable');
1980 // better disable any caching
1981 @header('Content-Type: text/html; charset=utf-8');
1982 @header('X-UA-Compatible: IE=edge');
1983 @header('Cache-Control: no-store, no-cache, must-revalidate');
1984 @header('Cache-Control: post-check=0, pre-check=0', false);
1985 @header('Pragma: no-cache');
1986 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1987 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1989 if (function_exists('get_string')) {
1990 $strerror = get_string('error');
1991 } else {
1992 $strerror = 'Error';
1995 $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
1997 return self::plain_page($strerror, $content);
2001 * Early notification message
2002 * @static
2003 * @param string $message
2004 * @param string $classes usually notifyproblem or notifysuccess
2005 * @return string
2007 public static function early_notification($message, $classes = 'notifyproblem') {
2008 return '<div class="' . $classes . '">' . $message . '</div>';
2012 * Page should redirect message.
2013 * @static
2014 * @param string $encodedurl redirect url
2015 * @return string
2017 public static function plain_redirect_message($encodedurl) {
2018 $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
2019 $encodedurl .'">'. get_string('continue') .'</a></div>';
2020 return self::plain_page(get_string('redirect'), $message);
2024 * Early redirection page, used before full init of $PAGE global
2025 * @static
2026 * @param string $encodedurl redirect url
2027 * @param string $message redirect message
2028 * @param int $delay time in seconds
2029 * @return string redirect page
2031 public static function early_redirect_message($encodedurl, $message, $delay) {
2032 $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
2033 $content = self::early_error_content($message, null, null, null);
2034 $content .= self::plain_redirect_message($encodedurl);
2036 return self::plain_page(get_string('redirect'), $content, $meta);
2040 * Output basic html page.
2041 * @static
2042 * @param string $title page title
2043 * @param string $content page content
2044 * @param string $meta meta tag
2045 * @return string html page
2047 public static function plain_page($title, $content, $meta = '') {
2048 if (function_exists('get_string') && function_exists('get_html_lang')) {
2049 $htmllang = get_html_lang();
2050 } else {
2051 $htmllang = '';
2054 $footer = '';
2055 if (MDL_PERF_TEST) {
2056 $perfinfo = get_performance_info();
2057 $footer = '<footer>' . $perfinfo['html'] . '</footer>';
2060 return '<!DOCTYPE html>
2061 <html ' . $htmllang . '>
2062 <head>
2063 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
2064 '.$meta.'
2065 <title>' . $title . '</title>
2066 </head><body>' . $content . $footer . '</body></html>';