2 // This file is part of Moodle - http://moodle.org/
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.
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/>.
18 * These functions are required very early in the Moodle
19 * setup process, before any of the main libraries are
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);
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 * Get the Whoops! handler.
57 * @return \Whoops\Run|null
59 function get_whoops(): ?\Whoops\Run
{
62 if (CLI_SCRIPT || AJAX_SCRIPT
) {
66 if (defined('PHPUNIT_TEST') && PHPUNIT_TEST
) {
70 if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING
) {
74 if (empty($CFG->debugdisplay
)) {
78 if (!$CFG->debug_developer_use_pretty_exceptions
) {
82 $composerautoload = "{$CFG->dirroot}/vendor/autoload.php";
83 if (file_exists($composerautoload)) {
84 require_once($composerautoload);
87 if (!class_exists(\Whoops\Run
::class)) {
91 // We have Whoops available, use it.
92 $whoops = new \Whoops\
Run();
94 // Append a custom handler to add some more information to the frames.
95 $whoops->appendHandler(function ($exception, $inspector, $run) {
96 $collection = $inspector->getFrames();
98 // Detect if the Whoops handler was immediately invoked by a call to `debugging()`.
99 // If so, we remove the top frames in the collection to avoid showing the inner
100 // workings of debugging, and the point that we trigger the error that is picked up by Whoops.
101 $isdebugging = count($collection) > 2;
102 $isdebugging = $isdebugging && str_ends_with($collection[1]->getFile(), '/lib/weblib.php');
103 $isdebugging = $isdebugging && $collection[2]->getFunction() === 'debugging';
106 $remove = array_slice($collection->getArray(), 0, 2);
107 $collection->filter(function ($frame) use ($remove): bool {
108 return array_search($frame, $remove) === false;
111 // Moodle exceptions often have a link to the Moodle docs pages for them.
112 // Add that to the first frame in the stack.
113 $info = get_exception_info($exception);
114 if ($info->moreinfourl
) {
115 $collection[0]->addComment("{$info->moreinfourl}", 'More info');
120 // Add the Pretty page handler. It's the bee's knees.
121 $handler = new \Whoops\Handler\
PrettyPageHandler();
122 if (isset($CFG->debug_developer_editor
)) {
123 $handler->setEditor($CFG->debug_developer_editor ?
: null);
125 $whoops->appendHandler($handler);
131 * Default exception handler.
133 * @param Throwable $ex
134 * @return void -does not return. Terminates execution!
136 function default_exception_handler(Throwable
$ex): void
{
137 global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION, $PAGE;
139 // detect active db transactions, rollback and log as error
140 abort_all_db_transactions();
142 if (($ex instanceof required_capability_exception
) && !CLI_SCRIPT
&& !AJAX_SCRIPT
&& !empty($CFG->autologinguests
) && !empty($USER->autologinguest
)) {
143 $SESSION->wantsurl
= qualified_me();
144 redirect(get_login_url());
147 $info = get_exception_info($ex);
149 // If we already tried to send the header remove it, the content length
150 // should be either empty or the length of the error page.
151 @header_remove
('Content-Length');
153 if ($whoops = get_whoops()) {
154 // If whoops is available we will use it. The get_whoops() function checks whether all conditions are met.
155 $whoops->handleException($ex);
158 if (is_early_init($info->backtrace
)) {
159 echo bootstrap_renderer
::early_error($info->message
, $info->moreinfourl
, $info->link
, $info->backtrace
, $info->debuginfo
, $info->errorcode
);
161 if (debugging('', DEBUG_MINIMAL
)) {
162 $logerrmsg = "Default exception handler: ".$info->message
.' Debug: '.$info->debuginfo
."\n".format_backtrace($info->backtrace
, true);
163 error_log($logerrmsg);
168 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
172 // If we are in an AJAX script we don't want to use PREFERRED_RENDERER_TARGET.
173 // Because we know we will want to use ajax format.
174 $renderer = new core_renderer_ajax($PAGE, 'ajax');
178 echo $renderer->fatal_error($info->message
, $info->moreinfourl
, $info->link
, $info->backtrace
, $info->debuginfo
,
180 } catch (Exception
$e) {
182 } catch (Throwable
$e) {
183 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
187 if (isset($out_ex)) {
188 // default exception handler MUST not throw any exceptions!!
189 // 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
190 // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
191 if (CLI_SCRIPT
or AJAX_SCRIPT
) {
192 // just ignore the error and send something back using the safest method
193 echo bootstrap_renderer
::early_error($info->message
, $info->moreinfourl
, $info->link
, $info->backtrace
, $info->debuginfo
, $info->errorcode
);
195 echo bootstrap_renderer
::early_error_content($info->message
, $info->moreinfourl
, $info->link
, $info->backtrace
, $info->debuginfo
);
196 $outinfo = get_exception_info($out_ex);
197 echo bootstrap_renderer
::early_error_content($outinfo->message
, $outinfo->moreinfourl
, $outinfo->link
, $outinfo->backtrace
, $outinfo->debuginfo
);
202 exit(1); // General error code
206 * Default error handler, prevents some white screens.
208 * @param string $errstr
209 * @param string $errfile
210 * @param int $errline
211 * @return bool false means use default error handler
213 function default_error_handler($errno, $errstr, $errfile, $errline) {
214 if ($whoops = get_whoops()) {
215 // If whoops is available we will use it. The get_whoops() function checks whether all conditions are met.
216 $whoops->handleError($errno, $errstr, $errfile, $errline);
218 if ($errno == 4096) {
219 //fatal catchable error
220 throw new coding_exception('PHP catchable fatal error', $errstr);
226 * Unconditionally abort all database transactions, this function
227 * should be called from exception handlers only.
230 function abort_all_db_transactions() {
231 global $CFG, $DB, $SCRIPT;
233 // default exception handler MUST not throw any exceptions!!
235 if ($DB && $DB->is_transaction_started()) {
236 error_log('Database transaction aborted automatically in ' . $CFG->dirroot
. $SCRIPT);
237 // note: transaction blocks should never change current $_SESSION
238 $DB->force_transaction_rollback();
243 * This function encapsulates the tests for whether an exception was thrown in
244 * early init -- either during setup.php or during init of $OUTPUT.
246 * If another exception is thrown then, and if we do not take special measures,
247 * we would just get a very cryptic message "Exception thrown without a stack
248 * frame in Unknown on line 0". That makes debugging very hard, so we do take
249 * special measures in default_exception_handler, with the help of this function.
251 * @param array $backtrace the stack trace to analyse.
252 * @return boolean whether the stack trace is somewhere in output initialisation.
254 function is_early_init($backtrace) {
255 $dangerouscode = array(
256 array('function' => 'header', 'type' => '->'),
257 array('class' => 'bootstrap_renderer'),
258 array('file' => __DIR__
.'/setup.php'),
260 foreach ($backtrace as $stackframe) {
261 foreach ($dangerouscode as $pattern) {
263 foreach ($pattern as $property => $value) {
264 if (!isset($stackframe[$property]) ||
$stackframe[$property] != $value) {
277 * Returns detailed information about specified exception.
279 * @param Throwable $ex any sort of exception or throwable.
280 * @return stdClass standardised info to display. Fields are clear if you look at the end of this function.
282 function get_exception_info($ex): stdClass
{
285 if ($ex instanceof moodle_exception
) {
286 $errorcode = $ex->errorcode
;
287 $module = $ex->module
;
290 $debuginfo = $ex->debuginfo
;
292 $errorcode = 'generalexceptionmessage';
294 $a = $ex->getMessage();
299 // Append the error code to the debug info to make grepping and googling easier
300 $debuginfo .= PHP_EOL
."Error code: $errorcode";
302 $backtrace = $ex->getTrace();
303 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
304 array_unshift($backtrace, $place);
306 // Be careful, no guarantee moodlelib.php is loaded.
307 if (empty($module) ||
$module == 'moodle' ||
$module == 'core') {
310 // Search for the $errorcode's associated string
311 // If not found, append the contents of $a to $debuginfo so helpful information isn't lost
312 if (function_exists('get_string_manager')) {
313 if (get_string_manager()->string_exists($errorcode, $module)) {
314 $message = get_string($errorcode, $module, $a);
315 } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
316 // Search in moodle file if error specified - needed for backwards compatibility
317 $message = get_string($errorcode, 'moodle', $a);
319 $message = $module . '/' . $errorcode;
320 $debuginfo .= PHP_EOL
.'$a contents: '.print_r($a, true);
323 $message = $module . '/' . $errorcode;
324 $debuginfo .= PHP_EOL
.'$a contents: '.print_r($a, true);
327 // Remove some absolute paths from message and debugging info.
330 $cfgnames = array('backuptempdir', 'tempdir', 'cachedir', 'localcachedir', 'themedir', 'dataroot', 'dirroot');
331 foreach ($cfgnames as $cfgname) {
332 if (property_exists($CFG, $cfgname)) {
333 $searches[] = $CFG->$cfgname;
334 $replaces[] = "[$cfgname]";
337 if (!empty($searches)) {
338 $message = str_replace($searches, $replaces, $message);
339 $debuginfo = str_replace($searches, $replaces, $debuginfo);
342 // Be careful, no guarantee weblib.php is loaded.
343 if (function_exists('clean_text')) {
344 $message = clean_text($message);
346 $message = htmlspecialchars($message, ENT_COMPAT
);
349 if (!empty($CFG->errordocroot
)) {
350 $errordoclink = $CFG->errordocroot
. '/en/';
352 // Only if the function is available. May be not for early errors.
353 if (function_exists('current_language')) {
354 $errordoclink = get_docs_url();
356 $errordoclink = 'https://docs.moodle.org/en/';
360 if ($module === 'error') {
361 $modulelink = 'moodle';
363 $modulelink = $module;
365 $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
368 $link = get_local_referer(false) ?
: ($CFG->wwwroot
. '/');
371 // When printing an error the continue button should never link offsite.
372 // We cannot use clean_param() here as it is not guaranteed that it has been loaded yet.
373 if (stripos($link, $CFG->wwwroot
) === 0) {
374 // Internal HTTP, all good.
376 // External link spotted!
377 $link = $CFG->wwwroot
. '/';
380 $info = new stdClass();
381 $info->message
= $message;
382 $info->errorcode
= $errorcode;
383 $info->backtrace
= $backtrace;
385 $info->moreinfourl
= $moreinfourl;
387 $info->debuginfo
= $debuginfo;
393 * @deprecated since Moodle 3.8 MDL-61038 - please do not use this function any more.
394 * @see \core\uuid::generate()
396 function generate_uuid() {
397 throw new coding_exception('generate_uuid() cannot be used anymore. Please use ' .
398 '\core\uuid::generate() instead.');
402 * Returns the Moodle Docs URL in the users language for a given 'More help' link.
404 * There are three cases:
406 * 1. In the normal case, $path will be a short relative path 'component/thing',
407 * like 'mod/folder/view' 'group/import'. This gets turned into an link to
408 * MoodleDocs in the user's language, and for the appropriate Moodle version.
409 * E.g. 'group/import' may become 'http://docs.moodle.org/2x/en/group/import'.
410 * The 'http://docs.moodle.org' bit comes from $CFG->docroot.
412 * This is the only option that should be used in standard Moodle code. The other
413 * two options have been implemented because they are useful for third-party plugins.
415 * 2. $path may be an absolute URL, starting http:// or https://. In this case,
416 * the link is used as is.
418 * 3. $path may start %%WWWROOT%%, in which case that is replaced by
419 * $CFG->wwwroot to make the link.
421 * @param string $path the place to link to. See above for details.
422 * @return string The MoodleDocs URL in the user's language. for example @link http://docs.moodle.org/2x/en/$path}
424 function get_docs_url($path = null) {
426 if ($path === null) {
431 // Absolute URLs are used unmodified.
432 if (substr($path, 0, 7) === 'http://' ||
substr($path, 0, 8) === 'https://') {
436 // Paths starting %%WWWROOT%% have that replaced by $CFG->wwwroot.
437 if (substr($path, 0, 11) === '%%WWWROOT%%') {
438 return $CFG->wwwroot
. substr($path, 11);
441 // Otherwise we do the normal case, and construct a MoodleDocs URL relative to $CFG->docroot.
443 // Check that $CFG->branch has been set up, during installation it won't be.
444 if (empty($CFG->branch
)) {
445 // It's not there yet so look at version.php.
446 include($CFG->dirroot
.'/version.php');
448 // We can use $CFG->branch and avoid having to include version.php.
449 $branch = $CFG->branch
;
451 // ensure branch is valid.
453 // We should never get here but in case we do lets set $branch to .
454 // the smart one's will know that this is the current directory
455 // and the smarter ones will know that there is some smart matching
456 // that will ensure people end up at the latest version of the docs.
459 if (empty($CFG->doclang
)) {
460 $lang = current_language();
462 $lang = $CFG->doclang
;
464 $end = '/' . $branch . '/' . $lang . '/' . $path;
465 if (empty($CFG->docroot
)) {
466 return 'http://docs.moodle.org'. $end;
468 return $CFG->docroot
. $end ;
473 * Formats a backtrace ready for output.
475 * This function does not include function arguments because they could contain sensitive information
476 * not suitable to be exposed in a response.
478 * @param array $callers backtrace array, as returned by debug_backtrace().
479 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
480 * @return string formatted backtrace, ready for output.
482 function format_backtrace($callers, $plaintext = false) {
483 // do not use $CFG->dirroot because it might not be available in destructors
484 $dirroot = dirname(__DIR__
);
486 if (empty($callers)) {
490 $from = $plaintext ?
'' : '<ul style="text-align: left" data-rel="backtrace">';
491 foreach ($callers as $caller) {
492 if (!isset($caller['line'])) {
493 $caller['line'] = '?'; // probably call_user_func()
495 if (!isset($caller['file'])) {
496 $caller['file'] = 'unknownfile'; // probably call_user_func()
498 $line = $plaintext ?
'* ' : '<li>';
499 $line .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
500 if (isset($caller['function'])) {
501 $line .= ': call to ';
502 if (isset($caller['class'])) {
503 $line .= $caller['class'] . $caller['type'];
505 $line .= $caller['function'] . '()';
506 } else if (isset($caller['exception'])) {
507 $line .= ': '.$caller['exception'].' thrown';
510 // Remove any non printable chars.
511 $line = preg_replace('/[[:^print:]]/', '', $line);
513 $line .= $plaintext ?
"\n" : '</li>';
516 $from .= $plaintext ?
'' : '</ul>';
522 * This function makes the return value of ini_get consistent if you are
523 * setting server directives through the .htaccess file in apache.
525 * Current behavior for value set from php.ini On = 1, Off = [blank]
526 * Current behavior for value set from .htaccess On = On, Off = Off
527 * Contributed by jdell @ unr.edu
529 * @param string $ini_get_arg The argument to get
530 * @return bool True for on false for not
532 function ini_get_bool($ini_get_arg) {
533 $temp = ini_get($ini_get_arg);
535 if ($temp == '1' or strtolower($temp) == 'on') {
542 * This function verifies the sanity of PHP configuration
543 * and stops execution if anything critical found.
545 function setup_validate_php_configuration() {
546 // this must be very fast - no slow checks here!!!
548 if (ini_get_bool('session.auto_start')) {
549 throw new \
moodle_exception('sessionautostartwarning', 'admin');
554 * Initialise global $CFG variable.
555 * @private to be used only from lib/setup.php
557 function initialise_cfg() {
561 // This should not happen.
566 $localcfg = get_config('core');
567 } catch (dml_exception
$e) {
568 // Most probably empty db, going to install soon.
572 foreach ($localcfg as $name => $value) {
573 // Note that get_config() keeps forced settings
574 // and normalises values to string if possible.
575 $CFG->{$name} = $value;
580 * Cache any immutable config locally to avoid constant DB lookups.
582 * Only to be used only from lib/setup.php
584 function initialise_local_config_cache() {
587 $bootstraplocalfile = $CFG->localcachedir
. '/bootstrap.php';
588 $bootstrapsharedfile = $CFG->cachedir
. '/bootstrap.php';
590 if (!is_readable($bootstraplocalfile) && is_readable($bootstrapsharedfile)) {
591 // If we don't have a local cache but do have a shared cache then clone it,
592 // for example when scaling up new front ends.
593 make_localcache_directory('', true);
594 copy($bootstrapsharedfile, $bootstraplocalfile);
597 if (!empty($CFG->siteidentifier
) && !file_exists($bootstrapsharedfile) && defined('SYSCONTEXTID')) {
599 // ********** This file is generated DO NOT EDIT **********
600 \$CFG->siteidentifier = " . var_export($CFG->siteidentifier
, true) . ";
601 \$CFG->bootstraphash = " . var_export(hash_local_config_cache(), true) . ";
602 // Only if the file is not stale and has not been defined.
603 if (\$CFG->bootstraphash === hash_local_config_cache() && !defined('SYSCONTEXTID')) {
604 define('SYSCONTEXTID', ".SYSCONTEXTID
.");
608 // Create the central bootstrap first.
609 $temp = $bootstrapsharedfile . '.tmp' . uniqid();
610 file_put_contents($temp, $contents);
611 @chmod
($temp, $CFG->filepermissions
);
612 rename($temp, $bootstrapsharedfile);
614 // Then prewarm the local cache as well.
615 make_localcache_directory('', true);
616 copy($bootstrapsharedfile, $bootstraplocalfile);
621 * Calculate a proper hash to be able to invalidate stale cached configs.
623 * Only to be used to verify bootstrap.php status.
625 * @return string md5 hash of all the sensible bits deciding if cached config is stale or no.
627 function hash_local_config_cache() {
630 // This is pretty much {@see moodle_database::get_settings_hash()} that is used
631 // as identifier for the database meta information MUC cache. Should be enough to
632 // react against any of the normal changes (new prefix, change of DB type) while
633 // *incorrectly* keeping the old dataroot directory unmodified with stale data.
634 // This may need more stuff to be considered if it's discovered that there are
635 // more variables making the file stale.
636 return md5($CFG->dbtype
. $CFG->dbhost
. $CFG->dbuser
. $CFG->dbname
. $CFG->prefix
);
640 * Initialises $FULLME and friends. Private function. Should only be called from
643 function initialise_fullme() {
644 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
646 // Detect common config error.
647 if (substr($CFG->wwwroot
, -1) == '/') {
648 throw new \
moodle_exception('wwwrootslash', 'error');
652 initialise_fullme_cli();
655 if (!empty($CFG->overridetossl
)) {
656 if (strpos($CFG->wwwroot
, 'http://') === 0) {
657 $CFG->wwwroot
= str_replace('http:', 'https:', $CFG->wwwroot
);
659 unset_config('overridetossl');
663 $rurl = setup_get_remote_url();
664 $wwwroot = parse_url($CFG->wwwroot
.'/');
666 if (empty($rurl['host'])) {
667 // missing host in request header, probably not a real browser, let's ignore them
669 } else if (!empty($CFG->reverseproxy
)) {
670 // $CFG->reverseproxy specifies if reverse proxy server used
671 // Used in load balancing scenarios.
672 // Do not abuse this to try to solve lan/wan access problems!!!!!
675 if (($rurl['host'] !== $wwwroot['host']) or
676 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port']) or
677 (strpos($rurl['path'], $wwwroot['path']) !== 0)) {
679 // Explain the problem and redirect them to the right URL
680 if (!defined('NO_MOODLE_COOKIES')) {
681 define('NO_MOODLE_COOKIES', true);
683 // The login/token.php script should call the correct url/port.
684 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS
) {
685 $wwwrootport = empty($wwwroot['port'])?
'':$wwwroot['port'];
686 $calledurl = $rurl['host'];
687 if (!empty($rurl['port'])) {
688 $calledurl .= ':'. $rurl['port'];
690 $correcturl = $wwwroot['host'];
691 if (!empty($wwwrootport)) {
692 $correcturl .= ':'. $wwwrootport;
694 throw new moodle_exception('requirecorrectaccess', 'error', '', null,
695 'You called ' . $calledurl .', you should have called ' . $correcturl);
697 $rfullpath = $rurl['fullpath'];
698 // Check that URL is under $CFG->wwwroot.
699 if (strpos($rfullpath, $wwwroot['path']) === 0) {
700 $rfullpath = substr($rurl['fullpath'], strlen($wwwroot['path']) - 1);
701 $rfullpath = (new moodle_url($rfullpath))->out(false);
703 redirect($rfullpath, get_string('wwwrootmismatch', 'error', $CFG->wwwroot
), 3);
707 // Check that URL is under $CFG->wwwroot.
708 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
709 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
711 // Probably some weird external script
712 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
716 // $CFG->sslproxy specifies if external SSL appliance is used
717 // (That is, the Moodle server uses http, with an external box translating everything to https).
718 if (empty($CFG->sslproxy
)) {
719 if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
720 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS
) {
721 throw new \
moodle_exception('sslonlyaccess', 'error');
723 redirect($CFG->wwwroot
, get_string('wwwrootmismatch', 'error', $CFG->wwwroot
), 3);
727 if ($wwwroot['scheme'] !== 'https') {
728 throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
730 $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
731 $_SERVER['HTTPS'] = 'on'; // Override $_SERVER to help external libraries with their HTTPS detection.
732 $_SERVER['SERVER_PORT'] = 443; // Assume default ssl port for the proxy.
735 // Using Moodle in "reverse proxy" mode, it's expected that the HTTP Host Moodle receives is different
736 // from the wwwroot configured host. Those URLs being identical could be the consequence of various
737 // issues, including:
738 // - Intentionally trying to set up moodle with 2 distinct addresses for intranet and Internet: this
739 // configuration is unsupported and will lead to bigger problems down the road (the proper solution
740 // for this is adjusting the network routes, and avoid relying on the application for network concerns).
741 // - Misconfiguration of the reverse proxy that would be forwarding the Host header: while it is
742 // standard in many cases that the reverse proxy would do that, in our case, the reverse proxy
743 // must leave the Host header pointing to the internal name of the server.
744 // Port forwarding is allowed, though.
745 if (!empty($CFG->reverseproxy
) && $rurl['host'] === $wwwroot['host'] && (empty($wwwroot['port']) ||
$rurl['port'] === $wwwroot['port'])) {
746 throw new \
moodle_exception('reverseproxyabused', 'error');
749 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
750 if (!empty($wwwroot['port'])) {
751 $hostandport .= ':'.$wwwroot['port'];
754 $FULLSCRIPT = $hostandport . $rurl['path'];
755 $FULLME = $hostandport . $rurl['fullpath'];
756 $ME = $rurl['fullpath'];
760 * Initialises $FULLME and friends for command line scripts.
761 * This is a private method for use by initialise_fullme.
763 function initialise_fullme_cli() {
764 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
766 // Urls do not make much sense in CLI scripts
767 $backtrace = debug_backtrace();
768 $topfile = array_pop($backtrace);
769 $topfile = realpath($topfile['file']);
770 $dirroot = realpath($CFG->dirroot
);
772 if (strpos($topfile, $dirroot) !== 0) {
773 // Probably some weird external script
774 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
776 $relativefile = substr($topfile, strlen($dirroot));
777 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
778 $SCRIPT = $FULLSCRIPT = $relativefile;
779 $FULLME = $ME = null;
784 * Get the URL that PHP/the web server thinks it is serving. Private function
785 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
786 * @return array in the same format that parse_url returns, with the addition of
787 * a 'fullpath' element, which includes any slasharguments path.
789 function setup_get_remote_url() {
791 if (isset($_SERVER['HTTP_HOST'])) {
792 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
794 $rurl['host'] = null;
796 $rurl['port'] = (int)$_SERVER['SERVER_PORT'];
797 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
798 $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ?
'http' : 'https';
800 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
802 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
804 // Fixing a known issue with:
805 // - Apache versions lesser than 2.4.11
806 // - PHP deployed in Apache as PHP-FPM via mod_proxy_fcgi
807 // - PHP versions lesser than 5.6.3 and 5.5.18.
808 if (isset($_SERVER['PATH_INFO']) && (php_sapi_name() === 'fpm-fcgi') && isset($_SERVER['SCRIPT_NAME'])) {
809 $pathinfodec = rawurldecode($_SERVER['PATH_INFO']);
810 $lenneedle = strlen($pathinfodec);
811 // Checks whether SCRIPT_NAME ends with PATH_INFO, URL-decoded.
812 if (substr($_SERVER['SCRIPT_NAME'], -$lenneedle) === $pathinfodec) {
813 // This is the "Apache 2.4.10- running PHP-FPM via mod_proxy_fcgi" fingerprint,
814 // 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)
815 // => SCRIPT_NAME contains 'slash arguments' data too, which is wrongly exposed via PATH_INFO as URL-encoded.
816 // Fix both $_SERVER['PATH_INFO'] and $_SERVER['SCRIPT_NAME'].
817 $lenhaystack = strlen($_SERVER['SCRIPT_NAME']);
818 $pos = $lenhaystack - $lenneedle;
819 // Here $pos is greater than 0 but let's double check it.
821 $_SERVER['PATH_INFO'] = $pathinfodec;
822 $_SERVER['SCRIPT_NAME'] = substr($_SERVER['SCRIPT_NAME'], 0, $pos);
827 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
828 //IIS - needs a lot of tweaking to make it work
829 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
831 // NOTE: we should ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS.
832 // Since 2.0, we rely on IIS rewrite extensions like Helicon ISAPI_rewrite
833 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
835 // we rely on a proper IIS 6.0+ configuration: the 'FastCGIUtf8ServerVariables' registry key.
836 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
837 // Check that PATH_INFO works == must not contain the script name.
838 if (strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === false) {
839 $rurl['fullpath'] .= clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH
);
843 if (isset($_SERVER['QUERY_STRING']) and $_SERVER['QUERY_STRING'] !== '') {
844 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
846 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
848 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
849 if (!isset($_SERVER['SCRIPT_NAME'])) {
850 die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
852 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
854 // Any other servers we can assume will pass the request_uri normally.
855 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
858 // sanitize the url a bit more, the encoding style may be different in vars above
859 $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
860 $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);
866 * Try to work around the 'max_input_vars' restriction if necessary.
868 function workaround_max_input_vars() {
869 // Make sure this gets executed only once from lib/setup.php!
870 static $executed = false;
872 debugging('workaround_max_input_vars() must be called only once!');
877 if (!isset($_SERVER["CONTENT_TYPE"]) or strpos($_SERVER["CONTENT_TYPE"], 'multipart/form-data') !== false) {
878 // Not a post or 'multipart/form-data' which is not compatible with "php://input" reading.
882 if (!isloggedin() or isguestuser()) {
883 // Only real users post huge forms.
887 $max = (int)ini_get('max_input_vars');
890 // Most probably PHP < 5.3.9 that does not implement this limit.
894 if ($max >= 200000) {
895 // This value should be ok for all our forms, by setting it in php.ini
896 // admins may prevent any unexpected regressions caused by this hack.
898 // Note there is no need to worry about DDoS caused by making this limit very high
899 // because there are very many easier ways to DDoS any Moodle server.
903 // Worst case is advanced checkboxes which use up to two max_input_vars
904 // slots for each entry in $_POST, because of sending two fields with the
905 // same name. So count everything twice just in case.
906 if (count($_POST, COUNT_RECURSIVE
) * 2 < $max) {
910 // Large POST request with enctype supported by php://input.
911 // Parse php://input in chunks to bypass max_input_vars limit, which also applies to parse_str().
912 $str = file_get_contents("php://input");
913 if ($str === false or $str === '') {
919 $fun = function($p) use ($delim) {
920 return implode($delim, $p);
922 $chunks = array_map($fun, array_chunk(explode($delim, $str), $max));
924 // Clear everything from existing $_POST array, otherwise it might be included
925 // twice (this affects array params primarily).
926 foreach ($_POST as $key => $value) {
928 // Also clear from request array - but only the things that are in $_POST,
929 // that way it will leave the things from a get request if any.
930 unset($_REQUEST[$key]);
933 foreach ($chunks as $chunk) {
935 parse_str($chunk, $values);
937 merge_query_params($_POST, $values);
938 merge_query_params($_REQUEST, $values);
943 * Merge parsed POST chunks.
945 * NOTE: this is not perfect, but it should work in most cases hopefully.
947 * @param array $target
948 * @param array $values
950 function merge_query_params(array &$target, array $values) {
951 if (isset($values[0]) and isset($target[0])) {
952 // This looks like a split [] array, lets verify the keys are continuous starting with 0.
953 $keys1 = array_keys($values);
954 $keys2 = array_keys($target);
955 if ($keys1 === array_keys($keys1) and $keys2 === array_keys($keys2)) {
956 foreach ($values as $v) {
962 foreach ($values as $k => $v) {
963 if (!isset($target[$k])) {
967 if (is_array($target[$k]) and is_array($v)) {
968 merge_query_params($target[$k], $v);
971 // We should not get here unless there are duplicates in params.
977 * Initializes our performance info early.
979 * Pairs up with get_performance_info() which is actually
980 * in moodlelib.php. This function is here so that we can
981 * call it before all the libs are pulled in.
985 function init_performance_info() {
987 global $PERF, $CFG, $USER;
989 $PERF = new stdClass();
990 if (function_exists('microtime')) {
991 $PERF->starttime
= microtime();
993 if (function_exists('memory_get_usage')) {
994 $PERF->startmemory
= memory_get_usage();
996 if (function_exists('posix_times')) {
997 $PERF->startposixtimes
= posix_times();
1002 * Indicates whether we are in the middle of the initial Moodle install.
1004 * Very occasionally it is necessary avoid running certain bits of code before the
1005 * Moodle installation has completed. The installed flag is set in admin/index.php
1006 * after Moodle core and all the plugins have been installed, but just before
1007 * the person doing the initial install is asked to choose the admin password.
1009 * @return boolean true if the initial install is not complete.
1011 function during_initial_install() {
1013 return empty($CFG->rolesactive
);
1017 * Function to raise the memory limit to a new value.
1018 * Will respect the memory limit if it is higher, thus allowing
1019 * settings in php.ini, apache conf or command line switches
1022 * The memory limit should be expressed with a constant
1023 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
1024 * It is possible to use strings or integers too (eg:'128M').
1026 * @param mixed $newlimit the new memory limit
1027 * @return bool success
1029 function raise_memory_limit($newlimit) {
1032 if ($newlimit == MEMORY_UNLIMITED
) {
1033 ini_set('memory_limit', -1);
1036 } else if ($newlimit == MEMORY_STANDARD
) {
1037 if (PHP_INT_SIZE
> 4) {
1038 $newlimit = get_real_size('128M'); // 64bit needs more memory
1040 $newlimit = get_real_size('96M');
1043 } else if ($newlimit == MEMORY_EXTRA
) {
1044 if (PHP_INT_SIZE
> 4) {
1045 $newlimit = get_real_size('384M'); // 64bit needs more memory
1047 $newlimit = get_real_size('256M');
1049 if (!empty($CFG->extramemorylimit
)) {
1050 $extra = get_real_size($CFG->extramemorylimit
);
1051 if ($extra > $newlimit) {
1056 } else if ($newlimit == MEMORY_HUGE
) {
1057 // MEMORY_HUGE uses 2G or MEMORY_EXTRA, whichever is bigger.
1058 $newlimit = get_real_size('2G');
1059 if (!empty($CFG->extramemorylimit
)) {
1060 $extra = get_real_size($CFG->extramemorylimit
);
1061 if ($extra > $newlimit) {
1067 $newlimit = get_real_size($newlimit);
1070 if ($newlimit <= 0) {
1071 debugging('Invalid memory limit specified.');
1075 $cur = ini_get('memory_limit');
1077 // if php is compiled without --enable-memory-limits
1078 // apparently memory_limit is set to ''
1082 return true; // unlimited mem!
1084 $cur = get_real_size($cur);
1087 if ($newlimit > $cur) {
1088 ini_set('memory_limit', $newlimit);
1095 * Function to reduce the memory limit to a new value.
1096 * Will respect the memory limit if it is lower, thus allowing
1097 * settings in php.ini, apache conf or command line switches
1100 * The memory limit should be expressed with a string (eg:'64M')
1102 * @param string $newlimit the new memory limit
1105 function reduce_memory_limit($newlimit) {
1106 if (empty($newlimit)) {
1109 $cur = ini_get('memory_limit');
1111 // if php is compiled without --enable-memory-limits
1112 // apparently memory_limit is set to ''
1116 return true; // unlimited mem!
1118 $cur = get_real_size($cur);
1121 $new = get_real_size($newlimit);
1122 // -1 is smaller, but it means unlimited
1123 if ($new < $cur && $new != -1) {
1124 ini_set('memory_limit', $newlimit);
1131 * Converts numbers like 10M into bytes.
1133 * @param string $size The size to be converted
1136 function get_real_size($size = 0) {
1141 static $binaryprefixes = array(
1154 if (preg_match('/^([0-9]+)([KMGTP])/i', $size, $matches)) {
1155 return $matches[1] * $binaryprefixes[$matches[2]];
1162 * Check whether a major upgrade is needed.
1164 * That is defined as an upgrade that changes something really fundamental
1165 * in the database, so nothing can possibly work until the database has
1166 * been updated, and that is defined by the hard-coded version number in
1171 function is_major_upgrade_required() {
1173 $lastmajordbchanges = 2024010400.00; // This should be the version where the breaking changes happen.
1175 $required = empty($CFG->version
);
1176 $required = $required ||
(float)$CFG->version
< $lastmajordbchanges;
1177 $required = $required ||
during_initial_install();
1178 $required = $required ||
!empty($CFG->adminsetuppending
);
1184 * Redirect to the Notifications page if a major upgrade is required, and
1185 * terminate the current user session.
1187 function redirect_if_major_upgrade_required() {
1189 if (is_major_upgrade_required()) {
1191 @\core\session\manager
::terminate_current();
1192 } catch (Exception
$e) {
1193 // Ignore any errors, redirect to upgrade anyway.
1195 $url = $CFG->wwwroot
. '/' . $CFG->admin
. '/index.php';
1196 @header
($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1197 @header
('Location: ' . $url);
1198 echo bootstrap_renderer
::plain_redirect_message(htmlspecialchars($url, ENT_COMPAT
));
1204 * Makes sure that upgrade process is not running
1206 * To be inserted in the core functions that can not be called by pluigns during upgrade.
1207 * Core upgrade should not use any API functions at all.
1208 * See {@link https://moodledev.io/docs/guides/upgrade#upgrade-code-restrictions}
1210 * @throws moodle_exception if executed from inside of upgrade script and $warningonly is false
1211 * @param bool $warningonly if true displays a warning instead of throwing an exception
1212 * @return bool true if executed from outside of upgrade process, false if from inside upgrade process and function is used for warning only
1214 function upgrade_ensure_not_running($warningonly = false) {
1216 if (!empty($CFG->upgraderunning
)) {
1217 if (!$warningonly) {
1218 throw new moodle_exception('cannotexecduringupgrade');
1220 debugging(get_string('cannotexecduringupgrade', 'error'), DEBUG_DEVELOPER
);
1228 * Function to check if a directory exists and by default create it if not exists.
1230 * Previously this was accepting paths only from dataroot, but we now allow
1231 * files outside of dataroot if you supply custom paths for some settings in config.php.
1232 * This function does not verify that the directory is writable.
1234 * NOTE: this function uses current file stat cache,
1235 * please use clearstatcache() before this if you expect that the
1236 * directories may have been removed recently from a different request.
1238 * @param string $dir absolute directory path
1239 * @param boolean $create directory if does not exist
1240 * @param boolean $recursive create directory recursively
1241 * @return boolean true if directory exists or created, false otherwise
1243 function check_dir_exists($dir, $create = true, $recursive = true) {
1246 umask($CFG->umaskpermissions
);
1256 return mkdir($dir, $CFG->directorypermissions
, $recursive);
1260 * Create a new unique directory within the specified directory.
1262 * @param string $basedir The directory to create your new unique directory within.
1263 * @param bool $exceptiononerror throw exception if error encountered
1264 * @return string The created directory
1265 * @throws invalid_dataroot_permissions
1267 function make_unique_writable_directory($basedir, $exceptiononerror = true) {
1268 if (!is_dir($basedir) ||
!is_writable($basedir)) {
1269 // The basedir is not writable. We will not be able to create the child directory.
1270 if ($exceptiononerror) {
1271 throw new invalid_dataroot_permissions($basedir . ' is not writable. Unable to create a unique directory within it.');
1278 // Let's use uniqid() because it's "unique enough" (microtime based). The loop does handle repetitions.
1279 // Windows and old PHP don't like very long paths, so try to keep this shorter. See MDL-69975.
1280 $uniquedir = $basedir . DIRECTORY_SEPARATOR
. uniqid();
1282 // Ensure that basedir is still writable - if we do not check, we could get stuck in a loop here.
1283 is_writable($basedir) &&
1285 // Make the new unique directory. If the directory already exists, it will return false.
1286 !make_writable_directory($uniquedir, $exceptiononerror) &&
1288 // Ensure that the directory now exists
1289 file_exists($uniquedir) && is_dir($uniquedir)
1292 // Check that the directory was correctly created.
1293 if (!file_exists($uniquedir) ||
!is_dir($uniquedir) ||
!is_writable($uniquedir)) {
1294 if ($exceptiononerror) {
1295 throw new invalid_dataroot_permissions('Unique directory creation failed.');
1305 * Create a directory and make sure it is writable.
1308 * @param string $dir the full path of the directory to be created
1309 * @param bool $exceptiononerror throw exception if error encountered
1310 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1312 function make_writable_directory($dir, $exceptiononerror = true) {
1315 if (file_exists($dir) and !is_dir($dir)) {
1316 if ($exceptiononerror) {
1317 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1323 umask($CFG->umaskpermissions
);
1325 if (!file_exists($dir)) {
1326 if (!@mkdir
($dir, $CFG->directorypermissions
, true)) {
1328 // There might be a race condition when creating directory.
1329 if (!is_dir($dir)) {
1330 if ($exceptiononerror) {
1331 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1333 debugging('Can not create directory: '.$dir, DEBUG_DEVELOPER
);
1340 if (!is_writable($dir)) {
1341 if ($exceptiononerror) {
1342 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1352 * Protect a directory from web access.
1353 * Could be extended in the future to support other mechanisms (e.g. other webservers).
1356 * @param string $dir the full path of the directory to be protected
1358 function protect_directory($dir) {
1360 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1361 if (!file_exists("$dir/.htaccess")) {
1362 if ($handle = fopen("$dir/.htaccess", 'w')) { // For safety
1363 @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");
1365 @chmod
("$dir/.htaccess", $CFG->filepermissions
);
1371 * Create a directory under dataroot and make sure it is writable.
1372 * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
1374 * @param string $directory the full path of the directory to be created under $CFG->dataroot
1375 * @param bool $exceptiononerror throw exception if error encountered
1376 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1378 function make_upload_directory($directory, $exceptiononerror = true) {
1381 if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1382 debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1384 } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
1385 debugging('Use make_cache_directory() for creation of cache directory and $CFG->cachedir to get the location.');
1387 } else if (strpos($directory, 'localcache/') === 0 or $directory === 'localcache') {
1388 debugging('Use make_localcache_directory() for creation of local cache directory and $CFG->localcachedir to get the location.');
1391 protect_directory($CFG->dataroot
);
1392 return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1396 * Get a per-request storage directory in the tempdir.
1398 * The directory is automatically cleaned up during the shutdown handler.
1400 * @param bool $exceptiononerror throw exception if error encountered
1401 * @param bool $forcecreate Force creation of a new parent directory
1402 * @return string Returns full path to directory if successful, false if not; may throw exception
1404 function get_request_storage_directory($exceptiononerror = true, bool $forcecreate = false) {
1407 static $requestdir = null;
1409 $writabledirectoryexists = (null !== $requestdir);
1410 $writabledirectoryexists = $writabledirectoryexists && file_exists($requestdir);
1411 $writabledirectoryexists = $writabledirectoryexists && is_dir($requestdir);
1412 $writabledirectoryexists = $writabledirectoryexists && is_writable($requestdir);
1413 $createnewdirectory = $forcecreate ||
!$writabledirectoryexists;
1415 if ($createnewdirectory) {
1417 // Let's add the first chars of siteidentifier only. This is to help separate
1418 // paths on systems which host multiple moodles. We don't use the full id
1419 // as Windows and old PHP don't like very long paths. See MDL-69975.
1420 $basedir = $CFG->localrequestdir
. '/' . substr($CFG->siteidentifier
, 0, 4);
1422 make_writable_directory($basedir);
1423 protect_directory($basedir);
1425 if ($dir = make_unique_writable_directory($basedir, $exceptiononerror)) {
1426 // Register a shutdown handler to remove the directory.
1427 \core_shutdown_manager
::register_function('remove_dir', [$dir]);
1437 * Create a per-request directory and make sure it is writable.
1438 * This can only be used during the current request and will be tidied away
1439 * automatically afterwards.
1441 * A new, unique directory is always created within a shared base request directory.
1443 * In some exceptional cases an alternative base directory may be required. This can be accomplished using the
1444 * $forcecreate parameter. Typically this will only be requried where the file may be required during a shutdown handler
1445 * which may or may not be registered after a previous request directory has been created.
1447 * @param bool $exceptiononerror throw exception if error encountered
1448 * @param bool $forcecreate Force creation of a new parent directory
1449 * @return string The full path to directory if successful, false if not; may throw exception
1451 function make_request_directory(bool $exceptiononerror = true, bool $forcecreate = false) {
1452 $basedir = get_request_storage_directory($exceptiononerror, $forcecreate);
1453 return make_unique_writable_directory($basedir, $exceptiononerror);
1457 * Get the full path of a directory under $CFG->backuptempdir.
1459 * @param string $directory the relative path of the directory under $CFG->backuptempdir
1460 * @return string|false Returns full path to directory given a valid string; otherwise, false.
1462 function get_backup_temp_directory($directory) {
1464 if (($directory === null) ||
($directory === false)) {
1467 return "$CFG->backuptempdir/$directory";
1471 * Create a directory under $CFG->backuptempdir and make sure it is writable.
1473 * Do not use for storing generic temp files - see make_temp_directory() instead for this purpose.
1475 * Backup temporary files must be on a shared storage.
1477 * @param string $directory the relative path of the directory to be created under $CFG->backuptempdir
1478 * @param bool $exceptiononerror throw exception if error encountered
1479 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1481 function make_backup_temp_directory($directory, $exceptiononerror = true) {
1483 if ($CFG->backuptempdir
!== "$CFG->tempdir/backup") {
1484 check_dir_exists($CFG->backuptempdir
, true, true);
1485 protect_directory($CFG->backuptempdir
);
1487 protect_directory($CFG->tempdir
);
1489 return make_writable_directory("$CFG->backuptempdir/$directory", $exceptiononerror);
1493 * Create a directory under tempdir and make sure it is writable.
1495 * Where possible, please use make_request_directory() and limit the scope
1496 * of your data to the current HTTP request.
1498 * Do not use for storing cache files - see make_cache_directory(), and
1499 * make_localcache_directory() instead for this purpose.
1501 * Temporary files must be on a shared storage, and heavy usage is
1502 * discouraged due to the performance impact upon clustered environments.
1504 * @param string $directory the full path of the directory to be created under $CFG->tempdir
1505 * @param bool $exceptiononerror throw exception if error encountered
1506 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1508 function make_temp_directory($directory, $exceptiononerror = true) {
1510 if ($CFG->tempdir
!== "$CFG->dataroot/temp") {
1511 check_dir_exists($CFG->tempdir
, true, true);
1512 protect_directory($CFG->tempdir
);
1514 protect_directory($CFG->dataroot
);
1516 return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1520 * Create a directory under cachedir and make sure it is writable.
1522 * Note: this cache directory is shared by all cluster nodes.
1524 * @param string $directory the full path of the directory to be created under $CFG->cachedir
1525 * @param bool $exceptiononerror throw exception if error encountered
1526 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1528 function make_cache_directory($directory, $exceptiononerror = true) {
1530 if ($CFG->cachedir
!== "$CFG->dataroot/cache") {
1531 check_dir_exists($CFG->cachedir
, true, true);
1532 protect_directory($CFG->cachedir
);
1534 protect_directory($CFG->dataroot
);
1536 return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1540 * Create a directory under localcachedir and make sure it is writable.
1541 * The files in this directory MUST NOT change, use revisions or content hashes to
1542 * work around this limitation - this means you can only add new files here.
1544 * The content of this directory gets purged automatically on all cluster nodes
1545 * after calling purge_all_caches() before new data is written to this directory.
1547 * Note: this local cache directory does not need to be shared by cluster nodes.
1549 * @param string $directory the relative path of the directory to be created under $CFG->localcachedir
1550 * @param bool $exceptiononerror throw exception if error encountered
1551 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1553 function make_localcache_directory($directory, $exceptiononerror = true) {
1556 make_writable_directory($CFG->localcachedir
, $exceptiononerror);
1558 if ($CFG->localcachedir
!== "$CFG->dataroot/localcache") {
1559 protect_directory($CFG->localcachedir
);
1561 protect_directory($CFG->dataroot
);
1564 if (!isset($CFG->localcachedirpurged
)) {
1565 $CFG->localcachedirpurged
= 0;
1567 $timestampfile = "$CFG->localcachedir/.lastpurged";
1569 if (!file_exists($timestampfile)) {
1570 touch($timestampfile);
1571 @chmod
($timestampfile, $CFG->filepermissions
);
1573 } else if (filemtime($timestampfile) < $CFG->localcachedirpurged
) {
1574 // This means our local cached dir was not purged yet.
1575 remove_dir($CFG->localcachedir
, true);
1576 if ($CFG->localcachedir
!== "$CFG->dataroot/localcache") {
1577 protect_directory($CFG->localcachedir
);
1579 touch($timestampfile);
1580 @chmod
($timestampfile, $CFG->filepermissions
);
1583 // Then prewarm the local boostrap.php file as well.
1584 initialise_local_config_cache();
1587 if ($directory === '') {
1588 return $CFG->localcachedir
;
1591 return make_writable_directory("$CFG->localcachedir/$directory", $exceptiononerror);
1595 * Webserver access user logging
1597 function set_access_log_user() {
1599 if ($USER && isset($USER->username
)) {
1602 if (!empty($CFG->apacheloguser
) && function_exists('apache_note')) {
1603 $logmethod = 'apache';
1604 $logvalue = $CFG->apacheloguser
;
1606 if (!empty($CFG->headerloguser
)) {
1607 $logmethod = 'header';
1608 $logvalue = $CFG->headerloguser
;
1610 if (!empty($logmethod)) {
1611 $loguserid = $USER->id
;
1612 $logusername = clean_filename($USER->username
);
1614 if (isset($USER->firstname
)) {
1615 // We can assume both will be set
1616 // - even if to empty.
1617 $logname = clean_filename($USER->firstname
. " " . $USER->lastname
);
1619 if (\core\session\manager
::is_loggedinas()) {
1620 $realuser = \core\session\manager
::get_realuser();
1621 $logusername = clean_filename($realuser->username
." as ".$logusername);
1622 $logname = clean_filename($realuser->firstname
." ".$realuser->lastname
." as ".$logname);
1623 $loguserid = clean_filename($realuser->id
." as ".$loguserid);
1625 switch ($logvalue) {
1627 $logname = $logusername;
1630 $logname = $logname;
1634 $logname = $loguserid;
1637 if ($logmethod == 'apache') {
1638 apache_note('MOODLEUSER', $logname);
1641 if ($logmethod == 'header' && !headers_sent()) {
1642 header("X-MOODLEUSER: $logname");
1650 * Add http stream instrumentation
1652 * This detects which any reads or writes to a php stream which uses
1653 * the 'http' handler. Ideally 100% of traffic uses the Moodle curl
1654 * libraries which do not use php streams.
1656 * @param array $code stream callback code
1658 function proxy_log_callback($code) {
1659 if ($code == STREAM_NOTIFY_CONNECT
) {
1660 $trace = debug_backtrace();
1661 $function = $trace[count($trace) - 1];
1662 $error = "Unsafe internet IO detected: {$function['function']} with arguments " . join(', ', $function['args']) . "\n";
1663 error_log($error . format_backtrace($trace, true)); // phpcs:ignore
1668 * A helper function for deprecated files to use to ensure that, when they are included for unit tests,
1669 * they are run in an isolated process.
1671 * @throws \coding_exception The exception thrown when the process is not isolated.
1673 function require_phpunit_isolation(): void
{
1674 if (!defined('PHPUNIT_TEST') ||
!PHPUNIT_TEST
) {
1679 if (defined('PHPUNIT_ISOLATED_TEST') && PHPUNIT_ISOLATED_TEST
) {
1680 // Already isolated.
1684 throw new \
coding_exception(
1685 'When including this file for a unit test, the test must be run in an isolated process. ' .
1686 'See the PHPUnit @runInSeparateProcess and @runTestsInSeparateProcesses annotations.'