MDL-18402 Put default value of 1 for grade item's aggregationcoef if parent category...
[moodle.git] / lib / setuplib.php
CommitLineData
251387d0 1<?php // $Id$
2 // These functions are required very early in the Moodle
3 // setup process, before any of the main libraries are
d3f9f1f8 4 // loaded.
5
6
6a525ce2 7/**
8 * Simple class
9 */
10class object {};
11
251387d0 12/**
13 * Base Moodle Exception class
14 */
15class moodle_exception extends Exception {
16 public $errorcode;
17 public $module;
18 public $a;
19 public $link;
eee5d9bb 20 public $debuginfo;
251387d0 21
22 /**
23 * Constructor
24 * @param string $errorcode The name of the string from error.php to print
25 * @param string $module name of module
26 * @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.
27 * @param object $a Extra words and phrases that might be required in the error string
eee5d9bb 28 * @param string $debuginfo optional debugging information
251387d0 29 */
5ca18631 30 function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
31 if (empty($module) || $module == 'moodle' || $module == 'core') {
251387d0 32 $module = 'error';
33 }
34
5ca18631 35 $this->errorcode = $errorcode;
36 $this->module = $module;
37 $this->link = $link;
38 $this->a = $a;
39 $this->debuginfo = $debuginfo;
251387d0 40
5ca18631 41 $message = get_string($errorcode, $module, $a);
251387d0 42
43 parent::__construct($message, 0);
44 }
45}
46
655bbf51 47/**
9214025e 48 * Exception indicating programming error, must be fixed by a programer.
655bbf51 49 */
50class coding_exception extends moodle_exception {
51
52 /**
53 * Constructor
54 * @param string $hint short description of problem
55 * @param string $debuginfo detailed information how to fix problem
56 */
57 function __construct($hint, $debuginfo=null) {
58 parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
59 }
60}
61
251387d0 62/**
63 * Default exception handler, uncought exceptions are equivalent to using print_error()
64 */
65function default_exception_handler($ex) {
1fe1d104 66 global $CFG;
67
251387d0 68 $backtrace = $ex->getTrace();
69 $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
70 array_unshift($backtrace, $place);
71
0ae8f5fc 72 $earlyerror = !isset($CFG->theme) || !isset($CFG->stylesheets);
73 foreach ($backtrace as $stackframe) {
74 if (isset($stackframe['function']) && $stackframe['function'] == 'print_header') {
75 $earlyerror = true;
76 break;
1fe1d104 77 }
0ae8f5fc 78 }
79
80 if ($ex instanceof moodle_exception) {
81 $errorcode = $ex->errorcode;
82 $module = $ex->module;
83 $a = $ex->a;
84 $link = $ex->link;
85 $debuginfo = $ex->debuginfo;
251387d0 86 } else {
0ae8f5fc 87 $errorcode = 'generalexceptionmessage';
88 $module = 'error';
89 $a = $ex->getMessage();
90 $link = '';
91 $debuginfo = null;
92 }
93
94 if ($earlyerror) {
95 _print_early_error($errorcode, $module, $a, $backtrace, $debuginfo);
96 } else {
97 _print_normal_error($errorcode, $module, $a, $link, $backtrace, $debuginfo);
251387d0 98 }
99}
6a525ce2 100
fbf2c91e 101/**
102 * This function verifies the sanity of PHP configuration
103 * and stops execution if anything critical found.
104 */
105function setup_validate_php_configuration() {
106 // this must be very fast - no slow checks here!!!
107
108 if (ini_get_bool('register_globals')) {
109 print_error('globalswarning', 'admin');
110 }
111 if (ini_get_bool('session.auto_start')) {
112 print_error('sessionautostartwarning', 'admin');
113 }
114 if (ini_get_bool('magic_quotes_runtime')) {
115 print_error('fatalmagicquotesruntime', 'admin');
116 }
117}
118
11e7b506 119/**
75781f87 120 * Initialises $FULLME and friends. Private function. Should only be called from
121 * setup.php.
11e7b506 122 */
123function initialise_fullme() {
124 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
125
75781f87 126 // Detect common config error.
84b88cfd 127 if (substr($CFG->wwwroot, -1) == '/') {
128 print_error('wwwrootslash', 'error');
129 }
130
75781f87 131 if (CLI_SCRIPT) {
132 initialise_fullme_cli();
133 return;
37ccf1fe 134 }
11e7b506 135
75781f87 136 $wwwroot = parse_url($CFG->wwwroot);
137 if (!isset($wwwroot['path'])) {
138 $wwwroot['path'] = '';
139 }
140 $wwwroot['path'] .= '/';
141
142 $rurl = setup_get_remote_url();
11e7b506 143
75781f87 144 // Check that URL is under $CFG->wwwroot.
145 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
146 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
147 } else {
148 // Probably some weird external script
149 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
11e7b506 150 return;
151 }
152
75781f87 153 // $CFG->sslproxy specifies if external SSL appliance is used
154 // (That is, the Moodle server uses http, with an external box translating everything to https).
155 if (empty($CFG->sslproxy)) {
156 if ($rurl['scheme'] == 'http' and $wwwroot['scheme'] == 'https') {
157 print_error('sslonlyaccess', 'error');
158 }
159 }
160
161 // $CFG->reverseproxy specifies if reverse proxy server used.
162 // Used in load balancing scenarios.
163 // Do not abuse this to try to solve lan/wan access problems!!!!!
164 if (empty($CFG->reverseproxy)) {
165 if (($rurl['host'] != $wwwroot['host']) or
166 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port'])) {
167 print_error('wwwrootmismatch', 'error', '', $CFG->wwwroot);
168 }
169 }
170
171 // hopefully this will stop all those "clever" admins trying to set up moodle
172 // with two different addresses in intranet and Internet
173 if (!empty($CFG->reverseproxy) && $rurl['host'] == $wwwroot['host']) {
174 print_error('reverseproxyabused', 'error');
175 }
176
177 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
178 if (!empty($wwwroot['port'])) {
179 $hostandport .= ':'.$wwwroot['port'];
180 }
181
182 $FULLSCRIPT = $hostandport . $rurl['path'];
183 $FULLME = $hostandport . $rurl['fullpath'];
184 $ME = $rurl['fullpath'];
185 $rurl['path'] = $rurl['fullpath'];
186}
187
188/**
189 * Initialises $FULLME and friends for command line scripts.
190 * This is a private method for use by initialise_fullme.
191 */
192function initialise_fullme_cli() {
193 // Urls do not make much sense in CLI scripts
194 $backtrace = debug_backtrace();
195 $topfile = array_pop($backtrace);
196 $topfile = realpath($topfile['file']);
197 $dirroot = realpath($CFG->dirroot);
198
199 if (strpos($topfile, $dirroot) !== 0) {
200 // Probably some weird external script
201 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
202 } else {
203 $relativefile = substr($topfile, strlen($dirroot));
204 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
205 $SCRIPT = $FULLSCRIPT = $relativefile;
206 $FULLME = $ME = null;
207 }
208}
209
210/**
211 * Get the URL that PHP/the web server thinks it is serving. Private function
212 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
213 * @return array in the same format that parse_url returns, with the addition of
214 * a 'fullpath' element, which includes any slasharguments path.
215 */
216function setup_get_remote_url() {
11e7b506 217 $rurl = array();
75781f87 218 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
11e7b506 219 $rurl['port'] = $_SERVER['SERVER_PORT'];
75781f87 220 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
11e7b506 221
222 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
223 //Apache server
224 $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
225 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
226
227 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
228 //lighttpd
229 $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
230 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
231
232 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
233 //IIS
234 $rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ? 'http' : 'https';
235 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
236
237 // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
238 // since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
21517960 239 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
11e7b506 240
241 if ($_SERVER['QUERY_STRING'] != '') {
991ec2ee 242 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
11e7b506 243 }
244 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
245
246 } else {
75781f87 247 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
11e7b506 248 }
75781f87 249 return $rurl;
11e7b506 250}
251
d3f9f1f8 252/**
253 * Initializes our performance info early.
254 *
255 * Pairs up with get_performance_info() which is actually
251387d0 256 * in moodlelib.php. This function is here so that we can
257 * call it before all the libs are pulled in.
d3f9f1f8 258 *
259 * @uses $PERF
260 */
261function init_performance_info() {
262
6fc4ad72 263 global $PERF, $CFG, $USER;
251387d0 264
ab130a0b 265 $PERF = new object();
d3f9f1f8 266 $PERF->logwrites = 0;
267 if (function_exists('microtime')) {
268 $PERF->starttime = microtime();
269 }
270 if (function_exists('memory_get_usage')) {
271 $PERF->startmemory = memory_get_usage();
272 }
273 if (function_exists('posix_times')) {
251387d0 274 $PERF->startposixtimes = posix_times();
d3f9f1f8 275 }
b65567f4 276 if (function_exists('apd_set_pprof_trace')) {
277 // APD profiling
6fc4ad72 278 if ($USER->id > 0 && $CFG->perfdebug >= 15) {
251387d0 279 $tempdir = $CFG->dataroot . '/temp/profile/' . $USER->id;
6fc4ad72 280 mkdir($tempdir);
281 apd_set_pprof_trace($tempdir);
282 $PERF->profiling = true;
283 }
b65567f4 284 }
d3f9f1f8 285}
286
76f3815b 287/**
288 * Function to raise the memory limit to a new value.
289 * Will respect the memory limit if it is higher, thus allowing
290 * settings in php.ini, apache conf or command line switches
291 * to override it
292 *
293 * The memory limit should be expressed with a string (eg:'64M')
294 *
295 * @param string $newlimit the new memory limit
296 * @return bool
297 */
11e7b506 298function raise_memory_limit($newlimit) {
76f3815b 299
300 if (empty($newlimit)) {
301 return false;
302 }
303
304 $cur = @ini_get('memory_limit');
305 if (empty($cur)) {
306 // if php is compiled without --enable-memory-limits
307 // apparently memory_limit is set to ''
308 $cur=0;
309 } else {
310 if ($cur == -1){
311 return true; // unlimited mem!
312 }
313 $cur = get_real_size($cur);
314 }
315
316 $new = get_real_size($newlimit);
317 if ($new > $cur) {
318 ini_set('memory_limit', $newlimit);
7022dd39 319 return true;
320 }
321 return false;
322}
323
324/**
325 * Function to reduce the memory limit to a new value.
326 * Will respect the memory limit if it is lower, thus allowing
327 * settings in php.ini, apache conf or command line switches
328 * to override it
329 *
330 * The memory limit should be expressed with a string (eg:'64M')
331 *
332 * @param string $newlimit the new memory limit
333 * @return bool
334 */
335function reduce_memory_limit ($newlimit) {
336 if (empty($newlimit)) {
337 return false;
338 }
339 $cur = @ini_get('memory_limit');
340 if (empty($cur)) {
341 // if php is compiled without --enable-memory-limits
342 // apparently memory_limit is set to ''
343 $cur=0;
344 } else {
345 if ($cur == -1){
346 return true; // unlimited mem!
347 }
348 $cur = get_real_size($cur);
349 }
350
351 $new = get_real_size($newlimit);
352 // -1 is smaller, but it means unlimited
353 if ($new < $cur && $new != -1) {
354 ini_set('memory_limit', $newlimit);
76f3815b 355 return true;
356 }
357 return false;
358}
359
360/**
361 * Converts numbers like 10M into bytes.
362 *
363 * @param mixed $size The size to be converted
364 * @return mixed
365 */
366function get_real_size($size=0) {
367 if (!$size) {
368 return 0;
369 }
11e7b506 370 $scan = array();
76f3815b 371 $scan['MB'] = 1048576;
372 $scan['Mb'] = 1048576;
373 $scan['M'] = 1048576;
374 $scan['m'] = 1048576;
375 $scan['KB'] = 1024;
376 $scan['Kb'] = 1024;
377 $scan['K'] = 1024;
378 $scan['k'] = 1024;
379
380 while (list($key) = each($scan)) {
381 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
382 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
383 break;
384 }
385 }
386 return $size;
387}
388
d3f9f1f8 389/**
390 * Create a directory.
391 *
392 * @uses $CFG
393 * @param string $directory a string of directory names under $CFG->dataroot eg stuff/assignment/1
394 * param bool $shownotices If true then notification messages will be printed out on error.
395 * @return string|false Returns full path to directory if successful, false if not
396 */
397function make_upload_directory($directory, $shownotices=true) {
398
399 global $CFG;
400
401 $currdir = $CFG->dataroot;
402
403 umask(0000);
404
405 if (!file_exists($currdir)) {
b10a14a3 406 if (!mkdir($currdir, $CFG->directorypermissions) or !is_writable($currdir)) {
d3f9f1f8 407 if ($shownotices) {
251387d0 408 echo '<div class="notifyproblem" align="center">ERROR: You need to create the directory '.
d3f9f1f8 409 $currdir .' with web server write access</div>'."<br />\n";
410 }
411 return false;
412 }
d100b8a0 413 }
414
415 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open
416 if (!file_exists($currdir.'/.htaccess')) {
d3f9f1f8 417 if ($handle = fopen($currdir.'/.htaccess', 'w')) { // For safety
d389b128 418 @fwrite($handle, "deny from all\r\nAllowOverride None\r\n");
d3f9f1f8 419 @fclose($handle);
420 }
421 }
422
423 $dirarray = explode('/', $directory);
424
425 foreach ($dirarray as $dir) {
426 $currdir = $currdir .'/'. $dir;
427 if (! file_exists($currdir)) {
428 if (! mkdir($currdir, $CFG->directorypermissions)) {
429 if ($shownotices) {
251387d0 430 echo '<div class="notifyproblem" align="center">ERROR: Could not find or create a directory ('.
d3f9f1f8 431 $currdir .')</div>'."<br />\n";
432 }
433 return false;
434 }
435 //@chmod($currdir, $CFG->directorypermissions); // Just in case mkdir didn't do it
436 }
437 }
438
439 return $currdir;
440}
441
419e1d93 442function init_memcached() {
443 global $CFG, $MCACHE;
444
f917d0ea 445 include_once($CFG->libdir . '/memcached.class.php');
446 $MCACHE = new memcached;
447 if ($MCACHE->status()) {
448 return true;
251387d0 449 }
f917d0ea 450 unset($MCACHE);
251387d0 451 return false;
419e1d93 452}
453
2142d492 454function init_eaccelerator() {
455 global $CFG, $MCACHE;
456
457 include_once($CFG->libdir . '/eaccelerator.class.php');
458 $MCACHE = new eaccelerator;
f917d0ea 459 if ($MCACHE->status()) {
2142d492 460 return true;
251387d0 461 }
2142d492 462 unset($MCACHE);
463 return false;
464}
465
466
467
d3f9f1f8 468?>