Automatic installer lang files (20101122)
[moodle.git] / lib / setuplib.php
blob33ddf81c7f4e58f5f674984a6d00de4a328d7f0b
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 * 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.
61 * @package core
62 * @subpackage lib
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 {};
69 /**
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).
75 * @package core
76 * @subpackage lib
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 {
81 public $errorcode;
82 public $module;
83 public $a;
84 public $link;
85 public $debuginfo;
87 /**
88 * Constructor
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') {
97 $module = 'error';
100 $this->errorcode = $errorcode;
101 $this->module = $module;
102 $this->link = $link;
103 $this->a = $a;
104 $this->debuginfo = $debuginfo;
106 if (get_string_manager()->string_exists($errorcode, $module)) {
107 $message = get_string($errorcode, $module, $a);
108 } else {
109 $message = $module . '/' . $errorcode;
112 parent::__construct($message, 0);
117 * Course/activity access exception.
119 * This exception is thrown from require_login()
121 * @package core
122 * @subpackage lib
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 {
140 * Constructor
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.
153 * @package core
154 * @subpackage lib
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);
165 } else {
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.
176 * @package core
177 * @subpackage lib
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 {
183 * Constructor
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.
198 * @package core
199 * @subpackage lib
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 {
205 * Constructor
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 {
221 * Constructor
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.
236 * @package core
237 * @subpackage lib
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 {
243 * Constructor
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
255 * @package core
256 * @subpackage lib
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 {
262 * Constructor
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
273 * @package core
274 * @subpackage lib
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 {
280 * Constructor
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);
314 } else {
315 try {
316 if ($DB) {
317 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
318 $DB->set_debug(0);
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);
328 } else {
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.
341 * @param int $errno
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);
353 return false;
357 * Unconditionally abort all database transactions, this function
358 * should be called from exception handlers only.
359 * @return void
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) {
393 $matches = true;
394 foreach ($pattern as $property => $value) {
395 if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
396 $matches = false;
399 if ($matches) {
400 return true;
404 return false;
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
427 * @return object
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;
435 $a = $ex->a;
436 $link = $ex->link;
437 $debuginfo = $ex->debuginfo;
438 } else {
439 $errorcode = 'generalexceptionmessage';
440 $module = 'error';
441 $a = $ex->getMessage();
442 $link = '';
443 $debuginfo = null;
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') {
452 $module = 'error';
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);
460 } else {
461 $message = $module . '/' . $errorcode;
463 } else {
464 $message = $module . '/' . $errorcode;
467 // Be careful, no guarantee weblib.php is loaded.
468 if (function_exists('clean_text')) {
469 $message = clean_text($message);
470 } else {
471 $message = htmlspecialchars($message);
474 if (!empty($CFG->errordocroot)) {
475 $errordocroot = $CFG->errordocroot;
476 } else if (!empty($CFG->docroot)) {
477 $errordocroot = $CFG->docroot;
478 } else {
479 $errordocroot = 'http://docs.moodle.org';
481 if ($module === 'error') {
482 $modulelink = 'moodle';
483 } else {
484 $modulelink = $module;
486 $moreinfourl = $errordocroot . '/en/error/' . $modulelink . '/' . $errorcode;
488 if (empty($link)) {
489 if (!empty($SESSION->fromurl)) {
490 $link = $SESSION->fromurl;
491 unset($SESSION->fromurl);
492 } else {
493 $link = $CFG->wwwroot .'/';
497 $info = new stdClass();
498 $info->message = $message;
499 $info->errorcode = $errorcode;
500 $info->backtrace = $backtrace;
501 $info->link = $link;
502 $info->moreinfourl = $moreinfourl;
503 $info->a = $a;
504 $info->debuginfo = $debuginfo;
506 return $info;
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)) {
521 return '';
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>';
547 return $from;
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') {
565 return true;
567 return false;
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
590 * @return void
592 function initialise_cfg() {
593 global $CFG, $DB;
595 try {
596 if ($DB) {
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
601 continue;
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
613 * setup.php.
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');
623 if (CLI_SCRIPT) {
624 initialise_fullme_cli();
625 return;
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);
639 } else {
640 // Probably some weird external script
641 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
642 return;
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');
651 } else {
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;
705 } else {
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() {
720 $rurl = array();
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) {
726 //Apache server
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 $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
754 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
756 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
757 //cherokee - not officially supported
758 $rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ? 'http' : 'https';
759 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
761 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
762 //zeus - not officially supported
763 $rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ? 'http' : 'https';
764 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
766 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
767 //LiteSpeed - not officially supported
768 $rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ? 'http' : 'https';
769 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
771 } else {
772 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
774 return $rurl;
778 * Initializes our performance info early.
780 * Pairs up with get_performance_info() which is actually
781 * in moodlelib.php. This function is here so that we can
782 * call it before all the libs are pulled in.
784 * @uses $PERF
786 function init_performance_info() {
788 global $PERF, $CFG, $USER;
790 $PERF = new stdClass();
791 $PERF->logwrites = 0;
792 if (function_exists('microtime')) {
793 $PERF->starttime = microtime();
795 if (function_exists('memory_get_usage')) {
796 $PERF->startmemory = memory_get_usage();
798 if (function_exists('posix_times')) {
799 $PERF->startposixtimes = posix_times();
801 if (function_exists('apd_set_pprof_trace')) {
802 // APD profiling
803 if ($USER->id > 0 && $CFG->perfdebug >= 15) {
804 $tempdir = $CFG->dataroot . '/temp/profile/' . $USER->id;
805 mkdir($tempdir);
806 apd_set_pprof_trace($tempdir);
807 $PERF->profiling = true;
813 * Indicates whether we are in the middle of the initial Moodle install.
815 * Very occasionally it is necessary avoid running certain bits of code before the
816 * Moodle installation has completed. The installed flag is set in admin/index.php
817 * after Moodle core and all the plugins have been installed, but just before
818 * the person doing the initial install is asked to choose the admin password.
820 * @return boolean true if the initial install is not complete.
822 function during_initial_install() {
823 global $CFG;
824 return empty($CFG->rolesactive);
828 * Function to raise the memory limit to a new value.
829 * Will respect the memory limit if it is higher, thus allowing
830 * settings in php.ini, apache conf or command line switches
831 * to override it.
833 * The memory limit should be expressed with a constant
834 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
835 * It is possible to use strings or integers too (eg:'128M').
837 * @param mixed $newlimit the new memory limit
838 * @return bool success
840 function raise_memory_limit($newlimit) {
841 global $CFG;
843 if ($newlimit == MEMORY_UNLIMITED) {
844 ini_set('memory_limit', -1);
845 return true;
847 } else if ($newlimit == MEMORY_STANDARD) {
848 if (PHP_INT_SIZE > 4) {
849 $newlimit = get_real_size('128M'); // 64bit needs more memory
850 } else {
851 $newlimit = get_real_size('96M');
854 } else if ($newlimit == MEMORY_EXTRA) {
855 if (PHP_INT_SIZE > 4) {
856 $newlimit = get_real_size('384M'); // 64bit needs more memory
857 } else {
858 $newlimit = get_real_size('256M');
860 if (!empty($CFG->extramemorylimit)) {
861 $extra = get_real_size($CFG->extramemorylimit);
862 if ($extra > $newlimit) {
863 $newlimit = $extra;
867 } else if ($newlimit == MEMORY_HUGE) {
868 $newlimit = get_real_size('2G');
870 } else {
871 $newlimit = get_real_size($newlimit);
874 if ($newlimit <= 0) {
875 debugging('Invalid memory limit specified.');
876 return false;
879 $cur = ini_get('memory_limit');
880 if (empty($cur)) {
881 // if php is compiled without --enable-memory-limits
882 // apparently memory_limit is set to ''
883 $cur = 0;
884 } else {
885 if ($cur == -1){
886 return true; // unlimited mem!
888 $cur = get_real_size($cur);
891 if ($newlimit > $cur) {
892 ini_set('memory_limit', $newlimit);
893 return true;
895 return false;
899 * Function to reduce the memory limit to a new value.
900 * Will respect the memory limit if it is lower, thus allowing
901 * settings in php.ini, apache conf or command line switches
902 * to override it
904 * The memory limit should be expressed with a string (eg:'64M')
906 * @param string $newlimit the new memory limit
907 * @return bool
909 function reduce_memory_limit($newlimit) {
910 if (empty($newlimit)) {
911 return false;
913 $cur = ini_get('memory_limit');
914 if (empty($cur)) {
915 // if php is compiled without --enable-memory-limits
916 // apparently memory_limit is set to ''
917 $cur = 0;
918 } else {
919 if ($cur == -1){
920 return true; // unlimited mem!
922 $cur = get_real_size($cur);
925 $new = get_real_size($newlimit);
926 // -1 is smaller, but it means unlimited
927 if ($new < $cur && $new != -1) {
928 ini_set('memory_limit', $newlimit);
929 return true;
931 return false;
935 * Converts numbers like 10M into bytes.
937 * @param string $size The size to be converted
938 * @return int
940 function get_real_size($size = 0) {
941 if (!$size) {
942 return 0;
944 $scan = array();
945 $scan['GB'] = 1073741824;
946 $scan['Gb'] = 1073741824;
947 $scan['G'] = 1073741824;
948 $scan['MB'] = 1048576;
949 $scan['Mb'] = 1048576;
950 $scan['M'] = 1048576;
951 $scan['m'] = 1048576;
952 $scan['KB'] = 1024;
953 $scan['Kb'] = 1024;
954 $scan['K'] = 1024;
955 $scan['k'] = 1024;
957 while (list($key) = each($scan)) {
958 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
959 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
960 break;
963 return $size;
967 * Try to disable all output buffering and purge
968 * all headers.
970 * @private to be called only from lib/setup.php !
971 * @return void
973 function disable_output_buffering() {
974 $olddebug = error_reporting(0);
976 // disable compression, it would prevent closing of buffers
977 if (ini_get_bool('zlib.output_compression')) {
978 ini_set('zlib.output_compression', 'Off');
981 // try to flush everything all the time
982 ob_implicit_flush(true);
984 // close all buffers if possible and discard any existing output
985 // this can actually work around some whitespace problems in config.php
986 while(ob_get_level()) {
987 if (!ob_end_clean()) {
988 // prevent infinite loop when buffer can not be closed
989 break;
993 error_reporting($olddebug);
997 * Check whether a major upgrade is needed. That is defined as an upgrade that
998 * changes something really fundamental in the database, so nothing can possibly
999 * work until the database has been updated, and that is defined by the hard-coded
1000 * version number in this function.
1002 function redirect_if_major_upgrade_required() {
1003 global $CFG;
1004 $lastmajordbchanges = 2010111700;
1005 if (empty($CFG->version) or (int)$CFG->version < $lastmajordbchanges or
1006 during_initial_install() or !empty($CFG->adminsetuppending)) {
1007 try {
1008 @session_get_instance()->terminate_current();
1009 } catch (Exception $e) {
1010 // Ignore any errors, redirect to upgrade anyway.
1012 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
1013 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1014 @header('Location: ' . $url);
1015 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
1016 exit;
1021 * Function to check if a directory exists and by default create it if not exists.
1023 * Previously this was accepting paths only from dataroot, but we now allow
1024 * files outside of dataroot if you supply custom paths for some settings in config.php.
1025 * This function does not verify that the directory is writable.
1027 * @param string $dir absolute directory path
1028 * @param boolean $create directory if does not exist
1029 * @param boolean $recursive create directory recursively
1030 * @return boolean true if directory exists or created, false otherwise
1032 function check_dir_exists($dir, $create = true, $recursive = true) {
1033 global $CFG;
1035 umask(0000); // just in case some evil code changed it
1037 if (is_dir($dir)) {
1038 return true;
1041 if (!$create) {
1042 return false;
1045 return mkdir($dir, $CFG->directorypermissions, $recursive);
1049 * Create a directory in dataroot and make sure it is writable.
1051 * @param string $directory a string of directory names under $CFG->dataroot eg temp/something
1052 * @param bool $exceptiononerror throw exception if error encountered
1053 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1055 function make_upload_directory($directory, $exceptiononerror = true) {
1056 global $CFG;
1058 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1059 if (!file_exists("$CFG->dataroot/.htaccess")) {
1060 if ($handle = fopen("$CFG->dataroot/.htaccess", 'w')) { // For safety
1061 @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");
1062 @fclose($handle);
1066 $dir = "$CFG->dataroot/$directory";
1068 if (file_exists($dir) and !is_dir($dir)) {
1069 if ($exceptiononerror) {
1070 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1071 } else {
1072 return false;
1076 umask(0000); // just in case some evil code changed it
1078 if (!file_exists($dir)) {
1079 if (!mkdir($dir, $CFG->directorypermissions, true)) {
1080 if ($exceptiononerror) {
1081 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1082 } else {
1083 return false;
1088 if (!is_writable($dir)) {
1089 if ($exceptiononerror) {
1090 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1091 } else {
1092 return false;
1096 return $dir;
1099 function init_memcached() {
1100 global $CFG, $MCACHE;
1102 include_once($CFG->libdir . '/memcached.class.php');
1103 $MCACHE = new memcached;
1104 if ($MCACHE->status()) {
1105 return true;
1107 unset($MCACHE);
1108 return false;
1111 function init_eaccelerator() {
1112 global $CFG, $MCACHE;
1114 include_once($CFG->libdir . '/eaccelerator.class.php');
1115 $MCACHE = new eaccelerator;
1116 if ($MCACHE->status()) {
1117 return true;
1119 unset($MCACHE);
1120 return false;
1125 * This class solves the problem of how to initialise $OUTPUT.
1127 * The problem is caused be two factors
1128 * <ol>
1129 * <li>On the one hand, we cannot be sure when output will start. In particular,
1130 * an error, which needs to be displayed, could be thrown at any time.</li>
1131 * <li>On the other hand, we cannot be sure when we will have all the information
1132 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1133 * (potentially) depends on the current course, course categories, and logged in user.
1134 * It also depends on whether the current page requires HTTPS.</li>
1135 * </ol>
1137 * So, it is hard to find a single natural place during Moodle script execution,
1138 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1139 * adopt the following strategy
1140 * <ol>
1141 * <li>We will initialise $OUTPUT the first time it is used.</li>
1142 * <li>If, after $OUTPUT has been initialised, the script tries to change something
1143 * that $OUTPUT depends on, we throw an exception making it clear that the script
1144 * did something wrong.
1145 * </ol>
1147 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1148 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1149 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1150 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1152 * Note that this class is used before lib/outputlib.php has been loaded, so we
1153 * must be careful referring to classes/functions from there, they may not be
1154 * defined yet, and we must avoid fatal errors.
1156 * @copyright 2009 Tim Hunt
1157 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1158 * @since Moodle 2.0
1160 class bootstrap_renderer {
1162 * Handles re-entrancy. Without this, errors or debugging output that occur
1163 * during the initialisation of $OUTPUT, cause infinite recursion.
1164 * @var boolean
1166 protected $initialising = false;
1169 * Have we started output yet?
1170 * @return boolean true if the header has been printed.
1172 public function has_started() {
1173 return false;
1176 public function __call($method, $arguments) {
1177 global $OUTPUT, $PAGE;
1179 $recursing = false;
1180 if ($method == 'notification') {
1181 // Catch infinite recursion caused by debugging output during print_header.
1182 $backtrace = debug_backtrace();
1183 array_shift($backtrace);
1184 array_shift($backtrace);
1185 $recursing = is_early_init($backtrace);
1188 $earlymethods = array(
1189 'fatal_error' => 'early_error',
1190 'notification' => 'early_notification',
1193 // If lib/outputlib.php has been loaded, call it.
1194 if (!empty($PAGE) && !$recursing) {
1195 if (array_key_exists($method, $earlymethods)) {
1196 //prevent PAGE->context warnings - exceptions might appear before we set any context
1197 $PAGE->set_context(null);
1199 $PAGE->initialise_theme_and_output();
1200 return call_user_func_array(array($OUTPUT, $method), $arguments);
1203 $this->initialising = true;
1205 // Too soon to initialise $OUTPUT, provide a couple of key methods.
1206 if (array_key_exists($method, $earlymethods)) {
1207 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1210 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1214 * Returns nicely formatted error message in a div box.
1215 * @return string
1217 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1218 global $CFG;
1220 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1221 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1222 width: 80%; -moz-border-radius: 20px; padding: 15px">
1223 ' . $message . '
1224 </div>';
1225 if (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER) {
1226 if (!empty($debuginfo)) {
1227 $debuginfo = s($debuginfo); // removes all nasty JS
1228 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1229 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
1231 if (!empty($backtrace)) {
1232 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1236 return $content;
1240 * This function should only be called by this class, or from exception handlers
1241 * @return string
1243 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1244 global $CFG;
1246 if (CLI_SCRIPT) {
1247 echo "!!! $message !!!\n";
1248 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1249 if (!empty($debuginfo)) {
1250 echo "\nDebug info: $debuginfo";
1252 if (!empty($backtrace)) {
1253 echo "\nStack trace: " . format_backtrace($backtrace, true);
1256 return;
1258 } else if (AJAX_SCRIPT) {
1259 $e = new stdClass();
1260 $e->error = $message;
1261 $e->stacktrace = NULL;
1262 $e->debuginfo = NULL;
1263 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1264 if (!empty($debuginfo)) {
1265 $e->debuginfo = $debuginfo;
1267 if (!empty($backtrace)) {
1268 $e->stacktrace = format_backtrace($backtrace, true);
1271 @header('Content-Type: application/json');
1272 echo json_encode($e);
1273 return;
1276 // In the name of protocol correctness, monitoring and performance
1277 // profiling, set the appropriate error headers for machine consumption
1278 if (isset($_SERVER['SERVER_PROTOCOL'])) {
1279 // Avoid it with cron.php. Note that we assume it's HTTP/1.x
1280 // The 503 ode here means our Moodle does not work at all, the error happened too early
1281 @header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
1284 // better disable any caching
1285 @header('Content-Type: text/html; charset=utf-8');
1286 @header('Cache-Control: no-store, no-cache, must-revalidate');
1287 @header('Cache-Control: post-check=0, pre-check=0', false);
1288 @header('Pragma: no-cache');
1289 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1290 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1292 if (function_exists('get_string')) {
1293 $strerror = get_string('error');
1294 } else {
1295 $strerror = 'Error';
1298 $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
1300 return self::plain_page($strerror, $content);
1303 public static function early_notification($message, $classes = 'notifyproblem') {
1304 return '<div class="' . $classes . '">' . $message . '</div>';
1307 public static function plain_redirect_message($encodedurl) {
1308 $message = '<p>' . get_string('pageshouldredirect') . '</p><p><a href="'.
1309 $encodedurl .'">'. get_string('continue') .'</a></p>';
1310 return self::plain_page(get_string('redirect'), $message);
1313 protected static function plain_page($title, $content) {
1314 if (function_exists('get_string') && function_exists('get_html_lang')) {
1315 $htmllang = get_html_lang();
1316 } else {
1317 $htmllang = '';
1320 return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1321 <html xmlns="http://www.w3.org/1999/xhtml" ' . $htmllang . '>
1322 <head>
1323 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1324 <title>' . $title . '</title>
1325 </head><body>' . $content . '</body></html>';