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