MDL-52927 qtype ddwtos and ddimageortext focus using keyboard
[moodle.git] / lib / setuplib.php
blobd20e639d9fcf66a6076102ae24d4f857ba7c72aa
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' => dirname(__FILE__).'/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(dirname(__FILE__));
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;
1330 $scan = array();
1331 $scan['GB'] = 1073741824;
1332 $scan['Gb'] = 1073741824;
1333 $scan['G'] = 1073741824;
1334 $scan['MB'] = 1048576;
1335 $scan['Mb'] = 1048576;
1336 $scan['M'] = 1048576;
1337 $scan['m'] = 1048576;
1338 $scan['KB'] = 1024;
1339 $scan['Kb'] = 1024;
1340 $scan['K'] = 1024;
1341 $scan['k'] = 1024;
1343 while (list($key) = each($scan)) {
1344 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
1345 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
1346 break;
1349 return $size;
1353 * Try to disable all output buffering and purge
1354 * all headers.
1356 * @access private to be called only from lib/setup.php !
1357 * @return void
1359 function disable_output_buffering() {
1360 $olddebug = error_reporting(0);
1362 // disable compression, it would prevent closing of buffers
1363 if (ini_get_bool('zlib.output_compression')) {
1364 ini_set('zlib.output_compression', 'Off');
1367 // try to flush everything all the time
1368 ob_implicit_flush(true);
1370 // close all buffers if possible and discard any existing output
1371 // this can actually work around some whitespace problems in config.php
1372 while(ob_get_level()) {
1373 if (!ob_end_clean()) {
1374 // prevent infinite loop when buffer can not be closed
1375 break;
1379 // disable any other output handlers
1380 ini_set('output_handler', '');
1382 error_reporting($olddebug);
1386 * Check whether a major upgrade is needed. That is defined as an upgrade that
1387 * changes something really fundamental in the database, so nothing can possibly
1388 * work until the database has been updated, and that is defined by the hard-coded
1389 * version number in this function.
1391 function redirect_if_major_upgrade_required() {
1392 global $CFG;
1393 $lastmajordbchanges = 2014093001.00;
1394 if (empty($CFG->version) or (float)$CFG->version < $lastmajordbchanges or
1395 during_initial_install() or !empty($CFG->adminsetuppending)) {
1396 try {
1397 @\core\session\manager::terminate_current();
1398 } catch (Exception $e) {
1399 // Ignore any errors, redirect to upgrade anyway.
1401 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
1402 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1403 @header('Location: ' . $url);
1404 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
1405 exit;
1410 * Makes sure that upgrade process is not running
1412 * To be inserted in the core functions that can not be called by pluigns during upgrade.
1413 * Core upgrade should not use any API functions at all.
1414 * See {@link http://docs.moodle.org/dev/Upgrade_API#Upgrade_code_restrictions}
1416 * @throws moodle_exception if executed from inside of upgrade script and $warningonly is false
1417 * @param bool $warningonly if true displays a warning instead of throwing an exception
1418 * @return bool true if executed from outside of upgrade process, false if from inside upgrade process and function is used for warning only
1420 function upgrade_ensure_not_running($warningonly = false) {
1421 global $CFG;
1422 if (!empty($CFG->upgraderunning)) {
1423 if (!$warningonly) {
1424 throw new moodle_exception('cannotexecduringupgrade');
1425 } else {
1426 debugging(get_string('cannotexecduringupgrade', 'error'), DEBUG_DEVELOPER);
1427 return false;
1430 return true;
1434 * Function to check if a directory exists and by default create it if not exists.
1436 * Previously this was accepting paths only from dataroot, but we now allow
1437 * files outside of dataroot if you supply custom paths for some settings in config.php.
1438 * This function does not verify that the directory is writable.
1440 * NOTE: this function uses current file stat cache,
1441 * please use clearstatcache() before this if you expect that the
1442 * directories may have been removed recently from a different request.
1444 * @param string $dir absolute directory path
1445 * @param boolean $create directory if does not exist
1446 * @param boolean $recursive create directory recursively
1447 * @return boolean true if directory exists or created, false otherwise
1449 function check_dir_exists($dir, $create = true, $recursive = true) {
1450 global $CFG;
1452 umask($CFG->umaskpermissions);
1454 if (is_dir($dir)) {
1455 return true;
1458 if (!$create) {
1459 return false;
1462 return mkdir($dir, $CFG->directorypermissions, $recursive);
1466 * Create a new unique directory within the specified directory.
1468 * @param string $basedir The directory to create your new unique directory within.
1469 * @param bool $exceptiononerror throw exception if error encountered
1470 * @return string The created directory
1471 * @throws invalid_dataroot_permissions
1473 function make_unique_writable_directory($basedir, $exceptiononerror = true) {
1474 if (!is_dir($basedir) || !is_writable($basedir)) {
1475 // The basedir is not writable. We will not be able to create the child directory.
1476 if ($exceptiononerror) {
1477 throw new invalid_dataroot_permissions($basedir . ' is not writable. Unable to create a unique directory within it.');
1478 } else {
1479 return false;
1483 do {
1484 // Generate a new (hopefully unique) directory name.
1485 $uniquedir = $basedir . DIRECTORY_SEPARATOR . generate_uuid();
1486 } while (
1487 // Ensure that basedir is still writable - if we do not check, we could get stuck in a loop here.
1488 is_writable($basedir) &&
1490 // Make the new unique directory. If the directory already exists, it will return false.
1491 !make_writable_directory($uniquedir, $exceptiononerror) &&
1493 // Ensure that the directory now exists
1494 file_exists($uniquedir) && is_dir($uniquedir)
1497 // Check that the directory was correctly created.
1498 if (!file_exists($uniquedir) || !is_dir($uniquedir) || !is_writable($uniquedir)) {
1499 if ($exceptiononerror) {
1500 throw new invalid_dataroot_permissions('Unique directory creation failed.');
1501 } else {
1502 return false;
1506 return $uniquedir;
1510 * Create a directory and make sure it is writable.
1512 * @private
1513 * @param string $dir the full path of the directory to be created
1514 * @param bool $exceptiononerror throw exception if error encountered
1515 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1517 function make_writable_directory($dir, $exceptiononerror = true) {
1518 global $CFG;
1520 if (file_exists($dir) and !is_dir($dir)) {
1521 if ($exceptiononerror) {
1522 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1523 } else {
1524 return false;
1528 umask($CFG->umaskpermissions);
1530 if (!file_exists($dir)) {
1531 if (!@mkdir($dir, $CFG->directorypermissions, true)) {
1532 clearstatcache();
1533 // There might be a race condition when creating directory.
1534 if (!is_dir($dir)) {
1535 if ($exceptiononerror) {
1536 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1537 } else {
1538 debugging('Can not create directory: '.$dir, DEBUG_DEVELOPER);
1539 return false;
1545 if (!is_writable($dir)) {
1546 if ($exceptiononerror) {
1547 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1548 } else {
1549 return false;
1553 return $dir;
1557 * Protect a directory from web access.
1558 * Could be extended in the future to support other mechanisms (e.g. other webservers).
1560 * @private
1561 * @param string $dir the full path of the directory to be protected
1563 function protect_directory($dir) {
1564 global $CFG;
1565 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1566 if (!file_exists("$dir/.htaccess")) {
1567 if ($handle = fopen("$dir/.htaccess", 'w')) { // For safety
1568 @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");
1569 @fclose($handle);
1570 @chmod("$dir/.htaccess", $CFG->filepermissions);
1576 * Create a directory under dataroot and make sure it is writable.
1577 * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
1579 * @param string $directory the full path of the directory to be created under $CFG->dataroot
1580 * @param bool $exceptiononerror throw exception if error encountered
1581 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1583 function make_upload_directory($directory, $exceptiononerror = true) {
1584 global $CFG;
1586 if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1587 debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1589 } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
1590 debugging('Use make_cache_directory() for creation of cache directory and $CFG->cachedir to get the location.');
1592 } else if (strpos($directory, 'localcache/') === 0 or $directory === 'localcache') {
1593 debugging('Use make_localcache_directory() for creation of local cache directory and $CFG->localcachedir to get the location.');
1596 protect_directory($CFG->dataroot);
1597 return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1601 * Get a per-request storage directory in the tempdir.
1603 * The directory is automatically cleaned up during the shutdown handler.
1605 * @param bool $exceptiononerror throw exception if error encountered
1606 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1608 function get_request_storage_directory($exceptiononerror = true) {
1609 global $CFG;
1611 static $requestdir = null;
1613 if (!$requestdir || !file_exists($requestdir) || !is_dir($requestdir) || !is_writable($requestdir)) {
1614 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1615 check_dir_exists($CFG->localcachedir, true, true);
1616 protect_directory($CFG->localcachedir);
1617 } else {
1618 protect_directory($CFG->dataroot);
1621 if ($requestdir = make_unique_writable_directory($CFG->localcachedir, $exceptiononerror)) {
1622 // Register a shutdown handler to remove the directory.
1623 \core_shutdown_manager::register_function('remove_dir', array($requestdir));
1627 return $requestdir;
1631 * Create a per-request directory and make sure it is writable.
1632 * This can only be used during the current request and will be tidied away
1633 * automatically afterwards.
1635 * A new, unique directory is always created within the current request directory.
1637 * @param bool $exceptiononerror throw exception if error encountered
1638 * @return string full path to directory if successful, false if not; may throw exception
1640 function make_request_directory($exceptiononerror = true) {
1641 $basedir = get_request_storage_directory($exceptiononerror);
1642 return make_unique_writable_directory($basedir, $exceptiononerror);
1646 * Create a directory under tempdir and make sure it is writable.
1648 * Where possible, please use make_request_directory() and limit the scope
1649 * of your data to the current HTTP request.
1651 * Do not use for storing cache files - see make_cache_directory(), and
1652 * make_localcache_directory() instead for this purpose.
1654 * Temporary files must be on a shared storage, and heavy usage is
1655 * discouraged due to the performance impact upon clustered environments.
1657 * @param string $directory the full path of the directory to be created under $CFG->tempdir
1658 * @param bool $exceptiononerror throw exception if error encountered
1659 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1661 function make_temp_directory($directory, $exceptiononerror = true) {
1662 global $CFG;
1663 if ($CFG->tempdir !== "$CFG->dataroot/temp") {
1664 check_dir_exists($CFG->tempdir, true, true);
1665 protect_directory($CFG->tempdir);
1666 } else {
1667 protect_directory($CFG->dataroot);
1669 return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1673 * Create a directory under cachedir and make sure it is writable.
1675 * Note: this cache directory is shared by all cluster nodes.
1677 * @param string $directory the full path of the directory to be created under $CFG->cachedir
1678 * @param bool $exceptiononerror throw exception if error encountered
1679 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1681 function make_cache_directory($directory, $exceptiononerror = true) {
1682 global $CFG;
1683 if ($CFG->cachedir !== "$CFG->dataroot/cache") {
1684 check_dir_exists($CFG->cachedir, true, true);
1685 protect_directory($CFG->cachedir);
1686 } else {
1687 protect_directory($CFG->dataroot);
1689 return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1693 * Create a directory under localcachedir and make sure it is writable.
1694 * The files in this directory MUST NOT change, use revisions or content hashes to
1695 * work around this limitation - this means you can only add new files here.
1697 * The content of this directory gets purged automatically on all cluster nodes
1698 * after calling purge_all_caches() before new data is written to this directory.
1700 * Note: this local cache directory does not need to be shared by cluster nodes.
1702 * @param string $directory the relative path of the directory to be created under $CFG->localcachedir
1703 * @param bool $exceptiononerror throw exception if error encountered
1704 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1706 function make_localcache_directory($directory, $exceptiononerror = true) {
1707 global $CFG;
1709 make_writable_directory($CFG->localcachedir, $exceptiononerror);
1711 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1712 protect_directory($CFG->localcachedir);
1713 } else {
1714 protect_directory($CFG->dataroot);
1717 if (!isset($CFG->localcachedirpurged)) {
1718 $CFG->localcachedirpurged = 0;
1720 $timestampfile = "$CFG->localcachedir/.lastpurged";
1722 if (!file_exists($timestampfile)) {
1723 touch($timestampfile);
1724 @chmod($timestampfile, $CFG->filepermissions);
1726 } else if (filemtime($timestampfile) < $CFG->localcachedirpurged) {
1727 // This means our local cached dir was not purged yet.
1728 remove_dir($CFG->localcachedir, true);
1729 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1730 protect_directory($CFG->localcachedir);
1732 touch($timestampfile);
1733 @chmod($timestampfile, $CFG->filepermissions);
1734 clearstatcache();
1737 if ($directory === '') {
1738 return $CFG->localcachedir;
1741 return make_writable_directory("$CFG->localcachedir/$directory", $exceptiononerror);
1745 * This class solves the problem of how to initialise $OUTPUT.
1747 * The problem is caused be two factors
1748 * <ol>
1749 * <li>On the one hand, we cannot be sure when output will start. In particular,
1750 * an error, which needs to be displayed, could be thrown at any time.</li>
1751 * <li>On the other hand, we cannot be sure when we will have all the information
1752 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1753 * (potentially) depends on the current course, course categories, and logged in user.
1754 * It also depends on whether the current page requires HTTPS.</li>
1755 * </ol>
1757 * So, it is hard to find a single natural place during Moodle script execution,
1758 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1759 * adopt the following strategy
1760 * <ol>
1761 * <li>We will initialise $OUTPUT the first time it is used.</li>
1762 * <li>If, after $OUTPUT has been initialised, the script tries to change something
1763 * that $OUTPUT depends on, we throw an exception making it clear that the script
1764 * did something wrong.
1765 * </ol>
1767 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1768 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1769 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1770 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1772 * Note that this class is used before lib/outputlib.php has been loaded, so we
1773 * must be careful referring to classes/functions from there, they may not be
1774 * defined yet, and we must avoid fatal errors.
1776 * @copyright 2009 Tim Hunt
1777 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1778 * @since Moodle 2.0
1780 class bootstrap_renderer {
1782 * Handles re-entrancy. Without this, errors or debugging output that occur
1783 * during the initialisation of $OUTPUT, cause infinite recursion.
1784 * @var boolean
1786 protected $initialising = false;
1789 * Have we started output yet?
1790 * @return boolean true if the header has been printed.
1792 public function has_started() {
1793 return false;
1797 * Constructor - to be used by core code only.
1798 * @param string $method The method to call
1799 * @param array $arguments Arguments to pass to the method being called
1800 * @return string
1802 public function __call($method, $arguments) {
1803 global $OUTPUT, $PAGE;
1805 $recursing = false;
1806 if ($method == 'notification') {
1807 // Catch infinite recursion caused by debugging output during print_header.
1808 $backtrace = debug_backtrace();
1809 array_shift($backtrace);
1810 array_shift($backtrace);
1811 $recursing = is_early_init($backtrace);
1814 $earlymethods = array(
1815 'fatal_error' => 'early_error',
1816 'notification' => 'early_notification',
1819 // If lib/outputlib.php has been loaded, call it.
1820 if (!empty($PAGE) && !$recursing) {
1821 if (array_key_exists($method, $earlymethods)) {
1822 //prevent PAGE->context warnings - exceptions might appear before we set any context
1823 $PAGE->set_context(null);
1825 $PAGE->initialise_theme_and_output();
1826 return call_user_func_array(array($OUTPUT, $method), $arguments);
1829 $this->initialising = true;
1831 // Too soon to initialise $OUTPUT, provide a couple of key methods.
1832 if (array_key_exists($method, $earlymethods)) {
1833 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1836 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1840 * Returns nicely formatted error message in a div box.
1841 * @static
1842 * @param string $message error message
1843 * @param string $moreinfourl (ignored in early errors)
1844 * @param string $link (ignored in early errors)
1845 * @param array $backtrace
1846 * @param string $debuginfo
1847 * @return string
1849 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1850 global $CFG;
1852 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1853 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1854 width: 80%; -moz-border-radius: 20px; padding: 15px">
1855 ' . $message . '
1856 </div>';
1857 // Check whether debug is set.
1858 $debug = (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER);
1859 // Also check we have it set in the config file. This occurs if the method to read the config table from the
1860 // database fails, reading from the config table is the first database interaction we have.
1861 $debug = $debug || (!empty($CFG->config_php_settings['debug']) && $CFG->config_php_settings['debug'] >= DEBUG_DEVELOPER );
1862 if ($debug) {
1863 if (!empty($debuginfo)) {
1864 $debuginfo = s($debuginfo); // removes all nasty JS
1865 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1866 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
1868 if (!empty($backtrace)) {
1869 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1873 return $content;
1877 * This function should only be called by this class, or from exception handlers
1878 * @static
1879 * @param string $message error message
1880 * @param string $moreinfourl (ignored in early errors)
1881 * @param string $link (ignored in early errors)
1882 * @param array $backtrace
1883 * @param string $debuginfo extra information for developers
1884 * @return string
1886 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = null) {
1887 global $CFG;
1889 if (CLI_SCRIPT) {
1890 echo "!!! $message !!!\n";
1891 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1892 if (!empty($debuginfo)) {
1893 echo "\nDebug info: $debuginfo";
1895 if (!empty($backtrace)) {
1896 echo "\nStack trace: " . format_backtrace($backtrace, true);
1899 return;
1901 } else if (AJAX_SCRIPT) {
1902 $e = new stdClass();
1903 $e->error = $message;
1904 $e->stacktrace = NULL;
1905 $e->debuginfo = NULL;
1906 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1907 if (!empty($debuginfo)) {
1908 $e->debuginfo = $debuginfo;
1910 if (!empty($backtrace)) {
1911 $e->stacktrace = format_backtrace($backtrace, true);
1914 $e->errorcode = $errorcode;
1915 @header('Content-Type: application/json; charset=utf-8');
1916 echo json_encode($e);
1917 return;
1920 // In the name of protocol correctness, monitoring and performance
1921 // profiling, set the appropriate error headers for machine consumption.
1922 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
1923 @header($protocol . ' 503 Service Unavailable');
1925 // better disable any caching
1926 @header('Content-Type: text/html; charset=utf-8');
1927 @header('X-UA-Compatible: IE=edge');
1928 @header('Cache-Control: no-store, no-cache, must-revalidate');
1929 @header('Cache-Control: post-check=0, pre-check=0', false);
1930 @header('Pragma: no-cache');
1931 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1932 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1934 if (function_exists('get_string')) {
1935 $strerror = get_string('error');
1936 } else {
1937 $strerror = 'Error';
1940 $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
1942 return self::plain_page($strerror, $content);
1946 * Early notification message
1947 * @static
1948 * @param string $message
1949 * @param string $classes usually notifyproblem or notifysuccess
1950 * @return string
1952 public static function early_notification($message, $classes = 'notifyproblem') {
1953 return '<div class="' . $classes . '">' . $message . '</div>';
1957 * Page should redirect message.
1958 * @static
1959 * @param string $encodedurl redirect url
1960 * @return string
1962 public static function plain_redirect_message($encodedurl) {
1963 $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
1964 $encodedurl .'">'. get_string('continue') .'</a></div>';
1965 return self::plain_page(get_string('redirect'), $message);
1969 * Early redirection page, used before full init of $PAGE global
1970 * @static
1971 * @param string $encodedurl redirect url
1972 * @param string $message redirect message
1973 * @param int $delay time in seconds
1974 * @return string redirect page
1976 public static function early_redirect_message($encodedurl, $message, $delay) {
1977 $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
1978 $content = self::early_error_content($message, null, null, null);
1979 $content .= self::plain_redirect_message($encodedurl);
1981 return self::plain_page(get_string('redirect'), $content, $meta);
1985 * Output basic html page.
1986 * @static
1987 * @param string $title page title
1988 * @param string $content page content
1989 * @param string $meta meta tag
1990 * @return string html page
1992 public static function plain_page($title, $content, $meta = '') {
1993 if (function_exists('get_string') && function_exists('get_html_lang')) {
1994 $htmllang = get_html_lang();
1995 } else {
1996 $htmllang = '';
1999 $footer = '';
2000 if (MDL_PERF_TEST) {
2001 $perfinfo = get_performance_info();
2002 $footer = '<footer>' . $perfinfo['html'] . '</footer>';
2005 return '<!DOCTYPE html>
2006 <html ' . $htmllang . '>
2007 <head>
2008 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
2009 '.$meta.'
2010 <title>' . $title . '</title>
2011 </head><body>' . $content . $footer . '</body></html>';