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