c6cb423c187a757cf23a3ca2c03f568cb61d25e7
[moodle.git] / lib / installlib.php
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.
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/>.
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  */
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
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'];
62     list($wwwroot, $xtra) = explode('/install.php', $wwwroot);
64     return $wwwroot;
65 }
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);
75     if ($temp == '1' or strtolower($temp) == 'on') {
76         return true;
77     }
78     return false;
79 }
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     }
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;
101         }
102     }
103     @chmod($dataroot, $dirpermissions);
105     if (!is_writable($dataroot)) {
106         return false; // we can not continue
107     }
109     // now create the lang folder - we need it and it makes sure we can really write in dataroot
110     if (!is_dir("$dataroot/lang")) {
111         if (!mkdir("$dataroot/lang", $dirpermissions, true)) {
112             return false;
113         }
114     }
115     if (!is_writable("$dataroot/lang")) {
116         return false; // we can not continue
117     }
119     // finally just in case some broken .htaccess that prevents access just in case it is allowed
120     if (!file_exists("$dataroot/.htaccess")) {
121         if ($handle = fopen("$dataroot/.htaccess", 'w')) {
122             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");
123             fclose($handle);
124         } else {
125             return false;
126         }
127     }
129     return true;
132 /**
133  * Print help button
134  * @param string $url
135  * @param string $titel
136  * @return void
137  */
138 function install_helpbutton($url, $title='') {
139     if ($title == '') {
140         $title = get_string('help');
141     }
142     echo "<a href=\"javascript:void(0)\" ";
143     echo "onclick=\"return window.open('$url','Help','menubar=0,location=0,scrollbars,resizable,width=500,height=400')\"";
144     echo ">";
145     echo "<img src=\"pix/help.gif\" class=\"iconhelp\" alt=\"$title\" title=\"$title\"/>";
146     echo "</a>\n";
149 /**
150  * This is in function because we want the /install.php to parse in PHP4
151  *
152  * @param object $database
153  * @param string $dbhsot
154  * @param string $dbuser
155  * @param string $dbpass
156  * @param string $dbname
157  * @param string $prefix
158  * @param mixed $dboptions
159  * @return string
160  */
161 function install_db_validate($database, $dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions) {
162     try {
163         try {
164             $database->connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
165         } catch (moodle_exception $e) {
166             // let's try to create new database
167             if ($database->create_database($dbhost, $dbuser, $dbpass, $dbname, $dboptions)) {
168                 $database->connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
169             } else {
170                 throw $e;
171             }
172         }
173         return '';
174     } catch (dml_exception $ex) {
175         return get_string($ex->errorcode, $ex->module, $ex->a).'<br />'.$ex->debuginfo;
176     }
179 /**
180  * Returns content of config.php file.
181  *
182  * Uses PHP_EOL for generating proper end of lines for the given platform.
183  *
184  * @param moodle_database $database database instance
185  * @param object $cfg copy of $CFG
186  * @return string
187  */
188 function install_generate_configphp($database, $cfg) {
189     $configphp = '<?php  // Moodle configuration file' . PHP_EOL . PHP_EOL;
191     $configphp .= 'unset($CFG);' . PHP_EOL;
192     $configphp .= 'global $CFG;' . PHP_EOL;
193     $configphp .= '$CFG = new stdClass();' . PHP_EOL . PHP_EOL; // prevent PHP5 strict warnings
195     $dbconfig = $database->export_dbconfig();
197     foreach ($dbconfig as $key=>$value) {
198         $key = str_pad($key, 9);
199         $configphp .= '$CFG->'.$key.' = '.var_export($value, true) . ';' . PHP_EOL;
200     }
201     $configphp .= PHP_EOL;
203     $configphp .= '$CFG->wwwroot   = '.var_export($cfg->wwwroot, true) . ';' . PHP_EOL ;
205     $configphp .= '$CFG->dataroot  = '.var_export($cfg->dataroot, true) . ';' . PHP_EOL;
207     $configphp .= '$CFG->admin     = '.var_export($cfg->admin, true) . ';' . PHP_EOL . PHP_EOL;
209     if (empty($cfg->directorypermissions)) {
210         $chmod = '02777';
211     } else {
212         $chmod = '0' . decoct($cfg->directorypermissions);
213     }
214     $configphp .= '$CFG->directorypermissions = ' . $chmod . ';' . PHP_EOL . PHP_EOL;
216     $configphp .= '$CFG->passwordsaltmain = '.var_export(complex_random_string(), true) . ';' . PHP_EOL . PHP_EOL;
218     $configphp .= 'require_once(dirname(__FILE__) . \'/lib/setup.php\');' . PHP_EOL . PHP_EOL;
219     $configphp .= '// There is no php closing tag in this file,' . PHP_EOL;
220     $configphp .= '// it is intentional because it prevents trailing whitespace problems!' . PHP_EOL;
222     return $configphp;
225 /**
226  * Prints complete help page used during installation.
227  * Does not return.
228  *
229  * @global object
230  * @param string $help
231  */
232 function install_print_help_page($help) {
233     global $CFG, $OUTPUT; //TODO: MUST NOT USE $OUTPUT HERE!!!
235     @header('Content-Type: text/html; charset=UTF-8');
236     @header('Cache-Control: no-store, no-cache, must-revalidate');
237     @header('Cache-Control: post-check=0, pre-check=0', false);
238     @header('Pragma: no-cache');
239     @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
240     @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
242     echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
243     echo '<html dir="'.(right_to_left() ? 'rtl' : 'ltr').'">
244           <head>
245           <link rel="shortcut icon" href="theme/standard/pix/favicon.ico" />
246           <link rel="stylesheet" type="text/css" href="'.$CFG->wwwroot.'/install/css.php" />
247           <title>'.get_string('installation','install').'</title>
248           <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
249           <meta http-equiv="pragma" content="no-cache" />
250           <meta http-equiv="expires" content="0" />';
252     echo '</head><body>';
253     switch ($help) {
254         case 'phpversionhelp':
255             print_string($help, 'install', phpversion());
256             break;
257         case 'memorylimithelp':
258             print_string($help, 'install', @ini_get('memory_limit'));
259             break;
260         default:
261             print_string($help, 'install');
262     }
263     echo $OUTPUT->close_window_button(); //TODO: MUST NOT USE $OUTPUT HERE!!!
264     echo '</body></html>';
265     die;
268 /**
269  * Prints installation page header, we can no use weblib yet in installer.
270  *
271  * @global object
272  * @param array $config
273  * @param string $stagename
274  * @param string $heading
275  * @param string $stagetext
276  * @return void
277  */
278 function install_print_header($config, $stagename, $heading, $stagetext) {
279     global $CFG;
281     @header('Content-Type: text/html; charset=UTF-8');
282     @header('Cache-Control: no-store, no-cache, must-revalidate');
283     @header('Cache-Control: post-check=0, pre-check=0', false);
284     @header('Pragma: no-cache');
285     @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
286     @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
288     echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
289     echo '<html dir="'.(right_to_left() ? 'rtl' : 'ltr').'">
290           <head>
291           <link rel="shortcut icon" href="theme/standard/pix/favicon.ico" />';
293     echo '<link rel="stylesheet" type="text/css" href="'.$CFG->wwwroot.'/install/css.php" />
294           <title>'.get_string('installation','install').' - Moodle '.$CFG->target_release.'</title>
295           <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
296           <meta http-equiv="pragma" content="no-cache" />
297           <meta http-equiv="expires" content="0" />';
299     echo '</head><body class="notloggedin">
300             <div id="page" class="stage'.$config->stage.'">
301                 <div id="page-header">
302                     <div id="header" class=" clearfix">
303                         <h1 class="headermain">'.get_string('installation','install').'</h1>
304                         <div class="headermenu">&nbsp;</div>
305                     </div>
306                     <div class="navbar clearfix">
307                         <div class="breadcrumb">
308                             <ul><li class="first">'.$stagename.'</li></ul>
309                         </div>
310                         <div class="navbutton">&nbsp;</div>
311                     </div>
312                 </div>
313           <!-- END OF HEADER -->
314           <div id="installdiv">';
316     echo '<h2>'.$heading.'</h2>';
318     if ($stagetext !== '') {
319         echo '<div class="stage generalbox box">';
320         echo $stagetext;
321         echo '</div>';
322     }
323     // main
324     echo '<form id="installform" method="post" action="install.php"><fieldset>';
325     foreach ($config as $name=>$value) {
326         echo '<input type="hidden" name="'.$name.'" value="'.s($value).'" />';
327     }
330 /**
331  * Prints installation page header, we can no use weblib yet in isntaller.
332  *
333  * @global object
334  * @param array $config
335  * @param bool $reload print reload button instead of next
336  * @return void
337  */
338 function install_print_footer($config, $reload=false) {
339     global $CFG;
341     if ($config->stage > INSTALL_WELCOME) {
342         $first = '<input type="submit" id="previousbutton" name="previous" value="&laquo; '.s(get_string('previous')).'" />';
343     } else {
344         $first = '<input type="submit" id="previousbutton" name="next" value="'.s(get_string('reload')).'" />';
345         $first .= '<script type="text/javascript">
346 //<![CDATA[
347     var first = document.getElementById("previousbutton");
348     first.style.visibility = "hidden";
349 //]]>
350 </script>
351 ';
352     }
354     if ($reload) {
355         $next = '<input type="submit" id="nextbutton" name="next" value="'.s(get_string('reload')).'" />';
356     } else {
357         $next = '<input type="submit" id="nextbutton" name="next" value="'.s(get_string('next')).' &raquo;" />';
358     }
360     echo '</fieldset><fieldset id="nav_buttons">'.$first.$next.'</fieldset>';
362     $homelink  = '<div class="sitelink">'.
363        '<a title="Moodle '. $CFG->target_release .'" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">'.
364        '<img style="width:100px;height:30px" src="pix/moodlelogo.gif" alt="moodlelogo" /></a></div>';
366     echo '</form></div>';
367     echo '<div id="footer"><hr />'.$homelink.'</div>';
368     echo '</div></body></html>';
371 /**
372  * Install Moodle DB,
373  * config.php must exist, there must not be any tables in db yet.
374  *
375  * @param array $options adminpass is mandatory
376  * @param bool $interactive
377  * @return void
378  */
379 function install_cli_database(array $options, $interactive) {
380     global $CFG, $DB;
381     require_once($CFG->libdir.'/environmentlib.php');
382     require_once($CFG->libdir.'/upgradelib.php');
384     // show as much debug as possible
385     @error_reporting(1023);
386     @ini_set('display_errors', '1');
387     $CFG->debug = 38911;
388     $CFG->debugdisplay = true;
390     $CFG->version = '';
391     $CFG->release = '';
392     $version = null;
393     $release = null;
395     // read $version and $release
396     require($CFG->dirroot.'/version.php');
398     if ($DB->get_tables() ) {
399         cli_error(get_string('clitablesexist', 'install'));
400     }
402     if (empty($options['adminpass'])) {
403         cli_error('Missing required admin password');
404     }
406     // test environment first
407     list($envstatus, $environment_results) = check_moodle_environment(normalize_version($release), ENV_SELECT_RELEASE);
408     if (!$envstatus) {
409         $errors = environment_get_errors($environment_results);
410         cli_heading(get_string('environment', 'admin'));
411         foreach ($errors as $error) {
412             list($info, $report) = $error;
413             echo "!! $info !!\n$report\n\n";
414         }
415         exit(1);
416     }
418     if (!$DB->setup_is_unicodedb()) {
419         if (!$DB->change_db_encoding()) {
420             // If could not convert successfully, throw error, and prevent installation
421             cli_error(get_string('unicoderequired', 'admin'));
422         }
423     }
425     if ($interactive) {
426         cli_separator();
427         cli_heading(get_string('databasesetup'));
428     }
430     // install core
431     install_core($version, true);
432     set_config('release', $release);
434     // install all plugins types, local, etc.
435     upgrade_noncore(true);
437     // set up admin user password
438     $DB->set_field('user', 'password', hash_internal_user_password($options['adminpass']), array('username' => 'admin'));
440     // rename admin username if needed
441     if (isset($options['adminuser']) and $options['adminuser'] !== 'admin' and $options['adminuser'] !== 'guest') {
442         $DB->set_field('user', 'username', $options['adminuser'], array('username' => 'admin'));
443     }
445     // indicate that this site is fully configured
446     set_config('rolesactive', 1);
447     upgrade_finished();
449     // log in as admin - we need do anything when applying defaults
450     $admins = get_admins();
451     $admin = reset($admins);
452     session_set_user($admin);
454     // apply all default settings, do it twice to fill all defaults - some settings depend on other setting
455     admin_apply_default_settings(NULL, true);
456     admin_apply_default_settings(NULL, true);
457     set_config('registerauth', '');
459     // set the site name
460     if (isset($options['shortname']) and $options['shortname'] !== '') {
461         $DB->set_field('course', 'shortname', $options['shortname'], array('format' => 'site'));
462     }
463     if (isset($options['fullname']) and $options['fullname'] !== '') {
464         $DB->set_field('course', 'fullname', $options['fullname'], array('format' => 'site'));
465     }