Debian Codegraph @

maintenance/update.php

raw symbols SCIP
1 #!/usr/bin/env php
2 <?php
3 /**
4 * Run all updaters.
5 *
6 * This is used when the database schema is modified and we need to apply patches.
7 *
8 * This program is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License along
19 * with this program; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
21 * http://www.gnu.org/copyleft/gpl.html
22 *
23 * @file
24 * @todo document
25 * @ingroup Maintenance
26 */
27
28 // NO_AUTOLOAD -- due to hashbang above
29
30 // @codeCoverageIgnoreStart
31 require_once __DIR__ . '/Maintenance.php';
32 // @codeCoverageIgnoreEnd
33
34 use MediaWiki\Context\RequestContext;
35 use MediaWiki\Installer\DatabaseInstaller;
36 use MediaWiki\Installer\DatabaseUpdater;
37 use MediaWiki\Installer\Installer;
38 use MediaWiki\Settings\SettingsBuilder;
39 use MediaWiki\WikiMap\WikiMap;
40 use Wikimedia\Rdbms\DatabaseSqlite;
41
42 /**
43 * Maintenance script to run database schema updates.
44 *
45 * @ingroup Maintenance
46 */
47 class UpdateMediaWiki extends Maintenance {
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() {
75 return Maintenance::DB_ADMIN;
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() {
86 global $wgLang, $wgAllowSchemaUpdates;
87
88 if ( !$wgAllowSchemaUpdates
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
145 /** @var DatabaseInstaller $dbInstallerClass */
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' ) {
156 /** @var DatabaseSqlite $db */
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() {
224 global $wgLocalisationCacheConf;
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)
229 $wgLocalisationCacheConf = [
230 'class' => LocalisationCache::class,
231 'storeClass' => LCStoreNull::class,
232 'storeDirectory' => false,
233 'manualRecache' => false,
234 ];
235 }
236
237 /**
238 * @suppress PhanPluginDuplicateConditionalNullCoalescing
239 */
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;
308 require_once RUN_MAINTENANCE_IF_MAIN;
309 // @codeCoverageIgnoreEnd