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);
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.
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
{
70 public function __construct() {
71 debugging("'object' class has been deprecated, please use stdClass instead.", DEBUG_DEVELOPER
);
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).
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
{
89 * @var string The name of the string from error.php to print
94 * @var string The name of module
99 * @var mixed Extra words and phrases that might be required in the error string
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.
109 * @var string Optional information to aid the debugging process
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') {
126 $this->errorcode
= $errorcode;
127 $this->module
= $module;
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;
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
{
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
{
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
{
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
{
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();
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.
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
{
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.
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
{
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
{
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.
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
{
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
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
{
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
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
{
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
);
384 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
387 echo $OUTPUT->fatal_error($info->message
, $info->moreinfourl
, $info->link
, $info->backtrace
, $info->debuginfo
,
389 } catch (Exception
$e) {
391 } catch (Throwable
$e) {
392 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
396 if (isset($out_ex)) {
397 // default exception handler MUST not throw any exceptions!!
398 // 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
399 // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
400 if (CLI_SCRIPT
or AJAX_SCRIPT
) {
401 // just ignore the error and send something back using the safest method
402 echo bootstrap_renderer
::early_error($info->message
, $info->moreinfourl
, $info->link
, $info->backtrace
, $info->debuginfo
, $info->errorcode
);
404 echo bootstrap_renderer
::early_error_content($info->message
, $info->moreinfourl
, $info->link
, $info->backtrace
, $info->debuginfo
);
405 $outinfo = get_exception_info($out_ex);
406 echo bootstrap_renderer
::early_error_content($outinfo->message
, $outinfo->moreinfourl
, $outinfo->link
, $outinfo->backtrace
, $outinfo->debuginfo
);
411 exit(1); // General error code
415 * Default error handler, prevents some white screens.
417 * @param string $errstr
418 * @param string $errfile
419 * @param int $errline
420 * @param array $errcontext
421 * @return bool false means use default error handler
423 function default_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
424 if ($errno == 4096) {
425 //fatal catchable error
426 throw new coding_exception('PHP catchable fatal error', $errstr);
432 * Unconditionally abort all database transactions, this function
433 * should be called from exception handlers only.
436 function abort_all_db_transactions() {
437 global $CFG, $DB, $SCRIPT;
439 // default exception handler MUST not throw any exceptions!!
441 if ($DB && $DB->is_transaction_started()) {
442 error_log('Database transaction aborted automatically in ' . $CFG->dirroot
. $SCRIPT);
443 // note: transaction blocks should never change current $_SESSION
444 $DB->force_transaction_rollback();
449 * This function encapsulates the tests for whether an exception was thrown in
450 * early init -- either during setup.php or during init of $OUTPUT.
452 * If another exception is thrown then, and if we do not take special measures,
453 * we would just get a very cryptic message "Exception thrown without a stack
454 * frame in Unknown on line 0". That makes debugging very hard, so we do take
455 * special measures in default_exception_handler, with the help of this function.
457 * @param array $backtrace the stack trace to analyse.
458 * @return boolean whether the stack trace is somewhere in output initialisation.
460 function is_early_init($backtrace) {
461 $dangerouscode = array(
462 array('function' => 'header', 'type' => '->'),
463 array('class' => 'bootstrap_renderer'),
464 array('file' => __DIR__
.'/setup.php'),
466 foreach ($backtrace as $stackframe) {
467 foreach ($dangerouscode as $pattern) {
469 foreach ($pattern as $property => $value) {
470 if (!isset($stackframe[$property]) ||
$stackframe[$property] != $value) {
483 * Abort execution by throwing of a general exception,
484 * default exception handler displays the error message in most cases.
486 * @param string $errorcode The name of the language string containing the error message.
487 * Normally this should be in the error.php lang file.
488 * @param string $module The language file to get the error message from.
489 * @param string $link The url where the user will be prompted to continue.
490 * If no url is provided the user will be directed to the site index page.
491 * @param object $a Extra words and phrases that might be required in the error string
492 * @param string $debuginfo optional debugging information
493 * @return void, always throws exception!
495 function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
496 throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
500 * Returns detailed information about specified exception.
501 * @param exception $ex
504 function get_exception_info($ex) {
505 global $CFG, $DB, $SESSION;
507 if ($ex instanceof moodle_exception
) {
508 $errorcode = $ex->errorcode
;
509 $module = $ex->module
;
512 $debuginfo = $ex->debuginfo
;
514 $errorcode = 'generalexceptionmessage';
516 $a = $ex->getMessage();
521 // Append the error code to the debug info to make grepping and googling easier
522 $debuginfo .= PHP_EOL
."Error code: $errorcode";
524 $backtrace = $ex->getTrace();
525 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
526 array_unshift($backtrace, $place);
528 // Be careful, no guarantee moodlelib.php is loaded.
529 if (empty($module) ||
$module == 'moodle' ||
$module == 'core') {
532 // Search for the $errorcode's associated string
533 // If not found, append the contents of $a to $debuginfo so helpful information isn't lost
534 if (function_exists('get_string_manager')) {
535 if (get_string_manager()->string_exists($errorcode, $module)) {
536 $message = get_string($errorcode, $module, $a);
537 } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
538 // Search in moodle file if error specified - needed for backwards compatibility
539 $message = get_string($errorcode, 'moodle', $a);
541 $message = $module . '/' . $errorcode;
542 $debuginfo .= PHP_EOL
.'$a contents: '.print_r($a, true);
545 $message = $module . '/' . $errorcode;
546 $debuginfo .= PHP_EOL
.'$a contents: '.print_r($a, true);
549 // Remove some absolute paths from message and debugging info.
552 $cfgnames = array('tempdir', 'cachedir', 'localcachedir', 'themedir', 'dataroot', 'dirroot');
553 foreach ($cfgnames as $cfgname) {
554 if (property_exists($CFG, $cfgname)) {
555 $searches[] = $CFG->$cfgname;
556 $replaces[] = "[$cfgname]";
559 if (!empty($searches)) {
560 $message = str_replace($searches, $replaces, $message);
561 $debuginfo = str_replace($searches, $replaces, $debuginfo);
564 // Be careful, no guarantee weblib.php is loaded.
565 if (function_exists('clean_text')) {
566 $message = clean_text($message);
568 $message = htmlspecialchars($message);
571 if (!empty($CFG->errordocroot
)) {
572 $errordoclink = $CFG->errordocroot
. '/en/';
574 $errordoclink = get_docs_url();
577 if ($module === 'error') {
578 $modulelink = 'moodle';
580 $modulelink = $module;
582 $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
585 if (!empty($SESSION->fromurl
)) {
586 $link = $SESSION->fromurl
;
587 unset($SESSION->fromurl
);
589 $link = $CFG->wwwroot
.'/';
593 // When printing an error the continue button should never link offsite.
594 // We cannot use clean_param() here as it is not guaranteed that it has been loaded yet.
595 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot
);
596 if (stripos($link, $CFG->wwwroot
) === 0) {
597 // Internal HTTP, all good.
598 } else if (!empty($CFG->loginhttps
) && stripos($link, $httpswwwroot) === 0) {
599 // Internal HTTPS, 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;
620 * Unique is hard. Very hard. Attempt to use the PECL UUID functions 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 * @return string The uuid.
628 function generate_uuid() {
631 if (function_exists("uuid_create")) {
633 uuid_create($context);
635 uuid_make($context, UUID_MAKE_V4
);
636 uuid_export($context, UUID_FMT_STR
, $uuid);
638 // Fallback uuid generation based on:
639 // "http://www.php.net/manual/en/function.uniqid.php#94959".
640 $uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
642 // 32 bits for "time_low".
643 mt_rand(0, 0xffff), mt_rand(0, 0xffff),
645 // 16 bits for "time_mid".
648 // 16 bits for "time_hi_and_version",
649 // four most significant bits holds version number 4.
650 mt_rand(0, 0x0fff) |
0x4000,
652 // 16 bits, 8 bits for "clk_seq_hi_res",
653 // 8 bits for "clk_seq_low",
654 // two most significant bits holds zero and one for variant DCE1.1.
655 mt_rand(0, 0x3fff) |
0x8000,
657 // 48 bits for "node".
658 mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
664 * Returns the Moodle Docs URL in the users language for a given 'More help' link.
666 * There are three cases:
668 * 1. In the normal case, $path will be a short relative path 'component/thing',
669 * like 'mod/folder/view' 'group/import'. This gets turned into an link to
670 * MoodleDocs in the user's language, and for the appropriate Moodle version.
671 * E.g. 'group/import' may become 'http://docs.moodle.org/2x/en/group/import'.
672 * The 'http://docs.moodle.org' bit comes from $CFG->docroot.
674 * This is the only option that should be used in standard Moodle code. The other
675 * two options have been implemented because they are useful for third-party plugins.
677 * 2. $path may be an absolute URL, starting http:// or https://. In this case,
678 * the link is used as is.
680 * 3. $path may start %%WWWROOT%%, in which case that is replaced by
681 * $CFG->wwwroot to make the link.
683 * @param string $path the place to link to. See above for details.
684 * @return string The MoodleDocs URL in the user's language. for example @link http://docs.moodle.org/2x/en/$path}
686 function get_docs_url($path = null) {
689 // Absolute URLs are used unmodified.
690 if (substr($path, 0, 7) === 'http://' ||
substr($path, 0, 8) === 'https://') {
694 // Paths starting %%WWWROOT%% have that replaced by $CFG->wwwroot.
695 if (substr($path, 0, 11) === '%%WWWROOT%%') {
696 return $CFG->wwwroot
. substr($path, 11);
699 // Otherwise we do the normal case, and construct a MoodleDocs URL relative to $CFG->docroot.
701 // Check that $CFG->branch has been set up, during installation it won't be.
702 if (empty($CFG->branch
)) {
703 // It's not there yet so look at version.php.
704 include($CFG->dirroot
.'/version.php');
706 // We can use $CFG->branch and avoid having to include version.php.
707 $branch = $CFG->branch
;
709 // ensure branch is valid.
711 // We should never get here but in case we do lets set $branch to .
712 // the smart one's will know that this is the current directory
713 // and the smarter ones will know that there is some smart matching
714 // that will ensure people end up at the latest version of the docs.
717 if (empty($CFG->doclang
)) {
718 $lang = current_language();
720 $lang = $CFG->doclang
;
722 $end = '/' . $branch . '/' . $lang . '/' . $path;
723 if (empty($CFG->docroot
)) {
724 return 'http://docs.moodle.org'. $end;
726 return $CFG->docroot
. $end ;
731 * Formats a backtrace ready for output.
733 * @param array $callers backtrace array, as returned by debug_backtrace().
734 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
735 * @return string formatted backtrace, ready for output.
737 function format_backtrace($callers, $plaintext = false) {
738 // do not use $CFG->dirroot because it might not be available in destructors
739 $dirroot = dirname(__DIR__
);
741 if (empty($callers)) {
745 $from = $plaintext ?
'' : '<ul style="text-align: left" data-rel="backtrace">';
746 foreach ($callers as $caller) {
747 if (!isset($caller['line'])) {
748 $caller['line'] = '?'; // probably call_user_func()
750 if (!isset($caller['file'])) {
751 $caller['file'] = 'unknownfile'; // probably call_user_func()
753 $from .= $plaintext ?
'* ' : '<li>';
754 $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
755 if (isset($caller['function'])) {
756 $from .= ': call to ';
757 if (isset($caller['class'])) {
758 $from .= $caller['class'] . $caller['type'];
760 $from .= $caller['function'] . '()';
761 } else if (isset($caller['exception'])) {
762 $from .= ': '.$caller['exception'].' thrown';
764 $from .= $plaintext ?
"\n" : '</li>';
766 $from .= $plaintext ?
'' : '</ul>';
772 * This function makes the return value of ini_get consistent if you are
773 * setting server directives through the .htaccess file in apache.
775 * Current behavior for value set from php.ini On = 1, Off = [blank]
776 * Current behavior for value set from .htaccess On = On, Off = Off
777 * Contributed by jdell @ unr.edu
779 * @param string $ini_get_arg The argument to get
780 * @return bool True for on false for not
782 function ini_get_bool($ini_get_arg) {
783 $temp = ini_get($ini_get_arg);
785 if ($temp == '1' or strtolower($temp) == 'on') {
792 * This function verifies the sanity of PHP configuration
793 * and stops execution if anything critical found.
795 function setup_validate_php_configuration() {
796 // this must be very fast - no slow checks here!!!
798 if (ini_get_bool('session.auto_start')) {
799 print_error('sessionautostartwarning', 'admin');
804 * Initialise global $CFG variable.
805 * @private to be used only from lib/setup.php
807 function initialise_cfg() {
811 // This should not happen.
816 $localcfg = get_config('core');
817 } catch (dml_exception
$e) {
818 // Most probably empty db, going to install soon.
822 foreach ($localcfg as $name => $value) {
823 // Note that get_config() keeps forced settings
824 // and normalises values to string if possible.
825 $CFG->{$name} = $value;
830 * Initialises $FULLME and friends. Private function. Should only be called from
833 function initialise_fullme() {
834 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
836 // Detect common config error.
837 if (substr($CFG->wwwroot
, -1) == '/') {
838 print_error('wwwrootslash', 'error');
842 initialise_fullme_cli();
846 $rurl = setup_get_remote_url();
847 $wwwroot = parse_url($CFG->wwwroot
.'/');
849 if (empty($rurl['host'])) {
850 // missing host in request header, probably not a real browser, let's ignore them
852 } else if (!empty($CFG->reverseproxy
)) {
853 // $CFG->reverseproxy specifies if reverse proxy server used
854 // Used in load balancing scenarios.
855 // Do not abuse this to try to solve lan/wan access problems!!!!!
858 if (($rurl['host'] !== $wwwroot['host']) or
859 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port']) or
860 (strpos($rurl['path'], $wwwroot['path']) !== 0)) {
862 // Explain the problem and redirect them to the right URL
863 if (!defined('NO_MOODLE_COOKIES')) {
864 define('NO_MOODLE_COOKIES', true);
866 // The login/token.php script should call the correct url/port.
867 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS
) {
868 $wwwrootport = empty($wwwroot['port'])?
'':$wwwroot['port'];
869 $calledurl = $rurl['host'];
870 if (!empty($rurl['port'])) {
871 $calledurl .= ':'. $rurl['port'];
873 $correcturl = $wwwroot['host'];
874 if (!empty($wwwrootport)) {
875 $correcturl .= ':'. $wwwrootport;
877 throw new moodle_exception('requirecorrectaccess', 'error', '', null,
878 'You called ' . $calledurl .', you should have called ' . $correcturl);
880 redirect($CFG->wwwroot
, get_string('wwwrootmismatch', 'error', $CFG->wwwroot
), 3);
884 // Check that URL is under $CFG->wwwroot.
885 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
886 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
888 // Probably some weird external script
889 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
893 // $CFG->sslproxy specifies if external SSL appliance is used
894 // (That is, the Moodle server uses http, with an external box translating everything to https).
895 if (empty($CFG->sslproxy
)) {
896 if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
897 print_error('sslonlyaccess', 'error');
900 if ($wwwroot['scheme'] !== 'https') {
901 throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
903 $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
904 $_SERVER['HTTPS'] = 'on'; // Override $_SERVER to help external libraries with their HTTPS detection.
905 $_SERVER['SERVER_PORT'] = 443; // Assume default ssl port for the proxy.
908 // hopefully this will stop all those "clever" admins trying to set up moodle
909 // with two different addresses in intranet and Internet
910 if (!empty($CFG->reverseproxy
) && $rurl['host'] === $wwwroot['host']) {
911 print_error('reverseproxyabused', 'error');
914 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
915 if (!empty($wwwroot['port'])) {
916 $hostandport .= ':'.$wwwroot['port'];
919 $FULLSCRIPT = $hostandport . $rurl['path'];
920 $FULLME = $hostandport . $rurl['fullpath'];
921 $ME = $rurl['fullpath'];
925 * Initialises $FULLME and friends for command line scripts.
926 * This is a private method for use by initialise_fullme.
928 function initialise_fullme_cli() {
929 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
931 // Urls do not make much sense in CLI scripts
932 $backtrace = debug_backtrace();
933 $topfile = array_pop($backtrace);
934 $topfile = realpath($topfile['file']);
935 $dirroot = realpath($CFG->dirroot
);
937 if (strpos($topfile, $dirroot) !== 0) {
938 // Probably some weird external script
939 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
941 $relativefile = substr($topfile, strlen($dirroot));
942 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
943 $SCRIPT = $FULLSCRIPT = $relativefile;
944 $FULLME = $ME = null;
949 * Get the URL that PHP/the web server thinks it is serving. Private function
950 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
951 * @return array in the same format that parse_url returns, with the addition of
952 * a 'fullpath' element, which includes any slasharguments path.
954 function setup_get_remote_url() {
956 if (isset($_SERVER['HTTP_HOST'])) {
957 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
959 $rurl['host'] = null;
961 $rurl['port'] = $_SERVER['SERVER_PORT'];
962 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
963 $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ?
'http' : 'https';
965 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
967 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
969 // Fixing a known issue with:
970 // - Apache versions lesser than 2.4.11
971 // - PHP deployed in Apache as PHP-FPM via mod_proxy_fcgi
972 // - PHP versions lesser than 5.6.3 and 5.5.18.
973 if (isset($_SERVER['PATH_INFO']) && (php_sapi_name() === 'fpm-fcgi') && isset($_SERVER['SCRIPT_NAME'])) {
974 $pathinfodec = rawurldecode($_SERVER['PATH_INFO']);
975 $lenneedle = strlen($pathinfodec);
976 // Checks whether SCRIPT_NAME ends with PATH_INFO, URL-decoded.
977 if (substr($_SERVER['SCRIPT_NAME'], -$lenneedle) === $pathinfodec) {
978 // This is the "Apache 2.4.10- running PHP-FPM via mod_proxy_fcgi" fingerprint,
979 // 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)
980 // => SCRIPT_NAME contains 'slash arguments' data too, which is wrongly exposed via PATH_INFO as URL-encoded.
981 // Fix both $_SERVER['PATH_INFO'] and $_SERVER['SCRIPT_NAME'].
982 $lenhaystack = strlen($_SERVER['SCRIPT_NAME']);
983 $pos = $lenhaystack - $lenneedle;
984 // Here $pos is greater than 0 but let's double check it.
986 $_SERVER['PATH_INFO'] = $pathinfodec;
987 $_SERVER['SCRIPT_NAME'] = substr($_SERVER['SCRIPT_NAME'], 0, $pos);
992 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
993 //IIS - needs a lot of tweaking to make it work
994 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
996 // NOTE: we should ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS.
997 // Since 2.0, we rely on IIS rewrite extensions like Helicon ISAPI_rewrite
998 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
1000 // we rely on a proper IIS 6.0+ configuration: the 'FastCGIUtf8ServerVariables' registry key.
1001 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
1002 // Check that PATH_INFO works == must not contain the script name.
1003 if (strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === false) {
1004 $rurl['fullpath'] .= clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH
);
1008 if (isset($_SERVER['QUERY_STRING']) and $_SERVER['QUERY_STRING'] !== '') {
1009 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
1011 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
1013 /* NOTE: following servers are not fully tested! */
1015 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
1016 //lighttpd - not officially supported
1017 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1019 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
1020 //nginx - not officially supported
1021 if (!isset($_SERVER['SCRIPT_NAME'])) {
1022 die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
1024 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1026 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
1027 //cherokee - not officially supported
1028 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1030 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
1031 //zeus - not officially supported
1032 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1034 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
1035 //LiteSpeed - not officially supported
1036 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1038 } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
1039 //obscure name found on some servers - this is definitely not supported
1040 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1042 } else if (strpos($_SERVER['SERVER_SOFTWARE'], 'PHP') === 0) {
1043 // built-in PHP Development Server
1044 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
1047 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
1050 // sanitize the url a bit more, the encoding style may be different in vars above
1051 $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
1052 $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);
1058 * Try to work around the 'max_input_vars' restriction if necessary.
1060 function workaround_max_input_vars() {
1061 // Make sure this gets executed only once from lib/setup.php!
1062 static $executed = false;
1064 debugging('workaround_max_input_vars() must be called only once!');
1069 if (!isset($_SERVER["CONTENT_TYPE"]) or strpos($_SERVER["CONTENT_TYPE"], 'multipart/form-data') !== false) {
1070 // Not a post or 'multipart/form-data' which is not compatible with "php://input" reading.
1074 if (!isloggedin() or isguestuser()) {
1075 // Only real users post huge forms.
1079 $max = (int)ini_get('max_input_vars');
1082 // Most probably PHP < 5.3.9 that does not implement this limit.
1086 if ($max >= 200000) {
1087 // This value should be ok for all our forms, by setting it in php.ini
1088 // admins may prevent any unexpected regressions caused by this hack.
1090 // Note there is no need to worry about DDoS caused by making this limit very high
1091 // because there are very many easier ways to DDoS any Moodle server.
1095 // Worst case is advanced checkboxes which use up to two max_input_vars
1096 // slots for each entry in $_POST, because of sending two fields with the
1097 // same name. So count everything twice just in case.
1098 if (count($_POST, COUNT_RECURSIVE
) * 2 < $max) {
1102 // Large POST request with enctype supported by php://input.
1103 // Parse php://input in chunks to bypass max_input_vars limit, which also applies to parse_str().
1104 $str = file_get_contents("php://input");
1105 if ($str === false or $str === '') {
1106 // Some weird error.
1111 $fun = create_function('$p', 'return implode("'.$delim.'", $p);');
1112 $chunks = array_map($fun, array_chunk(explode($delim, $str), $max));
1114 // Clear everything from existing $_POST array, otherwise it might be included
1115 // twice (this affects array params primarily).
1116 foreach ($_POST as $key => $value) {
1117 unset($_POST[$key]);
1118 // Also clear from request array - but only the things that are in $_POST,
1119 // that way it will leave the things from a get request if any.
1120 unset($_REQUEST[$key]);
1123 foreach ($chunks as $chunk) {
1125 parse_str($chunk, $values);
1127 merge_query_params($_POST, $values);
1128 merge_query_params($_REQUEST, $values);
1133 * Merge parsed POST chunks.
1135 * NOTE: this is not perfect, but it should work in most cases hopefully.
1137 * @param array $target
1138 * @param array $values
1140 function merge_query_params(array &$target, array $values) {
1141 if (isset($values[0]) and isset($target[0])) {
1142 // This looks like a split [] array, lets verify the keys are continuous starting with 0.
1143 $keys1 = array_keys($values);
1144 $keys2 = array_keys($target);
1145 if ($keys1 === array_keys($keys1) and $keys2 === array_keys($keys2)) {
1146 foreach ($values as $v) {
1152 foreach ($values as $k => $v) {
1153 if (!isset($target[$k])) {
1157 if (is_array($target[$k]) and is_array($v)) {
1158 merge_query_params($target[$k], $v);
1161 // We should not get here unless there are duplicates in params.
1167 * Initializes our performance info early.
1169 * Pairs up with get_performance_info() which is actually
1170 * in moodlelib.php. This function is here so that we can
1171 * call it before all the libs are pulled in.
1175 function init_performance_info() {
1177 global $PERF, $CFG, $USER;
1179 $PERF = new stdClass();
1180 $PERF->logwrites
= 0;
1181 if (function_exists('microtime')) {
1182 $PERF->starttime
= microtime();
1184 if (function_exists('memory_get_usage')) {
1185 $PERF->startmemory
= memory_get_usage();
1187 if (function_exists('posix_times')) {
1188 $PERF->startposixtimes
= posix_times();
1193 * Indicates whether we are in the middle of the initial Moodle install.
1195 * Very occasionally it is necessary avoid running certain bits of code before the
1196 * Moodle installation has completed. The installed flag is set in admin/index.php
1197 * after Moodle core and all the plugins have been installed, but just before
1198 * the person doing the initial install is asked to choose the admin password.
1200 * @return boolean true if the initial install is not complete.
1202 function during_initial_install() {
1204 return empty($CFG->rolesactive
);
1208 * Function to raise the memory limit to a new value.
1209 * Will respect the memory limit if it is higher, thus allowing
1210 * settings in php.ini, apache conf or command line switches
1213 * The memory limit should be expressed with a constant
1214 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
1215 * It is possible to use strings or integers too (eg:'128M').
1217 * @param mixed $newlimit the new memory limit
1218 * @return bool success
1220 function raise_memory_limit($newlimit) {
1223 if ($newlimit == MEMORY_UNLIMITED
) {
1224 ini_set('memory_limit', -1);
1227 } else if ($newlimit == MEMORY_STANDARD
) {
1228 if (PHP_INT_SIZE
> 4) {
1229 $newlimit = get_real_size('128M'); // 64bit needs more memory
1231 $newlimit = get_real_size('96M');
1234 } else if ($newlimit == MEMORY_EXTRA
) {
1235 if (PHP_INT_SIZE
> 4) {
1236 $newlimit = get_real_size('384M'); // 64bit needs more memory
1238 $newlimit = get_real_size('256M');
1240 if (!empty($CFG->extramemorylimit
)) {
1241 $extra = get_real_size($CFG->extramemorylimit
);
1242 if ($extra > $newlimit) {
1247 } else if ($newlimit == MEMORY_HUGE
) {
1248 // MEMORY_HUGE uses 2G or MEMORY_EXTRA, whichever is bigger.
1249 $newlimit = get_real_size('2G');
1250 if (!empty($CFG->extramemorylimit
)) {
1251 $extra = get_real_size($CFG->extramemorylimit
);
1252 if ($extra > $newlimit) {
1258 $newlimit = get_real_size($newlimit);
1261 if ($newlimit <= 0) {
1262 debugging('Invalid memory limit specified.');
1266 $cur = ini_get('memory_limit');
1268 // if php is compiled without --enable-memory-limits
1269 // apparently memory_limit is set to ''
1273 return true; // unlimited mem!
1275 $cur = get_real_size($cur);
1278 if ($newlimit > $cur) {
1279 ini_set('memory_limit', $newlimit);
1286 * Function to reduce the memory limit to a new value.
1287 * Will respect the memory limit if it is lower, thus allowing
1288 * settings in php.ini, apache conf or command line switches
1291 * The memory limit should be expressed with a string (eg:'64M')
1293 * @param string $newlimit the new memory limit
1296 function reduce_memory_limit($newlimit) {
1297 if (empty($newlimit)) {
1300 $cur = ini_get('memory_limit');
1302 // if php is compiled without --enable-memory-limits
1303 // apparently memory_limit is set to ''
1307 return true; // unlimited mem!
1309 $cur = get_real_size($cur);
1312 $new = get_real_size($newlimit);
1313 // -1 is smaller, but it means unlimited
1314 if ($new < $cur && $new != -1) {
1315 ini_set('memory_limit', $newlimit);
1322 * Converts numbers like 10M into bytes.
1324 * @param string $size The size to be converted
1327 function get_real_size($size = 0) {
1332 static $binaryprefixes = array(
1339 'T' => 1099511627776,
1340 't' => 1099511627776,
1343 if (preg_match('/^([0-9]+)([KMGT])/i', $size, $matches)) {
1344 return $matches[1] * $binaryprefixes[$matches[2]];
1351 * Try to disable all output buffering and purge
1354 * @access private to be called only from lib/setup.php !
1357 function disable_output_buffering() {
1358 $olddebug = error_reporting(0);
1360 // disable compression, it would prevent closing of buffers
1361 if (ini_get_bool('zlib.output_compression')) {
1362 ini_set('zlib.output_compression', 'Off');
1365 // try to flush everything all the time
1366 ob_implicit_flush(true);
1368 // close all buffers if possible and discard any existing output
1369 // this can actually work around some whitespace problems in config.php
1370 while(ob_get_level()) {
1371 if (!ob_end_clean()) {
1372 // prevent infinite loop when buffer can not be closed
1377 // disable any other output handlers
1378 ini_set('output_handler', '');
1380 error_reporting($olddebug);
1384 * Check whether a major upgrade is needed. That is defined as an upgrade that
1385 * changes something really fundamental in the database, so nothing can possibly
1386 * work until the database has been updated, and that is defined by the hard-coded
1387 * version number in this function.
1389 function redirect_if_major_upgrade_required() {
1391 $lastmajordbchanges = 2016100501.00;
1392 if (empty($CFG->version
) or (float)$CFG->version
< $lastmajordbchanges or
1393 during_initial_install() or !empty($CFG->adminsetuppending
)) {
1395 @\core\session\manager
::terminate_current();
1396 } catch (Exception
$e) {
1397 // Ignore any errors, redirect to upgrade anyway.
1399 $url = $CFG->wwwroot
. '/' . $CFG->admin
. '/index.php';
1400 @header
($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1401 @header
('Location: ' . $url);
1402 echo bootstrap_renderer
::plain_redirect_message(htmlspecialchars($url));
1408 * Makes sure that upgrade process is not running
1410 * To be inserted in the core functions that can not be called by pluigns during upgrade.
1411 * Core upgrade should not use any API functions at all.
1412 * See {@link http://docs.moodle.org/dev/Upgrade_API#Upgrade_code_restrictions}
1414 * @throws moodle_exception if executed from inside of upgrade script and $warningonly is false
1415 * @param bool $warningonly if true displays a warning instead of throwing an exception
1416 * @return bool true if executed from outside of upgrade process, false if from inside upgrade process and function is used for warning only
1418 function upgrade_ensure_not_running($warningonly = false) {
1420 if (!empty($CFG->upgraderunning
)) {
1421 if (!$warningonly) {
1422 throw new moodle_exception('cannotexecduringupgrade');
1424 debugging(get_string('cannotexecduringupgrade', 'error'), DEBUG_DEVELOPER
);
1432 * Function to check if a directory exists and by default create it if not exists.
1434 * Previously this was accepting paths only from dataroot, but we now allow
1435 * files outside of dataroot if you supply custom paths for some settings in config.php.
1436 * This function does not verify that the directory is writable.
1438 * NOTE: this function uses current file stat cache,
1439 * please use clearstatcache() before this if you expect that the
1440 * directories may have been removed recently from a different request.
1442 * @param string $dir absolute directory path
1443 * @param boolean $create directory if does not exist
1444 * @param boolean $recursive create directory recursively
1445 * @return boolean true if directory exists or created, false otherwise
1447 function check_dir_exists($dir, $create = true, $recursive = true) {
1450 umask($CFG->umaskpermissions
);
1460 return mkdir($dir, $CFG->directorypermissions
, $recursive);
1464 * Create a new unique directory within the specified directory.
1466 * @param string $basedir The directory to create your new unique directory within.
1467 * @param bool $exceptiononerror throw exception if error encountered
1468 * @return string The created directory
1469 * @throws invalid_dataroot_permissions
1471 function make_unique_writable_directory($basedir, $exceptiononerror = true) {
1472 if (!is_dir($basedir) ||
!is_writable($basedir)) {
1473 // The basedir is not writable. We will not be able to create the child directory.
1474 if ($exceptiononerror) {
1475 throw new invalid_dataroot_permissions($basedir . ' is not writable. Unable to create a unique directory within it.');
1482 // Generate a new (hopefully unique) directory name.
1483 $uniquedir = $basedir . DIRECTORY_SEPARATOR
. generate_uuid();
1485 // Ensure that basedir is still writable - if we do not check, we could get stuck in a loop here.
1486 is_writable($basedir) &&
1488 // Make the new unique directory. If the directory already exists, it will return false.
1489 !make_writable_directory($uniquedir, $exceptiononerror) &&
1491 // Ensure that the directory now exists
1492 file_exists($uniquedir) && is_dir($uniquedir)
1495 // Check that the directory was correctly created.
1496 if (!file_exists($uniquedir) ||
!is_dir($uniquedir) ||
!is_writable($uniquedir)) {
1497 if ($exceptiononerror) {
1498 throw new invalid_dataroot_permissions('Unique directory creation failed.');
1508 * Create a directory and make sure it is writable.
1511 * @param string $dir the full path of the directory to be created
1512 * @param bool $exceptiononerror throw exception if error encountered
1513 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1515 function make_writable_directory($dir, $exceptiononerror = true) {
1518 if (file_exists($dir) and !is_dir($dir)) {
1519 if ($exceptiononerror) {
1520 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1526 umask($CFG->umaskpermissions
);
1528 if (!file_exists($dir)) {
1529 if (!@mkdir
($dir, $CFG->directorypermissions
, true)) {
1531 // There might be a race condition when creating directory.
1532 if (!is_dir($dir)) {
1533 if ($exceptiononerror) {
1534 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1536 debugging('Can not create directory: '.$dir, DEBUG_DEVELOPER
);
1543 if (!is_writable($dir)) {
1544 if ($exceptiononerror) {
1545 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1555 * Protect a directory from web access.
1556 * Could be extended in the future to support other mechanisms (e.g. other webservers).
1559 * @param string $dir the full path of the directory to be protected
1561 function protect_directory($dir) {
1563 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1564 if (!file_exists("$dir/.htaccess")) {
1565 if ($handle = fopen("$dir/.htaccess", 'w')) { // For safety
1566 @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");
1568 @chmod
("$dir/.htaccess", $CFG->filepermissions
);
1574 * Create a directory under dataroot and make sure it is writable.
1575 * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
1577 * @param string $directory the full path of the directory to be created under $CFG->dataroot
1578 * @param bool $exceptiononerror throw exception if error encountered
1579 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1581 function make_upload_directory($directory, $exceptiononerror = true) {
1584 if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1585 debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1587 } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
1588 debugging('Use make_cache_directory() for creation of cache directory and $CFG->cachedir to get the location.');
1590 } else if (strpos($directory, 'localcache/') === 0 or $directory === 'localcache') {
1591 debugging('Use make_localcache_directory() for creation of local cache directory and $CFG->localcachedir to get the location.');
1594 protect_directory($CFG->dataroot
);
1595 return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1599 * Get a per-request storage directory in the tempdir.
1601 * The directory is automatically cleaned up during the shutdown handler.
1603 * @param bool $exceptiononerror throw exception if error encountered
1604 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1606 function get_request_storage_directory($exceptiononerror = true) {
1609 static $requestdir = null;
1611 if (!$requestdir ||
!file_exists($requestdir) ||
!is_dir($requestdir) ||
!is_writable($requestdir)) {
1612 if ($CFG->localcachedir
!== "$CFG->dataroot/localcache") {
1613 check_dir_exists($CFG->localcachedir
, true, true);
1614 protect_directory($CFG->localcachedir
);
1616 protect_directory($CFG->dataroot
);
1619 if ($requestdir = make_unique_writable_directory($CFG->localcachedir
, $exceptiononerror)) {
1620 // Register a shutdown handler to remove the directory.
1621 \core_shutdown_manager
::register_function('remove_dir', array($requestdir));
1629 * Create a per-request directory and make sure it is writable.
1630 * This can only be used during the current request and will be tidied away
1631 * automatically afterwards.
1633 * A new, unique directory is always created within the current request directory.
1635 * @param bool $exceptiononerror throw exception if error encountered
1636 * @return string full path to directory if successful, false if not; may throw exception
1638 function make_request_directory($exceptiononerror = true) {
1639 $basedir = get_request_storage_directory($exceptiononerror);
1640 return make_unique_writable_directory($basedir, $exceptiononerror);
1644 * Create a directory under tempdir and make sure it is writable.
1646 * Where possible, please use make_request_directory() and limit the scope
1647 * of your data to the current HTTP request.
1649 * Do not use for storing cache files - see make_cache_directory(), and
1650 * make_localcache_directory() instead for this purpose.
1652 * Temporary files must be on a shared storage, and heavy usage is
1653 * discouraged due to the performance impact upon clustered environments.
1655 * @param string $directory the full path of the directory to be created under $CFG->tempdir
1656 * @param bool $exceptiononerror throw exception if error encountered
1657 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1659 function make_temp_directory($directory, $exceptiononerror = true) {
1661 if ($CFG->tempdir
!== "$CFG->dataroot/temp") {
1662 check_dir_exists($CFG->tempdir
, true, true);
1663 protect_directory($CFG->tempdir
);
1665 protect_directory($CFG->dataroot
);
1667 return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1671 * Create a directory under cachedir and make sure it is writable.
1673 * Note: this cache directory is shared by all cluster nodes.
1675 * @param string $directory the full path of the directory to be created under $CFG->cachedir
1676 * @param bool $exceptiononerror throw exception if error encountered
1677 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1679 function make_cache_directory($directory, $exceptiononerror = true) {
1681 if ($CFG->cachedir
!== "$CFG->dataroot/cache") {
1682 check_dir_exists($CFG->cachedir
, true, true);
1683 protect_directory($CFG->cachedir
);
1685 protect_directory($CFG->dataroot
);
1687 return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1691 * Create a directory under localcachedir and make sure it is writable.
1692 * The files in this directory MUST NOT change, use revisions or content hashes to
1693 * work around this limitation - this means you can only add new files here.
1695 * The content of this directory gets purged automatically on all cluster nodes
1696 * after calling purge_all_caches() before new data is written to this directory.
1698 * Note: this local cache directory does not need to be shared by cluster nodes.
1700 * @param string $directory the relative path of the directory to be created under $CFG->localcachedir
1701 * @param bool $exceptiononerror throw exception if error encountered
1702 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1704 function make_localcache_directory($directory, $exceptiononerror = true) {
1707 make_writable_directory($CFG->localcachedir
, $exceptiononerror);
1709 if ($CFG->localcachedir
!== "$CFG->dataroot/localcache") {
1710 protect_directory($CFG->localcachedir
);
1712 protect_directory($CFG->dataroot
);
1715 if (!isset($CFG->localcachedirpurged
)) {
1716 $CFG->localcachedirpurged
= 0;
1718 $timestampfile = "$CFG->localcachedir/.lastpurged";
1720 if (!file_exists($timestampfile)) {
1721 touch($timestampfile);
1722 @chmod
($timestampfile, $CFG->filepermissions
);
1724 } else if (filemtime($timestampfile) < $CFG->localcachedirpurged
) {
1725 // This means our local cached dir was not purged yet.
1726 remove_dir($CFG->localcachedir
, true);
1727 if ($CFG->localcachedir
!== "$CFG->dataroot/localcache") {
1728 protect_directory($CFG->localcachedir
);
1730 touch($timestampfile);
1731 @chmod
($timestampfile, $CFG->filepermissions
);
1735 if ($directory === '') {
1736 return $CFG->localcachedir
;
1739 return make_writable_directory("$CFG->localcachedir/$directory", $exceptiononerror);
1743 * This class solves the problem of how to initialise $OUTPUT.
1745 * The problem is caused be two factors
1747 * <li>On the one hand, we cannot be sure when output will start. In particular,
1748 * an error, which needs to be displayed, could be thrown at any time.</li>
1749 * <li>On the other hand, we cannot be sure when we will have all the information
1750 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1751 * (potentially) depends on the current course, course categories, and logged in user.
1752 * It also depends on whether the current page requires HTTPS.</li>
1755 * So, it is hard to find a single natural place during Moodle script execution,
1756 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1757 * adopt the following strategy
1759 * <li>We will initialise $OUTPUT the first time it is used.</li>
1760 * <li>If, after $OUTPUT has been initialised, the script tries to change something
1761 * that $OUTPUT depends on, we throw an exception making it clear that the script
1762 * did something wrong.
1765 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1766 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1767 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1768 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1770 * Note that this class is used before lib/outputlib.php has been loaded, so we
1771 * must be careful referring to classes/functions from there, they may not be
1772 * defined yet, and we must avoid fatal errors.
1774 * @copyright 2009 Tim Hunt
1775 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1778 class bootstrap_renderer
{
1780 * Handles re-entrancy. Without this, errors or debugging output that occur
1781 * during the initialisation of $OUTPUT, cause infinite recursion.
1784 protected $initialising = false;
1787 * Have we started output yet?
1788 * @return boolean true if the header has been printed.
1790 public function has_started() {
1795 * Constructor - to be used by core code only.
1796 * @param string $method The method to call
1797 * @param array $arguments Arguments to pass to the method being called
1800 public function __call($method, $arguments) {
1801 global $OUTPUT, $PAGE;
1804 if ($method == 'notification') {
1805 // Catch infinite recursion caused by debugging output during print_header.
1806 $backtrace = debug_backtrace();
1807 array_shift($backtrace);
1808 array_shift($backtrace);
1809 $recursing = is_early_init($backtrace);
1812 $earlymethods = array(
1813 'fatal_error' => 'early_error',
1814 'notification' => 'early_notification',
1817 // If lib/outputlib.php has been loaded, call it.
1818 if (!empty($PAGE) && !$recursing) {
1819 if (array_key_exists($method, $earlymethods)) {
1820 //prevent PAGE->context warnings - exceptions might appear before we set any context
1821 $PAGE->set_context(null);
1823 $PAGE->initialise_theme_and_output();
1824 return call_user_func_array(array($OUTPUT, $method), $arguments);
1827 $this->initialising
= true;
1829 // Too soon to initialise $OUTPUT, provide a couple of key methods.
1830 if (array_key_exists($method, $earlymethods)) {
1831 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1834 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1838 * Returns nicely formatted error message in a div box.
1840 * @param string $message error message
1841 * @param string $moreinfourl (ignored in early errors)
1842 * @param string $link (ignored in early errors)
1843 * @param array $backtrace
1844 * @param string $debuginfo
1847 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1850 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1851 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1852 width: 80%; -moz-border-radius: 20px; padding: 15px">
1855 // Check whether debug is set.
1856 $debug = (!empty($CFG->debug
) && $CFG->debug
>= DEBUG_DEVELOPER
);
1857 // Also check we have it set in the config file. This occurs if the method to read the config table from the
1858 // database fails, reading from the config table is the first database interaction we have.
1859 $debug = $debug ||
(!empty($CFG->config_php_settings
['debug']) && $CFG->config_php_settings
['debug'] >= DEBUG_DEVELOPER
);
1861 if (!empty($debuginfo)) {
1862 $debuginfo = s($debuginfo); // removes all nasty JS
1863 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1864 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
1866 if (!empty($backtrace)) {
1867 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1875 * This function should only be called by this class, or from exception handlers
1877 * @param string $message error message
1878 * @param string $moreinfourl (ignored in early errors)
1879 * @param string $link (ignored in early errors)
1880 * @param array $backtrace
1881 * @param string $debuginfo extra information for developers
1884 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = null) {
1888 echo "!!! $message !!!\n";
1889 if (!empty($CFG->debug
) and $CFG->debug
>= DEBUG_DEVELOPER
) {
1890 if (!empty($debuginfo)) {
1891 echo "\nDebug info: $debuginfo";
1893 if (!empty($backtrace)) {
1894 echo "\nStack trace: " . format_backtrace($backtrace, true);
1899 } else if (AJAX_SCRIPT
) {
1900 $e = new stdClass();
1901 $e->error
= $message;
1902 $e->stacktrace
= NULL;
1903 $e->debuginfo
= NULL;
1904 if (!empty($CFG->debug
) and $CFG->debug
>= DEBUG_DEVELOPER
) {
1905 if (!empty($debuginfo)) {
1906 $e->debuginfo
= $debuginfo;
1908 if (!empty($backtrace)) {
1909 $e->stacktrace
= format_backtrace($backtrace, true);
1912 $e->errorcode
= $errorcode;
1913 @header
('Content-Type: application/json; charset=utf-8');
1914 echo json_encode($e);
1918 // In the name of protocol correctness, monitoring and performance
1919 // profiling, set the appropriate error headers for machine consumption.
1920 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ?
$_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
1921 @header
($protocol . ' 503 Service Unavailable');
1923 // better disable any caching
1924 @header
('Content-Type: text/html; charset=utf-8');
1925 @header
('X-UA-Compatible: IE=edge');
1926 @header
('Cache-Control: no-store, no-cache, must-revalidate');
1927 @header
('Cache-Control: post-check=0, pre-check=0', false);
1928 @header
('Pragma: no-cache');
1929 @header
('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1930 @header
('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1932 if (function_exists('get_string')) {
1933 $strerror = get_string('error');
1935 $strerror = 'Error';
1938 $content = self
::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
1940 return self
::plain_page($strerror, $content);
1944 * Early notification message
1946 * @param string $message
1947 * @param string $classes usually notifyproblem or notifysuccess
1950 public static function early_notification($message, $classes = 'notifyproblem') {
1951 return '<div class="' . $classes . '">' . $message . '</div>';
1955 * Page should redirect message.
1957 * @param string $encodedurl redirect url
1960 public static function plain_redirect_message($encodedurl) {
1961 $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
1962 $encodedurl .'">'. get_string('continue') .'</a></div>';
1963 return self
::plain_page(get_string('redirect'), $message);
1967 * Early redirection page, used before full init of $PAGE global
1969 * @param string $encodedurl redirect url
1970 * @param string $message redirect message
1971 * @param int $delay time in seconds
1972 * @return string redirect page
1974 public static function early_redirect_message($encodedurl, $message, $delay) {
1975 $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
1976 $content = self
::early_error_content($message, null, null, null);
1977 $content .= self
::plain_redirect_message($encodedurl);
1979 return self
::plain_page(get_string('redirect'), $content, $meta);
1983 * Output basic html page.
1985 * @param string $title page title
1986 * @param string $content page content
1987 * @param string $meta meta tag
1988 * @return string html page
1990 public static function plain_page($title, $content, $meta = '') {
1991 if (function_exists('get_string') && function_exists('get_html_lang')) {
1992 $htmllang = get_html_lang();
1998 if (MDL_PERF_TEST
) {
1999 $perfinfo = get_performance_info();
2000 $footer = '<footer>' . $perfinfo['html'] . '</footer>';
2003 return '<!DOCTYPE html>
2004 <html ' . $htmllang . '>
2006 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
2008 <title>' . $title . '</title>
2009 </head><body>' . $content . $footer . '</body></html>';