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