3 // This file is part of Moodle - http://moodle.org/
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.
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/>.
19 * Main administration script.
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');
32 // Check that PHP is of a sufficient version as soon as possible
33 if (version_compare(phpversion(), '5.3.3') < 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.5 or later requires at least PHP 5.3.3 (currently using version $phpversion).<br />";
37 echo "Please upgrade your server software or install older Moodle version.";
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.';
48 define('NO_OUTPUT_BUFFERING', true);
50 if ((isset($_GET['cache']) and $_GET['cache'] === '0')
51 or (isset($_POST['cache']) and $_POST['cache'] === '0')
52 or (!isset($_POST['cache']) and !isset($_GET['cache']) and empty($_GET['sesskey']) and empty($_POST['sesskey']))) {
53 // Prevent caching at all cost when visiting this page directly,
54 // we redirect to self once we known no upgrades are necessary.
55 // Note: $_GET and $_POST are used here intentionally because our param cleaning is not loaded yet.
56 // Note2: the sesskey is present in all block editing hacks, we can not redirect there, so enable caching.
57 define('CACHE_DISABLE_ALL', true);
59 // Force OPcache reset if used, we do not want any stale caches
60 // when detecting if upgrade necessary or when running upgrade.
61 if (function_exists('opcache_reset')) {
70 require('../config.php');
72 // Invalidate the cache of version.php in any circumstances to help core_component
73 // detecting if the version has changed and component cache should be reset.
74 if (function_exists('opcache_invalidate')) {
75 opcache_invalidate($CFG->dirroot . '/version.php', true);
77 // Make sure the component cache gets rebuilt if necessary, any method that
78 // indirectly calls the protected init() method is good here.
79 core_component::get_core_subsystems();
81 require_once($CFG->libdir.'/adminlib.php'); // various admin-only functions
82 require_once($CFG->libdir.'/upgradelib.php'); // general upgrade/install related functions
84 $id = optional_param('id', '', PARAM_TEXT);
85 $confirmupgrade = optional_param('confirmupgrade', 0, PARAM_BOOL);
86 $confirmrelease = optional_param('confirmrelease', 0, PARAM_BOOL);
87 $confirmplugins = optional_param('confirmplugincheck', 0, PARAM_BOOL);
88 $showallplugins = optional_param('showallplugins', 0, PARAM_BOOL);
89 $agreelicense = optional_param('agreelicense', 0, PARAM_BOOL);
90 $fetchupdates = optional_param('fetchupdates', 0, PARAM_BOOL);
91 $newaddonreq = optional_param('installaddonrequest', null, PARAM_RAW);
94 $url = new moodle_url('/admin/index.php');
95 $url->param('cache', $cache);
99 // Are we returning from an add-on installation request at moodle.org/plugins?
100 if ($newaddonreq and !$cache and empty($CFG->disableonclickaddoninstall)) {
101 $target = new moodle_url('/admin/tool/installaddon/index.php', array(
102 'installaddonrequest' => $newaddonreq,
104 if (!isloggedin() or isguestuser()) {
105 // Login and go the the add-on tool page.
106 $SESSION->wantsurl = $target->out();
107 redirect(get_login_url());
112 $PAGE->set_pagelayout('admin'); // Set a default pagelayout
114 $documentationlink = '<a href="http://docs.moodle.org/en/Installation">Installation docs</a>';
116 // Check some PHP server settings
118 if (ini_get_bool('session.auto_start')) {
119 print_error('phpvaroff', 'debug', '', (object)array('name'=>'session.auto_start', 'link'=>$documentationlink));
122 if (ini_get_bool('magic_quotes_runtime')) {
123 print_error('phpvaroff', 'debug', '', (object)array('name'=>'magic_quotes_runtime', 'link'=>$documentationlink));
126 if (!ini_get_bool('file_uploads')) {
127 print_error('phpvaron', 'debug', '', (object)array('name'=>'file_uploads', 'link'=>$documentationlink));
130 if (is_float_problem()) {
131 print_error('phpfloatproblem', 'admin', '', $documentationlink);
134 // Set some necessary variables during set-up to avoid PHP warnings later on this page
135 if (!isset($CFG->release)) {
138 if (!isset($CFG->version)) {
141 if (!isset($CFG->branch)) {
148 require("$CFG->dirroot/version.php"); // defines $version, $release, $branch and $maturity
149 $CFG->target_release = $release; // used during installation and upgrades
151 if (!$version or !$release) {
152 print_error('withoutversion', 'debug'); // without version, stop
155 if (!core_tables_exist()) {
156 $PAGE->set_pagelayout('maintenance');
157 $PAGE->set_popup_notification_allowed(false);
159 // fake some settings
160 $CFG->docroot = 'http://docs.moodle.org';
162 $strinstallation = get_string('installation', 'install');
164 // remove current session content completely
165 \core\session\manager::terminate_current();
167 if (empty($agreelicense)) {
168 $strlicense = get_string('license');
170 $PAGE->navbar->add($strlicense);
171 $PAGE->set_title($strinstallation.' - Moodle '.$CFG->target_release);
172 $PAGE->set_heading($strinstallation);
173 $PAGE->set_cacheable(false);
175 /** @var core_admin_renderer $output */
176 $output = $PAGE->get_renderer('core', 'admin');
177 echo $output->install_licence_page();
180 if (empty($confirmrelease)) {
181 require_once($CFG->libdir.'/environmentlib.php');
182 list($envstatus, $environment_results) = check_moodle_environment(normalize_version($release), ENV_SELECT_RELEASE);
183 $strcurrentrelease = get_string('currentrelease');
185 $PAGE->navbar->add($strcurrentrelease);
186 $PAGE->set_title($strinstallation);
187 $PAGE->set_heading($strinstallation . ' - Moodle ' . $CFG->target_release);
188 $PAGE->set_cacheable(false);
190 /** @var core_admin_renderer $output */
191 $output = $PAGE->get_renderer('core', 'admin');
192 echo $output->install_environment_page($maturity, $envstatus, $environment_results, $release);
196 // check plugin dependencies
198 if (!core_plugin_manager::instance()->all_plugins_ok($version, $failed)) {
199 $PAGE->navbar->add(get_string('pluginscheck', 'admin'));
200 $PAGE->set_title($strinstallation);
201 $PAGE->set_heading($strinstallation . ' - Moodle ' . $CFG->target_release);
203 $output = $PAGE->get_renderer('core', 'admin');
204 $url = new moodle_url('/admin/index.php', array('agreelicense' => 1, 'confirmrelease' => 1, 'lang' => $CFG->lang));
205 echo $output->unsatisfied_dependencies_page($version, $failed, $url);
210 //TODO: add a page with list of non-standard plugins here
212 $strdatabasesetup = get_string('databasesetup');
213 upgrade_init_javascript();
215 $PAGE->navbar->add($strdatabasesetup);
216 $PAGE->set_title($strinstallation.' - Moodle '.$CFG->target_release);
217 $PAGE->set_heading($strinstallation);
218 $PAGE->set_cacheable(false);
220 $output = $PAGE->get_renderer('core', 'admin');
221 echo $output->header();
223 if (!$DB->setup_is_unicodedb()) {
224 if (!$DB->change_db_encoding()) {
225 // If could not convert successfully, throw error, and prevent installation
226 print_error('unicoderequired', 'admin');
230 install_core($version, true);
234 // Check version of Moodle code on disk compared with database
235 // and upgrade if possible.
237 $stradministration = get_string('administration');
238 $PAGE->set_context(context_system::instance());
240 if (empty($CFG->version)) {
241 print_error('missingconfigversion', 'debug');
244 // Detect config cache inconsistency, this happens when you switch branches on dev servers.
245 if ($CFG->version != $DB->get_field('config', 'value', array('name'=>'version'))) {
247 redirect(new moodle_url('/admin/index.php'), 'Config cache inconsistency detected, resetting caches...');
250 if (!$cache and $version > $CFG->version) { // upgrade
252 // Warning about upgrading a test site.
254 if (defined('BEHAT_SITE_RUNNING')) {
258 // We purge all of MUC's caches here.
259 // Caches are disabled for upgrade by CACHE_DISABLE_ALL so we must set the first arg to true.
260 // This ensures a real config object is loaded and the stores will be purged.
261 // This is the only way we can purge custom caches such as memcache or APC.
262 // Note: all other calls to caches will still used the disabled API.
263 cache_helper::purge_all(true);
264 // We then purge the regular caches.
267 $PAGE->set_pagelayout('maintenance');
268 $PAGE->set_popup_notification_allowed(false);
270 /** @var core_admin_renderer $output */
271 $output = $PAGE->get_renderer('core', 'admin');
273 if (upgrade_stale_php_files_present()) {
274 $PAGE->set_title($stradministration);
275 $PAGE->set_cacheable(false);
277 echo $output->upgrade_stale_php_files_page();
281 if (empty($confirmupgrade)) {
283 $a->oldversion = "$CFG->release (".sprintf('%.2f', $CFG->version).")";
284 $a->newversion = "$release (".sprintf('%.2f', $version).")";
285 $strdatabasechecking = get_string('databasechecking', '', $a);
287 $PAGE->set_title($stradministration);
288 $PAGE->set_heading($strdatabasechecking);
289 $PAGE->set_cacheable(false);
291 echo $output->upgrade_confirm_page($a->newversion, $maturity, $testsite);
294 } else if (empty($confirmrelease)){
295 require_once($CFG->libdir.'/environmentlib.php');
296 list($envstatus, $environment_results) = check_moodle_environment($release, ENV_SELECT_RELEASE);
297 $strcurrentrelease = get_string('currentrelease');
299 $PAGE->navbar->add($strcurrentrelease);
300 $PAGE->set_title($strcurrentrelease);
301 $PAGE->set_heading($strcurrentrelease);
302 $PAGE->set_cacheable(false);
304 echo $output->upgrade_environment_page($release, $envstatus, $environment_results);
307 } else if (empty($confirmplugins)) {
308 $strplugincheck = get_string('plugincheck');
310 $PAGE->navbar->add($strplugincheck);
311 $PAGE->set_title($strplugincheck);
312 $PAGE->set_heading($strplugincheck);
313 $PAGE->set_cacheable(false);
315 $reloadurl = new moodle_url('/admin/index.php', array('confirmupgrade' => 1, 'confirmrelease' => 1, 'cache' => 0));
318 // No sesskey support guaranteed here, because sessions might not work yet.
319 $updateschecker = \core\update\checker::instance();
320 if ($updateschecker->enabled()) {
321 $updateschecker->fetch();
323 redirect($reloadurl);
326 $deployer = \core\update\deployer::instance();
327 if ($deployer->enabled()) {
328 $deployer->initialize($reloadurl, $reloadurl);
330 $deploydata = $deployer->submitted_data();
331 if (!empty($deploydata)) {
332 // No sesskey support guaranteed here, because sessions might not work yet.
333 echo $output->upgrade_plugin_confirm_deploy_page($deployer, $deploydata);
338 echo $output->upgrade_plugin_check_page(core_plugin_manager::instance(), \core\update\checker::instance(),
339 $version, $showallplugins, $reloadurl,
340 new moodle_url('/admin/index.php', array('confirmupgrade'=>1, 'confirmrelease'=>1, 'confirmplugincheck'=>1, 'cache'=>0)));
344 // Always verify plugin dependencies!
346 if (!core_plugin_manager::instance()->all_plugins_ok($version, $failed)) {
347 $PAGE->set_pagelayout('maintenance');
348 $PAGE->set_popup_notification_allowed(false);
349 $reloadurl = new moodle_url('/admin/index.php', array('confirmupgrade' => 1, 'confirmrelease' => 1, 'cache' => 0));
350 echo $output->unsatisfied_dependencies_page($version, $failed, $reloadurl);
355 // Launch main upgrade.
356 upgrade_core($version, true);
358 } else if ($version < $CFG->version) {
359 // better stop here, we can not continue with plugin upgrades or anything else
360 throw new moodle_exception('downgradedcore', 'error', new moodle_url('/admin/'));
363 // Updated human-readable release version if necessary
364 if (!$cache and $release <> $CFG->release) { // Update the release version
365 set_config('release', $release);
368 if (!$cache and $branch <> $CFG->branch) { // Update the branch
369 set_config('branch', $branch);
372 if (!$cache and moodle_needs_upgrading()) {
373 if (!$PAGE->headerprinted) {
374 // means core upgrade or installation was not already done
376 /** @var core_admin_renderer $output */
377 $output = $PAGE->get_renderer('core', 'admin');
379 if (!$confirmplugins) {
380 $strplugincheck = get_string('plugincheck');
382 $PAGE->set_pagelayout('maintenance');
383 $PAGE->set_popup_notification_allowed(false);
384 $PAGE->navbar->add($strplugincheck);
385 $PAGE->set_title($strplugincheck);
386 $PAGE->set_heading($strplugincheck);
387 $PAGE->set_cacheable(false);
391 $updateschecker = \core\update\checker::instance();
392 if ($updateschecker->enabled()) {
393 $updateschecker->fetch();
395 redirect($PAGE->url);
398 $deployer = \core\update\deployer::instance();
399 if ($deployer->enabled()) {
400 $deployer->initialize($PAGE->url, $PAGE->url);
402 $deploydata = $deployer->submitted_data();
403 if (!empty($deploydata)) {
405 echo $output->upgrade_plugin_confirm_deploy_page($deployer, $deploydata);
410 // Show plugins info.
411 echo $output->upgrade_plugin_check_page(core_plugin_manager::instance(), \core\update\checker::instance(),
412 $version, $showallplugins,
413 new moodle_url($PAGE->url),
414 new moodle_url('/admin/index.php', array('confirmplugincheck'=>1, 'cache'=>0)));
418 // Make sure plugin dependencies are always checked.
420 if (!core_plugin_manager::instance()->all_plugins_ok($version, $failed)) {
421 $PAGE->set_pagelayout('maintenance');
422 $PAGE->set_popup_notification_allowed(false);
423 $reloadurl = new moodle_url('/admin/index.php', array('cache' => 0));
424 echo $output->unsatisfied_dependencies_page($version, $failed, $reloadurl);
430 // install/upgrade all plugins and other parts
431 upgrade_noncore(true);
434 // If this is the first install, indicate that this site is fully configured
435 // except the admin password
436 if (during_initial_install()) {
437 set_config('rolesactive', 1); // after this, during_initial_install will return false.
438 set_config('adminsetuppending', 1);
439 // we need this redirect to setup proper session
440 upgrade_finished("index.php?sessionstarted=1&lang=$CFG->lang");
443 // make sure admin user is created - this is the last step because we need
444 // session to be working properly in order to edit admin account
445 if (!empty($CFG->adminsetuppending)) {
446 $sessionstarted = optional_param('sessionstarted', 0, PARAM_BOOL);
447 if (!$sessionstarted) {
448 redirect("index.php?sessionstarted=1&lang=$CFG->lang");
450 $sessionverify = optional_param('sessionverify', 0, PARAM_BOOL);
451 if (!$sessionverify) {
452 $SESSION->sessionverify = 1;
453 redirect("index.php?sessionstarted=1&sessionverify=1&lang=$CFG->lang");
455 if (empty($SESSION->sessionverify)) {
456 print_error('installsessionerror', 'admin', "index.php?sessionstarted=1&lang=$CFG->lang");
458 unset($SESSION->sessionverify);
462 // Cleanup SESSION to make sure other code does not complain in the future.
463 unset($SESSION->has_timed_out);
464 unset($SESSION->wantsurl);
466 // 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
467 $adminids = explode(',', $CFG->siteadmins);
468 $adminuser = get_complete_user_data('id', reset($adminids));
470 if ($adminuser->password === 'adminsetuppending') {
471 // prevent installation hijacking
472 if ($adminuser->lastip !== getremoteaddr()) {
473 print_error('installhijacked', 'admin');
475 // login user and let him set password and admin details
476 $adminuser->newadminuser = 1;
477 complete_user_login($adminuser);
478 redirect("$CFG->wwwroot/user/editadvanced.php?id=$adminuser->id"); // Edit thyself
481 unset_config('adminsetuppending');
485 // just make sure upgrade logging is properly terminated
486 upgrade_finished('upgradesettings.php');
489 if (has_capability('moodle/site:config', context_system::instance())) {
492 $updateschecker = \core\update\checker::instance();
493 if ($updateschecker->enabled()) {
494 $updateschecker->fetch();
496 redirect(new moodle_url('/admin/index.php', array('cache' => 0)));
500 // Now we can be sure everything was upgraded and caches work fine,
501 // redirect if necessary to make sure caching is enabled.
503 redirect(new moodle_url('/admin/index.php', array('cache' => 1)));
506 // Check for valid admin user - no guest autologin
507 require_login(0, false);
508 $context = context_system::instance();
509 require_capability('moodle/site:config', $context);
511 // check that site is properly customized
513 if (empty($site->shortname)) {
514 // probably new installation - lets return to frontpage after this step
515 // remove settings that we want uninitialised
516 unset_config('registerauth');
517 redirect('upgradesettings.php?return=site');
520 // Check if we are returning from moodle.org registration and if so, we mark that fact to remove reminders
521 if (!empty($id) and $id == $CFG->siteidentifier) {
522 set_config('registered', time());
525 // setup critical warnings before printing admin tree block
526 $insecuredataroot = is_dataroot_insecure(true);
527 $SESSION->admin_critical_warning = ($insecuredataroot==INSECURE_DATAROOT_ERROR);
529 $adminroot = admin_get_root();
531 // Check if there are any new admin settings which have still yet to be set
532 if (any_new_admin_settings($adminroot)){
533 redirect('upgradesettings.php');
536 // Return to original page that started the plugin uninstallation if necessary.
537 if (isset($SESSION->pluginuninstallreturn)) {
538 $return = $SESSION->pluginuninstallreturn;
539 unset($SESSION->pluginuninstallreturn);
545 // Everything should now be set up, and the user is an admin
547 // Print default admin page with notifications.
548 $errorsdisplayed = defined('WARN_DISPLAY_ERRORS_ENABLED');
550 $lastcron = $DB->get_field_sql('SELECT MAX(lastcron) FROM {modules}');
551 $cronoverdue = ($lastcron < time() - 3600 * 24);
552 $dbproblems = $DB->diagnose();
553 $maintenancemode = !empty($CFG->maintenance_enabled);
555 // Available updates for Moodle core
556 $updateschecker = \core\update\checker::instance();
557 $availableupdates = array();
558 $availableupdates['core'] = $updateschecker->get_update_info('core',
559 array('minmaturity' => $CFG->updateminmaturity, 'notifybuilds' => $CFG->updatenotifybuilds));
561 // Available updates for contributed plugins
562 $pluginman = core_plugin_manager::instance();
563 foreach ($pluginman->get_plugins() as $plugintype => $plugintypeinstances) {
564 foreach ($plugintypeinstances as $pluginname => $plugininfo) {
565 if (!empty($plugininfo->availableupdates)) {
566 foreach ($plugininfo->availableupdates as $pluginavailableupdate) {
567 if ($pluginavailableupdate->version > $plugininfo->versiondisk) {
568 if (!isset($availableupdates[$plugintype.'_'.$pluginname])) {
569 $availableupdates[$plugintype.'_'.$pluginname] = array();
571 $availableupdates[$plugintype.'_'.$pluginname][] = $pluginavailableupdate;
578 // The timestamp of the most recent check for available updates
579 $availableupdatesfetch = $updateschecker->get_last_timefetched();
581 $buggyiconvnomb = (!function_exists('mb_convert_encoding') and @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
582 //check if the site is registered on Moodle.org
583 $registered = $DB->count_records('registration_hubs', array('huburl' => HUB_MOODLEORGHUBURL, 'confirmed' => 1));
585 admin_externalpage_setup('adminnotifications');
587 $output = $PAGE->get_renderer('core', 'admin');
588 echo $output->admin_notifications_page($maturity, $insecuredataroot, $errorsdisplayed,
589 $cronoverdue, $dbproblems, $maintenancemode, $availableupdates, $availableupdatesfetch, $buggyiconvnomb,