3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
20 * These functions are required very early in the Moodle
21 * setup process, before any of the main libraries are
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();
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);
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);
57 * Simple class. It is usually used instead of stdClass because it looks
58 * more familiar to Java developers ;-) Do not use for type checking of
59 * function parameters. Please use stdClass instead.
63 * @copyright 2009 Petr Skoda {@link http://skodak.org}
64 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
65 * @deprecated since 2.0
67 class object extends stdClass
{};
70 * Base Moodle Exception class
72 * Although this class is defined here, you cannot throw a moodle_exception until
73 * after moodlelib.php has been included (which will happen very soon).
77 * @copyright 2008 Petr Skoda {@link http://skodak.org}
78 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
80 class moodle_exception
extends Exception
{
89 * @param string $errorcode The name of the string from error.php to print
90 * @param string $module name of module
91 * @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.
92 * @param object $a Extra words and phrases that might be required in the error string
93 * @param string $debuginfo optional debugging information
95 function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
96 if (empty($module) ||
$module == 'moodle' ||
$module == 'core') {
100 $this->errorcode
= $errorcode;
101 $this->module
= $module;
104 $this->debuginfo
= $debuginfo;
106 if (get_string_manager()->string_exists($errorcode, $module)) {
107 $message = get_string($errorcode, $module, $a);
109 $message = $module . '/' . $errorcode;
112 parent
::__construct($message, 0);
117 * Course/activity access exception.
119 * This exception is thrown from require_login()
123 * @copyright 2010 Petr Skoda {@link http://skodak.org}
124 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
126 class require_login_exception
extends moodle_exception
{
127 function __construct($debuginfo) {
128 parent
::__construct('requireloginerror', 'error', '', NULL, $debuginfo);
133 * Web service parameter exception class
135 * This exception must be thrown to the web service client when a web service parameter is invalid
136 * The error string is gotten from webservice.php
138 class webservice_parameter_exception
extends moodle_exception
{
141 * @param string $errorcode The name of the string from webservice.php to print
142 * @param string $a The name of the parameter
144 function __construct($errorcode=null, $a = '') {
145 parent
::__construct($errorcode, 'webservice', '', $a, null);
150 * Exceptions indicating user does not have permissions to do something
151 * and the execution can not continue.
155 * @copyright 2009 Petr Skoda {@link http://skodak.org}
156 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
158 class required_capability_exception
extends moodle_exception
{
159 function __construct($context, $capability, $errormessage, $stringfile) {
160 $capabilityname = get_capability_string($capability);
161 if ($context->contextlevel
== CONTEXT_MODULE
and preg_match('/:view$/', $capability)) {
162 // 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
163 $paranetcontext = get_context_instance_by_id(get_parent_contextid($context));
164 $link = get_context_url($paranetcontext);
166 $link = get_context_url($context);
168 parent
::__construct($errormessage, $stringfile, $link, $capabilityname);
173 * Exception indicating programming error, must be fixed by a programer. For example
174 * a core API might throw this type of exception if a plugin calls it incorrectly.
178 * @copyright 2008 Petr Skoda {@link http://skodak.org}
179 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
181 class coding_exception
extends moodle_exception
{
184 * @param string $hint short description of problem
185 * @param string $debuginfo detailed information how to fix problem
187 function __construct($hint, $debuginfo=null) {
188 parent
::__construct('codingerror', 'debug', '', $hint, $debuginfo);
193 * Exception indicating malformed parameter problem.
194 * This exception is not supposed to be thrown when processing
195 * user submitted data in forms. It is more suitable
196 * for WS and other low level stuff.
200 * @copyright 2009 Petr Skoda {@link http://skodak.org}
201 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
203 class invalid_parameter_exception
extends moodle_exception
{
206 * @param string $debuginfo some detailed information
208 function __construct($debuginfo=null) {
209 parent
::__construct('invalidparameter', 'debug', '', null, $debuginfo);
214 * Exception indicating malformed response problem.
215 * This exception is not supposed to be thrown when processing
216 * user submitted data in forms. It is more suitable
217 * for WS and other low level stuff.
219 class invalid_response_exception
extends moodle_exception
{
222 * @param string $debuginfo some detailed information
224 function __construct($debuginfo=null) {
225 parent
::__construct('invalidresponse', 'debug', '', null, $debuginfo);
230 * An exception that indicates something really weird happened. For example,
231 * if you do switch ($context->contextlevel), and have one case for each
232 * CONTEXT_... constant. You might throw an invalid_state_exception in the
233 * default case, to just in case something really weird is going on, and
234 * $context->contextlevel is invalid - rather than ignoring this possibility.
238 * @copyright 2009 onwards Martin Dougiamas {@link http://moodle.com}
239 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
241 class invalid_state_exception
extends moodle_exception
{
244 * @param string $hint short description of problem
245 * @param string $debuginfo optional more detailed information
247 function __construct($hint, $debuginfo=null) {
248 parent
::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
253 * An exception that indicates incorrect permissions in $CFG->dataroot
257 * @copyright 2010 Petr Skoda {@link http://skodak.org}
258 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
260 class invalid_dataroot_permissions
extends moodle_exception
{
263 * @param string $debuginfo optional more detailed information
265 function __construct($debuginfo = NULL) {
266 parent
::__construct('invaliddatarootpermissions', 'error', '', NULL, $debuginfo);
271 * An exception that indicates that file can not be served
275 * @copyright 2010 Petr Skoda {@link http://skodak.org}
276 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
278 class file_serving_exception
extends moodle_exception
{
281 * @param string $debuginfo optional more detailed information
283 function __construct($debuginfo = NULL) {
284 parent
::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
289 * Default exception handler, uncaught exceptions are equivalent to error() in 1.9 and earlier
291 * @param Exception $ex
292 * @return void -does not return. Terminates execution!
294 function default_exception_handler($ex) {
295 global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION;
297 // detect active db transactions, rollback and log as error
298 abort_all_db_transactions();
300 if (($ex instanceof required_capability_exception
) && !CLI_SCRIPT
&& !AJAX_SCRIPT
&& !empty($CFG->autologinguests
) && !empty($USER->autologinguest
)) {
301 $SESSION->wantsurl
= $FULLME;
302 redirect(get_login_url());
305 $info = get_exception_info($ex);
307 if (debugging('', DEBUG_MINIMAL
)) {
308 $logerrmsg = "Default exception handler: ".$info->message
.' Debug: '.$info->debuginfo
."\n".format_backtrace($info->backtrace
, true);
309 error_log($logerrmsg);
312 if (is_early_init($info->backtrace
)) {
313 echo bootstrap_renderer
::early_error($info->message
, $info->moreinfourl
, $info->link
, $info->backtrace
, $info->debuginfo
);
317 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
320 echo $OUTPUT->fatal_error($info->message
, $info->moreinfourl
, $info->link
, $info->backtrace
, $info->debuginfo
);
321 } catch (Exception
$out_ex) {
322 // default exception handler MUST not throw any exceptions!!
323 // 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
324 // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
325 if (CLI_SCRIPT
or AJAX_SCRIPT
) {
326 // just ignore the error and send something back using the safest method
327 echo bootstrap_renderer
::early_error($info->message
, $info->moreinfourl
, $info->link
, $info->backtrace
, $info->debuginfo
);
329 echo bootstrap_renderer
::early_error_content($info->message
, $info->moreinfourl
, $info->link
, $info->backtrace
, $info->debuginfo
);
330 $outinfo = get_exception_info($out_ex);
331 echo bootstrap_renderer
::early_error_content($outinfo->message
, $outinfo->moreinfourl
, $outinfo->link
, $outinfo->backtrace
, $outinfo->debuginfo
);
336 exit(1); // General error code
340 * Default error handler, prevents some white screens.
342 * @param string $errstr
343 * @param string $errfile
344 * @param int $errline
345 * @param array $errcontext
346 * @return bool false means use default error handler
348 function default_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
349 if ($errno == 4096) {
350 //fatal catchable error
351 throw new coding_exception('PHP catchable fatal error', $errstr);
357 * Unconditionally abort all database transactions, this function
358 * should be called from exception handlers only.
361 function abort_all_db_transactions() {
362 global $CFG, $DB, $SCRIPT;
364 // default exception handler MUST not throw any exceptions!!
366 if ($DB && $DB->is_transaction_started()) {
367 error_log('Database transaction aborted automatically in ' . $CFG->dirroot
. $SCRIPT);
368 // note: transaction blocks should never change current $_SESSION
369 $DB->force_transaction_rollback();
374 * This function encapsulates the tests for whether an exception was thrown in
375 * early init -- either during setup.php or during init of $OUTPUT.
377 * If another exception is thrown then, and if we do not take special measures,
378 * we would just get a very cryptic message "Exception thrown without a stack
379 * frame in Unknown on line 0". That makes debugging very hard, so we do take
380 * special measures in default_exception_handler, with the help of this function.
382 * @param array $backtrace the stack trace to analyse.
383 * @return boolean whether the stack trace is somewhere in output initialisation.
385 function is_early_init($backtrace) {
386 $dangerouscode = array(
387 array('function' => 'header', 'type' => '->'),
388 array('class' => 'bootstrap_renderer'),
389 array('file' => dirname(__FILE__
).'/setup.php'),
391 foreach ($backtrace as $stackframe) {
392 foreach ($dangerouscode as $pattern) {
394 foreach ($pattern as $property => $value) {
395 if (!isset($stackframe[$property]) ||
$stackframe[$property] != $value) {
408 * Abort execution by throwing of a general exception,
409 * default exception handler displays the error message in most cases.
411 * @param string $errorcode The name of the language string containing the error message.
412 * Normally this should be in the error.php lang file.
413 * @param string $module The language file to get the error message from.
414 * @param string $link The url where the user will be prompted to continue.
415 * If no url is provided the user will be directed to the site index page.
416 * @param object $a Extra words and phrases that might be required in the error string
417 * @param string $debuginfo optional debugging information
418 * @return void, always throws exception!
420 function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
421 throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
425 * Returns detailed information about specified exception.
426 * @param exception $ex
429 function get_exception_info($ex) {
430 global $CFG, $DB, $SESSION;
432 if ($ex instanceof moodle_exception
) {
433 $errorcode = $ex->errorcode
;
434 $module = $ex->module
;
437 $debuginfo = $ex->debuginfo
;
439 $errorcode = 'generalexceptionmessage';
441 $a = $ex->getMessage();
446 $backtrace = $ex->getTrace();
447 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
448 array_unshift($backtrace, $place);
450 // Be careful, no guarantee moodlelib.php is loaded.
451 if (empty($module) ||
$module == 'moodle' ||
$module == 'core') {
454 if (function_exists('get_string_manager')) {
455 if (get_string_manager()->string_exists($errorcode, $module)) {
456 $message = get_string($errorcode, $module, $a);
457 } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
458 // Search in moodle file if error specified - needed for backwards compatibility
459 $message = get_string($errorcode, 'moodle', $a);
461 $message = $module . '/' . $errorcode;
464 $message = $module . '/' . $errorcode;
467 // Be careful, no guarantee weblib.php is loaded.
468 if (function_exists('clean_text')) {
469 $message = clean_text($message);
471 $message = htmlspecialchars($message);
474 if (!empty($CFG->errordocroot
)) {
475 $errordocroot = $CFG->errordocroot
;
476 } else if (!empty($CFG->docroot
)) {
477 $errordocroot = $CFG->docroot
;
479 $errordocroot = 'http://docs.moodle.org';
481 if ($module === 'error') {
482 $modulelink = 'moodle';
484 $modulelink = $module;
486 $moreinfourl = $errordocroot . '/en/error/' . $modulelink . '/' . $errorcode;
489 if (!empty($SESSION->fromurl
)) {
490 $link = $SESSION->fromurl
;
491 unset($SESSION->fromurl
);
493 $link = $CFG->wwwroot
.'/';
497 $info = new stdClass();
498 $info->message
= $message;
499 $info->errorcode
= $errorcode;
500 $info->backtrace
= $backtrace;
502 $info->moreinfourl
= $moreinfourl;
504 $info->debuginfo
= $debuginfo;
510 * Formats a backtrace ready for output.
512 * @param array $callers backtrace array, as returned by debug_backtrace().
513 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
514 * @return string formatted backtrace, ready for output.
516 function format_backtrace($callers, $plaintext = false) {
517 // do not use $CFG->dirroot because it might not be available in destructors
518 $dirroot = dirname(dirname(__FILE__
));
520 if (empty($callers)) {
524 $from = $plaintext ?
'' : '<ul style="text-align: left">';
525 foreach ($callers as $caller) {
526 if (!isset($caller['line'])) {
527 $caller['line'] = '?'; // probably call_user_func()
529 if (!isset($caller['file'])) {
530 $caller['file'] = 'unknownfile'; // probably call_user_func()
532 $from .= $plaintext ?
'* ' : '<li>';
533 $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
534 if (isset($caller['function'])) {
535 $from .= ': call to ';
536 if (isset($caller['class'])) {
537 $from .= $caller['class'] . $caller['type'];
539 $from .= $caller['function'] . '()';
540 } else if (isset($caller['exception'])) {
541 $from .= ': '.$caller['exception'].' thrown';
543 $from .= $plaintext ?
"\n" : '</li>';
545 $from .= $plaintext ?
'' : '</ul>';
551 * This function makes the return value of ini_get consistent if you are
552 * setting server directives through the .htaccess file in apache.
554 * Current behavior for value set from php.ini On = 1, Off = [blank]
555 * Current behavior for value set from .htaccess On = On, Off = Off
556 * Contributed by jdell @ unr.edu
558 * @param string $ini_get_arg The argument to get
559 * @return bool True for on false for not
561 function ini_get_bool($ini_get_arg) {
562 $temp = ini_get($ini_get_arg);
564 if ($temp == '1' or strtolower($temp) == 'on') {
571 * This function verifies the sanity of PHP configuration
572 * and stops execution if anything critical found.
574 function setup_validate_php_configuration() {
575 // this must be very fast - no slow checks here!!!
577 if (ini_get_bool('register_globals')) {
578 print_error('globalswarning', 'admin');
580 if (ini_get_bool('session.auto_start')) {
581 print_error('sessionautostartwarning', 'admin');
583 if (ini_get_bool('magic_quotes_runtime')) {
584 print_error('fatalmagicquotesruntime', 'admin');
589 * Initialise global $CFG variable
592 function initialise_cfg() {
597 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
598 foreach ($localcfg as $name=>$value) {
599 if (property_exists($CFG, $name)) {
600 // config.php settings always take precedence
603 $CFG->{$name} = $value;
606 } catch (dml_read_exception
$e) {
607 // most probably empty db, going to install soon
612 * Initialises $FULLME and friends. Private function. Should only be called from
615 function initialise_fullme() {
616 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
618 // Detect common config error.
619 if (substr($CFG->wwwroot
, -1) == '/') {
620 print_error('wwwrootslash', 'error');
624 initialise_fullme_cli();
628 $wwwroot = parse_url($CFG->wwwroot
);
629 if (!isset($wwwroot['path'])) {
630 $wwwroot['path'] = '';
632 $wwwroot['path'] .= '/';
634 $rurl = setup_get_remote_url();
636 // Check that URL is under $CFG->wwwroot.
637 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
638 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
640 // Probably some weird external script
641 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
645 // $CFG->sslproxy specifies if external SSL appliance is used
646 // (That is, the Moodle server uses http, with an external box translating everything to https).
647 if (empty($CFG->sslproxy
)) {
648 if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
649 print_error('sslonlyaccess', 'error');
652 if ($wwwroot['scheme'] !== 'https') {
653 throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
655 $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
658 // $CFG->reverseproxy specifies if reverse proxy server used.
659 // Used in load balancing scenarios.
660 // Do not abuse this to try to solve lan/wan access problems!!!!!
661 if (empty($CFG->reverseproxy
)) {
662 if (($rurl['host'] != $wwwroot['host']) or
663 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port'])) {
664 // Explain the problem and redirect them to the right URL
665 if (!defined('NO_MOODLE_COOKIES')) {
666 define('NO_MOODLE_COOKIES', true);
668 redirect($CFG->wwwroot
, get_string('wwwrootmismatch', 'error', $CFG->wwwroot
), 3);
672 // hopefully this will stop all those "clever" admins trying to set up moodle
673 // with two different addresses in intranet and Internet
674 if (!empty($CFG->reverseproxy
) && $rurl['host'] == $wwwroot['host']) {
675 print_error('reverseproxyabused', 'error');
678 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
679 if (!empty($wwwroot['port'])) {
680 $hostandport .= ':'.$wwwroot['port'];
683 $FULLSCRIPT = $hostandport . $rurl['path'];
684 $FULLME = $hostandport . $rurl['fullpath'];
685 $ME = $rurl['fullpath'];
686 $rurl['path'] = $rurl['fullpath'];
690 * Initialises $FULLME and friends for command line scripts.
691 * This is a private method for use by initialise_fullme.
693 function initialise_fullme_cli() {
694 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
696 // Urls do not make much sense in CLI scripts
697 $backtrace = debug_backtrace();
698 $topfile = array_pop($backtrace);
699 $topfile = realpath($topfile['file']);
700 $dirroot = realpath($CFG->dirroot
);
702 if (strpos($topfile, $dirroot) !== 0) {
703 // Probably some weird external script
704 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
706 $relativefile = substr($topfile, strlen($dirroot));
707 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
708 $SCRIPT = $FULLSCRIPT = $relativefile;
709 $FULLME = $ME = null;
714 * Get the URL that PHP/the web server thinks it is serving. Private function
715 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
716 * @return array in the same format that parse_url returns, with the addition of
717 * a 'fullpath' element, which includes any slasharguments path.
719 function setup_get_remote_url() {
721 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
722 $rurl['port'] = $_SERVER['SERVER_PORT'];
723 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
725 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
727 $rurl['scheme'] = empty($_SERVER['HTTPS']) ?
'http' : 'https';
728 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
730 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
731 //IIS - needs a lot of tweaking to make it work
732 $rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ?
'http' : 'https';
733 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
735 // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
736 // since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
737 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
739 if ($_SERVER['QUERY_STRING'] != '') {
740 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
742 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
744 /* NOTE: following servers are not fully tested! */
746 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
747 //lighttpd - not officially supported
748 $rurl['scheme'] = empty($_SERVER['HTTPS']) ?
'http' : 'https';
749 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
751 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
752 //nginx - not officially supported
753 if (!isset($_SERVER['SCRIPT_NAME'])) {
754 die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
756 $rurl['scheme'] = empty($_SERVER['HTTPS']) ?
'http' : 'https';
757 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
759 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
760 //cherokee - not officially supported
761 $rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ?
'http' : 'https';
762 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
764 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
765 //zeus - not officially supported
766 $rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ?
'http' : 'https';
767 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
769 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
770 //LiteSpeed - not officially supported
771 $rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ?
'http' : 'https';
772 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
775 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
781 * Initializes our performance info early.
783 * Pairs up with get_performance_info() which is actually
784 * in moodlelib.php. This function is here so that we can
785 * call it before all the libs are pulled in.
789 function init_performance_info() {
791 global $PERF, $CFG, $USER;
793 $PERF = new stdClass();
794 $PERF->logwrites
= 0;
795 if (function_exists('microtime')) {
796 $PERF->starttime
= microtime();
798 if (function_exists('memory_get_usage')) {
799 $PERF->startmemory
= memory_get_usage();
801 if (function_exists('posix_times')) {
802 $PERF->startposixtimes
= posix_times();
804 if (function_exists('apd_set_pprof_trace')) {
806 if ($USER->id
> 0 && $CFG->perfdebug
>= 15) {
807 $tempdir = $CFG->dataroot
. '/temp/profile/' . $USER->id
;
809 apd_set_pprof_trace($tempdir);
810 $PERF->profiling
= true;
816 * Indicates whether we are in the middle of the initial Moodle install.
818 * Very occasionally it is necessary avoid running certain bits of code before the
819 * Moodle installation has completed. The installed flag is set in admin/index.php
820 * after Moodle core and all the plugins have been installed, but just before
821 * the person doing the initial install is asked to choose the admin password.
823 * @return boolean true if the initial install is not complete.
825 function during_initial_install() {
827 return empty($CFG->rolesactive
);
831 * Function to raise the memory limit to a new value.
832 * Will respect the memory limit if it is higher, thus allowing
833 * settings in php.ini, apache conf or command line switches
836 * The memory limit should be expressed with a constant
837 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
838 * It is possible to use strings or integers too (eg:'128M').
840 * @param mixed $newlimit the new memory limit
841 * @return bool success
843 function raise_memory_limit($newlimit) {
846 if ($newlimit == MEMORY_UNLIMITED
) {
847 ini_set('memory_limit', -1);
850 } else if ($newlimit == MEMORY_STANDARD
) {
851 if (PHP_INT_SIZE
> 4) {
852 $newlimit = get_real_size('128M'); // 64bit needs more memory
854 $newlimit = get_real_size('96M');
857 } else if ($newlimit == MEMORY_EXTRA
) {
858 if (PHP_INT_SIZE
> 4) {
859 $newlimit = get_real_size('384M'); // 64bit needs more memory
861 $newlimit = get_real_size('256M');
863 if (!empty($CFG->extramemorylimit
)) {
864 $extra = get_real_size($CFG->extramemorylimit
);
865 if ($extra > $newlimit) {
870 } else if ($newlimit == MEMORY_HUGE
) {
871 $newlimit = get_real_size('2G');
874 $newlimit = get_real_size($newlimit);
877 if ($newlimit <= 0) {
878 debugging('Invalid memory limit specified.');
882 $cur = ini_get('memory_limit');
884 // if php is compiled without --enable-memory-limits
885 // apparently memory_limit is set to ''
889 return true; // unlimited mem!
891 $cur = get_real_size($cur);
894 if ($newlimit > $cur) {
895 ini_set('memory_limit', $newlimit);
902 * Function to reduce the memory limit to a new value.
903 * Will respect the memory limit if it is lower, thus allowing
904 * settings in php.ini, apache conf or command line switches
907 * The memory limit should be expressed with a string (eg:'64M')
909 * @param string $newlimit the new memory limit
912 function reduce_memory_limit($newlimit) {
913 if (empty($newlimit)) {
916 $cur = ini_get('memory_limit');
918 // if php is compiled without --enable-memory-limits
919 // apparently memory_limit is set to ''
923 return true; // unlimited mem!
925 $cur = get_real_size($cur);
928 $new = get_real_size($newlimit);
929 // -1 is smaller, but it means unlimited
930 if ($new < $cur && $new != -1) {
931 ini_set('memory_limit', $newlimit);
938 * Converts numbers like 10M into bytes.
940 * @param string $size The size to be converted
943 function get_real_size($size = 0) {
948 $scan['GB'] = 1073741824;
949 $scan['Gb'] = 1073741824;
950 $scan['G'] = 1073741824;
951 $scan['MB'] = 1048576;
952 $scan['Mb'] = 1048576;
953 $scan['M'] = 1048576;
954 $scan['m'] = 1048576;
960 while (list($key) = each($scan)) {
961 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
962 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
970 * Try to disable all output buffering and purge
973 * @private to be called only from lib/setup.php !
976 function disable_output_buffering() {
977 $olddebug = error_reporting(0);
979 // disable compression, it would prevent closing of buffers
980 if (ini_get_bool('zlib.output_compression')) {
981 ini_set('zlib.output_compression', 'Off');
984 // try to flush everything all the time
985 ob_implicit_flush(true);
987 // close all buffers if possible and discard any existing output
988 // this can actually work around some whitespace problems in config.php
989 while(ob_get_level()) {
990 if (!ob_end_clean()) {
991 // prevent infinite loop when buffer can not be closed
996 error_reporting($olddebug);
1000 * Check whether a major upgrade is needed. That is defined as an upgrade that
1001 * changes something really fundamental in the database, so nothing can possibly
1002 * work until the database has been updated, and that is defined by the hard-coded
1003 * version number in this function.
1005 function redirect_if_major_upgrade_required() {
1007 $lastmajordbchanges = 2010111700;
1008 if (empty($CFG->version
) or (int)$CFG->version
< $lastmajordbchanges or
1009 during_initial_install() or !empty($CFG->adminsetuppending
)) {
1011 @session_get_instance
()->terminate_current();
1012 } catch (Exception
$e) {
1013 // Ignore any errors, redirect to upgrade anyway.
1015 $url = $CFG->wwwroot
. '/' . $CFG->admin
. '/index.php';
1016 @header
($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1017 @header
('Location: ' . $url);
1018 echo bootstrap_renderer
::plain_redirect_message(htmlspecialchars($url));
1024 * Function to check if a directory exists and by default create it if not exists.
1026 * Previously this was accepting paths only from dataroot, but we now allow
1027 * files outside of dataroot if you supply custom paths for some settings in config.php.
1028 * This function does not verify that the directory is writable.
1030 * @param string $dir absolute directory path
1031 * @param boolean $create directory if does not exist
1032 * @param boolean $recursive create directory recursively
1033 * @return boolean true if directory exists or created, false otherwise
1035 function check_dir_exists($dir, $create = true, $recursive = true) {
1038 umask(0000); // just in case some evil code changed it
1048 return mkdir($dir, $CFG->directorypermissions
, $recursive);
1052 * Create a directory in dataroot and make sure it is writable.
1054 * @param string $directory a string of directory names under $CFG->dataroot eg temp/something
1055 * @param bool $exceptiononerror throw exception if error encountered
1056 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1058 function make_upload_directory($directory, $exceptiononerror = true) {
1061 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1062 if (!file_exists("$CFG->dataroot/.htaccess")) {
1063 if ($handle = fopen("$CFG->dataroot/.htaccess", 'w')) { // For safety
1064 @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");
1069 $dir = "$CFG->dataroot/$directory";
1071 if (file_exists($dir) and !is_dir($dir)) {
1072 if ($exceptiononerror) {
1073 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1079 umask(0000); // just in case some evil code changed it
1081 if (!file_exists($dir)) {
1082 if (!mkdir($dir, $CFG->directorypermissions
, true)) {
1083 if ($exceptiononerror) {
1084 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1091 if (!is_writable($dir)) {
1092 if ($exceptiononerror) {
1093 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1102 function init_memcached() {
1103 global $CFG, $MCACHE;
1105 include_once($CFG->libdir
. '/memcached.class.php');
1106 $MCACHE = new memcached
;
1107 if ($MCACHE->status()) {
1114 function init_eaccelerator() {
1115 global $CFG, $MCACHE;
1117 include_once($CFG->libdir
. '/eaccelerator.class.php');
1118 $MCACHE = new eaccelerator
;
1119 if ($MCACHE->status()) {
1127 * Checks if current user is a web crawler.
1129 * This list can not be made complete, this is not a security
1130 * restriction, we make the list only to help these sites
1131 * especially when automatic guest login is disabled.
1133 * If admin needs security they should enable forcelogin
1134 * and disable guest access!!
1138 function is_web_crawler() {
1139 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
1140 if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
1142 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) { // Google
1144 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yahoo! Slurp') !== false ) { // Yahoo
1146 } else if (strpos($_SERVER['HTTP_USER_AGENT'], '[ZSEBOT]') !== false ) { // Zoomspider
1148 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSNBOT') !== false ) { // MSN Search
1150 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yandex') !== false ) {
1152 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'AltaVista') !== false ) {
1160 * This class solves the problem of how to initialise $OUTPUT.
1162 * The problem is caused be two factors
1164 * <li>On the one hand, we cannot be sure when output will start. In particular,
1165 * an error, which needs to be displayed, could be thrown at any time.</li>
1166 * <li>On the other hand, we cannot be sure when we will have all the information
1167 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1168 * (potentially) depends on the current course, course categories, and logged in user.
1169 * It also depends on whether the current page requires HTTPS.</li>
1172 * So, it is hard to find a single natural place during Moodle script execution,
1173 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1174 * adopt the following strategy
1176 * <li>We will initialise $OUTPUT the first time it is used.</li>
1177 * <li>If, after $OUTPUT has been initialised, the script tries to change something
1178 * that $OUTPUT depends on, we throw an exception making it clear that the script
1179 * did something wrong.
1182 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1183 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1184 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1185 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1187 * Note that this class is used before lib/outputlib.php has been loaded, so we
1188 * must be careful referring to classes/functions from there, they may not be
1189 * defined yet, and we must avoid fatal errors.
1191 * @copyright 2009 Tim Hunt
1192 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1195 class bootstrap_renderer
{
1197 * Handles re-entrancy. Without this, errors or debugging output that occur
1198 * during the initialisation of $OUTPUT, cause infinite recursion.
1201 protected $initialising = false;
1204 * Have we started output yet?
1205 * @return boolean true if the header has been printed.
1207 public function has_started() {
1211 public function __call($method, $arguments) {
1212 global $OUTPUT, $PAGE;
1215 if ($method == 'notification') {
1216 // Catch infinite recursion caused by debugging output during print_header.
1217 $backtrace = debug_backtrace();
1218 array_shift($backtrace);
1219 array_shift($backtrace);
1220 $recursing = is_early_init($backtrace);
1223 $earlymethods = array(
1224 'fatal_error' => 'early_error',
1225 'notification' => 'early_notification',
1228 // If lib/outputlib.php has been loaded, call it.
1229 if (!empty($PAGE) && !$recursing) {
1230 if (array_key_exists($method, $earlymethods)) {
1231 //prevent PAGE->context warnings - exceptions might appear before we set any context
1232 $PAGE->set_context(null);
1234 $PAGE->initialise_theme_and_output();
1235 return call_user_func_array(array($OUTPUT, $method), $arguments);
1238 $this->initialising
= true;
1240 // Too soon to initialise $OUTPUT, provide a couple of key methods.
1241 if (array_key_exists($method, $earlymethods)) {
1242 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1245 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1249 * Returns nicely formatted error message in a div box.
1252 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1255 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1256 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1257 width: 80%; -moz-border-radius: 20px; padding: 15px">
1260 if (!empty($CFG->debug
) && $CFG->debug
>= DEBUG_DEVELOPER
) {
1261 if (!empty($debuginfo)) {
1262 $debuginfo = s($debuginfo); // removes all nasty JS
1263 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1264 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
1266 if (!empty($backtrace)) {
1267 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1275 * This function should only be called by this class, or from exception handlers
1278 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1282 echo "!!! $message !!!\n";
1283 if (!empty($CFG->debug
) and $CFG->debug
>= DEBUG_DEVELOPER
) {
1284 if (!empty($debuginfo)) {
1285 echo "\nDebug info: $debuginfo";
1287 if (!empty($backtrace)) {
1288 echo "\nStack trace: " . format_backtrace($backtrace, true);
1293 } else if (AJAX_SCRIPT
) {
1294 $e = new stdClass();
1295 $e->error
= $message;
1296 $e->stacktrace
= NULL;
1297 $e->debuginfo
= NULL;
1298 if (!empty($CFG->debug
) and $CFG->debug
>= DEBUG_DEVELOPER
) {
1299 if (!empty($debuginfo)) {
1300 $e->debuginfo
= $debuginfo;
1302 if (!empty($backtrace)) {
1303 $e->stacktrace
= format_backtrace($backtrace, true);
1306 @header
('Content-Type: application/json; charset=utf-8');
1307 echo json_encode($e);
1311 // In the name of protocol correctness, monitoring and performance
1312 // profiling, set the appropriate error headers for machine consumption
1313 if (isset($_SERVER['SERVER_PROTOCOL'])) {
1314 // Avoid it with cron.php. Note that we assume it's HTTP/1.x
1315 // The 503 ode here means our Moodle does not work at all, the error happened too early
1316 @header
($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
1319 // better disable any caching
1320 @header
('Content-Type: text/html; charset=utf-8');
1321 @header
('Cache-Control: no-store, no-cache, must-revalidate');
1322 @header
('Cache-Control: post-check=0, pre-check=0', false);
1323 @header
('Pragma: no-cache');
1324 @header
('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1325 @header
('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1327 if (function_exists('get_string')) {
1328 $strerror = get_string('error');
1330 $strerror = 'Error';
1333 $content = self
::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
1335 return self
::plain_page($strerror, $content);
1338 public static function early_notification($message, $classes = 'notifyproblem') {
1339 return '<div class="' . $classes . '">' . $message . '</div>';
1342 public static function plain_redirect_message($encodedurl) {
1343 $message = '<p>' . get_string('pageshouldredirect') . '</p><p><a href="'.
1344 $encodedurl .'">'. get_string('continue') .'</a></p>';
1345 return self
::plain_page(get_string('redirect'), $message);
1348 protected static function plain_page($title, $content) {
1349 if (function_exists('get_string') && function_exists('get_html_lang')) {
1350 $htmllang = get_html_lang();
1355 return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1356 <html xmlns="http://www.w3.org/1999/xhtml" ' . $htmllang . '>
1358 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1359 <title>' . $title . '</title>
1360 </head><body>' . $content . '</body></html>';