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