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