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