3 // This file is part of Moodle - http://moodle.org/
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.
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.
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/>.
20 * These functions are required very early in the Moodle
21 * setup process, before any of the main libraries are
25 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
30 /** no warnings at all */
31 define ('DEBUG_NONE', 0);
32 /** E_ERROR | E_PARSE */
33 define ('DEBUG_MINIMAL', 5);
34 /** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */
35 define ('DEBUG_NORMAL', 15);
36 /** E_ALL without E_STRICT for now, do show recoverable fatal errors */
37 define ('DEBUG_ALL', 6143);
38 /** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL | 32768) */
39 define ('DEBUG_DEVELOPER', 38911);
42 * Simple class. It is usually used instead of stdClass because it looks
43 * more familiar to Java developers ;-) Do not use for type checking of
44 * function parameters.
47 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
48 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
50 class object extends stdClass {};
53 * Base Moodle Exception class
55 * Although this class is defined here, you cannot throw a moodle_exception until
56 * after moodlelib.php has been included (which will happen very soon).
59 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
60 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
62 class moodle_exception extends Exception {
71 * @param string $errorcode The name of the string from error.php to print
72 * @param string $module name of module
73 * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
74 * @param object $a Extra words and phrases that might be required in the error string
75 * @param string $debuginfo optional debugging information
77 function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
78 if (empty($module) || $module == 'moodle' || $module == 'core') {
82 $this->errorcode = $errorcode;
83 $this->module = $module;
86 $this->debuginfo = $debuginfo;
88 $message = get_string($errorcode, $module, $a);
90 parent::__construct($message, 0);
95 * Web service parameter exception class
97 * This exception must be thrown to the web service client when a web service parameter is invalid
98 * The error string is gotten from webservice.php
100 class webservice_parameter_exception extends moodle_exception {
103 * @param string $errorcode The name of the string from webservice.php to print
104 * @param string $a The name of the parameter
106 function __construct($errorcode=null, $a = '') {
107 parent::__construct($errorcode, 'webservice', '', $a, null);
112 * Exceptions indicating user does not have permissions to do something
113 * and the execution can not continue.
115 class required_capability_exception extends moodle_exception {
116 function __construct($context, $capability, $errormessage, $stringfile) {
117 $capabilityname = get_capability_string($capability);
118 parent::__construct($errormessage, $stringfile, get_context_url($context), $capabilityname);
123 * Exception indicating programming error, must be fixed by a programer. For example
124 * a core API might throw this type of exception if a plugin calls it incorrectly.
126 * @package moodlecore
127 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
128 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
130 class coding_exception extends moodle_exception {
133 * @param string $hint short description of problem
134 * @param string $debuginfo detailed information how to fix problem
136 function __construct($hint, $debuginfo=null) {
137 parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
142 * Exception indicating malformed parameter problem.
143 * This exception is not supposed to be thrown when processing
144 * user submitted data in forms. It is more suitable
145 * for WS and other low level stuff.
147 class invalid_parameter_exception extends moodle_exception {
150 * @param string $debuginfo some detailed information
152 function __construct($debuginfo=null) {
153 parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
158 * Exception indicating malformed response problem.
159 * This exception is not supposed to be thrown when processing
160 * user submitted data in forms. It is more suitable
161 * for WS and other low level stuff.
163 class invalid_response_exception extends moodle_exception {
166 * @param string $debuginfo some detailed information
168 function __construct($debuginfo=null) {
169 parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
174 * An exception that indicates something really weird happened. For example,
175 * if you do switch ($context->contextlevel), and have one case for each
176 * CONTEXT_... constant. You might throw an invalid_state_exception in the
177 * default case, to just in case something really weird is going on, and
178 * $context->contextlevel is invalid - rather than ignoring this possibility.
180 * @package moodlecore
181 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
182 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
184 class invalid_state_exception extends moodle_exception {
187 * @param string $hint short description of problem
188 * @param string $debuginfo optional more detailed information
190 function __construct($hint, $debuginfo=null) {
191 parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
196 * Default exception handler, uncaught exceptions are equivalent to error() in 1.9 and earlier
198 * @param Exception $ex
199 * @return void -does not return. Terminates execution!
201 function default_exception_handler($ex) {
204 // detect active db transactions, rollback and log as error
205 abort_all_db_transactions();
207 $info = get_exception_info($ex);
209 if (debugging('', DEBUG_MINIMAL)) {
210 $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
211 error_log($logerrmsg);
214 if (is_early_init($info->backtrace)) {
215 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
219 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
222 echo $OUTPUT->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
223 } catch (Exception $out_ex) {
224 // default exception handler MUST not throw any exceptions!!
225 // the problem here is we do not know if page already started or not, we only know that somebody messed up in outputlib or theme
226 // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
227 echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
228 $outinfo = get_exception_info($out_ex);
229 echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
233 exit(1); // General error code
237 * Unconditionally abort all database transactions, this function
238 * should be called from exception handlers only.
241 function abort_all_db_transactions() {
242 global $CFG, $DB, $SCRIPT;
244 // default exception handler MUST not throw any exceptions!!
246 if ($DB && $DB->is_transaction_started()) {
247 error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
248 // note: transaction blocks should never change current $_SESSION
249 $DB->force_transaction_rollback();
254 * This function encapsulates the tests for whether an exception was thrown in
255 * early init -- either during setup.php or during init of $OUTPUT.
257 * If another exception is thrown then, and if we do not take special measures,
258 * we would just get a very cryptic message "Exception thrown without a stack
259 * frame in Unknown on line 0". That makes debugging very hard, so we do take
260 * special measures in default_exception_handler, with the help of this function.
262 * @param array $backtrace the stack trace to analyse.
263 * @return boolean whether the stack trace is somewhere in output initialisation.
265 function is_early_init($backtrace) {
266 $dangerouscode = array(
267 array('function' => 'header', 'type' => '->'),
268 array('class' => 'bootstrap_renderer'),
269 array('file' => dirname(__FILE__).'/setup.php'),
271 foreach ($backtrace as $stackframe) {
272 foreach ($dangerouscode as $pattern) {
274 foreach ($pattern as $property => $value) {
275 if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
288 * Abort execution by throwing of a general exception,
289 * default exception handler displays the error message in most cases.
291 * @param string $errorcode The name of the language string containing the error message.
292 * Normally this should be in the error.php lang file.
293 * @param string $module The language file to get the error message from.
294 * @param string $link The url where the user will be prompted to continue.
295 * If no url is provided the user will be directed to the site index page.
296 * @param object $a Extra words and phrases that might be required in the error string
297 * @param string $debuginfo optional debugging information
298 * @return void, always throws exception!
300 function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
301 throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
305 * Returns detailed information about specified exception.
306 * @param exception $ex
309 function get_exception_info($ex) {
310 global $CFG, $DB, $SESSION;
312 if ($ex instanceof moodle_exception) {
313 $errorcode = $ex->errorcode;
314 $module = $ex->module;
317 $debuginfo = $ex->debuginfo;
319 $errorcode = 'generalexceptionmessage';
321 $a = $ex->getMessage();
326 $backtrace = $ex->getTrace();
327 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
328 array_unshift($backtrace, $place);
330 // Be careful, no guarantee moodlelib.php is loaded.
331 if (empty($module) || $module == 'moodle' || $module == 'core') {
334 if (function_exists('get_string')) {
335 $message = get_string($errorcode, $module, $a);
336 if ($module === 'error' and strpos($message, '[[') === 0) {
337 // Search in moodle file if error specified - needed for backwards compatibility
338 $message = get_string($errorcode, 'moodle', $a);
341 $message = $module . '/' . $errorcode;
344 // Be careful, no guarantee weblib.php is loaded.
345 if (function_exists('clean_text')) {
346 $message = clean_text($message);
348 $message = htmlspecialchars($message);
351 if (!empty($CFG->errordocroot)) {
352 $errordocroot = $CFG->errordocroot;
353 } else if (!empty($CFG->docroot)) {
354 $errordocroot = $CFG->docroot;
356 $errordocroot = 'http://docs.moodle.org';
358 if ($module === 'error') {
359 $modulelink = 'moodle';
361 $modulelink = $module;
363 $moreinfourl = $errordocroot . '/en/error/' . $modulelink . '/' . $errorcode;
366 if (!empty($SESSION->fromurl)) {
367 $link = $SESSION->fromurl;
368 unset($SESSION->fromurl);
370 $link = $CFG->wwwroot .'/';
374 $info = new object();
375 $info->message = $message;
376 $info->errorcode = $errorcode;
377 $info->backtrace = $backtrace;
379 $info->moreinfourl = $moreinfourl;
381 $info->debuginfo = $debuginfo;
387 * Formats a backtrace ready for output.
389 * @param array $callers backtrace array, as returned by debug_backtrace().
390 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
391 * @return string formatted backtrace, ready for output.
393 function format_backtrace($callers, $plaintext = false) {
394 // do not use $CFG->dirroot because it might not be available in destructors
395 $dirroot = dirname(dirname(__FILE__));
397 if (empty($callers)) {
401 $from = $plaintext ? '' : '<ul style="text-align: left">';
402 foreach ($callers as $caller) {
403 if (!isset($caller['line'])) {
404 $caller['line'] = '?'; // probably call_user_func()
406 if (!isset($caller['file'])) {
407 $caller['file'] = 'unknownfile'; // probably call_user_func()
409 $from .= $plaintext ? '* ' : '<li>';
410 $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
411 if (isset($caller['function'])) {
412 $from .= ': call to ';
413 if (isset($caller['class'])) {
414 $from .= $caller['class'] . $caller['type'];
416 $from .= $caller['function'] . '()';
417 } else if (isset($caller['exception'])) {
418 $from .= ': '.$caller['exception'].' thrown';
420 $from .= $plaintext ? "\n" : '</li>';
422 $from .= $plaintext ? '' : '</ul>';
428 * This function verifies the sanity of PHP configuration
429 * and stops execution if anything critical found.
431 function setup_validate_php_configuration() {
432 // this must be very fast - no slow checks here!!!
434 if (ini_get_bool('register_globals')) {
435 print_error('globalswarning', 'admin');
437 if (ini_get_bool('session.auto_start')) {
438 print_error('sessionautostartwarning', 'admin');
440 if (ini_get_bool('magic_quotes_runtime')) {
441 print_error('fatalmagicquotesruntime', 'admin');
446 * Initialises $FULLME and friends. Private function. Should only be called from
449 function initialise_fullme() {
450 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
452 // Detect common config error.
453 if (substr($CFG->wwwroot, -1) == '/') {
454 print_error('wwwrootslash', 'error');
458 initialise_fullme_cli();
462 $wwwroot = parse_url($CFG->wwwroot);
463 if (!isset($wwwroot['path'])) {
464 $wwwroot['path'] = '';
466 $wwwroot['path'] .= '/';
468 $rurl = setup_get_remote_url();
470 // Check that URL is under $CFG->wwwroot.
471 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
472 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
474 // Probably some weird external script
475 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
479 // $CFG->sslproxy specifies if external SSL appliance is used
480 // (That is, the Moodle server uses http, with an external box translating everything to https).
481 if (empty($CFG->sslproxy)) {
482 if ($rurl['scheme'] == 'http' and $wwwroot['scheme'] == 'https') {
483 print_error('sslonlyaccess', 'error');
487 // $CFG->reverseproxy specifies if reverse proxy server used.
488 // Used in load balancing scenarios.
489 // Do not abuse this to try to solve lan/wan access problems!!!!!
490 if (empty($CFG->reverseproxy)) {
491 if (($rurl['host'] != $wwwroot['host']) or
492 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port'])) {
493 print_error('wwwrootmismatch', 'error', '', $CFG->wwwroot);
497 // hopefully this will stop all those "clever" admins trying to set up moodle
498 // with two different addresses in intranet and Internet
499 if (!empty($CFG->reverseproxy) && $rurl['host'] == $wwwroot['host']) {
500 print_error('reverseproxyabused', 'error');
503 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
504 if (!empty($wwwroot['port'])) {
505 $hostandport .= ':'.$wwwroot['port'];
508 $FULLSCRIPT = $hostandport . $rurl['path'];
509 $FULLME = $hostandport . $rurl['fullpath'];
510 $ME = $rurl['fullpath'];
511 $rurl['path'] = $rurl['fullpath'];
515 * Initialises $FULLME and friends for command line scripts.
516 * This is a private method for use by initialise_fullme.
518 function initialise_fullme_cli() {
519 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
521 // Urls do not make much sense in CLI scripts
522 $backtrace = debug_backtrace();
523 $topfile = array_pop($backtrace);
524 $topfile = realpath($topfile['file']);
525 $dirroot = realpath($CFG->dirroot);
527 if (strpos($topfile, $dirroot) !== 0) {
528 // Probably some weird external script
529 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
531 $relativefile = substr($topfile, strlen($dirroot));
532 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
533 $SCRIPT = $FULLSCRIPT = $relativefile;
534 $FULLME = $ME = null;
539 * Get the URL that PHP/the web server thinks it is serving. Private function
540 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
541 * @return array in the same format that parse_url returns, with the addition of
542 * a 'fullpath' element, which includes any slasharguments path.
544 function setup_get_remote_url() {
546 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
547 $rurl['port'] = $_SERVER['SERVER_PORT'];
548 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
550 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
552 $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
553 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
555 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
557 $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
558 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
560 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
562 $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
563 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
565 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
567 $rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ? 'http' : 'https';
568 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
570 // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
571 // since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
572 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
574 if ($_SERVER['QUERY_STRING'] != '') {
575 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
577 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
580 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
586 * Initializes our performance info early.
588 * Pairs up with get_performance_info() which is actually
589 * in moodlelib.php. This function is here so that we can
590 * call it before all the libs are pulled in.
594 function init_performance_info() {
596 global $PERF, $CFG, $USER;
598 $PERF = new object();
599 $PERF->logwrites = 0;
600 if (function_exists('microtime')) {
601 $PERF->starttime = microtime();
603 if (function_exists('memory_get_usage')) {
604 $PERF->startmemory = memory_get_usage();
606 if (function_exists('posix_times')) {
607 $PERF->startposixtimes = posix_times();
609 if (function_exists('apd_set_pprof_trace')) {
611 if ($USER->id > 0 && $CFG->perfdebug >= 15) {
612 $tempdir = $CFG->dataroot . '/temp/profile/' . $USER->id;
614 apd_set_pprof_trace($tempdir);
615 $PERF->profiling = true;
621 * Indicates whether we are in the middle of the initial Moodle install.
623 * Very occasionally it is necessary avoid running certain bits of code before the
624 * Moodle installation has completed. The installed flag is set in admin/index.php
625 * after Moodle core and all the plugins have been installed, but just before
626 * the person doing the initial install is asked to choose the admin password.
628 * @return boolean true if the initial install is not complete.
630 function during_initial_install() {
632 return empty($CFG->rolesactive);
636 * Function to raise the memory limit to a new value.
637 * Will respect the memory limit if it is higher, thus allowing
638 * settings in php.ini, apache conf or command line switches
641 * The memory limit should be expressed with a string (eg:'64M')
643 * @param string $newlimit the new memory limit
646 function raise_memory_limit($newlimit) {
648 if (empty($newlimit)) {
652 $cur = @ini_get('memory_limit');
654 // if php is compiled without --enable-memory-limits
655 // apparently memory_limit is set to ''
659 return true; // unlimited mem!
661 $cur = get_real_size($cur);
664 $new = get_real_size($newlimit);
666 ini_set('memory_limit', $newlimit);
673 * Function to reduce the memory limit to a new value.
674 * Will respect the memory limit if it is lower, thus allowing
675 * settings in php.ini, apache conf or command line switches
678 * The memory limit should be expressed with a string (eg:'64M')
680 * @param string $newlimit the new memory limit
683 function reduce_memory_limit($newlimit) {
684 if (empty($newlimit)) {
687 $cur = @ini_get('memory_limit');
689 // if php is compiled without --enable-memory-limits
690 // apparently memory_limit is set to ''
694 return true; // unlimited mem!
696 $cur = get_real_size($cur);
699 $new = get_real_size($newlimit);
700 // -1 is smaller, but it means unlimited
701 if ($new < $cur && $new != -1) {
702 ini_set('memory_limit', $newlimit);
709 * Converts numbers like 10M into bytes.
711 * @param mixed $size The size to be converted
714 function get_real_size($size=0) {
719 $scan['MB'] = 1048576;
720 $scan['Mb'] = 1048576;
721 $scan['M'] = 1048576;
722 $scan['m'] = 1048576;
728 while (list($key) = each($scan)) {
729 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
730 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
738 * Check whether a major upgrade is needed. That is defined as an upgrade that
739 * changes something really fundamental in the database, so nothing can possibly
740 * work until the database has been updated, and that is defined by the hard-coded
741 * version number in this function.
743 function redirect_if_major_upgrade_required() {
745 $lastmajordbchanges = 2009110400;
746 if (empty($CFG->version) or (int)$CFG->version < $lastmajordbchanges or
747 during_initial_install() or !empty($CFG->adminsetuppending)) {
749 @session_get_instance()->terminate_current();
750 } catch (Exception $e) {
751 // Ignore any errors, redirect to upgrade anyway.
753 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
754 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
755 @header('Location: ' . $url);
756 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
762 * Create a directory.
765 * @param string $directory a string of directory names under $CFG->dataroot eg stuff/assignment/1
766 * param bool $shownotices If true then notification messages will be printed out on error.
767 * @return string|false Returns full path to directory if successful, false if not
769 function make_upload_directory($directory, $shownotices=true) {
773 $currdir = $CFG->dataroot;
777 if (!file_exists($currdir)) {
778 if (!mkdir($currdir, $CFG->directorypermissions) or !is_writable($currdir)) {
780 echo '<div class="notifyproblem" align="center">ERROR: You need to create the directory '.
781 $currdir .' with web server write access</div>'."<br />\n";
787 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open
788 if (!file_exists($currdir.'/.htaccess')) {
789 if ($handle = fopen($currdir.'/.htaccess', 'w')) { // For safety
790 @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");
795 $dirarray = explode('/', $directory);
797 foreach ($dirarray as $dir) {
798 $currdir = $currdir .'/'. $dir;
799 if (! file_exists($currdir)) {
800 if (! mkdir($currdir, $CFG->directorypermissions)) {
802 echo '<div class="notifyproblem" align="center">ERROR: Could not find or create a directory ('.
803 $currdir .')</div>'."<br />\n";
807 //@chmod($currdir, $CFG->directorypermissions); // Just in case mkdir didn't do it
814 function init_memcached() {
815 global $CFG, $MCACHE;
817 include_once($CFG->libdir . '/memcached.class.php');
818 $MCACHE = new memcached;
819 if ($MCACHE->status()) {
826 function init_eaccelerator() {
827 global $CFG, $MCACHE;
829 include_once($CFG->libdir . '/eaccelerator.class.php');
830 $MCACHE = new eaccelerator;
831 if ($MCACHE->status()) {
840 * This class solves the problem of how to initialise $OUTPUT.
842 * The problem is caused be two factors
844 * <li>On the one hand, we cannot be sure when output will start. In particular,
845 * an error, which needs to be displayed, could be thrown at any time.</li>
846 * <li>On the other hand, we cannot be sure when we will have all the information
847 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
848 * (potentially) depends on the current course, course categories, and logged in user.
849 * It also depends on whether the current page requires HTTPS.</li>
852 * So, it is hard to find a single natural place during Moodle script execution,
853 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
854 * adopt the following strategy
856 * <li>We will initialise $OUTPUT the first time it is used.</li>
857 * <li>If, after $OUTPUT has been initialised, the script tries to change something
858 * that $OUTPUT depends on, we throw an exception making it clear that the script
859 * did something wrong.
862 * The only problem with that is, how do we initialise $OUTPUT on first use if,
863 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
864 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
865 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
867 * Note that this class is used before lib/outputlib.php has been loaded, so we
868 * must be careful referring to classes/functions from there, they may not be
869 * defined yet, and we must avoid fatal errors.
871 * @copyright 2009 Tim Hunt
872 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
875 class bootstrap_renderer {
877 * Handles re-entrancy. Without this, errors or debugging output that occur
878 * during the initialisation of $OUTPUT, cause infinite recursion.
881 protected $initialising = false;
884 * Have we started output yet?
885 * @return boolean true if the header has been printed.
887 public function has_started() {
891 public function __call($method, $arguments) {
892 global $OUTPUT, $PAGE;
895 if ($method == 'notification') {
896 // Catch infinite recursion caused by debugging output during print_header.
897 $backtrace = debug_backtrace();
898 array_shift($backtrace);
899 array_shift($backtrace);
900 $recursing = is_early_init($backtrace);
903 // If lib/outputlib.php has been loaded, call it.
904 if (!empty($PAGE) && !$recursing) {
905 $PAGE->initialise_theme_and_output();
906 return call_user_func_array(array($OUTPUT, $method), $arguments);
909 $this->initialising = true;
910 // Too soon to initialise $OUTPUT, provide a couple of key methods.
911 $earlymethods = array(
912 'fatal_error' => 'early_error',
913 'notification' => 'early_notification',
915 if (array_key_exists($method, $earlymethods)) {
916 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
919 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
923 * Returns nicely formatted error message in a div box.
926 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
929 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
930 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
931 width: 80%; -moz-border-radius: 20px; padding: 15px">
934 if (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER) {
935 if (!empty($debuginfo)) {
936 $debuginfo = s($debuginfo); // removes all nasty JS
937 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
938 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
940 if (!empty($backtrace)) {
941 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
949 * This function should only be called by this class, or from exception handlers
952 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
953 // In the name of protocol correctness, monitoring and performance
954 // profiling, set the appropriate error headers for machine consumption
955 if (isset($_SERVER['SERVER_PROTOCOL'])) {
956 // Avoid it with cron.php. Note that we assume it's HTTP/1.x
957 // The 503 ode here means our Moodle does not work at all, the error happened too early
958 @header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
961 // better disable any caching
962 @header('Content-Type: text/html; charset=utf-8');
963 @header('Cache-Control: no-store, no-cache, must-revalidate');
964 @header('Cache-Control: post-check=0, pre-check=0', false);
965 @header('Pragma: no-cache');
966 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
967 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
969 if (function_exists('get_string')) {
970 $strerror = get_string('error');
975 $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
977 return self::plain_page($strerror, $content);
980 public static function early_notification($message, $classes = 'notifyproblem') {
981 return '<div class="' . $classes . '">' . $message . '</div>';
984 public static function plain_redirect_message($encodedurl) {
985 $message = '<p>' . get_string('pageshouldredirect') . '</p><p><a href="'.
986 $encodedurl .'">'. get_string('continue') .'</a></p>';
987 return self::plain_page(get_string('redirect'), $message);
990 protected static function plain_page($title, $content) {
991 if (function_exists('get_string') && function_exists('get_html_lang')) {
992 $htmllang = get_html_lang();
997 return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
998 <html xmlns="http://www.w3.org/1999/xhtml" ' . $htmllang . '>
1000 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1001 <title>' . $title . '</title>
1002 </head><body>' . $content . '</body></html>';