MDL-38466 filters: Redos protection and unit tests
[moodle.git] / admin / index.php
blob8e68e44578cb1404ad1652bf80d20165b529b556
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.
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/>.
18 /**
19 * Main administration script.
21 * @package core
22 * @copyright 1999 onwards Martin Dougiamas (http://dougiamas.com)
23 * @license http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
26 // Check that config.php exists, if not then call the install script
27 if (!file_exists('../config.php')) {
28 header('Location: ../install.php');
29 die();
32 // Check that PHP is of a sufficient version as soon as possible
33 if (version_compare(phpversion(), '5.4.4') < 0) {
34 $phpversion = phpversion();
35 // do NOT localise - lang strings would not work here and we CAN NOT move it to later place
36 echo "Moodle 2.7 or later requires at least PHP 5.4.4 (currently using version $phpversion).<br />";
37 echo "Please upgrade your server software or install older Moodle version.";
38 die();
41 // make sure iconv is available and actually works
42 if (!function_exists('iconv')) {
43 // this should not happen, this must be very borked install
44 echo 'Moodle requires the iconv PHP extension. Please install or enable the iconv extension.';
45 die();
48 // Make sure php5-json is available.
49 if (!function_exists('json_encode') || !function_exists('json_decode')) {
50 // This also shouldn't happen.
51 echo 'Moodle requires the json PHP extension. Please install or enable the json extension.';
52 die();
55 define('NO_OUTPUT_BUFFERING', true);
57 if ((isset($_GET['cache']) and $_GET['cache'] === '0')
58 or (isset($_POST['cache']) and $_POST['cache'] === '0')
59 or (!isset($_POST['cache']) and !isset($_GET['cache']) and empty($_GET['sesskey']) and empty($_POST['sesskey']))) {
60 // Prevent caching at all cost when visiting this page directly,
61 // we redirect to self once we known no upgrades are necessary.
62 // Note: $_GET and $_POST are used here intentionally because our param cleaning is not loaded yet.
63 // Note2: the sesskey is present in all block editing hacks, we can not redirect there, so enable caching.
64 define('CACHE_DISABLE_ALL', true);
66 // Force OPcache reset if used, we do not want any stale caches
67 // when detecting if upgrade necessary or when running upgrade.
68 if (function_exists('opcache_reset')) {
69 opcache_reset();
71 $cache = 0;
73 } else {
74 $cache = 1;
77 require('../config.php');
79 // Invalidate the cache of version.php in any circumstances to help core_component
80 // detecting if the version has changed and component cache should be reset.
81 if (function_exists('opcache_invalidate')) {
82 opcache_invalidate($CFG->dirroot . '/version.php', true);
84 // Make sure the component cache gets rebuilt if necessary, any method that
85 // indirectly calls the protected init() method is good here.
86 core_component::get_core_subsystems();
88 require_once($CFG->libdir.'/adminlib.php'); // various admin-only functions
89 require_once($CFG->libdir.'/upgradelib.php'); // general upgrade/install related functions
91 $id = optional_param('id', '', PARAM_TEXT);
92 $confirmupgrade = optional_param('confirmupgrade', 0, PARAM_BOOL);
93 $confirmrelease = optional_param('confirmrelease', 0, PARAM_BOOL);
94 $confirmplugins = optional_param('confirmplugincheck', 0, PARAM_BOOL);
95 $showallplugins = optional_param('showallplugins', 0, PARAM_BOOL);
96 $agreelicense = optional_param('agreelicense', 0, PARAM_BOOL);
97 $fetchupdates = optional_param('fetchupdates', 0, PARAM_BOOL);
98 $newaddonreq = optional_param('installaddonrequest', null, PARAM_RAW);
100 // Set up PAGE.
101 $url = new moodle_url('/admin/index.php');
102 $url->param('cache', $cache);
103 $PAGE->set_url($url);
104 unset($url);
106 // Are we returning from an add-on installation request at moodle.org/plugins?
107 if ($newaddonreq and !$cache and empty($CFG->disableonclickaddoninstall)) {
108 $target = new moodle_url('/admin/tool/installaddon/index.php', array(
109 'installaddonrequest' => $newaddonreq,
110 'confirm' => 0));
111 if (!isloggedin() or isguestuser()) {
112 // Login and go the the add-on tool page.
113 $SESSION->wantsurl = $target->out();
114 redirect(get_login_url());
116 redirect($target);
119 $PAGE->set_pagelayout('admin'); // Set a default pagelayout
121 $documentationlink = '<a href="http://docs.moodle.org/en/Installation">Installation docs</a>';
123 // Check some PHP server settings
125 if (ini_get_bool('session.auto_start')) {
126 print_error('phpvaroff', 'debug', '', (object)array('name'=>'session.auto_start', 'link'=>$documentationlink));
129 if (!ini_get_bool('file_uploads')) {
130 print_error('phpvaron', 'debug', '', (object)array('name'=>'file_uploads', 'link'=>$documentationlink));
133 if (is_float_problem()) {
134 print_error('phpfloatproblem', 'admin', '', $documentationlink);
137 // Set some necessary variables during set-up to avoid PHP warnings later on this page
138 if (!isset($CFG->release)) {
139 $CFG->release = '';
141 if (!isset($CFG->version)) {
142 $CFG->version = '';
144 if (!isset($CFG->branch)) {
145 $CFG->branch = '';
148 $version = null;
149 $release = null;
150 $branch = null;
151 require("$CFG->dirroot/version.php"); // defines $version, $release, $branch and $maturity
152 $CFG->target_release = $release; // used during installation and upgrades
154 if (!$version or !$release) {
155 print_error('withoutversion', 'debug'); // without version, stop
158 if (!core_tables_exist()) {
159 $PAGE->set_pagelayout('maintenance');
160 $PAGE->set_popup_notification_allowed(false);
162 // fake some settings
163 $CFG->docroot = 'http://docs.moodle.org';
165 $strinstallation = get_string('installation', 'install');
167 // remove current session content completely
168 \core\session\manager::terminate_current();
170 if (empty($agreelicense)) {
171 $strlicense = get_string('license');
173 $PAGE->navbar->add($strlicense);
174 $PAGE->set_title($strinstallation.' - Moodle '.$CFG->target_release);
175 $PAGE->set_heading($strinstallation);
176 $PAGE->set_cacheable(false);
178 /** @var core_admin_renderer $output */
179 $output = $PAGE->get_renderer('core', 'admin');
180 echo $output->install_licence_page();
181 die();
183 if (empty($confirmrelease)) {
184 require_once($CFG->libdir.'/environmentlib.php');
185 list($envstatus, $environment_results) = check_moodle_environment(normalize_version($release), ENV_SELECT_RELEASE);
186 $strcurrentrelease = get_string('currentrelease');
188 $PAGE->navbar->add($strcurrentrelease);
189 $PAGE->set_title($strinstallation);
190 $PAGE->set_heading($strinstallation . ' - Moodle ' . $CFG->target_release);
191 $PAGE->set_cacheable(false);
193 /** @var core_admin_renderer $output */
194 $output = $PAGE->get_renderer('core', 'admin');
195 echo $output->install_environment_page($maturity, $envstatus, $environment_results, $release);
196 die();
199 // check plugin dependencies
200 $failed = array();
201 if (!core_plugin_manager::instance()->all_plugins_ok($version, $failed)) {
202 $PAGE->navbar->add(get_string('pluginscheck', 'admin'));
203 $PAGE->set_title($strinstallation);
204 $PAGE->set_heading($strinstallation . ' - Moodle ' . $CFG->target_release);
206 $output = $PAGE->get_renderer('core', 'admin');
207 $url = new moodle_url('/admin/index.php', array('agreelicense' => 1, 'confirmrelease' => 1, 'lang' => $CFG->lang));
208 echo $output->unsatisfied_dependencies_page($version, $failed, $url);
209 die();
211 unset($failed);
213 //TODO: add a page with list of non-standard plugins here
215 $strdatabasesetup = get_string('databasesetup');
216 upgrade_init_javascript();
218 $PAGE->navbar->add($strdatabasesetup);
219 $PAGE->set_title($strinstallation.' - Moodle '.$CFG->target_release);
220 $PAGE->set_heading($strinstallation);
221 $PAGE->set_cacheable(false);
223 $output = $PAGE->get_renderer('core', 'admin');
224 echo $output->header();
226 if (!$DB->setup_is_unicodedb()) {
227 if (!$DB->change_db_encoding()) {
228 // If could not convert successfully, throw error, and prevent installation
229 print_error('unicoderequired', 'admin');
233 install_core($version, true);
237 // Check version of Moodle code on disk compared with database
238 // and upgrade if possible.
240 if (!$cache) {
241 // Do not try to do anything fancy in non-cached mode,
242 // this prevents themes from fetching data from non-existent tables.
243 $PAGE->set_pagelayout('maintenance');
244 $PAGE->set_popup_notification_allowed(false);
247 $stradministration = get_string('administration');
248 $PAGE->set_context(context_system::instance());
250 if (empty($CFG->version)) {
251 print_error('missingconfigversion', 'debug');
254 // Detect config cache inconsistency, this happens when you switch branches on dev servers.
255 if ($CFG->version != $DB->get_field('config', 'value', array('name'=>'version'))) {
256 purge_all_caches();
257 redirect(new moodle_url('/admin/index.php'), 'Config cache inconsistency detected, resetting caches...');
260 if (!$cache and $version > $CFG->version) { // upgrade
262 // Warning about upgrading a test site.
263 $testsite = false;
264 if (defined('BEHAT_SITE_RUNNING')) {
265 $testsite = 'behat';
268 // We purge all of MUC's caches here.
269 // Caches are disabled for upgrade by CACHE_DISABLE_ALL so we must set the first arg to true.
270 // This ensures a real config object is loaded and the stores will be purged.
271 // This is the only way we can purge custom caches such as memcache or APC.
272 // Note: all other calls to caches will still used the disabled API.
273 cache_helper::purge_all(true);
274 // We then purge the regular caches.
275 purge_all_caches();
277 /** @var core_admin_renderer $output */
278 $output = $PAGE->get_renderer('core', 'admin');
280 if (upgrade_stale_php_files_present()) {
281 $PAGE->set_title($stradministration);
282 $PAGE->set_cacheable(false);
284 echo $output->upgrade_stale_php_files_page();
285 die();
288 if (empty($confirmupgrade)) {
289 $a = new stdClass();
290 $a->oldversion = "$CFG->release (".sprintf('%.2f', $CFG->version).")";
291 $a->newversion = "$release (".sprintf('%.2f', $version).")";
292 $strdatabasechecking = get_string('databasechecking', '', $a);
294 $PAGE->set_title($stradministration);
295 $PAGE->set_heading($strdatabasechecking);
296 $PAGE->set_cacheable(false);
298 echo $output->upgrade_confirm_page($a->newversion, $maturity, $testsite);
299 die();
301 } else if (empty($confirmrelease)){
302 require_once($CFG->libdir.'/environmentlib.php');
303 list($envstatus, $environment_results) = check_moodle_environment($release, ENV_SELECT_RELEASE);
304 $strcurrentrelease = get_string('currentrelease');
306 $PAGE->navbar->add($strcurrentrelease);
307 $PAGE->set_title($strcurrentrelease);
308 $PAGE->set_heading($strcurrentrelease);
309 $PAGE->set_cacheable(false);
311 echo $output->upgrade_environment_page($release, $envstatus, $environment_results);
312 die();
314 } else if (empty($confirmplugins)) {
315 $strplugincheck = get_string('plugincheck');
317 $PAGE->navbar->add($strplugincheck);
318 $PAGE->set_title($strplugincheck);
319 $PAGE->set_heading($strplugincheck);
320 $PAGE->set_cacheable(false);
322 $reloadurl = new moodle_url('/admin/index.php', array('confirmupgrade' => 1, 'confirmrelease' => 1, 'cache' => 0));
324 if ($fetchupdates) {
325 // No sesskey support guaranteed here, because sessions might not work yet.
326 $updateschecker = \core\update\checker::instance();
327 if ($updateschecker->enabled()) {
328 $updateschecker->fetch();
330 redirect($reloadurl);
333 $deployer = \core\update\deployer::instance();
334 if ($deployer->enabled()) {
335 $deployer->initialize($reloadurl, $reloadurl);
337 $deploydata = $deployer->submitted_data();
338 if (!empty($deploydata)) {
339 // No sesskey support guaranteed here, because sessions might not work yet.
340 echo $output->upgrade_plugin_confirm_deploy_page($deployer, $deploydata);
341 die();
345 echo $output->upgrade_plugin_check_page(core_plugin_manager::instance(), \core\update\checker::instance(),
346 $version, $showallplugins, $reloadurl,
347 new moodle_url('/admin/index.php', array('confirmupgrade'=>1, 'confirmrelease'=>1, 'confirmplugincheck'=>1, 'cache'=>0)));
348 die();
350 } else {
351 // Always verify plugin dependencies!
352 $failed = array();
353 if (!core_plugin_manager::instance()->all_plugins_ok($version, $failed)) {
354 $reloadurl = new moodle_url('/admin/index.php', array('confirmupgrade' => 1, 'confirmrelease' => 1, 'cache' => 0));
355 echo $output->unsatisfied_dependencies_page($version, $failed, $reloadurl);
356 die();
358 unset($failed);
360 // Launch main upgrade.
361 upgrade_core($version, true);
363 } else if ($version < $CFG->version) {
364 // better stop here, we can not continue with plugin upgrades or anything else
365 throw new moodle_exception('downgradedcore', 'error', new moodle_url('/admin/'));
368 // Updated human-readable release version if necessary
369 if (!$cache and $release <> $CFG->release) { // Update the release version
370 set_config('release', $release);
373 if (!$cache and $branch <> $CFG->branch) { // Update the branch
374 set_config('branch', $branch);
377 if (!$cache and moodle_needs_upgrading()) {
378 if (!$PAGE->headerprinted) {
379 // means core upgrade or installation was not already done
381 if (!$confirmplugins) {
382 $strplugincheck = get_string('plugincheck');
384 $PAGE->navbar->add($strplugincheck);
385 $PAGE->set_title($strplugincheck);
386 $PAGE->set_heading($strplugincheck);
387 $PAGE->set_cacheable(false);
389 if ($fetchupdates) {
390 require_sesskey();
391 $updateschecker = \core\update\checker::instance();
392 if ($updateschecker->enabled()) {
393 $updateschecker->fetch();
395 redirect($PAGE->url);
398 /** @var core_admin_renderer $output */
399 $output = $PAGE->get_renderer('core', 'admin');
401 $deployer = \core\update\deployer::instance();
402 if ($deployer->enabled()) {
403 $deployer->initialize($PAGE->url, $PAGE->url);
405 $deploydata = $deployer->submitted_data();
406 if (!empty($deploydata)) {
407 require_sesskey();
408 echo $output->upgrade_plugin_confirm_deploy_page($deployer, $deploydata);
409 die();
413 // Show plugins info.
414 echo $output->upgrade_plugin_check_page(core_plugin_manager::instance(), \core\update\checker::instance(),
415 $version, $showallplugins,
416 new moodle_url($PAGE->url),
417 new moodle_url('/admin/index.php', array('confirmplugincheck'=>1, 'cache'=>0)));
418 die();
421 // Make sure plugin dependencies are always checked.
422 $failed = array();
423 if (!core_plugin_manager::instance()->all_plugins_ok($version, $failed)) {
424 /** @var core_admin_renderer $output */
425 $output = $PAGE->get_renderer('core', 'admin');
426 $reloadurl = new moodle_url('/admin/index.php', array('cache' => 0));
427 echo $output->unsatisfied_dependencies_page($version, $failed, $reloadurl);
428 die();
430 unset($failed);
433 // install/upgrade all plugins and other parts
434 upgrade_noncore(true);
437 // If this is the first install, indicate that this site is fully configured
438 // except the admin password
439 if (during_initial_install()) {
440 set_config('rolesactive', 1); // after this, during_initial_install will return false.
441 set_config('adminsetuppending', 1);
442 // we need this redirect to setup proper session
443 upgrade_finished("index.php?sessionstarted=1&amp;lang=$CFG->lang");
446 // make sure admin user is created - this is the last step because we need
447 // session to be working properly in order to edit admin account
448 if (!empty($CFG->adminsetuppending)) {
449 $sessionstarted = optional_param('sessionstarted', 0, PARAM_BOOL);
450 if (!$sessionstarted) {
451 redirect("index.php?sessionstarted=1&lang=$CFG->lang");
452 } else {
453 $sessionverify = optional_param('sessionverify', 0, PARAM_BOOL);
454 if (!$sessionverify) {
455 $SESSION->sessionverify = 1;
456 redirect("index.php?sessionstarted=1&sessionverify=1&lang=$CFG->lang");
457 } else {
458 if (empty($SESSION->sessionverify)) {
459 print_error('installsessionerror', 'admin', "index.php?sessionstarted=1&lang=$CFG->lang");
461 unset($SESSION->sessionverify);
465 // Cleanup SESSION to make sure other code does not complain in the future.
466 unset($SESSION->has_timed_out);
467 unset($SESSION->wantsurl);
469 // at this stage there can be only one admin unless more were added by install - users may change username, so do not rely on that
470 $adminids = explode(',', $CFG->siteadmins);
471 $adminuser = get_complete_user_data('id', reset($adminids));
473 if ($adminuser->password === 'adminsetuppending') {
474 // prevent installation hijacking
475 if ($adminuser->lastip !== getremoteaddr()) {
476 print_error('installhijacked', 'admin');
478 // login user and let him set password and admin details
479 $adminuser->newadminuser = 1;
480 complete_user_login($adminuser);
481 redirect("$CFG->wwwroot/user/editadvanced.php?id=$adminuser->id"); // Edit thyself
483 } else {
484 unset_config('adminsetuppending');
487 } else {
488 // just make sure upgrade logging is properly terminated
489 upgrade_finished('upgradesettings.php');
492 if (has_capability('moodle/site:config', context_system::instance())) {
493 if ($fetchupdates) {
494 require_sesskey();
495 $updateschecker = \core\update\checker::instance();
496 if ($updateschecker->enabled()) {
497 $updateschecker->fetch();
499 redirect(new moodle_url('/admin/index.php', array('cache' => 0)));
503 // Now we can be sure everything was upgraded and caches work fine,
504 // redirect if necessary to make sure caching is enabled.
505 if (!$cache) {
506 redirect(new moodle_url('/admin/index.php', array('cache' => 1)));
509 // Check for valid admin user - no guest autologin
510 require_login(0, false);
511 if (isguestuser()) {
512 // Login as real user!
513 $SESSION->wantsurl = (string)new moodle_url('/admin/index.php');
514 redirect(get_login_url());
516 $context = context_system::instance();
517 require_capability('moodle/site:config', $context);
519 // check that site is properly customized
520 $site = get_site();
521 if (empty($site->shortname)) {
522 // probably new installation - lets return to frontpage after this step
523 // remove settings that we want uninitialised
524 unset_config('registerauth');
525 redirect('upgradesettings.php?return=site');
528 // Check if we are returning from moodle.org registration and if so, we mark that fact to remove reminders
529 if (!empty($id) and $id == $CFG->siteidentifier) {
530 set_config('registered', time());
533 // setup critical warnings before printing admin tree block
534 $insecuredataroot = is_dataroot_insecure(true);
535 $SESSION->admin_critical_warning = ($insecuredataroot==INSECURE_DATAROOT_ERROR);
537 $adminroot = admin_get_root();
539 // Check if there are any new admin settings which have still yet to be set
540 if (any_new_admin_settings($adminroot)){
541 redirect('upgradesettings.php');
544 // Return to original page that started the plugin uninstallation if necessary.
545 if (isset($SESSION->pluginuninstallreturn)) {
546 $return = $SESSION->pluginuninstallreturn;
547 unset($SESSION->pluginuninstallreturn);
548 if ($return) {
549 redirect($return);
553 // Everything should now be set up, and the user is an admin
555 // Print default admin page with notifications.
556 $errorsdisplayed = defined('WARN_DISPLAY_ERRORS_ENABLED');
558 // We make the assumption that at least one schedule task should run once per day.
559 $lastcron = $DB->get_field_sql('SELECT MAX(lastruntime) FROM {task_scheduled}');
560 $cronoverdue = ($lastcron < time() - 3600 * 24);
561 $dbproblems = $DB->diagnose();
562 $maintenancemode = !empty($CFG->maintenance_enabled);
564 // Available updates for Moodle core
565 $updateschecker = \core\update\checker::instance();
566 $availableupdates = array();
567 $availableupdates['core'] = $updateschecker->get_update_info('core',
568 array('minmaturity' => $CFG->updateminmaturity, 'notifybuilds' => $CFG->updatenotifybuilds));
570 // Available updates for contributed plugins
571 $pluginman = core_plugin_manager::instance();
572 foreach ($pluginman->get_plugins() as $plugintype => $plugintypeinstances) {
573 foreach ($plugintypeinstances as $pluginname => $plugininfo) {
574 if (!empty($plugininfo->availableupdates)) {
575 foreach ($plugininfo->availableupdates as $pluginavailableupdate) {
576 if ($pluginavailableupdate->version > $plugininfo->versiondisk) {
577 if (!isset($availableupdates[$plugintype.'_'.$pluginname])) {
578 $availableupdates[$plugintype.'_'.$pluginname] = array();
580 $availableupdates[$plugintype.'_'.$pluginname][] = $pluginavailableupdate;
587 // The timestamp of the most recent check for available updates
588 $availableupdatesfetch = $updateschecker->get_last_timefetched();
590 $buggyiconvnomb = (!function_exists('mb_convert_encoding') and @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
591 //check if the site is registered on Moodle.org
592 $registered = $DB->count_records('registration_hubs', array('huburl' => HUB_MOODLEORGHUBURL, 'confirmed' => 1));
593 // Check if there are any cache warnings.
594 $cachewarnings = cache_helper::warnings();
596 admin_externalpage_setup('adminnotifications');
598 /* @var core_admin_renderer $output */
599 $output = $PAGE->get_renderer('core', 'admin');
601 echo $output->admin_notifications_page($maturity, $insecuredataroot, $errorsdisplayed, $cronoverdue, $dbproblems,
602 $maintenancemode, $availableupdates, $availableupdatesfetch, $buggyiconvnomb,
603 $registered, $cachewarnings);