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