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