Merge "Support multiple limits and arbitrary periods in account creation throttle"
[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 Database $db
174 * @param bool $shared
175 * @param Maintenance $maintenance
176 *
177 * @throws MWException
178 * @return DatabaseUpdater
179 */
180 public static function newForDB( Database $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 * Get appropriate schema variables in the current database connection.
407 *
408 * This should be called after any request data has been imported, but before
409 * any write operations to the database. The result should be passed to the DB
410 * setSchemaVars() method.
411 *
412 * @return array
413 * @since 1.28
414 */
415 public function getSchemaVars() {
416 return []; // DB-type specific
417 }
418
419 /**
420 * Do all the updates
421 *
422 * @param array $what What updates to perform
423 */
424 public function doUpdates( $what = [ 'core', 'extensions', 'stats' ] ) {
425 global $wgVersion;
426
427 $this->db->setSchemaVars( $this->getSchemaVars() );
428
429 $what = array_flip( $what );
430 $this->skipSchema = isset( $what['noschema'] ) || $this->fileHandle !== null;
431 if ( isset( $what['core'] ) ) {
432 $this->runUpdates( $this->getCoreUpdateList(), false );
433 }
434 if ( isset( $what['extensions'] ) ) {
435 $this->runUpdates( $this->getOldGlobalUpdates(), false );
436 $this->runUpdates( $this->getExtensionUpdates(), true );
437 }
438
439 if ( isset( $what['stats'] ) ) {
440 $this->checkStats();
441 }
442
443 $this->setAppliedUpdates( $wgVersion, $this->updates );
444
445 if ( $this->fileHandle ) {
446 $this->skipSchema = false;
447 $this->writeSchemaUpdateFile();
448 $this->setAppliedUpdates( "$wgVersion-schema", $this->updatesSkipped );
449 }
450 }
451
452 /**
453 * Helper function for doUpdates()
454 *
455 * @param array $updates Array of updates to run
456 * @param bool $passSelf Whether to pass this object we calling external functions
457 */
458 private function runUpdates( array $updates, $passSelf ) {
459 $updatesDone = [];
460 $updatesSkipped = [];
461 foreach ( $updates as $params ) {
462 $origParams = $params;
463 $func = array_shift( $params );
464 if ( !is_array( $func ) && method_exists( $this, $func ) ) {
465 $func = [ $this, $func ];
466 } elseif ( $passSelf ) {
467 array_unshift( $params, $this );
468 }
469 $ret = call_user_func_array( $func, $params );
470 flush();
471 if ( $ret !== false ) {
472 $updatesDone[] = $origParams;
473 wfGetLBFactory()->waitForReplication();
474 } else {
475 $updatesSkipped[] = [ $func, $params, $origParams ];
476 }
477 }
478 $this->updatesSkipped = array_merge( $this->updatesSkipped, $updatesSkipped );
479 $this->updates = array_merge( $this->updates, $updatesDone );
480 }
481
482 /**
483 * @param string $version
484 * @param array $updates
485 */
486 protected function setAppliedUpdates( $version, $updates = [] ) {
487 $this->db->clearFlag( DBO_DDLMODE );
488 if ( !$this->canUseNewUpdatelog() ) {
489 return;
490 }
491 $key = "updatelist-$version-" . time() . self::$updateCounter;
492 self::$updateCounter++;
493 $this->db->insert( 'updatelog',
494 [ 'ul_key' => $key, 'ul_value' => serialize( $updates ) ],
495 __METHOD__ );
496 $this->db->setFlag( DBO_DDLMODE );
497 }
498
499 /**
500 * Helper function: check if the given key is present in the updatelog table.
501 * Obviously, only use this for updates that occur after the updatelog table was
502 * created!
503 * @param string $key Name of the key to check for
504 * @return bool
505 */
506 public function updateRowExists( $key ) {
507 $row = $this->db->selectRow(
508 'updatelog',
509 # Bug 65813
510 '1 AS X',
511 [ 'ul_key' => $key ],
512 __METHOD__
513 );
514
515 return (bool)$row;
516 }
517
518 /**
519 * Helper function: Add a key to the updatelog table
520 * Obviously, only use this for updates that occur after the updatelog table was
521 * created!
522 * @param string $key Name of key to insert
523 * @param string $val [optional] Value to insert along with the key
524 */
525 public function insertUpdateRow( $key, $val = null ) {
526 $this->db->clearFlag( DBO_DDLMODE );
527 $values = [ 'ul_key' => $key ];
528 if ( $val && $this->canUseNewUpdatelog() ) {
529 $values['ul_value'] = $val;
530 }
531 $this->db->insert( 'updatelog', $values, __METHOD__, 'IGNORE' );
532 $this->db->setFlag( DBO_DDLMODE );
533 }
534
535 /**
536 * Updatelog was changed in 1.17 to have a ul_value column so we can record
537 * more information about what kind of updates we've done (that's what this
538 * class does). Pre-1.17 wikis won't have this column, and really old wikis
539 * might not even have updatelog at all
540 *
541 * @return bool
542 */
543 protected function canUseNewUpdatelog() {
544 return $this->db->tableExists( 'updatelog', __METHOD__ ) &&
545 $this->db->fieldExists( 'updatelog', 'ul_value', __METHOD__ );
546 }
547
548 /**
549 * Returns whether updates should be executed on the database table $name.
550 * Updates will be prevented if the table is a shared table and it is not
551 * specified to run updates on shared tables.
552 *
553 * @param string $name Table name
554 * @return bool
555 */
556 protected function doTable( $name ) {
557 global $wgSharedDB, $wgSharedTables;
558
559 // Don't bother to check $wgSharedTables if there isn't a shared database
560 // or the user actually also wants to do updates on the shared database.
561 if ( $wgSharedDB === null || $this->shared ) {
562 return true;
563 }
564
565 if ( in_array( $name, $wgSharedTables ) ) {
566 $this->output( "...skipping update to shared table $name.\n" );
567 return false;
568 } else {
569 return true;
570 }
571 }
572
573 /**
574 * Before 1.17, we used to handle updates via stuff like
575 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
576 * of this in 1.17 but we want to remain back-compatible for a while. So
577 * load up these old global-based things into our update list.
578 *
579 * @return array
580 */
581 protected function getOldGlobalUpdates() {
582 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
583 $wgExtNewIndexes;
584
585 $updates = [];
586
587 foreach ( $wgExtNewTables as $tableRecord ) {
588 $updates[] = [
589 'addTable', $tableRecord[0], $tableRecord[1], true
590 ];
591 }
592
593 foreach ( $wgExtNewFields as $fieldRecord ) {
594 $updates[] = [
595 'addField', $fieldRecord[0], $fieldRecord[1],
596 $fieldRecord[2], true
597 ];
598 }
599
600 foreach ( $wgExtNewIndexes as $fieldRecord ) {
601 $updates[] = [
602 'addIndex', $fieldRecord[0], $fieldRecord[1],
603 $fieldRecord[2], true
604 ];
605 }
606
607 foreach ( $wgExtModifiedFields as $fieldRecord ) {
608 $updates[] = [
609 'modifyField', $fieldRecord[0], $fieldRecord[1],
610 $fieldRecord[2], true
611 ];
612 }
613
614 return $updates;
615 }
616
617 /**
618 * Get an array of updates to perform on the database. Should return a
619 * multi-dimensional array. The main key is the MediaWiki version (1.12,
620 * 1.13...) with the values being arrays of updates, identical to how
621 * updaters.inc did it (for now)
622 *
623 * @return array
624 */
625 abstract protected function getCoreUpdateList();
626
627 /**
628 * Append an SQL fragment to the open file handle.
629 *
630 * @param string $filename File name to open
631 */
632 public function copyFile( $filename ) {
633 $this->db->sourceFile( $filename, false, false, false,
634 [ $this, 'appendLine' ]
635 );
636 }
637
638 /**
639 * Append a line to the open filehandle. The line is assumed to
640 * be a complete SQL statement.
641 *
642 * This is used as a callback for sourceLine().
643 *
644 * @param string $line Text to append to the file
645 * @return bool False to skip actually executing the file
646 * @throws MWException
647 */
648 public function appendLine( $line ) {
649 $line = rtrim( $line ) . ";\n";
650 if ( fwrite( $this->fileHandle, $line ) === false ) {
651 throw new MWException( "trouble writing file" );
652 }
653
654 return false;
655 }
656
657 /**
658 * Applies a SQL patch
659 *
660 * @param string $path Path to the patch file
661 * @param bool $isFullPath Whether to treat $path as a relative or not
662 * @param string $msg Description of the patch
663 * @return bool False if patch is skipped.
664 */
665 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
666 if ( $msg === null ) {
667 $msg = "Applying $path patch";
668 }
669 if ( $this->skipSchema ) {
670 $this->output( "...skipping schema change ($msg).\n" );
671
672 return false;
673 }
674
675 $this->output( "$msg ..." );
676
677 if ( !$isFullPath ) {
678 $path = $this->patchPath( $this->db, $path );
679 }
680 if ( $this->fileHandle !== null ) {
681 $this->copyFile( $path );
682 } else {
683 $this->db->sourceFile( $path );
684 }
685 $this->output( "done.\n" );
686
687 return true;
688 }
689
690 /**
691 * Get the full path of a patch file. Originally based on archive()
692 * from updaters.inc. Keep in mind this always returns a patch, as
693 * it fails back to MySQL if no DB-specific patch can be found
694 *
695 * @param IDatabase $db
696 * @param string $patch The name of the patch, like patch-something.sql
697 * @return string Full path to patch file
698 */
699 public function patchPath( IDatabase $db, $patch ) {
700 global $IP;
701
702 $dbType = $db->getType();
703 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
704 return "$IP/maintenance/$dbType/archives/$patch";
705 } else {
706 return "$IP/maintenance/archives/$patch";
707 }
708 }
709
710 /**
711 * Add a new table to the database
712 *
713 * @param string $name Name of the new table
714 * @param string $patch Path to the patch file
715 * @param bool $fullpath Whether to treat $patch path as a relative or not
716 * @return bool False if this was skipped because schema changes are skipped
717 */
718 protected function addTable( $name, $patch, $fullpath = false ) {
719 if ( !$this->doTable( $name ) ) {
720 return true;
721 }
722
723 if ( $this->db->tableExists( $name, __METHOD__ ) ) {
724 $this->output( "...$name table already exists.\n" );
725 } else {
726 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
727 }
728
729 return true;
730 }
731
732 /**
733 * Add a new field to an existing table
734 *
735 * @param string $table Name of the table to modify
736 * @param string $field Name of the new field
737 * @param string $patch Path to the patch file
738 * @param bool $fullpath Whether to treat $patch path as a relative or not
739 * @return bool False if this was skipped because schema changes are skipped
740 */
741 protected function addField( $table, $field, $patch, $fullpath = false ) {
742 if ( !$this->doTable( $table ) ) {
743 return true;
744 }
745
746 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
747 $this->output( "...$table table does not exist, skipping new field patch.\n" );
748 } elseif ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
749 $this->output( "...have $field field in $table table.\n" );
750 } else {
751 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
752 }
753
754 return true;
755 }
756
757 /**
758 * Add a new index to an existing table
759 *
760 * @param string $table Name of the table to modify
761 * @param string $index Name of the new index
762 * @param string $patch Path to the patch file
763 * @param bool $fullpath Whether to treat $patch path as a relative or not
764 * @return bool False if this was skipped because schema changes are skipped
765 */
766 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
767 if ( !$this->doTable( $table ) ) {
768 return true;
769 }
770
771 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
772 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
773 } elseif ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
774 $this->output( "...index $index already set on $table table.\n" );
775 } else {
776 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
777 }
778
779 return true;
780 }
781
782 /**
783 * Drop a field from an existing table
784 *
785 * @param string $table Name of the table to modify
786 * @param string $field Name of the old field
787 * @param string $patch Path to the patch file
788 * @param bool $fullpath Whether to treat $patch path as a relative or not
789 * @return bool False if this was skipped because schema changes are skipped
790 */
791 protected function dropField( $table, $field, $patch, $fullpath = false ) {
792 if ( !$this->doTable( $table ) ) {
793 return true;
794 }
795
796 if ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
797 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
798 } else {
799 $this->output( "...$table table does not contain $field field.\n" );
800 }
801
802 return true;
803 }
804
805 /**
806 * Drop an index from an existing table
807 *
808 * @param string $table Name of the table to modify
809 * @param string $index Name of the index
810 * @param string $patch Path to the patch file
811 * @param bool $fullpath Whether to treat $patch path as a relative or not
812 * @return bool False if this was skipped because schema changes are skipped
813 */
814 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
815 if ( !$this->doTable( $table ) ) {
816 return true;
817 }
818
819 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
820 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
821 } else {
822 $this->output( "...$index key doesn't exist.\n" );
823 }
824
825 return true;
826 }
827
828 /**
829 * Rename an index from an existing table
830 *
831 * @param string $table Name of the table to modify
832 * @param string $oldIndex Old name of the index
833 * @param string $newIndex New name of the index
834 * @param bool $skipBothIndexExistWarning Whether to warn if both the
835 * old and the new indexes exist.
836 * @param string $patch Path to the patch file
837 * @param bool $fullpath Whether to treat $patch path as a relative or not
838 * @return bool False if this was skipped because schema changes are skipped
839 */
840 protected function renameIndex( $table, $oldIndex, $newIndex,
841 $skipBothIndexExistWarning, $patch, $fullpath = false
842 ) {
843 if ( !$this->doTable( $table ) ) {
844 return true;
845 }
846
847 // First requirement: the table must exist
848 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
849 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
850
851 return true;
852 }
853
854 // Second requirement: the new index must be missing
855 if ( $this->db->indexExists( $table, $newIndex, __METHOD__ ) ) {
856 $this->output( "...index $newIndex already set on $table table.\n" );
857 if ( !$skipBothIndexExistWarning &&
858 $this->db->indexExists( $table, $oldIndex, __METHOD__ )
859 ) {
860 $this->output( "...WARNING: $oldIndex still exists, despite it has " .
861 "been renamed into $newIndex (which also exists).\n" .
862 " $oldIndex should be manually removed if not needed anymore.\n" );
863 }
864
865 return true;
866 }
867
868 // Third requirement: the old index must exist
869 if ( !$this->db->indexExists( $table, $oldIndex, __METHOD__ ) ) {
870 $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
871
872 return true;
873 }
874
875 // Requirements have been satisfied, patch can be applied
876 return $this->applyPatch(
877 $patch,
878 $fullpath,
879 "Renaming index $oldIndex into $newIndex to table $table"
880 );
881 }
882
883 /**
884 * If the specified table exists, drop it, or execute the
885 * patch if one is provided.
886 *
887 * Public @since 1.20
888 *
889 * @param string $table Table to drop.
890 * @param string|bool $patch String of patch file that will drop the table. Default: false.
891 * @param bool $fullpath Whether $patch is a full path. Default: false.
892 * @return bool False if this was skipped because schema changes are skipped
893 */
894 public function dropTable( $table, $patch = false, $fullpath = false ) {
895 if ( !$this->doTable( $table ) ) {
896 return true;
897 }
898
899 if ( $this->db->tableExists( $table, __METHOD__ ) ) {
900 $msg = "Dropping table $table";
901
902 if ( $patch === false ) {
903 $this->output( "$msg ..." );
904 $this->db->dropTable( $table, __METHOD__ );
905 $this->output( "done.\n" );
906 } else {
907 return $this->applyPatch( $patch, $fullpath, $msg );
908 }
909 } else {
910 $this->output( "...$table doesn't exist.\n" );
911 }
912
913 return true;
914 }
915
916 /**
917 * Modify an existing field
918 *
919 * @param string $table Name of the table to which the field belongs
920 * @param string $field Name of the field to modify
921 * @param string $patch Path to the patch file
922 * @param bool $fullpath Whether to treat $patch path as a relative or not
923 * @return bool False if this was skipped because schema changes are skipped
924 */
925 public function modifyField( $table, $field, $patch, $fullpath = false ) {
926 if ( !$this->doTable( $table ) ) {
927 return true;
928 }
929
930 $updateKey = "$table-$field-$patch";
931 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
932 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
933 } elseif ( !$this->db->fieldExists( $table, $field, __METHOD__ ) ) {
934 $this->output( "...$field field does not exist in $table table, " .
935 "skipping modify field patch.\n" );
936 } elseif ( $this->updateRowExists( $updateKey ) ) {
937 $this->output( "...$field in table $table already modified by patch $patch.\n" );
938 } else {
939 $this->insertUpdateRow( $updateKey );
940
941 return $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
942 }
943
944 return true;
945 }
946
947 /**
948 * Set any .htaccess files or equivilent for storage repos
949 *
950 * Some zones (e.g. "temp") used to be public and may have been initialized as such
951 */
952 public function setFileAccess() {
953 $repo = RepoGroup::singleton()->getLocalRepo();
954 $zonePath = $repo->getZonePath( 'temp' );
955 if ( $repo->getBackend()->directoryExists( [ 'dir' => $zonePath ] ) ) {
956 // If the directory was never made, then it will have the right ACLs when it is made
957 $status = $repo->getBackend()->secure( [
958 'dir' => $zonePath,
959 'noAccess' => true,
960 'noListing' => true
961 ] );
962 if ( $status->isOK() ) {
963 $this->output( "Set the local repo temp zone container to be private.\n" );
964 } else {
965 $this->output( "Failed to set the local repo temp zone container to be private.\n" );
966 }
967 }
968 }
969
970 /**
971 * Purge the objectcache table
972 */
973 public function purgeCache() {
974 global $wgLocalisationCacheConf;
975 # We can't guarantee that the user will be able to use TRUNCATE,
976 # but we know that DELETE is available to us
977 $this->output( "Purging caches..." );
978 $this->db->delete( 'objectcache', '*', __METHOD__ );
979 if ( $wgLocalisationCacheConf['manualRecache'] ) {
980 $this->rebuildLocalisationCache();
981 }
982 $blobStore = new MessageBlobStore();
983 $blobStore->clear();
984 $this->db->delete( 'module_deps', '*', __METHOD__ );
985 $this->output( "done.\n" );
986 }
987
988 /**
989 * Check the site_stats table is not properly populated.
990 */
991 protected function checkStats() {
992 $this->output( "...site_stats is populated..." );
993 $row = $this->db->selectRow( 'site_stats', '*', [ 'ss_row_id' => 1 ], __METHOD__ );
994 if ( $row === false ) {
995 $this->output( "data is missing! rebuilding...\n" );
996 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
997 $this->output( "missing ss_total_pages, rebuilding...\n" );
998 } else {
999 $this->output( "done.\n" );
1000
1001 return;
1002 }
1003 SiteStatsInit::doAllAndCommit( $this->db );
1004 }
1005
1006 # Common updater functions
1007
1008 /**
1009 * Sets the number of active users in the site_stats table
1010 */
1011 protected function doActiveUsersInit() {
1012 $activeUsers = $this->db->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
1013 if ( $activeUsers == -1 ) {
1014 $activeUsers = $this->db->selectField( 'recentchanges',
1015 'COUNT( DISTINCT rc_user_text )',
1016 [ 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ], __METHOD__
1017 );
1018 $this->db->update( 'site_stats',
1019 [ 'ss_active_users' => intval( $activeUsers ) ],
1020 [ 'ss_row_id' => 1 ], __METHOD__, [ 'LIMIT' => 1 ]
1021 );
1022 }
1023 $this->output( "...ss_active_users user count set...\n" );
1024 }
1025
1026 /**
1027 * Populates the log_user_text field in the logging table
1028 */
1029 protected function doLogUsertextPopulation() {
1030 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
1031 $this->output(
1032 "Populating log_user_text field, printing progress markers. For large\n" .
1033 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1034 "maintenance/populateLogUsertext.php.\n"
1035 );
1036
1037 $task = $this->maintenance->runChild( 'PopulateLogUsertext' );
1038 $task->execute();
1039 $this->output( "done.\n" );
1040 }
1041 }
1042
1043 /**
1044 * Migrate log params to new table and index for searching
1045 */
1046 protected function doLogSearchPopulation() {
1047 if ( !$this->updateRowExists( 'populate log_search' ) ) {
1048 $this->output(
1049 "Populating log_search table, printing progress markers. For large\n" .
1050 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1051 "maintenance/populateLogSearch.php.\n" );
1052
1053 $task = $this->maintenance->runChild( 'PopulateLogSearch' );
1054 $task->execute();
1055 $this->output( "done.\n" );
1056 }
1057 }
1058
1059 /**
1060 * Updates the timestamps in the transcache table
1061 * @return bool
1062 */
1063 protected function doUpdateTranscacheField() {
1064 if ( $this->updateRowExists( 'convert transcache field' ) ) {
1065 $this->output( "...transcache tc_time already converted.\n" );
1066
1067 return true;
1068 }
1069
1070 return $this->applyPatch( 'patch-tc-timestamp.sql', false,
1071 "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
1072 }
1073
1074 /**
1075 * Update CategoryLinks collation
1076 */
1077 protected function doCollationUpdate() {
1078 global $wgCategoryCollation;
1079 if ( $this->db->fieldExists( 'categorylinks', 'cl_collation', __METHOD__ ) ) {
1080 if ( $this->db->selectField(
1081 'categorylinks',
1082 'COUNT(*)',
1083 'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
1084 __METHOD__
1085 ) == 0
1086 ) {
1087 $this->output( "...collations up-to-date.\n" );
1088
1089 return;
1090 }
1091
1092 $this->output( "Updating category collations..." );
1093 $task = $this->maintenance->runChild( 'UpdateCollation' );
1094 $task->execute();
1095 $this->output( "...done.\n" );
1096 }
1097 }
1098
1099 /**
1100 * Migrates user options from the user table blob to user_properties
1101 */
1102 protected function doMigrateUserOptions() {
1103 if ( $this->db->tableExists( 'user_properties' ) ) {
1104 $cl = $this->maintenance->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
1105 $cl->execute();
1106 $this->output( "done.\n" );
1107 }
1108 }
1109
1110 /**
1111 * Enable profiling table when it's turned on
1112 */
1113 protected function doEnableProfiling() {
1114 global $wgProfiler;
1115
1116 if ( !$this->doTable( 'profiling' ) ) {
1117 return;
1118 }
1119
1120 $profileToDb = false;
1121 if ( isset( $wgProfiler['output'] ) ) {
1122 $out = $wgProfiler['output'];
1123 if ( $out === 'db' ) {
1124 $profileToDb = true;
1125 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
1126 $profileToDb = true;
1127 }
1128 }
1129
1130 if ( $profileToDb && !$this->db->tableExists( 'profiling', __METHOD__ ) ) {
1131 $this->applyPatch( 'patch-profiling.sql', false, 'Add profiling table' );
1132 }
1133 }
1134
1135 /**
1136 * Rebuilds the localisation cache
1137 */
1138 protected function rebuildLocalisationCache() {
1139 /**
1140 * @var $cl RebuildLocalisationCache
1141 */
1142 $cl = $this->maintenance->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
1143 $this->output( "Rebuilding localisation cache...\n" );
1144 $cl->setForce();
1145 $cl->execute();
1146 $this->output( "done.\n" );
1147 }
1148
1149 /**
1150 * Turns off content handler fields during parts of the upgrade
1151 * where they aren't available.
1152 */
1153 protected function disableContentHandlerUseDB() {
1154 global $wgContentHandlerUseDB;
1155
1156 if ( $wgContentHandlerUseDB ) {
1157 $this->output( "Turning off Content Handler DB fields for this part of upgrade.\n" );
1158 $this->holdContentHandlerUseDB = $wgContentHandlerUseDB;
1159 $wgContentHandlerUseDB = false;
1160 }
1161 }
1162
1163 /**
1164 * Turns content handler fields back on.
1165 */
1166 protected function enableContentHandlerUseDB() {
1167 global $wgContentHandlerUseDB;
1168
1169 if ( $this->holdContentHandlerUseDB ) {
1170 $this->output( "Content Handler DB fields should be usable now.\n" );
1171 $wgContentHandlerUseDB = $this->holdContentHandlerUseDB;
1172 }
1173 }
1174 }