MDL-34035 - fix typo in comment
[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
3d673fc4
DM
54/**
55 * Software maturity levels used by the core and plugins
56 */
57define('MATURITY_ALPHA', 50); // internals can be tested using white box techniques
58define('MATURITY_BETA', 100); // feature complete, ready for preview and testing
59define('MATURITY_RC', 150); // tested, will be released unless there are fatal bugs
60define('MATURITY_STABLE', 200); // ready for production deployment
61
0242bdc7
TH
62/**
63 * Special value that can be used in $plugin->dependencies in version.php files.
64 */
65define('ANY_VERSION', 'any');
66
67
6a525ce2 68/**
b08b3569 69 * Simple class. It is usually used instead of stdClass because it looks
1387fcdd 70 * more familiar to Java developers ;-) Do not use for type checking of
4f92410f 71 * function parameters. Please use stdClass instead.
b37eac91 72 *
47d2216e
PS
73 * @package core
74 * @subpackage lib
75 * @copyright 2009 Petr Skoda {@link http://skodak.org}
76 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
4f92410f 77 * @deprecated since 2.0
6a525ce2 78 */
b08b3569 79class object extends stdClass {};
6a525ce2 80
251387d0 81/**
82 * Base Moodle Exception class
b37eac91 83 *
c84a2dbe 84 * Although this class is defined here, you cannot throw a moodle_exception until
85 * after moodlelib.php has been included (which will happen very soon).
86 *
47d2216e
PS
87 * @package core
88 * @subpackage lib
89 * @copyright 2008 Petr Skoda {@link http://skodak.org}
90 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
251387d0 91 */
92class moodle_exception extends Exception {
34223e03
SH
93
94 /**
95 * @var string The name of the string from error.php to print
96 */
251387d0 97 public $errorcode;
34223e03
SH
98
99 /**
100 * @var string The name of module
101 */
251387d0 102 public $module;
34223e03
SH
103
104 /**
105 * @var mixed Extra words and phrases that might be required in the error string
106 */
251387d0 107 public $a;
34223e03
SH
108
109 /**
110 * @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.
111 */
251387d0 112 public $link;
34223e03
SH
113
114 /**
115 * @var string Optional information to aid the debugging process
116 */
eee5d9bb 117 public $debuginfo;
251387d0 118
119 /**
120 * Constructor
121 * @param string $errorcode The name of the string from error.php to print
122 * @param string $module name of module
123 * @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 124 * @param mixed $a Extra words and phrases that might be required in the error string
eee5d9bb 125 * @param string $debuginfo optional debugging information
251387d0 126 */
5ca18631 127 function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
128 if (empty($module) || $module == 'moodle' || $module == 'core') {
251387d0 129 $module = 'error';
130 }
131
5ca18631 132 $this->errorcode = $errorcode;
133 $this->module = $module;
134 $this->link = $link;
135 $this->a = $a;
98984c09 136 $this->debuginfo = is_null($debuginfo) ? null : (string)$debuginfo;
251387d0 137
4f6be42c
DM
138 if (get_string_manager()->string_exists($errorcode, $module)) {
139 $message = get_string($errorcode, $module, $a);
140 } else {
141 $message = $module . '/' . $errorcode;
142 }
251387d0 143
94a994b4 144 if (defined('PHPUNIT_TEST') and PHPUNIT_TEST and $debuginfo) {
a3d5830a
PS
145 $message = "$message ($debuginfo)";
146 }
147
251387d0 148 parent::__construct($message, 0);
149 }
150}
151
df997f84
PS
152/**
153 * Course/activity access exception.
154 *
155 * This exception is thrown from require_login()
47d2216e 156 *
f76249cc 157 * @package core_access
47d2216e
PS
158 * @copyright 2010 Petr Skoda {@link http://skodak.org}
159 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
df997f84
PS
160 */
161class require_login_exception extends moodle_exception {
34223e03
SH
162 /**
163 * Constructor
164 * @param string $debuginfo Information to aid the debugging process
165 */
df997f84
PS
166 function __construct($debuginfo) {
167 parent::__construct('requireloginerror', 'error', '', NULL, $debuginfo);
168 }
169}
170
559a5dbd 171/**
172 * Web service parameter exception class
92fe97f9 173 * @deprecated since Moodle 2.2 - use moodle exception instead
559a5dbd 174 * This exception must be thrown to the web service client when a web service parameter is invalid
175 * The error string is gotten from webservice.php
176 */
177class webservice_parameter_exception extends moodle_exception {
178 /**
179 * Constructor
180 * @param string $errorcode The name of the string from webservice.php to print
181 * @param string $a The name of the parameter
34223e03 182 * @param string $debuginfo Optional information to aid debugging
559a5dbd 183 */
93602569
JM
184 function __construct($errorcode=null, $a = '', $debuginfo = null) {
185 parent::__construct($errorcode, 'webservice', '', $a, $debuginfo);
559a5dbd 186 }
187}
188
9a0df45a 189/**
190 * Exceptions indicating user does not have permissions to do something
191 * and the execution can not continue.
47d2216e 192 *
f76249cc 193 * @package core_access
47d2216e
PS
194 * @copyright 2009 Petr Skoda {@link http://skodak.org}
195 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
9a0df45a 196 */
197class required_capability_exception extends moodle_exception {
34223e03
SH
198 /**
199 * Constructor
200 * @param context $context The context used for the capability check
201 * @param string $capability The required capability
202 * @param string $errormessage The error message to show the user
203 * @param string $stringfile
204 */
9a0df45a 205 function __construct($context, $capability, $errormessage, $stringfile) {
206 $capabilityname = get_capability_string($capability);
848fe203
PS
207 if ($context->contextlevel == CONTEXT_MODULE and preg_match('/:view$/', $capability)) {
208 // 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
209 $paranetcontext = get_context_instance_by_id(get_parent_contextid($context));
210 $link = get_context_url($paranetcontext);
211 } else {
212 $link = get_context_url($context);
213 }
214 parent::__construct($errormessage, $stringfile, $link, $capabilityname);
9a0df45a 215 }
216}
217
655bbf51 218/**
cce1b0b9 219 * Exception indicating programming error, must be fixed by a programer. For example
220 * a core API might throw this type of exception if a plugin calls it incorrectly.
b37eac91 221 *
47d2216e
PS
222 * @package core
223 * @subpackage lib
224 * @copyright 2008 Petr Skoda {@link http://skodak.org}
225 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
655bbf51 226 */
227class coding_exception extends moodle_exception {
655bbf51 228 /**
229 * Constructor
230 * @param string $hint short description of problem
231 * @param string $debuginfo detailed information how to fix problem
232 */
233 function __construct($hint, $debuginfo=null) {
234 parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
a3f7cbf6 235 }
236}
237
238/**
239 * Exception indicating malformed parameter problem.
240 * This exception is not supposed to be thrown when processing
241 * user submitted data in forms. It is more suitable
242 * for WS and other low level stuff.
47d2216e
PS
243 *
244 * @package core
245 * @subpackage lib
246 * @copyright 2009 Petr Skoda {@link http://skodak.org}
247 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
a3f7cbf6 248 */
249class invalid_parameter_exception extends moodle_exception {
250 /**
251 * Constructor
252 * @param string $debuginfo some detailed information
253 */
254 function __construct($debuginfo=null) {
255 parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
655bbf51 256 }
257}
258
d07ff72d 259/**
260 * Exception indicating malformed response problem.
261 * This exception is not supposed to be thrown when processing
262 * user submitted data in forms. It is more suitable
263 * for WS and other low level stuff.
264 */
265class invalid_response_exception extends moodle_exception {
266 /**
267 * Constructor
268 * @param string $debuginfo some detailed information
269 */
270 function __construct($debuginfo=null) {
271 parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
272 }
273}
274
cce1b0b9 275/**
1387fcdd 276 * An exception that indicates something really weird happened. For example,
cce1b0b9 277 * if you do switch ($context->contextlevel), and have one case for each
278 * CONTEXT_... constant. You might throw an invalid_state_exception in the
f630a546 279 * default case, to just in case something really weird is going on, and
8dc0ae8f 280 * $context->contextlevel is invalid - rather than ignoring this possibility.
b37eac91 281 *
47d2216e
PS
282 * @package core
283 * @subpackage lib
284 * @copyright 2009 onwards Martin Dougiamas {@link http://moodle.com}
285 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
cce1b0b9 286 */
287class invalid_state_exception extends moodle_exception {
288 /**
289 * Constructor
290 * @param string $hint short description of problem
291 * @param string $debuginfo optional more detailed information
292 */
293 function __construct($hint, $debuginfo=null) {
294 parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
295 }
296}
297
4031f6a2
PS
298/**
299 * An exception that indicates incorrect permissions in $CFG->dataroot
300 *
301 * @package core
302 * @subpackage lib
303 * @copyright 2010 Petr Skoda {@link http://skodak.org}
304 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
305 */
306class invalid_dataroot_permissions extends moodle_exception {
307 /**
308 * Constructor
309 * @param string $debuginfo optional more detailed information
310 */
311 function __construct($debuginfo = NULL) {
312 parent::__construct('invaliddatarootpermissions', 'error', '', NULL, $debuginfo);
313 }
314}
315
cbad562e
PS
316/**
317 * An exception that indicates that file can not be served
318 *
319 * @package core
320 * @subpackage lib
321 * @copyright 2010 Petr Skoda {@link http://skodak.org}
322 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
323 */
324class file_serving_exception extends moodle_exception {
325 /**
326 * Constructor
327 * @param string $debuginfo optional more detailed information
328 */
329 function __construct($debuginfo = NULL) {
330 parent::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
331 }
332}
333
251387d0 334/**
1387fcdd 335 * Default exception handler, uncaught exceptions are equivalent to error() in 1.9 and earlier
fd1a792e 336 *
30fa50d0 337 * @param Exception $ex
c19bc39c 338 * @return void -does not return. Terminates execution!
251387d0 339 */
c19bc39c 340function default_exception_handler($ex) {
f0202ae9 341 global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION, $PAGE;
1fbdf76d 342
343 // detect active db transactions, rollback and log as error
695c5ec4 344 abort_all_db_transactions();
1fe1d104 345
d9e07264 346 if (($ex instanceof required_capability_exception) && !CLI_SCRIPT && !AJAX_SCRIPT && !empty($CFG->autologinguests) && !empty($USER->autologinguest)) {
f0202ae9 347 $SESSION->wantsurl = qualified_me();
d9e07264
SH
348 redirect(get_login_url());
349 }
350
c19bc39c 351 $info = get_exception_info($ex);
34a2777c 352
c19bc39c 353 if (debugging('', DEBUG_MINIMAL)) {
2e9b772f 354 $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
695c5ec4 355 error_log($logerrmsg);
fd1a792e 356 }
357
c19bc39c
PS
358 if (is_early_init($info->backtrace)) {
359 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
b7009474 360 } else {
3c1ea58b 361 try {
a56c457e
PS
362 if ($DB) {
363 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
364 $DB->set_debug(0);
365 }
3c1ea58b
PS
366 echo $OUTPUT->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
367 } catch (Exception $out_ex) {
368 // default exception handler MUST not throw any exceptions!!
2e9b772f 369 // 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 370 // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
1adaa404
PS
371 if (CLI_SCRIPT or AJAX_SCRIPT) {
372 // just ignore the error and send something back using the safest method
373 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
374 } else {
375 echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
376 $outinfo = get_exception_info($out_ex);
377 echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
378 }
3c1ea58b 379 }
7544d13c 380 }
381
34a2777c 382 exit(1); // General error code
383}
384
85ba1e78
PS
385/**
386 * Default error handler, prevents some white screens.
387 * @param int $errno
388 * @param string $errstr
389 * @param string $errfile
390 * @param int $errline
391 * @param array $errcontext
392 * @return bool false means use default error handler
393 */
394function default_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
395 if ($errno == 4096) {
396 //fatal catchable error
397 throw new coding_exception('PHP catchable fatal error', $errstr);
398 }
399 return false;
400}
401
695c5ec4
PS
402/**
403 * Unconditionally abort all database transactions, this function
404 * should be called from exception handlers only.
405 * @return void
406 */
407function abort_all_db_transactions() {
408 global $CFG, $DB, $SCRIPT;
409
d5a8d9aa 410 // default exception handler MUST not throw any exceptions!!
03221650 411
695c5ec4
PS
412 if ($DB && $DB->is_transaction_started()) {
413 error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
d5a8d9aa
PS
414 // note: transaction blocks should never change current $_SESSION
415 $DB->force_transaction_rollback();
695c5ec4
PS
416 }
417}
418
b7009474 419/**
50764d37
PS
420 * This function encapsulates the tests for whether an exception was thrown in
421 * early init -- either during setup.php or during init of $OUTPUT.
b7009474 422 *
423 * If another exception is thrown then, and if we do not take special measures,
424 * we would just get a very cryptic message "Exception thrown without a stack
425 * frame in Unknown on line 0". That makes debugging very hard, so we do take
426 * special measures in default_exception_handler, with the help of this function.
427 *
428 * @param array $backtrace the stack trace to analyse.
429 * @return boolean whether the stack trace is somewhere in output initialisation.
430 */
50764d37 431function is_early_init($backtrace) {
b7009474 432 $dangerouscode = array(
433 array('function' => 'header', 'type' => '->'),
434 array('class' => 'bootstrap_renderer'),
50764d37 435 array('file' => dirname(__FILE__).'/setup.php'),
b7009474 436 );
437 foreach ($backtrace as $stackframe) {
438 foreach ($dangerouscode as $pattern) {
439 $matches = true;
440 foreach ($pattern as $property => $value) {
441 if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
442 $matches = false;
443 }
444 }
445 if ($matches) {
446 return true;
447 }
448 }
449 }
450 return false;
451}
452
34a2777c 453/**
cbf05caa
PS
454 * Abort execution by throwing of a general exception,
455 * default exception handler displays the error message in most cases.
34a2777c 456 *
457 * @param string $errorcode The name of the language string containing the error message.
458 * Normally this should be in the error.php lang file.
459 * @param string $module The language file to get the error message from.
460 * @param string $link The url where the user will be prompted to continue.
461 * If no url is provided the user will be directed to the site index page.
462 * @param object $a Extra words and phrases that might be required in the error string
cbf05caa
PS
463 * @param string $debuginfo optional debugging information
464 * @return void, always throws exception!
34a2777c 465 */
cbf05caa
PS
466function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
467 throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
34a2777c 468}
469
470/**
c19bc39c
PS
471 * Returns detailed information about specified exception.
472 * @param exception $ex
473 * @return object
34a2777c 474 */
c19bc39c 475function get_exception_info($ex) {
34a2777c 476 global $CFG, $DB, $SESSION;
477
c19bc39c
PS
478 if ($ex instanceof moodle_exception) {
479 $errorcode = $ex->errorcode;
480 $module = $ex->module;
481 $a = $ex->a;
482 $link = $ex->link;
483 $debuginfo = $ex->debuginfo;
484 } else {
485 $errorcode = 'generalexceptionmessage';
486 $module = 'error';
487 $a = $ex->getMessage();
488 $link = '';
98984c09 489 $debuginfo = '';
34a2777c 490 }
491
fb71453d
AD
492 // Append the error code to the debug info to make grepping and googling easier
493 $debuginfo .= PHP_EOL."Error code: $errorcode";
494
c19bc39c
PS
495 $backtrace = $ex->getTrace();
496 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
497 array_unshift($backtrace, $place);
498
c84a2dbe 499 // Be careful, no guarantee moodlelib.php is loaded.
34a2777c 500 if (empty($module) || $module == 'moodle' || $module == 'core') {
501 $module = 'error';
502 }
fb71453d
AD
503 // Search for the $errorcode's associated string
504 // If not found, append the contents of $a to $debuginfo so helpful information isn't lost
4f6be42c
DM
505 if (function_exists('get_string_manager')) {
506 if (get_string_manager()->string_exists($errorcode, $module)) {
507 $message = get_string($errorcode, $module, $a);
508 } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
c84a2dbe 509 // Search in moodle file if error specified - needed for backwards compatibility
510 $message = get_string($errorcode, 'moodle', $a);
4f6be42c
DM
511 } else {
512 $message = $module . '/' . $errorcode;
fb71453d 513 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
c84a2dbe 514 }
515 } else {
516 $message = $module . '/' . $errorcode;
fb71453d 517 $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
c84a2dbe 518 }
519
520 // Be careful, no guarantee weblib.php is loaded.
521 if (function_exists('clean_text')) {
522 $message = clean_text($message);
523 } else {
524 $message = htmlspecialchars($message);
34a2777c 525 }
34a2777c 526
527 if (!empty($CFG->errordocroot)) {
eea3341d 528 $errordoclink = $CFG->errordocroot . '/en/';
34a2777c 529 } else {
eea3341d 530 $errordoclink = get_docs_url();
34a2777c 531 }
eea3341d 532
34a2777c 533 if ($module === 'error') {
534 $modulelink = 'moodle';
0ae8f5fc 535 } else {
34a2777c 536 $modulelink = $module;
251387d0 537 }
eea3341d 538 $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
34a2777c 539
d4a03c00 540 if (empty($link)) {
34a2777c 541 if (!empty($SESSION->fromurl)) {
542 $link = $SESSION->fromurl;
543 unset($SESSION->fromurl);
544 } else {
545 $link = $CFG->wwwroot .'/';
546 }
547 }
548
c8d3345c
PS
549 // when printing an error the continue button should never link offsite
550 if (stripos($link, $CFG->wwwroot) === false &&
551 stripos($link, $CFG->httpswwwroot) === false) {
552 $link = $CFG->wwwroot.'/';
553 }
554
365a5941 555 $info = new stdClass();
c19bc39c
PS
556 $info->message = $message;
557 $info->errorcode = $errorcode;
558 $info->backtrace = $backtrace;
559 $info->link = $link;
560 $info->moreinfourl = $moreinfourl;
561 $info->a = $a;
562 $info->debuginfo = $debuginfo;
30fa50d0 563
c19bc39c 564 return $info;
34a2777c 565}
566
eea3341d 567/**
b86a48c5 568 * Returns the Moodle Docs URL in the users language for a given 'More help' link.
eea3341d 569 *
b86a48c5
TH
570 * There are three cases:
571 *
572 * 1. In the normal case, $path will be a short relative path 'component/thing',
573 * like 'mod/folder/view' 'group/import'. This gets turned into an link to
574 * MoodleDocs in the user's language, and for the appropriate Moodle version.
575 * E.g. 'group/import' may become 'http://docs.moodle.org/2x/en/group/import'.
576 * The 'http://docs.moodle.org' bit comes from $CFG->docroot.
577 *
578 * This is the only option that should be used in standard Moodle code. The other
579 * two options have been implemented because they are useful for third-party plugins.
580 *
617d260d 581 * 2. $path may be an absolute URL, starting http:// or https://. In this case,
b86a48c5
TH
582 * the link is used as is.
583 *
584 * 3. $path may start %%WWWROOT%%, in which case that is replaced by
585 * $CFG->wwwroot to make the link.
586 *
587 * @param string $path the place to link to. See above for details.
588 * @return string The MoodleDocs URL in the user's language. for example @link http://docs.moodle.org/2x/en/$path}
eea3341d 589 */
b86a48c5 590function get_docs_url($path = null) {
eea3341d 591 global $CFG;
b86a48c5
TH
592
593 // Absolute URLs are used unmodified.
594 if (substr($path, 0, 7) === 'http://' || substr($path, 0, 8) === 'https://') {
595 return $path;
596 }
597
598 // Paths starting %%WWWROOT%% have that replaced by $CFG->wwwroot.
599 if (substr($path, 0, 11) === '%%WWWROOT%%') {
600 return $CFG->wwwroot . substr($path, 11);
601 }
602
603 // Otherwise we do the normal case, and construct a MoodleDocs URL relative to $CFG->docroot.
604
ed01233a
AB
605 // Check that $CFG->branch has been set up, during installation it won't be.
606 if (empty($CFG->branch)) {
b86a48c5 607 // It's not there yet so look at version.php.
eea3341d
AB
608 include($CFG->dirroot.'/version.php');
609 } else {
b86a48c5 610 // We can use $CFG->branch and avoid having to include version.php.
ed01233a 611 $branch = $CFG->branch;
eea3341d 612 }
ed01233a
AB
613 // ensure branch is valid.
614 if (!$branch) {
eea3341d
AB
615 // We should never get here but in case we do lets set $branch to .
616 // the smart one's will know that this is the current directory
617 // and the smarter ones will know that there is some smart matching
618 // that will ensure people end up at the latest version of the docs.
619 $branch = '.';
620 }
621 if (!empty($CFG->docroot)) {
622 return $CFG->docroot . '/' . $branch . '/' . current_language() . '/' . $path;
623 } else {
b86a48c5 624 return 'http://docs.moodle.org/'. $branch . '/' . current_language() . '/' . $path;
eea3341d
AB
625 }
626}
627
34a2777c 628/**
629 * Formats a backtrace ready for output.
630 *
631 * @param array $callers backtrace array, as returned by debug_backtrace().
632 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
633 * @return string formatted backtrace, ready for output.
634 */
635function format_backtrace($callers, $plaintext = false) {
a0394be4 636 // do not use $CFG->dirroot because it might not be available in destructors
34a2777c 637 $dirroot = dirname(dirname(__FILE__));
30fa50d0 638
34a2777c 639 if (empty($callers)) {
640 return '';
641 }
642
643 $from = $plaintext ? '' : '<ul style="text-align: left">';
644 foreach ($callers as $caller) {
645 if (!isset($caller['line'])) {
646 $caller['line'] = '?'; // probably call_user_func()
647 }
648 if (!isset($caller['file'])) {
649 $caller['file'] = 'unknownfile'; // probably call_user_func()
650 }
651 $from .= $plaintext ? '* ' : '<li>';
652 $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
653 if (isset($caller['function'])) {
654 $from .= ': call to ';
655 if (isset($caller['class'])) {
656 $from .= $caller['class'] . $caller['type'];
657 }
658 $from .= $caller['function'] . '()';
659 } else if (isset($caller['exception'])) {
660 $from .= ': '.$caller['exception'].' thrown';
661 }
662 $from .= $plaintext ? "\n" : '</li>';
663 }
664 $from .= $plaintext ? '' : '</ul>';
665
666 return $from;
251387d0 667}
6a525ce2 668
cbad562e
PS
669/**
670 * This function makes the return value of ini_get consistent if you are
671 * setting server directives through the .htaccess file in apache.
672 *
673 * Current behavior for value set from php.ini On = 1, Off = [blank]
674 * Current behavior for value set from .htaccess On = On, Off = Off
675 * Contributed by jdell @ unr.edu
676 *
677 * @param string $ini_get_arg The argument to get
678 * @return bool True for on false for not
679 */
680function ini_get_bool($ini_get_arg) {
681 $temp = ini_get($ini_get_arg);
682
683 if ($temp == '1' or strtolower($temp) == 'on') {
684 return true;
685 }
686 return false;
687}
688
fbf2c91e 689/**
690 * This function verifies the sanity of PHP configuration
691 * and stops execution if anything critical found.
692 */
693function setup_validate_php_configuration() {
694 // this must be very fast - no slow checks here!!!
695
696 if (ini_get_bool('register_globals')) {
697 print_error('globalswarning', 'admin');
698 }
699 if (ini_get_bool('session.auto_start')) {
700 print_error('sessionautostartwarning', 'admin');
701 }
702 if (ini_get_bool('magic_quotes_runtime')) {
703 print_error('fatalmagicquotesruntime', 'admin');
704 }
705}
706
12bb0c3e
PS
707/**
708 * Initialise global $CFG variable
709 * @return void
710 */
711function initialise_cfg() {
712 global $CFG, $DB;
8b8aa060 713
12bb0c3e
PS
714 try {
715 if ($DB) {
716 $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
717 foreach ($localcfg as $name=>$value) {
718 if (property_exists($CFG, $name)) {
719 // config.php settings always take precedence
720 continue;
721 }
722 $CFG->{$name} = $value;
723 }
724 }
69ac5d47 725 } catch (dml_exception $e) {
12bb0c3e
PS
726 // most probably empty db, going to install soon
727 }
728}
729
11e7b506 730/**
75781f87 731 * Initialises $FULLME and friends. Private function. Should only be called from
732 * setup.php.
11e7b506 733 */
734function initialise_fullme() {
f0f8f9a7 735 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
11e7b506 736
75781f87 737 // Detect common config error.
84b88cfd 738 if (substr($CFG->wwwroot, -1) == '/') {
739 print_error('wwwrootslash', 'error');
740 }
741
75781f87 742 if (CLI_SCRIPT) {
743 initialise_fullme_cli();
744 return;
37ccf1fe 745 }
11e7b506 746
75781f87 747 $rurl = setup_get_remote_url();
f0f8f9a7
PS
748 $wwwroot = parse_url($CFG->wwwroot.'/');
749
750 if (empty($rurl['host'])) {
751 // missing host in request header, probably not a real browser, let's ignore them
752
753 } else if (!empty($CFG->reverseproxy)) {
754 // $CFG->reverseproxy specifies if reverse proxy server used
755 // Used in load balancing scenarios.
756 // Do not abuse this to try to solve lan/wan access problems!!!!!
757
758 } else {
759 if (($rurl['host'] !== $wwwroot['host']) or (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port'])) {
760 // Explain the problem and redirect them to the right URL
761 if (!defined('NO_MOODLE_COOKIES')) {
762 define('NO_MOODLE_COOKIES', true);
763 }
764 redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
765 }
766 }
11e7b506 767
75781f87 768 // Check that URL is under $CFG->wwwroot.
769 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
770 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
771 } else {
772 // Probably some weird external script
773 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
11e7b506 774 return;
775 }
776
75781f87 777 // $CFG->sslproxy specifies if external SSL appliance is used
778 // (That is, the Moodle server uses http, with an external box translating everything to https).
779 if (empty($CFG->sslproxy)) {
56048f83 780 if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
75781f87 781 print_error('sslonlyaccess', 'error');
782 }
56048f83
PS
783 } else {
784 if ($wwwroot['scheme'] !== 'https') {
785 throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
786 }
74162134 787 $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
75781f87 788 }
789
75781f87 790 // hopefully this will stop all those "clever" admins trying to set up moodle
791 // with two different addresses in intranet and Internet
e0f2718f 792 if (!empty($CFG->reverseproxy) && $rurl['host'] === $wwwroot['host']) {
75781f87 793 print_error('reverseproxyabused', 'error');
794 }
795
796 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
797 if (!empty($wwwroot['port'])) {
798 $hostandport .= ':'.$wwwroot['port'];
799 }
800
801 $FULLSCRIPT = $hostandport . $rurl['path'];
802 $FULLME = $hostandport . $rurl['fullpath'];
803 $ME = $rurl['fullpath'];
75781f87 804}
805
806/**
807 * Initialises $FULLME and friends for command line scripts.
808 * This is a private method for use by initialise_fullme.
809 */
810function initialise_fullme_cli() {
80e30f25 811 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
812
75781f87 813 // Urls do not make much sense in CLI scripts
814 $backtrace = debug_backtrace();
815 $topfile = array_pop($backtrace);
816 $topfile = realpath($topfile['file']);
817 $dirroot = realpath($CFG->dirroot);
818
819 if (strpos($topfile, $dirroot) !== 0) {
820 // Probably some weird external script
821 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
822 } else {
823 $relativefile = substr($topfile, strlen($dirroot));
824 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
825 $SCRIPT = $FULLSCRIPT = $relativefile;
826 $FULLME = $ME = null;
827 }
828}
829
830/**
831 * Get the URL that PHP/the web server thinks it is serving. Private function
832 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
833 * @return array in the same format that parse_url returns, with the addition of
834 * a 'fullpath' element, which includes any slasharguments path.
835 */
836function setup_get_remote_url() {
11e7b506 837 $rurl = array();
e0f2718f
PS
838 if (isset($_SERVER['HTTP_HOST'])) {
839 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
840 } else {
841 $rurl['host'] = null;
842 }
11e7b506 843 $rurl['port'] = $_SERVER['SERVER_PORT'];
75781f87 844 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
2a9c0d05 845 $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ? 'http' : 'https';
11e7b506 846
847 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
848 //Apache server
f49b359b 849 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
7e13a265 850
11e7b506 851 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
199c1981 852 //IIS - needs a lot of tweaking to make it work
11e7b506 853 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
854
855 // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
856 // since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
21517960 857 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
11e7b506 858
859 if ($_SERVER['QUERY_STRING'] != '') {
991ec2ee 860 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
11e7b506 861 }
862 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
863
f49b359b
PS
864/* NOTE: following servers are not fully tested! */
865
866 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
867 //lighttpd - not officially supported
f49b359b
PS
868 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
869
870 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
871 //nginx - not officially supported
28ec73dc
PS
872 if (!isset($_SERVER['SCRIPT_NAME'])) {
873 die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
874 }
f49b359b
PS
875 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
876
199c1981
PS
877 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
878 //cherokee - not officially supported
199c1981
PS
879 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
880
8b8aa060
PS
881 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
882 //zeus - not officially supported
8b8aa060
PS
883 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
884
f49b359b
PS
885 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
886 //LiteSpeed - not officially supported
f49b359b
PS
887 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
888
4e3e8464
PS
889 } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
890 //obscure name found on some servers - this is definitely not supported
891 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
892
d860f1ad
PS
893 } else if (strpos($_SERVER['SERVER_SOFTWARE'], 'PHP') === 0) {
894 // built-in PHP Development Server
895 $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
896
897 } else {
75781f87 898 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
11e7b506 899 }
0ae36f66
PS
900
901 // sanitize the url a bit more, the encoding style may be different in vars above
902 $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
903 $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);
904
75781f87 905 return $rurl;
11e7b506 906}
907
d3f9f1f8 908/**
909 * Initializes our performance info early.
910 *
911 * Pairs up with get_performance_info() which is actually
251387d0 912 * in moodlelib.php. This function is here so that we can
913 * call it before all the libs are pulled in.
d3f9f1f8 914 *
915 * @uses $PERF
916 */
917function init_performance_info() {
918
6fc4ad72 919 global $PERF, $CFG, $USER;
251387d0 920
365a5941 921 $PERF = new stdClass();
d3f9f1f8 922 $PERF->logwrites = 0;
923 if (function_exists('microtime')) {
924 $PERF->starttime = microtime();
c84a2dbe 925 }
d3f9f1f8 926 if (function_exists('memory_get_usage')) {
927 $PERF->startmemory = memory_get_usage();
928 }
929 if (function_exists('posix_times')) {
251387d0 930 $PERF->startposixtimes = posix_times();
d3f9f1f8 931 }
932}
933
31a99877 934/**
935 * Indicates whether we are in the middle of the initial Moodle install.
936 *
937 * Very occasionally it is necessary avoid running certain bits of code before the
938 * Moodle installation has completed. The installed flag is set in admin/index.php
939 * after Moodle core and all the plugins have been installed, but just before
940 * the person doing the initial install is asked to choose the admin password.
941 *
942 * @return boolean true if the initial install is not complete.
943 */
944function during_initial_install() {
945 global $CFG;
946 return empty($CFG->rolesactive);
947}
948
76f3815b 949/**
950 * Function to raise the memory limit to a new value.
951 * Will respect the memory limit if it is higher, thus allowing
952 * settings in php.ini, apache conf or command line switches
0f0f0768 953 * to override it.
76f3815b 954 *
0f0f0768
PS
955 * The memory limit should be expressed with a constant
956 * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
957 * It is possible to use strings or integers too (eg:'128M').
76f3815b 958 *
0f0f0768
PS
959 * @param mixed $newlimit the new memory limit
960 * @return bool success
76f3815b 961 */
11e7b506 962function raise_memory_limit($newlimit) {
0f0f0768 963 global $CFG;
76f3815b 964
0f0f0768
PS
965 if ($newlimit == MEMORY_UNLIMITED) {
966 ini_set('memory_limit', -1);
967 return true;
968
969 } else if ($newlimit == MEMORY_STANDARD) {
cd3059b1
PS
970 if (PHP_INT_SIZE > 4) {
971 $newlimit = get_real_size('128M'); // 64bit needs more memory
972 } else {
973 $newlimit = get_real_size('96M');
974 }
0f0f0768
PS
975
976 } else if ($newlimit == MEMORY_EXTRA) {
cd3059b1
PS
977 if (PHP_INT_SIZE > 4) {
978 $newlimit = get_real_size('384M'); // 64bit needs more memory
979 } else {
980 $newlimit = get_real_size('256M');
981 }
d827f7b8 982 if (!empty($CFG->extramemorylimit)) {
0f0f0768
PS
983 $extra = get_real_size($CFG->extramemorylimit);
984 if ($extra > $newlimit) {
985 $newlimit = $extra;
986 }
987 }
988
989 } else if ($newlimit == MEMORY_HUGE) {
990 $newlimit = get_real_size('2G');
991
992 } else {
993 $newlimit = get_real_size($newlimit);
994 }
995
996 if ($newlimit <= 0) {
997 debugging('Invalid memory limit specified.');
76f3815b 998 return false;
999 }
1000
cbad562e 1001 $cur = ini_get('memory_limit');
76f3815b 1002 if (empty($cur)) {
1003 // if php is compiled without --enable-memory-limits
1004 // apparently memory_limit is set to ''
0f0f0768 1005 $cur = 0;
76f3815b 1006 } else {
1007 if ($cur == -1){
1008 return true; // unlimited mem!
1009 }
0f0f0768 1010 $cur = get_real_size($cur);
76f3815b 1011 }
1012
0f0f0768 1013 if ($newlimit > $cur) {
76f3815b 1014 ini_set('memory_limit', $newlimit);
7022dd39 1015 return true;
1016 }
1017 return false;
1018}
1019
1020/**
1021 * Function to reduce the memory limit to a new value.
1022 * Will respect the memory limit if it is lower, thus allowing
1023 * settings in php.ini, apache conf or command line switches
1024 * to override it
1025 *
1026 * The memory limit should be expressed with a string (eg:'64M')
1027 *
1028 * @param string $newlimit the new memory limit
1029 * @return bool
1030 */
f630a546 1031function reduce_memory_limit($newlimit) {
7022dd39 1032 if (empty($newlimit)) {
1033 return false;
1034 }
cbad562e 1035 $cur = ini_get('memory_limit');
7022dd39 1036 if (empty($cur)) {
1037 // if php is compiled without --enable-memory-limits
1038 // apparently memory_limit is set to ''
0f0f0768 1039 $cur = 0;
7022dd39 1040 } else {
1041 if ($cur == -1){
1042 return true; // unlimited mem!
1043 }
1044 $cur = get_real_size($cur);
1045 }
1046
1047 $new = get_real_size($newlimit);
1048 // -1 is smaller, but it means unlimited
1049 if ($new < $cur && $new != -1) {
1050 ini_set('memory_limit', $newlimit);
76f3815b 1051 return true;
1052 }
1053 return false;
1054}
1055
1056/**
1057 * Converts numbers like 10M into bytes.
1058 *
0f0f0768
PS
1059 * @param string $size The size to be converted
1060 * @return int
76f3815b 1061 */
0f0f0768 1062function get_real_size($size = 0) {
76f3815b 1063 if (!$size) {
1064 return 0;
1065 }
11e7b506 1066 $scan = array();
0f0f0768
PS
1067 $scan['GB'] = 1073741824;
1068 $scan['Gb'] = 1073741824;
1069 $scan['G'] = 1073741824;
76f3815b 1070 $scan['MB'] = 1048576;
1071 $scan['Mb'] = 1048576;
1072 $scan['M'] = 1048576;
1073 $scan['m'] = 1048576;
1074 $scan['KB'] = 1024;
1075 $scan['Kb'] = 1024;
1076 $scan['K'] = 1024;
1077 $scan['k'] = 1024;
1078
1079 while (list($key) = each($scan)) {
1080 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
1081 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
1082 break;
1083 }
1084 }
1085 return $size;
1086}
1087
cbad562e 1088/**
871ed458
PS
1089 * Try to disable all output buffering and purge
1090 * all headers.
1091 *
34223e03 1092 * @access private to be called only from lib/setup.php !
cbad562e
PS
1093 * @return void
1094 */
1095function disable_output_buffering() {
1096 $olddebug = error_reporting(0);
1097
1098 // disable compression, it would prevent closing of buffers
1099 if (ini_get_bool('zlib.output_compression')) {
1100 ini_set('zlib.output_compression', 'Off');
1101 }
1102
1103 // try to flush everything all the time
1104 ob_implicit_flush(true);
1105
1106 // close all buffers if possible and discard any existing output
1107 // this can actually work around some whitespace problems in config.php
1108 while(ob_get_level()) {
1109 if (!ob_end_clean()) {
1110 // prevent infinite loop when buffer can not be closed
1111 break;
1112 }
1113 }
1114
99302c5e
PS
1115 // disable any other output handlers
1116 ini_set('output_handler', '');
1117
cbad562e
PS
1118 error_reporting($olddebug);
1119}
1120
5e39d7aa 1121/**
1122 * Check whether a major upgrade is needed. That is defined as an upgrade that
1123 * changes something really fundamental in the database, so nothing can possibly
1124 * work until the database has been updated, and that is defined by the hard-coded
1125 * version number in this function.
1126 */
1127function redirect_if_major_upgrade_required() {
1128 global $CFG;
b24d1dbb 1129 $lastmajordbchanges = 2012051700;
5e39d7aa 1130 if (empty($CFG->version) or (int)$CFG->version < $lastmajordbchanges or
1131 during_initial_install() or !empty($CFG->adminsetuppending)) {
1132 try {
1133 @session_get_instance()->terminate_current();
1134 } catch (Exception $e) {
1135 // Ignore any errors, redirect to upgrade anyway.
1136 }
a38c7a10 1137 $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
5e39d7aa 1138 @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
a38c7a10
PS
1139 @header('Location: ' . $url);
1140 echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
5e39d7aa 1141 exit;
1142 }
1143}
1144
d3f9f1f8 1145/**
4031f6a2
PS
1146 * Function to check if a directory exists and by default create it if not exists.
1147 *
1148 * Previously this was accepting paths only from dataroot, but we now allow
1149 * files outside of dataroot if you supply custom paths for some settings in config.php.
1150 * This function does not verify that the directory is writable.
d3f9f1f8 1151 *
0b9f2a02
PS
1152 * NOTE: this function uses current file stat cache,
1153 * please use clearstatcache() before this if you expect that the
1154 * directories may have been removed recently from a different request.
1155 *
4031f6a2
PS
1156 * @param string $dir absolute directory path
1157 * @param boolean $create directory if does not exist
1158 * @param boolean $recursive create directory recursively
1159 * @return boolean true if directory exists or created, false otherwise
d3f9f1f8 1160 */
4031f6a2 1161function check_dir_exists($dir, $create = true, $recursive = true) {
d3f9f1f8 1162 global $CFG;
1163
4031f6a2 1164 umask(0000); // just in case some evil code changed it
d3f9f1f8 1165
4031f6a2
PS
1166 if (is_dir($dir)) {
1167 return true;
1168 }
d3f9f1f8 1169
4031f6a2
PS
1170 if (!$create) {
1171 return false;
d100b8a0 1172 }
1173
4031f6a2
PS
1174 return mkdir($dir, $CFG->directorypermissions, $recursive);
1175}
1176
1177/**
e6958907 1178 * Create a directory and make sure it is writable.
4031f6a2 1179 *
32db0f0d 1180 * @private
e6958907 1181 * @param string $dir the full path of the directory to be created
4031f6a2
PS
1182 * @param bool $exceptiononerror throw exception if error encountered
1183 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1184 */
e6958907 1185function make_writable_directory($dir, $exceptiononerror = true) {
4031f6a2
PS
1186 global $CFG;
1187
4031f6a2
PS
1188 if (file_exists($dir) and !is_dir($dir)) {
1189 if ($exceptiononerror) {
1190 throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1191 } else {
1192 return false;
1193 }
1194 }
1195
1196 umask(0000); // just in case some evil code changed it
1197
1198 if (!file_exists($dir)) {
1199 if (!mkdir($dir, $CFG->directorypermissions, true)) {
1200 if ($exceptiononerror) {
1201 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1202 } else {
d3f9f1f8 1203 return false;
1204 }
d3f9f1f8 1205 }
1206 }
1207
4031f6a2
PS
1208 if (!is_writable($dir)) {
1209 if ($exceptiononerror) {
1210 throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1211 } else {
1212 return false;
1213 }
1214 }
1215
1216 return $dir;
d3f9f1f8 1217}
1218
e6958907
TL
1219/**
1220 * Protect a directory from web access.
1221 * Could be extended in the future to support other mechanisms (e.g. other webservers).
1222 *
32db0f0d 1223 * @private
e6958907
TL
1224 * @param string $dir the full path of the directory to be protected
1225 */
1226function protect_directory($dir) {
1227 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1228 if (!file_exists("$dir/.htaccess")) {
1229 if ($handle = fopen("$dir/.htaccess", 'w')) { // For safety
1230 @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");
1231 @fclose($handle);
1232 }
1233 }
1234}
1235
1236/**
1237 * Create a directory under dataroot and make sure it is writable.
32db0f0d 1238 * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
e6958907
TL
1239 *
1240 * @param string $directory the full path of the directory to be created under $CFG->dataroot
1241 * @param bool $exceptiononerror throw exception if error encountered
1242 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1243 */
1244function make_upload_directory($directory, $exceptiononerror = true) {
1245 global $CFG;
32db0f0d
PS
1246
1247 if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1248 debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1249
1250 } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
1251 debugging('Use make_cache_directory() for creation of chache directory and $CFG->cachedir to get the location.');
1252 }
1253
e6958907
TL
1254 protect_directory($CFG->dataroot);
1255 return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1256}
1257
1258/**
1259 * Create a directory under tempdir and make sure it is writable.
32db0f0d 1260 * Temporary files should be used during the current request only!
e6958907
TL
1261 *
1262 * @param string $directory the full path of the directory to be created under $CFG->tempdir
1263 * @param bool $exceptiononerror throw exception if error encountered
1264 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1265 */
1266function make_temp_directory($directory, $exceptiononerror = true) {
1267 global $CFG;
adf0fc0e
PS
1268 if ($CFG->tempdir !== "$CFG->dataroot/temp") {
1269 check_dir_exists($CFG->tempdir, true, true);
1270 protect_directory($CFG->tempdir);
7a7edd21
PS
1271 } else {
1272 protect_directory($CFG->dataroot);
adf0fc0e 1273 }
e6958907
TL
1274 return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1275}
1276
1277/**
1278 * Create a directory under cachedir and make sure it is writable.
1279 *
1280 * @param string $directory the full path of the directory to be created under $CFG->cachedir
1281 * @param bool $exceptiononerror throw exception if error encountered
1282 * @return string|false Returns full path to directory if successful, false if not; may throw exception
1283 */
1284function make_cache_directory($directory, $exceptiononerror = true) {
1285 global $CFG;
adf0fc0e
PS
1286 if ($CFG->cachedir !== "$CFG->dataroot/cache") {
1287 check_dir_exists($CFG->cachedir, true, true);
1288 protect_directory($CFG->cachedir);
7a7edd21
PS
1289 } else {
1290 protect_directory($CFG->dataroot);
adf0fc0e 1291 }
e6958907
TL
1292 return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1293}
1294
1295
34223e03
SH
1296/**
1297 * Initialises an Memcached instance
1298 * @global memcached $MCACHE
1299 * @return boolean Returns true if an mcached instance could be successfully initialised
1300 */
419e1d93 1301function init_memcached() {
1302 global $CFG, $MCACHE;
1303
f917d0ea 1304 include_once($CFG->libdir . '/memcached.class.php');
1305 $MCACHE = new memcached;
1306 if ($MCACHE->status()) {
1307 return true;
251387d0 1308 }
f917d0ea 1309 unset($MCACHE);
251387d0 1310 return false;
419e1d93 1311}
1312
34223e03
SH
1313/**
1314 * Initialises an eAccelerator instance
1315 * @global eaccelerator $MCACHE
1316 * @return boolean Returns true if an eAccelerator instance could be successfully initialised
1317 */
2142d492 1318function init_eaccelerator() {
1319 global $CFG, $MCACHE;
1320
1321 include_once($CFG->libdir . '/eaccelerator.class.php');
1322 $MCACHE = new eaccelerator;
f917d0ea 1323 if ($MCACHE->status()) {
2142d492 1324 return true;
251387d0 1325 }
2142d492 1326 unset($MCACHE);
1327 return false;
1328}
1329
81b58cc2
PS
1330/**
1331 * Checks if current user is a web crawler.
1332 *
1333 * This list can not be made complete, this is not a security
1334 * restriction, we make the list only to help these sites
1335 * especially when automatic guest login is disabled.
1336 *
1337 * If admin needs security they should enable forcelogin
1338 * and disable guest access!!
1339 *
1340 * @return bool
1341 */
1342function is_web_crawler() {
1343 if (!empty($_SERVER['HTTP_USER_AGENT'])) {
1344 if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
1345 return true;
1346 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) { // Google
1347 return true;
1348 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yahoo! Slurp') !== false ) { // Yahoo
1349 return true;
1350 } else if (strpos($_SERVER['HTTP_USER_AGENT'], '[ZSEBOT]') !== false ) { // Zoomspider
1351 return true;
1352 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSNBOT') !== false ) { // MSN Search
1353 return true;
1354 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yandex') !== false ) {
1355 return true;
1356 } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'AltaVista') !== false ) {
1357 return true;
1358 }
1359 }
1360 return false;
1361}
2142d492 1362
c84a2dbe 1363/**
1364 * This class solves the problem of how to initialise $OUTPUT.
1365 *
1366 * The problem is caused be two factors
1367 * <ol>
1368 * <li>On the one hand, we cannot be sure when output will start. In particular,
30fa50d0 1369 * an error, which needs to be displayed, could be thrown at any time.</li>
c84a2dbe 1370 * <li>On the other hand, we cannot be sure when we will have all the information
1371 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1372 * (potentially) depends on the current course, course categories, and logged in user.
1373 * It also depends on whether the current page requires HTTPS.</li>
1374 * </ol>
1375 *
1376 * So, it is hard to find a single natural place during Moodle script execution,
1377 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1378 * adopt the following strategy
1379 * <ol>
1380 * <li>We will initialise $OUTPUT the first time it is used.</li>
1381 * <li>If, after $OUTPUT has been initialised, the script tries to change something
7e0d6675 1382 * that $OUTPUT depends on, we throw an exception making it clear that the script
c84a2dbe 1383 * did something wrong.
1384 * </ol>
1385 *
1386 * The only problem with that is, how do we initialise $OUTPUT on first use if,
1387 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1388 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1389 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1390 *
1391 * Note that this class is used before lib/outputlib.php has been loaded, so we
1387fcdd 1392 * must be careful referring to classes/functions from there, they may not be
c84a2dbe 1393 * defined yet, and we must avoid fatal errors.
1394 *
1395 * @copyright 2009 Tim Hunt
1396 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1397 * @since Moodle 2.0
1398 */
1399class bootstrap_renderer {
1400 /**
1401 * Handles re-entrancy. Without this, errors or debugging output that occur
1402 * during the initialisation of $OUTPUT, cause infinite recursion.
1403 * @var boolean
1404 */
1405 protected $initialising = false;
1406
b7009474 1407 /**
1408 * Have we started output yet?
1409 * @return boolean true if the header has been printed.
1410 */
1411 public function has_started() {
1412 return false;
1413 }
1414
41701ffd
PS
1415 /**
1416 * Constructor - to be used by core code only.
34223e03
SH
1417 * @param string $method The method to call
1418 * @param array $arguments Arguments to pass to the method being called
41701ffd
PS
1419 * @return string
1420 */
c84a2dbe 1421 public function __call($method, $arguments) {
b7009474 1422 global $OUTPUT, $PAGE;
c84a2dbe 1423
87b6851c 1424 $recursing = false;
1425 if ($method == 'notification') {
1387fcdd 1426 // Catch infinite recursion caused by debugging output during print_header.
87b6851c 1427 $backtrace = debug_backtrace();
1428 array_shift($backtrace);
1429 array_shift($backtrace);
50764d37 1430 $recursing = is_early_init($backtrace);
87b6851c 1431 }
1432
eb5bdb35
PS
1433 $earlymethods = array(
1434 'fatal_error' => 'early_error',
1435 'notification' => 'early_notification',
1436 );
1437
c84a2dbe 1438 // If lib/outputlib.php has been loaded, call it.
87b6851c 1439 if (!empty($PAGE) && !$recursing) {
eb5bdb35
PS
1440 if (array_key_exists($method, $earlymethods)) {
1441 //prevent PAGE->context warnings - exceptions might appear before we set any context
1442 $PAGE->set_context(null);
1443 }
b7009474 1444 $PAGE->initialise_theme_and_output();
1445 return call_user_func_array(array($OUTPUT, $method), $arguments);
c84a2dbe 1446 }
2142d492 1447
c84a2dbe 1448 $this->initialising = true;
eb5bdb35 1449
c84a2dbe 1450 // Too soon to initialise $OUTPUT, provide a couple of key methods.
c84a2dbe 1451 if (array_key_exists($method, $earlymethods)) {
1452 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1453 }
1454
1455 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1456 }
1457
1458 /**
1387fcdd 1459 * Returns nicely formatted error message in a div box.
f0f8f9a7
PS
1460 * @static
1461 * @param string $message error message
41701ffd
PS
1462 * @param string $moreinfourl (ignored in early errors)
1463 * @param string $link (ignored in early errors)
f0f8f9a7
PS
1464 * @param array $backtrace
1465 * @param string $debuginfo
30fa50d0 1466 * @return string
c84a2dbe 1467 */
3c1ea58b 1468 public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
b7009474 1469 global $CFG;
1470
3c1ea58b
PS
1471 $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1472border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1473width: 80%; -moz-border-radius: 20px; padding: 15px">
1474' . $message . '
1475</div>';
1476 if (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER) {
1477 if (!empty($debuginfo)) {
c5d18164
PS
1478 $debuginfo = s($debuginfo); // removes all nasty JS
1479 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1480 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
3c1ea58b
PS
1481 }
1482 if (!empty($backtrace)) {
1483 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1484 }
1485 }
1486
1487 return $content;
1488 }
1489
1490 /**
1491 * This function should only be called by this class, or from exception handlers
f0f8f9a7
PS
1492 * @static
1493 * @param string $message error message
41701ffd
PS
1494 * @param string $moreinfourl (ignored in early errors)
1495 * @param string $link (ignored in early errors)
f0f8f9a7 1496 * @param array $backtrace
41701ffd 1497 * @param string $debuginfo extra information for developers
3c1ea58b
PS
1498 * @return string
1499 */
1500 public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1adaa404
PS
1501 global $CFG;
1502
1503 if (CLI_SCRIPT) {
1504 echo "!!! $message !!!\n";
1505 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1506 if (!empty($debuginfo)) {
1507 echo "\nDebug info: $debuginfo";
1508 }
1509 if (!empty($backtrace)) {
1510 echo "\nStack trace: " . format_backtrace($backtrace, true);
1511 }
1512 }
1513 return;
1514
1515 } else if (AJAX_SCRIPT) {
1516 $e = new stdClass();
1517 $e->error = $message;
1518 $e->stacktrace = NULL;
1519 $e->debuginfo = NULL;
1520 if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1521 if (!empty($debuginfo)) {
1522 $e->debuginfo = $debuginfo;
1523 }
1524 if (!empty($backtrace)) {
1525 $e->stacktrace = format_backtrace($backtrace, true);
1526 }
1527 }
8a7703ce 1528 @header('Content-Type: application/json; charset=utf-8');
1adaa404
PS
1529 echo json_encode($e);
1530 return;
1531 }
1532
c84a2dbe 1533 // In the name of protocol correctness, monitoring and performance
1387fcdd 1534 // profiling, set the appropriate error headers for machine consumption
c84a2dbe 1535 if (isset($_SERVER['SERVER_PROTOCOL'])) {
1536 // Avoid it with cron.php. Note that we assume it's HTTP/1.x
1387fcdd 1537 // The 503 ode here means our Moodle does not work at all, the error happened too early
c84a2dbe 1538 @header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
1539 }
1540
1541 // better disable any caching
1542 @header('Content-Type: text/html; charset=utf-8');
1543 @header('Cache-Control: no-store, no-cache, must-revalidate');
1544 @header('Cache-Control: post-check=0, pre-check=0', false);
1545 @header('Pragma: no-cache');
1546 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1547 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1548
5e39d7aa 1549 if (function_exists('get_string')) {
c84a2dbe 1550 $strerror = get_string('error');
1551 } else {
c84a2dbe 1552 $strerror = 'Error';
1553 }
1554
3c1ea58b 1555 $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
5e39d7aa 1556
1557 return self::plain_page($strerror, $content);
c84a2dbe 1558 }
1559
f0f8f9a7
PS
1560 /**
1561 * Early notification message
1562 * @static
34223e03 1563 * @param string $message
41701ffd 1564 * @param string $classes usually notifyproblem or notifysuccess
f0f8f9a7
PS
1565 * @return string
1566 */
c84a2dbe 1567 public static function early_notification($message, $classes = 'notifyproblem') {
1568 return '<div class="' . $classes . '">' . $message . '</div>';
1569 }
5e39d7aa 1570
f0f8f9a7
PS
1571 /**
1572 * Page should redirect message.
1573 * @static
34223e03 1574 * @param string $encodedurl redirect url
f0f8f9a7
PS
1575 * @return string
1576 */
5e39d7aa 1577 public static function plain_redirect_message($encodedurl) {
41701ffd 1578 $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
f0f8f9a7 1579 $encodedurl .'">'. get_string('continue') .'</a></div>';
a0a268d5 1580 return self::plain_page(get_string('redirect'), $message);
5e39d7aa 1581 }
1582
f0f8f9a7
PS
1583 /**
1584 * Early redirection page, used before full init of $PAGE global
1585 * @static
34223e03
SH
1586 * @param string $encodedurl redirect url
1587 * @param string $message redirect message
1588 * @param int $delay time in seconds
41701ffd 1589 * @return string redirect page
f0f8f9a7
PS
1590 */
1591 public static function early_redirect_message($encodedurl, $message, $delay) {
1592 $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
1593 $content = self::early_error_content($message, null, null, null);
1594 $content .= self::plain_redirect_message($encodedurl);
1595
1596 return self::plain_page(get_string('redirect'), $content, $meta);
1597 }
1598
1599 /**
1600 * Output basic html page.
1601 * @static
34223e03
SH
1602 * @param string $title page title
1603 * @param string $content page content
41701ffd
PS
1604 * @param string $meta meta tag
1605 * @return string html page
f0f8f9a7
PS
1606 */
1607 protected static function plain_page($title, $content, $meta = '') {
5e39d7aa 1608 if (function_exists('get_string') && function_exists('get_html_lang')) {
1609 $htmllang = get_html_lang();
1610 } else {
1611 $htmllang = '';
1612 }
1613
1614 return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1615<html xmlns="http://www.w3.org/1999/xhtml" ' . $htmllang . '>
1616<head>
1617<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
f0f8f9a7 1618'.$meta.'
5e39d7aa 1619<title>' . $title . '</title>
1620</head><body>' . $content . '</body></html>';
1621 }
c84a2dbe 1622}