Proyectos de Subversion Moodle

Rev

Rev 1 | | Comparar con el anterior | Ultima modificación | Ver Log |

Rev Autor Línea Nro. Línea
1 efrain 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
 * This is in function because we want the /install.php to parse in PHP4
154
 *
155
 * @param object $database
156
 * @param string $dbhsot
157
 * @param string $dbuser
158
 * @param string $dbpass
159
 * @param string $dbname
160
 * @param string $prefix
161
 * @param mixed $dboptions
162
 * @return string
163
 */
164
function install_db_validate($database, $dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions) {
165
    if (!preg_match('/^[a-z_]*$/', $prefix)) {
166
        return get_string('invaliddbprefix', 'install');
167
    }
168
    try {
169
        try {
170
            $database->connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
171
        } catch (moodle_exception $e) {
172
            // let's try to create new database
173
            if ($database->create_database($dbhost, $dbuser, $dbpass, $dbname, $dboptions)) {
174
                $database->connect($dbhost, $dbuser, $dbpass, $dbname, $prefix, $dboptions);
175
            } else {
176
                throw $e;
177
            }
178
        }
179
        return '';
180
    } catch (dml_exception $ex) {
181
        $stringmanager = get_string_manager();
182
        $errorstring = $ex->errorcode.'oninstall';
183
        $legacystring = $ex->errorcode;
184
        if ($stringmanager->string_exists($errorstring, $ex->module)) {
185
            // By using a different string id from the error code we are separating exception handling and output.
186
            $returnstring = $stringmanager->get_string($errorstring, $ex->module, $ex->a);
187
            if ($ex->debuginfo) {
188
                $returnstring .= '<br />'.$ex->debuginfo;
189
            }
190
 
191
            return $returnstring;
192
        } else if ($stringmanager->string_exists($legacystring, $ex->module)) {
193
            // There are some DML exceptions that may be thrown here as well as during normal operation.
194
            // If we have a translated message already we still want to serve it here.
195
            // However it is not the preferred way.
196
            $returnstring = $stringmanager->get_string($legacystring, $ex->module, $ex->a);
197
            if ($ex->debuginfo) {
198
                $returnstring .= '<br />'.$ex->debuginfo;
199
            }
200
 
201
            return $returnstring;
202
        }
203
        // No specific translation. Deliver a generic error message.
204
        return $stringmanager->get_string('dmlexceptiononinstall', 'error', $ex);
205
    }
206
}
207
 
208
/**
209
 * Returns content of config.php file.
210
 *
211
 * Uses PHP_EOL for generating proper end of lines for the given platform.
212
 *
213
 * @param moodle_database $database database instance
214
 * @param object $cfg copy of $CFG
215
 * @return string
216
 */
217
function install_generate_configphp($database, $cfg) {
218
    $configphp = '<?php  // Moodle configuration file' . PHP_EOL . PHP_EOL;
219
 
220
    $configphp .= 'unset($CFG);' . PHP_EOL;
221
    $configphp .= 'global $CFG;' . PHP_EOL;
222
    $configphp .= '$CFG = new stdClass();' . PHP_EOL . PHP_EOL; // prevent PHP5 strict warnings
223
 
224
    $dbconfig = $database->export_dbconfig();
225
 
226
    foreach ($dbconfig as $key=>$value) {
227
        $key = str_pad($key, 9);
228
        $configphp .= '$CFG->'.$key.' = '.var_export($value, true) . ';' . PHP_EOL;
229
    }
230
    $configphp .= PHP_EOL;
231
 
232
    $configphp .= '$CFG->wwwroot   = '.var_export($cfg->wwwroot, true) . ';' . PHP_EOL ;
233
 
234
    $configphp .= '$CFG->dataroot  = '.var_export($cfg->dataroot, true) . ';' . PHP_EOL;
235
 
236
    $configphp .= '$CFG->admin     = '.var_export($cfg->admin, true) . ';' . PHP_EOL . PHP_EOL;
237
 
238
    if (empty($cfg->directorypermissions)) {
239
        $chmod = '02777';
240
    } else {
241
        $chmod = '0' . decoct($cfg->directorypermissions);
242
    }
243
    $configphp .= '$CFG->directorypermissions = ' . $chmod . ';' . PHP_EOL . PHP_EOL;
244
 
245
    if (isset($cfg->upgradekey) and $cfg->upgradekey !== '') {
246
        $configphp .= '$CFG->upgradekey = ' . var_export($cfg->upgradekey, true) . ';' . PHP_EOL . PHP_EOL;
247
    }
248
 
249
    if (isset($cfg->setsitepresetduringinstall) and $cfg->setsitepresetduringinstall !== '') {
250
        $configphp .= '$CFG->setsitepresetduringinstall = ' . var_export($cfg->setsitepresetduringinstall, true) .
251
            ';' . PHP_EOL . PHP_EOL;
252
    }
253
 
254
    $configphp .= 'require_once(__DIR__ . \'/lib/setup.php\');' . PHP_EOL . PHP_EOL;
255
    $configphp .= '// There is no php closing tag in this file,' . PHP_EOL;
256
    $configphp .= '// it is intentional because it prevents trailing whitespace problems!' . PHP_EOL;
257
 
258
    return $configphp;
259
}
260
 
