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