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