MDL-30328 some whitespace changes
[moodle.git] / lib / setuplib.php
1 <?php
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/>.
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    core
25  * @subpackage lib
26  * @copyright  1999 onwards Martin Dougiamas  {@link http://moodle.com}
27  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
28  */
30 defined('MOODLE_INTERNAL') || die();
32 /// Debug levels ///
33 /** no warnings at all */
34 define('DEBUG_NONE', 0);
35 /** E_ERROR | E_PARSE */
36 define('DEBUG_MINIMAL', 5);
37 /** E_ERROR | E_PARSE | E_WARNING | E_NOTICE */
38 define('DEBUG_NORMAL', 15);
39 /** E_ALL without E_STRICT for now, do show recoverable fatal errors */
40 define('DEBUG_ALL', 6143);
41 /** DEBUG_ALL with extra Moodle debug messages - (DEBUG_ALL | 32768) */
42 define('DEBUG_DEVELOPER', 38911);
44 /** Remove any memory limits */
45 define('MEMORY_UNLIMITED', -1);
46 /** Standard memory limit for given platform */
47 define('MEMORY_STANDARD', -2);
48 /**
49  * Large memory limit for given platform - used in cron, upgrade, and other places that need a lot of memory.
50  * Can be overridden with $CFG->extramemorylimit setting.
51  */
52 define('MEMORY_EXTRA', -3);
53 /** Extremely large memory limit - not recommended for standard scripts */
54 define('MEMORY_HUGE', -4);
56 /**
57  * Software maturity levels used by the core and plugins
58  */
59 define('MATURITY_ALPHA',    50);    // internals can be tested using white box techniques
60 define('MATURITY_BETA',     100);   // feature complete, ready for preview and testing
61 define('MATURITY_RC',       150);   // tested, will be released unless there are fatal bugs
62 define('MATURITY_STABLE',   200);   // ready for production deployment
64 /**
65  * Special value that can be used in $plugin->dependencies in version.php files.
66  */
67 define('ANY_VERSION', 'any');
70 /**
71  * Simple class. It is usually used instead of stdClass because it looks
72  * more familiar to Java developers ;-) Do not use for type checking of
73  * function parameters. Please use stdClass instead.
74  *
75  * @package    core
76  * @subpackage lib
77  * @copyright  2009 Petr Skoda  {@link http://skodak.org}
78  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
79  * @deprecated since 2.0
80  */
81 class object extends stdClass {};
83 /**
84  * Base Moodle Exception class
85  *
86  * Although this class is defined here, you cannot throw a moodle_exception until
87  * after moodlelib.php has been included (which will happen very soon).
88  *
89  * @package    core
90  * @subpackage lib
91  * @copyright  2008 Petr Skoda  {@link http://skodak.org}
92  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
93  */
94 class moodle_exception extends Exception {
95     public $errorcode;
96     public $module;
97     public $a;
98     public $link;
99     public $debuginfo;
101     /**
102      * Constructor
103      * @param string $errorcode The name of the string from error.php to print
104      * @param string $module name of module
105      * @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.
106      * @param object $a Extra words and phrases that might be required in the error string
107      * @param string $debuginfo optional debugging information
108      */
109     function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
110         if (empty($module) || $module == 'moodle' || $module == 'core') {
111             $module = 'error';
112         }
114         $this->errorcode = $errorcode;
115         $this->module    = $module;
116         $this->link      = $link;
117         $this->a         = $a;
118         $this->debuginfo = $debuginfo;
120         if (get_string_manager()->string_exists($errorcode, $module)) {
121             $message = get_string($errorcode, $module, $a);
122         } else {
123             $message = $module . '/' . $errorcode;
124         }
126         parent::__construct($message, 0);
127     }
130 /**
131  * Course/activity access exception.
132  *
133  * This exception is thrown from require_login()
134  *
135  * @package    core
136  * @subpackage lib
137  * @copyright  2010 Petr Skoda  {@link http://skodak.org}
138  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
139  */
140 class require_login_exception extends moodle_exception {
141     function __construct($debuginfo) {
142         parent::__construct('requireloginerror', 'error', '', NULL, $debuginfo);
143     }
146 /**
147  * Web service parameter exception class
148  * @deprecated since Moodle 2.2 - use moodle exception instead
149  * This exception must be thrown to the web service client when a web service parameter is invalid
150  * The error string is gotten from webservice.php
151  */
152 class webservice_parameter_exception extends moodle_exception {
153     /**
154      * Constructor
155      * @param string $errorcode The name of the string from webservice.php to print
156      * @param string $a The name of the parameter
157      */
158     function __construct($errorcode=null, $a = '', $debuginfo = null) {
159         parent::__construct($errorcode, 'webservice', '', $a, $debuginfo);
160     }
163 /**
164  * Exceptions indicating user does not have permissions to do something
165  * and the execution can not continue.
166  *
167  * @package    core
168  * @subpackage lib
169  * @copyright  2009 Petr Skoda  {@link http://skodak.org}
170  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
171  */
172 class required_capability_exception extends moodle_exception {
173     function __construct($context, $capability, $errormessage, $stringfile) {
174         $capabilityname = get_capability_string($capability);
175         if ($context->contextlevel == CONTEXT_MODULE and preg_match('/:view$/', $capability)) {
176             // we can not go to mod/xx/view.php because we most probably do not have cap to view it, let's go to course instead
177             $paranetcontext = get_context_instance_by_id(get_parent_contextid($context));
178             $link = get_context_url($paranetcontext);
179         } else {
180             $link = get_context_url($context);
181         }
182         parent::__construct($errormessage, $stringfile, $link, $capabilityname);
183     }
186 /**
187  * Exception indicating programming error, must be fixed by a programer. For example
188  * a core API might throw this type of exception if a plugin calls it incorrectly.
189  *
190  * @package    core
191  * @subpackage lib
192  * @copyright  2008 Petr Skoda  {@link http://skodak.org}
193  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
194  */
195 class coding_exception extends moodle_exception {
196     /**
197      * Constructor
198      * @param string $hint short description of problem
199      * @param string $debuginfo detailed information how to fix problem
200      */
201     function __construct($hint, $debuginfo=null) {
202         parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
203     }
206 /**
207  * Exception indicating malformed parameter problem.
208  * This exception is not supposed to be thrown when processing
209  * user submitted data in forms. It is more suitable
210  * for WS and other low level stuff.
211  *
212  * @package    core
213  * @subpackage lib
214  * @copyright  2009 Petr Skoda  {@link http://skodak.org}
215  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
216  */
217 class invalid_parameter_exception extends moodle_exception {
218     /**
219      * Constructor
220      * @param string $debuginfo some detailed information
221      */
222     function __construct($debuginfo=null) {
223         parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
224     }
227 /**
228  * Exception indicating malformed response problem.
229  * This exception is not supposed to be thrown when processing
230  * user submitted data in forms. It is more suitable
231  * for WS and other low level stuff.
232  */
233 class invalid_response_exception extends moodle_exception {
234     /**
235      * Constructor
236      * @param string $debuginfo some detailed information
237      */
238     function __construct($debuginfo=null) {
239         parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
240     }
243 /**
244  * An exception that indicates something really weird happened. For example,
245  * if you do switch ($context->contextlevel), and have one case for each
246  * CONTEXT_... constant. You might throw an invalid_state_exception in the
247  * default case, to just in case something really weird is going on, and
248  * $context->contextlevel is invalid - rather than ignoring this possibility.
249  *
250  * @package    core
251  * @subpackage lib
252  * @copyright  2009 onwards Martin Dougiamas  {@link http://moodle.com}
253  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
254  */
255 class invalid_state_exception extends moodle_exception {
256     /**
257      * Constructor
258      * @param string $hint short description of problem
259      * @param string $debuginfo optional more detailed information
260      */
261     function __construct($hint, $debuginfo=null) {
262         parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
263     }
266 /**
267  * An exception that indicates incorrect permissions in $CFG->dataroot
268  *
269  * @package    core
270  * @subpackage lib
271  * @copyright  2010 Petr Skoda {@link http://skodak.org}
272  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
273  */
274 class invalid_dataroot_permissions extends moodle_exception {
275     /**
276      * Constructor
277      * @param string $debuginfo optional more detailed information
278      */
279     function __construct($debuginfo = NULL) {
280         parent::__construct('invaliddatarootpermissions', 'error', '', NULL, $debuginfo);
281     }
284 /**
285  * An exception that indicates that file can not be served
286  *
287  * @package    core
288  * @subpackage lib
289  * @copyright  2010 Petr Skoda {@link http://skodak.org}
290  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
291  */
292 class file_serving_exception extends moodle_exception {
293     /**
294      * Constructor
295      * @param string $debuginfo optional more detailed information
296      */
297     function __construct($debuginfo = NULL) {
298         parent::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
299     }
302 /**
303  * Default exception handler, uncaught exceptions are equivalent to error() in 1.9 and earlier
304  *
305  * @param Exception $ex
306  * @return void -does not return. Terminates execution!
307  */
308 function default_exception_handler($ex) {
309     global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION;
311     // detect active db transactions, rollback and log as error
312     abort_all_db_transactions();
314     if (($ex instanceof required_capability_exception) && !CLI_SCRIPT && !AJAX_SCRIPT && !empty($CFG->autologinguests) && !empty($USER->autologinguest)) {
315         $SESSION->wantsurl = $FULLME;
316         redirect(get_login_url());
317     }
319     $info = get_exception_info($ex);
321     if (debugging('', DEBUG_MINIMAL)) {
322         $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
323         error_log($logerrmsg);
324     }
326     if (is_early_init($info->backtrace)) {
327         echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
328     } else {
329         try {
330             if ($DB) {
331                 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
332                 $DB->set_debug(0);
333             }
334             echo $OUTPUT->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
335         } catch (Exception $out_ex) {
336             // default exception handler MUST not throw any exceptions!!
337             // 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
338             // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
339             if (CLI_SCRIPT or AJAX_SCRIPT) {
340                 // just ignore the error and send something back using the safest method
341                 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
342             } else {
343                 echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
344                 $outinfo = get_exception_info($out_ex);
345                 echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
346             }
347         }
348     }
350     exit(1); // General error code
353 /**
354  * Default error handler, prevents some white screens.
355  * @param int $errno
356  * @param string $errstr
357  * @param string $errfile
358  * @param int $errline
359  * @param array $errcontext
360  * @return bool false means use default error handler
361  */
362 function default_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
363     if ($errno == 4096) {
364         //fatal catchable error
365         throw new coding_exception('PHP catchable fatal error', $errstr);
366     }
367     return false;
370 /**
371  * Unconditionally abort all database transactions, this function
372  * should be called from exception handlers only.
373  * @return void
374  */
375 function abort_all_db_transactions() {
376     global $CFG, $DB, $SCRIPT;
378     // default exception handler MUST not throw any exceptions!!
380     if ($DB && $DB->is_transaction_started()) {
381         error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
382         // note: transaction blocks should never change current $_SESSION
383         $DB->force_transaction_rollback();
384     }
387 /**
388  * This function encapsulates the tests for whether an exception was thrown in
389  * early init -- either during setup.php or during init of $OUTPUT.
390  *
391  * If another exception is thrown then, and if we do not take special measures,
392  * we would just get a very cryptic message "Exception thrown without a stack
393  * frame in Unknown on line 0". That makes debugging very hard, so we do take
394  * special measures in default_exception_handler, with the help of this function.
395  *
396  * @param array $backtrace the stack trace to analyse.
397  * @return boolean whether the stack trace is somewhere in output initialisation.
398  */
399 function is_early_init($backtrace) {
400     $dangerouscode = array(
401         array('function' => 'header', 'type' => '->'),
402         array('class' => 'bootstrap_renderer'),
403         array('file' => dirname(__FILE__).'/setup.php'),
404     );
405     foreach ($backtrace as $stackframe) {
406         foreach ($dangerouscode as $pattern) {
407             $matches = true;
408             foreach ($pattern as $property => $value) {
409                 if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
410                     $matches = false;
411                 }
412             }
413             if ($matches) {
414                 return true;
415             }
416         }
417     }
418     return false;
421 /**
422  * Abort execution by throwing of a general exception,
423  * default exception handler displays the error message in most cases.
424  *
425  * @param string $errorcode The name of the language string containing the error message.
426  *      Normally this should be in the error.php lang file.
427  * @param string $module The language file to get the error message from.
428  * @param string $link The url where the user will be prompted to continue.
429  *      If no url is provided the user will be directed to the site index page.
430  * @param object $a Extra words and phrases that might be required in the error string
431  * @param string $debuginfo optional debugging information
432  * @return void, always throws exception!
433  */
434 function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
435     throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
438 /**
439  * Returns detailed information about specified exception.
440  * @param exception $ex
441  * @return object
442  */
443 function get_exception_info($ex) {
444     global $CFG, $DB, $SESSION;
446     if ($ex instanceof moodle_exception) {
447         $errorcode = $ex->errorcode;
448         $module = $ex->module;
449         $a = $ex->a;
450         $link = $ex->link;
451         $debuginfo = $ex->debuginfo;
452     } else {
453         $errorcode = 'generalexceptionmessage';
454         $module = 'error';
455         $a = $ex->getMessage();
456         $link = '';
457         $debuginfo = null;
458     }
460     $backtrace = $ex->getTrace();
461     $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
462     array_unshift($backtrace, $place);
464     // Be careful, no guarantee moodlelib.php is loaded.
465     if (empty($module) || $module == 'moodle' || $module == 'core') {
466         $module = 'error';
467     }
468     if (function_exists('get_string_manager')) {
469         if (get_string_manager()->string_exists($errorcode, $module)) {
470             $message = get_string($errorcode, $module, $a);
471         } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
472             // Search in moodle file if error specified - needed for backwards compatibility
473             $message = get_string($errorcode, 'moodle', $a);
474         } else {
475             $message = $module . '/' . $errorcode;
476         }
477     } else {
478         $message = $module . '/' . $errorcode;
479     }
481     // Be careful, no guarantee weblib.php is loaded.
482     if (function_exists('clean_text')) {
483         $message = clean_text($message);
484     } else {
485         $message = htmlspecialchars($message);
486     }
488     if (!empty($CFG->errordocroot)) {
489         $errordoclink = $CFG->errordocroot . '/en/';
490     } else {
491         $errordoclink = get_docs_url();
492     }
494     if ($module === 'error') {
495         $modulelink = 'moodle';
496     } else {
497         $modulelink = $module;
498     }
499     $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
501     if (empty($link)) {
502         if (!empty($SESSION->fromurl)) {
503             $link = $SESSION->fromurl;
504             unset($SESSION->fromurl);
505         } else {
506             $link = $CFG->wwwroot .'/';
507         }
508     }
510     // when printing an error the continue button should never link offsite
511     if (stripos($link, $CFG->wwwroot) === false &&
512         stripos($link, $CFG->httpswwwroot) === false) {
513         $link = $CFG->wwwroot.'/';
514     }
516     $info = new stdClass();
517     $info->message     = $message;
518     $info->errorcode   = $errorcode;
519     $info->backtrace   = $backtrace;
520     $info->link        = $link;
521     $info->moreinfourl = $moreinfourl;
522     $info->a           = $a;
523     $info->debuginfo   = $debuginfo;
525     return $info;
528 /**
529  * Returns the Moodle Docs URL in the users language
530  *
531  * @global object
532  * @param string $path the end of the URL.
533  * @return string The MoodleDocs URL in the user's language. for example {@link http://docs.moodle.org/en/ http://docs.moodle.org/en/$path}
534  */
535 function get_docs_url($path=null) {
536     global $CFG;
537     // Check that $CFG->release has been set up, during installation it won't be.
538     if (empty($CFG->release)) {
539         // It's not there yet so look at version.php
540         include($CFG->dirroot.'/version.php');
541     } else {
542         // We can use $CFG->release and avoid having to include version.php
543         $release = $CFG->release;
544     }
545     // Attempt to match the branch from the release
546     if (preg_match('/^(.)\.(.)/', $release, $matches)) {
547         // We should ALWAYS get here
548         $branch = $matches[1].$matches[2];
549     } else {
550         // We should never get here but in case we do lets set $branch to .
551         // the smart one's will know that this is the current directory
552         // and the smarter ones will know that there is some smart matching
553         // that will ensure people end up at the latest version of the docs.
554         $branch = '.';
555     }
556     if (!empty($CFG->docroot)) {
557         return $CFG->docroot . '/' . $branch . '/' . current_language() . '/' . $path;
558     } else {
559         return 'http://docs.moodle.org/'. $branch . '/en/' . $path;
560     }
563 /**
564  * Formats a backtrace ready for output.
565  *
566  * @param array $callers backtrace array, as returned by debug_backtrace().
567  * @param boolean $plaintext if false, generates HTML, if true generates plain text.
568  * @return string formatted backtrace, ready for output.
569  */
570 function format_backtrace($callers, $plaintext = false) {
571     // do not use $CFG->dirroot because it might not be available in destructors
572     $dirroot = dirname(dirname(__FILE__));
574     if (empty($callers)) {
575         return '';
576     }
578     $from = $plaintext ? '' : '<ul style="text-align: left">';
579     foreach ($callers as $caller) {
580         if (!isset($caller['line'])) {
581             $caller['line'] = '?'; // probably call_user_func()
582         }
583         if (!isset($caller['file'])) {
584             $caller['file'] = 'unknownfile'; // probably call_user_func()
585         }
586         $from .= $plaintext ? '* ' : '<li>';
587         $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
588         if (isset($caller['function'])) {
589             $from .= ': call to ';
590             if (isset($caller['class'])) {
591                 $from .= $caller['class'] . $caller['type'];
592             }
593             $from .= $caller['function'] . '()';
594         } else if (isset($caller['exception'])) {
595             $from .= ': '.$caller['exception'].' thrown';
596         }
597         $from .= $plaintext ? "\n" : '</li>';
598     }
599     $from .= $plaintext ? '' : '</ul>';
601     return $from;
604 /**
605  * This function makes the return value of ini_get consistent if you are
606  * setting server directives through the .htaccess file in apache.
607  *
608  * Current behavior for value set from php.ini On = 1, Off = [blank]
609  * Current behavior for value set from .htaccess On = On, Off = Off
610  * Contributed by jdell @ unr.edu
611  *
612  * @param string $ini_get_arg The argument to get
613  * @return bool True for on false for not
614  */
615 function ini_get_bool($ini_get_arg) {
616     $temp = ini_get($ini_get_arg);
618     if ($temp == '1' or strtolower($temp) == 'on') {
619         return true;
620     }
621     return false;
624 /**
625  * This function verifies the sanity of PHP configuration
626  * and stops execution if anything critical found.
627  */
628 function setup_validate_php_configuration() {
629    // this must be very fast - no slow checks here!!!
631    if (ini_get_bool('register_globals')) {
632        print_error('globalswarning', 'admin');
633    }
634    if (ini_get_bool('session.auto_start')) {
635        print_error('sessionautostartwarning', 'admin');
636    }
637    if (ini_get_bool('magic_quotes_runtime')) {
638        print_error('fatalmagicquotesruntime', 'admin');
639    }
642 /**
643  * Initialise global $CFG variable
644  * @return void
645  */
646 function initialise_cfg() {
647     global $CFG, $DB;
649     try {
650         if ($DB) {
651             $localcfg = $DB->get_records_menu('config', array(), '', 'name,value');
652             foreach ($localcfg as $name=>$value) {
653                 if (property_exists($CFG, $name)) {
654                     // config.php settings always take precedence
655                     continue;
656                 }
657                 $CFG->{$name} = $value;
658             }
659         }
660     } catch (dml_read_exception $e) {
661         // most probably empty db, going to install soon
662     }
665 /**
666  * Initialises $FULLME and friends. Private function. Should only be called from
667  * setup.php.
668  */
669 function initialise_fullme() {
670     global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
672     // Detect common config error.
673     if (substr($CFG->wwwroot, -1) == '/') {
674         print_error('wwwrootslash', 'error');
675     }
677     if (CLI_SCRIPT) {
678         initialise_fullme_cli();
679         return;
680     }
682     $rurl = setup_get_remote_url();
683     $wwwroot = parse_url($CFG->wwwroot.'/');
685     if (empty($rurl['host'])) {
686         // missing host in request header, probably not a real browser, let's ignore them
688     } else if (!empty($CFG->reverseproxy)) {
689         // $CFG->reverseproxy specifies if reverse proxy server used
690         // Used in load balancing scenarios.
691         // Do not abuse this to try to solve lan/wan access problems!!!!!
693     } else {
694         if (($rurl['host'] !== $wwwroot['host']) or (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port'])) {
695             // Explain the problem and redirect them to the right URL
696             if (!defined('NO_MOODLE_COOKIES')) {
697                 define('NO_MOODLE_COOKIES', true);
698             }
699             redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
700         }
701     }
703     // Check that URL is under $CFG->wwwroot.
704     if (strpos($rurl['path'], $wwwroot['path']) === 0) {
705         $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
706     } else {
707         // Probably some weird external script
708         $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
709         return;
710     }
712     // $CFG->sslproxy specifies if external SSL appliance is used
713     // (That is, the Moodle server uses http, with an external box translating everything to https).
714     if (empty($CFG->sslproxy)) {
715         if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
716             print_error('sslonlyaccess', 'error');
717         }
718     } else {
719         if ($wwwroot['scheme'] !== 'https') {
720             throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
721         }
722         $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
723     }
725     // hopefully this will stop all those "clever" admins trying to set up moodle
726     // with two different addresses in intranet and Internet
727     if (!empty($CFG->reverseproxy) && $rurl['host'] === $wwwroot['host']) {
728         print_error('reverseproxyabused', 'error');
729     }
731     $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
732     if (!empty($wwwroot['port'])) {
733         $hostandport .= ':'.$wwwroot['port'];
734     }
736     $FULLSCRIPT = $hostandport . $rurl['path'];
737     $FULLME = $hostandport . $rurl['fullpath'];
738     $ME = $rurl['fullpath'];
741 /**
742  * Initialises $FULLME and friends for command line scripts.
743  * This is a private method for use by initialise_fullme.
744  */
745 function initialise_fullme_cli() {
746     global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
748     // Urls do not make much sense in CLI scripts
749     $backtrace = debug_backtrace();
750     $topfile = array_pop($backtrace);
751     $topfile = realpath($topfile['file']);
752     $dirroot = realpath($CFG->dirroot);
754     if (strpos($topfile, $dirroot) !== 0) {
755         // Probably some weird external script
756         $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
757     } else {
758         $relativefile = substr($topfile, strlen($dirroot));
759         $relativefile = str_replace('\\', '/', $relativefile); // Win fix
760         $SCRIPT = $FULLSCRIPT = $relativefile;
761         $FULLME = $ME = null;
762     }
765 /**
766  * Get the URL that PHP/the web server thinks it is serving. Private function
767  * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
768  * @return array in the same format that parse_url returns, with the addition of
769  *      a 'fullpath' element, which includes any slasharguments path.
770  */
771 function setup_get_remote_url() {
772     $rurl = array();
773     if (isset($_SERVER['HTTP_HOST'])) {
774         list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
775     } else {
776         $rurl['host'] = null;
777     }
778     $rurl['port'] = $_SERVER['SERVER_PORT'];
779     $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
780     $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ? 'http' : 'https';
782     if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
783         //Apache server
784         $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
786     } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
787         //IIS - needs a lot of tweaking to make it work
788         $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
790         // NOTE: ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS
791         //       since 2.0 we rely on iis rewrite extenssion like Helicon ISAPI_rewrite
792         //       example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
794         if ($_SERVER['QUERY_STRING'] != '') {
795             $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
796         }
797         $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
799 /* NOTE: following servers are not fully tested! */
801     } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
802         //lighttpd - not officially supported
803         $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
805     } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
806         //nginx - not officially supported
807         if (!isset($_SERVER['SCRIPT_NAME'])) {
808             die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
809         }
810         $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
812      } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
813          //cherokee - not officially supported
814          $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
816      } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
817          //zeus - not officially supported
818          $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
820     } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
821         //LiteSpeed - not officially supported
822         $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
824     } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
825         //obscure name found on some servers - this is definitely not supported
826         $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
828      } else {
829         throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
830     }
832     // sanitize the url a bit more, the encoding style may be different in vars above
833     $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
834     $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);
836     return $rurl;
839 /**
840  * Initializes our performance info early.
841  *
842  * Pairs up with get_performance_info() which is actually
843  * in moodlelib.php. This function is here so that we can
844  * call it before all the libs are pulled in.
845  *
846  * @uses $PERF
847  */
848 function init_performance_info() {
850     global $PERF, $CFG, $USER;
852     $PERF = new stdClass();
853     $PERF->logwrites = 0;
854     if (function_exists('microtime')) {
855         $PERF->starttime = microtime();
856     }
857     if (function_exists('memory_get_usage')) {
858         $PERF->startmemory = memory_get_usage();
859     }
860     if (function_exists('posix_times')) {
861         $PERF->startposixtimes = posix_times();
862     }
865 /**
866  * Indicates whether we are in the middle of the initial Moodle install.
867  *
868  * Very occasionally it is necessary avoid running certain bits of code before the
869  * Moodle installation has completed. The installed flag is set in admin/index.php
870  * after Moodle core and all the plugins have been installed, but just before
871  * the person doing the initial install is asked to choose the admin password.
872  *
873  * @return boolean true if the initial install is not complete.
874  */
875 function during_initial_install() {
876     global $CFG;
877     return empty($CFG->rolesactive);
880 /**
881  * Function to raise the memory limit to a new value.
882  * Will respect the memory limit if it is higher, thus allowing
883  * settings in php.ini, apache conf or command line switches
884  * to override it.
885  *
886  * The memory limit should be expressed with a constant
887  * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
888  * It is possible to use strings or integers too (eg:'128M').
889  *
890  * @param mixed $newlimit the new memory limit
891  * @return bool success
892  */
893 function raise_memory_limit($newlimit) {
894     global $CFG;
896     if ($newlimit == MEMORY_UNLIMITED) {
897         ini_set('memory_limit', -1);
898         return true;
900     } else if ($newlimit == MEMORY_STANDARD) {
901         if (PHP_INT_SIZE > 4) {
902             $newlimit = get_real_size('128M'); // 64bit needs more memory
903         } else {
904             $newlimit = get_real_size('96M');
905         }
907     } else if ($newlimit == MEMORY_EXTRA) {
908         if (PHP_INT_SIZE > 4) {
909             $newlimit = get_real_size('384M'); // 64bit needs more memory
910         } else {
911             $newlimit = get_real_size('256M');
912         }
913         if (!empty($CFG->extramemorylimit)) {
914             $extra = get_real_size($CFG->extramemorylimit);
915             if ($extra > $newlimit) {
916                 $newlimit = $extra;
917             }
918         }
920     } else if ($newlimit == MEMORY_HUGE) {
921         $newlimit = get_real_size('2G');
923     } else {
924         $newlimit = get_real_size($newlimit);
925     }
927     if ($newlimit <= 0) {
928         debugging('Invalid memory limit specified.');
929         return false;
930     }
932     $cur = ini_get('memory_limit');
933     if (empty($cur)) {
934         // if php is compiled without --enable-memory-limits
935         // apparently memory_limit is set to ''
936         $cur = 0;
937     } else {
938         if ($cur == -1){
939             return true; // unlimited mem!
940         }
941         $cur = get_real_size($cur);
942     }
944     if ($newlimit > $cur) {
945         ini_set('memory_limit', $newlimit);
946         return true;
947     }
948     return false;
951 /**
952  * Function to reduce the memory limit to a new value.
953  * Will respect the memory limit if it is lower, thus allowing
954  * settings in php.ini, apache conf or command line switches
955  * to override it
956  *
957  * The memory limit should be expressed with a string (eg:'64M')
958  *
959  * @param string $newlimit the new memory limit
960  * @return bool
961  */
962 function reduce_memory_limit($newlimit) {
963     if (empty($newlimit)) {
964         return false;
965     }
966     $cur = ini_get('memory_limit');
967     if (empty($cur)) {
968         // if php is compiled without --enable-memory-limits
969         // apparently memory_limit is set to ''
970         $cur = 0;
971     } else {
972         if ($cur == -1){
973             return true; // unlimited mem!
974         }
975         $cur = get_real_size($cur);
976     }
978     $new = get_real_size($newlimit);
979     // -1 is smaller, but it means unlimited
980     if ($new < $cur && $new != -1) {
981         ini_set('memory_limit', $newlimit);
982         return true;
983     }
984     return false;
987 /**
988  * Converts numbers like 10M into bytes.
989  *
990  * @param string $size The size to be converted
991  * @return int
992  */
993 function get_real_size($size = 0) {
994     if (!$size) {
995         return 0;
996     }
997     $scan = array();
998     $scan['GB'] = 1073741824;
999     $scan['Gb'] = 1073741824;
1000     $scan['G'] = 1073741824;
1001     $scan['MB'] = 1048576;
1002     $scan['Mb'] = 1048576;
1003     $scan['M'] = 1048576;
1004     $scan['m'] = 1048576;
1005     $scan['KB'] = 1024;
1006     $scan['Kb'] = 1024;
1007     $scan['K'] = 1024;
1008     $scan['k'] = 1024;
1010     while (list($key) = each($scan)) {
1011         if ((strlen($size)>strlen($key))&&(substr($size, strlen($size) - strlen($key))==$key)) {
1012             $size = substr($size, 0, strlen($size) - strlen($key)) * $scan[$key];
1013             break;
1014         }
1015     }
1016     return $size;
1019 /**
1020  * Try to disable all output buffering and purge
1021  * all headers.
1022  *
1023  * @private to be called only from lib/setup.php !
1024  * @return void
1025  */
1026 function disable_output_buffering() {
1027     $olddebug = error_reporting(0);
1029     // disable compression, it would prevent closing of buffers
1030     if (ini_get_bool('zlib.output_compression')) {
1031         ini_set('zlib.output_compression', 'Off');
1032     }
1034     // try to flush everything all the time
1035     ob_implicit_flush(true);
1037     // close all buffers if possible and discard any existing output
1038     // this can actually work around some whitespace problems in config.php
1039     while(ob_get_level()) {
1040         if (!ob_end_clean()) {
1041             // prevent infinite loop when buffer can not be closed
1042             break;
1043         }
1044     }
1046     error_reporting($olddebug);
1049 /**
1050  * Check whether a major upgrade is needed. That is defined as an upgrade that
1051  * changes something really fundamental in the database, so nothing can possibly
1052  * work until the database has been updated, and that is defined by the hard-coded
1053  * version number in this function.
1054  */
1055 function redirect_if_major_upgrade_required() {
1056     global $CFG;
1057     $lastmajordbchanges = 2010111700;
1058     if (empty($CFG->version) or (int)$CFG->version < $lastmajordbchanges or
1059             during_initial_install() or !empty($CFG->adminsetuppending)) {
1060         try {
1061             @session_get_instance()->terminate_current();
1062         } catch (Exception $e) {
1063             // Ignore any errors, redirect to upgrade anyway.
1064         }
1065         $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
1066         @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1067         @header('Location: ' . $url);
1068         echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
1069         exit;
1070     }
1073 /**
1074  * Function to check if a directory exists and by default create it if not exists.
1075  *
1076  * Previously this was accepting paths only from dataroot, but we now allow
1077  * files outside of dataroot if you supply custom paths for some settings in config.php.
1078  * This function does not verify that the directory is writable.
1079  *
1080  * @param string $dir absolute directory path
1081  * @param boolean $create directory if does not exist
1082  * @param boolean $recursive create directory recursively
1083  * @return boolean true if directory exists or created, false otherwise
1084  */
1085 function check_dir_exists($dir, $create = true, $recursive = true) {
1086     global $CFG;
1088     umask(0000); // just in case some evil code changed it
1090     if (is_dir($dir)) {
1091         return true;
1092     }
1094     if (!$create) {
1095         return false;
1096     }
1098     return mkdir($dir, $CFG->directorypermissions, $recursive);
1101 /**
1102  * Create a directory and make sure it is writable.
1103  *
1104  * @private
1105  * @param string $dir  the full path of the directory to be created
1106  * @param bool $exceptiononerror throw exception if error encountered
1107  * @return string|false Returns full path to directory if successful, false if not; may throw exception
1108  */
1109 function make_writable_directory($dir, $exceptiononerror = true) {
1110     global $CFG;
1112     if (file_exists($dir) and !is_dir($dir)) {
1113         if ($exceptiononerror) {
1114             throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1115         } else {
1116             return false;
1117         }
1118     }
1120     umask(0000); // just in case some evil code changed it
1122     if (!file_exists($dir)) {
1123         if (!mkdir($dir, $CFG->directorypermissions, true)) {
1124             if ($exceptiononerror) {
1125                 throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1126             } else {
1127                 return false;
1128             }
1129         }
1130     }
1132     if (!is_writable($dir)) {
1133         if ($exceptiononerror) {
1134             throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1135         } else {
1136             return false;
1137         }
1138     }
1140     return $dir;
1143 /**
1144  * Protect a directory from web access.
1145  * Could be extended in the future to support other mechanisms (e.g. other webservers).
1146  *
1147  * @private
1148  * @param string $dir  the full path of the directory to be protected
1149  */
1150 function protect_directory($dir) {
1151     // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1152     if (!file_exists("$dir/.htaccess")) {
1153         if ($handle = fopen("$dir/.htaccess", 'w')) {   // For safety
1154             @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");
1155             @fclose($handle);
1156         }
1157     }
1160 /**
1161  * Create a directory under dataroot and make sure it is writable.
1162  * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
1163  *
1164  * @param string $directory  the full path of the directory to be created under $CFG->dataroot
1165  * @param bool $exceptiononerror throw exception if error encountered
1166  * @return string|false Returns full path to directory if successful, false if not; may throw exception
1167  */
1168 function make_upload_directory($directory, $exceptiononerror = true) {
1169     global $CFG;
1171     if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1172         debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1174     } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
1175         debugging('Use make_cache_directory() for creation of chache directory and $CFG->cachedir to get the location.');
1176     }
1178     protect_directory($CFG->dataroot);
1179     return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1182 /**
1183  * Create a directory under tempdir and make sure it is writable.
1184  * Temporary files should be used during the current request only!
1185  *
1186  * @param string $directory  the full path of the directory to be created under $CFG->tempdir
1187  * @param bool $exceptiononerror throw exception if error encountered
1188  * @return string|false Returns full path to directory if successful, false if not; may throw exception
1189  */
1190 function make_temp_directory($directory, $exceptiononerror = true) {
1191     global $CFG;
1192     protect_directory($CFG->tempdir);
1193     return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1196 /**
1197  * Create a directory under cachedir and make sure it is writable.
1198  *
1199  * @param string $directory  the full path of the directory to be created under $CFG->cachedir
1200  * @param bool $exceptiononerror throw exception if error encountered
1201  * @return string|false Returns full path to directory if successful, false if not; may throw exception
1202  */
1203 function make_cache_directory($directory, $exceptiononerror = true) {
1204     global $CFG;
1205     protect_directory($CFG->cachedir);
1206     return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1210 function init_memcached() {
1211     global $CFG, $MCACHE;
1213     include_once($CFG->libdir . '/memcached.class.php');
1214     $MCACHE = new memcached;
1215     if ($MCACHE->status()) {
1216         return true;
1217     }
1218     unset($MCACHE);
1219     return false;
1222 function init_eaccelerator() {
1223     global $CFG, $MCACHE;
1225     include_once($CFG->libdir . '/eaccelerator.class.php');
1226     $MCACHE = new eaccelerator;
1227     if ($MCACHE->status()) {
1228         return true;
1229     }
1230     unset($MCACHE);
1231     return false;
1234 /**
1235  * Checks if current user is a web crawler.
1236  *
1237  * This list can not be made complete, this is not a security
1238  * restriction, we make the list only to help these sites
1239  * especially when automatic guest login is disabled.
1240  *
1241  * If admin needs security they should enable forcelogin
1242  * and disable guest access!!
1243  *
1244  * @return bool
1245  */
1246 function is_web_crawler() {
1247     if (!empty($_SERVER['HTTP_USER_AGENT'])) {
1248         if (strpos($_SERVER['HTTP_USER_AGENT'], 'Googlebot') !== false ) {
1249             return true;
1250         } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'google.com') !== false ) { // Google
1251             return true;
1252         } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yahoo! Slurp') !== false ) {  // Yahoo
1253             return true;
1254         } else if (strpos($_SERVER['HTTP_USER_AGENT'], '[ZSEBOT]') !== false ) {  // Zoomspider
1255             return true;
1256         } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'MSNBOT') !== false ) {  // MSN Search
1257             return true;
1258         } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'Yandex') !== false ) {
1259             return true;
1260         } else if (strpos($_SERVER['HTTP_USER_AGENT'], 'AltaVista') !== false ) {
1261             return true;
1262         }
1263     }
1264     return false;
1267 /**
1268  * This class solves the problem of how to initialise $OUTPUT.
1269  *
1270  * The problem is caused be two factors
1271  * <ol>
1272  * <li>On the one hand, we cannot be sure when output will start. In particular,
1273  * an error, which needs to be displayed, could be thrown at any time.</li>
1274  * <li>On the other hand, we cannot be sure when we will have all the information
1275  * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1276  * (potentially) depends on the current course, course categories, and logged in user.
1277  * It also depends on whether the current page requires HTTPS.</li>
1278  * </ol>
1279  *
1280  * So, it is hard to find a single natural place during Moodle script execution,
1281  * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1282  * adopt the following strategy
1283  * <ol>
1284  * <li>We will initialise $OUTPUT the first time it is used.</li>
1285  * <li>If, after $OUTPUT has been initialised, the script tries to change something
1286  * that $OUTPUT depends on, we throw an exception making it clear that the script
1287  * did something wrong.
1288  * </ol>
1289  *
1290  * The only problem with that is, how do we initialise $OUTPUT on first use if,
1291  * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1292  * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1293  * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1294  *
1295  * Note that this class is used before lib/outputlib.php has been loaded, so we
1296  * must be careful referring to classes/functions from there, they may not be
1297  * defined yet, and we must avoid fatal errors.
1298  *
1299  * @copyright 2009 Tim Hunt
1300  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1301  * @since     Moodle 2.0
1302  */
1303 class bootstrap_renderer {
1304     /**
1305      * Handles re-entrancy. Without this, errors or debugging output that occur
1306      * during the initialisation of $OUTPUT, cause infinite recursion.
1307      * @var boolean
1308      */
1309     protected $initialising = false;
1311     /**
1312      * Have we started output yet?
1313      * @return boolean true if the header has been printed.
1314      */
1315     public function has_started() {
1316         return false;
1317     }
1319     /**
1320      * Constructor - to be used by core code only.
1321      * @param $method
1322      * @param $arguments
1323      * @return string
1324      */
1325     public function __call($method, $arguments) {
1326         global $OUTPUT, $PAGE;
1328         $recursing = false;
1329         if ($method == 'notification') {
1330             // Catch infinite recursion caused by debugging output during print_header.
1331             $backtrace = debug_backtrace();
1332             array_shift($backtrace);
1333             array_shift($backtrace);
1334             $recursing = is_early_init($backtrace);
1335         }
1337         $earlymethods = array(
1338             'fatal_error' => 'early_error',
1339             'notification' => 'early_notification',
1340         );
1342         // If lib/outputlib.php has been loaded, call it.
1343         if (!empty($PAGE) && !$recursing) {
1344             if (array_key_exists($method, $earlymethods)) {
1345                 //prevent PAGE->context warnings - exceptions might appear before we set any context
1346                 $PAGE->set_context(null);
1347             }
1348             $PAGE->initialise_theme_and_output();
1349             return call_user_func_array(array($OUTPUT, $method), $arguments);
1350         }
1352         $this->initialising = true;
1354         // Too soon to initialise $OUTPUT, provide a couple of key methods.
1355         if (array_key_exists($method, $earlymethods)) {
1356             return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1357         }
1359         throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1360     }
1362     /**
1363      * Returns nicely formatted error message in a div box.
1364      * @static
1365      * @param string $message error message
1366      * @param string $moreinfourl (ignored in early errors)
1367      * @param string $link (ignored in early errors)
1368      * @param array $backtrace
1369      * @param string $debuginfo
1370      * @return string
1371      */
1372     public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1373         global $CFG;
1375         $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1376 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1377 width: 80%; -moz-border-radius: 20px; padding: 15px">
1378 ' . $message . '
1379 </div>';
1380         if (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER) {
1381             if (!empty($debuginfo)) {
1382                 $debuginfo = s($debuginfo); // removes all nasty JS
1383                 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1384                 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
1385             }
1386             if (!empty($backtrace)) {
1387                 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1388             }
1389         }
1391         return $content;
1392     }
1394     /**
1395      * This function should only be called by this class, or from exception handlers
1396      * @static
1397      * @param string $message error message
1398      * @param string $moreinfourl (ignored in early errors)
1399      * @param string $link (ignored in early errors)
1400      * @param array $backtrace
1401      * @param string $debuginfo extra information for developers
1402      * @return string
1403      */
1404     public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1405         global $CFG;
1407         if (CLI_SCRIPT) {
1408             echo "!!! $message !!!\n";
1409             if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1410                 if (!empty($debuginfo)) {
1411                     echo "\nDebug info: $debuginfo";
1412                 }
1413                 if (!empty($backtrace)) {
1414                     echo "\nStack trace: " . format_backtrace($backtrace, true);
1415                 }
1416             }
1417             return;
1419         } else if (AJAX_SCRIPT) {
1420             $e = new stdClass();
1421             $e->error      = $message;
1422             $e->stacktrace = NULL;
1423             $e->debuginfo  = NULL;
1424             if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1425                 if (!empty($debuginfo)) {
1426                     $e->debuginfo = $debuginfo;
1427                 }
1428                 if (!empty($backtrace)) {
1429                     $e->stacktrace = format_backtrace($backtrace, true);
1430                 }
1431             }
1432             @header('Content-Type: application/json; charset=utf-8');
1433             echo json_encode($e);
1434             return;
1435         }
1437         // In the name of protocol correctness, monitoring and performance
1438         // profiling, set the appropriate error headers for machine consumption
1439         if (isset($_SERVER['SERVER_PROTOCOL'])) {
1440             // Avoid it with cron.php. Note that we assume it's HTTP/1.x
1441             // The 503 ode here means our Moodle does not work at all, the error happened too early
1442             @header($_SERVER['SERVER_PROTOCOL'] . ' 503 Service Unavailable');
1443         }
1445         // better disable any caching
1446         @header('Content-Type: text/html; charset=utf-8');
1447         @header('Cache-Control: no-store, no-cache, must-revalidate');
1448         @header('Cache-Control: post-check=0, pre-check=0', false);
1449         @header('Pragma: no-cache');
1450         @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1451         @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1453         if (function_exists('get_string')) {
1454             $strerror = get_string('error');
1455         } else {
1456             $strerror = 'Error';
1457         }
1459         $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
1461         return self::plain_page($strerror, $content);
1462     }
1464     /**
1465      * Early notification message
1466      * @static
1467      * @param $message
1468      * @param string $classes usually notifyproblem or notifysuccess
1469      * @return string
1470      */
1471     public static function early_notification($message, $classes = 'notifyproblem') {
1472         return '<div class="' . $classes . '">' . $message . '</div>';
1473     }
1475     /**
1476      * Page should redirect message.
1477      * @static
1478      * @param $encodedurl redirect url
1479      * @return string
1480      */
1481     public static function plain_redirect_message($encodedurl) {
1482         $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
1483                 $encodedurl .'">'. get_string('continue') .'</a></div>';
1484         return self::plain_page(get_string('redirect'), $message);
1485     }
1487     /**
1488      * Early redirection page, used before full init of $PAGE global
1489      * @static
1490      * @param $encodedurl redirect url
1491      * @param $message redirect message
1492      * @param $delay time in seconds
1493      * @return string redirect page
1494      */
1495     public static function early_redirect_message($encodedurl, $message, $delay) {
1496         $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
1497         $content = self::early_error_content($message, null, null, null);
1498         $content .= self::plain_redirect_message($encodedurl);
1500         return self::plain_page(get_string('redirect'), $content, $meta);
1501     }
1503     /**
1504      * Output basic html page.
1505      * @static
1506      * @param $title page title
1507      * @param $content page content
1508      * @param string $meta meta tag
1509      * @return string html page
1510      */
1511     protected static function plain_page($title, $content, $meta = '') {
1512         if (function_exists('get_string') && function_exists('get_html_lang')) {
1513             $htmllang = get_html_lang();
1514         } else {
1515             $htmllang = '';
1516         }
1518         return '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
1519 <html xmlns="http://www.w3.org/1999/xhtml" ' . $htmllang . '>
1520 <head>
1521 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
1522 '.$meta.'
1523 <title>' . $title . '</title>
1524 </head><body>' . $content . '</body></html>';
1525     }