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