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