add since tag; please do this if you add new public methods, it avoids bugs and hassl...
[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 *
198 * @since 1.19
199 *
200 * @param $class string Name of a Maintenance subclass
201 */
202 public function addPostDatabaseUpdateMaintenance( $class ) {
203 $this->postDatabaseUpdateMaintenance[] = $class;
204 }
205
206 /**
207 * Get the list of extension-defined updates
208 *
209 * @return Array
210 */
211 protected function getExtensionUpdates() {
212 return $this->extensionUpdates;
213 }
214
215 /**
216 * @since 1.17
217 *
218 * @return array
219 */
220 public function getPostDatabaseUpdateMaintenance() {
221 return $this->postDatabaseUpdateMaintenance;
222 }
223
224 /**
225 * Do all the updates
226 *
227 * @param $what Array: what updates to perform
228 */
229 public function doUpdates( $what = array( 'core', 'extensions', 'purge', 'stats' ) ) {
230 global $wgLocalisationCacheConf, $wgVersion;
231
232 $what = array_flip( $what );
233 if ( isset( $what['core'] ) ) {
234 $this->runUpdates( $this->getCoreUpdateList(), false );
235 }
236 if ( isset( $what['extensions'] ) ) {
237 $this->runUpdates( $this->getOldGlobalUpdates(), false );
238 $this->runUpdates( $this->getExtensionUpdates(), true );
239 }
240
241 $this->setAppliedUpdates( $wgVersion, $this->updates );
242
243 if ( isset( $what['purge'] ) ) {
244 $this->purgeCache();
245
246 if ( $wgLocalisationCacheConf['manualRecache'] ) {
247 $this->rebuildLocalisationCache();
248 }
249 }
250 if ( isset( $what['stats'] ) ) {
251 $this->checkStats();
252 }
253 }
254
255 /**
256 * Helper function for doUpdates()
257 *
258 * @param $updates Array of updates to run
259 * @param $passSelf Boolean: whether to pass this object we calling external
260 * functions
261 */
262 private function runUpdates( array $updates, $passSelf ) {
263 foreach ( $updates as $params ) {
264 $func = array_shift( $params );
265 if( !is_array( $func ) && method_exists( $this, $func ) ) {
266 $func = array( $this, $func );
267 } elseif ( $passSelf ) {
268 array_unshift( $params, $this );
269 }
270 call_user_func_array( $func, $params );
271 flush();
272 }
273 $this->updates = array_merge( $this->updates, $updates );
274 }
275
276 /**
277 * @param $version
278 * @param $updates array
279 */
280 protected function setAppliedUpdates( $version, $updates = array() ) {
281 $this->db->clearFlag( DBO_DDLMODE );
282 if( !$this->canUseNewUpdatelog() ) {
283 return;
284 }
285 $key = "updatelist-$version-" . time();
286 $this->db->insert( 'updatelog',
287 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
288 __METHOD__ );
289 $this->db->setFlag( DBO_DDLMODE );
290 }
291
292 /**
293 * Helper function: check if the given key is present in the updatelog table.
294 * Obviously, only use this for updates that occur after the updatelog table was
295 * created!
296 * @param $key String Name of the key to check for
297 *
298 * @return bool
299 */
300 public function updateRowExists( $key ) {
301 $row = $this->db->selectRow(
302 'updatelog',
303 '1',
304 array( 'ul_key' => $key ),
305 __METHOD__
306 );
307 return (bool)$row;
308 }
309
310 /**
311 * Helper function: Add a key to the updatelog table
312 * Obviously, only use this for updates that occur after the updatelog table was
313 * created!
314 * @param $key String Name of key to insert
315 * @param $val String [optional] value to insert along with the key
316 */
317 public function insertUpdateRow( $key, $val = null ) {
318 $this->db->clearFlag( DBO_DDLMODE );
319 $values = array( 'ul_key' => $key );
320 if( $val && $this->canUseNewUpdatelog() ) {
321 $values['ul_value'] = $val;
322 }
323 $this->db->insert( 'updatelog', $values, __METHOD__, 'IGNORE' );
324 $this->db->setFlag( DBO_DDLMODE );
325 }
326
327 /**
328 * Updatelog was changed in 1.17 to have a ul_value column so we can record
329 * more information about what kind of updates we've done (that's what this
330 * class does). Pre-1.17 wikis won't have this column, and really old wikis
331 * might not even have updatelog at all
332 *
333 * @return boolean
334 */
335 protected function canUseNewUpdatelog() {
336 return $this->db->tableExists( 'updatelog', __METHOD__ ) &&
337 $this->db->fieldExists( 'updatelog', 'ul_value', __METHOD__ );
338 }
339
340 /**
341 * Before 1.17, we used to handle updates via stuff like
342 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
343 * of this in 1.17 but we want to remain back-compatible for a while. So
344 * load up these old global-based things into our update list.
345 *
346 * @return array
347 */
348 protected function getOldGlobalUpdates() {
349 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
350 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
351
352 $doUser = $this->shared ?
353 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
354 !$wgSharedDB || !in_array( 'user', $wgSharedTables );
355
356 $updates = array();
357
358 foreach ( $wgExtNewTables as $tableRecord ) {
359 $updates[] = array(
360 'addTable', $tableRecord[0], $tableRecord[1], true
361 );
362 }
363
364 foreach ( $wgExtNewFields as $fieldRecord ) {
365 if ( $fieldRecord[0] != 'user' || $doUser ) {
366 $updates[] = array(
367 'addField', $fieldRecord[0], $fieldRecord[1],
368 $fieldRecord[2], true
369 );
370 }
371 }
372
373 foreach ( $wgExtNewIndexes as $fieldRecord ) {
374 $updates[] = array(
375 'addIndex', $fieldRecord[0], $fieldRecord[1],
376 $fieldRecord[2], true
377 );
378 }
379
380 foreach ( $wgExtModifiedFields as $fieldRecord ) {
381 $updates[] = array(
382 'modifyField', $fieldRecord[0], $fieldRecord[1],
383 $fieldRecord[2], true
384 );
385 }
386
387 return $updates;
388 }
389
390 /**
391 * Get an array of updates to perform on the database. Should return a
392 * multi-dimensional array. The main key is the MediaWiki version (1.12,
393 * 1.13...) with the values being arrays of updates, identical to how
394 * updaters.inc did it (for now)
395 *
396 * @return Array
397 */
398 protected abstract function getCoreUpdateList();
399
400 /**
401 * Applies a SQL patch
402 * @param $path String Path to the patch file
403 * @param $isFullPath Boolean Whether to treat $path as a relative or not
404 */
405 protected function applyPatch( $path, $isFullPath = false ) {
406 if ( $isFullPath ) {
407 $this->db->sourceFile( $path );
408 } else {
409 $this->db->sourceFile( $this->db->patchPath( $path ) );
410 }
411 }
412
413 /**
414 * Add a new table to the database
415 * @param $name String Name of the new table
416 * @param $patch String Path to the patch file
417 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
418 */
419 protected function addTable( $name, $patch, $fullpath = false ) {
420 if ( $this->db->tableExists( $name, __METHOD__ ) ) {
421 $this->output( "...$name table already exists.\n" );
422 } else {
423 $this->output( "Creating $name table..." );
424 $this->applyPatch( $patch, $fullpath );
425 $this->output( "done.\n" );
426 }
427 }
428
429 /**
430 * Add a new field to an existing table
431 * @param $table String Name of the table to modify
432 * @param $field String Name of the new field
433 * @param $patch String Path to the patch file
434 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
435 */
436 protected function addField( $table, $field, $patch, $fullpath = false ) {
437 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
438 $this->output( "...$table table does not exist, skipping new field patch.\n" );
439 } elseif ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
440 $this->output( "...have $field field in $table table.\n" );
441 } else {
442 $this->output( "Adding $field field to table $table..." );
443 $this->applyPatch( $patch, $fullpath );
444 $this->output( "done.\n" );
445 }
446 }
447
448 /**
449 * Add a new index to an existing table
450 * @param $table String Name of the table to modify
451 * @param $index String Name of the new index
452 * @param $patch String Path to the patch file
453 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
454 */
455 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
456 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
457 $this->output( "...$index key already set on $table table.\n" );
458 } else {
459 $this->output( "Adding $index key to table $table... " );
460 $this->applyPatch( $patch, $fullpath );
461 $this->output( "done.\n" );
462 }
463 }
464
465 /**
466 * Drop a field from an existing table
467 *
468 * @param $table String Name of the table to modify
469 * @param $field String Name of the old field
470 * @param $patch String Path to the patch file
471 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
472 */
473 protected function dropField( $table, $field, $patch, $fullpath = false ) {
474 if ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
475 $this->output( "Table $table contains $field field. Dropping... " );
476 $this->applyPatch( $patch, $fullpath );
477 $this->output( "done.\n" );
478 } else {
479 $this->output( "...$table table does not contain $field field.\n" );
480 }
481 }
482
483 /**
484 * Drop an index from an existing table
485 *
486 * @param $table String: Name of the table to modify
487 * @param $index String: Name of the old index
488 * @param $patch String: Path to the patch file
489 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
490 */
491 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
492 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
493 $this->output( "Dropping $index key from table $table... " );
494 $this->applyPatch( $patch, $fullpath );
495 $this->output( "done.\n" );
496 } else {
497 $this->output( "...$index key doesn't exist.\n" );
498 }
499 }
500
501 /**
502 * @param $table string
503 * @param $patch string
504 * @param $fullpath bool
505 */
506 protected function dropTable( $table, $patch, $fullpath = false ) {
507 if ( $this->db->tableExists( $table, __METHOD__ ) ) {
508 $this->output( "Dropping table $table... " );
509 $this->applyPatch( $patch, $fullpath );
510 $this->output( "done.\n" );
511 } else {
512 $this->output( "...$table doesn't exist.\n" );
513 }
514 }
515
516 /**
517 * Modify an existing field
518 *
519 * @param $table String: name of the table to which the field belongs
520 * @param $field String: name of the field to modify
521 * @param $patch String: path to the patch file
522 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
523 */
524 public function modifyField( $table, $field, $patch, $fullpath = false ) {
525 $updateKey = "$table-$field-$patch";
526 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
527 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
528 } elseif ( !$this->db->fieldExists( $table, $field, __METHOD__ ) ) {
529 $this->output( "...$field field does not exist in $table table, skipping modify field patch.\n" );
530 } elseif( $this->updateRowExists( $updateKey ) ) {
531 $this->output( "...$field in table $table already modified by patch $patch.\n" );
532 } else {
533 $this->output( "Modifying $field field of table $table..." );
534 $this->applyPatch( $patch, $fullpath );
535 $this->insertUpdateRow( $updateKey );
536 $this->output( "done.\n" );
537 }
538 }
539
540 /**
541 * Purge the objectcache table
542 */
543 protected function purgeCache() {
544 # We can't guarantee that the user will be able to use TRUNCATE,
545 # but we know that DELETE is available to us
546 $this->output( "Purging caches..." );
547 $this->db->delete( 'objectcache', '*', __METHOD__ );
548 $this->output( "done.\n" );
549 }
550
551 /**
552 * Check the site_stats table is not properly populated.
553 */
554 protected function checkStats() {
555 $this->output( "Checking site_stats row..." );
556 $row = $this->db->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
557 if ( $row === false ) {
558 $this->output( "data is missing! rebuilding...\n" );
559 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
560 $this->output( "missing ss_total_pages, rebuilding...\n" );
561 } else {
562 $this->output( "done.\n" );
563 return;
564 }
565 SiteStatsInit::doAllAndCommit( $this->db );
566 }
567
568 # Common updater functions
569
570 /**
571 * Sets the number of active users in the site_stats table
572 */
573 protected function doActiveUsersInit() {
574 $activeUsers = $this->db->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
575 if ( $activeUsers == -1 ) {
576 $activeUsers = $this->db->selectField( 'recentchanges',
577 'COUNT( DISTINCT rc_user_text )',
578 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
579 );
580 $this->db->update( 'site_stats',
581 array( 'ss_active_users' => intval( $activeUsers ) ),
582 array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
583 );
584 }
585 $this->output( "...ss_active_users user count set...\n" );
586 }
587
588 /**
589 * Populates the log_user_text field in the logging table
590 */
591 protected function doLogUsertextPopulation() {
592 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
593 $this->output(
594 "Populating log_user_text field, printing progress markers. For large\n" .
595 "databases, you may want to hit Ctrl-C and do this manually with\n" .
596 "maintenance/populateLogUsertext.php.\n" );
597
598 $task = $this->maintenance->runChild( 'PopulateLogUsertext' );
599 $task->execute();
600 $this->output( "done.\n" );
601 }
602 }
603
604 /**
605 * Migrate log params to new table and index for searching
606 */
607 protected function doLogSearchPopulation() {
608 if ( !$this->updateRowExists( 'populate log_search' ) ) {
609 $this->output(
610 "Populating log_search table, printing progress markers. For large\n" .
611 "databases, you may want to hit Ctrl-C and do this manually with\n" .
612 "maintenance/populateLogSearch.php.\n" );
613
614 $task = $this->maintenance->runChild( 'PopulateLogSearch' );
615 $task->execute();
616 $this->output( "done.\n" );
617 }
618 }
619
620 /**
621 * Updates the timestamps in the transcache table
622 */
623 protected function doUpdateTranscacheField() {
624 if ( $this->updateRowExists( 'convert transcache field' ) ) {
625 $this->output( "...transcache tc_time already converted.\n" );
626 return;
627 }
628
629 $this->output( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
630 $this->applyPatch( 'patch-tc-timestamp.sql' );
631 $this->output( "done.\n" );
632 }
633
634 /**
635 * Update CategoryLinks collation
636 */
637 protected function doCollationUpdate() {
638 global $wgCategoryCollation;
639 if ( $this->db->selectField(
640 'categorylinks',
641 'COUNT(*)',
642 'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
643 __METHOD__
644 ) == 0 ) {
645 $this->output( "...collations up-to-date.\n" );
646 return;
647 }
648
649 $this->output( "Updating category collations..." );
650 $task = $this->maintenance->runChild( 'UpdateCollation' );
651 $task->execute();
652 $this->output( "...done.\n" );
653 }
654
655 /**
656 * Migrates user options from the user table blob to user_properties
657 */
658 protected function doMigrateUserOptions() {
659 $cl = $this->maintenance->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
660 $this->output( "Migrating remaining user_options... " );
661 $cl->execute();
662 $this->output( "done.\n" );
663 }
664
665 /**
666 * Rebuilds the localisation cache
667 */
668 protected function rebuildLocalisationCache() {
669 /**
670 * @var $cl RebuildLocalisationCache
671 */
672 $cl = $this->maintenance->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
673 $this->output( "Rebuilding localisation cache...\n" );
674 $cl->setForce();
675 $cl->execute();
676 $this->output( "done.\n" );
677 }
678 }