3 * DBMS-specific updater helper.
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.
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.
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
24 require_once __DIR__
. '/../../maintenance/Maintenance.php';
27 * Class for handling database updates. Roughly based off of updaters.inc, with
28 * a few improvements :)
33 abstract class DatabaseUpdater
{
34 protected static $updateCounter = 0;
37 * Array of updates to perform on the database
41 protected $updates = [];
44 * Array of updates that were skipped
48 protected $updatesSkipped = [];
51 * List of extension-provided database updates
54 protected $extensionUpdates = [];
57 * Handle to the database subclass
63 protected $shared = false;
66 * @var string[] Scripts to run after database update
67 * Should be a subclass of LoggedUpdateMaintenance
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,
82 * File handle for SQL output.
86 protected $fileHandle = null;
89 * Flag specifying whether or not to skip schema (e.g. SQL-only) updates.
93 protected $skipSchema = false;
96 * Hold the value of $wgContentHandlerUseDB during the upgrade.
98 protected $holdContentHandlerUseDB = true;
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
107 protected function __construct( DatabaseBase
&$db, $shared, Maintenance
$maintenance = null ) {
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
;
115 $this->maintenance
= new FakeMaintenance
;
117 $this->maintenance
->setDB( $db );
118 $this->initOldGlobals();
119 $this->loadExtensions();
120 Hooks
::run( 'LoadExtensionSchemaUpdates', [ $this ] );
124 * Initialize all of the old globals. One day this should all become
125 * something much nicer
127 private function initOldGlobals() {
128 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
129 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
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
142 * Loads LocalSettings.php, if needed, and initialises everything needed for
143 * LoadExtensionSchemaUpdates hook.
145 private function loadExtensions() {
146 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
147 return; // already loaded
149 $vars = Installer
::getExistingLocalSettings();
151 $registry = ExtensionRegistry
::getInstance();
152 $queue = $registry->getQueue();
153 // Don't accidentally load extensions in the future
154 $registry->clearQueue();
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'];
162 if ( $vars && isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
163 $hooks = array_merge_recursive( $hooks, $vars['wgHooks']['LoadExtensionSchemaUpdates'] );
165 global $wgHooks, $wgAutoloadClasses;
166 $wgHooks['LoadExtensionSchemaUpdates'] = $hooks;
167 if ( $vars && isset( $vars['wgAutoloadClasses'] ) ) {
168 $wgAutoloadClasses +
= $vars['wgAutoloadClasses'];
173 * @param DatabaseBase $db
174 * @param bool $shared
175 * @param Maintenance $maintenance
177 * @throws MWException
178 * @return DatabaseUpdater
180 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
181 $type = $db->getType();
182 if ( in_array( $type, Installer
::getDBTypes() ) ) {
183 $class = ucfirst( $type ) . 'Updater';
185 return new $class( $db, $shared, $maintenance );
187 throw new MWException( __METHOD__
. ' called for unsupported $wgDBtype' );
192 * Get a database connection to run updates
194 * @return DatabaseBase
196 public function getDB() {
201 * Output some text. If we're running from web, escape the text first.
203 * @param string $str Text to output
205 public function output( $str ) {
206 if ( $this->maintenance
->isQuiet() ) {
209 global $wgCommandLineMode;
210 if ( !$wgCommandLineMode ) {
211 $str = htmlspecialchars( $str );
218 * Add a new update coming from an extension. This should be called by
219 * extensions while executing the LoadExtensionSchemaUpdates hook.
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
230 public function addExtensionUpdate( array $update ) {
231 $this->extensionUpdates
[] = $update;
235 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
236 * is the most common usage of updaters in an extension)
240 * @param string $tableName Name of table to create
241 * @param string $sqlPath Full path to the schema file
243 public function addExtensionTable( $tableName, $sqlPath ) {
244 $this->extensionUpdates
[] = [ 'addTable', $tableName, $sqlPath, true ];
250 * @param string $tableName
251 * @param string $indexName
252 * @param string $sqlPath
254 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
255 $this->extensionUpdates
[] = [ 'addIndex', $tableName, $indexName, $sqlPath, true ];
262 * @param string $tableName
263 * @param string $columnName
264 * @param string $sqlPath
266 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
267 $this->extensionUpdates
[] = [ 'addField', $tableName, $columnName, $sqlPath, true ];
274 * @param string $tableName
275 * @param string $columnName
276 * @param string $sqlPath
278 public function dropExtensionField( $tableName, $columnName, $sqlPath ) {
279 $this->extensionUpdates
[] = [ 'dropField', $tableName, $columnName, $sqlPath, true ];
283 * Drop an index from an extension table
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
291 public function dropExtensionIndex( $tableName, $indexName, $sqlPath ) {
292 $this->extensionUpdates
[] = [ 'dropIndex', $tableName, $indexName, $sqlPath, true ];
299 * @param string $tableName
300 * @param string $sqlPath
302 public function dropExtensionTable( $tableName, $sqlPath ) {
303 $this->extensionUpdates
[] = [ 'dropTable', $tableName, $sqlPath, true ];
307 * Rename an index on an extension table
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]
318 public function renameExtensionIndex( $tableName, $oldIndexName, $newIndexName,
319 $sqlPath, $skipBothIndexExistWarning = false
321 $this->extensionUpdates
[] = [
326 $skipBothIndexExistWarning,
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
339 public function modifyExtensionField( $tableName, $fieldName, $sqlPath ) {
340 $this->extensionUpdates
[] = [ 'modifyField', $tableName, $fieldName, $sqlPath, true ];
347 * @param string $tableName
350 public function tableExists( $tableName ) {
351 return ( $this->db
->tableExists( $tableName, __METHOD__
) );
355 * Add a maintenance script to be run after the database updates are complete.
357 * Script should subclass LoggedUpdateMaintenance
361 * @param string $class Name of a Maintenance subclass
363 public function addPostDatabaseUpdateMaintenance( $class ) {
364 $this->postDatabaseUpdateMaintenance
[] = $class;
368 * Get the list of extension-defined updates
372 protected function getExtensionUpdates() {
373 return $this->extensionUpdates
;
381 public function getPostDatabaseUpdateMaintenance() {
382 return $this->postDatabaseUpdateMaintenance
;
388 * Writes the schema updates desired to a file for the DB Admin to run.
389 * @param array $schemaUpdate
391 private function writeSchemaUpdateFile( $schemaUpdate = [] ) {
392 $updates = $this->updatesSkipped
;
393 $this->updatesSkipped
= [];
395 foreach ( $updates as $funcList ) {
396 $func = $funcList[0];
398 $origParams = $funcList[2];
399 call_user_func_array( $func, $arg );
401 $this->updatesSkipped
[] = $origParams;
408 * @param array $what What updates to perform
410 public function doUpdates( $what = [ 'core', 'extensions', 'stats' ] ) {
413 $what = array_flip( $what );
414 $this->skipSchema
= isset( $what['noschema'] ) ||
$this->fileHandle
!== null;
415 if ( isset( $what['core'] ) ) {
416 $this->runUpdates( $this->getCoreUpdateList(), false );
418 if ( isset( $what['extensions'] ) ) {
419 $this->runUpdates( $this->getOldGlobalUpdates(), false );
420 $this->runUpdates( $this->getExtensionUpdates(), true );
423 if ( isset( $what['stats'] ) ) {
427 $this->setAppliedUpdates( $wgVersion, $this->updates
);
429 if ( $this->fileHandle
) {
430 $this->skipSchema
= false;
431 $this->writeSchemaUpdateFile();
432 $this->setAppliedUpdates( "$wgVersion-schema", $this->updatesSkipped
);
437 * Helper function for doUpdates()
439 * @param array $updates Array of updates to run
440 * @param bool $passSelf Whether to pass this object we calling external functions
442 private function runUpdates( array $updates, $passSelf ) {
444 $updatesSkipped = [];
445 foreach ( $updates as $params ) {
446 $origParams = $params;
447 $func = array_shift( $params );
448 if ( !is_array( $func ) && method_exists( $this, $func ) ) {
449 $func = [ $this, $func ];
450 } elseif ( $passSelf ) {
451 array_unshift( $params, $this );
453 $ret = call_user_func_array( $func, $params );
455 if ( $ret !== false ) {
456 $updatesDone[] = $origParams;
457 wfGetLBFactory()->waitForReplication();
459 $updatesSkipped[] = [ $func, $params, $origParams ];
462 $this->updatesSkipped
= array_merge( $this->updatesSkipped
, $updatesSkipped );
463 $this->updates
= array_merge( $this->updates
, $updatesDone );
467 * @param string $version
468 * @param array $updates
470 protected function setAppliedUpdates( $version, $updates = [] ) {
471 $this->db
->clearFlag( DBO_DDLMODE
);
472 if ( !$this->canUseNewUpdatelog() ) {
475 $key = "updatelist-$version-" . time() . self
::$updateCounter;
476 self
::$updateCounter++
;
477 $this->db
->insert( 'updatelog',
478 [ 'ul_key' => $key, 'ul_value' => serialize( $updates ) ],
480 $this->db
->setFlag( DBO_DDLMODE
);
484 * Helper function: check if the given key is present in the updatelog table.
485 * Obviously, only use this for updates that occur after the updatelog table was
487 * @param string $key Name of the key to check for
490 public function updateRowExists( $key ) {
491 $row = $this->db
->selectRow(
495 [ 'ul_key' => $key ],
503 * Helper function: Add a key to the updatelog table
504 * Obviously, only use this for updates that occur after the updatelog table was
506 * @param string $key Name of key to insert
507 * @param string $val [optional] Value to insert along with the key
509 public function insertUpdateRow( $key, $val = null ) {
510 $this->db
->clearFlag( DBO_DDLMODE
);
511 $values = [ 'ul_key' => $key ];
512 if ( $val && $this->canUseNewUpdatelog() ) {
513 $values['ul_value'] = $val;
515 $this->db
->insert( 'updatelog', $values, __METHOD__
, 'IGNORE' );
516 $this->db
->setFlag( DBO_DDLMODE
);
520 * Updatelog was changed in 1.17 to have a ul_value column so we can record
521 * more information about what kind of updates we've done (that's what this
522 * class does). Pre-1.17 wikis won't have this column, and really old wikis
523 * might not even have updatelog at all
527 protected function canUseNewUpdatelog() {
528 return $this->db
->tableExists( 'updatelog', __METHOD__
) &&
529 $this->db
->fieldExists( 'updatelog', 'ul_value', __METHOD__
);
533 * Returns whether updates should be executed on the database table $name.
534 * Updates will be prevented if the table is a shared table and it is not
535 * specified to run updates on shared tables.
537 * @param string $name Table name
540 protected function doTable( $name ) {
541 global $wgSharedDB, $wgSharedTables;
543 // Don't bother to check $wgSharedTables if there isn't a shared database
544 // or the user actually also wants to do updates on the shared database.
545 if ( $wgSharedDB === null ||
$this->shared
) {
549 if ( in_array( $name, $wgSharedTables ) ) {
550 $this->output( "...skipping update to shared table $name.\n" );
558 * Before 1.17, we used to handle updates via stuff like
559 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
560 * of this in 1.17 but we want to remain back-compatible for a while. So
561 * load up these old global-based things into our update list.
565 protected function getOldGlobalUpdates() {
566 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
571 foreach ( $wgExtNewTables as $tableRecord ) {
573 'addTable', $tableRecord[0], $tableRecord[1], true
577 foreach ( $wgExtNewFields as $fieldRecord ) {
579 'addField', $fieldRecord[0], $fieldRecord[1],
580 $fieldRecord[2], true
584 foreach ( $wgExtNewIndexes as $fieldRecord ) {
586 'addIndex', $fieldRecord[0], $fieldRecord[1],
587 $fieldRecord[2], true
591 foreach ( $wgExtModifiedFields as $fieldRecord ) {
593 'modifyField', $fieldRecord[0], $fieldRecord[1],
594 $fieldRecord[2], true
602 * Get an array of updates to perform on the database. Should return a
603 * multi-dimensional array. The main key is the MediaWiki version (1.12,
604 * 1.13...) with the values being arrays of updates, identical to how
605 * updaters.inc did it (for now)
609 abstract protected function getCoreUpdateList();
612 * Append an SQL fragment to the open file handle.
614 * @param string $filename File name to open
616 public function copyFile( $filename ) {
617 $this->db
->sourceFile( $filename, false, false, false,
618 [ $this, 'appendLine' ]
623 * Append a line to the open filehandle. The line is assumed to
624 * be a complete SQL statement.
626 * This is used as a callback for sourceLine().
628 * @param string $line Text to append to the file
629 * @return bool False to skip actually executing the file
630 * @throws MWException
632 public function appendLine( $line ) {
633 $line = rtrim( $line ) . ";\n";
634 if ( fwrite( $this->fileHandle
, $line ) === false ) {
635 throw new MWException( "trouble writing file" );
642 * Applies a SQL patch
644 * @param string $path Path to the patch file
645 * @param bool $isFullPath Whether to treat $path as a relative or not
646 * @param string $msg Description of the patch
647 * @return bool False if patch is skipped.
649 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
650 if ( $msg === null ) {
651 $msg = "Applying $path patch";
653 if ( $this->skipSchema
) {
654 $this->output( "...skipping schema change ($msg).\n" );
659 $this->output( "$msg ..." );
661 if ( !$isFullPath ) {
662 $path = $this->patchPath( $this->db
, $path );
664 if ( $this->fileHandle
!== null ) {
665 $this->copyFile( $path );
667 $this->db
->sourceFile( $path );
669 $this->output( "done.\n" );
675 * Get the full path of a patch file. Originally based on archive()
676 * from updaters.inc. Keep in mind this always returns a patch, as
677 * it fails back to MySQL if no DB-specific patch can be found
679 * @param IDatabase $db
680 * @param string $patch The name of the patch, like patch-something.sql
681 * @return string Full path to patch file
683 public function patchPath( IDatabase
$db, $patch ) {
686 $dbType = $db->getType();
687 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
688 return "$IP/maintenance/$dbType/archives/$patch";
690 return "$IP/maintenance/archives/$patch";
695 * Add a new table to the database
697 * @param string $name Name of the new table
698 * @param string $patch Path to the patch file
699 * @param bool $fullpath Whether to treat $patch path as a relative or not
700 * @return bool False if this was skipped because schema changes are skipped
702 protected function addTable( $name, $patch, $fullpath = false ) {
703 if ( !$this->doTable( $name ) ) {
707 if ( $this->db
->tableExists( $name, __METHOD__
) ) {
708 $this->output( "...$name table already exists.\n" );
710 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
717 * Add a new field to an existing table
719 * @param string $table Name of the table to modify
720 * @param string $field Name of the new field
721 * @param string $patch Path to the patch file
722 * @param bool $fullpath Whether to treat $patch path as a relative or not
723 * @return bool False if this was skipped because schema changes are skipped
725 protected function addField( $table, $field, $patch, $fullpath = false ) {
726 if ( !$this->doTable( $table ) ) {
730 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
731 $this->output( "...$table table does not exist, skipping new field patch.\n" );
732 } elseif ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
733 $this->output( "...have $field field in $table table.\n" );
735 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
742 * Add a new index to an existing table
744 * @param string $table Name of the table to modify
745 * @param string $index Name of the new index
746 * @param string $patch Path to the patch file
747 * @param bool $fullpath Whether to treat $patch path as a relative or not
748 * @return bool False if this was skipped because schema changes are skipped
750 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
751 if ( !$this->doTable( $table ) ) {
755 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
756 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
757 } elseif ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
758 $this->output( "...index $index already set on $table table.\n" );
760 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
767 * Drop a field from an existing table
769 * @param string $table Name of the table to modify
770 * @param string $field Name of the old field
771 * @param string $patch Path to the patch file
772 * @param bool $fullpath Whether to treat $patch path as a relative or not
773 * @return bool False if this was skipped because schema changes are skipped
775 protected function dropField( $table, $field, $patch, $fullpath = false ) {
776 if ( !$this->doTable( $table ) ) {
780 if ( $this->db
->fieldExists( $table, $field, __METHOD__
) ) {
781 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
783 $this->output( "...$table table does not contain $field field.\n" );
790 * Drop an index from an existing table
792 * @param string $table Name of the table to modify
793 * @param string $index Name of the index
794 * @param string $patch Path to the patch file
795 * @param bool $fullpath Whether to treat $patch path as a relative or not
796 * @return bool False if this was skipped because schema changes are skipped
798 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
799 if ( !$this->doTable( $table ) ) {
803 if ( $this->db
->indexExists( $table, $index, __METHOD__
) ) {
804 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
806 $this->output( "...$index key doesn't exist.\n" );
813 * Rename an index from an existing table
815 * @param string $table Name of the table to modify
816 * @param string $oldIndex Old name of the index
817 * @param string $newIndex New name of the index
818 * @param bool $skipBothIndexExistWarning Whether to warn if both the
819 * old and the new indexes exist.
820 * @param string $patch Path to the patch file
821 * @param bool $fullpath Whether to treat $patch path as a relative or not
822 * @return bool False if this was skipped because schema changes are skipped
824 protected function renameIndex( $table, $oldIndex, $newIndex,
825 $skipBothIndexExistWarning, $patch, $fullpath = false
827 if ( !$this->doTable( $table ) ) {
831 // First requirement: the table must exist
832 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
833 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
838 // Second requirement: the new index must be missing
839 if ( $this->db
->indexExists( $table, $newIndex, __METHOD__
) ) {
840 $this->output( "...index $newIndex already set on $table table.\n" );
841 if ( !$skipBothIndexExistWarning &&
842 $this->db
->indexExists( $table, $oldIndex, __METHOD__
)
844 $this->output( "...WARNING: $oldIndex still exists, despite it has " .
845 "been renamed into $newIndex (which also exists).\n" .
846 " $oldIndex should be manually removed if not needed anymore.\n" );
852 // Third requirement: the old index must exist
853 if ( !$this->db
->indexExists( $table, $oldIndex, __METHOD__
) ) {
854 $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
859 // Requirements have been satisfied, patch can be applied
860 return $this->applyPatch(
863 "Renaming index $oldIndex into $newIndex to table $table"
868 * If the specified table exists, drop it, or execute the
869 * patch if one is provided.
873 * @param string $table Table to drop.
874 * @param string|bool $patch String of patch file that will drop the table. Default: false.
875 * @param bool $fullpath Whether $patch is a full path. Default: false.
876 * @return bool False if this was skipped because schema changes are skipped
878 public function dropTable( $table, $patch = false, $fullpath = false ) {
879 if ( !$this->doTable( $table ) ) {
883 if ( $this->db
->tableExists( $table, __METHOD__
) ) {
884 $msg = "Dropping table $table";
886 if ( $patch === false ) {
887 $this->output( "$msg ..." );
888 $this->db
->dropTable( $table, __METHOD__
);
889 $this->output( "done.\n" );
891 return $this->applyPatch( $patch, $fullpath, $msg );
894 $this->output( "...$table doesn't exist.\n" );
901 * Modify an existing field
903 * @param string $table Name of the table to which the field belongs
904 * @param string $field Name of the field to modify
905 * @param string $patch Path to the patch file
906 * @param bool $fullpath Whether to treat $patch path as a relative or not
907 * @return bool False if this was skipped because schema changes are skipped
909 public function modifyField( $table, $field, $patch, $fullpath = false ) {
910 if ( !$this->doTable( $table ) ) {
914 $updateKey = "$table-$field-$patch";
915 if ( !$this->db
->tableExists( $table, __METHOD__
) ) {
916 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
917 } elseif ( !$this->db
->fieldExists( $table, $field, __METHOD__
) ) {
918 $this->output( "...$field field does not exist in $table table, " .
919 "skipping modify field patch.\n" );
920 } elseif ( $this->updateRowExists( $updateKey ) ) {
921 $this->output( "...$field in table $table already modified by patch $patch.\n" );
923 $this->insertUpdateRow( $updateKey );
925 return $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
932 * Set any .htaccess files or equivilent for storage repos
934 * Some zones (e.g. "temp") used to be public and may have been initialized as such
936 public function setFileAccess() {
937 $repo = RepoGroup
::singleton()->getLocalRepo();
938 $zonePath = $repo->getZonePath( 'temp' );
939 if ( $repo->getBackend()->directoryExists( [ 'dir' => $zonePath ] ) ) {
940 // If the directory was never made, then it will have the right ACLs when it is made
941 $status = $repo->getBackend()->secure( [
946 if ( $status->isOK() ) {
947 $this->output( "Set the local repo temp zone container to be private.\n" );
949 $this->output( "Failed to set the local repo temp zone container to be private.\n" );
955 * Purge the objectcache table
957 public function purgeCache() {
958 global $wgLocalisationCacheConf;
959 # We can't guarantee that the user will be able to use TRUNCATE,
960 # but we know that DELETE is available to us
961 $this->output( "Purging caches..." );
962 $this->db
->delete( 'objectcache', '*', __METHOD__
);
963 if ( $wgLocalisationCacheConf['manualRecache'] ) {
964 $this->rebuildLocalisationCache();
966 $blobStore = new MessageBlobStore();
968 $this->db
->delete( 'module_deps', '*', __METHOD__
);
969 $this->output( "done.\n" );
973 * Check the site_stats table is not properly populated.
975 protected function checkStats() {
976 $this->output( "...site_stats is populated..." );
977 $row = $this->db
->selectRow( 'site_stats', '*', [ 'ss_row_id' => 1 ], __METHOD__
);
978 if ( $row === false ) {
979 $this->output( "data is missing! rebuilding...\n" );
980 } elseif ( isset( $row->site_stats
) && $row->ss_total_pages
== -1 ) {
981 $this->output( "missing ss_total_pages, rebuilding...\n" );
983 $this->output( "done.\n" );
987 SiteStatsInit
::doAllAndCommit( $this->db
);
990 # Common updater functions
993 * Sets the number of active users in the site_stats table
995 protected function doActiveUsersInit() {
996 $activeUsers = $this->db
->selectField( 'site_stats', 'ss_active_users', false, __METHOD__
);
997 if ( $activeUsers == -1 ) {
998 $activeUsers = $this->db
->selectField( 'recentchanges',
999 'COUNT( DISTINCT rc_user_text )',
1000 [ 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ], __METHOD__
1002 $this->db
->update( 'site_stats',
1003 [ 'ss_active_users' => intval( $activeUsers ) ],
1004 [ 'ss_row_id' => 1 ], __METHOD__
, [ 'LIMIT' => 1 ]
1007 $this->output( "...ss_active_users user count set...\n" );
1011 * Populates the log_user_text field in the logging table
1013 protected function doLogUsertextPopulation() {
1014 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
1016 "Populating log_user_text field, printing progress markers. For large\n" .
1017 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1018 "maintenance/populateLogUsertext.php.\n"
1021 $task = $this->maintenance
->runChild( 'PopulateLogUsertext' );
1023 $this->output( "done.\n" );
1028 * Migrate log params to new table and index for searching
1030 protected function doLogSearchPopulation() {
1031 if ( !$this->updateRowExists( 'populate log_search' ) ) {
1033 "Populating log_search table, printing progress markers. For large\n" .
1034 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1035 "maintenance/populateLogSearch.php.\n" );
1037 $task = $this->maintenance
->runChild( 'PopulateLogSearch' );
1039 $this->output( "done.\n" );
1044 * Updates the timestamps in the transcache table
1047 protected function doUpdateTranscacheField() {
1048 if ( $this->updateRowExists( 'convert transcache field' ) ) {
1049 $this->output( "...transcache tc_time already converted.\n" );
1054 return $this->applyPatch( 'patch-tc-timestamp.sql', false,
1055 "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
1059 * Update CategoryLinks collation
1061 protected function doCollationUpdate() {
1062 global $wgCategoryCollation;
1063 if ( $this->db
->fieldExists( 'categorylinks', 'cl_collation', __METHOD__
) ) {
1064 if ( $this->db
->selectField(
1067 'cl_collation != ' . $this->db
->addQuotes( $wgCategoryCollation ),
1071 $this->output( "...collations up-to-date.\n" );
1076 $this->output( "Updating category collations..." );
1077 $task = $this->maintenance
->runChild( 'UpdateCollation' );
1079 $this->output( "...done.\n" );
1084 * Migrates user options from the user table blob to user_properties
1086 protected function doMigrateUserOptions() {
1087 if ( $this->db
->tableExists( 'user_properties' ) ) {
1088 $cl = $this->maintenance
->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
1090 $this->output( "done.\n" );
1095 * Enable profiling table when it's turned on
1097 protected function doEnableProfiling() {
1100 if ( !$this->doTable( 'profiling' ) ) {
1104 $profileToDb = false;
1105 if ( isset( $wgProfiler['output'] ) ) {
1106 $out = $wgProfiler['output'];
1107 if ( $out === 'db' ) {
1108 $profileToDb = true;
1109 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
1110 $profileToDb = true;
1114 if ( $profileToDb && !$this->db
->tableExists( 'profiling', __METHOD__
) ) {
1115 $this->applyPatch( 'patch-profiling.sql', false, 'Add profiling table' );
1120 * Rebuilds the localisation cache
1122 protected function rebuildLocalisationCache() {
1124 * @var $cl RebuildLocalisationCache
1126 $cl = $this->maintenance
->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
1127 $this->output( "Rebuilding localisation cache...\n" );
1130 $this->output( "done.\n" );
1134 * Turns off content handler fields during parts of the upgrade
1135 * where they aren't available.
1137 protected function disableContentHandlerUseDB() {
1138 global $wgContentHandlerUseDB;
1140 if ( $wgContentHandlerUseDB ) {
1141 $this->output( "Turning off Content Handler DB fields for this part of upgrade.\n" );
1142 $this->holdContentHandlerUseDB
= $wgContentHandlerUseDB;
1143 $wgContentHandlerUseDB = false;
1148 * Turns content handler fields back on.
1150 protected function enableContentHandlerUseDB() {
1151 global $wgContentHandlerUseDB;
1153 if ( $this->holdContentHandlerUseDB
) {
1154 $this->output( "Content Handler DB fields should be usable now.\n" );
1155 $wgContentHandlerUseDB = $this->holdContentHandlerUseDB
;