Make Skin::formatDebugHTML()'s formatting work when memory usage is greather that 10M
[lhc/web/wiklou.git] / includes / installer / DatabaseUpdater.php
1 <?php
2 /**
3 * DBMS-specific updater helper.
4 *
5 * @file
6 * @ingroup Deployment
7 */
8
9 require_once( dirname(__FILE__) . '/../../maintenance/Maintenance.php' );
10
11 /**
12 * Class for handling database updates. Roughly based off of updaters.inc, with
13 * a few improvements :)
14 *
15 * @ingroup Deployment
16 * @since 1.17
17 */
18 abstract class DatabaseUpdater {
19
20 /**
21 * Array of updates to perform on the database
22 *
23 * @var array
24 */
25 protected $updates = array();
26
27 /**
28 * List of extension-provided database updates
29 * @var array
30 */
31 protected $extensionUpdates = array();
32
33 /**
34 * Handle to the database subclass
35 *
36 * @var DatabaseBase
37 */
38 protected $db;
39
40 protected $shared = false;
41
42 protected $postDatabaseUpdateMaintenance = array(
43 'DeleteDefaultMessages',
44 'PopulateRevisionLength',
45 'PopulateRevisionSha1',
46 'PopulateImageSha1',
47 'FixExtLinksProtocolRelative',
48 );
49
50 /**
51 * Constructor
52 *
53 * @param $db DatabaseBase object to perform updates on
54 * @param $shared bool Whether to perform updates on shared tables
55 * @param $maintenance Maintenance Maintenance object which created us
56 */
57 protected function __construct( DatabaseBase &$db, $shared, Maintenance $maintenance = null ) {
58 $this->db = $db;
59 $this->db->setFlag( DBO_DDLMODE ); // For Oracle's handling of schema files
60 $this->shared = $shared;
61 if ( $maintenance ) {
62 $this->maintenance = $maintenance;
63 } else {
64 $this->maintenance = new FakeMaintenance;
65 }
66 $this->maintenance->setDB( $db );
67 $this->initOldGlobals();
68 $this->loadExtensions();
69 wfRunHooks( 'LoadExtensionSchemaUpdates', array( $this ) );
70 }
71
72 /**
73 * Initialize all of the old globals. One day this should all become
74 * something much nicer
75 */
76 private function initOldGlobals() {
77 global $wgExtNewTables, $wgExtNewFields, $wgExtPGNewFields,
78 $wgExtPGAlteredFields, $wgExtNewIndexes, $wgExtModifiedFields;
79
80 # For extensions only, should be populated via hooks
81 # $wgDBtype should be checked to specifiy the proper file
82 $wgExtNewTables = array(); // table, dir
83 $wgExtNewFields = array(); // table, column, dir
84 $wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
85 $wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
86 $wgExtNewIndexes = array(); // table, index, dir
87 $wgExtModifiedFields = array(); // table, index, dir
88 }
89
90 /**
91 * Loads LocalSettings.php, if needed, and initialises everything needed for LoadExtensionSchemaUpdates hook
92 */
93 private function loadExtensions() {
94 if ( !defined( 'MEDIAWIKI_INSTALL' ) ) {
95 return; // already loaded
96 }
97 $vars = Installer::getExistingLocalSettings();
98 if ( !$vars ) {
99 return; // no LocalSettings found
100 }
101 if ( !isset( $vars['wgHooks'] ) || !isset( $vars['wgHooks']['LoadExtensionSchemaUpdates'] ) ) {
102 return;
103 }
104 global $wgHooks, $wgAutoloadClasses;
105 $wgHooks['LoadExtensionSchemaUpdates'] = $vars['wgHooks']['LoadExtensionSchemaUpdates'];
106 $wgAutoloadClasses = $wgAutoloadClasses + $vars['wgAutoloadClasses'];
107 }
108
109 /**
110 * @throws MWException
111 * @param DatabaseBase $db
112 * @param bool $shared
113 * @param null $maintenance
114 * @return DatabaseUpdater
115 */
116 public static function newForDB( &$db, $shared = false, $maintenance = null ) {
117 $type = $db->getType();
118 if( in_array( $type, Installer::getDBTypes() ) ) {
119 $class = ucfirst( $type ) . 'Updater';
120 return new $class( $db, $shared, $maintenance );
121 } else {
122 throw new MWException( __METHOD__ . ' called for unsupported $wgDBtype' );
123 }
124 }
125
126 /**
127 * Get a database connection to run updates
128 *
129 * @return DatabaseBase
130 */
131 public function getDB() {
132 return $this->db;
133 }
134
135 /**
136 * Output some text. If we're running from web, escape the text first.
137 *
138 * @param $str String: Text to output
139 */
140 public function output( $str ) {
141 if ( $this->maintenance->isQuiet() ) {
142 return;
143 }
144 global $wgCommandLineMode;
145 if( !$wgCommandLineMode ) {
146 $str = htmlspecialchars( $str );
147 }
148 echo $str;
149 flush();
150 }
151
152 /**
153 * Add a new update coming from an extension. This should be called by
154 * extensions while executing the LoadExtensionSchemaUpdates hook.
155 *
156 * @param $update Array: the update to run. Format is the following:
157 * first item is the callback function, it also can be a
158 * simple string with the name of a function in this class,
159 * following elements are parameters to the function.
160 * Note that callback functions will receive this object as
161 * first parameter.
162 */
163 public function addExtensionUpdate( Array $update ) {
164 $this->extensionUpdates[] = $update;
165 }
166
167 /**
168 * Convenience wrapper for addExtensionUpdate() when adding a new table (which
169 * is the most common usage of updaters in an extension)
170 * @param $tableName String Name of table to create
171 * @param $sqlPath String Full path to the schema file
172 */
173 public function addExtensionTable( $tableName, $sqlPath ) {
174 $this->extensionUpdates[] = array( 'addTable', $tableName, $sqlPath, true );
175 }
176
177 /**
178 * @param $tableName string
179 * @param $indexName string
180 * @param $sqlPath string
181 */
182 public function addExtensionIndex( $tableName, $indexName, $sqlPath ) {
183 $this->extensionUpdates[] = array( 'addIndex', $tableName, $indexName, $sqlPath, true );
184 }
185
186 /**
187 * @param $tableName string
188 * @param $columnName string
189 * @param $sqlPath string
190 */
191 public function addExtensionField( $tableName, $columnName, $sqlPath ) {
192 $this->extensionUpdates[] = array( 'addField', $tableName, $columnName, $sqlPath, true );
193 }
194
195 /**
196 * Add a maintenance script to be run after the database updates are complete
197 * @param $class string Name of a Maintenance subclass
198 */
199 public function addPostDatabaseUpdateMaintenance( $class ) {
200 $this->postDatabaseUpdateMaintenance[] = $class;
201 }
202
203 /**
204 * Get the list of extension-defined updates
205 *
206 * @return Array
207 */
208 protected function getExtensionUpdates() {
209 return $this->extensionUpdates;
210 }
211
212 /**
213 * @return array
214 */
215 public function getPostDatabaseUpdateMaintenance() {
216 return $this->postDatabaseUpdateMaintenance;
217 }
218
219 /**
220 * Do all the updates
221 *
222 * @param $what Array: what updates to perform
223 */
224 public function doUpdates( $what = array( 'core', 'extensions', 'purge', 'stats' ) ) {
225 global $wgLocalisationCacheConf, $wgVersion;
226
227 $what = array_flip( $what );
228 if ( isset( $what['core'] ) ) {
229 $this->runUpdates( $this->getCoreUpdateList(), false );
230 }
231 if ( isset( $what['extensions'] ) ) {
232 $this->runUpdates( $this->getOldGlobalUpdates(), false );
233 $this->runUpdates( $this->getExtensionUpdates(), true );
234 }
235
236 $this->setAppliedUpdates( $wgVersion, $this->updates );
237
238 if ( isset( $what['purge'] ) ) {
239 $this->purgeCache();
240
241 if ( $wgLocalisationCacheConf['manualRecache'] ) {
242 $this->rebuildLocalisationCache();
243 }
244 }
245 if ( isset( $what['stats'] ) ) {
246 $this->checkStats();
247 }
248 }
249
250 /**
251 * Helper function for doUpdates()
252 *
253 * @param $updates Array of updates to run
254 * @param $passSelf Boolean: whether to pass this object we calling external
255 * functions
256 */
257 private function runUpdates( array $updates, $passSelf ) {
258 foreach ( $updates as $params ) {
259 $func = array_shift( $params );
260 if( !is_array( $func ) && method_exists( $this, $func ) ) {
261 $func = array( $this, $func );
262 } elseif ( $passSelf ) {
263 array_unshift( $params, $this );
264 }
265 call_user_func_array( $func, $params );
266 flush();
267 }
268 $this->updates = array_merge( $this->updates, $updates );
269 }
270
271 /**
272 * @param $version
273 * @param $updates array
274 */
275 protected function setAppliedUpdates( $version, $updates = array() ) {
276 $this->db->clearFlag( DBO_DDLMODE );
277 if( !$this->canUseNewUpdatelog() ) {
278 return;
279 }
280 $key = "updatelist-$version-" . time();
281 $this->db->insert( 'updatelog',
282 array( 'ul_key' => $key, 'ul_value' => serialize( $updates ) ),
283 __METHOD__ );
284 $this->db->setFlag( DBO_DDLMODE );
285 }
286
287 /**
288 * Helper function: check if the given key is present in the updatelog table.
289 * Obviously, only use this for updates that occur after the updatelog table was
290 * created!
291 * @param $key String Name of the key to check for
292 *
293 * @return bool
294 */
295 public function updateRowExists( $key ) {
296 $row = $this->db->selectRow(
297 'updatelog',
298 '1',
299 array( 'ul_key' => $key ),
300 __METHOD__
301 );
302 return (bool)$row;
303 }
304
305 /**
306 * Helper function: Add a key to the updatelog table
307 * Obviously, only use this for updates that occur after the updatelog table was
308 * created!
309 * @param $key String Name of key to insert
310 * @param $val String [optional] value to insert along with the key
311 */
312 public function insertUpdateRow( $key, $val = null ) {
313 $this->db->clearFlag( DBO_DDLMODE );
314 $values = array( 'ul_key' => $key );
315 if( $val && $this->canUseNewUpdatelog() ) {
316 $values['ul_value'] = $val;
317 }
318 $this->db->insert( 'updatelog', $values, __METHOD__, 'IGNORE' );
319 $this->db->setFlag( DBO_DDLMODE );
320 }
321
322 /**
323 * Updatelog was changed in 1.17 to have a ul_value column so we can record
324 * more information about what kind of updates we've done (that's what this
325 * class does). Pre-1.17 wikis won't have this column, and really old wikis
326 * might not even have updatelog at all
327 *
328 * @return boolean
329 */
330 protected function canUseNewUpdatelog() {
331 return $this->db->tableExists( 'updatelog', __METHOD__ ) &&
332 $this->db->fieldExists( 'updatelog', 'ul_value', __METHOD__ );
333 }
334
335 /**
336 * Before 1.17, we used to handle updates via stuff like
337 * $wgExtNewTables/Fields/Indexes. This is nasty :) We refactored a lot
338 * of this in 1.17 but we want to remain back-compatible for a while. So
339 * load up these old global-based things into our update list.
340 *
341 * @return array
342 */
343 protected function getOldGlobalUpdates() {
344 global $wgExtNewFields, $wgExtNewTables, $wgExtModifiedFields,
345 $wgExtNewIndexes, $wgSharedDB, $wgSharedTables;
346
347 $doUser = $this->shared ?
348 $wgSharedDB && in_array( 'user', $wgSharedTables ) :
349 !$wgSharedDB || !in_array( 'user', $wgSharedTables );
350
351 $updates = array();
352
353 foreach ( $wgExtNewTables as $tableRecord ) {
354 $updates[] = array(
355 'addTable', $tableRecord[0], $tableRecord[1], true
356 );
357 }
358
359 foreach ( $wgExtNewFields as $fieldRecord ) {
360 if ( $fieldRecord[0] != 'user' || $doUser ) {
361 $updates[] = array(
362 'addField', $fieldRecord[0], $fieldRecord[1],
363 $fieldRecord[2], true
364 );
365 }
366 }
367
368 foreach ( $wgExtNewIndexes as $fieldRecord ) {
369 $updates[] = array(
370 'addIndex', $fieldRecord[0], $fieldRecord[1],
371 $fieldRecord[2], true
372 );
373 }
374
375 foreach ( $wgExtModifiedFields as $fieldRecord ) {
376 $updates[] = array(
377 'modifyField', $fieldRecord[0], $fieldRecord[1],
378 $fieldRecord[2], true
379 );
380 }
381
382 return $updates;
383 }
384
385 /**
386 * Get an array of updates to perform on the database. Should return a
387 * multi-dimensional array. The main key is the MediaWiki version (1.12,
388 * 1.13...) with the values being arrays of updates, identical to how
389 * updaters.inc did it (for now)
390 *
391 * @return Array
392 */
393 protected abstract function getCoreUpdateList();
394
395 /**
396 * Applies a SQL patch
397 * @param $path String Path to the patch file
398 * @param $isFullPath Boolean Whether to treat $path as a relative or not
399 */
400 protected function applyPatch( $path, $isFullPath = false ) {
401 if ( $isFullPath ) {
402 $this->db->sourceFile( $path );
403 } else {
404 $this->db->sourceFile( $this->db->patchPath( $path ) );
405 }
406 }
407
408 /**
409 * Add a new table to the database
410 * @param $name String Name of the new table
411 * @param $patch String Path to the patch file
412 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
413 */
414 protected function addTable( $name, $patch, $fullpath = false ) {
415 if ( $this->db->tableExists( $name, __METHOD__ ) ) {
416 $this->output( "...$name table already exists.\n" );
417 } else {
418 $this->output( "Creating $name table..." );
419 $this->applyPatch( $patch, $fullpath );
420 $this->output( "done.\n" );
421 }
422 }
423
424 /**
425 * Add a new field to an existing table
426 * @param $table String Name of the table to modify
427 * @param $field String Name of the new field
428 * @param $patch String Path to the patch file
429 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
430 */
431 protected function addField( $table, $field, $patch, $fullpath = false ) {
432 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
433 $this->output( "...$table table does not exist, skipping new field patch.\n" );
434 } elseif ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
435 $this->output( "...have $field field in $table table.\n" );
436 } else {
437 $this->output( "Adding $field field to table $table..." );
438 $this->applyPatch( $patch, $fullpath );
439 $this->output( "done.\n" );
440 }
441 }
442
443 /**
444 * Add a new index to an existing table
445 * @param $table String Name of the table to modify
446 * @param $index String Name of the new index
447 * @param $patch String Path to the patch file
448 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
449 */
450 protected function addIndex( $table, $index, $patch, $fullpath = false ) {
451 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
452 $this->output( "...$index key already set on $table table.\n" );
453 } else {
454 $this->output( "Adding $index key to table $table... " );
455 $this->applyPatch( $patch, $fullpath );
456 $this->output( "done.\n" );
457 }
458 }
459
460 /**
461 * Drop a field from an existing table
462 *
463 * @param $table String Name of the table to modify
464 * @param $field String Name of the old field
465 * @param $patch String Path to the patch file
466 * @param $fullpath Boolean Whether to treat $patch path as a relative or not
467 */
468 protected function dropField( $table, $field, $patch, $fullpath = false ) {
469 if ( $this->db->fieldExists( $table, $field, __METHOD__ ) ) {
470 $this->output( "Table $table contains $field field. Dropping... " );
471 $this->applyPatch( $patch, $fullpath );
472 $this->output( "done.\n" );
473 } else {
474 $this->output( "...$table table does not contain $field field.\n" );
475 }
476 }
477
478 /**
479 * Drop an index from an existing table
480 *
481 * @param $table String: Name of the table to modify
482 * @param $index String: Name of the old index
483 * @param $patch String: Path to the patch file
484 * @param $fullpath Boolean: Whether to treat $patch path as a relative or not
485 */
486 protected function dropIndex( $table, $index, $patch, $fullpath = false ) {
487 if ( $this->db->indexExists( $table, $index, __METHOD__ ) ) {
488 $this->output( "Dropping $index key from table $table... " );
489 $this->applyPatch( $patch, $fullpath );
490 $this->output( "done.\n" );
491 } else {
492 $this->output( "...$index key doesn't exist.\n" );
493 }
494 }
495
496 /**
497 * @param $table string
498 * @param $patch string
499 * @param $fullpath bool
500 */
501 protected function dropTable( $table, $patch, $fullpath = false ) {
502 if ( $this->db->tableExists( $table, __METHOD__ ) ) {
503 $this->output( "Dropping table $table... " );
504 $this->applyPatch( $patch, $fullpath );
505 $this->output( "done.\n" );
506 } else {
507 $this->output( "...$table doesn't exist.\n" );
508 }
509 }
510
511 /**
512 * Modify an existing field
513 *
514 * @param $table String: name of the table to which the field belongs
515 * @param $field String: name of the field to modify
516 * @param $patch String: path to the patch file
517 * @param $fullpath Boolean: whether to treat $patch path as a relative or not
518 */
519 public function modifyField( $table, $field, $patch, $fullpath = false ) {
520 $updateKey = "$table-$field-$patch";
521 if ( !$this->db->tableExists( $table, __METHOD__ ) ) {
522 $this->output( "...$table table does not exist, skipping modify field patch.\n" );
523 } elseif ( !$this->db->fieldExists( $table, $field, __METHOD__ ) ) {
524 $this->output( "...$field field does not exist in $table table, skipping modify field patch.\n" );
525 } elseif( $this->updateRowExists( $updateKey ) ) {
526 $this->output( "...$field in table $table already modified by patch $patch.\n" );
527 } else {
528 $this->output( "Modifying $field field of table $table..." );
529 $this->applyPatch( $patch, $fullpath );
530 $this->insertUpdateRow( $updateKey );
531 $this->output( "done.\n" );
532 }
533 }
534
535 /**
536 * Purge the objectcache table
537 */
538 protected function purgeCache() {
539 # We can't guarantee that the user will be able to use TRUNCATE,
540 # but we know that DELETE is available to us
541 $this->output( "Purging caches..." );
542 $this->db->delete( 'objectcache', '*', __METHOD__ );
543 $this->output( "done.\n" );
544 }
545
546 /**
547 * Check the site_stats table is not properly populated.
548 */
549 protected function checkStats() {
550 $this->output( "Checking site_stats row..." );
551 $row = $this->db->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
552 if ( $row === false ) {
553 $this->output( "data is missing! rebuilding...\n" );
554 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
555 $this->output( "missing ss_total_pages, rebuilding...\n" );
556 } else {
557 $this->output( "done.\n" );
558 return;
559 }
560 SiteStatsInit::doAllAndCommit( $this->db );
561 }
562
563 # Common updater functions
564
565 /**
566 * Sets the number of active users in the site_stats table
567 */
568 protected function doActiveUsersInit() {
569 $activeUsers = $this->db->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
570 if ( $activeUsers == -1 ) {
571 $activeUsers = $this->db->selectField( 'recentchanges',
572 'COUNT( DISTINCT rc_user_text )',
573 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
574 );
575 $this->db->update( 'site_stats',
576 array( 'ss_active_users' => intval( $activeUsers ) ),
577 array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
578 );
579 }
580 $this->output( "...ss_active_users user count set...\n" );
581 }
582
583 /**
584 * Populates the log_user_text field in the logging table
585 */
586 protected function doLogUsertextPopulation() {
587 if ( !$this->updateRowExists( 'populate log_usertext' ) ) {
588 $this->output(
589 "Populating log_user_text field, printing progress markers. For large\n" .
590 "databases, you may want to hit Ctrl-C and do this manually with\n" .
591 "maintenance/populateLogUsertext.php.\n" );
592
593 $task = $this->maintenance->runChild( 'PopulateLogUsertext' );
594 $task->execute();
595 $this->output( "done.\n" );
596 }
597 }
598
599 /**
600 * Migrate log params to new table and index for searching
601 */
602 protected function doLogSearchPopulation() {
603 if ( !$this->updateRowExists( 'populate log_search' ) ) {
604 $this->output(
605 "Populating log_search table, printing progress markers. For large\n" .
606 "databases, you may want to hit Ctrl-C and do this manually with\n" .
607 "maintenance/populateLogSearch.php.\n" );
608
609 $task = $this->maintenance->runChild( 'PopulateLogSearch' );
610 $task->execute();
611 $this->output( "done.\n" );
612 }
613 }
614
615 /**
616 * Updates the timestamps in the transcache table
617 */
618 protected function doUpdateTranscacheField() {
619 if ( $this->updateRowExists( 'convert transcache field' ) ) {
620 $this->output( "...transcache tc_time already converted.\n" );
621 return;
622 }
623
624 $this->output( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
625 $this->applyPatch( 'patch-tc-timestamp.sql' );
626 $this->output( "done.\n" );
627 }
628
629 /**
630 * Update CategoryLinks collation
631 */
632 protected function doCollationUpdate() {
633 global $wgCategoryCollation;
634 if ( $this->db->selectField(
635 'categorylinks',
636 'COUNT(*)',
637 'cl_collation != ' . $this->db->addQuotes( $wgCategoryCollation ),
638 __METHOD__
639 ) == 0 ) {
640 $this->output( "...collations up-to-date.\n" );
641 return;
642 }
643
644 $this->output( "Updating category collations..." );
645 $task = $this->maintenance->runChild( 'UpdateCollation' );
646 $task->execute();
647 $this->output( "...done.\n" );
648 }
649
650 /**
651 * Migrates user options from the user table blob to user_properties
652 */
653 protected function doMigrateUserOptions() {
654 $cl = $this->maintenance->runChild( 'ConvertUserOptions', 'convertUserOptions.php' );
655 $this->output( "Migrating remaining user_options... " );
656 $cl->execute();
657 $this->output( "done.\n" );
658 }
659
660 /**
661 * Rebuilds the localisation cache
662 */
663 protected function rebuildLocalisationCache() {
664 /**
665 * @var $cl RebuildLocalisationCache
666 */
667 $cl = $this->maintenance->runChild( 'RebuildLocalisationCache', 'rebuildLocalisationCache.php' );
668 $this->output( "Rebuilding localisation cache...\n" );
669 $cl->setForce();
670 $cl->execute();
671 $this->output( "done.\n" );
672 }
673 }