MediaWiki master
update.php
Go to the documentation of this file.
1#!/usr/bin/env php
2<?php
28// NO_AUTOLOAD -- due to hashbang above
29
30// @codeCoverageIgnoreStart
31require_once __DIR__ . '/Maintenance.php';
32// @codeCoverageIgnoreEnd
33
43
50 public function __construct() {
51 parent::__construct();
52 $this->addDescription( 'MediaWiki database updater' );
53 $this->addOption( 'quick', 'Skip 5 second countdown before starting' );
54 $this->addOption( 'initial',
55 'Do initial updates required after manual installation using tables-generated.sql' );
56 $this->addOption( 'doshared', 'Also update shared tables' );
57 $this->addOption( 'noschema', 'Only do the updates that are not done during schema updates' );
58 $this->addOption(
59 'schema',
60 'Output SQL to do the schema updates instead of doing them. Works '
61 . 'even when $wgAllowSchemaUpdates is false',
62 false,
63 true
64 );
65 $this->addOption( 'force', 'Override when $wgAllowSchemaUpdates disables this script' );
66 $this->addOption(
67 'skip-external-dependencies',
68 'Skips checking whether external dependencies are up to date, mostly for developers'
69 );
70 $this->addOption(
71 'skip-config-validation',
72 'Skips checking whether the existing configuration is valid'
73 );
74 }
75
77 public function getDbType() {
78 return Maintenance::DB_ADMIN;
79 }
80
81 public function setup() {
82 global $wgMessagesDirs;
83 // T206765: We need to load the installer i18n files as some of errors come installer/updater code
84 // T310378: We have to ensure we do this before execute()
85 $wgMessagesDirs['MediaWikiInstaller'] = dirname( __DIR__ ) . '/includes/installer/i18n';
86 }
87
88 public function execute() {
90
92 && !( $this->hasOption( 'force' )
93 || $this->hasOption( 'schema' )
94 || $this->hasOption( 'noschema' ) )
95 ) {
96 $this->fatalError( "Do not run update.php on this wiki. If you're seeing this you should\n"
97 . "probably ask for some help in performing your schema updates or use\n"
98 . "the --noschema and --schema options to get an SQL file for someone\n"
99 . "else to inspect and run.\n\n"
100 . "If you know what you are doing, you can continue with --force\n" );
101 }
102
103 $this->fileHandle = null;
104 if ( str_starts_with( $this->getOption( 'schema', '' ), '--' ) ) {
105 $this->fatalError( "The --schema option requires a file as an argument.\n" );
106 } elseif ( $this->hasOption( 'schema' ) ) {
107 $file = $this->getOption( 'schema' );
108 $this->fileHandle = fopen( $file, "w" );
109 if ( $this->fileHandle === false ) {
110 $err = error_get_last();
111 $this->fatalError( "Problem opening the schema file for writing: $file\n\t{$err['message']}" );
112 }
113 }
114
115 // Check for warnings about settings, and abort if there are any.
116 if ( !$this->hasOption( 'skip-config-validation' ) ) {
117 $this->validateSettings();
118 }
119
120 $lang = $this->getServiceContainer()->getLanguageFactory()->getLanguage( 'en' );
121 // Set global language to ensure localised errors are in English (T22633)
122 RequestContext::getMain()->setLanguage( $lang );
123
124 // BackCompat
125 $wgLang = $lang;
126
127 define( 'MW_UPDATER', true );
128
129 $this->output( 'MediaWiki ' . MW_VERSION . " Updater\n\n" );
130
131 $this->waitForReplication();
132
133 // Check external dependencies are up to date
134 if ( !$this->hasOption( 'skip-external-dependencies' ) && !getenv( 'MW_SKIP_EXTERNAL_DEPENDENCIES' ) ) {
135 $composerLockUpToDate = $this->runChild( CheckComposerLockUpToDate::class );
136 $composerLockUpToDate->execute();
137 } else {
138 $this->output(
139 "Skipping checking whether external dependencies are up to date, proceed at your own risk\n"
140 );
141 }
142
143 # Attempt to connect to the database as a privileged user
144 # This will vomit up an error if there are permissions problems
145 $db = $this->getPrimaryDB();
146
147 # Check to see whether the database server meets the minimum requirements
149 $dbInstallerClass = Installer::getDBInstallerClass( $db->getType() );
150 $status = $dbInstallerClass::meetsMinimumRequirement( $db );
151 if ( !$status->isOK() ) {
152 // This might output some wikitext like <strong> but it should be comprehensible
153 $this->fatalError( $status );
154 }
155
156 $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
157 $this->output( "Going to run database updates for $dbDomain\n" );
158 if ( $db->getType() === 'sqlite' ) {
160 '@phan-var DatabaseSqlite $db';
161 $this->output( "Using SQLite file: '{$db->getDbFilePath()}'\n" );
162 }
163 $this->output( "Depending on the size of your database this may take a while!\n" );
164
165 if ( !$this->hasOption( 'quick' ) ) {
166 $this->output( "Abort with control-c in the next five seconds "
167 . "(skip this countdown with --quick) ..." );
168 $this->countDown( 5 );
169 }
170
171 $time1 = microtime( true );
172
173 $shared = $this->hasOption( 'doshared' );
174
175 $updates = [ 'core', 'extensions' ];
176 if ( !$this->hasOption( 'schema' ) ) {
177 if ( $this->hasOption( 'noschema' ) ) {
178 $updates[] = 'noschema';
179 }
180 $updates[] = 'stats';
181 }
182 if ( $this->hasOption( 'initial' ) ) {
183 $updates[] = 'initial';
184 }
185
186 $updater = DatabaseUpdater::newForDB( $db, $shared, $this );
187
188 // Avoid upgrading from versions older than 1.35
189 // Using an implicit marker (rev_actor was introduced in 1.34)
190 // TODO: Use an explicit marker
191 // See T259771
192 if ( !$updater->fieldExists( 'revision', 'rev_actor' ) ) {
193 $this->fatalError(
194 "Can not upgrade from versions older than 1.35, please upgrade to that version or later first."
195 );
196 }
197
198 $updater->doUpdates( $updates );
199
200 foreach ( $updater->getPostDatabaseUpdateMaintenance() as $maint ) {
201 $child = $this->runChild( $maint );
202
203 // LoggedUpdateMaintenance is checking the updatelog itself
204 $isLoggedUpdate = $child instanceof LoggedUpdateMaintenance;
205
206 if ( !$isLoggedUpdate && $updater->updateRowExists( $maint ) ) {
207 continue;
208 }
209
210 $child->execute();
211 if ( !$isLoggedUpdate ) {
212 $updater->insertUpdateRow( $maint );
213 }
214 }
215
216 $updater->setFileAccess();
217
218 $updater->purgeCache();
219
220 $time2 = microtime( true );
221
222 $timeDiff = $lang->formatTimePeriod( $time2 - $time1 );
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:37
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
if(!defined( 'MW_NO_SESSION') &&MW_ENTRY_POINT !=='cli' $wgLang
Definition Setup.php:563
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:84
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...
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.
runChild( $maintClass, $classFile=null)
Returns an instance of the given maintenance script, with all of the current arguments passed to it.
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...
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:31
Maintenance script to run database schema updates.
Definition update.php:49
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:77
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:81
execute()
Do the actual work.
Definition update.php:88
__construct()
Default constructor.
Definition update.php:50
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