MDL-68588 Backup: Hide ->backuptempdir in exception info
[moodle.git] / lib / setuplib.php
CommitLineData
b37eac91 1<?php
b37eac91 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.
13//
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/>.
16
b37eac91 17/**
18 * These functions are required very early in the Moodle
19 * setup process, before any of the main libraries are
20 * loaded.
30fa50d0 21 *
78bfb562
PS
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
b37eac91 26 */
d3f9f1f8 27
78bfb562
PS
28defined('MOODLE_INTERNAL') || die();
29
e63f95d7
PS
30// Debug levels - always keep the values in ascending order!
31/** No warnings and errors at all */
0f0f0768 32define('DEBUG_NONE', 0);
e63f95d7
PS
33/** Fatal errors only */
34define('DEBUG_MINIMAL', E_ERROR | E_PARSE);
35/** Errors, warnings and notices */
36define('DEBUG_NORMAL', E_ERROR | E_PARSE | E_WARNING | E_NOTICE);
37/** All problems except strict PHP warnings */
38define('DEBUG_ALL', E_ALL & ~E_STRICT);
39/** DEBUG_ALL with all debug messages and strict warnings */
40define('DEBUG_DEVELOPER', E_ALL | E_STRICT);
0f0f0768
PS
41
42/** Remove any memory limits */
43define('MEMORY_UNLIMITED', -1);
44/** Standard memory limit for given platform */
45define('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.
49 */
50define('MEMORY_EXTRA', -3);
51/** Extremely large memory limit - not recommended for standard scripts */
52define('MEMORY_HUGE', -4);
c84a2dbe 53
251387d0 54/**
55 * Base Moodle Exception class
b37eac91 56 *
c84a2dbe 57 * Although this class is defined here, you cannot throw a moodle_exception until
58 * after moodlelib.php has been included (which will happen very soon).
59 *
47d2216e
PS
60 * @package core
61 * @subpackage lib
62 * @copyright 2008 Petr Skoda {@link http://skodak.org}
63 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
251387d0 64 */
65class moodle_exception extends Exception {
34223e03
SH
66
67 /**
68 * @var string The name of the string from error.php to print
69 */
251387d0 70 public $errorcode;
34223e03
SH
71
72 /**
73 * @var string The name of module
74 */
251387d0 75 public $module;
34223e03
SH
76
77 /**
78 * @var mixed Extra words and phrases that might be required in the error string
79 */
251387d0 80 public $a;
34223e03
SH
81
82 /**
83 * @var string The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
84 */
251387d0 85 public $link;
34223e03
SH
86
87 /**
88 * @var string Optional information to aid the debugging process
89 */
eee5d9bb 90 public $debuginfo;
251387d0 91
92 /**
93 * Constructor
94 * @param string $errorcode The name of the string from error.php to print
95 * @param string $module name of module
96 * @param string $link The url where the user will be prompted to continue. If no url is provided the user will be directed to the site index page.
34223e03 97 * @param mixed $a Extra words and phrases that might be required in the error string
eee5d9bb 98 * @param string $debuginfo optional debugging information
251387d0 99 */
5ca18631 100 function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
c912cd73
RW
101 global $CFG;
102
5ca18631 103 if (empty($module) || $module == 'moodle' || $module == 'core') {
251387d0 104 $module = 'error';
105 }
106
5ca18631 107 $this->errorcode = $errorcode;
108 $this->module = $module;
109 $this->link = $link;
110 $this->a = $a;
98984c09 111 $this->debuginfo = is_null($debuginfo) ? null : (string)$debuginfo;
251387d0 112
4f6be42c
DM
113 if (get_string_manager()->string_exists($errorcode, $module)) {
114 $message = get_string($errorcode, $module, $a);
8d37c9b2 115 $haserrorstring = true;
4f6be42c
DM
116 } else {
117 $message = $module . '/' . $errorcode;
8d37c9b2 118 $haserrorstring = false;
4f6be42c 119 }
251387d0 120
c912cd73
RW
121 $isinphpunittest = (defined('PHPUNIT_TEST') && PHPUNIT_TEST);
122 $hasdebugdeveloper = (
123 isset($CFG->debugdisplay) &&
124 isset($CFG->debug) &&
125 $CFG->debugdisplay &&
126 $CFG->debug === DEBUG_DEVELOPER
127 );
128
129 if ($debuginfo) {
130 if ($isinphpunittest || $hasdebugdeveloper) {
131 $message = "$message ($debuginfo)";
132 }
a3d5830a
PS
133 }
134
c912cd73 135 if (!$haserrorstring and $isinphpunittest) {
8d37c9b2
DM
136 // Append the contents of $a to $debuginfo so helpful information isn't lost.
137 // This emulates what {@link get_exception_info()} does. Unfortunately that
138 // function is not used by phpunit.
139 $message .= PHP_EOL.'$a contents: '.print_r($a, true);
140 }
141
251387d0 142 parent::__construct($message, 0);
143 }
144}
145
df997f84
PS
146/**
147 * Course/activity access exception.
148 *
149 * This exception is thrown from require_login()
47d2216e 150 *
f76249cc 151 * @package core_access
47d2216e
PS
152 * @copyright 2010 Petr Skoda {@link http://skodak.org}
153 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
df997f84
PS
154 */
155class require_login_exception extends moodle_exception {
34223e03
SH
156 /**
157 * Constructor
158 * @param string $debuginfo Information to aid the debugging process
159 */
df997f84
PS
160 function __construct($debuginfo) {
161 parent::__construct('requireloginerror', 'error', '', NULL, $debuginfo);
162 }
163}
164
2ed6be87
AN
165/**
166 * Session timeout exception.
167 *
168 * This exception is thrown from require_login()
169 *
170 * @package core_access
171 * @copyright 2015 Andrew Nicols <andrew@nicols.co.uk>
172 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
173 */
174class require_login_session_timeout_exception extends require_login_exception {
175 /**
176 * Constructor
177 */
178 public function __construct() {
179 moodle_exception::__construct('sessionerroruser', 'error');
180 }
181}
182
559a5dbd 183/**
184 * Web service parameter exception class
92fe97f9 185 * @deprecated since Moodle 2.2 - use moodle exception instead
559a5dbd 186 * This exception must be thrown to the web service client when a web service parameter is invalid
187 * The error string is gotten from webservice.php
188 */
189class webservice_parameter_exception extends moodle_exception {
190 /**
191 * Constructor
192 * @param string $errorcode The name of the string from webservice.php to print
193 * @param string $a The name of the parameter
34223e03 194 * @param string $debuginfo Optional information to aid debugging
559a5dbd 195 */
93602569
JM
196 function __construct($errorcode=null, $a = '', $debuginfo = null) {
197 parent::__construct($errorcode, 'webservice', '', $a, $debuginfo);
559a5dbd 198 }
199}
200
9a0df45a 201/**
202 * Exceptions indicating user does not have permissions to do something
203 * and the execution can not continue.
47d2216e 204 *
f76249cc 205 * @package core_access
47d2216e
PS
206 * @copyright 2009 Petr Skoda {@link http://skodak.org}
207 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9a0df45a 208 */
209class required_capability_exception extends moodle_exception {
34223e03
SH
210 /**
211 * Constructor
212 * @param context $context The context used for the capability check
213 * @param string $capability The required capability
214 * @param string $errormessage The error message to show the user
215 * @param string $stringfile
216 */
9a0df45a 217 function __construct($context, $capability, $errormessage, $stringfile) {
218 $capabilityname = get_capability_string($capability);
848fe203
PS
219 if ($context->contextlevel == CONTEXT_MODULE and preg_match('/:view$/', $capability)) {
220 // we can not go to mod/xx/view.php because we most probably do not have cap to view it, let's go to course instead
6c89d4e1
MN
221 $parentcontext = $context->get_parent_context();
222 $link = $parentcontext->get_url();
848fe203 223 } else {
6c89d4e1 224 $link = $context->get_url();
848fe203
PS
225 }
226 parent::__construct($errormessage, $stringfile, $link, $capabilityname);
9a0df45a 227 }
228}
229
655bbf51 230/**
cce1b0b9 231 * Exception indicating programming error, must be fixed by a programer. For example
232 * a core API might throw this type of exception if a plugin calls it incorrectly.
b37eac91 233 *
47d2216e
PS
234 * @package core
235 * @subpackage lib
236 * @copyright 2008 Petr Skoda {@link http://skodak.org}
237 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
655bbf51 238 */
239class coding_exception extends moodle_exception {
655bbf51 240 /**
241 * Constructor
242 * @param string $hint short description of problem
243 * @param string $debuginfo detailed information how to fix problem
244 */
245 function __construct($hint, $debuginfo=null) {
246 parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
a3f7cbf6 247 }
248}
249
250/**
251 * Exception indicating malformed parameter problem.
252 * This exception is not supposed to be thrown when processing
253 * user submitted data in forms. It is more suitable
254 * for WS and other low level stuff.
47d2216e
PS
255 *
256 * @package core
257 * @subpackage lib
258 * @copyright 2009 Petr Skoda {@link http://skodak.org}
259 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
a3f7cbf6 260 */
261class invalid_parameter_exception extends moodle_exception {
262 /**
263 * Constructor
264 * @param string $debuginfo some detailed information
265 */
266 function __construct($debuginfo=null) {
267 parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
655bbf51 268 }
269}
270
d07ff72d 271/**
272 * Exception indicating malformed response problem.
273 * This exception is not supposed to be thrown when processing
274 * user submitted data in forms. It is more suitable
275 * for WS and other low level stuff.
276 */
277class invalid_response_exception extends moodle_exception {
278 /**
279 * Constructor
280 * @param string $debuginfo some detailed information
281 */
282 function __construct($debuginfo=null) {
283 parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
284 }
285}
286
cce1b0b9 287/**
1387fcdd 288 * An exception that indicates something really weird happened. For example,
cce1b0b9 289 * if you do switch ($context->contextlevel), and have one case for each
290 * CONTEXT_... constant. You might throw an invalid_state_exception in the
f630a546 291 * default case, to just in case something really weird is going on, and
8dc0ae8f 292 * $context->contextlevel is invalid - rather than ignoring this possibility.
b37eac91 293 *
47d2216e
PS
294 * @package core
295 * @subpackage lib
296 * @copyright 2009 onwards Martin Dougiamas {@link http://moodle.com}
297 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
cce1b0b9 298 */
299class invalid_state_exception extends moodle_exception {
300 /**
301 * Constructor
302 * @param string $hint short description of problem
303 * @param string $debuginfo optional more detailed information
304 */
305 function __construct($hint, $debuginfo=null) {
306 parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
307 }
308}
309
4031f6a2
PS
310/**
311 * An exception that indicates incorrect permissions in $CFG->dataroot
312 *
313 * @package core
314 * @subpackage lib
315 * @copyright 2010 Petr Skoda {@link http://skodak.org}
316 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
317 */
318class invalid_dataroot_permissions extends moodle_exception {
319 /**
320 * Constructor
321 * @param string $debuginfo optional more detailed information
322 */
323 function __construct($debuginfo = NULL) {
324 parent::__construct('invaliddatarootpermissions', 'error', '', NULL, $debuginfo);
325 }
326}
327
cbad562e
PS
328/**
329 * An exception that indicates that file can not be served
330 *
331 * @package core
332 * @subpackage lib
333 * @copyright 2010 Petr Skoda {@link http://skodak.org}
334 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
335 */
336class file_serving_exception extends moodle_exception {
337 /**
338 * Constructor
339 * @param string $debuginfo optional more detailed information
340 */
341 function __construct($debuginfo = NULL) {
342 parent::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
343 }
344}
345
251387d0 346/**
188458a6 347 * Default exception handler.
fd1a792e 348 *
30fa50d0 349 * @param Exception $ex
c19bc39c 350 * @return void -does not return. Terminates execution!
251387d0 351 */
c19bc39c 352function default_exception_handler($ex) {
f0202ae9 353 global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION, $PAGE;
1fbdf76d 354
355 // detect active db transactions, rollback and log as error
695c5ec4 356 abort_all_db_transactions();
1fe1d104 357
d9e07264 358 if (($ex instanceof required_capability_exception) && !CLI_SCRIPT && !AJAX_SCRIPT && !empty($CFG->autologinguests) && !empty($USER->autologinguest)) {
f0202ae9 359 $SESSION->wantsurl = qualified_me();
d9e07264
SH
360 redirect(get_login_url());
361 }
362
c19bc39c 363 $info = get_exception_info($ex);
34a2777c 364
1fef1de5
BH
365 // If we already tried to send the header remove it, the content length
366 // should be either empty or the length of the error page.
367 @header_remove('Content-Length');
368
c19bc39c 369 if (is_early_init($info->backtrace)) {
e9e567f3 370 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
b7009474 371 } else {
df272345
EL
372 if (debugging('', DEBUG_MINIMAL)) {
373 $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
374 error_log($logerrmsg);
375 }
376
3c1ea58b 377 try {
a56c457e
PS
378 if ($DB) {
379 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
380 $DB->set_debug(0);
381 }
c9a4d37c
JO
382 if (AJAX_SCRIPT) {
383 // If we are in an AJAX script we don't want to use PREFERRED_RENDERER_TARGET.
384 // Because we know we will want to use ajax format.
168635fb 385 $renderer = new core_renderer_ajax($PAGE, 'ajax');
c9a4d37c
JO
386 } else {
387 $renderer = $OUTPUT;
388 }
389 echo $renderer->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo,
9201a00a 390 $info->errorcode);
d74b7e42
TL
391 } catch (Exception $e) {
392 $out_ex = $e;
393 } catch (Throwable $e) {
1766e6a1
MG
394 // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
395 $out_ex = $e;
d74b7e42
TL
396 }
397
398 if (isset($out_ex)) {
3c1ea58b 399 // default exception handler MUST not throw any exceptions!!
2e9b772f 400 // 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
3c1ea58b 401 // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
1adaa404
PS
402 if (CLI_SCRIPT or AJAX_SCRIPT) {
403 // just ignore the error and send something back using the safest method
e9e567f3 404 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
1adaa404
PS
405 } else {
406 echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
407 $outinfo = get_exception_info($out_ex);
408 echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
409 }
3c1ea58b 410 }
7544d13c 411 }
412
34a2777c 413 exit(1); // General error code
414}
415
85ba1e78
PS
416/**
417 * Default error handler, prevents some white screens.
418 * @param int $errno
419 * @param string $errstr
420 * @param string $errfile
421 * @param int $errline
422 * @param array $errcontext
423 * @return bool false means use default error handler
424 */
425function default_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
426 if ($errno == 4096) {
427 //fatal catchable error
428 throw new coding_exception('PHP catchable fatal error', $errstr);
429 }
430 return false;
431}
432
695c5ec4
PS
433/**
434 * Unconditionally abort all database transactions, this function
435 * should be called from exception handlers only.
436 * @return void
437 */
438function abort_all_db_transactions() {
439 global $CFG, $DB, $SCRIPT;
440
d5a8d9aa 441 // default exception handler MUST not throw any exceptions!!
03221650 442
695c5ec4
PS
443 if ($DB && $DB->is_transaction_started()) {
444 error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
d5a8d9aa
PS
445 // note: transaction blocks should never change current $_SESSION
446 $DB->force_transaction_rollback();
695c5ec4
PS
447 }
448}
449
b7009474 450/**
50764d37
PS
451 * This function encapsulates the tests for whether an exception was thrown in
452 * early init -- either during setup.php or during init of $OUTPUT.
b7009474 453 *
454 * If another exception is thrown then, and if we do not take special measures,
455 * we would just get a very cryptic message "Exception thrown without a stack
456 * frame in Unknown on line 0". That makes debugging very hard, so we do take
457 * special measures in default_exception_handler, with the help of this function.
458 *
459 * @param array $backtrace the stack trace to analyse.
460 * @return boolean whether the stack trace is somewhere in output initialisation.
461 */
50764d37 462function is_early_init($backtrace) {
b7009474 463 $dangerouscode = array(
464 array('function' => 'header', 'type' => '->'),
465 array('class' => 'bootstrap_renderer'),
1fcf0ca8 466 array('file' => __DIR__.'/setup.php'),
b7009474 467 );
468 foreach ($backtrace as $stackframe) {
469 foreach ($dangerouscode as $pattern) {
470 $matches = true;
471 foreach ($pattern as $property => $value) {
472 if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
473 $matches = false;
474 }
475 }
476 if ($matches) {
477 return true;
478 }
479 }
480 }
481 return false;
482}
483
34a2777c 484/**
cbf05caa
PS
485 * Abort execution by throwing of a general exception,
486 * default exception handler displays the error message in most cases.
34a2777c 487 *
488 * @param string $errorcode The name of the language string containing the error message.
489 * Normally this should be in the error.php lang file.
490 * @param string $module The language file to get the error message from.
491 * @param string $link The url where the user will be prompted to continue.
492 * If no url is provided the user will be directed to the site index page.
493 * @param object $a Extra words and phrases that might be required in the error string
cbf05caa
PS
494 * @param string $debuginfo optional debugging information
495 * @return void, always throws exception!
34a2777c 496 */
cbf05caa
PS
497function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
498 throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
34a2777c 499}
500
501/**
c19bc39c
PS
502 * Returns detailed information about specified exception.
503 * @param exception $ex
504 * @return object
34a2777c 505 */
c19bc39c 506function get_exception_info($ex) {
34a2777c 507 global $CFG, $DB, $SESSION;
508
c19bc39c
PS
509 if ($ex instanceof moodle_exception) {
510 $errorcode = $ex->errorcode;
511 $module = $ex->module;
512 $a = $ex->a;
513 $link = $ex->link;
514 $debuginfo = $ex->debuginfo;
515 } else {
516 $errorcode = 'generalexceptionmessage';
517 $module = 'error';
518 $a = $ex->getMessage();
519 $link = '';
98984c09 520 $debuginfo = '';
34a2777c 521 }
522
fb71453d
AD
523 // Append the error code to the debug info to make grepping and googling easier
524 $debuginfo .= PHP_EOL."Error code: $errorcode";
525
c19bc39c
PS
526 $backtrace = $ex->getTrace();
527 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
528 array_unshift($backtrace, $place);
529
c84a2dbe 530 // Be careful, no guarantee moodlelib.php is loaded.
34a2777c 531 if (empty($module) || $module == 'moodle' || $module == 'core') {
532 $module = 'error';
533 }
fb71453d
AD
534 // Search for the $errorcode's associated string
535 // If not found, append the contents of $a to $debuginfo so helpful information isn't lost
4f6be42c
DM
536 if (function_exists('get_string_manager')) {
537 if (get_string_manager()->string_exists($errorcode, $module)) {
538 $message = get_string($errorcode, $module, $a);
539 } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
c84a2dbe 540 // Search in moodle file if error specified - needed for backwards compatibility
541 $message = get_string($errorcode, 'moodle', $a);
4f6be42c
DM
542 } else {
543 $message = $module . '/' . $errorcode;
fb71453d 544 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
c84a2dbe 545 }
546 } else {
547 $message = $module . '/' . $errorcode;
fb71453d 548 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
c84a2dbe 549 }
550
8d220cb5
MN
551 // Remove some absolute paths from message and debugging info.
552 $searches = array();
553 $replaces = array();
846422a9 554 $cfgnames = array('backuptempdir', 'tempdir', 'cachedir', 'localcachedir', 'themedir', 'dataroot', 'dirroot');
8d220cb5
MN
555 foreach ($cfgnames as $cfgname) {
556 if (property_exists($CFG, $cfgname)) {
557 $searches[] = $CFG->$cfgname;
558 $replaces[] = "[$cfgname]";
559 }
560 }
561 if (!empty($searches)) {
562 $message = str_replace($searches, $replaces, $message);
563 $debuginfo = str_replace($searches, $replaces, $debuginfo);
564 }
565
c84a2dbe 566 // Be careful, no guarantee weblib.php is loaded.
567 if (function_exists('clean_text')) {
568 $message = clean_text($message);
569 } else {
570 $message = htmlspecialchars($message);
34a2777c 571 }
34a2777c 572
573 if (!empty($CFG->errordocroot)) {
eea3341d 574 $errordoclink = $CFG->errordocroot . '/en/';
34a2777c 575 } else {
df272345
EL
576 // Only if the function is available. May be not for early errors.
577 if (function_exists('current_language')) {
578 $errordoclink = get_docs_url();
579 } else {
580 $errordoclink = 'https://docs.moodle.org/en/';
581 }
34a2777c 582 }
eea3341d 583
34a2777c 584 if ($module === 'error') {
585 $modulelink = 'moodle';
0ae8f5fc 586 } else {
34a2777c 587 $modulelink = $module;
251387d0 588 }
eea3341d 589 $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
34a2777c 590
d4a03c00 591 if (empty($link)) {
34a2777c 592 if (!empty($SESSION->fromurl)) {
593 $link = $SESSION->fromurl;
594 unset($SESSION->fromurl);
595 } else {
596 $link = $CFG->wwwroot .'/';
597 }
598 }
599
db200a8e
FM
600 // When printing an error the continue button should never link offsite.
601 // We cannot use clean_param() here as it is not guaranteed that it has been loaded yet.
db200a8e
FM
602 if (stripos($link, $CFG->wwwroot) === 0) {
603 // Internal HTTP, all good.
db200a8e
FM
604 } else {
605 // External link spotted!
606 $link = $CFG->wwwroot . '/';
c8d3345c
PS
607 }
608
365a5941 609 $info = new stdClass();
c19bc39c
PS
610 $info->message = $message;
611 $info->errorcode = $errorcode;
612 $info->backtrace = $backtrace;
613 $info->link = $link;
614 $info->moreinfourl = $moreinfourl;
615 $info->a = $a;
616 $info->debuginfo = $debuginfo;
30fa50d0 617
c19bc39c 618 return $info;
34a2777c 619}
620
ad3532de 621/**
c7321899 622 * Generate a V4 UUID.
ad3532de 623 *
c7321899 624 * Unique is hard. Very hard. Attempt to use the PECL UUID function if available, and if not then revert to
ad3532de
AN
625 * constructing the uuid using mt_rand.
626 *
627 * It is important that this token is not solely based on time as this could lead
628 * to duplicates in a clustered environment (especially on VMs due to poor time precision).
629 *
c7321899
MS
630 * @see https://tools.ietf.org/html/rfc4122
631 *
632 * @deprecated since Moodle 3.8 MDL-61038 - please do not use this function any more.
633 * @see \core\uuid::generate()
634 *
ad3532de
AN
635 * @return string The uuid.
636 */
637function generate_uuid() {
c7321899
MS
638 debugging('generate_uuid() is deprecated. Please use \core\uuid::generate() instead.', DEBUG_DEVELOPER);
639 return \core\uuid::generate();
ad3532de
AN
640}
641
eea3341d 642/**
32c842e2 643 * Returns the Moodle Docs URL in the users language for a given 'More help' link.
eea3341d 644 *
32c842e2
TH
645 * There are three cases:
646 *
647 * 1. In the normal case, $path will be a short relative path 'component/thing',
648 * like 'mod/folder/view' 'group/import'. This gets turned into an link to
649 * MoodleDocs in the user's language, and for the appropriate Moodle version.
650 * E.g. 'group/import' may become 'http://docs.moodle.org/2x/en/group/import'.
651 * The 'http://docs.moodle.org' bit comes from $CFG->docroot.
652 *
653 * This is the only option that should be used in standard Moodle code. The other
654 * two options have been implemented because they are useful for third-party plugins.
655 *
e2554394 656 * 2. $path may be an absolute URL, starting http:// or https://. In this case,
32c842e2
TH
657 * the link is used as is.
658 *
659 * 3. $path may start %%WWWROOT%%, in which case that is replaced by
660 * $CFG->wwwroot to make the link.
661 *
662 * @param string $path the place to link to. See above for details.
663 * @return string The MoodleDocs URL in the user's language. for example @link http://docs.moodle.org/2x/en/$path}
eea3341d 664 */
32c842e2 665function get_docs_url($path = null) {
eea3341d 666 global $CFG;
32c842e2
TH
667
668 // Absolute URLs are used unmodified.
669 if (substr($path, 0, 7) === 'http://' || substr($path, 0, 8) === 'https://') {
670 return $path;
671 }
672
673 // Paths starting %%WWWROOT%% have that replaced by $CFG->wwwroot.
674 if (substr($path, 0, 11) === '%%WWWROOT%%') {
675 return $CFG->wwwroot . substr($path, 11);
676 }
677
678 // Otherwise we do the normal case, and construct a MoodleDocs URL relative to $CFG->docroot.
679
ed01233a
AB
680 // Check that $CFG->branch has been set up, during installation it won't be.
681 if (empty($CFG->branch)) {
32c842e2 682 // It's not there yet so look at version.php.
eea3341d
AB
683 include($CFG->dirroot.'/version.php');
684 } else {
32c842e2 685 // We can use $CFG->branch and avoid having to include version.php.
ed01233a 686 $branch = $CFG->branch;
eea3341d 687 }
ed01233a
AB
688 // ensure branch is valid.
689 if (!$branch) {
eea3341d
AB
690 // We should never get here but in case we do lets set $branch to .
691 // the smart one's will know that this is the current directory
692 // and the smarter ones will know that there is some smart matching
693 // that will ensure people end up at the latest version of the docs.
694 $branch = '.';
695 }
9452cae8
DN
696 if (empty($CFG->doclang)) {
697 $lang = current_language();
eea3341d 698 } else {
9452cae8
DN
699 $lang = $CFG->doclang;
700 }
701 $end = '/' . $branch . '/' . $lang . '/' . $path;
702 if (empty($CFG->docroot)) {
703 return 'http://docs.moodle.org'. $end;
704 } else {
705 return $CFG->docroot . $end ;
eea3341d
AB
706 }
707}
708
34a2777c 709/**
710 * Formats a backtrace ready for output.
711 *
1e17258b
JL
712 * This function does not include function arguments because they could contain sensitive information
713 * not suitable to be exposed in a response.
714 *
34a2777c 715 * @param array $callers backtrace array, as returned by debug_backtrace().
716 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
717 * @return string formatted backtrace, ready for output.
718 */
719function format_backtrace($callers, $plaintext = false) {
a0394be4 720 // do not use $CFG->dirroot because it might not be available in destructors
1fcf0ca8 721 $dirroot = dirname(__DIR__);
30fa50d0 722
34a2777c 723 if (empty($callers)) {
724 return '';
725 }
726
3e76c7fa 727 $from = $plaintext ? '' : '<ul style="text-align: left" data-rel="backtrace">';
34a2777c 728 foreach ($callers as $caller) {
729 if (!isset($caller['line'])) {
730 $caller['line'] = '?'; // probably call_user_func()
731 }
732 if (!isset($caller['file'])) {
733 $caller['file'] = 'unknownfile'; // probably call_user_func()
734 }
735 $from .= $plaintext ? '* ' : '<li>';
736 $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
737 if (isset($caller['function'])) {
738 $from .= ': call to ';
739 if (isset($caller['class'])) {
740 $from .= $caller['class'] . $caller['type'];
741 }
742 $from .= $caller['function'] . '()';
743 } else if (isset($caller['exception'])) {
744 $from .= ': '.$caller['exception'].' thrown';
745 }
746 $from .= $plaintext ? "\n" : '</li>';
747 }
748 $from .= $plaintext ? '' : '</ul>';
749
750 return $from;
251387d0 751}
6a525ce2 752
cbad562e
PS
753/**
754 * This function makes the return value of ini_get consistent if you are
755 * setting server directives through the .htaccess file in apache.
756 *
757 * Current behavior for value set from php.ini On = 1, Off = [blank]
758 * Current behavior for value set from .htaccess On = On, Off = Off
759 * Contributed by jdell @ unr.edu
760 *
761 * @param string $ini_get_arg The argument to get
762 * @return bool True for on false for not
763 */
764function ini_get_bool($ini_get_arg) {
765 $temp = ini_get($ini_get_arg);
766
767 if ($temp == '1' or strtolower($temp) == 'on') {
768 return true;
769 }
770 return false;
771}
772
fbf2c91e 773/**
774 * This function verifies the sanity of PHP configuration
775 * and stops execution if anything critical found.
776 */
777function setup_validate_php_configuration() {
778 // this must be very fast - no slow checks here!!!
779
fbf2c91e 780 if (ini_get_bool('session.auto_start')) {
781 print_error('sessionautostartwarning', 'admin');
782 }
fbf2c91e 783}
784
12bb0c3e 785/**
96f81ea3
PS
786 * Initialise global $CFG variable.
787 * @private to be used only from lib/setup.php
12bb0c3e
PS
788 */
789function initialise_cfg() {
790 global $CFG, $DB;
8b8aa060 791
96f81ea3
PS
792 if (!$DB) {
793 // This should not happen.
794 return;
795 }
796
12bb0c3e 797 try {
96f81ea3 798 $localcfg = get_config('core');
69ac5d47 799 } catch (dml_exception $e) {
96f81ea3
PS
800 // Most probably empty db, going to install soon.
801 return;
802 }
803
804 foreach ($localcfg as $name => $value) {
805 // Note that get_config() keeps forced settings
806 // and normalises values to string if possible.
807 $CFG->{$name} = $value;
12bb0c3e
PS
808 }
809}
810
11e7b506 811/**
75781f87 812 * Initialises $FULLME and friends. Private function. Should only be called from
813 * setup.php.
11e7b506 814 */
815function initialise_fullme() {
f0f8f9a7 816 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
11e7b506 817
75781f87 818 // Detect common config error.
84b88cfd 819 if (substr($CFG->wwwroot, -1) == '/') {
820 print_error('wwwrootslash', 'error');
821 }
822
75781f87 823 if (CLI_SCRIPT) {
824 initialise_fullme_cli();
825 return;
37ccf1fe 826 }
cd1eb7ce
JO
827 if (!empty($CFG->overridetossl)) {
828 if (strpos($CFG->wwwroot, 'http://') === 0) {
829 $CFG->wwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
830 } else {
831 unset_config('overridetossl');
832 }
833 }
11e7b506 834
75781f87 835 $rurl = setup_get_remote_url();
f0f8f9a7
PS
836 $wwwroot = parse_url($CFG->wwwroot.'/');
837
838 if (empty($rurl['host'])) {
839 // missing host in request header, probably not a real browser, let's ignore them
840
841 } else if (!empty($CFG->reverseproxy)) {
842 // $CFG->reverseproxy specifies if reverse proxy server used
843 // Used in load balancing scenarios.
844 // Do not abuse this to try to solve lan/wan access problems!!!!!
845
846 } else {
677b2e79
DM
847 if (($rurl['host'] !== $wwwroot['host']) or
848 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port']) or
849 (strpos($rurl['path'], $wwwroot['path']) !== 0)) {
850
f0f8f9a7
PS
851 // Explain the problem and redirect them to the right URL
852 if (!defined('NO_MOODLE_COOKIES')) {
853 define('NO_MOODLE_COOKIES', true);
854 }
e9e567f3 855 // The login/token.php script should call the correct url/port.
31d5b2dd 856 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
e9e567f3
JM
857 $wwwrootport = empty($wwwroot['port'])?'':$wwwroot['port'];
858 $calledurl = $rurl['host'];
859 if (!empty($rurl['port'])) {
860 $calledurl .= ':'. $rurl['port'];
861 }
862 $correcturl = $wwwroot['host'];
863 if (!empty($wwwrootport)) {
864 $correcturl .= ':'. $wwwrootport;
865 }
866 throw new moodle_exception('requirecorrectaccess', 'error', '', null,
867 'You called ' . $calledurl .', you should have called ' . $correcturl);
868 }
f0f8f9a7
PS
869 redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
870 }
871 }
11e7b506 872
75781f87 873 // Check that URL is under $CFG->wwwroot.
874 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
875 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
876 } else {
877 // Probably some weird external script
878 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
11e7b506 879 return;
880 }
881
75781f87 882 // $CFG->sslproxy specifies if external SSL appliance is used
883 // (That is, the Moodle server uses http, with an external box translating everything to https).
884 if (empty($CFG->sslproxy)) {
56048f83 885 if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
d4d41469
DW
886 if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
887 print_error('sslonlyaccess', 'error');
888 } else {
889 redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
890 }
75781f87 891 }
56048f83
PS
892 } else {
893 if ($wwwroot['scheme'] !== 'https') {
894 throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
895 }
74162134 896 $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
1e31f118 897 $_SERVER['HTTPS'] = 'on'; // Override $_SERVER to help external libraries with their HTTPS detection.
12938e89 898 $_SERVER['SERVER_PORT'] = 443; // Assume default ssl port for the proxy.
75781f87 899 }
900
75781f87 901 // hopefully this will stop all those "clever" admins trying to set up moodle
902 // with two different addresses in intranet and Internet
e0f2718f 903 if (!empty($CFG->reverseproxy) && $rurl['host'] === $wwwroot['host']) {
75781f87 904 print_error('reverseproxyabused', 'error');
905 }
906
907 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
908 if (!empty($wwwroot['port'])) {
909 $hostandport .= ':'.$wwwroot['port'];
910 }
911
912 $FULLSCRIPT = $hostandport . $rurl['path'];
913 $FULLME = $hostandport . $rurl['fullpath'];
914 $ME = $rurl['fullpath'];
75781f87 915}
916
917/**
918 * Initialises $FULLME and friends for command line scripts.
919 * This is a private method for use by initialise_fullme.
920 */
921function initialise_fullme_cli() {
80e30f25 922 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
923
75781f87 924 // Urls do not make much sense in CLI scripts
925 $backtrace = debug_backtrace();
926 $topfile = array_pop($backtrace);
927 $topfile = realpath($topfile['file']);
928 $dirroot = realpath($CFG->dirroot);
929
930 if (strpos($topfile, $dirroot) !== 0) {
931 // Probably some weird external script
932 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
933 } else {
934 $relativefile = substr($topfile, strlen($dirroot));
935 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
936 $SCRIPT = $FULLSCRIPT = $relativefile;
937 $FULLME = $ME = null;
938 }
939}
940
941/**
942 * Get the URL that PHP/the web server thinks it is serving. Private function
943 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
944 * @return array in the same format that parse_url returns, with the addition of
945 * a 'fullpath' element, which includes any slasharguments path.
946 */
947function setup_get_remote_url() {
11e7b506 948 $rurl = array();
e0f2718f
PS
949 if (isset($_SERVER['HTTP_HOST'])) {
950 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
951 } else {
952 $rurl['host'] = null;
953 }
11e7b506 954 $rurl['port'] = $_SERVER['SERVER_PORT'];
75781f87 955 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
2a9c0d05 956 $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ? 'http' : 'https';
11e7b506 957
958 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
959 //Apache server
f49b359b 960 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
7e13a265 961
3b1a3abc
MS
962 // Fixing a known issue with:
963 // - Apache versions lesser than 2.4.11
964 // - PHP deployed in Apache as PHP-FPM via mod_proxy_fcgi
965 // - PHP versions lesser than 5.6.3 and 5.5.18.
966 if (isset($_SERVER['PATH_INFO']) && (php_sapi_name() === 'fpm-fcgi') && isset($_SERVER['SCRIPT_NAME'])) {
967 $pathinfodec = rawurldecode($_SERVER['PATH_INFO']);
968 $lenneedle = strlen($pathinfodec);
969 // Checks whether SCRIPT_NAME ends with PATH_INFO, URL-decoded.
970 if (substr($_SERVER['SCRIPT_NAME'], -$lenneedle) === $pathinfodec) {
971 // This is the "Apache 2.4.10- running PHP-FPM via mod_proxy_fcgi" fingerprint,
972 // at least on CentOS 7 (Apache/2.4.6 PHP/5.4.16) and Ubuntu 14.04 (Apache/2.4.7 PHP/5.5.9)
973 // => SCRIPT_NAME contains 'slash arguments' data too, which is wrongly exposed via PATH_INFO as URL-encoded.
974 // Fix both $_SERVER['PATH_INFO'] and $_SERVER['SCRIPT_NAME'].
975 $lenhaystack = strlen($_SERVER['SCRIPT_NAME']);
976 $pos = $lenhaystack - $lenneedle;
977 // Here $pos is greater than 0 but let's double check it.
978 if ($pos > 0) {
979 $_SERVER['PATH_INFO'] = $pathinfodec;
980 $_SERVER['SCRIPT_NAME'] = substr($_SERVER['SCRIPT_NAME'], 0, $pos);
981 }
982 }
983 }
984
11e7b506 985 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
199c1981 986 //IIS - needs a lot of tweaking to make it work
11e7b506 987 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
988
ce1cc198
MS
989 // NOTE: we should ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS.
990 // Since 2.0, we rely on IIS rewrite extensions like Helicon ISAPI_rewrite
991 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
992 // OR
993 // we rely on a proper IIS 6.0+ configuration: the 'FastCGIUtf8ServerVariables' registry key.
994 if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
995 // Check that PATH_INFO works == must not contain the script name.
996 if (strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === false) {
997 $rurl['fullpath'] .= clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
998 }
999 }
11e7b506 1000
ce1cc198 1001 if (isset($_SERVER['QUERY_STRING']) and $_SERVER['QUERY_STRING'] !== '') {
991ec2ee 1002 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
11e7b506 1003 }
1004 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
1005
f49b359b
PS
1006/* NOTE: following servers are not fully tested! */
1007
1008 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
1009 //lighttpd - not officially supported
f49b359b
PS
1010 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1011
1012 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
1013 //nginx - not officially supported
28ec73dc
PS
1014 if (!isset($_SERVER['SCRIPT_NAME'])) {
1015 die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
1016 }
f49b359b
PS
1017 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1018
199c1981
PS
1019 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
1020 //cherokee - not officially supported
199c1981
PS
1021 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1022
8b8aa060
PS
1023 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
1024 //zeus - not officially supported
8b8aa060
PS
1025 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1026
f49b359b
PS
1027 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
1028 //LiteSpeed - not officially supported
f49b359b
PS
1029 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1030
4e3e8464
PS
1031 } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
1032 //obscure name found on some servers - this is definitely not supported
1033 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1034
d860f1ad
PS
1035 } else if (strpos($_SERVER['SERVER_SOFTWARE'], 'PHP') === 0) {
1036 // built-in PHP Development Server
1037 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
1038
1039 } else {
75781f87 1040 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
11e7b506 1041 }
0ae36f66
PS
1042
1043 // sanitize the url a bit more, the encoding style may be different in vars above
1044 $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
1045 $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);
1046
75781f87 1047 return $rurl;
11e7b506 1048}
1049
a3777547
PS
1050/**
1051 * Try to work around the 'max_input_vars' restriction if necessary.
1052 */
1053function workaround_max_input_vars() {
1054 // Make sure this gets executed only once from lib/setup.php!
1055 static $executed = false;
1056 if ($executed) {
1057 debugging('workaround_max_input_vars() must be called only once!');
1058 return;
1059 }
1060 $executed = true;
1061
1062 if (!isset($_SERVER["CONTENT_TYPE"]) or strpos($_SERVER["CONTENT_TYPE"], 'multipart/form-data') !== false) {
1063 // Not a post or 'multipart/form-data' which is not compatible with "php://input" reading.
1064 return;
1065 }
1066
1067 if (!isloggedin() or isguestuser()) {
1068 // Only real users post huge forms.
1069 return;
1070 }
1071
1072 $max = (int)ini_get('max_input_vars');
1073
1074 if ($max <= 0) {
1075 // Most probably PHP < 5.3.9 that does not implement this limit.
1076 return;
1077 }
1078
1079 if ($max >= 200000) {
1080 // This value should be ok for all our forms, by setting it in php.ini
1081 // admins may prevent any unexpected regressions caused by this hack.
1082
1083 // Note there is no need to worry about DDoS caused by making this limit very high
1084 // because there are very many easier ways to DDoS any Moodle server.
1085 return;
1086 }
1087
6d4858d5 1088 // Worst case is advanced checkboxes which use up to two max_input_vars
1089 // slots for each entry in $_POST, because of sending two fields with the
1090 // same name. So count everything twice just in case.
1091 if (count($_POST, COUNT_RECURSIVE) * 2 < $max) {
a3777547
PS
1092 return;
1093 }
1094
1095 // Large POST request with enctype supported by php://input.
1096 // Parse php://input in chunks to bypass max_input_vars limit, which also applies to parse_str().
1097 $str = file_get_contents("php://input");
1098 if ($str === false or $str === '') {
1099 // Some weird error.
1100 return;
1101 }
1102
1103 $delim = '&';
484b43f4
MG
1104 $fun = function($p) use ($delim) {
1105 return implode($delim, $p);
1106 };
a3777547
PS
1107 $chunks = array_map($fun, array_chunk(explode($delim, $str), $max));
1108
6d4858d5 1109 // Clear everything from existing $_POST array, otherwise it might be included
1110 // twice (this affects array params primarily).
1111 foreach ($_POST as $key => $value) {
1112 unset($_POST[$key]);
1113 // Also clear from request array - but only the things that are in $_POST,
1114 // that way it will leave the things from a get request if any.
1115 unset($_REQUEST[$key]);
1116 }
1117
a3777547
PS
1118 foreach ($chunks as $chunk) {
1119 $values = array();
1120 parse_str($chunk, $values);
1121
a3777547
PS
1122 merge_query_params($_POST, $values);
1123 merge_query_params($_REQUEST, $values);
1124 }
1125}
1126
1127/**
1128 * Merge parsed POST chunks.
1129 *
1130 * NOTE: this is not perfect, but it should work in most cases hopefully.
1131 *
1132 * @param array $target
1133 * @param array $values
1134 */
1135function merge_query_params(array &$target, array $values) {
1136 if (isset($values[0]) and isset($target[0])) {
1137 // This looks like a split [] array, lets verify the keys are continuous starting with 0.
1138 $keys1 = array_keys($values);
1139 $keys2 = array_keys($target);
1140 if ($keys1 === array_keys($keys1) and $keys2 === array_keys($keys2)) {
1141 foreach ($values as $v) {
1142 $target[] = $v;
1143 }
1144 return;
1145 }
1146 }
1147 foreach ($values as $k => $v) {
1148 if (!isset($target[$k])) {
1149 $target[$k] = $v;
1150 continue;
1151 }
1152 if (is_array($target[$k]) and is_array($v)) {
1153 merge_query_params($target[$k], $v);
1154 continue;
1155 }
1156 // We should not get here unless there are duplicates in params.
1157 $target[$k] = $v;
1158 }
1159}
1160
d3f9f1f8 1161/**
1162 * Initializes our performance info early.
1163 *
1164 * Pairs up with get_performance_info() which is actually
251387d0 1165 * in moodlelib.php. This function is here so that we can
1166 * call it before all the libs are pulled in.
d3f9f1f8 1167 *
1168 * @uses $PERF
1169 */
1170function init_performance_info() {
1171
6fc4ad72 1172 global $PERF, $CFG, $USER;
251387d0 1173
365a5941 1174 $PERF = new stdClass();
d3f9f1f8 1175 $PERF->logwrites = 0;
1176 if (function_exists('microtime')) {
1177 $PERF->starttime = microtime();
c84a2dbe 1178 }
d3f9f1f8 1179 if (function_exists('memory_get_usage')) {
1180 $PERF->startmemory = memory_get_usage();
1181 }
1182 if (function_exists('posix_times')) {
251387d0 1183 $PERF->startposixtimes = posix_times();
d3f9f1f8 1184 }
1185}
1186
31a99877 1187/**
1188 * Indicates whether we are in the middle of the initial Moodle install.
1189 *
1190 * Very occasionally it is necessary avoid running certain bits of code before the
1191 * Moodle installation has completed. The installed flag is set in admin/index.php
1192 * after Moodle core and all the plugins have been installed, but just before
1193 * the person doing the initial install is asked to choose the admin password.
1194 *
1195 * @return boolean true if the initial install is not complete.
1196 */
1197function during_initial_install() {
1198 global $CFG;
1199 return empty($CFG->rolesactive);
1200}
1201
76f3815b 1202/**
1203 * Function to raise the memory limit to a new value.
1204 * Will respect the memory limit if it is higher, thus allowing
1205 * settings in php.ini, apache conf or command line switches
0f0f0768 1206 * to override it.
76f3815b 1207 *
0f0f0768
PS
1208 * The memory limit should be expressed with a constant
1209 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
1210 * It is possible to use strings or integers too (eg:'128M').
76f3815b 1211 *
0f0f0768
PS
1212 * @param mixed $newlimit the new memory limit
1213 * @return bool success
76f3815b 1214 */
11e7b506 1215function raise_memory_limit($newlimit) {
0f0f0768 1216 global $CFG;
76f3815b 1217
0f0f0768
PS
1218 if ($newlimit == MEMORY_UNLIMITED) {
1219 ini_set('memory_limit', -1);
1220 return true;
1221
1222 } else if ($newlimit == MEMORY_STANDARD) {
cd3059b1
PS
1223 if (PHP_INT_SIZE > 4) {
1224 $newlimit = get_real_size('128M'); // 64bit needs more memory
1225 } else {
1226 $newlimit = get_real_size('96M');
1227 }
0f0f0768
PS
1228
1229 } else if ($newlimit == MEMORY_EXTRA) {
cd3059b1
PS
1230 if (PHP_INT_SIZE > 4) {
1231 $newlimit = get_real_size('384M'); // 64bit needs more memory
1232 } else {
1233 $newlimit = get_real_size('256M');
1234 }
d827f7b8 1235 if (!empty($CFG->extramemorylimit)) {
0f0f0768
PS
1236 $extra = get_real_size($CFG->extramemorylimit);
1237 if ($extra > $newlimit) {
1238 $newlimit = $extra;
1239 }
1240 }
1241
1242 } else if ($newlimit == MEMORY_HUGE) {
975f8442 1243 // MEMORY_HUGE uses 2G or MEMORY_EXTRA, whichever is bigger.
0f0f0768 1244 $newlimit = get_real_size('2G');
975f8442 1245 if (!empty($CFG->extramemorylimit)) {
1246 $extra = get_real_size($CFG->extramemorylimit);
1247 if ($extra > $newlimit) {
1248 $newlimit = $extra;
1249 }
1250 }
0f0f0768
PS
1251
1252 } else {
1253 $newlimit = get_real_size($newlimit);
1254 }
1255
1256 if ($newlimit <= 0) {
1257 debugging('Invalid memory limit specified.');
76f3815b 1258 return false;
1259 }
1260
cbad562e 1261 $cur = ini_get('memory_limit');
76f3815b 1262 if (empty($cur)) {
1263 // if php is compiled without --enable-memory-limits
1264 // apparently memory_limit is set to ''
0f0f0768 1265 $cur = 0;
76f3815b 1266 } else {
1267 if ($cur == -1){
1268 return true; // unlimited mem!
1269 }
0f0f0768 1270 $cur = get_real_size($cur);
76f3815b 1271 }
1272
0f0f0768 1273 if ($newlimit > $cur) {
76f3815b 1274 ini_set('memory_limit', $newlimit);
7022dd39 1275 return true;
1276 }
1277 return false;
1278}
1279
1280/**
1281 * Function to reduce the memory limit to a new value.
1282 * Will respect the memory limit if it is lower, thus allowing
1283 * settings in php.ini, apache conf or command line switches
1284 * to override it
1285 *
1286 * The memory limit should be expressed with a string (eg:'64M')
1287 *
1288 * @param string $newlimit the new memory limit
1289 * @return bool
1290 */
f630a546 1291function reduce_memory_limit($newlimit) {
7022dd39 1292 if (empty($newlimit)) {
1293 return false;
1294 }
cbad562e 1295 $cur = ini_get('memory_limit');
7022dd39 1296 if (empty($cur)) {
1297 // if php is compiled without --enable-memory-limits
1298 // apparently memory_limit is set to ''
0f0f0768 1299 $cur = 0;
7022dd39 1300 } else {
1301 if ($cur == -1){
1302 return true; // unlimited mem!
1303 }
1304 $cur = get_real_size($cur);
1305 }
1306
1307 $new = get_real_size($newlimit);
1308 // -1 is smaller, but it means unlimited
1309 if ($new < $cur && $new != -1) {
1310 ini_set('memory_limit', $newlimit);
76f3815b 1311 return true;
1312 }
1313 return false;
1314}
1315
1316/**
1317 * Converts numbers like 10M into bytes.
1318 *
0f0f0768
PS
1319 * @param string $size The size to be converted
1320 * @return int
76f3815b 1321 */
0f0f0768 1322function get_real_size($size = 0) {
76f3815b 1323 if (!$size) {
1324 return 0;
1325 }
ddf98cca
JC
1326
1327 static $binaryprefixes = array(
1328 'K' => 1024,
1329 'k' => 1024,
1330 'M' => 1048576,
1331 'm' => 1048576,
1332 'G' => 1073741824,
1333 'g' => 1073741824,
1334 'T' => 1099511627776,
1335 't' => 1099511627776,
1336 );
1337
1338 if (preg_match('/^([0-9]+)([KMGT])/i', $size, $matches)) {
1339 return $matches[1] * $binaryprefixes[$matches[2]];
76f3815b 1340 }
ddf98cca
JC
1341
1342 return (int) $size;
76f3815b 1343}
1344
cbad562e 1345/**
871ed458
PS
1346 * Try to disable all output buffering and purge
1347 * all headers.
1348 *
34223e03 1349 * @access private to be called only from lib/setup.php !
cbad562e
PS
1350 * @return void
1351 */
1352function disable_output_buffering() {
1353 $olddebug = error_reporting(0);
1354
1355 // disable compression, it would prevent closing of buffers
1356 if (ini_get_bool('zlib.output_compression')) {
1357 ini_set('zlib.output_compression', 'Off');
1358 }
1359
1360 // try to flush everything all the time
1361 ob_implicit_flush(true);
1362
1363 // close all buffers if possible and discard any existing output
1364 // this can actually work around some whitespace problems in config.php
1365 while(ob_get_level()) {
1366 if (!ob_end_clean()) {
1367 // prevent infinite loop when buffer can not be closed
1368 break;
1369 }
1370 }
1371
99302c5e
PS
1372 // disable any other output handlers
1373 ini_set('output_handler', '');
1374
cbad562e 1375 error_reporting($olddebug);
cfd35ec8
BH
1376
1377 // Disable buffering in nginx.
1378 header('X-Accel-Buffering: no');
1379
cbad562e
PS
1380}
1381
5e39d7aa 1382/**
a011effb
AN
1383 * Check whether a major upgrade is needed.
1384 *
1385 * That is defined as an upgrade that changes something really fundamental
1386 * in the database, so nothing can possibly work until the database has
1387 * been updated, and that is defined by the hard-coded version number in
1388 * this function.
1389 *
1390 * @return bool
5e39d7aa 1391 */
a011effb 1392function is_major_upgrade_required() {
5e39d7aa 1393 global $CFG;
aae219ac 1394 $lastmajordbchanges = 2019050100.01;
a011effb
AN
1395
1396 $required = empty($CFG->version);
1397 $required = $required || (float)$CFG->version < $lastmajordbchanges;
1398 $required = $required || during_initial_install();
1399 $required = $required || !empty($CFG->adminsetuppending);
1400
1401 return $required;
1402}
1403
1404/**
1405 * Redirect to the Notifications page if a major upgrade is required, and
1406 * terminate the current user session.
1407 */
1408function redirect_if_major_upgrade_required() {
1409 global $CFG;
1410 if (is_major_upgrade_required()) {
5e39d7aa 1411 try {
d79d5ac2 1412 @\core\session\manager::terminate_current();
5e39d7aa 1413 } catch (Exception $e) {
1414 // Ignore any errors, redirect to upgrade anyway.
1415 }
a38c7a10 1416 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
5e39d7aa 1417 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
a38c7a10
PS
1418 @header('Location: ' . $url);
1419 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
5e39d7aa 1420 exit;
1421 }
1422}
1423
4202471a
MG
1424/**
1425 * Makes sure that upgrade process is not running
1426 *
1427 * To be inserted in the core functions that can not be called by pluigns during upgrade.
1428 * Core upgrade should not use any API functions at all.
1429 * See {@link http://docs.moodle.org/dev/Upgrade_API#Upgrade_code_restrictions}
1430 *
1431 * @throws moodle_exception if executed from inside of upgrade script and $warningonly is false
1432 * @param bool $warningonly if true displays a warning instead of throwing an exception
1433 * @return bool true if executed from outside of upgrade process, false if from inside upgrade process and function is used for warning only
1434 */
1435function upgrade_ensure_not_running($warningonly = false) {
1436 global $CFG;
1437 if (!empty($CFG->upgraderunning)) {
1438 if (!$warningonly) {
1439 throw new moodle_exception('cannotexecduringupgrade');
1440 } else {
1441 debugging(get_string('cannotexecduringupgrade', 'error'), DEBUG_DEVELOPER);
1442 return false;
1443 }
1444 }
1445 return true;
1446}
1447
d3f9f1f8 1448/**
4031f6a2
PS
1449 * Function to check if a directory exists and by default create it if not exists.
1450 *
1451 * Previously this was accepting paths only from dataroot, but we now allow
1452 * files outside of dataroot if you supply custom paths for some settings in config.php.
1453 * This function does not verify that the directory is writable.
d3f9f1f8 1454 *
0b9f2a02
PS
1455 * NOTE: this function uses current file stat cache,
1456 * please use clearstatcache() before this if you expect that the
1457 * directories may have been removed recently from a different request.
1458 *
4031f6a2
PS
1459 * @param string $dir absolute directory path
1460 * @param boolean $create directory if does not exist
1461 * @param boolean $recursive create directory recursively
1462 * @return boolean true if directory exists or created, false otherwise
d3f9f1f8 1463 */
4031f6a2 1464function check_dir_exists($dir, $create = true, $recursive = true) {
d3f9f1f8 1465 global $CFG;
1466
eb459f71 1467 umask($CFG->umaskpermissions);
d3f9f1f8 1468
4031f6a2
PS
1469 if (is_dir($dir)) {
1470 return true;
1471 }
d3f9f1f8 1472
4031f6a2
PS
1473 if (!$create) {
1474 return false;
d100b8a0 1475 }
1476
4031f6a2
PS
1477 return mkdir($dir, $CFG->directorypermissions, $recursive);
1478}
1479
70be2642
AN
1480/**
1481 * Create a new unique directory within the specified directory.
1482 *
1483 * @param string $basedir The directory to create your new unique directory within.
1484 * @param bool $exceptiononerror throw exception if error encountered
1485 * @return string The created directory
1486 * @throws invalid_dataroot_permissions
1487 */
1488function make_unique_writable_directory($basedir, $exceptiononerror = true) {
1489 if (!is_dir($basedir) || !is_writable($basedir)) {
1490 // The basedir is not writable. We will not be able to create the child directory.
1491 if ($exceptiononerror) {
1492 throw new invalid_dataroot_permissions($basedir . ' is not writable. Unable to create a unique directory within it.');
1493 } else {
1494 return false;
1495 }
1496 }
1497
1498 do {
1499 // Generate a new (hopefully unique) directory name.
c7321899 1500 $uniquedir = $basedir . DIRECTORY_SEPARATOR . \core\uuid::generate();
70be2642
AN
1501 } while (
1502 // Ensure that basedir is still writable - if we do not check, we could get stuck in a loop here.
1503 is_writable($basedir) &&
1504
1505 // Make the new unique directory. If the directory already exists, it will return false.
1506 !make_writable_directory($uniquedir, $exceptiononerror) &&
1507
1508 // Ensure that the directory now exists
1509 file_exists($uniquedir) && is_dir($uniquedir)
1510 );
1511
1512 // Check that the directory was correctly created.
1513 if (!file_exists($uniquedir) || !is_dir($uniquedir) || !is_writable($uniquedir)) {
1514 if ($exceptiononerror) {
1515 throw new invalid_dataroot_permissions('Unique directory creation failed.');
1516 } else {
1517 return false;
1518 }
1519 }
1520
1521 return $uniquedir;
1522}
1523
4031f6a2 1524/**
e6958907 1525 * Create a directory and make sure it is writable.
4031f6a2 1526 *
32db0f0d 1527 * @private
e6958907 1528 * @param string $dir the full path of the directory to be created
4031f6a2
PS
1529 * @param bool $exceptiononerror throw exception if error encountered
1530 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1531 */
e6958907 1532function make_writable_directory($dir, $exceptiononerror = true) {
4031f6a2
PS
1533 global $CFG;
1534
4031f6a2
PS
1535 if (file_exists($dir) and !is_dir($dir)) {
1536 if ($exceptiononerror) {
1537 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1538 } else {
1539 return false;
1540 }
1541 }
1542
eb459f71 1543 umask($CFG->umaskpermissions);
4031f6a2
PS
1544
1545 if (!file_exists($dir)) {
3c71c15c 1546 if (!@mkdir($dir, $CFG->directorypermissions, true)) {
e7451fb5
PS
1547 clearstatcache();
1548 // There might be a race condition when creating directory.
1549 if (!is_dir($dir)) {
1550 if ($exceptiononerror) {
1551 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1552 } else {
1553 debugging('Can not create directory: '.$dir, DEBUG_DEVELOPER);
1554 return false;
1555 }
d3f9f1f8 1556 }
d3f9f1f8 1557 }
1558 }
1559
4031f6a2
PS
1560 if (!is_writable($dir)) {
1561 if ($exceptiononerror) {
1562 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1563 } else {
1564 return false;
1565 }
1566 }
1567
1568 return $dir;
d3f9f1f8 1569}
1570
e6958907
TL
1571/**
1572 * Protect a directory from web access.
1573 * Could be extended in the future to support other mechanisms (e.g. other webservers).
1574 *
32db0f0d 1575 * @private
e6958907
TL
1576 * @param string $dir the full path of the directory to be protected
1577 */
1578function protect_directory($dir) {
eb459f71 1579 global $CFG;
e6958907
TL
1580 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1581 if (!file_exists("$dir/.htaccess")) {
1582 if ($handle = fopen("$dir/.htaccess", 'w')) { // For safety
1583 @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");
1584 @fclose($handle);
eb459f71 1585 @chmod("$dir/.htaccess", $CFG->filepermissions);
e6958907
TL
1586 }
1587 }
1588}
1589
1590/**
1591 * Create a directory under dataroot and make sure it is writable.
32db0f0d 1592 * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
e6958907
TL
1593 *
1594 * @param string $directory the full path of the directory to be created under $CFG->dataroot
1595 * @param bool $exceptiononerror throw exception if error encountered
1596 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1597 */
1598function make_upload_directory($directory, $exceptiononerror = true) {
1599 global $CFG;
32db0f0d
PS
1600
1601 if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1602 debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1603
1604 } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
85b38061
PS
1605 debugging('Use make_cache_directory() for creation of cache directory and $CFG->cachedir to get the location.');
1606
1607 } else if (strpos($directory, 'localcache/') === 0 or $directory === 'localcache') {
1608 debugging('Use make_localcache_directory() for creation of local cache directory and $CFG->localcachedir to get the location.');
32db0f0d
PS
1609 }
1610
e6958907
TL
1611 protect_directory($CFG->dataroot);
1612 return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1613}
1614
70be2642
AN
1615/**
1616 * Get a per-request storage directory in the tempdir.
1617 *
1618 * The directory is automatically cleaned up during the shutdown handler.
1619 *
cca12f68
AN
1620 * @param bool $exceptiononerror throw exception if error encountered
1621 * @param bool $forcecreate Force creation of a new parent directory
1622 * @return string Returns full path to directory if successful, false if not; may throw exception
70be2642 1623 */
cca12f68 1624function get_request_storage_directory($exceptiononerror = true, bool $forcecreate = false) {
70be2642
AN
1625 global $CFG;
1626
1627 static $requestdir = null;
1628
cca12f68
AN
1629 $writabledirectoryexists = (null !== $requestdir);
1630 $writabledirectoryexists = $writabledirectoryexists && file_exists($requestdir);
1631 $writabledirectoryexists = $writabledirectoryexists && is_dir($requestdir);
1632 $writabledirectoryexists = $writabledirectoryexists && is_writable($requestdir);
1633 $createnewdirectory = $forcecreate || !$writabledirectoryexists;
1634
1635 if ($createnewdirectory) {
70be2642
AN
1636 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1637 check_dir_exists($CFG->localcachedir, true, true);
1638 protect_directory($CFG->localcachedir);
1639 } else {
1640 protect_directory($CFG->dataroot);
1641 }
1642
cca12f68 1643 if ($dir = make_unique_writable_directory($CFG->localcachedir, $exceptiononerror)) {
70be2642 1644 // Register a shutdown handler to remove the directory.
cca12f68 1645 \core_shutdown_manager::register_function('remove_dir', [$dir]);
70be2642 1646 }
cca12f68
AN
1647
1648 $requestdir = $dir;
70be2642
AN
1649 }
1650
1651 return $requestdir;
1652}
1653
1654/**
1655 * Create a per-request directory and make sure it is writable.
1656 * This can only be used during the current request and will be tidied away
1657 * automatically afterwards.
1658 *
cca12f68 1659 * A new, unique directory is always created within a shared base request directory.
70be2642 1660 *
cca12f68
AN
1661 * In some exceptional cases an alternative base directory may be required. This can be accomplished using the
1662 * $forcecreate parameter. Typically this will only be requried where the file may be required during a shutdown handler
1663 * which may or may not be registered after a previous request directory has been created.
1664 *
1665 * @param bool $exceptiononerror throw exception if error encountered
1666 * @param bool $forcecreate Force creation of a new parent directory
1667 * @return string The full path to directory if successful, false if not; may throw exception
70be2642 1668 */
cca12f68
AN
1669function make_request_directory($exceptiononerror = true, bool $forcecreate = false) {
1670 $basedir = get_request_storage_directory($exceptiononerror, $forcecreate);
70be2642
AN
1671 return make_unique_writable_directory($basedir, $exceptiononerror);
1672}
1673
ef844148
MS
1674/**
1675 * Get the full path of a directory under $CFG->backuptempdir.
1676 *
1677 * @param string $directory the relative path of the directory under $CFG->backuptempdir
1678 * @return string|false Returns full path to directory given a valid string; otherwise, false.
1679 */
1680function get_backup_temp_directory($directory) {
1681 global $CFG;
1682 if (($directory === null) || ($directory === false)) {
1683 return false;
1684 }
1685 return "$CFG->backuptempdir/$directory";
1686}
1687
1688/**
1689 * Create a directory under $CFG->backuptempdir and make sure it is writable.
1690 *
1691 * Do not use for storing generic temp files - see make_temp_directory() instead for this purpose.
1692 *
1693 * Backup temporary files must be on a shared storage.
1694 *
1695 * @param string $directory the relative path of the directory to be created under $CFG->backuptempdir
1696 * @param bool $exceptiononerror throw exception if error encountered
1697 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1698 */
1699function make_backup_temp_directory($directory, $exceptiononerror = true) {
1700 global $CFG;
1701 if ($CFG->backuptempdir !== "$CFG->tempdir/backup") {
1702 check_dir_exists($CFG->backuptempdir, true, true);
1703 protect_directory($CFG->backuptempdir);
1704 } else {
1705 protect_directory($CFG->tempdir);
1706 }
1707 return make_writable_directory("$CFG->backuptempdir/$directory", $exceptiononerror);
1708}
1709
e6958907
TL
1710/**
1711 * Create a directory under tempdir and make sure it is writable.
70be2642
AN
1712 *
1713 * Where possible, please use make_request_directory() and limit the scope
1714 * of your data to the current HTTP request.
1715 *
1716 * Do not use for storing cache files - see make_cache_directory(), and
1717 * make_localcache_directory() instead for this purpose.
1718 *
1719 * Temporary files must be on a shared storage, and heavy usage is
1720 * discouraged due to the performance impact upon clustered environments.
e6958907
TL
1721 *
1722 * @param string $directory the full path of the directory to be created under $CFG->tempdir
1723 * @param bool $exceptiononerror throw exception if error encountered
1724 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1725 */
1726function make_temp_directory($directory, $exceptiononerror = true) {
1727 global $CFG;
adf0fc0e
PS
1728 if ($CFG->tempdir !== "$CFG->dataroot/temp") {
1729 check_dir_exists($CFG->tempdir, true, true);
1730 protect_directory($CFG->tempdir);
7a7edd21
PS
1731 } else {
1732 protect_directory($CFG->dataroot);
adf0fc0e 1733 }
e6958907
TL
1734 return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1735}
1736
1737/**
1738 * Create a directory under cachedir and make sure it is writable.
1739 *
85b38061
PS
1740 * Note: this cache directory is shared by all cluster nodes.
1741 *
e6958907
TL
1742 * @param string $directory the full path of the directory to be created under $CFG->cachedir
1743 * @param bool $exceptiononerror throw exception if error encountered
1744 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1745 */
1746function make_cache_directory($directory, $exceptiononerror = true) {
1747 global $CFG;
adf0fc0e
PS
1748 if ($CFG->cachedir !== "$CFG->dataroot/cache") {
1749 check_dir_exists($CFG->cachedir, true, true);
1750 protect_directory($CFG->cachedir);
7a7edd21
PS
1751 } else {
1752 protect_directory($CFG->dataroot);
adf0fc0e 1753 }
e6958907
TL
1754 return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1755}
1756
85b38061
PS
1757/**
1758 * Create a directory under localcachedir and make sure it is writable.
1759 * The files in this directory MUST NOT change, use revisions or content hashes to
1760 * work around this limitation - this means you can only add new files here.
1761 *
1762 * The content of this directory gets purged automatically on all cluster nodes
1763 * after calling purge_all_caches() before new data is written to this directory.
1764 *
1765 * Note: this local cache directory does not need to be shared by cluster nodes.
1766 *
1767 * @param string $directory the relative path of the directory to be created under $CFG->localcachedir
1768 * @param bool $exceptiononerror throw exception if error encountered
1769 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1770 */
1771function make_localcache_directory($directory, $exceptiononerror = true) {
1772 global $CFG;
1773
1774 make_writable_directory($CFG->localcachedir, $exceptiononerror);
1775
1776 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1777 protect_directory($CFG->localcachedir);
1778 } else {
1779 protect_directory($CFG->dataroot);
1780 }
1781
1782 if (!isset($CFG->localcachedirpurged)) {
1783 $CFG->localcachedirpurged = 0;
1784 }
1785 $timestampfile = "$CFG->localcachedir/.lastpurged";
1786
1787 if (!file_exists($timestampfile)) {
1788 touch($timestampfile);
1789 @chmod($timestampfile, $CFG->filepermissions);
1790
1791 } else if (filemtime($timestampfile) < $CFG->localcachedirpurged) {
1792 // This means our local cached dir was not purged yet.
1793 remove_dir($CFG->localcachedir, true);
1794 if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1795 protect_directory($CFG->localcachedir);
1796 }
1797 touch($timestampfile);
1798 @chmod($timestampfile, $CFG->filepermissions);
1799 clearstatcache();
1800 }
1801
1802 if ($directory === '') {
1803 return $CFG->localcachedir;
1804 }
1805
1806 return make_writable_directory("$CFG->localcachedir/$directory", $exceptiononerror);
1807}
1808
b940ca99
BH
1809/**
1810 * Webserver access user logging
1811 */
1812function set_access_log_user() {
1813 global $USER, $CFG;
1814 if ($USER && isset($USER->username)) {
1815 $logmethod = '';
1816 $logvalue = 0;
1817 if (!empty($CFG->apacheloguser) && function_exists('apache_note')) {
1818 $logmethod = 'apache';
1819 $logvalue = $CFG->apacheloguser;
1820 }
1821 if (!empty($CFG->headerloguser)) {
1822 $logmethod = 'header';
1823 $logvalue = $CFG->headerloguser;
1824 }
1825 if (!empty($logmethod)) {
1826 $loguserid = $USER->id;
1827 $logusername = clean_filename($USER->username);
1828 $logname = '';
1829 if (isset($USER->firstname)) {
1830 // We can assume both will be set
1831 // - even if to empty.
1832 $logname = clean_filename($USER->firstname . " " . $USER->lastname);
1833 }
1834 if (\core\session\manager::is_loggedinas()) {
1835 $realuser = \core\session\manager::get_realuser();
1836 $logusername = clean_filename($realuser->username." as ".$logusername);
1837 $logname = clean_filename($realuser->firstname." ".$realuser->lastname ." as ".$logname);
1838 $loguserid = clean_filename($realuser->id." as ".$loguserid);
1839 }
1840 switch ($logvalue) {
1841 case 3:
1842 $logname = $logusername;
1843 break;
1844 case 2:
1845 $logname = $logname;
1846 break;
1847 case 1:
1848 default:
1849 $logname = $loguserid;
1850 break;
1851 }
1852 if ($logmethod == 'apache') {
1853 apache_note('MOODLEUSER', $logname);
1854 }
1855
1856 if ($logmethod == 'header') {
1857 header("X-MOODLEUSER: $logname");
1858 }
1859 }
1860 }
1861}
1862
c84a2dbe 1863/**
1864 * This class solves the problem of how to initialise $OUTPUT.
1865 *
1866 * The problem is caused be two factors
1867 * <ol>
1868 * <li>On the one hand, we cannot be sure when output will start. In particular,
30fa50d0 1869 * an error, which needs to be displayed, could be thrown at any time.</li>
c84a2dbe 1870 * <li>On the other hand, we cannot be sure when we will have all the information
1871 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1872 * (potentially) depends on the current course, course categories, and logged in user.
1873 * It also depends on whether the current page requires HTTPS.</li>
1874 * </ol>
1875 *
1876 * So, it is hard to find a single natural place during Moodle script execution,
1877 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1878 * adopt the following strategy
1879 * <ol>
1880 * <li>We will initialise $OUTPUT the first time it is used.</li>
1881 * <li>If, after $OUTPUT has been initialised, the script tries to change something
7e0d6675 1882 * that $OUTPUT depends on, we throw an exception making it clear that the script
c84a2dbe 1883 * did something wrong.
1884 * </ol>
1885 *
1886 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1887 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1888 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1889 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1890 *
1891 * Note that this class is used before lib/outputlib.php has been loaded, so we
1387fcdd 1892 * must be careful referring to classes/functions from there, they may not be
c84a2dbe 1893 * defined yet, and we must avoid fatal errors.
1894 *
1895 * @copyright 2009 Tim Hunt
1896 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1897 * @since Moodle 2.0
1898 */
1899class bootstrap_renderer {
1900 /**
1901 * Handles re-entrancy. Without this, errors or debugging output that occur
1902 * during the initialisation of $OUTPUT, cause infinite recursion.
1903 * @var boolean
1904 */
1905 protected $initialising = false;
1906
b7009474 1907 /**
1908 * Have we started output yet?
1909 * @return boolean true if the header has been printed.
1910 */
1911 public function has_started() {
1912 return false;
1913 }
1914
41701ffd
PS
1915 /**
1916 * Constructor - to be used by core code only.
34223e03
SH
1917 * @param string $method The method to call
1918 * @param array $arguments Arguments to pass to the method being called
41701ffd
PS
1919 * @return string
1920 */
c84a2dbe 1921 public function __call($method, $arguments) {
b7009474 1922 global $OUTPUT, $PAGE;
c84a2dbe 1923
87b6851c 1924 $recursing = false;
1925 if ($method == 'notification') {
1387fcdd 1926 // Catch infinite recursion caused by debugging output during print_header.
87b6851c 1927 $backtrace = debug_backtrace();
1928 array_shift($backtrace);
1929 array_shift($backtrace);
50764d37 1930 $recursing = is_early_init($backtrace);
87b6851c 1931 }
1932
eb5bdb35
PS
1933 $earlymethods = array(
1934 'fatal_error' => 'early_error',
1935 'notification' => 'early_notification',
1936 );
1937
c84a2dbe 1938 // If lib/outputlib.php has been loaded, call it.
87b6851c 1939 if (!empty($PAGE) && !$recursing) {
eb5bdb35
PS
1940 if (array_key_exists($method, $earlymethods)) {
1941 //prevent PAGE->context warnings - exceptions might appear before we set any context
1942 $PAGE->set_context(null);
1943 }
b7009474 1944 $PAGE->initialise_theme_and_output();
1945 return call_user_func_array(array($OUTPUT, $method), $arguments);
c84a2dbe 1946 }
2142d492 1947
c84a2dbe 1948 $this->initialising = true;
eb5bdb35 1949
c84a2dbe 1950 // Too soon to initialise $OUTPUT, provide a couple of key methods.
c84a2dbe 1951 if (array_key_exists($method, $earlymethods)) {
1952 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1953 }
1954
1955 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1956 }
1957
1958 /**
1387fcdd 1959 * Returns nicely formatted error message in a div box.
f0f8f9a7
PS
1960 * @static
1961 * @param string $message error message
41701ffd
PS
1962 * @param string $moreinfourl (ignored in early errors)
1963 * @param string $link (ignored in early errors)
f0f8f9a7
PS
1964 * @param array $backtrace
1965 * @param string $debuginfo
30fa50d0 1966 * @return string
c84a2dbe 1967 */
3c1ea58b 1968 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
b7009474 1969 global $CFG;
1970
3c1ea58b
PS
1971 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1972border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1973width: 80%; -moz-border-radius: 20px; padding: 15px">
1974' . $message . '
1975</div>';
7383a7e2
SH
1976 // Check whether debug is set.
1977 $debug = (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER);
1978 // Also check we have it set in the config file. This occurs if the method to read the config table from the
1979 // database fails, reading from the config table is the first database interaction we have.
1980 $debug = $debug || (!empty($CFG->config_php_settings['debug']) && $CFG->config_php_settings['debug'] >= DEBUG_DEVELOPER );
1981 if ($debug) {
3c1ea58b 1982 if (!empty($debuginfo)) {
df272345
EL
1983 // Remove all nasty JS.
1984 if (function_exists('s')) { // Function may be not available for some early errors.
1985 $debuginfo = s($debuginfo);
1986 } else {
1987 // Because weblib is not available for these early errors, we
1988 // just duplicate s() code here to be safe.
1989 $debuginfo = preg_replace('/&amp;#(\d+|x[0-9a-f]+);/i', '&#$1;',
1990 htmlspecialchars($debuginfo, ENT_QUOTES | ENT_HTML401 | ENT_SUBSTITUTE));
1991 }
c5d18164
PS
1992 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1993 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
3c1ea58b
PS
1994 }
1995 if (!empty($backtrace)) {
1996 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1997 }
1998 }
1999
2000 return $content;
2001 }
2002
2003 /**
2004 * This function should only be called by this class, or from exception handlers
f0f8f9a7
PS
2005 * @static
2006 * @param string $message error message
41701ffd
PS
2007 * @param string $moreinfourl (ignored in early errors)
2008 * @param string $link (ignored in early errors)
f0f8f9a7 2009 * @param array $backtrace
41701ffd 2010 * @param string $debuginfo extra information for developers
3c1ea58b
PS
2011 * @return string
2012 */
e9e567f3 2013 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = null) {
1adaa404
PS
2014 global $CFG;
2015
2016 if (CLI_SCRIPT) {
2017 echo "!!! $message !!!\n";
2018 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
2019 if (!empty($debuginfo)) {
2020 echo "\nDebug info: $debuginfo";
2021 }
2022 if (!empty($backtrace)) {
2023 echo "\nStack trace: " . format_backtrace($backtrace, true);
2024 }
2025 }
2026 return;
2027
2028 } else if (AJAX_SCRIPT) {
2029 $e = new stdClass();
2030 $e->error = $message;
2031 $e->stacktrace = NULL;
2032 $e->debuginfo = NULL;
2033 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
2034 if (!empty($debuginfo)) {
2035 $e->debuginfo = $debuginfo;
2036 }
2037 if (!empty($backtrace)) {
2038 $e->stacktrace = format_backtrace($backtrace, true);
2039 }
2040 }
e9e567f3 2041 $e->errorcode = $errorcode;
8a7703ce 2042 @header('Content-Type: application/json; charset=utf-8');
1adaa404
PS
2043 echo json_encode($e);
2044 return;
2045 }
2046
c84a2dbe 2047 // In the name of protocol correctness, monitoring and performance
f22f1caf
PS
2048 // profiling, set the appropriate error headers for machine consumption.
2049 $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
2050 @header($protocol . ' 503 Service Unavailable');
c84a2dbe 2051
2052 // better disable any caching
2053 @header('Content-Type: text/html; charset=utf-8');
398862b9 2054 @header('X-UA-Compatible: IE=edge');
c84a2dbe 2055 @header('Cache-Control: no-store, no-cache, must-revalidate');
2056 @header('Cache-Control: post-check=0, pre-check=0', false);
2057 @header('Pragma: no-cache');
2058 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
2059 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
2060
5e39d7aa 2061 if (function_exists('get_string')) {
c84a2dbe 2062 $strerror = get_string('error');
2063 } else {
c84a2dbe 2064 $strerror = 'Error';
2065 }
2066
3c1ea58b 2067 $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
5e39d7aa 2068
2069 return self::plain_page($strerror, $content);
c84a2dbe 2070 }
2071
f0f8f9a7
PS
2072 /**
2073 * Early notification message
2074 * @static
34223e03 2075 * @param string $message
41701ffd 2076 * @param string $classes usually notifyproblem or notifysuccess
f0f8f9a7
PS
2077 * @return string
2078 */
c84a2dbe 2079 public static function early_notification($message, $classes = 'notifyproblem') {
2080 return '<div class="' . $classes . '">' . $message . '</div>';
2081 }
5e39d7aa 2082
f0f8f9a7
PS
2083 /**
2084 * Page should redirect message.
2085 * @static
34223e03 2086 * @param string $encodedurl redirect url
f0f8f9a7
PS
2087 * @return string
2088 */
5e39d7aa 2089 public static function plain_redirect_message($encodedurl) {
41701ffd 2090 $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
f0f8f9a7 2091 $encodedurl .'">'. get_string('continue') .'</a></div>';
a0a268d5 2092 return self::plain_page(get_string('redirect'), $message);
5e39d7aa 2093 }
2094
f0f8f9a7
PS
2095 /**
2096 * Early redirection page, used before full init of $PAGE global
2097 * @static
34223e03
SH
2098 * @param string $encodedurl redirect url
2099 * @param string $message redirect message
2100 * @param int $delay time in seconds
41701ffd 2101 * @return string redirect page
f0f8f9a7
PS
2102 */
2103 public static function early_redirect_message($encodedurl, $message, $delay) {
2104 $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
2105 $content = self::early_error_content($message, null, null, null);
2106 $content .= self::plain_redirect_message($encodedurl);
2107
2108 return self::plain_page(get_string('redirect'), $content, $meta);
2109 }
2110
2111 /**
2112 * Output basic html page.
2113 * @static
34223e03
SH
2114 * @param string $title page title
2115 * @param string $content page content
41701ffd
PS
2116 * @param string $meta meta tag
2117 * @return string html page
f0f8f9a7 2118 */
48e114a5 2119 public static function plain_page($title, $content, $meta = '') {
5e39d7aa 2120 if (function_exists('get_string') && function_exists('get_html_lang')) {
2121 $htmllang = get_html_lang();
2122 } else {
2123 $htmllang = '';
2124 }
2125
58a3a34e 2126 $footer = '';
df272345
EL
2127 if (function_exists('get_performance_info')) { // Function may be not available for some early errors.
2128 if (MDL_PERF_TEST) {
2129 $perfinfo = get_performance_info();
2130 $footer = '<footer>' . $perfinfo['html'] . '</footer>';
2131 }
58a3a34e
DM
2132 }
2133
48e114a5
PS
2134 return '<!DOCTYPE html>
2135<html ' . $htmllang . '>
5e39d7aa 2136<head>
2137<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
f0f8f9a7 2138'.$meta.'
5e39d7aa 2139<title>' . $title . '</title>
58a3a34e 2140</head><body>' . $content . $footer . '</body></html>';
5e39d7aa 2141 }
c84a2dbe 2142}