Allow extensions to add post-update maintenance scripts
[lhc/web/wiklou.git] / includes / installer / DatabaseUpdater.php
1 <?php
2 /**
3 * DBMS-specific updater helper.
4 *
5 * @file
6 * @ingroup Deployment
7 */
8
9 require_once( dirname(__FILE__) . '/../../maintenance/Maintenance.php' );
10
11 /**
12 * Class for handling database updates. Roughly based off of updaters.inc, with
13 * a few improvements :)
14 *
15 * @ingroup Deployment
16 * @since 1.17
17 */
18 abstract class DatabaseUpdater {
19
20 /**
21 * Array of updates to perform on the database
22 *
23 * @var array
24 */
25 protected $updates = array();
26
27 /**
28 * List of extension-provided database updates
29 * @var array
30 */
31 protected $extensionUpdates = array();
32
33 /**
34 * Handle to the database subclass
35 *
36 * @var DatabaseBase
37 */
38 protected $db;
39
40 protected $shared = false;
41
42 protected $postDatabaseUpdateMaintenance = array(
43 'DeleteDefaultMessages',
44 'PopulateRevisionLength',
45 'PopulateRevisionSha1',
46 'PopulateImageSha1'
47 );
48
49 /**
50 * Constructor
51 *
52 * @param $db DatabaseBase object to perform updates on
53 * @param $shared bool Whether to perform updates on shared tables
54 * @param $maintenance Maintenance Maintenance object which created us
55 */
56 protected function __construct( DatabaseBase &$db, $shared, Maintenance $maintenance = null ) {
57 $this->db = $db;
58 $this->db->setFlag( DBO_DDLMODE ); // For Oracle's handling of schema files
59 $this->shared = $shared;
60 if ( $maintenance ) {
61 $this->maintenance = $maintenance;
62 } else {
63 $this->maintenance = new FakeMaintenance;
64 }
65 $this->maintenance->setDB( $db );
66 $this->initOldGlobals();
67 $this->loadExtensions();
68 wfRunHooks( 'LoadExtensionSchemaUpdates', array( $this ) );
69 }
70
71 /**
72 * Initialize all of the old globals. One day this should all become
73 * something much nicer
74 */
75 private function initOldGlobals() {
76 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
77 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
78
79 # For extensions only, should be populated via hooks
80 # $wgDBtype should be checked to specifiy the proper file
81 $wgExtNewTables = array(); // table, dir
82 $wgExtNewFields = array(); // table, column, dir
83 $wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
84 $wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
85 $wgExtNewIndexes = array(); // table, index, dir
86 $wgExtModifiedFields = array(); // table, index, dir
87 }
88
89 /**
90 * Loads LocalSettings.php, if needed, and initialises everything needed for LoadExtensionSchemaUpdates hook
91 */
92 private function loadExtensions() {
93 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
94 return; // already loaded
95 }
96 $vars = Installer::getExistingLocalSettings();
97 if ( !$vars ) {
98 return; // no LocalSettings found
99 }
100 if ( !isset( $vars['wgHooks'] ) || !isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
101 return;
102 }
103 global $wgHooks, $wgAutoloadClasses;
104 $wgHooks['LoadExtensionSchemaUpdates'] = $vars['wgHooks']['LoadExtensionSchemaUpdates'];
105 $wgAutoloadClasses = $wgAutoloadClasses + $vars['wgAutoloadClasses'];
106 }
107
108 /**
109 * @throws MWException
110 * @param DatabaseBase $db
111 * @param bool $shared
112 * @param null $maintenance
113 * @return DatabaseUpdater
114 */
115 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
116 $type = $db->getType();
117 if( in_array( $type, Installer::getDBTypes() ) ) {
118 $class = ucfirst( $type ) . 'Updater';
119 return new $class( $db, $shared, $maintenance );
120 } else {
121 throw new MWException( __METHOD__ . ' called for unsupported $wgDBtype' );
122 }
123 }
124
125 /**
126 * Get a database connection to run updates
127 *
128 * @return DatabaseBase
129 */
130 public function getDB() {
131 return $this->db;
132 }
133
134 /**
135 * Output some text. If we're running from web, escape the text first.
136 *
137 * @param $str String: Text to output
138 */
139 public function output( $str ) {
140 if ( $this->maintenance->isQuiet() ) {
141 return;
142 }
143 global $wgCommandLineMode;
144 if( !$wgCommandLineMode ) {
145 $str = htmlspecialchars( $str );
146 }
147 echo $str;
148 flush();
149 }
150
151 /**
152 * Add a new update coming from an extension. This should be called by
153 * extensions while executing the LoadExtensionSchemaUpdates hook.
154 *
155 * @param $update Array: the update to run. Format is the following:
156 * first item is the callback function, it also can be a
157 * simple string with the name of a function in this class,
158 * following elements are parameters to the function.
159 * Note that callback functions will receive this object as
160 * first parameter.
161 */
162 public function addExtensionUpdate( Array $update ) {
163 $this->extensionUpdates[] = $update;
164 }
165
166 /**
167 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
168 * is the most common usage of updaters in an extension)
169 * @param $tableName String Name of table to create
170 * @param $sqlPath String Full path to the schema file
171 */
172 public function addExtensionTable( $tableName, $sqlPath ) {
173 $this->extensionUpdates[] = array( 'addTable', $tableName, $sqlPath, true );
174 }
175
176 /**
177 * @param $tableName string
178 * @param $indexName string
179 * @param $sqlPath string
180 */
181 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
182 $this->extensionUpdates[] = array( 'addIndex', $tableName, $indexName, $sqlPath, true );
183 }
184
185 /**
186 * @param $tableName string
187 * @param $columnName string
188 * @param $sqlPath string
189 */
190 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
191 $this->extensionUpdates[] = array( 'addField', $tableName, $columnName, $sqlPath, true );
192 }
193
194 /**
195 * Add a maintenance script to be run after the database updates are complete
196 * @param $class string Name of a Maintenance subclass
197 */
198 public function addPostDatabaseUpdateMaintenance( $class ) {
199 $this->postDatabaseUpdateMaintenance[] = $class;
200 }
201
202 /**
203 * Get the list of extension-defined updates
204 *
205 * @return Array
206 */
207 protected function getExtensionUpdates() {
208 return $this->extensionUpdates;
209 }
210
211 /**
212 * @return array
213 */
214 public function getPostDatabaseUpdateMaintenance() {
215 return $this->postDatabaseUpdateMaintenance;
216 }
217
218 /**
219 * Do all the updates
220 *
221 * @param $what Array: what updates to perform
222 */
223 public function doUpdates( $what = array( 'core', 'extensions', 'purge', 'stats' ) ) {
224 global $wgVersion;
225
226 $what = array_flip( $what );
227 if ( isset( $what['core'] ) ) {
228 $this->runUpdates( $this->getCoreUpdateList(), false );
229 }
230 if ( isset( $what['extensions'] ) ) {
231 $this->runUpdates( $this->getOldGlobalUpdates(), false );
232 $this->runUpdates( $this->getExtensionUpdates(), true );
233 }
234
235 $this->setAppliedUpdates( $wgVersion, $this->updates );
236
237 if( isset( $what['purge'] ) ) {
238 $this->purgeCache();
239 }
240 if ( isset( $what['stats'] ) ) {
241 $this->checkStats();
242 }
243 }
244
245 /**
246 * Helper function for doUpdates()
247 *
248 * @param $updates Array of updates to run
249 * @param $passSelf Boolean: whether to pass this object we calling external
250 * functions
251 */
252 private function runUpdates( array $updates, $passSelf ) {
253 foreach ( $updates as $params ) {
254 $func = array_shift( $params );
255 if( !is_array( $func ) && method_exists( $this, $func ) ) {
256 $func = array( $this, $func );
257 } elseif ( $passSelf ) {
258 array_unshift( $params, $this );
259 }
260 call_user_func_array( $func, $params );
261 flush();
262 }
263 $this->updates = array_merge( $this->updates, $updates );
264 }
265
266 /**
267 * @param $version
268 * @param $updates array
269 */
270 protected function setAppliedUpdates( $version, $updates = array() ) {
271 $this->db->clearFlag( DBO_DDLMODE );
272 if( !$this->canUseNewUpdatelog() ) {
273 return;
274 }
275 $key = "updatelist-$version-" . time();
276 $this->db->insert( 'updatelog',
277 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
278 __METHOD__ );
279 $this->db->setFlag( DBO_DDLMODE );
280 }
281
282 /**
283 * Helper function: check if the given key is present in the updatelog table.
284 * Obviously, only use this for updates that occur after the updatelog table was
285 * created!
286 * @param $key String Name of the key to check for
287 *
288 * @return bool
289 */
290 public function updateRowExists( $key ) {
291 $row = $this->db->selectRow(
292 'updatelog',
293 '1',
294 array( 'ul_key' => $key ),
295 __METHOD__
296 );
297 return (bool)$row;
298 }
299
300 /**
301 * Helper function: Add a key to the updatelog table
302 * Obviously, only use this for updates that occur after the updatelog table was
303 * created!
304 * @param $key String Name of key to insert
305 * @param $val String [optional] value to insert along with the key
306 */
307 public function insertUpdateRow( $key, $val = null ) {
308 $this->db->clearFlag( DBO_DDLMODE );
309 $values = array( 'ul_key' => $key );
310 if( $val && $this->canUseNewUpdatelog() ) {
311 $values['ul_value'] = $val;
312 }
313 $this->db->insert( 'updatelog', $values, __METHOD__, 'IGNORE' );
314 $this->db->setFlag( DBO_DDLMODE );
315 }
316
317 /**
318 * Updatelog was changed in 1.17 to have a ul_value column so we can record
319 * more information about what kind of updates we've done (that's what this
320 * class does). Pre-1.17 wikis won't have this column, and really old wikis
321 * might not even have updatelog at all
322 *
323 * @return boolean
324 */
325 protected function canUseNewUpdatelog() {
326 return $this->db->tableExists( 'updatelog', __METHOD__ ) &&
327 $this->db->fieldExists( 'updatelog', 'ul_value', __METHOD__ );
328 }
329
330 /**
331 * Before 1.17, we used to handle updates via stuff like
332 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
333 * of this in 1.17 but we want to remain back-compatible for a while. So
334 * load up these old global-based things into our update list.
335 *
336 * @return array
337 */
338 protected function getOldGlobalUpdates() {
339 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
340 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
341
342 $doUser = $this->shared ?
343 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
344 !$wgSharedDB || !in_array( 'user', $wgSharedTables );
345
346 $updates = array();
347
348 foreach ( $wgExtNewTables as $tableRecord ) {
349 $updates[] = array(
350 'addTable', $tableRecord[0], $tableRecord[1], true
351 );
352 }
353
354 foreach ( $wgExtNewFields as $fieldRecord ) {
355 if ( $fieldRecord[0] != 'user' || $doUser ) {
356 $updates[] = array(
357 'addField', $fieldRecord[0], $fieldRecord[1],
358 $fieldRecord[2], true
359 );
360 }
361 }
362
363 foreach ( $wgExtNewIndexes as $fieldRecord ) {
364 $updates[] = array(
365 'addIndex', $fieldRecord[0], $fieldRecord[1],
366 $fieldRecord[2], true
367 );
368 }
369
370 foreach ( $wgExtModifiedFields as $fieldRecord ) {
371 $updates[] = array(
372 'modifyField', $fieldRecord[0], $fieldRecord[1],
373 $fieldRecord[2], true
374 );
375 }
376
377 return $updates;
378 }
379
380 /**
381 * Get an array of updates to perform on the database. Should return a
382 * multi-dimensional array. The main key is the MediaWiki version (1.12,
383 * 1.13...) with the values being arrays of updates, identical to how
384 * updaters.inc did it (for now)
385 *
386 * @return Array
387 */
388 protected abstract function getCoreUpdateList();
389
390 /**
391 * Applies a SQL patch
392 * @param $path String Path to the patch file
393 * @param $isFullPath Boolean Whether to treat $path as a relative or not
394 */
395 protected function applyPatch( $path, $isFullPath = false ) {
396 if ( $isFullPath ) {
397 $this->db->sourceFile( $path );
398 } else {
399 $this->db->sourceFile( $this->db->patchPath( $path ) );
400 }
401 }
402
403 /**
404 * Add a new table to the database
405 * @param $name String Name of the new table
406 * @param $patch String Path to the patch file
407 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
408 */
409 protected function addTable( $name, $patch, $fullpath = false ) {
410 if ( $this->db->tableExists( $name, __METHOD__ ) ) {
411 $this->output( "...$name table already exists.\n" );
412 } else {
413 $this->output( "Creating $name table..." );
414 $this->applyPatch( $patch, $fullpath );
415 $this->output( "ok\n" );
416 }
417 }
418
419 /**
420 * Add a new field to an existing table
421 * @param $table String Name of the table to modify
422 * @param $field String Name of the new field
423 * @param $patch String Path to the patch file
424 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
425 */
426 protected function addField( $table, $field, $patch, $fullpath = false ) {
427 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
428 $this->output( "...$table table does not exist, skipping new field patch\n" );
429 } elseif ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
430 $this->output( "...have $field field in $table table.\n" );
431 } else {
432 $this->output( "Adding $field field to table $table..." );
433 $this->applyPatch( $patch, $fullpath );
434 $this->output( "ok\n" );
435 }
436 }
437
438 /**
439 * Add a new index to an existing table
440 * @param $table String Name of the table to modify
441 * @param $index String Name of the new index
442 * @param $patch String Path to the patch file
443 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
444 */
445 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
446 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
447 $this->output( "...$index key already set on $table table.\n" );
448 } else {
449 $this->output( "Adding $index key to table $table... " );
450 $this->applyPatch( $patch, $fullpath );
451 $this->output( "ok\n" );
452 }
453 }
454
455 /**
456 * Drop a field from an existing table
457 *
458 * @param $table String Name of the table to modify
459 * @param $field String Name of the old field
460 * @param $patch String Path to the patch file
461 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
462 */
463 protected function dropField( $table, $field, $patch, $fullpath = false ) {
464 if ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
465 $this->output( "Table $table contains $field field. Dropping... " );
466 $this->applyPatch( $patch, $fullpath );
467 $this->output( "ok\n" );
468 } else {
469 $this->output( "...$table table does not contain $field field.\n" );
470 }
471 }
472
473 /**
474 * Drop an index from an existing table
475 *
476 * @param $table String: Name of the table to modify
477 * @param $index String: Name of the old index
478 * @param $patch String: Path to the patch file
479 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
480 */
481 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
482 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
483 $this->output( "Dropping $index key from table $table... " );
484 $this->applyPatch( $patch, $fullpath );
485 $this->output( "ok\n" );
486 } else {
487 $this->output( "...$index key doesn't exist.\n" );
488 }
489 }
490
491 /**
492 * @param $table string
493 * @param $patch string
494 * @param $fullpath bool
495 */
496 protected function dropTable( $table, $patch, $fullpath = false ) {
497 if ( $this->db->tableExists( $table, __METHOD__ ) ) {
498 $this->output( "Dropping table $table... " );
499 $this->applyPatch( $patch, $fullpath );
500 $this->output( "ok\n" );
501 } else {
502 $this->output( "...$table doesn't exist.\n" );
503 }
504 }
505
506 /**
507 * Modify an existing field
508 *
509 * @param $table String: name of the table to which the field belongs
510 * @param $field String: name of the field to modify
511 * @param $patch String: path to the patch file
512 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
513 */
514 public function modifyField( $table, $field, $patch, $fullpath = false ) {
515 $updateKey = "$table-$field-$patch";
516 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
517 $this->output( "...$table table does not exist, skipping modify field patch\n" );
518 } elseif ( !$this->db->fieldExists( $table, $field, __METHOD__ ) ) {
519 $this->output( "...$field field does not exist in $table table, skipping modify field patch\n" );
520 } elseif( $this->updateRowExists( $updateKey ) ) {
521 $this->output( "...$field in table $table already modified by patch $patch\n" );
522 } else {
523 $this->output( "Modifying $field field of table $table..." );
524 $this->applyPatch( $patch, $fullpath );
525 $this->insertUpdateRow( $updateKey );
526 $this->output( "ok\n" );
527 }
528 }
529
530 /**
531 * Purge the objectcache table
532 */
533 protected function purgeCache() {
534 # We can't guarantee that the user will be able to use TRUNCATE,
535 # but we know that DELETE is available to us
536 $this->output( "Purging caches..." );
537 $this->db->delete( 'objectcache', '*', __METHOD__ );
538 $this->output( "done.\n" );
539 }
540
541 /**
542 * Check the site_stats table is not properly populated.
543 */
544 protected function checkStats() {
545 $this->output( "Checking site_stats row..." );
546 $row = $this->db->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
547 if ( $row === false ) {
548 $this->output( "data is missing! rebuilding...\n" );
549 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
550 $this->output( "missing ss_total_pages, rebuilding...\n" );
551 } else {
552 $this->output( "done.\n" );
553 return;
554 }
555 SiteStatsInit::doAllAndCommit( $this->db );
556 }
557
558 # Common updater functions
559
560 protected function doActiveUsersInit() {
561 $activeUsers = $this->db->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
562 if ( $activeUsers == -1 ) {
563 $activeUsers = $this->db->selectField( 'recentchanges',
564 'COUNT( DISTINCT rc_user_text )',
565 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
566 );
567 $this->db->update( 'site_stats',
568 array( 'ss_active_users' => intval( $activeUsers ) ),
569 array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
570 );
571 }
572 $this->output( "...ss_active_users user count set...\n" );
573 }
574
575 protected function doLogUsertextPopulation() {
576 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
577 $this->output(
578 "Populating log_user_text field, printing progress markers. For large\n" .
579 "databases, you may want to hit Ctrl-C and do this manually with\n" .
580 "maintenance/populateLogUsertext.php.\n" );
581
582 $task = $this->maintenance->runChild( 'PopulateLogUsertext' );
583 $task->execute();
584 $this->insertUpdateRow( 'populate log_usertext' );
585 }
586 }
587
588 protected function doLogSearchPopulation() {
589 if ( !$this->updateRowExists( 'populate log_search' ) ) {
590 $this->output(
591 "Populating log_search table, printing progress markers. For large\n" .
592 "databases, you may want to hit Ctrl-C and do this manually with\n" .
593 "maintenance/populateLogSearch.php.\n" );
594
595 $task = $this->maintenance->runChild( 'PopulateLogSearch' );
596 $task->execute();
597 $this->insertUpdateRow( 'populate log_search' );
598 }
599 }
600
601 protected function doUpdateTranscacheField() {
602 if ( $this->updateRowExists( 'convert transcache field' ) ) {
603 $this->output( "...transcache tc_time already converted.\n" );
604 return;
605 }
606
607 $this->output( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
608 $this->applyPatch( 'patch-tc-timestamp.sql' );
609 $this->output( "ok\n" );
610 }
611
612 protected function doCollationUpdate() {
613 global $wgCategoryCollation;
614 if ( $this->db->selectField(
615 'categorylinks',
616 'COUNT(*)',
617 'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
618 __METHOD__
619 ) == 0 ) {
620 $this->output( "...collations up-to-date.\n" );
621 return;
622 }
623
624 $task = $this->maintenance->runChild( 'UpdateCollation' );
625 $task->execute();
626 }
627
628 protected function doMigrateUserOptions() {
629 $cl = $this->maintenance->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
630 $this->output( "Migrating remaining user_options... " );
631 $cl->execute();
632 $this->output( "done.\n" );
633 }
634
635 protected function doRebuildLocalisationCache() {
636 /**
637 * @var $cl RebuildLocalisationCache
638 */
639 $cl = $this->maintenance->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
640 $this->output( "Rebuilding localisation cache...\n" );
641 $cl->setForce();
642 $cl->execute();
643 $this->output( "Rebuilding localisation cache done.\n" );
644 }
645 }