source: moodle/trunk/fuentes/admin/index.php @ 136

Last change on this file since 136 was 136, checked in by mabarracus, 3 years ago

Ported code to xenial

File size: 22.7 KB
Line 
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
27if (!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
33if (version_compare(phpversion(), '5.4.4') < 0) {
34    $phpversion = phpversion();
35    // do NOT localise - lang strings would not work here and we CAN NOT move it to later place
36    echo "Moodle 2.7 or later requires at least PHP 5.4.4 (currently using version $phpversion).<br />";
37    echo "Please upgrade your server software or install older Moodle version.";
38    die();
39}
40
41// make sure iconv is available and actually works
42if (!function_exists('iconv')) {
43    // this should not happen, this must be very borked install
44    echo 'Moodle requires the iconv PHP extension. Please install or enable the iconv extension.';
45    die();
46}
47
48// Make sure php5-json is available.
49if (!function_exists('json_encode') || !function_exists('json_decode')) {
50    // This also shouldn't happen.
51    echo 'Moodle requires the json PHP extension. Please install or enable the json extension.';
52    die();
53}
54
55define('NO_OUTPUT_BUFFERING', true);
56
57if ((isset($_GET['cache']) and $_GET['cache'] === '0')
58        or (isset($_POST['cache']) and $_POST['cache'] === '0')
59        or (!isset($_POST['cache']) and !isset($_GET['cache']) and empty($_GET['sesskey']) and empty($_POST['sesskey']))) {
60    // Prevent caching at all cost when visiting this page directly,
61    // we redirect to self once we known no upgrades are necessary.
62    // Note: $_GET and $_POST are used here intentionally because our param cleaning is not loaded yet.
63    // Note2: the sesskey is present in all block editing hacks, we can not redirect there, so enable caching.
64    define('CACHE_DISABLE_ALL', true);
65
66    // Force OPcache reset if used, we do not want any stale caches
67    // when detecting if upgrade necessary or when running upgrade.
68    if (function_exists('opcache_reset')) {
69        opcache_reset();
70    }
71    $cache = 0;
72
73} else {
74    $cache = 1;
75}
76
77require('../config.php');
78
79// Invalidate the cache of version.php in any circumstances to help core_component
80// detecting if the version has changed and component cache should be reset.
81if (function_exists('opcache_invalidate')) {
82    opcache_invalidate($CFG->dirroot . '/version.php', true);
83}
84// Make sure the component cache gets rebuilt if necessary, any method that
85// indirectly calls the protected init() method is good here.
86core_component::get_core_subsystems();
87
88require_once($CFG->libdir.'/adminlib.php');    // various admin-only functions
89require_once($CFG->libdir.'/upgradelib.php');  // general upgrade/install related functions
90
91$id             = optional_param('id', '', PARAM_TEXT);
92$confirmupgrade = optional_param('confirmupgrade', 0, PARAM_BOOL);
93$confirmrelease = optional_param('confirmrelease', 0, PARAM_BOOL);
94$confirmplugins = optional_param('confirmplugincheck', 0, PARAM_BOOL);
95$showallplugins = optional_param('showallplugins', 0, PARAM_BOOL);
96$agreelicense   = optional_param('agreelicense', 0, PARAM_BOOL);
97$fetchupdates   = optional_param('fetchupdates', 0, PARAM_BOOL);
98$newaddonreq    = optional_param('installaddonrequest', null, PARAM_RAW);
99
100// Set up PAGE.
101$url = new moodle_url('/admin/index.php');
102$url->param('cache', $cache);
103$PAGE->set_url($url);
104unset($url);
105
106// Are we returning from an add-on installation request at moodle.org/plugins?
107if ($newaddonreq and !$cache and empty($CFG->disableonclickaddoninstall)) {
108    $target = new moodle_url('/admin/tool/installaddon/index.php', array(
109        'installaddonrequest' => $newaddonreq,
110        'confirm' => 0));
111    if (!isloggedin() or isguestuser()) {
112        // Login and go the the add-on tool page.
113        $SESSION->wantsurl = $target->out();
114        redirect(get_login_url());
115    }
116    redirect($target);
117}
118
119$PAGE->set_pagelayout('admin'); // Set a default pagelayout
120
121$documentationlink = '<a href="http://docs.moodle.org/en/Installation">Installation docs</a>';
122
123// Check some PHP server settings
124
125if (ini_get_bool('session.auto_start')) {
126    print_error('phpvaroff', 'debug', '', (object)array('name'=>'session.auto_start', 'link'=>$documentationlink));
127}
128
129if (!ini_get_bool('file_uploads')) {
130    print_error('phpvaron', 'debug', '', (object)array('name'=>'file_uploads', 'link'=>$documentationlink));
131}
132
133if (is_float_problem()) {
134    print_error('phpfloatproblem', 'admin', '', $documentationlink);
135}
136
137// Set some necessary variables during set-up to avoid PHP warnings later on this page
138if (!isset($CFG->release)) {
139    $CFG->release = '';
140}
141if (!isset($CFG->version)) {
142    $CFG->version = '';
143}
144if (!isset($CFG->branch)) {
145    $CFG->branch = '';
146}
147
148$version = null;
149$release = null;
150$branch = null;
151require("$CFG->dirroot/version.php");       // defines $version, $release, $branch and $maturity
152$CFG->target_release = $release;            // used during installation and upgrades
153
154if (!$version or !$release) {
155    print_error('withoutversion', 'debug'); // without version, stop
156}
157
158if (!core_tables_exist()) {
159    $PAGE->set_pagelayout('maintenance');
160    $PAGE->set_popup_notification_allowed(false);
161
162    // fake some settings
163    $CFG->docroot = 'http://docs.moodle.org';
164
165    $strinstallation = get_string('installation', 'install');
166
167    // remove current session content completely
168    \core\session\manager::terminate_current();
169
170    if (empty($agreelicense)) {
171        $strlicense = get_string('license');
172
173        $PAGE->navbar->add($strlicense);
174        $PAGE->set_title($strinstallation.' - Moodle '.$CFG->target_release);
175        $PAGE->set_heading($strinstallation);
176        $PAGE->set_cacheable(false);
177
178        /** @var core_admin_renderer $output */
179        $output = $PAGE->get_renderer('core', 'admin');
180        echo $output->install_licence_page();
181        die();
182    }
183    if (empty($confirmrelease)) {
184        require_once($CFG->libdir.'/environmentlib.php');
185        list($envstatus, $environment_results) = check_moodle_environment(normalize_version($release), ENV_SELECT_RELEASE);
186        $strcurrentrelease = get_string('currentrelease');
187
188        $PAGE->navbar->add($strcurrentrelease);
189        $PAGE->set_title($strinstallation);
190        $PAGE->set_heading($strinstallation . ' - Moodle ' . $CFG->target_release);
191        $PAGE->set_cacheable(false);
192
193        /** @var core_admin_renderer $output */
194        $output = $PAGE->get_renderer('core', 'admin');
195        echo $output->install_environment_page($maturity, $envstatus, $environment_results, $release);
196        die();
197    }
198
199    // check plugin dependencies
200    $failed = array();
201    if (!core_plugin_manager::instance()->all_plugins_ok($version, $failed)) {
202        $PAGE->navbar->add(get_string('pluginscheck', 'admin'));
203        $PAGE->set_title($strinstallation);
204        $PAGE->set_heading($strinstallation . ' - Moodle ' . $CFG->target_release);
205
206        $output = $PAGE->get_renderer('core', 'admin');
207        $url = new moodle_url('/admin/index.php', array('agreelicense' => 1, 'confirmrelease' => 1, 'lang' => $CFG->lang));
208        echo $output->unsatisfied_dependencies_page($version, $failed, $url);
209        die();
210    }
211    unset($failed);
212
213    //TODO: add a page with list of non-standard plugins here
214
215    $strdatabasesetup = get_string('databasesetup');
216    upgrade_init_javascript();
217
218    $PAGE->navbar->add($strdatabasesetup);
219    $PAGE->set_title($strinstallation.' - Moodle '.$CFG->target_release);
220    $PAGE->set_heading($strinstallation);
221    $PAGE->set_cacheable(false);
222
223    $output = $PAGE->get_renderer('core', 'admin');
224    echo $output->header();
225
226    if (!$DB->setup_is_unicodedb()) {
227        if (!$DB->change_db_encoding()) {
228            // If could not convert successfully, throw error, and prevent installation
229            print_error('unicoderequired', 'admin');
230        }
231    }
232
233    install_core($version, true);
234}
235
236
237// Check version of Moodle code on disk compared with database
238// and upgrade if possible.
239
240if (!$cache) {
241    // Do not try to do anything fancy in non-cached mode,
242    // this prevents themes from fetching data from non-existent tables.
243    $PAGE->set_pagelayout('maintenance');
244    $PAGE->set_popup_notification_allowed(false);
245}
246
247$stradministration = get_string('administration');
248$PAGE->set_context(context_system::instance());
249
250if (empty($CFG->version)) {
251    print_error('missingconfigversion', 'debug');
252}
253
254// Detect config cache inconsistency, this happens when you switch branches on dev servers.
255if ($CFG->version != $DB->get_field('config', 'value', array('name'=>'version'))) {
256    purge_all_caches();
257    redirect(new moodle_url('/admin/index.php'), 'Config cache inconsistency detected, resetting caches...');
258}
259
260if (!$cache and $version > $CFG->version) {  // upgrade
261
262    // Warning about upgrading a test site.
263    $testsite = false;
264    if (defined('BEHAT_SITE_RUNNING')) {
265        $testsite = 'behat';
266    }
267
268    // We purge all of MUC's caches here.
269    // Caches are disabled for upgrade by CACHE_DISABLE_ALL so we must set the first arg to true.
270    // This ensures a real config object is loaded and the stores will be purged.
271    // This is the only way we can purge custom caches such as memcache or APC.
272    // Note: all other calls to caches will still used the disabled API.
273    cache_helper::purge_all(true);
274    // We then purge the regular caches.
275    purge_all_caches();
276
277    /** @var core_admin_renderer $output */
278    $output = $PAGE->get_renderer('core', 'admin');
279
280    if (upgrade_stale_php_files_present()) {
281        $PAGE->set_title($stradministration);
282        $PAGE->set_cacheable(false);
283
284        echo $output->upgrade_stale_php_files_page();
285        die();
286    }
287
288    if (empty($confirmupgrade)) {
289        $a = new stdClass();
290        $a->oldversion = "$CFG->release (".sprintf('%.2f', $CFG->version).")";
291        $a->newversion = "$release (".sprintf('%.2f', $version).")";
292        $strdatabasechecking = get_string('databasechecking', '', $a);
293
294        $PAGE->set_title($stradministration);
295        $PAGE->set_heading($strdatabasechecking);
296        $PAGE->set_cacheable(false);
297
298        echo $output->upgrade_confirm_page($a->newversion, $maturity, $testsite);
299        die();
300
301    } else if (empty($confirmrelease)){
302        require_once($CFG->libdir.'/environmentlib.php');
303        list($envstatus, $environment_results) = check_moodle_environment($release, ENV_SELECT_RELEASE);
304        $strcurrentrelease = get_string('currentrelease');
305
306        $PAGE->navbar->add($strcurrentrelease);
307        $PAGE->set_title($strcurrentrelease);
308        $PAGE->set_heading($strcurrentrelease);
309        $PAGE->set_cacheable(false);
310
311        echo $output->upgrade_environment_page($release, $envstatus, $environment_results);
312        die();
313
314    } else if (empty($confirmplugins)) {
315        $strplugincheck = get_string('plugincheck');
316
317        $PAGE->navbar->add($strplugincheck);
318        $PAGE->set_title($strplugincheck);
319        $PAGE->set_heading($strplugincheck);
320        $PAGE->set_cacheable(false);
321
322        $reloadurl = new moodle_url('/admin/index.php', array('confirmupgrade' => 1, 'confirmrelease' => 1, 'cache' => 0));
323
324        if ($fetchupdates) {
325            // No sesskey support guaranteed here, because sessions might not work yet.
326            $updateschecker = \core\update\checker::instance();
327            if ($updateschecker->enabled()) {
328                $updateschecker->fetch();
329            }
330            redirect($reloadurl);
331        }
332
333        $deployer = \core\update\deployer::instance();
334        if ($deployer->enabled()) {
335            $deployer->initialize($reloadurl, $reloadurl);
336
337            $deploydata = $deployer->submitted_data();
338            if (!empty($deploydata)) {
339                // No sesskey support guaranteed here, because sessions might not work yet.
340                echo $output->upgrade_plugin_confirm_deploy_page($deployer, $deploydata);
341                die();
342            }
343        }
344
345        echo $output->upgrade_plugin_check_page(core_plugin_manager::instance(), \core\update\checker::instance(),
346                $version, $showallplugins, $reloadurl,
347                new moodle_url('/admin/index.php', array('confirmupgrade'=>1, 'confirmrelease'=>1, 'confirmplugincheck'=>1, 'cache'=>0)));
348        die();
349
350    } else {
351        // Always verify plugin dependencies!
352        $failed = array();
353        if (!core_plugin_manager::instance()->all_plugins_ok($version, $failed)) {
354            $reloadurl = new moodle_url('/admin/index.php', array('confirmupgrade' => 1, 'confirmrelease' => 1, 'cache' => 0));
355            echo $output->unsatisfied_dependencies_page($version, $failed, $reloadurl);
356            die();
357        }
358        unset($failed);
359
360        // Launch main upgrade.
361        upgrade_core($version, true);
362    }
363} else if ($version < $CFG->version) {
364    // better stop here, we can not continue with plugin upgrades or anything else
365    throw new moodle_exception('downgradedcore', 'error', new moodle_url('/admin/'));
366}
367
368// Updated human-readable release version if necessary
369if (!$cache and $release <> $CFG->release) {  // Update the release version
370    set_config('release', $release);
371}
372
373if (!$cache and $branch <> $CFG->branch) {  // Update the branch
374    set_config('branch', $branch);
375}
376
377if (!$cache and moodle_needs_upgrading()) {
378    if (!$PAGE->headerprinted) {
379        // means core upgrade or installation was not already done
380
381        if (!$confirmplugins) {
382            $strplugincheck = get_string('plugincheck');
383
384            $PAGE->navbar->add($strplugincheck);
385            $PAGE->set_title($strplugincheck);
386            $PAGE->set_heading($strplugincheck);
387            $PAGE->set_cacheable(false);
388
389            if ($fetchupdates) {
390                require_sesskey();
391                $updateschecker = \core\update\checker::instance();
392                if ($updateschecker->enabled()) {
393                    $updateschecker->fetch();
394                }
395                redirect($PAGE->url);
396            }
397
398            /** @var core_admin_renderer $output */
399            $output = $PAGE->get_renderer('core', 'admin');
400
401            $deployer = \core\update\deployer::instance();
402            if ($deployer->enabled()) {
403                $deployer->initialize($PAGE->url, $PAGE->url);
404
405                $deploydata = $deployer->submitted_data();
406                if (!empty($deploydata)) {
407                    require_sesskey();
408                    echo $output->upgrade_plugin_confirm_deploy_page($deployer, $deploydata);
409                    die();
410                }
411            }
412
413            // Show plugins info.
414            echo $output->upgrade_plugin_check_page(core_plugin_manager::instance(), \core\update\checker::instance(),
415                    $version, $showallplugins,
416                    new moodle_url($PAGE->url),
417                    new moodle_url('/admin/index.php', array('confirmplugincheck'=>1, 'cache'=>0)));
418            die();
419        }
420
421        // Make sure plugin dependencies are always checked.
422        $failed = array();
423        if (!core_plugin_manager::instance()->all_plugins_ok($version, $failed)) {
424            /** @var core_admin_renderer $output */
425            $output = $PAGE->get_renderer('core', 'admin');
426            $reloadurl = new moodle_url('/admin/index.php', array('cache' => 0));
427            echo $output->unsatisfied_dependencies_page($version, $failed, $reloadurl);
428            die();
429        }
430        unset($failed);
431    }
432
433    // install/upgrade all plugins and other parts
434    upgrade_noncore(true);
435}
436
437// If this is the first install, indicate that this site is fully configured
438// except the admin password
439if (during_initial_install()) {
440    set_config('rolesactive', 1); // after this, during_initial_install will return false.
441    set_config('adminsetuppending', 1);
442    // we need this redirect to setup proper session
443    upgrade_finished("index.php?sessionstarted=1&amp;lang=$CFG->lang");
444}
445
446// make sure admin user is created - this is the last step because we need
447// session to be working properly in order to edit admin account
448 if (!empty($CFG->adminsetuppending)) {
449    $sessionstarted = optional_param('sessionstarted', 0, PARAM_BOOL);
450    if (!$sessionstarted) {
451        redirect("index.php?sessionstarted=1&lang=$CFG->lang");
452    } else {
453        $sessionverify = optional_param('sessionverify', 0, PARAM_BOOL);
454        if (!$sessionverify) {
455            $SESSION->sessionverify = 1;
456            redirect("index.php?sessionstarted=1&sessionverify=1&lang=$CFG->lang");
457        } else {
458            if (empty($SESSION->sessionverify)) {
459                print_error('installsessionerror', 'admin', "index.php?sessionstarted=1&lang=$CFG->lang");
460            }
461            unset($SESSION->sessionverify);
462        }
463    }
464
465    // Cleanup SESSION to make sure other code does not complain in the future.
466    unset($SESSION->has_timed_out);
467    unset($SESSION->wantsurl);
468
469    // 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
470    $adminids = explode(',', $CFG->siteadmins);
471    $adminuser = get_complete_user_data('id', reset($adminids));
472
473    if ($adminuser->password === 'adminsetuppending') {
474        // prevent installation hijacking
475        //if ($adminuser->lastip !== getremoteaddr()) {
476        //    print_error('installhijacked', 'admin');
477        //}
478        // login user and let him set password and admin details
479        $adminuser->newadminuser = 1;
480        complete_user_login($adminuser);
481        redirect("$CFG->wwwroot/user/editadvanced.php?id=$adminuser->id"); // Edit thyself
482
483    } else {
484        unset_config('adminsetuppending');
485    }
486
487} else {
488    // just make sure upgrade logging is properly terminated
489    upgrade_finished('upgradesettings.php');
490}
491
492if (has_capability('moodle/site:config', context_system::instance())) {
493    if ($fetchupdates) {
494        require_sesskey();
495        $updateschecker = \core\update\checker::instance();
496        if ($updateschecker->enabled()) {
497            $updateschecker->fetch();
498        }
499        redirect(new moodle_url('/admin/index.php', array('cache' => 0)));
500    }
501}
502
503// Now we can be sure everything was upgraded and caches work fine,
504// redirect if necessary to make sure caching is enabled.
505if (!$cache) {
506    redirect(new moodle_url('/admin/index.php', array('cache' => 1)));
507}
508
509// Check for valid admin user - no guest autologin
510require_login(0, false);
511if (isguestuser()) {
512    // Login as real user!
513    $SESSION->wantsurl = (string)new moodle_url('/admin/index.php');
514    redirect(get_login_url());
515}
516$context = context_system::instance();
517require_capability('moodle/site:config', $context);
518
519// check that site is properly customized
520$site = get_site();
521if (empty($site->shortname)) {
522    // probably new installation - lets return to frontpage after this step
523    // remove settings that we want uninitialised
524    unset_config('registerauth');
525    redirect('upgradesettings.php?return=site');
526}
527
528// Check if we are returning from moodle.org registration and if so, we mark that fact to remove reminders
529if (!empty($id) and $id == $CFG->siteidentifier) {
530    set_config('registered', time());
531}
532
533// setup critical warnings before printing admin tree block
534$insecuredataroot = is_dataroot_insecure(true);
535$SESSION->admin_critical_warning = ($insecuredataroot==INSECURE_DATAROOT_ERROR);
536
537$adminroot = admin_get_root();
538
539// Check if there are any new admin settings which have still yet to be set
540if (any_new_admin_settings($adminroot)){
541    redirect('upgradesettings.php');
542}
543
544// Return to original page that started the plugin uninstallation if necessary.
545if (isset($SESSION->pluginuninstallreturn)) {
546    $return = $SESSION->pluginuninstallreturn;
547    unset($SESSION->pluginuninstallreturn);
548    if ($return) {
549        redirect($return);
550    }
551}
552
553// Everything should now be set up, and the user is an admin
554
555// Print default admin page with notifications.
556$errorsdisplayed = defined('WARN_DISPLAY_ERRORS_ENABLED');
557
558// We make the assumption that at least one schedule task should run once per day.
559$lastcron = $DB->get_field_sql('SELECT MAX(lastruntime) FROM {task_scheduled}');
560$cronoverdue = ($lastcron < time() - 3600 * 24);
561$dbproblems = $DB->diagnose();
562$maintenancemode = !empty($CFG->maintenance_enabled);
563
564// Available updates for Moodle core
565$updateschecker = \core\update\checker::instance();
566$availableupdates = array();
567$availableupdates['core'] = $updateschecker->get_update_info('core',
568    array('minmaturity' => $CFG->updateminmaturity, 'notifybuilds' => $CFG->updatenotifybuilds));
569
570// Available updates for contributed plugins
571$pluginman = core_plugin_manager::instance();
572foreach ($pluginman->get_plugins() as $plugintype => $plugintypeinstances) {
573    foreach ($plugintypeinstances as $pluginname => $plugininfo) {
574        if (!empty($plugininfo->availableupdates)) {
575            foreach ($plugininfo->availableupdates as $pluginavailableupdate) {
576                if ($pluginavailableupdate->version > $plugininfo->versiondisk) {
577                    if (!isset($availableupdates[$plugintype.'_'.$pluginname])) {
578                        $availableupdates[$plugintype.'_'.$pluginname] = array();
579                    }
580                    $availableupdates[$plugintype.'_'.$pluginname][] = $pluginavailableupdate;
581                }
582            }
583        }
584    }
585}
586
587// The timestamp of the most recent check for available updates
588$availableupdatesfetch = $updateschecker->get_last_timefetched();
589
590$buggyiconvnomb = (!function_exists('mb_convert_encoding') and @iconv('UTF-8', 'UTF-8//IGNORE', '100'.chr(130).'€') !== '100€');
591//check if the site is registered on Moodle.org
592$registered = $DB->count_records('registration_hubs', array('huburl' => HUB_MOODLEORGHUBURL, 'confirmed' => 1));
593// Check if there are any cache warnings.
594$cachewarnings = cache_helper::warnings();
595
596admin_externalpage_setup('adminnotifications');
597
598/* @var core_admin_renderer $output */
599$output = $PAGE->get_renderer('core', 'admin');
600
601echo $output->admin_notifications_page($maturity, $insecuredataroot, $errorsdisplayed, $cronoverdue, $dbproblems,
602                                       $maintenancemode, $availableupdates, $availableupdatesfetch, $buggyiconvnomb,
603                                       $registered, $cachewarnings);
Note: See TracBrowser for help on using the repository browser.