MDL-19674 - err - slighly more sensible version of the previous commit.
[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.
23 *
24 * @package moodlecore
25 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
26 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
27 */
d3f9f1f8 28
c84a2dbe 29/// Debug levels ///
30/** no warnings at all */
31define ('DEBUG_NONE', 0);
32/** E_ERROR | E_PARSE */
33define ('DEBUG_MINIMAL', 5);
34/** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */
35define ('DEBUG_NORMAL', 15);
36/** E_ALL without E_STRICT for now, do show recoverable fatal errors */
37define ('DEBUG_ALL', 6143);
38/** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL | 32768) */
39define ('DEBUG_DEVELOPER', 38911);
40
6a525ce2 41/**
42 * Simple class
b37eac91 43 *
44 * @package moodlecore
45 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
46 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
6a525ce2 47 */
48class object {};
49
251387d0 50/**
51 * Base Moodle Exception class
b37eac91 52 *
c84a2dbe 53 * Although this class is defined here, you cannot throw a moodle_exception until
54 * after moodlelib.php has been included (which will happen very soon).
55 *
b37eac91 56 * @package moodlecore
57 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
58 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
251387d0 59 */
60class moodle_exception extends Exception {
61 public $errorcode;
62 public $module;
63 public $a;
64 public $link;
eee5d9bb 65 public $debuginfo;
251387d0 66
67 /**
68 * Constructor
69 * @param string $errorcode The name of the string from error.php to print
70 * @param string $module name of module
71 * @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.
72 * @param object $a Extra words and phrases that might be required in the error string
eee5d9bb 73 * @param string $debuginfo optional debugging information
251387d0 74 */
5ca18631 75 function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
76 if (empty($module) || $module == 'moodle' || $module == 'core') {
251387d0 77 $module = 'error';
78 }
79
5ca18631 80 $this->errorcode = $errorcode;
81 $this->module = $module;
82 $this->link = $link;
83 $this->a = $a;
84 $this->debuginfo = $debuginfo;
251387d0 85
5ca18631 86 $message = get_string($errorcode, $module, $a);
251387d0 87
88 parent::__construct($message, 0);
89 }
90}
91
655bbf51 92/**
cce1b0b9 93 * Exception indicating programming error, must be fixed by a programer. For example
94 * a core API might throw this type of exception if a plugin calls it incorrectly.
b37eac91 95 *
96 * @package moodlecore
97 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
98 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
655bbf51 99 */
100class coding_exception extends moodle_exception {
655bbf51 101 /**
102 * Constructor
103 * @param string $hint short description of problem
104 * @param string $debuginfo detailed information how to fix problem
105 */
106 function __construct($hint, $debuginfo=null) {
107 parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
108 }
109}
110
cce1b0b9 111/**
112 * An exception that indicates something really weird happended. For example,
113 * if you do switch ($context->contextlevel), and have one case for each
114 * CONTEXT_... constant. You might throw an invalid_state_exception in the
f630a546 115 * default case, to just in case something really weird is going on, and
8dc0ae8f 116 * $context->contextlevel is invalid - rather than ignoring this possibility.
b37eac91 117 *
118 * @package moodlecore
119 * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com}
120 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
cce1b0b9 121 */
122class invalid_state_exception extends moodle_exception {
123 /**
124 * Constructor
125 * @param string $hint short description of problem
126 * @param string $debuginfo optional more detailed information
127 */
128 function __construct($hint, $debuginfo=null) {
129 parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
130 }
131}
132
251387d0 133/**
134 * Default exception handler, uncought exceptions are equivalent to using print_error()
fd1a792e 135 *
136 * @param Exception $ex
137 * @param boolean $isupgrade
138 * @param string $plugin
139 * Does not return. Terminates execution.
251387d0 140 */
fd1a792e 141function default_exception_handler($ex, $isupgrade = false, $plugin = null) {
c84a2dbe 142 global $CFG, $DB, $OUTPUT, $SCRIPT;
1fbdf76d 143
144 // detect active db transactions, rollback and log as error
c84a2dbe 145 if ($DB && $DB->is_transaction_started()) {
146 error_log('Database transaction aborted by exception in ' . $CFG->dirroot . $SCRIPT);
1fbdf76d 147 try {
148 // note: transaction blocks should never change current $_SESSION
149 $DB->rollback_sql();
150 } catch (Exception $ignored) {
151 }
152 }
1fe1d104 153
251387d0 154 $backtrace = $ex->getTrace();
155 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
156 array_unshift($backtrace, $place);
157
0ae8f5fc 158 if ($ex instanceof moodle_exception) {
159 $errorcode = $ex->errorcode;
160 $module = $ex->module;
161 $a = $ex->a;
162 $link = $ex->link;
163 $debuginfo = $ex->debuginfo;
251387d0 164 } else {
0ae8f5fc 165 $errorcode = 'generalexceptionmessage';
166 $module = 'error';
167 $a = $ex->getMessage();
168 $link = '';
169 $debuginfo = null;
170 }
171
34a2777c 172 list($message, $moreinfourl, $link) = prepare_error_message($errorcode, $module, $link, $a);
173
fd1a792e 174 if ($isupgrade) {
175 // First log upgrade error
176 upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $message, $backtrace);
177
178 // Always turn on debugging - admins need to know what is going on
179 $CFG->debug = DEBUG_DEVELOPER;
180 }
181
7544d13c 182 // If another exception is thrown when we are already handling one, or during $OUTPUT->header,
183 // and if we did not take special measures, we would just get a very cryptic message
184 // "Exception thrown without a stack frame in Unknown on line 0", rather than the true error.
185 // Therefore, we do take special measures.
186 foreach ($backtrace as $stackframe) {
187 if (isset($stackframe['function']) && isset($stackframe['type']) &&
188 $stackframe['type'] == '->' && $stackframe['function'] == 'header') {
189 echo bootstrap_renderer::early_error($message, $moreinfourl, $link, debug_backtrace());
190 exit(1); // General error code
191 }
192 }
193
c84a2dbe 194 echo $OUTPUT->fatal_error($message, $moreinfourl, $link, debug_backtrace());
34a2777c 195 exit(1); // General error code
196}
197
198/**
199 * Abort execution, displaying an error message.
200 *
201 * @param string $errorcode The name of the language string containing the error message.
202 * Normally this should be in the error.php lang file.
203 * @param string $module The language file to get the error message from.
204 * @param string $link The url where the user will be prompted to continue.
205 * If no url is provided the user will be directed to the site index page.
206 * @param object $a Extra words and phrases that might be required in the error string
207 * @return void terminates script, does not return!
208 */
209function print_error($errorcode, $module = 'error', $link = '', $a = null) {
210 global $OUTPUT, $UNITTEST;
211
212 // Errors in unit test become exceptions, so you can unit test code that might call print_error().
213 if (!empty($UNITTEST->running)) {
214 throw new moodle_exception($errorcode, $module, $link, $a);
215 }
216
217 list($message, $moreinfourl, $link) = prepare_error_message($errorcode, $module, $link, $a);
c84a2dbe 218 echo $OUTPUT->fatal_error($message, $moreinfourl, $link, debug_backtrace());
34a2777c 219
220 exit(1); // General error code
221}
222
223/**
224 * Private method used by print_error and default_exception_handler.
225 * @param $errorcode
226 * @param $module
227 * @param $link
228 * @param $a
229 * @return array
230 */
231function prepare_error_message($errorcode, $module, $link, $a) {
232 global $CFG, $DB, $SESSION;
233
234 if ($DB) {
235 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
236 $DB->set_debug(0);
237 }
238
c84a2dbe 239 // Be careful, no guarantee moodlelib.php is loaded.
34a2777c 240 if (empty($module) || $module == 'moodle' || $module == 'core') {
241 $module = 'error';
242 }
c84a2dbe 243 if (function_exists('get_string')) {
244 $message = get_string($errorcode, $module, $a);
245 if ($module === 'error' and strpos($message, '[[') === 0) {
246 // Search in moodle file if error specified - needed for backwards compatibility
247 $message = get_string($errorcode, 'moodle', $a);
248 }
249 } else {
250 $message = $module . '/' . $errorcode;
251 }
252
253 // Be careful, no guarantee weblib.php is loaded.
254 if (function_exists('clean_text')) {
255 $message = clean_text($message);
256 } else {
257 $message = htmlspecialchars($message);
34a2777c 258 }
34a2777c 259
260 if (!empty($CFG->errordocroot)) {
261 $errordocroot = $CFG->errordocroot;
262 } else if (!empty($CFG->docroot)) {
263 $errordocroot = $CFG->docroot;
264 } else {
265 $errordocroot = 'http://docs.moodle.org';
266 }
267 if ($module === 'error') {
268 $modulelink = 'moodle';
0ae8f5fc 269 } else {
34a2777c 270 $modulelink = $module;
251387d0 271 }
34a2777c 272 $moreinfourl = $errordocroot . '/en/error/' . $modulelink . '/' . $errorcode;
273
274 if (empty($link) && !defined('ADMIN_EXT_HEADER_PRINTED')) {
275 if (!empty($SESSION->fromurl)) {
276 $link = $SESSION->fromurl;
277 unset($SESSION->fromurl);
278 } else {
279 $link = $CFG->wwwroot .'/';
280 }
281 }
282
283 return array($message, $moreinfourl, $link);
284}
285
34a2777c 286/**
287 * Formats a backtrace ready for output.
288 *
289 * @param array $callers backtrace array, as returned by debug_backtrace().
290 * @param boolean $plaintext if false, generates HTML, if true generates plain text.
291 * @return string formatted backtrace, ready for output.
292 */
293function format_backtrace($callers, $plaintext = false) {
294 // do not use $CFG->dirroot because it might not be available in desctructors
295 $dirroot = dirname(dirname(__FILE__));
296
297 if (empty($callers)) {
298 return '';
299 }
300
301 $from = $plaintext ? '' : '<ul style="text-align: left">';
302 foreach ($callers as $caller) {
303 if (!isset($caller['line'])) {
304 $caller['line'] = '?'; // probably call_user_func()
305 }
306 if (!isset($caller['file'])) {
307 $caller['file'] = 'unknownfile'; // probably call_user_func()
308 }
309 $from .= $plaintext ? '* ' : '<li>';
310 $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
311 if (isset($caller['function'])) {
312 $from .= ': call to ';
313 if (isset($caller['class'])) {
314 $from .= $caller['class'] . $caller['type'];
315 }
316 $from .= $caller['function'] . '()';
317 } else if (isset($caller['exception'])) {
318 $from .= ': '.$caller['exception'].' thrown';
319 }
320 $from .= $plaintext ? "\n" : '</li>';
321 }
322 $from .= $plaintext ? '' : '</ul>';
323
324 return $from;
251387d0 325}
6a525ce2 326
fbf2c91e 327/**
328 * This function verifies the sanity of PHP configuration
329 * and stops execution if anything critical found.
330 */
331function setup_validate_php_configuration() {
332 // this must be very fast - no slow checks here!!!
333
334 if (ini_get_bool('register_globals')) {
335 print_error('globalswarning', 'admin');
336 }
337 if (ini_get_bool('session.auto_start')) {
338 print_error('sessionautostartwarning', 'admin');
339 }
340 if (ini_get_bool('magic_quotes_runtime')) {
341 print_error('fatalmagicquotesruntime', 'admin');
342 }
343}
344
11e7b506 345/**
75781f87 346 * Initialises $FULLME and friends. Private function. Should only be called from
347 * setup.php.
11e7b506 348 */
349function initialise_fullme() {
350 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
351
75781f87 352 // Detect common config error.
84b88cfd 353 if (substr($CFG->wwwroot, -1) == '/') {
354 print_error('wwwrootslash', 'error');
355 }
356
75781f87 357 if (CLI_SCRIPT) {
358 initialise_fullme_cli();
359 return;
37ccf1fe 360 }
11e7b506 361
75781f87 362 $wwwroot = parse_url($CFG->wwwroot);
363 if (!isset($wwwroot['path'])) {
364 $wwwroot['path'] = '';
365 }
366 $wwwroot['path'] .= '/';
367
368 $rurl = setup_get_remote_url();
11e7b506 369
75781f87 370 // Check that URL is under $CFG->wwwroot.
371 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
372 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
373 } else {
374 // Probably some weird external script
375 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
11e7b506 376 return;
377 }
378
75781f87 379 // $CFG->sslproxy specifies if external SSL appliance is used
380 // (That is, the Moodle server uses http, with an external box translating everything to https).
381 if (empty($CFG->sslproxy)) {
382 if ($rurl['scheme'] == 'http' and $wwwroot['scheme'] == 'https') {
383 print_error('sslonlyaccess', 'error');
384 }
385 }
386
387 // $CFG->reverseproxy specifies if reverse proxy server used.
388 // Used in load balancing scenarios.
389 // Do not abuse this to try to solve lan/wan access problems!!!!!
390 if (empty($CFG->reverseproxy)) {
391 if (($rurl['host'] != $wwwroot['host']) or
392 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port'])) {
393 print_error('wwwrootmismatch', 'error', '', $CFG->wwwroot);
394 }
395 }
396
397 // hopefully this will stop all those "clever" admins trying to set up moodle
398 // with two different addresses in intranet and Internet
399 if (!empty($CFG->reverseproxy) && $rurl['host'] == $wwwroot['host']) {
400 print_error('reverseproxyabused', 'error');
401 }
402
403 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
404 if (!empty($wwwroot['port'])) {
405 $hostandport .= ':'.$wwwroot['port'];
406 }
407
408 $FULLSCRIPT = $hostandport . $rurl['path'];
409 $FULLME = $hostandport . $rurl['fullpath'];
410 $ME = $rurl['fullpath'];
411 $rurl['path'] = $rurl['fullpath'];
412}
413
414/**
415 * Initialises $FULLME and friends for command line scripts.
416 * This is a private method for use by initialise_fullme.
417 */
418function initialise_fullme_cli() {
80e30f25 419 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
420
75781f87 421 // Urls do not make much sense in CLI scripts
422 $backtrace = debug_backtrace();
423 $topfile = array_pop($backtrace);
424 $topfile = realpath($topfile['file']);
425 $dirroot = realpath($CFG->dirroot);
426
427 if (strpos($topfile, $dirroot) !== 0) {
428 // Probably some weird external script
429 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
430 } else {
431 $relativefile = substr($topfile, strlen($dirroot));
432 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
433 $SCRIPT = $FULLSCRIPT = $relativefile;
434 $FULLME = $ME = null;
435 }
436}
437
438/**
439 * Get the URL that PHP/the web server thinks it is serving. Private function
440 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
441 * @return array in the same format that parse_url returns, with the addition of
442 * a 'fullpath' element, which includes any slasharguments path.
443 */
444function setup_get_remote_url() {
11e7b506 445 $rurl = array();
75781f87 446 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
11e7b506 447 $rurl['port'] = $_SERVER['SERVER_PORT'];
75781f87 448 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
11e7b506 449
450 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
451 //Apache server
452 $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
453 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
454
455 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
456 //lighttpd
457 $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
458 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
459
460 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
461 //IIS
462 $rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ? 'http' : 'https';
463 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
464
465 // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
466 // since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
21517960 467 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
11e7b506 468
469 if ($_SERVER['QUERY_STRING'] != '') {
991ec2ee 470 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
11e7b506 471 }
472 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
473
474 } else {
75781f87 475 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
11e7b506 476 }
75781f87 477 return $rurl;
11e7b506 478}
479
d3f9f1f8 480/**
481 * Initializes our performance info early.
482 *
483 * Pairs up with get_performance_info() which is actually
251387d0 484 * in moodlelib.php. This function is here so that we can
485 * call it before all the libs are pulled in.
d3f9f1f8 486 *
487 * @uses $PERF
488 */
489function init_performance_info() {
490
6fc4ad72 491 global $PERF, $CFG, $USER;
251387d0 492
ab130a0b 493 $PERF = new object();
d3f9f1f8 494 $PERF->logwrites = 0;
495 if (function_exists('microtime')) {
496 $PERF->starttime = microtime();
c84a2dbe 497 }
d3f9f1f8 498 if (function_exists('memory_get_usage')) {
499 $PERF->startmemory = memory_get_usage();
500 }
501 if (function_exists('posix_times')) {
251387d0 502 $PERF->startposixtimes = posix_times();
d3f9f1f8 503 }
b65567f4 504 if (function_exists('apd_set_pprof_trace')) {
505 // APD profiling
6fc4ad72 506 if ($USER->id > 0 && $CFG->perfdebug >= 15) {
251387d0 507 $tempdir = $CFG->dataroot . '/temp/profile/' . $USER->id;
6fc4ad72 508 mkdir($tempdir);
509 apd_set_pprof_trace($tempdir);
510 $PERF->profiling = true;
511 }
b65567f4 512 }
d3f9f1f8 513}
514
31a99877 515/**
516 * Indicates whether we are in the middle of the initial Moodle install.
517 *
518 * Very occasionally it is necessary avoid running certain bits of code before the
519 * Moodle installation has completed. The installed flag is set in admin/index.php
520 * after Moodle core and all the plugins have been installed, but just before
521 * the person doing the initial install is asked to choose the admin password.
522 *
523 * @return boolean true if the initial install is not complete.
524 */
525function during_initial_install() {
526 global $CFG;
527 return empty($CFG->rolesactive);
528}
529
76f3815b 530/**
531 * Function to raise the memory limit to a new value.
532 * Will respect the memory limit if it is higher, thus allowing
533 * settings in php.ini, apache conf or command line switches
534 * to override it
535 *
536 * The memory limit should be expressed with a string (eg:'64M')
537 *
538 * @param string $newlimit the new memory limit
539 * @return bool
540 */
11e7b506 541function raise_memory_limit($newlimit) {
76f3815b 542
543 if (empty($newlimit)) {
544 return false;
545 }
546
547 $cur = @ini_get('memory_limit');
548 if (empty($cur)) {
549 // if php is compiled without --enable-memory-limits
550 // apparently memory_limit is set to ''
551 $cur=0;
552 } else {
553 if ($cur == -1){
554 return true; // unlimited mem!
555 }
556 $cur = get_real_size($cur);
557 }
558
559 $new = get_real_size($newlimit);
560 if ($new > $cur) {
561 ini_set('memory_limit', $newlimit);
7022dd39 562 return true;
563 }
564 return false;
565}
566
567/**
568 * Function to reduce the memory limit to a new value.
569 * Will respect the memory limit if it is lower, thus allowing
570 * settings in php.ini, apache conf or command line switches
571 * to override it
572 *
573 * The memory limit should be expressed with a string (eg:'64M')
574 *
575 * @param string $newlimit the new memory limit
576 * @return bool
577 */
f630a546 578function reduce_memory_limit($newlimit) {
7022dd39 579 if (empty($newlimit)) {
580 return false;
581 }
582 $cur = @ini_get('memory_limit');
583 if (empty($cur)) {
584 // if php is compiled without --enable-memory-limits
585 // apparently memory_limit is set to ''
586 $cur=0;
587 } else {
588 if ($cur == -1){
589 return true; // unlimited mem!
590 }
591 $cur = get_real_size($cur);
592 }
593
594 $new = get_real_size($newlimit);
595 // -1 is smaller, but it means unlimited
596 if ($new < $cur && $new != -1) {
597 ini_set('memory_limit', $newlimit);
76f3815b 598 return true;
599 }
600 return false;
601}
602
603/**
604 * Converts numbers like 10M into bytes.
605 *
606 * @param mixed $size The size to be converted
607 * @return mixed
608 */
609function get_real_size($size=0) {
610 if (!$size) {
611 return 0;
612 }
11e7b506 613 $scan = array();
76f3815b 614 $scan['MB'] = 1048576;
615 $scan['Mb'] = 1048576;
616 $scan['M'] = 1048576;
617 $scan['m'] = 1048576;
618 $scan['KB'] = 1024;
619 $scan['Kb'] = 1024;
620 $scan['K'] = 1024;
621 $scan['k'] = 1024;
622
623 while (list($key) = each($scan)) {
624 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
625 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
626 break;
627 }
628 }
629 return $size;
630}
631
d3f9f1f8 632/**
633 * Create a directory.
634 *
635 * @uses $CFG
636 * @param string $directory a string of directory names under $CFG->dataroot eg stuff/assignment/1
637 * param bool $shownotices If true then notification messages will be printed out on error.
638 * @return string|false Returns full path to directory if successful, false if not
639 */
640function make_upload_directory($directory, $shownotices=true) {
641
642 global $CFG;
643
644 $currdir = $CFG->dataroot;
645
646 umask(0000);
647
648 if (!file_exists($currdir)) {
b10a14a3 649 if (!mkdir($currdir, $CFG->directorypermissions) or !is_writable($currdir)) {
d3f9f1f8 650 if ($shownotices) {
251387d0 651 echo '<div class="notifyproblem" align="center">ERROR: You need to create the directory '.
d3f9f1f8 652 $currdir .' with web server write access</div>'."<br />\n";
653 }
654 return false;
655 }
d100b8a0 656 }
657
658 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open
659 if (!file_exists($currdir.'/.htaccess')) {
d3f9f1f8 660 if ($handle = fopen($currdir.'/.htaccess', 'w')) { // For safety
edaf04d4 661 @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");
d3f9f1f8 662 @fclose($handle);
663 }
664 }
665
666 $dirarray = explode('/', $directory);
667
668 foreach ($dirarray as $dir) {
669 $currdir = $currdir .'/'. $dir;
670 if (! file_exists($currdir)) {
671 if (! mkdir($currdir, $CFG->directorypermissions)) {
672 if ($shownotices) {
251387d0 673 echo '<div class="notifyproblem" align="center">ERROR: Could not find or create a directory ('.
d3f9f1f8 674 $currdir .')</div>'."<br />\n";
675 }
676 return false;
677 }
678 //@chmod($currdir, $CFG->directorypermissions); // Just in case mkdir didn't do it
679 }
680 }
681
682 return $currdir;
683}
684
419e1d93 685function init_memcached() {
686 global $CFG, $MCACHE;
687
f917d0ea 688 include_once($CFG->libdir . '/memcached.class.php');
689 $MCACHE = new memcached;
690 if ($MCACHE->status()) {
691 return true;
251387d0 692 }
f917d0ea 693 unset($MCACHE);
251387d0 694 return false;
419e1d93 695}
696
2142d492 697function init_eaccelerator() {
698 global $CFG, $MCACHE;
699
700 include_once($CFG->libdir . '/eaccelerator.class.php');
701 $MCACHE = new eaccelerator;
f917d0ea 702 if ($MCACHE->status()) {
2142d492 703 return true;
251387d0 704 }
2142d492 705 unset($MCACHE);
706 return false;
707}
708
709
c84a2dbe 710/**
711 * This class solves the problem of how to initialise $OUTPUT.
712 *
713 * The problem is caused be two factors
714 * <ol>
715 * <li>On the one hand, we cannot be sure when output will start. In particular,
716 * an error, which needs to be displayed, could br thrown at any time.</li>
717 * <li>On the other hand, we cannot be sure when we will have all the information
718 * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
719 * (potentially) depends on the current course, course categories, and logged in user.
720 * It also depends on whether the current page requires HTTPS.</li>
721 * </ol>
722 *
723 * So, it is hard to find a single natural place during Moodle script execution,
724 * which we can guarantee is the right time to initialise $OUTPUT. Instead we
725 * adopt the following strategy
726 * <ol>
727 * <li>We will initialise $OUTPUT the first time it is used.</li>
728 * <li>If, after $OUTPUT has been initialised, the script tries to change something
729 * that $OUPTUT depends on, we throw an exception making it clear that the script
730 * did something wrong.
731 * </ol>
732 *
733 * The only problem with that is, how do we initialise $OUTPUT on first use if,
734 * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
735 * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
736 * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
737 *
738 * Note that this class is used before lib/outputlib.php has been loaded, so we
739 * must be careful referring to classes/funtions from there, they may not be
740 * defined yet, and we must avoid fatal errors.
741 *
742 * @copyright 2009 Tim Hunt
743 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
744 * @since Moodle 2.0
745 */
746class bootstrap_renderer {
747 /**
748 * Handles re-entrancy. Without this, errors or debugging output that occur
749 * during the initialisation of $OUTPUT, cause infinite recursion.
750 * @var boolean
751 */
752 protected $initialising = false;
753
754 public function __call($method, $arguments) {
755 global $OUTPUT;
756
757 // If lib/outputlib.php has been loaded, call it.
758 if (!$this->initialising && function_exists('initialise_theme_and_output')) {
759 $this->initialising = true;
760 initialise_theme_and_output(debug_backtrace());
761 if (!($OUTPUT instanceof bootstrap_renderer)) {
762 return call_user_func_array(array($OUTPUT, $method), $arguments);
763 }
764 }
2142d492 765
c84a2dbe 766 $this->initialising = true;
767 // Too soon to initialise $OUTPUT, provide a couple of key methods.
768 $earlymethods = array(
769 'fatal_error' => 'early_error',
770 'notification' => 'early_notification',
771 );
772 if (array_key_exists($method, $earlymethods)) {
773 return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
774 }
775
776 throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
777 }
778
779 /**
780 * This function should only be called by this class, or by
781 * @return unknown_type
782 */
783 public static function early_error($message, $moreinfourl, $link, $backtrace,
784 $debuginfo = null, $showerrordebugwarning = false) {
785 // In the name of protocol correctness, monitoring and performance
786 // profiling, set the appropriate error headers for machine comsumption
787 if (isset($_SERVER['SERVER_PROTOCOL'])) {
788 // Avoid it with cron.php. Note that we assume it's HTTP/1.x
789 @header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
790 }
791
792 // better disable any caching
793 @header('Content-Type: text/html; charset=utf-8');
794 @header('Cache-Control: no-store, no-cache, must-revalidate');
795 @header('Cache-Control: post-check=0, pre-check=0', false);
796 @header('Pragma: no-cache');
797 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
798 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
799
800 if (function_exists('get_string') && function_exists('get_html_lang')) {
801 $htmllang = get_html_lang();
802 $strerror = get_string('error');
803 } else {
804 $htmllang = '';
805 $strerror = 'Error';
806 }
807
c84a2dbe 808 $output = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
809<html xmlns="http://www.w3.org/1999/xhtml" ' . $htmllang . '>
810<head>
811<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
812<title>' . $strerror . '</title>
813</head><body>
814<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
815 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
816 width: 80%; -moz-border-radius: 20px; padding: 15px">
817' . $message . '
818</div>';
819 if (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER) {
820 if (!empty($debuginfo)) {
821 $output .= '<div class="notifytiny">' . $debuginfo . '</div>';
822 }
823 if (!empty($backtrace)) {
824 $output .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
825 }
826 }
827
828 $output .= '</body></html>';
829 return $output;
830 }
831
832 public static function early_notification($message, $classes = 'notifyproblem') {
833 return '<div class="' . $classes . '">' . $message . '</div>';
834 }
835}