MDL-16438 standardized component names
[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
0ae8f5fc 138 $earlyerror = !isset($CFG->theme) || !isset($CFG->stylesheets);
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
160 if ($earlyerror) {
161 _print_early_error($errorcode, $module, $a, $backtrace, $debuginfo);
162 } else {
163 _print_normal_error($errorcode, $module, $a, $link, $backtrace, $debuginfo);
251387d0 164 }
165}
6a525ce2 166
fbf2c91e 167/**
168 * This function verifies the sanity of PHP configuration
169 * and stops execution if anything critical found.
170 */
171function setup_validate_php_configuration() {
172 // this must be very fast - no slow checks here!!!
173
174 if (ini_get_bool('register_globals')) {
175 print_error('globalswarning', 'admin');
176 }
177 if (ini_get_bool('session.auto_start')) {
178 print_error('sessionautostartwarning', 'admin');
179 }
180 if (ini_get_bool('magic_quotes_runtime')) {
181 print_error('fatalmagicquotesruntime', 'admin');
182 }
183}
184
11e7b506 185/**
75781f87 186 * Initialises $FULLME and friends. Private function. Should only be called from
187 * setup.php.
11e7b506 188 */
189function initialise_fullme() {
190 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
191
75781f87 192 // Detect common config error.
84b88cfd 193 if (substr($CFG->wwwroot, -1) == '/') {
194 print_error('wwwrootslash', 'error');
195 }
196
75781f87 197 if (CLI_SCRIPT) {
198 initialise_fullme_cli();
199 return;
37ccf1fe 200 }
11e7b506 201
75781f87 202 $wwwroot = parse_url($CFG->wwwroot);
203 if (!isset($wwwroot['path'])) {
204 $wwwroot['path'] = '';
205 }
206 $wwwroot['path'] .= '/';
207
208 $rurl = setup_get_remote_url();
11e7b506 209
75781f87 210 // Check that URL is under $CFG->wwwroot.
211 if (strpos($rurl['path'], $wwwroot['path']) === 0) {
212 $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
213 } else {
214 // Probably some weird external script
215 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
11e7b506 216 return;
217 }
218
75781f87 219 // $CFG->sslproxy specifies if external SSL appliance is used
220 // (That is, the Moodle server uses http, with an external box translating everything to https).
221 if (empty($CFG->sslproxy)) {
222 if ($rurl['scheme'] == 'http' and $wwwroot['scheme'] == 'https') {
223 print_error('sslonlyaccess', 'error');
224 }
225 }
226
227 // $CFG->reverseproxy specifies if reverse proxy server used.
228 // Used in load balancing scenarios.
229 // Do not abuse this to try to solve lan/wan access problems!!!!!
230 if (empty($CFG->reverseproxy)) {
231 if (($rurl['host'] != $wwwroot['host']) or
232 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port'])) {
233 print_error('wwwrootmismatch', 'error', '', $CFG->wwwroot);
234 }
235 }
236
237 // hopefully this will stop all those "clever" admins trying to set up moodle
238 // with two different addresses in intranet and Internet
239 if (!empty($CFG->reverseproxy) && $rurl['host'] == $wwwroot['host']) {
240 print_error('reverseproxyabused', 'error');
241 }
242
243 $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
244 if (!empty($wwwroot['port'])) {
245 $hostandport .= ':'.$wwwroot['port'];
246 }
247
248 $FULLSCRIPT = $hostandport . $rurl['path'];
249 $FULLME = $hostandport . $rurl['fullpath'];
250 $ME = $rurl['fullpath'];
251 $rurl['path'] = $rurl['fullpath'];
252}
253
254/**
255 * Initialises $FULLME and friends for command line scripts.
256 * This is a private method for use by initialise_fullme.
257 */
258function initialise_fullme_cli() {
80e30f25 259 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
260
75781f87 261 // Urls do not make much sense in CLI scripts
262 $backtrace = debug_backtrace();
263 $topfile = array_pop($backtrace);
264 $topfile = realpath($topfile['file']);
265 $dirroot = realpath($CFG->dirroot);
266
267 if (strpos($topfile, $dirroot) !== 0) {
268 // Probably some weird external script
269 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
270 } else {
271 $relativefile = substr($topfile, strlen($dirroot));
272 $relativefile = str_replace('\\', '/', $relativefile); // Win fix
273 $SCRIPT = $FULLSCRIPT = $relativefile;
274 $FULLME = $ME = null;
275 }
276}
277
278/**
279 * Get the URL that PHP/the web server thinks it is serving. Private function
280 * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
281 * @return array in the same format that parse_url returns, with the addition of
282 * a 'fullpath' element, which includes any slasharguments path.
283 */
284function setup_get_remote_url() {
11e7b506 285 $rurl = array();
75781f87 286 list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
11e7b506 287 $rurl['port'] = $_SERVER['SERVER_PORT'];
75781f87 288 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
11e7b506 289
290 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
291 //Apache server
292 $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
293 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
294
295 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
296 //lighttpd
297 $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
298 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
299
300 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
301 //IIS
302 $rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ? 'http' : 'https';
303 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
304
305 // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
306 // since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
21517960 307 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
11e7b506 308
309 if ($_SERVER['QUERY_STRING'] != '') {
991ec2ee 310 $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
11e7b506 311 }
312 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
313
314 } else {
75781f87 315 throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
11e7b506 316 }
75781f87 317 return $rurl;
11e7b506 318}
319
d3f9f1f8 320/**
321 * Initializes our performance info early.
322 *
323 * Pairs up with get_performance_info() which is actually
251387d0 324 * in moodlelib.php. This function is here so that we can
325 * call it before all the libs are pulled in.
d3f9f1f8 326 *
327 * @uses $PERF
328 */
329function init_performance_info() {
330
6fc4ad72 331 global $PERF, $CFG, $USER;
251387d0 332
ab130a0b 333 $PERF = new object();
d3f9f1f8 334 $PERF->logwrites = 0;
335 if (function_exists('microtime')) {
336 $PERF->starttime = microtime();
337 }
338 if (function_exists('memory_get_usage')) {
339 $PERF->startmemory = memory_get_usage();
340 }
341 if (function_exists('posix_times')) {
251387d0 342 $PERF->startposixtimes = posix_times();
d3f9f1f8 343 }
b65567f4 344 if (function_exists('apd_set_pprof_trace')) {
345 // APD profiling
6fc4ad72 346 if ($USER->id > 0 && $CFG->perfdebug >= 15) {
251387d0 347 $tempdir = $CFG->dataroot . '/temp/profile/' . $USER->id;
6fc4ad72 348 mkdir($tempdir);
349 apd_set_pprof_trace($tempdir);
350 $PERF->profiling = true;
351 }
b65567f4 352 }
d3f9f1f8 353}
354
31a99877 355/**
356 * Indicates whether we are in the middle of the initial Moodle install.
357 *
358 * Very occasionally it is necessary avoid running certain bits of code before the
359 * Moodle installation has completed. The installed flag is set in admin/index.php
360 * after Moodle core and all the plugins have been installed, but just before
361 * the person doing the initial install is asked to choose the admin password.
362 *
363 * @return boolean true if the initial install is not complete.
364 */
365function during_initial_install() {
366 global $CFG;
367 return empty($CFG->rolesactive);
368}
369
76f3815b 370/**
371 * Function to raise the memory limit to a new value.
372 * Will respect the memory limit if it is higher, thus allowing
373 * settings in php.ini, apache conf or command line switches
374 * to override it
375 *
376 * The memory limit should be expressed with a string (eg:'64M')
377 *
378 * @param string $newlimit the new memory limit
379 * @return bool
380 */
11e7b506 381function raise_memory_limit($newlimit) {
76f3815b 382
383 if (empty($newlimit)) {
384 return false;
385 }
386
387 $cur = @ini_get('memory_limit');
388 if (empty($cur)) {
389 // if php is compiled without --enable-memory-limits
390 // apparently memory_limit is set to ''
391 $cur=0;
392 } else {
393 if ($cur == -1){
394 return true; // unlimited mem!
395 }
396 $cur = get_real_size($cur);
397 }
398
399 $new = get_real_size($newlimit);
400 if ($new > $cur) {
401 ini_set('memory_limit', $newlimit);
7022dd39 402 return true;
403 }
404 return false;
405}
406
407/**
408 * Function to reduce the memory limit to a new value.
409 * Will respect the memory limit if it is lower, thus allowing
410 * settings in php.ini, apache conf or command line switches
411 * to override it
412 *
413 * The memory limit should be expressed with a string (eg:'64M')
414 *
415 * @param string $newlimit the new memory limit
416 * @return bool
417 */
f630a546 418function reduce_memory_limit($newlimit) {
7022dd39 419 if (empty($newlimit)) {
420 return false;
421 }
422 $cur = @ini_get('memory_limit');
423 if (empty($cur)) {
424 // if php is compiled without --enable-memory-limits
425 // apparently memory_limit is set to ''
426 $cur=0;
427 } else {
428 if ($cur == -1){
429 return true; // unlimited mem!
430 }
431 $cur = get_real_size($cur);
432 }
433
434 $new = get_real_size($newlimit);
435 // -1 is smaller, but it means unlimited
436 if ($new < $cur && $new != -1) {
437 ini_set('memory_limit', $newlimit);
76f3815b 438 return true;
439 }
440 return false;
441}
442
443/**
444 * Converts numbers like 10M into bytes.
445 *
446 * @param mixed $size The size to be converted
447 * @return mixed
448 */
449function get_real_size($size=0) {
450 if (!$size) {
451 return 0;
452 }
11e7b506 453 $scan = array();
76f3815b 454 $scan['MB'] = 1048576;
455 $scan['Mb'] = 1048576;
456 $scan['M'] = 1048576;
457 $scan['m'] = 1048576;
458 $scan['KB'] = 1024;
459 $scan['Kb'] = 1024;
460 $scan['K'] = 1024;
461 $scan['k'] = 1024;
462
463 while (list($key) = each($scan)) {
464 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
465 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
466 break;
467 }
468 }
469 return $size;
470}
471
d3f9f1f8 472/**
473 * Create a directory.
474 *
475 * @uses $CFG
476 * @param string $directory a string of directory names under $CFG->dataroot eg stuff/assignment/1
477 * param bool $shownotices If true then notification messages will be printed out on error.
478 * @return string|false Returns full path to directory if successful, false if not
479 */
480function make_upload_directory($directory, $shownotices=true) {
481
482 global $CFG;
483
484 $currdir = $CFG->dataroot;
485
486 umask(0000);
487
488 if (!file_exists($currdir)) {
b10a14a3 489 if (!mkdir($currdir, $CFG->directorypermissions) or !is_writable($currdir)) {
d3f9f1f8 490 if ($shownotices) {
251387d0 491 echo '<div class="notifyproblem" align="center">ERROR: You need to create the directory '.
d3f9f1f8 492 $currdir .' with web server write access</div>'."<br />\n";
493 }
494 return false;
495 }
d100b8a0 496 }
497
498 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open
499 if (!file_exists($currdir.'/.htaccess')) {
d3f9f1f8 500 if ($handle = fopen($currdir.'/.htaccess', 'w')) { // For safety
edaf04d4 501 @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 502 @fclose($handle);
503 }
504 }
505
506 $dirarray = explode('/', $directory);
507
508 foreach ($dirarray as $dir) {
509 $currdir = $currdir .'/'. $dir;
510 if (! file_exists($currdir)) {
511 if (! mkdir($currdir, $CFG->directorypermissions)) {
512 if ($shownotices) {
251387d0 513 echo '<div class="notifyproblem" align="center">ERROR: Could not find or create a directory ('.
d3f9f1f8 514 $currdir .')</div>'."<br />\n";
515 }
516 return false;
517 }
518 //@chmod($currdir, $CFG->directorypermissions); // Just in case mkdir didn't do it
519 }
520 }
521
522 return $currdir;
523}
524
419e1d93 525function init_memcached() {
526 global $CFG, $MCACHE;
527
f917d0ea 528 include_once($CFG->libdir . '/memcached.class.php');
529 $MCACHE = new memcached;
530 if ($MCACHE->status()) {
531 return true;
251387d0 532 }
f917d0ea 533 unset($MCACHE);
251387d0 534 return false;
419e1d93 535}
536
2142d492 537function init_eaccelerator() {
538 global $CFG, $MCACHE;
539
540 include_once($CFG->libdir . '/eaccelerator.class.php');
541 $MCACHE = new eaccelerator;
f917d0ea 542 if ($MCACHE->status()) {
2142d492 543 return true;
251387d0 544 }
2142d492 545 unset($MCACHE);
546 return false;
547}
548
549
550
d3f9f1f8 551?>