MDL-26211 improve detection of https from _SERVER
[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
cbad562e
PS
270/**
271 * An exception that indicates that file can not be served
272 *
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
277 */
278class file_serving_exception extends moodle_exception {
279 /**
280 * Constructor
281 * @param string $debuginfo optional more detailed information
282 */
283 function __construct($debuginfo = NULL) {
284 parent::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
285 }
286}
287
251387d0 288/**
1387fcdd 289 * Default exception handler, uncaught exceptions are equivalent to error() in 1.9 and earlier
fd1a792e 290 *
30fa50d0 291 * @param Exception $ex
c19bc39c 292 * @return void -does not return. Terminates execution!
251387d0 293 */
c19bc39c 294function default_exception_handler($ex) {
d9e07264 295 global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION;
1fbdf76d 296
297 // detect active db transactions, rollback and log as error
695c5ec4 298 abort_all_db_transactions();
1fe1d104 299
d9e07264
SH
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());
303 }
304
c19bc39c 305 $info = get_exception_info($ex);
34a2777c 306
c19bc39c 307 if (debugging('', DEBUG_MINIMAL)) {
2e9b772f 308 $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
695c5ec4 309 error_log($logerrmsg);
fd1a792e 310 }
311
c19bc39c
PS
312 if (is_early_init($info->backtrace)) {
313 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
b7009474 314 } else {
3c1ea58b 315 try {
a56c457e
PS
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);
319 }
3c1ea58b
PS
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!!
2e9b772f 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
3c1ea58b 324 // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
1adaa404
PS
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);
332 }
3c1ea58b 333 }
7544d13c 334 }
335
34a2777c 336 exit(1); // General error code
337}
338
85ba1e78
PS
339/**
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
347 */
348function 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);
352 }
353 return false;
354}
355
695c5ec4
PS
356/**
357 * Unconditionally abort all database transactions, this function
358 * should be called from exception handlers only.
359 * @return void
360 */
361function abort_all_db_transactions() {
362 global $CFG, $DB, $SCRIPT;
363
d5a8d9aa 364 // default exception handler MUST not throw any exceptions!!
03221650 365
695c5ec4
PS
366 if ($DB && $DB->is_transaction_started()) {
367 error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
d5a8d9aa
PS
368 // note: transaction blocks should never change current $_SESSION
369 $DB->force_transaction_rollback();
695c5ec4
PS
370 }
371}
372
b7009474 373/**
50764d37
PS
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.
b7009474 376 *
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.
381 *
382 * @param array $backtrace the stack trace to analyse.
383 * @return boolean whether the stack trace is somewhere in output initialisation.
384 */
50764d37 385function is_early_init($backtrace) {
b7009474 386 $dangerouscode = array(
387 array('function' => 'header', 'type' => '->'),
388 array('class' => 'bootstrap_renderer'),
50764d37 389 array('file' => dirname(__FILE__).'/setup.php'),
b7009474 390 );
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;
397 }
398 }
399 if ($matches) {
400 return true;
401 }
402 }
403 }
404 return false;
405}
406
34a2777c 407/**
cbf05caa
PS
408 * Abort execution by throwing of a general exception,
409 * default exception handler displays the error message in most cases.
34a2777c 410 *
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
cbf05caa
PS
417 * @param string $debuginfo optional debugging information
418 * @return void, always throws exception!
34a2777c 419 */
cbf05caa
PS
420function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
421 throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
34a2777c 422}
423
424/**
c19bc39c
PS
425 * Returns detailed information about specified exception.
426 * @param exception $ex
427 * @return object
34a2777c 428 */
c19bc39c 429function get_exception_info($ex) {
34a2777c 430 global $CFG, $DB, $SESSION;
431
c19bc39c
PS
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;
34a2777c 444 }
445
c19bc39c
PS
446 $backtrace = $ex->getTrace();
447 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
448 array_unshift($backtrace, $place);
449
c84a2dbe 450 // Be careful, no guarantee moodlelib.php is loaded.
34a2777c 451 if (empty($module) || $module == 'moodle' || $module == 'core') {
452 $module = 'error';
453 }
4f6be42c
DM
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')) {
c84a2dbe 458 // Search in moodle file if error specified - needed for backwards compatibility
459 $message = get_string($errorcode, 'moodle', $a);
4f6be42c
DM
460 } else {
461 $message = $module . '/' . $errorcode;
c84a2dbe 462 }
463 } else {
464 $message = $module . '/' . $errorcode;
465 }
466
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);
34a2777c 472 }
34a2777c 473
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';
480 }
481 if ($module === 'error') {
482 $modulelink = 'moodle';
0ae8f5fc 483 } else {
34a2777c 484 $modulelink = $module;
251387d0 485 }
34a2777c 486 $moreinfourl = $errordocroot . '/en/error/' . $modulelink . '/' . $errorcode;
487
d4a03c00 488 if (empty($link)) {
34a2777c 489 if (!empty($SESSION->fromurl)) {
490 $link = $SESSION->fromurl;
491 unset($SESSION->fromurl);
492 } else {
493 $link = $CFG->wwwroot .'/';
494 }
495 }
496
365a5941 497 $info = new stdClass();
c19bc39c
PS
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;
30fa50d0 505
c19bc39c 506 return $info;
34a2777c 507}
508
34a2777c 509/**
510 * Formats a backtrace ready for output.
511 *
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.
515 */
516function format_backtrace($callers, $plaintext = false) {
a0394be4 517 // do not use $CFG->dirroot because it might not be available in destructors
34a2777c 518 $dirroot = dirname(dirname(__FILE__));
30fa50d0 519
34a2777c 520 if (empty($callers)) {
521 return '';
522 }
523
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()
528 }
529 if (!isset($caller['file'])) {
530 $caller['file'] = 'unknownfile'; // probably call_user_func()
531 }
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'];
538 }
539 $from .= $caller['function'] . '()';
540 } else if (isset($caller['exception'])) {
541 $from .= ': '.$caller['exception'].' thrown';
542 }
543 $from .= $plaintext ? "\n" : '</li>';
544 }
545 $from .= $plaintext ? '' : '</ul>';
546
547 return $from;
251387d0 548}
6a525ce2 549
cbad562e
PS
550/**
551 * This function makes the return value of ini_get consistent if you are
552 * setting server directives through the .htaccess file in apache.
553 *
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
557 *
558 * @param string $ini_get_arg The argument to get
559 * @return bool True for on false for not
560 */
561function ini_get_bool($ini_get_arg) {
562 $temp = ini_get($ini_get_arg);
563
564 if ($temp == '1' or strtolower($temp) == 'on') {
565 return true;
566 }
567 return false;
568}
569
fbf2c91e 570/**
571 * This function verifies the sanity of PHP configuration
572 * and stops execution if anything critical found.
573 */
574function setup_validate_php_configuration() {
575 // this must be very fast - no slow checks here!!!
576
577 if (ini_get_bool('register_globals')) {
578 print_error('globalswarning', 'admin');
579 }
580 if (ini_get_bool('session.auto_start')) {
581 print_error('sessionautostartwarning', 'admin');
582 }
583 if (ini_get_bool('magic_quotes_runtime')) {
584 print_error('fatalmagicquotesruntime', 'admin');
585 }
586}
587
12bb0c3e
PS
588/**
589 * Initialise global $CFG variable
590 * @return void
591 */
592function initialise_cfg() {
593 global $CFG, $DB;
8b8aa060 594
12bb0c3e
PS
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;
602 }
603 $CFG->{$name} = $value;
604 }
605 }
606 } catch (dml_read_exception $e) {
607 // most probably empty db, going to install soon
608 }
609}
610
11e7b506 611/**
75781f87 612 * Initialises $FULLME and friends. Private function. Should only be called from
613 * setup.php.
11e7b506 614 */
615function initialise_fullme() {
616 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
617
75781f87 618 // Detect common config error.
84b88cfd 619 if (substr($CFG->wwwroot, -1) == '/') {
620 print_error('wwwrootslash', 'error');
621 }
622
75781f87 623 if (CLI_SCRIPT) {
624 initialise_fullme_cli();
625 return;
37ccf1fe 626 }
11e7b506 627
75781f87 628 $wwwroot = parse_url($CFG->wwwroot);
629 if (!isset($wwwroot['path'])) {
630 $wwwroot['path'] = '';
631 }
632 $wwwroot['path'] .= '/';
633
634 $rurl = setup_get_remote_url();
11e7b506 635
75781f87 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;
11e7b506 642 return;
643 }
644
75781f87 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)) {
56048f83 648 if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
75781f87 649 print_error('sslonlyaccess', 'error');
650 }
56048f83
PS
651 } else {
652 if ($wwwroot['scheme'] !== 'https') {
653 throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
654 }
74162134 655 $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
75781f87 656 }
657
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'])) {
68a45361 664 // Explain the problem and redirect them to the right URL
df92ba9a
PS
665 if (!defined('NO_MOODLE_COOKIES')) {
666 define('NO_MOODLE_COOKIES', true);
667 }
68a45361 668 redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
75781f87 669 }
670 }
671
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');
676 }
677
678 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
679 if (!empty($wwwroot['port'])) {
680 $hostandport .= ':'.$wwwroot['port'];
681 }
682
683 $FULLSCRIPT = $hostandport . $rurl['path'];
684 $FULLME = $hostandport . $rurl['fullpath'];
685 $ME = $rurl['fullpath'];
686 $rurl['path'] = $rurl['fullpath'];
687}
688
689/**
690 * Initialises $FULLME and friends for command line scripts.
691 * This is a private method for use by initialise_fullme.
692 */
693function initialise_fullme_cli() {
80e30f25 694 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
695
75781f87 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);
701
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;
710 }
711}
712
713/**
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.
718 */
719function setup_get_remote_url() {
11e7b506 720 $rurl = array();
75781f87 721 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
11e7b506 722 $rurl['port'] = $_SERVER['SERVER_PORT'];
75781f87 723 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
2a9c0d05 724 $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ? 'http' : 'https';
11e7b506 725
726 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
727 //Apache server
f49b359b 728 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
7e13a265 729
11e7b506 730 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
199c1981 731 //IIS - needs a lot of tweaking to make it work
11e7b506 732 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
733
734 // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
735 // since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
21517960 736 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
11e7b506 737
738 if ($_SERVER['QUERY_STRING'] != '') {
991ec2ee 739 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
11e7b506 740 }
741 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
742
f49b359b
PS
743/* NOTE: following servers are not fully tested! */
744
745 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
746 //lighttpd - not officially supported
f49b359b
PS
747 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
748
749 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
750 //nginx - not officially supported
28ec73dc
PS
751 if (!isset($_SERVER['SCRIPT_NAME'])) {
752 die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
753 }
f49b359b
PS
754 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
755
199c1981
PS
756 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
757 //cherokee - not officially supported
199c1981
PS
758 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
759
8b8aa060
PS
760 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
761 //zeus - not officially supported
8b8aa060
PS
762 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
763
f49b359b
PS
764 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
765 //LiteSpeed - not officially supported
f49b359b
PS
766 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
767
8b8aa060 768 } else {
75781f87 769 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
11e7b506 770 }
75781f87 771 return $rurl;
11e7b506 772}
773
d3f9f1f8 774/**
775 * Initializes our performance info early.
776 *
777 * Pairs up with get_performance_info() which is actually
251387d0 778 * in moodlelib.php. This function is here so that we can
779 * call it before all the libs are pulled in.
d3f9f1f8 780 *
781 * @uses $PERF
782 */
783function init_performance_info() {
784
6fc4ad72 785 global $PERF, $CFG, $USER;
251387d0 786
365a5941 787 $PERF = new stdClass();
d3f9f1f8 788 $PERF->logwrites = 0;
789 if (function_exists('microtime')) {
790 $PERF->starttime = microtime();
c84a2dbe 791 }
d3f9f1f8 792 if (function_exists('memory_get_usage')) {
793 $PERF->startmemory = memory_get_usage();
794 }
795 if (function_exists('posix_times')) {
251387d0 796 $PERF->startposixtimes = posix_times();
d3f9f1f8 797 }
b65567f4 798 if (function_exists('apd_set_pprof_trace')) {
799 // APD profiling
6fc4ad72 800 if ($USER->id > 0 && $CFG->perfdebug >= 15) {
251387d0 801 $tempdir = $CFG->dataroot . '/temp/profile/' . $USER->id;
6fc4ad72 802 mkdir($tempdir);
803 apd_set_pprof_trace($tempdir);
804 $PERF->profiling = true;
805 }
b65567f4 806 }
d3f9f1f8 807}
808
31a99877 809/**
810 * Indicates whether we are in the middle of the initial Moodle install.
811 *
812 * Very occasionally it is necessary avoid running certain bits of code before the
813 * Moodle installation has completed. The installed flag is set in admin/index.php
814 * after Moodle core and all the plugins have been installed, but just before
815 * the person doing the initial install is asked to choose the admin password.
816 *
817 * @return boolean true if the initial install is not complete.
818 */
819function during_initial_install() {
820 global $CFG;
821 return empty($CFG->rolesactive);
822}
823
76f3815b 824/**
825 * Function to raise the memory limit to a new value.
826 * Will respect the memory limit if it is higher, thus allowing
827 * settings in php.ini, apache conf or command line switches
0f0f0768 828 * to override it.
76f3815b 829 *
0f0f0768
PS
830 * The memory limit should be expressed with a constant
831 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
832 * It is possible to use strings or integers too (eg:'128M').
76f3815b 833 *
0f0f0768
PS
834 * @param mixed $newlimit the new memory limit
835 * @return bool success
76f3815b 836 */
11e7b506 837function raise_memory_limit($newlimit) {
0f0f0768 838 global $CFG;
76f3815b 839
0f0f0768
PS
840 if ($newlimit == MEMORY_UNLIMITED) {
841 ini_set('memory_limit', -1);
842 return true;
843
844 } else if ($newlimit == MEMORY_STANDARD) {
cd3059b1
PS
845 if (PHP_INT_SIZE > 4) {
846 $newlimit = get_real_size('128M'); // 64bit needs more memory
847 } else {
848 $newlimit = get_real_size('96M');
849 }
0f0f0768
PS
850
851 } else if ($newlimit == MEMORY_EXTRA) {
cd3059b1
PS
852 if (PHP_INT_SIZE > 4) {
853 $newlimit = get_real_size('384M'); // 64bit needs more memory
854 } else {
855 $newlimit = get_real_size('256M');
856 }
d827f7b8 857 if (!empty($CFG->extramemorylimit)) {
0f0f0768
PS
858 $extra = get_real_size($CFG->extramemorylimit);
859 if ($extra > $newlimit) {
860 $newlimit = $extra;
861 }
862 }
863
864 } else if ($newlimit == MEMORY_HUGE) {
865 $newlimit = get_real_size('2G');
866
867 } else {
868 $newlimit = get_real_size($newlimit);
869 }
870
871 if ($newlimit <= 0) {
872 debugging('Invalid memory limit specified.');
76f3815b 873 return false;
874 }
875
cbad562e 876 $cur = ini_get('memory_limit');
76f3815b 877 if (empty($cur)) {
878 // if php is compiled without --enable-memory-limits
879 // apparently memory_limit is set to ''
0f0f0768 880 $cur = 0;
76f3815b 881 } else {
882 if ($cur == -1){
883 return true; // unlimited mem!
884 }
0f0f0768 885 $cur = get_real_size($cur);
76f3815b 886 }
887
0f0f0768 888 if ($newlimit > $cur) {
76f3815b 889 ini_set('memory_limit', $newlimit);
7022dd39 890 return true;
891 }
892 return false;
893}
894
895/**
896 * Function to reduce the memory limit to a new value.
897 * Will respect the memory limit if it is lower, thus allowing
898 * settings in php.ini, apache conf or command line switches
899 * to override it
900 *
901 * The memory limit should be expressed with a string (eg:'64M')
902 *
903 * @param string $newlimit the new memory limit
904 * @return bool
905 */
f630a546 906function reduce_memory_limit($newlimit) {
7022dd39 907 if (empty($newlimit)) {
908 return false;
909 }
cbad562e 910 $cur = ini_get('memory_limit');
7022dd39 911 if (empty($cur)) {
912 // if php is compiled without --enable-memory-limits
913 // apparently memory_limit is set to ''
0f0f0768 914 $cur = 0;
7022dd39 915 } else {
916 if ($cur == -1){
917 return true; // unlimited mem!
918 }
919 $cur = get_real_size($cur);
920 }
921
922 $new = get_real_size($newlimit);
923 // -1 is smaller, but it means unlimited
924 if ($new < $cur && $new != -1) {
925 ini_set('memory_limit', $newlimit);
76f3815b 926 return true;
927 }
928 return false;
929}
930
931/**
932 * Converts numbers like 10M into bytes.
933 *
0f0f0768
PS
934 * @param string $size The size to be converted
935 * @return int
76f3815b 936 */
0f0f0768 937function get_real_size($size = 0) {
76f3815b 938 if (!$size) {
939 return 0;
940 }
11e7b506 941 $scan = array();
0f0f0768
PS
942 $scan['GB'] = 1073741824;
943 $scan['Gb'] = 1073741824;
944 $scan['G'] = 1073741824;
76f3815b 945 $scan['MB'] = 1048576;
946 $scan['Mb'] = 1048576;
947 $scan['M'] = 1048576;
948 $scan['m'] = 1048576;
949 $scan['KB'] = 1024;
950 $scan['Kb'] = 1024;
951 $scan['K'] = 1024;
952 $scan['k'] = 1024;
953
954 while (list($key) = each($scan)) {
955 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
956 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
957 break;
958 }
959 }
960 return $size;
961}
962
cbad562e 963/**
871ed458
PS
964 * Try to disable all output buffering and purge
965 * all headers.
966 *
cbad562e
PS
967 * @private to be called only from lib/setup.php !
968 * @return void
969 */
970function disable_output_buffering() {
971 $olddebug = error_reporting(0);
972
973 // disable compression, it would prevent closing of buffers
974 if (ini_get_bool('zlib.output_compression')) {
975 ini_set('zlib.output_compression', 'Off');
976 }
977
978 // try to flush everything all the time
979 ob_implicit_flush(true);
980
981 // close all buffers if possible and discard any existing output
982 // this can actually work around some whitespace problems in config.php
983 while(ob_get_level()) {
984 if (!ob_end_clean()) {
985 // prevent infinite loop when buffer can not be closed
986 break;
987 }
988 }
989
990 error_reporting($olddebug);
991}
992
5e39d7aa 993/**
994 * Check whether a major upgrade is needed. That is defined as an upgrade that
995 * changes something really fundamental in the database, so nothing can possibly
996 * work until the database has been updated, and that is defined by the hard-coded
997 * version number in this function.
998 */
999function redirect_if_major_upgrade_required() {
1000 global $CFG;
2c0b6ab2 1001 $lastmajordbchanges = 2010111700;
5e39d7aa 1002 if (empty($CFG->version) or (int)$CFG->version < $lastmajordbchanges or
1003 during_initial_install() or !empty($CFG->adminsetuppending)) {
1004 try {
1005 @session_get_instance()->terminate_current();
1006 } catch (Exception $e) {
1007 // Ignore any errors, redirect to upgrade anyway.
1008 }
a38c7a10 1009 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
5e39d7aa 1010 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
a38c7a10
PS
1011 @header('Location: ' . $url);
1012 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
5e39d7aa 1013 exit;
1014 }
1015}
1016
d3f9f1f8 1017/**
4031f6a2
PS
1018 * Function to check if a directory exists and by default create it if not exists.
1019 *
1020 * Previously this was accepting paths only from dataroot, but we now allow
1021 * files outside of dataroot if you supply custom paths for some settings in config.php.
1022 * This function does not verify that the directory is writable.
d3f9f1f8 1023 *
4031f6a2
PS
1024 * @param string $dir absolute directory path
1025 * @param boolean $create directory if does not exist
1026 * @param boolean $recursive create directory recursively
1027 * @return boolean true if directory exists or created, false otherwise
d3f9f1f8 1028 */
4031f6a2 1029function check_dir_exists($dir, $create = true, $recursive = true) {
d3f9f1f8 1030 global $CFG;
1031
4031f6a2 1032 umask(0000); // just in case some evil code changed it
d3f9f1f8 1033
4031f6a2
PS
1034 if (is_dir($dir)) {
1035 return true;
1036 }
d3f9f1f8 1037
4031f6a2
PS
1038 if (!$create) {
1039 return false;
d100b8a0 1040 }
1041
4031f6a2
PS
1042 return mkdir($dir, $CFG->directorypermissions, $recursive);
1043}
1044
1045/**
1046 * Create a directory in dataroot and make sure it is writable.
1047 *
1048 * @param string $directory a string of directory names under $CFG->dataroot eg temp/something
1049 * @param bool $exceptiononerror throw exception if error encountered
1050 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1051 */
1052function make_upload_directory($directory, $exceptiononerror = true) {
1053 global $CFG;
1054
1055 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1056 if (!file_exists("$CFG->dataroot/.htaccess")) {
1057 if ($handle = fopen("$CFG->dataroot/.htaccess", 'w')) { // For safety
edaf04d4 1058 @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 1059 @fclose($handle);
1060 }
1061 }
1062
4031f6a2 1063 $dir = "$CFG->dataroot/$directory";
d3f9f1f8 1064
4031f6a2
PS
1065 if (file_exists($dir) and !is_dir($dir)) {
1066 if ($exceptiononerror) {
1067 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1068 } else {
1069 return false;
1070 }
1071 }
1072
1073 umask(0000); // just in case some evil code changed it
1074
1075 if (!file_exists($dir)) {
1076 if (!mkdir($dir, $CFG->directorypermissions, true)) {
1077 if ($exceptiononerror) {
1078 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1079 } else {
d3f9f1f8 1080 return false;
1081 }
d3f9f1f8 1082 }
1083 }
1084
4031f6a2
PS
1085 if (!is_writable($dir)) {
1086 if ($exceptiononerror) {
1087 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1088 } else {
1089 return false;
1090 }
1091 }
1092
1093 return $dir;
d3f9f1f8 1094}
1095
419e1d93 1096function init_memcached() {
1097 global $CFG, $MCACHE;
1098
f917d0ea 1099 include_once($CFG->libdir . '/memcached.class.php');
1100 $MCACHE = new memcached;
1101 if ($MCACHE->status()) {
1102 return true;
251387d0 1103 }
f917d0ea 1104 unset($MCACHE);
251387d0 1105 return false;
419e1d93 1106}
1107
2142d492 1108function init_eaccelerator() {
1109 global $CFG, $MCACHE;
1110
1111 include_once($CFG->libdir . '/eaccelerator.class.php');
1112 $MCACHE = new eaccelerator;
f917d0ea 1113 if ($MCACHE->status()) {
2142d492 1114 return true;
251387d0 1115 }
2142d492 1116 unset($MCACHE);
1117 return false;
1118}
1119
1120
c84a2dbe 1121/**
1122 * This class solves the problem of how to initialise $OUTPUT.
1123 *
1124 * The problem is caused be two factors
1125 * <ol>
1126 * <li>On the one hand, we cannot be sure when output will start. In particular,
30fa50d0 1127 * an error, which needs to be displayed, could be thrown at any time.</li>
c84a2dbe 1128 * <li>On the other hand, we cannot be sure when we will have all the information
1129 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1130 * (potentially) depends on the current course, course categories, and logged in user.
1131 * It also depends on whether the current page requires HTTPS.</li>
1132 * </ol>
1133 *
1134 * So, it is hard to find a single natural place during Moodle script execution,
1135 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1136 * adopt the following strategy
1137 * <ol>
1138 * <li>We will initialise $OUTPUT the first time it is used.</li>
1139 * <li>If, after $OUTPUT has been initialised, the script tries to change something
7e0d6675 1140 * that $OUTPUT depends on, we throw an exception making it clear that the script
c84a2dbe 1141 * did something wrong.
1142 * </ol>
1143 *
1144 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1145 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1146 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1147 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1148 *
1149 * Note that this class is used before lib/outputlib.php has been loaded, so we
1387fcdd 1150 * must be careful referring to classes/functions from there, they may not be
c84a2dbe 1151 * defined yet, and we must avoid fatal errors.
1152 *
1153 * @copyright 2009 Tim Hunt
1154 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1155 * @since Moodle 2.0
1156 */
1157class bootstrap_renderer {
1158 /**
1159 * Handles re-entrancy. Without this, errors or debugging output that occur
1160 * during the initialisation of $OUTPUT, cause infinite recursion.
1161 * @var boolean
1162 */
1163 protected $initialising = false;
1164
b7009474 1165 /**
1166 * Have we started output yet?
1167 * @return boolean true if the header has been printed.
1168 */
1169 public function has_started() {
1170 return false;
1171 }
1172
c84a2dbe 1173 public function __call($method, $arguments) {
b7009474 1174 global $OUTPUT, $PAGE;
c84a2dbe 1175
87b6851c 1176 $recursing = false;
1177 if ($method == 'notification') {
1387fcdd 1178 // Catch infinite recursion caused by debugging output during print_header.
87b6851c 1179 $backtrace = debug_backtrace();
1180 array_shift($backtrace);
1181 array_shift($backtrace);
50764d37 1182 $recursing = is_early_init($backtrace);
87b6851c 1183 }
1184
eb5bdb35
PS
1185 $earlymethods = array(
1186 'fatal_error' => 'early_error',
1187 'notification' => 'early_notification',
1188 );
1189
c84a2dbe 1190 // If lib/outputlib.php has been loaded, call it.
87b6851c 1191 if (!empty($PAGE) && !$recursing) {
eb5bdb35
PS
1192 if (array_key_exists($method, $earlymethods)) {
1193 //prevent PAGE->context warnings - exceptions might appear before we set any context
1194 $PAGE->set_context(null);
1195 }
b7009474 1196 $PAGE->initialise_theme_and_output();
1197 return call_user_func_array(array($OUTPUT, $method), $arguments);
c84a2dbe 1198 }
2142d492 1199
c84a2dbe 1200 $this->initialising = true;
eb5bdb35 1201
c84a2dbe 1202 // Too soon to initialise $OUTPUT, provide a couple of key methods.
c84a2dbe 1203 if (array_key_exists($method, $earlymethods)) {
1204 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1205 }
1206
1207 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1208 }
1209
1210 /**
1387fcdd 1211 * Returns nicely formatted error message in a div box.
30fa50d0 1212 * @return string
c84a2dbe 1213 */
3c1ea58b 1214 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
b7009474 1215 global $CFG;
1216
3c1ea58b
PS
1217 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1218border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1219width: 80%; -moz-border-radius: 20px; padding: 15px">
1220' . $message . '
1221</div>';
1222 if (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER) {
1223 if (!empty($debuginfo)) {
c5d18164
PS
1224 $debuginfo = s($debuginfo); // removes all nasty JS
1225 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1226 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
3c1ea58b
PS
1227 }
1228 if (!empty($backtrace)) {
1229 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1230 }
1231 }
1232
1233 return $content;
1234 }
1235
1236 /**
1237 * This function should only be called by this class, or from exception handlers
1238 * @return string
1239 */
1240 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1adaa404
PS
1241 global $CFG;
1242
1243 if (CLI_SCRIPT) {
1244 echo "!!! $message !!!\n";
1245 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1246 if (!empty($debuginfo)) {
1247 echo "\nDebug info: $debuginfo";
1248 }
1249 if (!empty($backtrace)) {
1250 echo "\nStack trace: " . format_backtrace($backtrace, true);
1251 }
1252 }
1253 return;
1254
1255 } else if (AJAX_SCRIPT) {
1256 $e = new stdClass();
1257 $e->error = $message;
1258 $e->stacktrace = NULL;
1259 $e->debuginfo = NULL;
1260 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1261 if (!empty($debuginfo)) {
1262 $e->debuginfo = $debuginfo;
1263 }
1264 if (!empty($backtrace)) {
1265 $e->stacktrace = format_backtrace($backtrace, true);
1266 }
1267 }
8a7703ce 1268 @header('Content-Type: application/json; charset=utf-8');
1adaa404
PS
1269 echo json_encode($e);
1270 return;
1271 }
1272
c84a2dbe 1273 // In the name of protocol correctness, monitoring and performance
1387fcdd 1274 // profiling, set the appropriate error headers for machine consumption
c84a2dbe 1275 if (isset($_SERVER['SERVER_PROTOCOL'])) {
1276 // Avoid it with cron.php. Note that we assume it's HTTP/1.x
1387fcdd 1277 // The 503 ode here means our Moodle does not work at all, the error happened too early
c84a2dbe 1278 @header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
1279 }
1280
1281 // better disable any caching
1282 @header('Content-Type: text/html; charset=utf-8');
1283 @header('Cache-Control: no-store, no-cache, must-revalidate');
1284 @header('Cache-Control: post-check=0, pre-check=0', false);
1285 @header('Pragma: no-cache');
1286 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1287 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1288
5e39d7aa 1289 if (function_exists('get_string')) {
c84a2dbe 1290 $strerror = get_string('error');
1291 } else {
c84a2dbe 1292 $strerror = 'Error';
1293 }
1294
3c1ea58b 1295 $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
5e39d7aa 1296
1297 return self::plain_page($strerror, $content);
c84a2dbe 1298 }
1299
1300 public static function early_notification($message, $classes = 'notifyproblem') {
1301 return '<div class="' . $classes . '">' . $message . '</div>';
1302 }
5e39d7aa 1303
1304 public static function plain_redirect_message($encodedurl) {
1305 $message = '<p>' . get_string('pageshouldredirect') . '</p><p><a href="'.
1306 $encodedurl .'">'. get_string('continue') .'</a></p>';
a0a268d5 1307 return self::plain_page(get_string('redirect'), $message);
5e39d7aa 1308 }
1309
1310 protected static function plain_page($title, $content) {
1311 if (function_exists('get_string') && function_exists('get_html_lang')) {
1312 $htmllang = get_html_lang();
1313 } else {
1314 $htmllang = '';
1315 }
1316
1317 return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1318<html xmlns="http://www.w3.org/1999/xhtml" ' . $htmllang . '>
1319<head>
1320<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1321<title>' . $title . '</title>
1322</head><body>' . $content . '</body></html>';
1323 }
c84a2dbe 1324}