MDL-58857 admin: Terminate the session if a major upgrade is required
[moodle.git] / lib / setuplib.php
1 <?php
2 // This file is part of Moodle - http://moodle.org/
3 //
4 // Moodle is free software: you can redistribute it and/or modify
5 // it under the terms of the GNU General Public License as published by
6 // the Free Software Foundation, either version 3 of the License, or
7 // (at your option) any later version.
8 //
9 // Moodle is distributed in the hope that it will be useful,
10 // but WITHOUT ANY WARRANTY; without even the implied warranty of
11 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
12 // GNU General Public License for more details.
13 //
14 // You should have received a copy of the GNU General Public License
15 // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
17 /**
18  * These functions are required very early in the Moodle
19  * setup process, before any of the main libraries are
20  * loaded.
21  *
22  * @package    core
23  * @subpackage lib
24  * @copyright  1999 onwards Martin Dougiamas  {@link http://moodle.com}
25  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26  */
28 defined('MOODLE_INTERNAL') || die();
30 // Debug levels - always keep the values in ascending order!
31 /** No warnings and errors at all */
32 define('DEBUG_NONE', 0);
33 /** Fatal errors only */
34 define('DEBUG_MINIMAL', E_ERROR | E_PARSE);
35 /** Errors, warnings and notices */
36 define('DEBUG_NORMAL', E_ERROR | E_PARSE | E_WARNING | E_NOTICE);
37 /** All problems except strict PHP warnings */
38 define('DEBUG_ALL', E_ALL & ~E_STRICT);
39 /** DEBUG_ALL with all debug messages and strict warnings */
40 define('DEBUG_DEVELOPER', E_ALL | E_STRICT);
42 /** Remove any memory limits */
43 define('MEMORY_UNLIMITED', -1);
44 /** Standard memory limit for given platform */
45 define('MEMORY_STANDARD', -2);
46 /**
47  * Large memory limit for given platform - used in cron, upgrade, and other places that need a lot of memory.
48  * Can be overridden with $CFG->extramemorylimit setting.
49  */
50 define('MEMORY_EXTRA', -3);
51 /** Extremely large memory limit - not recommended for standard scripts */
52 define('MEMORY_HUGE', -4);
55 /**
56  * Simple class. It is usually used instead of stdClass because it looks
57  * more familiar to Java developers ;-) Do not use for type checking of
58  * function parameters. Please use stdClass instead.
59  *
60  * @package    core
61  * @subpackage lib
62  * @copyright  2009 Petr Skoda  {@link http://skodak.org}
63  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
64  * @deprecated since 2.0
65  */
66 class object extends stdClass {
67     /**
68      * Constructor.
69      */
70     public function __construct() {
71         debugging("'object' class has been deprecated, please use stdClass instead.", DEBUG_DEVELOPER);
72     }
73 };
75 /**
76  * Base Moodle Exception class
77  *
78  * Although this class is defined here, you cannot throw a moodle_exception until
79  * after moodlelib.php has been included (which will happen very soon).
80  *
81  * @package    core
82  * @subpackage lib
83  * @copyright  2008 Petr Skoda  {@link http://skodak.org}
84  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
85  */
86 class moodle_exception extends Exception {
88     /**
89      * @var string The name of the string from error.php to print
90      */
91     public $errorcode;
93     /**
94      * @var string The name of module
95      */
96     public $module;
98     /**
99      * @var mixed Extra words and phrases that might be required in the error string
100      */
101     public $a;
103     /**
104      * @var string 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.
105      */
106     public $link;
108     /**
109      * @var string Optional information to aid the debugging process
110      */
111     public $debuginfo;
113     /**
114      * Constructor
115      * @param string $errorcode The name of the string from error.php to print
116      * @param string $module name of module
117      * @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.
118      * @param mixed $a Extra words and phrases that might be required in the error string
119      * @param string $debuginfo optional debugging information
120      */
121     function __construct($errorcode, $module='', $link='', $a=NULL, $debuginfo=null) {
122         if (empty($module) || $module == 'moodle' || $module == 'core') {
123             $module = 'error';
124         }
126         $this->errorcode = $errorcode;
127         $this->module    = $module;
128         $this->link      = $link;
129         $this->a         = $a;
130         $this->debuginfo = is_null($debuginfo) ? null : (string)$debuginfo;
132         if (get_string_manager()->string_exists($errorcode, $module)) {
133             $message = get_string($errorcode, $module, $a);
134             $haserrorstring = true;
135         } else {
136             $message = $module . '/' . $errorcode;
137             $haserrorstring = false;
138         }
140         if (defined('PHPUNIT_TEST') and PHPUNIT_TEST and $debuginfo) {
141             $message = "$message ($debuginfo)";
142         }
144         if (!$haserrorstring and defined('PHPUNIT_TEST') and PHPUNIT_TEST) {
145             // Append the contents of $a to $debuginfo so helpful information isn't lost.
146             // This emulates what {@link get_exception_info()} does. Unfortunately that
147             // function is not used by phpunit.
148             $message .= PHP_EOL.'$a contents: '.print_r($a, true);
149         }
151         parent::__construct($message, 0);
152     }
155 /**
156  * Course/activity access exception.
157  *
158  * This exception is thrown from require_login()
159  *
160  * @package    core_access
161  * @copyright  2010 Petr Skoda  {@link http://skodak.org}
162  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
163  */
164 class require_login_exception extends moodle_exception {
165     /**
166      * Constructor
167      * @param string $debuginfo Information to aid the debugging process
168      */
169     function __construct($debuginfo) {
170         parent::__construct('requireloginerror', 'error', '', NULL, $debuginfo);
171     }
174 /**
175  * Session timeout exception.
176  *
177  * This exception is thrown from require_login()
178  *
179  * @package    core_access
180  * @copyright  2015 Andrew Nicols <andrew@nicols.co.uk>
181  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
182  */
183 class require_login_session_timeout_exception extends require_login_exception {
184     /**
185      * Constructor
186      */
187     public function __construct() {
188         moodle_exception::__construct('sessionerroruser', 'error');
189     }
192 /**
193  * Web service parameter exception class
194  * @deprecated since Moodle 2.2 - use moodle exception instead
195  * This exception must be thrown to the web service client when a web service parameter is invalid
196  * The error string is gotten from webservice.php
197  */
198 class webservice_parameter_exception extends moodle_exception {
199     /**
200      * Constructor
201      * @param string $errorcode The name of the string from webservice.php to print
202      * @param string $a The name of the parameter
203      * @param string $debuginfo Optional information to aid debugging
204      */
205     function __construct($errorcode=null, $a = '', $debuginfo = null) {
206         parent::__construct($errorcode, 'webservice', '', $a, $debuginfo);
207     }
210 /**
211  * Exceptions indicating user does not have permissions to do something
212  * and the execution can not continue.
213  *
214  * @package    core_access
215  * @copyright  2009 Petr Skoda  {@link http://skodak.org}
216  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
217  */
218 class required_capability_exception extends moodle_exception {
219     /**
220      * Constructor
221      * @param context $context The context used for the capability check
222      * @param string $capability The required capability
223      * @param string $errormessage The error message to show the user
224      * @param string $stringfile
225      */
226     function __construct($context, $capability, $errormessage, $stringfile) {
227         $capabilityname = get_capability_string($capability);
228         if ($context->contextlevel == CONTEXT_MODULE and preg_match('/:view$/', $capability)) {
229             // 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
230             $parentcontext = $context->get_parent_context();
231             $link = $parentcontext->get_url();
232         } else {
233             $link = $context->get_url();
234         }
235         parent::__construct($errormessage, $stringfile, $link, $capabilityname);
236     }
239 /**
240  * Exception indicating programming error, must be fixed by a programer. For example
241  * a core API might throw this type of exception if a plugin calls it incorrectly.
242  *
243  * @package    core
244  * @subpackage lib
245  * @copyright  2008 Petr Skoda  {@link http://skodak.org}
246  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
247  */
248 class coding_exception extends moodle_exception {
249     /**
250      * Constructor
251      * @param string $hint short description of problem
252      * @param string $debuginfo detailed information how to fix problem
253      */
254     function __construct($hint, $debuginfo=null) {
255         parent::__construct('codingerror', 'debug', '', $hint, $debuginfo);
256     }
259 /**
260  * Exception indicating malformed parameter problem.
261  * This exception is not supposed to be thrown when processing
262  * user submitted data in forms. It is more suitable
263  * for WS and other low level stuff.
264  *
265  * @package    core
266  * @subpackage lib
267  * @copyright  2009 Petr Skoda  {@link http://skodak.org}
268  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
269  */
270 class invalid_parameter_exception extends moodle_exception {
271     /**
272      * Constructor
273      * @param string $debuginfo some detailed information
274      */
275     function __construct($debuginfo=null) {
276         parent::__construct('invalidparameter', 'debug', '', null, $debuginfo);
277     }
280 /**
281  * Exception indicating malformed response problem.
282  * This exception is not supposed to be thrown when processing
283  * user submitted data in forms. It is more suitable
284  * for WS and other low level stuff.
285  */
286 class invalid_response_exception extends moodle_exception {
287     /**
288      * Constructor
289      * @param string $debuginfo some detailed information
290      */
291     function __construct($debuginfo=null) {
292         parent::__construct('invalidresponse', 'debug', '', null, $debuginfo);
293     }
296 /**
297  * An exception that indicates something really weird happened. For example,
298  * if you do switch ($context->contextlevel), and have one case for each
299  * CONTEXT_... constant. You might throw an invalid_state_exception in the
300  * default case, to just in case something really weird is going on, and
301  * $context->contextlevel is invalid - rather than ignoring this possibility.
302  *
303  * @package    core
304  * @subpackage lib
305  * @copyright  2009 onwards Martin Dougiamas  {@link http://moodle.com}
306  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
307  */
308 class invalid_state_exception extends moodle_exception {
309     /**
310      * Constructor
311      * @param string $hint short description of problem
312      * @param string $debuginfo optional more detailed information
313      */
314     function __construct($hint, $debuginfo=null) {
315         parent::__construct('invalidstatedetected', 'debug', '', $hint, $debuginfo);
316     }
319 /**
320  * An exception that indicates incorrect permissions in $CFG->dataroot
321  *
322  * @package    core
323  * @subpackage lib
324  * @copyright  2010 Petr Skoda {@link http://skodak.org}
325  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
326  */
327 class invalid_dataroot_permissions extends moodle_exception {
328     /**
329      * Constructor
330      * @param string $debuginfo optional more detailed information
331      */
332     function __construct($debuginfo = NULL) {
333         parent::__construct('invaliddatarootpermissions', 'error', '', NULL, $debuginfo);
334     }
337 /**
338  * An exception that indicates that file can not be served
339  *
340  * @package    core
341  * @subpackage lib
342  * @copyright  2010 Petr Skoda {@link http://skodak.org}
343  * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
344  */
345 class file_serving_exception extends moodle_exception {
346     /**
347      * Constructor
348      * @param string $debuginfo optional more detailed information
349      */
350     function __construct($debuginfo = NULL) {
351         parent::__construct('cannotservefile', 'error', '', NULL, $debuginfo);
352     }
355 /**
356  * Default exception handler.
357  *
358  * @param Exception $ex
359  * @return void -does not return. Terminates execution!
360  */
361 function default_exception_handler($ex) {
362     global $CFG, $DB, $OUTPUT, $USER, $FULLME, $SESSION, $PAGE;
364     // detect active db transactions, rollback and log as error
365     abort_all_db_transactions();
367     if (($ex instanceof required_capability_exception) && !CLI_SCRIPT && !AJAX_SCRIPT && !empty($CFG->autologinguests) && !empty($USER->autologinguest)) {
368         $SESSION->wantsurl = qualified_me();
369         redirect(get_login_url());
370     }
372     $info = get_exception_info($ex);
374     if (debugging('', DEBUG_MINIMAL)) {
375         $logerrmsg = "Default exception handler: ".$info->message.' Debug: '.$info->debuginfo."\n".format_backtrace($info->backtrace, true);
376         error_log($logerrmsg);
377     }
379     if (is_early_init($info->backtrace)) {
380         echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
381     } else {
382         try {
383             if ($DB) {
384                 // If you enable db debugging and exception is thrown, the print footer prints a lot of rubbish
385                 $DB->set_debug(0);
386             }
387             echo $OUTPUT->fatal_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo,
388                 $info->errorcode);
389         } catch (Exception $e) {
390             $out_ex = $e;
391         } catch (Throwable $e) {
392             // Engine errors in PHP7 throw exceptions of type Throwable (this "catch" will be ignored in PHP5).
393             $out_ex = $e;
394         }
396         if (isset($out_ex)) {
397             // default exception handler MUST not throw any exceptions!!
398             // 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
399             // so we just print at least something instead of "Exception thrown without a stack frame in Unknown on line 0":-(
400             if (CLI_SCRIPT or AJAX_SCRIPT) {
401                 // just ignore the error and send something back using the safest method
402                 echo bootstrap_renderer::early_error($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo, $info->errorcode);
403             } else {
404                 echo bootstrap_renderer::early_error_content($info->message, $info->moreinfourl, $info->link, $info->backtrace, $info->debuginfo);
405                 $outinfo = get_exception_info($out_ex);
406                 echo bootstrap_renderer::early_error_content($outinfo->message, $outinfo->moreinfourl, $outinfo->link, $outinfo->backtrace, $outinfo->debuginfo);
407             }
408         }
409     }
411     exit(1); // General error code
414 /**
415  * Default error handler, prevents some white screens.
416  * @param int $errno
417  * @param string $errstr
418  * @param string $errfile
419  * @param int $errline
420  * @param array $errcontext
421  * @return bool false means use default error handler
422  */
423 function default_error_handler($errno, $errstr, $errfile, $errline, $errcontext) {
424     if ($errno == 4096) {
425         //fatal catchable error
426         throw new coding_exception('PHP catchable fatal error', $errstr);
427     }
428     return false;
431 /**
432  * Unconditionally abort all database transactions, this function
433  * should be called from exception handlers only.
434  * @return void
435  */
436 function abort_all_db_transactions() {
437     global $CFG, $DB, $SCRIPT;
439     // default exception handler MUST not throw any exceptions!!
441     if ($DB && $DB->is_transaction_started()) {
442         error_log('Database transaction aborted automatically in ' . $CFG->dirroot . $SCRIPT);
443         // note: transaction blocks should never change current $_SESSION
444         $DB->force_transaction_rollback();
445     }
448 /**
449  * This function encapsulates the tests for whether an exception was thrown in
450  * early init -- either during setup.php or during init of $OUTPUT.
451  *
452  * If another exception is thrown then, and if we do not take special measures,
453  * we would just get a very cryptic message "Exception thrown without a stack
454  * frame in Unknown on line 0". That makes debugging very hard, so we do take
455  * special measures in default_exception_handler, with the help of this function.
456  *
457  * @param array $backtrace the stack trace to analyse.
458  * @return boolean whether the stack trace is somewhere in output initialisation.
459  */
460 function is_early_init($backtrace) {
461     $dangerouscode = array(
462         array('function' => 'header', 'type' => '->'),
463         array('class' => 'bootstrap_renderer'),
464         array('file' => __DIR__.'/setup.php'),
465     );
466     foreach ($backtrace as $stackframe) {
467         foreach ($dangerouscode as $pattern) {
468             $matches = true;
469             foreach ($pattern as $property => $value) {
470                 if (!isset($stackframe[$property]) || $stackframe[$property] != $value) {
471                     $matches = false;
472                 }
473             }
474             if ($matches) {
475                 return true;
476             }
477         }
478     }
479     return false;
482 /**
483  * Abort execution by throwing of a general exception,
484  * default exception handler displays the error message in most cases.
485  *
486  * @param string $errorcode The name of the language string containing the error message.
487  *      Normally this should be in the error.php lang file.
488  * @param string $module The language file to get the error message from.
489  * @param string $link The url where the user will be prompted to continue.
490  *      If no url is provided the user will be directed to the site index page.
491  * @param object $a Extra words and phrases that might be required in the error string
492  * @param string $debuginfo optional debugging information
493  * @return void, always throws exception!
494  */
495 function print_error($errorcode, $module = 'error', $link = '', $a = null, $debuginfo = null) {
496     throw new moodle_exception($errorcode, $module, $link, $a, $debuginfo);
499 /**
500  * Returns detailed information about specified exception.
501  * @param exception $ex
502  * @return object
503  */
504 function get_exception_info($ex) {
505     global $CFG, $DB, $SESSION;
507     if ($ex instanceof moodle_exception) {
508         $errorcode = $ex->errorcode;
509         $module = $ex->module;
510         $a = $ex->a;
511         $link = $ex->link;
512         $debuginfo = $ex->debuginfo;
513     } else {
514         $errorcode = 'generalexceptionmessage';
515         $module = 'error';
516         $a = $ex->getMessage();
517         $link = '';
518         $debuginfo = '';
519     }
521     // Append the error code to the debug info to make grepping and googling easier
522     $debuginfo .= PHP_EOL."Error code: $errorcode";
524     $backtrace = $ex->getTrace();
525     $place = array('file'=>$ex->getFile(), 'line'=>$ex->getLine(), 'exception'=>get_class($ex));
526     array_unshift($backtrace, $place);
528     // Be careful, no guarantee moodlelib.php is loaded.
529     if (empty($module) || $module == 'moodle' || $module == 'core') {
530         $module = 'error';
531     }
532     // Search for the $errorcode's associated string
533     // If not found, append the contents of $a to $debuginfo so helpful information isn't lost
534     if (function_exists('get_string_manager')) {
535         if (get_string_manager()->string_exists($errorcode, $module)) {
536             $message = get_string($errorcode, $module, $a);
537         } elseif ($module == 'error' && get_string_manager()->string_exists($errorcode, 'moodle')) {
538             // Search in moodle file if error specified - needed for backwards compatibility
539             $message = get_string($errorcode, 'moodle', $a);
540         } else {
541             $message = $module . '/' . $errorcode;
542             $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
543         }
544     } else {
545         $message = $module . '/' . $errorcode;
546         $debuginfo .= PHP_EOL.'$a contents: '.print_r($a, true);
547     }
549     // Remove some absolute paths from message and debugging info.
550     $searches = array();
551     $replaces = array();
552     $cfgnames = array('tempdir', 'cachedir', 'localcachedir', 'themedir', 'dataroot', 'dirroot');
553     foreach ($cfgnames as $cfgname) {
554         if (property_exists($CFG, $cfgname)) {
555             $searches[] = $CFG->$cfgname;
556             $replaces[] = "[$cfgname]";
557         }
558     }
559     if (!empty($searches)) {
560         $message   = str_replace($searches, $replaces, $message);
561         $debuginfo = str_replace($searches, $replaces, $debuginfo);
562     }
564     // Be careful, no guarantee weblib.php is loaded.
565     if (function_exists('clean_text')) {
566         $message = clean_text($message);
567     } else {
568         $message = htmlspecialchars($message);
569     }
571     if (!empty($CFG->errordocroot)) {
572         $errordoclink = $CFG->errordocroot . '/en/';
573     } else {
574         $errordoclink = get_docs_url();
575     }
577     if ($module === 'error') {
578         $modulelink = 'moodle';
579     } else {
580         $modulelink = $module;
581     }
582     $moreinfourl = $errordoclink . 'error/' . $modulelink . '/' . $errorcode;
584     if (empty($link)) {
585         if (!empty($SESSION->fromurl)) {
586             $link = $SESSION->fromurl;
587             unset($SESSION->fromurl);
588         } else {
589             $link = $CFG->wwwroot .'/';
590         }
591     }
593     // When printing an error the continue button should never link offsite.
594     // We cannot use clean_param() here as it is not guaranteed that it has been loaded yet.
595     $httpswwwroot = str_replace('http:', 'https:', $CFG->wwwroot);
596     if (stripos($link, $CFG->wwwroot) === 0) {
597         // Internal HTTP, all good.
598     } else if (!empty($CFG->loginhttps) && stripos($link, $httpswwwroot) === 0) {
599         // Internal HTTPS, all good.
600     } else {
601         // External link spotted!
602         $link = $CFG->wwwroot . '/';
603     }
605     $info = new stdClass();
606     $info->message     = $message;
607     $info->errorcode   = $errorcode;
608     $info->backtrace   = $backtrace;
609     $info->link        = $link;
610     $info->moreinfourl = $moreinfourl;
611     $info->a           = $a;
612     $info->debuginfo   = $debuginfo;
614     return $info;
617 /**
618  * Generate a uuid.
619  *
620  * Unique is hard. Very hard. Attempt to use the PECL UUID functions if available, and if not then revert to
621  * constructing the uuid using mt_rand.
622  *
623  * It is important that this token is not solely based on time as this could lead
624  * to duplicates in a clustered environment (especially on VMs due to poor time precision).
625  *
626  * @return string The uuid.
627  */
628 function generate_uuid() {
629     $uuid = '';
631     if (function_exists("uuid_create")) {
632         $context = null;
633         uuid_create($context);
635         uuid_make($context, UUID_MAKE_V4);
636         uuid_export($context, UUID_FMT_STR, $uuid);
637     } else {
638         // Fallback uuid generation based on:
639         // "http://www.php.net/manual/en/function.uniqid.php#94959".
640         $uuid = sprintf('%04x%04x-%04x-%04x-%04x-%04x%04x%04x',
642             // 32 bits for "time_low".
643             mt_rand(0, 0xffff), mt_rand(0, 0xffff),
645             // 16 bits for "time_mid".
646             mt_rand(0, 0xffff),
648             // 16 bits for "time_hi_and_version",
649             // four most significant bits holds version number 4.
650             mt_rand(0, 0x0fff) | 0x4000,
652             // 16 bits, 8 bits for "clk_seq_hi_res",
653             // 8 bits for "clk_seq_low",
654             // two most significant bits holds zero and one for variant DCE1.1.
655             mt_rand(0, 0x3fff) | 0x8000,
657             // 48 bits for "node".
658             mt_rand(0, 0xffff), mt_rand(0, 0xffff), mt_rand(0, 0xffff));
659     }
660     return trim($uuid);
663 /**
664  * Returns the Moodle Docs URL in the users language for a given 'More help' link.
665  *
666  * There are three cases:
667  *
668  * 1. In the normal case, $path will be a short relative path 'component/thing',
669  * like 'mod/folder/view' 'group/import'. This gets turned into an link to
670  * MoodleDocs in the user's language, and for the appropriate Moodle version.
671  * E.g. 'group/import' may become 'http://docs.moodle.org/2x/en/group/import'.
672  * The 'http://docs.moodle.org' bit comes from $CFG->docroot.
673  *
674  * This is the only option that should be used in standard Moodle code. The other
675  * two options have been implemented because they are useful for third-party plugins.
676  *
677  * 2. $path may be an absolute URL, starting http:// or https://. In this case,
678  * the link is used as is.
679  *
680  * 3. $path may start %%WWWROOT%%, in which case that is replaced by
681  * $CFG->wwwroot to make the link.
682  *
683  * @param string $path the place to link to. See above for details.
684  * @return string The MoodleDocs URL in the user's language. for example @link http://docs.moodle.org/2x/en/$path}
685  */
686 function get_docs_url($path = null) {
687     global $CFG;
689     // Absolute URLs are used unmodified.
690     if (substr($path, 0, 7) === 'http://' || substr($path, 0, 8) === 'https://') {
691         return $path;
692     }
694     // Paths starting %%WWWROOT%% have that replaced by $CFG->wwwroot.
695     if (substr($path, 0, 11) === '%%WWWROOT%%') {
696         return $CFG->wwwroot . substr($path, 11);
697     }
699     // Otherwise we do the normal case, and construct a MoodleDocs URL relative to $CFG->docroot.
701     // Check that $CFG->branch has been set up, during installation it won't be.
702     if (empty($CFG->branch)) {
703         // It's not there yet so look at version.php.
704         include($CFG->dirroot.'/version.php');
705     } else {
706         // We can use $CFG->branch and avoid having to include version.php.
707         $branch = $CFG->branch;
708     }
709     // ensure branch is valid.
710     if (!$branch) {
711         // We should never get here but in case we do lets set $branch to .
712         // the smart one's will know that this is the current directory
713         // and the smarter ones will know that there is some smart matching
714         // that will ensure people end up at the latest version of the docs.
715         $branch = '.';
716     }
717     if (empty($CFG->doclang)) {
718         $lang = current_language();
719     } else {
720         $lang = $CFG->doclang;
721     }
722     $end = '/' . $branch . '/' . $lang . '/' . $path;
723     if (empty($CFG->docroot)) {
724         return 'http://docs.moodle.org'. $end;
725     } else {
726         return $CFG->docroot . $end ;
727     }
730 /**
731  * Formats a backtrace ready for output.
732  *
733  * This function does not include function arguments because they could contain sensitive information
734  * not suitable to be exposed in a response.
735  *
736  * @param array $callers backtrace array, as returned by debug_backtrace().
737  * @param boolean $plaintext if false, generates HTML, if true generates plain text.
738  * @return string formatted backtrace, ready for output.
739  */
740 function format_backtrace($callers, $plaintext = false) {
741     // do not use $CFG->dirroot because it might not be available in destructors
742     $dirroot = dirname(__DIR__);
744     if (empty($callers)) {
745         return '';
746     }
748     $from = $plaintext ? '' : '<ul style="text-align: left" data-rel="backtrace">';
749     foreach ($callers as $caller) {
750         if (!isset($caller['line'])) {
751             $caller['line'] = '?'; // probably call_user_func()
752         }
753         if (!isset($caller['file'])) {
754             $caller['file'] = 'unknownfile'; // probably call_user_func()
755         }
756         $from .= $plaintext ? '* ' : '<li>';
757         $from .= 'line ' . $caller['line'] . ' of ' . str_replace($dirroot, '', $caller['file']);
758         if (isset($caller['function'])) {
759             $from .= ': call to ';
760             if (isset($caller['class'])) {
761                 $from .= $caller['class'] . $caller['type'];
762             }
763             $from .= $caller['function'] . '()';
764         } else if (isset($caller['exception'])) {
765             $from .= ': '.$caller['exception'].' thrown';
766         }
767         $from .= $plaintext ? "\n" : '</li>';
768     }
769     $from .= $plaintext ? '' : '</ul>';
771     return $from;
774 /**
775  * This function makes the return value of ini_get consistent if you are
776  * setting server directives through the .htaccess file in apache.
777  *
778  * Current behavior for value set from php.ini On = 1, Off = [blank]
779  * Current behavior for value set from .htaccess On = On, Off = Off
780  * Contributed by jdell @ unr.edu
781  *
782  * @param string $ini_get_arg The argument to get
783  * @return bool True for on false for not
784  */
785 function ini_get_bool($ini_get_arg) {
786     $temp = ini_get($ini_get_arg);
788     if ($temp == '1' or strtolower($temp) == 'on') {
789         return true;
790     }
791     return false;
794 /**
795  * This function verifies the sanity of PHP configuration
796  * and stops execution if anything critical found.
797  */
798 function setup_validate_php_configuration() {
799    // this must be very fast - no slow checks here!!!
801    if (ini_get_bool('session.auto_start')) {
802        print_error('sessionautostartwarning', 'admin');
803    }
806 /**
807  * Initialise global $CFG variable.
808  * @private to be used only from lib/setup.php
809  */
810 function initialise_cfg() {
811     global $CFG, $DB;
813     if (!$DB) {
814         // This should not happen.
815         return;
816     }
818     try {
819         $localcfg = get_config('core');
820     } catch (dml_exception $e) {
821         // Most probably empty db, going to install soon.
822         return;
823     }
825     foreach ($localcfg as $name => $value) {
826         // Note that get_config() keeps forced settings
827         // and normalises values to string if possible.
828         $CFG->{$name} = $value;
829     }
832 /**
833  * Initialises $FULLME and friends. Private function. Should only be called from
834  * setup.php.
835  */
836 function initialise_fullme() {
837     global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
839     // Detect common config error.
840     if (substr($CFG->wwwroot, -1) == '/') {
841         print_error('wwwrootslash', 'error');
842     }
844     if (CLI_SCRIPT) {
845         initialise_fullme_cli();
846         return;
847     }
849     $rurl = setup_get_remote_url();
850     $wwwroot = parse_url($CFG->wwwroot.'/');
852     if (empty($rurl['host'])) {
853         // missing host in request header, probably not a real browser, let's ignore them
855     } else if (!empty($CFG->reverseproxy)) {
856         // $CFG->reverseproxy specifies if reverse proxy server used
857         // Used in load balancing scenarios.
858         // Do not abuse this to try to solve lan/wan access problems!!!!!
860     } else {
861         if (($rurl['host'] !== $wwwroot['host']) or
862                 (!empty($wwwroot['port']) and $rurl['port'] != $wwwroot['port']) or
863                 (strpos($rurl['path'], $wwwroot['path']) !== 0)) {
865             // Explain the problem and redirect them to the right URL
866             if (!defined('NO_MOODLE_COOKIES')) {
867                 define('NO_MOODLE_COOKIES', true);
868             }
869             // The login/token.php script should call the correct url/port.
870             if (defined('REQUIRE_CORRECT_ACCESS') && REQUIRE_CORRECT_ACCESS) {
871                 $wwwrootport = empty($wwwroot['port'])?'':$wwwroot['port'];
872                 $calledurl = $rurl['host'];
873                 if (!empty($rurl['port'])) {
874                     $calledurl .=  ':'. $rurl['port'];
875                 }
876                 $correcturl = $wwwroot['host'];
877                 if (!empty($wwwrootport)) {
878                     $correcturl .=  ':'. $wwwrootport;
879                 }
880                 throw new moodle_exception('requirecorrectaccess', 'error', '', null,
881                     'You called ' . $calledurl .', you should have called ' . $correcturl);
882             }
883             redirect($CFG->wwwroot, get_string('wwwrootmismatch', 'error', $CFG->wwwroot), 3);
884         }
885     }
887     // Check that URL is under $CFG->wwwroot.
888     if (strpos($rurl['path'], $wwwroot['path']) === 0) {
889         $SCRIPT = substr($rurl['path'], strlen($wwwroot['path'])-1);
890     } else {
891         // Probably some weird external script
892         $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
893         return;
894     }
896     // $CFG->sslproxy specifies if external SSL appliance is used
897     // (That is, the Moodle server uses http, with an external box translating everything to https).
898     if (empty($CFG->sslproxy)) {
899         if ($rurl['scheme'] === 'http' and $wwwroot['scheme'] === 'https') {
900             print_error('sslonlyaccess', 'error');
901         }
902     } else {
903         if ($wwwroot['scheme'] !== 'https') {
904             throw new coding_exception('Must use https address in wwwroot when ssl proxy enabled!');
905         }
906         $rurl['scheme'] = 'https'; // make moodle believe it runs on https, squid or something else it doing it
907         $_SERVER['HTTPS'] = 'on'; // Override $_SERVER to help external libraries with their HTTPS detection.
908         $_SERVER['SERVER_PORT'] = 443; // Assume default ssl port for the proxy.
909     }
911     // hopefully this will stop all those "clever" admins trying to set up moodle
912     // with two different addresses in intranet and Internet
913     if (!empty($CFG->reverseproxy) && $rurl['host'] === $wwwroot['host']) {
914         print_error('reverseproxyabused', 'error');
915     }
917     $hostandport = $rurl['scheme'] . '://' . $wwwroot['host'];
918     if (!empty($wwwroot['port'])) {
919         $hostandport .= ':'.$wwwroot['port'];
920     }
922     $FULLSCRIPT = $hostandport . $rurl['path'];
923     $FULLME = $hostandport . $rurl['fullpath'];
924     $ME = $rurl['fullpath'];
927 /**
928  * Initialises $FULLME and friends for command line scripts.
929  * This is a private method for use by initialise_fullme.
930  */
931 function initialise_fullme_cli() {
932     global $CFG, $FULLME, $ME, $SCRIPT, $FULLSCRIPT;
934     // Urls do not make much sense in CLI scripts
935     $backtrace = debug_backtrace();
936     $topfile = array_pop($backtrace);
937     $topfile = realpath($topfile['file']);
938     $dirroot = realpath($CFG->dirroot);
940     if (strpos($topfile, $dirroot) !== 0) {
941         // Probably some weird external script
942         $SCRIPT = $FULLSCRIPT = $FULLME = $ME = null;
943     } else {
944         $relativefile = substr($topfile, strlen($dirroot));
945         $relativefile = str_replace('\\', '/', $relativefile); // Win fix
946         $SCRIPT = $FULLSCRIPT = $relativefile;
947         $FULLME = $ME = null;
948     }
951 /**
952  * Get the URL that PHP/the web server thinks it is serving. Private function
953  * used by initialise_fullme. In your code, use $PAGE->url, $SCRIPT, etc.
954  * @return array in the same format that parse_url returns, with the addition of
955  *      a 'fullpath' element, which includes any slasharguments path.
956  */
957 function setup_get_remote_url() {
958     $rurl = array();
959     if (isset($_SERVER['HTTP_HOST'])) {
960         list($rurl['host']) = explode(':', $_SERVER['HTTP_HOST']);
961     } else {
962         $rurl['host'] = null;
963     }
964     $rurl['port'] = $_SERVER['SERVER_PORT'];
965     $rurl['path'] = $_SERVER['SCRIPT_NAME']; // Script path without slash arguments
966     $rurl['scheme'] = (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] === 'off' or $_SERVER['HTTPS'] === 'Off' or $_SERVER['HTTPS'] === 'OFF') ? 'http' : 'https';
968     if (stripos($_SERVER['SERVER_SOFTWARE'], 'apache') !== false) {
969         //Apache server
970         $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
972         // Fixing a known issue with:
973         // - Apache versions lesser than 2.4.11
974         // - PHP deployed in Apache as PHP-FPM via mod_proxy_fcgi
975         // - PHP versions lesser than 5.6.3 and 5.5.18.
976         if (isset($_SERVER['PATH_INFO']) && (php_sapi_name() === 'fpm-fcgi') && isset($_SERVER['SCRIPT_NAME'])) {
977             $pathinfodec = rawurldecode($_SERVER['PATH_INFO']);
978             $lenneedle = strlen($pathinfodec);
979             // Checks whether SCRIPT_NAME ends with PATH_INFO, URL-decoded.
980             if (substr($_SERVER['SCRIPT_NAME'], -$lenneedle) === $pathinfodec) {
981                 // This is the "Apache 2.4.10- running PHP-FPM via mod_proxy_fcgi" fingerprint,
982                 // at least on CentOS 7 (Apache/2.4.6 PHP/5.4.16) and Ubuntu 14.04 (Apache/2.4.7 PHP/5.5.9)
983                 // => SCRIPT_NAME contains 'slash arguments' data too, which is wrongly exposed via PATH_INFO as URL-encoded.
984                 // Fix both $_SERVER['PATH_INFO'] and $_SERVER['SCRIPT_NAME'].
985                 $lenhaystack = strlen($_SERVER['SCRIPT_NAME']);
986                 $pos = $lenhaystack - $lenneedle;
987                 // Here $pos is greater than 0 but let's double check it.
988                 if ($pos > 0) {
989                     $_SERVER['PATH_INFO'] = $pathinfodec;
990                     $_SERVER['SCRIPT_NAME'] = substr($_SERVER['SCRIPT_NAME'], 0, $pos);
991                 }
992             }
993         }
995     } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'iis') !== false) {
996         //IIS - needs a lot of tweaking to make it work
997         $rurl['fullpath'] = $_SERVER['SCRIPT_NAME'];
999         // NOTE: we should ignore PATH_INFO because it is incorrectly encoded using 8bit filesystem legacy encoding in IIS.
1000         //       Since 2.0, we rely on IIS rewrite extensions like Helicon ISAPI_rewrite
1001         //         example rule: RewriteRule ^([^\?]+?\.php)(\/.+)$ $1\?file=$2 [QSA]
1002         //       OR
1003         //       we rely on a proper IIS 6.0+ configuration: the 'FastCGIUtf8ServerVariables' registry key.
1004         if (isset($_SERVER['PATH_INFO']) and $_SERVER['PATH_INFO'] !== '') {
1005             // Check that PATH_INFO works == must not contain the script name.
1006             if (strpos($_SERVER['PATH_INFO'], $_SERVER['SCRIPT_NAME']) === false) {
1007                 $rurl['fullpath'] .= clean_param(urldecode($_SERVER['PATH_INFO']), PARAM_PATH);
1008             }
1009         }
1011         if (isset($_SERVER['QUERY_STRING']) and $_SERVER['QUERY_STRING'] !== '') {
1012             $rurl['fullpath'] .= '?'.$_SERVER['QUERY_STRING'];
1013         }
1014         $_SERVER['REQUEST_URI'] = $rurl['fullpath']; // extra IIS compatibility
1016 /* NOTE: following servers are not fully tested! */
1018     } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'lighttpd') !== false) {
1019         //lighttpd - not officially supported
1020         $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1022     } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'nginx') !== false) {
1023         //nginx - not officially supported
1024         if (!isset($_SERVER['SCRIPT_NAME'])) {
1025             die('Invalid server configuration detected, please try to add "fastcgi_param SCRIPT_NAME $fastcgi_script_name;" to the nginx server configuration.');
1026         }
1027         $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1029      } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'cherokee') !== false) {
1030          //cherokee - not officially supported
1031          $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1033      } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'zeus') !== false) {
1034          //zeus - not officially supported
1035          $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1037     } else if (stripos($_SERVER['SERVER_SOFTWARE'], 'LiteSpeed') !== false) {
1038         //LiteSpeed - not officially supported
1039         $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1041     } else if ($_SERVER['SERVER_SOFTWARE'] === 'HTTPD') {
1042         //obscure name found on some servers - this is definitely not supported
1043         $rurl['fullpath'] = $_SERVER['REQUEST_URI']; // TODO: verify this is always properly encoded
1045     } else if (strpos($_SERVER['SERVER_SOFTWARE'], 'PHP') === 0) {
1046         // built-in PHP Development Server
1047         $rurl['fullpath'] = $_SERVER['REQUEST_URI'];
1049     } else {
1050         throw new moodle_exception('unsupportedwebserver', 'error', '', $_SERVER['SERVER_SOFTWARE']);
1051     }
1053     // sanitize the url a bit more, the encoding style may be different in vars above
1054     $rurl['fullpath'] = str_replace('"', '%22', $rurl['fullpath']);
1055     $rurl['fullpath'] = str_replace('\'', '%27', $rurl['fullpath']);
1057     return $rurl;
1060 /**
1061  * Try to work around the 'max_input_vars' restriction if necessary.
1062  */
1063 function workaround_max_input_vars() {
1064     // Make sure this gets executed only once from lib/setup.php!
1065     static $executed = false;
1066     if ($executed) {
1067         debugging('workaround_max_input_vars() must be called only once!');
1068         return;
1069     }
1070     $executed = true;
1072     if (!isset($_SERVER["CONTENT_TYPE"]) or strpos($_SERVER["CONTENT_TYPE"], 'multipart/form-data') !== false) {
1073         // Not a post or 'multipart/form-data' which is not compatible with "php://input" reading.
1074         return;
1075     }
1077     if (!isloggedin() or isguestuser()) {
1078         // Only real users post huge forms.
1079         return;
1080     }
1082     $max = (int)ini_get('max_input_vars');
1084     if ($max <= 0) {
1085         // Most probably PHP < 5.3.9 that does not implement this limit.
1086         return;
1087     }
1089     if ($max >= 200000) {
1090         // This value should be ok for all our forms, by setting it in php.ini
1091         // admins may prevent any unexpected regressions caused by this hack.
1093         // Note there is no need to worry about DDoS caused by making this limit very high
1094         // because there are very many easier ways to DDoS any Moodle server.
1095         return;
1096     }
1098     // Worst case is advanced checkboxes which use up to two max_input_vars
1099     // slots for each entry in $_POST, because of sending two fields with the
1100     // same name. So count everything twice just in case.
1101     if (count($_POST, COUNT_RECURSIVE) * 2 < $max) {
1102         return;
1103     }
1105     // Large POST request with enctype supported by php://input.
1106     // Parse php://input in chunks to bypass max_input_vars limit, which also applies to parse_str().
1107     $str = file_get_contents("php://input");
1108     if ($str === false or $str === '') {
1109         // Some weird error.
1110         return;
1111     }
1113     $delim = '&';
1114     $fun = create_function('$p', 'return implode("'.$delim.'", $p);');
1115     $chunks = array_map($fun, array_chunk(explode($delim, $str), $max));
1117     // Clear everything from existing $_POST array, otherwise it might be included
1118     // twice (this affects array params primarily).
1119     foreach ($_POST as $key => $value) {
1120         unset($_POST[$key]);
1121         // Also clear from request array - but only the things that are in $_POST,
1122         // that way it will leave the things from a get request if any.
1123         unset($_REQUEST[$key]);
1124     }
1126     foreach ($chunks as $chunk) {
1127         $values = array();
1128         parse_str($chunk, $values);
1130         merge_query_params($_POST, $values);
1131         merge_query_params($_REQUEST, $values);
1132     }
1135 /**
1136  * Merge parsed POST chunks.
1137  *
1138  * NOTE: this is not perfect, but it should work in most cases hopefully.
1139  *
1140  * @param array $target
1141  * @param array $values
1142  */
1143 function merge_query_params(array &$target, array $values) {
1144     if (isset($values[0]) and isset($target[0])) {
1145         // This looks like a split [] array, lets verify the keys are continuous starting with 0.
1146         $keys1 = array_keys($values);
1147         $keys2 = array_keys($target);
1148         if ($keys1 === array_keys($keys1) and $keys2 === array_keys($keys2)) {
1149             foreach ($values as $v) {
1150                 $target[] = $v;
1151             }
1152             return;
1153         }
1154     }
1155     foreach ($values as $k => $v) {
1156         if (!isset($target[$k])) {
1157             $target[$k] = $v;
1158             continue;
1159         }
1160         if (is_array($target[$k]) and is_array($v)) {
1161             merge_query_params($target[$k], $v);
1162             continue;
1163         }
1164         // We should not get here unless there are duplicates in params.
1165         $target[$k] = $v;
1166     }
1169 /**
1170  * Initializes our performance info early.
1171  *
1172  * Pairs up with get_performance_info() which is actually
1173  * in moodlelib.php. This function is here so that we can
1174  * call it before all the libs are pulled in.
1175  *
1176  * @uses $PERF
1177  */
1178 function init_performance_info() {
1180     global $PERF, $CFG, $USER;
1182     $PERF = new stdClass();
1183     $PERF->logwrites = 0;
1184     if (function_exists('microtime')) {
1185         $PERF->starttime = microtime();
1186     }
1187     if (function_exists('memory_get_usage')) {
1188         $PERF->startmemory = memory_get_usage();
1189     }
1190     if (function_exists('posix_times')) {
1191         $PERF->startposixtimes = posix_times();
1192     }
1195 /**
1196  * Indicates whether we are in the middle of the initial Moodle install.
1197  *
1198  * Very occasionally it is necessary avoid running certain bits of code before the
1199  * Moodle installation has completed. The installed flag is set in admin/index.php
1200  * after Moodle core and all the plugins have been installed, but just before
1201  * the person doing the initial install is asked to choose the admin password.
1202  *
1203  * @return boolean true if the initial install is not complete.
1204  */
1205 function during_initial_install() {
1206     global $CFG;
1207     return empty($CFG->rolesactive);
1210 /**
1211  * Function to raise the memory limit to a new value.
1212  * Will respect the memory limit if it is higher, thus allowing
1213  * settings in php.ini, apache conf or command line switches
1214  * to override it.
1215  *
1216  * The memory limit should be expressed with a constant
1217  * MEMORY_STANDARD, MEMORY_EXTRA or MEMORY_HUGE.
1218  * It is possible to use strings or integers too (eg:'128M').
1219  *
1220  * @param mixed $newlimit the new memory limit
1221  * @return bool success
1222  */
1223 function raise_memory_limit($newlimit) {
1224     global $CFG;
1226     if ($newlimit == MEMORY_UNLIMITED) {
1227         ini_set('memory_limit', -1);
1228         return true;
1230     } else if ($newlimit == MEMORY_STANDARD) {
1231         if (PHP_INT_SIZE > 4) {
1232             $newlimit = get_real_size('128M'); // 64bit needs more memory
1233         } else {
1234             $newlimit = get_real_size('96M');
1235         }
1237     } else if ($newlimit == MEMORY_EXTRA) {
1238         if (PHP_INT_SIZE > 4) {
1239             $newlimit = get_real_size('384M'); // 64bit needs more memory
1240         } else {
1241             $newlimit = get_real_size('256M');
1242         }
1243         if (!empty($CFG->extramemorylimit)) {
1244             $extra = get_real_size($CFG->extramemorylimit);
1245             if ($extra > $newlimit) {
1246                 $newlimit = $extra;
1247             }
1248         }
1250     } else if ($newlimit == MEMORY_HUGE) {
1251         // MEMORY_HUGE uses 2G or MEMORY_EXTRA, whichever is bigger.
1252         $newlimit = get_real_size('2G');
1253         if (!empty($CFG->extramemorylimit)) {
1254             $extra = get_real_size($CFG->extramemorylimit);
1255             if ($extra > $newlimit) {
1256                 $newlimit = $extra;
1257             }
1258         }
1260     } else {
1261         $newlimit = get_real_size($newlimit);
1262     }
1264     if ($newlimit <= 0) {
1265         debugging('Invalid memory limit specified.');
1266         return false;
1267     }
1269     $cur = ini_get('memory_limit');
1270     if (empty($cur)) {
1271         // if php is compiled without --enable-memory-limits
1272         // apparently memory_limit is set to ''
1273         $cur = 0;
1274     } else {
1275         if ($cur == -1){
1276             return true; // unlimited mem!
1277         }
1278         $cur = get_real_size($cur);
1279     }
1281     if ($newlimit > $cur) {
1282         ini_set('memory_limit', $newlimit);
1283         return true;
1284     }
1285     return false;
1288 /**
1289  * Function to reduce the memory limit to a new value.
1290  * Will respect the memory limit if it is lower, thus allowing
1291  * settings in php.ini, apache conf or command line switches
1292  * to override it
1293  *
1294  * The memory limit should be expressed with a string (eg:'64M')
1295  *
1296  * @param string $newlimit the new memory limit
1297  * @return bool
1298  */
1299 function reduce_memory_limit($newlimit) {
1300     if (empty($newlimit)) {
1301         return false;
1302     }
1303     $cur = ini_get('memory_limit');
1304     if (empty($cur)) {
1305         // if php is compiled without --enable-memory-limits
1306         // apparently memory_limit is set to ''
1307         $cur = 0;
1308     } else {
1309         if ($cur == -1){
1310             return true; // unlimited mem!
1311         }
1312         $cur = get_real_size($cur);
1313     }
1315     $new = get_real_size($newlimit);
1316     // -1 is smaller, but it means unlimited
1317     if ($new < $cur && $new != -1) {
1318         ini_set('memory_limit', $newlimit);
1319         return true;
1320     }
1321     return false;
1324 /**
1325  * Converts numbers like 10M into bytes.
1326  *
1327  * @param string $size The size to be converted
1328  * @return int
1329  */
1330 function get_real_size($size = 0) {
1331     if (!$size) {
1332         return 0;
1333     }
1335     static $binaryprefixes = array(
1336         'K' => 1024,
1337         'k' => 1024,
1338         'M' => 1048576,
1339         'm' => 1048576,
1340         'G' => 1073741824,
1341         'g' => 1073741824,
1342         'T' => 1099511627776,
1343         't' => 1099511627776,
1344     );
1346     if (preg_match('/^([0-9]+)([KMGT])/i', $size, $matches)) {
1347         return $matches[1] * $binaryprefixes[$matches[2]];
1348     }
1350     return (int) $size;
1353 /**
1354  * Try to disable all output buffering and purge
1355  * all headers.
1356  *
1357  * @access private to be called only from lib/setup.php !
1358  * @return void
1359  */
1360 function disable_output_buffering() {
1361     $olddebug = error_reporting(0);
1363     // disable compression, it would prevent closing of buffers
1364     if (ini_get_bool('zlib.output_compression')) {
1365         ini_set('zlib.output_compression', 'Off');
1366     }
1368     // try to flush everything all the time
1369     ob_implicit_flush(true);
1371     // close all buffers if possible and discard any existing output
1372     // this can actually work around some whitespace problems in config.php
1373     while(ob_get_level()) {
1374         if (!ob_end_clean()) {
1375             // prevent infinite loop when buffer can not be closed
1376             break;
1377         }
1378     }
1380     // disable any other output handlers
1381     ini_set('output_handler', '');
1383     error_reporting($olddebug);
1385     // Disable buffering in nginx.
1386     header('X-Accel-Buffering: no');
1390 /**
1391  * Check whether a major upgrade is needed.
1392  *
1393  * That is defined as an upgrade that changes something really fundamental
1394  * in the database, so nothing can possibly work until the database has
1395  * been updated, and that is defined by the hard-coded version number in
1396  * this function.
1397  *
1398  * @return bool
1399  */
1400 function is_major_upgrade_required() {
1401     global $CFG;
1402     $lastmajordbchanges = 2017040403.00;
1404     $required = empty($CFG->version);
1405     $required = $required || (float)$CFG->version < $lastmajordbchanges;
1406     $required = $required || during_initial_install();
1407     $required = $required || !empty($CFG->adminsetuppending);
1409     return $required;
1412 /**
1413  * Redirect to the Notifications page if a major upgrade is required, and
1414  * terminate the current user session.
1415  */
1416 function redirect_if_major_upgrade_required() {
1417     global $CFG;
1418     if (is_major_upgrade_required()) {
1419         try {
1420             @\core\session\manager::terminate_current();
1421         } catch (Exception $e) {
1422             // Ignore any errors, redirect to upgrade anyway.
1423         }
1424         $url = $CFG->wwwroot . '/' . $CFG->admin . '/index.php';
1425         @header($_SERVER['SERVER_PROTOCOL'] . ' 303 See Other');
1426         @header('Location: ' . $url);
1427         echo bootstrap_renderer::plain_redirect_message(htmlspecialchars($url));
1428         exit;
1429     }
1432 /**
1433  * Makes sure that upgrade process is not running
1434  *
1435  * To be inserted in the core functions that can not be called by pluigns during upgrade.
1436  * Core upgrade should not use any API functions at all.
1437  * See {@link http://docs.moodle.org/dev/Upgrade_API#Upgrade_code_restrictions}
1438  *
1439  * @throws moodle_exception if executed from inside of upgrade script and $warningonly is false
1440  * @param bool $warningonly if true displays a warning instead of throwing an exception
1441  * @return bool true if executed from outside of upgrade process, false if from inside upgrade process and function is used for warning only
1442  */
1443 function upgrade_ensure_not_running($warningonly = false) {
1444     global $CFG;
1445     if (!empty($CFG->upgraderunning)) {
1446         if (!$warningonly) {
1447             throw new moodle_exception('cannotexecduringupgrade');
1448         } else {
1449             debugging(get_string('cannotexecduringupgrade', 'error'), DEBUG_DEVELOPER);
1450             return false;
1451         }
1452     }
1453     return true;
1456 /**
1457  * Function to check if a directory exists and by default create it if not exists.
1458  *
1459  * Previously this was accepting paths only from dataroot, but we now allow
1460  * files outside of dataroot if you supply custom paths for some settings in config.php.
1461  * This function does not verify that the directory is writable.
1462  *
1463  * NOTE: this function uses current file stat cache,
1464  *       please use clearstatcache() before this if you expect that the
1465  *       directories may have been removed recently from a different request.
1466  *
1467  * @param string $dir absolute directory path
1468  * @param boolean $create directory if does not exist
1469  * @param boolean $recursive create directory recursively
1470  * @return boolean true if directory exists or created, false otherwise
1471  */
1472 function check_dir_exists($dir, $create = true, $recursive = true) {
1473     global $CFG;
1475     umask($CFG->umaskpermissions);
1477     if (is_dir($dir)) {
1478         return true;
1479     }
1481     if (!$create) {
1482         return false;
1483     }
1485     return mkdir($dir, $CFG->directorypermissions, $recursive);
1488 /**
1489  * Create a new unique directory within the specified directory.
1490  *
1491  * @param string $basedir The directory to create your new unique directory within.
1492  * @param bool $exceptiononerror throw exception if error encountered
1493  * @return string The created directory
1494  * @throws invalid_dataroot_permissions
1495  */
1496 function make_unique_writable_directory($basedir, $exceptiononerror = true) {
1497     if (!is_dir($basedir) || !is_writable($basedir)) {
1498         // The basedir is not writable. We will not be able to create the child directory.
1499         if ($exceptiononerror) {
1500             throw new invalid_dataroot_permissions($basedir . ' is not writable. Unable to create a unique directory within it.');
1501         } else {
1502             return false;
1503         }
1504     }
1506     do {
1507         // Generate a new (hopefully unique) directory name.
1508         $uniquedir = $basedir . DIRECTORY_SEPARATOR . generate_uuid();
1509     } while (
1510             // Ensure that basedir is still writable - if we do not check, we could get stuck in a loop here.
1511             is_writable($basedir) &&
1513             // Make the new unique directory. If the directory already exists, it will return false.
1514             !make_writable_directory($uniquedir, $exceptiononerror) &&
1516             // Ensure that the directory now exists
1517             file_exists($uniquedir) && is_dir($uniquedir)
1518         );
1520     // Check that the directory was correctly created.
1521     if (!file_exists($uniquedir) || !is_dir($uniquedir) || !is_writable($uniquedir)) {
1522         if ($exceptiononerror) {
1523             throw new invalid_dataroot_permissions('Unique directory creation failed.');
1524         } else {
1525             return false;
1526         }
1527     }
1529     return $uniquedir;
1532 /**
1533  * Create a directory and make sure it is writable.
1534  *
1535  * @private
1536  * @param string $dir  the full path of the directory to be created
1537  * @param bool $exceptiononerror throw exception if error encountered
1538  * @return string|false Returns full path to directory if successful, false if not; may throw exception
1539  */
1540 function make_writable_directory($dir, $exceptiononerror = true) {
1541     global $CFG;
1543     if (file_exists($dir) and !is_dir($dir)) {
1544         if ($exceptiononerror) {
1545             throw new coding_exception($dir.' directory can not be created, file with the same name already exists.');
1546         } else {
1547             return false;
1548         }
1549     }
1551     umask($CFG->umaskpermissions);
1553     if (!file_exists($dir)) {
1554         if (!@mkdir($dir, $CFG->directorypermissions, true)) {
1555             clearstatcache();
1556             // There might be a race condition when creating directory.
1557             if (!is_dir($dir)) {
1558                 if ($exceptiononerror) {
1559                     throw new invalid_dataroot_permissions($dir.' can not be created, check permissions.');
1560                 } else {
1561                     debugging('Can not create directory: '.$dir, DEBUG_DEVELOPER);
1562                     return false;
1563                 }
1564             }
1565         }
1566     }
1568     if (!is_writable($dir)) {
1569         if ($exceptiononerror) {
1570             throw new invalid_dataroot_permissions($dir.' is not writable, check permissions.');
1571         } else {
1572             return false;
1573         }
1574     }
1576     return $dir;
1579 /**
1580  * Protect a directory from web access.
1581  * Could be extended in the future to support other mechanisms (e.g. other webservers).
1582  *
1583  * @private
1584  * @param string $dir  the full path of the directory to be protected
1585  */
1586 function protect_directory($dir) {
1587     global $CFG;
1588     // Make sure a .htaccess file is here, JUST IN CASE the files area is in the open and .htaccess is supported
1589     if (!file_exists("$dir/.htaccess")) {
1590         if ($handle = fopen("$dir/.htaccess", 'w')) {   // For safety
1591             @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");
1592             @fclose($handle);
1593             @chmod("$dir/.htaccess", $CFG->filepermissions);
1594         }
1595     }
1598 /**
1599  * Create a directory under dataroot and make sure it is writable.
1600  * Do not use for temporary and cache files - see make_temp_directory() and make_cache_directory().
1601  *
1602  * @param string $directory  the full path of the directory to be created under $CFG->dataroot
1603  * @param bool $exceptiononerror throw exception if error encountered
1604  * @return string|false Returns full path to directory if successful, false if not; may throw exception
1605  */
1606 function make_upload_directory($directory, $exceptiononerror = true) {
1607     global $CFG;
1609     if (strpos($directory, 'temp/') === 0 or $directory === 'temp') {
1610         debugging('Use make_temp_directory() for creation of temporary directory and $CFG->tempdir to get the location.');
1612     } else if (strpos($directory, 'cache/') === 0 or $directory === 'cache') {
1613         debugging('Use make_cache_directory() for creation of cache directory and $CFG->cachedir to get the location.');
1615     } else if (strpos($directory, 'localcache/') === 0 or $directory === 'localcache') {
1616         debugging('Use make_localcache_directory() for creation of local cache directory and $CFG->localcachedir to get the location.');
1617     }
1619     protect_directory($CFG->dataroot);
1620     return make_writable_directory("$CFG->dataroot/$directory", $exceptiononerror);
1623 /**
1624  * Get a per-request storage directory in the tempdir.
1625  *
1626  * The directory is automatically cleaned up during the shutdown handler.
1627  *
1628  * @param bool $exceptiononerror throw exception if error encountered
1629  * @return string|false Returns full path to directory if successful, false if not; may throw exception
1630  */
1631 function get_request_storage_directory($exceptiononerror = true) {
1632     global $CFG;
1634     static $requestdir = null;
1636     if (!$requestdir || !file_exists($requestdir) || !is_dir($requestdir) || !is_writable($requestdir)) {
1637         if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1638             check_dir_exists($CFG->localcachedir, true, true);
1639             protect_directory($CFG->localcachedir);
1640         } else {
1641             protect_directory($CFG->dataroot);
1642         }
1644         if ($requestdir = make_unique_writable_directory($CFG->localcachedir, $exceptiononerror)) {
1645             // Register a shutdown handler to remove the directory.
1646             \core_shutdown_manager::register_function('remove_dir', array($requestdir));
1647         }
1648     }
1650     return $requestdir;
1653 /**
1654  * Create a per-request directory and make sure it is writable.
1655  * This can only be used during the current request and will be tidied away
1656  * automatically afterwards.
1657  *
1658  * A new, unique directory is always created within the current request directory.
1659  *
1660  * @param bool $exceptiononerror throw exception if error encountered
1661  * @return string full path to directory if successful, false if not; may throw exception
1662  */
1663 function make_request_directory($exceptiononerror = true) {
1664     $basedir = get_request_storage_directory($exceptiononerror);
1665     return make_unique_writable_directory($basedir, $exceptiononerror);
1668 /**
1669  * Create a directory under tempdir and make sure it is writable.
1670  *
1671  * Where possible, please use make_request_directory() and limit the scope
1672  * of your data to the current HTTP request.
1673  *
1674  * Do not use for storing cache files - see make_cache_directory(), and
1675  * make_localcache_directory() instead for this purpose.
1676  *
1677  * Temporary files must be on a shared storage, and heavy usage is
1678  * discouraged due to the performance impact upon clustered environments.
1679  *
1680  * @param string $directory  the full path of the directory to be created under $CFG->tempdir
1681  * @param bool $exceptiononerror throw exception if error encountered
1682  * @return string|false Returns full path to directory if successful, false if not; may throw exception
1683  */
1684 function make_temp_directory($directory, $exceptiononerror = true) {
1685     global $CFG;
1686     if ($CFG->tempdir !== "$CFG->dataroot/temp") {
1687         check_dir_exists($CFG->tempdir, true, true);
1688         protect_directory($CFG->tempdir);
1689     } else {
1690         protect_directory($CFG->dataroot);
1691     }
1692     return make_writable_directory("$CFG->tempdir/$directory", $exceptiononerror);
1695 /**
1696  * Create a directory under cachedir and make sure it is writable.
1697  *
1698  * Note: this cache directory is shared by all cluster nodes.
1699  *
1700  * @param string $directory  the full path of the directory to be created under $CFG->cachedir
1701  * @param bool $exceptiononerror throw exception if error encountered
1702  * @return string|false Returns full path to directory if successful, false if not; may throw exception
1703  */
1704 function make_cache_directory($directory, $exceptiononerror = true) {
1705     global $CFG;
1706     if ($CFG->cachedir !== "$CFG->dataroot/cache") {
1707         check_dir_exists($CFG->cachedir, true, true);
1708         protect_directory($CFG->cachedir);
1709     } else {
1710         protect_directory($CFG->dataroot);
1711     }
1712     return make_writable_directory("$CFG->cachedir/$directory", $exceptiononerror);
1715 /**
1716  * Create a directory under localcachedir and make sure it is writable.
1717  * The files in this directory MUST NOT change, use revisions or content hashes to
1718  * work around this limitation - this means you can only add new files here.
1719  *
1720  * The content of this directory gets purged automatically on all cluster nodes
1721  * after calling purge_all_caches() before new data is written to this directory.
1722  *
1723  * Note: this local cache directory does not need to be shared by cluster nodes.
1724  *
1725  * @param string $directory the relative path of the directory to be created under $CFG->localcachedir
1726  * @param bool $exceptiononerror throw exception if error encountered
1727  * @return string|false Returns full path to directory if successful, false if not; may throw exception
1728  */
1729 function make_localcache_directory($directory, $exceptiononerror = true) {
1730     global $CFG;
1732     make_writable_directory($CFG->localcachedir, $exceptiononerror);
1734     if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1735         protect_directory($CFG->localcachedir);
1736     } else {
1737         protect_directory($CFG->dataroot);
1738     }
1740     if (!isset($CFG->localcachedirpurged)) {
1741         $CFG->localcachedirpurged = 0;
1742     }
1743     $timestampfile = "$CFG->localcachedir/.lastpurged";
1745     if (!file_exists($timestampfile)) {
1746         touch($timestampfile);
1747         @chmod($timestampfile, $CFG->filepermissions);
1749     } else if (filemtime($timestampfile) <  $CFG->localcachedirpurged) {
1750         // This means our local cached dir was not purged yet.
1751         remove_dir($CFG->localcachedir, true);
1752         if ($CFG->localcachedir !== "$CFG->dataroot/localcache") {
1753             protect_directory($CFG->localcachedir);
1754         }
1755         touch($timestampfile);
1756         @chmod($timestampfile, $CFG->filepermissions);
1757         clearstatcache();
1758     }
1760     if ($directory === '') {
1761         return $CFG->localcachedir;
1762     }
1764     return make_writable_directory("$CFG->localcachedir/$directory", $exceptiononerror);
1767 /**
1768  * This class solves the problem of how to initialise $OUTPUT.
1769  *
1770  * The problem is caused be two factors
1771  * <ol>
1772  * <li>On the one hand, we cannot be sure when output will start. In particular,
1773  * an error, which needs to be displayed, could be thrown at any time.</li>
1774  * <li>On the other hand, we cannot be sure when we will have all the information
1775  * necessary to correctly initialise $OUTPUT. $OUTPUT depends on the theme, which
1776  * (potentially) depends on the current course, course categories, and logged in user.
1777  * It also depends on whether the current page requires HTTPS.</li>
1778  * </ol>
1779  *
1780  * So, it is hard to find a single natural place during Moodle script execution,
1781  * which we can guarantee is the right time to initialise $OUTPUT. Instead we
1782  * adopt the following strategy
1783  * <ol>
1784  * <li>We will initialise $OUTPUT the first time it is used.</li>
1785  * <li>If, after $OUTPUT has been initialised, the script tries to change something
1786  * that $OUTPUT depends on, we throw an exception making it clear that the script
1787  * did something wrong.
1788  * </ol>
1789  *
1790  * The only problem with that is, how do we initialise $OUTPUT on first use if,
1791  * it is going to be used like $OUTPUT->somthing(...)? Well that is where this
1792  * class comes in. Initially, we set up $OUTPUT = new bootstrap_renderer(). Then,
1793  * when any method is called on that object, we initialise $OUTPUT, and pass the call on.
1794  *
1795  * Note that this class is used before lib/outputlib.php has been loaded, so we
1796  * must be careful referring to classes/functions from there, they may not be
1797  * defined yet, and we must avoid fatal errors.
1798  *
1799  * @copyright 2009 Tim Hunt
1800  * @license   http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
1801  * @since     Moodle 2.0
1802  */
1803 class bootstrap_renderer {
1804     /**
1805      * Handles re-entrancy. Without this, errors or debugging output that occur
1806      * during the initialisation of $OUTPUT, cause infinite recursion.
1807      * @var boolean
1808      */
1809     protected $initialising = false;
1811     /**
1812      * Have we started output yet?
1813      * @return boolean true if the header has been printed.
1814      */
1815     public function has_started() {
1816         return false;
1817     }
1819     /**
1820      * Constructor - to be used by core code only.
1821      * @param string $method The method to call
1822      * @param array $arguments Arguments to pass to the method being called
1823      * @return string
1824      */
1825     public function __call($method, $arguments) {
1826         global $OUTPUT, $PAGE;
1828         $recursing = false;
1829         if ($method == 'notification') {
1830             // Catch infinite recursion caused by debugging output during print_header.
1831             $backtrace = debug_backtrace();
1832             array_shift($backtrace);
1833             array_shift($backtrace);
1834             $recursing = is_early_init($backtrace);
1835         }
1837         $earlymethods = array(
1838             'fatal_error' => 'early_error',
1839             'notification' => 'early_notification',
1840         );
1842         // If lib/outputlib.php has been loaded, call it.
1843         if (!empty($PAGE) && !$recursing) {
1844             if (array_key_exists($method, $earlymethods)) {
1845                 //prevent PAGE->context warnings - exceptions might appear before we set any context
1846                 $PAGE->set_context(null);
1847             }
1848             $PAGE->initialise_theme_and_output();
1849             return call_user_func_array(array($OUTPUT, $method), $arguments);
1850         }
1852         $this->initialising = true;
1854         // Too soon to initialise $OUTPUT, provide a couple of key methods.
1855         if (array_key_exists($method, $earlymethods)) {
1856             return call_user_func_array(array('bootstrap_renderer', $earlymethods[$method]), $arguments);
1857         }
1859         throw new coding_exception('Attempt to start output before enough information is known to initialise the theme.');
1860     }
1862     /**
1863      * Returns nicely formatted error message in a div box.
1864      * @static
1865      * @param string $message error message
1866      * @param string $moreinfourl (ignored in early errors)
1867      * @param string $link (ignored in early errors)
1868      * @param array $backtrace
1869      * @param string $debuginfo
1870      * @return string
1871      */
1872     public static function early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo = null) {
1873         global $CFG;
1875         $content = '<div style="margin-top: 6em; margin-left:auto; margin-right:auto; color:#990000; text-align:center; font-size:large; border-width:1px;
1876 border-color:black; background-color:#ffffee; border-style:solid; border-radius: 20px; border-collapse: collapse;
1877 width: 80%; -moz-border-radius: 20px; padding: 15px">
1878 ' . $message . '
1879 </div>';
1880         // Check whether debug is set.
1881         $debug = (!empty($CFG->debug) && $CFG->debug >= DEBUG_DEVELOPER);
1882         // Also check we have it set in the config file. This occurs if the method to read the config table from the
1883         // database fails, reading from the config table is the first database interaction we have.
1884         $debug = $debug || (!empty($CFG->config_php_settings['debug'])  && $CFG->config_php_settings['debug'] >= DEBUG_DEVELOPER );
1885         if ($debug) {
1886             if (!empty($debuginfo)) {
1887                 $debuginfo = s($debuginfo); // removes all nasty JS
1888                 $debuginfo = str_replace("\n", '<br />', $debuginfo); // keep newlines
1889                 $content .= '<div class="notifytiny">Debug info: ' . $debuginfo . '</div>';
1890             }
1891             if (!empty($backtrace)) {
1892                 $content .= '<div class="notifytiny">Stack trace: ' . format_backtrace($backtrace, false) . '</div>';
1893             }
1894         }
1896         return $content;
1897     }
1899     /**
1900      * This function should only be called by this class, or from exception handlers
1901      * @static
1902      * @param string $message error message
1903      * @param string $moreinfourl (ignored in early errors)
1904      * @param string $link (ignored in early errors)
1905      * @param array $backtrace
1906      * @param string $debuginfo extra information for developers
1907      * @return string
1908      */
1909     public static function early_error($message, $moreinfourl, $link, $backtrace, $debuginfo = null, $errorcode = null) {
1910         global $CFG;
1912         if (CLI_SCRIPT) {
1913             echo "!!! $message !!!\n";
1914             if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1915                 if (!empty($debuginfo)) {
1916                     echo "\nDebug info: $debuginfo";
1917                 }
1918                 if (!empty($backtrace)) {
1919                     echo "\nStack trace: " . format_backtrace($backtrace, true);
1920                 }
1921             }
1922             return;
1924         } else if (AJAX_SCRIPT) {
1925             $e = new stdClass();
1926             $e->error      = $message;
1927             $e->stacktrace = NULL;
1928             $e->debuginfo  = NULL;
1929             if (!empty($CFG->debug) and $CFG->debug >= DEBUG_DEVELOPER) {
1930                 if (!empty($debuginfo)) {
1931                     $e->debuginfo = $debuginfo;
1932                 }
1933                 if (!empty($backtrace)) {
1934                     $e->stacktrace = format_backtrace($backtrace, true);
1935                 }
1936             }
1937             $e->errorcode  = $errorcode;
1938             @header('Content-Type: application/json; charset=utf-8');
1939             echo json_encode($e);
1940             return;
1941         }
1943         // In the name of protocol correctness, monitoring and performance
1944         // profiling, set the appropriate error headers for machine consumption.
1945         $protocol = (isset($_SERVER['SERVER_PROTOCOL']) ? $_SERVER['SERVER_PROTOCOL'] : 'HTTP/1.0');
1946         @header($protocol . ' 503 Service Unavailable');
1948         // better disable any caching
1949         @header('Content-Type: text/html; charset=utf-8');
1950         @header('X-UA-Compatible: IE=edge');
1951         @header('Cache-Control: no-store, no-cache, must-revalidate');
1952         @header('Cache-Control: post-check=0, pre-check=0', false);
1953         @header('Pragma: no-cache');
1954         @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
1955         @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
1957         if (function_exists('get_string')) {
1958             $strerror = get_string('error');
1959         } else {
1960             $strerror = 'Error';
1961         }
1963         $content = self::early_error_content($message, $moreinfourl, $link, $backtrace, $debuginfo);
1965         return self::plain_page($strerror, $content);
1966     }
1968     /**
1969      * Early notification message
1970      * @static
1971      * @param string $message
1972      * @param string $classes usually notifyproblem or notifysuccess
1973      * @return string
1974      */
1975     public static function early_notification($message, $classes = 'notifyproblem') {
1976         return '<div class="' . $classes . '">' . $message . '</div>';
1977     }
1979     /**
1980      * Page should redirect message.
1981      * @static
1982      * @param string $encodedurl redirect url
1983      * @return string
1984      */
1985     public static function plain_redirect_message($encodedurl) {
1986         $message = '<div style="margin-top: 3em; margin-left:auto; margin-right:auto; text-align:center;">' . get_string('pageshouldredirect') . '<br /><a href="'.
1987                 $encodedurl .'">'. get_string('continue') .'</a></div>';
1988         return self::plain_page(get_string('redirect'), $message);
1989     }
1991     /**
1992      * Early redirection page, used before full init of $PAGE global
1993      * @static
1994      * @param string $encodedurl redirect url
1995      * @param string $message redirect message
1996      * @param int $delay time in seconds
1997      * @return string redirect page
1998      */
1999     public static function early_redirect_message($encodedurl, $message, $delay) {
2000         $meta = '<meta http-equiv="refresh" content="'. $delay .'; url='. $encodedurl .'" />';
2001         $content = self::early_error_content($message, null, null, null);
2002         $content .= self::plain_redirect_message($encodedurl);
2004         return self::plain_page(get_string('redirect'), $content, $meta);
2005     }
2007     /**
2008      * Output basic html page.
2009      * @static
2010      * @param string $title page title
2011      * @param string $content page content
2012      * @param string $meta meta tag
2013      * @return string html page
2014      */
2015     public static function plain_page($title, $content, $meta = '') {
2016         if (function_exists('get_string') && function_exists('get_html_lang')) {
2017             $htmllang = get_html_lang();
2018         } else {
2019             $htmllang = '';
2020         }
2022         $footer = '';
2023         if (MDL_PERF_TEST) {
2024             $perfinfo = get_performance_info();
2025             $footer = '<footer>' . $perfinfo['html'] . '</footer>';
2026         }
2028         return '<!DOCTYPE html>
2029 <html ' . $htmllang . '>
2030 <head>
2031 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
2032 '.$meta.'
2033 <title>' . $title . '</title>
2034 </head><body>' . $content . $footer . '</body></html>';
2035     }