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