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