Search moodle.org's
Developer Documentation

See Release Notes

  • Bug fixes for general core bugs in 4.0.x will end 8 May 2023 (12 months).
  • Bug fixes for security issues in 4.0.x will end 13 November 2023 (18 months).
  • PHP version: minimum PHP 7.3.0 Note: the minimum PHP version has increased since Moodle 3.10. PHP 7.4.x is also supported.
/lib/ -> installlib.php (source)

Differences Between: [Versions 310 and 400] [Versions 311 and 400] [Versions 39 and 400] [Versions 400 and 401] [Versions 400 and 402] [Versions 400 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   * Functions to support installation process
  20   *
  21   * @package    core
  22   * @subpackage install
  23   * @copyright  2009 Petr Skoda (http://skodak.org)
  24   * @license    http://www.gnu.org/copyleft/gpl.html GNU GPL v3 or later
  25   */
  26  
  27  defined('MOODLE_INTERNAL') || die();
  28  
  29  /** INSTALL_WELCOME = 0 */
  30  define('INSTALL_WELCOME',       0);
  31  /** INSTALL_ENVIRONMENT = 1 */
  32  define('INSTALL_ENVIRONMENT',   1);
  33  /** INSTALL_PATHS = 2 */
  34  define('INSTALL_PATHS',         2);
  35  /** INSTALL_DOWNLOADLANG = 3 */
  36  define('INSTALL_DOWNLOADLANG',  3);
  37  /** INSTALL_DATABASETYPE = 4 */
  38  define('INSTALL_DATABASETYPE',  4);
  39  /** INSTALL_DATABASE = 5 */
  40  define('INSTALL_DATABASE',      5);
  41  /** INSTALL_SAVE = 6 */
  42  define('INSTALL_SAVE',          6);
  43  
  44  /**
  45   * Tries to detect the right www root setting.
  46   * @return string detected www root
  47   */
  48  function install_guess_wwwroot() {
  49      $wwwroot = '';
  50      if (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] == 'off') {
  51          $wwwroot .= 'http://';
  52      } else {
  53          $wwwroot .= 'https://';
  54      }
  55      $hostport = explode(':', $_SERVER['HTTP_HOST']);
  56      $wwwroot .= reset($hostport);
  57      if ($_SERVER['SERVER_PORT'] != 80 and $_SERVER['SERVER_PORT'] != '443') {
  58          $wwwroot .= ':'.$_SERVER['SERVER_PORT'];
  59      }
  60      $wwwroot .= $_SERVER['SCRIPT_NAME'];
  61  
  62      list($wwwroot, $xtra) = explode('/install.php', $wwwroot);
  63  
  64      return $wwwroot;
  65  }
  66  
  67  /**
  68   * Copy of @see{ini_get_bool()}
  69   * @param string $ini_get_arg
  70   * @return bool
  71   */
  72  function install_ini_get_bool($ini_get_arg) {
  73      $temp = ini_get($ini_get_arg);
  74  
  75      if ($temp == '1' or strtolower($temp) == 'on') {
  76          return true;
  77      }
  78      return false;
  79  }
  80  
  81  /**
  82   * Creates dataroot if not exists yet,
  83   * makes sure it is writable, add lang directory
  84   * and add .htaccess just in case it works.
  85   *
  86   * @param string $dataroot full path to dataroot
  87   * @param int $dirpermissions
  88   * @return bool success
  89   */
  90  function install_init_dataroot($dataroot, $dirpermissions) {
  91      if (file_exists($dataroot) and !is_dir($dataroot)) {
  92          // file with the same name exists
  93          return false;
  94      }
  95  
  96      umask(0000); // $CFG->umaskpermissions is not set yet.
  97      if (!file_exists($dataroot)) {
  98          if (!mkdir($dataroot, $dirpermissions, true)) {
  99              // most probably this does not work, but anyway
 100              return false;
 101          }
 102      }
 103      @chmod($dataroot, $dirpermissions);
 104  
 105      if (!is_writable($dataroot)) {
 106          return false; // we can not continue
 107      }
 108  
 109      // create the directory for $CFG->tempdir
 110      if (!is_dir("$dataroot/temp")) {
 111          if (!mkdir("$dataroot/temp", $dirpermissions, true)) {
 112              return false;
 113          }
 114      }
 115      if (!is_writable("$dataroot/temp")) {
 116          return false; // we can not continue
 117      }
 118  
 119      // create the directory for $CFG->cachedir
 120      if (!is_dir("$dataroot/cache")) {
 121          if (!mkdir("$dataroot/cache", $dirpermissions, true)) {
 122              return false;
 123          }
 124      }
 125      if (!is_writable("$dataroot/cache")) {
 126          return false; // we can not continue
 127      }
 128  
 129      // create the directory for $CFG->langotherroot
 130      if (!is_dir("$dataroot/lang")) {
 131          if (!mkdir("$dataroot/lang", $dirpermissions, true)) {
 132              return false;
 133          }
 134      }
 135      if (!is_writable("$dataroot/lang")) {
 136          return false; // we can not continue
 137      }
 138  
 139      // finally just in case some broken .htaccess that prevents access just in case it is allowed
 140      if (!file_exists("$dataroot/.htaccess")) {
 141          if ($handle = fopen("$dataroot/.htaccess", 'w')) {
 142              fwrite($handle, "deny from all\r\nAllowOverride None\r\nNote: this file is broken intentionally, we do not want anybody to undo it in subdirectory!\r\n");
 143              fclose($handle);
 144          } else {
 145              return false;
 146          }
 147      }
 148  
 149      return true;
 150  }
 151  
 152  /**
 153   * Print help button
 154   * @param string $url
 155   * @param string $titel
 156   * @return void
 157   */
 158  function install_helpbutton($url, $title='') {
 159      if ($title == '') {
 160          $title = get_string('help');
 161      }
 162      echo "<a href=\"javascript:void(0)\" ";
 163      echo "onclick=\"return window.open('$url','Help','menubar=0,location=0,scrollbars,resizable,width=500,height=400')\"";
 164      echo ">";
 165      echo "<img src=\"pix/help.gif\" class=\"iconhelp\" alt=\"$title\" title=\"$title\"/>";
 166      echo "</a>\n";
 167  }
 168  
 169  /**
 170   * This is in function because we want the /install.php to parse in PHP4
 171   *
 172   * @param object $database
 173   * @param string $dbhsot
 174   * @param string $dbuser
 175   * @param string $dbpass
 176   * @param string $dbname
 177   * @param string $prefix
 178   * @param mixed $dboptions
 179   * @return string
 180   */
 181  function install_db_validate($database, $dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions) {
 182      if (!preg_match('/^[a-z_]*$/', $prefix)) {
 183          return get_string('invaliddbprefix', 'install');
 184      }
 185      try {
 186          try {
 187              $database->connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
 188          } catch (moodle_exception $e) {
 189              // let's try to create new database
 190              if ($database->create_database($dbhost, $dbuser, $dbpass, $dbname, $dboptions)) {
 191                  $database->connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
 192              } else {
 193                  throw $e;
 194              }
 195          }
 196          return '';
 197      } catch (dml_exception $ex) {
 198          $stringmanager = get_string_manager();
 199          $errorstring = $ex->errorcode.'oninstall';
 200          $legacystring = $ex->errorcode;
 201          if ($stringmanager->string_exists($errorstring, $ex->module)) {
 202              // By using a different string id from the error code we are separating exception handling and output.
 203              $returnstring = $stringmanager->get_string($errorstring, $ex->module, $ex->a);
 204              if ($ex->debuginfo) {
 205                  $returnstring .= '<br />'.$ex->debuginfo;
 206              }
 207  
 208              return $returnstring;
 209          } else if ($stringmanager->string_exists($legacystring, $ex->module)) {
 210              // There are some DML exceptions that may be thrown here as well as during normal operation.
 211              // If we have a translated message already we still want to serve it here.
 212              // However it is not the preferred way.
 213              $returnstring = $stringmanager->get_string($legacystring, $ex->module, $ex->a);
 214              if ($ex->debuginfo) {
 215                  $returnstring .= '<br />'.$ex->debuginfo;
 216              }
 217  
 218              return $returnstring;
 219          }
 220          // No specific translation. Deliver a generic error message.
 221          return $stringmanager->get_string('dmlexceptiononinstall', 'error', $ex);
 222      }
 223  }
 224  
 225  /**
 226   * Returns content of config.php file.
 227   *
 228   * Uses PHP_EOL for generating proper end of lines for the given platform.
 229   *
 230   * @param moodle_database $database database instance
 231   * @param object $cfg copy of $CFG
 232   * @return string
 233   */
 234  function install_generate_configphp($database, $cfg) {
 235      $configphp = '<?php  // Moodle configuration file' . PHP_EOL . PHP_EOL;
 236  
 237      $configphp .= 'unset($CFG);' . PHP_EOL;
 238      $configphp .= 'global $CFG;' . PHP_EOL;
 239      $configphp .= '$CFG = new stdClass();' . PHP_EOL . PHP_EOL; // prevent PHP5 strict warnings
 240  
 241      $dbconfig = $database->export_dbconfig();
 242  
 243      foreach ($dbconfig as $key=>$value) {
 244          $key = str_pad($key, 9);
 245          $configphp .= '$CFG->'.$key.' = '.var_export($value, true) . ';' . PHP_EOL;
 246      }
 247      $configphp .= PHP_EOL;
 248  
 249      $configphp .= '$CFG->wwwroot   = '.var_export($cfg->wwwroot, true) . ';' . PHP_EOL ;
 250  
 251      $configphp .= '$CFG->dataroot  = '.var_export($cfg->dataroot, true) . ';' . PHP_EOL;
 252  
 253      $configphp .= '$CFG->admin     = '.var_export($cfg->admin, true) . ';' . PHP_EOL . PHP_EOL;
 254  
 255      if (empty($cfg->directorypermissions)) {
 256          $chmod = '02777';
 257      } else {
 258          $chmod = '0' . decoct($cfg->directorypermissions);
 259      }
 260      $configphp .= '$CFG->directorypermissions = ' . $chmod . ';' . PHP_EOL . PHP_EOL;
 261  
 262      if (isset($cfg->upgradekey) and $cfg->upgradekey !== '') {
 263          $configphp .= '$CFG->upgradekey = ' . var_export($cfg->upgradekey, true) . ';' . PHP_EOL . PHP_EOL;
 264      }
 265  
 266      if (isset($cfg->setsitepresetduringinstall) and $cfg->setsitepresetduringinstall !== '') {
 267          $configphp .= '$CFG->setsitepresetduringinstall = ' . var_export($cfg->setsitepresetduringinstall, true) .
 268              ';' . PHP_EOL . PHP_EOL;
 269      }
 270  
 271      $configphp .= 'require_once(__DIR__ . \'/lib/setup.php\');' . PHP_EOL . PHP_EOL;
 272      $configphp .= '// There is no php closing tag in this file,' . PHP_EOL;
 273      $configphp .= '// it is intentional because it prevents trailing whitespace problems!' . PHP_EOL;
 274  
 275      return $configphp;
 276  }
 277  
 278  /**
 279   * Prints complete help page used during installation.
 280   * Does not return.
 281   *
 282   * @global object
 283   * @param string $help
 284   */
 285  function install_print_help_page($help) {
 286      global $CFG, $OUTPUT; //TODO: MUST NOT USE $OUTPUT HERE!!!
 287  
 288      @header('Content-Type: text/html; charset=UTF-8');
 289      @header('X-UA-Compatible: IE=edge');
 290      @header('Cache-Control: no-store, no-cache, must-revalidate');
 291      @header('Cache-Control: post-check=0, pre-check=0', false);
 292      @header('Pragma: no-cache');
 293      @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
 294      @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
 295  
 296      echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
 297      echo '<html dir="'.(right_to_left() ? 'rtl' : 'ltr').'">
 298            <head>
 299            <link rel="shortcut icon" href="theme/clean/pix/favicon.ico" />
 300            <link rel="stylesheet" type="text/css" href="'.$CFG->wwwroot.'/install/css.php" />
 301            <title>'.get_string('installation','install').'</title>
 302            <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
 303            </head><body>';
 304      switch ($help) {
 305          case 'phpversionhelp':
 306              print_string($help, 'install', phpversion());
 307              break;
 308          case 'memorylimithelp':
 309              print_string($help, 'install', @ini_get('memory_limit'));
 310              break;
 311          default:
 312              print_string($help, 'install');
 313      }
 314      echo $OUTPUT->close_window_button(); //TODO: MUST NOT USE $OUTPUT HERE!!!
 315      echo '</body></html>';
 316      die;
 317  }
 318  
 319  /**
 320   * Prints installation page header, we can not use weblib yet in installer.
 321   *
 322   * @global object
 323   * @param stdClass $config
 324   * @param string $stagename
 325   * @param string $heading
 326   * @param string $stagetext
 327   * @param string $stageclass
 328   * @return void
 329   */
 330  function install_print_header($config, $stagename, $heading, $stagetext, $stageclass = "alert-info") {
 331      global $CFG;
 332  
 333      @header('Content-Type: text/html; charset=UTF-8');
 334      @header('X-UA-Compatible: IE=edge');
 335      @header('Cache-Control: no-store, no-cache, must-revalidate');
 336      @header('Cache-Control: post-check=0, pre-check=0', false);
 337      @header('Pragma: no-cache');
 338      @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
 339      @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
 340  
 341      echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
 342      echo '<html dir="'.(right_to_left() ? 'rtl' : 'ltr').'">
 343            <head>
 344            <link rel="shortcut icon" href="theme/clean/pix/favicon.ico" />';
 345  
 346      echo '<link rel="stylesheet" type="text/css" href="'.$CFG->wwwroot.'/install/css.php" />
 347            <title>'.get_string('installation','install').' - Moodle '.$CFG->target_release.'</title>
 348            <meta name="robots" content="noindex">
 349            <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
 350            <meta http-equiv="pragma" content="no-cache" />
 351            <meta http-equiv="expires" content="0" />';
 352  
 353      echo '</head><body class="notloggedin">
 354              <div id="page" class="mt-0 container stage'.$config->stage.'">
 355                  <div id="page-header">
 356                      <div id="header" class=" clearfix">
 357                          <h1 class="headermain">'.get_string('installation','install').'</h1>
 358                          <div class="headermenu">&nbsp;</div>
 359                      </div>
 360                      <div class="bg-light p-3 mb-3"><h3 class="m-0">'.$stagename.'</h3></div>
 361                  </div>
 362            <!-- END OF HEADER -->
 363            <div id="installdiv">';
 364  
 365      echo '<h2>'.$heading.'</h2>';
 366  
 367      if ($stagetext !== '') {
 368          echo '<div class="alert ' . $stageclass . '">';
 369          echo $stagetext;
 370          echo '</div>';
 371      }
 372      // main
 373      echo '<form id="installform" method="post" action="install.php"><fieldset>';
 374      foreach ($config as $name=>$value) {
 375          echo '<input type="hidden" name="'.$name.'" value="'.s($value).'" />';
 376      }
 377  }
 378  
 379  /**
 380   * Prints installation page header, we can not use weblib yet in installer.
 381   *
 382   * @global object
 383   * @param stdClass $config
 384   * @param bool $reload print reload button instead of next
 385   * @return void
 386   */
 387  function install_print_footer($config, $reload=false) {
 388      global $CFG;
 389  
 390      if ($config->stage > INSTALL_WELCOME) {
 391          $first = '<input type="submit" id="previousbutton" class="btn btn-secondary flex-grow-0 ml-auto" name="previous" value="&laquo; '.s(get_string('previous')).'" />';
 392      } else {
 393          $first = '<input type="submit" id="previousbutton" class="btn btn-secondary flex-grow-0  ml-auto" name="next" value="'.s(get_string('reload')).'" />';
 394          $first .= '<script type="text/javascript">
 395  //<![CDATA[
 396      var first = document.getElementById("previousbutton");
 397      first.style.visibility = "hidden";
 398  //]]>
 399  </script>
 400  ';
 401      }
 402  
 403      if ($reload) {
 404          $next = '<input type="submit" id="nextbutton" class="btn btn-primary ml-1 flex-grow-0 mr-auto" name="next" value="'.s(get_string('reload')).'" />';
 405      } else {
 406          $next = '<input type="submit" id="nextbutton" class="btn btn-primary ml-1 flex-grow-0 mr-auto" name="next" value="'.s(get_string('next')).' &raquo;" />';
 407      }
 408  
 409      echo '</fieldset><div id="nav_buttons" class="mb-3 w-100 d-flex">'.$first.$next.'</div>';
 410  
 411      $homelink  = '<div class="sitelink">'.
 412         '<a title="Moodle '. $CFG->target_release .'" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">'.
 413         '<img src="pix/moodlelogo.png" alt="'.get_string('moodlelogo').'" /></a></div>';
 414  
 415      echo '</form></div>';
 416      echo '<div id="page-footer">'.$homelink.'</div>';
 417      echo '</div></body></html>';
 418  }
 419  
 420  /**
 421   * Install Moodle DB,
 422   * config.php must exist, there must not be any tables in db yet.
 423   *
 424   * @param array $options adminpass is mandatory
 425   * @param bool $interactive
 426   * @return void
 427   */
 428  function install_cli_database(array $options, $interactive) {
 429      global $CFG, $DB;
 430      require_once($CFG->libdir.'/environmentlib.php');
 431      require_once($CFG->libdir.'/upgradelib.php');
 432  
 433      // show as much debug as possible
 434      @error_reporting(E_ALL | E_STRICT);
 435      @ini_set('display_errors', '1');
 436      $CFG->debug = (E_ALL | E_STRICT);
 437      $CFG->debugdisplay = true;
 438      $CFG->debugdeveloper = true;
 439  
 440      $CFG->version = '';
 441      $CFG->release = '';
 442      $CFG->branch = '';
 443  
 444      $version = null;
 445      $release = null;
 446      $branch = null;
 447  
 448      // read $version and $release
 449      require($CFG->dirroot.'/version.php');
 450  
 451      if ($DB->get_tables() ) {
 452          cli_error(get_string('clitablesexist', 'install'));
 453      }
 454  
 455      if (empty($options['adminpass'])) {
 456          cli_error('Missing required admin password');
 457      }
 458  
 459      // test environment first
 460      list($envstatus, $environment_results) = check_moodle_environment(normalize_version($release), ENV_SELECT_RELEASE);
 461      if (!$envstatus) {
 462          $errors = environment_get_errors($environment_results);
 463          cli_heading(get_string('environment', 'admin'));
 464          foreach ($errors as $error) {
 465              list($info, $report) = $error;
 466              echo "!! $info !!\n$report\n\n";
 467          }
 468          exit(1);
 469      }
 470  
 471      if (!$DB->setup_is_unicodedb()) {
 472          if (!$DB->change_db_encoding()) {
 473              // If could not convert successfully, throw error, and prevent installation
 474              cli_error(get_string('unicoderequired', 'admin'));
 475          }
 476      }
 477  
 478      if ($interactive) {
 479          cli_separator();
 480          cli_heading(get_string('databasesetup'));
 481      }
 482  
 483      // install core
 484      install_core($version, true);
 485      set_config('release', $release);
 486      set_config('branch', $branch);
 487  
 488      if (PHPUNIT_TEST) {
 489          // mark as test database as soon as possible
 490          set_config('phpunittest', 'na');
 491      }
 492  
 493      // install all plugins types, local, etc.
 494      upgrade_noncore(true);
 495  
 496      // set up admin user password
 497      $DB->set_field('user', 'password', hash_internal_user_password($options['adminpass']), array('username' => 'admin'));
 498  
 499      // Set the admin email address if specified.
 500      if (isset($options['adminemail'])) {
 501          $DB->set_field('user', 'email', $options['adminemail'], array('username' => 'admin'));
 502      }
 503  
 504      // rename admin username if needed
 505      if (isset($options['adminuser']) and $options['adminuser'] !== 'admin' and $options['adminuser'] !== 'guest') {
 506          $DB->set_field('user', 'username', $options['adminuser'], array('username' => 'admin'));
 507      }
 508  
 509      // Set the support email address if specified.
 510      if (isset($options['supportemail'])) {
 511          set_config('supportemail', $options['supportemail']);
 512      }
 513  
 514      // indicate that this site is fully configured
 515      set_config('rolesactive', 1);
 516      upgrade_finished();
 517  
 518      // log in as admin - we need do anything when applying defaults
 519      \core\session\manager::set_user(get_admin());
 520  
 521      // Apply all default settings.
 522      admin_apply_default_settings(NULL, true);
 523      set_config('registerauth', '');
 524  
 525      // set the site name
 526      if (isset($options['shortname']) and $options['shortname'] !== '') {
 527          $DB->set_field('course', 'shortname', $options['shortname'], array('format' => 'site'));
 528      }
 529      if (isset($options['fullname']) and $options['fullname'] !== '') {
 530          $DB->set_field('course', 'fullname', $options['fullname'], array('format' => 'site'));
 531      }
 532      if (isset($options['summary'])) {
 533          $DB->set_field('course', 'summary', $options['summary'], array('format' => 'site'));
 534      }
 535  
 536      // Redirect to site registration on first login.
 537      set_config('registrationpending', 1);
 538  
 539      // Apply default preset, if it is defined in $CFG and has a valid value.
 540      if (!empty($CFG->setsitepresetduringinstall)) {
 541          \core_adminpresets\helper::change_default_preset($CFG->setsitepresetduringinstall);
 542      }
 543  }