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