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