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