MDL-56303 quiz: lack of quiz filtering
[moodle.git] / lib / setuplib.php
blob61de50a7e79e94d8689800154cda77c5d094adde
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);
55 /**
56 * Simple class. It is usually used instead of stdClass because it looks
57 * more familiar to Java developers ;-) Do not use for type checking of
58 * function parameters. Please use stdClass instead.
60 * @package core
61 * @subpackage lib
62 * @copyright 2009 Petr Skoda {@link http://skodak.org}
63 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
64 * @deprecated since 2.0
66 class object extends stdClass {};
68 /**
69 * Base Moodle Exception class
71 * Although this class is defined here, you cannot throw a moodle_exception until
72 * after moodlelib.php has been included (which will happen very soon).
74 * @package core
75 * @subpackage lib
76 * @copyright 2008 Petr Skoda {@link http://skodak.org}
77 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
79 class moodle_exception extends Exception {
81 /**
82 * @var string The name of the string from error.php to print
84 public $errorcode;
86 /**
87 * @var string The name of module
89 public $module;
91 /**
92 * @var mixed Extra words and phrases that might be required in the error string
94 public $a;
96 /**
97 * @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.
99 public $link;
102 * @var string Optional information to aid the debugging process
104 public $debuginfo;
107 * Constructor
108 * @param string $errorcode The name of the string from error.php to print
109 * @param string $module name of module
110 * @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.
111 * @param mixed $a Extra words and phrases that might be required in the error string
112 * @param string $debuginfo optional debugging information
114 function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
115 if (empty($module) || $module == 'moodle' || $module == 'core') {
116 $module = 'error';
119 $this->errorcode = $errorcode;
120 $this->module = $module;
121 $this->link = $link;
122 $this->a = $a;
123 $this->debuginfo = is_null($debuginfo) ? null : (string)$debuginfo;
125 if (get_string_manager()->string_exists($errorcode, $module)) {
126 $message = get_string($errorcode, $module, $a);
127 $haserrorstring = true;
128 } else {
129 $message = $module . '/' . $errorcode;
130 $haserrorstring = false;
133 if (defined('PHPUNIT_TEST') and PHPUNIT_TEST and $debuginfo) {
134 $message = "$message ($debuginfo)";
137 if (!$haserrorstring and defined('PHPUNIT_TEST') and PHPUNIT_TEST) {
138 // Append the contents of $a to $debuginfo so helpful information isn't lost.
139 // This emulates what {@link get_exception_info()} does. Unfortunately that
140 // function is not used by phpunit.
141 $message .= PHP_EOL.'$a contents: '.print_r($a, true);
144 parent::__construct($message, 0);
149 * Course/activity access exception.
151 * This exception is thrown from require_login()
153 * @package core_access
154 * @copyright 2010 Petr Skoda {@link http://skodak.org}
155 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
157 class require_login_exception extends moodle_exception {
159 * Constructor
160 * @param string $debuginfo Information to aid the debugging process
162 function __construct($debuginfo) {
163 parent::__construct('requireloginerror', 'error', '', NULL, $debuginfo);
168 * Session timeout exception.
170 * This exception is thrown from require_login()
172 * @package core_access
173 * @copyright 2015 Andrew Nicols <andrew@nicols.co.uk>
174 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
176 class require_login_session_timeout_exception extends require_login_exception {
178 * Constructor
180 public function __construct() {
181 moodle_exception::__construct('sessionerroruser', 'error');
186 * Web service parameter exception class
187 * @deprecated since Moodle 2.2 - use moodle exception instead
188 * This exception must be thrown to the web service client when a web service parameter is invalid
189 * The error string is gotten from webservice.php
191 class webservice_parameter_exception extends moodle_exception {
193 * Constructor
194 * @param string $errorcode The name of the string from webservice.php to print
195 * @param string $a The name of the parameter
196 * @param string $debuginfo Optional information to aid debugging
198 function __construct($errorcode=null, $a = '', $debuginfo = null) {
199 parent::__construct($errorcode, 'webservice', '', $a, $debuginfo);
204 * Exceptions indicating user does not have permissions to do something
205 * and the execution can not continue.
207 * @package core_access
208 * @copyright 2009 Petr Skoda {@link http://skodak.org}
209 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
211 class required_capability_exception extends moodle_exception {
213 * Constructor
214 * @param context $context The context used for the capability check
215 * @param string $capability The required capability
216 * @param string $errormessage The error message to show the user
217 * @param string $stringfile
219 function __construct($context, $capability, $errormessage, $stringfile) {
220 $capabilityname = get_capability_string($capability);
221 if ($context->contextlevel == CONTEXT_MODULE and preg_match('/:view$/', $capability)) {
222 // 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
223 $parentcontext = $context->get_parent_context();
224 $link = $parentcontext->get_url();
225 } else {
226 $link = $context->get_url();
228 parent::__construct($errormessage, $stringfile, $link, $capabilityname);
233 * Exception indicating programming error, must be fixed by a programer. For example
234 * a core API might throw this type of exception if a plugin calls it incorrectly.
236 * @package core
237 * @subpackage lib
238 * @copyright 2008 Petr Skoda {@link http://skodak.org}
239 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
241 class coding_exception extends moodle_exception {
243 * Constructor
244 * @param string $hint short description of problem
245 * @param string $debuginfo detailed information how to fix problem
247 function __construct($hint, $debuginfo=null) {
248 parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
253 * Exception indicating malformed parameter problem.
254 * This exception is not supposed to be thrown when processing
255 * user submitted data in forms. It is more suitable
256 * for WS and other low level stuff.
258 * @package core
259 * @subpackage lib
260 * @copyright 2009 Petr Skoda {@link http://skodak.org}
261 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
263 class invalid_parameter_exception extends moodle_exception {
265 * Constructor
266 * @param string $debuginfo some detailed information
268 function __construct($debuginfo=null) {
269 parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
274 * Exception indicating malformed response problem.
275 * This exception is not supposed to be thrown when processing
276 * user submitted data in forms. It is more suitable
277 * for WS and other low level stuff.
279 class invalid_response_exception extends moodle_exception {
281 * Constructor
282 * @param string $debuginfo some detailed information
284 function __construct($debuginfo=null) {
285 parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
290 * An exception that indicates something really weird happened. For example,
291 * if you do switch ($context->contextlevel), and have one case for each
292 * CONTEXT_... constant. You might throw an invalid_state_exception in the
293 * default case, to just in case something really weird is going on, and
294 * $context->contextlevel is invalid - rather than ignoring this possibility.
296 * @package core
297 * @subpackage lib
298 * @copyright 2009 onwards Martin Dougiamas {@link http://moodle.com}
299 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
301 class invalid_state_exception extends moodle_exception {
303 * Constructor
304 * @param string $hint short description of problem
305 * @param string $debuginfo optional more detailed information
307 function __construct($hint, $debuginfo=null) {
308 parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
313 * An exception that indicates incorrect permissions in $CFG->dataroot
315 * @package core
316 * @subpackage lib
317 * @copyright 2010 Petr Skoda {@link http://skodak.org}
318 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
320 class invalid_dataroot_permissions extends moodle_exception {
322 * Constructor
323 * @param string $debuginfo optional more detailed information
325 function __construct($debuginfo = NULL) {
326 parent::__construct('invaliddatarootpermissions', 'error', '', NULL, $debuginfo);
331 * An exception that indicates that file can not be served
333 * @package core
334 * @subpackage lib
335 * @copyright 2010 Petr Skoda {@link http://skodak.org}
336 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
338 class file_serving_exception extends moodle_exception {
340 * Constructor
341 * @param string $debuginfo optional more detailed information
343 function __construct($debuginfo = NULL) {
344 parent::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
349 * Default exception handler.
351 * @param Exception $ex
352 * @return void -does not return. Terminates execution!
354 function default_exception_handler($ex) {
355 global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION, $PAGE;
357 // detect active db transactions, rollback and log as error
358 abort_all_db_transactions();
360 if (($ex instanceof required_capability_exception) && !CLI_SCRIPT && !AJAX_SCRIPT && !empty($CFG->autologinguests) && !empty($USER->autologinguest)) {
361 $SESSION->wantsurl = qualified_me();
362 redirect(get_login_url());
365 $info = get_exception_info($ex);
367 if (debugging('', DEBUG_MINIMAL)) {
368 $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
369 error_log($logerrmsg);
372 if (is_early_init($info->backtrace)) {
373 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
374 } else {
375 try {
376 if ($DB) {
377 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
378 $DB->set_debug(0);
380 echo $OUTPUT->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo,
381 $info->errorcode);
382 } catch (Exception $e) {
383 $out_ex = $e;
384 } catch (Throwable $e) {
385 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
386 $out_ex = $e;
389 if (isset($out_ex)) {
390 // default exception handler MUST not throw any exceptions!!
391 // 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
392 // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
393 if (CLI_SCRIPT or AJAX_SCRIPT) {
394 // just ignore the error and send something back using the safest method
395 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
396 } else {
397 echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
398 $outinfo = get_exception_info($out_ex);
399 echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
404 exit(1); // General error code
408 * Default error handler, prevents some white screens.
409 * @param int $errno
410 * @param string $errstr
411 * @param string $errfile
412 * @param int $errline
413 * @param array $errcontext
414 * @return bool false means use default error handler
416 function default_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
417 if ($errno == 4096) {
418 //fatal catchable error
419 throw new coding_exception('PHP catchable fatal error', $errstr);
421 return false;
425 * Unconditionally abort all database transactions, this function
426 * should be called from exception handlers only.
427 * @return void
429 function abort_all_db_transactions() {
430 global $CFG, $DB, $SCRIPT;
432 // default exception handler MUST not throw any exceptions!!
434 if ($DB && $DB->is_transaction_started()) {
435 error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
436 // note: transaction blocks should never change current $_SESSION
437 $DB->force_transaction_rollback();
442 * This function encapsulates the tests for whether an exception was thrown in
443 * early init -- either during setup.php or during init of $OUTPUT.
445 * If another exception is thrown then, and if we do not take special measures,
446 * we would just get a very cryptic message "Exception thrown without a stack
447 * frame in Unknown on line 0". That makes debugging very hard, so we do take
448 * special measures in default_exception_handler, with the help of this function.
450 * @param array $backtrace the stack trace to analyse.
451 * @return boolean whether the stack trace is somewhere in output initialisation.
453 function is_early_init($backtrace) {
454 $dangerouscode = array(
455 array('function' => 'header', 'type' => '->'),
456 array('class' => 'bootstrap_renderer'),
457 array('file' => dirname(__FILE__).'/setup.php'),
459 foreach ($backtrace as $stackframe) {
460 foreach ($dangerouscode as $pattern) {
461 $matches = true;
462 foreach ($pattern as $property => $value) {
463 if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
464 $matches = false;
467 if ($matches) {
468 return true;
472 return false;
476 * Abort execution by throwing of a general exception,
477 * default exception handler displays the error message in most cases.
479 * @param string $errorcode The name of the language string containing the error message.
480 * Normally this should be in the error.php lang file.
481 * @param string $module The language file to get the error message from.
482 * @param string $link The url where the user will be prompted to continue.
483 * If no url is provided the user will be directed to the site index page.
484 * @param object $a Extra words and phrases that might be required in the error string
485 * @param string $debuginfo optional debugging information
486 * @return void, always throws exception!
488 function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
489 throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
493 * Returns detailed information about specified exception.
494 * @param exception $ex
495 * @return object
497 function get_exception_info($ex) {
498 global $CFG, $DB, $SESSION;
500 if ($ex instanceof moodle_exception) {
501 $errorcode = $ex->errorcode;
502 $module = $ex->module;
503 $a = $ex->a;
504 $link = $ex->link;
505 $debuginfo = $ex->debuginfo;
506 } else {
507 $errorcode = 'generalexceptionmessage';
508 $module = 'error';
509 $a = $ex->getMessage();
510 $link = '';
511 $debuginfo = '';
514 // Append the error code to the debug info to make grepping and googling easier
515 $debuginfo .= PHP_EOL."Error code: $errorcode";
517 $backtrace = $ex->getTrace();
518 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
519 array_unshift($backtrace, $place);
521 // Be careful, no guarantee moodlelib.php is loaded.
522 if (empty($module) || $module == 'moodle' || $module == 'core') {
523 $module = 'error';
525 // Search for the $errorcode's associated string
526 // If not found, append the contents of $a to $debuginfo so helpful information isn't lost
527 if (function_exists('get_string_manager')) {
528 if (get_string_manager()->string_exists($errorcode, $module)) {
529 $message = get_string($errorcode, $module, $a);
530 } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
531 // Search in moodle file if error specified - needed for backwards compatibility
532 $message = get_string($errorcode, 'moodle', $a);
533 } else {
534 $message = $module . '/' . $errorcode;
535 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
537 } else {
538 $message = $module . '/' . $errorcode;
539 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
542 // Remove some absolute paths from message and debugging info.
543 $searches = array();
544 $replaces = array();
545 $cfgnames = array('tempdir', 'cachedir', 'localcachedir', 'themedir', 'dataroot', 'dirroot');
546 foreach ($cfgnames as $cfgname) {
547 if (property_exists($CFG, $cfgname)) {
548 $searches[] = $CFG->$cfgname;
549 $replaces[] = "[$cfgname]";
552 if (!empty($searches)) {
553 $message = str_replace($searches, $replaces, $message);
554 $debuginfo = str_replace($searches, $replaces, $debuginfo);
557 // Be careful, no guarantee weblib.php is loaded.
558 if (function_exists('clean_text')) {
559 $message = clean_text($message);
560 } else {
561 $message = htmlspecialchars($message);
564 if (!empty($CFG->errordocroot)) {
565 $errordoclink = $CFG->errordocroot . '/en/';
566 } else {
567 $errordoclink = get_docs_url();
570 if ($module === 'error') {
571 $modulelink = 'moodle';
572 } else {
573 $modulelink = $module;
575 $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
577 if (empty($link)) {
578 if (!empty($SESSION->fromurl)) {
579 $link = $SESSION->fromurl;
580 unset($SESSION->fromurl);
581 } else {
582 $link = $CFG->wwwroot .'/';
586 // When printing an error the continue button should never link offsite.
587 // We cannot use clean_param() here as it is not guaranteed that it has been loaded yet.
588 $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
589 if (stripos($link, $CFG->wwwroot) === 0) {
590 // Internal HTTP, all good.
591 } else if (!empty($CFG->loginhttps) && stripos($link, $httpswwwroot) === 0) {
592 // Internal HTTPS, all good.
593 } else {
594 // External link spotted!
595 $link = $CFG->wwwroot . '/';
598 $info = new stdClass();
599 $info->message = $message;
600 $info->errorcode = $errorcode;
601 $info->backtrace = $backtrace;
602 $info->link = $link;
603 $info->moreinfourl = $moreinfourl;
604 $info->a = $a;
605 $info->debuginfo = $debuginfo;
607 return $info;
611 * Generate a uuid.
613 * Unique is hard. Very hard. Attempt to use the PECL UUID functions if available, and if not then revert to
614 * constructing the uuid using mt_rand.
616 * It is important that this token is not solely based on time as this could lead
617 * to duplicates in a clustered environment (especially on VMs due to poor time precision).
619 * @return string The uuid.
621 function generate_uuid() {
622 $uuid = '';
624 if (function_exists("uuid_create")) {
625 $context = null;
626 uuid_create($context);
628 uuid_make($context, UUID_MAKE_V4);
629 uuid_export($context, UUID_FMT_STR, $uuid);
630 } else {
631 // Fallback uuid generation based on:
632 // "http://www.php.net/manual/en/function.uniqid.php#94959".
633 $uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
635 // 32 bits for "time_low".
636 mt_rand(0, 0xffff), mt_rand(0, 0xffff),
638 // 16 bits for "time_mid".
639 mt_rand(0, 0xffff),
641 // 16 bits for "time_hi_and_version",
642 // four most significant bits holds version number 4.
643 mt_rand(0, 0x0fff) | 0x4000,
645 // 16 bits, 8 bits for "clk_seq_hi_res",
646 // 8 bits for "clk_seq_low",
647 // two most significant bits holds zero and one for variant DCE1.1.
648 mt_rand(0, 0x3fff) | 0x8000,
650 // 48 bits for "node".
651 mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
653 return trim($uuid);
657 * Returns the Moodle Docs URL in the users language for a given 'More help' link.
659 * There are three cases:
661 * 1. In the normal case, $path will be a short relative path 'component/thing',
662 * like 'mod/folder/view' 'group/import'. This gets turned into an link to
663 * MoodleDocs in the user's language, and for the appropriate Moodle version.
664 * E.g. 'group/import' may become 'http://docs.moodle.org/2x/en/group/import'.
665 * The 'http://docs.moodle.org' bit comes from $CFG->docroot.
667 * This is the only option that should be used in standard Moodle code. The other
668 * two options have been implemented because they are useful for third-party plugins.
670 * 2. $path may be an absolute URL, starting http:// or https://. In this case,
671 * the link is used as is.
673 * 3. $path may start %%WWWROOT%%, in which case that is replaced by
674 * $CFG->wwwroot to make the link.
676 * @param string $path the place to link to. See above for details.
677 * @return string The MoodleDocs URL in the user's language. for example @link http://docs.moodle.org/2x/en/$path}
679 function get_docs_url($path = null) {
680 global $CFG;
682 // Absolute URLs are used unmodified.
683 if (substr($path, 0, 7) === 'http://' || substr($path, 0, 8) === 'https://') {
684 return $path;
687 // Paths starting %%WWWROOT%% have that replaced by $CFG->wwwroot.
688 if (substr($path, 0, 11) === '%%WWWROOT%%') {
689 return $CFG->wwwroot . substr($path, 11);
692 // Otherwise we do the normal case, and construct a MoodleDocs URL relative to $CFG->docroot.
694 // Check that $CFG->branch has been set up, during installation it won't be.
695 if (empty($CFG->branch)) {
696 // It's not there yet so look at version.php.
697 include($CFG->dirroot.'/version.php');
698 } else {
699 // We can use $CFG->branch and avoid having to include version.php.
700 $branch = $CFG->branch;
702 // ensure branch is valid.
703 if (!$branch) {
704 // We should never get here but in case we do lets set $branch to .
705 // the smart one's will know that this is the current directory
706 // and the smarter ones will know that there is some smart matching
707 // that will ensure people end up at the latest version of the docs.
708 $branch = '.';
710 if (empty($CFG->doclang)) {
711 $lang = current_language();
712 } else {
713 $lang = $CFG->doclang;
715 $end = '/' . $branch . '/' . $lang . '/' . $path;
716 if (empty($CFG->docroot)) {
717 return 'http://docs.moodle.org'. $end;
718 } else {
719 return $CFG->docroot . $end ;
724 * Formats a backtrace ready for output.
726 * @param array $callers backtrace array, as returned by debug_backtrace().
727 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
728 * @return string formatted backtrace, ready for output.
730 function format_backtrace($callers, $plaintext = false) {
731 // do not use $CFG->dirroot because it might not be available in destructors
732 $dirroot = dirname(dirname(__FILE__));
734 if (empty($callers)) {
735 return '';
738 $from = $plaintext ? '' : '<ul style="text-align: left" data-rel="backtrace">';
739 foreach ($callers as $caller) {
740 if (!isset($caller['line'])) {
741 $caller['line'] = '?'; // probably call_user_func()
743 if (!isset($caller['file'])) {
744 $caller['file'] = 'unknownfile'; // probably call_user_func()
746 $from .= $plaintext ? '* ' : '<li>';
747 $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
748 if (isset($caller['function'])) {
749 $from .= ': call to ';
750 if (isset($caller['class'])) {
751 $from .= $caller['class'] . $caller['type'];
753 $from .= $caller['function'] . '()';
754 } else if (isset($caller['exception'])) {
755 $from .= ': '.$caller['exception'].' thrown';
757 $from .= $plaintext ? "\n" : '</li>';
759 $from .= $plaintext ? '' : '</ul>';
761 return $from;
765 * This function makes the return value of ini_get consistent if you are
766 * setting server directives through the .htaccess file in apache.
768 * Current behavior for value set from php.ini On = 1, Off = [blank]
769 * Current behavior for value set from .htaccess On = On, Off = Off
770 * Contributed by jdell @ unr.edu
772 * @param string $ini_get_arg The argument to get
773 * @return bool True for on false for not
775 function ini_get_bool($ini_get_arg) {
776 $temp = ini_get($ini_get_arg);
778 if ($temp == '1' or strtolower($temp) == 'on') {
779 return true;
781 return false;
785 * This function verifies the sanity of PHP configuration
786 * and stops execution if anything critical found.
788 function setup_validate_php_configuration() {
789 // this must be very fast - no slow checks here!!!
791 if (ini_get_bool('session.auto_start')) {
792 print_error('sessionautostartwarning', 'admin');
797 * Initialise global $CFG variable.
798 * @private to be used only from lib/setup.php
800 function initialise_cfg() {
801 global $CFG, $DB;
803 if (!$DB) {
804 // This should not happen.
805 return;
808 try {
809 $localcfg = get_config('core');
810 } catch (dml_exception $e) {
811 // Most probably empty db, going to install soon.
812 return;
815 foreach ($localcfg as $name => $value) {
816 // Note that get_config() keeps forced settings
817 // and normalises values to string if possible.
818 $CFG->{$name} = $value;
823 * Initialises $FULLME and friends. Private function. Should only be called from
824 * setup.php.
826 function initialise_fullme() {
827 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
829 // Detect common config error.
830 if (substr($CFG->wwwroot, -1) == '/') {
831 print_error('wwwrootslash', 'error');
834 if (CLI_SCRIPT) {
835 initialise_fullme_cli();
836 return;
839 $rurl = setup_get_remote_url();
840 $wwwroot = parse_url($CFG->wwwroot.'/');
842 if (empty($rurl['host'])) {
843 // missing host in request header, probably not a real browser, let's ignore them
845 } else if (!empty($CFG->reverseproxy)) {
846 // $CFG->reverseproxy specifies if reverse proxy server used
847 // Used in load balancing scenarios.
848 // Do not abuse this to try to solve lan/wan access problems!!!!!
850 } else {
851 if (($rurl['host'] !== $wwwroot['host']) or
852 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port']) or
853 (strpos($rurl['path'], $wwwroot['path']) !== 0)) {
855 // Explain the problem and redirect them to the right URL
856 if (!defined('NO_MOODLE_COOKIES')) {
857 define('NO_MOODLE_COOKIES', true);
859 // The login/token.php script should call the correct url/port.
860 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
861 $wwwrootport = empty($wwwroot['port'])?'':$wwwroot['port'];
862 $calledurl = $rurl['host'];
863 if (!empty($rurl['port'])) {
864 $calledurl .= ':'. $rurl['port'];
866 $correcturl = $wwwroot['host'];
867 if (!empty($wwwrootport)) {
868 $correcturl .= ':'. $wwwrootport;
870 throw new moodle_exception('requirecorrectaccess', 'error', '', null,
871 'You called ' . $calledurl .', you should have called ' . $correcturl);
873 redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
877 // Check that URL is under $CFG->wwwroot.
878 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
879 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
880 } else {
881 // Probably some weird external script
882 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
883 return;
886 // $CFG->sslproxy specifies if external SSL appliance is used
887 // (That is, the Moodle server uses http, with an external box translating everything to https).
888 if (empty($CFG->sslproxy)) {
889 if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
890 print_error('sslonlyaccess', 'error');
892 } else {
893 if ($wwwroot['scheme'] !== 'https') {
894 throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
896 $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
897 $_SERVER['HTTPS'] = 'on'; // Override $_SERVER to help external libraries with their HTTPS detection.
898 $_SERVER['SERVER_PORT'] = 443; // Assume default ssl port for the proxy.
901 // hopefully this will stop all those "clever" admins trying to set up moodle
902 // with two different addresses in intranet and Internet
903 if (!empty($CFG->reverseproxy) && $rurl['host'] === $wwwroot['host']) {
904 print_error('reverseproxyabused', 'error');
907 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
908 if (!empty($wwwroot['port'])) {
909 $hostandport .= ':'.$wwwroot['port'];
912 $FULLSCRIPT = $hostandport . $rurl['path'];
913 $FULLME = $hostandport . $rurl['fullpath'];
914 $ME = $rurl['fullpath'];
918 * Initialises $FULLME and friends for command line scripts.
919 * This is a private method for use by initialise_fullme.
921 function initialise_fullme_cli() {
922 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
924 // Urls do not make much sense in CLI scripts
925 $backtrace = debug_backtrace();
926 $topfile = array_pop($backtrace);
927 $topfile = realpath($topfile['file']);
928 $dirroot = realpath($CFG->dirroot);
930 if (strpos($topfile, $dirroot) !== 0) {
931 // Probably some weird external script
932 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
933 } else {
934 $relativefile = substr($topfile, strlen($dirroot));
935 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
936 $SCRIPT = $FULLSCRIPT = $relativefile;
937 $FULLME = $ME = null;
942 * Get the URL that PHP/the web server thinks it is serving. Private function
943 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
944 * @return array in the same format that parse_url returns, with the addition of
945 * a 'fullpath' element, which includes any slasharguments path.
947 function setup_get_remote_url() {
948 $rurl = array();
949 if (isset($_SERVER['HTTP_HOST'])) {
950 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
951 } else {
952 $rurl['host'] = null;
954 $rurl['port'] = $_SERVER['SERVER_PORT'];
955 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
956 $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ? 'http' : 'https';
958 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
959 //Apache server
960 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
962 // Fixing a known issue with:
963 // - Apache versions lesser than 2.4.11
964 // - PHP deployed in Apache as PHP-FPM via mod_proxy_fcgi
965 // - PHP versions lesser than 5.6.3 and 5.5.18.
966 if (isset($_SERVER['PATH_INFO']) && (php_sapi_name() === 'fpm-fcgi') && isset($_SERVER['SCRIPT_NAME'])) {
967 $pathinfodec = rawurldecode($_SERVER['PATH_INFO']);
968 $lenneedle = strlen($pathinfodec);
969 // Checks whether SCRIPT_NAME ends with PATH_INFO, URL-decoded.
970 if (substr($_SERVER['SCRIPT_NAME'], -$lenneedle) === $pathinfodec) {
971 // This is the "Apache 2.4.10- running PHP-FPM via mod_proxy_fcgi" fingerprint,
972 // at least on CentOS 7 (Apache/2.4.6 PHP/5.4.16) and Ubuntu 14.04 (Apache/2.4.7 PHP/5.5.9)
973 // => SCRIPT_NAME contains 'slash arguments' data too, which is wrongly exposed via PATH_INFO as URL-encoded.
974 // Fix both $_SERVER['PATH_INFO'] and $_SERVER['SCRIPT_NAME'].
975 $lenhaystack = strlen($_SERVER['SCRIPT_NAME']);
976 $pos = $lenhaystack - $lenneedle;
977 // Here $pos is greater than 0 but let's double check it.
978 if ($pos > 0) {
979 $_SERVER['PATH_INFO'] = $pathinfodec;
980 $_SERVER['SCRIPT_NAME'] = substr($_SERVER['SCRIPT_NAME'], 0, $pos);
985 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
986 //IIS - needs a lot of tweaking to make it work
987 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
989 // NOTE: we should ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS.
990 // Since 2.0, we rely on IIS rewrite extensions like Helicon ISAPI_rewrite
991 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
992 // OR
993 // we rely on a proper IIS 6.0+ configuration: the 'FastCGIUtf8ServerVariables' registry key.
994 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
995 // Check that PATH_INFO works == must not contain the script name.
996 if (strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === false) {
997 $rurl['fullpath'] .= clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
1001 if (isset($_SERVER['QUERY_STRING']) and $_SERVER['QUERY_STRING'] !== '') {
1002 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
1004 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
1006 /* NOTE: following servers are not fully tested! */
1008 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
1009 //lighttpd - not officially supported
1010 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1012 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
1013 //nginx - not officially supported
1014 if (!isset($_SERVER['SCRIPT_NAME'])) {
1015 die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
1017 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1019 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
1020 //cherokee - not officially supported
1021 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1023 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
1024 //zeus - not officially supported
1025 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1027 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
1028 //LiteSpeed - not officially supported
1029 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1031 } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
1032 //obscure name found on some servers - this is definitely not supported
1033 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1035 } else if (strpos($_SERVER['SERVER_SOFTWARE'], 'PHP') === 0) {
1036 // built-in PHP Development Server
1037 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
1039 } else {
1040 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
1043 // sanitize the url a bit more, the encoding style may be different in vars above
1044 $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
1045 $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);
1047 return $rurl;
1051 * Try to work around the 'max_input_vars' restriction if necessary.
1053 function workaround_max_input_vars() {
1054 // Make sure this gets executed only once from lib/setup.php!
1055 static $executed = false;
1056 if ($executed) {
1057 debugging('workaround_max_input_vars() must be called only once!');
1058 return;
1060 $executed = true;
1062 if (!isset($_SERVER["CONTENT_TYPE"]) or strpos($_SERVER["CONTENT_TYPE"], 'multipart/form-data') !== false) {
1063 // Not a post or 'multipart/form-data' which is not compatible with "php://input" reading.
1064 return;
1067 if (!isloggedin() or isguestuser()) {
1068 // Only real users post huge forms.
1069 return;
1072 $max = (int)ini_get('max_input_vars');
1074 if ($max <= 0) {
1075 // Most probably PHP < 5.3.9 that does not implement this limit.
1076 return;
1079 if ($max >= 200000) {
1080 // This value should be ok for all our forms, by setting it in php.ini
1081 // admins may prevent any unexpected regressions caused by this hack.
1083 // Note there is no need to worry about DDoS caused by making this limit very high
1084 // because there are very many easier ways to DDoS any Moodle server.
1085 return;
1088 // Worst case is advanced checkboxes which use up to two max_input_vars
1089 // slots for each entry in $_POST, because of sending two fields with the
1090 // same name. So count everything twice just in case.
1091 if (count($_POST, COUNT_RECURSIVE) * 2 < $max) {
1092 return;
1095 // Large POST request with enctype supported by php://input.
1096 // Parse php://input in chunks to bypass max_input_vars limit, which also applies to parse_str().
1097 $str = file_get_contents("php://input");
1098 if ($str === false or $str === '') {
1099 // Some weird error.
1100 return;
1103 $delim = '&';
1104 $fun = create_function('$p', 'return implode("'.$delim.'", $p);');
1105 $chunks = array_map($fun, array_chunk(explode($delim, $str), $max));
1107 // Clear everything from existing $_POST array, otherwise it might be included
1108 // twice (this affects array params primarily).
1109 foreach ($_POST as $key => $value) {
1110 unset($_POST[$key]);
1111 // Also clear from request array - but only the things that are in $_POST,
1112 // that way it will leave the things from a get request if any.
1113 unset($_REQUEST[$key]);
1116 foreach ($chunks as $chunk) {
1117 $values = array();
1118 parse_str($chunk, $values);
1120 merge_query_params($_POST, $values);
1121 merge_query_params($_REQUEST, $values);
1126 * Merge parsed POST chunks.
1128 * NOTE: this is not perfect, but it should work in most cases hopefully.
1130 * @param array $target
1131 * @param array $values
1133 function merge_query_params(array &$target, array $values) {
1134 if (isset($values[0]) and isset($target[0])) {
1135 // This looks like a split [] array, lets verify the keys are continuous starting with 0.
1136 $keys1 = array_keys($values);
1137 $keys2 = array_keys($target);
1138 if ($keys1 === array_keys($keys1) and $keys2 === array_keys($keys2)) {
1139 foreach ($values as $v) {
1140 $target[] = $v;
1142 return;
1145 foreach ($values as $k => $v) {
1146 if (!isset($target[$k])) {
1147 $target[$k] = $v;
1148 continue;
1150 if (is_array($target[$k]) and is_array($v)) {
1151 merge_query_params($target[$k], $v);
1152 continue;
1154 // We should not get here unless there are duplicates in params.
1155 $target[$k] = $v;
1160 * Initializes our performance info early.
1162 * Pairs up with get_performance_info() which is actually
1163 * in moodlelib.php. This function is here so that we can
1164 * call it before all the libs are pulled in.
1166 * @uses $PERF
1168 function init_performance_info() {
1170 global $PERF, $CFG, $USER;
1172 $PERF = new stdClass();
1173 $PERF->logwrites = 0;
1174 if (function_exists('microtime')) {
1175 $PERF->starttime = microtime();
1177 if (function_exists('memory_get_usage')) {
1178 $PERF->startmemory = memory_get_usage();
1180 if (function_exists('posix_times')) {
1181 $PERF->startposixtimes = posix_times();
1186 * Indicates whether we are in the middle of the initial Moodle install.
1188 * Very occasionally it is necessary avoid running certain bits of code before the
1189 * Moodle installation has completed. The installed flag is set in admin/index.php
1190 * after Moodle core and all the plugins have been installed, but just before
1191 * the person doing the initial install is asked to choose the admin password.
1193 * @return boolean true if the initial install is not complete.
1195 function during_initial_install() {
1196 global $CFG;
1197 return empty($CFG->rolesactive);
1201 * Function to raise the memory limit to a new value.
1202 * Will respect the memory limit if it is higher, thus allowing
1203 * settings in php.ini, apache conf or command line switches
1204 * to override it.
1206 * The memory limit should be expressed with a constant
1207 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
1208 * It is possible to use strings or integers too (eg:'128M').
1210 * @param mixed $newlimit the new memory limit
1211 * @return bool success
1213 function raise_memory_limit($newlimit) {
1214 global $CFG;
1216 if ($newlimit == MEMORY_UNLIMITED) {
1217 ini_set('memory_limit', -1);
1218 return true;
1220 } else if ($newlimit == MEMORY_STANDARD) {
1221 if (PHP_INT_SIZE > 4) {
1222 $newlimit = get_real_size('128M'); // 64bit needs more memory
1223 } else {
1224 $newlimit = get_real_size('96M');
1227 } else if ($newlimit == MEMORY_EXTRA) {
1228 if (PHP_INT_SIZE > 4) {
1229 $newlimit = get_real_size('384M'); // 64bit needs more memory
1230 } else {
1231 $newlimit = get_real_size('256M');
1233 if (!empty($CFG->extramemorylimit)) {
1234 $extra = get_real_size($CFG->extramemorylimit);
1235 if ($extra > $newlimit) {
1236 $newlimit = $extra;
1240 } else if ($newlimit == MEMORY_HUGE) {
1241 // MEMORY_HUGE uses 2G or MEMORY_EXTRA, whichever is bigger.
1242 $newlimit = get_real_size('2G');
1243 if (!empty($CFG->extramemorylimit)) {
1244 $extra = get_real_size($CFG->extramemorylimit);
1245 if ($extra > $newlimit) {
1246 $newlimit = $extra;
1250 } else {
1251 $newlimit = get_real_size($newlimit);
1254 if ($newlimit <= 0) {
1255 debugging('Invalid memory limit specified.');
1256 return false;
1259 $cur = ini_get('memory_limit');
1260 if (empty($cur)) {
1261 // if php is compiled without --enable-memory-limits
1262 // apparently memory_limit is set to ''
1263 $cur = 0;
1264 } else {
1265 if ($cur == -1){
1266 return true; // unlimited mem!
1268 $cur = get_real_size($cur);
1271 if ($newlimit > $cur) {
1272 ini_set('memory_limit', $newlimit);
1273 return true;
1275 return false;
1279 * Function to reduce the memory limit to a new value.
1280 * Will respect the memory limit if it is lower, thus allowing
1281 * settings in php.ini, apache conf or command line switches
1282 * to override it
1284 * The memory limit should be expressed with a string (eg:'64M')
1286 * @param string $newlimit the new memory limit
1287 * @return bool
1289 function reduce_memory_limit($newlimit) {
1290 if (empty($newlimit)) {
1291 return false;
1293 $cur = ini_get('memory_limit');
1294 if (empty($cur)) {
1295 // if php is compiled without --enable-memory-limits
1296 // apparently memory_limit is set to ''
1297 $cur = 0;
1298 } else {
1299 if ($cur == -1){
1300 return true; // unlimited mem!
1302 $cur = get_real_size($cur);
1305 $new = get_real_size($newlimit);
1306 // -1 is smaller, but it means unlimited
1307 if ($new < $cur && $new != -1) {
1308 ini_set('memory_limit', $newlimit);
1309 return true;
1311 return false;
1315 * Converts numbers like 10M into bytes.
1317 * @param string $size The size to be converted
1318 * @return int
1320 function get_real_size($size = 0) {
1321 if (!$size) {
1322 return 0;
1324 $scan = array();
1325 $scan['GB'] = 1073741824;
1326 $scan['Gb'] = 1073741824;
1327 $scan['G'] = 1073741824;
1328 $scan['MB'] = 1048576;
1329 $scan['Mb'] = 1048576;
1330 $scan['M'] = 1048576;
1331 $scan['m'] = 1048576;
1332 $scan['KB'] = 1024;
1333 $scan['Kb'] = 1024;
1334 $scan['K'] = 1024;
1335 $scan['k'] = 1024;
1337 while (list($key) = each($scan)) {
1338 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
1339 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
1340 break;
1343 return $size;
1347 * Try to disable all output buffering and purge
1348 * all headers.
1350 * @access private to be called only from lib/setup.php !
1351 * @return void
1353 function disable_output_buffering() {
1354 $olddebug = error_reporting(0);
1356 // disable compression, it would prevent closing of buffers
1357 if (ini_get_bool('zlib.output_compression')) {
1358 ini_set('zlib.output_compression', 'Off');
1361 // try to flush everything all the time
1362 ob_implicit_flush(true);
1364 // close all buffers if possible and discard any existing output
1365 // this can actually work around some whitespace problems in config.php
1366 while(ob_get_level()) {
1367 if (!ob_end_clean()) {
1368 // prevent infinite loop when buffer can not be closed
1369 break;
1373 // disable any other output handlers
1374 ini_set('output_handler', '');
1376 error_reporting($olddebug);
1380 * Check whether a major upgrade is needed. That is defined as an upgrade that
1381 * changes something really fundamental in the database, so nothing can possibly
1382 * work until the database has been updated, and that is defined by the hard-coded
1383 * version number in this function.
1385 function redirect_if_major_upgrade_required() {
1386 global $CFG;
1387 $lastmajordbchanges = 2014093001.00;
1388 if (empty($CFG->version) or (float)$CFG->version < $lastmajordbchanges or
1389 during_initial_install() or !empty($CFG->adminsetuppending)) {
1390 try {
1391 @\core\session\manager::terminate_current();
1392 } catch (Exception $e) {
1393 // Ignore any errors, redirect to upgrade anyway.
1395 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
1396 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1397 @header('Location: ' . $url);
1398 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
1399 exit;
1404 * Makes sure that upgrade process is not running
1406 * To be inserted in the core functions that can not be called by pluigns during upgrade.
1407 * Core upgrade should not use any API functions at all.
1408 * See {@link http://docs.moodle.org/dev/Upgrade_API#Upgrade_code_restrictions}
1410 * @throws moodle_exception if executed from inside of upgrade script and $warningonly is false
1411 * @param bool $warningonly if true displays a warning instead of throwing an exception
1412 * @return bool true if executed from outside of upgrade process, false if from inside upgrade process and function is used for warning only
1414 function upgrade_ensure_not_running($warningonly = false) {
1415 global $CFG;
1416 if (!empty($CFG->upgraderunning)) {
1417 if (!$warningonly) {
1418 throw new moodle_exception('cannotexecduringupgrade');
1419 } else {
1420 debugging(get_string('cannotexecduringupgrade', 'error'), DEBUG_DEVELOPER);
1421 return false;
1424 return true;
1428 * Function to check if a directory exists and by default create it if not exists.
1430 * Previously this was accepting paths only from dataroot, but we now allow
1431 * files outside of dataroot if you supply custom paths for some settings in config.php.
1432 * This function does not verify that the directory is writable.
1434 * NOTE: this function uses current file stat cache,
1435 * please use clearstatcache() before this if you expect that the
1436 * directories may have been removed recently from a different request.
1438 * @param string $dir absolute directory path
1439 * @param boolean $create directory if does not exist
1440 * @param boolean $recursive create directory recursively
1441 * @return boolean true if directory exists or created, false otherwise
1443 function check_dir_exists($dir, $create = true, $recursive = true) {
1444 global $CFG;
1446 umask($CFG->umaskpermissions);
1448 if (is_dir($dir)) {
1449 return true;
1452 if (!$create) {
1453 return false;
1456 return mkdir($dir, $CFG->directorypermissions, $recursive);
1460 * Create a new unique directory within the specified directory.
1462 * @param string $basedir The directory to create your new unique directory within.
1463 * @param bool $exceptiononerror throw exception if error encountered
1464 * @return string The created directory
1465 * @throws invalid_dataroot_permissions
1467 function make_unique_writable_directory($basedir, $exceptiononerror = true) {
1468 if (!is_dir($basedir) || !is_writable($basedir)) {
1469 // The basedir is not writable. We will not be able to create the child directory.
1470 if ($exceptiononerror) {
1471 throw new invalid_dataroot_permissions($basedir . ' is not writable. Unable to create a unique directory within it.');
1472 } else {
1473 return false;
1477 do {
1478 // Generate a new (hopefully unique) directory name.
1479 $uniquedir = $basedir . DIRECTORY_SEPARATOR . generate_uuid();
1480 } while (
1481 // Ensure that basedir is still writable - if we do not check, we could get stuck in a loop here.
1482 is_writable($basedir) &&
1484 // Make the new unique directory. If the directory already exists, it will return false.
1485 !make_writable_directory($uniquedir, $exceptiononerror) &&
1487 // Ensure that the directory now exists
1488 file_exists($uniquedir) && is_dir($uniquedir)
1491 // Check that the directory was correctly created.
1492 if (!file_exists($uniquedir) || !is_dir($uniquedir) || !is_writable($uniquedir)) {
1493 if ($exceptiononerror) {
1494 throw new invalid_dataroot_permissions('Unique directory creation failed.');
1495 } else {
1496 return false;
1500 return $uniquedir;
1504 * Create a directory and make sure it is writable.
1506 * @private
1507 * @param string $dir the full path of the directory to be created
1508 * @param bool $exceptiononerror throw exception if error encountered
1509 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1511 function make_writable_directory($dir, $exceptiononerror = true) {
1512 global $CFG;
1514 if (file_exists($dir) and !is_dir($dir)) {
1515 if ($exceptiononerror) {
1516 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1517 } else {
1518 return false;
1522 umask($CFG->umaskpermissions);
1524 if (!file_exists($dir)) {
1525 if (!@mkdir($dir, $CFG->directorypermissions, true)) {
1526 clearstatcache();
1527 // There might be a race condition when creating directory.
1528 if (!is_dir($dir)) {
1529 if ($exceptiononerror) {
1530 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1531 } else {
1532 debugging('Can not create directory: '.$dir, DEBUG_DEVELOPER);
1533 return false;
1539 if (!is_writable($dir)) {
1540 if ($exceptiononerror) {
1541 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1542 } else {
1543 return false;
1547 return $dir;
1551 * Protect a directory from web access.
1552 * Could be extended in the future to support other mechanisms (e.g. other webservers).
1554 * @private
1555 * @param string $dir the full path of the directory to be protected
1557 function protect_directory($dir) {
1558 global $CFG;
1559 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1560 if (!file_exists("$dir/.htaccess")) {
1561 if ($handle = fopen("$dir/.htaccess", 'w')) { // For safety
1562 @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");
1563 @fclose($handle);
1564 @chmod("$dir/.htaccess", $CFG->filepermissions);
1570 * Create a directory under dataroot and make sure it is writable.
1571 * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
1573 * @param string $directory the full path of the directory to be created under $CFG->dataroot
1574 * @param bool $exceptiononerror throw exception if error encountered
1575 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1577 function make_upload_directory($directory, $exceptiononerror = true) {
1578 global $CFG;
1580 if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1581 debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1583 } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
1584 debugging('Use make_cache_directory() for creation of cache directory and $CFG->cachedir to get the location.');
1586 } else if (strpos($directory, 'localcache/') === 0 or $directory === 'localcache') {
1587 debugging('Use make_localcache_directory() for creation of local cache directory and $CFG->localcachedir to get the location.');
1590 protect_directory($CFG->dataroot);
1591 return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1595 * Get a per-request storage directory in the tempdir.
1597 * The directory is automatically cleaned up during the shutdown handler.
1599 * @param bool $exceptiononerror throw exception if error encountered
1600 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1602 function get_request_storage_directory($exceptiononerror = true) {
1603 global $CFG;
1605 static $requestdir = null;
1607 if (!$requestdir || !file_exists($requestdir) || !is_dir($requestdir) || !is_writable($requestdir)) {
1608 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1609 check_dir_exists($CFG->localcachedir, true, true);
1610 protect_directory($CFG->localcachedir);
1611 } else {
1612 protect_directory($CFG->dataroot);
1615 if ($requestdir = make_unique_writable_directory($CFG->localcachedir, $exceptiononerror)) {
1616 // Register a shutdown handler to remove the directory.
1617 \core_shutdown_manager::register_function('remove_dir', array($requestdir));
1621 return $requestdir;
1625 * Create a per-request directory and make sure it is writable.
1626 * This can only be used during the current request and will be tidied away
1627 * automatically afterwards.
1629 * A new, unique directory is always created within the current request directory.
1631 * @param bool $exceptiononerror throw exception if error encountered
1632 * @return string full path to directory if successful, false if not; may throw exception
1634 function make_request_directory($exceptiononerror = true) {
1635 $basedir = get_request_storage_directory($exceptiononerror);
1636 return make_unique_writable_directory($basedir, $exceptiononerror);
1640 * Create a directory under tempdir and make sure it is writable.
1642 * Where possible, please use make_request_directory() and limit the scope
1643 * of your data to the current HTTP request.
1645 * Do not use for storing cache files - see make_cache_directory(), and
1646 * make_localcache_directory() instead for this purpose.
1648 * Temporary files must be on a shared storage, and heavy usage is
1649 * discouraged due to the performance impact upon clustered environments.
1651 * @param string $directory the full path of the directory to be created under $CFG->tempdir
1652 * @param bool $exceptiononerror throw exception if error encountered
1653 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1655 function make_temp_directory($directory, $exceptiononerror = true) {
1656 global $CFG;
1657 if ($CFG->tempdir !== "$CFG->dataroot/temp") {
1658 check_dir_exists($CFG->tempdir, true, true);
1659 protect_directory($CFG->tempdir);
1660 } else {
1661 protect_directory($CFG->dataroot);
1663 return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1667 * Create a directory under cachedir and make sure it is writable.
1669 * Note: this cache directory is shared by all cluster nodes.
1671 * @param string $directory the full path of the directory to be created under $CFG->cachedir
1672 * @param bool $exceptiononerror throw exception if error encountered
1673 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1675 function make_cache_directory($directory, $exceptiononerror = true) {
1676 global $CFG;
1677 if ($CFG->cachedir !== "$CFG->dataroot/cache") {
1678 check_dir_exists($CFG->cachedir, true, true);
1679 protect_directory($CFG->cachedir);
1680 } else {
1681 protect_directory($CFG->dataroot);
1683 return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1687 * Create a directory under localcachedir and make sure it is writable.
1688 * The files in this directory MUST NOT change, use revisions or content hashes to
1689 * work around this limitation - this means you can only add new files here.
1691 * The content of this directory gets purged automatically on all cluster nodes
1692 * after calling purge_all_caches() before new data is written to this directory.
1694 * Note: this local cache directory does not need to be shared by cluster nodes.
1696 * @param string $directory the relative path of the directory to be created under $CFG->localcachedir
1697 * @param bool $exceptiononerror throw exception if error encountered
1698 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1700 function make_localcache_directory($directory, $exceptiononerror = true) {
1701 global $CFG;
1703 make_writable_directory($CFG->localcachedir, $exceptiononerror);
1705 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1706 protect_directory($CFG->localcachedir);
1707 } else {
1708 protect_directory($CFG->dataroot);
1711 if (!isset($CFG->localcachedirpurged)) {
1712 $CFG->localcachedirpurged = 0;
1714 $timestampfile = "$CFG->localcachedir/.lastpurged";
1716 if (!file_exists($timestampfile)) {
1717 touch($timestampfile);
1718 @chmod($timestampfile, $CFG->filepermissions);
1720 } else if (filemtime($timestampfile) < $CFG->localcachedirpurged) {
1721 // This means our local cached dir was not purged yet.
1722 remove_dir($CFG->localcachedir, true);
1723 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1724 protect_directory($CFG->localcachedir);
1726 touch($timestampfile);
1727 @chmod($timestampfile, $CFG->filepermissions);
1728 clearstatcache();
1731 if ($directory === '') {
1732 return $CFG->localcachedir;
1735 return make_writable_directory("$CFG->localcachedir/$directory", $exceptiononerror);
1739 * This class solves the problem of how to initialise $OUTPUT.
1741 * The problem is caused be two factors
1742 * <ol>
1743 * <li>On the one hand, we cannot be sure when output will start. In particular,
1744 * an error, which needs to be displayed, could be thrown at any time.</li>
1745 * <li>On the other hand, we cannot be sure when we will have all the information
1746 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1747 * (potentially) depends on the current course, course categories, and logged in user.
1748 * It also depends on whether the current page requires HTTPS.</li>
1749 * </ol>
1751 * So, it is hard to find a single natural place during Moodle script execution,
1752 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1753 * adopt the following strategy
1754 * <ol>
1755 * <li>We will initialise $OUTPUT the first time it is used.</li>
1756 * <li>If, after $OUTPUT has been initialised, the script tries to change something
1757 * that $OUTPUT depends on, we throw an exception making it clear that the script
1758 * did something wrong.
1759 * </ol>
1761 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1762 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1763 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1764 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1766 * Note that this class is used before lib/outputlib.php has been loaded, so we
1767 * must be careful referring to classes/functions from there, they may not be
1768 * defined yet, and we must avoid fatal errors.
1770 * @copyright 2009 Tim Hunt
1771 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1772 * @since Moodle 2.0
1774 class bootstrap_renderer {
1776 * Handles re-entrancy. Without this, errors or debugging output that occur
1777 * during the initialisation of $OUTPUT, cause infinite recursion.
1778 * @var boolean
1780 protected $initialising = false;
1783 * Have we started output yet?
1784 * @return boolean true if the header has been printed.
1786 public function has_started() {
1787 return false;
1791 * Constructor - to be used by core code only.
1792 * @param string $method The method to call
1793 * @param array $arguments Arguments to pass to the method being called
1794 * @return string
1796 public function __call($method, $arguments) {
1797 global $OUTPUT, $PAGE;
1799 $recursing = false;
1800 if ($method == 'notification') {
1801 // Catch infinite recursion caused by debugging output during print_header.
1802 $backtrace = debug_backtrace();
1803 array_shift($backtrace);
1804 array_shift($backtrace);
1805 $recursing = is_early_init($backtrace);
1808 $earlymethods = array(
1809 'fatal_error' => 'early_error',
1810 'notification' => 'early_notification',
1813 // If lib/outputlib.php has been loaded, call it.
1814 if (!empty($PAGE) && !$recursing) {
1815 if (array_key_exists($method, $earlymethods)) {
1816 //prevent PAGE->context warnings - exceptions might appear before we set any context
1817 $PAGE->set_context(null);
1819 $PAGE->initialise_theme_and_output();
1820 return call_user_func_array(array($OUTPUT, $method), $arguments);
1823 $this->initialising = true;
1825 // Too soon to initialise $OUTPUT, provide a couple of key methods.
1826 if (array_key_exists($method, $earlymethods)) {
1827 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1830 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1834 * Returns nicely formatted error message in a div box.
1835 * @static
1836 * @param string $message error message
1837 * @param string $moreinfourl (ignored in early errors)
1838 * @param string $link (ignored in early errors)
1839 * @param array $backtrace
1840 * @param string $debuginfo
1841 * @return string
1843 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1844 global $CFG;
1846 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1847 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1848 width: 80%; -moz-border-radius: 20px; padding: 15px">
1849 ' . $message . '
1850 </div>';
1851 // Check whether debug is set.
1852 $debug = (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER);
1853 // Also check we have it set in the config file. This occurs if the method to read the config table from the
1854 // database fails, reading from the config table is the first database interaction we have.
1855 $debug = $debug || (!empty($CFG->config_php_settings['debug']) && $CFG->config_php_settings['debug'] >= DEBUG_DEVELOPER );
1856 if ($debug) {
1857 if (!empty($debuginfo)) {
1858 $debuginfo = s($debuginfo); // removes all nasty JS
1859 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1860 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
1862 if (!empty($backtrace)) {
1863 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1867 return $content;
1871 * This function should only be called by this class, or from exception handlers
1872 * @static
1873 * @param string $message error message
1874 * @param string $moreinfourl (ignored in early errors)
1875 * @param string $link (ignored in early errors)
1876 * @param array $backtrace
1877 * @param string $debuginfo extra information for developers
1878 * @return string
1880 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = null) {
1881 global $CFG;
1883 if (CLI_SCRIPT) {
1884 echo "!!! $message !!!\n";
1885 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1886 if (!empty($debuginfo)) {
1887 echo "\nDebug info: $debuginfo";
1889 if (!empty($backtrace)) {
1890 echo "\nStack trace: " . format_backtrace($backtrace, true);
1893 return;
1895 } else if (AJAX_SCRIPT) {
1896 $e = new stdClass();
1897 $e->error = $message;
1898 $e->stacktrace = NULL;
1899 $e->debuginfo = NULL;
1900 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1901 if (!empty($debuginfo)) {
1902 $e->debuginfo = $debuginfo;
1904 if (!empty($backtrace)) {
1905 $e->stacktrace = format_backtrace($backtrace, true);
1908 $e->errorcode = $errorcode;
1909 @header('Content-Type: application/json; charset=utf-8');
1910 echo json_encode($e);
1911 return;
1914 // In the name of protocol correctness, monitoring and performance
1915 // profiling, set the appropriate error headers for machine consumption.
1916 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
1917 @header($protocol . ' 503 Service Unavailable');
1919 // better disable any caching
1920 @header('Content-Type: text/html; charset=utf-8');
1921 @header('X-UA-Compatible: IE=edge');
1922 @header('Cache-Control: no-store, no-cache, must-revalidate');
1923 @header('Cache-Control: post-check=0, pre-check=0', false);
1924 @header('Pragma: no-cache');
1925 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1926 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1928 if (function_exists('get_string')) {
1929 $strerror = get_string('error');
1930 } else {
1931 $strerror = 'Error';
1934 $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
1936 return self::plain_page($strerror, $content);
1940 * Early notification message
1941 * @static
1942 * @param string $message
1943 * @param string $classes usually notifyproblem or notifysuccess
1944 * @return string
1946 public static function early_notification($message, $classes = 'notifyproblem') {
1947 return '<div class="' . $classes . '">' . $message . '</div>';
1951 * Page should redirect message.
1952 * @static
1953 * @param string $encodedurl redirect url
1954 * @return string
1956 public static function plain_redirect_message($encodedurl) {
1957 $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
1958 $encodedurl .'">'. get_string('continue') .'</a></div>';
1959 return self::plain_page(get_string('redirect'), $message);
1963 * Early redirection page, used before full init of $PAGE global
1964 * @static
1965 * @param string $encodedurl redirect url
1966 * @param string $message redirect message
1967 * @param int $delay time in seconds
1968 * @return string redirect page
1970 public static function early_redirect_message($encodedurl, $message, $delay) {
1971 $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
1972 $content = self::early_error_content($message, null, null, null);
1973 $content .= self::plain_redirect_message($encodedurl);
1975 return self::plain_page(get_string('redirect'), $content, $meta);
1979 * Output basic html page.
1980 * @static
1981 * @param string $title page title
1982 * @param string $content page content
1983 * @param string $meta meta tag
1984 * @return string html page
1986 public static function plain_page($title, $content, $meta = '') {
1987 if (function_exists('get_string') && function_exists('get_html_lang')) {
1988 $htmllang = get_html_lang();
1989 } else {
1990 $htmllang = '';
1993 $footer = '';
1994 if (MDL_PERF_TEST) {
1995 $perfinfo = get_performance_info();
1996 $footer = '<footer>' . $perfinfo['html'] . '</footer>';
1999 return '<!DOCTYPE html>
2000 <html ' . $htmllang . '>
2001 <head>
2002 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
2003 '.$meta.'
2004 <title>' . $title . '</title>
2005 </head><body>' . $content . $footer . '</body></html>';