MDL-25314 adding some header/session related notes
[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
11e7b506 724
725 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
726 //Apache server
727 $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
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['scheme'] = ($_SERVER['HTTPS'] == 'off') ? 'http' : 'https';
733 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
734
735 // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
736 // since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
21517960 737 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
11e7b506 738
739 if ($_SERVER['QUERY_STRING'] != '') {
991ec2ee 740 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
11e7b506 741 }
742 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
743
f49b359b
PS
744/* NOTE: following servers are not fully tested! */
745
746 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
747 //lighttpd - not officially supported
748 $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
749 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
750
751 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
752 //nginx - not officially supported
753 $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
754 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
755
199c1981
PS
756 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
757 //cherokee - not officially supported
758 $rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ? 'http' : 'https';
759 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
760
8b8aa060
PS
761 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
762 //zeus - not officially supported
763 $rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ? 'http' : 'https';
764 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
765
f49b359b
PS
766 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
767 //LiteSpeed - not officially supported
768 $rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ? 'http' : 'https';
769 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
770
8b8aa060 771 } else {
75781f87 772 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
11e7b506 773 }
75781f87 774 return $rurl;
11e7b506 775}
776
d3f9f1f8 777/**
778 * Initializes our performance info early.
779 *
780 * Pairs up with get_performance_info() which is actually
251387d0 781 * in moodlelib.php. This function is here so that we can
782 * call it before all the libs are pulled in.
d3f9f1f8 783 *
784 * @uses $PERF
785 */
786function init_performance_info() {
787
6fc4ad72 788 global $PERF, $CFG, $USER;
251387d0 789
365a5941 790 $PERF = new stdClass();
d3f9f1f8 791 $PERF->logwrites = 0;
792 if (function_exists('microtime')) {
793 $PERF->starttime = microtime();
c84a2dbe 794 }
d3f9f1f8 795 if (function_exists('memory_get_usage')) {
796 $PERF->startmemory = memory_get_usage();
797 }
798 if (function_exists('posix_times')) {
251387d0 799 $PERF->startposixtimes = posix_times();
d3f9f1f8 800 }
b65567f4 801 if (function_exists('apd_set_pprof_trace')) {
802 // APD profiling
6fc4ad72 803 if ($USER->id > 0 && $CFG->perfdebug >= 15) {
251387d0 804 $tempdir = $CFG->dataroot . '/temp/profile/' . $USER->id;
6fc4ad72 805 mkdir($tempdir);
806 apd_set_pprof_trace($tempdir);
807 $PERF->profiling = true;
808 }
b65567f4 809 }
d3f9f1f8 810}
811
31a99877 812/**
813 * Indicates whether we are in the middle of the initial Moodle install.
814 *
815 * Very occasionally it is necessary avoid running certain bits of code before the
816 * Moodle installation has completed. The installed flag is set in admin/index.php
817 * after Moodle core and all the plugins have been installed, but just before
818 * the person doing the initial install is asked to choose the admin password.
819 *
820 * @return boolean true if the initial install is not complete.
821 */
822function during_initial_install() {
823 global $CFG;
824 return empty($CFG->rolesactive);
825}
826
76f3815b 827/**
828 * Function to raise the memory limit to a new value.
829 * Will respect the memory limit if it is higher, thus allowing
830 * settings in php.ini, apache conf or command line switches
0f0f0768 831 * to override it.
76f3815b 832 *
0f0f0768
PS
833 * The memory limit should be expressed with a constant
834 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
835 * It is possible to use strings or integers too (eg:'128M').
76f3815b 836 *
0f0f0768
PS
837 * @param mixed $newlimit the new memory limit
838 * @return bool success
76f3815b 839 */
11e7b506 840function raise_memory_limit($newlimit) {
0f0f0768 841 global $CFG;
76f3815b 842
0f0f0768
PS
843 if ($newlimit == MEMORY_UNLIMITED) {
844 ini_set('memory_limit', -1);
845 return true;
846
847 } else if ($newlimit == MEMORY_STANDARD) {
cd3059b1
PS
848 if (PHP_INT_SIZE > 4) {
849 $newlimit = get_real_size('128M'); // 64bit needs more memory
850 } else {
851 $newlimit = get_real_size('96M');
852 }
0f0f0768
PS
853
854 } else if ($newlimit == MEMORY_EXTRA) {
cd3059b1
PS
855 if (PHP_INT_SIZE > 4) {
856 $newlimit = get_real_size('384M'); // 64bit needs more memory
857 } else {
858 $newlimit = get_real_size('256M');
859 }
d827f7b8 860 if (!empty($CFG->extramemorylimit)) {
0f0f0768
PS
861 $extra = get_real_size($CFG->extramemorylimit);
862 if ($extra > $newlimit) {
863 $newlimit = $extra;
864 }
865 }
866
867 } else if ($newlimit == MEMORY_HUGE) {
868 $newlimit = get_real_size('2G');
869
870 } else {
871 $newlimit = get_real_size($newlimit);
872 }
873
874 if ($newlimit <= 0) {
875 debugging('Invalid memory limit specified.');
76f3815b 876 return false;
877 }
878
cbad562e 879 $cur = ini_get('memory_limit');
76f3815b 880 if (empty($cur)) {
881 // if php is compiled without --enable-memory-limits
882 // apparently memory_limit is set to ''
0f0f0768 883 $cur = 0;
76f3815b 884 } else {
885 if ($cur == -1){
886 return true; // unlimited mem!
887 }
0f0f0768 888 $cur = get_real_size($cur);
76f3815b 889 }
890
0f0f0768 891 if ($newlimit > $cur) {
76f3815b 892 ini_set('memory_limit', $newlimit);
7022dd39 893 return true;
894 }
895 return false;
896}
897
898/**
899 * Function to reduce the memory limit to a new value.
900 * Will respect the memory limit if it is lower, thus allowing
901 * settings in php.ini, apache conf or command line switches
902 * to override it
903 *
904 * The memory limit should be expressed with a string (eg:'64M')
905 *
906 * @param string $newlimit the new memory limit
907 * @return bool
908 */
f630a546 909function reduce_memory_limit($newlimit) {
7022dd39 910 if (empty($newlimit)) {
911 return false;
912 }
cbad562e 913 $cur = ini_get('memory_limit');
7022dd39 914 if (empty($cur)) {
915 // if php is compiled without --enable-memory-limits
916 // apparently memory_limit is set to ''
0f0f0768 917 $cur = 0;
7022dd39 918 } else {
919 if ($cur == -1){
920 return true; // unlimited mem!
921 }
922 $cur = get_real_size($cur);
923 }
924
925 $new = get_real_size($newlimit);
926 // -1 is smaller, but it means unlimited
927 if ($new < $cur && $new != -1) {
928 ini_set('memory_limit', $newlimit);
76f3815b 929 return true;
930 }
931 return false;
932}
933
934/**
935 * Converts numbers like 10M into bytes.
936 *
0f0f0768
PS
937 * @param string $size The size to be converted
938 * @return int
76f3815b 939 */
0f0f0768 940function get_real_size($size = 0) {
76f3815b 941 if (!$size) {
942 return 0;
943 }
11e7b506 944 $scan = array();
0f0f0768
PS
945 $scan['GB'] = 1073741824;
946 $scan['Gb'] = 1073741824;
947 $scan['G'] = 1073741824;
76f3815b 948 $scan['MB'] = 1048576;
949 $scan['Mb'] = 1048576;
950 $scan['M'] = 1048576;
951 $scan['m'] = 1048576;
952 $scan['KB'] = 1024;
953 $scan['Kb'] = 1024;
954 $scan['K'] = 1024;
955 $scan['k'] = 1024;
956
957 while (list($key) = each($scan)) {
958 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
959 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
960 break;
961 }
962 }
963 return $size;
964}
965
cbad562e 966/**
871ed458
PS
967 * Try to disable all output buffering and purge
968 * all headers.
969 *
cbad562e
PS
970 * @private to be called only from lib/setup.php !
971 * @return void
972 */
973function disable_output_buffering() {
974 $olddebug = error_reporting(0);
975
976 // disable compression, it would prevent closing of buffers
977 if (ini_get_bool('zlib.output_compression')) {
978 ini_set('zlib.output_compression', 'Off');
979 }
980
981 // try to flush everything all the time
982 ob_implicit_flush(true);
983
984 // close all buffers if possible and discard any existing output
985 // this can actually work around some whitespace problems in config.php
986 while(ob_get_level()) {
987 if (!ob_end_clean()) {
988 // prevent infinite loop when buffer can not be closed
989 break;
990 }
991 }
992
993 error_reporting($olddebug);
994}
995
5e39d7aa 996/**
997 * Check whether a major upgrade is needed. That is defined as an upgrade that
998 * changes something really fundamental in the database, so nothing can possibly
999 * work until the database has been updated, and that is defined by the hard-coded
1000 * version number in this function.
1001 */
1002function redirect_if_major_upgrade_required() {
1003 global $CFG;
2c0b6ab2 1004 $lastmajordbchanges = 2010111700;
5e39d7aa 1005 if (empty($CFG->version) or (int)$CFG->version < $lastmajordbchanges or
1006 during_initial_install() or !empty($CFG->adminsetuppending)) {
1007 try {
1008 @session_get_instance()->terminate_current();
1009 } catch (Exception $e) {
1010 // Ignore any errors, redirect to upgrade anyway.
1011 }
a38c7a10 1012 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
5e39d7aa 1013 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
a38c7a10
PS
1014 @header('Location: ' . $url);
1015 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
5e39d7aa 1016 exit;
1017 }
1018}
1019
d3f9f1f8 1020/**
4031f6a2
PS
1021 * Function to check if a directory exists and by default create it if not exists.
1022 *
1023 * Previously this was accepting paths only from dataroot, but we now allow
1024 * files outside of dataroot if you supply custom paths for some settings in config.php.
1025 * This function does not verify that the directory is writable.
d3f9f1f8 1026 *
4031f6a2
PS
1027 * @param string $dir absolute directory path
1028 * @param boolean $create directory if does not exist
1029 * @param boolean $recursive create directory recursively
1030 * @return boolean true if directory exists or created, false otherwise
d3f9f1f8 1031 */
4031f6a2 1032function check_dir_exists($dir, $create = true, $recursive = true) {
d3f9f1f8 1033 global $CFG;
1034
4031f6a2 1035 umask(0000); // just in case some evil code changed it
d3f9f1f8 1036
4031f6a2
PS
1037 if (is_dir($dir)) {
1038 return true;
1039 }
d3f9f1f8 1040
4031f6a2
PS
1041 if (!$create) {
1042 return false;
d100b8a0 1043 }
1044
4031f6a2
PS
1045 return mkdir($dir, $CFG->directorypermissions, $recursive);
1046}
1047
1048/**
1049 * Create a directory in dataroot and make sure it is writable.
1050 *
1051 * @param string $directory a string of directory names under $CFG->dataroot eg temp/something
1052 * @param bool $exceptiononerror throw exception if error encountered
1053 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1054 */
1055function make_upload_directory($directory, $exceptiononerror = true) {
1056 global $CFG;
1057
1058 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1059 if (!file_exists("$CFG->dataroot/.htaccess")) {
1060 if ($handle = fopen("$CFG->dataroot/.htaccess", 'w')) { // For safety
edaf04d4 1061 @fwrite($handle, "deny from all\r\nAllowOverride None\r\nNote: this file is broken intentionally, we do not want anybody to undo it in subdirectory!\r\n");
d3f9f1f8 1062 @fclose($handle);
1063 }
1064 }
1065
4031f6a2 1066 $dir = "$CFG->dataroot/$directory";
d3f9f1f8 1067
4031f6a2
PS
1068 if (file_exists($dir) and !is_dir($dir)) {
1069 if ($exceptiononerror) {
1070 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1071 } else {
1072 return false;
1073 }
1074 }
1075
1076 umask(0000); // just in case some evil code changed it
1077
1078 if (!file_exists($dir)) {
1079 if (!mkdir($dir, $CFG->directorypermissions, true)) {
1080 if ($exceptiononerror) {
1081 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1082 } else {
d3f9f1f8 1083 return false;
1084 }
d3f9f1f8 1085 }
1086 }
1087
4031f6a2
PS
1088 if (!is_writable($dir)) {
1089 if ($exceptiononerror) {
1090 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1091 } else {
1092 return false;
1093 }
1094 }
1095
1096 return $dir;
d3f9f1f8 1097}
1098
419e1d93 1099function init_memcached() {
1100 global $CFG, $MCACHE;
1101
f917d0ea 1102 include_once($CFG->libdir . '/memcached.class.php');
1103 $MCACHE = new memcached;
1104 if ($MCACHE->status()) {
1105 return true;
251387d0 1106 }
f917d0ea 1107 unset($MCACHE);
251387d0 1108 return false;
419e1d93 1109}
1110
2142d492 1111function init_eaccelerator() {
1112 global $CFG, $MCACHE;
1113
1114 include_once($CFG->libdir . '/eaccelerator.class.php');
1115 $MCACHE = new eaccelerator;
f917d0ea 1116 if ($MCACHE->status()) {
2142d492 1117 return true;
251387d0 1118 }
2142d492 1119 unset($MCACHE);
1120 return false;
1121}
1122
1123
c84a2dbe 1124/**
1125 * This class solves the problem of how to initialise $OUTPUT.
1126 *
1127 * The problem is caused be two factors
1128 * <ol>
1129 * <li>On the one hand, we cannot be sure when output will start. In particular,
30fa50d0 1130 * an error, which needs to be displayed, could be thrown at any time.</li>
c84a2dbe 1131 * <li>On the other hand, we cannot be sure when we will have all the information
1132 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1133 * (potentially) depends on the current course, course categories, and logged in user.
1134 * It also depends on whether the current page requires HTTPS.</li>
1135 * </ol>
1136 *
1137 * So, it is hard to find a single natural place during Moodle script execution,
1138 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1139 * adopt the following strategy
1140 * <ol>
1141 * <li>We will initialise $OUTPUT the first time it is used.</li>
1142 * <li>If, after $OUTPUT has been initialised, the script tries to change something
7e0d6675 1143 * that $OUTPUT depends on, we throw an exception making it clear that the script
c84a2dbe 1144 * did something wrong.
1145 * </ol>
1146 *
1147 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1148 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1149 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1150 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1151 *
1152 * Note that this class is used before lib/outputlib.php has been loaded, so we
1387fcdd 1153 * must be careful referring to classes/functions from there, they may not be
c84a2dbe 1154 * defined yet, and we must avoid fatal errors.
1155 *
1156 * @copyright 2009 Tim Hunt
1157 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1158 * @since Moodle 2.0
1159 */
1160class bootstrap_renderer {
1161 /**
1162 * Handles re-entrancy. Without this, errors or debugging output that occur
1163 * during the initialisation of $OUTPUT, cause infinite recursion.
1164 * @var boolean
1165 */
1166 protected $initialising = false;
1167
b7009474 1168 /**
1169 * Have we started output yet?
1170 * @return boolean true if the header has been printed.
1171 */
1172 public function has_started() {
1173 return false;
1174 }
1175
c84a2dbe 1176 public function __call($method, $arguments) {
b7009474 1177 global $OUTPUT, $PAGE;
c84a2dbe 1178
87b6851c 1179 $recursing = false;
1180 if ($method == 'notification') {
1387fcdd 1181 // Catch infinite recursion caused by debugging output during print_header.
87b6851c 1182 $backtrace = debug_backtrace();
1183 array_shift($backtrace);
1184 array_shift($backtrace);
50764d37 1185 $recursing = is_early_init($backtrace);
87b6851c 1186 }
1187
eb5bdb35
PS
1188 $earlymethods = array(
1189 'fatal_error' => 'early_error',
1190 'notification' => 'early_notification',
1191 );
1192
c84a2dbe 1193 // If lib/outputlib.php has been loaded, call it.
87b6851c 1194 if (!empty($PAGE) && !$recursing) {
eb5bdb35
PS
1195 if (array_key_exists($method, $earlymethods)) {
1196 //prevent PAGE->context warnings - exceptions might appear before we set any context
1197 $PAGE->set_context(null);
1198 }
b7009474 1199 $PAGE->initialise_theme_and_output();
1200 return call_user_func_array(array($OUTPUT, $method), $arguments);
c84a2dbe 1201 }
2142d492 1202
c84a2dbe 1203 $this->initialising = true;
eb5bdb35 1204
c84a2dbe 1205 // Too soon to initialise $OUTPUT, provide a couple of key methods.
c84a2dbe 1206 if (array_key_exists($method, $earlymethods)) {
1207 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1208 }
1209
1210 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1211 }
1212
1213 /**
1387fcdd 1214 * Returns nicely formatted error message in a div box.
30fa50d0 1215 * @return string
c84a2dbe 1216 */
3c1ea58b 1217 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
b7009474 1218 global $CFG;
1219
3c1ea58b
PS
1220 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1221border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1222width: 80%; -moz-border-radius: 20px; padding: 15px">
1223' . $message . '
1224</div>';
1225 if (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER) {
1226 if (!empty($debuginfo)) {
c5d18164
PS
1227 $debuginfo = s($debuginfo); // removes all nasty JS
1228 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1229 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
3c1ea58b
PS
1230 }
1231 if (!empty($backtrace)) {
1232 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1233 }
1234 }
1235
1236 return $content;
1237 }
1238
1239 /**
1240 * This function should only be called by this class, or from exception handlers
1241 * @return string
1242 */
1243 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1adaa404
PS
1244 global $CFG;
1245
1246 if (CLI_SCRIPT) {
1247 echo "!!! $message !!!\n";
1248 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1249 if (!empty($debuginfo)) {
1250 echo "\nDebug info: $debuginfo";
1251 }
1252 if (!empty($backtrace)) {
1253 echo "\nStack trace: " . format_backtrace($backtrace, true);
1254 }
1255 }
1256 return;
1257
1258 } else if (AJAX_SCRIPT) {
1259 $e = new stdClass();
1260 $e->error = $message;
1261 $e->stacktrace = NULL;
1262 $e->debuginfo = NULL;
1263 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1264 if (!empty($debuginfo)) {
1265 $e->debuginfo = $debuginfo;
1266 }
1267 if (!empty($backtrace)) {
1268 $e->stacktrace = format_backtrace($backtrace, true);
1269 }
1270 }
6db3eee0 1271 @header('Content-Type: application/json');
1adaa404
PS
1272 echo json_encode($e);
1273 return;
1274 }
1275
c84a2dbe 1276 // In the name of protocol correctness, monitoring and performance
1387fcdd 1277 // profiling, set the appropriate error headers for machine consumption
c84a2dbe 1278 if (isset($_SERVER['SERVER_PROTOCOL'])) {
1279 // Avoid it with cron.php. Note that we assume it's HTTP/1.x
1387fcdd 1280 // The 503 ode here means our Moodle does not work at all, the error happened too early
c84a2dbe 1281 @header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
1282 }
1283
1284 // better disable any caching
1285 @header('Content-Type: text/html; charset=utf-8');
1286 @header('Cache-Control: no-store, no-cache, must-revalidate');
1287 @header('Cache-Control: post-check=0, pre-check=0', false);
1288 @header('Pragma: no-cache');
1289 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1290 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1291
5e39d7aa 1292 if (function_exists('get_string')) {
c84a2dbe 1293 $strerror = get_string('error');
1294 } else {
c84a2dbe 1295 $strerror = 'Error';
1296 }
1297
3c1ea58b 1298 $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
5e39d7aa 1299
1300 return self::plain_page($strerror, $content);
c84a2dbe 1301 }
1302
1303 public static function early_notification($message, $classes = 'notifyproblem') {
1304 return '<div class="' . $classes . '">' . $message . '</div>';
1305 }
5e39d7aa 1306
1307 public static function plain_redirect_message($encodedurl) {
1308 $message = '<p>' . get_string('pageshouldredirect') . '</p><p><a href="'.
1309 $encodedurl .'">'. get_string('continue') .'</a></p>';
a0a268d5 1310 return self::plain_page(get_string('redirect'), $message);
5e39d7aa 1311 }
1312
1313 protected static function plain_page($title, $content) {
1314 if (function_exists('get_string') && function_exists('get_html_lang')) {
1315 $htmllang = get_html_lang();
1316 } else {
1317 $htmllang = '';
1318 }
1319
1320 return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1321<html xmlns="http://www.w3.org/1999/xhtml" ' . $htmllang . '>
1322<head>
1323<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1324<title>' . $title . '</title>
1325</head><body>' . $content . '</body></html>';
1326 }
c84a2dbe 1327}