Search moodle.org's
Developer Documentation

See Release Notes
Long Term Support Release

  • Bug fixes for general core bugs in 4.1.x will end 13 November 2023 (12 months).
  • Bug fixes for security issues in 4.1.x will end 10 November 2025 (36 months).
  • PHP version: minimum PHP 7.4.0 Note: minimum PHP version has increased since Moodle 4.0. PHP 8.0.x is supported too.
/admin/ -> index.php (source)

Differences Between: [Versions 310 and 401] [Versions 311 and 401] [Versions 39 and 401] [Versions 400 and 401] [Versions 401 and 402] [Versions 401 and 403]

   1  <?php
   2  
   3  // This file is part of Moodle - http://moodle.org/
   4  //
   5  // Moodle is free software: you can redistribute it and/or modify
   6  // it under the terms of the GNU General Public License as published by
   7  // the Free Software Foundation, either version 3 of the License, or
   8  // (at your option) any later version.
   9  //
  10  // Moodle is distributed in the hope that it will be useful,
  11  // but WITHOUT ANY WARRANTY; without even the implied warranty of
  12  // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  13  // GNU General Public License for more details.
  14  //
  15  // You should have received a copy of the GNU General Public License
  16  // along with Moodle.  If not, see <http://www.gnu.org/licenses/>.
  17  
  18  /**
  19   * Main administration script.
  20   *
  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
  24   */
  25  
  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();
  30  }
  31  
  32  // Check that PHP is of a sufficient version as soon as possible.
  33  require_once (__DIR__.'/../lib/phpminimumversionlib.php');
  34  moodle_require_minimum_php_version();
  35  
  36  // make sure iconv is available and actually works
  37  if (!function_exists('iconv')) {
  38      // this should not happen, this must be very borked install
  39      echo 'Moodle requires the iconv PHP extension. Please install or enable the iconv extension.';
  40      die();
  41  }
  42  
  43  // Make sure php5-json is available.
  44  if (!function_exists('json_encode') || !function_exists('json_decode')) {
  45      // This also shouldn't happen.
  46      echo 'Moodle requires the json PHP extension. Please install or enable the json extension.';
  47      die();
  48  }
  49  
  50  // Make sure xml extension is available.
  51  if (!extension_loaded('xml')) {
  52      echo 'Moodle requires the xml PHP extension. Please install or enable the xml extension.';
  53      die();
  54  }
  55  
  56  // Make sure mbstring extension is available.
  57  if (!extension_loaded('mbstring')) {
  58      echo 'Moodle requires the mbstring PHP extension. Please install or enable the mbstring extension.';
  59      die();
  60  }
  61  
  62  define('NO_OUTPUT_BUFFERING', true);
  63  
  64  if (isset($_POST['upgradekey'])) {
  65      // Before you start reporting issues about the collision attacks against
  66      // SHA-1, you should understand that we are not actually attempting to do
  67      // any cryptography here. This is hashed purely so that the key is not
  68      // that apparent in the address bar itself. Anyone who catches the HTTP
  69      // traffic can immediately use it as a valid admin key.
  70      header('Location: index.php?cache=0&upgradekeyhash='.sha1($_POST['upgradekey']));
  71      die();
  72  }
  73  
  74  if ((isset($_GET['cache']) and $_GET['cache'] === '0')
  75          or (isset($_POST['cache']) and $_POST['cache'] === '0')
  76          or (!isset($_POST['cache']) and !isset($_GET['cache']) and empty($_GET['sesskey']) and empty($_POST['sesskey']))) {
  77      // Prevent caching at all cost when visiting this page directly,
  78      // we redirect to self once we known no upgrades are necessary.
  79      // Note: $_GET and $_POST are used here intentionally because our param cleaning is not loaded yet.
  80      // Note2: the sesskey is present in all block editing hacks, we can not redirect there, so enable caching.
  81      define('CACHE_DISABLE_ALL', true);
  82  
  83      // Force OPcache reset if used, we do not want any stale caches
  84      // when detecting if upgrade necessary or when running upgrade.
  85      if (function_exists('opcache_reset')) {
  86          opcache_reset();
  87      }
  88      $cache = 0;
  89  
  90  } else {
  91      $cache = 1;
  92  }
  93  
  94  require('../config.php');
  95  
  96  // Invalidate the cache of version.php in any circumstances to help core_component
  97  // detecting if the version has changed and component cache should be reset.
  98  if (function_exists('opcache_invalidate')) {
  99      opcache_invalidate($CFG->dirroot . '/version.php', true);
 100  }
 101  // Make sure the component cache gets rebuilt if necessary, any method that
 102  // indirectly calls the protected init() method is good here.
 103  core_component::get_core_subsystems();
 104  
 105  if (is_major_upgrade_required() && isloggedin()) {
 106      // A major upgrade is required.
 107      // Terminate the session and redirect back here before anything DB-related happens.
 108      redirect_if_major_upgrade_required();
 109  }
 110  
 111  require_once($CFG->libdir.'/adminlib.php');    // various admin-only functions
 112  require_once($CFG->libdir.'/upgradelib.php');  // general upgrade/install related functions
 113  
 114  $confirmupgrade = optional_param('confirmupgrade', 0, PARAM_BOOL); // Core upgrade confirmed?
 115  $confirmrelease = optional_param('confirmrelease', 0, PARAM_BOOL); // Core release info and server checks confirmed?
 116  $confirmplugins = optional_param('confirmplugincheck', 0, PARAM_BOOL); // Plugins check page confirmed?
 117  $showallplugins = optional_param('showallplugins', 0, PARAM_BOOL); // Show all plugins on the plugins check page?
 118  $agreelicense = optional_param('agreelicense', 0, PARAM_BOOL); // GPL license confirmed for installation?
 119  $fetchupdates = optional_param('fetchupdates', 0, PARAM_BOOL); // Should check for available updates?
 120  $newaddonreq = optional_param('installaddonrequest', null, PARAM_RAW); // Plugin installation requested at moodle.org/plugins.
 121  $upgradekeyhash = optional_param('upgradekeyhash', null, PARAM_ALPHANUM); // Hash of provided upgrade key.
 122  $installdep = optional_param('installdep', null, PARAM_COMPONENT); // Install given missing dependency (required plugin).
 123  $installdepx = optional_param('installdepx', false, PARAM_BOOL); // Install all missing dependencies.
 124  $confirminstalldep = optional_param('confirminstalldep', false, PARAM_BOOL); // Installing dependencies confirmed.
 125  $abortinstall = optional_param('abortinstall', null, PARAM_COMPONENT); // Cancel installation of the given new plugin.
 126  $abortinstallx = optional_param('abortinstallx', null, PARAM_BOOL); // Cancel installation of all new plugins.
 127  $confirmabortinstall = optional_param('confirmabortinstall', false, PARAM_BOOL); // Installation cancel confirmed.
 128  $abortupgrade = optional_param('abortupgrade', null, PARAM_COMPONENT); // Cancel upgrade of the given existing plugin.
 129  $abortupgradex = optional_param('abortupgradex', null, PARAM_BOOL); // Cancel upgrade of all upgradable plugins.
 130  $confirmabortupgrade = optional_param('confirmabortupgrade', false, PARAM_BOOL); // Upgrade cancel confirmed.
 131  $installupdate = optional_param('installupdate', null, PARAM_COMPONENT); // Install given available update.
 132  $installupdateversion = optional_param('installupdateversion', null, PARAM_INT); // Version of the available update to install.
 133  $installupdatex = optional_param('installupdatex', false, PARAM_BOOL); // Install all available plugin updates.
 134  $confirminstallupdate = optional_param('confirminstallupdate', false, PARAM_BOOL); // Available update(s) install confirmed?
 135  
 136  if (!empty($CFG->disableupdateautodeploy)) {
 137      // Invalidate all requests to install plugins via the admin UI.
 138      $newaddonreq = null;
 139      $installdep = null;
 140      $installdepx = false;
 141      $abortupgrade = null;
 142      $abortupgradex = null;
 143      $installupdate = null;
 144      $installupdateversion = null;
 145      $installupdatex = false;
 146  }
 147  
 148  // Set up PAGE.
 149  $url = new moodle_url('/admin/index.php');
 150  $url->param('cache', $cache);
 151  if (isset($upgradekeyhash)) {
 152      $url->param('upgradekeyhash', $upgradekeyhash);
 153  }
 154  $PAGE->set_url($url);
 155  unset($url);
 156  
 157  // Are we returning from an add-on installation request at moodle.org/plugins?
 158  if ($newaddonreq and !$cache and empty($CFG->disableupdateautodeploy)) {
 159      $target = new moodle_url('/admin/tool/installaddon/index.php', array(
 160          'installaddonrequest' => $newaddonreq,
 161          'confirm' => 0));
 162      if (!isloggedin() or isguestuser()) {
 163          // Login and go the the add-on tool page.
 164          $SESSION->wantsurl = $target->out();
 165          redirect(get_login_url());
 166      }
 167      redirect($target);
 168  }
 169  
 170  $PAGE->set_pagelayout('admin'); // Set a default pagelayout
 171  
 172  $documentationlink = '<a href="http://docs.moodle.org/en/Installation">Installation docs</a>';
 173  
 174  // Check some PHP server settings
 175  
 176  if (ini_get_bool('session.auto_start')) {
 177      throw new \moodle_exception('phpvaroff', 'debug', '',
 178          (object)array('name' => 'session.auto_start', 'link' => $documentationlink));
 179  }
 180  
 181  if (!ini_get_bool('file_uploads')) {
 182      throw new \moodle_exception('phpvaron', 'debug', '',
 183          (object)array('name' => 'file_uploads', 'link' => $documentationlink));
 184  }
 185  
 186  if (is_float_problem()) {
 187      throw new \moodle_exception('phpfloatproblem', 'admin', '', $documentationlink);
 188  }
 189  
 190  // Set some necessary variables during set-up to avoid PHP warnings later on this page
 191  if (!isset($CFG->release)) {
 192      $CFG->release = '';
 193  }
 194  if (!isset($CFG->version)) {
 195      $CFG->version = '';
 196  }
 197  if (!isset($CFG->branch)) {
 198      $CFG->branch = '';
 199  }
 200  
 201  $version = null;
 202  $release = null;
 203  $branch = null;
 204  require("$CFG->dirroot/version.php");       // defines $version, $release, $branch and $maturity
 205  $CFG->target_release = $release;            // used during installation and upgrades
 206  
 207  if (!$version or !$release) {
 208      throw new \moodle_exception('withoutversion', 'debug'); // Without version, stop.
 209  }
 210  
 211  if (!core_tables_exist()) {
 212      $PAGE->set_pagelayout('maintenance');
 213      $PAGE->set_popup_notification_allowed(false);
 214  
 215      // fake some settings
 216      $CFG->docroot = 'http://docs.moodle.org';
 217  
 218      $strinstallation = get_string('installation', 'install');
 219  
 220      // remove current session content completely
 221      \core\session\manager::terminate_current();
 222  
 223      if (empty($agreelicense)) {
 224          $strlicense = get_string('license');
 225  
 226          $PAGE->navbar->add($strlicense);
 227          $PAGE->set_title($strinstallation . moodle_page::TITLE_SEPARATOR . 'Moodle ' . $CFG->target_release, false);
 228          $PAGE->set_heading($strinstallation);
 229          $PAGE->set_cacheable(false);
 230  
 231          $output = $PAGE->get_renderer('core', 'admin');
 232          echo $output->install_licence_page();
 233          die();
 234      }
 235      if (empty($confirmrelease)) {
 236          require_once($CFG->libdir.'/environmentlib.php');
 237          list($envstatus, $environmentresults) = check_moodle_environment(normalize_version($release), ENV_SELECT_RELEASE);
 238          $strcurrentrelease = get_string('currentrelease');
 239  
 240          $PAGE->navbar->add($strcurrentrelease);
 241          $PAGE->set_title($strinstallation);
 242          $PAGE->set_heading($strinstallation . ' - Moodle ' . $CFG->target_release);
 243          $PAGE->set_cacheable(false);
 244  
 245          $output = $PAGE->get_renderer('core', 'admin');
 246          echo $output->install_environment_page($maturity, $envstatus, $environmentresults, $release);
 247          die();
 248      }
 249  
 250      // check plugin dependencies
 251      $failed = array();
 252      if (!core_plugin_manager::instance()->all_plugins_ok($version, $failed, $CFG->branch)) {
 253          $PAGE->navbar->add(get_string('pluginscheck', 'admin'));
 254          $PAGE->set_title($strinstallation);
 255          $PAGE->set_heading($strinstallation . ' - Moodle ' . $CFG->target_release);
 256  
 257          $output = $PAGE->get_renderer('core', 'admin');
 258          $url = new moodle_url($PAGE->url, array('agreelicense' => 1, 'confirmrelease' => 1, 'lang' => $CFG->lang));
 259          echo $output->unsatisfied_dependencies_page($version, $failed, $url);
 260          die();
 261      }
 262      unset($failed);
 263  
 264      //TODO: add a page with list of non-standard plugins here
 265  
 266      $strdatabasesetup = get_string('databasesetup');
 267      upgrade_init_javascript();
 268  
 269      $PAGE->navbar->add($strdatabasesetup);
 270      $PAGE->set_title($strinstallation . moodle_page::TITLE_SEPARATOR . $CFG->target_release, false);
 271      $PAGE->set_heading($strinstallation);
 272      $PAGE->set_cacheable(false);
 273  
 274      $output = $PAGE->get_renderer('core', 'admin');
 275      echo $output->header();
 276  
 277      if (!$DB->setup_is_unicodedb()) {
 278          if (!$DB->change_db_encoding()) {
 279              // If could not convert successfully, throw error, and prevent installation
 280              throw new \moodle_exception('unicoderequired', 'admin');
 281          }
 282      }
 283  
 284      install_core($version, true);
 285  }
 286  
 287  
 288  // Check version of Moodle code on disk compared with database
 289  // and upgrade if possible.
 290  
 291  if (!$cache) {
 292      // Do not try to do anything fancy in non-cached mode,
 293      // this prevents themes from fetching data from non-existent tables.
 294      $PAGE->set_pagelayout('maintenance');
 295      $PAGE->set_popup_notification_allowed(false);
 296  }
 297  
 298  $stradministration = get_string('administration');
 299  $PAGE->set_context(context_system::instance());
 300  
 301  if (empty($CFG->version)) {
 302      throw new \moodle_exception('missingconfigversion', 'debug');
 303  }
 304  
 305  // Detect config cache inconsistency, this happens when you switch branches on dev servers.
 306  if ($CFG->version != $DB->get_field('config', 'value', array('name'=>'version'))) {
 307      purge_all_caches();
 308      redirect(new moodle_url($PAGE->url), 'Config cache inconsistency detected, resetting caches...');
 309  }
 310  
 311  if (!$cache and $version > $CFG->version) {  // upgrade
 312  
 313      $PAGE->set_url(new moodle_url($PAGE->url, array(
 314          'confirmupgrade' => $confirmupgrade,
 315          'confirmrelease' => $confirmrelease,
 316          'confirmplugincheck' => $confirmplugins,
 317      )));
 318  
 319      check_upgrade_key($upgradekeyhash);
 320  
 321      // Warning about upgrading a test site.
 322      $testsite = false;
 323      if (defined('BEHAT_SITE_RUNNING')) {
 324          $testsite = 'behat';
 325      }
 326  
 327      if (isset($CFG->themerev)) {
 328          // Store the themerev to restore after purging caches.
 329          $themerev = $CFG->themerev;
 330      }
 331  
 332      // We purge all of MUC's caches here.
 333      // Caches are disabled for upgrade by CACHE_DISABLE_ALL so we must set the first arg to true.
 334      // This ensures a real config object is loaded and the stores will be purged.
 335      // This is the only way we can purge custom caches such as memcache or APC.
 336      // Note: all other calls to caches will still used the disabled API.
 337      cache_helper::purge_all(true);
 338      // We then purge the regular caches.
 339      purge_all_caches();
 340  
 341      if (isset($themerev)) {
 342          // Restore the themerev
 343          set_config('themerev', $themerev);
 344      }
 345  
 346      $output = $PAGE->get_renderer('core', 'admin');
 347  
 348      if (upgrade_stale_php_files_present()) {
 349          $PAGE->set_title($stradministration);
 350          $PAGE->set_cacheable(false);
 351  
 352          echo $output->upgrade_stale_php_files_page();
 353          die();
 354      }
 355  
 356      if (empty($confirmupgrade)) {
 357          $a = new stdClass();
 358          $a->oldversion = "$CFG->release (".sprintf('%.2f', $CFG->version).")";
 359          $a->newversion = "$release (".sprintf('%.2f', $version).")";
 360          $strdatabasechecking = get_string('databasechecking', '', $a);
 361  
 362          $PAGE->set_title($stradministration);
 363          $PAGE->set_heading($strdatabasechecking);
 364          $PAGE->set_cacheable(false);
 365  
 366          echo $output->upgrade_confirm_page($a->newversion, $maturity, $testsite);
 367          die();
 368  
 369      } else if (empty($confirmrelease)) {
 370          require_once($CFG->libdir.'/environmentlib.php');
 371          list($envstatus, $environmentresults) = check_moodle_environment($release, ENV_SELECT_RELEASE);
 372          $strcurrentrelease = get_string('currentrelease');
 373  
 374          $PAGE->navbar->add($strcurrentrelease);
 375          $PAGE->set_title($strcurrentrelease);
 376          $PAGE->set_heading($strcurrentrelease);
 377          $PAGE->set_cacheable(false);
 378  
 379          echo $output->upgrade_environment_page($release, $envstatus, $environmentresults);
 380          die();
 381  
 382      } else if (empty($confirmplugins)) {
 383          $strplugincheck = get_string('plugincheck');
 384  
 385          $PAGE->navbar->add($strplugincheck);
 386          $PAGE->set_title($strplugincheck);
 387          $PAGE->set_heading($strplugincheck);
 388          $PAGE->set_cacheable(false);
 389  
 390          $pluginman = core_plugin_manager::instance();
 391  
 392          // Check for available updates.
 393          if ($fetchupdates) {
 394              // No sesskey support guaranteed here, because sessions might not work yet.
 395              $updateschecker = \core\update\checker::instance();
 396              if ($updateschecker->enabled()) {
 397                  $updateschecker->fetch();
 398              }
 399              redirect($PAGE->url);
 400          }
 401  
 402          // Cancel all plugin installations.
 403          if ($abortinstallx) {
 404              // No sesskey support guaranteed here, because sessions might not work yet.
 405              $abortables = $pluginman->list_cancellable_installations();
 406              if ($abortables) {
 407                  if ($confirmabortinstall) {
 408                      foreach ($abortables as $plugin) {
 409                          $pluginman->cancel_plugin_installation($plugin->component);
 410                      }
 411                      redirect($PAGE->url);
 412                  } else {
 413                      $continue = new moodle_url($PAGE->url, array('abortinstallx' => $abortinstallx, 'confirmabortinstall' => 1));
 414                      echo $output->upgrade_confirm_abort_install_page($abortables, $continue);
 415                      die();
 416                  }
 417              }
 418              redirect($PAGE->url);
 419          }
 420  
 421          // Cancel single plugin installation.
 422          if ($abortinstall) {
 423              // No sesskey support guaranteed here, because sessions might not work yet.
 424              if ($confirmabortinstall) {
 425                  $pluginman->cancel_plugin_installation($abortinstall);
 426                  redirect($PAGE->url);
 427              } else {
 428                  $continue = new moodle_url($PAGE->url, array('abortinstall' => $abortinstall, 'confirmabortinstall' => 1));
 429                  $abortable = $pluginman->get_plugin_info($abortinstall);
 430                  if ($pluginman->can_cancel_plugin_installation($abortable)) {
 431                      echo $output->upgrade_confirm_abort_install_page(array($abortable), $continue);
 432                      die();
 433                  }
 434                  redirect($PAGE->url);
 435              }
 436          }
 437  
 438          // Cancel all plugins upgrades (that is, restore archived versions).
 439          if ($abortupgradex) {
 440              // No sesskey support guaranteed here, because sessions might not work yet.
 441              $restorable = $pluginman->list_restorable_archives();
 442              if ($restorable) {
 443                  upgrade_install_plugins($restorable, $confirmabortupgrade,
 444                      get_string('cancelupgradehead', 'core_plugin'),
 445                      new moodle_url($PAGE->url, array('abortupgradex' => 1, 'confirmabortupgrade' => 1))
 446                  );
 447              }
 448              redirect($PAGE->url);
 449          }
 450  
 451          // Cancel single plugin upgrade (that is, install the archived version).
 452          if ($abortupgrade) {
 453              // No sesskey support guaranteed here, because sessions might not work yet.
 454              $restorable = $pluginman->list_restorable_archives();
 455              if (isset($restorable[$abortupgrade])) {
 456                  $restorable = array($restorable[$abortupgrade]);
 457                  upgrade_install_plugins($restorable, $confirmabortupgrade,
 458                      get_string('cancelupgradehead', 'core_plugin'),
 459                      new moodle_url($PAGE->url, array('abortupgrade' => $abortupgrade, 'confirmabortupgrade' => 1))
 460                  );
 461              }
 462              redirect($PAGE->url);
 463          }
 464  
 465          // Install all available missing dependencies.
 466          if ($installdepx) {
 467              // No sesskey support guaranteed here, because sessions might not work yet.
 468              $installable = $pluginman->filter_installable($pluginman->missing_dependencies(true));
 469              upgrade_install_plugins($installable, $confirminstalldep,
 470                  get_string('dependencyinstallhead', 'core_plugin'),
 471                  new moodle_url($PAGE->url, array('installdepx' => 1, 'confirminstalldep' => 1))
 472              );
 473          }
 474  
 475          // Install single available missing dependency.
 476          if ($installdep) {
 477              // No sesskey support guaranteed here, because sessions might not work yet.
 478              $installable = $pluginman->filter_installable($pluginman->missing_dependencies(true));
 479              if (!empty($installable[$installdep])) {
 480                  $installable = array($installable[$installdep]);
 481                  upgrade_install_plugins($installable, $confirminstalldep,
 482                      get_string('dependencyinstallhead', 'core_plugin'),
 483                      new moodle_url($PAGE->url, array('installdep' => $installdep, 'confirminstalldep' => 1))
 484                  );
 485              }
 486          }
 487  
 488          // Install all available updates.
 489          if ($installupdatex) {
 490              // No sesskey support guaranteed here, because sessions might not work yet.
 491              $installable = $pluginman->filter_installable($pluginman->available_updates());
 492              upgrade_install_plugins($installable, $confirminstallupdate,
 493                  get_string('updateavailableinstallallhead', 'core_admin'),
 494                  new moodle_url($PAGE->url, array('installupdatex' => 1, 'confirminstallupdate' => 1))
 495              );
 496          }
 497  
 498          // Install single available update.
 499          if ($installupdate and $installupdateversion) {
 500              // No sesskey support guaranteed here, because sessions might not work yet.
 501              if ($pluginman->is_remote_plugin_installable($installupdate, $installupdateversion)) {
 502                  $installable = array($pluginman->get_remote_plugin_info($installupdate, $installupdateversion, true));
 503                  upgrade_install_plugins($installable, $confirminstallupdate,
 504                      get_string('updateavailableinstallallhead', 'core_admin'),
 505                      new moodle_url($PAGE->url, array('installupdate' => $installupdate,
 506                          'installupdateversion' => $installupdateversion, 'confirminstallupdate' => 1)
 507                      )
 508                  );
 509              }
 510          }
 511  
 512          echo $output->upgrade_plugin_check_page(core_plugin_manager::instance(), \core\update\checker::instance(),
 513                  $version, $showallplugins, $PAGE->url, new moodle_url($PAGE->url, array('confirmplugincheck' => 1)));
 514          die();
 515  
 516      } else {
 517          // Always verify plugin dependencies!
 518          $failed = array();
 519          if (!core_plugin_manager::instance()->all_plugins_ok($version, $failed, $CFG->branch)) {
 520              echo $output->unsatisfied_dependencies_page($version, $failed, new moodle_url($PAGE->url,
 521                  array('confirmplugincheck' => 0)));
 522              die();
 523          }
 524          unset($failed);
 525  
 526          // Launch main upgrade.
 527          upgrade_core($version, true);
 528      }
 529  } else if ($version < $CFG->version) {
 530      // better stop here, we can not continue with plugin upgrades or anything else
 531      throw new moodle_exception('downgradedcore', 'error', new moodle_url('/admin/'));
 532  }
 533  
 534  // Updated human-readable release version if necessary
 535  if (!$cache and $release <> $CFG->release) {  // Update the release version
 536      set_config('release', $release);
 537  }
 538  
 539  if (!$cache and $branch <> $CFG->branch) {  // Update the branch
 540      set_config('branch', $branch);
 541  }
 542  
 543  if (!$cache and moodle_needs_upgrading()) {
 544  
 545      $PAGE->set_url(new moodle_url($PAGE->url, array(
 546          'confirmrelease' => $confirmrelease,
 547          'confirmplugincheck' => $confirmplugins,
 548      )));
 549  
 550      check_upgrade_key($upgradekeyhash);
 551  
 552      if (!$PAGE->headerprinted) {
 553          // means core upgrade or installation was not already done
 554  
 555          $pluginman = core_plugin_manager::instance();
 556          $output = $PAGE->get_renderer('core', 'admin');
 557  
 558          if (empty($confirmrelease)) {
 559              require_once($CFG->libdir . '/environmentlib.php');
 560  
 561              list($envstatus, $environmentresults) = check_moodle_environment($release, ENV_SELECT_RELEASE);
 562              $strcurrentrelease = get_string('currentrelease');
 563  
 564              $PAGE->navbar->add($strcurrentrelease);
 565              $PAGE->set_title($strcurrentrelease);
 566              $PAGE->set_heading($strcurrentrelease);
 567              $PAGE->set_cacheable(false);
 568  
 569              echo $output->upgrade_environment_page($release, $envstatus, $environmentresults);
 570              die();
 571  
 572          } else if (!$confirmplugins) {
 573              $strplugincheck = get_string('plugincheck');
 574  
 575              $PAGE->navbar->add($strplugincheck);
 576              $PAGE->set_title($strplugincheck);
 577              $PAGE->set_heading($strplugincheck);
 578              $PAGE->set_cacheable(false);
 579  
 580              // Check for available updates.
 581              if ($fetchupdates) {
 582                  require_sesskey();
 583                  $updateschecker = \core\update\checker::instance();
 584                  if ($updateschecker->enabled()) {
 585                      $updateschecker->fetch();
 586                  }
 587                  redirect($PAGE->url);
 588              }
 589  
 590              // Cancel all plugin installations.
 591              if ($abortinstallx) {
 592                  require_sesskey();
 593                  $abortables = $pluginman->list_cancellable_installations();
 594                  if ($abortables) {
 595                      if ($confirmabortinstall) {
 596                          foreach ($abortables as $plugin) {
 597                              $pluginman->cancel_plugin_installation($plugin->component);
 598                          }
 599                          redirect($PAGE->url);
 600                      } else {
 601                          $continue = new moodle_url($PAGE->url, array('abortinstallx' => $abortinstallx,
 602                              'confirmabortinstall' => 1));
 603                          echo $output->upgrade_confirm_abort_install_page($abortables, $continue);
 604                          die();
 605                      }
 606                  }
 607                  redirect($PAGE->url);
 608              }
 609  
 610              // Cancel single plugin installation.
 611              if ($abortinstall) {
 612                  require_sesskey();
 613                  if ($confirmabortinstall) {
 614                      $pluginman->cancel_plugin_installation($abortinstall);
 615                      redirect($PAGE->url);
 616                  } else {
 617                      $continue = new moodle_url($PAGE->url, array('abortinstall' => $abortinstall, 'confirmabortinstall' => 1));
 618                      $abortable = $pluginman->get_plugin_info($abortinstall);
 619                      if ($pluginman->can_cancel_plugin_installation($abortable)) {
 620                          echo $output->upgrade_confirm_abort_install_page(array($abortable), $continue);
 621                          die();
 622                      }
 623                      redirect($PAGE->url);
 624                  }
 625              }
 626  
 627              // Cancel all plugins upgrades (that is, restore archived versions).
 628              if ($abortupgradex) {
 629                  require_sesskey();
 630                  $restorable = $pluginman->list_restorable_archives();
 631                  if ($restorable) {
 632                      upgrade_install_plugins($restorable, $confirmabortupgrade,
 633                          get_string('cancelupgradehead', 'core_plugin'),
 634                          new moodle_url($PAGE->url, array('abortupgradex' => 1, 'confirmabortupgrade' => 1))
 635                      );
 636                  }
 637                  redirect($PAGE->url);
 638              }
 639  
 640              // Cancel single plugin upgrade (that is, install the archived version).
 641              if ($abortupgrade) {
 642                  require_sesskey();
 643                  $restorable = $pluginman->list_restorable_archives();
 644                  if (isset($restorable[$abortupgrade])) {
 645                      $restorable = array($restorable[$abortupgrade]);
 646                      upgrade_install_plugins($restorable, $confirmabortupgrade,
 647                          get_string('cancelupgradehead', 'core_plugin'),
 648                          new moodle_url($PAGE->url, array('abortupgrade' => $abortupgrade, 'confirmabortupgrade' => 1))
 649                      );
 650                  }
 651                  redirect($PAGE->url);
 652              }
 653  
 654              // Install all available missing dependencies.
 655              if ($installdepx) {
 656                  require_sesskey();
 657                  $installable = $pluginman->filter_installable($pluginman->missing_dependencies(true));
 658                  upgrade_install_plugins($installable, $confirminstalldep,
 659                      get_string('dependencyinstallhead', 'core_plugin'),
 660                      new moodle_url($PAGE->url, array('installdepx' => 1, 'confirminstalldep' => 1))
 661                  );
 662              }
 663  
 664              // Install single available missing dependency.
 665              if ($installdep) {
 666                  require_sesskey();
 667                  $installable = $pluginman->filter_installable($pluginman->missing_dependencies(true));
 668                  if (!empty($installable[$installdep])) {
 669                      $installable = array($installable[$installdep]);
 670                      upgrade_install_plugins($installable, $confirminstalldep,
 671                          get_string('dependencyinstallhead', 'core_plugin'),
 672                          new moodle_url($PAGE->url, array('installdep' => $installdep, 'confirminstalldep' => 1))
 673                      );
 674                  }
 675              }
 676  
 677              // Install all available updates.
 678              if ($installupdatex) {
 679                  require_sesskey();
 680                  $installable = $pluginman->filter_installable($pluginman->available_updates());
 681                  upgrade_install_plugins($installable, $confirminstallupdate,
 682                      get_string('updateavailableinstallallhead', 'core_admin'),
 683                      new moodle_url($PAGE->url, array('installupdatex' => 1, 'confirminstallupdate' => 1))
 684                  );
 685              }
 686  
 687              // Install single available update.
 688              if ($installupdate and $installupdateversion) {
 689                  require_sesskey();
 690                  if ($pluginman->is_remote_plugin_installable($installupdate, $installupdateversion)) {
 691                      $installable = array($pluginman->get_remote_plugin_info($installupdate, $installupdateversion, true));
 692                      upgrade_install_plugins($installable, $confirminstallupdate,
 693                          get_string('updateavailableinstallallhead', 'core_admin'),
 694                          new moodle_url($PAGE->url, array('installupdate' => $installupdate,
 695                              'installupdateversion' => $installupdateversion, 'confirminstallupdate' => 1)
 696                          )
 697                      );
 698                  }
 699              }
 700  
 701              // Show plugins info.
 702              echo $output->upgrade_plugin_check_page($pluginman, \core\update\checker::instance(),
 703                      $version, $showallplugins,
 704                      new moodle_url($PAGE->url),
 705                      new moodle_url($PAGE->url, array('confirmplugincheck' => 1, 'cache' => 0)));
 706              die();
 707          }
 708  
 709          // Make sure plugin dependencies are always checked.
 710          $failed = array();
 711          if (!$pluginman->all_plugins_ok($version, $failed, $CFG->branch)) {
 712              $output = $PAGE->get_renderer('core', 'admin');
 713              echo $output->unsatisfied_dependencies_page($version, $failed, new moodle_url($PAGE->url,
 714                  array('confirmplugincheck' => 0)));
 715              die();
 716          }
 717          unset($failed);
 718      }
 719  
 720      // install/upgrade all plugins and other parts
 721      upgrade_noncore(true);
 722  }
 723  
 724  // If this is the first install, indicate that this site is fully configured
 725  // except the admin password
 726  if (during_initial_install()) {
 727      set_config('rolesactive', 1); // after this, during_initial_install will return false.
 728      set_config('adminsetuppending', 1);
 729      set_config('registrationpending', 1); // Remind to register site after all other setup is finished.
 730  
 731      // Apply default preset, if it is defined in $CFG and has a valid value.
 732      if (!empty($CFG->setsitepresetduringinstall)) {
 733          \core_adminpresets\helper::change_default_preset($CFG->setsitepresetduringinstall);
 734      }
 735  
 736      // we need this redirect to setup proper session
 737      upgrade_finished("index.php?sessionstarted=1&amp;lang=$CFG->lang");
 738  }
 739  
 740  // make sure admin user is created - this is the last step because we need
 741  // session to be working properly in order to edit admin account
 742   if (!empty($CFG->adminsetuppending)) {
 743      $sessionstarted = optional_param('sessionstarted', 0, PARAM_BOOL);
 744      if (!$sessionstarted) {
 745          redirect("index.php?sessionstarted=1&lang=$CFG->lang");
 746      } else {
 747          $sessionverify = optional_param('sessionverify', 0, PARAM_BOOL);
 748          if (!$sessionverify) {
 749              $SESSION->sessionverify = 1;
 750              redirect("index.php?sessionstarted=1&sessionverify=1&lang=$CFG->lang");
 751          } else {
 752              if (empty($SESSION->sessionverify)) {
 753                  throw new \moodle_exception('installsessionerror', 'admin', "index.php?sessionstarted=1&lang=$CFG->lang");
 754              }
 755              unset($SESSION->sessionverify);
 756          }
 757      }
 758  
 759      // Cleanup SESSION to make sure other code does not complain in the future.
 760      unset($SESSION->has_timed_out);
 761      unset($SESSION->wantsurl);
 762  
 763      // 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
 764      $adminids = explode(',', $CFG->siteadmins);
 765      $adminuser = get_complete_user_data('id', reset($adminids));
 766  
 767      if ($adminuser->password === 'adminsetuppending') {
 768          // prevent installation hijacking
 769          if ($adminuser->lastip !== getremoteaddr()) {
 770              throw new \moodle_exception('installhijacked', 'admin');
 771          }
 772          // login user and let him set password and admin details
 773          $adminuser->newadminuser = 1;
 774          complete_user_login($adminuser);
 775          redirect("$CFG->wwwroot/user/editadvanced.php?id=$adminuser->id"); // Edit thyself
 776  
 777      } else {
 778          unset_config('adminsetuppending');
 779      }
 780  
 781  } else {
 782      // just make sure upgrade logging is properly terminated
 783      upgrade_finished('upgradesettings.php');
 784  }
 785  
 786  if (has_capability('moodle/site:config', context_system::instance())) {
 787      if ($fetchupdates) {
 788          require_sesskey();
 789          $updateschecker = \core\update\checker::instance();
 790          if ($updateschecker->enabled()) {
 791              $updateschecker->fetch();
 792          }
 793          redirect(new moodle_url('/admin/index.php', array('cache' => 0)));
 794      }
 795  }
 796  
 797  // Now we can be sure everything was upgraded and caches work fine,
 798  // redirect if necessary to make sure caching is enabled.
 799  if (!$cache) {
 800      redirect(new moodle_url('/admin/index.php', array('cache' => 1)));
 801  }
 802  
 803  // Check for valid admin user - no guest autologin
 804  require_login(0, false);
 805  if (isguestuser()) {
 806      // Login as real user!
 807      $SESSION->wantsurl = (string)new moodle_url('/admin/index.php');
 808      redirect(get_login_url());
 809  }
 810  $context = context_system::instance();
 811  
 812  if (!has_capability('moodle/site:config', $context)) {
 813      // Do not throw exception display an empty page with administration menu if visible for current user.
 814      $PAGE->set_title(get_string('home'));
 815      $PAGE->set_heading($SITE->fullname);
 816      echo $OUTPUT->header();
 817      echo $OUTPUT->footer();
 818      exit;
 819  }
 820  
 821  // check that site is properly customized
 822  $site = get_site();
 823  if (empty($site->shortname)) {
 824      // probably new installation - lets return to frontpage after this step
 825      // remove settings that we want uninitialised
 826      unset_config('registerauth');
 827      unset_config('timezone'); // Force admin to select timezone!
 828      redirect('upgradesettings.php?return=site');
 829  }
 830  
 831  // setup critical warnings before printing admin tree block
 832  $insecuredataroot = is_dataroot_insecure(true);
 833  $SESSION->admin_critical_warning = ($insecuredataroot==INSECURE_DATAROOT_ERROR);
 834  
 835  $adminroot = admin_get_root();
 836  $PAGE->set_primary_active_tab('siteadminnode');
 837  
 838  // Check if there are any new admin settings which have still yet to be set
 839  if (any_new_admin_settings($adminroot)) {
 840      redirect('upgradesettings.php');
 841  }
 842  
 843  // Return to original page that started the plugin uninstallation if necessary.
 844  if (isset($SESSION->pluginuninstallreturn)) {
 845      $return = $SESSION->pluginuninstallreturn;
 846      unset($SESSION->pluginuninstallreturn);
 847      if ($return) {
 848          redirect($return);
 849      }
 850  }
 851  
 852  // If site registration needs updating, redirect.
 853  \core\hub\registration::registration_reminder('/admin/index.php');
 854  
 855  // Everything should now be set up, and the user is an admin
 856  
 857  // Print default admin page with notifications.
 858  $errorsdisplayed = defined('WARN_DISPLAY_ERRORS_ENABLED');
 859  
 860  $lastcron = get_config('tool_task', 'lastcronstart');
 861  $cronoverdue = ($lastcron < time() - 3600 * 24);
 862  $lastcroninterval = get_config('tool_task', 'lastcroninterval');
 863  
 864  $expectedfrequency = $CFG->expectedcronfrequency ?? MINSECS;
 865  $croninfrequent = !$cronoverdue && ($lastcroninterval > ($expectedfrequency + MINSECS) || $lastcron < time() - $expectedfrequency);
 866  $dbproblems = $DB->diagnose();
 867  $maintenancemode = !empty($CFG->maintenance_enabled);
 868  
 869  // Available updates for Moodle core.
 870  $updateschecker = \core\update\checker::instance();
 871  $availableupdates = array();
 872  $availableupdatesfetch = null;
 873  
 874  if ($updateschecker->enabled()) {
 875      // Only compute the update information when it is going to be displayed to the user.
 876      $availableupdates['core'] = $updateschecker->get_update_info('core',
 877          array('minmaturity' => $CFG->updateminmaturity, 'notifybuilds' => $CFG->updatenotifybuilds));
 878  
 879      // Available updates for contributed plugins
 880      $pluginman = core_plugin_manager::instance();
 881      foreach ($pluginman->get_plugins() as $plugintype => $plugintypeinstances) {
 882          foreach ($plugintypeinstances as $pluginname => $plugininfo) {
 883              $pluginavailableupdates = $plugininfo->available_updates();
 884              if (!empty($pluginavailableupdates)) {
 885                  foreach ($pluginavailableupdates as $pluginavailableupdate) {
 886                      if (!isset($availableupdates[$plugintype.'_'.$pluginname])) {
 887                          $availableupdates[$plugintype.'_'.$pluginname] = array();
 888                      }
 889                      $availableupdates[$plugintype.'_'.$pluginname][] = $pluginavailableupdate;
 890                  }
 891              }
 892          }
 893      }
 894  
 895      // The timestamp of the most recent check for available updates
 896      $availableupdatesfetch = $updateschecker->get_last_timefetched();
 897  }
 898  
 899  $buggyiconvnomb = (!function_exists('mb_convert_encoding') and @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
 900  //check if the site is registered on Moodle.org
 901  $registered = \core\hub\registration::is_registered();
 902  // Check if there are any cache warnings.
 903  $cachewarnings = cache_helper::warnings();
 904  // Check if there are events 1 API handlers.
 905  $eventshandlers = $DB->get_records_sql('SELECT DISTINCT component FROM {events_handlers}');
 906  $themedesignermode = !empty($CFG->themedesignermode);
 907  $mobileconfigured = !empty($CFG->enablemobilewebservice);
 908  $invalidforgottenpasswordurl = !empty($CFG->forgottenpasswordurl) && empty(clean_param($CFG->forgottenpasswordurl, PARAM_URL));
 909  
 910  // Check if a directory with development libraries exists.
 911  if (empty($CFG->disabledevlibdirscheck) && (is_dir($CFG->dirroot.'/vendor') || is_dir($CFG->dirroot.'/node_modules'))) {
 912      $devlibdir = true;
 913  } else {
 914      $devlibdir = false;
 915  }
 916  // Check if the site is being foced onto ssl.
 917  $overridetossl = !empty($CFG->overridetossl);
 918  
 919  // Check if moodle campaign content setting is enabled or not.
 920  $showcampaigncontent = !isset($CFG->showcampaigncontent) || $CFG->showcampaigncontent;
 921  
 922  // Encourage admins to enable the user feedback feature if it is not enabled already.
 923  $showfeedbackencouragement = empty($CFG->enableuserfeedback);
 924  
 925  // Check if the service and support content setting is enabled or not.
 926  $servicesandsupportcontent = !isset($CFG->showservicesandsupportcontent) || $CFG->showservicesandsupportcontent;
 927  
 928  // Check whether the XML-RPC protocol is enabled or not.
 929  require_once($CFG->libdir . '/environmentlib.php');
 930  $result = new environment_results('custom_checks');
 931  $result = check_xmlrpc_usage($result);
 932  $xmlrpcwarning = !is_null($result) ? get_string($result->getFeedbackStr(), 'admin') : '';
 933  
 934  admin_externalpage_setup('adminnotifications');
 935  
 936  $output = $PAGE->get_renderer('core', 'admin');
 937  
 938  echo $output->admin_notifications_page($maturity, $insecuredataroot, $errorsdisplayed, $cronoverdue, $dbproblems,
 939                                         $maintenancemode, $availableupdates, $availableupdatesfetch, $buggyiconvnomb,
 940                                         $registered, $cachewarnings, $eventshandlers, $themedesignermode, $devlibdir,
 941                                         $mobileconfigured, $overridetossl, $invalidforgottenpasswordurl, $croninfrequent,
 942                                         $showcampaigncontent, $showfeedbackencouragement, $servicesandsupportcontent,
 943                                         $xmlrpcwarning);