Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
42.11% covered (danger)
42.11%
64 / 152
37.50% covered (danger)
37.50%
3 / 8
CRAP
0.00% covered (danger)
0.00%
0 / 1
UpdateMediaWiki
42.11% covered (danger)
42.11%
64 / 152
37.50% covered (danger)
37.50%
3 / 8
401.80
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
27 / 27
100.00% covered (success)
100.00%
1 / 1
1
 getDbType
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 setup
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
 execute
17.50% covered (danger)
17.50%
14 / 80
0.00% covered (danger)
0.00%
0 / 1
347.43
 afterFinalSetup
0.00% covered (danger)
0.00%
0 / 6
0.00% covered (danger)
0.00%
0 / 1
2
 validateParamsAndArgs
0.00% covered (danger)
0.00%
0 / 12
0.00% covered (danger)
0.00%
0 / 1
42
 formatWarnings
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 validateSettings
85.00% covered (warning)
85.00%
17 / 20
0.00% covered (danger)
0.00%
0 / 1
7.17
1#!/usr/bin/env php
2<?php
3/**
4 * Run all updaters.
5 *
6 * This is used when the database schema is modified and we need to apply patches.
7 *
8 * @license GPL-2.0-or-later
9 * @file
10 * @todo document
11 * @ingroup Maintenance
12 */
13
14// NO_AUTOLOAD -- due to hashbang above
15
16// @codeCoverageIgnoreStart
17require_once __DIR__ . '/Maintenance.php';
18// @codeCoverageIgnoreEnd
19
20use MediaWiki\Context\RequestContext;
21use MediaWiki\Installer\DatabaseInstaller;
22use MediaWiki\Installer\DatabaseUpdater;
23use MediaWiki\Installer\Installer;
24use MediaWiki\Language\LCStoreNull;
25use MediaWiki\Language\LocalisationCache;
26use MediaWiki\Maintenance\LoggedUpdateMaintenance;
27use MediaWiki\Maintenance\Maintenance;
28use MediaWiki\Settings\SettingsBuilder;
29use MediaWiki\WikiMap\WikiMap;
30use Wikimedia\Rdbms\DatabaseSqlite;
31
32/**
33 * Maintenance script to run database schema updates.
34 *
35 * @ingroup Maintenance
36 */
37class UpdateMediaWiki extends Maintenance {
38    public function __construct() {
39        parent::__construct();
40        $this->addDescription( 'MediaWiki database updater' );
41        $this->addOption( 'quick', 'Skip 5 second countdown before starting' );
42        $this->addOption( 'initial',
43            'Do initial updates required after manual installation using tables-generated.sql' );
44        $this->addOption( 'doshared', 'Also update shared tables' );
45        $this->addOption( 'noschema', 'Only do the updates that are not done during schema updates' );
46        $this->addOption(
47            'schema',
48            'Output SQL to do the schema updates instead of doing them. Works '
49                . 'even when $wgAllowSchemaUpdates is false',
50            false,
51            true
52        );
53        $this->addOption( 'force', 'Override when $wgAllowSchemaUpdates disables this script' );
54        $this->addOption(
55            'skip-external-dependencies',
56            'Skips checking whether external dependencies are up to date, mostly for developers'
57        );
58        $this->addOption(
59            'skip-config-validation',
60            'Skips checking whether the existing configuration is valid'
61        );
62        $this->addOption(
63            'log-applied',
64            'Output a message for each update that has already been applied before'
65        );
66    }
67
68    /** @inheritDoc */
69    public function getDbType() {
70        return Maintenance::DB_ADMIN;
71    }
72
73    public function setup() {
74        global $wgMessagesDirs;
75        // T206765: We need to load the installer i18n files as some errors come from installer/updater code
76        // T310378: We have to ensure we do this before execute()
77        $wgMessagesDirs['MediaWikiInstaller'] = dirname( __DIR__ ) . '/includes/Installer/i18n';
78    }
79
80    public function execute() {
81        // phpcs:ignore MediaWiki.Usage.DeprecatedGlobalVariables.Deprecated$wgLang
82        global $wgLang, $wgAllowSchemaUpdates;
83
84        if ( !$wgAllowSchemaUpdates
85            && !( $this->hasOption( 'force' )
86                || $this->hasOption( 'schema' )
87                || $this->hasOption( 'noschema' ) )
88        ) {
89            $this->fatalError( "Do not run update.php on this wiki. If you're seeing this you should\n"
90                . "probably ask for some help in performing your schema updates or use\n"
91                . "the --noschema and --schema options to get an SQL file for someone\n"
92                . "else to inspect and run.\n\n"
93                . "If you know what you are doing, you can continue with --force\n" );
94        }
95
96        $this->fileHandle = null;
97        if ( str_starts_with( $this->getOption( 'schema', '' ), '--' ) ) {
98            $this->fatalError( "The --schema option requires a file as an argument.\n" );
99        } elseif ( $this->hasOption( 'schema' ) ) {
100            $file = $this->getOption( 'schema' );
101            $this->fileHandle = fopen( $file, "w" );
102            if ( $this->fileHandle === false ) {
103                $err = error_get_last();
104                $this->fatalError( "Problem opening the schema file for writing: $file\n\t{$err['message']}" );
105            }
106        }
107
108        // Check for warnings about settings, and abort if there are any.
109        if ( !$this->hasOption( 'skip-config-validation' ) ) {
110            $this->validateSettings();
111        }
112
113        $lang = $this->getServiceContainer()->getLanguageFactory()->getLanguage( 'en' );
114        // Set global language to ensure localised errors are in English (T22633)
115        RequestContext::getMain()->setLanguage( $lang );
116
117        // BackCompat
118        $wgLang = $lang;
119
120        define( 'MW_UPDATER', true );
121
122        $this->output( 'MediaWiki ' . MW_VERSION . " Updater\n\n" );
123
124        $this->waitForReplication();
125
126        // Check external dependencies are up to date
127        if ( !$this->hasOption( 'skip-external-dependencies' ) && !getenv( 'MW_SKIP_EXTERNAL_DEPENDENCIES' ) ) {
128            $composerLockUpToDate = $this->createChild( CheckComposerLockUpToDate::class );
129            $composerLockUpToDate->execute();
130        } else {
131            $this->output(
132                "Skipping checking whether external dependencies are up to date, proceed at your own risk\n"
133            );
134        }
135
136        # Attempt to connect to the database as a privileged user
137        # This will vomit up an error if there are permissions problems
138        $db = $this->getPrimaryDB();
139
140        # Check to see whether the database server meets the minimum requirements
141        /** @var DatabaseInstaller $dbInstallerClass */
142        $dbInstallerClass = Installer::getDBInstallerClass( $db->getType() );
143        $status = $dbInstallerClass::meetsMinimumRequirement( $db );
144        if ( !$status->isOK() ) {
145            // This might output some wikitext like <strong> but it should be comprehensible
146            $this->fatalError( $status );
147        }
148
149        $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
150        $this->output( "Going to run database updates for $dbDomain\n" );
151        if ( $db->getType() === 'sqlite' ) {
152            /** @var DatabaseSqlite $db */
153            '@phan-var DatabaseSqlite $db';
154            $this->output( "Using SQLite file: '{$db->getDbFilePath()}'\n" );
155        }
156        $this->output( "Depending on the size of your database this may take a while!\n" );
157
158        if ( !$this->hasOption( 'quick' ) ) {
159            $this->output( "Abort with control-c in the next five seconds "
160                . "(skip this countdown with --quick) ..." );
161            $this->countDown( 5 );
162        }
163
164        $time1 = microtime( true );
165
166        $shared = $this->hasOption( 'doshared' );
167
168        $updates = [ 'core', 'extensions' ];
169        if ( !$this->hasOption( 'schema' ) ) {
170            if ( $this->hasOption( 'noschema' ) ) {
171                $updates[] = 'noschema';
172            }
173            $updates[] = 'stats';
174        }
175        if ( $this->hasOption( 'initial' ) ) {
176            $updates[] = 'initial';
177        }
178
179        $updater = DatabaseUpdater::newForDB( $db, $shared, $this );
180        $updater->logApplied = $this->hasOption( 'log-applied' );
181
182        // Avoid upgrading from versions older than 1.39
183        // Using an implicit marker (user_autocreate_serial was introduced in 1.39)
184        // TODO: Use an explicit marker
185        // See T259771
186        if ( !$updater->tableExists( 'user_autocreate_serial' ) ) {
187            $this->fatalError(
188                "Can not upgrade from versions older than 1.39, please upgrade to that version or later first."
189            );
190        }
191
192        $updater->doUpdates( $updates );
193
194        foreach ( $updater->getPostDatabaseUpdateMaintenance() as $maint ) {
195            $child = $this->createChild( $maint );
196
197            $isLoggedUpdate = $child instanceof LoggedUpdateMaintenance;
198
199            if ( !$isLoggedUpdate && $updater->updateRowExists( $maint ) ) {
200                $updater->outputApplied( "...Update '{$maint}' already logged as completed.\n" );
201                continue;
202            }
203            if ( $child instanceof LoggedUpdateMaintenance && $child->isAlreadyCompleted() ) {
204                $updater->outputApplied( "..." . $child->updateSkippedMessage() . "\n" );
205                continue;
206            }
207
208            $child->execute();
209            if ( !$isLoggedUpdate ) {
210                $updater->insertUpdateRow( $maint );
211            }
212        }
213        $updater->outputAppliedSummary();
214
215        $updater->setFileAccess();
216
217        $updater->purgeCache();
218
219        $time2 = microtime( true );
220
221        $timeDiff = $lang->formatTimePeriod( $time2 - $time1 );
222        $this->output( "\nDone in $timeDiff.\n" );
223    }
224
225    protected function afterFinalSetup() {
226        global $wgLocalisationCacheConf;
227
228        # Don't try to access the database
229        # This needs to be disabled early since extensions will try to use the l10n
230        # cache from $wgExtensionFunctions (T22471)
231        $wgLocalisationCacheConf = [
232            'class' => LocalisationCache::class,
233            'storeClass' => LCStoreNull::class,
234            'storeDirectory' => false,
235            'manualRecache' => false,
236        ];
237    }
238
239    /**
240     * @suppress PhanPluginDuplicateConditionalNullCoalescing
241     */
242    public function validateParamsAndArgs() {
243        // Allow extensions to add additional params.
244        $params = [];
245        $this->getHookRunner()->onMaintenanceUpdateAddParams( $params );
246
247        // This executes before the PHP version check, so don't use null coalesce (??).
248        // Keeping this compatible with older PHP versions lets us reach the code that
249        // displays a more helpful error.
250        foreach ( $params as $name => $param ) {
251            $this->addOption(
252                $name,
253                $param['desc'],
254                isset( $param['require'] ) ? $param['require'] : false,
255                isset( $param['withArg'] ) ? $param['withArg'] : false,
256                isset( $param['shortName'] ) ? $param['shortName'] : false,
257                isset( $param['multiOccurrence'] ) ? $param['multiOccurrence'] : false
258            );
259        }
260
261        parent::validateParamsAndArgs();
262    }
263
264    private function formatWarnings( array $warnings ): string {
265        $text = '';
266        foreach ( $warnings as $warning ) {
267            $warning = wordwrap( $warning, 75, "\n  " );
268            $text .= "$warning\n";
269        }
270        return $text;
271    }
272
273    private function validateSettings() {
274        $settings = SettingsBuilder::getInstance();
275
276        $warnings = [];
277        if ( $settings->getWarnings() ) {
278            $warnings = $settings->getWarnings();
279        }
280
281        $status = $settings->validate();
282        if ( !$status->isOK() ) {
283            foreach ( $status->getMessages( 'error' ) as $msg ) {
284                $warnings[] = wfMessage( $msg )->text();
285            }
286        }
287
288        $deprecations = $settings->detectDeprecatedConfig();
289        foreach ( $deprecations as $key => $msg ) {
290            $warnings[] = "$key is deprecated: $msg";
291        }
292
293        $obsolete = $settings->detectObsoleteConfig();
294        foreach ( $obsolete as $key => $msg ) {
295            $warnings[] = "$key is obsolete: $msg";
296        }
297
298        if ( $warnings ) {
299            $this->fatalError( "Some of your configuration settings caused a warning:\n\n"
300                . $this->formatWarnings( $warnings ) . "\n"
301                . "Please correct the issue before running update.php again.\n"
302                . "If you know what you are doing, you can bypass this check\n"
303                . "using --skip-config-validation.\n" );
304        }
305    }
306}
307
308// @codeCoverageIgnoreStart
309$maintClass = UpdateMediaWiki::class;
310require_once RUN_MAINTENANCE_IF_MAIN;
311// @codeCoverageIgnoreEnd