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