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