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