Merge branch 'm22_MDL-33053_AICC_flattened_TOC' of git://github.com/scara/moodle...
[moodle.git] / lib / setuplib.php
blobcc1cd12030d1e1b2555cc50ed6af5406b1a09f85
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
19 /**
20 * These functions are required very early in the Moodle
21 * setup process, before any of the main libraries are
22 * loaded.
24 * @package core
25 * @subpackage lib
26 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
27 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 defined('MOODLE_INTERNAL') || die();
32 /// Debug levels ///
33 /** no warnings at all */
34 define('DEBUG_NONE', 0);
35 /** E_ERROR | E_PARSE */
36 define('DEBUG_MINIMAL', 5);
37 /** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */
38 define('DEBUG_NORMAL', 15);
39 /** E_ALL without E_STRICT for now, do show recoverable fatal errors */
40 define('DEBUG_ALL', 6143);
41 /** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL | 32768) */
42 define('DEBUG_DEVELOPER', 38911);
44 /** Remove any memory limits */
45 define('MEMORY_UNLIMITED', -1);
46 /** Standard memory limit for given platform */
47 define('MEMORY_STANDARD', -2);
48 /**
49 * Large memory limit for given platform - used in cron, upgrade, and other places that need a lot of memory.
50 * Can be overridden with $CFG->extramemorylimit setting.
52 define('MEMORY_EXTRA', -3);
53 /** Extremely large memory limit - not recommended for standard scripts */
54 define('MEMORY_HUGE', -4);
56 /**
57 * Software maturity levels used by the core and plugins
59 define('MATURITY_ALPHA', 50); // internals can be tested using white box techniques
60 define('MATURITY_BETA', 100); // feature complete, ready for preview and testing
61 define('MATURITY_RC', 150); // tested, will be released unless there are fatal bugs
62 define('MATURITY_STABLE', 200); // ready for production deployment
64 /**
65 * Special value that can be used in $plugin->dependencies in version.php files.
67 define('ANY_VERSION', 'any');
70 /**
71 * Simple class. It is usually used instead of stdClass because it looks
72 * more familiar to Java developers ;-) Do not use for type checking of
73 * function parameters. Please use stdClass instead.
75 * @package core
76 * @subpackage lib
77 * @copyright 2009 Petr Skoda {@link http://skodak.org}
78 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
79 * @deprecated since 2.0
81 class object extends stdClass {};
83 /**
84 * Base Moodle Exception class
86 * Although this class is defined here, you cannot throw a moodle_exception until
87 * after moodlelib.php has been included (which will happen very soon).
89 * @package core
90 * @subpackage lib
91 * @copyright 2008 Petr Skoda {@link http://skodak.org}
92 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
94 class moodle_exception extends Exception {
95 public $errorcode;
96 public $module;
97 public $a;
98 public $link;
99 public $debuginfo;
102 * Constructor
103 * @param string $errorcode The name of the string from error.php to print
104 * @param string $module name of module
105 * @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.
106 * @param object $a Extra words and phrases that might be required in the error string
107 * @param string $debuginfo optional debugging information
109 function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
110 if (empty($module) || $module == 'moodle' || $module == 'core') {
111 $module = 'error';
114 $this->errorcode = $errorcode;
115 $this->module = $module;
116 $this->link = $link;
117 $this->a = $a;
118 $this->debuginfo = $debuginfo;
120 if (get_string_manager()->string_exists($errorcode, $module)) {
121 $message = get_string($errorcode, $module, $a);
122 } else {
123 $message = $module . '/' . $errorcode;
126 parent::__construct($message, 0);
131 * Course/activity access exception.
133 * This exception is thrown from require_login()
135 * @package core
136 * @subpackage lib
137 * @copyright 2010 Petr Skoda {@link http://skodak.org}
138 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
140 class require_login_exception extends moodle_exception {
141 function __construct($debuginfo) {
142 parent::__construct('requireloginerror', 'error', '', NULL, $debuginfo);
147 * Web service parameter exception class
148 * @deprecated since Moodle 2.2 - use moodle exception instead
149 * This exception must be thrown to the web service client when a web service parameter is invalid
150 * The error string is gotten from webservice.php
152 class webservice_parameter_exception extends moodle_exception {
154 * Constructor
155 * @param string $errorcode The name of the string from webservice.php to print
156 * @param string $a The name of the parameter
158 function __construct($errorcode=null, $a = '', $debuginfo = null) {
159 parent::__construct($errorcode, 'webservice', '', $a, $debuginfo);
164 * Exceptions indicating user does not have permissions to do something
165 * and the execution can not continue.
167 * @package core
168 * @subpackage lib
169 * @copyright 2009 Petr Skoda {@link http://skodak.org}
170 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
172 class required_capability_exception extends moodle_exception {
173 function __construct($context, $capability, $errormessage, $stringfile) {
174 $capabilityname = get_capability_string($capability);
175 if ($context->contextlevel == CONTEXT_MODULE and preg_match('/:view$/', $capability)) {
176 // 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
177 $paranetcontext = get_context_instance_by_id(get_parent_contextid($context));
178 $link = get_context_url($paranetcontext);
179 } else {
180 $link = get_context_url($context);
182 parent::__construct($errormessage, $stringfile, $link, $capabilityname);
187 * Exception indicating programming error, must be fixed by a programer. For example
188 * a core API might throw this type of exception if a plugin calls it incorrectly.
190 * @package core
191 * @subpackage lib
192 * @copyright 2008 Petr Skoda {@link http://skodak.org}
193 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
195 class coding_exception extends moodle_exception {
197 * Constructor
198 * @param string $hint short description of problem
199 * @param string $debuginfo detailed information how to fix problem
201 function __construct($hint, $debuginfo=null) {
202 parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
207 * Exception indicating malformed parameter problem.
208 * This exception is not supposed to be thrown when processing
209 * user submitted data in forms. It is more suitable
210 * for WS and other low level stuff.
212 * @package core
213 * @subpackage lib
214 * @copyright 2009 Petr Skoda {@link http://skodak.org}
215 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
217 class invalid_parameter_exception extends moodle_exception {
219 * Constructor
220 * @param string $debuginfo some detailed information
222 function __construct($debuginfo=null) {
223 parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
228 * Exception indicating malformed response problem.
229 * This exception is not supposed to be thrown when processing
230 * user submitted data in forms. It is more suitable
231 * for WS and other low level stuff.
233 class invalid_response_exception extends moodle_exception {
235 * Constructor
236 * @param string $debuginfo some detailed information
238 function __construct($debuginfo=null) {
239 parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
244 * An exception that indicates something really weird happened. For example,
245 * if you do switch ($context->contextlevel), and have one case for each
246 * CONTEXT_... constant. You might throw an invalid_state_exception in the
247 * default case, to just in case something really weird is going on, and
248 * $context->contextlevel is invalid - rather than ignoring this possibility.
250 * @package core
251 * @subpackage lib
252 * @copyright 2009 onwards Martin Dougiamas {@link http://moodle.com}
253 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
255 class invalid_state_exception extends moodle_exception {
257 * Constructor
258 * @param string $hint short description of problem
259 * @param string $debuginfo optional more detailed information
261 function __construct($hint, $debuginfo=null) {
262 parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
267 * An exception that indicates incorrect permissions in $CFG->dataroot
269 * @package core
270 * @subpackage lib
271 * @copyright 2010 Petr Skoda {@link http://skodak.org}
272 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
274 class invalid_dataroot_permissions extends moodle_exception {
276 * Constructor
277 * @param string $debuginfo optional more detailed information
279 function __construct($debuginfo = NULL) {
280 parent::__construct('invaliddatarootpermissions', 'error', '', NULL, $debuginfo);
285 * An exception that indicates that file can not be served
287 * @package core
288 * @subpackage lib
289 * @copyright 2010 Petr Skoda {@link http://skodak.org}
290 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
292 class file_serving_exception extends moodle_exception {
294 * Constructor
295 * @param string $debuginfo optional more detailed information
297 function __construct($debuginfo = NULL) {
298 parent::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
303 * Default exception handler, uncaught exceptions are equivalent to error() in 1.9 and earlier
305 * @param Exception $ex
306 * @return void -does not return. Terminates execution!
308 function default_exception_handler($ex) {
309 global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION;
311 // detect active db transactions, rollback and log as error
312 abort_all_db_transactions();
314 if (($ex instanceof required_capability_exception) && !CLI_SCRIPT && !AJAX_SCRIPT && !empty($CFG->autologinguests) && !empty($USER->autologinguest)) {
315 $SESSION->wantsurl = $FULLME;
316 redirect(get_login_url());
319 $info = get_exception_info($ex);
321 if (debugging('', DEBUG_MINIMAL)) {
322 $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
323 error_log($logerrmsg);
326 if (is_early_init($info->backtrace)) {
327 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
328 } else {
329 try {
330 if ($DB) {
331 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
332 $DB->set_debug(0);
334 echo $OUTPUT->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
335 } catch (Exception $out_ex) {
336 // default exception handler MUST not throw any exceptions!!
337 // 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
338 // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
339 if (CLI_SCRIPT or AJAX_SCRIPT) {
340 // just ignore the error and send something back using the safest method
341 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
342 } else {
343 echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
344 $outinfo = get_exception_info($out_ex);
345 echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
350 exit(1); // General error code
354 * Default error handler, prevents some white screens.
355 * @param int $errno
356 * @param string $errstr
357 * @param string $errfile
358 * @param int $errline
359 * @param array $errcontext
360 * @return bool false means use default error handler
362 function default_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
363 if ($errno == 4096) {
364 //fatal catchable error
365 throw new coding_exception('PHP catchable fatal error', $errstr);
367 return false;
371 * Unconditionally abort all database transactions, this function
372 * should be called from exception handlers only.
373 * @return void
375 function abort_all_db_transactions() {
376 global $CFG, $DB, $SCRIPT;
378 // default exception handler MUST not throw any exceptions!!
380 if ($DB && $DB->is_transaction_started()) {
381 error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
382 // note: transaction blocks should never change current $_SESSION
383 $DB->force_transaction_rollback();
388 * This function encapsulates the tests for whether an exception was thrown in
389 * early init -- either during setup.php or during init of $OUTPUT.
391 * If another exception is thrown then, and if we do not take special measures,
392 * we would just get a very cryptic message "Exception thrown without a stack
393 * frame in Unknown on line 0". That makes debugging very hard, so we do take
394 * special measures in default_exception_handler, with the help of this function.
396 * @param array $backtrace the stack trace to analyse.
397 * @return boolean whether the stack trace is somewhere in output initialisation.
399 function is_early_init($backtrace) {
400 $dangerouscode = array(
401 array('function' => 'header', 'type' => '->'),
402 array('class' => 'bootstrap_renderer'),
403 array('file' => dirname(__FILE__).'/setup.php'),
405 foreach ($backtrace as $stackframe) {
406 foreach ($dangerouscode as $pattern) {
407 $matches = true;
408 foreach ($pattern as $property => $value) {
409 if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
410 $matches = false;
413 if ($matches) {
414 return true;
418 return false;
422 * Abort execution by throwing of a general exception,
423 * default exception handler displays the error message in most cases.
425 * @param string $errorcode The name of the language string containing the error message.
426 * Normally this should be in the error.php lang file.
427 * @param string $module The language file to get the error message from.
428 * @param string $link The url where the user will be prompted to continue.
429 * If no url is provided the user will be directed to the site index page.
430 * @param object $a Extra words and phrases that might be required in the error string
431 * @param string $debuginfo optional debugging information
432 * @return void, always throws exception!
434 function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
435 throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
439 * Returns detailed information about specified exception.
440 * @param exception $ex
441 * @return object
443 function get_exception_info($ex) {
444 global $CFG, $DB, $SESSION;
446 if ($ex instanceof moodle_exception) {
447 $errorcode = $ex->errorcode;
448 $module = $ex->module;
449 $a = $ex->a;
450 $link = $ex->link;
451 $debuginfo = $ex->debuginfo;
452 } else {
453 $errorcode = 'generalexceptionmessage';
454 $module = 'error';
455 $a = $ex->getMessage();
456 $link = '';
457 $debuginfo = null;
460 $backtrace = $ex->getTrace();
461 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
462 array_unshift($backtrace, $place);
464 // Be careful, no guarantee moodlelib.php is loaded.
465 if (empty($module) || $module == 'moodle' || $module == 'core') {
466 $module = 'error';
468 if (function_exists('get_string_manager')) {
469 if (get_string_manager()->string_exists($errorcode, $module)) {
470 $message = get_string($errorcode, $module, $a);
471 } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
472 // Search in moodle file if error specified - needed for backwards compatibility
473 $message = get_string($errorcode, 'moodle', $a);
474 } else {
475 $message = $module . '/' . $errorcode;
477 } else {
478 $message = $module . '/' . $errorcode;
481 // Be careful, no guarantee weblib.php is loaded.
482 if (function_exists('clean_text')) {
483 $message = clean_text($message);
484 } else {
485 $message = htmlspecialchars($message);
488 if (!empty($CFG->errordocroot)) {
489 $errordoclink = $CFG->errordocroot . '/en/';
490 } else {
491 $errordoclink = get_docs_url();
494 if ($module === 'error') {
495 $modulelink = 'moodle';
496 } else {
497 $modulelink = $module;
499 $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
501 if (empty($link)) {
502 if (!empty($SESSION->fromurl)) {
503 $link = $SESSION->fromurl;
504 unset($SESSION->fromurl);
505 } else {
506 $link = $CFG->wwwroot .'/';
510 // when printing an error the continue button should never link offsite
511 if (stripos($link, $CFG->wwwroot) === false &&
512 stripos($link, $CFG->httpswwwroot) === false) {
513 $link = $CFG->wwwroot.'/';
516 $info = new stdClass();
517 $info->message = $message;
518 $info->errorcode = $errorcode;
519 $info->backtrace = $backtrace;
520 $info->link = $link;
521 $info->moreinfourl = $moreinfourl;
522 $info->a = $a;
523 $info->debuginfo = $debuginfo;
525 return $info;
529 * Returns the Moodle Docs URL in the users language
531 * @global object
532 * @param string $path the end of the URL.
533 * @return string The MoodleDocs URL in the user's language. for example {@link http://docs.moodle.org/en/ http://docs.moodle.org/en/$path}
535 function get_docs_url($path=null) {
536 global $CFG;
537 // Check that $CFG->release has been set up, during installation it won't be.
538 if (empty($CFG->release)) {
539 // It's not there yet so look at version.php
540 include($CFG->dirroot.'/version.php');
541 } else {
542 // We can use $CFG->release and avoid having to include version.php
543 $release = $CFG->release;
545 // Attempt to match the branch from the release
546 if (preg_match('/^(.)\.(.)/', $release, $matches)) {
547 // We should ALWAYS get here
548 $branch = $matches[1].$matches[2];
549 } else {
550 // We should never get here but in case we do lets set $branch to .
551 // the smart one's will know that this is the current directory
552 // and the smarter ones will know that there is some smart matching
553 // that will ensure people end up at the latest version of the docs.
554 $branch = '.';
556 if (!empty($CFG->docroot)) {
557 return $CFG->docroot . '/' . $branch . '/' . current_language() . '/' . $path;
558 } else {
559 return 'http://docs.moodle.org/'. $branch . '/en/' . $path;
564 * Formats a backtrace ready for output.
566 * @param array $callers backtrace array, as returned by debug_backtrace().
567 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
568 * @return string formatted backtrace, ready for output.
570 function format_backtrace($callers, $plaintext = false) {
571 // do not use $CFG->dirroot because it might not be available in destructors
572 $dirroot = dirname(dirname(__FILE__));
574 if (empty($callers)) {
575 return '';
578 $from = $plaintext ? '' : '<ul style="text-align: left">';
579 foreach ($callers as $caller) {
580 if (!isset($caller['line'])) {
581 $caller['line'] = '?'; // probably call_user_func()
583 if (!isset($caller['file'])) {
584 $caller['file'] = 'unknownfile'; // probably call_user_func()
586 $from .= $plaintext ? '* ' : '<li>';
587 $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
588 if (isset($caller['function'])) {
589 $from .= ': call to ';
590 if (isset($caller['class'])) {
591 $from .= $caller['class'] . $caller['type'];
593 $from .= $caller['function'] . '()';
594 } else if (isset($caller['exception'])) {
595 $from .= ': '.$caller['exception'].' thrown';
597 $from .= $plaintext ? "\n" : '</li>';
599 $from .= $plaintext ? '' : '</ul>';
601 return $from;
605 * This function makes the return value of ini_get consistent if you are
606 * setting server directives through the .htaccess file in apache.
608 * Current behavior for value set from php.ini On = 1, Off = [blank]
609 * Current behavior for value set from .htaccess On = On, Off = Off
610 * Contributed by jdell @ unr.edu
612 * @param string $ini_get_arg The argument to get
613 * @return bool True for on false for not
615 function ini_get_bool($ini_get_arg) {
616 $temp = ini_get($ini_get_arg);
618 if ($temp == '1' or strtolower($temp) == 'on') {
619 return true;
621 return false;
625 * This function verifies the sanity of PHP configuration
626 * and stops execution if anything critical found.
628 function setup_validate_php_configuration() {
629 // this must be very fast - no slow checks here!!!
631 if (ini_get_bool('register_globals')) {
632 print_error('globalswarning', 'admin');
634 if (ini_get_bool('session.auto_start')) {
635 print_error('sessionautostartwarning', 'admin');
637 if (ini_get_bool('magic_quotes_runtime')) {
638 print_error('fatalmagicquotesruntime', 'admin');
643 * Initialise global $CFG variable
644 * @return void
646 function initialise_cfg() {
647 global $CFG, $DB;
649 try {
650 if ($DB) {
651 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
652 foreach ($localcfg as $name=>$value) {
653 if (property_exists($CFG, $name)) {
654 // config.php settings always take precedence
655 continue;
657 $CFG->{$name} = $value;
660 } catch (dml_exception $e) {
661 // most probably empty db, going to install soon
666 * Initialises $FULLME and friends. Private function. Should only be called from
667 * setup.php.
669 function initialise_fullme() {
670 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
672 // Detect common config error.
673 if (substr($CFG->wwwroot, -1) == '/') {
674 print_error('wwwrootslash', 'error');
677 if (CLI_SCRIPT) {
678 initialise_fullme_cli();
679 return;
682 $rurl = setup_get_remote_url();
683 $wwwroot = parse_url($CFG->wwwroot.'/');
685 if (empty($rurl['host'])) {
686 // missing host in request header, probably not a real browser, let's ignore them
688 } else if (!empty($CFG->reverseproxy)) {
689 // $CFG->reverseproxy specifies if reverse proxy server used
690 // Used in load balancing scenarios.
691 // Do not abuse this to try to solve lan/wan access problems!!!!!
693 } else {
694 if (($rurl['host'] !== $wwwroot['host']) or (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port'])) {
695 // Explain the problem and redirect them to the right URL
696 if (!defined('NO_MOODLE_COOKIES')) {
697 define('NO_MOODLE_COOKIES', true);
699 redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
703 // Check that URL is under $CFG->wwwroot.
704 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
705 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
706 } else {
707 // Probably some weird external script
708 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
709 return;
712 // $CFG->sslproxy specifies if external SSL appliance is used
713 // (That is, the Moodle server uses http, with an external box translating everything to https).
714 if (empty($CFG->sslproxy)) {
715 if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
716 print_error('sslonlyaccess', 'error');
718 } else {
719 if ($wwwroot['scheme'] !== 'https') {
720 throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
722 $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
725 // hopefully this will stop all those "clever" admins trying to set up moodle
726 // with two different addresses in intranet and Internet
727 if (!empty($CFG->reverseproxy) && $rurl['host'] === $wwwroot['host']) {
728 print_error('reverseproxyabused', 'error');
731 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
732 if (!empty($wwwroot['port'])) {
733 $hostandport .= ':'.$wwwroot['port'];
736 $FULLSCRIPT = $hostandport . $rurl['path'];
737 $FULLME = $hostandport . $rurl['fullpath'];
738 $ME = $rurl['fullpath'];
742 * Initialises $FULLME and friends for command line scripts.
743 * This is a private method for use by initialise_fullme.
745 function initialise_fullme_cli() {
746 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
748 // Urls do not make much sense in CLI scripts
749 $backtrace = debug_backtrace();
750 $topfile = array_pop($backtrace);
751 $topfile = realpath($topfile['file']);
752 $dirroot = realpath($CFG->dirroot);
754 if (strpos($topfile, $dirroot) !== 0) {
755 // Probably some weird external script
756 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
757 } else {
758 $relativefile = substr($topfile, strlen($dirroot));
759 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
760 $SCRIPT = $FULLSCRIPT = $relativefile;
761 $FULLME = $ME = null;
766 * Get the URL that PHP/the web server thinks it is serving. Private function
767 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
768 * @return array in the same format that parse_url returns, with the addition of
769 * a 'fullpath' element, which includes any slasharguments path.
771 function setup_get_remote_url() {
772 $rurl = array();
773 if (isset($_SERVER['HTTP_HOST'])) {
774 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
775 } else {
776 $rurl['host'] = null;
778 $rurl['port'] = $_SERVER['SERVER_PORT'];
779 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
780 $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ? 'http' : 'https';
782 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
783 //Apache server
784 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
786 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
787 //IIS - needs a lot of tweaking to make it work
788 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
790 // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
791 // since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
792 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
794 if ($_SERVER['QUERY_STRING'] != '') {
795 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
797 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
799 /* NOTE: following servers are not fully tested! */
801 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
802 //lighttpd - not officially supported
803 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
805 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
806 //nginx - not officially supported
807 if (!isset($_SERVER['SCRIPT_NAME'])) {
808 die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
810 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
812 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
813 //cherokee - not officially supported
814 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
816 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
817 //zeus - not officially supported
818 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
820 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
821 //LiteSpeed - not officially supported
822 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
824 } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
825 //obscure name found on some servers - this is definitely not supported
826 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
828 } else {
829 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
832 // sanitize the url a bit more, the encoding style may be different in vars above
833 $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
834 $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);
836 return $rurl;
840 * Initializes our performance info early.
842 * Pairs up with get_performance_info() which is actually
843 * in moodlelib.php. This function is here so that we can
844 * call it before all the libs are pulled in.
846 * @uses $PERF
848 function init_performance_info() {
850 global $PERF, $CFG, $USER;
852 $PERF = new stdClass();
853 $PERF->logwrites = 0;
854 if (function_exists('microtime')) {
855 $PERF->starttime = microtime();
857 if (function_exists('memory_get_usage')) {
858 $PERF->startmemory = memory_get_usage();
860 if (function_exists('posix_times')) {
861 $PERF->startposixtimes = posix_times();
866 * Indicates whether we are in the middle of the initial Moodle install.
868 * Very occasionally it is necessary avoid running certain bits of code before the
869 * Moodle installation has completed. The installed flag is set in admin/index.php
870 * after Moodle core and all the plugins have been installed, but just before
871 * the person doing the initial install is asked to choose the admin password.
873 * @return boolean true if the initial install is not complete.
875 function during_initial_install() {
876 global $CFG;
877 return empty($CFG->rolesactive);
881 * Function to raise the memory limit to a new value.
882 * Will respect the memory limit if it is higher, thus allowing
883 * settings in php.ini, apache conf or command line switches
884 * to override it.
886 * The memory limit should be expressed with a constant
887 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
888 * It is possible to use strings or integers too (eg:'128M').
890 * @param mixed $newlimit the new memory limit
891 * @return bool success
893 function raise_memory_limit($newlimit) {
894 global $CFG;
896 if ($newlimit == MEMORY_UNLIMITED) {
897 ini_set('memory_limit', -1);
898 return true;
900 } else if ($newlimit == MEMORY_STANDARD) {
901 if (PHP_INT_SIZE > 4) {
902 $newlimit = get_real_size('128M'); // 64bit needs more memory
903 } else {
904 $newlimit = get_real_size('96M');
907 } else if ($newlimit == MEMORY_EXTRA) {
908 if (PHP_INT_SIZE > 4) {
909 $newlimit = get_real_size('384M'); // 64bit needs more memory
910 } else {
911 $newlimit = get_real_size('256M');
913 if (!empty($CFG->extramemorylimit)) {
914 $extra = get_real_size($CFG->extramemorylimit);
915 if ($extra > $newlimit) {
916 $newlimit = $extra;
920 } else if ($newlimit == MEMORY_HUGE) {
921 $newlimit = get_real_size('2G');
923 } else {
924 $newlimit = get_real_size($newlimit);
927 if ($newlimit <= 0) {
928 debugging('Invalid memory limit specified.');
929 return false;
932 $cur = ini_get('memory_limit');
933 if (empty($cur)) {
934 // if php is compiled without --enable-memory-limits
935 // apparently memory_limit is set to ''
936 $cur = 0;
937 } else {
938 if ($cur == -1){
939 return true; // unlimited mem!
941 $cur = get_real_size($cur);
944 if ($newlimit > $cur) {
945 ini_set('memory_limit', $newlimit);
946 return true;
948 return false;
952 * Function to reduce the memory limit to a new value.
953 * Will respect the memory limit if it is lower, thus allowing
954 * settings in php.ini, apache conf or command line switches
955 * to override it
957 * The memory limit should be expressed with a string (eg:'64M')
959 * @param string $newlimit the new memory limit
960 * @return bool
962 function reduce_memory_limit($newlimit) {
963 if (empty($newlimit)) {
964 return false;
966 $cur = ini_get('memory_limit');
967 if (empty($cur)) {
968 // if php is compiled without --enable-memory-limits
969 // apparently memory_limit is set to ''
970 $cur = 0;
971 } else {
972 if ($cur == -1){
973 return true; // unlimited mem!
975 $cur = get_real_size($cur);
978 $new = get_real_size($newlimit);
979 // -1 is smaller, but it means unlimited
980 if ($new < $cur && $new != -1) {
981 ini_set('memory_limit', $newlimit);
982 return true;
984 return false;
988 * Converts numbers like 10M into bytes.
990 * @param string $size The size to be converted
991 * @return int
993 function get_real_size($size = 0) {
994 if (!$size) {
995 return 0;
997 $scan = array();
998 $scan['GB'] = 1073741824;
999 $scan['Gb'] = 1073741824;
1000 $scan['G'] = 1073741824;
1001 $scan['MB'] = 1048576;
1002 $scan['Mb'] = 1048576;
1003 $scan['M'] = 1048576;
1004 $scan['m'] = 1048576;
1005 $scan['KB'] = 1024;
1006 $scan['Kb'] = 1024;
1007 $scan['K'] = 1024;
1008 $scan['k'] = 1024;
1010 while (list($key) = each($scan)) {
1011 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
1012 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
1013 break;
1016 return $size;
1020 * Try to disable all output buffering and purge
1021 * all headers.
1023 * @private to be called only from lib/setup.php !
1024 * @return void
1026 function disable_output_buffering() {
1027 $olddebug = error_reporting(0);
1029 // disable compression, it would prevent closing of buffers
1030 if (ini_get_bool('zlib.output_compression')) {
1031 ini_set('zlib.output_compression', 'Off');
1034 // try to flush everything all the time
1035 ob_implicit_flush(true);
1037 // close all buffers if possible and discard any existing output
1038 // this can actually work around some whitespace problems in config.php
1039 while(ob_get_level()) {
1040 if (!ob_end_clean()) {
1041 // prevent infinite loop when buffer can not be closed
1042 break;
1046 error_reporting($olddebug);
1050 * Check whether a major upgrade is needed. That is defined as an upgrade that
1051 * changes something really fundamental in the database, so nothing can possibly
1052 * work until the database has been updated, and that is defined by the hard-coded
1053 * version number in this function.
1055 function redirect_if_major_upgrade_required() {
1056 global $CFG;
1057 $lastmajordbchanges = 2010111700;
1058 if (empty($CFG->version) or (int)$CFG->version < $lastmajordbchanges or
1059 during_initial_install() or !empty($CFG->adminsetuppending)) {
1060 try {
1061 @session_get_instance()->terminate_current();
1062 } catch (Exception $e) {
1063 // Ignore any errors, redirect to upgrade anyway.
1065 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
1066 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1067 @header('Location: ' . $url);
1068 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
1069 exit;
1074 * Function to check if a directory exists and by default create it if not exists.
1076 * Previously this was accepting paths only from dataroot, but we now allow
1077 * files outside of dataroot if you supply custom paths for some settings in config.php.
1078 * This function does not verify that the directory is writable.
1080 * NOTE: this function uses current file stat cache,
1081 * please use clearstatcache() before this if you expect that the
1082 * directories may have been removed recently from a different request.
1084 * @param string $dir absolute directory path
1085 * @param boolean $create directory if does not exist
1086 * @param boolean $recursive create directory recursively
1087 * @return boolean true if directory exists or created, false otherwise
1089 function check_dir_exists($dir, $create = true, $recursive = true) {
1090 global $CFG;
1092 umask(0000); // just in case some evil code changed it
1094 if (is_dir($dir)) {
1095 return true;
1098 if (!$create) {
1099 return false;
1102 return mkdir($dir, $CFG->directorypermissions, $recursive);
1106 * Create a directory and make sure it is writable.
1108 * @private
1109 * @param string $dir the full path of the directory to be created
1110 * @param bool $exceptiononerror throw exception if error encountered
1111 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1113 function make_writable_directory($dir, $exceptiononerror = true) {
1114 global $CFG;
1116 if (file_exists($dir) and !is_dir($dir)) {
1117 if ($exceptiononerror) {
1118 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1119 } else {
1120 return false;
1124 umask(0000); // just in case some evil code changed it
1126 if (!file_exists($dir)) {
1127 if (!mkdir($dir, $CFG->directorypermissions, true)) {
1128 if ($exceptiononerror) {
1129 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1130 } else {
1131 return false;
1136 if (!is_writable($dir)) {
1137 if ($exceptiononerror) {
1138 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1139 } else {
1140 return false;
1144 return $dir;
1148 * Protect a directory from web access.
1149 * Could be extended in the future to support other mechanisms (e.g. other webservers).
1151 * @private
1152 * @param string $dir the full path of the directory to be protected
1154 function protect_directory($dir) {
1155 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1156 if (!file_exists("$dir/.htaccess")) {
1157 if ($handle = fopen("$dir/.htaccess", 'w')) { // For safety
1158 @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");
1159 @fclose($handle);
1165 * Create a directory under dataroot and make sure it is writable.
1166 * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
1168 * @param string $directory the full path of the directory to be created under $CFG->dataroot
1169 * @param bool $exceptiononerror throw exception if error encountered
1170 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1172 function make_upload_directory($directory, $exceptiononerror = true) {
1173 global $CFG;
1175 if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1176 debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1178 } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
1179 debugging('Use make_cache_directory() for creation of chache directory and $CFG->cachedir to get the location.');
1182 protect_directory($CFG->dataroot);
1183 return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1187 * Create a directory under tempdir and make sure it is writable.
1188 * Temporary files should be used during the current request only!
1190 * @param string $directory the full path of the directory to be created under $CFG->tempdir
1191 * @param bool $exceptiononerror throw exception if error encountered
1192 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1194 function make_temp_directory($directory, $exceptiononerror = true) {
1195 global $CFG;
1196 if ($CFG->tempdir !== "$CFG->dataroot/temp") {
1197 check_dir_exists($CFG->tempdir, true, true);
1198 protect_directory($CFG->tempdir);
1199 } else {
1200 protect_directory($CFG->dataroot);
1202 return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1206 * Create a directory under cachedir and make sure it is writable.
1208 * @param string $directory the full path of the directory to be created under $CFG->cachedir
1209 * @param bool $exceptiononerror throw exception if error encountered
1210 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1212 function make_cache_directory($directory, $exceptiononerror = true) {
1213 global $CFG;
1214 if ($CFG->cachedir !== "$CFG->dataroot/cache") {
1215 check_dir_exists($CFG->cachedir, true, true);
1216 protect_directory($CFG->cachedir);
1217 } else {
1218 protect_directory($CFG->dataroot);
1220 return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1224 function init_memcached() {
1225 global $CFG, $MCACHE;
1227 include_once($CFG->libdir . '/memcached.class.php');
1228 $MCACHE = new memcached;
1229 if ($MCACHE->status()) {
1230 return true;
1232 unset($MCACHE);
1233 return false;
1236 function init_eaccelerator() {
1237 global $CFG, $MCACHE;
1239 include_once($CFG->libdir . '/eaccelerator.class.php');
1240 $MCACHE = new eaccelerator;
1241 if ($MCACHE->status()) {
1242 return true;
1244 unset($MCACHE);
1245 return false;
1249 * Checks if current user is a web crawler.
1251 * This list can not be made complete, this is not a security
1252 * restriction, we make the list only to help these sites
1253 * especially when automatic guest login is disabled.
1255 * If admin needs security they should enable forcelogin
1256 * and disable guest access!!
1258 * @return bool
1260 function is_web_crawler() {
1261 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
1262 if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
1263 return true;
1264 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) { // Google
1265 return true;
1266 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yahoo! Slurp') !== false ) { // Yahoo
1267 return true;
1268 } else if (strpos($_SERVER['HTTP_USER_AGENT'], '[ZSEBOT]') !== false ) { // Zoomspider
1269 return true;
1270 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSNBOT') !== false ) { // MSN Search
1271 return true;
1272 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yandex') !== false ) {
1273 return true;
1274 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'AltaVista') !== false ) {
1275 return true;
1278 return false;
1282 * This class solves the problem of how to initialise $OUTPUT.
1284 * The problem is caused be two factors
1285 * <ol>
1286 * <li>On the one hand, we cannot be sure when output will start. In particular,
1287 * an error, which needs to be displayed, could be thrown at any time.</li>
1288 * <li>On the other hand, we cannot be sure when we will have all the information
1289 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1290 * (potentially) depends on the current course, course categories, and logged in user.
1291 * It also depends on whether the current page requires HTTPS.</li>
1292 * </ol>
1294 * So, it is hard to find a single natural place during Moodle script execution,
1295 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1296 * adopt the following strategy
1297 * <ol>
1298 * <li>We will initialise $OUTPUT the first time it is used.</li>
1299 * <li>If, after $OUTPUT has been initialised, the script tries to change something
1300 * that $OUTPUT depends on, we throw an exception making it clear that the script
1301 * did something wrong.
1302 * </ol>
1304 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1305 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1306 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1307 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1309 * Note that this class is used before lib/outputlib.php has been loaded, so we
1310 * must be careful referring to classes/functions from there, they may not be
1311 * defined yet, and we must avoid fatal errors.
1313 * @copyright 2009 Tim Hunt
1314 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1315 * @since Moodle 2.0
1317 class bootstrap_renderer {
1319 * Handles re-entrancy. Without this, errors or debugging output that occur
1320 * during the initialisation of $OUTPUT, cause infinite recursion.
1321 * @var boolean
1323 protected $initialising = false;
1326 * Have we started output yet?
1327 * @return boolean true if the header has been printed.
1329 public function has_started() {
1330 return false;
1334 * Constructor - to be used by core code only.
1335 * @param $method
1336 * @param $arguments
1337 * @return string
1339 public function __call($method, $arguments) {
1340 global $OUTPUT, $PAGE;
1342 $recursing = false;
1343 if ($method == 'notification') {
1344 // Catch infinite recursion caused by debugging output during print_header.
1345 $backtrace = debug_backtrace();
1346 array_shift($backtrace);
1347 array_shift($backtrace);
1348 $recursing = is_early_init($backtrace);
1351 $earlymethods = array(
1352 'fatal_error' => 'early_error',
1353 'notification' => 'early_notification',
1356 // If lib/outputlib.php has been loaded, call it.
1357 if (!empty($PAGE) && !$recursing) {
1358 if (array_key_exists($method, $earlymethods)) {
1359 //prevent PAGE->context warnings - exceptions might appear before we set any context
1360 $PAGE->set_context(null);
1362 $PAGE->initialise_theme_and_output();
1363 return call_user_func_array(array($OUTPUT, $method), $arguments);
1366 $this->initialising = true;
1368 // Too soon to initialise $OUTPUT, provide a couple of key methods.
1369 if (array_key_exists($method, $earlymethods)) {
1370 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1373 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1377 * Returns nicely formatted error message in a div box.
1378 * @static
1379 * @param string $message error message
1380 * @param string $moreinfourl (ignored in early errors)
1381 * @param string $link (ignored in early errors)
1382 * @param array $backtrace
1383 * @param string $debuginfo
1384 * @return string
1386 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1387 global $CFG;
1389 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1390 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1391 width: 80%; -moz-border-radius: 20px; padding: 15px">
1392 ' . $message . '
1393 </div>';
1394 if (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER) {
1395 if (!empty($debuginfo)) {
1396 $debuginfo = s($debuginfo); // removes all nasty JS
1397 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1398 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
1400 if (!empty($backtrace)) {
1401 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1405 return $content;
1409 * This function should only be called by this class, or from exception handlers
1410 * @static
1411 * @param string $message error message
1412 * @param string $moreinfourl (ignored in early errors)
1413 * @param string $link (ignored in early errors)
1414 * @param array $backtrace
1415 * @param string $debuginfo extra information for developers
1416 * @return string
1418 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1419 global $CFG;
1421 if (CLI_SCRIPT) {
1422 echo "!!! $message !!!\n";
1423 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1424 if (!empty($debuginfo)) {
1425 echo "\nDebug info: $debuginfo";
1427 if (!empty($backtrace)) {
1428 echo "\nStack trace: " . format_backtrace($backtrace, true);
1431 return;
1433 } else if (AJAX_SCRIPT) {
1434 $e = new stdClass();
1435 $e->error = $message;
1436 $e->stacktrace = NULL;
1437 $e->debuginfo = NULL;
1438 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1439 if (!empty($debuginfo)) {
1440 $e->debuginfo = $debuginfo;
1442 if (!empty($backtrace)) {
1443 $e->stacktrace = format_backtrace($backtrace, true);
1446 @header('Content-Type: application/json; charset=utf-8');
1447 echo json_encode($e);
1448 return;
1451 // In the name of protocol correctness, monitoring and performance
1452 // profiling, set the appropriate error headers for machine consumption
1453 if (isset($_SERVER['SERVER_PROTOCOL'])) {
1454 // Avoid it with cron.php. Note that we assume it's HTTP/1.x
1455 // The 503 ode here means our Moodle does not work at all, the error happened too early
1456 @header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
1459 // better disable any caching
1460 @header('Content-Type: text/html; charset=utf-8');
1461 @header('Cache-Control: no-store, no-cache, must-revalidate');
1462 @header('Cache-Control: post-check=0, pre-check=0', false);
1463 @header('Pragma: no-cache');
1464 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1465 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1467 if (function_exists('get_string')) {
1468 $strerror = get_string('error');
1469 } else {
1470 $strerror = 'Error';
1473 $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
1475 return self::plain_page($strerror, $content);
1479 * Early notification message
1480 * @static
1481 * @param $message
1482 * @param string $classes usually notifyproblem or notifysuccess
1483 * @return string
1485 public static function early_notification($message, $classes = 'notifyproblem') {
1486 return '<div class="' . $classes . '">' . $message . '</div>';
1490 * Page should redirect message.
1491 * @static
1492 * @param $encodedurl redirect url
1493 * @return string
1495 public static function plain_redirect_message($encodedurl) {
1496 $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
1497 $encodedurl .'">'. get_string('continue') .'</a></div>';
1498 return self::plain_page(get_string('redirect'), $message);
1502 * Early redirection page, used before full init of $PAGE global
1503 * @static
1504 * @param $encodedurl redirect url
1505 * @param $message redirect message
1506 * @param $delay time in seconds
1507 * @return string redirect page
1509 public static function early_redirect_message($encodedurl, $message, $delay) {
1510 $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
1511 $content = self::early_error_content($message, null, null, null);
1512 $content .= self::plain_redirect_message($encodedurl);
1514 return self::plain_page(get_string('redirect'), $content, $meta);
1518 * Output basic html page.
1519 * @static
1520 * @param $title page title
1521 * @param $content page content
1522 * @param string $meta meta tag
1523 * @return string html page
1525 protected static function plain_page($title, $content, $meta = '') {
1526 if (function_exists('get_string') && function_exists('get_html_lang')) {
1527 $htmllang = get_html_lang();
1528 } else {
1529 $htmllang = '';
1532 return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1533 <html xmlns="http://www.w3.org/1999/xhtml" ' . $htmllang . '>
1534 <head>
1535 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1536 '.$meta.'
1537 <title>' . $title . '</title>
1538 </head><body>' . $content . '</body></html>';