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 * Software maturity levels used by the core and plugins
57 define('MATURITY_ALPHA', 50); // internals can be tested using white box techniques
58 define('MATURITY_BETA', 100); // feature complete, ready for preview and testing
59 define('MATURITY_RC', 150); // tested, will be released unless there are fatal bugs
60 define('MATURITY_STABLE', 200); // ready for production deployment
63 * Special value that can be used in $plugin->dependencies in version.php files.
65 define('ANY_VERSION', 'any');
69 * Simple class. It is usually used instead of stdClass because it looks
70 * more familiar to Java developers ;-) Do not use for type checking of
71 * function parameters. Please use stdClass instead.
75 * @copyright 2009 Petr Skoda {@link http://skodak.org}
76 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
77 * @deprecated since 2.0
79 class object extends stdClass {};
82 * Base Moodle Exception class
84 * Although this class is defined here, you cannot throw a moodle_exception until
85 * after moodlelib.php has been included (which will happen very soon).
89 * @copyright 2008 Petr Skoda {@link http://skodak.org}
90 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
92 class moodle_exception extends Exception {
95 * @var string The name of the string from error.php to print
100 * @var string The name of module
105 * @var mixed Extra words and phrases that might be required in the error string
110 * @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.
115 * @var string Optional information to aid the debugging process
121 * @param string $errorcode The name of the string from error.php to print
122 * @param string $module name of module
123 * @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.
124 * @param mixed $a Extra words and phrases that might be required in the error string
125 * @param string $debuginfo optional debugging information
127 function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
128 if (empty($module) || $module == 'moodle' || $module == 'core') {
132 $this->errorcode = $errorcode;
133 $this->module = $module;
136 $this->debuginfo = is_null($debuginfo) ? null : (string)$debuginfo;
138 if (get_string_manager()->string_exists($errorcode, $module)) {
139 $message = get_string($errorcode, $module, $a);
141 $message = $module . '/' . $errorcode;
144 if (defined('PHPUNIT_TEST') and PHPUNIT_TEST and $debuginfo) {
145 $message = "$message ($debuginfo)";
148 parent::__construct($message, 0);
153 * Course/activity access exception.
155 * This exception is thrown from require_login()
157 * @package core_access
158 * @copyright 2010 Petr Skoda {@link http://skodak.org}
159 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
161 class require_login_exception extends moodle_exception {
164 * @param string $debuginfo Information to aid the debugging process
166 function __construct($debuginfo) {
167 parent::__construct('requireloginerror', 'error', '', NULL, $debuginfo);
172 * Web service parameter exception class
173 * @deprecated since Moodle 2.2 - use moodle exception instead
174 * This exception must be thrown to the web service client when a web service parameter is invalid
175 * The error string is gotten from webservice.php
177 class webservice_parameter_exception extends moodle_exception {
180 * @param string $errorcode The name of the string from webservice.php to print
181 * @param string $a The name of the parameter
182 * @param string $debuginfo Optional information to aid debugging
184 function __construct($errorcode=null, $a = '', $debuginfo = null) {
185 parent::__construct($errorcode, 'webservice', '', $a, $debuginfo);
190 * Exceptions indicating user does not have permissions to do something
191 * and the execution can not continue.
193 * @package core_access
194 * @copyright 2009 Petr Skoda {@link http://skodak.org}
195 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
197 class required_capability_exception extends moodle_exception {
200 * @param context $context The context used for the capability check
201 * @param string $capability The required capability
202 * @param string $errormessage The error message to show the user
203 * @param string $stringfile
205 function __construct($context, $capability, $errormessage, $stringfile) {
206 $capabilityname = get_capability_string($capability);
207 if ($context->contextlevel == CONTEXT_MODULE and preg_match('/:view$/', $capability)) {
208 // we can not go to mod/xx/view.php because we most probably do not have cap to view it, let's go to course instead
209 $paranetcontext = context::instance_by_id(get_parent_contextid($context));
210 $link = get_context_url($paranetcontext);
212 $link = get_context_url($context);
214 parent::__construct($errormessage, $stringfile, $link, $capabilityname);
219 * Exception indicating programming error, must be fixed by a programer. For example
220 * a core API might throw this type of exception if a plugin calls it incorrectly.
224 * @copyright 2008 Petr Skoda {@link http://skodak.org}
225 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
227 class coding_exception extends moodle_exception {
230 * @param string $hint short description of problem
231 * @param string $debuginfo detailed information how to fix problem
233 function __construct($hint, $debuginfo=null) {
234 parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
239 * Exception indicating malformed parameter problem.
240 * This exception is not supposed to be thrown when processing
241 * user submitted data in forms. It is more suitable
242 * for WS and other low level stuff.
246 * @copyright 2009 Petr Skoda {@link http://skodak.org}
247 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
249 class invalid_parameter_exception extends moodle_exception {
252 * @param string $debuginfo some detailed information
254 function __construct($debuginfo=null) {
255 parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
260 * Exception indicating malformed response problem.
261 * This exception is not supposed to be thrown when processing
262 * user submitted data in forms. It is more suitable
263 * for WS and other low level stuff.
265 class invalid_response_exception extends moodle_exception {
268 * @param string $debuginfo some detailed information
270 function __construct($debuginfo=null) {
271 parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
276 * An exception that indicates something really weird happened. For example,
277 * if you do switch ($context->contextlevel), and have one case for each
278 * CONTEXT_... constant. You might throw an invalid_state_exception in the
279 * default case, to just in case something really weird is going on, and
280 * $context->contextlevel is invalid - rather than ignoring this possibility.
284 * @copyright 2009 onwards Martin Dougiamas {@link http://moodle.com}
285 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
287 class invalid_state_exception extends moodle_exception {
290 * @param string $hint short description of problem
291 * @param string $debuginfo optional more detailed information
293 function __construct($hint, $debuginfo=null) {
294 parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
299 * An exception that indicates incorrect permissions in $CFG->dataroot
303 * @copyright 2010 Petr Skoda {@link http://skodak.org}
304 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
306 class invalid_dataroot_permissions extends moodle_exception {
309 * @param string $debuginfo optional more detailed information
311 function __construct($debuginfo = NULL) {
312 parent::__construct('invaliddatarootpermissions', 'error', '', NULL, $debuginfo);
317 * An exception that indicates that file can not be served
321 * @copyright 2010 Petr Skoda {@link http://skodak.org}
322 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
324 class file_serving_exception extends moodle_exception {
327 * @param string $debuginfo optional more detailed information
329 function __construct($debuginfo = NULL) {
330 parent::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
335 * Default exception handler, uncaught exceptions are equivalent to error() in 1.9 and earlier
337 * @param Exception $ex
338 * @return void -does not return. Terminates execution!
340 function default_exception_handler($ex) {
341 global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION, $PAGE;
343 // detect active db transactions, rollback and log as error
344 abort_all_db_transactions();
346 if (($ex instanceof required_capability_exception) && !CLI_SCRIPT && !AJAX_SCRIPT && !empty($CFG->autologinguests) && !empty($USER->autologinguest)) {
347 $SESSION->wantsurl = qualified_me();
348 redirect(get_login_url());
351 $info = get_exception_info($ex);
353 if (debugging('', DEBUG_MINIMAL)) {
354 $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
355 error_log($logerrmsg);
358 if (is_early_init($info->backtrace)) {
359 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
363 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
366 echo $OUTPUT->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
367 } catch (Exception $out_ex) {
368 // default exception handler MUST not throw any exceptions!!
369 // 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
370 // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
371 if (CLI_SCRIPT or AJAX_SCRIPT) {
372 // just ignore the error and send something back using the safest method
373 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
375 echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
376 $outinfo = get_exception_info($out_ex);
377 echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
382 exit(1); // General error code
386 * Default error handler, prevents some white screens.
388 * @param string $errstr
389 * @param string $errfile
390 * @param int $errline
391 * @param array $errcontext
392 * @return bool false means use default error handler
394 function default_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
395 if ($errno == 4096) {
396 //fatal catchable error
397 throw new coding_exception('PHP catchable fatal error', $errstr);
403 * Unconditionally abort all database transactions, this function
404 * should be called from exception handlers only.
407 function abort_all_db_transactions() {
408 global $CFG, $DB, $SCRIPT;
410 // default exception handler MUST not throw any exceptions!!
412 if ($DB && $DB->is_transaction_started()) {
413 error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
414 // note: transaction blocks should never change current $_SESSION
415 $DB->force_transaction_rollback();
420 * This function encapsulates the tests for whether an exception was thrown in
421 * early init -- either during setup.php or during init of $OUTPUT.
423 * If another exception is thrown then, and if we do not take special measures,
424 * we would just get a very cryptic message "Exception thrown without a stack
425 * frame in Unknown on line 0". That makes debugging very hard, so we do take
426 * special measures in default_exception_handler, with the help of this function.
428 * @param array $backtrace the stack trace to analyse.
429 * @return boolean whether the stack trace is somewhere in output initialisation.
431 function is_early_init($backtrace) {
432 $dangerouscode = array(
433 array('function' => 'header', 'type' => '->'),
434 array('class' => 'bootstrap_renderer'),
435 array('file' => dirname(__FILE__).'/setup.php'),
437 foreach ($backtrace as $stackframe) {
438 foreach ($dangerouscode as $pattern) {
440 foreach ($pattern as $property => $value) {
441 if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
454 * Abort execution by throwing of a general exception,
455 * default exception handler displays the error message in most cases.
457 * @param string $errorcode The name of the language string containing the error message.
458 * Normally this should be in the error.php lang file.
459 * @param string $module The language file to get the error message from.
460 * @param string $link The url where the user will be prompted to continue.
461 * If no url is provided the user will be directed to the site index page.
462 * @param object $a Extra words and phrases that might be required in the error string
463 * @param string $debuginfo optional debugging information
464 * @return void, always throws exception!
466 function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
467 throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
471 * Returns detailed information about specified exception.
472 * @param exception $ex
475 function get_exception_info($ex) {
476 global $CFG, $DB, $SESSION;
478 if ($ex instanceof moodle_exception) {
479 $errorcode = $ex->errorcode;
480 $module = $ex->module;
483 $debuginfo = $ex->debuginfo;
485 $errorcode = 'generalexceptionmessage';
487 $a = $ex->getMessage();
492 // Append the error code to the debug info to make grepping and googling easier
493 $debuginfo .= PHP_EOL."Error code: $errorcode";
495 $backtrace = $ex->getTrace();
496 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
497 array_unshift($backtrace, $place);
499 // Be careful, no guarantee moodlelib.php is loaded.
500 if (empty($module) || $module == 'moodle' || $module == 'core') {
503 // Search for the $errorcode's associated string
504 // If not found, append the contents of $a to $debuginfo so helpful information isn't lost
505 if (function_exists('get_string_manager')) {
506 if (get_string_manager()->string_exists($errorcode, $module)) {
507 $message = get_string($errorcode, $module, $a);
508 } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
509 // Search in moodle file if error specified - needed for backwards compatibility
510 $message = get_string($errorcode, 'moodle', $a);
512 $message = $module . '/' . $errorcode;
513 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
516 $message = $module . '/' . $errorcode;
517 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
520 // Be careful, no guarantee weblib.php is loaded.
521 if (function_exists('clean_text')) {
522 $message = clean_text($message);
524 $message = htmlspecialchars($message);
527 if (!empty($CFG->errordocroot)) {
528 $errordoclink = $CFG->errordocroot . '/en/';
530 $errordoclink = get_docs_url();
533 if ($module === 'error') {
534 $modulelink = 'moodle';
536 $modulelink = $module;
538 $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
541 if (!empty($SESSION->fromurl)) {
542 $link = $SESSION->fromurl;
543 unset($SESSION->fromurl);
545 $link = $CFG->wwwroot .'/';
549 // when printing an error the continue button should never link offsite
550 if (stripos($link, $CFG->wwwroot) === false &&
551 stripos($link, $CFG->httpswwwroot) === false) {
552 $link = $CFG->wwwroot.'/';
555 $info = new stdClass();
556 $info->message = $message;
557 $info->errorcode = $errorcode;
558 $info->backtrace = $backtrace;
560 $info->moreinfourl = $moreinfourl;
562 $info->debuginfo = $debuginfo;
568 * Returns the Moodle Docs URL in the users language for a given 'More help' link.
570 * There are three cases:
572 * 1. In the normal case, $path will be a short relative path 'component/thing',
573 * like 'mod/folder/view' 'group/import'. This gets turned into an link to
574 * MoodleDocs in the user's language, and for the appropriate Moodle version.
575 * E.g. 'group/import' may become 'http://docs.moodle.org/2x/en/group/import'.
576 * The 'http://docs.moodle.org' bit comes from $CFG->docroot.
578 * This is the only option that should be used in standard Moodle code. The other
579 * two options have been implemented because they are useful for third-party plugins.
581 * 2. $path may be an absolute URL, starting http:// or https://. In this case,
582 * the link is used as is.
584 * 3. $path may start %%WWWROOT%%, in which case that is replaced by
585 * $CFG->wwwroot to make the link.
587 * @param string $path the place to link to. See above for details.
588 * @return string The MoodleDocs URL in the user's language. for example @link http://docs.moodle.org/2x/en/$path}
590 function get_docs_url($path = null) {
593 // Absolute URLs are used unmodified.
594 if (substr($path, 0, 7) === 'http://' || substr($path, 0, 8) === 'https://') {
598 // Paths starting %%WWWROOT%% have that replaced by $CFG->wwwroot.
599 if (substr($path, 0, 11) === '%%WWWROOT%%') {
600 return $CFG->wwwroot . substr($path, 11);
603 // Otherwise we do the normal case, and construct a MoodleDocs URL relative to $CFG->docroot.
605 // Check that $CFG->branch has been set up, during installation it won't be.
606 if (empty($CFG->branch)) {
607 // It's not there yet so look at version.php.
608 include($CFG->dirroot.'/version.php');
610 // We can use $CFG->branch and avoid having to include version.php.
611 $branch = $CFG->branch;
613 // ensure branch is valid.
615 // We should never get here but in case we do lets set $branch to .
616 // the smart one's will know that this is the current directory
617 // and the smarter ones will know that there is some smart matching
618 // that will ensure people end up at the latest version of the docs.
621 if (!empty($CFG->docroot)) {
622 return $CFG->docroot . '/' . $branch . '/' . current_language() . '/' . $path;
624 return 'http://docs.moodle.org/'. $branch . '/' . current_language() . '/' . $path;
629 * Formats a backtrace ready for output.
631 * @param array $callers backtrace array, as returned by debug_backtrace().
632 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
633 * @return string formatted backtrace, ready for output.
635 function format_backtrace($callers, $plaintext = false) {
636 // do not use $CFG->dirroot because it might not be available in destructors
637 $dirroot = dirname(dirname(__FILE__));
639 if (empty($callers)) {
643 $from = $plaintext ? '' : '<ul style="text-align: left">';
644 foreach ($callers as $caller) {
645 if (!isset($caller['line'])) {
646 $caller['line'] = '?'; // probably call_user_func()
648 if (!isset($caller['file'])) {
649 $caller['file'] = 'unknownfile'; // probably call_user_func()
651 $from .= $plaintext ? '* ' : '<li>';
652 $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
653 if (isset($caller['function'])) {
654 $from .= ': call to ';
655 if (isset($caller['class'])) {
656 $from .= $caller['class'] . $caller['type'];
658 $from .= $caller['function'] . '()';
659 } else if (isset($caller['exception'])) {
660 $from .= ': '.$caller['exception'].' thrown';
662 $from .= $plaintext ? "\n" : '</li>';
664 $from .= $plaintext ? '' : '</ul>';
670 * This function makes the return value of ini_get consistent if you are
671 * setting server directives through the .htaccess file in apache.
673 * Current behavior for value set from php.ini On = 1, Off = [blank]
674 * Current behavior for value set from .htaccess On = On, Off = Off
675 * Contributed by jdell @ unr.edu
677 * @param string $ini_get_arg The argument to get
678 * @return bool True for on false for not
680 function ini_get_bool($ini_get_arg) {
681 $temp = ini_get($ini_get_arg);
683 if ($temp == '1' or strtolower($temp) == 'on') {
690 * This function verifies the sanity of PHP configuration
691 * and stops execution if anything critical found.
693 function setup_validate_php_configuration() {
694 // this must be very fast - no slow checks here!!!
696 if (ini_get_bool('register_globals')) {
697 print_error('globalswarning', 'admin');
699 if (ini_get_bool('session.auto_start')) {
700 print_error('sessionautostartwarning', 'admin');
702 if (ini_get_bool('magic_quotes_runtime')) {
703 print_error('fatalmagicquotesruntime', 'admin');
708 * Initialise global $CFG variable
711 function initialise_cfg() {
716 $localcfg = get_config('core');
717 foreach ($localcfg as $name => $value) {
718 if (property_exists($CFG, $name)) {
719 // config.php settings always take precedence
722 $CFG->{$name} = $value;
725 } catch (dml_exception $e) {
726 // most probably empty db, going to install soon
731 * Initialises $FULLME and friends. Private function. Should only be called from
734 function initialise_fullme() {
735 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
737 // Detect common config error.
738 if (substr($CFG->wwwroot, -1) == '/') {
739 print_error('wwwrootslash', 'error');
743 initialise_fullme_cli();
747 $rurl = setup_get_remote_url();
748 $wwwroot = parse_url($CFG->wwwroot.'/');
750 if (empty($rurl['host'])) {
751 // missing host in request header, probably not a real browser, let's ignore them
753 } else if (!empty($CFG->reverseproxy)) {
754 // $CFG->reverseproxy specifies if reverse proxy server used
755 // Used in load balancing scenarios.
756 // Do not abuse this to try to solve lan/wan access problems!!!!!
759 if (($rurl['host'] !== $wwwroot['host']) or (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port'])) {
760 // Explain the problem and redirect them to the right URL
761 if (!defined('NO_MOODLE_COOKIES')) {
762 define('NO_MOODLE_COOKIES', true);
764 // The login/token.php script should call the correct url/port.
765 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
766 $wwwrootport = empty($wwwroot['port'])?'':$wwwroot['port'];
767 $calledurl = $rurl['host'];
768 if (!empty($rurl['port'])) {
769 $calledurl .= ':'. $rurl['port'];
771 $correcturl = $wwwroot['host'];
772 if (!empty($wwwrootport)) {
773 $correcturl .= ':'. $wwwrootport;
775 throw new moodle_exception('requirecorrectaccess', 'error', '', null,
776 'You called ' . $calledurl .', you should have called ' . $correcturl);
778 redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
782 // Check that URL is under $CFG->wwwroot.
783 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
784 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
786 // Probably some weird external script
787 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
791 // $CFG->sslproxy specifies if external SSL appliance is used
792 // (That is, the Moodle server uses http, with an external box translating everything to https).
793 if (empty($CFG->sslproxy)) {
794 if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
795 print_error('sslonlyaccess', 'error');
798 if ($wwwroot['scheme'] !== 'https') {
799 throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
801 $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
804 // hopefully this will stop all those "clever" admins trying to set up moodle
805 // with two different addresses in intranet and Internet
806 if (!empty($CFG->reverseproxy) && $rurl['host'] === $wwwroot['host']) {
807 print_error('reverseproxyabused', 'error');
810 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
811 if (!empty($wwwroot['port'])) {
812 $hostandport .= ':'.$wwwroot['port'];
815 $FULLSCRIPT = $hostandport . $rurl['path'];
816 $FULLME = $hostandport . $rurl['fullpath'];
817 $ME = $rurl['fullpath'];
821 * Initialises $FULLME and friends for command line scripts.
822 * This is a private method for use by initialise_fullme.
824 function initialise_fullme_cli() {
825 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
827 // Urls do not make much sense in CLI scripts
828 $backtrace = debug_backtrace();
829 $topfile = array_pop($backtrace);
830 $topfile = realpath($topfile['file']);
831 $dirroot = realpath($CFG->dirroot);
833 if (strpos($topfile, $dirroot) !== 0) {
834 // Probably some weird external script
835 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
837 $relativefile = substr($topfile, strlen($dirroot));
838 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
839 $SCRIPT = $FULLSCRIPT = $relativefile;
840 $FULLME = $ME = null;
845 * Get the URL that PHP/the web server thinks it is serving. Private function
846 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
847 * @return array in the same format that parse_url returns, with the addition of
848 * a 'fullpath' element, which includes any slasharguments path.
850 function setup_get_remote_url() {
852 if (isset($_SERVER['HTTP_HOST'])) {
853 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
855 $rurl['host'] = null;
857 $rurl['port'] = $_SERVER['SERVER_PORT'];
858 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
859 $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ? 'http' : 'https';
861 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
863 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
865 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
866 //IIS - needs a lot of tweaking to make it work
867 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
869 // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
870 // since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
871 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
873 if ($_SERVER['QUERY_STRING'] != '') {
874 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
876 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
878 /* NOTE: following servers are not fully tested! */
880 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
881 //lighttpd - not officially supported
882 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
884 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
885 //nginx - not officially supported
886 if (!isset($_SERVER['SCRIPT_NAME'])) {
887 die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
889 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
891 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
892 //cherokee - not officially supported
893 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
895 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
896 //zeus - not officially supported
897 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
899 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
900 //LiteSpeed - not officially supported
901 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
903 } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
904 //obscure name found on some servers - this is definitely not supported
905 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
907 } else if (strpos($_SERVER['SERVER_SOFTWARE'], 'PHP') === 0) {
908 // built-in PHP Development Server
909 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
912 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
915 // sanitize the url a bit more, the encoding style may be different in vars above
916 $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
917 $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);
923 * Initializes our performance info early.
925 * Pairs up with get_performance_info() which is actually
926 * in moodlelib.php. This function is here so that we can
927 * call it before all the libs are pulled in.
931 function init_performance_info() {
933 global $PERF, $CFG, $USER;
935 $PERF = new stdClass();
936 $PERF->logwrites = 0;
937 if (function_exists('microtime')) {
938 $PERF->starttime = microtime();
940 if (function_exists('memory_get_usage')) {
941 $PERF->startmemory = memory_get_usage();
943 if (function_exists('posix_times')) {
944 $PERF->startposixtimes = posix_times();
949 * Indicates whether we are in the middle of the initial Moodle install.
951 * Very occasionally it is necessary avoid running certain bits of code before the
952 * Moodle installation has completed. The installed flag is set in admin/index.php
953 * after Moodle core and all the plugins have been installed, but just before
954 * the person doing the initial install is asked to choose the admin password.
956 * @return boolean true if the initial install is not complete.
958 function during_initial_install() {
960 return empty($CFG->rolesactive);
964 * Function to raise the memory limit to a new value.
965 * Will respect the memory limit if it is higher, thus allowing
966 * settings in php.ini, apache conf or command line switches
969 * The memory limit should be expressed with a constant
970 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
971 * It is possible to use strings or integers too (eg:'128M').
973 * @param mixed $newlimit the new memory limit
974 * @return bool success
976 function raise_memory_limit($newlimit) {
979 if ($newlimit == MEMORY_UNLIMITED) {
980 ini_set('memory_limit', -1);
983 } else if ($newlimit == MEMORY_STANDARD) {
984 if (PHP_INT_SIZE > 4) {
985 $newlimit = get_real_size('128M'); // 64bit needs more memory
987 $newlimit = get_real_size('96M');
990 } else if ($newlimit == MEMORY_EXTRA) {
991 if (PHP_INT_SIZE > 4) {
992 $newlimit = get_real_size('384M'); // 64bit needs more memory
994 $newlimit = get_real_size('256M');
996 if (!empty($CFG->extramemorylimit)) {
997 $extra = get_real_size($CFG->extramemorylimit);
998 if ($extra > $newlimit) {
1003 } else if ($newlimit == MEMORY_HUGE) {
1004 $newlimit = get_real_size('2G');
1007 $newlimit = get_real_size($newlimit);
1010 if ($newlimit <= 0) {
1011 debugging('Invalid memory limit specified.');
1015 $cur = ini_get('memory_limit');
1017 // if php is compiled without --enable-memory-limits
1018 // apparently memory_limit is set to ''
1022 return true; // unlimited mem!
1024 $cur = get_real_size($cur);
1027 if ($newlimit > $cur) {
1028 ini_set('memory_limit', $newlimit);
1035 * Function to reduce the memory limit to a new value.
1036 * Will respect the memory limit if it is lower, thus allowing
1037 * settings in php.ini, apache conf or command line switches
1040 * The memory limit should be expressed with a string (eg:'64M')
1042 * @param string $newlimit the new memory limit
1045 function reduce_memory_limit($newlimit) {
1046 if (empty($newlimit)) {
1049 $cur = ini_get('memory_limit');
1051 // if php is compiled without --enable-memory-limits
1052 // apparently memory_limit is set to ''
1056 return true; // unlimited mem!
1058 $cur = get_real_size($cur);
1061 $new = get_real_size($newlimit);
1062 // -1 is smaller, but it means unlimited
1063 if ($new < $cur && $new != -1) {
1064 ini_set('memory_limit', $newlimit);
1071 * Converts numbers like 10M into bytes.
1073 * @param string $size The size to be converted
1076 function get_real_size($size = 0) {
1081 $scan['GB'] = 1073741824;
1082 $scan['Gb'] = 1073741824;
1083 $scan['G'] = 1073741824;
1084 $scan['MB'] = 1048576;
1085 $scan['Mb'] = 1048576;
1086 $scan['M'] = 1048576;
1087 $scan['m'] = 1048576;
1093 while (list($key) = each($scan)) {
1094 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
1095 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
1103 * Try to disable all output buffering and purge
1106 * @access private to be called only from lib/setup.php !
1109 function disable_output_buffering() {
1110 $olddebug = error_reporting(0);
1112 // disable compression, it would prevent closing of buffers
1113 if (ini_get_bool('zlib.output_compression')) {
1114 ini_set('zlib.output_compression', 'Off');
1117 // try to flush everything all the time
1118 ob_implicit_flush(true);
1120 // close all buffers if possible and discard any existing output
1121 // this can actually work around some whitespace problems in config.php
1122 while(ob_get_level()) {
1123 if (!ob_end_clean()) {
1124 // prevent infinite loop when buffer can not be closed
1129 // disable any other output handlers
1130 ini_set('output_handler', '');
1132 error_reporting($olddebug);
1136 * Check whether a major upgrade is needed. That is defined as an upgrade that
1137 * changes something really fundamental in the database, so nothing can possibly
1138 * work until the database has been updated, and that is defined by the hard-coded
1139 * version number in this function.
1141 function redirect_if_major_upgrade_required() {
1143 $lastmajordbchanges = 2013021100.01;
1144 if (empty($CFG->version) or (float)$CFG->version < $lastmajordbchanges or
1145 during_initial_install() or !empty($CFG->adminsetuppending)) {
1147 @session_get_instance()->terminate_current();
1148 } catch (Exception $e) {
1149 // Ignore any errors, redirect to upgrade anyway.
1151 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
1152 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1153 @header('Location: ' . $url);
1154 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
1160 * Function to check if a directory exists and by default create it if not exists.
1162 * Previously this was accepting paths only from dataroot, but we now allow
1163 * files outside of dataroot if you supply custom paths for some settings in config.php.
1164 * This function does not verify that the directory is writable.
1166 * NOTE: this function uses current file stat cache,
1167 * please use clearstatcache() before this if you expect that the
1168 * directories may have been removed recently from a different request.
1170 * @param string $dir absolute directory path
1171 * @param boolean $create directory if does not exist
1172 * @param boolean $recursive create directory recursively
1173 * @return boolean true if directory exists or created, false otherwise
1175 function check_dir_exists($dir, $create = true, $recursive = true) {
1178 umask(0000); // just in case some evil code changed it
1188 return mkdir($dir, $CFG->directorypermissions, $recursive);
1192 * Create a directory and make sure it is writable.
1195 * @param string $dir the full path of the directory to be created
1196 * @param bool $exceptiononerror throw exception if error encountered
1197 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1199 function make_writable_directory($dir, $exceptiononerror = true) {
1202 if (file_exists($dir) and !is_dir($dir)) {
1203 if ($exceptiononerror) {
1204 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1210 umask(0000); // just in case some evil code changed it
1212 if (!file_exists($dir)) {
1213 if (!mkdir($dir, $CFG->directorypermissions, true)) {
1214 if ($exceptiononerror) {
1215 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1222 if (!is_writable($dir)) {
1223 if ($exceptiononerror) {
1224 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1234 * Protect a directory from web access.
1235 * Could be extended in the future to support other mechanisms (e.g. other webservers).
1238 * @param string $dir the full path of the directory to be protected
1240 function protect_directory($dir) {
1241 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1242 if (!file_exists("$dir/.htaccess")) {
1243 if ($handle = fopen("$dir/.htaccess", 'w')) { // For safety
1244 @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");
1251 * Create a directory under dataroot and make sure it is writable.
1252 * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
1254 * @param string $directory the full path of the directory to be created under $CFG->dataroot
1255 * @param bool $exceptiononerror throw exception if error encountered
1256 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1258 function make_upload_directory($directory, $exceptiononerror = true) {
1261 if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1262 debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1264 } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
1265 debugging('Use make_cache_directory() for creation of chache directory and $CFG->cachedir to get the location.');
1268 protect_directory($CFG->dataroot);
1269 return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1273 * Create a directory under tempdir and make sure it is writable.
1274 * Temporary files should be used during the current request only!
1276 * @param string $directory the full path of the directory to be created under $CFG->tempdir
1277 * @param bool $exceptiononerror throw exception if error encountered
1278 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1280 function make_temp_directory($directory, $exceptiononerror = true) {
1282 if ($CFG->tempdir !== "$CFG->dataroot/temp") {
1283 check_dir_exists($CFG->tempdir, true, true);
1284 protect_directory($CFG->tempdir);
1286 protect_directory($CFG->dataroot);
1288 return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1292 * Create a directory under cachedir and make sure it is writable.
1294 * @param string $directory the full path of the directory to be created under $CFG->cachedir
1295 * @param bool $exceptiononerror throw exception if error encountered
1296 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1298 function make_cache_directory($directory, $exceptiononerror = true) {
1300 if ($CFG->cachedir !== "$CFG->dataroot/cache") {
1301 check_dir_exists($CFG->cachedir, true, true);
1302 protect_directory($CFG->cachedir);
1304 protect_directory($CFG->dataroot);
1306 return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1310 * Checks if current user is a web crawler.
1312 * This list can not be made complete, this is not a security
1313 * restriction, we make the list only to help these sites
1314 * especially when automatic guest login is disabled.
1316 * If admin needs security they should enable forcelogin
1317 * and disable guest access!!
1321 function is_web_crawler() {
1322 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
1323 if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
1325 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) { // Google
1327 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yahoo! Slurp') !== false ) { // Yahoo
1329 } else if (strpos($_SERVER['HTTP_USER_AGENT'], '[ZSEBOT]') !== false ) { // Zoomspider
1331 } else if (stripos($_SERVER['HTTP_USER_AGENT'], 'msnbot') !== false ) { // MSN Search
1333 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'bingbot') !== false ) { // Bing
1335 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yandex') !== false ) {
1337 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'AltaVista') !== false ) {
1339 } else if (stripos($_SERVER['HTTP_USER_AGENT'], 'baiduspider') !== false ) { // Baidu
1341 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Teoma') !== false ) { // Ask.com
1349 * This class solves the problem of how to initialise $OUTPUT.
1351 * The problem is caused be two factors
1353 * <li>On the one hand, we cannot be sure when output will start. In particular,
1354 * an error, which needs to be displayed, could be thrown at any time.</li>
1355 * <li>On the other hand, we cannot be sure when we will have all the information
1356 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1357 * (potentially) depends on the current course, course categories, and logged in user.
1358 * It also depends on whether the current page requires HTTPS.</li>
1361 * So, it is hard to find a single natural place during Moodle script execution,
1362 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1363 * adopt the following strategy
1365 * <li>We will initialise $OUTPUT the first time it is used.</li>
1366 * <li>If, after $OUTPUT has been initialised, the script tries to change something
1367 * that $OUTPUT depends on, we throw an exception making it clear that the script
1368 * did something wrong.
1371 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1372 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1373 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1374 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1376 * Note that this class is used before lib/outputlib.php has been loaded, so we
1377 * must be careful referring to classes/functions from there, they may not be
1378 * defined yet, and we must avoid fatal errors.
1380 * @copyright 2009 Tim Hunt
1381 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1384 class bootstrap_renderer {
1386 * Handles re-entrancy. Without this, errors or debugging output that occur
1387 * during the initialisation of $OUTPUT, cause infinite recursion.
1390 protected $initialising = false;
1393 * Have we started output yet?
1394 * @return boolean true if the header has been printed.
1396 public function has_started() {
1401 * Constructor - to be used by core code only.
1402 * @param string $method The method to call
1403 * @param array $arguments Arguments to pass to the method being called
1406 public function __call($method, $arguments) {
1407 global $OUTPUT, $PAGE;
1410 if ($method == 'notification') {
1411 // Catch infinite recursion caused by debugging output during print_header.
1412 $backtrace = debug_backtrace();
1413 array_shift($backtrace);
1414 array_shift($backtrace);
1415 $recursing = is_early_init($backtrace);
1418 $earlymethods = array(
1419 'fatal_error' => 'early_error',
1420 'notification' => 'early_notification',
1423 // If lib/outputlib.php has been loaded, call it.
1424 if (!empty($PAGE) && !$recursing) {
1425 if (array_key_exists($method, $earlymethods)) {
1426 //prevent PAGE->context warnings - exceptions might appear before we set any context
1427 $PAGE->set_context(null);
1429 $PAGE->initialise_theme_and_output();
1430 return call_user_func_array(array($OUTPUT, $method), $arguments);
1433 $this->initialising = true;
1435 // Too soon to initialise $OUTPUT, provide a couple of key methods.
1436 if (array_key_exists($method, $earlymethods)) {
1437 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1440 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1444 * Returns nicely formatted error message in a div box.
1446 * @param string $message error message
1447 * @param string $moreinfourl (ignored in early errors)
1448 * @param string $link (ignored in early errors)
1449 * @param array $backtrace
1450 * @param string $debuginfo
1453 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1456 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1457 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1458 width: 80%; -moz-border-radius: 20px; padding: 15px">
1461 // Check whether debug is set.
1462 $debug = (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER);
1463 // Also check we have it set in the config file. This occurs if the method to read the config table from the
1464 // database fails, reading from the config table is the first database interaction we have.
1465 $debug = $debug || (!empty($CFG->config_php_settings['debug']) && $CFG->config_php_settings['debug'] >= DEBUG_DEVELOPER );
1467 if (!empty($debuginfo)) {
1468 $debuginfo = s($debuginfo); // removes all nasty JS
1469 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1470 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
1472 if (!empty($backtrace)) {
1473 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1481 * This function should only be called by this class, or from exception handlers
1483 * @param string $message error message
1484 * @param string $moreinfourl (ignored in early errors)
1485 * @param string $link (ignored in early errors)
1486 * @param array $backtrace
1487 * @param string $debuginfo extra information for developers
1490 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = null) {
1494 echo "!!! $message !!!\n";
1495 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1496 if (!empty($debuginfo)) {
1497 echo "\nDebug info: $debuginfo";
1499 if (!empty($backtrace)) {
1500 echo "\nStack trace: " . format_backtrace($backtrace, true);
1505 } else if (AJAX_SCRIPT) {
1506 $e = new stdClass();
1507 $e->error = $message;
1508 $e->stacktrace = NULL;
1509 $e->debuginfo = NULL;
1510 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1511 if (!empty($debuginfo)) {
1512 $e->debuginfo = $debuginfo;
1514 if (!empty($backtrace)) {
1515 $e->stacktrace = format_backtrace($backtrace, true);
1518 $e->errorcode = $errorcode;
1519 @header('Content-Type: application/json; charset=utf-8');
1520 echo json_encode($e);
1524 // In the name of protocol correctness, monitoring and performance
1525 // profiling, set the appropriate error headers for machine consumption
1526 if (isset($_SERVER['SERVER_PROTOCOL'])) {
1527 // Avoid it with cron.php. Note that we assume it's HTTP/1.x
1528 // The 503 ode here means our Moodle does not work at all, the error happened too early
1529 @header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
1532 // better disable any caching
1533 @header('Content-Type: text/html; charset=utf-8');
1534 @header('X-UA-Compatible: IE=edge');
1535 @header('Cache-Control: no-store, no-cache, must-revalidate');
1536 @header('Cache-Control: post-check=0, pre-check=0', false);
1537 @header('Pragma: no-cache');
1538 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1539 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1541 if (function_exists('get_string')) {
1542 $strerror = get_string('error');
1544 $strerror = 'Error';
1547 $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
1549 return self::plain_page($strerror, $content);
1553 * Early notification message
1555 * @param string $message
1556 * @param string $classes usually notifyproblem or notifysuccess
1559 public static function early_notification($message, $classes = 'notifyproblem') {
1560 return '<div class="' . $classes . '">' . $message . '</div>';
1564 * Page should redirect message.
1566 * @param string $encodedurl redirect url
1569 public static function plain_redirect_message($encodedurl) {
1570 $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
1571 $encodedurl .'">'. get_string('continue') .'</a></div>';
1572 return self::plain_page(get_string('redirect'), $message);
1576 * Early redirection page, used before full init of $PAGE global
1578 * @param string $encodedurl redirect url
1579 * @param string $message redirect message
1580 * @param int $delay time in seconds
1581 * @return string redirect page
1583 public static function early_redirect_message($encodedurl, $message, $delay) {
1584 $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
1585 $content = self::early_error_content($message, null, null, null);
1586 $content .= self::plain_redirect_message($encodedurl);
1588 return self::plain_page(get_string('redirect'), $content, $meta);
1592 * Output basic html page.
1594 * @param string $title page title
1595 * @param string $content page content
1596 * @param string $meta meta tag
1597 * @return string html page
1599 public static function plain_page($title, $content, $meta = '') {
1600 if (function_exists('get_string') && function_exists('get_html_lang')) {
1601 $htmllang = get_html_lang();
1606 return '<!DOCTYPE html>
1607 <html ' . $htmllang . '>
1609 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1611 <title>' . $title . '</title>
1612 </head><body>' . $content . '</body></html>';