adding new forced upgrade version
[moodle.git] / lib / setuplib.php
CommitLineData
b37eac91 1<?php
d3f9f1f8 2
b37eac91 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.
14//
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/>.
17
18
19/**
20 * These functions are required very early in the Moodle
21 * setup process, before any of the main libraries are
22 * loaded.
30fa50d0 23 *
b37eac91 24 * @package moodlecore
25 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 */
d3f9f1f8 28
c84a2dbe 29/// Debug levels ///
30/** no warnings at all */
31define ('DEBUG_NONE', 0);
32/** E_ERROR | E_PARSE */
33define ('DEBUG_MINIMAL', 5);
34/** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */
35define ('DEBUG_NORMAL', 15);
36/** E_ALL without E_STRICT for now, do show recoverable fatal errors */
37define ('DEBUG_ALL', 6143);
38/** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL | 32768) */
39define ('DEBUG_DEVELOPER', 38911);
40
6a525ce2 41/**
b08b3569 42 * Simple class. It is usually used instead of stdClass because it looks
1387fcdd 43 * more familiar to Java developers ;-) Do not use for type checking of
b08b3569 44 * function parameters.
b37eac91 45 *
46 * @package moodlecore
47 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6a525ce2 49 */
b08b3569 50class object extends stdClass {};
6a525ce2 51
251387d0 52/**
53 * Base Moodle Exception class
b37eac91 54 *
c84a2dbe 55 * Although this class is defined here, you cannot throw a moodle_exception until
56 * after moodlelib.php has been included (which will happen very soon).
57 *
b37eac91 58 * @package moodlecore
59 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
60 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
251387d0 61 */
62class moodle_exception extends Exception {
63 public $errorcode;
64 public $module;
65 public $a;
66 public $link;
eee5d9bb 67 public $debuginfo;
251387d0 68
69 /**
70 * Constructor
71 * @param string $errorcode The name of the string from error.php to print
72 * @param string $module name of module
73 * @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.
74 * @param object $a Extra words and phrases that might be required in the error string
eee5d9bb 75 * @param string $debuginfo optional debugging information
251387d0 76 */
5ca18631 77 function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
78 if (empty($module) || $module == 'moodle' || $module == 'core') {
251387d0 79 $module = 'error';
80 }
81
5ca18631 82 $this->errorcode = $errorcode;
83 $this->module = $module;
84 $this->link = $link;
85 $this->a = $a;
86 $this->debuginfo = $debuginfo;
251387d0 87
5ca18631 88 $message = get_string($errorcode, $module, $a);
251387d0 89
90 parent::__construct($message, 0);
91 }
92}
93
559a5dbd 94/**
95 * Web service parameter exception class
96 *
97 * This exception must be thrown to the web service client when a web service parameter is invalid
98 * The error string is gotten from webservice.php
99 */
100class webservice_parameter_exception extends moodle_exception {
101 /**
102 * Constructor
103 * @param string $errorcode The name of the string from webservice.php to print
104 * @param string $a The name of the parameter
105 */
106 function __construct($errorcode=null, $a = '') {
107 parent::__construct($errorcode, 'webservice', '', $a, null);
108 }
109}
110
9a0df45a 111/**
112 * Exceptions indicating user does not have permissions to do something
113 * and the execution can not continue.
114 */
115class required_capability_exception extends moodle_exception {
116 function __construct($context, $capability, $errormessage, $stringfile) {
117 $capabilityname = get_capability_string($capability);
118 parent::__construct($errormessage, $stringfile, get_context_url($context), $capabilityname);
119 }
120}
121
655bbf51 122/**
cce1b0b9 123 * Exception indicating programming error, must be fixed by a programer. For example
124 * a core API might throw this type of exception if a plugin calls it incorrectly.
b37eac91 125 *
126 * @package moodlecore
127 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
128 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
655bbf51 129 */
130class coding_exception extends moodle_exception {
655bbf51 131 /**
132 * Constructor
133 * @param string $hint short description of problem
134 * @param string $debuginfo detailed information how to fix problem
135 */
136 function __construct($hint, $debuginfo=null) {
137 parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
a3f7cbf6 138 }
139}
140
141/**
142 * Exception indicating malformed parameter problem.
143 * This exception is not supposed to be thrown when processing
144 * user submitted data in forms. It is more suitable
145 * for WS and other low level stuff.
146 */
147class invalid_parameter_exception extends moodle_exception {
148 /**
149 * Constructor
150 * @param string $debuginfo some detailed information
151 */
152 function __construct($debuginfo=null) {
153 parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
655bbf51 154 }
155}
156
d07ff72d 157/**
158 * Exception indicating malformed response problem.
159 * This exception is not supposed to be thrown when processing
160 * user submitted data in forms. It is more suitable
161 * for WS and other low level stuff.
162 */
163class invalid_response_exception extends moodle_exception {
164 /**
165 * Constructor
166 * @param string $debuginfo some detailed information
167 */
168 function __construct($debuginfo=null) {
169 parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
170 }
171}
172
cce1b0b9 173/**
1387fcdd 174 * An exception that indicates something really weird happened. For example,
cce1b0b9 175 * if you do switch ($context->contextlevel), and have one case for each
176 * CONTEXT_... constant. You might throw an invalid_state_exception in the
f630a546 177 * default case, to just in case something really weird is going on, and
8dc0ae8f 178 * $context->contextlevel is invalid - rather than ignoring this possibility.
b37eac91 179 *
180 * @package moodlecore
181 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
182 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
cce1b0b9 183 */
184class invalid_state_exception extends moodle_exception {
185 /**
186 * Constructor
187 * @param string $hint short description of problem
188 * @param string $debuginfo optional more detailed information
189 */
190 function __construct($hint, $debuginfo=null) {
191 parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
192 }
193}
194
251387d0 195/**
1387fcdd 196 * Default exception handler, uncaught exceptions are equivalent to error() in 1.9 and earlier
fd1a792e 197 *
30fa50d0 198 * @param Exception $ex
c19bc39c 199 * @return void -does not return. Terminates execution!
251387d0 200 */
c19bc39c 201function default_exception_handler($ex) {
695c5ec4 202 global $DB, $OUTPUT;
1fbdf76d 203
204 // detect active db transactions, rollback and log as error
695c5ec4 205 abort_all_db_transactions();
1fe1d104 206
c19bc39c 207 $info = get_exception_info($ex);
34a2777c 208
c19bc39c 209 if (debugging('', DEBUG_MINIMAL)) {
2e9b772f 210 $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
695c5ec4 211 error_log($logerrmsg);
fd1a792e 212 }
213
c19bc39c
PS
214 if (is_early_init($info->backtrace)) {
215 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
b7009474 216 } else {
3c1ea58b 217 try {
a56c457e
PS
218 if ($DB) {
219 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
220 $DB->set_debug(0);
221 }
3c1ea58b
PS
222 echo $OUTPUT->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
223 } catch (Exception $out_ex) {
224 // default exception handler MUST not throw any exceptions!!
2e9b772f 225 // 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
3c1ea58b 226 // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
1adaa404
PS
227 if (CLI_SCRIPT or AJAX_SCRIPT) {
228 // just ignore the error and send something back using the safest method
229 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
230 } else {
231 echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
232 $outinfo = get_exception_info($out_ex);
233 echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
234 }
3c1ea58b 235 }
7544d13c 236 }
237
34a2777c 238 exit(1); // General error code
239}
240
695c5ec4
PS
241/**
242 * Unconditionally abort all database transactions, this function
243 * should be called from exception handlers only.
244 * @return void
245 */
246function abort_all_db_transactions() {
247 global $CFG, $DB, $SCRIPT;
248
d5a8d9aa 249 // default exception handler MUST not throw any exceptions!!
03221650 250
695c5ec4
PS
251 if ($DB && $DB->is_transaction_started()) {
252 error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
d5a8d9aa
PS
253 // note: transaction blocks should never change current $_SESSION
254 $DB->force_transaction_rollback();
695c5ec4
PS
255 }
256}
257
b7009474 258/**
50764d37
PS
259 * This function encapsulates the tests for whether an exception was thrown in
260 * early init -- either during setup.php or during init of $OUTPUT.
b7009474 261 *
262 * If another exception is thrown then, and if we do not take special measures,
263 * we would just get a very cryptic message "Exception thrown without a stack
264 * frame in Unknown on line 0". That makes debugging very hard, so we do take
265 * special measures in default_exception_handler, with the help of this function.
266 *
267 * @param array $backtrace the stack trace to analyse.
268 * @return boolean whether the stack trace is somewhere in output initialisation.
269 */
50764d37 270function is_early_init($backtrace) {
b7009474 271 $dangerouscode = array(
272 array('function' => 'header', 'type' => '->'),
273 array('class' => 'bootstrap_renderer'),
50764d37 274 array('file' => dirname(__FILE__).'/setup.php'),
b7009474 275 );
276 foreach ($backtrace as $stackframe) {
277 foreach ($dangerouscode as $pattern) {
278 $matches = true;
279 foreach ($pattern as $property => $value) {
280 if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
281 $matches = false;
282 }
283 }
284 if ($matches) {
285 return true;
286 }
287 }
288 }
289 return false;
290}
291
34a2777c 292/**
cbf05caa
PS
293 * Abort execution by throwing of a general exception,
294 * default exception handler displays the error message in most cases.
34a2777c 295 *
296 * @param string $errorcode The name of the language string containing the error message.
297 * Normally this should be in the error.php lang file.
298 * @param string $module The language file to get the error message from.
299 * @param string $link The url where the user will be prompted to continue.
300 * If no url is provided the user will be directed to the site index page.
301 * @param object $a Extra words and phrases that might be required in the error string
cbf05caa
PS
302 * @param string $debuginfo optional debugging information
303 * @return void, always throws exception!
34a2777c 304 */
cbf05caa
PS
305function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
306 throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
34a2777c 307}
308
309/**
c19bc39c
PS
310 * Returns detailed information about specified exception.
311 * @param exception $ex
312 * @return object
34a2777c 313 */
c19bc39c 314function get_exception_info($ex) {
34a2777c 315 global $CFG, $DB, $SESSION;
316
c19bc39c
PS
317 if ($ex instanceof moodle_exception) {
318 $errorcode = $ex->errorcode;
319 $module = $ex->module;
320 $a = $ex->a;
321 $link = $ex->link;
322 $debuginfo = $ex->debuginfo;
323 } else {
324 $errorcode = 'generalexceptionmessage';
325 $module = 'error';
326 $a = $ex->getMessage();
327 $link = '';
328 $debuginfo = null;
34a2777c 329 }
330
c19bc39c
PS
331 $backtrace = $ex->getTrace();
332 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
333 array_unshift($backtrace, $place);
334
c84a2dbe 335 // Be careful, no guarantee moodlelib.php is loaded.
34a2777c 336 if (empty($module) || $module == 'moodle' || $module == 'core') {
337 $module = 'error';
338 }
c84a2dbe 339 if (function_exists('get_string')) {
340 $message = get_string($errorcode, $module, $a);
341 if ($module === 'error' and strpos($message, '[[') === 0) {
342 // Search in moodle file if error specified - needed for backwards compatibility
343 $message = get_string($errorcode, 'moodle', $a);
344 }
345 } else {
346 $message = $module . '/' . $errorcode;
347 }
348
349 // Be careful, no guarantee weblib.php is loaded.
350 if (function_exists('clean_text')) {
351 $message = clean_text($message);
352 } else {
353 $message = htmlspecialchars($message);
34a2777c 354 }
34a2777c 355
356 if (!empty($CFG->errordocroot)) {
357 $errordocroot = $CFG->errordocroot;
358 } else if (!empty($CFG->docroot)) {
359 $errordocroot = $CFG->docroot;
360 } else {
361 $errordocroot = 'http://docs.moodle.org';
362 }
363 if ($module === 'error') {
364 $modulelink = 'moodle';
0ae8f5fc 365 } else {
34a2777c 366 $modulelink = $module;
251387d0 367 }
34a2777c 368 $moreinfourl = $errordocroot . '/en/error/' . $modulelink . '/' . $errorcode;
369
d4a03c00 370 if (empty($link)) {
34a2777c 371 if (!empty($SESSION->fromurl)) {
372 $link = $SESSION->fromurl;
373 unset($SESSION->fromurl);
374 } else {
375 $link = $CFG->wwwroot .'/';
376 }
377 }
378
c19bc39c
PS
379 $info = new object();
380 $info->message = $message;
381 $info->errorcode = $errorcode;
382 $info->backtrace = $backtrace;
383 $info->link = $link;
384 $info->moreinfourl = $moreinfourl;
385 $info->a = $a;
386 $info->debuginfo = $debuginfo;
30fa50d0 387
c19bc39c 388 return $info;
34a2777c 389}
390
34a2777c 391/**
392 * Formats a backtrace ready for output.
393 *
394 * @param array $callers backtrace array, as returned by debug_backtrace().
395 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
396 * @return string formatted backtrace, ready for output.
397 */
398function format_backtrace($callers, $plaintext = false) {
a0394be4 399 // do not use $CFG->dirroot because it might not be available in destructors
34a2777c 400 $dirroot = dirname(dirname(__FILE__));
30fa50d0 401
34a2777c 402 if (empty($callers)) {
403 return '';
404 }
405
406 $from = $plaintext ? '' : '<ul style="text-align: left">';
407 foreach ($callers as $caller) {
408 if (!isset($caller['line'])) {
409 $caller['line'] = '?'; // probably call_user_func()
410 }
411 if (!isset($caller['file'])) {
412 $caller['file'] = 'unknownfile'; // probably call_user_func()
413 }
414 $from .= $plaintext ? '* ' : '<li>';
415 $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
416 if (isset($caller['function'])) {
417 $from .= ': call to ';
418 if (isset($caller['class'])) {
419 $from .= $caller['class'] . $caller['type'];
420 }
421 $from .= $caller['function'] . '()';
422 } else if (isset($caller['exception'])) {
423 $from .= ': '.$caller['exception'].' thrown';
424 }
425 $from .= $plaintext ? "\n" : '</li>';
426 }
427 $from .= $plaintext ? '' : '</ul>';
428
429 return $from;
251387d0 430}
6a525ce2 431
fbf2c91e 432/**
433 * This function verifies the sanity of PHP configuration
434 * and stops execution if anything critical found.
435 */
436function setup_validate_php_configuration() {
437 // this must be very fast - no slow checks here!!!
438
439 if (ini_get_bool('register_globals')) {
440 print_error('globalswarning', 'admin');
441 }
442 if (ini_get_bool('session.auto_start')) {
443 print_error('sessionautostartwarning', 'admin');
444 }
445 if (ini_get_bool('magic_quotes_runtime')) {
446 print_error('fatalmagicquotesruntime', 'admin');
447 }
448}
449
11e7b506 450/**
75781f87 451 * Initialises $FULLME and friends. Private function. Should only be called from
452 * setup.php.
11e7b506 453 */
454function initialise_fullme() {
455 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
456
75781f87 457 // Detect common config error.
84b88cfd 458 if (substr($CFG->wwwroot, -1) == '/') {
459 print_error('wwwrootslash', 'error');
460 }
461
75781f87 462 if (CLI_SCRIPT) {
463 initialise_fullme_cli();
464 return;
37ccf1fe 465 }
11e7b506 466
75781f87 467 $wwwroot = parse_url($CFG->wwwroot);
468 if (!isset($wwwroot['path'])) {
469 $wwwroot['path'] = '';
470 }
471 $wwwroot['path'] .= '/';
472
473 $rurl = setup_get_remote_url();
11e7b506 474
75781f87 475 // Check that URL is under $CFG->wwwroot.
476 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
477 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
478 } else {
479 // Probably some weird external script
480 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
11e7b506 481 return;
482 }
483
75781f87 484 // $CFG->sslproxy specifies if external SSL appliance is used
485 // (That is, the Moodle server uses http, with an external box translating everything to https).
486 if (empty($CFG->sslproxy)) {
487 if ($rurl['scheme'] == 'http' and $wwwroot['scheme'] == 'https') {
488 print_error('sslonlyaccess', 'error');
489 }
490 }
491
492 // $CFG->reverseproxy specifies if reverse proxy server used.
493 // Used in load balancing scenarios.
494 // Do not abuse this to try to solve lan/wan access problems!!!!!
495 if (empty($CFG->reverseproxy)) {
496 if (($rurl['host'] != $wwwroot['host']) or
497 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port'])) {
498 print_error('wwwrootmismatch', 'error', '', $CFG->wwwroot);
499 }
500 }
501
502 // hopefully this will stop all those "clever" admins trying to set up moodle
503 // with two different addresses in intranet and Internet
504 if (!empty($CFG->reverseproxy) && $rurl['host'] == $wwwroot['host']) {
505 print_error('reverseproxyabused', 'error');
506 }
507
508 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
509 if (!empty($wwwroot['port'])) {
510 $hostandport .= ':'.$wwwroot['port'];
511 }
512
513 $FULLSCRIPT = $hostandport . $rurl['path'];
514 $FULLME = $hostandport . $rurl['fullpath'];
515 $ME = $rurl['fullpath'];
516 $rurl['path'] = $rurl['fullpath'];
517}
518
519/**
520 * Initialises $FULLME and friends for command line scripts.
521 * This is a private method for use by initialise_fullme.
522 */
523function initialise_fullme_cli() {
80e30f25 524 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
525
75781f87 526 // Urls do not make much sense in CLI scripts
527 $backtrace = debug_backtrace();
528 $topfile = array_pop($backtrace);
529 $topfile = realpath($topfile['file']);
530 $dirroot = realpath($CFG->dirroot);
531
532 if (strpos($topfile, $dirroot) !== 0) {
533 // Probably some weird external script
534 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
535 } else {
536 $relativefile = substr($topfile, strlen($dirroot));
537 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
538 $SCRIPT = $FULLSCRIPT = $relativefile;
539 $FULLME = $ME = null;
540 }
541}
542
543/**
544 * Get the URL that PHP/the web server thinks it is serving. Private function
545 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
546 * @return array in the same format that parse_url returns, with the addition of
547 * a 'fullpath' element, which includes any slasharguments path.
548 */
549function setup_get_remote_url() {
11e7b506 550 $rurl = array();
75781f87 551 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
11e7b506 552 $rurl['port'] = $_SERVER['SERVER_PORT'];
75781f87 553 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
11e7b506 554
555 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
556 //Apache server
557 $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
558 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
559
560 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
199c1981 561 //lighttpd - not officially supported
11e7b506 562 $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
563 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
564
7e13a265 565 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
199c1981 566 //nginx - not officially supported
7e13a265 567 $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
568 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
569
11e7b506 570 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
199c1981 571 //IIS - needs a lot of tweaking to make it work
11e7b506 572 $rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ? 'http' : 'https';
573 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
574
575 // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
576 // since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
21517960 577 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
11e7b506 578
579 if ($_SERVER['QUERY_STRING'] != '') {
991ec2ee 580 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
11e7b506 581 }
582 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
583
199c1981
PS
584 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
585 //cherokee - not officially supported
586 $rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ? 'http' : 'https';
587 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
588
11e7b506 589 } else {
75781f87 590 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
11e7b506 591 }
75781f87 592 return $rurl;
11e7b506 593}
594
d3f9f1f8 595/**
596 * Initializes our performance info early.
597 *
598 * Pairs up with get_performance_info() which is actually
251387d0 599 * in moodlelib.php. This function is here so that we can
600 * call it before all the libs are pulled in.
d3f9f1f8 601 *
602 * @uses $PERF
603 */
604function init_performance_info() {
605
6fc4ad72 606 global $PERF, $CFG, $USER;
251387d0 607
ab130a0b 608 $PERF = new object();
d3f9f1f8 609 $PERF->logwrites = 0;
610 if (function_exists('microtime')) {
611 $PERF->starttime = microtime();
c84a2dbe 612 }
d3f9f1f8 613 if (function_exists('memory_get_usage')) {
614 $PERF->startmemory = memory_get_usage();
615 }
616 if (function_exists('posix_times')) {
251387d0 617 $PERF->startposixtimes = posix_times();
d3f9f1f8 618 }
b65567f4 619 if (function_exists('apd_set_pprof_trace')) {
620 // APD profiling
6fc4ad72 621 if ($USER->id > 0 && $CFG->perfdebug >= 15) {
251387d0 622 $tempdir = $CFG->dataroot . '/temp/profile/' . $USER->id;
6fc4ad72 623 mkdir($tempdir);
624 apd_set_pprof_trace($tempdir);
625 $PERF->profiling = true;
626 }
b65567f4 627 }
d3f9f1f8 628}
629
31a99877 630/**
631 * Indicates whether we are in the middle of the initial Moodle install.
632 *
633 * Very occasionally it is necessary avoid running certain bits of code before the
634 * Moodle installation has completed. The installed flag is set in admin/index.php
635 * after Moodle core and all the plugins have been installed, but just before
636 * the person doing the initial install is asked to choose the admin password.
637 *
638 * @return boolean true if the initial install is not complete.
639 */
640function during_initial_install() {
641 global $CFG;
642 return empty($CFG->rolesactive);
643}
644
76f3815b 645/**
646 * Function to raise the memory limit to a new value.
647 * Will respect the memory limit if it is higher, thus allowing
648 * settings in php.ini, apache conf or command line switches
649 * to override it
650 *
651 * The memory limit should be expressed with a string (eg:'64M')
652 *
653 * @param string $newlimit the new memory limit
654 * @return bool
655 */
11e7b506 656function raise_memory_limit($newlimit) {
76f3815b 657
658 if (empty($newlimit)) {
659 return false;
660 }
661
662 $cur = @ini_get('memory_limit');
663 if (empty($cur)) {
664 // if php is compiled without --enable-memory-limits
665 // apparently memory_limit is set to ''
666 $cur=0;
667 } else {
668 if ($cur == -1){
669 return true; // unlimited mem!
670 }
671 $cur = get_real_size($cur);
672 }
673
674 $new = get_real_size($newlimit);
675 if ($new > $cur) {
676 ini_set('memory_limit', $newlimit);
7022dd39 677 return true;
678 }
679 return false;
680}
681
682/**
683 * Function to reduce the memory limit to a new value.
684 * Will respect the memory limit if it is lower, thus allowing
685 * settings in php.ini, apache conf or command line switches
686 * to override it
687 *
688 * The memory limit should be expressed with a string (eg:'64M')
689 *
690 * @param string $newlimit the new memory limit
691 * @return bool
692 */
f630a546 693function reduce_memory_limit($newlimit) {
7022dd39 694 if (empty($newlimit)) {
695 return false;
696 }
697 $cur = @ini_get('memory_limit');
698 if (empty($cur)) {
699 // if php is compiled without --enable-memory-limits
700 // apparently memory_limit is set to ''
701 $cur=0;
702 } else {
703 if ($cur == -1){
704 return true; // unlimited mem!
705 }
706 $cur = get_real_size($cur);
707 }
708
709 $new = get_real_size($newlimit);
710 // -1 is smaller, but it means unlimited
711 if ($new < $cur && $new != -1) {
712 ini_set('memory_limit', $newlimit);
76f3815b 713 return true;
714 }
715 return false;
716}
717
718/**
719 * Converts numbers like 10M into bytes.
720 *
721 * @param mixed $size The size to be converted
722 * @return mixed
723 */
724function get_real_size($size=0) {
725 if (!$size) {
726 return 0;
727 }
11e7b506 728 $scan = array();
76f3815b 729 $scan['MB'] = 1048576;
730 $scan['Mb'] = 1048576;
731 $scan['M'] = 1048576;
732 $scan['m'] = 1048576;
733 $scan['KB'] = 1024;
734 $scan['Kb'] = 1024;
735 $scan['K'] = 1024;
736 $scan['k'] = 1024;
737
738 while (list($key) = each($scan)) {
739 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
740 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
741 break;
742 }
743 }
744 return $size;
745}
746
5e39d7aa 747/**
748 * Check whether a major upgrade is needed. That is defined as an upgrade that
749 * changes something really fundamental in the database, so nothing can possibly
750 * work until the database has been updated, and that is defined by the hard-coded
751 * version number in this function.
752 */
753function redirect_if_major_upgrade_required() {
754 global $CFG;
b81e18f8 755 $lastmajordbchanges = 2010042303;
5e39d7aa 756 if (empty($CFG->version) or (int)$CFG->version < $lastmajordbchanges or
757 during_initial_install() or !empty($CFG->adminsetuppending)) {
758 try {
759 @session_get_instance()->terminate_current();
760 } catch (Exception $e) {
761 // Ignore any errors, redirect to upgrade anyway.
762 }
a38c7a10 763 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
5e39d7aa 764 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
a38c7a10
PS
765 @header('Location: ' . $url);
766 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
5e39d7aa 767 exit;
768 }
769}
770
d3f9f1f8 771/**
772 * Create a directory.
773 *
774 * @uses $CFG
775 * @param string $directory a string of directory names under $CFG->dataroot eg stuff/assignment/1
776 * param bool $shownotices If true then notification messages will be printed out on error.
777 * @return string|false Returns full path to directory if successful, false if not
778 */
779function make_upload_directory($directory, $shownotices=true) {
780
781 global $CFG;
782
783 $currdir = $CFG->dataroot;
784
785 umask(0000);
786
787 if (!file_exists($currdir)) {
b10a14a3 788 if (!mkdir($currdir, $CFG->directorypermissions) or !is_writable($currdir)) {
d3f9f1f8 789 if ($shownotices) {
251387d0 790 echo '<div class="notifyproblem" align="center">ERROR: You need to create the directory '.
d3f9f1f8 791 $currdir .' with web server write access</div>'."<br />\n";
792 }
793 return false;
794 }
d100b8a0 795 }
796
797 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open
798 if (!file_exists($currdir.'/.htaccess')) {
d3f9f1f8 799 if ($handle = fopen($currdir.'/.htaccess', 'w')) { // For safety
edaf04d4 800 @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");
d3f9f1f8 801 @fclose($handle);
802 }
803 }
804
805 $dirarray = explode('/', $directory);
806
807 foreach ($dirarray as $dir) {
808 $currdir = $currdir .'/'. $dir;
809 if (! file_exists($currdir)) {
810 if (! mkdir($currdir, $CFG->directorypermissions)) {
811 if ($shownotices) {
251387d0 812 echo '<div class="notifyproblem" align="center">ERROR: Could not find or create a directory ('.
d3f9f1f8 813 $currdir .')</div>'."<br />\n";
814 }
815 return false;
816 }
817 //@chmod($currdir, $CFG->directorypermissions); // Just in case mkdir didn't do it
818 }
819 }
820
821 return $currdir;
822}
823
419e1d93 824function init_memcached() {
825 global $CFG, $MCACHE;
826
f917d0ea 827 include_once($CFG->libdir . '/memcached.class.php');
828 $MCACHE = new memcached;
829 if ($MCACHE->status()) {
830 return true;
251387d0 831 }
f917d0ea 832 unset($MCACHE);
251387d0 833 return false;
419e1d93 834}
835
2142d492 836function init_eaccelerator() {
837 global $CFG, $MCACHE;
838
839 include_once($CFG->libdir . '/eaccelerator.class.php');
840 $MCACHE = new eaccelerator;
f917d0ea 841 if ($MCACHE->status()) {
2142d492 842 return true;
251387d0 843 }
2142d492 844 unset($MCACHE);
845 return false;
846}
847
848
c84a2dbe 849/**
850 * This class solves the problem of how to initialise $OUTPUT.
851 *
852 * The problem is caused be two factors
853 * <ol>
854 * <li>On the one hand, we cannot be sure when output will start. In particular,
30fa50d0 855 * an error, which needs to be displayed, could be thrown at any time.</li>
c84a2dbe 856 * <li>On the other hand, we cannot be sure when we will have all the information
857 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
858 * (potentially) depends on the current course, course categories, and logged in user.
859 * It also depends on whether the current page requires HTTPS.</li>
860 * </ol>
861 *
862 * So, it is hard to find a single natural place during Moodle script execution,
863 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
864 * adopt the following strategy
865 * <ol>
866 * <li>We will initialise $OUTPUT the first time it is used.</li>
867 * <li>If, after $OUTPUT has been initialised, the script tries to change something
7e0d6675 868 * that $OUTPUT depends on, we throw an exception making it clear that the script
c84a2dbe 869 * did something wrong.
870 * </ol>
871 *
872 * The only problem with that is, how do we initialise $OUTPUT on first use if,
873 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
874 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
875 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
876 *
877 * Note that this class is used before lib/outputlib.php has been loaded, so we
1387fcdd 878 * must be careful referring to classes/functions from there, they may not be
c84a2dbe 879 * defined yet, and we must avoid fatal errors.
880 *
881 * @copyright 2009 Tim Hunt
882 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
883 * @since Moodle 2.0
884 */
885class bootstrap_renderer {
886 /**
887 * Handles re-entrancy. Without this, errors or debugging output that occur
888 * during the initialisation of $OUTPUT, cause infinite recursion.
889 * @var boolean
890 */
891 protected $initialising = false;
892
b7009474 893 /**
894 * Have we started output yet?
895 * @return boolean true if the header has been printed.
896 */
897 public function has_started() {
898 return false;
899 }
900
c84a2dbe 901 public function __call($method, $arguments) {
b7009474 902 global $OUTPUT, $PAGE;
c84a2dbe 903
87b6851c 904 $recursing = false;
905 if ($method == 'notification') {
1387fcdd 906 // Catch infinite recursion caused by debugging output during print_header.
87b6851c 907 $backtrace = debug_backtrace();
908 array_shift($backtrace);
909 array_shift($backtrace);
50764d37 910 $recursing = is_early_init($backtrace);
87b6851c 911 }
912
c84a2dbe 913 // If lib/outputlib.php has been loaded, call it.
87b6851c 914 if (!empty($PAGE) && !$recursing) {
b7009474 915 $PAGE->initialise_theme_and_output();
916 return call_user_func_array(array($OUTPUT, $method), $arguments);
c84a2dbe 917 }
2142d492 918
c84a2dbe 919 $this->initialising = true;
920 // Too soon to initialise $OUTPUT, provide a couple of key methods.
921 $earlymethods = array(
922 'fatal_error' => 'early_error',
923 'notification' => 'early_notification',
924 );
925 if (array_key_exists($method, $earlymethods)) {
926 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
927 }
928
929 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
930 }
931
932 /**
1387fcdd 933 * Returns nicely formatted error message in a div box.
30fa50d0 934 * @return string
c84a2dbe 935 */
3c1ea58b 936 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
b7009474 937 global $CFG;
938
3c1ea58b
PS
939 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
940border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
941width: 80%; -moz-border-radius: 20px; padding: 15px">
942' . $message . '
943</div>';
944 if (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER) {
945 if (!empty($debuginfo)) {
c5d18164
PS
946 $debuginfo = s($debuginfo); // removes all nasty JS
947 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
948 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
3c1ea58b
PS
949 }
950 if (!empty($backtrace)) {
951 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
952 }
953 }
954
955 return $content;
956 }
957
958 /**
959 * This function should only be called by this class, or from exception handlers
960 * @return string
961 */
962 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1adaa404
PS
963 global $CFG;
964
965 if (CLI_SCRIPT) {
966 echo "!!! $message !!!\n";
967 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
968 if (!empty($debuginfo)) {
969 echo "\nDebug info: $debuginfo";
970 }
971 if (!empty($backtrace)) {
972 echo "\nStack trace: " . format_backtrace($backtrace, true);
973 }
974 }
975 return;
976
977 } else if (AJAX_SCRIPT) {
978 $e = new stdClass();
979 $e->error = $message;
980 $e->stacktrace = NULL;
981 $e->debuginfo = NULL;
982 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
983 if (!empty($debuginfo)) {
984 $e->debuginfo = $debuginfo;
985 }
986 if (!empty($backtrace)) {
987 $e->stacktrace = format_backtrace($backtrace, true);
988 }
989 }
990 echo json_encode($e);
991 return;
992 }
993
c84a2dbe 994 // In the name of protocol correctness, monitoring and performance
1387fcdd 995 // profiling, set the appropriate error headers for machine consumption
c84a2dbe 996 if (isset($_SERVER['SERVER_PROTOCOL'])) {
997 // Avoid it with cron.php. Note that we assume it's HTTP/1.x
1387fcdd 998 // The 503 ode here means our Moodle does not work at all, the error happened too early
c84a2dbe 999 @header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
1000 }
1001
1002 // better disable any caching
1003 @header('Content-Type: text/html; charset=utf-8');
1004 @header('Cache-Control: no-store, no-cache, must-revalidate');
1005 @header('Cache-Control: post-check=0, pre-check=0', false);
1006 @header('Pragma: no-cache');
1007 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1008 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1009
5e39d7aa 1010 if (function_exists('get_string')) {
c84a2dbe 1011 $strerror = get_string('error');
1012 } else {
c84a2dbe 1013 $strerror = 'Error';
1014 }
1015
3c1ea58b 1016 $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
5e39d7aa 1017
1018 return self::plain_page($strerror, $content);
c84a2dbe 1019 }
1020
1021 public static function early_notification($message, $classes = 'notifyproblem') {
1022 return '<div class="' . $classes . '">' . $message . '</div>';
1023 }
5e39d7aa 1024
1025 public static function plain_redirect_message($encodedurl) {
1026 $message = '<p>' . get_string('pageshouldredirect') . '</p><p><a href="'.
1027 $encodedurl .'">'. get_string('continue') .'</a></p>';
a0a268d5 1028 return self::plain_page(get_string('redirect'), $message);
5e39d7aa 1029 }
1030
1031 protected static function plain_page($title, $content) {
1032 if (function_exists('get_string') && function_exists('get_html_lang')) {
1033 $htmllang = get_html_lang();
1034 } else {
1035 $htmllang = '';
1036 }
1037
1038 return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1039<html xmlns="http://www.w3.org/1999/xhtml" ' . $htmllang . '>
1040<head>
1041<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1042<title>' . $title . '</title>
1043</head><body>' . $content . '</body></html>';
1044 }
c84a2dbe 1045}