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