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