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