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