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 
34 
41  public function __construct() {
42  parent::__construct();
43  $this->addDescription( 'MediaWiki database updater' );
44  $this->addOption( 'skip-compat-checks', 'Skips compatibility checks, mostly for developers' );
45  $this->addOption( 'quick', 'Skip 5 second countdown before starting' );
46  $this->addOption( 'doshared', 'Also update shared tables' );
47  $this->addOption( 'noschema', 'Only do the updates that are not done during schema updates' );
48  $this->addOption(
49  'schema',
50  'Output SQL to do the schema updates instead of doing them. Works '
51  . 'even when $wgAllowSchemaUpdates is false',
52  false,
53  true
54  );
55  $this->addOption( 'force', 'Override when $wgAllowSchemaUpdates disables this script' );
56  $this->addOption(
57  'skip-external-dependencies',
58  'Skips checking whether external dependencies are up to date, mostly for developers'
59  );
60  $this->addOption(
61  'skip-config-validation',
62  'Skips checking whether the existing configuration is valid'
63  );
64  }
65 
66  public function getDbType() {
67  return Maintenance::DB_ADMIN;
68  }
69 
70  private function compatChecks() {
71  $minimumPcreVersion = Installer::MINIMUM_PCRE_VERSION;
72 
73  $pcreVersion = explode( ' ', PCRE_VERSION, 2 )[0];
74  if ( version_compare( $pcreVersion, $minimumPcreVersion, '<' ) ) {
75  $this->fatalError(
76  "PCRE $minimumPcreVersion or later is required.\n" .
77  "Your PHP binary is linked with PCRE $pcreVersion.\n\n" .
78  "More information:\n" .
79  "https://www.mediawiki.org/wiki/Manual:Errors_and_symptoms/PCRE\n\n" .
80  "ABORTING.\n" );
81  }
82  }
83 
84  public function execute() {
86 
88  && !( $this->hasOption( 'force' )
89  || $this->hasOption( 'schema' )
90  || $this->hasOption( 'noschema' ) )
91  ) {
92  $this->fatalError( "Do not run update.php on this wiki. If you're seeing this you should\n"
93  . "probably ask for some help in performing your schema updates or use\n"
94  . "the --noschema and --schema options to get an SQL file for someone\n"
95  . "else to inspect and run.\n\n"
96  . "If you know what you are doing, you can continue with --force\n" );
97  }
98 
99  $this->fileHandle = null;
100  if ( substr( $this->getOption( 'schema', '' ), 0, 2 ) === "--" ) {
101  $this->fatalError( "The --schema option requires a file as an argument.\n" );
102  } elseif ( $this->hasOption( 'schema' ) ) {
103  $file = $this->getOption( 'schema' );
104  $this->fileHandle = fopen( $file, "w" );
105  if ( $this->fileHandle === false ) {
106  $err = error_get_last();
107  $this->fatalError( "Problem opening the schema file for writing: $file\n\t{$err['message']}" );
108  }
109  }
110 
111  // Check for warnings about settings, and abort if there are any.
112  if ( !$this->hasOption( 'skip-config-validation' ) ) {
113  $this->validateSettings();
114  }
115 
116  // T206765: We need to load the installer i18n files as some of errors come installer/updater code
117  $wgMessagesDirs['MediawikiInstaller'] = dirname( __DIR__ ) . '/includes/installer/i18n';
118 
119  $lang = MediaWikiServices::getInstance()->getLanguageFactory()->getLanguage( 'en' );
120  // Set global language to ensure localised errors are in English (T22633)
121  RequestContext::getMain()->setLanguage( $lang );
122 
123  // BackCompat
124  $wgLang = $lang;
125 
126  define( 'MW_UPDATER', true );
127 
128  $this->output( 'MediaWiki ' . MW_VERSION . " Updater\n\n" );
129 
130  MediaWikiServices::getInstance()->getDBLoadBalancerFactory()->waitForReplication();
131 
132  if ( !$this->hasOption( 'skip-compat-checks' ) ) {
133  $this->compatChecks();
134  } else {
135  $this->output( "Skipping compatibility checks, proceed at your own risk (Ctrl+C to abort)\n" );
136  $this->countDown( 5 );
137  }
138 
139  // Check external dependencies are up to date
140  if ( !$this->hasOption( 'skip-external-dependencies' ) ) {
141  $composerLockUpToDate = $this->runChild( CheckComposerLockUpToDate::class );
142  $composerLockUpToDate->execute();
143  } else {
144  $this->output(
145  "Skipping checking whether external dependencies are up to date, proceed at your own risk\n"
146  );
147  }
148 
149  # Attempt to connect to the database as a privileged user
150  # This will vomit up an error if there are permissions problems
151  $db = $this->getDB( DB_PRIMARY );
152 
153  # Check to see whether the database server meets the minimum requirements
155  $dbInstallerClass = Installer::getDBInstallerClass( $db->getType() );
156  $status = $dbInstallerClass::meetsMinimumRequirement( $db->getServerVersion() );
157  if ( !$status->isOK() ) {
158  // This might output some wikitext like <strong> but it should be comprehensible
159  $text = $status->getWikiText();
160  $this->fatalError( $text );
161  }
162 
163  $dbDomain = WikiMap::getCurrentWikiDbDomain()->getId();
164  $this->output( "Going to run database updates for $dbDomain\n" );
165  if ( $db->getType() === 'sqlite' ) {
167  '@phan-var DatabaseSqlite $db';
168  $this->output( "Using SQLite file: '{$db->getDbFilePath()}'\n" );
169  }
170  $this->output( "Depending on the size of your database this may take a while!\n" );
171 
172  if ( !$this->hasOption( 'quick' ) ) {
173  $this->output( "Abort with control-c in the next five seconds "
174  . "(skip this countdown with --quick) ..." );
175  $this->countDown( 5 );
176  }
177 
178  $time1 = microtime( true );
179 
180  $shared = $this->hasOption( 'doshared' );
181 
182  $updates = [ 'core', 'extensions' ];
183  if ( !$this->hasOption( 'schema' ) ) {
184  if ( $this->hasOption( 'noschema' ) ) {
185  $updates[] = 'noschema';
186  }
187  $updates[] = 'stats';
188  }
189 
190  $updater = DatabaseUpdater::newForDB( $db, $shared, $this );
191 
192  // Avoid upgrading from versions older than 1.31
193  // Using an implicit marker (slots table didn't exist until 1.31)
194  // TODO: Use an explicit marker
195  // See T259771
196  if ( !$updater->tableExists( 'slots' ) ) {
197  $this->fatalError(
198  "Can not upgrade from versions older than 1.31, please upgrade to that version or later first."
199  );
200  }
201 
202  $updater->doUpdates( $updates );
203 
204  foreach ( $updater->getPostDatabaseUpdateMaintenance() as $maint ) {
205  $child = $this->runChild( $maint );
206 
207  // LoggedUpdateMaintenance is checking the updatelog itself
208  $isLoggedUpdate = $child instanceof LoggedUpdateMaintenance;
209 
210  if ( !$isLoggedUpdate && $updater->updateRowExists( $maint ) ) {
211  continue;
212  }
213 
214  $child->execute();
215  if ( !$isLoggedUpdate ) {
216  $updater->insertUpdateRow( $maint );
217  }
218  }
219 
220  $updater->setFileAccess();
221 
222  $updater->purgeCache();
223 
224  $time2 = microtime( true );
225 
226  $timeDiff = $lang->formatTimePeriod( $time2 - $time1 );
227  $this->output( "\nDone in $timeDiff.\n" );
228  }
229 
230  protected function afterFinalSetup() {
232 
233  # Don't try to access the database
234  # This needs to be disabled early since extensions will try to use the l10n
235  # cache from $wgExtensionFunctions (T22471)
237  'class' => LocalisationCache::class,
238  'storeClass' => LCStoreNull::class,
239  'storeDirectory' => false,
240  'manualRecache' => false,
241  ];
242  }
243 
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  global $wgSettings;
282 
283  $warnings = [];
284  if ( $wgSettings->getWarnings() ) {
285  $warnings = $wgSettings->getWarnings();
286  }
287 
288  $status = $wgSettings->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 = $wgSettings->detectDeprecatedConfig();
297  foreach ( $deprecations as $key => $msg ) {
298  $warnings[] = "$key is deprecated: $msg";
299  }
300 
301  if ( $warnings ) {
302  $this->fatalError( "Some of your configuration settings caused a warning:\n\n"
303  . $this->formatWarnings( $warnings ) . "\n"
304  . "Please correct the issue before running update.php again.\n"
305  . "If you know what you are doing, you can bypass this check\n"
306  . "using --skip-config-validation.\n" );
307  }
308  }
309 }
310 
311 $maintClass = UpdateMediaWiki::class;
312 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:497
$wgSettings
Definition: Setup.php:143
static newForDB(IMaintainableDatabase $db, $shared=false, Maintenance $maintenance=null)
const MINIMUM_PCRE_VERSION
The oldest version of PCRE we can support.
Definition: Installer.php:65
static getDBInstallerClass( $type)
Get the DatabaseInstaller class name for this type.
Definition: Installer.php:624
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.
static getMain()
Get the RequestContext object associated with the main request.
Maintenance script to run database schema updates.
Definition: update.php:40
afterFinalSetup()
Override to perform any required operation at the end of initialisation.
Definition: update.php:230
getDbType()
Does the script need different DB access? By default, we give Maintenance scripts normal rights to th...
Definition: update.php:66
validateParamsAndArgs()
Definition: update.php:249
execute()
Do the actual work.
Definition: update.php:84
__construct()
Default constructor.
Definition: update.php:41
static getCurrentWikiDbDomain()
Definition: WikiMap.php:293
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:311