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