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
30require_once __DIR__ . '/Maintenance.php';
31
39
46 public function __construct() {
47 parent::__construct();
48 $this->addDescription( 'MediaWiki database updater' );
49 $this->addOption( 'quick', 'Skip 5 second countdown before starting' );
50 $this->addOption( 'doshared', 'Also update shared tables' );
51 $this->addOption( 'noschema', 'Only do the updates that are not done during schema updates' );
52 $this->addOption(
53 'schema',
54 'Output SQL to do the schema updates instead of doing them. Works '
55 . 'even when $wgAllowSchemaUpdates is false',
56 false,
57 true
58 );
59 $this->addOption( 'force', 'Override when $wgAllowSchemaUpdates disables this script' );
60 $this->addOption(
61 'skip-external-dependencies',
62 'Skips checking whether external dependencies are up to date, mostly for developers'
63 );
64 $this->addOption(
65 'skip-config-validation',
66 'Skips checking whether the existing configuration is valid'
67 );
68 }
69
70 public function getDbType() {
72 }
73
74 public function setup() {
75 global $wgMessagesDirs;
76 // T206765: We need to load the installer i18n files as some of errors come 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() {
83
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' ) ) {
128 $composerLockUpToDate = $this->runChild( 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
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' ) {
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
176 $updater = DatabaseUpdater::newForDB( $db, $shared, $this );
177
178 // Avoid upgrading from versions older than 1.35
179 // Using an implicit marker (rev_actor was introduced in 1.34)
180 // TODO: Use an explicit marker
181 // See T259771
182 if ( !$updater->fieldExists( 'revision', 'rev_actor' ) ) {
183 $this->fatalError(
184 "Can not upgrade from versions older than 1.35, please upgrade to that version or later first."
185 );
186 }
187
188 $updater->doUpdates( $updates );
189
190 foreach ( $updater->getPostDatabaseUpdateMaintenance() as $maint ) {
191 $child = $this->runChild( $maint );
192
193 // LoggedUpdateMaintenance is checking the updatelog itself
194 $isLoggedUpdate = $child instanceof LoggedUpdateMaintenance;
195
196 if ( !$isLoggedUpdate && $updater->updateRowExists( $maint ) ) {
197 continue;
198 }
199
200 $child->execute();
201 if ( !$isLoggedUpdate ) {
202 $updater->insertUpdateRow( $maint );
203 }
204 }
205
206 $updater->setFileAccess();
207
208 $updater->purgeCache();
209
210 $time2 = microtime( true );
211
212 $timeDiff = $lang->formatTimePeriod( $time2 - $time1 );
213 $this->output( "\nDone in $timeDiff.\n" );
214 }
215
216 protected function afterFinalSetup() {
218
219 # Don't try to access the database
220 # This needs to be disabled early since extensions will try to use the l10n
221 # cache from $wgExtensionFunctions (T22471)
223 'class' => LocalisationCache::class,
224 'storeClass' => LCStoreNull::class,
225 'storeDirectory' => false,
226 'manualRecache' => false,
227 ];
228 }
229
233 public function validateParamsAndArgs() {
234 // Allow extensions to add additional params.
235 $params = [];
236 $this->getHookRunner()->onMaintenanceUpdateAddParams( $params );
237
238 // This executes before the PHP version check, so don't use null coalesce (??).
239 // Keeping this compatible with older PHP versions lets us reach the code that
240 // displays a more helpful error.
241 foreach ( $params as $name => $param ) {
242 $this->addOption(
243 $name,
244 $param['desc'],
245 isset( $param['require'] ) ? $param['require'] : false,
246 isset( $param['withArg'] ) ? $param['withArg'] : false,
247 isset( $param['shortName'] ) ? $param['shortName'] : false,
248 isset( $param['multiOccurrence'] ) ? $param['multiOccurrence'] : false
249 );
250 }
251
252 parent::validateParamsAndArgs();
253 }
254
255 private function formatWarnings( array $warnings ) {
256 $text = '';
257 foreach ( $warnings as $warning ) {
258 $warning = wordwrap( $warning, 75, "\n " );
259 $text .= "* $warning\n";
260 }
261 return $text;
262 }
263
264 private function validateSettings() {
265 $settings = SettingsBuilder::getInstance();
266
267 $warnings = [];
268 if ( $settings->getWarnings() ) {
269 $warnings = $settings->getWarnings();
270 }
271
272 $status = $settings->validate();
273 if ( !$status->isOK() ) {
274 foreach ( $status->getMessages( 'error' ) as $msg ) {
275 $warnings[] = wfMessage( $msg )->text();
276 }
277 }
278
279 $deprecations = $settings->detectDeprecatedConfig();
280 foreach ( $deprecations as $key => $msg ) {
281 $warnings[] = "$key is deprecated: $msg";
282 }
283
284 $obsolete = $settings->detectObsoleteConfig();
285 foreach ( $obsolete as $key => $msg ) {
286 $warnings[] = "$key is obsolete: $msg";
287 }
288
289 if ( $warnings ) {
290 $this->fatalError( "Some of your configuration settings caused a warning:\n\n"
291 . $this->formatWarnings( $warnings ) . "\n"
292 . "Please correct the issue before running update.php again.\n"
293 . "If you know what you are doing, you can bypass this check\n"
294 . "using --skip-config-validation.\n" );
295 }
296 }
297}
298
299$maintClass = UpdateMediaWiki::class;
300require_once RUN_MAINTENANCE_IF_MAIN;
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:538
array $params
The job parameters.
Class for scripts that perform database maintenance and want to log the update in updatelog so we can...
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
output( $out, $channel=null)
Throw some output to the user.
getHookRunner()
Get a HookRunner for running core hooks.
waitForReplication()
Wait for replica DBs to catch up.
hasOption( $name)
Checks to see if a particular option was set.
countDown( $seconds)
Count down from $seconds to zero on the terminal, with a one-second pause between showing each number...
runChild( $maintClass, $classFile=null)
Run a child maintenance script.
getServiceContainer()
Returns the main service container.
addDescription( $text)
Set the description text.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Group all the pieces relevant to the context of a request into one instance.
Base class for DBMS-specific installation helper classes.
Class for handling database updates.
Base installer class.
Definition Installer.php:90
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:45
afterFinalSetup()
Override to perform any required operation at the end of initialisation.
Definition update.php:216
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:233
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:46
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:299