Merge branch 'MDL-40119-25' of git://github.com/andrewnicols/moodle into MOODLE_25_STABLE
[moodle.git] / lib / setuplib.php
blob78633827b8f5c509108ccb1d5951205318528b3d
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * These functions are required very early in the Moodle
19 * setup process, before any of the main libraries are
20 * loaded.
22 * @package core
23 * @subpackage lib
24 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
30 // Debug levels - always keep the values in ascending order!
31 /** No warnings and errors at all */
32 define('DEBUG_NONE', 0);
33 /** Fatal errors only */
34 define('DEBUG_MINIMAL', E_ERROR | E_PARSE);
35 /** Errors, warnings and notices */
36 define('DEBUG_NORMAL', E_ERROR | E_PARSE | E_WARNING | E_NOTICE);
37 /** All problems except strict PHP warnings */
38 define('DEBUG_ALL', E_ALL & ~E_STRICT);
39 /** DEBUG_ALL with all debug messages and strict warnings */
40 define('DEBUG_DEVELOPER', E_ALL | E_STRICT);
42 /** Remove any memory limits */
43 define('MEMORY_UNLIMITED', -1);
44 /** Standard memory limit for given platform */
45 define('MEMORY_STANDARD', -2);
46 /**
47 * Large memory limit for given platform - used in cron, upgrade, and other places that need a lot of memory.
48 * Can be overridden with $CFG->extramemorylimit setting.
50 define('MEMORY_EXTRA', -3);
51 /** Extremely large memory limit - not recommended for standard scripts */
52 define('MEMORY_HUGE', -4);
54 /**
55 * Software maturity levels used by the core and plugins
57 define('MATURITY_ALPHA', 50); // internals can be tested using white box techniques
58 define('MATURITY_BETA', 100); // feature complete, ready for preview and testing
59 define('MATURITY_RC', 150); // tested, will be released unless there are fatal bugs
60 define('MATURITY_STABLE', 200); // ready for production deployment
62 /**
63 * Special value that can be used in $plugin->dependencies in version.php files.
65 define('ANY_VERSION', 'any');
68 /**
69 * Simple class. It is usually used instead of stdClass because it looks
70 * more familiar to Java developers ;-) Do not use for type checking of
71 * function parameters. Please use stdClass instead.
73 * @package core
74 * @subpackage lib
75 * @copyright 2009 Petr Skoda {@link http://skodak.org}
76 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
77 * @deprecated since 2.0
79 class object extends stdClass {};
81 /**
82 * Base Moodle Exception class
84 * Although this class is defined here, you cannot throw a moodle_exception until
85 * after moodlelib.php has been included (which will happen very soon).
87 * @package core
88 * @subpackage lib
89 * @copyright 2008 Petr Skoda {@link http://skodak.org}
90 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
92 class moodle_exception extends Exception {
94 /**
95 * @var string The name of the string from error.php to print
97 public $errorcode;
99 /**
100 * @var string The name of module
102 public $module;
105 * @var mixed Extra words and phrases that might be required in the error string
107 public $a;
110 * @var string 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.
112 public $link;
115 * @var string Optional information to aid the debugging process
117 public $debuginfo;
120 * Constructor
121 * @param string $errorcode The name of the string from error.php to print
122 * @param string $module name of module
123 * @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.
124 * @param mixed $a Extra words and phrases that might be required in the error string
125 * @param string $debuginfo optional debugging information
127 function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
128 if (empty($module) || $module == 'moodle' || $module == 'core') {
129 $module = 'error';
132 $this->errorcode = $errorcode;
133 $this->module = $module;
134 $this->link = $link;
135 $this->a = $a;
136 $this->debuginfo = is_null($debuginfo) ? null : (string)$debuginfo;
138 if (get_string_manager()->string_exists($errorcode, $module)) {
139 $message = get_string($errorcode, $module, $a);
140 $haserrorstring = true;
141 } else {
142 $message = $module . '/' . $errorcode;
143 $haserrorstring = false;
146 if (defined('PHPUNIT_TEST') and PHPUNIT_TEST and $debuginfo) {
147 $message = "$message ($debuginfo)";
150 if (!$haserrorstring and defined('PHPUNIT_TEST') and PHPUNIT_TEST) {
151 // Append the contents of $a to $debuginfo so helpful information isn't lost.
152 // This emulates what {@link get_exception_info()} does. Unfortunately that
153 // function is not used by phpunit.
154 $message .= PHP_EOL.'$a contents: '.print_r($a, true);
157 parent::__construct($message, 0);
162 * Course/activity access exception.
164 * This exception is thrown from require_login()
166 * @package core_access
167 * @copyright 2010 Petr Skoda {@link http://skodak.org}
168 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
170 class require_login_exception extends moodle_exception {
172 * Constructor
173 * @param string $debuginfo Information to aid the debugging process
175 function __construct($debuginfo) {
176 parent::__construct('requireloginerror', 'error', '', NULL, $debuginfo);
181 * Web service parameter exception class
182 * @deprecated since Moodle 2.2 - use moodle exception instead
183 * This exception must be thrown to the web service client when a web service parameter is invalid
184 * The error string is gotten from webservice.php
186 class webservice_parameter_exception extends moodle_exception {
188 * Constructor
189 * @param string $errorcode The name of the string from webservice.php to print
190 * @param string $a The name of the parameter
191 * @param string $debuginfo Optional information to aid debugging
193 function __construct($errorcode=null, $a = '', $debuginfo = null) {
194 parent::__construct($errorcode, 'webservice', '', $a, $debuginfo);
199 * Exceptions indicating user does not have permissions to do something
200 * and the execution can not continue.
202 * @package core_access
203 * @copyright 2009 Petr Skoda {@link http://skodak.org}
204 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
206 class required_capability_exception extends moodle_exception {
208 * Constructor
209 * @param context $context The context used for the capability check
210 * @param string $capability The required capability
211 * @param string $errormessage The error message to show the user
212 * @param string $stringfile
214 function __construct($context, $capability, $errormessage, $stringfile) {
215 $capabilityname = get_capability_string($capability);
216 if ($context->contextlevel == CONTEXT_MODULE and preg_match('/:view$/', $capability)) {
217 // 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
218 $paranetcontext = context::instance_by_id(get_parent_contextid($context));
219 $link = get_context_url($paranetcontext);
220 } else {
221 $link = get_context_url($context);
223 parent::__construct($errormessage, $stringfile, $link, $capabilityname);
228 * Exception indicating programming error, must be fixed by a programer. For example
229 * a core API might throw this type of exception if a plugin calls it incorrectly.
231 * @package core
232 * @subpackage lib
233 * @copyright 2008 Petr Skoda {@link http://skodak.org}
234 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
236 class coding_exception extends moodle_exception {
238 * Constructor
239 * @param string $hint short description of problem
240 * @param string $debuginfo detailed information how to fix problem
242 function __construct($hint, $debuginfo=null) {
243 parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
248 * Exception indicating malformed parameter problem.
249 * This exception is not supposed to be thrown when processing
250 * user submitted data in forms. It is more suitable
251 * for WS and other low level stuff.
253 * @package core
254 * @subpackage lib
255 * @copyright 2009 Petr Skoda {@link http://skodak.org}
256 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
258 class invalid_parameter_exception extends moodle_exception {
260 * Constructor
261 * @param string $debuginfo some detailed information
263 function __construct($debuginfo=null) {
264 parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
269 * Exception indicating malformed response problem.
270 * This exception is not supposed to be thrown when processing
271 * user submitted data in forms. It is more suitable
272 * for WS and other low level stuff.
274 class invalid_response_exception extends moodle_exception {
276 * Constructor
277 * @param string $debuginfo some detailed information
279 function __construct($debuginfo=null) {
280 parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
285 * An exception that indicates something really weird happened. For example,
286 * if you do switch ($context->contextlevel), and have one case for each
287 * CONTEXT_... constant. You might throw an invalid_state_exception in the
288 * default case, to just in case something really weird is going on, and
289 * $context->contextlevel is invalid - rather than ignoring this possibility.
291 * @package core
292 * @subpackage lib
293 * @copyright 2009 onwards Martin Dougiamas {@link http://moodle.com}
294 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
296 class invalid_state_exception extends moodle_exception {
298 * Constructor
299 * @param string $hint short description of problem
300 * @param string $debuginfo optional more detailed information
302 function __construct($hint, $debuginfo=null) {
303 parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
308 * An exception that indicates incorrect permissions in $CFG->dataroot
310 * @package core
311 * @subpackage lib
312 * @copyright 2010 Petr Skoda {@link http://skodak.org}
313 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
315 class invalid_dataroot_permissions extends moodle_exception {
317 * Constructor
318 * @param string $debuginfo optional more detailed information
320 function __construct($debuginfo = NULL) {
321 parent::__construct('invaliddatarootpermissions', 'error', '', NULL, $debuginfo);
326 * An exception that indicates that file can not be served
328 * @package core
329 * @subpackage lib
330 * @copyright 2010 Petr Skoda {@link http://skodak.org}
331 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
333 class file_serving_exception extends moodle_exception {
335 * Constructor
336 * @param string $debuginfo optional more detailed information
338 function __construct($debuginfo = NULL) {
339 parent::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
344 * Default exception handler, uncaught exceptions are equivalent to error() in 1.9 and earlier
346 * @param Exception $ex
347 * @return void -does not return. Terminates execution!
349 function default_exception_handler($ex) {
350 global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION, $PAGE;
352 // detect active db transactions, rollback and log as error
353 abort_all_db_transactions();
355 if (($ex instanceof required_capability_exception) && !CLI_SCRIPT && !AJAX_SCRIPT && !empty($CFG->autologinguests) && !empty($USER->autologinguest)) {
356 $SESSION->wantsurl = qualified_me();
357 redirect(get_login_url());
360 $info = get_exception_info($ex);
362 if (debugging('', DEBUG_MINIMAL)) {
363 $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
364 error_log($logerrmsg);
367 if (is_early_init($info->backtrace)) {
368 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
369 } else {
370 try {
371 if ($DB) {
372 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
373 $DB->set_debug(0);
375 echo $OUTPUT->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
376 } catch (Exception $out_ex) {
377 // default exception handler MUST not throw any exceptions!!
378 // 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
379 // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
380 if (CLI_SCRIPT or AJAX_SCRIPT) {
381 // just ignore the error and send something back using the safest method
382 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
383 } else {
384 echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
385 $outinfo = get_exception_info($out_ex);
386 echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
391 exit(1); // General error code
395 * Default error handler, prevents some white screens.
396 * @param int $errno
397 * @param string $errstr
398 * @param string $errfile
399 * @param int $errline
400 * @param array $errcontext
401 * @return bool false means use default error handler
403 function default_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
404 if ($errno == 4096) {
405 //fatal catchable error
406 throw new coding_exception('PHP catchable fatal error', $errstr);
408 return false;
412 * Unconditionally abort all database transactions, this function
413 * should be called from exception handlers only.
414 * @return void
416 function abort_all_db_transactions() {
417 global $CFG, $DB, $SCRIPT;
419 // default exception handler MUST not throw any exceptions!!
421 if ($DB && $DB->is_transaction_started()) {
422 error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
423 // note: transaction blocks should never change current $_SESSION
424 $DB->force_transaction_rollback();
429 * This function encapsulates the tests for whether an exception was thrown in
430 * early init -- either during setup.php or during init of $OUTPUT.
432 * If another exception is thrown then, and if we do not take special measures,
433 * we would just get a very cryptic message "Exception thrown without a stack
434 * frame in Unknown on line 0". That makes debugging very hard, so we do take
435 * special measures in default_exception_handler, with the help of this function.
437 * @param array $backtrace the stack trace to analyse.
438 * @return boolean whether the stack trace is somewhere in output initialisation.
440 function is_early_init($backtrace) {
441 $dangerouscode = array(
442 array('function' => 'header', 'type' => '->'),
443 array('class' => 'bootstrap_renderer'),
444 array('file' => dirname(__FILE__).'/setup.php'),
446 foreach ($backtrace as $stackframe) {
447 foreach ($dangerouscode as $pattern) {
448 $matches = true;
449 foreach ($pattern as $property => $value) {
450 if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
451 $matches = false;
454 if ($matches) {
455 return true;
459 return false;
463 * Abort execution by throwing of a general exception,
464 * default exception handler displays the error message in most cases.
466 * @param string $errorcode The name of the language string containing the error message.
467 * Normally this should be in the error.php lang file.
468 * @param string $module The language file to get the error message from.
469 * @param string $link The url where the user will be prompted to continue.
470 * If no url is provided the user will be directed to the site index page.
471 * @param object $a Extra words and phrases that might be required in the error string
472 * @param string $debuginfo optional debugging information
473 * @return void, always throws exception!
475 function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
476 throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
480 * Returns detailed information about specified exception.
481 * @param exception $ex
482 * @return object
484 function get_exception_info($ex) {
485 global $CFG, $DB, $SESSION;
487 if ($ex instanceof moodle_exception) {
488 $errorcode = $ex->errorcode;
489 $module = $ex->module;
490 $a = $ex->a;
491 $link = $ex->link;
492 $debuginfo = $ex->debuginfo;
493 } else {
494 $errorcode = 'generalexceptionmessage';
495 $module = 'error';
496 $a = $ex->getMessage();
497 $link = '';
498 $debuginfo = '';
501 // Append the error code to the debug info to make grepping and googling easier
502 $debuginfo .= PHP_EOL."Error code: $errorcode";
504 $backtrace = $ex->getTrace();
505 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
506 array_unshift($backtrace, $place);
508 // Be careful, no guarantee moodlelib.php is loaded.
509 if (empty($module) || $module == 'moodle' || $module == 'core') {
510 $module = 'error';
512 // Search for the $errorcode's associated string
513 // If not found, append the contents of $a to $debuginfo so helpful information isn't lost
514 if (function_exists('get_string_manager')) {
515 if (get_string_manager()->string_exists($errorcode, $module)) {
516 $message = get_string($errorcode, $module, $a);
517 } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
518 // Search in moodle file if error specified - needed for backwards compatibility
519 $message = get_string($errorcode, 'moodle', $a);
520 } else {
521 $message = $module . '/' . $errorcode;
522 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
524 } else {
525 $message = $module . '/' . $errorcode;
526 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
529 // Remove some absolute paths from message and debugging info.
530 $searches = array();
531 $replaces = array();
532 $cfgnames = array('tempdir', 'cachedir', 'themedir',
533 'langmenucachefile', 'langcacheroot', 'dataroot', 'dirroot');
534 foreach ($cfgnames as $cfgname) {
535 if (property_exists($CFG, $cfgname)) {
536 $searches[] = $CFG->$cfgname;
537 $replaces[] = "[$cfgname]";
540 if (!empty($searches)) {
541 $message = str_replace($searches, $replaces, $message);
542 $debuginfo = str_replace($searches, $replaces, $debuginfo);
545 // Be careful, no guarantee weblib.php is loaded.
546 if (function_exists('clean_text')) {
547 $message = clean_text($message);
548 } else {
549 $message = htmlspecialchars($message);
552 if (!empty($CFG->errordocroot)) {
553 $errordoclink = $CFG->errordocroot . '/en/';
554 } else {
555 $errordoclink = get_docs_url();
558 if ($module === 'error') {
559 $modulelink = 'moodle';
560 } else {
561 $modulelink = $module;
563 $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
565 if (empty($link)) {
566 if (!empty($SESSION->fromurl)) {
567 $link = $SESSION->fromurl;
568 unset($SESSION->fromurl);
569 } else {
570 $link = $CFG->wwwroot .'/';
574 // when printing an error the continue button should never link offsite
575 if (stripos($link, $CFG->wwwroot) === false &&
576 stripos($link, $CFG->httpswwwroot) === false) {
577 $link = $CFG->wwwroot.'/';
580 $info = new stdClass();
581 $info->message = $message;
582 $info->errorcode = $errorcode;
583 $info->backtrace = $backtrace;
584 $info->link = $link;
585 $info->moreinfourl = $moreinfourl;
586 $info->a = $a;
587 $info->debuginfo = $debuginfo;
589 return $info;
593 * Returns the Moodle Docs URL in the users language for a given 'More help' link.
595 * There are three cases:
597 * 1. In the normal case, $path will be a short relative path 'component/thing',
598 * like 'mod/folder/view' 'group/import'. This gets turned into an link to
599 * MoodleDocs in the user's language, and for the appropriate Moodle version.
600 * E.g. 'group/import' may become 'http://docs.moodle.org/2x/en/group/import'.
601 * The 'http://docs.moodle.org' bit comes from $CFG->docroot.
603 * This is the only option that should be used in standard Moodle code. The other
604 * two options have been implemented because they are useful for third-party plugins.
606 * 2. $path may be an absolute URL, starting http:// or https://. In this case,
607 * the link is used as is.
609 * 3. $path may start %%WWWROOT%%, in which case that is replaced by
610 * $CFG->wwwroot to make the link.
612 * @param string $path the place to link to. See above for details.
613 * @return string The MoodleDocs URL in the user's language. for example @link http://docs.moodle.org/2x/en/$path}
615 function get_docs_url($path = null) {
616 global $CFG;
618 // Absolute URLs are used unmodified.
619 if (substr($path, 0, 7) === 'http://' || substr($path, 0, 8) === 'https://') {
620 return $path;
623 // Paths starting %%WWWROOT%% have that replaced by $CFG->wwwroot.
624 if (substr($path, 0, 11) === '%%WWWROOT%%') {
625 return $CFG->wwwroot . substr($path, 11);
628 // Otherwise we do the normal case, and construct a MoodleDocs URL relative to $CFG->docroot.
630 // Check that $CFG->branch has been set up, during installation it won't be.
631 if (empty($CFG->branch)) {
632 // It's not there yet so look at version.php.
633 include($CFG->dirroot.'/version.php');
634 } else {
635 // We can use $CFG->branch and avoid having to include version.php.
636 $branch = $CFG->branch;
638 // ensure branch is valid.
639 if (!$branch) {
640 // We should never get here but in case we do lets set $branch to .
641 // the smart one's will know that this is the current directory
642 // and the smarter ones will know that there is some smart matching
643 // that will ensure people end up at the latest version of the docs.
644 $branch = '.';
646 if (!empty($CFG->docroot)) {
647 return $CFG->docroot . '/' . $branch . '/' . current_language() . '/' . $path;
648 } else {
649 return 'http://docs.moodle.org/'. $branch . '/' . current_language() . '/' . $path;
654 * Formats a backtrace ready for output.
656 * @param array $callers backtrace array, as returned by debug_backtrace().
657 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
658 * @return string formatted backtrace, ready for output.
660 function format_backtrace($callers, $plaintext = false) {
661 // do not use $CFG->dirroot because it might not be available in destructors
662 $dirroot = dirname(dirname(__FILE__));
664 if (empty($callers)) {
665 return '';
668 $from = $plaintext ? '' : '<ul style="text-align: left">';
669 foreach ($callers as $caller) {
670 if (!isset($caller['line'])) {
671 $caller['line'] = '?'; // probably call_user_func()
673 if (!isset($caller['file'])) {
674 $caller['file'] = 'unknownfile'; // probably call_user_func()
676 $from .= $plaintext ? '* ' : '<li>';
677 $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
678 if (isset($caller['function'])) {
679 $from .= ': call to ';
680 if (isset($caller['class'])) {
681 $from .= $caller['class'] . $caller['type'];
683 $from .= $caller['function'] . '()';
684 } else if (isset($caller['exception'])) {
685 $from .= ': '.$caller['exception'].' thrown';
687 $from .= $plaintext ? "\n" : '</li>';
689 $from .= $plaintext ? '' : '</ul>';
691 return $from;
695 * This function makes the return value of ini_get consistent if you are
696 * setting server directives through the .htaccess file in apache.
698 * Current behavior for value set from php.ini On = 1, Off = [blank]
699 * Current behavior for value set from .htaccess On = On, Off = Off
700 * Contributed by jdell @ unr.edu
702 * @param string $ini_get_arg The argument to get
703 * @return bool True for on false for not
705 function ini_get_bool($ini_get_arg) {
706 $temp = ini_get($ini_get_arg);
708 if ($temp == '1' or strtolower($temp) == 'on') {
709 return true;
711 return false;
715 * This function verifies the sanity of PHP configuration
716 * and stops execution if anything critical found.
718 function setup_validate_php_configuration() {
719 // this must be very fast - no slow checks here!!!
721 if (ini_get_bool('register_globals')) {
722 print_error('globalswarning', 'admin');
724 if (ini_get_bool('session.auto_start')) {
725 print_error('sessionautostartwarning', 'admin');
727 if (ini_get_bool('magic_quotes_runtime')) {
728 print_error('fatalmagicquotesruntime', 'admin');
733 * Initialise global $CFG variable
734 * @return void
736 function initialise_cfg() {
737 global $CFG, $DB;
739 try {
740 if ($DB) {
741 $localcfg = get_config('core');
742 foreach ($localcfg as $name => $value) {
743 if (property_exists($CFG, $name)) {
744 // config.php settings always take precedence
745 continue;
747 $CFG->{$name} = $value;
750 } catch (dml_exception $e) {
751 // most probably empty db, going to install soon
756 * Initialises $FULLME and friends. Private function. Should only be called from
757 * setup.php.
759 function initialise_fullme() {
760 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
762 // Detect common config error.
763 if (substr($CFG->wwwroot, -1) == '/') {
764 print_error('wwwrootslash', 'error');
767 if (CLI_SCRIPT) {
768 initialise_fullme_cli();
769 return;
772 $rurl = setup_get_remote_url();
773 $wwwroot = parse_url($CFG->wwwroot.'/');
775 if (empty($rurl['host'])) {
776 // missing host in request header, probably not a real browser, let's ignore them
778 } else if (!empty($CFG->reverseproxy)) {
779 // $CFG->reverseproxy specifies if reverse proxy server used
780 // Used in load balancing scenarios.
781 // Do not abuse this to try to solve lan/wan access problems!!!!!
783 } else {
784 if (($rurl['host'] !== $wwwroot['host']) or
785 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port']) or
786 (strpos($rurl['path'], $wwwroot['path']) !== 0)) {
788 // Explain the problem and redirect them to the right URL
789 if (!defined('NO_MOODLE_COOKIES')) {
790 define('NO_MOODLE_COOKIES', true);
792 // The login/token.php script should call the correct url/port.
793 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
794 $wwwrootport = empty($wwwroot['port'])?'':$wwwroot['port'];
795 $calledurl = $rurl['host'];
796 if (!empty($rurl['port'])) {
797 $calledurl .= ':'. $rurl['port'];
799 $correcturl = $wwwroot['host'];
800 if (!empty($wwwrootport)) {
801 $correcturl .= ':'. $wwwrootport;
803 throw new moodle_exception('requirecorrectaccess', 'error', '', null,
804 'You called ' . $calledurl .', you should have called ' . $correcturl);
806 redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
810 // Check that URL is under $CFG->wwwroot.
811 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
812 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
813 } else {
814 // Probably some weird external script
815 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
816 return;
819 // $CFG->sslproxy specifies if external SSL appliance is used
820 // (That is, the Moodle server uses http, with an external box translating everything to https).
821 if (empty($CFG->sslproxy)) {
822 if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
823 print_error('sslonlyaccess', 'error');
825 } else {
826 if ($wwwroot['scheme'] !== 'https') {
827 throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
829 $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
832 // hopefully this will stop all those "clever" admins trying to set up moodle
833 // with two different addresses in intranet and Internet
834 if (!empty($CFG->reverseproxy) && $rurl['host'] === $wwwroot['host']) {
835 print_error('reverseproxyabused', 'error');
838 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
839 if (!empty($wwwroot['port'])) {
840 $hostandport .= ':'.$wwwroot['port'];
843 $FULLSCRIPT = $hostandport . $rurl['path'];
844 $FULLME = $hostandport . $rurl['fullpath'];
845 $ME = $rurl['fullpath'];
849 * Initialises $FULLME and friends for command line scripts.
850 * This is a private method for use by initialise_fullme.
852 function initialise_fullme_cli() {
853 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
855 // Urls do not make much sense in CLI scripts
856 $backtrace = debug_backtrace();
857 $topfile = array_pop($backtrace);
858 $topfile = realpath($topfile['file']);
859 $dirroot = realpath($CFG->dirroot);
861 if (strpos($topfile, $dirroot) !== 0) {
862 // Probably some weird external script
863 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
864 } else {
865 $relativefile = substr($topfile, strlen($dirroot));
866 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
867 $SCRIPT = $FULLSCRIPT = $relativefile;
868 $FULLME = $ME = null;
873 * Get the URL that PHP/the web server thinks it is serving. Private function
874 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
875 * @return array in the same format that parse_url returns, with the addition of
876 * a 'fullpath' element, which includes any slasharguments path.
878 function setup_get_remote_url() {
879 $rurl = array();
880 if (isset($_SERVER['HTTP_HOST'])) {
881 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
882 } else {
883 $rurl['host'] = null;
885 $rurl['port'] = $_SERVER['SERVER_PORT'];
886 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
887 $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ? 'http' : 'https';
889 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
890 //Apache server
891 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
893 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
894 //IIS - needs a lot of tweaking to make it work
895 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
897 // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
898 // since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
899 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
901 if ($_SERVER['QUERY_STRING'] != '') {
902 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
904 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
906 /* NOTE: following servers are not fully tested! */
908 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
909 //lighttpd - not officially supported
910 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
912 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
913 //nginx - not officially supported
914 if (!isset($_SERVER['SCRIPT_NAME'])) {
915 die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
917 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
919 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
920 //cherokee - not officially supported
921 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
923 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
924 //zeus - not officially supported
925 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
927 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
928 //LiteSpeed - not officially supported
929 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
931 } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
932 //obscure name found on some servers - this is definitely not supported
933 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
935 } else if (strpos($_SERVER['SERVER_SOFTWARE'], 'PHP') === 0) {
936 // built-in PHP Development Server
937 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
939 } else {
940 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
943 // sanitize the url a bit more, the encoding style may be different in vars above
944 $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
945 $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);
947 return $rurl;
951 * Try to work around the 'max_input_vars' restriction if necessary.
953 function workaround_max_input_vars() {
954 // Make sure this gets executed only once from lib/setup.php!
955 static $executed = false;
956 if ($executed) {
957 debugging('workaround_max_input_vars() must be called only once!');
958 return;
960 $executed = true;
962 if (!isset($_SERVER["CONTENT_TYPE"]) or strpos($_SERVER["CONTENT_TYPE"], 'multipart/form-data') !== false) {
963 // Not a post or 'multipart/form-data' which is not compatible with "php://input" reading.
964 return;
967 if (!isloggedin() or isguestuser()) {
968 // Only real users post huge forms.
969 return;
972 $max = (int)ini_get('max_input_vars');
974 if ($max <= 0) {
975 // Most probably PHP < 5.3.9 that does not implement this limit.
976 return;
979 if ($max >= 200000) {
980 // This value should be ok for all our forms, by setting it in php.ini
981 // admins may prevent any unexpected regressions caused by this hack.
983 // Note there is no need to worry about DDoS caused by making this limit very high
984 // because there are very many easier ways to DDoS any Moodle server.
985 return;
988 if (count($_POST, COUNT_RECURSIVE) < $max) {
989 return;
992 // Large POST request with enctype supported by php://input.
993 // Parse php://input in chunks to bypass max_input_vars limit, which also applies to parse_str().
994 $str = file_get_contents("php://input");
995 if ($str === false or $str === '') {
996 // Some weird error.
997 return;
1000 $delim = '&';
1001 $fun = create_function('$p', 'return implode("'.$delim.'", $p);');
1002 $chunks = array_map($fun, array_chunk(explode($delim, $str), $max));
1004 foreach ($chunks as $chunk) {
1005 $values = array();
1006 parse_str($chunk, $values);
1008 if (ini_get_bool('magic_quotes_gpc')) {
1009 // Use the same logic as lib/setup.php to work around deprecated magic quotes.
1010 $values = array_map('stripslashes_deep', $values);
1013 merge_query_params($_POST, $values);
1014 merge_query_params($_REQUEST, $values);
1019 * Merge parsed POST chunks.
1021 * NOTE: this is not perfect, but it should work in most cases hopefully.
1023 * @param array $target
1024 * @param array $values
1026 function merge_query_params(array &$target, array $values) {
1027 if (isset($values[0]) and isset($target[0])) {
1028 // This looks like a split [] array, lets verify the keys are continuous starting with 0.
1029 $keys1 = array_keys($values);
1030 $keys2 = array_keys($target);
1031 if ($keys1 === array_keys($keys1) and $keys2 === array_keys($keys2)) {
1032 foreach ($values as $v) {
1033 $target[] = $v;
1035 return;
1038 foreach ($values as $k => $v) {
1039 if (!isset($target[$k])) {
1040 $target[$k] = $v;
1041 continue;
1043 if (is_array($target[$k]) and is_array($v)) {
1044 merge_query_params($target[$k], $v);
1045 continue;
1047 // We should not get here unless there are duplicates in params.
1048 $target[$k] = $v;
1053 * Initializes our performance info early.
1055 * Pairs up with get_performance_info() which is actually
1056 * in moodlelib.php. This function is here so that we can
1057 * call it before all the libs are pulled in.
1059 * @uses $PERF
1061 function init_performance_info() {
1063 global $PERF, $CFG, $USER;
1065 $PERF = new stdClass();
1066 $PERF->logwrites = 0;
1067 if (function_exists('microtime')) {
1068 $PERF->starttime = microtime();
1070 if (function_exists('memory_get_usage')) {
1071 $PERF->startmemory = memory_get_usage();
1073 if (function_exists('posix_times')) {
1074 $PERF->startposixtimes = posix_times();
1079 * Indicates whether we are in the middle of the initial Moodle install.
1081 * Very occasionally it is necessary avoid running certain bits of code before the
1082 * Moodle installation has completed. The installed flag is set in admin/index.php
1083 * after Moodle core and all the plugins have been installed, but just before
1084 * the person doing the initial install is asked to choose the admin password.
1086 * @return boolean true if the initial install is not complete.
1088 function during_initial_install() {
1089 global $CFG;
1090 return empty($CFG->rolesactive);
1094 * Function to raise the memory limit to a new value.
1095 * Will respect the memory limit if it is higher, thus allowing
1096 * settings in php.ini, apache conf or command line switches
1097 * to override it.
1099 * The memory limit should be expressed with a constant
1100 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
1101 * It is possible to use strings or integers too (eg:'128M').
1103 * @param mixed $newlimit the new memory limit
1104 * @return bool success
1106 function raise_memory_limit($newlimit) {
1107 global $CFG;
1109 if ($newlimit == MEMORY_UNLIMITED) {
1110 ini_set('memory_limit', -1);
1111 return true;
1113 } else if ($newlimit == MEMORY_STANDARD) {
1114 if (PHP_INT_SIZE > 4) {
1115 $newlimit = get_real_size('128M'); // 64bit needs more memory
1116 } else {
1117 $newlimit = get_real_size('96M');
1120 } else if ($newlimit == MEMORY_EXTRA) {
1121 if (PHP_INT_SIZE > 4) {
1122 $newlimit = get_real_size('384M'); // 64bit needs more memory
1123 } else {
1124 $newlimit = get_real_size('256M');
1126 if (!empty($CFG->extramemorylimit)) {
1127 $extra = get_real_size($CFG->extramemorylimit);
1128 if ($extra > $newlimit) {
1129 $newlimit = $extra;
1133 } else if ($newlimit == MEMORY_HUGE) {
1134 $newlimit = get_real_size('2G');
1136 } else {
1137 $newlimit = get_real_size($newlimit);
1140 if ($newlimit <= 0) {
1141 debugging('Invalid memory limit specified.');
1142 return false;
1145 $cur = ini_get('memory_limit');
1146 if (empty($cur)) {
1147 // if php is compiled without --enable-memory-limits
1148 // apparently memory_limit is set to ''
1149 $cur = 0;
1150 } else {
1151 if ($cur == -1){
1152 return true; // unlimited mem!
1154 $cur = get_real_size($cur);
1157 if ($newlimit > $cur) {
1158 ini_set('memory_limit', $newlimit);
1159 return true;
1161 return false;
1165 * Function to reduce the memory limit to a new value.
1166 * Will respect the memory limit if it is lower, thus allowing
1167 * settings in php.ini, apache conf or command line switches
1168 * to override it
1170 * The memory limit should be expressed with a string (eg:'64M')
1172 * @param string $newlimit the new memory limit
1173 * @return bool
1175 function reduce_memory_limit($newlimit) {
1176 if (empty($newlimit)) {
1177 return false;
1179 $cur = ini_get('memory_limit');
1180 if (empty($cur)) {
1181 // if php is compiled without --enable-memory-limits
1182 // apparently memory_limit is set to ''
1183 $cur = 0;
1184 } else {
1185 if ($cur == -1){
1186 return true; // unlimited mem!
1188 $cur = get_real_size($cur);
1191 $new = get_real_size($newlimit);
1192 // -1 is smaller, but it means unlimited
1193 if ($new < $cur && $new != -1) {
1194 ini_set('memory_limit', $newlimit);
1195 return true;
1197 return false;
1201 * Converts numbers like 10M into bytes.
1203 * @param string $size The size to be converted
1204 * @return int
1206 function get_real_size($size = 0) {
1207 if (!$size) {
1208 return 0;
1210 $scan = array();
1211 $scan['GB'] = 1073741824;
1212 $scan['Gb'] = 1073741824;
1213 $scan['G'] = 1073741824;
1214 $scan['MB'] = 1048576;
1215 $scan['Mb'] = 1048576;
1216 $scan['M'] = 1048576;
1217 $scan['m'] = 1048576;
1218 $scan['KB'] = 1024;
1219 $scan['Kb'] = 1024;
1220 $scan['K'] = 1024;
1221 $scan['k'] = 1024;
1223 while (list($key) = each($scan)) {
1224 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
1225 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
1226 break;
1229 return $size;
1233 * Try to disable all output buffering and purge
1234 * all headers.
1236 * @access private to be called only from lib/setup.php !
1237 * @return void
1239 function disable_output_buffering() {
1240 $olddebug = error_reporting(0);
1242 // disable compression, it would prevent closing of buffers
1243 if (ini_get_bool('zlib.output_compression')) {
1244 ini_set('zlib.output_compression', 'Off');
1247 // try to flush everything all the time
1248 ob_implicit_flush(true);
1250 // close all buffers if possible and discard any existing output
1251 // this can actually work around some whitespace problems in config.php
1252 while(ob_get_level()) {
1253 if (!ob_end_clean()) {
1254 // prevent infinite loop when buffer can not be closed
1255 break;
1259 // disable any other output handlers
1260 ini_set('output_handler', '');
1262 error_reporting($olddebug);
1266 * Check whether a major upgrade is needed. That is defined as an upgrade that
1267 * changes something really fundamental in the database, so nothing can possibly
1268 * work until the database has been updated, and that is defined by the hard-coded
1269 * version number in this function.
1271 function redirect_if_major_upgrade_required() {
1272 global $CFG;
1273 $lastmajordbchanges = 2013041800.00;
1274 if (empty($CFG->version) or (float)$CFG->version < $lastmajordbchanges or
1275 during_initial_install() or !empty($CFG->adminsetuppending)) {
1276 try {
1277 @session_get_instance()->terminate_current();
1278 } catch (Exception $e) {
1279 // Ignore any errors, redirect to upgrade anyway.
1281 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
1282 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1283 @header('Location: ' . $url);
1284 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
1285 exit;
1290 * Makes sure that upgrade process is not running
1292 * To be inserted in the core functions that can not be called by pluigns during upgrade.
1293 * Core upgrade should not use any API functions at all.
1294 * See {@link http://docs.moodle.org/dev/Upgrade_API#Upgrade_code_restrictions}
1296 * @throws moodle_exception if executed from inside of upgrade script and $warningonly is false
1297 * @param bool $warningonly if true displays a warning instead of throwing an exception
1298 * @return bool true if executed from outside of upgrade process, false if from inside upgrade process and function is used for warning only
1300 function upgrade_ensure_not_running($warningonly = false) {
1301 global $CFG;
1302 if (!empty($CFG->upgraderunning)) {
1303 if (!$warningonly) {
1304 throw new moodle_exception('cannotexecduringupgrade');
1305 } else {
1306 debugging(get_string('cannotexecduringupgrade', 'error'), DEBUG_DEVELOPER);
1307 return false;
1310 return true;
1314 * Function to check if a directory exists and by default create it if not exists.
1316 * Previously this was accepting paths only from dataroot, but we now allow
1317 * files outside of dataroot if you supply custom paths for some settings in config.php.
1318 * This function does not verify that the directory is writable.
1320 * NOTE: this function uses current file stat cache,
1321 * please use clearstatcache() before this if you expect that the
1322 * directories may have been removed recently from a different request.
1324 * @param string $dir absolute directory path
1325 * @param boolean $create directory if does not exist
1326 * @param boolean $recursive create directory recursively
1327 * @return boolean true if directory exists or created, false otherwise
1329 function check_dir_exists($dir, $create = true, $recursive = true) {
1330 global $CFG;
1332 umask(0000); // just in case some evil code changed it
1334 if (is_dir($dir)) {
1335 return true;
1338 if (!$create) {
1339 return false;
1342 return mkdir($dir, $CFG->directorypermissions, $recursive);
1346 * Create a directory and make sure it is writable.
1348 * @private
1349 * @param string $dir the full path of the directory to be created
1350 * @param bool $exceptiononerror throw exception if error encountered
1351 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1353 function make_writable_directory($dir, $exceptiononerror = true) {
1354 global $CFG;
1356 if (file_exists($dir) and !is_dir($dir)) {
1357 if ($exceptiononerror) {
1358 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1359 } else {
1360 return false;
1364 umask(0000); // just in case some evil code changed it
1366 if (!file_exists($dir)) {
1367 if (!mkdir($dir, $CFG->directorypermissions, true)) {
1368 clearstatcache();
1369 // There might be a race condition when creating directory.
1370 if (!is_dir($dir)) {
1371 if ($exceptiononerror) {
1372 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1373 } else {
1374 debugging('Can not create directory: '.$dir, DEBUG_DEVELOPER);
1375 return false;
1381 if (!is_writable($dir)) {
1382 if ($exceptiononerror) {
1383 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1384 } else {
1385 return false;
1389 return $dir;
1393 * Protect a directory from web access.
1394 * Could be extended in the future to support other mechanisms (e.g. other webservers).
1396 * @private
1397 * @param string $dir the full path of the directory to be protected
1399 function protect_directory($dir) {
1400 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1401 if (!file_exists("$dir/.htaccess")) {
1402 if ($handle = fopen("$dir/.htaccess", 'w')) { // For safety
1403 @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");
1404 @fclose($handle);
1410 * Create a directory under dataroot and make sure it is writable.
1411 * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
1413 * @param string $directory the full path of the directory to be created under $CFG->dataroot
1414 * @param bool $exceptiononerror throw exception if error encountered
1415 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1417 function make_upload_directory($directory, $exceptiononerror = true) {
1418 global $CFG;
1420 if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1421 debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1423 } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
1424 debugging('Use make_cache_directory() for creation of chache directory and $CFG->cachedir to get the location.');
1427 protect_directory($CFG->dataroot);
1428 return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1432 * Create a directory under tempdir and make sure it is writable.
1433 * Temporary files should be used during the current request only!
1435 * @param string $directory the full path of the directory to be created under $CFG->tempdir
1436 * @param bool $exceptiononerror throw exception if error encountered
1437 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1439 function make_temp_directory($directory, $exceptiononerror = true) {
1440 global $CFG;
1441 if ($CFG->tempdir !== "$CFG->dataroot/temp") {
1442 check_dir_exists($CFG->tempdir, true, true);
1443 protect_directory($CFG->tempdir);
1444 } else {
1445 protect_directory($CFG->dataroot);
1447 return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1451 * Create a directory under cachedir and make sure it is writable.
1453 * @param string $directory the full path of the directory to be created under $CFG->cachedir
1454 * @param bool $exceptiononerror throw exception if error encountered
1455 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1457 function make_cache_directory($directory, $exceptiononerror = true) {
1458 global $CFG;
1459 if ($CFG->cachedir !== "$CFG->dataroot/cache") {
1460 check_dir_exists($CFG->cachedir, true, true);
1461 protect_directory($CFG->cachedir);
1462 } else {
1463 protect_directory($CFG->dataroot);
1465 return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1469 * Checks if current user is a web crawler.
1471 * This list can not be made complete, this is not a security
1472 * restriction, we make the list only to help these sites
1473 * especially when automatic guest login is disabled.
1475 * If admin needs security they should enable forcelogin
1476 * and disable guest access!!
1478 * @return bool
1480 function is_web_crawler() {
1481 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
1482 if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
1483 return true;
1484 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) { // Google
1485 return true;
1486 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yahoo! Slurp') !== false ) { // Yahoo
1487 return true;
1488 } else if (strpos($_SERVER['HTTP_USER_AGENT'], '[ZSEBOT]') !== false ) { // Zoomspider
1489 return true;
1490 } else if (stripos($_SERVER['HTTP_USER_AGENT'], 'msnbot') !== false ) { // MSN Search
1491 return true;
1492 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'bingbot') !== false ) { // Bing
1493 return true;
1494 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yandex') !== false ) {
1495 return true;
1496 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'AltaVista') !== false ) {
1497 return true;
1498 } else if (stripos($_SERVER['HTTP_USER_AGENT'], 'baiduspider') !== false ) { // Baidu
1499 return true;
1500 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Teoma') !== false ) { // Ask.com
1501 return true;
1504 return false;
1508 * This class solves the problem of how to initialise $OUTPUT.
1510 * The problem is caused be two factors
1511 * <ol>
1512 * <li>On the one hand, we cannot be sure when output will start. In particular,
1513 * an error, which needs to be displayed, could be thrown at any time.</li>
1514 * <li>On the other hand, we cannot be sure when we will have all the information
1515 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1516 * (potentially) depends on the current course, course categories, and logged in user.
1517 * It also depends on whether the current page requires HTTPS.</li>
1518 * </ol>
1520 * So, it is hard to find a single natural place during Moodle script execution,
1521 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1522 * adopt the following strategy
1523 * <ol>
1524 * <li>We will initialise $OUTPUT the first time it is used.</li>
1525 * <li>If, after $OUTPUT has been initialised, the script tries to change something
1526 * that $OUTPUT depends on, we throw an exception making it clear that the script
1527 * did something wrong.
1528 * </ol>
1530 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1531 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1532 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1533 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1535 * Note that this class is used before lib/outputlib.php has been loaded, so we
1536 * must be careful referring to classes/functions from there, they may not be
1537 * defined yet, and we must avoid fatal errors.
1539 * @copyright 2009 Tim Hunt
1540 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1541 * @since Moodle 2.0
1543 class bootstrap_renderer {
1545 * Handles re-entrancy. Without this, errors or debugging output that occur
1546 * during the initialisation of $OUTPUT, cause infinite recursion.
1547 * @var boolean
1549 protected $initialising = false;
1552 * Have we started output yet?
1553 * @return boolean true if the header has been printed.
1555 public function has_started() {
1556 return false;
1560 * Constructor - to be used by core code only.
1561 * @param string $method The method to call
1562 * @param array $arguments Arguments to pass to the method being called
1563 * @return string
1565 public function __call($method, $arguments) {
1566 global $OUTPUT, $PAGE;
1568 $recursing = false;
1569 if ($method == 'notification') {
1570 // Catch infinite recursion caused by debugging output during print_header.
1571 $backtrace = debug_backtrace();
1572 array_shift($backtrace);
1573 array_shift($backtrace);
1574 $recursing = is_early_init($backtrace);
1577 $earlymethods = array(
1578 'fatal_error' => 'early_error',
1579 'notification' => 'early_notification',
1582 // If lib/outputlib.php has been loaded, call it.
1583 if (!empty($PAGE) && !$recursing) {
1584 if (array_key_exists($method, $earlymethods)) {
1585 //prevent PAGE->context warnings - exceptions might appear before we set any context
1586 $PAGE->set_context(null);
1588 $PAGE->initialise_theme_and_output();
1589 return call_user_func_array(array($OUTPUT, $method), $arguments);
1592 $this->initialising = true;
1594 // Too soon to initialise $OUTPUT, provide a couple of key methods.
1595 if (array_key_exists($method, $earlymethods)) {
1596 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1599 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1603 * Returns nicely formatted error message in a div box.
1604 * @static
1605 * @param string $message error message
1606 * @param string $moreinfourl (ignored in early errors)
1607 * @param string $link (ignored in early errors)
1608 * @param array $backtrace
1609 * @param string $debuginfo
1610 * @return string
1612 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1613 global $CFG;
1615 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1616 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1617 width: 80%; -moz-border-radius: 20px; padding: 15px">
1618 ' . $message . '
1619 </div>';
1620 // Check whether debug is set.
1621 $debug = (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER);
1622 // Also check we have it set in the config file. This occurs if the method to read the config table from the
1623 // database fails, reading from the config table is the first database interaction we have.
1624 $debug = $debug || (!empty($CFG->config_php_settings['debug']) && $CFG->config_php_settings['debug'] >= DEBUG_DEVELOPER );
1625 if ($debug) {
1626 if (!empty($debuginfo)) {
1627 $debuginfo = s($debuginfo); // removes all nasty JS
1628 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1629 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
1631 if (!empty($backtrace)) {
1632 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1636 return $content;
1640 * This function should only be called by this class, or from exception handlers
1641 * @static
1642 * @param string $message error message
1643 * @param string $moreinfourl (ignored in early errors)
1644 * @param string $link (ignored in early errors)
1645 * @param array $backtrace
1646 * @param string $debuginfo extra information for developers
1647 * @return string
1649 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = null) {
1650 global $CFG;
1652 if (CLI_SCRIPT) {
1653 echo "!!! $message !!!\n";
1654 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1655 if (!empty($debuginfo)) {
1656 echo "\nDebug info: $debuginfo";
1658 if (!empty($backtrace)) {
1659 echo "\nStack trace: " . format_backtrace($backtrace, true);
1662 return;
1664 } else if (AJAX_SCRIPT) {
1665 $e = new stdClass();
1666 $e->error = $message;
1667 $e->stacktrace = NULL;
1668 $e->debuginfo = NULL;
1669 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1670 if (!empty($debuginfo)) {
1671 $e->debuginfo = $debuginfo;
1673 if (!empty($backtrace)) {
1674 $e->stacktrace = format_backtrace($backtrace, true);
1677 $e->errorcode = $errorcode;
1678 @header('Content-Type: application/json; charset=utf-8');
1679 echo json_encode($e);
1680 return;
1683 // In the name of protocol correctness, monitoring and performance
1684 // profiling, set the appropriate error headers for machine consumption.
1685 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
1686 @header($protocol . ' 503 Service Unavailable');
1688 // better disable any caching
1689 @header('Content-Type: text/html; charset=utf-8');
1690 @header('X-UA-Compatible: IE=edge');
1691 @header('Cache-Control: no-store, no-cache, must-revalidate');
1692 @header('Cache-Control: post-check=0, pre-check=0', false);
1693 @header('Pragma: no-cache');
1694 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1695 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1697 if (function_exists('get_string')) {
1698 $strerror = get_string('error');
1699 } else {
1700 $strerror = 'Error';
1703 $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
1705 return self::plain_page($strerror, $content);
1709 * Early notification message
1710 * @static
1711 * @param string $message
1712 * @param string $classes usually notifyproblem or notifysuccess
1713 * @return string
1715 public static function early_notification($message, $classes = 'notifyproblem') {
1716 return '<div class="' . $classes . '">' . $message . '</div>';
1720 * Page should redirect message.
1721 * @static
1722 * @param string $encodedurl redirect url
1723 * @return string
1725 public static function plain_redirect_message($encodedurl) {
1726 $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
1727 $encodedurl .'">'. get_string('continue') .'</a></div>';
1728 return self::plain_page(get_string('redirect'), $message);
1732 * Early redirection page, used before full init of $PAGE global
1733 * @static
1734 * @param string $encodedurl redirect url
1735 * @param string $message redirect message
1736 * @param int $delay time in seconds
1737 * @return string redirect page
1739 public static function early_redirect_message($encodedurl, $message, $delay) {
1740 $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
1741 $content = self::early_error_content($message, null, null, null);
1742 $content .= self::plain_redirect_message($encodedurl);
1744 return self::plain_page(get_string('redirect'), $content, $meta);
1748 * Output basic html page.
1749 * @static
1750 * @param string $title page title
1751 * @param string $content page content
1752 * @param string $meta meta tag
1753 * @return string html page
1755 public static function plain_page($title, $content, $meta = '') {
1756 if (function_exists('get_string') && function_exists('get_html_lang')) {
1757 $htmllang = get_html_lang();
1758 } else {
1759 $htmllang = '';
1762 $footer = '';
1763 if (MDL_PERF_TEST) {
1764 $perfinfo = get_performance_info();
1765 $footer = '<footer>' . $perfinfo['html'] . '</footer>';
1768 return '<!DOCTYPE html>
1769 <html ' . $htmllang . '>
1770 <head>
1771 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1772 '.$meta.'
1773 <title>' . $title . '</title>
1774 </head><body>' . $content . $footer . '</body></html>';