Merge "Linker: Deprecate formatSize()"
[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 DatabaseBase $db
174 * @param bool $shared
175 * @param Maintenance $maintenance
176 *
177 * @throws MWException
178 * @return DatabaseUpdater
179 */
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';
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 * Do all the updates
407 *
408 * @param array $what What updates to perform
409 */
410 public function doUpdates( $what = [ 'core', 'extensions', 'stats' ] ) {
411 global $wgVersion;
412
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 );
417 }
418 if ( isset( $what['extensions'] ) ) {
419 $this->runUpdates( $this->getOldGlobalUpdates(), false );
420 $this->runUpdates( $this->getExtensionUpdates(), true );
421 }
422
423 if ( isset( $what['stats'] ) ) {
424 $this->checkStats();
425 }
426
427 $this->setAppliedUpdates( $wgVersion, $this->updates );
428
429 if ( $this->fileHandle ) {
430 $this->skipSchema = false;
431 $this->writeSchemaUpdateFile();
432 $this->setAppliedUpdates( "$wgVersion-schema", $this->updatesSkipped );
433 }
434 }
435
436 /**
437 * Helper function for doUpdates()
438 *
439 * @param array $updates Array of updates to run
440 * @param bool $passSelf Whether to pass this object we calling external functions
441 */
442 private function runUpdates( array $updates, $passSelf ) {
443 $updatesDone = [];
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 );
452 }
453 $ret = call_user_func_array( $func, $params );
454 flush();
455 if ( $ret !== false ) {
456 $updatesDone[] = $origParams;
457 wfGetLBFactory()->waitForReplication();
458 } else {
459 $updatesSkipped[] = [ $func, $params, $origParams ];
460 }
461 }
462 $this->updatesSkipped = array_merge( $this->updatesSkipped, $updatesSkipped );
463 $this->updates = array_merge( $this->updates, $updatesDone );
464 }
465
466 /**
467 * @param string $version
468 * @param array $updates
469 */
470 protected function setAppliedUpdates( $version, $updates = [] ) {
471 $this->db->clearFlag( DBO_DDLMODE );
472 if ( !$this->canUseNewUpdatelog() ) {
473 return;
474 }
475 $key = "updatelist-$version-" . time() . self::$updateCounter;
476 self::$updateCounter++;
477 $this->db->insert( 'updatelog',
478 [ 'ul_key' => $key, 'ul_value' => serialize( $updates ) ],
479 __METHOD__ );
480 $this->db->setFlag( DBO_DDLMODE );
481 }
482
483 /**
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
486 * created!
487 * @param string $key Name of the key to check for
488 * @return bool
489 */
490 public function updateRowExists( $key ) {
491 $row = $this->db->selectRow(
492 'updatelog',
493 # Bug 65813
494 '1 AS X',
495 [ 'ul_key' => $key ],
496 __METHOD__
497 );
498
499 return (bool)$row;
500 }
501
502 /**
503 * Helper function: Add a key to the updatelog table
504 * Obviously, only use this for updates that occur after the updatelog table was
505 * created!
506 * @param string $key Name of key to insert
507 * @param string $val [optional] Value to insert along with the key
508 */
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;
514 }
515 $this->db->insert( 'updatelog', $values, __METHOD__, 'IGNORE' );
516 $this->db->setFlag( DBO_DDLMODE );
517 }
518
519 /**
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
524 *
525 * @return bool
526 */
527 protected function canUseNewUpdatelog() {
528 return $this->db->tableExists( 'updatelog', __METHOD__ ) &&
529 $this->db->fieldExists( 'updatelog', 'ul_value', __METHOD__ );
530 }
531
532 /**
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.
536 *
537 * @param string $name Table name
538 * @return bool
539 */
540 protected function doTable( $name ) {
541 global $wgSharedDB, $wgSharedTables;
542
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 ) {
546 return true;
547 }
548
549 if ( in_array( $name, $wgSharedTables ) ) {
550 $this->output( "...skipping update to shared table $name.\n" );
551 return false;
552 } else {
553 return true;
554 }
555 }
556
557 /**
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.
562 *
563 * @return array
564 */
565 protected function getOldGlobalUpdates() {
566 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
567 $wgExtNewIndexes;
568
569 $updates = [];
570
571 foreach ( $wgExtNewTables as $tableRecord ) {
572 $updates[] = [
573 'addTable', $tableRecord[0], $tableRecord[1], true
574 ];
575 }
576
577 foreach ( $wgExtNewFields as $fieldRecord ) {
578 $updates[] = [
579 'addField', $fieldRecord[0], $fieldRecord[1],
580 $fieldRecord[2], true
581 ];
582 }
583
584 foreach ( $wgExtNewIndexes as $fieldRecord ) {
585 $updates[] = [
586 'addIndex', $fieldRecord[0], $fieldRecord[1],
587 $fieldRecord[2], true
588 ];
589 }
590
591 foreach ( $wgExtModifiedFields as $fieldRecord ) {
592 $updates[] = [
593 'modifyField', $fieldRecord[0], $fieldRecord[1],
594 $fieldRecord[2], true
595 ];
596 }
597
598 return $updates;
599 }
600
601 /**
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)
606 *
607 * @return array
608 */
609 abstract protected function getCoreUpdateList();
610
611 /**
612 * Append an SQL fragment to the open file handle.
613 *
614 * @param string $filename File name to open
615 */
616 public function copyFile( $filename ) {
617 $this->db->sourceFile( $filename, false, false, false,
618 [ $this, 'appendLine' ]
619 );
620 }
621
622 /**
623 * Append a line to the open filehandle. The line is assumed to
624 * be a complete SQL statement.
625 *
626 * This is used as a callback for sourceLine().
627 *
628 * @param string $line Text to append to the file
629 * @return bool False to skip actually executing the file
630 * @throws MWException
631 */
632 public function appendLine( $line ) {
633 $line = rtrim( $line ) . ";\n";
634 if ( fwrite( $this->fileHandle, $line ) === false ) {
635 throw new MWException( "trouble writing file" );
636 }
637
638 return false;
639 }
640
641 /**
642 * Applies a SQL patch
643 *
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.
648 */
649 protected function applyPatch( $path, $isFullPath = false, $msg = null ) {
650 if ( $msg === null ) {
651 $msg = "Applying $path patch";
652 }
653 if ( $this->skipSchema ) {
654 $this->output( "...skipping schema change ($msg).\n" );
655
656 return false;
657 }
658
659 $this->output( "$msg ..." );
660
661 if ( !$isFullPath ) {
662 $path = $this->patchPath( $this->db, $path );
663 }
664 if ( $this->fileHandle !== null ) {
665 $this->copyFile( $path );
666 } else {
667 $this->db->sourceFile( $path );
668 }
669 $this->output( "done.\n" );
670
671 return true;
672 }
673
674 /**
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
678 *
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
682 */
683 public function patchPath( IDatabase $db, $patch ) {
684 global $IP;
685
686 $dbType = $db->getType();
687 if ( file_exists( "$IP/maintenance/$dbType/archives/$patch" ) ) {
688 return "$IP/maintenance/$dbType/archives/$patch";
689 } else {
690 return "$IP/maintenance/archives/$patch";
691 }
692 }
693
694 /**
695 * Add a new table to the database
696 *
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
701 */
702 protected function addTable( $name, $patch, $fullpath = false ) {
703 if ( !$this->doTable( $name ) ) {
704 return true;
705 }
706
707 if ( $this->db->tableExists( $name, __METHOD__ ) ) {
708 $this->output( "...$name table already exists.\n" );
709 } else {
710 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
711 }
712
713 return true;
714 }
715
716 /**
717 * Add a new field to an existing table
718 *
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
724 */
725 protected function addField( $table, $field, $patch, $fullpath = false ) {
726 if ( !$this->doTable( $table ) ) {
727 return true;
728 }
729
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" );
734 } else {
735 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
736 }
737
738 return true;
739 }
740
741 /**
742 * Add a new index to an existing table
743 *
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
749 */
750 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
751 if ( !$this->doTable( $table ) ) {
752 return true;
753 }
754
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" );
759 } else {
760 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
761 }
762
763 return true;
764 }
765
766 /**
767 * Drop a field from an existing table
768 *
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
774 */
775 protected function dropField( $table, $field, $patch, $fullpath = false ) {
776 if ( !$this->doTable( $table ) ) {
777 return true;
778 }
779
780 if ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
781 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
782 } else {
783 $this->output( "...$table table does not contain $field field.\n" );
784 }
785
786 return true;
787 }
788
789 /**
790 * Drop an index from an existing table
791 *
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
797 */
798 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
799 if ( !$this->doTable( $table ) ) {
800 return true;
801 }
802
803 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
804 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
805 } else {
806 $this->output( "...$index key doesn't exist.\n" );
807 }
808
809 return true;
810 }
811
812 /**
813 * Rename an index from an existing table
814 *
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
823 */
824 protected function renameIndex( $table, $oldIndex, $newIndex,
825 $skipBothIndexExistWarning, $patch, $fullpath = false
826 ) {
827 if ( !$this->doTable( $table ) ) {
828 return true;
829 }
830
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" );
834
835 return true;
836 }
837
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__ )
843 ) {
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" );
847 }
848
849 return true;
850 }
851
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" );
855
856 return true;
857 }
858
859 // Requirements have been satisfied, patch can be applied
860 return $this->applyPatch(
861 $patch,
862 $fullpath,
863 "Renaming index $oldIndex into $newIndex to table $table"
864 );
865 }
866
867 /**
868 * If the specified table exists, drop it, or execute the
869 * patch if one is provided.
870 *
871 * Public @since 1.20
872 *
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
877 */
878 public function dropTable( $table, $patch = false, $fullpath = false ) {
879 if ( !$this->doTable( $table ) ) {
880 return true;
881 }
882
883 if ( $this->db->tableExists( $table, __METHOD__ ) ) {
884 $msg = "Dropping table $table";
885
886 if ( $patch === false ) {
887 $this->output( "$msg ..." );
888 $this->db->dropTable( $table, __METHOD__ );
889 $this->output( "done.\n" );
890 } else {
891 return $this->applyPatch( $patch, $fullpath, $msg );
892 }
893 } else {
894 $this->output( "...$table doesn't exist.\n" );
895 }
896
897 return true;
898 }
899
900 /**
901 * Modify an existing field
902 *
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
908 */
909 public function modifyField( $table, $field, $patch, $fullpath = false ) {
910 if ( !$this->doTable( $table ) ) {
911 return true;
912 }
913
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" );
922 } else {
923 $this->insertUpdateRow( $updateKey );
924
925 return $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
926 }
927
928 return true;
929 }
930
931 /**
932 * Set any .htaccess files or equivilent for storage repos
933 *
934 * Some zones (e.g. "temp") used to be public and may have been initialized as such
935 */
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( [
942 'dir' => $zonePath,
943 'noAccess' => true,
944 'noListing' => true
945 ] );
946 if ( $status->isOK() ) {
947 $this->output( "Set the local repo temp zone container to be private.\n" );
948 } else {
949 $this->output( "Failed to set the local repo temp zone container to be private.\n" );
950 }
951 }
952 }
953
954 /**
955 * Purge the objectcache table
956 */
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();
965 }
966 $blobStore = new MessageBlobStore();
967 $blobStore->clear();
968 $this->db->delete( 'module_deps', '*', __METHOD__ );
969 $this->output( "done.\n" );
970 }
971
972 /**
973 * Check the site_stats table is not properly populated.
974 */
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" );
982 } else {
983 $this->output( "done.\n" );
984
985 return;
986 }
987 SiteStatsInit::doAllAndCommit( $this->db );
988 }
989
990 # Common updater functions
991
992 /**
993 * Sets the number of active users in the site_stats table
994 */
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__
1001 );
1002 $this->db->update( 'site_stats',
1003 [ 'ss_active_users' => intval( $activeUsers ) ],
1004 [ 'ss_row_id' => 1 ], __METHOD__, [ 'LIMIT' => 1 ]
1005 );
1006 }
1007 $this->output( "...ss_active_users user count set...\n" );
1008 }
1009
1010 /**
1011 * Populates the log_user_text field in the logging table
1012 */
1013 protected function doLogUsertextPopulation() {
1014 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
1015 $this->output(
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"
1019 );
1020
1021 $task = $this->maintenance->runChild( 'PopulateLogUsertext' );
1022 $task->execute();
1023 $this->output( "done.\n" );
1024 }
1025 }
1026
1027 /**
1028 * Migrate log params to new table and index for searching
1029 */
1030 protected function doLogSearchPopulation() {
1031 if ( !$this->updateRowExists( 'populate log_search' ) ) {
1032 $this->output(
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" );
1036
1037 $task = $this->maintenance->runChild( 'PopulateLogSearch' );
1038 $task->execute();
1039 $this->output( "done.\n" );
1040 }
1041 }
1042
1043 /**
1044 * Updates the timestamps in the transcache table
1045 * @return bool
1046 */
1047 protected function doUpdateTranscacheField() {
1048 if ( $this->updateRowExists( 'convert transcache field' ) ) {
1049 $this->output( "...transcache tc_time already converted.\n" );
1050
1051 return true;
1052 }
1053
1054 return $this->applyPatch( 'patch-tc-timestamp.sql', false,
1055 "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
1056 }
1057
1058 /**
1059 * Update CategoryLinks collation
1060 */
1061 protected function doCollationUpdate() {
1062 global $wgCategoryCollation;
1063 if ( $this->db->fieldExists( 'categorylinks', 'cl_collation', __METHOD__ ) ) {
1064 if ( $this->db->selectField(
1065 'categorylinks',
1066 'COUNT(*)',
1067 'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
1068 __METHOD__
1069 ) == 0
1070 ) {
1071 $this->output( "...collations up-to-date.\n" );
1072
1073 return;
1074 }
1075
1076 $this->output( "Updating category collations..." );
1077 $task = $this->maintenance->runChild( 'UpdateCollation' );
1078 $task->execute();
1079 $this->output( "...done.\n" );
1080 }
1081 }
1082
1083 /**
1084 * Migrates user options from the user table blob to user_properties
1085 */
1086 protected function doMigrateUserOptions() {
1087 if ( $this->db->tableExists( 'user_properties' ) ) {
1088 $cl = $this->maintenance->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
1089 $cl->execute();
1090 $this->output( "done.\n" );
1091 }
1092 }
1093
1094 /**
1095 * Enable profiling table when it's turned on
1096 */
1097 protected function doEnableProfiling() {
1098 global $wgProfiler;
1099
1100 if ( !$this->doTable( 'profiling' ) ) {
1101 return;
1102 }
1103
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;
1111 }
1112 }
1113
1114 if ( $profileToDb && !$this->db->tableExists( 'profiling', __METHOD__ ) ) {
1115 $this->applyPatch( 'patch-profiling.sql', false, 'Add profiling table' );
1116 }
1117 }
1118
1119 /**
1120 * Rebuilds the localisation cache
1121 */
1122 protected function rebuildLocalisationCache() {
1123 /**
1124 * @var $cl RebuildLocalisationCache
1125 */
1126 $cl = $this->maintenance->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
1127 $this->output( "Rebuilding localisation cache...\n" );
1128 $cl->setForce();
1129 $cl->execute();
1130 $this->output( "done.\n" );
1131 }
1132
1133 /**
1134 * Turns off content handler fields during parts of the upgrade
1135 * where they aren't available.
1136 */
1137 protected function disableContentHandlerUseDB() {
1138 global $wgContentHandlerUseDB;
1139
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;
1144 }
1145 }
1146
1147 /**
1148 * Turns content handler fields back on.
1149 */
1150 protected function enableContentHandlerUseDB() {
1151 global $wgContentHandlerUseDB;
1152
1153 if ( $this->holdContentHandlerUseDB ) {
1154 $this->output( "Content Handler DB fields should be usable now.\n" );
1155 $wgContentHandlerUseDB = $this->holdContentHandlerUseDB;
1156 }
1157 }
1158 }