Merge branch 'wip-MDL-31248-MOODLE_21_STABLE-v2' of git://github.com/abgreeve/moodle...
[moodle.git] / lib / setuplib.php
blob93fbe27b1c24b2eb5a69fee382c12865128228c0
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 * Simple class. It is usually used instead of stdClass because it looks
66 * more familiar to Java developers ;-) Do not use for type checking of
67 * function parameters. Please use stdClass instead.
69 * @package core
70 * @subpackage lib
71 * @copyright 2009 Petr Skoda {@link http://skodak.org}
72 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
73 * @deprecated since 2.0
75 class object extends stdClass {};
77 /**
78 * Base Moodle Exception class
80 * Although this class is defined here, you cannot throw a moodle_exception until
81 * after moodlelib.php has been included (which will happen very soon).
83 * @package core
84 * @subpackage lib
85 * @copyright 2008 Petr Skoda {@link http://skodak.org}
86 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
88 class moodle_exception extends Exception {
89 public $errorcode;
90 public $module;
91 public $a;
92 public $link;
93 public $debuginfo;
95 /**
96 * Constructor
97 * @param string $errorcode The name of the string from error.php to print
98 * @param string $module name of module
99 * @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.
100 * @param object $a Extra words and phrases that might be required in the error string
101 * @param string $debuginfo optional debugging information
103 function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
104 if (empty($module) || $module == 'moodle' || $module == 'core') {
105 $module = 'error';
108 $this->errorcode = $errorcode;
109 $this->module = $module;
110 $this->link = $link;
111 $this->a = $a;
112 $this->debuginfo = $debuginfo;
114 if (get_string_manager()->string_exists($errorcode, $module)) {
115 $message = get_string($errorcode, $module, $a);
116 } else {
117 $message = $module . '/' . $errorcode;
120 parent::__construct($message, 0);
125 * Course/activity access exception.
127 * This exception is thrown from require_login()
129 * @package core
130 * @subpackage lib
131 * @copyright 2010 Petr Skoda {@link http://skodak.org}
132 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
134 class require_login_exception extends moodle_exception {
135 function __construct($debuginfo) {
136 parent::__construct('requireloginerror', 'error', '', NULL, $debuginfo);
141 * Web service parameter exception class
143 * This exception must be thrown to the web service client when a web service parameter is invalid
144 * The error string is gotten from webservice.php
146 class webservice_parameter_exception extends moodle_exception {
148 * Constructor
149 * @param string $errorcode The name of the string from webservice.php to print
150 * @param string $a The name of the parameter
152 function __construct($errorcode=null, $a = '') {
153 parent::__construct($errorcode, 'webservice', '', $a, null);
158 * Exceptions indicating user does not have permissions to do something
159 * and the execution can not continue.
161 * @package core
162 * @subpackage lib
163 * @copyright 2009 Petr Skoda {@link http://skodak.org}
164 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
166 class required_capability_exception extends moodle_exception {
167 function __construct($context, $capability, $errormessage, $stringfile) {
168 $capabilityname = get_capability_string($capability);
169 if ($context->contextlevel == CONTEXT_MODULE and preg_match('/:view$/', $capability)) {
170 // 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
171 $paranetcontext = get_context_instance_by_id(get_parent_contextid($context));
172 $link = get_context_url($paranetcontext);
173 } else {
174 $link = get_context_url($context);
176 parent::__construct($errormessage, $stringfile, $link, $capabilityname);
181 * Exception indicating programming error, must be fixed by a programer. For example
182 * a core API might throw this type of exception if a plugin calls it incorrectly.
184 * @package core
185 * @subpackage lib
186 * @copyright 2008 Petr Skoda {@link http://skodak.org}
187 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
189 class coding_exception extends moodle_exception {
191 * Constructor
192 * @param string $hint short description of problem
193 * @param string $debuginfo detailed information how to fix problem
195 function __construct($hint, $debuginfo=null) {
196 parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
201 * Exception indicating malformed parameter problem.
202 * This exception is not supposed to be thrown when processing
203 * user submitted data in forms. It is more suitable
204 * for WS and other low level stuff.
206 * @package core
207 * @subpackage lib
208 * @copyright 2009 Petr Skoda {@link http://skodak.org}
209 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
211 class invalid_parameter_exception extends moodle_exception {
213 * Constructor
214 * @param string $debuginfo some detailed information
216 function __construct($debuginfo=null) {
217 parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
222 * Exception indicating malformed response problem.
223 * This exception is not supposed to be thrown when processing
224 * user submitted data in forms. It is more suitable
225 * for WS and other low level stuff.
227 class invalid_response_exception extends moodle_exception {
229 * Constructor
230 * @param string $debuginfo some detailed information
232 function __construct($debuginfo=null) {
233 parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
238 * An exception that indicates something really weird happened. For example,
239 * if you do switch ($context->contextlevel), and have one case for each
240 * CONTEXT_... constant. You might throw an invalid_state_exception in the
241 * default case, to just in case something really weird is going on, and
242 * $context->contextlevel is invalid - rather than ignoring this possibility.
244 * @package core
245 * @subpackage lib
246 * @copyright 2009 onwards Martin Dougiamas {@link http://moodle.com}
247 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
249 class invalid_state_exception extends moodle_exception {
251 * Constructor
252 * @param string $hint short description of problem
253 * @param string $debuginfo optional more detailed information
255 function __construct($hint, $debuginfo=null) {
256 parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
261 * An exception that indicates incorrect permissions in $CFG->dataroot
263 * @package core
264 * @subpackage lib
265 * @copyright 2010 Petr Skoda {@link http://skodak.org}
266 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
268 class invalid_dataroot_permissions extends moodle_exception {
270 * Constructor
271 * @param string $debuginfo optional more detailed information
273 function __construct($debuginfo = NULL) {
274 parent::__construct('invaliddatarootpermissions', 'error', '', NULL, $debuginfo);
279 * An exception that indicates that file can not be served
281 * @package core
282 * @subpackage lib
283 * @copyright 2010 Petr Skoda {@link http://skodak.org}
284 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
286 class file_serving_exception extends moodle_exception {
288 * Constructor
289 * @param string $debuginfo optional more detailed information
291 function __construct($debuginfo = NULL) {
292 parent::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
297 * Default exception handler, uncaught exceptions are equivalent to error() in 1.9 and earlier
299 * @param Exception $ex
300 * @return void -does not return. Terminates execution!
302 function default_exception_handler($ex) {
303 global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION;
305 // detect active db transactions, rollback and log as error
306 abort_all_db_transactions();
308 if (($ex instanceof required_capability_exception) && !CLI_SCRIPT && !AJAX_SCRIPT && !empty($CFG->autologinguests) && !empty($USER->autologinguest)) {
309 $SESSION->wantsurl = $FULLME;
310 redirect(get_login_url());
313 $info = get_exception_info($ex);
315 if (debugging('', DEBUG_MINIMAL)) {
316 $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
317 error_log($logerrmsg);
320 if (is_early_init($info->backtrace)) {
321 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
322 } else {
323 try {
324 if ($DB) {
325 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
326 $DB->set_debug(0);
328 echo $OUTPUT->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
329 } catch (Exception $out_ex) {
330 // default exception handler MUST not throw any exceptions!!
331 // 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
332 // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
333 if (CLI_SCRIPT or AJAX_SCRIPT) {
334 // just ignore the error and send something back using the safest method
335 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
336 } else {
337 echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
338 $outinfo = get_exception_info($out_ex);
339 echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
344 exit(1); // General error code
348 * Default error handler, prevents some white screens.
349 * @param int $errno
350 * @param string $errstr
351 * @param string $errfile
352 * @param int $errline
353 * @param array $errcontext
354 * @return bool false means use default error handler
356 function default_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
357 if ($errno == 4096) {
358 //fatal catchable error
359 throw new coding_exception('PHP catchable fatal error', $errstr);
361 return false;
365 * Unconditionally abort all database transactions, this function
366 * should be called from exception handlers only.
367 * @return void
369 function abort_all_db_transactions() {
370 global $CFG, $DB, $SCRIPT;
372 // default exception handler MUST not throw any exceptions!!
374 if ($DB && $DB->is_transaction_started()) {
375 error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
376 // note: transaction blocks should never change current $_SESSION
377 $DB->force_transaction_rollback();
382 * This function encapsulates the tests for whether an exception was thrown in
383 * early init -- either during setup.php or during init of $OUTPUT.
385 * If another exception is thrown then, and if we do not take special measures,
386 * we would just get a very cryptic message "Exception thrown without a stack
387 * frame in Unknown on line 0". That makes debugging very hard, so we do take
388 * special measures in default_exception_handler, with the help of this function.
390 * @param array $backtrace the stack trace to analyse.
391 * @return boolean whether the stack trace is somewhere in output initialisation.
393 function is_early_init($backtrace) {
394 $dangerouscode = array(
395 array('function' => 'header', 'type' => '->'),
396 array('class' => 'bootstrap_renderer'),
397 array('file' => dirname(__FILE__).'/setup.php'),
399 foreach ($backtrace as $stackframe) {
400 foreach ($dangerouscode as $pattern) {
401 $matches = true;
402 foreach ($pattern as $property => $value) {
403 if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
404 $matches = false;
407 if ($matches) {
408 return true;
412 return false;
416 * Abort execution by throwing of a general exception,
417 * default exception handler displays the error message in most cases.
419 * @param string $errorcode The name of the language string containing the error message.
420 * Normally this should be in the error.php lang file.
421 * @param string $module The language file to get the error message from.
422 * @param string $link The url where the user will be prompted to continue.
423 * If no url is provided the user will be directed to the site index page.
424 * @param object $a Extra words and phrases that might be required in the error string
425 * @param string $debuginfo optional debugging information
426 * @return void, always throws exception!
428 function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
429 throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
433 * Returns detailed information about specified exception.
434 * @param exception $ex
435 * @return object
437 function get_exception_info($ex) {
438 global $CFG, $DB, $SESSION;
440 if ($ex instanceof moodle_exception) {
441 $errorcode = $ex->errorcode;
442 $module = $ex->module;
443 $a = $ex->a;
444 $link = $ex->link;
445 $debuginfo = $ex->debuginfo;
446 } else {
447 $errorcode = 'generalexceptionmessage';
448 $module = 'error';
449 $a = $ex->getMessage();
450 $link = '';
451 $debuginfo = null;
454 $backtrace = $ex->getTrace();
455 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
456 array_unshift($backtrace, $place);
458 // Be careful, no guarantee moodlelib.php is loaded.
459 if (empty($module) || $module == 'moodle' || $module == 'core') {
460 $module = 'error';
462 if (function_exists('get_string_manager')) {
463 if (get_string_manager()->string_exists($errorcode, $module)) {
464 $message = get_string($errorcode, $module, $a);
465 } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
466 // Search in moodle file if error specified - needed for backwards compatibility
467 $message = get_string($errorcode, 'moodle', $a);
468 } else {
469 $message = $module . '/' . $errorcode;
471 } else {
472 $message = $module . '/' . $errorcode;
475 // Be careful, no guarantee weblib.php is loaded.
476 if (function_exists('clean_text')) {
477 $message = clean_text($message);
478 } else {
479 $message = htmlspecialchars($message);
482 if (!empty($CFG->errordocroot)) {
483 $errordoclink = $CFG->errordocroot . '/en/';
484 } else {
485 $errordoclink = get_docs_url();
488 if ($module === 'error') {
489 $modulelink = 'moodle';
490 } else {
491 $modulelink = $module;
493 $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
495 if (empty($link)) {
496 if (!empty($SESSION->fromurl)) {
497 $link = $SESSION->fromurl;
498 unset($SESSION->fromurl);
499 } else {
500 $link = $CFG->wwwroot .'/';
504 // when printing an error the continue button should never link offsite
505 if (stripos($link, $CFG->wwwroot) === false &&
506 stripos($link, $CFG->httpswwwroot) === false) {
507 $link = $CFG->wwwroot.'/';
510 $info = new stdClass();
511 $info->message = $message;
512 $info->errorcode = $errorcode;
513 $info->backtrace = $backtrace;
514 $info->link = $link;
515 $info->moreinfourl = $moreinfourl;
516 $info->a = $a;
517 $info->debuginfo = $debuginfo;
519 return $info;
523 * Returns the Moodle Docs URL in the users language
525 * @global object
526 * @param string $path the end of the URL.
527 * @return string The MoodleDocs URL in the user's language. for example {@link http://docs.moodle.org/en/ http://docs.moodle.org/en/$path}
529 function get_docs_url($path=null) {
530 global $CFG;
531 // Check that $CFG->release has been set up, during installation it won't be.
532 if (empty($CFG->release)) {
533 // It's not there yet so look at version.php
534 include($CFG->dirroot.'/version.php');
535 } else {
536 // We can use $CFG->release and avoid having to include version.php
537 $release = $CFG->release;
539 // Attempt to match the branch from the release
540 if (preg_match('/^(.)\.(.)/', $release, $matches)) {
541 // We should ALWAYS get here
542 $branch = $matches[1].$matches[2];
543 } else {
544 // We should never get here but in case we do lets set $branch to .
545 // the smart one's will know that this is the current directory
546 // and the smarter ones will know that there is some smart matching
547 // that will ensure people end up at the latest version of the docs.
548 $branch = '.';
550 if (!empty($CFG->docroot)) {
551 return $CFG->docroot . '/' . $branch . '/' . current_language() . '/' . $path;
552 } else {
553 return 'http://docs.moodle.org/'. $branch . '/en/' . $path;
558 * Formats a backtrace ready for output.
560 * @param array $callers backtrace array, as returned by debug_backtrace().
561 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
562 * @return string formatted backtrace, ready for output.
564 function format_backtrace($callers, $plaintext = false) {
565 // do not use $CFG->dirroot because it might not be available in destructors
566 $dirroot = dirname(dirname(__FILE__));
568 if (empty($callers)) {
569 return '';
572 $from = $plaintext ? '' : '<ul style="text-align: left">';
573 foreach ($callers as $caller) {
574 if (!isset($caller['line'])) {
575 $caller['line'] = '?'; // probably call_user_func()
577 if (!isset($caller['file'])) {
578 $caller['file'] = 'unknownfile'; // probably call_user_func()
580 $from .= $plaintext ? '* ' : '<li>';
581 $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
582 if (isset($caller['function'])) {
583 $from .= ': call to ';
584 if (isset($caller['class'])) {
585 $from .= $caller['class'] . $caller['type'];
587 $from .= $caller['function'] . '()';
588 } else if (isset($caller['exception'])) {
589 $from .= ': '.$caller['exception'].' thrown';
591 $from .= $plaintext ? "\n" : '</li>';
593 $from .= $plaintext ? '' : '</ul>';
595 return $from;
599 * This function makes the return value of ini_get consistent if you are
600 * setting server directives through the .htaccess file in apache.
602 * Current behavior for value set from php.ini On = 1, Off = [blank]
603 * Current behavior for value set from .htaccess On = On, Off = Off
604 * Contributed by jdell @ unr.edu
606 * @param string $ini_get_arg The argument to get
607 * @return bool True for on false for not
609 function ini_get_bool($ini_get_arg) {
610 $temp = ini_get($ini_get_arg);
612 if ($temp == '1' or strtolower($temp) == 'on') {
613 return true;
615 return false;
619 * This function verifies the sanity of PHP configuration
620 * and stops execution if anything critical found.
622 function setup_validate_php_configuration() {
623 // this must be very fast - no slow checks here!!!
625 if (ini_get_bool('register_globals')) {
626 print_error('globalswarning', 'admin');
628 if (ini_get_bool('session.auto_start')) {
629 print_error('sessionautostartwarning', 'admin');
631 if (ini_get_bool('magic_quotes_runtime')) {
632 print_error('fatalmagicquotesruntime', 'admin');
637 * Initialise global $CFG variable
638 * @return void
640 function initialise_cfg() {
641 global $CFG, $DB;
643 try {
644 if ($DB) {
645 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
646 foreach ($localcfg as $name=>$value) {
647 if (property_exists($CFG, $name)) {
648 // config.php settings always take precedence
649 continue;
651 $CFG->{$name} = $value;
654 } catch (dml_read_exception $e) {
655 // most probably empty db, going to install soon
660 * Initialises $FULLME and friends. Private function. Should only be called from
661 * setup.php.
663 function initialise_fullme() {
664 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT, $USER;
666 // Detect common config error.
667 if (substr($CFG->wwwroot, -1) == '/') {
668 print_error('wwwrootslash', 'error');
671 if (CLI_SCRIPT) {
672 initialise_fullme_cli();
673 return;
676 $wwwroot = parse_url($CFG->wwwroot);
677 if (!isset($wwwroot['path'])) {
678 $wwwroot['path'] = '';
680 $wwwroot['path'] .= '/';
682 $rurl = setup_get_remote_url();
684 // Check that URL is under $CFG->wwwroot.
685 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
686 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
687 } else {
688 // Probably some weird external script
689 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
690 return;
693 // $CFG->sslproxy specifies if external SSL appliance is used
694 // (That is, the Moodle server uses http, with an external box translating everything to https).
695 if (empty($CFG->sslproxy)) {
696 if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
697 print_error('sslonlyaccess', 'error');
699 } else {
700 if ($wwwroot['scheme'] !== 'https') {
701 throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
703 $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
706 // $CFG->reverseproxy specifies if reverse proxy server used.
707 // Used in load balancing scenarios.
708 // Do not abuse this to try to solve lan/wan access problems!!!!!
709 if (empty($CFG->reverseproxy)) {
710 if (empty($rurl['host'])) {
711 // missing host in request header, probably not a real browser, let's ignore them
712 } else if (($rurl['host'] !== $wwwroot['host']) or
713 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port'])) {
714 // Explain the problem and redirect them to the right URL
715 if (!defined('NO_MOODLE_COOKIES')) {
716 define('NO_MOODLE_COOKIES', true);
718 if (!isset($USER->id)) {
719 // MDL-27899 workaround
720 $USER = new stdClass();
721 $USER->id = 0;
723 redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
727 // hopefully this will stop all those "clever" admins trying to set up moodle
728 // with two different addresses in intranet and Internet
729 if (!empty($CFG->reverseproxy) && $rurl['host'] === $wwwroot['host']) {
730 print_error('reverseproxyabused', 'error');
733 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
734 if (!empty($wwwroot['port'])) {
735 $hostandport .= ':'.$wwwroot['port'];
738 $FULLSCRIPT = $hostandport . $rurl['path'];
739 $FULLME = $hostandport . $rurl['fullpath'];
740 $ME = $rurl['fullpath'];
744 * Initialises $FULLME and friends for command line scripts.
745 * This is a private method for use by initialise_fullme.
747 function initialise_fullme_cli() {
748 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
750 // Urls do not make much sense in CLI scripts
751 $backtrace = debug_backtrace();
752 $topfile = array_pop($backtrace);
753 $topfile = realpath($topfile['file']);
754 $dirroot = realpath($CFG->dirroot);
756 if (strpos($topfile, $dirroot) !== 0) {
757 // Probably some weird external script
758 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
759 } else {
760 $relativefile = substr($topfile, strlen($dirroot));
761 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
762 $SCRIPT = $FULLSCRIPT = $relativefile;
763 $FULLME = $ME = null;
768 * Get the URL that PHP/the web server thinks it is serving. Private function
769 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
770 * @return array in the same format that parse_url returns, with the addition of
771 * a 'fullpath' element, which includes any slasharguments path.
773 function setup_get_remote_url() {
774 $rurl = array();
775 if (isset($_SERVER['HTTP_HOST'])) {
776 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
777 } else {
778 $rurl['host'] = null;
780 $rurl['port'] = $_SERVER['SERVER_PORT'];
781 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
782 $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ? 'http' : 'https';
784 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
785 //Apache server
786 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
788 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
789 //IIS - needs a lot of tweaking to make it work
790 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
792 // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
793 // since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
794 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
796 if ($_SERVER['QUERY_STRING'] != '') {
797 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
799 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
801 /* NOTE: following servers are not fully tested! */
803 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
804 //lighttpd - not officially supported
805 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
807 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
808 //nginx - not officially supported
809 if (!isset($_SERVER['SCRIPT_NAME'])) {
810 die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
812 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
814 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
815 //cherokee - not officially supported
816 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
818 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
819 //zeus - not officially supported
820 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
822 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
823 //LiteSpeed - not officially supported
824 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
826 } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
827 //obscure name found on some servers - this is definitely not supported
828 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
830 } else {
831 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
834 // sanitize the url a bit more, the encoding style may be different in vars above
835 $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
836 $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);
838 return $rurl;
842 * Initializes our performance info early.
844 * Pairs up with get_performance_info() which is actually
845 * in moodlelib.php. This function is here so that we can
846 * call it before all the libs are pulled in.
848 * @uses $PERF
850 function init_performance_info() {
852 global $PERF, $CFG, $USER;
854 $PERF = new stdClass();
855 $PERF->logwrites = 0;
856 if (function_exists('microtime')) {
857 $PERF->starttime = microtime();
859 if (function_exists('memory_get_usage')) {
860 $PERF->startmemory = memory_get_usage();
862 if (function_exists('posix_times')) {
863 $PERF->startposixtimes = posix_times();
865 if (function_exists('apd_set_pprof_trace')) {
866 // APD profiling
867 if ($USER->id > 0 && $CFG->perfdebug >= 15) {
868 $tempdir = $CFG->dataroot . '/temp/profile/' . $USER->id;
869 mkdir($tempdir);
870 apd_set_pprof_trace($tempdir);
871 $PERF->profiling = true;
877 * Indicates whether we are in the middle of the initial Moodle install.
879 * Very occasionally it is necessary avoid running certain bits of code before the
880 * Moodle installation has completed. The installed flag is set in admin/index.php
881 * after Moodle core and all the plugins have been installed, but just before
882 * the person doing the initial install is asked to choose the admin password.
884 * @return boolean true if the initial install is not complete.
886 function during_initial_install() {
887 global $CFG;
888 return empty($CFG->rolesactive);
892 * Function to raise the memory limit to a new value.
893 * Will respect the memory limit if it is higher, thus allowing
894 * settings in php.ini, apache conf or command line switches
895 * to override it.
897 * The memory limit should be expressed with a constant
898 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
899 * It is possible to use strings or integers too (eg:'128M').
901 * @param mixed $newlimit the new memory limit
902 * @return bool success
904 function raise_memory_limit($newlimit) {
905 global $CFG;
907 if ($newlimit == MEMORY_UNLIMITED) {
908 ini_set('memory_limit', -1);
909 return true;
911 } else if ($newlimit == MEMORY_STANDARD) {
912 if (PHP_INT_SIZE > 4) {
913 $newlimit = get_real_size('128M'); // 64bit needs more memory
914 } else {
915 $newlimit = get_real_size('96M');
918 } else if ($newlimit == MEMORY_EXTRA) {
919 if (PHP_INT_SIZE > 4) {
920 $newlimit = get_real_size('384M'); // 64bit needs more memory
921 } else {
922 $newlimit = get_real_size('256M');
924 if (!empty($CFG->extramemorylimit)) {
925 $extra = get_real_size($CFG->extramemorylimit);
926 if ($extra > $newlimit) {
927 $newlimit = $extra;
931 } else if ($newlimit == MEMORY_HUGE) {
932 $newlimit = get_real_size('2G');
934 } else {
935 $newlimit = get_real_size($newlimit);
938 if ($newlimit <= 0) {
939 debugging('Invalid memory limit specified.');
940 return false;
943 $cur = ini_get('memory_limit');
944 if (empty($cur)) {
945 // if php is compiled without --enable-memory-limits
946 // apparently memory_limit is set to ''
947 $cur = 0;
948 } else {
949 if ($cur == -1){
950 return true; // unlimited mem!
952 $cur = get_real_size($cur);
955 if ($newlimit > $cur) {
956 ini_set('memory_limit', $newlimit);
957 return true;
959 return false;
963 * Function to reduce the memory limit to a new value.
964 * Will respect the memory limit if it is lower, thus allowing
965 * settings in php.ini, apache conf or command line switches
966 * to override it
968 * The memory limit should be expressed with a string (eg:'64M')
970 * @param string $newlimit the new memory limit
971 * @return bool
973 function reduce_memory_limit($newlimit) {
974 if (empty($newlimit)) {
975 return false;
977 $cur = ini_get('memory_limit');
978 if (empty($cur)) {
979 // if php is compiled without --enable-memory-limits
980 // apparently memory_limit is set to ''
981 $cur = 0;
982 } else {
983 if ($cur == -1){
984 return true; // unlimited mem!
986 $cur = get_real_size($cur);
989 $new = get_real_size($newlimit);
990 // -1 is smaller, but it means unlimited
991 if ($new < $cur && $new != -1) {
992 ini_set('memory_limit', $newlimit);
993 return true;
995 return false;
999 * Converts numbers like 10M into bytes.
1001 * @param string $size The size to be converted
1002 * @return int
1004 function get_real_size($size = 0) {
1005 if (!$size) {
1006 return 0;
1008 $scan = array();
1009 $scan['GB'] = 1073741824;
1010 $scan['Gb'] = 1073741824;
1011 $scan['G'] = 1073741824;
1012 $scan['MB'] = 1048576;
1013 $scan['Mb'] = 1048576;
1014 $scan['M'] = 1048576;
1015 $scan['m'] = 1048576;
1016 $scan['KB'] = 1024;
1017 $scan['Kb'] = 1024;
1018 $scan['K'] = 1024;
1019 $scan['k'] = 1024;
1021 while (list($key) = each($scan)) {
1022 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
1023 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
1024 break;
1027 return $size;
1031 * Try to disable all output buffering and purge
1032 * all headers.
1034 * @private to be called only from lib/setup.php !
1035 * @return void
1037 function disable_output_buffering() {
1038 $olddebug = error_reporting(0);
1040 // disable compression, it would prevent closing of buffers
1041 if (ini_get_bool('zlib.output_compression')) {
1042 ini_set('zlib.output_compression', 'Off');
1045 // try to flush everything all the time
1046 ob_implicit_flush(true);
1048 // close all buffers if possible and discard any existing output
1049 // this can actually work around some whitespace problems in config.php
1050 while(ob_get_level()) {
1051 if (!ob_end_clean()) {
1052 // prevent infinite loop when buffer can not be closed
1053 break;
1057 error_reporting($olddebug);
1061 * Check whether a major upgrade is needed. That is defined as an upgrade that
1062 * changes something really fundamental in the database, so nothing can possibly
1063 * work until the database has been updated, and that is defined by the hard-coded
1064 * version number in this function.
1066 function redirect_if_major_upgrade_required() {
1067 global $CFG;
1068 $lastmajordbchanges = 2010111700;
1069 if (empty($CFG->version) or (int)$CFG->version < $lastmajordbchanges or
1070 during_initial_install() or !empty($CFG->adminsetuppending)) {
1071 try {
1072 @session_get_instance()->terminate_current();
1073 } catch (Exception $e) {
1074 // Ignore any errors, redirect to upgrade anyway.
1076 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
1077 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1078 @header('Location: ' . $url);
1079 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
1080 exit;
1085 * Function to check if a directory exists and by default create it if not exists.
1087 * Previously this was accepting paths only from dataroot, but we now allow
1088 * files outside of dataroot if you supply custom paths for some settings in config.php.
1089 * This function does not verify that the directory is writable.
1091 * @param string $dir absolute directory path
1092 * @param boolean $create directory if does not exist
1093 * @param boolean $recursive create directory recursively
1094 * @return boolean true if directory exists or created, false otherwise
1096 function check_dir_exists($dir, $create = true, $recursive = true) {
1097 global $CFG;
1099 umask(0000); // just in case some evil code changed it
1101 if (is_dir($dir)) {
1102 return true;
1105 if (!$create) {
1106 return false;
1109 return mkdir($dir, $CFG->directorypermissions, $recursive);
1113 * Create a directory in dataroot and make sure it is writable.
1115 * @param string $directory a string of directory names under $CFG->dataroot eg temp/something
1116 * @param bool $exceptiononerror throw exception if error encountered
1117 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1119 function make_upload_directory($directory, $exceptiononerror = true) {
1120 global $CFG;
1122 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1123 if (!file_exists("$CFG->dataroot/.htaccess")) {
1124 if ($handle = fopen("$CFG->dataroot/.htaccess", 'w')) { // For safety
1125 @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");
1126 @fclose($handle);
1130 $dir = "$CFG->dataroot/$directory";
1132 if (file_exists($dir) and !is_dir($dir)) {
1133 if ($exceptiononerror) {
1134 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1135 } else {
1136 return false;
1140 umask(0000); // just in case some evil code changed it
1142 if (!file_exists($dir)) {
1143 if (!mkdir($dir, $CFG->directorypermissions, true)) {
1144 if ($exceptiononerror) {
1145 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1146 } else {
1147 return false;
1152 if (!is_writable($dir)) {
1153 if ($exceptiononerror) {
1154 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1155 } else {
1156 return false;
1160 return $dir;
1163 function init_memcached() {
1164 global $CFG, $MCACHE;
1166 include_once($CFG->libdir . '/memcached.class.php');
1167 $MCACHE = new memcached;
1168 if ($MCACHE->status()) {
1169 return true;
1171 unset($MCACHE);
1172 return false;
1175 function init_eaccelerator() {
1176 global $CFG, $MCACHE;
1178 include_once($CFG->libdir . '/eaccelerator.class.php');
1179 $MCACHE = new eaccelerator;
1180 if ($MCACHE->status()) {
1181 return true;
1183 unset($MCACHE);
1184 return false;
1188 * Checks if current user is a web crawler.
1190 * This list can not be made complete, this is not a security
1191 * restriction, we make the list only to help these sites
1192 * especially when automatic guest login is disabled.
1194 * If admin needs security they should enable forcelogin
1195 * and disable guest access!!
1197 * @return bool
1199 function is_web_crawler() {
1200 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
1201 if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
1202 return true;
1203 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) { // Google
1204 return true;
1205 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yahoo! Slurp') !== false ) { // Yahoo
1206 return true;
1207 } else if (strpos($_SERVER['HTTP_USER_AGENT'], '[ZSEBOT]') !== false ) { // Zoomspider
1208 return true;
1209 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSNBOT') !== false ) { // MSN Search
1210 return true;
1211 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yandex') !== false ) {
1212 return true;
1213 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'AltaVista') !== false ) {
1214 return true;
1217 return false;
1221 * This class solves the problem of how to initialise $OUTPUT.
1223 * The problem is caused be two factors
1224 * <ol>
1225 * <li>On the one hand, we cannot be sure when output will start. In particular,
1226 * an error, which needs to be displayed, could be thrown at any time.</li>
1227 * <li>On the other hand, we cannot be sure when we will have all the information
1228 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1229 * (potentially) depends on the current course, course categories, and logged in user.
1230 * It also depends on whether the current page requires HTTPS.</li>
1231 * </ol>
1233 * So, it is hard to find a single natural place during Moodle script execution,
1234 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1235 * adopt the following strategy
1236 * <ol>
1237 * <li>We will initialise $OUTPUT the first time it is used.</li>
1238 * <li>If, after $OUTPUT has been initialised, the script tries to change something
1239 * that $OUTPUT depends on, we throw an exception making it clear that the script
1240 * did something wrong.
1241 * </ol>
1243 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1244 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1245 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1246 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1248 * Note that this class is used before lib/outputlib.php has been loaded, so we
1249 * must be careful referring to classes/functions from there, they may not be
1250 * defined yet, and we must avoid fatal errors.
1252 * @copyright 2009 Tim Hunt
1253 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1254 * @since Moodle 2.0
1256 class bootstrap_renderer {
1258 * Handles re-entrancy. Without this, errors or debugging output that occur
1259 * during the initialisation of $OUTPUT, cause infinite recursion.
1260 * @var boolean
1262 protected $initialising = false;
1265 * Have we started output yet?
1266 * @return boolean true if the header has been printed.
1268 public function has_started() {
1269 return false;
1272 public function __call($method, $arguments) {
1273 global $OUTPUT, $PAGE;
1275 $recursing = false;
1276 if ($method == 'notification') {
1277 // Catch infinite recursion caused by debugging output during print_header.
1278 $backtrace = debug_backtrace();
1279 array_shift($backtrace);
1280 array_shift($backtrace);
1281 $recursing = is_early_init($backtrace);
1284 $earlymethods = array(
1285 'fatal_error' => 'early_error',
1286 'notification' => 'early_notification',
1289 // If lib/outputlib.php has been loaded, call it.
1290 if (!empty($PAGE) && !$recursing) {
1291 if (array_key_exists($method, $earlymethods)) {
1292 //prevent PAGE->context warnings - exceptions might appear before we set any context
1293 $PAGE->set_context(null);
1295 $PAGE->initialise_theme_and_output();
1296 return call_user_func_array(array($OUTPUT, $method), $arguments);
1299 $this->initialising = true;
1301 // Too soon to initialise $OUTPUT, provide a couple of key methods.
1302 if (array_key_exists($method, $earlymethods)) {
1303 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1306 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1310 * Returns nicely formatted error message in a div box.
1311 * @return string
1313 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1314 global $CFG;
1316 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1317 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1318 width: 80%; -moz-border-radius: 20px; padding: 15px">
1319 ' . $message . '
1320 </div>';
1321 if (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER) {
1322 if (!empty($debuginfo)) {
1323 $debuginfo = s($debuginfo); // removes all nasty JS
1324 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1325 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
1327 if (!empty($backtrace)) {
1328 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1332 return $content;
1336 * This function should only be called by this class, or from exception handlers
1337 * @return string
1339 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1340 global $CFG;
1342 if (CLI_SCRIPT) {
1343 echo "!!! $message !!!\n";
1344 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1345 if (!empty($debuginfo)) {
1346 echo "\nDebug info: $debuginfo";
1348 if (!empty($backtrace)) {
1349 echo "\nStack trace: " . format_backtrace($backtrace, true);
1352 return;
1354 } else if (AJAX_SCRIPT) {
1355 $e = new stdClass();
1356 $e->error = $message;
1357 $e->stacktrace = NULL;
1358 $e->debuginfo = NULL;
1359 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1360 if (!empty($debuginfo)) {
1361 $e->debuginfo = $debuginfo;
1363 if (!empty($backtrace)) {
1364 $e->stacktrace = format_backtrace($backtrace, true);
1367 @header('Content-Type: application/json; charset=utf-8');
1368 echo json_encode($e);
1369 return;
1372 // In the name of protocol correctness, monitoring and performance
1373 // profiling, set the appropriate error headers for machine consumption
1374 if (isset($_SERVER['SERVER_PROTOCOL'])) {
1375 // Avoid it with cron.php. Note that we assume it's HTTP/1.x
1376 // The 503 ode here means our Moodle does not work at all, the error happened too early
1377 @header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
1380 // better disable any caching
1381 @header('Content-Type: text/html; charset=utf-8');
1382 @header('Cache-Control: no-store, no-cache, must-revalidate');
1383 @header('Cache-Control: post-check=0, pre-check=0', false);
1384 @header('Pragma: no-cache');
1385 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1386 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1388 if (function_exists('get_string')) {
1389 $strerror = get_string('error');
1390 } else {
1391 $strerror = 'Error';
1394 $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
1396 return self::plain_page($strerror, $content);
1399 public static function early_notification($message, $classes = 'notifyproblem') {
1400 return '<div class="' . $classes . '">' . $message . '</div>';
1403 public static function plain_redirect_message($encodedurl) {
1404 $message = '<p>' . get_string('pageshouldredirect') . '</p><p><a href="'.
1405 $encodedurl .'">'. get_string('continue') .'</a></p>';
1406 return self::plain_page(get_string('redirect'), $message);
1409 protected static function plain_page($title, $content) {
1410 if (function_exists('get_string') && function_exists('get_html_lang')) {
1411 $htmllang = get_html_lang();
1412 } else {
1413 $htmllang = '';
1416 return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1417 <html xmlns="http://www.w3.org/1999/xhtml" ' . $htmllang . '>
1418 <head>
1419 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1420 <title>' . $title . '</title>
1421 </head><body>' . $content . '</body></html>';