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