Merge branch 'MDL-37858_master' of git://github.com/dmonllao/moodle
[moodle.git] / lib / installlib.php
blob30e129770f19abe73151e778eb5e0c62fa5cbfc4
1 <?php
3 // This file is part of Moodle - http://moodle.org/
4 //
5 // Moodle is free software: you can redistribute it and/or modify
6 // it under the terms of the GNU General Public License as published by
7 // the Free Software Foundation, either version 3 of the License, or
8 // (at your option) any later version.
9 //
10 // Moodle is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 // GNU General Public License for more details.
15 // You should have received a copy of the GNU General Public License
16 // along with Moodle. If not, see <http://www.gnu.org/licenses/>.
18 /**
19 * Functions to support installation process
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
27 defined('MOODLE_INTERNAL') || die();
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);
44 /**
45 * Tries to detect the right www root setting.
46 * @return string detected www root
48 function install_guess_wwwroot() {
49 $wwwroot = '';
50 if (empty($_SERVER['HTTPS']) or $_SERVER['HTTPS'] == 'off') {
51 $wwwroot .= 'http://';
52 } else {
53 $wwwroot .= 'https://';
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'];
60 $wwwroot .= $_SERVER['SCRIPT_NAME'];
62 list($wwwroot, $xtra) = explode('/install.php', $wwwroot);
64 return $wwwroot;
67 /**
68 * Copy of @see{ini_get_bool()}
69 * @param string $ini_get_arg
70 * @return bool
72 function install_ini_get_bool($ini_get_arg) {
73 $temp = ini_get($ini_get_arg);
75 if ($temp == '1' or strtolower($temp) == 'on') {
76 return true;
78 return false;
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.
86 * @param string $dataroot full path to dataroot
87 * @param int $dirpermissions
88 * @return bool success
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;
96 umask(0000);
97 if (!file_exists($dataroot)) {
98 if (!mkdir($dataroot, $dirpermissions, true)) {
99 // most probably this does not work, but anyway
100 return false;
103 @chmod($dataroot, $dirpermissions);
105 if (!is_writable($dataroot)) {
106 return false; // we can not continue
109 // create the directory for $CFG->tempdir
110 if (!is_dir("$dataroot/temp")) {
111 if (!mkdir("$dataroot/temp", $dirpermissions, true)) {
112 return false;
115 if (!is_writable("$dataroot/temp")) {
116 return false; // we can not continue
119 // create the directory for $CFG->cachedir
120 if (!is_dir("$dataroot/cache")) {
121 if (!mkdir("$dataroot/cache", $dirpermissions, true)) {
122 return false;
125 if (!is_writable("$dataroot/cache")) {
126 return false; // we can not continue
129 // create the directory for $CFG->langotherroot
130 if (!is_dir("$dataroot/lang")) {
131 if (!mkdir("$dataroot/lang", $dirpermissions, true)) {
132 return false;
135 if (!is_writable("$dataroot/lang")) {
136 return false; // we can not continue
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;
149 return true;
153 * Print help button
154 * @param string $url
155 * @param string $titel
156 * @return void
158 function install_helpbutton($url, $title='') {
159 if ($title == '') {
160 $title = get_string('help');
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";
170 * This is in function because we want the /install.php to parse in PHP4
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
181 function install_db_validate($database, $dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions) {
182 try {
183 try {
184 $database->connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
185 } catch (moodle_exception $e) {
186 // let's try to create new database
187 if ($database->create_database($dbhost, $dbuser, $dbpass, $dbname, $dboptions)) {
188 $database->connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
189 } else {
190 throw $e;
193 return '';
194 } catch (dml_exception $ex) {
195 return get_string($ex->errorcode, $ex->module, $ex->a).'<br />'.$ex->debuginfo;
200 * Returns content of config.php file.
202 * Uses PHP_EOL for generating proper end of lines for the given platform.
204 * @param moodle_database $database database instance
205 * @param object $cfg copy of $CFG
206 * @return string
208 function install_generate_configphp($database, $cfg) {
209 $configphp = '<?php // Moodle configuration file' . PHP_EOL . PHP_EOL;
211 $configphp .= 'unset($CFG);' . PHP_EOL;
212 $configphp .= 'global $CFG;' . PHP_EOL;
213 $configphp .= '$CFG = new stdClass();' . PHP_EOL . PHP_EOL; // prevent PHP5 strict warnings
215 $dbconfig = $database->export_dbconfig();
217 foreach ($dbconfig as $key=>$value) {
218 $key = str_pad($key, 9);
219 $configphp .= '$CFG->'.$key.' = '.var_export($value, true) . ';' . PHP_EOL;
221 $configphp .= PHP_EOL;
223 $configphp .= '$CFG->wwwroot = '.var_export($cfg->wwwroot, true) . ';' . PHP_EOL ;
225 $configphp .= '$CFG->dataroot = '.var_export($cfg->dataroot, true) . ';' . PHP_EOL;
227 $configphp .= '$CFG->admin = '.var_export($cfg->admin, true) . ';' . PHP_EOL . PHP_EOL;
229 if (empty($cfg->directorypermissions)) {
230 $chmod = '02777';
231 } else {
232 $chmod = '0' . decoct($cfg->directorypermissions);
234 $configphp .= '$CFG->directorypermissions = ' . $chmod . ';' . PHP_EOL . PHP_EOL;
236 // A site-wide salt is only needed if bcrypt is not properly supported by the current version of PHP.
237 if (password_compat_not_supported()) {
238 $configphp .= '$CFG->passwordsaltmain = '.var_export(complex_random_string(), true) . ';' . PHP_EOL . PHP_EOL;
241 $configphp .= 'require_once(dirname(__FILE__) . \'/lib/setup.php\');' . PHP_EOL . PHP_EOL;
242 $configphp .= '// There is no php closing tag in this file,' . PHP_EOL;
243 $configphp .= '// it is intentional because it prevents trailing whitespace problems!' . PHP_EOL;
245 return $configphp;
249 * Prints complete help page used during installation.
250 * Does not return.
252 * @global object
253 * @param string $help
255 function install_print_help_page($help) {
256 global $CFG, $OUTPUT; //TODO: MUST NOT USE $OUTPUT HERE!!!
258 @header('Content-Type: text/html; charset=UTF-8');
259 @header('X-UA-Compatible: IE=edge');
260 @header('Cache-Control: no-store, no-cache, must-revalidate');
261 @header('Cache-Control: post-check=0, pre-check=0', false);
262 @header('Pragma: no-cache');
263 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
264 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
266 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
267 echo '<html dir="'.(right_to_left() ? 'rtl' : 'ltr').'">
268 <head>
269 <link rel="shortcut icon" href="theme/standard/pix/favicon.ico" />
270 <link rel="stylesheet" type="text/css" href="'.$CFG->wwwroot.'/install/css.php" />
271 <title>'.get_string('installation','install').'</title>
272 <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
273 <meta http-equiv="pragma" content="no-cache" />
274 <meta http-equiv="expires" content="0" />';
276 echo '</head><body>';
277 switch ($help) {
278 case 'phpversionhelp':
279 print_string($help, 'install', phpversion());
280 break;
281 case 'memorylimithelp':
282 print_string($help, 'install', @ini_get('memory_limit'));
283 break;
284 default:
285 print_string($help, 'install');
287 echo $OUTPUT->close_window_button(); //TODO: MUST NOT USE $OUTPUT HERE!!!
288 echo '</body></html>';
289 die;
293 * Prints installation page header, we can no use weblib yet in installer.
295 * @global object
296 * @param array $config
297 * @param string $stagename
298 * @param string $heading
299 * @param string $stagetext
300 * @return void
302 function install_print_header($config, $stagename, $heading, $stagetext) {
303 global $CFG;
305 @header('Content-Type: text/html; charset=UTF-8');
306 @header('X-UA-Compatible: IE=edge');
307 @header('Cache-Control: no-store, no-cache, must-revalidate');
308 @header('Cache-Control: post-check=0, pre-check=0', false);
309 @header('Pragma: no-cache');
310 @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
311 @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
313 echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
314 echo '<html dir="'.(right_to_left() ? 'rtl' : 'ltr').'">
315 <head>
316 <link rel="shortcut icon" href="theme/standard/pix/favicon.ico" />';
318 echo '<link rel="stylesheet" type="text/css" href="'.$CFG->wwwroot.'/install/css.php" />
319 <title>'.get_string('installation','install').' - Moodle '.$CFG->target_release.'</title>
320 <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
321 <meta http-equiv="pragma" content="no-cache" />
322 <meta http-equiv="expires" content="0" />';
324 echo '</head><body class="notloggedin">
325 <div id="page" class="stage'.$config->stage.'">
326 <div id="page-header">
327 <div id="header" class=" clearfix">
328 <h1 class="headermain">'.get_string('installation','install').'</h1>
329 <div class="headermenu">&nbsp;</div>
330 </div>
331 <div class="navbar clearfix">
332 <div class="breadcrumb">
333 <ul><li class="first">'.$stagename.'</li></ul>
334 </div>
335 <div class="navbutton">&nbsp;</div>
336 </div>
337 </div>
338 <!-- END OF HEADER -->
339 <div id="installdiv">';
341 echo '<h2>'.$heading.'</h2>';
343 if ($stagetext !== '') {
344 echo '<div class="stage generalbox box">';
345 echo $stagetext;
346 echo '</div>';
348 // main
349 echo '<form id="installform" method="post" action="install.php"><fieldset>';
350 foreach ($config as $name=>$value) {
351 echo '<input type="hidden" name="'.$name.'" value="'.s($value).'" />';
356 * Prints installation page header, we can no use weblib yet in isntaller.
358 * @global object
359 * @param array $config
360 * @param bool $reload print reload button instead of next
361 * @return void
363 function install_print_footer($config, $reload=false) {
364 global $CFG;
366 if ($config->stage > INSTALL_WELCOME) {
367 $first = '<input type="submit" id="previousbutton" name="previous" value="&laquo; '.s(get_string('previous')).'" />';
368 } else {
369 $first = '<input type="submit" id="previousbutton" name="next" value="'.s(get_string('reload')).'" />';
370 $first .= '<script type="text/javascript">
371 //<![CDATA[
372 var first = document.getElementById("previousbutton");
373 first.style.visibility = "hidden";
374 //]]>
375 </script>
379 if ($reload) {
380 $next = '<input type="submit" id="nextbutton" name="next" value="'.s(get_string('reload')).'" />';
381 } else {
382 $next = '<input type="submit" id="nextbutton" name="next" value="'.s(get_string('next')).' &raquo;" />';
385 echo '</fieldset><fieldset id="nav_buttons">'.$first.$next.'</fieldset>';
387 $homelink = '<div class="sitelink">'.
388 '<a title="Moodle '. $CFG->target_release .'" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">'.
389 '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
391 echo '</form></div>';
392 echo '<div id="footer"><hr />'.$homelink.'</div>';
393 echo '</div></body></html>';
397 * Install Moodle DB,
398 * config.php must exist, there must not be any tables in db yet.
400 * @param array $options adminpass is mandatory
401 * @param bool $interactive
402 * @return void
404 function install_cli_database(array $options, $interactive) {
405 global $CFG, $DB;
406 require_once($CFG->libdir.'/environmentlib.php');
407 require_once($CFG->libdir.'/upgradelib.php');
409 // show as much debug as possible
410 @error_reporting(E_ALL | E_STRICT);
411 @ini_set('display_errors', '1');
412 $CFG->debug = (E_ALL | E_STRICT);
413 $CFG->debugdisplay = true;
415 $CFG->version = '';
416 $CFG->release = '';
417 $CFG->branch = '';
419 $version = null;
420 $release = null;
421 $branch = null;
423 // read $version and $release
424 require($CFG->dirroot.'/version.php');
426 if ($DB->get_tables() ) {
427 cli_error(get_string('clitablesexist', 'install'));
430 if (empty($options['adminpass'])) {
431 cli_error('Missing required admin password');
434 // test environment first
435 list($envstatus, $environment_results) = check_moodle_environment(normalize_version($release), ENV_SELECT_RELEASE);
436 if (!$envstatus) {
437 $errors = environment_get_errors($environment_results);
438 cli_heading(get_string('environment', 'admin'));
439 foreach ($errors as $error) {
440 list($info, $report) = $error;
441 echo "!! $info !!\n$report\n\n";
443 exit(1);
446 if (!$DB->setup_is_unicodedb()) {
447 if (!$DB->change_db_encoding()) {
448 // If could not convert successfully, throw error, and prevent installation
449 cli_error(get_string('unicoderequired', 'admin'));
453 if ($interactive) {
454 cli_separator();
455 cli_heading(get_string('databasesetup'));
458 // install core
459 install_core($version, true);
460 set_config('release', $release);
461 set_config('branch', $branch);
463 if (PHPUNIT_TEST) {
464 // mark as test database as soon as possible
465 set_config('phpunittest', 'na');
468 // install all plugins types, local, etc.
469 upgrade_noncore(true);
471 // set up admin user password
472 $DB->set_field('user', 'password', hash_internal_user_password($options['adminpass']), array('username' => 'admin'));
474 // rename admin username if needed
475 if (isset($options['adminuser']) and $options['adminuser'] !== 'admin' and $options['adminuser'] !== 'guest') {
476 $DB->set_field('user', 'username', $options['adminuser'], array('username' => 'admin'));
479 // indicate that this site is fully configured
480 set_config('rolesactive', 1);
481 upgrade_finished();
483 // log in as admin - we need do anything when applying defaults
484 session_set_user(get_admin());
486 // apply all default settings, do it twice to fill all defaults - some settings depend on other setting
487 admin_apply_default_settings(NULL, true);
488 admin_apply_default_settings(NULL, true);
489 set_config('registerauth', '');
491 // set the site name
492 if (isset($options['shortname']) and $options['shortname'] !== '') {
493 $DB->set_field('course', 'shortname', $options['shortname'], array('format' => 'site'));
495 if (isset($options['fullname']) and $options['fullname'] !== '') {
496 $DB->set_field('course', 'fullname', $options['fullname'], array('format' => 'site'));