261
/**
262
 * Prints installation page header, we can not use weblib yet in installer.
263
 *
264
 * @global object
265
 * @param stdClass $config
266
 * @param string $stagename
267
 * @param string $heading
268
 * @param string $stagetext
269
 * @param string $stageclass
270
 * @return void
271
 */
272
function install_print_header($config, $stagename, $heading, $stagetext, $stageclass = "alert-info") {
273
    global $CFG;
274
 
275
    @header('Content-Type: text/html; charset=UTF-8');
276
    @header('X-UA-Compatible: IE=edge');
277
    @header('Cache-Control: no-store, no-cache, must-revalidate');
278
    @header('Cache-Control: post-check=0, pre-check=0', false);
279
    @header('Pragma: no-cache');
280
    @header('Expires: Mon, 20 Aug 1969 09:23:00 GMT');
281
    @header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
282
 
283
    echo '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';
284
    echo '<html dir="'.(right_to_left() ? 'rtl' : 'ltr').'">
285
          <head>
286
          <link rel="shortcut icon" href="theme/clean/pix/favicon.ico" />';
287
 
288
    echo '<link rel="stylesheet" type="text/css" href="'.$CFG->wwwroot.'/install/css.php" />
289
          <title>'.get_string('installation', 'install') . moodle_page::TITLE_SEPARATOR . 'Moodle '.$CFG->target_release.'</title>
290
          <meta name="robots" content="noindex">
291
          <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
292
          <meta http-equiv="pragma" content="no-cache" />
293
          <meta http-equiv="expires" content="0" />';
294
 
295
    echo '</head><body class="notloggedin">
296
            <div id="page" class="mt-0 container stage'.$config->stage.'">
297
                <div id="page-header">
298
                    <div id="header" class=" clearfix">
299
                        <h1 class="headermain">'.get_string('installation','install').'</h1>
300
                        <div class="headermenu">&nbsp;</div>
301
                    </div>
302
                    <div class="bg-light p-3 mb-3"><h3 class="m-0">'.$stagename.'</h3></div>
303
                </div>
304
          <!-- END OF HEADER -->
305
          <div id="installdiv">';
306
 
307
    echo '<h2>'.$heading.'</h2>';
308
 
309
    if ($stagetext !== '') {
310
        echo '<div class="alert ' . $stageclass . '">';
311
        echo $stagetext;
312
        echo '</div>';
313
    }
314
    // main
315
    echo '<form id="installform" method="post" action="install.php"><fieldset>';
316
    foreach ($config as $name=>$value) {
317
        echo '<input type="hidden" name="'.$name.'" value="'.s($value).'" />';
318
    }
319
}
320
 
321
/**
322
 * Prints installation page header, we can not use weblib yet in installer.
323
 *
324
 * @global object
325
 * @param stdClass $config
326
 * @param bool $reload print reload button instead of next
327
 * @return void
328
 */
329
function install_print_footer($config, $reload=false) {
330
    global $CFG;
331
 
332
    if ($config->stage > INSTALL_WELCOME) {
1441 ariadna 333
        $first = '<input type="submit" id="previousbutton" class="btn btn-secondary flex-grow-0 ms-auto" name="previous" value="&laquo; '.s(get_string('previous')).'" />';
1 efrain 334
    } else {
1441 ariadna 335
        $first = '<input type="submit" id="previousbutton" class="btn btn-secondary flex-grow-0  ms-auto" name="next" value="'.s(get_string('reload')).'" />';
1 efrain 336
        $first .= '<script type="text/javascript">
337
//<![CDATA[
338
    var first = document.getElementById("previousbutton");
339
    first.style.visibility = "hidden";
340
//]]>
341
</script>
342
';
343
    }
344
 
345
    if ($reload) {
1441 ariadna 346
        $next = '<input type="submit" id="nextbutton" class="btn btn-primary ms-1 flex-grow-0 me-auto" name="next" value="'.s(get_string('reload')).'" />';
1 efrain 347
    } else {
1441 ariadna 348
        $next = '<input type="submit" id="nextbutton" class="btn btn-primary ms-1 flex-grow-0 me-auto" name="next" value="'.s(get_string('next')).' &raquo;" />';
1 efrain 349
    }
350
 
351
    echo '</fieldset><div id="nav_buttons" class="mb-3 w-100 d-flex">'.$first.$next.'</div>';
352
 
353
    $homelink  = '<div class="sitelink">'.
354
       '<a title="Moodle '. $CFG->target_release .'" href="http://docs.moodle.org/en/Administrator_documentation" onclick="this.target=\'_blank\'">'.
355
       '<img src="pix/moodlelogo.png" alt="'.get_string('moodlelogo').'" /></a></div>';
356
 
357
    echo '</form></div>';
358
    echo '<div id="page-footer">'.$homelink.'</div>';
359
    echo '</div></body></html>';
360
}
361
 
