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