2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * These functions are required very early in the Moodle
19 * setup process, before any of the main libraries are
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);
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 * Base Moodle Exception class
57 * Although this class is defined here, you cannot throw a moodle_exception until
58 * after moodlelib.php has been included (which will happen very soon).
62 * @copyright 2008 Petr Skoda {@link http://skodak.org}
63 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
65 class moodle_exception
extends Exception
{
68 * @var string The name of the string from error.php to print
73 * @var string The name of module
78 * @var mixed Extra words and phrases that might be required in the error string
83 * @var string The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
88 * @var string Optional information to aid the debugging process
94 * @param string $errorcode The name of the string from error.php to print
95 * @param string $module name of module
96 * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
97 * @param mixed $a Extra words and phrases that might be required in the error string
98 * @param string $debuginfo optional debugging information
100 function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
103 if (empty($module) ||
$module == 'moodle' ||
$module == 'core') {
107 $this->errorcode
= $errorcode;
108 $this->module
= $module;
111 $this->debuginfo
= is_null($debuginfo) ?
null : (string)$debuginfo;
113 if (get_string_manager()->string_exists($errorcode, $module)) {
114 $message = get_string($errorcode, $module, $a);
115 $haserrorstring = true;
117 $message = $module . '/' . $errorcode;
118 $haserrorstring = false;
121 $isinphpunittest = (defined('PHPUNIT_TEST') && PHPUNIT_TEST
);
122 $hasdebugdeveloper = (
123 isset($CFG->debugdisplay
) &&
124 isset($CFG->debug
) &&
125 $CFG->debugdisplay
&&
126 $CFG->debug
=== DEBUG_DEVELOPER
130 if ($isinphpunittest ||
$hasdebugdeveloper) {
131 $message = "$message ($debuginfo)";
135 if (!$haserrorstring and $isinphpunittest) {
136 // Append the contents of $a to $debuginfo so helpful information isn't lost.
137 // This emulates what {@link get_exception_info()} does. Unfortunately that
138 // function is not used by phpunit.
139 $message .= PHP_EOL
.'$a contents: '.print_r($a, true);
142 parent
::__construct($message, 0);
147 * Course/activity access exception.
149 * This exception is thrown from require_login()
151 * @package core_access
152 * @copyright 2010 Petr Skoda {@link http://skodak.org}
153 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
155 class require_login_exception
extends moodle_exception
{
158 * @param string $debuginfo Information to aid the debugging process
160 function __construct($debuginfo) {
161 parent
::__construct('requireloginerror', 'error', '', NULL, $debuginfo);
166 * Session timeout exception.
168 * This exception is thrown from require_login()
170 * @package core_access
171 * @copyright 2015 Andrew Nicols <andrew@nicols.co.uk>
172 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
174 class require_login_session_timeout_exception
extends require_login_exception
{
178 public function __construct() {
179 moodle_exception
::__construct('sessionerroruser', 'error');
184 * Web service parameter exception class
185 * @deprecated since Moodle 2.2 - use moodle exception instead
186 * This exception must be thrown to the web service client when a web service parameter is invalid
187 * The error string is gotten from webservice.php
189 class webservice_parameter_exception
extends moodle_exception
{
192 * @param string $errorcode The name of the string from webservice.php to print
193 * @param string $a The name of the parameter
194 * @param string $debuginfo Optional information to aid debugging
196 function __construct($errorcode=null, $a = '', $debuginfo = null) {
197 parent
::__construct($errorcode, 'webservice', '', $a, $debuginfo);
202 * Exceptions indicating user does not have permissions to do something
203 * and the execution can not continue.
205 * @package core_access
206 * @copyright 2009 Petr Skoda {@link http://skodak.org}
207 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
209 class required_capability_exception
extends moodle_exception
{
212 * @param context $context The context used for the capability check
213 * @param string $capability The required capability
214 * @param string $errormessage The error message to show the user
215 * @param string $stringfile
217 function __construct($context, $capability, $errormessage, $stringfile) {
218 $capabilityname = get_capability_string($capability);
219 if ($context->contextlevel
== CONTEXT_MODULE
and preg_match('/:view$/', $capability)) {
220 // 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
221 $parentcontext = $context->get_parent_context();
222 $link = $parentcontext->get_url();
224 $link = $context->get_url();
226 parent
::__construct($errormessage, $stringfile, $link, $capabilityname);
231 * Exception indicating programming error, must be fixed by a programer. For example
232 * a core API might throw this type of exception if a plugin calls it incorrectly.
236 * @copyright 2008 Petr Skoda {@link http://skodak.org}
237 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
239 class coding_exception
extends moodle_exception
{
242 * @param string $hint short description of problem
243 * @param string $debuginfo detailed information how to fix problem
245 function __construct($hint, $debuginfo=null) {
246 parent
::__construct('codingerror', 'debug', '', $hint, $debuginfo);
251 * Exception indicating malformed parameter problem.
252 * This exception is not supposed to be thrown when processing
253 * user submitted data in forms. It is more suitable
254 * for WS and other low level stuff.
258 * @copyright 2009 Petr Skoda {@link http://skodak.org}
259 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
261 class invalid_parameter_exception
extends moodle_exception
{
264 * @param string $debuginfo some detailed information
266 function __construct($debuginfo=null) {
267 parent
::__construct('invalidparameter', 'debug', '', null, $debuginfo);
272 * Exception indicating malformed response problem.
273 * This exception is not supposed to be thrown when processing
274 * user submitted data in forms. It is more suitable
275 * for WS and other low level stuff.
277 class invalid_response_exception
extends moodle_exception
{
280 * @param string $debuginfo some detailed information
282 function __construct($debuginfo=null) {
283 parent
::__construct('invalidresponse', 'debug', '', null, $debuginfo);
288 * An exception that indicates something really weird happened. For example,
289 * if you do switch ($context->contextlevel), and have one case for each
290 * CONTEXT_... constant. You might throw an invalid_state_exception in the
291 * default case, to just in case something really weird is going on, and
292 * $context->contextlevel is invalid - rather than ignoring this possibility.
296 * @copyright 2009 onwards Martin Dougiamas {@link http://moodle.com}
297 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
299 class invalid_state_exception
extends moodle_exception
{
302 * @param string $hint short description of problem
303 * @param string $debuginfo optional more detailed information
305 function __construct($hint, $debuginfo=null) {
306 parent
::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
311 * An exception that indicates incorrect permissions in $CFG->dataroot
315 * @copyright 2010 Petr Skoda {@link http://skodak.org}
316 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
318 class invalid_dataroot_permissions
extends moodle_exception
{
321 * @param string $debuginfo optional more detailed information
323 function __construct($debuginfo = NULL) {
324 parent
::__construct('invaliddatarootpermissions', 'error', '', NULL, $debuginfo);
329 * An exception that indicates that file can not be served
333 * @copyright 2010 Petr Skoda {@link http://skodak.org}
334 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
336 class file_serving_exception
extends moodle_exception
{
339 * @param string $debuginfo optional more detailed information
341 function __construct($debuginfo = NULL) {
342 parent
::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
347 * Default exception handler.
349 * @param Exception $ex
350 * @return void -does not return. Terminates execution!
352 function default_exception_handler($ex) {
353 global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION, $PAGE;
355 // detect active db transactions, rollback and log as error
356 abort_all_db_transactions();
358 if (($ex instanceof required_capability_exception
) && !CLI_SCRIPT
&& !AJAX_SCRIPT
&& !empty($CFG->autologinguests
) && !empty($USER->autologinguest
)) {
359 $SESSION->wantsurl
= qualified_me();
360 redirect(get_login_url());
363 $info = get_exception_info($ex);
365 if (is_early_init($info->backtrace
)) {
366 echo bootstrap_renderer
::early_error($info->message
, $info->moreinfourl
, $info->link
, $info->backtrace
, $info->debuginfo
, $info->errorcode
);
368 if (debugging('', DEBUG_MINIMAL
)) {
369 $logerrmsg = "Default exception handler: ".$info->message
.' Debug: '.$info->debuginfo
."\n".format_backtrace($info->backtrace
, true);
370 error_log($logerrmsg);
375 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
379 // If we are in an AJAX script we don't want to use PREFERRED_RENDERER_TARGET.
380 // Because we know we will want to use ajax format.
381 $renderer = new core_renderer_ajax($PAGE, 'ajax');
385 echo $renderer->fatal_error($info->message
, $info->moreinfourl
, $info->link
, $info->backtrace
, $info->debuginfo
,
387 } catch (Exception
$e) {
389 } catch (Throwable
$e) {
390 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
394 if (isset($out_ex)) {
395 // default exception handler MUST not throw any exceptions!!
396 // 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
397 // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
398 if (CLI_SCRIPT
or AJAX_SCRIPT
) {
399 // just ignore the error and send something back using the safest method
400 echo bootstrap_renderer
::early_error($info->message
, $info->moreinfourl
, $info->link
, $info->backtrace
, $info->debuginfo
, $info->errorcode
);
402 echo bootstrap_renderer
::early_error_content($info->message
, $info->moreinfourl
, $info->link
, $info->backtrace
, $info->debuginfo
);
403 $outinfo = get_exception_info($out_ex);
404 echo bootstrap_renderer
::early_error_content($outinfo->message
, $outinfo->moreinfourl
, $outinfo->link
, $outinfo->backtrace
, $outinfo->debuginfo
);
409 exit(1); // General error code
413 * Default error handler, prevents some white screens.
415 * @param string $errstr
416 * @param string $errfile
417 * @param int $errline
418 * @param array $errcontext
419 * @return bool false means use default error handler
421 function default_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
422 if ($errno == 4096) {
423 //fatal catchable error
424 throw new coding_exception('PHP catchable fatal error', $errstr);
430 * Unconditionally abort all database transactions, this function
431 * should be called from exception handlers only.
434 function abort_all_db_transactions() {
435 global $CFG, $DB, $SCRIPT;
437 // default exception handler MUST not throw any exceptions!!
439 if ($DB && $DB->is_transaction_started()) {
440 error_log('Database transaction aborted automatically in ' . $CFG->dirroot
. $SCRIPT);
441 // note: transaction blocks should never change current $_SESSION
442 $DB->force_transaction_rollback();
447 * This function encapsulates the tests for whether an exception was thrown in
448 * early init -- either during setup.php or during init of $OUTPUT.
450 * If another exception is thrown then, and if we do not take special measures,
451 * we would just get a very cryptic message "Exception thrown without a stack
452 * frame in Unknown on line 0". That makes debugging very hard, so we do take
453 * special measures in default_exception_handler, with the help of this function.
455 * @param array $backtrace the stack trace to analyse.
456 * @return boolean whether the stack trace is somewhere in output initialisation.
458 function is_early_init($backtrace) {
459 $dangerouscode = array(
460 array('function' => 'header', 'type' => '->'),
461 array('class' => 'bootstrap_renderer'),
462 array('file' => __DIR__
.'/setup.php'),
464 foreach ($backtrace as $stackframe) {
465 foreach ($dangerouscode as $pattern) {
467 foreach ($pattern as $property => $value) {
468 if (!isset($stackframe[$property]) ||
$stackframe[$property] != $value) {
481 * Abort execution by throwing of a general exception,
482 * default exception handler displays the error message in most cases.
484 * @param string $errorcode The name of the language string containing the error message.
485 * Normally this should be in the error.php lang file.
486 * @param string $module The language file to get the error message from.
487 * @param string $link The url where the user will be prompted to continue.
488 * If no url is provided the user will be directed to the site index page.
489 * @param object $a Extra words and phrases that might be required in the error string
490 * @param string $debuginfo optional debugging information
491 * @return void, always throws exception!
493 function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
494 throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
498 * Returns detailed information about specified exception.
499 * @param exception $ex
502 function get_exception_info($ex) {
503 global $CFG, $DB, $SESSION;
505 if ($ex instanceof moodle_exception
) {
506 $errorcode = $ex->errorcode
;
507 $module = $ex->module
;
510 $debuginfo = $ex->debuginfo
;
512 $errorcode = 'generalexceptionmessage';
514 $a = $ex->getMessage();
519 // Append the error code to the debug info to make grepping and googling easier
520 $debuginfo .= PHP_EOL
."Error code: $errorcode";
522 $backtrace = $ex->getTrace();
523 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
524 array_unshift($backtrace, $place);
526 // Be careful, no guarantee moodlelib.php is loaded.
527 if (empty($module) ||
$module == 'moodle' ||
$module == 'core') {
530 // Search for the $errorcode's associated string
531 // If not found, append the contents of $a to $debuginfo so helpful information isn't lost
532 if (function_exists('get_string_manager')) {
533 if (get_string_manager()->string_exists($errorcode, $module)) {
534 $message = get_string($errorcode, $module, $a);
535 } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
536 // Search in moodle file if error specified - needed for backwards compatibility
537 $message = get_string($errorcode, 'moodle', $a);
539 $message = $module . '/' . $errorcode;
540 $debuginfo .= PHP_EOL
.'$a contents: '.print_r($a, true);
543 $message = $module . '/' . $errorcode;
544 $debuginfo .= PHP_EOL
.'$a contents: '.print_r($a, true);
547 // Remove some absolute paths from message and debugging info.
550 $cfgnames = array('tempdir', 'cachedir', 'localcachedir', 'themedir', 'dataroot', 'dirroot');
551 foreach ($cfgnames as $cfgname) {
552 if (property_exists($CFG, $cfgname)) {
553 $searches[] = $CFG->$cfgname;
554 $replaces[] = "[$cfgname]";
557 if (!empty($searches)) {
558 $message = str_replace($searches, $replaces, $message);
559 $debuginfo = str_replace($searches, $replaces, $debuginfo);
562 // Be careful, no guarantee weblib.php is loaded.
563 if (function_exists('clean_text')) {
564 $message = clean_text($message);
566 $message = htmlspecialchars($message);
569 if (!empty($CFG->errordocroot
)) {
570 $errordoclink = $CFG->errordocroot
. '/en/';
572 // Only if the function is available. May be not for early errors.
573 if (function_exists('current_language')) {
574 $errordoclink = get_docs_url();
576 $errordoclink = 'https://docs.moodle.org/en/';
580 if ($module === 'error') {
581 $modulelink = 'moodle';
583 $modulelink = $module;
585 $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
588 if (!empty($SESSION->fromurl
)) {
589 $link = $SESSION->fromurl
;
590 unset($SESSION->fromurl
);
592 $link = $CFG->wwwroot
.'/';
596 // When printing an error the continue button should never link offsite.
597 // We cannot use clean_param() here as it is not guaranteed that it has been loaded yet.
598 if (stripos($link, $CFG->wwwroot
) === 0) {
599 // Internal HTTP, all good.
601 // External link spotted!
602 $link = $CFG->wwwroot
. '/';
605 $info = new stdClass();
606 $info->message
= $message;
607 $info->errorcode
= $errorcode;
608 $info->backtrace
= $backtrace;
610 $info->moreinfourl
= $moreinfourl;
612 $info->debuginfo
= $debuginfo;
618 * Generate a V4 UUID.
620 * Unique is hard. Very hard. Attempt to use the PECL UUID function if available, and if not then revert to
621 * constructing the uuid using mt_rand.
623 * It is important that this token is not solely based on time as this could lead
624 * to duplicates in a clustered environment (especially on VMs due to poor time precision).
626 * @see https://tools.ietf.org/html/rfc4122
628 * @deprecated since Moodle 3.8 MDL-61038 - please do not use this function any more.
629 * @see \core\uuid::generate()
631 * @return string The uuid.
633 function generate_uuid() {
634 debugging('generate_uuid() is deprecated. Please use \core\uuid::generate() instead.', DEBUG_DEVELOPER
);
635 return \core\uuid
::generate();
639 * Returns the Moodle Docs URL in the users language for a given 'More help' link.
641 * There are three cases:
643 * 1. In the normal case, $path will be a short relative path 'component/thing',
644 * like 'mod/folder/view' 'group/import'. This gets turned into an link to
645 * MoodleDocs in the user's language, and for the appropriate Moodle version.
646 * E.g. 'group/import' may become 'http://docs.moodle.org/2x/en/group/import'.
647 * The 'http://docs.moodle.org' bit comes from $CFG->docroot.
649 * This is the only option that should be used in standard Moodle code. The other
650 * two options have been implemented because they are useful for third-party plugins.
652 * 2. $path may be an absolute URL, starting http:// or https://. In this case,
653 * the link is used as is.
655 * 3. $path may start %%WWWROOT%%, in which case that is replaced by
656 * $CFG->wwwroot to make the link.
658 * @param string $path the place to link to. See above for details.
659 * @return string The MoodleDocs URL in the user's language. for example @link http://docs.moodle.org/2x/en/$path}
661 function get_docs_url($path = null) {
664 // Absolute URLs are used unmodified.
665 if (substr($path, 0, 7) === 'http://' ||
substr($path, 0, 8) === 'https://') {
669 // Paths starting %%WWWROOT%% have that replaced by $CFG->wwwroot.
670 if (substr($path, 0, 11) === '%%WWWROOT%%') {
671 return $CFG->wwwroot
. substr($path, 11);
674 // Otherwise we do the normal case, and construct a MoodleDocs URL relative to $CFG->docroot.
676 // Check that $CFG->branch has been set up, during installation it won't be.
677 if (empty($CFG->branch
)) {
678 // It's not there yet so look at version.php.
679 include($CFG->dirroot
.'/version.php');
681 // We can use $CFG->branch and avoid having to include version.php.
682 $branch = $CFG->branch
;
684 // ensure branch is valid.
686 // We should never get here but in case we do lets set $branch to .
687 // the smart one's will know that this is the current directory
688 // and the smarter ones will know that there is some smart matching
689 // that will ensure people end up at the latest version of the docs.
692 if (empty($CFG->doclang
)) {
693 $lang = current_language();
695 $lang = $CFG->doclang
;
697 $end = '/' . $branch . '/' . $lang . '/' . $path;
698 if (empty($CFG->docroot
)) {
699 return 'http://docs.moodle.org'. $end;
701 return $CFG->docroot
. $end ;
706 * Formats a backtrace ready for output.
708 * This function does not include function arguments because they could contain sensitive information
709 * not suitable to be exposed in a response.
711 * @param array $callers backtrace array, as returned by debug_backtrace().
712 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
713 * @return string formatted backtrace, ready for output.
715 function format_backtrace($callers, $plaintext = false) {
716 // do not use $CFG->dirroot because it might not be available in destructors
717 $dirroot = dirname(__DIR__
);
719 if (empty($callers)) {
723 $from = $plaintext ?
'' : '<ul style="text-align: left" data-rel="backtrace">';
724 foreach ($callers as $caller) {
725 if (!isset($caller['line'])) {
726 $caller['line'] = '?'; // probably call_user_func()
728 if (!isset($caller['file'])) {
729 $caller['file'] = 'unknownfile'; // probably call_user_func()
731 $from .= $plaintext ?
'* ' : '<li>';
732 $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
733 if (isset($caller['function'])) {
734 $from .= ': call to ';
735 if (isset($caller['class'])) {
736 $from .= $caller['class'] . $caller['type'];
738 $from .= $caller['function'] . '()';
739 } else if (isset($caller['exception'])) {
740 $from .= ': '.$caller['exception'].' thrown';
742 $from .= $plaintext ?
"\n" : '</li>';
744 $from .= $plaintext ?
'' : '</ul>';
750 * This function makes the return value of ini_get consistent if you are
751 * setting server directives through the .htaccess file in apache.
753 * Current behavior for value set from php.ini On = 1, Off = [blank]
754 * Current behavior for value set from .htaccess On = On, Off = Off
755 * Contributed by jdell @ unr.edu
757 * @param string $ini_get_arg The argument to get
758 * @return bool True for on false for not
760 function ini_get_bool($ini_get_arg) {
761 $temp = ini_get($ini_get_arg);
763 if ($temp == '1' or strtolower($temp) == 'on') {
770 * This function verifies the sanity of PHP configuration
771 * and stops execution if anything critical found.
773 function setup_validate_php_configuration() {
774 // this must be very fast - no slow checks here!!!
776 if (ini_get_bool('session.auto_start')) {
777 print_error('sessionautostartwarning', 'admin');
782 * Initialise global $CFG variable.
783 * @private to be used only from lib/setup.php
785 function initialise_cfg() {
789 // This should not happen.
794 $localcfg = get_config('core');
795 } catch (dml_exception
$e) {
796 // Most probably empty db, going to install soon.
800 foreach ($localcfg as $name => $value) {
801 // Note that get_config() keeps forced settings
802 // and normalises values to string if possible.
803 $CFG->{$name} = $value;
808 * Initialises $FULLME and friends. Private function. Should only be called from
811 function initialise_fullme() {
812 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
814 // Detect common config error.
815 if (substr($CFG->wwwroot
, -1) == '/') {
816 print_error('wwwrootslash', 'error');
820 initialise_fullme_cli();
823 if (!empty($CFG->overridetossl
)) {
824 if (strpos($CFG->wwwroot
, 'http://') === 0) {
825 $CFG->wwwroot
= str_replace('http:', 'https:', $CFG->wwwroot
);
827 unset_config('overridetossl');
831 $rurl = setup_get_remote_url();
832 $wwwroot = parse_url($CFG->wwwroot
.'/');
834 if (empty($rurl['host'])) {
835 // missing host in request header, probably not a real browser, let's ignore them
837 } else if (!empty($CFG->reverseproxy
)) {
838 // $CFG->reverseproxy specifies if reverse proxy server used
839 // Used in load balancing scenarios.
840 // Do not abuse this to try to solve lan/wan access problems!!!!!
843 if (($rurl['host'] !== $wwwroot['host']) or
844 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port']) or
845 (strpos($rurl['path'], $wwwroot['path']) !== 0)) {
847 // Explain the problem and redirect them to the right URL
848 if (!defined('NO_MOODLE_COOKIES')) {
849 define('NO_MOODLE_COOKIES', true);
851 // The login/token.php script should call the correct url/port.
852 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS
) {
853 $wwwrootport = empty($wwwroot['port'])?
'':$wwwroot['port'];
854 $calledurl = $rurl['host'];
855 if (!empty($rurl['port'])) {
856 $calledurl .= ':'. $rurl['port'];
858 $correcturl = $wwwroot['host'];
859 if (!empty($wwwrootport)) {
860 $correcturl .= ':'. $wwwrootport;
862 throw new moodle_exception('requirecorrectaccess', 'error', '', null,
863 'You called ' . $calledurl .', you should have called ' . $correcturl);
865 redirect($CFG->wwwroot
, get_string('wwwrootmismatch', 'error', $CFG->wwwroot
), 3);
869 // Check that URL is under $CFG->wwwroot.
870 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
871 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
873 // Probably some weird external script
874 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
878 // $CFG->sslproxy specifies if external SSL appliance is used
879 // (That is, the Moodle server uses http, with an external box translating everything to https).
880 if (empty($CFG->sslproxy
)) {
881 if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
882 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS
) {
883 print_error('sslonlyaccess', 'error');
885 redirect($CFG->wwwroot
, get_string('wwwrootmismatch', 'error', $CFG->wwwroot
), 3);
889 if ($wwwroot['scheme'] !== 'https') {
890 throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
892 $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
893 $_SERVER['HTTPS'] = 'on'; // Override $_SERVER to help external libraries with their HTTPS detection.
894 $_SERVER['SERVER_PORT'] = 443; // Assume default ssl port for the proxy.
897 // hopefully this will stop all those "clever" admins trying to set up moodle
898 // with two different addresses in intranet and Internet
899 if (!empty($CFG->reverseproxy
) && $rurl['host'] === $wwwroot['host']) {
900 print_error('reverseproxyabused', 'error');
903 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
904 if (!empty($wwwroot['port'])) {
905 $hostandport .= ':'.$wwwroot['port'];
908 $FULLSCRIPT = $hostandport . $rurl['path'];
909 $FULLME = $hostandport . $rurl['fullpath'];
910 $ME = $rurl['fullpath'];
914 * Initialises $FULLME and friends for command line scripts.
915 * This is a private method for use by initialise_fullme.
917 function initialise_fullme_cli() {
918 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
920 // Urls do not make much sense in CLI scripts
921 $backtrace = debug_backtrace();
922 $topfile = array_pop($backtrace);
923 $topfile = realpath($topfile['file']);
924 $dirroot = realpath($CFG->dirroot
);
926 if (strpos($topfile, $dirroot) !== 0) {
927 // Probably some weird external script
928 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
930 $relativefile = substr($topfile, strlen($dirroot));
931 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
932 $SCRIPT = $FULLSCRIPT = $relativefile;
933 $FULLME = $ME = null;
938 * Get the URL that PHP/the web server thinks it is serving. Private function
939 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
940 * @return array in the same format that parse_url returns, with the addition of
941 * a 'fullpath' element, which includes any slasharguments path.
943 function setup_get_remote_url() {
945 if (isset($_SERVER['HTTP_HOST'])) {
946 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
948 $rurl['host'] = null;
950 $rurl['port'] = $_SERVER['SERVER_PORT'];
951 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
952 $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ?
'http' : 'https';
954 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
956 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
958 // Fixing a known issue with:
959 // - Apache versions lesser than 2.4.11
960 // - PHP deployed in Apache as PHP-FPM via mod_proxy_fcgi
961 // - PHP versions lesser than 5.6.3 and 5.5.18.
962 if (isset($_SERVER['PATH_INFO']) && (php_sapi_name() === 'fpm-fcgi') && isset($_SERVER['SCRIPT_NAME'])) {
963 $pathinfodec = rawurldecode($_SERVER['PATH_INFO']);
964 $lenneedle = strlen($pathinfodec);
965 // Checks whether SCRIPT_NAME ends with PATH_INFO, URL-decoded.
966 if (substr($_SERVER['SCRIPT_NAME'], -$lenneedle) === $pathinfodec) {
967 // This is the "Apache 2.4.10- running PHP-FPM via mod_proxy_fcgi" fingerprint,
968 // 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)
969 // => SCRIPT_NAME contains 'slash arguments' data too, which is wrongly exposed via PATH_INFO as URL-encoded.
970 // Fix both $_SERVER['PATH_INFO'] and $_SERVER['SCRIPT_NAME'].
971 $lenhaystack = strlen($_SERVER['SCRIPT_NAME']);
972 $pos = $lenhaystack - $lenneedle;
973 // Here $pos is greater than 0 but let's double check it.
975 $_SERVER['PATH_INFO'] = $pathinfodec;
976 $_SERVER['SCRIPT_NAME'] = substr($_SERVER['SCRIPT_NAME'], 0, $pos);
981 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
982 //IIS - needs a lot of tweaking to make it work
983 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
985 // NOTE: we should ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS.
986 // Since 2.0, we rely on IIS rewrite extensions like Helicon ISAPI_rewrite
987 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
989 // we rely on a proper IIS 6.0+ configuration: the 'FastCGIUtf8ServerVariables' registry key.
990 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
991 // Check that PATH_INFO works == must not contain the script name.
992 if (strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === false) {
993 $rurl['fullpath'] .= clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH
);
997 if (isset($_SERVER['QUERY_STRING']) and $_SERVER['QUERY_STRING'] !== '') {
998 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
1000 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
1002 /* NOTE: following servers are not fully tested! */
1004 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
1005 //lighttpd - not officially supported
1006 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1008 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
1009 //nginx - not officially supported
1010 if (!isset($_SERVER['SCRIPT_NAME'])) {
1011 die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
1013 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1015 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
1016 //cherokee - not officially supported
1017 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1019 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
1020 //zeus - not officially supported
1021 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1023 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
1024 //LiteSpeed - not officially supported
1025 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1027 } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
1028 //obscure name found on some servers - this is definitely not supported
1029 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1031 } else if (strpos($_SERVER['SERVER_SOFTWARE'], 'PHP') === 0) {
1032 // built-in PHP Development Server
1033 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
1036 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
1039 // sanitize the url a bit more, the encoding style may be different in vars above
1040 $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
1041 $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);
1047 * Try to work around the 'max_input_vars' restriction if necessary.
1049 function workaround_max_input_vars() {
1050 // Make sure this gets executed only once from lib/setup.php!
1051 static $executed = false;
1053 debugging('workaround_max_input_vars() must be called only once!');
1058 if (!isset($_SERVER["CONTENT_TYPE"]) or strpos($_SERVER["CONTENT_TYPE"], 'multipart/form-data') !== false) {
1059 // Not a post or 'multipart/form-data' which is not compatible with "php://input" reading.
1063 if (!isloggedin() or isguestuser()) {
1064 // Only real users post huge forms.
1068 $max = (int)ini_get('max_input_vars');
1071 // Most probably PHP < 5.3.9 that does not implement this limit.
1075 if ($max >= 200000) {
1076 // This value should be ok for all our forms, by setting it in php.ini
1077 // admins may prevent any unexpected regressions caused by this hack.
1079 // Note there is no need to worry about DDoS caused by making this limit very high
1080 // because there are very many easier ways to DDoS any Moodle server.
1084 // Worst case is advanced checkboxes which use up to two max_input_vars
1085 // slots for each entry in $_POST, because of sending two fields with the
1086 // same name. So count everything twice just in case.
1087 if (count($_POST, COUNT_RECURSIVE
) * 2 < $max) {
1091 // Large POST request with enctype supported by php://input.
1092 // Parse php://input in chunks to bypass max_input_vars limit, which also applies to parse_str().
1093 $str = file_get_contents("php://input");
1094 if ($str === false or $str === '') {
1095 // Some weird error.
1100 $fun = function($p) use ($delim) {
1101 return implode($delim, $p);
1103 $chunks = array_map($fun, array_chunk(explode($delim, $str), $max));
1105 // Clear everything from existing $_POST array, otherwise it might be included
1106 // twice (this affects array params primarily).
1107 foreach ($_POST as $key => $value) {
1108 unset($_POST[$key]);
1109 // Also clear from request array - but only the things that are in $_POST,
1110 // that way it will leave the things from a get request if any.
1111 unset($_REQUEST[$key]);
1114 foreach ($chunks as $chunk) {
1116 parse_str($chunk, $values);
1118 merge_query_params($_POST, $values);
1119 merge_query_params($_REQUEST, $values);
1124 * Merge parsed POST chunks.
1126 * NOTE: this is not perfect, but it should work in most cases hopefully.
1128 * @param array $target
1129 * @param array $values
1131 function merge_query_params(array &$target, array $values) {
1132 if (isset($values[0]) and isset($target[0])) {
1133 // This looks like a split [] array, lets verify the keys are continuous starting with 0.
1134 $keys1 = array_keys($values);
1135 $keys2 = array_keys($target);
1136 if ($keys1 === array_keys($keys1) and $keys2 === array_keys($keys2)) {
1137 foreach ($values as $v) {
1143 foreach ($values as $k => $v) {
1144 if (!isset($target[$k])) {
1148 if (is_array($target[$k]) and is_array($v)) {
1149 merge_query_params($target[$k], $v);
1152 // We should not get here unless there are duplicates in params.
1158 * Initializes our performance info early.
1160 * Pairs up with get_performance_info() which is actually
1161 * in moodlelib.php. This function is here so that we can
1162 * call it before all the libs are pulled in.
1166 function init_performance_info() {
1168 global $PERF, $CFG, $USER;
1170 $PERF = new stdClass();
1171 $PERF->logwrites
= 0;
1172 if (function_exists('microtime')) {
1173 $PERF->starttime
= microtime();
1175 if (function_exists('memory_get_usage')) {
1176 $PERF->startmemory
= memory_get_usage();
1178 if (function_exists('posix_times')) {
1179 $PERF->startposixtimes
= posix_times();
1184 * Indicates whether we are in the middle of the initial Moodle install.
1186 * Very occasionally it is necessary avoid running certain bits of code before the
1187 * Moodle installation has completed. The installed flag is set in admin/index.php
1188 * after Moodle core and all the plugins have been installed, but just before
1189 * the person doing the initial install is asked to choose the admin password.
1191 * @return boolean true if the initial install is not complete.
1193 function during_initial_install() {
1195 return empty($CFG->rolesactive
);
1199 * Function to raise the memory limit to a new value.
1200 * Will respect the memory limit if it is higher, thus allowing
1201 * settings in php.ini, apache conf or command line switches
1204 * The memory limit should be expressed with a constant
1205 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
1206 * It is possible to use strings or integers too (eg:'128M').
1208 * @param mixed $newlimit the new memory limit
1209 * @return bool success
1211 function raise_memory_limit($newlimit) {
1214 if ($newlimit == MEMORY_UNLIMITED
) {
1215 ini_set('memory_limit', -1);
1218 } else if ($newlimit == MEMORY_STANDARD
) {
1219 if (PHP_INT_SIZE
> 4) {
1220 $newlimit = get_real_size('128M'); // 64bit needs more memory
1222 $newlimit = get_real_size('96M');
1225 } else if ($newlimit == MEMORY_EXTRA
) {
1226 if (PHP_INT_SIZE
> 4) {
1227 $newlimit = get_real_size('384M'); // 64bit needs more memory
1229 $newlimit = get_real_size('256M');
1231 if (!empty($CFG->extramemorylimit
)) {
1232 $extra = get_real_size($CFG->extramemorylimit
);
1233 if ($extra > $newlimit) {
1238 } else if ($newlimit == MEMORY_HUGE
) {
1239 // MEMORY_HUGE uses 2G or MEMORY_EXTRA, whichever is bigger.
1240 $newlimit = get_real_size('2G');
1241 if (!empty($CFG->extramemorylimit
)) {
1242 $extra = get_real_size($CFG->extramemorylimit
);
1243 if ($extra > $newlimit) {
1249 $newlimit = get_real_size($newlimit);
1252 if ($newlimit <= 0) {
1253 debugging('Invalid memory limit specified.');
1257 $cur = ini_get('memory_limit');
1259 // if php is compiled without --enable-memory-limits
1260 // apparently memory_limit is set to ''
1264 return true; // unlimited mem!
1266 $cur = get_real_size($cur);
1269 if ($newlimit > $cur) {
1270 ini_set('memory_limit', $newlimit);
1277 * Function to reduce the memory limit to a new value.
1278 * Will respect the memory limit if it is lower, thus allowing
1279 * settings in php.ini, apache conf or command line switches
1282 * The memory limit should be expressed with a string (eg:'64M')
1284 * @param string $newlimit the new memory limit
1287 function reduce_memory_limit($newlimit) {
1288 if (empty($newlimit)) {
1291 $cur = ini_get('memory_limit');
1293 // if php is compiled without --enable-memory-limits
1294 // apparently memory_limit is set to ''
1298 return true; // unlimited mem!
1300 $cur = get_real_size($cur);
1303 $new = get_real_size($newlimit);
1304 // -1 is smaller, but it means unlimited
1305 if ($new < $cur && $new != -1) {
1306 ini_set('memory_limit', $newlimit);
1313 * Converts numbers like 10M into bytes.
1315 * @param string $size The size to be converted
1318 function get_real_size($size = 0) {
1323 static $binaryprefixes = array(
1330 'T' => 1099511627776,
1331 't' => 1099511627776,
1334 if (preg_match('/^([0-9]+)([KMGT])/i', $size, $matches)) {
1335 return $matches[1] * $binaryprefixes[$matches[2]];
1342 * Try to disable all output buffering and purge
1345 * @access private to be called only from lib/setup.php !
1348 function disable_output_buffering() {
1349 $olddebug = error_reporting(0);
1351 // disable compression, it would prevent closing of buffers
1352 if (ini_get_bool('zlib.output_compression')) {
1353 ini_set('zlib.output_compression', 'Off');
1356 // try to flush everything all the time
1357 ob_implicit_flush(true);
1359 // close all buffers if possible and discard any existing output
1360 // this can actually work around some whitespace problems in config.php
1361 while(ob_get_level()) {
1362 if (!ob_end_clean()) {
1363 // prevent infinite loop when buffer can not be closed
1368 // disable any other output handlers
1369 ini_set('output_handler', '');
1371 error_reporting($olddebug);
1373 // Disable buffering in nginx.
1374 header('X-Accel-Buffering: no');
1379 * Check whether a major upgrade is needed.
1381 * That is defined as an upgrade that changes something really fundamental
1382 * in the database, so nothing can possibly work until the database has
1383 * been updated, and that is defined by the hard-coded version number in
1388 function is_major_upgrade_required() {
1390 $lastmajordbchanges = 2019050100.01;
1392 $required = empty($CFG->version
);
1393 $required = $required ||
(float)$CFG->version
< $lastmajordbchanges;
1394 $required = $required ||
during_initial_install();
1395 $required = $required ||
!empty($CFG->adminsetuppending
);
1401 * Redirect to the Notifications page if a major upgrade is required, and
1402 * terminate the current user session.
1404 function redirect_if_major_upgrade_required() {
1406 if (is_major_upgrade_required()) {
1408 @\core\session\manager
::terminate_current();
1409 } catch (Exception
$e) {
1410 // Ignore any errors, redirect to upgrade anyway.
1412 $url = $CFG->wwwroot
. '/' . $CFG->admin
. '/index.php';
1413 @header
($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1414 @header
('Location: ' . $url);
1415 echo bootstrap_renderer
::plain_redirect_message(htmlspecialchars($url));
1421 * Makes sure that upgrade process is not running
1423 * To be inserted in the core functions that can not be called by pluigns during upgrade.
1424 * Core upgrade should not use any API functions at all.
1425 * See {@link http://docs.moodle.org/dev/Upgrade_API#Upgrade_code_restrictions}
1427 * @throws moodle_exception if executed from inside of upgrade script and $warningonly is false
1428 * @param bool $warningonly if true displays a warning instead of throwing an exception
1429 * @return bool true if executed from outside of upgrade process, false if from inside upgrade process and function is used for warning only
1431 function upgrade_ensure_not_running($warningonly = false) {
1433 if (!empty($CFG->upgraderunning
)) {
1434 if (!$warningonly) {
1435 throw new moodle_exception('cannotexecduringupgrade');
1437 debugging(get_string('cannotexecduringupgrade', 'error'), DEBUG_DEVELOPER
);
1445 * Function to check if a directory exists and by default create it if not exists.
1447 * Previously this was accepting paths only from dataroot, but we now allow
1448 * files outside of dataroot if you supply custom paths for some settings in config.php.
1449 * This function does not verify that the directory is writable.
1451 * NOTE: this function uses current file stat cache,
1452 * please use clearstatcache() before this if you expect that the
1453 * directories may have been removed recently from a different request.
1455 * @param string $dir absolute directory path
1456 * @param boolean $create directory if does not exist
1457 * @param boolean $recursive create directory recursively
1458 * @return boolean true if directory exists or created, false otherwise
1460 function check_dir_exists($dir, $create = true, $recursive = true) {
1463 umask($CFG->umaskpermissions
);
1473 return mkdir($dir, $CFG->directorypermissions
, $recursive);
1477 * Create a new unique directory within the specified directory.
1479 * @param string $basedir The directory to create your new unique directory within.
1480 * @param bool $exceptiononerror throw exception if error encountered
1481 * @return string The created directory
1482 * @throws invalid_dataroot_permissions
1484 function make_unique_writable_directory($basedir, $exceptiononerror = true) {
1485 if (!is_dir($basedir) ||
!is_writable($basedir)) {
1486 // The basedir is not writable. We will not be able to create the child directory.
1487 if ($exceptiononerror) {
1488 throw new invalid_dataroot_permissions($basedir . ' is not writable. Unable to create a unique directory within it.');
1495 // Generate a new (hopefully unique) directory name.
1496 $uniquedir = $basedir . DIRECTORY_SEPARATOR
. \core\uuid
::generate();
1498 // Ensure that basedir is still writable - if we do not check, we could get stuck in a loop here.
1499 is_writable($basedir) &&
1501 // Make the new unique directory. If the directory already exists, it will return false.
1502 !make_writable_directory($uniquedir, $exceptiononerror) &&
1504 // Ensure that the directory now exists
1505 file_exists($uniquedir) && is_dir($uniquedir)
1508 // Check that the directory was correctly created.
1509 if (!file_exists($uniquedir) ||
!is_dir($uniquedir) ||
!is_writable($uniquedir)) {
1510 if ($exceptiononerror) {
1511 throw new invalid_dataroot_permissions('Unique directory creation failed.');
1521 * Create a directory and make sure it is writable.
1524 * @param string $dir the full path of the directory to be created
1525 * @param bool $exceptiononerror throw exception if error encountered
1526 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1528 function make_writable_directory($dir, $exceptiononerror = true) {
1531 if (file_exists($dir) and !is_dir($dir)) {
1532 if ($exceptiononerror) {
1533 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1539 umask($CFG->umaskpermissions
);
1541 if (!file_exists($dir)) {
1542 if (!@mkdir
($dir, $CFG->directorypermissions
, true)) {
1544 // There might be a race condition when creating directory.
1545 if (!is_dir($dir)) {
1546 if ($exceptiononerror) {
1547 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1549 debugging('Can not create directory: '.$dir, DEBUG_DEVELOPER
);
1556 if (!is_writable($dir)) {
1557 if ($exceptiononerror) {
1558 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1568 * Protect a directory from web access.
1569 * Could be extended in the future to support other mechanisms (e.g. other webservers).
1572 * @param string $dir the full path of the directory to be protected
1574 function protect_directory($dir) {
1576 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1577 if (!file_exists("$dir/.htaccess")) {
1578 if ($handle = fopen("$dir/.htaccess", 'w')) { // For safety
1579 @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");
1581 @chmod
("$dir/.htaccess", $CFG->filepermissions
);
1587 * Create a directory under dataroot and make sure it is writable.
1588 * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
1590 * @param string $directory the full path of the directory to be created under $CFG->dataroot
1591 * @param bool $exceptiononerror throw exception if error encountered
1592 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1594 function make_upload_directory($directory, $exceptiononerror = true) {
1597 if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1598 debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1600 } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
1601 debugging('Use make_cache_directory() for creation of cache directory and $CFG->cachedir to get the location.');
1603 } else if (strpos($directory, 'localcache/') === 0 or $directory === 'localcache') {
1604 debugging('Use make_localcache_directory() for creation of local cache directory and $CFG->localcachedir to get the location.');
1607 protect_directory($CFG->dataroot
);
1608 return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1612 * Get a per-request storage directory in the tempdir.
1614 * The directory is automatically cleaned up during the shutdown handler.
1616 * @param bool $exceptiononerror throw exception if error encountered
1617 * @param bool $forcecreate Force creation of a new parent directory
1618 * @return string Returns full path to directory if successful, false if not; may throw exception
1620 function get_request_storage_directory($exceptiononerror = true, bool $forcecreate = false) {
1623 static $requestdir = null;
1625 $writabledirectoryexists = (null !== $requestdir);
1626 $writabledirectoryexists = $writabledirectoryexists && file_exists($requestdir);
1627 $writabledirectoryexists = $writabledirectoryexists && is_dir($requestdir);
1628 $writabledirectoryexists = $writabledirectoryexists && is_writable($requestdir);
1629 $createnewdirectory = $forcecreate ||
!$writabledirectoryexists;
1631 if ($createnewdirectory) {
1632 if ($CFG->localcachedir
!== "$CFG->dataroot/localcache") {
1633 check_dir_exists($CFG->localcachedir
, true, true);
1634 protect_directory($CFG->localcachedir
);
1636 protect_directory($CFG->dataroot
);
1639 if ($dir = make_unique_writable_directory($CFG->localcachedir
, $exceptiononerror)) {
1640 // Register a shutdown handler to remove the directory.
1641 \core_shutdown_manager
::register_function('remove_dir', [$dir]);
1651 * Create a per-request directory and make sure it is writable.
1652 * This can only be used during the current request and will be tidied away
1653 * automatically afterwards.
1655 * A new, unique directory is always created within a shared base request directory.
1657 * In some exceptional cases an alternative base directory may be required. This can be accomplished using the
1658 * $forcecreate parameter. Typically this will only be requried where the file may be required during a shutdown handler
1659 * which may or may not be registered after a previous request directory has been created.
1661 * @param bool $exceptiononerror throw exception if error encountered
1662 * @param bool $forcecreate Force creation of a new parent directory
1663 * @return string The full path to directory if successful, false if not; may throw exception
1665 function make_request_directory($exceptiononerror = true, bool $forcecreate = false) {
1666 $basedir = get_request_storage_directory($exceptiononerror, $forcecreate);
1667 return make_unique_writable_directory($basedir, $exceptiononerror);
1671 * Get the full path of a directory under $CFG->backuptempdir.
1673 * @param string $directory the relative path of the directory under $CFG->backuptempdir
1674 * @return string|false Returns full path to directory given a valid string; otherwise, false.
1676 function get_backup_temp_directory($directory) {
1678 if (($directory === null) ||
($directory === false)) {
1681 return "$CFG->backuptempdir/$directory";
1685 * Create a directory under $CFG->backuptempdir and make sure it is writable.
1687 * Do not use for storing generic temp files - see make_temp_directory() instead for this purpose.
1689 * Backup temporary files must be on a shared storage.
1691 * @param string $directory the relative path of the directory to be created under $CFG->backuptempdir
1692 * @param bool $exceptiononerror throw exception if error encountered
1693 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1695 function make_backup_temp_directory($directory, $exceptiononerror = true) {
1697 if ($CFG->backuptempdir
!== "$CFG->tempdir/backup") {
1698 check_dir_exists($CFG->backuptempdir
, true, true);
1699 protect_directory($CFG->backuptempdir
);
1701 protect_directory($CFG->tempdir
);
1703 return make_writable_directory("$CFG->backuptempdir/$directory", $exceptiononerror);
1707 * Create a directory under tempdir and make sure it is writable.
1709 * Where possible, please use make_request_directory() and limit the scope
1710 * of your data to the current HTTP request.
1712 * Do not use for storing cache files - see make_cache_directory(), and
1713 * make_localcache_directory() instead for this purpose.
1715 * Temporary files must be on a shared storage, and heavy usage is
1716 * discouraged due to the performance impact upon clustered environments.
1718 * @param string $directory the full path of the directory to be created under $CFG->tempdir
1719 * @param bool $exceptiononerror throw exception if error encountered
1720 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1722 function make_temp_directory($directory, $exceptiononerror = true) {
1724 if ($CFG->tempdir
!== "$CFG->dataroot/temp") {
1725 check_dir_exists($CFG->tempdir
, true, true);
1726 protect_directory($CFG->tempdir
);
1728 protect_directory($CFG->dataroot
);
1730 return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1734 * Create a directory under cachedir and make sure it is writable.
1736 * Note: this cache directory is shared by all cluster nodes.
1738 * @param string $directory the full path of the directory to be created under $CFG->cachedir
1739 * @param bool $exceptiononerror throw exception if error encountered
1740 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1742 function make_cache_directory($directory, $exceptiononerror = true) {
1744 if ($CFG->cachedir
!== "$CFG->dataroot/cache") {
1745 check_dir_exists($CFG->cachedir
, true, true);
1746 protect_directory($CFG->cachedir
);
1748 protect_directory($CFG->dataroot
);
1750 return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1754 * Create a directory under localcachedir and make sure it is writable.
1755 * The files in this directory MUST NOT change, use revisions or content hashes to
1756 * work around this limitation - this means you can only add new files here.
1758 * The content of this directory gets purged automatically on all cluster nodes
1759 * after calling purge_all_caches() before new data is written to this directory.
1761 * Note: this local cache directory does not need to be shared by cluster nodes.
1763 * @param string $directory the relative path of the directory to be created under $CFG->localcachedir
1764 * @param bool $exceptiononerror throw exception if error encountered
1765 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1767 function make_localcache_directory($directory, $exceptiononerror = true) {
1770 make_writable_directory($CFG->localcachedir
, $exceptiononerror);
1772 if ($CFG->localcachedir
!== "$CFG->dataroot/localcache") {
1773 protect_directory($CFG->localcachedir
);
1775 protect_directory($CFG->dataroot
);
1778 if (!isset($CFG->localcachedirpurged
)) {
1779 $CFG->localcachedirpurged
= 0;
1781 $timestampfile = "$CFG->localcachedir/.lastpurged";
1783 if (!file_exists($timestampfile)) {
1784 touch($timestampfile);
1785 @chmod
($timestampfile, $CFG->filepermissions
);
1787 } else if (filemtime($timestampfile) < $CFG->localcachedirpurged
) {
1788 // This means our local cached dir was not purged yet.
1789 remove_dir($CFG->localcachedir
, true);
1790 if ($CFG->localcachedir
!== "$CFG->dataroot/localcache") {
1791 protect_directory($CFG->localcachedir
);
1793 touch($timestampfile);
1794 @chmod
($timestampfile, $CFG->filepermissions
);
1798 if ($directory === '') {
1799 return $CFG->localcachedir
;
1802 return make_writable_directory("$CFG->localcachedir/$directory", $exceptiononerror);
1806 * Webserver access user logging
1808 function set_access_log_user() {
1810 if ($USER && isset($USER->username
)) {
1813 if (!empty($CFG->apacheloguser
) && function_exists('apache_note')) {
1814 $logmethod = 'apache';
1815 $logvalue = $CFG->apacheloguser
;
1817 if (!empty($CFG->headerloguser
)) {
1818 $logmethod = 'header';
1819 $logvalue = $CFG->headerloguser
;
1821 if (!empty($logmethod)) {
1822 $loguserid = $USER->id
;
1823 $logusername = clean_filename($USER->username
);
1825 if (isset($USER->firstname
)) {
1826 // We can assume both will be set
1827 // - even if to empty.
1828 $logname = clean_filename($USER->firstname
. " " . $USER->lastname
);
1830 if (\core\session\manager
::is_loggedinas()) {
1831 $realuser = \core\session\manager
::get_realuser();
1832 $logusername = clean_filename($realuser->username
." as ".$logusername);
1833 $logname = clean_filename($realuser->firstname
." ".$realuser->lastname
." as ".$logname);
1834 $loguserid = clean_filename($realuser->id
." as ".$loguserid);
1836 switch ($logvalue) {
1838 $logname = $logusername;
1841 $logname = $logname;
1845 $logname = $loguserid;
1848 if ($logmethod == 'apache') {
1849 apache_note('MOODLEUSER', $logname);
1852 if ($logmethod == 'header') {
1853 header("X-MOODLEUSER: $logname");
1860 * This class solves the problem of how to initialise $OUTPUT.
1862 * The problem is caused be two factors
1864 * <li>On the one hand, we cannot be sure when output will start. In particular,
1865 * an error, which needs to be displayed, could be thrown at any time.</li>
1866 * <li>On the other hand, we cannot be sure when we will have all the information
1867 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1868 * (potentially) depends on the current course, course categories, and logged in user.
1869 * It also depends on whether the current page requires HTTPS.</li>
1872 * So, it is hard to find a single natural place during Moodle script execution,
1873 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1874 * adopt the following strategy
1876 * <li>We will initialise $OUTPUT the first time it is used.</li>
1877 * <li>If, after $OUTPUT has been initialised, the script tries to change something
1878 * that $OUTPUT depends on, we throw an exception making it clear that the script
1879 * did something wrong.
1882 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1883 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1884 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1885 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1887 * Note that this class is used before lib/outputlib.php has been loaded, so we
1888 * must be careful referring to classes/functions from there, they may not be
1889 * defined yet, and we must avoid fatal errors.
1891 * @copyright 2009 Tim Hunt
1892 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1895 class bootstrap_renderer
{
1897 * Handles re-entrancy. Without this, errors or debugging output that occur
1898 * during the initialisation of $OUTPUT, cause infinite recursion.
1901 protected $initialising = false;
1904 * Have we started output yet?
1905 * @return boolean true if the header has been printed.
1907 public function has_started() {
1912 * Constructor - to be used by core code only.
1913 * @param string $method The method to call
1914 * @param array $arguments Arguments to pass to the method being called
1917 public function __call($method, $arguments) {
1918 global $OUTPUT, $PAGE;
1921 if ($method == 'notification') {
1922 // Catch infinite recursion caused by debugging output during print_header.
1923 $backtrace = debug_backtrace();
1924 array_shift($backtrace);
1925 array_shift($backtrace);
1926 $recursing = is_early_init($backtrace);
1929 $earlymethods = array(
1930 'fatal_error' => 'early_error',
1931 'notification' => 'early_notification',
1934 // If lib/outputlib.php has been loaded, call it.
1935 if (!empty($PAGE) && !$recursing) {
1936 if (array_key_exists($method, $earlymethods)) {
1937 //prevent PAGE->context warnings - exceptions might appear before we set any context
1938 $PAGE->set_context(null);
1940 $PAGE->initialise_theme_and_output();
1941 return call_user_func_array(array($OUTPUT, $method), $arguments);
1944 $this->initialising
= true;
1946 // Too soon to initialise $OUTPUT, provide a couple of key methods.
1947 if (array_key_exists($method, $earlymethods)) {
1948 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1951 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1955 * Returns nicely formatted error message in a div box.
1957 * @param string $message error message
1958 * @param string $moreinfourl (ignored in early errors)
1959 * @param string $link (ignored in early errors)
1960 * @param array $backtrace
1961 * @param string $debuginfo
1964 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1967 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1968 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1969 width: 80%; -moz-border-radius: 20px; padding: 15px">
1972 // Check whether debug is set.
1973 $debug = (!empty($CFG->debug
) && $CFG->debug
>= DEBUG_DEVELOPER
);
1974 // Also check we have it set in the config file. This occurs if the method to read the config table from the
1975 // database fails, reading from the config table is the first database interaction we have.
1976 $debug = $debug ||
(!empty($CFG->config_php_settings
['debug']) && $CFG->config_php_settings
['debug'] >= DEBUG_DEVELOPER
);
1978 if (!empty($debuginfo)) {
1979 // Remove all nasty JS.
1980 if (function_exists('s')) { // Function may be not available for some early errors.
1981 $debuginfo = s($debuginfo);
1983 // Because weblib is not available for these early errors, we
1984 // just duplicate s() code here to be safe.
1985 $debuginfo = preg_replace('/&#(\d+|x[0-9a-f]+);/i', '&#$1;',
1986 htmlspecialchars($debuginfo, ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE
));
1988 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1989 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
1991 if (!empty($backtrace)) {
1992 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
2000 * This function should only be called by this class, or from exception handlers
2002 * @param string $message error message
2003 * @param string $moreinfourl (ignored in early errors)
2004 * @param string $link (ignored in early errors)
2005 * @param array $backtrace
2006 * @param string $debuginfo extra information for developers
2009 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = null) {
2013 echo "!!! $message !!!\n";
2014 if (!empty($CFG->debug
) and $CFG->debug
>= DEBUG_DEVELOPER
) {
2015 if (!empty($debuginfo)) {
2016 echo "\nDebug info: $debuginfo";
2018 if (!empty($backtrace)) {
2019 echo "\nStack trace: " . format_backtrace($backtrace, true);
2024 } else if (AJAX_SCRIPT
) {
2025 $e = new stdClass();
2026 $e->error
= $message;
2027 $e->stacktrace
= NULL;
2028 $e->debuginfo
= NULL;
2029 if (!empty($CFG->debug
) and $CFG->debug
>= DEBUG_DEVELOPER
) {
2030 if (!empty($debuginfo)) {
2031 $e->debuginfo
= $debuginfo;
2033 if (!empty($backtrace)) {
2034 $e->stacktrace
= format_backtrace($backtrace, true);
2037 $e->errorcode
= $errorcode;
2038 @header
('Content-Type: application/json; charset=utf-8');
2039 echo json_encode($e);
2043 // In the name of protocol correctness, monitoring and performance
2044 // profiling, set the appropriate error headers for machine consumption.
2045 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ?
$_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2046 @header
($protocol . ' 503 Service Unavailable');
2048 // better disable any caching
2049 @header
('Content-Type: text/html; charset=utf-8');
2050 @header
('X-UA-Compatible: IE=edge');
2051 @header
('Cache-Control: no-store, no-cache, must-revalidate');
2052 @header
('Cache-Control: post-check=0, pre-check=0', false);
2053 @header
('Pragma: no-cache');
2054 @header
('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2055 @header
('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2057 if (function_exists('get_string')) {
2058 $strerror = get_string('error');
2060 $strerror = 'Error';
2063 $content = self
::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
2065 return self
::plain_page($strerror, $content);
2069 * Early notification message
2071 * @param string $message
2072 * @param string $classes usually notifyproblem or notifysuccess
2075 public static function early_notification($message, $classes = 'notifyproblem') {
2076 return '<div class="' . $classes . '">' . $message . '</div>';
2080 * Page should redirect message.
2082 * @param string $encodedurl redirect url
2085 public static function plain_redirect_message($encodedurl) {
2086 $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
2087 $encodedurl .'">'. get_string('continue') .'</a></div>';
2088 return self
::plain_page(get_string('redirect'), $message);
2092 * Early redirection page, used before full init of $PAGE global
2094 * @param string $encodedurl redirect url
2095 * @param string $message redirect message
2096 * @param int $delay time in seconds
2097 * @return string redirect page
2099 public static function early_redirect_message($encodedurl, $message, $delay) {
2100 $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
2101 $content = self
::early_error_content($message, null, null, null);
2102 $content .= self
::plain_redirect_message($encodedurl);
2104 return self
::plain_page(get_string('redirect'), $content, $meta);
2108 * Output basic html page.
2110 * @param string $title page title
2111 * @param string $content page content
2112 * @param string $meta meta tag
2113 * @return string html page
2115 public static function plain_page($title, $content, $meta = '') {
2116 if (function_exists('get_string') && function_exists('get_html_lang')) {
2117 $htmllang = get_html_lang();
2123 if (function_exists('get_performance_info')) { // Function may be not available for some early errors.
2124 if (MDL_PERF_TEST
) {
2125 $perfinfo = get_performance_info();
2126 $footer = '<footer>' . $perfinfo['html'] . '</footer>';
2130 return '<!DOCTYPE html>
2131 <html ' . $htmllang . '>
2133 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
2135 <title>' . $title . '</title>
2136 </head><body>' . $content . $footer . '</body></html>';