MDL-17791 Can make a link from user data when adding a new custom user
[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)) {
80 _print_early_error('generalexceptionmessage', 'error', $ex->getMessage());
81 } else {
82 _print_normal_error('generalexceptionmessage', 'error', $ex->getMessage(), '', $backtrace);
83 }
251387d0 84 }
85}
6a525ce2 86
11e7b506 87/**
88 * Initialises $FULLME and friends.
89 * @return void
90 */
91function initialise_fullme() {
92 global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
93
94 $url = parse_url($CFG->wwwroot);
95
96 if (CLI_SCRIPT) {
97 // urls do not make much sense in CLI scripts
98 $backtrace = debug_backtrace();
99 $topfile = array_pop($backtrace);
100 $topfile = realpath($topfile['file']);
101 $dirroot = realpath($CFG->dirroot);
102
103 if (strpos($topfile, $dirroot) !== 0) {
104 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
105 } else {
106 $relme = substr($topfile, strlen($dirroot));
107 $relme = str_replace('\\', '/', $relme); // Win fix
108 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = $relme;
109 }
110
111 return;
112 }
113
114 $rurl = array();
115 $hostport = explode(':', $_SERVER['HTTP_HOST']);
116 $rurl['host'] = reset($hostport);
117 $rurl['port'] = $_SERVER['SERVER_PORT'];
118 $rurl['path'] = $_SERVER['SCRIPT_NAME']; // script path without slash arguments
119
120 if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
121 //Apache server
122 $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
123 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
124
125 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
126 //lighttpd
127 $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https';
128 $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
129
130 } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
131 //IIS
132 $rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ? 'http' : 'https';
133 $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
134
135 // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
136 // since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
21517960 137 // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
11e7b506 138
139 if ($_SERVER['QUERY_STRING'] != '') {
140 // iis is decoding the query string, let's reencode it in order to emulate QUERY_STRING in Apache
141 // TODO: move this into lib/setup.php
142 $encoded = urlencode($_SERVER['QUERY_STRING']);
143 $encoded = str_replace(urlencode('='), '=', $encoded);
144 $encoded = str_replace(urlencode('%'), '%', $encoded);
145 $encoded = str_replace(urlencode('&'), '&', $encoded);
146 $rurl['fullpath'] .= '?'.$encoded;
147 }
148 $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
149
150 } else {
151 print_error('usupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
152 }
153
154 if (strpos($rurl['path'], $url['path']) === 0) {
155 $SCRIPT = substr($rurl['path'], strlen($url['path']));
156 } else {
157 // probably some weird external script
158 $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
159 return;
160 }
161
162 // $CFG->sslproxy specifies if external SSL apliance is used (server using http, ext box translating everything to https)
163 if (empty($CFG->sslproxy)) {
164 if ($rurl['scheme'] == 'http' and $url['scheme'] == 'https') {
165 print_error('sslonlyaccess', 'error');
166 }
167 }
168
169 // $CFG->reverseproxy specifies if reverse proxy server used - used in advanced load balancing setups only!
170 // this is not supposed to solve lan/wan access problems!!!!!
171 if (empty($CFG->reverseproxy)) {
172 if (($rurl['host'] != $url['host']) or (!empty($url['port']) and $rurl['port'] != $url['port'])) {
173 print_error('wwwrootmismatch', 'error', '', $CFG->wwwroot);
174 }
175 }
176
177 $FULLME = $rurl['scheme'].'://'.$url['host'];
178 if (!empty($url['port'])) {
179 $FULLME .= ':'.$url['port'];
180 }
181 $FULLSCRIPT = $FULLME.$rurl['path'];
182 $FULLME = $FULLME.$rurl['fullpath'];
183 $ME = $rurl['fullpath'];
184
185}
186
d3f9f1f8 187/**
188 * Initializes our performance info early.
189 *
190 * Pairs up with get_performance_info() which is actually
251387d0 191 * in moodlelib.php. This function is here so that we can
192 * call it before all the libs are pulled in.
d3f9f1f8 193 *
194 * @uses $PERF
195 */
196function init_performance_info() {
197
6fc4ad72 198 global $PERF, $CFG, $USER;
251387d0 199
ab130a0b 200 $PERF = new object();
d3f9f1f8 201 $PERF->logwrites = 0;
202 if (function_exists('microtime')) {
203 $PERF->starttime = microtime();
204 }
205 if (function_exists('memory_get_usage')) {
206 $PERF->startmemory = memory_get_usage();
207 }
208 if (function_exists('posix_times')) {
251387d0 209 $PERF->startposixtimes = posix_times();
d3f9f1f8 210 }
b65567f4 211 if (function_exists('apd_set_pprof_trace')) {
212 // APD profiling
6fc4ad72 213 if ($USER->id > 0 && $CFG->perfdebug >= 15) {
251387d0 214 $tempdir = $CFG->dataroot . '/temp/profile/' . $USER->id;
6fc4ad72 215 mkdir($tempdir);
216 apd_set_pprof_trace($tempdir);
217 $PERF->profiling = true;
218 }
b65567f4 219 }
d3f9f1f8 220}
221
76f3815b 222/**
223 * Function to raise the memory limit to a new value.
224 * Will respect the memory limit if it is higher, thus allowing
225 * settings in php.ini, apache conf or command line switches
226 * to override it
227 *
228 * The memory limit should be expressed with a string (eg:'64M')
229 *
230 * @param string $newlimit the new memory limit
231 * @return bool
232 */
11e7b506 233function raise_memory_limit($newlimit) {
76f3815b 234
235 if (empty($newlimit)) {
236 return false;
237 }
238
239 $cur = @ini_get('memory_limit');
240 if (empty($cur)) {
241 // if php is compiled without --enable-memory-limits
242 // apparently memory_limit is set to ''
243 $cur=0;
244 } else {
245 if ($cur == -1){
246 return true; // unlimited mem!
247 }
248 $cur = get_real_size($cur);
249 }
250
251 $new = get_real_size($newlimit);
252 if ($new > $cur) {
253 ini_set('memory_limit', $newlimit);
254 return true;
255 }
256 return false;
257}
258
259/**
260 * Converts numbers like 10M into bytes.
261 *
262 * @param mixed $size The size to be converted
263 * @return mixed
264 */
265function get_real_size($size=0) {
266 if (!$size) {
267 return 0;
268 }
11e7b506 269 $scan = array();
76f3815b 270 $scan['MB'] = 1048576;
271 $scan['Mb'] = 1048576;
272 $scan['M'] = 1048576;
273 $scan['m'] = 1048576;
274 $scan['KB'] = 1024;
275 $scan['Kb'] = 1024;
276 $scan['K'] = 1024;
277 $scan['k'] = 1024;
278
279 while (list($key) = each($scan)) {
280 if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
281 $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
282 break;
283 }
284 }
285 return $size;
286}
287
d3f9f1f8 288/**
289 * Create a directory.
290 *
291 * @uses $CFG
292 * @param string $directory a string of directory names under $CFG->dataroot eg stuff/assignment/1
293 * param bool $shownotices If true then notification messages will be printed out on error.
294 * @return string|false Returns full path to directory if successful, false if not
295 */
296function make_upload_directory($directory, $shownotices=true) {
297
298 global $CFG;
299
300 $currdir = $CFG->dataroot;
301
302 umask(0000);
303
304 if (!file_exists($currdir)) {
305 if (! mkdir($currdir, $CFG->directorypermissions)) {
306 if ($shownotices) {
251387d0 307 echo '<div class="notifyproblem" align="center">ERROR: You need to create the directory '.
d3f9f1f8 308 $currdir .' with web server write access</div>'."<br />\n";
309 }
310 return false;
311 }
d100b8a0 312 }
313
314 // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open
315 if (!file_exists($currdir.'/.htaccess')) {
d3f9f1f8 316 if ($handle = fopen($currdir.'/.htaccess', 'w')) { // For safety
d389b128 317 @fwrite($handle, "deny from all\r\nAllowOverride None\r\n");
d3f9f1f8 318 @fclose($handle);
319 }
320 }
321
322 $dirarray = explode('/', $directory);
323
324 foreach ($dirarray as $dir) {
325 $currdir = $currdir .'/'. $dir;
326 if (! file_exists($currdir)) {
327 if (! mkdir($currdir, $CFG->directorypermissions)) {
328 if ($shownotices) {
251387d0 329 echo '<div class="notifyproblem" align="center">ERROR: Could not find or create a directory ('.
d3f9f1f8 330 $currdir .')</div>'."<br />\n";
331 }
332 return false;
333 }
334 //@chmod($currdir, $CFG->directorypermissions); // Just in case mkdir didn't do it
335 }
336 }
337
338 return $currdir;
339}
340
419e1d93 341function init_memcached() {
342 global $CFG, $MCACHE;
343
f917d0ea 344 include_once($CFG->libdir . '/memcached.class.php');
345 $MCACHE = new memcached;
346 if ($MCACHE->status()) {
347 return true;
251387d0 348 }
f917d0ea 349 unset($MCACHE);
251387d0 350 return false;
419e1d93 351}
352
2142d492 353function init_eaccelerator() {
354 global $CFG, $MCACHE;
355
356 include_once($CFG->libdir . '/eaccelerator.class.php');
357 $MCACHE = new eaccelerator;
f917d0ea 358 if ($MCACHE->status()) {
2142d492 359 return true;
251387d0 360 }
2142d492 361 unset($MCACHE);
362 return false;
363}
364
365
366
d3f9f1f8 367?>