MDL-52105 enrol_self: Fix wrong holdkey cap restriction for manager
[moodle.git] / lib / setuplib.php
blobd3b7d1286ee79dce0a53ff5f2a35c83a59feb634
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 echo $OUTPUT->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
388 } catch (Exception $e) {
389 $out_ex = $e;
390 } catch (Throwable $e) {
391 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
392 $out_ex = $e;
395 if (isset($out_ex)) {
396 // default exception handler MUST not throw any exceptions!!
397 // 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
398 // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
399 if (CLI_SCRIPT or AJAX_SCRIPT) {
400 // just ignore the error and send something back using the safest method
401 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
402 } else {
403 echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
404 $outinfo = get_exception_info($out_ex);
405 echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
410 exit(1); // General error code
414 * Default error handler, prevents some white screens.
415 * @param int $errno
416 * @param string $errstr
417 * @param string $errfile
418 * @param int $errline
419 * @param array $errcontext
420 * @return bool false means use default error handler
422 function default_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
423 if ($errno == 4096) {
424 //fatal catchable error
425 throw new coding_exception('PHP catchable fatal error', $errstr);
427 return false;
431 * Unconditionally abort all database transactions, this function
432 * should be called from exception handlers only.
433 * @return void
435 function abort_all_db_transactions() {
436 global $CFG, $DB, $SCRIPT;
438 // default exception handler MUST not throw any exceptions!!
440 if ($DB && $DB->is_transaction_started()) {
441 error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
442 // note: transaction blocks should never change current $_SESSION
443 $DB->force_transaction_rollback();
448 * This function encapsulates the tests for whether an exception was thrown in
449 * early init -- either during setup.php or during init of $OUTPUT.
451 * If another exception is thrown then, and if we do not take special measures,
452 * we would just get a very cryptic message "Exception thrown without a stack
453 * frame in Unknown on line 0". That makes debugging very hard, so we do take
454 * special measures in default_exception_handler, with the help of this function.
456 * @param array $backtrace the stack trace to analyse.
457 * @return boolean whether the stack trace is somewhere in output initialisation.
459 function is_early_init($backtrace) {
460 $dangerouscode = array(
461 array('function' => 'header', 'type' => '->'),
462 array('class' => 'bootstrap_renderer'),
463 array('file' => __DIR__.'/setup.php'),
465 foreach ($backtrace as $stackframe) {
466 foreach ($dangerouscode as $pattern) {
467 $matches = true;
468 foreach ($pattern as $property => $value) {
469 if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
470 $matches = false;
473 if ($matches) {
474 return true;
478 return false;
482 * Abort execution by throwing of a general exception,
483 * default exception handler displays the error message in most cases.
485 * @param string $errorcode The name of the language string containing the error message.
486 * Normally this should be in the error.php lang file.
487 * @param string $module The language file to get the error message from.
488 * @param string $link The url where the user will be prompted to continue.
489 * If no url is provided the user will be directed to the site index page.
490 * @param object $a Extra words and phrases that might be required in the error string
491 * @param string $debuginfo optional debugging information
492 * @return void, always throws exception!
494 function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
495 throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
499 * Returns detailed information about specified exception.
500 * @param exception $ex
501 * @return object
503 function get_exception_info($ex) {
504 global $CFG, $DB, $SESSION;
506 if ($ex instanceof moodle_exception) {
507 $errorcode = $ex->errorcode;
508 $module = $ex->module;
509 $a = $ex->a;
510 $link = $ex->link;
511 $debuginfo = $ex->debuginfo;
512 } else {
513 $errorcode = 'generalexceptionmessage';
514 $module = 'error';
515 $a = $ex->getMessage();
516 $link = '';
517 $debuginfo = '';
520 // Append the error code to the debug info to make grepping and googling easier
521 $debuginfo .= PHP_EOL."Error code: $errorcode";
523 $backtrace = $ex->getTrace();
524 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
525 array_unshift($backtrace, $place);
527 // Be careful, no guarantee moodlelib.php is loaded.
528 if (empty($module) || $module == 'moodle' || $module == 'core') {
529 $module = 'error';
531 // Search for the $errorcode's associated string
532 // If not found, append the contents of $a to $debuginfo so helpful information isn't lost
533 if (function_exists('get_string_manager')) {
534 if (get_string_manager()->string_exists($errorcode, $module)) {
535 $message = get_string($errorcode, $module, $a);
536 } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
537 // Search in moodle file if error specified - needed for backwards compatibility
538 $message = get_string($errorcode, 'moodle', $a);
539 } else {
540 $message = $module . '/' . $errorcode;
541 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
543 } else {
544 $message = $module . '/' . $errorcode;
545 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
548 // Remove some absolute paths from message and debugging info.
549 $searches = array();
550 $replaces = array();
551 $cfgnames = array('tempdir', 'cachedir', 'localcachedir', 'themedir', 'dataroot', 'dirroot');
552 foreach ($cfgnames as $cfgname) {
553 if (property_exists($CFG, $cfgname)) {
554 $searches[] = $CFG->$cfgname;
555 $replaces[] = "[$cfgname]";
558 if (!empty($searches)) {
559 $message = str_replace($searches, $replaces, $message);
560 $debuginfo = str_replace($searches, $replaces, $debuginfo);
563 // Be careful, no guarantee weblib.php is loaded.
564 if (function_exists('clean_text')) {
565 $message = clean_text($message);
566 } else {
567 $message = htmlspecialchars($message);
570 if (!empty($CFG->errordocroot)) {
571 $errordoclink = $CFG->errordocroot . '/en/';
572 } else {
573 $errordoclink = get_docs_url();
576 if ($module === 'error') {
577 $modulelink = 'moodle';
578 } else {
579 $modulelink = $module;
581 $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
583 if (empty($link)) {
584 if (!empty($SESSION->fromurl)) {
585 $link = $SESSION->fromurl;
586 unset($SESSION->fromurl);
587 } else {
588 $link = $CFG->wwwroot .'/';
592 // When printing an error the continue button should never link offsite.
593 // We cannot use clean_param() here as it is not guaranteed that it has been loaded yet.
594 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
595 if (stripos($link, $CFG->wwwroot) === 0) {
596 // Internal HTTP, all good.
597 } else if (!empty($CFG->loginhttps) && stripos($link, $httpswwwroot) === 0) {
598 // Internal HTTPS, all good.
599 } else {
600 // External link spotted!
601 $link = $CFG->wwwroot . '/';
604 $info = new stdClass();
605 $info->message = $message;
606 $info->errorcode = $errorcode;
607 $info->backtrace = $backtrace;
608 $info->link = $link;
609 $info->moreinfourl = $moreinfourl;
610 $info->a = $a;
611 $info->debuginfo = $debuginfo;
613 return $info;
617 * Generate a uuid.
619 * Unique is hard. Very hard. Attempt to use the PECL UUID functions if available, and if not then revert to
620 * constructing the uuid using mt_rand.
622 * It is important that this token is not solely based on time as this could lead
623 * to duplicates in a clustered environment (especially on VMs due to poor time precision).
625 * @return string The uuid.
627 function generate_uuid() {
628 $uuid = '';
630 if (function_exists("uuid_create")) {
631 $context = null;
632 uuid_create($context);
634 uuid_make($context, UUID_MAKE_V4);
635 uuid_export($context, UUID_FMT_STR, $uuid);
636 } else {
637 // Fallback uuid generation based on:
638 // "http://www.php.net/manual/en/function.uniqid.php#94959".
639 $uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
641 // 32 bits for "time_low".
642 mt_rand(0, 0xffff), mt_rand(0, 0xffff),
644 // 16 bits for "time_mid".
645 mt_rand(0, 0xffff),
647 // 16 bits for "time_hi_and_version",
648 // four most significant bits holds version number 4.
649 mt_rand(0, 0x0fff) | 0x4000,
651 // 16 bits, 8 bits for "clk_seq_hi_res",
652 // 8 bits for "clk_seq_low",
653 // two most significant bits holds zero and one for variant DCE1.1.
654 mt_rand(0, 0x3fff) | 0x8000,
656 // 48 bits for "node".
657 mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
659 return trim($uuid);
663 * Returns the Moodle Docs URL in the users language for a given 'More help' link.
665 * There are three cases:
667 * 1. In the normal case, $path will be a short relative path 'component/thing',
668 * like 'mod/folder/view' 'group/import'. This gets turned into an link to
669 * MoodleDocs in the user's language, and for the appropriate Moodle version.
670 * E.g. 'group/import' may become 'http://docs.moodle.org/2x/en/group/import'.
671 * The 'http://docs.moodle.org' bit comes from $CFG->docroot.
673 * This is the only option that should be used in standard Moodle code. The other
674 * two options have been implemented because they are useful for third-party plugins.
676 * 2. $path may be an absolute URL, starting http:// or https://. In this case,
677 * the link is used as is.
679 * 3. $path may start %%WWWROOT%%, in which case that is replaced by
680 * $CFG->wwwroot to make the link.
682 * @param string $path the place to link to. See above for details.
683 * @return string The MoodleDocs URL in the user's language. for example @link http://docs.moodle.org/2x/en/$path}
685 function get_docs_url($path = null) {
686 global $CFG;
688 // Absolute URLs are used unmodified.
689 if (substr($path, 0, 7) === 'http://' || substr($path, 0, 8) === 'https://') {
690 return $path;
693 // Paths starting %%WWWROOT%% have that replaced by $CFG->wwwroot.
694 if (substr($path, 0, 11) === '%%WWWROOT%%') {
695 return $CFG->wwwroot . substr($path, 11);
698 // Otherwise we do the normal case, and construct a MoodleDocs URL relative to $CFG->docroot.
700 // Check that $CFG->branch has been set up, during installation it won't be.
701 if (empty($CFG->branch)) {
702 // It's not there yet so look at version.php.
703 include($CFG->dirroot.'/version.php');
704 } else {
705 // We can use $CFG->branch and avoid having to include version.php.
706 $branch = $CFG->branch;
708 // ensure branch is valid.
709 if (!$branch) {
710 // We should never get here but in case we do lets set $branch to .
711 // the smart one's will know that this is the current directory
712 // and the smarter ones will know that there is some smart matching
713 // that will ensure people end up at the latest version of the docs.
714 $branch = '.';
716 if (empty($CFG->doclang)) {
717 $lang = current_language();
718 } else {
719 $lang = $CFG->doclang;
721 $end = '/' . $branch . '/' . $lang . '/' . $path;
722 if (empty($CFG->docroot)) {
723 return 'http://docs.moodle.org'. $end;
724 } else {
725 return $CFG->docroot . $end ;
730 * Formats a backtrace ready for output.
732 * @param array $callers backtrace array, as returned by debug_backtrace().
733 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
734 * @return string formatted backtrace, ready for output.
736 function format_backtrace($callers, $plaintext = false) {
737 // do not use $CFG->dirroot because it might not be available in destructors
738 $dirroot = dirname(__DIR__);
740 if (empty($callers)) {
741 return '';
744 $from = $plaintext ? '' : '<ul style="text-align: left" data-rel="backtrace">';
745 foreach ($callers as $caller) {
746 if (!isset($caller['line'])) {
747 $caller['line'] = '?'; // probably call_user_func()
749 if (!isset($caller['file'])) {
750 $caller['file'] = 'unknownfile'; // probably call_user_func()
752 $from .= $plaintext ? '* ' : '<li>';
753 $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
754 if (isset($caller['function'])) {
755 $from .= ': call to ';
756 if (isset($caller['class'])) {
757 $from .= $caller['class'] . $caller['type'];
759 $from .= $caller['function'] . '()';
760 } else if (isset($caller['exception'])) {
761 $from .= ': '.$caller['exception'].' thrown';
763 $from .= $plaintext ? "\n" : '</li>';
765 $from .= $plaintext ? '' : '</ul>';
767 return $from;
771 * This function makes the return value of ini_get consistent if you are
772 * setting server directives through the .htaccess file in apache.
774 * Current behavior for value set from php.ini On = 1, Off = [blank]
775 * Current behavior for value set from .htaccess On = On, Off = Off
776 * Contributed by jdell @ unr.edu
778 * @param string $ini_get_arg The argument to get
779 * @return bool True for on false for not
781 function ini_get_bool($ini_get_arg) {
782 $temp = ini_get($ini_get_arg);
784 if ($temp == '1' or strtolower($temp) == 'on') {
785 return true;
787 return false;
791 * This function verifies the sanity of PHP configuration
792 * and stops execution if anything critical found.
794 function setup_validate_php_configuration() {
795 // this must be very fast - no slow checks here!!!
797 if (ini_get_bool('session.auto_start')) {
798 print_error('sessionautostartwarning', 'admin');
803 * Initialise global $CFG variable.
804 * @private to be used only from lib/setup.php
806 function initialise_cfg() {
807 global $CFG, $DB;
809 if (!$DB) {
810 // This should not happen.
811 return;
814 try {
815 $localcfg = get_config('core');
816 } catch (dml_exception $e) {
817 // Most probably empty db, going to install soon.
818 return;
821 foreach ($localcfg as $name => $value) {
822 // Note that get_config() keeps forced settings
823 // and normalises values to string if possible.
824 $CFG->{$name} = $value;
829 * Initialises $FULLME and friends. Private function. Should only be called from
830 * setup.php.
832 function initialise_fullme() {
833 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
835 // Detect common config error.
836 if (substr($CFG->wwwroot, -1) == '/') {
837 print_error('wwwrootslash', 'error');
840 if (CLI_SCRIPT) {
841 initialise_fullme_cli();
842 return;
845 $rurl = setup_get_remote_url();
846 $wwwroot = parse_url($CFG->wwwroot.'/');
848 if (empty($rurl['host'])) {
849 // missing host in request header, probably not a real browser, let's ignore them
851 } else if (!empty($CFG->reverseproxy)) {
852 // $CFG->reverseproxy specifies if reverse proxy server used
853 // Used in load balancing scenarios.
854 // Do not abuse this to try to solve lan/wan access problems!!!!!
856 } else {
857 if (($rurl['host'] !== $wwwroot['host']) or
858 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port']) or
859 (strpos($rurl['path'], $wwwroot['path']) !== 0)) {
861 // Explain the problem and redirect them to the right URL
862 if (!defined('NO_MOODLE_COOKIES')) {
863 define('NO_MOODLE_COOKIES', true);
865 // The login/token.php script should call the correct url/port.
866 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
867 $wwwrootport = empty($wwwroot['port'])?'':$wwwroot['port'];
868 $calledurl = $rurl['host'];
869 if (!empty($rurl['port'])) {
870 $calledurl .= ':'. $rurl['port'];
872 $correcturl = $wwwroot['host'];
873 if (!empty($wwwrootport)) {
874 $correcturl .= ':'. $wwwrootport;
876 throw new moodle_exception('requirecorrectaccess', 'error', '', null,
877 'You called ' . $calledurl .', you should have called ' . $correcturl);
879 redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
883 // Check that URL is under $CFG->wwwroot.
884 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
885 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
886 } else {
887 // Probably some weird external script
888 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
889 return;
892 // $CFG->sslproxy specifies if external SSL appliance is used
893 // (That is, the Moodle server uses http, with an external box translating everything to https).
894 if (empty($CFG->sslproxy)) {
895 if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
896 print_error('sslonlyaccess', 'error');
898 } else {
899 if ($wwwroot['scheme'] !== 'https') {
900 throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
902 $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
903 $_SERVER['HTTPS'] = 'on'; // Override $_SERVER to help external libraries with their HTTPS detection.
904 $_SERVER['SERVER_PORT'] = 443; // Assume default ssl port for the proxy.
907 // hopefully this will stop all those "clever" admins trying to set up moodle
908 // with two different addresses in intranet and Internet
909 if (!empty($CFG->reverseproxy) && $rurl['host'] === $wwwroot['host']) {
910 print_error('reverseproxyabused', 'error');
913 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
914 if (!empty($wwwroot['port'])) {
915 $hostandport .= ':'.$wwwroot['port'];
918 $FULLSCRIPT = $hostandport . $rurl['path'];
919 $FULLME = $hostandport . $rurl['fullpath'];
920 $ME = $rurl['fullpath'];
924 * Initialises $FULLME and friends for command line scripts.
925 * This is a private method for use by initialise_fullme.
927 function initialise_fullme_cli() {
928 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
930 // Urls do not make much sense in CLI scripts
931 $backtrace = debug_backtrace();
932 $topfile = array_pop($backtrace);
933 $topfile = realpath($topfile['file']);
934 $dirroot = realpath($CFG->dirroot);
936 if (strpos($topfile, $dirroot) !== 0) {
937 // Probably some weird external script
938 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
939 } else {
940 $relativefile = substr($topfile, strlen($dirroot));
941 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
942 $SCRIPT = $FULLSCRIPT = $relativefile;
943 $FULLME = $ME = null;
948 * Get the URL that PHP/the web server thinks it is serving. Private function
949 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
950 * @return array in the same format that parse_url returns, with the addition of
951 * a 'fullpath' element, which includes any slasharguments path.
953 function setup_get_remote_url() {
954 $rurl = array();
955 if (isset($_SERVER['HTTP_HOST'])) {
956 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
957 } else {
958 $rurl['host'] = null;
960 $rurl['port'] = $_SERVER['SERVER_PORT'];
961 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
962 $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ? 'http' : 'https';
964 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
965 //Apache server
966 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
968 // Fixing a known issue with:
969 // - Apache versions lesser than 2.4.11
970 // - PHP deployed in Apache as PHP-FPM via mod_proxy_fcgi
971 // - PHP versions lesser than 5.6.3 and 5.5.18.
972 if (isset($_SERVER['PATH_INFO']) && (php_sapi_name() === 'fpm-fcgi') && isset($_SERVER['SCRIPT_NAME'])) {
973 $pathinfodec = rawurldecode($_SERVER['PATH_INFO']);
974 $lenneedle = strlen($pathinfodec);
975 // Checks whether SCRIPT_NAME ends with PATH_INFO, URL-decoded.
976 if (substr($_SERVER['SCRIPT_NAME'], -$lenneedle) === $pathinfodec) {
977 // This is the "Apache 2.4.10- running PHP-FPM via mod_proxy_fcgi" fingerprint,
978 // 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)
979 // => SCRIPT_NAME contains 'slash arguments' data too, which is wrongly exposed via PATH_INFO as URL-encoded.
980 // Fix both $_SERVER['PATH_INFO'] and $_SERVER['SCRIPT_NAME'].
981 $lenhaystack = strlen($_SERVER['SCRIPT_NAME']);
982 $pos = $lenhaystack - $lenneedle;
983 // Here $pos is greater than 0 but let's double check it.
984 if ($pos > 0) {
985 $_SERVER['PATH_INFO'] = $pathinfodec;
986 $_SERVER['SCRIPT_NAME'] = substr($_SERVER['SCRIPT_NAME'], 0, $pos);
991 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
992 //IIS - needs a lot of tweaking to make it work
993 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
995 // NOTE: we should ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS.
996 // Since 2.0, we rely on IIS rewrite extensions like Helicon ISAPI_rewrite
997 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
998 // OR
999 // we rely on a proper IIS 6.0+ configuration: the 'FastCGIUtf8ServerVariables' registry key.
1000 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
1001 // Check that PATH_INFO works == must not contain the script name.
1002 if (strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === false) {
1003 $rurl['fullpath'] .= clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
1007 if (isset($_SERVER['QUERY_STRING']) and $_SERVER['QUERY_STRING'] !== '') {
1008 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
1010 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
1012 /* NOTE: following servers are not fully tested! */
1014 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
1015 //lighttpd - not officially supported
1016 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1018 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
1019 //nginx - not officially supported
1020 if (!isset($_SERVER['SCRIPT_NAME'])) {
1021 die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
1023 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1025 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
1026 //cherokee - not officially supported
1027 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1029 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
1030 //zeus - not officially supported
1031 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1033 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
1034 //LiteSpeed - not officially supported
1035 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1037 } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
1038 //obscure name found on some servers - this is definitely not supported
1039 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1041 } else if (strpos($_SERVER['SERVER_SOFTWARE'], 'PHP') === 0) {
1042 // built-in PHP Development Server
1043 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
1045 } else {
1046 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
1049 // sanitize the url a bit more, the encoding style may be different in vars above
1050 $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
1051 $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);
1053 return $rurl;
1057 * Try to work around the 'max_input_vars' restriction if necessary.
1059 function workaround_max_input_vars() {
1060 // Make sure this gets executed only once from lib/setup.php!
1061 static $executed = false;
1062 if ($executed) {
1063 debugging('workaround_max_input_vars() must be called only once!');
1064 return;
1066 $executed = true;
1068 if (!isset($_SERVER["CONTENT_TYPE"]) or strpos($_SERVER["CONTENT_TYPE"], 'multipart/form-data') !== false) {
1069 // Not a post or 'multipart/form-data' which is not compatible with "php://input" reading.
1070 return;
1073 if (!isloggedin() or isguestuser()) {
1074 // Only real users post huge forms.
1075 return;
1078 $max = (int)ini_get('max_input_vars');
1080 if ($max <= 0) {
1081 // Most probably PHP < 5.3.9 that does not implement this limit.
1082 return;
1085 if ($max >= 200000) {
1086 // This value should be ok for all our forms, by setting it in php.ini
1087 // admins may prevent any unexpected regressions caused by this hack.
1089 // Note there is no need to worry about DDoS caused by making this limit very high
1090 // because there are very many easier ways to DDoS any Moodle server.
1091 return;
1094 // Worst case is advanced checkboxes which use up to two max_input_vars
1095 // slots for each entry in $_POST, because of sending two fields with the
1096 // same name. So count everything twice just in case.
1097 if (count($_POST, COUNT_RECURSIVE) * 2 < $max) {
1098 return;
1101 // Large POST request with enctype supported by php://input.
1102 // Parse php://input in chunks to bypass max_input_vars limit, which also applies to parse_str().
1103 $str = file_get_contents("php://input");
1104 if ($str === false or $str === '') {
1105 // Some weird error.
1106 return;
1109 $delim = '&';
1110 $fun = create_function('$p', '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);
1383 * Check whether a major upgrade is needed. That is defined as an upgrade that
1384 * changes something really fundamental in the database, so nothing can possibly
1385 * work until the database has been updated, and that is defined by the hard-coded
1386 * version number in this function.
1388 function redirect_if_major_upgrade_required() {
1389 global $CFG;
1390 $lastmajordbchanges = 2014093001.00;
1391 if (empty($CFG->version) or (float)$CFG->version < $lastmajordbchanges or
1392 during_initial_install() or !empty($CFG->adminsetuppending)) {
1393 try {
1394 @\core\session\manager::terminate_current();
1395 } catch (Exception $e) {
1396 // Ignore any errors, redirect to upgrade anyway.
1398 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
1399 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1400 @header('Location: ' . $url);
1401 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
1402 exit;
1407 * Makes sure that upgrade process is not running
1409 * To be inserted in the core functions that can not be called by pluigns during upgrade.
1410 * Core upgrade should not use any API functions at all.
1411 * See {@link http://docs.moodle.org/dev/Upgrade_API#Upgrade_code_restrictions}
1413 * @throws moodle_exception if executed from inside of upgrade script and $warningonly is false
1414 * @param bool $warningonly if true displays a warning instead of throwing an exception
1415 * @return bool true if executed from outside of upgrade process, false if from inside upgrade process and function is used for warning only
1417 function upgrade_ensure_not_running($warningonly = false) {
1418 global $CFG;
1419 if (!empty($CFG->upgraderunning)) {
1420 if (!$warningonly) {
1421 throw new moodle_exception('cannotexecduringupgrade');
1422 } else {
1423 debugging(get_string('cannotexecduringupgrade', 'error'), DEBUG_DEVELOPER);
1424 return false;
1427 return true;
1431 * Function to check if a directory exists and by default create it if not exists.
1433 * Previously this was accepting paths only from dataroot, but we now allow
1434 * files outside of dataroot if you supply custom paths for some settings in config.php.
1435 * This function does not verify that the directory is writable.
1437 * NOTE: this function uses current file stat cache,
1438 * please use clearstatcache() before this if you expect that the
1439 * directories may have been removed recently from a different request.
1441 * @param string $dir absolute directory path
1442 * @param boolean $create directory if does not exist
1443 * @param boolean $recursive create directory recursively
1444 * @return boolean true if directory exists or created, false otherwise
1446 function check_dir_exists($dir, $create = true, $recursive = true) {
1447 global $CFG;
1449 umask($CFG->umaskpermissions);
1451 if (is_dir($dir)) {
1452 return true;
1455 if (!$create) {
1456 return false;
1459 return mkdir($dir, $CFG->directorypermissions, $recursive);
1463 * Create a new unique directory within the specified directory.
1465 * @param string $basedir The directory to create your new unique directory within.
1466 * @param bool $exceptiononerror throw exception if error encountered
1467 * @return string The created directory
1468 * @throws invalid_dataroot_permissions
1470 function make_unique_writable_directory($basedir, $exceptiononerror = true) {
1471 if (!is_dir($basedir) || !is_writable($basedir)) {
1472 // The basedir is not writable. We will not be able to create the child directory.
1473 if ($exceptiononerror) {
1474 throw new invalid_dataroot_permissions($basedir . ' is not writable. Unable to create a unique directory within it.');
1475 } else {
1476 return false;
1480 do {
1481 // Generate a new (hopefully unique) directory name.
1482 $uniquedir = $basedir . DIRECTORY_SEPARATOR . generate_uuid();
1483 } while (
1484 // Ensure that basedir is still writable - if we do not check, we could get stuck in a loop here.
1485 is_writable($basedir) &&
1487 // Make the new unique directory. If the directory already exists, it will return false.
1488 !make_writable_directory($uniquedir, $exceptiononerror) &&
1490 // Ensure that the directory now exists
1491 file_exists($uniquedir) && is_dir($uniquedir)
1494 // Check that the directory was correctly created.
1495 if (!file_exists($uniquedir) || !is_dir($uniquedir) || !is_writable($uniquedir)) {
1496 if ($exceptiononerror) {
1497 throw new invalid_dataroot_permissions('Unique directory creation failed.');
1498 } else {
1499 return false;
1503 return $uniquedir;
1507 * Create a directory and make sure it is writable.
1509 * @private
1510 * @param string $dir the full path of the directory to be created
1511 * @param bool $exceptiononerror throw exception if error encountered
1512 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1514 function make_writable_directory($dir, $exceptiononerror = true) {
1515 global $CFG;
1517 if (file_exists($dir) and !is_dir($dir)) {
1518 if ($exceptiononerror) {
1519 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1520 } else {
1521 return false;
1525 umask($CFG->umaskpermissions);
1527 if (!file_exists($dir)) {
1528 if (!@mkdir($dir, $CFG->directorypermissions, true)) {
1529 clearstatcache();
1530 // There might be a race condition when creating directory.
1531 if (!is_dir($dir)) {
1532 if ($exceptiononerror) {
1533 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1534 } else {
1535 debugging('Can not create directory: '.$dir, DEBUG_DEVELOPER);
1536 return false;
1542 if (!is_writable($dir)) {
1543 if ($exceptiononerror) {
1544 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1545 } else {
1546 return false;
1550 return $dir;
1554 * Protect a directory from web access.
1555 * Could be extended in the future to support other mechanisms (e.g. other webservers).
1557 * @private
1558 * @param string $dir the full path of the directory to be protected
1560 function protect_directory($dir) {
1561 global $CFG;
1562 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1563 if (!file_exists("$dir/.htaccess")) {
1564 if ($handle = fopen("$dir/.htaccess", 'w')) { // For safety
1565 @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");
1566 @fclose($handle);
1567 @chmod("$dir/.htaccess", $CFG->filepermissions);
1573 * Create a directory under dataroot and make sure it is writable.
1574 * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
1576 * @param string $directory the full path of the directory to be created under $CFG->dataroot
1577 * @param bool $exceptiononerror throw exception if error encountered
1578 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1580 function make_upload_directory($directory, $exceptiononerror = true) {
1581 global $CFG;
1583 if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1584 debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1586 } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
1587 debugging('Use make_cache_directory() for creation of cache directory and $CFG->cachedir to get the location.');
1589 } else if (strpos($directory, 'localcache/') === 0 or $directory === 'localcache') {
1590 debugging('Use make_localcache_directory() for creation of local cache directory and $CFG->localcachedir to get the location.');
1593 protect_directory($CFG->dataroot);
1594 return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1598 * Get a per-request storage directory in the tempdir.
1600 * The directory is automatically cleaned up during the shutdown handler.
1602 * @param bool $exceptiononerror throw exception if error encountered
1603 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1605 function get_request_storage_directory($exceptiononerror = true) {
1606 global $CFG;
1608 static $requestdir = null;
1610 if (!$requestdir || !file_exists($requestdir) || !is_dir($requestdir) || !is_writable($requestdir)) {
1611 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1612 check_dir_exists($CFG->localcachedir, true, true);
1613 protect_directory($CFG->localcachedir);
1614 } else {
1615 protect_directory($CFG->dataroot);
1618 if ($requestdir = make_unique_writable_directory($CFG->localcachedir, $exceptiononerror)) {
1619 // Register a shutdown handler to remove the directory.
1620 \core_shutdown_manager::register_function('remove_dir', array($requestdir));
1624 return $requestdir;
1628 * Create a per-request directory and make sure it is writable.
1629 * This can only be used during the current request and will be tidied away
1630 * automatically afterwards.
1632 * A new, unique directory is always created within the current request directory.
1634 * @param bool $exceptiononerror throw exception if error encountered
1635 * @return string full path to directory if successful, false if not; may throw exception
1637 function make_request_directory($exceptiononerror = true) {
1638 $basedir = get_request_storage_directory($exceptiononerror);
1639 return make_unique_writable_directory($basedir, $exceptiononerror);
1643 * Create a directory under tempdir and make sure it is writable.
1645 * Where possible, please use make_request_directory() and limit the scope
1646 * of your data to the current HTTP request.
1648 * Do not use for storing cache files - see make_cache_directory(), and
1649 * make_localcache_directory() instead for this purpose.
1651 * Temporary files must be on a shared storage, and heavy usage is
1652 * discouraged due to the performance impact upon clustered environments.
1654 * @param string $directory the full path of the directory to be created under $CFG->tempdir
1655 * @param bool $exceptiononerror throw exception if error encountered
1656 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1658 function make_temp_directory($directory, $exceptiononerror = true) {
1659 global $CFG;
1660 if ($CFG->tempdir !== "$CFG->dataroot/temp") {
1661 check_dir_exists($CFG->tempdir, true, true);
1662 protect_directory($CFG->tempdir);
1663 } else {
1664 protect_directory($CFG->dataroot);
1666 return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1670 * Create a directory under cachedir and make sure it is writable.
1672 * Note: this cache directory is shared by all cluster nodes.
1674 * @param string $directory the full path of the directory to be created under $CFG->cachedir
1675 * @param bool $exceptiononerror throw exception if error encountered
1676 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1678 function make_cache_directory($directory, $exceptiononerror = true) {
1679 global $CFG;
1680 if ($CFG->cachedir !== "$CFG->dataroot/cache") {
1681 check_dir_exists($CFG->cachedir, true, true);
1682 protect_directory($CFG->cachedir);
1683 } else {
1684 protect_directory($CFG->dataroot);
1686 return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1690 * Create a directory under localcachedir and make sure it is writable.
1691 * The files in this directory MUST NOT change, use revisions or content hashes to
1692 * work around this limitation - this means you can only add new files here.
1694 * The content of this directory gets purged automatically on all cluster nodes
1695 * after calling purge_all_caches() before new data is written to this directory.
1697 * Note: this local cache directory does not need to be shared by cluster nodes.
1699 * @param string $directory the relative path of the directory to be created under $CFG->localcachedir
1700 * @param bool $exceptiononerror throw exception if error encountered
1701 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1703 function make_localcache_directory($directory, $exceptiononerror = true) {
1704 global $CFG;
1706 make_writable_directory($CFG->localcachedir, $exceptiononerror);
1708 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1709 protect_directory($CFG->localcachedir);
1710 } else {
1711 protect_directory($CFG->dataroot);
1714 if (!isset($CFG->localcachedirpurged)) {
1715 $CFG->localcachedirpurged = 0;
1717 $timestampfile = "$CFG->localcachedir/.lastpurged";
1719 if (!file_exists($timestampfile)) {
1720 touch($timestampfile);
1721 @chmod($timestampfile, $CFG->filepermissions);
1723 } else if (filemtime($timestampfile) < $CFG->localcachedirpurged) {
1724 // This means our local cached dir was not purged yet.
1725 remove_dir($CFG->localcachedir, true);
1726 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1727 protect_directory($CFG->localcachedir);
1729 touch($timestampfile);
1730 @chmod($timestampfile, $CFG->filepermissions);
1731 clearstatcache();
1734 if ($directory === '') {
1735 return $CFG->localcachedir;
1738 return make_writable_directory("$CFG->localcachedir/$directory", $exceptiononerror);
1742 * This class solves the problem of how to initialise $OUTPUT.
1744 * The problem is caused be two factors
1745 * <ol>
1746 * <li>On the one hand, we cannot be sure when output will start. In particular,
1747 * an error, which needs to be displayed, could be thrown at any time.</li>
1748 * <li>On the other hand, we cannot be sure when we will have all the information
1749 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1750 * (potentially) depends on the current course, course categories, and logged in user.
1751 * It also depends on whether the current page requires HTTPS.</li>
1752 * </ol>
1754 * So, it is hard to find a single natural place during Moodle script execution,
1755 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1756 * adopt the following strategy
1757 * <ol>
1758 * <li>We will initialise $OUTPUT the first time it is used.</li>
1759 * <li>If, after $OUTPUT has been initialised, the script tries to change something
1760 * that $OUTPUT depends on, we throw an exception making it clear that the script
1761 * did something wrong.
1762 * </ol>
1764 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1765 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1766 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1767 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1769 * Note that this class is used before lib/outputlib.php has been loaded, so we
1770 * must be careful referring to classes/functions from there, they may not be
1771 * defined yet, and we must avoid fatal errors.
1773 * @copyright 2009 Tim Hunt
1774 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1775 * @since Moodle 2.0
1777 class bootstrap_renderer {
1779 * Handles re-entrancy. Without this, errors or debugging output that occur
1780 * during the initialisation of $OUTPUT, cause infinite recursion.
1781 * @var boolean
1783 protected $initialising = false;
1786 * Have we started output yet?
1787 * @return boolean true if the header has been printed.
1789 public function has_started() {
1790 return false;
1794 * Constructor - to be used by core code only.
1795 * @param string $method The method to call
1796 * @param array $arguments Arguments to pass to the method being called
1797 * @return string
1799 public function __call($method, $arguments) {
1800 global $OUTPUT, $PAGE;
1802 $recursing = false;
1803 if ($method == 'notification') {
1804 // Catch infinite recursion caused by debugging output during print_header.
1805 $backtrace = debug_backtrace();
1806 array_shift($backtrace);
1807 array_shift($backtrace);
1808 $recursing = is_early_init($backtrace);
1811 $earlymethods = array(
1812 'fatal_error' => 'early_error',
1813 'notification' => 'early_notification',
1816 // If lib/outputlib.php has been loaded, call it.
1817 if (!empty($PAGE) && !$recursing) {
1818 if (array_key_exists($method, $earlymethods)) {
1819 //prevent PAGE->context warnings - exceptions might appear before we set any context
1820 $PAGE->set_context(null);
1822 $PAGE->initialise_theme_and_output();
1823 return call_user_func_array(array($OUTPUT, $method), $arguments);
1826 $this->initialising = true;
1828 // Too soon to initialise $OUTPUT, provide a couple of key methods.
1829 if (array_key_exists($method, $earlymethods)) {
1830 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1833 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1837 * Returns nicely formatted error message in a div box.
1838 * @static
1839 * @param string $message error message
1840 * @param string $moreinfourl (ignored in early errors)
1841 * @param string $link (ignored in early errors)
1842 * @param array $backtrace
1843 * @param string $debuginfo
1844 * @return string
1846 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1847 global $CFG;
1849 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1850 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1851 width: 80%; -moz-border-radius: 20px; padding: 15px">
1852 ' . $message . '
1853 </div>';
1854 // Check whether debug is set.
1855 $debug = (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER);
1856 // Also check we have it set in the config file. This occurs if the method to read the config table from the
1857 // database fails, reading from the config table is the first database interaction we have.
1858 $debug = $debug || (!empty($CFG->config_php_settings['debug']) && $CFG->config_php_settings['debug'] >= DEBUG_DEVELOPER );
1859 if ($debug) {
1860 if (!empty($debuginfo)) {
1861 $debuginfo = s($debuginfo); // removes all nasty JS
1862 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1863 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
1865 if (!empty($backtrace)) {
1866 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1870 return $content;
1874 * This function should only be called by this class, or from exception handlers
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 extra information for developers
1881 * @return string
1883 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = null) {
1884 global $CFG;
1886 if (CLI_SCRIPT) {
1887 echo "!!! $message !!!\n";
1888 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1889 if (!empty($debuginfo)) {
1890 echo "\nDebug info: $debuginfo";
1892 if (!empty($backtrace)) {
1893 echo "\nStack trace: " . format_backtrace($backtrace, true);
1896 return;
1898 } else if (AJAX_SCRIPT) {
1899 $e = new stdClass();
1900 $e->error = $message;
1901 $e->stacktrace = NULL;
1902 $e->debuginfo = NULL;
1903 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1904 if (!empty($debuginfo)) {
1905 $e->debuginfo = $debuginfo;
1907 if (!empty($backtrace)) {
1908 $e->stacktrace = format_backtrace($backtrace, true);
1911 $e->errorcode = $errorcode;
1912 @header('Content-Type: application/json; charset=utf-8');
1913 echo json_encode($e);
1914 return;
1917 // In the name of protocol correctness, monitoring and performance
1918 // profiling, set the appropriate error headers for machine consumption.
1919 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
1920 @header($protocol . ' 503 Service Unavailable');
1922 // better disable any caching
1923 @header('Content-Type: text/html; charset=utf-8');
1924 @header('X-UA-Compatible: IE=edge');
1925 @header('Cache-Control: no-store, no-cache, must-revalidate');
1926 @header('Cache-Control: post-check=0, pre-check=0', false);
1927 @header('Pragma: no-cache');
1928 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1929 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1931 if (function_exists('get_string')) {
1932 $strerror = get_string('error');
1933 } else {
1934 $strerror = 'Error';
1937 $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
1939 return self::plain_page($strerror, $content);
1943 * Early notification message
1944 * @static
1945 * @param string $message
1946 * @param string $classes usually notifyproblem or notifysuccess
1947 * @return string
1949 public static function early_notification($message, $classes = 'notifyproblem') {
1950 return '<div class="' . $classes . '">' . $message . '</div>';
1954 * Page should redirect message.
1955 * @static
1956 * @param string $encodedurl redirect url
1957 * @return string
1959 public static function plain_redirect_message($encodedurl) {
1960 $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
1961 $encodedurl .'">'. get_string('continue') .'</a></div>';
1962 return self::plain_page(get_string('redirect'), $message);
1966 * Early redirection page, used before full init of $PAGE global
1967 * @static
1968 * @param string $encodedurl redirect url
1969 * @param string $message redirect message
1970 * @param int $delay time in seconds
1971 * @return string redirect page
1973 public static function early_redirect_message($encodedurl, $message, $delay) {
1974 $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
1975 $content = self::early_error_content($message, null, null, null);
1976 $content .= self::plain_redirect_message($encodedurl);
1978 return self::plain_page(get_string('redirect'), $content, $meta);
1982 * Output basic html page.
1983 * @static
1984 * @param string $title page title
1985 * @param string $content page content
1986 * @param string $meta meta tag
1987 * @return string html page
1989 public static function plain_page($title, $content, $meta = '') {
1990 if (function_exists('get_string') && function_exists('get_html_lang')) {
1991 $htmllang = get_html_lang();
1992 } else {
1993 $htmllang = '';
1996 $footer = '';
1997 if (MDL_PERF_TEST) {
1998 $perfinfo = get_performance_info();
1999 $footer = '<footer>' . $perfinfo['html'] . '</footer>';
2002 return '<!DOCTYPE html>
2003 <html ' . $htmllang . '>
2004 <head>
2005 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
2006 '.$meta.'
2007 <title>' . $title . '</title>
2008 </head><body>' . $content . $footer . '</body></html>';