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.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.";
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 // 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.';
55 define('NO_OUTPUT_BUFFERING', true);
57 if (isset($_POST['upgradekey'])) {
58 // Before you start reporting issues about the collision attacks against
59 // SHA-1, you should understand that we are not actually attempting to do
60 // any cryptography here. This is hashed purely so that the key is not
61 // that apparent in the address bar itself. Anyone who catches the HTTP
62 // traffic can immediately use it as a valid admin key.
63 header('Location: index.php?cache=0&upgradekeyhash='.sha1($_POST['upgradekey']));
67 if ((isset($_GET['cache']) and $_GET['cache'] === '0')
68 or (isset($_POST['cache']) and $_POST['cache'] === '0')
69 or (!isset($_POST['cache']) and !isset($_GET['cache']) and empty($_GET['sesskey']) and empty($_POST['sesskey']))) {
70 // Prevent caching at all cost when visiting this page directly,
71 // we redirect to self once we known no upgrades are necessary.
72 // Note: $_GET and $_POST are used here intentionally because our param cleaning is not loaded yet.
73 // Note2: the sesskey is present in all block editing hacks, we can not redirect there, so enable caching.
74 define('CACHE_DISABLE_ALL', true);
76 // Force OPcache reset if used, we do not want any stale caches
77 // when detecting if upgrade necessary or when running upgrade.
78 if (function_exists('opcache_reset')) {
87 require('../config.php');
89 // Invalidate the cache of version.php in any circumstances to help core_component
90 // detecting if the version has changed and component cache should be reset.
91 if (function_exists('opcache_invalidate')) {
92 opcache_invalidate($CFG->dirroot
. '/version.php', true);
94 // Make sure the component cache gets rebuilt if necessary, any method that
95 // indirectly calls the protected init() method is good here.
96 core_component
::get_core_subsystems();
98 require_once($CFG->libdir
.'/adminlib.php'); // various admin-only functions
99 require_once($CFG->libdir
.'/upgradelib.php'); // general upgrade/install related functions
101 $confirmupgrade = optional_param('confirmupgrade', 0, PARAM_BOOL
);
102 $confirmrelease = optional_param('confirmrelease', 0, PARAM_BOOL
);
103 $confirmplugins = optional_param('confirmplugincheck', 0, PARAM_BOOL
);
104 $showallplugins = optional_param('showallplugins', 0, PARAM_BOOL
);
105 $agreelicense = optional_param('agreelicense', 0, PARAM_BOOL
);
106 $fetchupdates = optional_param('fetchupdates', 0, PARAM_BOOL
);
107 $newaddonreq = optional_param('installaddonrequest', null, PARAM_RAW
);
108 $upgradekeyhash = optional_param('upgradekeyhash', null, PARAM_ALPHANUM
);
111 $url = new moodle_url('/admin/index.php');
112 $url->param('cache', $cache);
113 if (isset($upgradekeyhash)) {
114 $url->param('upgradekeyhash', $upgradekeyhash);
116 $PAGE->set_url($url);
119 // Are we returning from an add-on installation request at moodle.org/plugins?
120 if ($newaddonreq and !$cache and empty($CFG->disableonclickaddoninstall
)) {
121 $target = new moodle_url('/admin/tool/installaddon/index.php', array(
122 'installaddonrequest' => $newaddonreq,
124 if (!isloggedin() or isguestuser()) {
125 // Login and go the the add-on tool page.
126 $SESSION->wantsurl
= $target->out();
127 redirect(get_login_url());
132 $PAGE->set_pagelayout('admin'); // Set a default pagelayout
134 $documentationlink = '<a href="http://docs.moodle.org/en/Installation">Installation docs</a>';
136 // Check some PHP server settings
138 if (ini_get_bool('session.auto_start')) {
139 print_error('phpvaroff', 'debug', '', (object)array('name'=>'session.auto_start', 'link'=>$documentationlink));
142 if (!ini_get_bool('file_uploads')) {
143 print_error('phpvaron', 'debug', '', (object)array('name'=>'file_uploads', 'link'=>$documentationlink));
146 if (is_float_problem()) {
147 print_error('phpfloatproblem', 'admin', '', $documentationlink);
150 // Set some necessary variables during set-up to avoid PHP warnings later on this page
151 if (!isset($CFG->release
)) {
154 if (!isset($CFG->version
)) {
157 if (!isset($CFG->branch
)) {
164 require("$CFG->dirroot/version.php"); // defines $version, $release, $branch and $maturity
165 $CFG->target_release
= $release; // used during installation and upgrades
167 if (!$version or !$release) {
168 print_error('withoutversion', 'debug'); // without version, stop
171 if (!core_tables_exist()) {
172 $PAGE->set_pagelayout('maintenance');
173 $PAGE->set_popup_notification_allowed(false);
175 // fake some settings
176 $CFG->docroot
= 'http://docs.moodle.org';
178 $strinstallation = get_string('installation', 'install');
180 // remove current session content completely
181 \core\session\manager
::terminate_current();
183 if (empty($agreelicense)) {
184 $strlicense = get_string('license');
186 $PAGE->navbar
->add($strlicense);
187 $PAGE->set_title($strinstallation.' - Moodle '.$CFG->target_release
);
188 $PAGE->set_heading($strinstallation);
189 $PAGE->set_cacheable(false);
191 /** @var core_admin_renderer $output */
192 $output = $PAGE->get_renderer('core', 'admin');
193 echo $output->install_licence_page();
196 if (empty($confirmrelease)) {
197 require_once($CFG->libdir
.'/environmentlib.php');
198 list($envstatus, $environment_results) = check_moodle_environment(normalize_version($release), ENV_SELECT_RELEASE
);
199 $strcurrentrelease = get_string('currentrelease');
201 $PAGE->navbar
->add($strcurrentrelease);
202 $PAGE->set_title($strinstallation);
203 $PAGE->set_heading($strinstallation . ' - Moodle ' . $CFG->target_release
);
204 $PAGE->set_cacheable(false);
206 /** @var core_admin_renderer $output */
207 $output = $PAGE->get_renderer('core', 'admin');
208 echo $output->install_environment_page($maturity, $envstatus, $environment_results, $release);
212 // check plugin dependencies
214 if (!core_plugin_manager
::instance()->all_plugins_ok($version, $failed)) {
215 $PAGE->navbar
->add(get_string('pluginscheck', 'admin'));
216 $PAGE->set_title($strinstallation);
217 $PAGE->set_heading($strinstallation . ' - Moodle ' . $CFG->target_release
);
219 $output = $PAGE->get_renderer('core', 'admin');
220 $url = new moodle_url($PAGE->url
, array('agreelicense' => 1, 'confirmrelease' => 1, 'lang' => $CFG->lang
));
221 echo $output->unsatisfied_dependencies_page($version, $failed, $url);
226 //TODO: add a page with list of non-standard plugins here
228 $strdatabasesetup = get_string('databasesetup');
229 upgrade_init_javascript();
231 $PAGE->navbar
->add($strdatabasesetup);
232 $PAGE->set_title($strinstallation.' - Moodle '.$CFG->target_release
);
233 $PAGE->set_heading($strinstallation);
234 $PAGE->set_cacheable(false);
236 $output = $PAGE->get_renderer('core', 'admin');
237 echo $output->header();
239 if (!$DB->setup_is_unicodedb()) {
240 if (!$DB->change_db_encoding()) {
241 // If could not convert successfully, throw error, and prevent installation
242 print_error('unicoderequired', 'admin');
246 install_core($version, true);
250 // Check version of Moodle code on disk compared with database
251 // and upgrade if possible.
254 // Do not try to do anything fancy in non-cached mode,
255 // this prevents themes from fetching data from non-existent tables.
256 $PAGE->set_pagelayout('maintenance');
257 $PAGE->set_popup_notification_allowed(false);
260 $stradministration = get_string('administration');
261 $PAGE->set_context(context_system
::instance());
263 if (empty($CFG->version
)) {
264 print_error('missingconfigversion', 'debug');
267 // Detect config cache inconsistency, this happens when you switch branches on dev servers.
268 if ($CFG->version
!= $DB->get_field('config', 'value', array('name'=>'version'))) {
270 redirect(new moodle_url($PAGE->url
), 'Config cache inconsistency detected, resetting caches...');
273 if (!$cache and $version > $CFG->version
) { // upgrade
275 check_upgrade_key($upgradekeyhash);
277 // Warning about upgrading a test site.
279 if (defined('BEHAT_SITE_RUNNING')) {
283 // We purge all of MUC's caches here.
284 // Caches are disabled for upgrade by CACHE_DISABLE_ALL so we must set the first arg to true.
285 // This ensures a real config object is loaded and the stores will be purged.
286 // This is the only way we can purge custom caches such as memcache or APC.
287 // Note: all other calls to caches will still used the disabled API.
288 cache_helper
::purge_all(true);
289 // We then purge the regular caches.
292 /** @var core_admin_renderer $output */
293 $output = $PAGE->get_renderer('core', 'admin');
295 if (upgrade_stale_php_files_present()) {
296 $PAGE->set_title($stradministration);
297 $PAGE->set_cacheable(false);
299 echo $output->upgrade_stale_php_files_page();
303 if (empty($confirmupgrade)) {
305 $a->oldversion
= "$CFG->release (".sprintf('%.2f', $CFG->version
).")";
306 $a->newversion
= "$release (".sprintf('%.2f', $version).")";
307 $strdatabasechecking = get_string('databasechecking', '', $a);
309 $PAGE->set_title($stradministration);
310 $PAGE->set_heading($strdatabasechecking);
311 $PAGE->set_cacheable(false);
313 echo $output->upgrade_confirm_page($a->newversion
, $maturity, $testsite);
316 } else if (empty($confirmrelease)){
317 require_once($CFG->libdir
.'/environmentlib.php');
318 list($envstatus, $environment_results) = check_moodle_environment($release, ENV_SELECT_RELEASE
);
319 $strcurrentrelease = get_string('currentrelease');
321 $PAGE->navbar
->add($strcurrentrelease);
322 $PAGE->set_title($strcurrentrelease);
323 $PAGE->set_heading($strcurrentrelease);
324 $PAGE->set_cacheable(false);
326 echo $output->upgrade_environment_page($release, $envstatus, $environment_results);
329 } else if (empty($confirmplugins)) {
330 $strplugincheck = get_string('plugincheck');
332 $PAGE->navbar
->add($strplugincheck);
333 $PAGE->set_title($strplugincheck);
334 $PAGE->set_heading($strplugincheck);
335 $PAGE->set_cacheable(false);
337 $reloadurl = new moodle_url($PAGE->url
, array('confirmupgrade' => 1, 'confirmrelease' => 1, 'cache' => 0));
340 // No sesskey support guaranteed here, because sessions might not work yet.
341 $updateschecker = \core\update\checker
::instance();
342 if ($updateschecker->enabled()) {
343 $updateschecker->fetch();
345 redirect($reloadurl);
348 $deployer = \core\update\deployer
::instance();
349 if ($deployer->enabled()) {
350 $deployer->initialize($reloadurl, $reloadurl);
352 $deploydata = $deployer->submitted_data();
353 if (!empty($deploydata)) {
354 // No sesskey support guaranteed here, because sessions might not work yet.
355 echo $output->upgrade_plugin_confirm_deploy_page($deployer, $deploydata);
360 echo $output->upgrade_plugin_check_page(core_plugin_manager
::instance(), \core\update\checker
::instance(),
361 $version, $showallplugins, $reloadurl, new moodle_url($PAGE->url
, array(
362 'confirmupgrade' => 1, 'confirmrelease' => 1, 'confirmplugincheck' => 1, 'cache' => 0)));
366 // Always verify plugin dependencies!
368 if (!core_plugin_manager
::instance()->all_plugins_ok($version, $failed)) {
369 $reloadurl = new moodle_url($PAGE->url
, array('confirmupgrade' => 1, 'confirmrelease' => 1, 'cache' => 0));
370 echo $output->unsatisfied_dependencies_page($version, $failed, $reloadurl);
375 // Launch main upgrade.
376 upgrade_core($version, true);
378 } else if ($version < $CFG->version
) {
379 // better stop here, we can not continue with plugin upgrades or anything else
380 throw new moodle_exception('downgradedcore', 'error', new moodle_url('/admin/'));
383 // Updated human-readable release version if necessary
384 if (!$cache and $release <> $CFG->release
) { // Update the release version
385 set_config('release', $release);
388 if (!$cache and $branch <> $CFG->branch
) { // Update the branch
389 set_config('branch', $branch);
392 if (!$cache and moodle_needs_upgrading()) {
394 check_upgrade_key($upgradekeyhash);
396 if (!$PAGE->headerprinted
) {
397 // means core upgrade or installation was not already done
399 if (!$confirmplugins) {
400 $strplugincheck = get_string('plugincheck');
402 $PAGE->navbar
->add($strplugincheck);
403 $PAGE->set_title($strplugincheck);
404 $PAGE->set_heading($strplugincheck);
405 $PAGE->set_cacheable(false);
409 $updateschecker = \core\update\checker
::instance();
410 if ($updateschecker->enabled()) {
411 $updateschecker->fetch();
413 redirect($PAGE->url
);
416 /** @var core_admin_renderer $output */
417 $output = $PAGE->get_renderer('core', 'admin');
419 $deployer = \core\update\deployer
::instance();
420 if ($deployer->enabled()) {
421 $deployer->initialize($PAGE->url
, $PAGE->url
);
423 $deploydata = $deployer->submitted_data();
424 if (!empty($deploydata)) {
426 echo $output->upgrade_plugin_confirm_deploy_page($deployer, $deploydata);
431 // Show plugins info.
432 echo $output->upgrade_plugin_check_page(core_plugin_manager
::instance(), \core\update\checker
::instance(),
433 $version, $showallplugins,
434 new moodle_url($PAGE->url
),
435 new moodle_url($PAGE->url
, array('confirmplugincheck' => 1, 'cache' => 0)));
439 // Make sure plugin dependencies are always checked.
441 if (!core_plugin_manager
::instance()->all_plugins_ok($version, $failed)) {
442 /** @var core_admin_renderer $output */
443 $output = $PAGE->get_renderer('core', 'admin');
444 $reloadurl = new moodle_url($PAGE->url
, array('cache' => 0));
445 echo $output->unsatisfied_dependencies_page($version, $failed, $reloadurl);
451 // install/upgrade all plugins and other parts
452 upgrade_noncore(true);
455 // If this is the first install, indicate that this site is fully configured
456 // except the admin password
457 if (during_initial_install()) {
458 set_config('rolesactive', 1); // after this, during_initial_install will return false.
459 set_config('adminsetuppending', 1);
460 // we need this redirect to setup proper session
461 upgrade_finished("index.php?sessionstarted=1&lang=$CFG->lang");
464 // make sure admin user is created - this is the last step because we need
465 // session to be working properly in order to edit admin account
466 if (!empty($CFG->adminsetuppending
)) {
467 $sessionstarted = optional_param('sessionstarted', 0, PARAM_BOOL
);
468 if (!$sessionstarted) {
469 redirect("index.php?sessionstarted=1&lang=$CFG->lang");
471 $sessionverify = optional_param('sessionverify', 0, PARAM_BOOL
);
472 if (!$sessionverify) {
473 $SESSION->sessionverify
= 1;
474 redirect("index.php?sessionstarted=1&sessionverify=1&lang=$CFG->lang");
476 if (empty($SESSION->sessionverify
)) {
477 print_error('installsessionerror', 'admin', "index.php?sessionstarted=1&lang=$CFG->lang");
479 unset($SESSION->sessionverify
);
483 // Cleanup SESSION to make sure other code does not complain in the future.
484 unset($SESSION->has_timed_out
);
485 unset($SESSION->wantsurl
);
487 // 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
488 $adminids = explode(',', $CFG->siteadmins
);
489 $adminuser = get_complete_user_data('id', reset($adminids));
491 if ($adminuser->password
=== 'adminsetuppending') {
492 // prevent installation hijacking
493 if ($adminuser->lastip
!== getremoteaddr()) {
494 print_error('installhijacked', 'admin');
496 // login user and let him set password and admin details
497 $adminuser->newadminuser
= 1;
498 complete_user_login($adminuser);
499 redirect("$CFG->wwwroot/user/editadvanced.php?id=$adminuser->id"); // Edit thyself
502 unset_config('adminsetuppending');
506 // just make sure upgrade logging is properly terminated
507 upgrade_finished('upgradesettings.php');
510 if (has_capability('moodle/site:config', context_system
::instance())) {
513 $updateschecker = \core\update\checker
::instance();
514 if ($updateschecker->enabled()) {
515 $updateschecker->fetch();
517 redirect(new moodle_url('/admin/index.php', array('cache' => 0)));
521 // Now we can be sure everything was upgraded and caches work fine,
522 // redirect if necessary to make sure caching is enabled.
524 redirect(new moodle_url('/admin/index.php', array('cache' => 1)));
527 // Check for valid admin user - no guest autologin
528 require_login(0, false);
530 // Login as real user!
531 $SESSION->wantsurl
= (string)new moodle_url('/admin/index.php');
532 redirect(get_login_url());
534 $context = context_system
::instance();
536 if (!has_capability('moodle/site:config', $context)) {
537 // Do not throw exception display an empty page with administration menu if visible for current user.
538 $PAGE->set_title($SITE->fullname
);
539 $PAGE->set_heading($SITE->fullname
);
540 echo $OUTPUT->header();
541 echo $OUTPUT->footer();
545 // check that site is properly customized
547 if (empty($site->shortname
)) {
548 // probably new installation - lets return to frontpage after this step
549 // remove settings that we want uninitialised
550 unset_config('registerauth');
551 unset_config('timezone'); // Force admin to select timezone!
552 redirect('upgradesettings.php?return=site');
555 // setup critical warnings before printing admin tree block
556 $insecuredataroot = is_dataroot_insecure(true);
557 $SESSION->admin_critical_warning
= ($insecuredataroot==INSECURE_DATAROOT_ERROR
);
559 $adminroot = admin_get_root();
561 // Check if there are any new admin settings which have still yet to be set
562 if (any_new_admin_settings($adminroot)){
563 redirect('upgradesettings.php');
566 // Return to original page that started the plugin uninstallation if necessary.
567 if (isset($SESSION->pluginuninstallreturn
)) {
568 $return = $SESSION->pluginuninstallreturn
;
569 unset($SESSION->pluginuninstallreturn
);
575 // Everything should now be set up, and the user is an admin
577 // Print default admin page with notifications.
578 $errorsdisplayed = defined('WARN_DISPLAY_ERRORS_ENABLED');
580 // We make the assumption that at least one schedule task should run once per day.
581 $lastcron = $DB->get_field_sql('SELECT MAX(lastruntime) FROM {task_scheduled}');
582 $cronoverdue = ($lastcron < time() - 3600 * 24);
583 $dbproblems = $DB->diagnose();
584 $maintenancemode = !empty($CFG->maintenance_enabled
);
586 // Available updates for Moodle core.
587 $updateschecker = \core\update\checker
::instance();
588 $availableupdates = array();
589 $availableupdatesfetch = null;
591 if (empty($CFG->disableupdatenotifications
)) {
592 // Only compute the update information when it is going to be displayed to the user.
593 $availableupdates['core'] = $updateschecker->get_update_info('core',
594 array('minmaturity' => $CFG->updateminmaturity
, 'notifybuilds' => $CFG->updatenotifybuilds
));
596 // Available updates for contributed plugins
597 $pluginman = core_plugin_manager
::instance();
598 foreach ($pluginman->get_plugins() as $plugintype => $plugintypeinstances) {
599 foreach ($plugintypeinstances as $pluginname => $plugininfo) {
600 if (!empty($plugininfo->availableupdates
)) {
601 foreach ($plugininfo->availableupdates
as $pluginavailableupdate) {
602 if ($pluginavailableupdate->version
> $plugininfo->versiondisk
) {
603 if (!isset($availableupdates[$plugintype.'_'.$pluginname])) {
604 $availableupdates[$plugintype.'_'.$pluginname] = array();
606 $availableupdates[$plugintype.'_'.$pluginname][] = $pluginavailableupdate;
613 // The timestamp of the most recent check for available updates
614 $availableupdatesfetch = $updateschecker->get_last_timefetched();
617 $buggyiconvnomb = (!function_exists('mb_convert_encoding') and @iconv
('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
618 //check if the site is registered on Moodle.org
619 $registered = $DB->count_records('registration_hubs', array('huburl' => HUB_MOODLEORGHUBURL
, 'confirmed' => 1));
620 // Check if there are any cache warnings.
621 $cachewarnings = cache_helper
::warnings();
623 admin_externalpage_setup('adminnotifications');
625 /* @var core_admin_renderer $output */
626 $output = $PAGE->get_renderer('core', 'admin');
628 echo $output->admin_notifications_page($maturity, $insecuredataroot, $errorsdisplayed, $cronoverdue, $dbproblems,
629 $maintenancemode, $availableupdates, $availableupdatesfetch, $buggyiconvnomb,
630 $registered, $cachewarnings);