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