MediaWiki master
update.php
Go to the documentation of this file.
1#!/usr/bin/env php
2<?php
14// NO_AUTOLOAD -- due to hashbang above
15
16// @codeCoverageIgnoreStart
17require_once __DIR__ . '/Maintenance.php';
18// @codeCoverageIgnoreEnd
19
31
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
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() {
82
84 && !( $this->hasOption( 'force' )
85 || $this->hasOption( 'schema' )
86 || $this->hasOption( 'noschema' ) )
87 ) {
88 $this->fatalError( "Do not run update.php on this wiki. If you're seeing this you should\n"
89 . "probably ask for some help in performing your schema updates or use\n"
90 . "the --noschema and --schema options to get an SQL file for someone\n"
91 . "else to inspect and run.\n\n"
92 . "If you know what you are doing, you can continue with --force\n" );
93 }
94
95 $this->fileHandle = null;
96 if ( str_starts_with( $this->getOption( 'schema', '' ), '--' ) ) {
97 $this->fatalError( "The --schema option requires a file as an argument.\n" );
98 } elseif ( $this->hasOption( 'schema' ) ) {
99 $file = $this->getOption( 'schema' );
100 $this->fileHandle = fopen( $file, "w" );
101 if ( $this->fileHandle === false ) {
102 $err = error_get_last();
103 $this->fatalError( "Problem opening the schema file for writing: $file\n\t{$err['message']}" );
104 }
105 }
106
107 // Check for warnings about settings, and abort if there are any.
108 if ( !$this->hasOption( 'skip-config-validation' ) ) {
109 $this->validateSettings();
110 }
111
112 $lang = $this->getServiceContainer()->getLanguageFactory()->getLanguage( 'en' );
113 // Set global language to ensure localised errors are in English (T22633)
114 RequestContext::getMain()->setLanguage( $lang );
115
116 // BackCompat
117 $wgLang = $lang;
118
119 define( 'MW_UPDATER', true );
120
121 $this->output( 'MediaWiki ' . MW_VERSION . " Updater\n\n" );
122
123 $this->waitForReplication();
124
125 // Check external dependencies are up to date
126 if ( !$this->hasOption( 'skip-external-dependencies' ) && !getenv( 'MW_SKIP_EXTERNAL_DEPENDENCIES' ) ) {
127 $composerLockUpToDate = $this->createChild( CheckComposerLockUpToDate::class );
128 $composerLockUpToDate->execute();
129 } else {
130 $this->output(
131 "Skipping checking whether external dependencies are up to date, proceed at your own risk\n"
132 );
133 }
134
135 # Attempt to connect to the database as a privileged user
136 # This will vomit up an error if there are permissions problems
137 $db = $this->getPrimaryDB();
138
139 # Check to see whether the database server meets the minimum requirements
141 $dbInstallerClass = Installer::getDBInstallerClass( $db->getType() );
142 $status = $dbInstallerClass::meetsMinimumRequirement( $db );
143 if ( !$status->isOK() ) {
144 // This might output some wikitext like <strong> but it should be comprehensible
145 $this->fatalError( $status );
146 }
147
148 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
149 $this->output( "Going to run database updates for $dbDomain\n" );
150 if ( $db->getType() === 'sqlite' ) {
152 '@phan-var DatabaseSqlite $db';
153 $this->output( "Using SQLite file: '{$db->getDbFilePath()}'\n" );
154 }
155 $this->output( "Depending on the size of your database this may take a while!\n" );
156
157 if ( !$this->hasOption( 'quick' ) ) {
158 $this->output( "Abort with control-c in the next five seconds "
159 . "(skip this countdown with --quick) ..." );
160 $this->countDown( 5 );
161 }
162
163 $time1 = microtime( true );
164
165 $shared = $this->hasOption( 'doshared' );
166
167 $updates = [ 'core', 'extensions' ];
168 if ( !$this->hasOption( 'schema' ) ) {
169 if ( $this->hasOption( 'noschema' ) ) {
170 $updates[] = 'noschema';
171 }
172 $updates[] = 'stats';
173 }
174 if ( $this->hasOption( 'initial' ) ) {
175 $updates[] = 'initial';
176 }
177
178 $updater = DatabaseUpdater::newForDB( $db, $shared, $this );
179 $updater->logApplied = $this->hasOption( 'log-applied' );
180
181 // Avoid upgrading from versions older than 1.39
182 // Using an implicit marker (user_autocreate_serial was introduced in 1.39)
183 // TODO: Use an explicit marker
184 // See T259771
185 if ( !$updater->tableExists( 'user_autocreate_serial' ) ) {
186 $this->fatalError(
187 "Can not upgrade from versions older than 1.39, please upgrade to that version or later first."
188 );
189 }
190
191 $updater->doUpdates( $updates );
192
193 foreach ( $updater->getPostDatabaseUpdateMaintenance() as $maint ) {
194 $child = $this->createChild( $maint );
195
196 $isLoggedUpdate = $child instanceof LoggedUpdateMaintenance;
197
198 if ( !$isLoggedUpdate && $updater->updateRowExists( $maint ) ) {
199 $updater->outputApplied( "...Update '{$maint}' already logged as completed.\n" );
200 continue;
201 }
202 if ( $child instanceof LoggedUpdateMaintenance && $child->isAlreadyCompleted() ) {
203 $updater->outputApplied( "..." . $child->updateSkippedMessage() . "\n" );
204 continue;
205 }
206
207 $child->execute();
208 if ( !$isLoggedUpdate ) {
209 $updater->insertUpdateRow( $maint );
210 }
211 }
212 $updater->outputAppliedSummary();
213
214 $updater->setFileAccess();
215
216 $updater->purgeCache();
217
218 $time2 = microtime( true );
219
220 $timeDiff = $lang->formatTimePeriod( $time2 - $time1 );
221 $this->output( "\nDone in $timeDiff.\n" );
222 }
223
224 protected function afterFinalSetup() {
226
227 # Don't try to access the database
228 # This needs to be disabled early since extensions will try to use the l10n
229 # cache from $wgExtensionFunctions (T22471)
231 'class' => LocalisationCache::class,
232 'storeClass' => LCStoreNull::class,
233 'storeDirectory' => false,
234 'manualRecache' => false,
235 ];
236 }
237
241 public function validateParamsAndArgs() {
242 // Allow extensions to add additional params.
243 $params = [];
244 $this->getHookRunner()->onMaintenanceUpdateAddParams( $params );
245
246 // This executes before the PHP version check, so don't use null coalesce (??).
247 // Keeping this compatible with older PHP versions lets us reach the code that
248 // displays a more helpful error.
249 foreach ( $params as $name => $param ) {
250 $this->addOption(
251 $name,
252 $param['desc'],
253 isset( $param['require'] ) ? $param['require'] : false,
254 isset( $param['withArg'] ) ? $param['withArg'] : false,
255 isset( $param['shortName'] ) ? $param['shortName'] : false,
256 isset( $param['multiOccurrence'] ) ? $param['multiOccurrence'] : false
257 );
258 }
259
260 parent::validateParamsAndArgs();
261 }
262
263 private function formatWarnings( array $warnings ): string {
264 $text = '';
265 foreach ( $warnings as $warning ) {
266 $warning = wordwrap( $warning, 75, "\n " );
267 $text .= "* $warning\n";
268 }
269 return $text;
270 }
271
272 private function validateSettings() {
273 $settings = SettingsBuilder::getInstance();
274
275 $warnings = [];
276 if ( $settings->getWarnings() ) {
277 $warnings = $settings->getWarnings();
278 }
279
280 $status = $settings->validate();
281 if ( !$status->isOK() ) {
282 foreach ( $status->getMessages( 'error' ) as $msg ) {
283 $warnings[] = wfMessage( $msg )->text();
284 }
285 }
286
287 $deprecations = $settings->detectDeprecatedConfig();
288 foreach ( $deprecations as $key => $msg ) {
289 $warnings[] = "$key is deprecated: $msg";
290 }
291
292 $obsolete = $settings->detectObsoleteConfig();
293 foreach ( $obsolete as $key => $msg ) {
294 $warnings[] = "$key is obsolete: $msg";
295 }
296
297 if ( $warnings ) {
298 $this->fatalError( "Some of your configuration settings caused a warning:\n\n"
299 . $this->formatWarnings( $warnings ) . "\n"
300 . "Please correct the issue before running update.php again.\n"
301 . "If you know what you are doing, you can bypass this check\n"
302 . "using --skip-config-validation.\n" );
303 }
304 }
305}
306
307// @codeCoverageIgnoreStart
308$maintClass = UpdateMediaWiki::class;
309require_once RUN_MAINTENANCE_IF_MAIN;
310// @codeCoverageIgnoreEnd
const MW_VERSION
The running version of MediaWiki.
Definition Defines.php:23
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
$wgLang
Definition Setup.php:554
Group all the pieces relevant to the context of a request into one instance.
Base class for DBMS-specific installation helper classes.
Apply database changes after updating MediaWiki.
Base installer class.
Definition Installer.php:69
Null store backend, used to avoid DB errors during MediaWiki installation.
Caching for the contents of localisation files.
Class for scripts that perform database maintenance and want to log the update in updatelog so we can...
execute()
Do the actual work.All child classes will need to implement thisbool|null|void True for success,...
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
createChild(string $maintClass, ?string $classFile=null)
Returns an instance of the given maintenance script, with all of the current arguments passed to it.
output( $out, $channel=null)
Throw some output to the user.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
waitForReplication()
Wait for replica DB servers to catch up.
hasOption( $name)
Checks to see if a particular option was set.
getOption( $name, $default=null)
Get an option, or return the default.
getHookRunner()
Get a HookRunner for running core hooks.
getServiceContainer()
Returns the main service container.
countDown( $seconds)
Count down from $seconds to zero on the terminal, with a one-second pause between showing each number...
getPrimaryDB(string|false $virtualDomain=false)
addDescription( $text)
Set the description text.
Builder class for constructing a Config object from a set of sources during bootstrap.
Tools for dealing with other locally-hosted wikis.
Definition WikiMap.php:19
Maintenance script to run database schema updates.
Definition update.php:37
afterFinalSetup()
Override to perform any required operation at the end of initialisation.
Definition update.php:224
getDbType()
Does the script need different DB access? By default, we give Maintenance scripts normal rights to th...
Definition update.php:69
validateParamsAndArgs()
Run some validation checks on the params, etc.
Definition update.php:241
setup()
Provides subclasses with an opportunity to perform initial checks.
Definition update.php:73
execute()
Do the actual work.
Definition update.php:80
__construct()
Default constructor.
Definition update.php:38
This is the SQLite database abstraction layer.
$wgMessagesDirs
Config variable stub for the MessagesDirs setting, for use by phpdoc and IDEs.
$wgAllowSchemaUpdates
Config variable stub for the AllowSchemaUpdates setting, for use by phpdoc and IDEs.
$wgLocalisationCacheConf
Config variable stub for the LocalisationCacheConf setting, for use by phpdoc and IDEs.
$maintClass
Definition update.php:308