362
/**
363
 * Install Moodle DB,
364
 * config.php must exist, there must not be any tables in db yet.
365
 *
366
 * @param array $options adminpass is mandatory
367
 * @param bool $interactive
368
 * @return void
369
 */
370
function install_cli_database(array $options, $interactive) {
371
    global $CFG, $DB;
372
    require_once($CFG->libdir.'/environmentlib.php');
373
    require_once($CFG->libdir.'/upgradelib.php');
374
 
375
    // show as much debug as possible
1441 ariadna 376
    @error_reporting(E_ALL);
1 efrain 377
    @ini_set('display_errors', '1');
1441 ariadna 378
    $CFG->debug = (E_ALL);
1 efrain 379
    $CFG->debugdisplay = true;
380
    $CFG->debugdeveloper = true;
381
 
382
    $CFG->version = '';
383
    $CFG->release = '';
384
    $CFG->branch = '';
385
 
386
    $version = null;
387
    $release = null;
388
    $branch = null;
389
 
390
    // read $version and $release
391
    require($CFG->dirroot.'/version.php');
392
 
393
    if ($DB->get_tables() ) {
394
        cli_error(get_string('clitablesexist', 'install'));
395
    }
396
 
397
    if (empty($options['adminpass'])) {
398
        cli_error('Missing required admin password');
399
    }
400
 
401
    // test environment first
402
    list($envstatus, $environment_results) = check_moodle_environment(normalize_version($release), ENV_SELECT_RELEASE);
403
    if (!$envstatus) {
404
        $errors = environment_get_errors($environment_results);
405
        cli_heading(get_string('environment', 'admin'));
406
        foreach ($errors as $error) {
407
            list($info, $report) = $error;
408
            echo "!! $info !!\n$report\n\n";
409
        }
410
        exit(1);
411
    }
412
 
413
    if (!$DB->setup_is_unicodedb()) {
414
        if (!$DB->change_db_encoding()) {
415
            // If could not convert successfully, throw error, and prevent installation
416
            cli_error(get_string('unicoderequired', 'admin'));
417
        }
418
    }
419
 
420
    if ($interactive) {
421
        cli_separator();
422
        cli_heading(get_string('databasesetup'));
423
    }
424
 
425
    // install core
426
    install_core($version, true);
427
    set_config('release', $release);
428
    set_config('branch', $branch);
429
 
430
    if (PHPUNIT_TEST) {
431
        // mark as test database as soon as possible
432
        set_config('phpunittest', 'na');
433
    }
434
 
435
    // install all plugins types, local, etc.
436
    upgrade_noncore(true);
437
 
438
    // set up admin user password
439
    $DB->set_field('user', 'password', hash_internal_user_password($options['adminpass']), array('username' => 'admin'));
440
 
441
    // Set the admin email address if specified.
442
    if (isset($options['adminemail'])) {
443
        $DB->set_field('user', 'email', $options['adminemail'], array('username' => 'admin'));
444
    }
445
 
446
    // rename admin username if needed
447
    if (isset($options['adminuser']) and $options['adminuser'] !== 'admin' and $options['adminuser'] !== 'guest') {
448
        $DB->set_field('user', 'username', $options['adminuser'], array('username' => 'admin'));
449
    }
450
 
451
    // Set the support email address if specified.
452
    if (!empty($options['supportemail'])) {
453
        set_config('supportemail', $options['supportemail']);
454
    } else if (!empty($options['adminemail'])) {
455
        set_config('supportemail', $options['adminemail']);
456
    }
457
 
458
    // indicate that this site is fully configured
459
    set_config('rolesactive', 1);
460
    upgrade_finished();
461
 
462
    // log in as admin - we need do anything when applying defaults
463
    \core\session\manager::set_user(get_admin());
464
 
465
    // Apply all default settings.
466
    admin_apply_default_settings(NULL, true);
467
    set_config('registerauth', '');
468
 
469
    // set the site name
470
    if (isset($options['shortname']) and $options['shortname'] !== '') {
471
        $DB->set_field('course', 'shortname', $options['shortname'], array('format' => 'site'));
472
    }
473
    if (isset($options['fullname']) and $options['fullname'] !== '') {
474
        $DB->set_field('course', 'fullname', $options['fullname'], array('format' => 'site'));
475
    }
476
    if (isset($options['summary'])) {
477
        $DB->set_field('course', 'summary', $options['summary'], array('format' => 'site'));
478
    }
479
 
480
    // Redirect to site registration on first login.
481
    set_config('registrationpending', 1);
482
 
483
    // Apply default preset, if it is defined in $CFG and has a valid value.
484
    if (!empty($CFG->setsitepresetduringinstall)) {
485
        \core_adminpresets\helper::change_default_preset($CFG->setsitepresetduringinstall);
486
    }
487
}