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