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