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