73574828ee265f8949a6a3906d07cb308e8c5e8d
[lhc/web/wiklou.git] / includes / installer / DatabaseUpdater.php
1 <?php
2 /**
3 * DBMS-specific updater helper.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Deployment
22 */
23
24 require_once( __DIR__ . '/../../maintenance/Maintenance.php' );
25
26 /**
27 * Class for handling database updates. Roughly based off of updaters.inc, with
28 * a few improvements :)
29 *
30 * @ingroup Deployment
31 * @since 1.17
32 */
33 abstract class DatabaseUpdater {
34
35 /**
36 * Array of updates to perform on the database
37 *
38 * @var array
39 */
40 protected $updates = array();
41
42 /**
43 * Array of updates that were skipped
44 *
45 * @var array
46 */
47 protected $updatesSkipped = array();
48
49 /**
50 * List of extension-provided database updates
51 * @var array
52 */
53 protected $extensionUpdates = array();
54
55 /**
56 * Handle to the database subclass
57 *
58 * @var DatabaseBase
59 */
60 protected $db;
61
62 protected $shared = false;
63
64 /**
65 * Scripts to run after database update
66 * Should be a subclass of LoggedUpdateMaintenance
67 */
68 protected $postDatabaseUpdateMaintenance = array(
69 'DeleteDefaultMessages',
70 'PopulateRevisionLength',
71 'PopulateRevisionSha1',
72 'PopulateImageSha1',
73 'FixExtLinksProtocolRelative',
74 'PopulateFilearchiveSha1',
75 );
76
77 /**
78 * File handle for SQL output.
79 *
80 * @var Filehandle
81 */
82 protected $fileHandle = null;
83
84 /**
85 * Flag specifying whether or not to skip schema (e.g. SQL-only) updates.
86 *
87 * @var bool
88 */
89 protected $skipSchema = false;
90
91 /**
92 * Constructor
93 *
94 * @param $db DatabaseBase object to perform updates on
95 * @param $shared bool Whether to perform updates on shared tables
96 * @param $maintenance Maintenance Maintenance object which created us
97 */
98 protected function __construct( DatabaseBase &$db, $shared, Maintenance $maintenance = null ) {
99 $this->db = $db;
100 $this->db->setFlag( DBO_DDLMODE ); // For Oracle's handling of schema files
101 $this->shared = $shared;
102 if ( $maintenance ) {
103 $this->maintenance = $maintenance;
104 $this->fileHandle = $maintenance->fileHandle;
105 } else {
106 $this->maintenance = new FakeMaintenance;
107 }
108 $this->maintenance->setDB( $db );
109 $this->initOldGlobals();
110 $this->loadExtensions();
111 wfRunHooks( 'LoadExtensionSchemaUpdates', array( $this ) );
112 }
113
114 /**
115 * Initialize all of the old globals. One day this should all become
116 * something much nicer
117 */
118 private function initOldGlobals() {
119 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
120 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
121
122 # For extensions only, should be populated via hooks
123 # $wgDBtype should be checked to specifiy the proper file
124 $wgExtNewTables = array(); // table, dir
125 $wgExtNewFields = array(); // table, column, dir
126 $wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
127 $wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
128 $wgExtNewIndexes = array(); // table, index, dir
129 $wgExtModifiedFields = array(); // table, index, dir
130 }
131
132 /**
133 * Loads LocalSettings.php, if needed, and initialises everything needed for LoadExtensionSchemaUpdates hook
134 */
135 private function loadExtensions() {
136 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
137 return; // already loaded
138 }
139 $vars = Installer::getExistingLocalSettings();
140 if ( !$vars ) {
141 return; // no LocalSettings found
142 }
143 if ( !isset( $vars['wgHooks'] ) || !isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
144 return;
145 }
146 global $wgHooks, $wgAutoloadClasses;
147 $wgHooks['LoadExtensionSchemaUpdates'] = $vars['wgHooks']['LoadExtensionSchemaUpdates'];
148 $wgAutoloadClasses = $wgAutoloadClasses + $vars['wgAutoloadClasses'];
149 }
150
151 /**
152 * @throws MWException
153 * @param DatabaseBase $db
154 * @param bool $shared
155 * @param null $maintenance
156 * @return DatabaseUpdater
157 */
158 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
159 $type = $db->getType();
160 if( in_array( $type, Installer::getDBTypes() ) ) {
161 $class = ucfirst( $type ) . 'Updater';
162 return new $class( $db, $shared, $maintenance );
163 } else {
164 throw new MWException( __METHOD__ . ' called for unsupported $wgDBtype' );
165 }
166 }
167
168 /**
169 * Get a database connection to run updates
170 *
171 * @return DatabaseBase
172 */
173 public function getDB() {
174 return $this->db;
175 }
176
177 /**
178 * Output some text. If we're running from web, escape the text first.
179 *
180 * @param $str String: Text to output
181 */
182 public function output( $str ) {
183 if ( $this->maintenance->isQuiet() ) {
184 return;
185 }
186 global $wgCommandLineMode;
187 if( !$wgCommandLineMode ) {
188 $str = htmlspecialchars( $str );
189 }
190 echo $str;
191 flush();
192 }
193
194 /**
195 * Add a new update coming from an extension. This should be called by
196 * extensions while executing the LoadExtensionSchemaUpdates hook.
197 *
198 * @since 1.17
199 *
200 * @param $update Array: the update to run. Format is the following:
201 * first item is the callback function, it also can be a
202 * simple string with the name of a function in this class,
203 * following elements are parameters to the function.
204 * Note that callback functions will receive this object as
205 * first parameter.
206 */
207 public function addExtensionUpdate( array $update ) {
208 $this->extensionUpdates[] = $update;
209 }
210
211 /**
212 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
213 * is the most common usage of updaters in an extension)
214 *
215 * @since 1.18
216 *
217 * @param $tableName String Name of table to create
218 * @param $sqlPath String Full path to the schema file
219 */
220 public function addExtensionTable( $tableName, $sqlPath ) {
221 $this->extensionUpdates[] = array( 'addTable', $tableName, $sqlPath, true );
222 }
223
224 /**
225 * @since 1.19
226 *
227 * @param $tableName string
228 * @param $indexName string
229 * @param $sqlPath string
230 */
231 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
232 $this->extensionUpdates[] = array( 'addIndex', $tableName, $indexName, $sqlPath, true );
233 }
234
235 /**
236 *
237 * @since 1.19
238 *
239 * @param $tableName string
240 * @param $columnName string
241 * @param $sqlPath string
242 */
243 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
244 $this->extensionUpdates[] = array( 'addField', $tableName, $columnName, $sqlPath, true );
245 }
246
247 /**
248 *
249 * @since 1.20
250 *
251 * @param $tableName string
252 * @param $columnName string
253 * @param $sqlPath string
254 */
255 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
256 $this->extensionUpdates[] = array( 'dropField', $tableName, $columnName, $sqlPath, true );
257 }
258
259 /**
260 * Drop an index from an extension table
261 *
262 * @since 1.21
263 *
264 * @param $tableName string The table name
265 * @param $indexName string The index name
266 * @param $sqlPath string The path to the SQL change path
267 */
268 public function dropExtensionIndex( $tableName, $indexName, $sqlPath ) {
269 $this->extensionUpdates[] = array( 'dropIndex', $tableName, $indexName, $sqlPath, true );
270 }
271
272 /**
273 *
274 * @since 1.20
275 *
276 * @param $tableName string
277 * @param $sqlPath string
278 */
279 public function dropExtensionTable( $tableName, $sqlPath ) {
280 $this->extensionUpdates[] = array( 'dropTable', $tableName, $sqlPath, true );
281 }
282
283 /**
284 * Rename an index on an extension table
285 *
286 * @since 1.21
287 *
288 * @param $tableName string The table name
289 * @param $oldIndexName string The old index name
290 * @param $newIndexName string The new index name
291 * @param $skipBothIndexExistWarning Boolean: Whether to warn if both the old and the new indexes exist. [facultative; by default, false]
292 * @param $sqlPath string The path to the SQL change path
293 */
294 public function renameExtensionIndex( $tableName, $oldIndexName, $newIndexName, $sqlPath, $skipBothIndexExistWarning = false ) {
295 $this->extensionUpdates[] = array( 'renameIndex', $tableName, $oldIndexName, $newIndexName, $skipBothIndexExistWarning, $sqlPath, true );
296 }
297
298 /**
299 *
300 * @since 1.20
301 *
302 * @param $tableName string
303 * @return bool
304 */
305 public function tableExists( $tableName ) {
306 return ( $this->db->tableExists( $tableName, __METHOD__ ) );
307 }
308
309 /**
310 * Add a maintenance script to be run after the database updates are complete.
311 *
312 * Script should subclass LoggedUpdateMaintenance
313 *
314 * @since 1.19
315 *
316 * @param $class string Name of a Maintenance subclass
317 */
318 public function addPostDatabaseUpdateMaintenance( $class ) {
319 $this->postDatabaseUpdateMaintenance[] = $class;
320 }
321
322 /**
323 * Get the list of extension-defined updates
324 *
325 * @return Array
326 */
327 protected function getExtensionUpdates() {
328 return $this->extensionUpdates;
329 }
330
331 /**
332 * @since 1.17
333 *
334 * @return array
335 */
336 public function getPostDatabaseUpdateMaintenance() {
337 return $this->postDatabaseUpdateMaintenance;
338 }
339
340 /**
341 * @since 1.21
342 *
343 * Writes the schema updates desired to a file for the DB Admin to run.
344 */
345 private function writeSchemaUpdateFile( $schemaUpdate = array() ) {
346 $updates = $this->updatesSkipped;
347 $this->updatesSkipped = array();
348
349 foreach( $updates as $funcList ) {
350 $func = $funcList[0];
351 $arg = $funcList[1];
352 $origParams = $funcList[2];
353 $ret = call_user_func_array( $func, $arg );
354 flush();
355 $this->updatesSkipped[] = $origParams;
356 }
357 }
358
359 /**
360 * Do all the updates
361 *
362 * @param $what Array: what updates to perform
363 */
364 public function doUpdates( $what = array( 'core', 'extensions', 'stats' ) ) {
365 global $wgVersion, $wgLocalisationCacheConf;
366
367 $this->db->begin( __METHOD__ );
368 $what = array_flip( $what );
369 $this->skipSchema = isset( $what['noschema'] ) || $this->fileHandle !== null;
370 if ( isset( $what['core'] ) ) {
371 $this->runUpdates( $this->getCoreUpdateList(), false );
372 }
373 if ( isset( $what['extensions'] ) ) {
374 $this->runUpdates( $this->getOldGlobalUpdates(), false );
375 $this->runUpdates( $this->getExtensionUpdates(), true );
376 }
377
378 if ( isset( $what['stats'] ) ) {
379 $this->checkStats();
380 }
381
382 if ( isset( $what['purge'] ) ) {
383 $this->purgeCache();
384
385 if ( $wgLocalisationCacheConf['manualRecache'] ) {
386 $this->rebuildLocalisationCache();
387 }
388 }
389
390 $this->setAppliedUpdates( $wgVersion, $this->updates );
391
392 if( $this->fileHandle ) {
393 $this->skipSchema = false;
394 $this->writeSchemaUpdateFile( );
395 $this->setAppliedUpdates( "$wgVersion-schema", $this->updatesSkipped );
396 }
397
398 $this->db->commit( __METHOD__ );
399 }
400
401 /**
402 * Helper function for doUpdates()
403 *
404 * @param $updates Array of updates to run
405 * @param $passSelf Boolean: whether to pass this object we calling external
406 * functions
407 */
408 private function runUpdates( array $updates, $passSelf ) {
409 $updatesDone = array();
410 $updatesSkipped = array();
411 foreach ( $updates as $params ) {
412 $origParams = $params;
413 $func = array_shift( $params );
414 if( !is_array( $func ) && method_exists( $this, $func ) ) {
415 $func = array( $this, $func );
416 } elseif ( $passSelf ) {
417 array_unshift( $params, $this );
418 }
419 $ret = call_user_func_array( $func, $params );
420 flush();
421 if( $ret !== false ) {
422 $updatesDone[] = $origParams;
423 } else {
424 $updatesSkipped[] = array( $func, $params, $origParams );
425 }
426 }
427 $this->updatesSkipped = array_merge( $this->updatesSkipped, $updatesSkipped );
428 $this->updates = array_merge( $this->updates, $updatesDone );
429 }
430
431 /**
432 * @param $version
433 * @param $updates array
434 */
435 protected function setAppliedUpdates( $version, $updates = array() ) {
436 $this->db->clearFlag( DBO_DDLMODE );
437 if( !$this->canUseNewUpdatelog() ) {
438 return;
439 }
440 $key = "updatelist-$version-" . time();
441 $this->db->insert( 'updatelog',
442 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
443 __METHOD__ );
444 $this->db->setFlag( DBO_DDLMODE );
445 }
446
447 /**
448 * Helper function: check if the given key is present in the updatelog table.
449 * Obviously, only use this for updates that occur after the updatelog table was
450 * created!
451 * @param $key String Name of the key to check for
452 *
453 * @return bool
454 */
455 public function updateRowExists( $key ) {
456 $row = $this->db->selectRow(
457 'updatelog',
458 '1',
459 array( 'ul_key' => $key ),
460 __METHOD__
461 );
462 return (bool)$row;
463 }
464
465 /**
466 * Helper function: Add a key to the updatelog table
467 * Obviously, only use this for updates that occur after the updatelog table was
468 * created!
469 * @param $key String Name of key to insert
470 * @param $val String [optional] value to insert along with the key
471 */
472 public function insertUpdateRow( $key, $val = null ) {
473 $this->db->clearFlag( DBO_DDLMODE );
474 $values = array( 'ul_key' => $key );
475 if( $val && $this->canUseNewUpdatelog() ) {
476 $values['ul_value'] = $val;
477 }
478 $this->db->insert( 'updatelog', $values, __METHOD__, 'IGNORE' );
479 $this->db->setFlag( DBO_DDLMODE );
480 }
481
482 /**
483 * Updatelog was changed in 1.17 to have a ul_value column so we can record
484 * more information about what kind of updates we've done (that's what this
485 * class does). Pre-1.17 wikis won't have this column, and really old wikis
486 * might not even have updatelog at all
487 *
488 * @return boolean
489 */
490 protected function canUseNewUpdatelog() {
491 return $this->db->tableExists( 'updatelog', __METHOD__ ) &&
492 $this->db->fieldExists( 'updatelog', 'ul_value', __METHOD__ );
493 }
494
495 /**
496 * Returns whether updates should be executed on the database table $name.
497 * Updates will be prevented if the table is a shared table and it is not
498 * specified to run updates on shared tables.
499 *
500 * @param $name String table name
501 * @return bool
502 */
503 protected function doTable( $name ) {
504 global $wgSharedDB, $wgSharedTables;
505
506 // Don't bother to check $wgSharedTables if there isn't a shared database
507 // or the user actually also wants to do updates on the shared database.
508 if ( $wgSharedDB === null || $this->shared ) {
509 return true;
510 }
511
512 return !in_array( $name, $wgSharedTables );
513 }
514
515 /**
516 * Before 1.17, we used to handle updates via stuff like
517 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
518 * of this in 1.17 but we want to remain back-compatible for a while. So
519 * load up these old global-based things into our update list.
520 *
521 * @return array
522 */
523 protected function getOldGlobalUpdates() {
524 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
525 $wgExtNewIndexes;
526
527 $updates = array();
528
529 foreach ( $wgExtNewTables as $tableRecord ) {
530 $updates[] = array(
531 'addTable', $tableRecord[0], $tableRecord[1], true
532 );
533 }
534
535 foreach ( $wgExtNewFields as $fieldRecord ) {
536 $updates[] = array(
537 'addField', $fieldRecord[0], $fieldRecord[1],
538 $fieldRecord[2], true
539 );
540 }
541
542 foreach ( $wgExtNewIndexes as $fieldRecord ) {
543 $updates[] = array(
544 'addIndex', $fieldRecord[0], $fieldRecord[1],
545 $fieldRecord[2], true
546 );
547 }
548
549 foreach ( $wgExtModifiedFields as $fieldRecord ) {
550 $updates[] = array(
551 'modifyField', $fieldRecord[0], $fieldRecord[1],
552 $fieldRecord[2], true
553 );
554 }
555
556 return $updates;
557 }
558
559 /**
560 * Get an array of updates to perform on the database. Should return a
561 * multi-dimensional array. The main key is the MediaWiki version (1.12,
562 * 1.13...) with the values being arrays of updates, identical to how
563 * updaters.inc did it (for now)
564 *
565 * @return Array
566 */
567 protected abstract function getCoreUpdateList();
568
569 /**
570 * Append an SQL fragment to the open file handle.
571 *
572 * @param $filename String: File name to open
573 */
574 public function copyFile( $filename ) {
575 $this->db->sourceFile( $filename, false, false, false,
576 array( $this, 'appendLine' )
577 );
578 }
579
580 /**
581 * Append a line to the open filehandle. The line is assumed to
582 * be a complete SQL statement.
583 *
584 * This is used as a callback for for sourceLine().
585 *
586 * @param $line String text to append to the file
587 * @return Boolean false to skip actually executing the file
588 * @throws MWException
589 */
590 public function appendLine( $line ) {
591 $line = rtrim( $line ) . ";\n";
592 if( fwrite( $this->fileHandle, $line ) === false ) {
593 throw new MWException( "trouble writing file" );
594 }
595 return false;
596 }
597
598 /**
599 * Applies a SQL patch
600 *
601 * @param $path String Path to the patch file
602 * @param $isFullPath Boolean Whether to treat $path as a relative or not
603 * @param $msg String Description of the patch
604 * @return boolean false if patch is skipped.
605 */
606 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
607 if ( $msg === null ) {
608 $msg = "Applying $path patch";
609 }
610 if ( $this->skipSchema ) {
611 $this->output( "...skipping schema change ($msg).\n" );
612 return false;
613 }
614
615 $this->output( "$msg ..." );
616
617 if ( !$isFullPath ) {
618 $path = $this->db->patchPath( $path );
619 }
620 if( $this->fileHandle !== null ) {
621 $this->copyFile( $path );
622 } else {
623 $this->db->sourceFile( $path );
624 }
625 $this->output( "done.\n" );
626 return true;
627 }
628
629 /**
630 * Add a new table to the database
631 *
632 * @param $name String Name of the new table
633 * @param $patch String Path to the patch file
634 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
635 * @return Boolean false if this was skipped because schema changes are skipped
636 */
637 protected function addTable( $name, $patch, $fullpath = false ) {
638 if ( !$this->doTable( $name ) ) {
639 return true;
640 }
641
642 if ( $this->db->tableExists( $name, __METHOD__ ) ) {
643 $this->output( "...$name table already exists.\n" );
644 } else {
645 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
646 }
647 return true;
648 }
649
650 /**
651 * Add a new field to an existing table
652 *
653 * @param $table String Name of the table to modify
654 * @param $field String Name of the new field
655 * @param $patch String Path to the patch file
656 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
657 * @return Boolean false if this was skipped because schema changes are skipped
658 */
659 protected function addField( $table, $field, $patch, $fullpath = false ) {
660 if ( !$this->doTable( $table ) ) {
661 return true;
662 }
663
664 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
665 $this->output( "...$table table does not exist, skipping new field patch.\n" );
666 } elseif ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
667 $this->output( "...have $field field in $table table.\n" );
668 } else {
669 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
670 }
671 return true;
672 }
673
674 /**
675 * Add a new index to an existing table
676 *
677 * @param $table String Name of the table to modify
678 * @param $index String Name of the new index
679 * @param $patch String Path to the patch file
680 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
681 * @return Boolean false if this was skipped because schema changes are skipped
682 */
683 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
684 if ( !$this->doTable( $table ) ) {
685 return true;
686 }
687
688 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
689 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
690 } else if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
691 $this->output( "...index $index already set on $table table.\n" );
692 } else {
693 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
694 }
695 return true;
696 }
697
698 /**
699 * Drop a field from an existing table
700 *
701 * @param $table String Name of the table to modify
702 * @param $field String Name of the old field
703 * @param $patch String Path to the patch file
704 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
705 * @return Boolean false if this was skipped because schema changes are skipped
706 */
707 protected function dropField( $table, $field, $patch, $fullpath = false ) {
708 if ( !$this->doTable( $table ) ) {
709 return true;
710 }
711
712 if ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
713 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
714 } else {
715 $this->output( "...$table table does not contain $field field.\n" );
716 }
717 return true;
718 }
719
720 /**
721 * Drop an index from an existing table
722 *
723 * @param $table String: Name of the table to modify
724 * @param $index String: Name of the index
725 * @param $patch String: Path to the patch file
726 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
727 * @return Boolean false if this was skipped because schema changes are skipped
728 */
729 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
730 if ( !$this->doTable( $table ) ) {
731 return true;
732 }
733
734 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
735 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
736 } else {
737 $this->output( "...$index key doesn't exist.\n" );
738 }
739 return true;
740 }
741
742 /**
743 * Rename an index from an existing table
744 *
745 * @param $table String: Name of the table to modify
746 * @param $oldIndex String: Old name of the index
747 * @param $newIndex String: New name of the index
748 * @param $skipBothIndexExistWarning Boolean: Whether to warn if both the old and the new indexes exist.
749 * @param $patch String: Path to the patch file
750 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
751 * @return Boolean false if this was skipped because schema changes are skipped
752 */
753 protected function renameIndex( $table, $oldIndex, $newIndex, $skipBothIndexExistWarning, $patch, $fullpath = false ) {
754 if ( !$this->doTable( $table ) ) {
755 return true;
756 }
757
758 // First requirement: the table must exist
759 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
760 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
761 return true;
762 }
763
764 // Second requirement: the new index must be missing
765 if ( $this->db->indexExists( $table, $newIndex, __METHOD__ ) ) {
766 $this->output( "...index $newIndex already set on $table table.\n" );
767 if ( !$skipBothIndexExistWarning && $this->db->indexExists( $table, $oldIndex, __METHOD__ ) ) {
768 $this->output( "...WARNING: $oldIndex still exists, despite it has been renamed into $newIndex (which also exists).\n" .
769 " $oldIndex should be manually removed if not needed anymore.\n" );
770 }
771 return true;
772 }
773
774 // Third requirement: the old index must exist
775 if ( !$this->db->indexExists( $table, $oldIndex, __METHOD__ ) ) {
776 $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
777 return true;
778 }
779
780 // Requirements have been satisfied, patch can be applied
781 return $this->applyPatch( $patch, $fullpath, "Renaming index $oldIndex into $newIndex to table $table" );
782 }
783
784 /**
785 * If the specified table exists, drop it, or execute the
786 * patch if one is provided.
787 *
788 * Public @since 1.20
789 *
790 * @param $table string
791 * @param $patch string|false
792 * @param $fullpath bool
793 * @return Boolean false if this was skipped because schema changes are skipped
794 */
795 public function dropTable( $table, $patch = false, $fullpath = false ) {
796 if ( !$this->doTable( $table ) ) {
797 return true;
798 }
799
800 if ( $this->db->tableExists( $table, __METHOD__ ) ) {
801 $msg = "Dropping table $table";
802
803 if ( $patch === false ) {
804 $this->output( "$msg ..." );
805 $this->db->dropTable( $table, __METHOD__ );
806 $this->output( "done.\n" );
807 }
808 else {
809 return $this->applyPatch( $patch, $fullpath, $msg );
810 }
811 } else {
812 $this->output( "...$table doesn't exist.\n" );
813 }
814 return true;
815 }
816
817 /**
818 * Modify an existing field
819 *
820 * @param $table String: name of the table to which the field belongs
821 * @param $field String: name of the field to modify
822 * @param $patch String: path to the patch file
823 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
824 * @return Boolean false if this was skipped because schema changes are skipped
825 */
826 public function modifyField( $table, $field, $patch, $fullpath = false ) {
827 if ( !$this->doTable( $table ) ) {
828 return true;
829 }
830
831 $updateKey = "$table-$field-$patch";
832 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
833 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
834 } elseif ( !$this->db->fieldExists( $table, $field, __METHOD__ ) ) {
835 $this->output( "...$field field does not exist in $table table, skipping modify field patch.\n" );
836 } elseif( $this->updateRowExists( $updateKey ) ) {
837 $this->output( "...$field in table $table already modified by patch $patch.\n" );
838 } else {
839 $this->insertUpdateRow( $updateKey );
840 return $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
841 }
842 return true;
843 }
844
845 /**
846 * Purge the objectcache table
847 */
848 public function purgeCache() {
849 global $wgLocalisationCacheConf;
850 # We can't guarantee that the user will be able to use TRUNCATE,
851 # but we know that DELETE is available to us
852 $this->output( "Purging caches..." );
853 $this->db->delete( 'objectcache', '*', __METHOD__ );
854 if ( $wgLocalisationCacheConf['manualRecache'] ) {
855 $this->rebuildLocalisationCache();
856 }
857 $this->output( "done.\n" );
858 }
859
860 /**
861 * Check the site_stats table is not properly populated.
862 */
863 protected function checkStats() {
864 $this->output( "...site_stats is populated..." );
865 $row = $this->db->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
866 if ( $row === false ) {
867 $this->output( "data is missing! rebuilding...\n" );
868 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
869 $this->output( "missing ss_total_pages, rebuilding...\n" );
870 } else {
871 $this->output( "done.\n" );
872 return;
873 }
874 SiteStatsInit::doAllAndCommit( $this->db );
875 }
876
877 # Common updater functions
878
879 /**
880 * Sets the number of active users in the site_stats table
881 */
882 protected function doActiveUsersInit() {
883 $activeUsers = $this->db->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
884 if ( $activeUsers == -1 ) {
885 $activeUsers = $this->db->selectField( 'recentchanges',
886 'COUNT( DISTINCT rc_user_text )',
887 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
888 );
889 $this->db->update( 'site_stats',
890 array( 'ss_active_users' => intval( $activeUsers ) ),
891 array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
892 );
893 }
894 $this->output( "...ss_active_users user count set...\n" );
895 }
896
897 /**
898 * Populates the log_user_text field in the logging table
899 */
900 protected function doLogUsertextPopulation() {
901 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
902 $this->output(
903 "Populating log_user_text field, printing progress markers. For large\n" .
904 "databases, you may want to hit Ctrl-C and do this manually with\n" .
905 "maintenance/populateLogUsertext.php.\n" );
906
907 $task = $this->maintenance->runChild( 'PopulateLogUsertext' );
908 $task->execute();
909 $this->output( "done.\n" );
910 }
911 }
912
913 /**
914 * Migrate log params to new table and index for searching
915 */
916 protected function doLogSearchPopulation() {
917 if ( !$this->updateRowExists( 'populate log_search' ) ) {
918 $this->output(
919 "Populating log_search table, printing progress markers. For large\n" .
920 "databases, you may want to hit Ctrl-C and do this manually with\n" .
921 "maintenance/populateLogSearch.php.\n" );
922
923 $task = $this->maintenance->runChild( 'PopulateLogSearch' );
924 $task->execute();
925 $this->output( "done.\n" );
926 }
927 }
928
929 /**
930 * Updates the timestamps in the transcache table
931 */
932 protected function doUpdateTranscacheField() {
933 if ( $this->updateRowExists( 'convert transcache field' ) ) {
934 $this->output( "...transcache tc_time already converted.\n" );
935 return true;
936 }
937
938 return $this->applyPatch( 'patch-tc-timestamp.sql', false,
939 "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
940 }
941
942 /**
943 * Update CategoryLinks collation
944 */
945 protected function doCollationUpdate() {
946 global $wgCategoryCollation;
947 if ( $this->db->fieldExists( 'categorylinks', 'cl_collation', __METHOD__ ) ) {
948 if ( $this->db->selectField(
949 'categorylinks',
950 'COUNT(*)',
951 'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
952 __METHOD__
953 ) == 0 ) {
954 $this->output( "...collations up-to-date.\n" );
955 return;
956 }
957
958 $this->output( "Updating category collations..." );
959 $task = $this->maintenance->runChild( 'UpdateCollation' );
960 $task->execute();
961 $this->output( "...done.\n" );
962 }
963 }
964
965 /**
966 * Migrates user options from the user table blob to user_properties
967 */
968 protected function doMigrateUserOptions() {
969 if( $this->db->tableExists( 'user_properties' ) ) {
970 $cl = $this->maintenance->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
971 $cl->execute();
972 $this->output( "done.\n" );
973 }
974 }
975
976 /**
977 * Rebuilds the localisation cache
978 */
979 protected function rebuildLocalisationCache() {
980 /**
981 * @var $cl RebuildLocalisationCache
982 */
983 $cl = $this->maintenance->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
984 $this->output( "Rebuilding localisation cache...\n" );
985 $cl->setForce();
986 $cl->execute();
987 $this->output( "done.\n" );
988 }
989 }