style: normalize end of files
[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 * @since 1.21
300 *
301 * @param $tableName string The table name
302 * @param $fieldName string The field to be modified
303 * @param $sqlPath string The path to the SQL change path
304 */
305 public function modifyExtensionField( $tableName, $fieldName, $sqlPath) {
306 $this->extensionUpdates[] = array( 'modifyField', $tableName, $fieldName, $sqlPath, true );
307 }
308
309 /**
310 *
311 * @since 1.20
312 *
313 * @param $tableName string
314 * @return bool
315 */
316 public function tableExists( $tableName ) {
317 return ( $this->db->tableExists( $tableName, __METHOD__ ) );
318 }
319
320 /**
321 * Add a maintenance script to be run after the database updates are complete.
322 *
323 * Script should subclass LoggedUpdateMaintenance
324 *
325 * @since 1.19
326 *
327 * @param $class string Name of a Maintenance subclass
328 */
329 public function addPostDatabaseUpdateMaintenance( $class ) {
330 $this->postDatabaseUpdateMaintenance[] = $class;
331 }
332
333 /**
334 * Get the list of extension-defined updates
335 *
336 * @return Array
337 */
338 protected function getExtensionUpdates() {
339 return $this->extensionUpdates;
340 }
341
342 /**
343 * @since 1.17
344 *
345 * @return array
346 */
347 public function getPostDatabaseUpdateMaintenance() {
348 return $this->postDatabaseUpdateMaintenance;
349 }
350
351 /**
352 * @since 1.21
353 *
354 * Writes the schema updates desired to a file for the DB Admin to run.
355 */
356 private function writeSchemaUpdateFile( $schemaUpdate = array() ) {
357 $updates = $this->updatesSkipped;
358 $this->updatesSkipped = array();
359
360 foreach( $updates as $funcList ) {
361 $func = $funcList[0];
362 $arg = $funcList[1];
363 $origParams = $funcList[2];
364 $ret = call_user_func_array( $func, $arg );
365 flush();
366 $this->updatesSkipped[] = $origParams;
367 }
368 }
369
370 /**
371 * Do all the updates
372 *
373 * @param $what Array: what updates to perform
374 */
375 public function doUpdates( $what = array( 'core', 'extensions', 'stats' ) ) {
376 global $wgVersion, $wgLocalisationCacheConf;
377
378 $this->db->begin( __METHOD__ );
379 $what = array_flip( $what );
380 $this->skipSchema = isset( $what['noschema'] ) || $this->fileHandle !== null;
381 if ( isset( $what['core'] ) ) {
382 $this->runUpdates( $this->getCoreUpdateList(), false );
383 }
384 if ( isset( $what['extensions'] ) ) {
385 $this->runUpdates( $this->getOldGlobalUpdates(), false );
386 $this->runUpdates( $this->getExtensionUpdates(), true );
387 }
388
389 if ( isset( $what['stats'] ) ) {
390 $this->checkStats();
391 }
392
393 if ( isset( $what['purge'] ) ) {
394 $this->purgeCache();
395
396 if ( $wgLocalisationCacheConf['manualRecache'] ) {
397 $this->rebuildLocalisationCache();
398 }
399 }
400
401 $this->setAppliedUpdates( $wgVersion, $this->updates );
402
403 if( $this->fileHandle ) {
404 $this->skipSchema = false;
405 $this->writeSchemaUpdateFile( );
406 $this->setAppliedUpdates( "$wgVersion-schema", $this->updatesSkipped );
407 }
408
409 $this->db->commit( __METHOD__ );
410 }
411
412 /**
413 * Helper function for doUpdates()
414 *
415 * @param $updates Array of updates to run
416 * @param $passSelf Boolean: whether to pass this object we calling external
417 * functions
418 */
419 private function runUpdates( array $updates, $passSelf ) {
420 $updatesDone = array();
421 $updatesSkipped = array();
422 foreach ( $updates as $params ) {
423 $origParams = $params;
424 $func = array_shift( $params );
425 if( !is_array( $func ) && method_exists( $this, $func ) ) {
426 $func = array( $this, $func );
427 } elseif ( $passSelf ) {
428 array_unshift( $params, $this );
429 }
430 $ret = call_user_func_array( $func, $params );
431 flush();
432 if( $ret !== false ) {
433 $updatesDone[] = $origParams;
434 } else {
435 $updatesSkipped[] = array( $func, $params, $origParams );
436 }
437 }
438 $this->updatesSkipped = array_merge( $this->updatesSkipped, $updatesSkipped );
439 $this->updates = array_merge( $this->updates, $updatesDone );
440 }
441
442 /**
443 * @param $version
444 * @param $updates array
445 */
446 protected function setAppliedUpdates( $version, $updates = array() ) {
447 $this->db->clearFlag( DBO_DDLMODE );
448 if( !$this->canUseNewUpdatelog() ) {
449 return;
450 }
451 $key = "updatelist-$version-" . time();
452 $this->db->insert( 'updatelog',
453 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
454 __METHOD__ );
455 $this->db->setFlag( DBO_DDLMODE );
456 }
457
458 /**
459 * Helper function: check if the given key is present in the updatelog table.
460 * Obviously, only use this for updates that occur after the updatelog table was
461 * created!
462 * @param $key String Name of the key to check for
463 *
464 * @return bool
465 */
466 public function updateRowExists( $key ) {
467 $row = $this->db->selectRow(
468 'updatelog',
469 '1',
470 array( 'ul_key' => $key ),
471 __METHOD__
472 );
473 return (bool)$row;
474 }
475
476 /**
477 * Helper function: Add a key to the updatelog table
478 * Obviously, only use this for updates that occur after the updatelog table was
479 * created!
480 * @param $key String Name of key to insert
481 * @param $val String [optional] value to insert along with the key
482 */
483 public function insertUpdateRow( $key, $val = null ) {
484 $this->db->clearFlag( DBO_DDLMODE );
485 $values = array( 'ul_key' => $key );
486 if( $val && $this->canUseNewUpdatelog() ) {
487 $values['ul_value'] = $val;
488 }
489 $this->db->insert( 'updatelog', $values, __METHOD__, 'IGNORE' );
490 $this->db->setFlag( DBO_DDLMODE );
491 }
492
493 /**
494 * Updatelog was changed in 1.17 to have a ul_value column so we can record
495 * more information about what kind of updates we've done (that's what this
496 * class does). Pre-1.17 wikis won't have this column, and really old wikis
497 * might not even have updatelog at all
498 *
499 * @return boolean
500 */
501 protected function canUseNewUpdatelog() {
502 return $this->db->tableExists( 'updatelog', __METHOD__ ) &&
503 $this->db->fieldExists( 'updatelog', 'ul_value', __METHOD__ );
504 }
505
506 /**
507 * Returns whether updates should be executed on the database table $name.
508 * Updates will be prevented if the table is a shared table and it is not
509 * specified to run updates on shared tables.
510 *
511 * @param $name String table name
512 * @return bool
513 */
514 protected function doTable( $name ) {
515 global $wgSharedDB, $wgSharedTables;
516
517 // Don't bother to check $wgSharedTables if there isn't a shared database
518 // or the user actually also wants to do updates on the shared database.
519 if ( $wgSharedDB === null || $this->shared ) {
520 return true;
521 }
522
523 return !in_array( $name, $wgSharedTables );
524 }
525
526 /**
527 * Before 1.17, we used to handle updates via stuff like
528 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
529 * of this in 1.17 but we want to remain back-compatible for a while. So
530 * load up these old global-based things into our update list.
531 *
532 * @return array
533 */
534 protected function getOldGlobalUpdates() {
535 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
536 $wgExtNewIndexes;
537
538 $updates = array();
539
540 foreach ( $wgExtNewTables as $tableRecord ) {
541 $updates[] = array(
542 'addTable', $tableRecord[0], $tableRecord[1], true
543 );
544 }
545
546 foreach ( $wgExtNewFields as $fieldRecord ) {
547 $updates[] = array(
548 'addField', $fieldRecord[0], $fieldRecord[1],
549 $fieldRecord[2], true
550 );
551 }
552
553 foreach ( $wgExtNewIndexes as $fieldRecord ) {
554 $updates[] = array(
555 'addIndex', $fieldRecord[0], $fieldRecord[1],
556 $fieldRecord[2], true
557 );
558 }
559
560 foreach ( $wgExtModifiedFields as $fieldRecord ) {
561 $updates[] = array(
562 'modifyField', $fieldRecord[0], $fieldRecord[1],
563 $fieldRecord[2], true
564 );
565 }
566
567 return $updates;
568 }
569
570 /**
571 * Get an array of updates to perform on the database. Should return a
572 * multi-dimensional array. The main key is the MediaWiki version (1.12,
573 * 1.13...) with the values being arrays of updates, identical to how
574 * updaters.inc did it (for now)
575 *
576 * @return Array
577 */
578 abstract protected function getCoreUpdateList();
579
580 /**
581 * Append an SQL fragment to the open file handle.
582 *
583 * @param $filename String: File name to open
584 */
585 public function copyFile( $filename ) {
586 $this->db->sourceFile( $filename, false, false, false,
587 array( $this, 'appendLine' )
588 );
589 }
590
591 /**
592 * Append a line to the open filehandle. The line is assumed to
593 * be a complete SQL statement.
594 *
595 * This is used as a callback for for sourceLine().
596 *
597 * @param $line String text to append to the file
598 * @return Boolean false to skip actually executing the file
599 * @throws MWException
600 */
601 public function appendLine( $line ) {
602 $line = rtrim( $line ) . ";\n";
603 if( fwrite( $this->fileHandle, $line ) === false ) {
604 throw new MWException( "trouble writing file" );
605 }
606 return false;
607 }
608
609 /**
610 * Applies a SQL patch
611 *
612 * @param $path String Path to the patch file
613 * @param $isFullPath Boolean Whether to treat $path as a relative or not
614 * @param $msg String Description of the patch
615 * @return boolean false if patch is skipped.
616 */
617 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
618 if ( $msg === null ) {
619 $msg = "Applying $path patch";
620 }
621 if ( $this->skipSchema ) {
622 $this->output( "...skipping schema change ($msg).\n" );
623 return false;
624 }
625
626 $this->output( "$msg ..." );
627
628 if ( !$isFullPath ) {
629 $path = $this->db->patchPath( $path );
630 }
631 if( $this->fileHandle !== null ) {
632 $this->copyFile( $path );
633 } else {
634 $this->db->sourceFile( $path );
635 }
636 $this->output( "done.\n" );
637 return true;
638 }
639
640 /**
641 * Add a new table to the database
642 *
643 * @param $name String Name of the new table
644 * @param $patch String Path to the patch file
645 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
646 * @return Boolean false if this was skipped because schema changes are skipped
647 */
648 protected function addTable( $name, $patch, $fullpath = false ) {
649 if ( !$this->doTable( $name ) ) {
650 return true;
651 }
652
653 if ( $this->db->tableExists( $name, __METHOD__ ) ) {
654 $this->output( "...$name table already exists.\n" );
655 } else {
656 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
657 }
658 return true;
659 }
660
661 /**
662 * Add a new field to an existing table
663 *
664 * @param $table String Name of the table to modify
665 * @param $field String Name of the new field
666 * @param $patch String Path to the patch file
667 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
668 * @return Boolean false if this was skipped because schema changes are skipped
669 */
670 protected function addField( $table, $field, $patch, $fullpath = false ) {
671 if ( !$this->doTable( $table ) ) {
672 return true;
673 }
674
675 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
676 $this->output( "...$table table does not exist, skipping new field patch.\n" );
677 } elseif ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
678 $this->output( "...have $field field in $table table.\n" );
679 } else {
680 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
681 }
682 return true;
683 }
684
685 /**
686 * Add a new index to an existing table
687 *
688 * @param $table String Name of the table to modify
689 * @param $index String Name of the new index
690 * @param $patch String Path to the patch file
691 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
692 * @return Boolean false if this was skipped because schema changes are skipped
693 */
694 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
695 if ( !$this->doTable( $table ) ) {
696 return true;
697 }
698
699 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
700 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
701 } else if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
702 $this->output( "...index $index already set on $table table.\n" );
703 } else {
704 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
705 }
706 return true;
707 }
708
709 /**
710 * Drop a field from an existing table
711 *
712 * @param $table String Name of the table to modify
713 * @param $field String Name of the old field
714 * @param $patch String Path to the patch file
715 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
716 * @return Boolean false if this was skipped because schema changes are skipped
717 */
718 protected function dropField( $table, $field, $patch, $fullpath = false ) {
719 if ( !$this->doTable( $table ) ) {
720 return true;
721 }
722
723 if ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
724 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
725 } else {
726 $this->output( "...$table table does not contain $field field.\n" );
727 }
728 return true;
729 }
730
731 /**
732 * Drop an index from an existing table
733 *
734 * @param $table String: Name of the table to modify
735 * @param $index String: Name of the index
736 * @param $patch String: Path to the patch file
737 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
738 * @return Boolean false if this was skipped because schema changes are skipped
739 */
740 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
741 if ( !$this->doTable( $table ) ) {
742 return true;
743 }
744
745 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
746 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
747 } else {
748 $this->output( "...$index key doesn't exist.\n" );
749 }
750 return true;
751 }
752
753 /**
754 * Rename an index from an existing table
755 *
756 * @param $table String: Name of the table to modify
757 * @param $oldIndex String: Old name of the index
758 * @param $newIndex String: New name of the index
759 * @param $skipBothIndexExistWarning Boolean: Whether to warn if both the old and the new indexes exist.
760 * @param $patch String: Path to the patch file
761 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
762 * @return Boolean false if this was skipped because schema changes are skipped
763 */
764 protected function renameIndex( $table, $oldIndex, $newIndex, $skipBothIndexExistWarning, $patch, $fullpath = false ) {
765 if ( !$this->doTable( $table ) ) {
766 return true;
767 }
768
769 // First requirement: the table must exist
770 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
771 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
772 return true;
773 }
774
775 // Second requirement: the new index must be missing
776 if ( $this->db->indexExists( $table, $newIndex, __METHOD__ ) ) {
777 $this->output( "...index $newIndex already set on $table table.\n" );
778 if ( !$skipBothIndexExistWarning && $this->db->indexExists( $table, $oldIndex, __METHOD__ ) ) {
779 $this->output( "...WARNING: $oldIndex still exists, despite it has been renamed into $newIndex (which also exists).\n" .
780 " $oldIndex should be manually removed if not needed anymore.\n" );
781 }
782 return true;
783 }
784
785 // Third requirement: the old index must exist
786 if ( !$this->db->indexExists( $table, $oldIndex, __METHOD__ ) ) {
787 $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
788 return true;
789 }
790
791 // Requirements have been satisfied, patch can be applied
792 return $this->applyPatch( $patch, $fullpath, "Renaming index $oldIndex into $newIndex to table $table" );
793 }
794
795 /**
796 * If the specified table exists, drop it, or execute the
797 * patch if one is provided.
798 *
799 * Public @since 1.20
800 *
801 * @param $table string
802 * @param $patch string|false
803 * @param $fullpath bool
804 * @return Boolean false if this was skipped because schema changes are skipped
805 */
806 public function dropTable( $table, $patch = false, $fullpath = false ) {
807 if ( !$this->doTable( $table ) ) {
808 return true;
809 }
810
811 if ( $this->db->tableExists( $table, __METHOD__ ) ) {
812 $msg = "Dropping table $table";
813
814 if ( $patch === false ) {
815 $this->output( "$msg ..." );
816 $this->db->dropTable( $table, __METHOD__ );
817 $this->output( "done.\n" );
818 }
819 else {
820 return $this->applyPatch( $patch, $fullpath, $msg );
821 }
822 } else {
823 $this->output( "...$table doesn't exist.\n" );
824 }
825 return true;
826 }
827
828 /**
829 * Modify an existing field
830 *
831 * @param $table String: name of the table to which the field belongs
832 * @param $field String: name of the field to modify
833 * @param $patch String: path to the patch file
834 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
835 * @return Boolean false if this was skipped because schema changes are skipped
836 */
837 public function modifyField( $table, $field, $patch, $fullpath = false ) {
838 if ( !$this->doTable( $table ) ) {
839 return true;
840 }
841
842 $updateKey = "$table-$field-$patch";
843 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
844 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
845 } elseif ( !$this->db->fieldExists( $table, $field, __METHOD__ ) ) {
846 $this->output( "...$field field does not exist in $table table, skipping modify field patch.\n" );
847 } elseif( $this->updateRowExists( $updateKey ) ) {
848 $this->output( "...$field in table $table already modified by patch $patch.\n" );
849 } else {
850 $this->insertUpdateRow( $updateKey );
851 return $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
852 }
853 return true;
854 }
855
856 /**
857 * Purge the objectcache table
858 */
859 public function purgeCache() {
860 global $wgLocalisationCacheConf;
861 # We can't guarantee that the user will be able to use TRUNCATE,
862 # but we know that DELETE is available to us
863 $this->output( "Purging caches..." );
864 $this->db->delete( 'objectcache', '*', __METHOD__ );
865 if ( $wgLocalisationCacheConf['manualRecache'] ) {
866 $this->rebuildLocalisationCache();
867 }
868 $this->output( "done.\n" );
869 }
870
871 /**
872 * Check the site_stats table is not properly populated.
873 */
874 protected function checkStats() {
875 $this->output( "...site_stats is populated..." );
876 $row = $this->db->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
877 if ( $row === false ) {
878 $this->output( "data is missing! rebuilding...\n" );
879 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
880 $this->output( "missing ss_total_pages, rebuilding...\n" );
881 } else {
882 $this->output( "done.\n" );
883 return;
884 }
885 SiteStatsInit::doAllAndCommit( $this->db );
886 }
887
888 # Common updater functions
889
890 /**
891 * Sets the number of active users in the site_stats table
892 */
893 protected function doActiveUsersInit() {
894 $activeUsers = $this->db->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
895 if ( $activeUsers == -1 ) {
896 $activeUsers = $this->db->selectField( 'recentchanges',
897 'COUNT( DISTINCT rc_user_text )',
898 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
899 );
900 $this->db->update( 'site_stats',
901 array( 'ss_active_users' => intval( $activeUsers ) ),
902 array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
903 );
904 }
905 $this->output( "...ss_active_users user count set...\n" );
906 }
907
908 /**
909 * Populates the log_user_text field in the logging table
910 */
911 protected function doLogUsertextPopulation() {
912 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
913 $this->output(
914 "Populating log_user_text field, printing progress markers. For large\n" .
915 "databases, you may want to hit Ctrl-C and do this manually with\n" .
916 "maintenance/populateLogUsertext.php.\n" );
917
918 $task = $this->maintenance->runChild( 'PopulateLogUsertext' );
919 $task->execute();
920 $this->output( "done.\n" );
921 }
922 }
923
924 /**
925 * Migrate log params to new table and index for searching
926 */
927 protected function doLogSearchPopulation() {
928 if ( !$this->updateRowExists( 'populate log_search' ) ) {
929 $this->output(
930 "Populating log_search table, printing progress markers. For large\n" .
931 "databases, you may want to hit Ctrl-C and do this manually with\n" .
932 "maintenance/populateLogSearch.php.\n" );
933
934 $task = $this->maintenance->runChild( 'PopulateLogSearch' );
935 $task->execute();
936 $this->output( "done.\n" );
937 }
938 }
939
940 /**
941 * Updates the timestamps in the transcache table
942 */
943 protected function doUpdateTranscacheField() {
944 if ( $this->updateRowExists( 'convert transcache field' ) ) {
945 $this->output( "...transcache tc_time already converted.\n" );
946 return true;
947 }
948
949 return $this->applyPatch( 'patch-tc-timestamp.sql', false,
950 "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
951 }
952
953 /**
954 * Update CategoryLinks collation
955 */
956 protected function doCollationUpdate() {
957 global $wgCategoryCollation;
958 if ( $this->db->fieldExists( 'categorylinks', 'cl_collation', __METHOD__ ) ) {
959 if ( $this->db->selectField(
960 'categorylinks',
961 'COUNT(*)',
962 'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
963 __METHOD__
964 ) == 0 ) {
965 $this->output( "...collations up-to-date.\n" );
966 return;
967 }
968
969 $this->output( "Updating category collations..." );
970 $task = $this->maintenance->runChild( 'UpdateCollation' );
971 $task->execute();
972 $this->output( "...done.\n" );
973 }
974 }
975
976 /**
977 * Migrates user options from the user table blob to user_properties
978 */
979 protected function doMigrateUserOptions() {
980 if( $this->db->tableExists( 'user_properties' ) ) {
981 $cl = $this->maintenance->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
982 $cl->execute();
983 $this->output( "done.\n" );
984 }
985 }
986
987 /**
988 * Rebuilds the localisation cache
989 */
990 protected function rebuildLocalisationCache() {
991 /**
992 * @var $cl RebuildLocalisationCache
993 */
994 $cl = $this->maintenance->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
995 $this->output( "Rebuilding localisation cache...\n" );
996 $cl->setForce();
997 $cl->execute();
998 $this->output( "done.\n" );
999 }
1000 }