Merge branch 'MDL-82530-spelling' of https://github.com/leonstr/moodle
[moodle.git] / lib / setuplib.php
blobeb2d347bbe01efbdfe130a82a2b85c3a5d41bc8d
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 // GNU General Public License for more details.
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
17 /**
18 * These functions are required very early in the Moodle
19 * setup process, before any of the main libraries are
20 * loaded.
22 * @package core
23 * @subpackage lib
24 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
25 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28 defined('MOODLE_INTERNAL') || die();
30 // Debug levels - always keep the values in ascending order!
31 /** No warnings and errors at all */
32 define('DEBUG_NONE', 0);
33 /** Fatal errors only */
34 define('DEBUG_MINIMAL', E_ERROR | E_PARSE);
35 /** Errors, warnings and notices */
36 define('DEBUG_NORMAL', E_ERROR | E_PARSE | E_WARNING | E_NOTICE);
37 /** All problems except strict PHP warnings */
38 define('DEBUG_ALL', E_ALL & ~E_STRICT);
39 /** DEBUG_ALL with all debug messages and strict warnings */
40 define('DEBUG_DEVELOPER', E_ALL | E_STRICT);
42 /** Remove any memory limits */
43 define('MEMORY_UNLIMITED', -1);
44 /** Standard memory limit for given platform */
45 define('MEMORY_STANDARD', -2);
46 /**
47 * Large memory limit for given platform - used in cron, upgrade, and other places that need a lot of memory.
48 * Can be overridden with $CFG->extramemorylimit setting.
50 define('MEMORY_EXTRA', -3);
51 /** Extremely large memory limit - not recommended for standard scripts */
52 define('MEMORY_HUGE', -4);
54 /**
55 * Get the Whoops! handler.
57 * @return \Whoops\Run|null
59 function get_whoops(): ?\Whoops\Run {
60 global $CFG;
62 if (CLI_SCRIPT || AJAX_SCRIPT) {
63 return null;
66 if (defined('PHPUNIT_TEST') && PHPUNIT_TEST) {
67 return null;
70 if (defined('BEHAT_SITE_RUNNING') && BEHAT_SITE_RUNNING) {
71 return null;
74 if (empty($CFG->debugdisplay)) {
75 return null;
78 if (!$CFG->debug_developer_use_pretty_exceptions) {
79 return null;
82 $composerautoload = "{$CFG->dirroot}/vendor/autoload.php";
83 if (file_exists($composerautoload)) {
84 require_once($composerautoload);
87 if (!class_exists(\Whoops\Run::class)) {
88 return null;
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';
105 if ($isdebugging) {
106 $remove = array_slice($collection->getArray(), 0, 2);
107 $collection->filter(function ($frame) use ($remove): bool {
108 return array_search($frame, $remove) === false;
110 } else {
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);
127 return $whoops;
131 * Default exception handler.
133 * @param Exception $ex
134 * @return void -does not return. Terminates execution!
136 function default_exception_handler($ex) {
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);
160 } else {
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);
166 try {
167 if ($DB) {
168 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
169 $DB->set_debug(0);
171 if (AJAX_SCRIPT) {
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');
175 } else {
176 $renderer = $OUTPUT;
178 echo $renderer->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo,
179 $info->errorcode);
180 } catch (Exception $e) {
181 $out_ex = $e;
182 } catch (Throwable $e) {
183 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
184 $out_ex = $e;
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);
194 } else {
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.
207 * @param int $errno
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);
222 return false;
226 * Unconditionally abort all database transactions, this function
227 * should be called from exception handlers only.
228 * @return void
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) {
262 $matches = true;
263 foreach ($pattern as $property => $value) {
264 if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
265 $matches = false;
268 if ($matches) {
269 return true;
273 return false;
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 {
283 global $CFG;
285 if ($ex instanceof moodle_exception) {
286 $errorcode = $ex->errorcode;
287 $module = $ex->module;
288 $a = $ex->a;
289 $link = $ex->link;
290 $debuginfo = $ex->debuginfo;
291 } else {
292 $errorcode = 'generalexceptionmessage';
293 $module = 'error';
294 $a = $ex->getMessage();
295 $link = '';
296 $debuginfo = '';
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') {
308 $module = 'error';
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);
318 } else {
319 $message = $module . '/' . $errorcode;
320 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
322 } else {
323 $message = $module . '/' . $errorcode;
324 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
327 // Remove some absolute paths from message and debugging info.
328 $searches = array();
329 $replaces = array();
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);
345 } else {
346 $message = htmlspecialchars($message, ENT_COMPAT);
349 if (!empty($CFG->errordocroot)) {
350 $errordoclink = $CFG->errordocroot . '/en/';
351 } else {
352 // Only if the function is available. May be not for early errors.
353 if (function_exists('current_language')) {
354 $errordoclink = get_docs_url();
355 } else {
356 $errordoclink = 'https://docs.moodle.org/en/';
360 if ($module === 'error') {
361 $modulelink = 'moodle';
362 } else {
363 $modulelink = $module;
365 $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
367 if (empty($link)) {
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.
375 } else {
376 // External link spotted!
377 $link = $CFG->wwwroot . '/';
380 $info = new stdClass();
381 $info->message = $message;
382 $info->errorcode = $errorcode;
383 $info->backtrace = $backtrace;
384 $info->link = $link;
385 $info->moreinfourl = $moreinfourl;
386 $info->a = $a;
387 $info->debuginfo = $debuginfo;
389 return $info;
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) {
425 global $CFG;
426 if ($path === null) {
427 $path = '';
430 $path = $path ?? '';
431 // Absolute URLs are used unmodified.
432 if (substr($path, 0, 7) === 'http://' || substr($path, 0, 8) === 'https://') {
433 return $path;
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');
447 } else {
448 // We can use $CFG->branch and avoid having to include version.php.
449 $branch = $CFG->branch;
451 // ensure branch is valid.
452 if (!$branch) {
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.
457 $branch = '.';
459 if (empty($CFG->doclang)) {
460 $lang = current_language();
461 } else {
462 $lang = $CFG->doclang;
464 $end = '/' . $branch . '/' . $lang . '/' . $path;
465 if (empty($CFG->docroot)) {
466 return 'http://docs.moodle.org'. $end;
467 } else {
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)) {
487 return '';
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>';
514 $from .= $line;
516 $from .= $plaintext ? '' : '</ul>';
518 return $from;
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') {
536 return true;
538 return false;
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() {
558 global $CFG, $DB;
560 if (!$DB) {
561 // This should not happen.
562 return;
565 try {
566 $localcfg = get_config('core');
567 } catch (dml_exception $e) {
568 // Most probably empty db, going to install soon.
569 return;
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() {
585 global $CFG;
587 $bootstrapcachefile = $CFG->localcachedir . '/bootstrap.php';
589 if (!empty($CFG->siteidentifier) && !file_exists($bootstrapcachefile)) {
590 $contents = "<?php
591 // ********** This file is generated DO NOT EDIT **********
592 \$CFG->siteidentifier = " . var_export($CFG->siteidentifier, true) . ";
593 \$CFG->bootstraphash = " . var_export(hash_local_config_cache(), true) . ";
594 // Only if the file is not stale and has not been defined.
595 if (\$CFG->bootstraphash === hash_local_config_cache() && !defined('SYSCONTEXTID')) {
596 define('SYSCONTEXTID', ".SYSCONTEXTID.");
600 $temp = $bootstrapcachefile . '.tmp' . uniqid();
601 file_put_contents($temp, $contents);
602 @chmod($temp, $CFG->filepermissions);
603 rename($temp, $bootstrapcachefile);
608 * Calculate a proper hash to be able to invalidate stale cached configs.
610 * Only to be used to verify bootstrap.php status.
612 * @return string md5 hash of all the sensible bits deciding if cached config is stale or no.
614 function hash_local_config_cache() {
615 global $CFG;
617 // This is pretty much {@see moodle_database::get_settings_hash()} that is used
618 // as identifier for the database meta information MUC cache. Should be enough to
619 // react against any of the normal changes (new prefix, change of DB type) while
620 // *incorrectly* keeping the old dataroot directory unmodified with stale data.
621 // This may need more stuff to be considered if it's discovered that there are
622 // more variables making the file stale.
623 return md5($CFG->dbtype . $CFG->dbhost . $CFG->dbuser . $CFG->dbname . $CFG->prefix);
627 * Initialises $FULLME and friends. Private function. Should only be called from
628 * setup.php.
630 function initialise_fullme() {
631 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
633 // Detect common config error.
634 if (substr($CFG->wwwroot, -1) == '/') {
635 throw new \moodle_exception('wwwrootslash', 'error');
638 if (CLI_SCRIPT) {
639 initialise_fullme_cli();
640 return;
642 if (!empty($CFG->overridetossl)) {
643 if (strpos($CFG->wwwroot, 'http://') === 0) {
644 $CFG->wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
645 } else {
646 unset_config('overridetossl');
650 $rurl = setup_get_remote_url();
651 $wwwroot = parse_url($CFG->wwwroot.'/');
653 if (empty($rurl['host'])) {
654 // missing host in request header, probably not a real browser, let's ignore them
656 } else if (!empty($CFG->reverseproxy)) {
657 // $CFG->reverseproxy specifies if reverse proxy server used
658 // Used in load balancing scenarios.
659 // Do not abuse this to try to solve lan/wan access problems!!!!!
661 } else {
662 if (($rurl['host'] !== $wwwroot['host']) or
663 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port']) or
664 (strpos($rurl['path'], $wwwroot['path']) !== 0)) {
666 // Explain the problem and redirect them to the right URL
667 if (!defined('NO_MOODLE_COOKIES')) {
668 define('NO_MOODLE_COOKIES', true);
670 // The login/token.php script should call the correct url/port.
671 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
672 $wwwrootport = empty($wwwroot['port'])?'':$wwwroot['port'];
673 $calledurl = $rurl['host'];
674 if (!empty($rurl['port'])) {
675 $calledurl .= ':'. $rurl['port'];
677 $correcturl = $wwwroot['host'];
678 if (!empty($wwwrootport)) {
679 $correcturl .= ':'. $wwwrootport;
681 throw new moodle_exception('requirecorrectaccess', 'error', '', null,
682 'You called ' . $calledurl .', you should have called ' . $correcturl);
684 $rfullpath = $rurl['fullpath'];
685 // Check that URL is under $CFG->wwwroot.
686 if (strpos($rfullpath, $wwwroot['path']) === 0) {
687 $rfullpath = substr($rurl['fullpath'], strlen($wwwroot['path']) - 1);
688 $rfullpath = (new moodle_url($rfullpath))->out(false);
690 redirect($rfullpath, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
694 // Check that URL is under $CFG->wwwroot.
695 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
696 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
697 } else {
698 // Probably some weird external script
699 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
700 return;
703 // $CFG->sslproxy specifies if external SSL appliance is used
704 // (That is, the Moodle server uses http, with an external box translating everything to https).
705 if (empty($CFG->sslproxy)) {
706 if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
707 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
708 throw new \moodle_exception('sslonlyaccess', 'error');
709 } else {
710 redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
713 } else {
714 if ($wwwroot['scheme'] !== 'https') {
715 throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
717 $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
718 $_SERVER['HTTPS'] = 'on'; // Override $_SERVER to help external libraries with their HTTPS detection.
719 $_SERVER['SERVER_PORT'] = 443; // Assume default ssl port for the proxy.
722 // Using Moodle in "reverse proxy" mode, it's expected that the HTTP Host Moodle receives is different
723 // from the wwwroot configured host. Those URLs being identical could be the consequence of various
724 // issues, including:
725 // - Intentionally trying to set up moodle with 2 distinct addresses for intranet and Internet: this
726 // configuration is unsupported and will lead to bigger problems down the road (the proper solution
727 // for this is adjusting the network routes, and avoid relying on the application for network concerns).
728 // - Misconfiguration of the reverse proxy that would be forwarding the Host header: while it is
729 // standard in many cases that the reverse proxy would do that, in our case, the reverse proxy
730 // must leave the Host header pointing to the internal name of the server.
731 // Port forwarding is allowed, though.
732 if (!empty($CFG->reverseproxy) && $rurl['host'] === $wwwroot['host'] && (empty($wwwroot['port']) || $rurl['port'] === $wwwroot['port'])) {
733 throw new \moodle_exception('reverseproxyabused', 'error');
736 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
737 if (!empty($wwwroot['port'])) {
738 $hostandport .= ':'.$wwwroot['port'];
741 $FULLSCRIPT = $hostandport . $rurl['path'];
742 $FULLME = $hostandport . $rurl['fullpath'];
743 $ME = $rurl['fullpath'];
747 * Initialises $FULLME and friends for command line scripts.
748 * This is a private method for use by initialise_fullme.
750 function initialise_fullme_cli() {
751 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
753 // Urls do not make much sense in CLI scripts
754 $backtrace = debug_backtrace();
755 $topfile = array_pop($backtrace);
756 $topfile = realpath($topfile['file']);
757 $dirroot = realpath($CFG->dirroot);
759 if (strpos($topfile, $dirroot) !== 0) {
760 // Probably some weird external script
761 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
762 } else {
763 $relativefile = substr($topfile, strlen($dirroot));
764 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
765 $SCRIPT = $FULLSCRIPT = $relativefile;
766 $FULLME = $ME = null;
771 * Get the URL that PHP/the web server thinks it is serving. Private function
772 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
773 * @return array in the same format that parse_url returns, with the addition of
774 * a 'fullpath' element, which includes any slasharguments path.
776 function setup_get_remote_url() {
777 $rurl = array();
778 if (isset($_SERVER['HTTP_HOST'])) {
779 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
780 } else {
781 $rurl['host'] = null;
783 $rurl['port'] = (int)$_SERVER['SERVER_PORT'];
784 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
785 $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ? 'http' : 'https';
787 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
788 //Apache server
789 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
791 // Fixing a known issue with:
792 // - Apache versions lesser than 2.4.11
793 // - PHP deployed in Apache as PHP-FPM via mod_proxy_fcgi
794 // - PHP versions lesser than 5.6.3 and 5.5.18.
795 if (isset($_SERVER['PATH_INFO']) && (php_sapi_name() === 'fpm-fcgi') && isset($_SERVER['SCRIPT_NAME'])) {
796 $pathinfodec = rawurldecode($_SERVER['PATH_INFO']);
797 $lenneedle = strlen($pathinfodec);
798 // Checks whether SCRIPT_NAME ends with PATH_INFO, URL-decoded.
799 if (substr($_SERVER['SCRIPT_NAME'], -$lenneedle) === $pathinfodec) {
800 // This is the "Apache 2.4.10- running PHP-FPM via mod_proxy_fcgi" fingerprint,
801 // 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)
802 // => SCRIPT_NAME contains 'slash arguments' data too, which is wrongly exposed via PATH_INFO as URL-encoded.
803 // Fix both $_SERVER['PATH_INFO'] and $_SERVER['SCRIPT_NAME'].
804 $lenhaystack = strlen($_SERVER['SCRIPT_NAME']);
805 $pos = $lenhaystack - $lenneedle;
806 // Here $pos is greater than 0 but let's double check it.
807 if ($pos > 0) {
808 $_SERVER['PATH_INFO'] = $pathinfodec;
809 $_SERVER['SCRIPT_NAME'] = substr($_SERVER['SCRIPT_NAME'], 0, $pos);
814 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
815 //IIS - needs a lot of tweaking to make it work
816 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
818 // NOTE: we should ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS.
819 // Since 2.0, we rely on IIS rewrite extensions like Helicon ISAPI_rewrite
820 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
821 // OR
822 // we rely on a proper IIS 6.0+ configuration: the 'FastCGIUtf8ServerVariables' registry key.
823 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
824 // Check that PATH_INFO works == must not contain the script name.
825 if (strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === false) {
826 $rurl['fullpath'] .= clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
830 if (isset($_SERVER['QUERY_STRING']) and $_SERVER['QUERY_STRING'] !== '') {
831 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
833 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
835 /* NOTE: following servers are not fully tested! */
837 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
838 //lighttpd - not officially supported
839 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
841 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
842 //nginx - not officially supported
843 if (!isset($_SERVER['SCRIPT_NAME'])) {
844 die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
846 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
848 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
849 //cherokee - not officially supported
850 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
852 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
853 //zeus - not officially supported
854 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
856 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
857 //LiteSpeed - not officially supported
858 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
860 } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
861 //obscure name found on some servers - this is definitely not supported
862 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
864 } else if (strpos($_SERVER['SERVER_SOFTWARE'], 'PHP') === 0) {
865 // built-in PHP Development Server
866 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
868 } else {
869 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
872 // sanitize the url a bit more, the encoding style may be different in vars above
873 $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
874 $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);
876 return $rurl;
880 * Try to work around the 'max_input_vars' restriction if necessary.
882 function workaround_max_input_vars() {
883 // Make sure this gets executed only once from lib/setup.php!
884 static $executed = false;
885 if ($executed) {
886 debugging('workaround_max_input_vars() must be called only once!');
887 return;
889 $executed = true;
891 if (!isset($_SERVER["CONTENT_TYPE"]) or strpos($_SERVER["CONTENT_TYPE"], 'multipart/form-data') !== false) {
892 // Not a post or 'multipart/form-data' which is not compatible with "php://input" reading.
893 return;
896 if (!isloggedin() or isguestuser()) {
897 // Only real users post huge forms.
898 return;
901 $max = (int)ini_get('max_input_vars');
903 if ($max <= 0) {
904 // Most probably PHP < 5.3.9 that does not implement this limit.
905 return;
908 if ($max >= 200000) {
909 // This value should be ok for all our forms, by setting it in php.ini
910 // admins may prevent any unexpected regressions caused by this hack.
912 // Note there is no need to worry about DDoS caused by making this limit very high
913 // because there are very many easier ways to DDoS any Moodle server.
914 return;
917 // Worst case is advanced checkboxes which use up to two max_input_vars
918 // slots for each entry in $_POST, because of sending two fields with the
919 // same name. So count everything twice just in case.
920 if (count($_POST, COUNT_RECURSIVE) * 2 < $max) {
921 return;
924 // Large POST request with enctype supported by php://input.
925 // Parse php://input in chunks to bypass max_input_vars limit, which also applies to parse_str().
926 $str = file_get_contents("php://input");
927 if ($str === false or $str === '') {
928 // Some weird error.
929 return;
932 $delim = '&';
933 $fun = function($p) use ($delim) {
934 return implode($delim, $p);
936 $chunks = array_map($fun, array_chunk(explode($delim, $str), $max));
938 // Clear everything from existing $_POST array, otherwise it might be included
939 // twice (this affects array params primarily).
940 foreach ($_POST as $key => $value) {
941 unset($_POST[$key]);
942 // Also clear from request array - but only the things that are in $_POST,
943 // that way it will leave the things from a get request if any.
944 unset($_REQUEST[$key]);
947 foreach ($chunks as $chunk) {
948 $values = array();
949 parse_str($chunk, $values);
951 merge_query_params($_POST, $values);
952 merge_query_params($_REQUEST, $values);
957 * Merge parsed POST chunks.
959 * NOTE: this is not perfect, but it should work in most cases hopefully.
961 * @param array $target
962 * @param array $values
964 function merge_query_params(array &$target, array $values) {
965 if (isset($values[0]) and isset($target[0])) {
966 // This looks like a split [] array, lets verify the keys are continuous starting with 0.
967 $keys1 = array_keys($values);
968 $keys2 = array_keys($target);
969 if ($keys1 === array_keys($keys1) and $keys2 === array_keys($keys2)) {
970 foreach ($values as $v) {
971 $target[] = $v;
973 return;
976 foreach ($values as $k => $v) {
977 if (!isset($target[$k])) {
978 $target[$k] = $v;
979 continue;
981 if (is_array($target[$k]) and is_array($v)) {
982 merge_query_params($target[$k], $v);
983 continue;
985 // We should not get here unless there are duplicates in params.
986 $target[$k] = $v;
991 * Initializes our performance info early.
993 * Pairs up with get_performance_info() which is actually
994 * in moodlelib.php. This function is here so that we can
995 * call it before all the libs are pulled in.
997 * @uses $PERF
999 function init_performance_info() {
1001 global $PERF, $CFG, $USER;
1003 $PERF = new stdClass();
1004 if (function_exists('microtime')) {
1005 $PERF->starttime = microtime();
1007 if (function_exists('memory_get_usage')) {
1008 $PERF->startmemory = memory_get_usage();
1010 if (function_exists('posix_times')) {
1011 $PERF->startposixtimes = posix_times();
1016 * Indicates whether we are in the middle of the initial Moodle install.
1018 * Very occasionally it is necessary avoid running certain bits of code before the
1019 * Moodle installation has completed. The installed flag is set in admin/index.php
1020 * after Moodle core and all the plugins have been installed, but just before
1021 * the person doing the initial install is asked to choose the admin password.
1023 * @return boolean true if the initial install is not complete.
1025 function during_initial_install() {
1026 global $CFG;
1027 return empty($CFG->rolesactive);
1031 * Function to raise the memory limit to a new value.
1032 * Will respect the memory limit if it is higher, thus allowing
1033 * settings in php.ini, apache conf or command line switches
1034 * to override it.
1036 * The memory limit should be expressed with a constant
1037 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
1038 * It is possible to use strings or integers too (eg:'128M').
1040 * @param mixed $newlimit the new memory limit
1041 * @return bool success
1043 function raise_memory_limit($newlimit) {
1044 global $CFG;
1046 if ($newlimit == MEMORY_UNLIMITED) {
1047 ini_set('memory_limit', -1);
1048 return true;
1050 } else if ($newlimit == MEMORY_STANDARD) {
1051 if (PHP_INT_SIZE > 4) {
1052 $newlimit = get_real_size('128M'); // 64bit needs more memory
1053 } else {
1054 $newlimit = get_real_size('96M');
1057 } else if ($newlimit == MEMORY_EXTRA) {
1058 if (PHP_INT_SIZE > 4) {
1059 $newlimit = get_real_size('384M'); // 64bit needs more memory
1060 } else {
1061 $newlimit = get_real_size('256M');
1063 if (!empty($CFG->extramemorylimit)) {
1064 $extra = get_real_size($CFG->extramemorylimit);
1065 if ($extra > $newlimit) {
1066 $newlimit = $extra;
1070 } else if ($newlimit == MEMORY_HUGE) {
1071 // MEMORY_HUGE uses 2G or MEMORY_EXTRA, whichever is bigger.
1072 $newlimit = get_real_size('2G');
1073 if (!empty($CFG->extramemorylimit)) {
1074 $extra = get_real_size($CFG->extramemorylimit);
1075 if ($extra > $newlimit) {
1076 $newlimit = $extra;
1080 } else {
1081 $newlimit = get_real_size($newlimit);
1084 if ($newlimit <= 0) {
1085 debugging('Invalid memory limit specified.');
1086 return false;
1089 $cur = ini_get('memory_limit');
1090 if (empty($cur)) {
1091 // if php is compiled without --enable-memory-limits
1092 // apparently memory_limit is set to ''
1093 $cur = 0;
1094 } else {
1095 if ($cur == -1){
1096 return true; // unlimited mem!
1098 $cur = get_real_size($cur);
1101 if ($newlimit > $cur) {
1102 ini_set('memory_limit', $newlimit);
1103 return true;
1105 return false;
1109 * Function to reduce the memory limit to a new value.
1110 * Will respect the memory limit if it is lower, thus allowing
1111 * settings in php.ini, apache conf or command line switches
1112 * to override it
1114 * The memory limit should be expressed with a string (eg:'64M')
1116 * @param string $newlimit the new memory limit
1117 * @return bool
1119 function reduce_memory_limit($newlimit) {
1120 if (empty($newlimit)) {
1121 return false;
1123 $cur = ini_get('memory_limit');
1124 if (empty($cur)) {
1125 // if php is compiled without --enable-memory-limits
1126 // apparently memory_limit is set to ''
1127 $cur = 0;
1128 } else {
1129 if ($cur == -1){
1130 return true; // unlimited mem!
1132 $cur = get_real_size($cur);
1135 $new = get_real_size($newlimit);
1136 // -1 is smaller, but it means unlimited
1137 if ($new < $cur && $new != -1) {
1138 ini_set('memory_limit', $newlimit);
1139 return true;
1141 return false;
1145 * Converts numbers like 10M into bytes.
1147 * @param string $size The size to be converted
1148 * @return int
1150 function get_real_size($size = 0) {
1151 if (!$size) {
1152 return 0;
1155 static $binaryprefixes = array(
1156 'K' => 1024 ** 1,
1157 'k' => 1024 ** 1,
1158 'M' => 1024 ** 2,
1159 'm' => 1024 ** 2,
1160 'G' => 1024 ** 3,
1161 'g' => 1024 ** 3,
1162 'T' => 1024 ** 4,
1163 't' => 1024 ** 4,
1164 'P' => 1024 ** 5,
1165 'p' => 1024 ** 5,
1168 if (preg_match('/^([0-9]+)([KMGTP])/i', $size, $matches)) {
1169 return $matches[1] * $binaryprefixes[$matches[2]];
1172 return (int) $size;
1176 * Check whether a major upgrade is needed.
1178 * That is defined as an upgrade that changes something really fundamental
1179 * in the database, so nothing can possibly work until the database has
1180 * been updated, and that is defined by the hard-coded version number in
1181 * this function.
1183 * @return bool
1185 function is_major_upgrade_required() {
1186 global $CFG;
1187 $lastmajordbchanges = 2024010400.00; // This should be the version where the breaking changes happen.
1189 $required = empty($CFG->version);
1190 $required = $required || (float)$CFG->version < $lastmajordbchanges;
1191 $required = $required || during_initial_install();
1192 $required = $required || !empty($CFG->adminsetuppending);
1194 return $required;
1198 * Redirect to the Notifications page if a major upgrade is required, and
1199 * terminate the current user session.
1201 function redirect_if_major_upgrade_required() {
1202 global $CFG;
1203 if (is_major_upgrade_required()) {
1204 try {
1205 @\core\session\manager::terminate_current();
1206 } catch (Exception $e) {
1207 // Ignore any errors, redirect to upgrade anyway.
1209 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
1210 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1211 @header('Location: ' . $url);
1212 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url, ENT_COMPAT));
1213 exit;
1218 * Makes sure that upgrade process is not running
1220 * To be inserted in the core functions that can not be called by pluigns during upgrade.
1221 * Core upgrade should not use any API functions at all.
1222 * See {@link https://moodledev.io/docs/guides/upgrade#upgrade-code-restrictions}
1224 * @throws moodle_exception if executed from inside of upgrade script and $warningonly is false
1225 * @param bool $warningonly if true displays a warning instead of throwing an exception
1226 * @return bool true if executed from outside of upgrade process, false if from inside upgrade process and function is used for warning only
1228 function upgrade_ensure_not_running($warningonly = false) {
1229 global $CFG;
1230 if (!empty($CFG->upgraderunning)) {
1231 if (!$warningonly) {
1232 throw new moodle_exception('cannotexecduringupgrade');
1233 } else {
1234 debugging(get_string('cannotexecduringupgrade', 'error'), DEBUG_DEVELOPER);
1235 return false;
1238 return true;
1242 * Function to check if a directory exists and by default create it if not exists.
1244 * Previously this was accepting paths only from dataroot, but we now allow
1245 * files outside of dataroot if you supply custom paths for some settings in config.php.
1246 * This function does not verify that the directory is writable.
1248 * NOTE: this function uses current file stat cache,
1249 * please use clearstatcache() before this if you expect that the
1250 * directories may have been removed recently from a different request.
1252 * @param string $dir absolute directory path
1253 * @param boolean $create directory if does not exist
1254 * @param boolean $recursive create directory recursively
1255 * @return boolean true if directory exists or created, false otherwise
1257 function check_dir_exists($dir, $create = true, $recursive = true) {
1258 global $CFG;
1260 umask($CFG->umaskpermissions);
1262 if (is_dir($dir)) {
1263 return true;
1266 if (!$create) {
1267 return false;
1270 return mkdir($dir, $CFG->directorypermissions, $recursive);
1274 * Create a new unique directory within the specified directory.
1276 * @param string $basedir The directory to create your new unique directory within.
1277 * @param bool $exceptiononerror throw exception if error encountered
1278 * @return string The created directory
1279 * @throws invalid_dataroot_permissions
1281 function make_unique_writable_directory($basedir, $exceptiononerror = true) {
1282 if (!is_dir($basedir) || !is_writable($basedir)) {
1283 // The basedir is not writable. We will not be able to create the child directory.
1284 if ($exceptiononerror) {
1285 throw new invalid_dataroot_permissions($basedir . ' is not writable. Unable to create a unique directory within it.');
1286 } else {
1287 return false;
1291 do {
1292 // Let's use uniqid() because it's "unique enough" (microtime based). The loop does handle repetitions.
1293 // Windows and old PHP don't like very long paths, so try to keep this shorter. See MDL-69975.
1294 $uniquedir = $basedir . DIRECTORY_SEPARATOR . uniqid();
1295 } while (
1296 // Ensure that basedir is still writable - if we do not check, we could get stuck in a loop here.
1297 is_writable($basedir) &&
1299 // Make the new unique directory. If the directory already exists, it will return false.
1300 !make_writable_directory($uniquedir, $exceptiononerror) &&
1302 // Ensure that the directory now exists
1303 file_exists($uniquedir) && is_dir($uniquedir)
1306 // Check that the directory was correctly created.
1307 if (!file_exists($uniquedir) || !is_dir($uniquedir) || !is_writable($uniquedir)) {
1308 if ($exceptiononerror) {
1309 throw new invalid_dataroot_permissions('Unique directory creation failed.');
1310 } else {
1311 return false;
1315 return $uniquedir;
1319 * Create a directory and make sure it is writable.
1321 * @private
1322 * @param string $dir the full path of the directory to be created
1323 * @param bool $exceptiononerror throw exception if error encountered
1324 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1326 function make_writable_directory($dir, $exceptiononerror = true) {
1327 global $CFG;
1329 if (file_exists($dir) and !is_dir($dir)) {
1330 if ($exceptiononerror) {
1331 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1332 } else {
1333 return false;
1337 umask($CFG->umaskpermissions);
1339 if (!file_exists($dir)) {
1340 if (!@mkdir($dir, $CFG->directorypermissions, true)) {
1341 clearstatcache();
1342 // There might be a race condition when creating directory.
1343 if (!is_dir($dir)) {
1344 if ($exceptiononerror) {
1345 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1346 } else {
1347 debugging('Can not create directory: '.$dir, DEBUG_DEVELOPER);
1348 return false;
1354 if (!is_writable($dir)) {
1355 if ($exceptiononerror) {
1356 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1357 } else {
1358 return false;
1362 return $dir;
1366 * Protect a directory from web access.
1367 * Could be extended in the future to support other mechanisms (e.g. other webservers).
1369 * @private
1370 * @param string $dir the full path of the directory to be protected
1372 function protect_directory($dir) {
1373 global $CFG;
1374 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1375 if (!file_exists("$dir/.htaccess")) {
1376 if ($handle = fopen("$dir/.htaccess", 'w')) { // For safety
1377 @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");
1378 @fclose($handle);
1379 @chmod("$dir/.htaccess", $CFG->filepermissions);
1385 * Create a directory under dataroot and make sure it is writable.
1386 * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
1388 * @param string $directory the full path of the directory to be created under $CFG->dataroot
1389 * @param bool $exceptiononerror throw exception if error encountered
1390 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1392 function make_upload_directory($directory, $exceptiononerror = true) {
1393 global $CFG;
1395 if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1396 debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1398 } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
1399 debugging('Use make_cache_directory() for creation of cache directory and $CFG->cachedir to get the location.');
1401 } else if (strpos($directory, 'localcache/') === 0 or $directory === 'localcache') {
1402 debugging('Use make_localcache_directory() for creation of local cache directory and $CFG->localcachedir to get the location.');
1405 protect_directory($CFG->dataroot);
1406 return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1410 * Get a per-request storage directory in the tempdir.
1412 * The directory is automatically cleaned up during the shutdown handler.
1414 * @param bool $exceptiononerror throw exception if error encountered
1415 * @param bool $forcecreate Force creation of a new parent directory
1416 * @return string Returns full path to directory if successful, false if not; may throw exception
1418 function get_request_storage_directory($exceptiononerror = true, bool $forcecreate = false) {
1419 global $CFG;
1421 static $requestdir = null;
1423 $writabledirectoryexists = (null !== $requestdir);
1424 $writabledirectoryexists = $writabledirectoryexists && file_exists($requestdir);
1425 $writabledirectoryexists = $writabledirectoryexists && is_dir($requestdir);
1426 $writabledirectoryexists = $writabledirectoryexists && is_writable($requestdir);
1427 $createnewdirectory = $forcecreate || !$writabledirectoryexists;
1429 if ($createnewdirectory) {
1431 // Let's add the first chars of siteidentifier only. This is to help separate
1432 // paths on systems which host multiple moodles. We don't use the full id
1433 // as Windows and old PHP don't like very long paths. See MDL-69975.
1434 $basedir = $CFG->localrequestdir . '/' . substr($CFG->siteidentifier, 0, 4);
1436 make_writable_directory($basedir);
1437 protect_directory($basedir);
1439 if ($dir = make_unique_writable_directory($basedir, $exceptiononerror)) {
1440 // Register a shutdown handler to remove the directory.
1441 \core_shutdown_manager::register_function('remove_dir', [$dir]);
1444 $requestdir = $dir;
1447 return $requestdir;
1451 * Create a per-request directory and make sure it is writable.
1452 * This can only be used during the current request and will be tidied away
1453 * automatically afterwards.
1455 * A new, unique directory is always created within a shared base request directory.
1457 * In some exceptional cases an alternative base directory may be required. This can be accomplished using the
1458 * $forcecreate parameter. Typically this will only be requried where the file may be required during a shutdown handler
1459 * which may or may not be registered after a previous request directory has been created.
1461 * @param bool $exceptiononerror throw exception if error encountered
1462 * @param bool $forcecreate Force creation of a new parent directory
1463 * @return string The full path to directory if successful, false if not; may throw exception
1465 function make_request_directory(bool $exceptiononerror = true, bool $forcecreate = false) {
1466 $basedir = get_request_storage_directory($exceptiononerror, $forcecreate);
1467 return make_unique_writable_directory($basedir, $exceptiononerror);
1471 * Get the full path of a directory under $CFG->backuptempdir.
1473 * @param string $directory the relative path of the directory under $CFG->backuptempdir
1474 * @return string|false Returns full path to directory given a valid string; otherwise, false.
1476 function get_backup_temp_directory($directory) {
1477 global $CFG;
1478 if (($directory === null) || ($directory === false)) {
1479 return false;
1481 return "$CFG->backuptempdir/$directory";
1485 * Create a directory under $CFG->backuptempdir and make sure it is writable.
1487 * Do not use for storing generic temp files - see make_temp_directory() instead for this purpose.
1489 * Backup temporary files must be on a shared storage.
1491 * @param string $directory the relative path of the directory to be created under $CFG->backuptempdir
1492 * @param bool $exceptiononerror throw exception if error encountered
1493 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1495 function make_backup_temp_directory($directory, $exceptiononerror = true) {
1496 global $CFG;
1497 if ($CFG->backuptempdir !== "$CFG->tempdir/backup") {
1498 check_dir_exists($CFG->backuptempdir, true, true);
1499 protect_directory($CFG->backuptempdir);
1500 } else {
1501 protect_directory($CFG->tempdir);
1503 return make_writable_directory("$CFG->backuptempdir/$directory", $exceptiononerror);
1507 * Create a directory under tempdir and make sure it is writable.
1509 * Where possible, please use make_request_directory() and limit the scope
1510 * of your data to the current HTTP request.
1512 * Do not use for storing cache files - see make_cache_directory(), and
1513 * make_localcache_directory() instead for this purpose.
1515 * Temporary files must be on a shared storage, and heavy usage is
1516 * discouraged due to the performance impact upon clustered environments.
1518 * @param string $directory the full path of the directory to be created under $CFG->tempdir
1519 * @param bool $exceptiononerror throw exception if error encountered
1520 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1522 function make_temp_directory($directory, $exceptiononerror = true) {
1523 global $CFG;
1524 if ($CFG->tempdir !== "$CFG->dataroot/temp") {
1525 check_dir_exists($CFG->tempdir, true, true);
1526 protect_directory($CFG->tempdir);
1527 } else {
1528 protect_directory($CFG->dataroot);
1530 return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1534 * Create a directory under cachedir and make sure it is writable.
1536 * Note: this cache directory is shared by all cluster nodes.
1538 * @param string $directory the full path of the directory to be created under $CFG->cachedir
1539 * @param bool $exceptiononerror throw exception if error encountered
1540 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1542 function make_cache_directory($directory, $exceptiononerror = true) {
1543 global $CFG;
1544 if ($CFG->cachedir !== "$CFG->dataroot/cache") {
1545 check_dir_exists($CFG->cachedir, true, true);
1546 protect_directory($CFG->cachedir);
1547 } else {
1548 protect_directory($CFG->dataroot);
1550 return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1554 * Create a directory under localcachedir and make sure it is writable.
1555 * The files in this directory MUST NOT change, use revisions or content hashes to
1556 * work around this limitation - this means you can only add new files here.
1558 * The content of this directory gets purged automatically on all cluster nodes
1559 * after calling purge_all_caches() before new data is written to this directory.
1561 * Note: this local cache directory does not need to be shared by cluster nodes.
1563 * @param string $directory the relative path of the directory to be created under $CFG->localcachedir
1564 * @param bool $exceptiononerror throw exception if error encountered
1565 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1567 function make_localcache_directory($directory, $exceptiononerror = true) {
1568 global $CFG;
1570 make_writable_directory($CFG->localcachedir, $exceptiononerror);
1572 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1573 protect_directory($CFG->localcachedir);
1574 } else {
1575 protect_directory($CFG->dataroot);
1578 if (!isset($CFG->localcachedirpurged)) {
1579 $CFG->localcachedirpurged = 0;
1581 $timestampfile = "$CFG->localcachedir/.lastpurged";
1583 if (!file_exists($timestampfile)) {
1584 touch($timestampfile);
1585 @chmod($timestampfile, $CFG->filepermissions);
1587 } else if (filemtime($timestampfile) < $CFG->localcachedirpurged) {
1588 // This means our local cached dir was not purged yet.
1589 remove_dir($CFG->localcachedir, true);
1590 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1591 protect_directory($CFG->localcachedir);
1593 touch($timestampfile);
1594 @chmod($timestampfile, $CFG->filepermissions);
1595 clearstatcache();
1598 if ($directory === '') {
1599 return $CFG->localcachedir;
1602 return make_writable_directory("$CFG->localcachedir/$directory", $exceptiononerror);
1606 * Webserver access user logging
1608 function set_access_log_user() {
1609 global $USER, $CFG;
1610 if ($USER && isset($USER->username)) {
1611 $logmethod = '';
1612 $logvalue = 0;
1613 if (!empty($CFG->apacheloguser) && function_exists('apache_note')) {
1614 $logmethod = 'apache';
1615 $logvalue = $CFG->apacheloguser;
1617 if (!empty($CFG->headerloguser)) {
1618 $logmethod = 'header';
1619 $logvalue = $CFG->headerloguser;
1621 if (!empty($logmethod)) {
1622 $loguserid = $USER->id;
1623 $logusername = clean_filename($USER->username);
1624 $logname = '';
1625 if (isset($USER->firstname)) {
1626 // We can assume both will be set
1627 // - even if to empty.
1628 $logname = clean_filename($USER->firstname . " " . $USER->lastname);
1630 if (\core\session\manager::is_loggedinas()) {
1631 $realuser = \core\session\manager::get_realuser();
1632 $logusername = clean_filename($realuser->username." as ".$logusername);
1633 $logname = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$logname);
1634 $loguserid = clean_filename($realuser->id." as ".$loguserid);
1636 switch ($logvalue) {
1637 case 3:
1638 $logname = $logusername;
1639 break;
1640 case 2:
1641 $logname = $logname;
1642 break;
1643 case 1:
1644 default:
1645 $logname = $loguserid;
1646 break;
1648 if ($logmethod == 'apache') {
1649 apache_note('MOODLEUSER', $logname);
1652 if ($logmethod == 'header' && !headers_sent()) {
1653 header("X-MOODLEUSER: $logname");
1661 * Add http stream instrumentation
1663 * This detects which any reads or writes to a php stream which uses
1664 * the 'http' handler. Ideally 100% of traffic uses the Moodle curl
1665 * libraries which do not use php streams.
1667 * @param array $code stream callback code
1669 function proxy_log_callback($code) {
1670 if ($code == STREAM_NOTIFY_CONNECT) {
1671 $trace = debug_backtrace();
1672 $function = $trace[count($trace) - 1];
1673 $error = "Unsafe internet IO detected: {$function['function']} with arguments " . join(', ', $function['args']) . "\n";
1674 error_log($error . format_backtrace($trace, true)); // phpcs:ignore
1679 * A helper function for deprecated files to use to ensure that, when they are included for unit tests,
1680 * they are run in an isolated process.
1682 * @throws \coding_exception The exception thrown when the process is not isolated.
1684 function require_phpunit_isolation(): void {
1685 if (!defined('PHPUNIT_TEST') || !PHPUNIT_TEST) {
1686 // Not a test.
1687 return;
1690 if (defined('PHPUNIT_ISOLATED_TEST') && PHPUNIT_ISOLATED_TEST) {
1691 // Already isolated.
1692 return;
1695 throw new \coding_exception(
1696 'When including this file for a unit test, the test must be run in an isolated process. ' .
1697 'See the PHPUnit @runInSeparateProcess and @runTestsInSeparateProcesses annotations.'