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 | |
c84a2dbe |
29 | /// Debug levels /// |
30 | /** no warnings at all */ |
31 | define ('DEBUG_NONE', 0); |
32 | /** E_ERROR | E_PARSE */ |
33 | define ('DEBUG_MINIMAL', 5); |
34 | /** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */ |
35 | define ('DEBUG_NORMAL', 15); |
36 | /** E_ALL without E_STRICT for now, do show recoverable fatal errors */ |
37 | define ('DEBUG_ALL', 6143); |
38 | /** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL | 32768) */ |
39 | define ('DEBUG_DEVELOPER', 38911); |
40 | |
6a525ce2 |
41 | /** |
b08b3569 |
42 | * Simple class. It is usually used instead of stdClass because it looks |
43 | * more familiar to Java develpers ;-) Do not use for type checking of |
44 | * function parameters. |
b37eac91 |
45 | * |
46 | * @package moodlecore |
47 | * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} |
48 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later |
6a525ce2 |
49 | */ |
b08b3569 |
50 | class object extends stdClass {}; |
6a525ce2 |
51 | |
251387d0 |
52 | /** |
53 | * Base Moodle Exception class |
b37eac91 |
54 | * |
c84a2dbe |
55 | * Although this class is defined here, you cannot throw a moodle_exception until |
56 | * after moodlelib.php has been included (which will happen very soon). |
57 | * |
b37eac91 |
58 | * @package moodlecore |
59 | * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} |
60 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later |
251387d0 |
61 | */ |
62 | class moodle_exception extends Exception { |
63 | public $errorcode; |
64 | public $module; |
65 | public $a; |
66 | public $link; |
eee5d9bb |
67 | public $debuginfo; |
251387d0 |
68 | |
69 | /** |
70 | * Constructor |
71 | * @param string $errorcode The name of the string from error.php to print |
72 | * @param string $module name of module |
73 | * @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. |
74 | * @param object $a Extra words and phrases that might be required in the error string |
eee5d9bb |
75 | * @param string $debuginfo optional debugging information |
251387d0 |
76 | */ |
5ca18631 |
77 | function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) { |
78 | if (empty($module) || $module == 'moodle' || $module == 'core') { |
251387d0 |
79 | $module = 'error'; |
80 | } |
81 | |
5ca18631 |
82 | $this->errorcode = $errorcode; |
83 | $this->module = $module; |
84 | $this->link = $link; |
85 | $this->a = $a; |
86 | $this->debuginfo = $debuginfo; |
251387d0 |
87 | |
5ca18631 |
88 | $message = get_string($errorcode, $module, $a); |
251387d0 |
89 | |
90 | parent::__construct($message, 0); |
91 | } |
92 | } |
93 | |
9a0df45a |
94 | /** |
95 | * Exceptions indicating user does not have permissions to do something |
96 | * and the execution can not continue. |
97 | */ |
98 | class required_capability_exception extends moodle_exception { |
99 | function __construct($context, $capability, $errormessage, $stringfile) { |
100 | $capabilityname = get_capability_string($capability); |
101 | parent::__construct($errormessage, $stringfile, get_context_url($context), $capabilityname); |
102 | } |
103 | } |
104 | |
655bbf51 |
105 | /** |
cce1b0b9 |
106 | * Exception indicating programming error, must be fixed by a programer. For example |
107 | * a core API might throw this type of exception if a plugin calls it incorrectly. |
b37eac91 |
108 | * |
109 | * @package moodlecore |
110 | * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} |
111 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later |
655bbf51 |
112 | */ |
113 | class coding_exception extends moodle_exception { |
655bbf51 |
114 | /** |
115 | * Constructor |
116 | * @param string $hint short description of problem |
117 | * @param string $debuginfo detailed information how to fix problem |
118 | */ |
119 | function __construct($hint, $debuginfo=null) { |
120 | parent::__construct('codingerror', 'debug', '', $hint, $debuginfo); |
121 | } |
122 | } |
123 | |
cce1b0b9 |
124 | /** |
125 | * An exception that indicates something really weird happended. For example, |
126 | * if you do switch ($context->contextlevel), and have one case for each |
127 | * CONTEXT_... constant. You might throw an invalid_state_exception in the |
f630a546 |
128 | * default case, to just in case something really weird is going on, and |
8dc0ae8f |
129 | * $context->contextlevel is invalid - rather than ignoring this possibility. |
b37eac91 |
130 | * |
131 | * @package moodlecore |
132 | * @copyright 1999 onwards Martin Dougiamas {@link http://moodle.com} |
133 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later |
cce1b0b9 |
134 | */ |
135 | class invalid_state_exception extends moodle_exception { |
136 | /** |
137 | * Constructor |
138 | * @param string $hint short description of problem |
139 | * @param string $debuginfo optional more detailed information |
140 | */ |
141 | function __construct($hint, $debuginfo=null) { |
142 | parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo); |
143 | } |
144 | } |
145 | |
251387d0 |
146 | /** |
147 | * Default exception handler, uncought exceptions are equivalent to using print_error() |
fd1a792e |
148 | * |
149 | * @param Exception $ex |
150 | * @param boolean $isupgrade |
151 | * @param string $plugin |
152 | * Does not return. Terminates execution. |
251387d0 |
153 | */ |
fd1a792e |
154 | function default_exception_handler($ex, $isupgrade = false, $plugin = null) { |
c84a2dbe |
155 | global $CFG, $DB, $OUTPUT, $SCRIPT; |
1fbdf76d |
156 | |
157 | // detect active db transactions, rollback and log as error |
c84a2dbe |
158 | if ($DB && $DB->is_transaction_started()) { |
159 | error_log('Database transaction aborted by exception in ' . $CFG->dirroot . $SCRIPT); |
1fbdf76d |
160 | try { |
161 | // note: transaction blocks should never change current $_SESSION |
162 | $DB->rollback_sql(); |
163 | } catch (Exception $ignored) { |
164 | } |
165 | } |
1fe1d104 |
166 | |
251387d0 |
167 | $backtrace = $ex->getTrace(); |
168 | $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex)); |
169 | array_unshift($backtrace, $place); |
170 | |
0ae8f5fc |
171 | if ($ex instanceof moodle_exception) { |
172 | $errorcode = $ex->errorcode; |
173 | $module = $ex->module; |
174 | $a = $ex->a; |
175 | $link = $ex->link; |
176 | $debuginfo = $ex->debuginfo; |
251387d0 |
177 | } else { |
0ae8f5fc |
178 | $errorcode = 'generalexceptionmessage'; |
179 | $module = 'error'; |
180 | $a = $ex->getMessage(); |
181 | $link = ''; |
182 | $debuginfo = null; |
183 | } |
184 | |
34a2777c |
185 | list($message, $moreinfourl, $link) = prepare_error_message($errorcode, $module, $link, $a); |
186 | |
fd1a792e |
187 | if ($isupgrade) { |
188 | // First log upgrade error |
189 | upgrade_log(UPGRADE_LOG_ERROR, $plugin, 'Exception: ' . get_class($ex), $message, $backtrace); |
190 | |
191 | // Always turn on debugging - admins need to know what is going on |
192 | $CFG->debug = DEBUG_DEVELOPER; |
193 | } |
194 | |
b7009474 |
195 | if (is_stacktrace_during_output_init($backtrace)) { |
c72465aa |
196 | echo bootstrap_renderer::early_error($message, $moreinfourl, $link, $backtrace, $debuginfo); |
b7009474 |
197 | } else { |
198 | echo $OUTPUT->fatal_error($message, $moreinfourl, $link, $backtrace, $debuginfo); |
7544d13c |
199 | } |
200 | |
34a2777c |
201 | exit(1); // General error code |
202 | } |
203 | |
b7009474 |
204 | /** |
205 | * This function encapsulates the tests for whether an exception was thrown in the middle |
206 | * of initialising the $OUTPUT variable and starting output. |
207 | * |
208 | * If another exception is thrown then, and if we do not take special measures, |
209 | * we would just get a very cryptic message "Exception thrown without a stack |
210 | * frame in Unknown on line 0". That makes debugging very hard, so we do take |
211 | * special measures in default_exception_handler, with the help of this function. |
212 | * |
213 | * @param array $backtrace the stack trace to analyse. |
214 | * @return boolean whether the stack trace is somewhere in output initialisation. |
215 | */ |
216 | function is_stacktrace_during_output_init($backtrace) { |
217 | $dangerouscode = array( |
218 | array('function' => 'header', 'type' => '->'), |
219 | array('class' => 'bootstrap_renderer'), |
220 | ); |
221 | foreach ($backtrace as $stackframe) { |
222 | foreach ($dangerouscode as $pattern) { |
223 | $matches = true; |
224 | foreach ($pattern as $property => $value) { |
225 | if (!isset($stackframe[$property]) || $stackframe[$property] != $value) { |
226 | $matches = false; |
227 | } |
228 | } |
229 | if ($matches) { |
230 | return true; |
231 | } |
232 | } |
233 | } |
234 | return false; |
235 | } |
236 | |
34a2777c |
237 | /** |
238 | * Abort execution, displaying an error message. |
239 | * |
240 | * @param string $errorcode The name of the language string containing the error message. |
241 | * Normally this should be in the error.php lang file. |
242 | * @param string $module The language file to get the error message from. |
243 | * @param string $link The url where the user will be prompted to continue. |
244 | * If no url is provided the user will be directed to the site index page. |
245 | * @param object $a Extra words and phrases that might be required in the error string |
246 | * @return void terminates script, does not return! |
247 | */ |
248 | function print_error($errorcode, $module = 'error', $link = '', $a = null) { |
249 | global $OUTPUT, $UNITTEST; |
250 | |
251 | // Errors in unit test become exceptions, so you can unit test code that might call print_error(). |
252 | if (!empty($UNITTEST->running)) { |
253 | throw new moodle_exception($errorcode, $module, $link, $a); |
c05e49c7 |
254 | } else { |
255 | // It is really bad if library code calls print_error when output buffering |
256 | // is on. |
257 | while (ob_get_level() > 0) { |
258 | ob_end_clean(); |
259 | } |
34a2777c |
260 | } |
261 | |
262 | list($message, $moreinfourl, $link) = prepare_error_message($errorcode, $module, $link, $a); |
c05e49c7 |
263 | if (is_stacktrace_during_output_init(debug_backtrace())) { |
264 | echo bootstrap_renderer::early_error($message, $moreinfourl, $link, debug_backtrace()); |
265 | } else { |
266 | echo $OUTPUT->fatal_error($message, $moreinfourl, $link, debug_backtrace()); |
267 | } |
34a2777c |
268 | |
269 | exit(1); // General error code |
270 | } |
271 | |
272 | /** |
273 | * Private method used by print_error and default_exception_handler. |
274 | * @param $errorcode |
275 | * @param $module |
276 | * @param $link |
277 | * @param $a |
278 | * @return array |
279 | */ |
280 | function prepare_error_message($errorcode, $module, $link, $a) { |
281 | global $CFG, $DB, $SESSION; |
282 | |
283 | if ($DB) { |
284 | // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish |
285 | $DB->set_debug(0); |
286 | } |
287 | |
c84a2dbe |
288 | // Be careful, no guarantee moodlelib.php is loaded. |
34a2777c |
289 | if (empty($module) || $module == 'moodle' || $module == 'core') { |
290 | $module = 'error'; |
291 | } |
c84a2dbe |
292 | if (function_exists('get_string')) { |
293 | $message = get_string($errorcode, $module, $a); |
294 | if ($module === 'error' and strpos($message, '[[') === 0) { |
295 | // Search in moodle file if error specified - needed for backwards compatibility |
296 | $message = get_string($errorcode, 'moodle', $a); |
297 | } |
298 | } else { |
299 | $message = $module . '/' . $errorcode; |
300 | } |
301 | |
302 | // Be careful, no guarantee weblib.php is loaded. |
303 | if (function_exists('clean_text')) { |
304 | $message = clean_text($message); |
305 | } else { |
306 | $message = htmlspecialchars($message); |
34a2777c |
307 | } |
34a2777c |
308 | |
309 | if (!empty($CFG->errordocroot)) { |
310 | $errordocroot = $CFG->errordocroot; |
311 | } else if (!empty($CFG->docroot)) { |
312 | $errordocroot = $CFG->docroot; |
313 | } else { |
314 | $errordocroot = 'http://docs.moodle.org'; |
315 | } |
316 | if ($module === 'error') { |
317 | $modulelink = 'moodle'; |
0ae8f5fc |
318 | } else { |
34a2777c |
319 | $modulelink = $module; |
251387d0 |
320 | } |
34a2777c |
321 | $moreinfourl = $errordocroot . '/en/error/' . $modulelink . '/' . $errorcode; |
322 | |
d4a03c00 |
323 | if (empty($link)) { |
34a2777c |
324 | if (!empty($SESSION->fromurl)) { |
325 | $link = $SESSION->fromurl; |
326 | unset($SESSION->fromurl); |
327 | } else { |
328 | $link = $CFG->wwwroot .'/'; |
329 | } |
330 | } |
331 | |
332 | return array($message, $moreinfourl, $link); |
333 | } |
334 | |
34a2777c |
335 | /** |
336 | * Formats a backtrace ready for output. |
337 | * |
338 | * @param array $callers backtrace array, as returned by debug_backtrace(). |
339 | * @param boolean $plaintext if false, generates HTML, if true generates plain text. |
340 | * @return string formatted backtrace, ready for output. |
341 | */ |
342 | function format_backtrace($callers, $plaintext = false) { |
343 | // do not use $CFG->dirroot because it might not be available in desctructors |
344 | $dirroot = dirname(dirname(__FILE__)); |
345 | |
346 | if (empty($callers)) { |
347 | return ''; |
348 | } |
349 | |
350 | $from = $plaintext ? '' : '<ul style="text-align: left">'; |
351 | foreach ($callers as $caller) { |
352 | if (!isset($caller['line'])) { |
353 | $caller['line'] = '?'; // probably call_user_func() |
354 | } |
355 | if (!isset($caller['file'])) { |
356 | $caller['file'] = 'unknownfile'; // probably call_user_func() |
357 | } |
358 | $from .= $plaintext ? '* ' : '<li>'; |
359 | $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']); |
360 | if (isset($caller['function'])) { |
361 | $from .= ': call to '; |
362 | if (isset($caller['class'])) { |
363 | $from .= $caller['class'] . $caller['type']; |
364 | } |
365 | $from .= $caller['function'] . '()'; |
366 | } else if (isset($caller['exception'])) { |
367 | $from .= ': '.$caller['exception'].' thrown'; |
368 | } |
369 | $from .= $plaintext ? "\n" : '</li>'; |
370 | } |
371 | $from .= $plaintext ? '' : '</ul>'; |
372 | |
373 | return $from; |
251387d0 |
374 | } |
6a525ce2 |
375 | |
fbf2c91e |
376 | /** |
377 | * This function verifies the sanity of PHP configuration |
378 | * and stops execution if anything critical found. |
379 | */ |
380 | function setup_validate_php_configuration() { |
381 | // this must be very fast - no slow checks here!!! |
382 | |
383 | if (ini_get_bool('register_globals')) { |
384 | print_error('globalswarning', 'admin'); |
385 | } |
386 | if (ini_get_bool('session.auto_start')) { |
387 | print_error('sessionautostartwarning', 'admin'); |
388 | } |
389 | if (ini_get_bool('magic_quotes_runtime')) { |
390 | print_error('fatalmagicquotesruntime', 'admin'); |
391 | } |
392 | } |
393 | |
11e7b506 |
394 | /** |
75781f87 |
395 | * Initialises $FULLME and friends. Private function. Should only be called from |
396 | * setup.php. |
11e7b506 |
397 | */ |
398 | function initialise_fullme() { |
399 | global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT; |
400 | |
75781f87 |
401 | // Detect common config error. |
84b88cfd |
402 | if (substr($CFG->wwwroot, -1) == '/') { |
403 | print_error('wwwrootslash', 'error'); |
404 | } |
405 | |
75781f87 |
406 | if (CLI_SCRIPT) { |
407 | initialise_fullme_cli(); |
408 | return; |
37ccf1fe |
409 | } |
11e7b506 |
410 | |
75781f87 |
411 | $wwwroot = parse_url($CFG->wwwroot); |
412 | if (!isset($wwwroot['path'])) { |
413 | $wwwroot['path'] = ''; |
414 | } |
415 | $wwwroot['path'] .= '/'; |
416 | |
417 | $rurl = setup_get_remote_url(); |
11e7b506 |
418 | |
75781f87 |
419 | // Check that URL is under $CFG->wwwroot. |
420 | if (strpos($rurl['path'], $wwwroot['path']) === 0) { |
421 | $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1); |
422 | } else { |
423 | // Probably some weird external script |
424 | $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null; |
11e7b506 |
425 | return; |
426 | } |
427 | |
75781f87 |
428 | // $CFG->sslproxy specifies if external SSL appliance is used |
429 | // (That is, the Moodle server uses http, with an external box translating everything to https). |
430 | if (empty($CFG->sslproxy)) { |
431 | if ($rurl['scheme'] == 'http' and $wwwroot['scheme'] == 'https') { |
432 | print_error('sslonlyaccess', 'error'); |
433 | } |
434 | } |
435 | |
436 | // $CFG->reverseproxy specifies if reverse proxy server used. |
437 | // Used in load balancing scenarios. |
438 | // Do not abuse this to try to solve lan/wan access problems!!!!! |
439 | if (empty($CFG->reverseproxy)) { |
440 | if (($rurl['host'] != $wwwroot['host']) or |
441 | (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port'])) { |
442 | print_error('wwwrootmismatch', 'error', '', $CFG->wwwroot); |
443 | } |
444 | } |
445 | |
446 | // hopefully this will stop all those "clever" admins trying to set up moodle |
447 | // with two different addresses in intranet and Internet |
448 | if (!empty($CFG->reverseproxy) && $rurl['host'] == $wwwroot['host']) { |
449 | print_error('reverseproxyabused', 'error'); |
450 | } |
451 | |
452 | $hostandport = $rurl['scheme'] . '://' . $wwwroot['host']; |
453 | if (!empty($wwwroot['port'])) { |
454 | $hostandport .= ':'.$wwwroot['port']; |
455 | } |
456 | |
457 | $FULLSCRIPT = $hostandport . $rurl['path']; |
458 | $FULLME = $hostandport . $rurl['fullpath']; |
459 | $ME = $rurl['fullpath']; |
460 | $rurl['path'] = $rurl['fullpath']; |
461 | } |
462 | |
463 | /** |
464 | * Initialises $FULLME and friends for command line scripts. |
465 | * This is a private method for use by initialise_fullme. |
466 | */ |
467 | function initialise_fullme_cli() { |
80e30f25 |
468 | global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT; |
469 | |
75781f87 |
470 | // Urls do not make much sense in CLI scripts |
471 | $backtrace = debug_backtrace(); |
472 | $topfile = array_pop($backtrace); |
473 | $topfile = realpath($topfile['file']); |
474 | $dirroot = realpath($CFG->dirroot); |
475 | |
476 | if (strpos($topfile, $dirroot) !== 0) { |
477 | // Probably some weird external script |
478 | $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null; |
479 | } else { |
480 | $relativefile = substr($topfile, strlen($dirroot)); |
481 | $relativefile = str_replace('\\', '/', $relativefile); // Win fix |
482 | $SCRIPT = $FULLSCRIPT = $relativefile; |
483 | $FULLME = $ME = null; |
484 | } |
485 | } |
486 | |
487 | /** |
488 | * Get the URL that PHP/the web server thinks it is serving. Private function |
489 | * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc. |
490 | * @return array in the same format that parse_url returns, with the addition of |
491 | * a 'fullpath' element, which includes any slasharguments path. |
492 | */ |
493 | function setup_get_remote_url() { |
11e7b506 |
494 | $rurl = array(); |
75781f87 |
495 | list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']); |
11e7b506 |
496 | $rurl['port'] = $_SERVER['SERVER_PORT']; |
75781f87 |
497 | $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments |
11e7b506 |
498 | |
499 | if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) { |
500 | //Apache server |
501 | $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https'; |
502 | $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded |
503 | |
504 | } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) { |
505 | //lighttpd |
506 | $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https'; |
507 | $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded |
508 | |
7e13a265 |
509 | } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) { |
510 | //nginx |
511 | $rurl['scheme'] = empty($_SERVER['HTTPS']) ? 'http' : 'https'; |
512 | $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded |
513 | |
11e7b506 |
514 | } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) { |
515 | //IIS |
516 | $rurl['scheme'] = ($_SERVER['HTTPS'] == 'off') ? 'http' : 'https'; |
517 | $rurl['fullpath'] = $_SERVER['SCRIPT_NAME']; |
518 | |
519 | // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS |
520 | // since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite |
21517960 |
521 | // example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA] |
11e7b506 |
522 | |
523 | if ($_SERVER['QUERY_STRING'] != '') { |
991ec2ee |
524 | $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING']; |
11e7b506 |
525 | } |
526 | $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility |
527 | |
528 | } else { |
75781f87 |
529 | throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']); |
11e7b506 |
530 | } |
75781f87 |
531 | return $rurl; |
11e7b506 |
532 | } |
533 | |
d3f9f1f8 |
534 | /** |
535 | * Initializes our performance info early. |
536 | * |
537 | * Pairs up with get_performance_info() which is actually |
251387d0 |
538 | * in moodlelib.php. This function is here so that we can |
539 | * call it before all the libs are pulled in. |
d3f9f1f8 |
540 | * |
541 | * @uses $PERF |
542 | */ |
543 | function init_performance_info() { |
544 | |
6fc4ad72 |
545 | global $PERF, $CFG, $USER; |
251387d0 |
546 | |
ab130a0b |
547 | $PERF = new object(); |
d3f9f1f8 |
548 | $PERF->logwrites = 0; |
549 | if (function_exists('microtime')) { |
550 | $PERF->starttime = microtime(); |
c84a2dbe |
551 | } |
d3f9f1f8 |
552 | if (function_exists('memory_get_usage')) { |
553 | $PERF->startmemory = memory_get_usage(); |
554 | } |
555 | if (function_exists('posix_times')) { |
251387d0 |
556 | $PERF->startposixtimes = posix_times(); |
d3f9f1f8 |
557 | } |
b65567f4 |
558 | if (function_exists('apd_set_pprof_trace')) { |
559 | // APD profiling |
6fc4ad72 |
560 | if ($USER->id > 0 && $CFG->perfdebug >= 15) { |
251387d0 |
561 | $tempdir = $CFG->dataroot . '/temp/profile/' . $USER->id; |
6fc4ad72 |
562 | mkdir($tempdir); |
563 | apd_set_pprof_trace($tempdir); |
564 | $PERF->profiling = true; |
565 | } |
b65567f4 |
566 | } |
d3f9f1f8 |
567 | } |
568 | |
31a99877 |
569 | /** |
570 | * Indicates whether we are in the middle of the initial Moodle install. |
571 | * |
572 | * Very occasionally it is necessary avoid running certain bits of code before the |
573 | * Moodle installation has completed. The installed flag is set in admin/index.php |
574 | * after Moodle core and all the plugins have been installed, but just before |
575 | * the person doing the initial install is asked to choose the admin password. |
576 | * |
577 | * @return boolean true if the initial install is not complete. |
578 | */ |
579 | function during_initial_install() { |
580 | global $CFG; |
581 | return empty($CFG->rolesactive); |
582 | } |
583 | |
76f3815b |
584 | /** |
585 | * Function to raise the memory limit to a new value. |
586 | * Will respect the memory limit if it is higher, thus allowing |
587 | * settings in php.ini, apache conf or command line switches |
588 | * to override it |
589 | * |
590 | * The memory limit should be expressed with a string (eg:'64M') |
591 | * |
592 | * @param string $newlimit the new memory limit |
593 | * @return bool |
594 | */ |
11e7b506 |
595 | function raise_memory_limit($newlimit) { |
76f3815b |
596 | |
597 | if (empty($newlimit)) { |
598 | return false; |
599 | } |
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 | if ($new > $cur) { |
615 | ini_set('memory_limit', $newlimit); |
7022dd39 |
616 | return true; |
617 | } |
618 | return false; |
619 | } |
620 | |
621 | /** |
622 | * Function to reduce the memory limit to a new value. |
623 | * Will respect the memory limit if it is lower, thus allowing |
624 | * settings in php.ini, apache conf or command line switches |
625 | * to override it |
626 | * |
627 | * The memory limit should be expressed with a string (eg:'64M') |
628 | * |
629 | * @param string $newlimit the new memory limit |
630 | * @return bool |
631 | */ |
f630a546 |
632 | function reduce_memory_limit($newlimit) { |
7022dd39 |
633 | if (empty($newlimit)) { |
634 | return false; |
635 | } |
636 | $cur = @ini_get('memory_limit'); |
637 | if (empty($cur)) { |
638 | // if php is compiled without --enable-memory-limits |
639 | // apparently memory_limit is set to '' |
640 | $cur=0; |
641 | } else { |
642 | if ($cur == -1){ |
643 | return true; // unlimited mem! |
644 | } |
645 | $cur = get_real_size($cur); |
646 | } |
647 | |
648 | $new = get_real_size($newlimit); |
649 | // -1 is smaller, but it means unlimited |
650 | if ($new < $cur && $new != -1) { |
651 | ini_set('memory_limit', $newlimit); |
76f3815b |
652 | return true; |
653 | } |
654 | return false; |
655 | } |
656 | |
657 | /** |
658 | * Converts numbers like 10M into bytes. |
659 | * |
660 | * @param mixed $size The size to be converted |
661 | * @return mixed |
662 | */ |
663 | function get_real_size($size=0) { |
664 | if (!$size) { |
665 | return 0; |
666 | } |
11e7b506 |
667 | $scan = array(); |
76f3815b |
668 | $scan['MB'] = 1048576; |
669 | $scan['Mb'] = 1048576; |
670 | $scan['M'] = 1048576; |
671 | $scan['m'] = 1048576; |
672 | $scan['KB'] = 1024; |
673 | $scan['Kb'] = 1024; |
674 | $scan['K'] = 1024; |
675 | $scan['k'] = 1024; |
676 | |
677 | while (list($key) = each($scan)) { |
678 | if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) { |
679 | $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key]; |
680 | break; |
681 | } |
682 | } |
683 | return $size; |
684 | } |
685 | |
5e39d7aa |
686 | /** |
687 | * Check whether a major upgrade is needed. That is defined as an upgrade that |
688 | * changes something really fundamental in the database, so nothing can possibly |
689 | * work until the database has been updated, and that is defined by the hard-coded |
690 | * version number in this function. |
691 | */ |
692 | function redirect_if_major_upgrade_required() { |
693 | global $CFG; |
694 | $lastmajordbchanges = 2009071000; |
695 | if (empty($CFG->version) or (int)$CFG->version < $lastmajordbchanges or |
696 | during_initial_install() or !empty($CFG->adminsetuppending)) { |
697 | try { |
698 | @session_get_instance()->terminate_current(); |
699 | } catch (Exception $e) { |
700 | // Ignore any errors, redirect to upgrade anyway. |
701 | } |
702 | @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other'); |
703 | @header('Location: ' . $CFG->wwwroot . '/' . $CFG->admin . '/index.php'); |
704 | echo bootstrap_renderer::plain_redirect_message($encodedurl); |
705 | exit; |
706 | } |
707 | } |
708 | |
d3f9f1f8 |
709 | /** |
710 | * Create a directory. |
711 | * |
712 | * @uses $CFG |
713 | * @param string $directory a string of directory names under $CFG->dataroot eg stuff/assignment/1 |
714 | * param bool $shownotices If true then notification messages will be printed out on error. |
715 | * @return string|false Returns full path to directory if successful, false if not |
716 | */ |
717 | function make_upload_directory($directory, $shownotices=true) { |
718 | |
719 | global $CFG; |
720 | |
721 | $currdir = $CFG->dataroot; |
722 | |
723 | umask(0000); |
724 | |
725 | if (!file_exists($currdir)) { |
b10a14a3 |
726 | if (!mkdir($currdir, $CFG->directorypermissions) or !is_writable($currdir)) { |
d3f9f1f8 |
727 | if ($shownotices) { |
251387d0 |
728 | echo '<div class="notifyproblem" align="center">ERROR: You need to create the directory '. |
d3f9f1f8 |
729 | $currdir .' with web server write access</div>'."<br />\n"; |
730 | } |
731 | return false; |
732 | } |
d100b8a0 |
733 | } |
734 | |
735 | // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open |
736 | if (!file_exists($currdir.'/.htaccess')) { |
d3f9f1f8 |
737 | if ($handle = fopen($currdir.'/.htaccess', 'w')) { // For safety |
edaf04d4 |
738 | @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 |
739 | @fclose($handle); |
740 | } |
741 | } |
742 | |
743 | $dirarray = explode('/', $directory); |
744 | |
745 | foreach ($dirarray as $dir) { |
746 | $currdir = $currdir .'/'. $dir; |
747 | if (! file_exists($currdir)) { |
748 | if (! mkdir($currdir, $CFG->directorypermissions)) { |
749 | if ($shownotices) { |
251387d0 |
750 | echo '<div class="notifyproblem" align="center">ERROR: Could not find or create a directory ('. |
d3f9f1f8 |
751 | $currdir .')</div>'."<br />\n"; |
752 | } |
753 | return false; |
754 | } |
755 | //@chmod($currdir, $CFG->directorypermissions); // Just in case mkdir didn't do it |
756 | } |
757 | } |
758 | |
759 | return $currdir; |
760 | } |
761 | |
419e1d93 |
762 | function init_memcached() { |
763 | global $CFG, $MCACHE; |
764 | |
f917d0ea |
765 | include_once($CFG->libdir . '/memcached.class.php'); |
766 | $MCACHE = new memcached; |
767 | if ($MCACHE->status()) { |
768 | return true; |
251387d0 |
769 | } |
f917d0ea |
770 | unset($MCACHE); |
251387d0 |
771 | return false; |
419e1d93 |
772 | } |
773 | |
2142d492 |
774 | function init_eaccelerator() { |
775 | global $CFG, $MCACHE; |
776 | |
777 | include_once($CFG->libdir . '/eaccelerator.class.php'); |
778 | $MCACHE = new eaccelerator; |
f917d0ea |
779 | if ($MCACHE->status()) { |
2142d492 |
780 | return true; |
251387d0 |
781 | } |
2142d492 |
782 | unset($MCACHE); |
783 | return false; |
784 | } |
785 | |
786 | |
c84a2dbe |
787 | /** |
788 | * This class solves the problem of how to initialise $OUTPUT. |
789 | * |
790 | * The problem is caused be two factors |
791 | * <ol> |
792 | * <li>On the one hand, we cannot be sure when output will start. In particular, |
793 | * an error, which needs to be displayed, could br thrown at any time.</li> |
794 | * <li>On the other hand, we cannot be sure when we will have all the information |
795 | * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which |
796 | * (potentially) depends on the current course, course categories, and logged in user. |
797 | * It also depends on whether the current page requires HTTPS.</li> |
798 | * </ol> |
799 | * |
800 | * So, it is hard to find a single natural place during Moodle script execution, |
801 | * which we can guarantee is the right time to initialise $OUTPUT. Instead we |
802 | * adopt the following strategy |
803 | * <ol> |
804 | * <li>We will initialise $OUTPUT the first time it is used.</li> |
805 | * <li>If, after $OUTPUT has been initialised, the script tries to change something |
7e0d6675 |
806 | * that $OUTPUT depends on, we throw an exception making it clear that the script |
c84a2dbe |
807 | * did something wrong. |
808 | * </ol> |
809 | * |
810 | * The only problem with that is, how do we initialise $OUTPUT on first use if, |
811 | * it is going to be used like $OUTPUT->somthing(...)? Well that is where this |
812 | * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then, |
813 | * when any method is called on that object, we initialise $OUTPUT, and pass the call on. |
814 | * |
815 | * Note that this class is used before lib/outputlib.php has been loaded, so we |
816 | * must be careful referring to classes/funtions from there, they may not be |
817 | * defined yet, and we must avoid fatal errors. |
818 | * |
819 | * @copyright 2009 Tim Hunt |
820 | * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later |
821 | * @since Moodle 2.0 |
822 | */ |
823 | class bootstrap_renderer { |
824 | /** |
825 | * Handles re-entrancy. Without this, errors or debugging output that occur |
826 | * during the initialisation of $OUTPUT, cause infinite recursion. |
827 | * @var boolean |
828 | */ |
829 | protected $initialising = false; |
830 | |
b7009474 |
831 | /** |
832 | * Have we started output yet? |
833 | * @return boolean true if the header has been printed. |
834 | */ |
835 | public function has_started() { |
836 | return false; |
837 | } |
838 | |
c84a2dbe |
839 | public function __call($method, $arguments) { |
b7009474 |
840 | global $OUTPUT, $PAGE; |
c84a2dbe |
841 | |
87b6851c |
842 | $recursing = false; |
843 | if ($method == 'notification') { |
844 | // Catch infinite recursion cuased by debugging output during print_header. |
845 | $backtrace = debug_backtrace(); |
846 | array_shift($backtrace); |
847 | array_shift($backtrace); |
848 | $recursing = is_stacktrace_during_output_init($backtrace); |
849 | } |
850 | |
c84a2dbe |
851 | // If lib/outputlib.php has been loaded, call it. |
87b6851c |
852 | if (!empty($PAGE) && !$recursing) { |
b7009474 |
853 | $PAGE->initialise_theme_and_output(); |
854 | return call_user_func_array(array($OUTPUT, $method), $arguments); |
c84a2dbe |
855 | } |
2142d492 |
856 | |
c84a2dbe |
857 | $this->initialising = true; |
858 | // Too soon to initialise $OUTPUT, provide a couple of key methods. |
859 | $earlymethods = array( |
860 | 'fatal_error' => 'early_error', |
861 | 'notification' => 'early_notification', |
862 | ); |
863 | if (array_key_exists($method, $earlymethods)) { |
864 | return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments); |
865 | } |
866 | |
867 | throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.'); |
868 | } |
869 | |
870 | /** |
871 | * This function should only be called by this class, or by |
872 | * @return unknown_type |
873 | */ |
874 | public static function early_error($message, $moreinfourl, $link, $backtrace, |
875 | $debuginfo = null, $showerrordebugwarning = false) { |
b7009474 |
876 | global $CFG; |
877 | |
c84a2dbe |
878 | // In the name of protocol correctness, monitoring and performance |
879 | // profiling, set the appropriate error headers for machine comsumption |
880 | if (isset($_SERVER['SERVER_PROTOCOL'])) { |
881 | // Avoid it with cron.php. Note that we assume it's HTTP/1.x |
882 | @header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable'); |
883 | } |
884 | |
885 | // better disable any caching |
886 | @header('Content-Type: text/html; charset=utf-8'); |
887 | @header('Cache-Control: no-store, no-cache, must-revalidate'); |
888 | @header('Cache-Control: post-check=0, pre-check=0', false); |
889 | @header('Pragma: no-cache'); |
890 | @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT'); |
891 | @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); |
892 | |
5e39d7aa |
893 | if (function_exists('get_string')) { |
c84a2dbe |
894 | $strerror = get_string('error'); |
895 | } else { |
c84a2dbe |
896 | $strerror = 'Error'; |
897 | } |
898 | |
5e39d7aa |
899 | $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px; |
c84a2dbe |
900 | border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse; |
901 | width: 80%; -moz-border-radius: 20px; padding: 15px"> |
902 | ' . $message . ' |
903 | </div>'; |
904 | if (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER) { |
905 | if (!empty($debuginfo)) { |
5e39d7aa |
906 | $content .= '<div class="notifytiny">' . $debuginfo . '</div>'; |
c84a2dbe |
907 | } |
908 | if (!empty($backtrace)) { |
5e39d7aa |
909 | $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>'; |
c84a2dbe |
910 | } |
911 | } |
5e39d7aa |
912 | |
913 | return self::plain_page($strerror, $content); |
c84a2dbe |
914 | } |
915 | |
916 | public static function early_notification($message, $classes = 'notifyproblem') { |
917 | return '<div class="' . $classes . '">' . $message . '</div>'; |
918 | } |
5e39d7aa |
919 | |
920 | public static function plain_redirect_message($encodedurl) { |
921 | $message = '<p>' . get_string('pageshouldredirect') . '</p><p><a href="'. |
922 | $encodedurl .'">'. get_string('continue') .'</a></p>'; |
a0a268d5 |
923 | return self::plain_page(get_string('redirect'), $message); |
5e39d7aa |
924 | } |
925 | |
926 | protected static function plain_page($title, $content) { |
927 | if (function_exists('get_string') && function_exists('get_html_lang')) { |
928 | $htmllang = get_html_lang(); |
929 | } else { |
930 | $htmllang = ''; |
931 | } |
932 | |
933 | return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> |
934 | <html xmlns="http://www.w3.org/1999/xhtml" ' . $htmllang . '> |
935 | <head> |
936 | <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> |
937 | <title>' . $title . '</title> |
938 | </head><body>' . $content . '</body></html>'; |
939 | } |
c84a2dbe |
940 | } |