Merge "EditPage: Show a different label for the button on create vs. modify"
[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->db->patchPath( $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 * Add a new table to the database
676 *
677 * @param string $name Name of the new table
678 * @param string $patch Path to the patch file
679 * @param bool $fullpath Whether to treat $patch path as a relative or not
680 * @return bool False if this was skipped because schema changes are skipped
681 */
682 protected function addTable( $name, $patch, $fullpath = false ) {
683 if ( !$this->doTable( $name ) ) {
684 return true;
685 }
686
687 if ( $this->db->tableExists( $name, __METHOD__ ) ) {
688 $this->output( "...$name table already exists.\n" );
689 } else {
690 return $this->applyPatch( $patch, $fullpath, "Creating $name table" );
691 }
692
693 return true;
694 }
695
696 /**
697 * Add a new field to an existing table
698 *
699 * @param string $table Name of the table to modify
700 * @param string $field Name of the new field
701 * @param string $patch Path to the patch file
702 * @param bool $fullpath Whether to treat $patch path as a relative or not
703 * @return bool False if this was skipped because schema changes are skipped
704 */
705 protected function addField( $table, $field, $patch, $fullpath = false ) {
706 if ( !$this->doTable( $table ) ) {
707 return true;
708 }
709
710 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
711 $this->output( "...$table table does not exist, skipping new field patch.\n" );
712 } elseif ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
713 $this->output( "...have $field field in $table table.\n" );
714 } else {
715 return $this->applyPatch( $patch, $fullpath, "Adding $field field to table $table" );
716 }
717
718 return true;
719 }
720
721 /**
722 * Add a new index to an existing table
723 *
724 * @param string $table Name of the table to modify
725 * @param string $index Name of the new index
726 * @param string $patch Path to the patch file
727 * @param bool $fullpath Whether to treat $patch path as a relative or not
728 * @return bool False if this was skipped because schema changes are skipped
729 */
730 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
731 if ( !$this->doTable( $table ) ) {
732 return true;
733 }
734
735 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
736 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
737 } elseif ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
738 $this->output( "...index $index already set on $table table.\n" );
739 } else {
740 return $this->applyPatch( $patch, $fullpath, "Adding index $index to table $table" );
741 }
742
743 return true;
744 }
745
746 /**
747 * Drop a field from an existing table
748 *
749 * @param string $table Name of the table to modify
750 * @param string $field Name of the old field
751 * @param string $patch Path to the patch file
752 * @param bool $fullpath Whether to treat $patch path as a relative or not
753 * @return bool False if this was skipped because schema changes are skipped
754 */
755 protected function dropField( $table, $field, $patch, $fullpath = false ) {
756 if ( !$this->doTable( $table ) ) {
757 return true;
758 }
759
760 if ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
761 return $this->applyPatch( $patch, $fullpath, "Table $table contains $field field. Dropping" );
762 } else {
763 $this->output( "...$table table does not contain $field field.\n" );
764 }
765
766 return true;
767 }
768
769 /**
770 * Drop an index from an existing table
771 *
772 * @param string $table Name of the table to modify
773 * @param string $index Name of the index
774 * @param string $patch Path to the patch file
775 * @param bool $fullpath Whether to treat $patch path as a relative or not
776 * @return bool False if this was skipped because schema changes are skipped
777 */
778 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
779 if ( !$this->doTable( $table ) ) {
780 return true;
781 }
782
783 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
784 return $this->applyPatch( $patch, $fullpath, "Dropping $index index from table $table" );
785 } else {
786 $this->output( "...$index key doesn't exist.\n" );
787 }
788
789 return true;
790 }
791
792 /**
793 * Rename an index from an existing table
794 *
795 * @param string $table Name of the table to modify
796 * @param string $oldIndex Old name of the index
797 * @param string $newIndex New name of the index
798 * @param bool $skipBothIndexExistWarning Whether to warn if both the
799 * old and the new indexes exist.
800 * @param string $patch Path to the patch file
801 * @param bool $fullpath Whether to treat $patch path as a relative or not
802 * @return bool False if this was skipped because schema changes are skipped
803 */
804 protected function renameIndex( $table, $oldIndex, $newIndex,
805 $skipBothIndexExistWarning, $patch, $fullpath = false
806 ) {
807 if ( !$this->doTable( $table ) ) {
808 return true;
809 }
810
811 // First requirement: the table must exist
812 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
813 $this->output( "...skipping: '$table' table doesn't exist yet.\n" );
814
815 return true;
816 }
817
818 // Second requirement: the new index must be missing
819 if ( $this->db->indexExists( $table, $newIndex, __METHOD__ ) ) {
820 $this->output( "...index $newIndex already set on $table table.\n" );
821 if ( !$skipBothIndexExistWarning &&
822 $this->db->indexExists( $table, $oldIndex, __METHOD__ )
823 ) {
824 $this->output( "...WARNING: $oldIndex still exists, despite it has " .
825 "been renamed into $newIndex (which also exists).\n" .
826 " $oldIndex should be manually removed if not needed anymore.\n" );
827 }
828
829 return true;
830 }
831
832 // Third requirement: the old index must exist
833 if ( !$this->db->indexExists( $table, $oldIndex, __METHOD__ ) ) {
834 $this->output( "...skipping: index $oldIndex doesn't exist.\n" );
835
836 return true;
837 }
838
839 // Requirements have been satisfied, patch can be applied
840 return $this->applyPatch(
841 $patch,
842 $fullpath,
843 "Renaming index $oldIndex into $newIndex to table $table"
844 );
845 }
846
847 /**
848 * If the specified table exists, drop it, or execute the
849 * patch if one is provided.
850 *
851 * Public @since 1.20
852 *
853 * @param string $table Table to drop.
854 * @param string|bool $patch String of patch file that will drop the table. Default: false.
855 * @param bool $fullpath Whether $patch is a full path. Default: false.
856 * @return bool False if this was skipped because schema changes are skipped
857 */
858 public function dropTable( $table, $patch = false, $fullpath = false ) {
859 if ( !$this->doTable( $table ) ) {
860 return true;
861 }
862
863 if ( $this->db->tableExists( $table, __METHOD__ ) ) {
864 $msg = "Dropping table $table";
865
866 if ( $patch === false ) {
867 $this->output( "$msg ..." );
868 $this->db->dropTable( $table, __METHOD__ );
869 $this->output( "done.\n" );
870 } else {
871 return $this->applyPatch( $patch, $fullpath, $msg );
872 }
873 } else {
874 $this->output( "...$table doesn't exist.\n" );
875 }
876
877 return true;
878 }
879
880 /**
881 * Modify an existing field
882 *
883 * @param string $table Name of the table to which the field belongs
884 * @param string $field Name of the field to modify
885 * @param string $patch Path to the patch file
886 * @param bool $fullpath Whether to treat $patch path as a relative or not
887 * @return bool False if this was skipped because schema changes are skipped
888 */
889 public function modifyField( $table, $field, $patch, $fullpath = false ) {
890 if ( !$this->doTable( $table ) ) {
891 return true;
892 }
893
894 $updateKey = "$table-$field-$patch";
895 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
896 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
897 } elseif ( !$this->db->fieldExists( $table, $field, __METHOD__ ) ) {
898 $this->output( "...$field field does not exist in $table table, " .
899 "skipping modify field patch.\n" );
900 } elseif ( $this->updateRowExists( $updateKey ) ) {
901 $this->output( "...$field in table $table already modified by patch $patch.\n" );
902 } else {
903 $this->insertUpdateRow( $updateKey );
904
905 return $this->applyPatch( $patch, $fullpath, "Modifying $field field of table $table" );
906 }
907
908 return true;
909 }
910
911 /**
912 * Set any .htaccess files or equivilent for storage repos
913 *
914 * Some zones (e.g. "temp") used to be public and may have been initialized as such
915 */
916 public function setFileAccess() {
917 $repo = RepoGroup::singleton()->getLocalRepo();
918 $zonePath = $repo->getZonePath( 'temp' );
919 if ( $repo->getBackend()->directoryExists( [ 'dir' => $zonePath ] ) ) {
920 // If the directory was never made, then it will have the right ACLs when it is made
921 $status = $repo->getBackend()->secure( [
922 'dir' => $zonePath,
923 'noAccess' => true,
924 'noListing' => true
925 ] );
926 if ( $status->isOK() ) {
927 $this->output( "Set the local repo temp zone container to be private.\n" );
928 } else {
929 $this->output( "Failed to set the local repo temp zone container to be private.\n" );
930 }
931 }
932 }
933
934 /**
935 * Purge the objectcache table
936 */
937 public function purgeCache() {
938 global $wgLocalisationCacheConf;
939 # We can't guarantee that the user will be able to use TRUNCATE,
940 # but we know that DELETE is available to us
941 $this->output( "Purging caches..." );
942 $this->db->delete( 'objectcache', '*', __METHOD__ );
943 if ( $wgLocalisationCacheConf['manualRecache'] ) {
944 $this->rebuildLocalisationCache();
945 }
946 $blobStore = new MessageBlobStore();
947 $blobStore->clear();
948 $this->db->delete( 'module_deps', '*', __METHOD__ );
949 $this->output( "done.\n" );
950 }
951
952 /**
953 * Check the site_stats table is not properly populated.
954 */
955 protected function checkStats() {
956 $this->output( "...site_stats is populated..." );
957 $row = $this->db->selectRow( 'site_stats', '*', [ 'ss_row_id' => 1 ], __METHOD__ );
958 if ( $row === false ) {
959 $this->output( "data is missing! rebuilding...\n" );
960 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
961 $this->output( "missing ss_total_pages, rebuilding...\n" );
962 } else {
963 $this->output( "done.\n" );
964
965 return;
966 }
967 SiteStatsInit::doAllAndCommit( $this->db );
968 }
969
970 # Common updater functions
971
972 /**
973 * Sets the number of active users in the site_stats table
974 */
975 protected function doActiveUsersInit() {
976 $activeUsers = $this->db->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
977 if ( $activeUsers == -1 ) {
978 $activeUsers = $this->db->selectField( 'recentchanges',
979 'COUNT( DISTINCT rc_user_text )',
980 [ 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ], __METHOD__
981 );
982 $this->db->update( 'site_stats',
983 [ 'ss_active_users' => intval( $activeUsers ) ],
984 [ 'ss_row_id' => 1 ], __METHOD__, [ 'LIMIT' => 1 ]
985 );
986 }
987 $this->output( "...ss_active_users user count set...\n" );
988 }
989
990 /**
991 * Populates the log_user_text field in the logging table
992 */
993 protected function doLogUsertextPopulation() {
994 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
995 $this->output(
996 "Populating log_user_text field, printing progress markers. For large\n" .
997 "databases, you may want to hit Ctrl-C and do this manually with\n" .
998 "maintenance/populateLogUsertext.php.\n"
999 );
1000
1001 $task = $this->maintenance->runChild( 'PopulateLogUsertext' );
1002 $task->execute();
1003 $this->output( "done.\n" );
1004 }
1005 }
1006
1007 /**
1008 * Migrate log params to new table and index for searching
1009 */
1010 protected function doLogSearchPopulation() {
1011 if ( !$this->updateRowExists( 'populate log_search' ) ) {
1012 $this->output(
1013 "Populating log_search table, printing progress markers. For large\n" .
1014 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1015 "maintenance/populateLogSearch.php.\n" );
1016
1017 $task = $this->maintenance->runChild( 'PopulateLogSearch' );
1018 $task->execute();
1019 $this->output( "done.\n" );
1020 }
1021 }
1022
1023 /**
1024 * Updates the timestamps in the transcache table
1025 * @return bool
1026 */
1027 protected function doUpdateTranscacheField() {
1028 if ( $this->updateRowExists( 'convert transcache field' ) ) {
1029 $this->output( "...transcache tc_time already converted.\n" );
1030
1031 return true;
1032 }
1033
1034 return $this->applyPatch( 'patch-tc-timestamp.sql', false,
1035 "Converting tc_time from UNIX epoch to MediaWiki timestamp" );
1036 }
1037
1038 /**
1039 * Update CategoryLinks collation
1040 */
1041 protected function doCollationUpdate() {
1042 global $wgCategoryCollation;
1043 if ( $this->db->fieldExists( 'categorylinks', 'cl_collation', __METHOD__ ) ) {
1044 if ( $this->db->selectField(
1045 'categorylinks',
1046 'COUNT(*)',
1047 'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
1048 __METHOD__
1049 ) == 0
1050 ) {
1051 $this->output( "...collations up-to-date.\n" );
1052
1053 return;
1054 }
1055
1056 $this->output( "Updating category collations..." );
1057 $task = $this->maintenance->runChild( 'UpdateCollation' );
1058 $task->execute();
1059 $this->output( "...done.\n" );
1060 }
1061 }
1062
1063 /**
1064 * Migrates user options from the user table blob to user_properties
1065 */
1066 protected function doMigrateUserOptions() {
1067 if ( $this->db->tableExists( 'user_properties' ) ) {
1068 $cl = $this->maintenance->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
1069 $cl->execute();
1070 $this->output( "done.\n" );
1071 }
1072 }
1073
1074 /**
1075 * Enable profiling table when it's turned on
1076 */
1077 protected function doEnableProfiling() {
1078 global $wgProfiler;
1079
1080 if ( !$this->doTable( 'profiling' ) ) {
1081 return true;
1082 }
1083
1084 $profileToDb = false;
1085 if ( isset( $wgProfiler['output'] ) ) {
1086 $out = $wgProfiler['output'];
1087 if ( $out === 'db' ) {
1088 $profileToDb = true;
1089 } elseif ( is_array( $out ) && in_array( 'db', $out ) ) {
1090 $profileToDb = true;
1091 }
1092 }
1093
1094 if ( $profileToDb && !$this->db->tableExists( 'profiling', __METHOD__ ) ) {
1095 $this->applyPatch( 'patch-profiling.sql', false, 'Add profiling table' );
1096 }
1097 }
1098
1099 /**
1100 * Rebuilds the localisation cache
1101 */
1102 protected function rebuildLocalisationCache() {
1103 /**
1104 * @var $cl RebuildLocalisationCache
1105 */
1106 $cl = $this->maintenance->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
1107 $this->output( "Rebuilding localisation cache...\n" );
1108 $cl->setForce();
1109 $cl->execute();
1110 $this->output( "done.\n" );
1111 }
1112
1113 /**
1114 * Turns off content handler fields during parts of the upgrade
1115 * where they aren't available.
1116 */
1117 protected function disableContentHandlerUseDB() {
1118 global $wgContentHandlerUseDB;
1119
1120 if ( $wgContentHandlerUseDB ) {
1121 $this->output( "Turning off Content Handler DB fields for this part of upgrade.\n" );
1122 $this->holdContentHandlerUseDB = $wgContentHandlerUseDB;
1123 $wgContentHandlerUseDB = false;
1124 }
1125 }
1126
1127 /**
1128 * Turns content handler fields back on.
1129 */
1130 protected function enableContentHandlerUseDB() {
1131 global $wgContentHandlerUseDB;
1132
1133 if ( $this->holdContentHandlerUseDB ) {
1134 $this->output( "Content Handler DB fields should be usable now.\n" );
1135 $wgContentHandlerUseDB = $this->holdContentHandlerUseDB;
1136 }
1137 }
1138 }