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