* (bug 14473) Add iwlinks table to track inline interwiki link usage
[lhc/web/wiklou.git] / maintenance / updaters.inc
1 <?php
2 /**
3 * @file
4 * @ingroup Maintenance
5 */
6
7 if ( !defined( 'MEDIAWIKI' ) ) {
8 echo "This file is not a valid entry point\n";
9 exit( 1 );
10 }
11
12 require_once 'convertLinks.inc';
13 require_once 'userDupes.inc';
14 # Extension updates
15 require_once( "$IP/includes/Hooks.php" );
16
17 /**
18 * List of update functions to call for each DB type, in sequence. First item
19 * is function name, rest are parameters to pass.
20 */
21 $wgUpdates = array(
22 'mysql' => array(
23 // 1.2
24 // update_passwords obsolete
25 array( 'add_field', 'ipblocks', 'ipb_id', 'patch-ipblocks.sql' ),
26 array( 'add_field', 'ipblocks', 'ipb_expiry', 'patch-ipb_expiry.sql' ),
27 array( 'do_interwiki_update' ),
28 array( 'do_index_update' ),
29 // do_linkscc_update obsolete
30 array( 'add_table', 'hitcounter', 'patch-hitcounter.sql' ),
31 array( 'add_field', 'recentchanges', 'rc_type', 'patch-rc_type.sql' ),
32
33 // 1.3
34 array( 'add_field', 'user', 'user_real_name', 'patch-user-realname.sql' ),
35 array( 'add_table', 'querycache', 'patch-querycache.sql' ),
36 array( 'add_table', 'objectcache', 'patch-objectcache.sql' ),
37 array( 'add_table', 'categorylinks', 'patch-categorylinks.sql' ),
38 // do_linkscc_1_3_update obsolete
39 array( 'do_old_links_update' ),
40 array( 'fix_ancient_imagelinks' ),
41 array( 'add_field', 'recentchanges', 'rc_ip', 'patch-rc_ip.sql' ),
42
43 // 1.4
44 array( 'do_image_name_unique_update' ),
45 array( 'add_field', 'recentchanges', 'rc_id', 'patch-rc_id.sql' ),
46 array( 'add_field', 'recentchanges', 'rc_patrolled', 'patch-rc-patrol.sql' ),
47 array( 'add_table', 'logging', 'patch-logging.sql' ),
48 // do_user_rights_update obsolete
49 array( 'add_field', 'user', 'user_token', 'patch-user_token.sql' ),
50 // old, old_articleid, patch-remove-old-title-namespace.sql obsolete
51 // user_groups, patch-userlevels.sql obsolete
52 // do_group_update() obsolete
53 array( 'do_watchlist_update' ),
54 array( 'do_user_update' ),
55 // do_copy_newtalk_to_watchlist obsolete
56
57 // 1.5
58 array( 'do_schema_restructuring' ),
59 array( 'add_field', 'logging', 'log_params', 'patch-log_params.sql' ),
60 array( 'check_bin', 'logging', 'log_title', 'patch-logging-title.sql', ),
61 array( 'add_field', 'archive', 'ar_rev_id', 'patch-archive-rev_id.sql' ),
62 array( 'add_field', 'page', 'page_len', 'patch-page_len.sql' ),
63 array( 'do_inverse_timestamp' ),
64 array( 'do_text_id' ),
65 array( 'add_field', 'revision', 'rev_deleted', 'patch-rev_deleted.sql' ),
66 array( 'add_field', 'image', 'img_width', 'patch-img_width.sql' ),
67 array( 'add_field', 'image', 'img_metadata', 'patch-img_metadata.sql' ),
68 array( 'add_field', 'user', 'user_email_token', 'patch-user_email_token.sql' ),
69 array( 'add_field', 'archive', 'ar_text_id', 'patch-archive-text_id.sql' ),
70 array( 'do_namespace_size' ),
71 array( 'add_field', 'image', 'img_media_type', 'patch-img_media_type.sql' ),
72 array( 'do_pagelinks_update' ),
73 array( 'do_drop_img_type' ),
74 array( 'do_user_unique_update' ),
75 array( 'do_user_groups_update' ),
76 array( 'add_field', 'site_stats', 'ss_total_pages', 'patch-ss_total_articles.sql' ),
77 array( 'add_table', 'user_newtalk', 'patch-usernewtalk2.sql' ),
78 array( 'add_table', 'transcache', 'patch-transcache.sql' ),
79 array( 'add_field', 'interwiki', 'iw_trans', 'patch-interwiki-trans.sql' ),
80 array( 'add_table', 'trackbacks', 'patch-trackbacks.sql' ),
81
82 // 1.6
83 array( 'do_watchlist_null' ),
84 // do_image_index_update obsolete
85 array( 'do_logging_timestamp_index' ),
86 array( 'add_field', 'ipblocks', 'ipb_range_start', 'patch-ipb_range_start.sql' ),
87 array( 'do_page_random_update' ),
88 array( 'add_field', 'user', 'user_registration','patch-user_registration.sql' ),
89 array( 'do_templatelinks_update' ),
90 array( 'add_table', 'externallinks', 'patch-externallinks.sql' ),
91 array( 'add_table', 'job', 'patch-job.sql' ),
92 array( 'add_field', 'site_stats', 'ss_images', 'patch-ss_images.sql' ),
93 array( 'add_table', 'langlinks', 'patch-langlinks.sql' ),
94 array( 'add_table', 'querycache_info', 'patch-querycacheinfo.sql' ),
95 array( 'add_table', 'filearchive', 'patch-filearchive.sql' ),
96 array( 'add_field', 'ipblocks', 'ipb_anon_only', 'patch-ipb_anon_only.sql' ),
97 array( 'do_rc_indices_update' ),
98
99 // 1.9
100 array( 'add_field', 'user', 'user_newpass_time', 'patch-user_newpass_time.sql' ),
101 array( 'add_table', 'redirect', 'patch-redirect.sql' ),
102 array( 'add_table', 'querycachetwo', 'patch-querycachetwo.sql' ),
103 array( 'add_field', 'ipblocks', 'ipb_enable_autoblock', 'patch-ipb_optional_autoblock.sql' ),
104 array( 'do_backlinking_indices_update' ),
105 array( 'add_field', 'recentchanges', 'rc_old_len', 'patch-rc_len.sql' ),
106 array( 'add_field', 'user', 'user_editcount', 'patch-user_editcount.sql' ),
107
108 // 1.10
109 array( 'do_restrictions_update' ),
110 array( 'add_field', 'logging', 'log_id', 'patch-log_id.sql' ),
111 array( 'add_field', 'revision', 'rev_parent_id', 'patch-rev_parent_id.sql' ),
112 array( 'add_field', 'page_restrictions', 'pr_id', 'patch-page_restrictions_sortkey.sql' ),
113 array( 'add_field', 'revision', 'rev_len', 'patch-rev_len.sql' ),
114 array( 'add_field', 'recentchanges', 'rc_deleted', 'patch-rc_deleted.sql' ),
115 array( 'add_field', 'logging', 'log_deleted', 'patch-log_deleted.sql' ),
116 array( 'add_field', 'archive', 'ar_deleted', 'patch-ar_deleted.sql' ),
117 array( 'add_field', 'ipblocks', 'ipb_deleted', 'patch-ipb_deleted.sql' ),
118 array( 'add_field', 'filearchive', 'fa_deleted', 'patch-fa_deleted.sql' ),
119 array( 'add_field', 'archive', 'ar_len', 'patch-ar_len.sql' ),
120
121 // 1.11
122 array( 'add_field', 'ipblocks', 'ipb_block_email', 'patch-ipb_emailban.sql' ),
123 array( 'do_categorylinks_indices_update' ),
124 array( 'add_field', 'oldimage', 'oi_metadata', 'patch-oi_metadata.sql'),
125 array( 'do_archive_user_index' ),
126 array( 'do_image_user_index' ),
127 array( 'do_oldimage_user_index' ),
128 array( 'add_field', 'archive', 'ar_page_id', 'patch-archive-page_id.sql'),
129 array( 'add_field', 'image', 'img_sha1', 'patch-img_sha1.sql' ),
130
131 // 1.12
132 array( 'add_table', 'protected_titles', 'patch-protected_titles.sql' ),
133
134 // 1.13
135 array( 'add_field', 'ipblocks', 'ipb_by_text', 'patch-ipb_by_text.sql' ),
136 array( 'add_table', 'page_props', 'patch-page_props.sql' ),
137 array( 'add_table', 'updatelog', 'patch-updatelog.sql' ),
138 array( 'add_table', 'category', 'patch-category.sql' ),
139 array( 'do_category_population' ),
140 array( 'add_field', 'archive', 'ar_parent_id', 'patch-ar_parent_id.sql'),
141 array( 'add_field', 'user_newtalk', 'user_last_timestamp', 'patch-user_last_timestamp.sql'),
142 array( 'do_populate_parent_id' ),
143 array( 'check_bin', 'protected_titles', 'pt_title', 'patch-pt_title-encoding.sql', ),
144 array( 'maybe_do_profiling_memory_update' ),
145 array( 'do_filearchive_indices_update' ),
146
147 // 1.14
148 array( 'add_field', 'site_stats', 'ss_active_users', 'patch-ss_active_users.sql' ),
149 array( 'do_active_users_init' ),
150 array( 'add_field', 'ipblocks', 'ipb_allow_usertalk', 'patch-ipb_allow_usertalk.sql' ),
151
152 // 1.15
153 array( 'do_unique_pl_tl_il' ),
154 array( 'add_table', 'change_tag', 'patch-change_tag.sql' ),
155 array( 'add_table', 'tag_summary', 'patch-change_tag.sql' ),
156 array( 'add_table', 'valid_tag', 'patch-change_tag.sql' ),
157
158 // 1.16
159 array( 'add_table', 'user_properties', 'patch-user_properties.sql' ),
160 array( 'add_table', 'log_search', 'patch-log_search.sql' ),
161 array( 'do_log_search_population' ),
162 array( 'add_field', 'logging', 'log_user_text', 'patch-log_user_text.sql' ),
163 array( 'add_table', 'l10n_cache', 'patch-l10n_cache.sql' ),
164 array( 'add_table', 'external_user', 'patch-external_user.sql' ),
165 array( 'add_index', 'log_search', 'ls_field_val', 'patch-log_search-rename-index.sql' ),
166 array( 'add_index', 'change_tag', 'change_tag_rc_tag', 'patch-change_tag-indexes.sql' ),
167 array( 'add_field', 'redirect', 'rd_interwiki', 'patch-rd_interwiki.sql' ),
168 array( 'do_update_transcache_field' ),
169 // A field changed name mid-release cycle, so fix it for anyone using
170 // trunk
171 array( 'rename_eu_wiki_id' ),
172 array( 'do_update_mime_minor_field' ),
173 // Should've done this back in 1.10, but better late than never:
174 array( 'do_populate_rev_len' ),
175
176 // 1.17
177 array( 'add_table', 'iwlinks', 'patch-iwlinks.sql' ),
178 ),
179
180 'sqlite' => array(
181 // 1.14
182 array( 'add_field', 'site_stats', 'ss_active_users', 'patch-ss_active_users.sql' ),
183 array( 'do_active_users_init' ),
184 array( 'add_field', 'ipblocks', 'ipb_allow_usertalk', 'patch-ipb_allow_usertalk.sql' ),
185 array( 'sqlite_initial_indexes' ),
186
187 // 1.15
188 array( 'add_table', 'change_tag', 'patch-change_tag.sql' ),
189 array( 'add_table', 'tag_summary', 'patch-change_tag.sql' ),
190 array( 'add_table', 'valid_tag', 'patch-change_tag.sql' ),
191
192 // 1.16
193 array( 'add_table', 'user_properties', 'patch-user_properties.sql' ),
194 array( 'add_table', 'log_search', 'patch-log_search.sql' ),
195 array( 'do_log_search_population' ),
196 array( 'add_field', 'logging', 'log_user_text', 'patch-log_user_text.sql' ),
197 array( 'add_table', 'l10n_cache', 'patch-l10n_cache.sql' ),
198 array( 'add_table', 'external_user', 'patch-external_user.sql' ),
199 array( 'add_index', 'log_search', 'ls_field_val', 'patch-log_search-rename-index.sql' ),
200 array( 'add_index', 'change_tag', 'change_tag_rc_tag', 'patch-change_tag-indexes.sql' ),
201 array( 'add_field', 'redirect', 'rd_interwiki', 'patch-rd_interwiki.sql' ),
202 array( 'do_update_transcache_field' ),
203 // version-independent searchindex setup, added in 1.16
204 array( 'sqlite_setup_searchindex' ),
205
206 // 1.17
207 array( 'add_table', 'iwlinks', 'patch-iwlinks.sql' ), // @fixme so far untested on sqlite 2010-04-16
208 ),
209 );
210
211
212 # For extensions only, should be populated via hooks
213 # $wgDBtype should be checked to specifiy the proper file
214 $wgExtNewTables = array(); // table, dir
215 $wgExtNewFields = array(); // table, column, dir
216 $wgExtPGNewFields = array(); // table, column, column attributes; for PostgreSQL
217 $wgExtPGAlteredFields = array(); // table, column, new type, conversion method; for PostgreSQL
218 $wgExtNewIndexes = array(); // table, index, dir
219 $wgExtModifiedFields = array(); //table, index, dir
220
221 # Helper function: check if the given key is present in the updatelog table.
222 # Obviously, only use this for updates that occur after the updatelog table was
223 # created!
224 function update_row_exists( $key ) {
225 $dbr = wfGetDB( DB_SLAVE );
226 $row = $dbr->selectRow(
227 'updatelog',
228 '1',
229 array( 'ul_key' => $key ),
230 __FUNCTION__
231 );
232 return (bool)$row;
233 }
234
235 function rename_table( $from, $to, $patch ) {
236 global $wgDatabase;
237 if ( $wgDatabase->tableExists( $from ) ) {
238 if ( $wgDatabase->tableExists( $to ) ) {
239 wfOut( "...can't move table $from to $to, $to already exists.\n" );
240 } else {
241 wfOut( "Moving table $from to $to..." );
242 $wgDatabase->sourceFile( archive($patch) );
243 wfOut( "ok\n" );
244 }
245 } else {
246 // Source table does not exist
247 // Renames are done before creations, so this is typical for a new installation
248 // Ignore silently
249 }
250 }
251
252 function add_table( $name, $patch, $fullpath=false ) {
253 global $wgDatabase;
254 if ( $wgDatabase->tableExists( $name ) ) {
255 wfOut( "...$name table already exists.\n" );
256 } else {
257 wfOut( "Creating $name table..." );
258 if( $fullpath ) {
259 $wgDatabase->sourceFile( $patch );
260 } else {
261 $wgDatabase->sourceFile( archive($patch) );
262 }
263 wfOut( "ok\n" );
264 }
265 }
266
267 function modify_field($table, $field, $patch, $fullpath=false){
268 global $wgDatabase;
269 if ( !$wgDatabase->tableExists( $table ) ) {
270 wfOut( "...$table table does not exist, skipping modify field patch\n" );
271 } elseif (! $wgDatabase->fieldExists( $table, $field ) ) {
272 wfOut( "...$field field does not exist in $table table, skipping modify field patch\n" );
273 } else {
274 wfOut( "Modifying $field field of table $table..." );
275 if( $fullpath ) {
276 $wgDatabase->sourceFile( $patch );
277 } else {
278 $wgDatabase->sourceFile( archive($patch) );
279 }
280 wfOut( "ok\n" );
281 }
282 }
283
284
285
286 function add_field( $table, $field, $patch, $fullpath=false ) {
287 global $wgDatabase;
288 if ( !$wgDatabase->tableExists( $table ) ) {
289 wfOut( "...$table table does not exist, skipping new field patch\n" );
290 } elseif ( $wgDatabase->fieldExists( $table, $field ) ) {
291 wfOut( "...have $field field in $table table.\n" );
292 } else {
293 wfOut( "Adding $field field to table $table..." );
294 if( $fullpath ) {
295 $wgDatabase->sourceFile( $patch );
296 } else {
297 $wgDatabase->sourceFile( archive($patch) );
298 }
299 wfOut( "ok\n" );
300 }
301 }
302
303 function add_index( $table, $index, $patch, $fullpath=false ) {
304 global $wgDatabase;
305 if( $wgDatabase->indexExists( $table, $index ) ) {
306 wfOut( "...$index key already set on $table table.\n" );
307 } else {
308 wfOut( "Adding $index key to table $table... " );
309 if( $fullpath ) {
310 $wgDatabase->sourceFile( $patch );
311 } else {
312 $wgDatabase->sourceFile( archive($patch) );
313 }
314 wfOut( "ok\n" );
315 }
316 }
317
318 function do_interwiki_update() {
319 # Check that interwiki table exists; if it doesn't source it
320 global $wgDatabase, $IP;
321 if( $wgDatabase->tableExists( "interwiki" ) ) {
322 wfOut( "...already have interwiki table\n" );
323 return true;
324 }
325 wfOut( "Creating interwiki table: " );
326 $wgDatabase->sourceFile( archive("patch-interwiki.sql") );
327 wfOut( "ok\n" );
328 wfOut( "Adding default interwiki definitions: " );
329 $wgDatabase->sourceFile( "$IP/maintenance/interwiki.sql" );
330 wfOut( "ok\n" );
331 }
332
333 function do_index_update() {
334 # Check that proper indexes are in place
335 global $wgDatabase;
336 $meta = $wgDatabase->fieldInfo( "recentchanges", "rc_timestamp" );
337 if( !$meta->isMultipleKey() ) {
338 wfOut( "Updating indexes to 20031107: " );
339 $wgDatabase->sourceFile( archive("patch-indexes.sql") );
340 wfOut( "ok\n" );
341 return true;
342 }
343 wfOut( "...indexes seem up to 20031107 standards\n" );
344 return false;
345 }
346
347 function do_image_index_update() {
348 global $wgDatabase;
349
350 $meta = $wgDatabase->fieldInfo( "image", "img_major_mime" );
351 if( !$meta->isMultipleKey() ) {
352 wfOut( "Updating indexes to 20050912: " );
353 $wgDatabase->sourceFile( archive("patch-mimesearch-indexes.sql") );
354 wfOut( "ok\n" );
355 return true;
356 }
357 wfOut( "...indexes seem up to 20050912 standards\n" );
358 return false;
359 }
360
361 function do_image_name_unique_update() {
362 global $wgDatabase;
363 if( $wgDatabase->indexExists( 'image', 'PRIMARY' ) ) {
364 wfOut( "...image primary key already set.\n" );
365 } else {
366 wfOut( "Making img_name the primary key... " );
367 $wgDatabase->sourceFile( archive("patch-image_name_primary.sql") );
368 wfOut( "ok\n" );
369 }
370 }
371
372 function do_logging_timestamp_index() {
373 global $wgDatabase;
374 if( $wgDatabase->indexExists( 'logging', 'times' ) ) {
375 wfOut( "...timestamp key on logging already exists.\n" );
376 } else {
377 wfOut( "Adding timestamp key on logging table... " );
378 $wgDatabase->sourceFile( archive("patch-logging-times-index.sql") );
379 wfOut( "ok\n" );
380 }
381 }
382
383 function do_archive_user_index() {
384 global $wgDatabase;
385 if( $wgDatabase->indexExists( 'archive', 'usertext_timestamp' ) ) {
386 wfOut( "...usertext,timestamp key on archive already exists.\n" );
387 } else {
388 wfOut( "Adding usertext,timestamp key on archive table... " );
389 $wgDatabase->sourceFile( archive("patch-archive-user-index.sql") );
390 wfOut( "ok\n" );
391 }
392 }
393
394 function do_image_user_index() {
395 global $wgDatabase;
396 if( $wgDatabase->indexExists( 'image', 'img_usertext_timestamp' ) ) {
397 wfOut( "...usertext,timestamp key on image already exists.\n" );
398 } else {
399 wfOut( "Adding usertext,timestamp key on image table... " );
400 $wgDatabase->sourceFile( archive("patch-image-user-index.sql") );
401 wfOut( "ok\n" );
402 }
403 }
404
405 function do_oldimage_user_index() {
406 global $wgDatabase;
407 if( $wgDatabase->indexExists( 'oldimage', 'oi_usertext_timestamp' ) ) {
408 wfOut( "...usertext,timestamp key on oldimage already exists.\n" );
409 } else {
410 wfOut( "Adding usertext,timestamp key on oldimage table... " );
411 $wgDatabase->sourceFile( archive("patch-oldimage-user-index.sql") );
412 wfOut( "ok\n" );
413 }
414 }
415
416 function do_watchlist_update() {
417 global $wgDatabase;
418 $fname = 'do_watchlist_update';
419 if( $wgDatabase->fieldExists( 'watchlist', 'wl_notificationtimestamp' ) ) {
420 wfOut( "The watchlist table is already set up for email notification.\n" );
421 } else {
422 wfOut( "Adding wl_notificationtimestamp field for email notification management." );
423 /* ALTER TABLE watchlist ADD (wl_notificationtimestamp varchar(14) binary NOT NULL default '0'); */
424 $wgDatabase->sourceFile( archive( 'patch-email-notification.sql' ) );
425 wfOut( "ok\n" );
426 }
427 # Check if we need to add talk page rows to the watchlist
428 $talk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'wl_namespace & 1', $fname );
429 $nontalk = $wgDatabase->selectField( 'watchlist', 'count(*)', 'NOT (wl_namespace & 1)', $fname );
430 if ( $talk != $nontalk ) {
431 wfOut( "Adding missing watchlist talk page rows... " );
432 flush();
433
434 $wgDatabase->insertSelect( 'watchlist', 'watchlist',
435 array(
436 'wl_user' => 'wl_user',
437 'wl_namespace' => 'wl_namespace | 1',
438 'wl_title' => 'wl_title',
439 'wl_notificationtimestamp' => 'wl_notificationtimestamp'
440 ), array( 'NOT (wl_namespace & 1)' ), $fname, 'IGNORE' );
441 wfOut( "ok\n" );
442 } else {
443 wfOut( "...watchlist talk page rows already present\n" );
444 }
445 }
446
447 function do_copy_newtalk_to_watchlist() {
448 global $wgDatabase;
449 global $wgCommandLineMode; # this needs to be saved while getID() and getName() are called
450
451 $res = $wgDatabase->safeQuery( 'SELECT user_id, user_ip FROM !',
452 $wgDatabase->tableName( 'user_newtalk' ) );
453 $num_newtalks=$wgDatabase->numRows($res);
454 wfOut( "Now converting $num_newtalks user_newtalk entries to watchlist table entries ... \n" );
455
456 $user = new User();
457 for ( $i = 1; $i <= $num_newtalks; $i++ ) {
458 $wluser = $wgDatabase->fetchObject( $res );
459 if ($wluser->user_id == 0) { # anonymous users ... have IP numbers as "names"
460 if ($user->isIP($wluser->user_ip)) { # do only if it really looks like an IP number (double checked)
461 $wgDatabase->replace( 'watchlist',
462 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
463 array('wl_user' => 0,
464 'wl_namespace' => NS_USER_TALK,
465 'wl_title' => $wluser->user_ip,
466 'wl_notificationtimestamp' => '19700101000000'
467 ), 'updaters.inc::do_watchlist_update2'
468 );
469 }
470 } else { # normal users ... have user_ids
471 $user->setID($wluser->user_id);
472 $wgDatabase->replace( 'watchlist',
473 array(array('wl_user','wl_namespace', 'wl_title', 'wl_notificationtimestamp' )),
474 array('wl_user' => $user->getID(),
475 'wl_namespace' => NS_USER_TALK,
476 'wl_title' => $user->getName(),
477 'wl_notificationtimestamp' => '19700101000000'
478 ), 'updaters.inc::do_watchlist_update3'
479 );
480 }
481 }
482 wfOut( "Done.\n" );
483 }
484
485
486 function do_user_update() {
487 global $wgDatabase;
488 if( $wgDatabase->fieldExists( 'user', 'user_emailauthenticationtimestamp' ) ) {
489 wfOut( "User table contains old email authentication field. Dropping... " );
490 $wgDatabase->sourceFile( archive( 'patch-email-authentication.sql' ) );
491 wfOut( "ok\n" );
492 } else {
493 wfOut( "...user table does not contain old email authentication field.\n" );
494 }
495 }
496
497 /**
498 * 1.4 betas were missing the 'binary' marker from logging.log_title,
499 * which causes a collation mismatch error on joins in MySQL 4.1.
500 */
501 function check_bin( $table, $field, $patchFile ) {
502 global $wgDatabase, $wgDBtype;
503 if ($wgDBtype != 'mysql')
504 return;
505 $tableName = $wgDatabase->tableName( $table );
506 $res = $wgDatabase->query( "SELECT $field FROM $tableName LIMIT 0" );
507 $flags = explode( ' ', mysql_field_flags( $res->result, 0 ) );
508 $wgDatabase->freeResult( $res );
509
510 if( in_array( 'binary', $flags ) ) {
511 wfOut( "$table table has correct $field encoding.\n" );
512 } else {
513 wfOut( "Fixing $field encoding on $table table... " );
514 $wgDatabase->sourceFile( archive( $patchFile ) );
515 wfOut( "ok\n" );
516 }
517 }
518
519 function do_schema_restructuring() {
520 global $wgDatabase;
521 $fname="do_schema_restructuring";
522 if ( $wgDatabase->tableExists( 'page' ) ) {
523 wfOut( "...page table already exists.\n" );
524 } else {
525 wfOut( "...converting from cur/old to page/revision/text DB structure.\n" );
526 wfOut( wfTimestamp( TS_DB ) );
527 wfOut( "......checking for duplicate entries.\n" );
528
529 list ($cur, $old, $page, $revision, $text) = $wgDatabase->tableNamesN( 'cur', 'old', 'page', 'revision', 'text' );
530
531 $rows = $wgDatabase->query( "SELECT cur_title, cur_namespace, COUNT(cur_namespace) AS c
532 FROM $cur GROUP BY cur_title, cur_namespace HAVING c>1", $fname );
533
534 if ( $wgDatabase->numRows( $rows ) > 0 ) {
535 wfOut( wfTimestamp( TS_DB ) );
536 wfOut( "......<b>Found duplicate entries</b>\n" );
537 wfOut( sprintf( "<b> %-60s %3s %5s</b>\n", 'Title', 'NS', 'Count' ) );
538 while ( $row = $wgDatabase->fetchObject( $rows ) ) {
539 if ( ! isset( $duplicate[$row->cur_namespace] ) ) {
540 $duplicate[$row->cur_namespace] = array();
541 }
542 $duplicate[$row->cur_namespace][] = $row->cur_title;
543 wfOut( sprintf( " %-60s %3s %5s\n", $row->cur_title, $row->cur_namespace, $row->c ) );
544 }
545 $sql = "SELECT cur_title, cur_namespace, cur_id, cur_timestamp FROM $cur WHERE ";
546 $firstCond = true;
547 foreach ( $duplicate as $ns => $titles ) {
548 if ( $firstCond ) {
549 $firstCond = false;
550 } else {
551 $sql .= ' OR ';
552 }
553 $sql .= "( cur_namespace = {$ns} AND cur_title in (";
554 $first = true;
555 foreach ( $titles as $t ) {
556 if ( $first ) {
557 $sql .= $wgDatabase->addQuotes( $t );
558 $first = false;
559 } else {
560 $sql .= ', ' . $wgDatabase->addQuotes( $t );
561 }
562 }
563 $sql .= ") ) \n";
564 }
565 # By sorting descending, the most recent entry will be the first in the list.
566 # All following entries will be deleted by the next while-loop.
567 $sql .= 'ORDER BY cur_namespace, cur_title, cur_timestamp DESC';
568
569 $rows = $wgDatabase->query( $sql, $fname );
570
571 $prev_title = $prev_namespace = false;
572 $deleteId = array();
573
574 while ( $row = $wgDatabase->fetchObject( $rows ) ) {
575 if ( $prev_title == $row->cur_title && $prev_namespace == $row->cur_namespace ) {
576 $deleteId[] = $row->cur_id;
577 }
578 $prev_title = $row->cur_title;
579 $prev_namespace = $row->cur_namespace;
580 }
581 $sql = "DELETE FROM $cur WHERE cur_id IN ( " . join( ',', $deleteId ) . ')';
582 $rows = $wgDatabase->query( $sql, $fname );
583 wfOut( wfTimestamp( TS_DB ) );
584 wfOut( "......<b>Deleted</b> ".$wgDatabase->affectedRows()." records.\n" );
585 }
586
587
588 wfOut( wfTimestamp( TS_DB ) );
589 wfOut( "......Creating tables.\n" );
590 $wgDatabase->query("CREATE TABLE $page (
591 page_id int(8) unsigned NOT NULL auto_increment,
592 page_namespace int NOT NULL,
593 page_title varchar(255) binary NOT NULL,
594 page_restrictions tinyblob NOT NULL,
595 page_counter bigint(20) unsigned NOT NULL default '0',
596 page_is_redirect tinyint(1) unsigned NOT NULL default '0',
597 page_is_new tinyint(1) unsigned NOT NULL default '0',
598 page_random real unsigned NOT NULL,
599 page_touched char(14) binary NOT NULL default '',
600 page_latest int(8) unsigned NOT NULL,
601 page_len int(8) unsigned NOT NULL,
602
603 PRIMARY KEY page_id (page_id),
604 UNIQUE INDEX name_title (page_namespace,page_title),
605 INDEX (page_random),
606 INDEX (page_len)
607 ) ENGINE=InnoDB", $fname );
608 $wgDatabase->query("CREATE TABLE $revision (
609 rev_id int(8) unsigned NOT NULL auto_increment,
610 rev_page int(8) unsigned NOT NULL,
611 rev_comment tinyblob NOT NULL,
612 rev_user int(5) unsigned NOT NULL default '0',
613 rev_user_text varchar(255) binary NOT NULL default '',
614 rev_timestamp char(14) binary NOT NULL default '',
615 rev_minor_edit tinyint(1) unsigned NOT NULL default '0',
616 rev_deleted tinyint(1) unsigned NOT NULL default '0',
617 rev_len int(8) unsigned,
618 rev_parent_id int(8) unsigned default NULL,
619 PRIMARY KEY rev_page_id (rev_page, rev_id),
620 UNIQUE INDEX rev_id (rev_id),
621 INDEX rev_timestamp (rev_timestamp),
622 INDEX page_timestamp (rev_page,rev_timestamp),
623 INDEX user_timestamp (rev_user,rev_timestamp),
624 INDEX usertext_timestamp (rev_user_text,rev_timestamp)
625 ) ENGINE=InnoDB", $fname );
626
627 wfOut( wfTimestamp( TS_DB ) );
628 wfOut( "......Locking tables.\n" );
629 $wgDatabase->query( "LOCK TABLES $page WRITE, $revision WRITE, $old WRITE, $cur WRITE", $fname );
630
631 $maxold = intval( $wgDatabase->selectField( 'old', 'max(old_id)', '', $fname ) );
632 wfOut( wfTimestamp( TS_DB ) );
633 wfOut( "......maxold is {$maxold}\n" );
634
635 wfOut( wfTimestamp( TS_DB ) );
636 global $wgLegacySchemaConversion;
637 if( $wgLegacySchemaConversion ) {
638 // Create HistoryBlobCurStub entries.
639 // Text will be pulled from the leftover 'cur' table at runtime.
640 wfOut( "......Moving metadata from cur; using blob references to text in cur table.\n" );
641 $cur_text = "concat('O:18:\"historyblobcurstub\":1:{s:6:\"mCurId\";i:',cur_id,';}')";
642 $cur_flags = "'object'";
643 } else {
644 // Copy all cur text in immediately: this may take longer but avoids
645 // having to keep an extra table around.
646 wfOut( "......Moving text from cur.\n" );
647 $cur_text = 'cur_text';
648 $cur_flags = "''";
649 }
650 $wgDatabase->query( "INSERT INTO $old (old_namespace, old_title, old_text, old_comment, old_user, old_user_text,
651 old_timestamp, old_minor_edit, old_flags)
652 SELECT cur_namespace, cur_title, $cur_text, cur_comment, cur_user, cur_user_text, cur_timestamp, cur_minor_edit, $cur_flags
653 FROM $cur", $fname );
654
655 wfOut( wfTimestamp( TS_DB ) );
656 wfOut( "......Setting up revision table.\n" );
657 $wgDatabase->query( "INSERT INTO $revision (rev_id, rev_page, rev_comment, rev_user, rev_user_text, rev_timestamp,
658 rev_minor_edit)
659 SELECT old_id, cur_id, old_comment, old_user, old_user_text,
660 old_timestamp, old_minor_edit
661 FROM $old,$cur WHERE old_namespace=cur_namespace AND old_title=cur_title", $fname );
662
663 wfOut( wfTimestamp( TS_DB ) );
664 wfOut( "......Setting up page table.\n" );
665 $wgDatabase->query( "INSERT INTO $page (page_id, page_namespace, page_title, page_restrictions, page_counter,
666 page_is_redirect, page_is_new, page_random, page_touched, page_latest, page_len)
667 SELECT cur_id, cur_namespace, cur_title, cur_restrictions, cur_counter, cur_is_redirect, cur_is_new,
668 cur_random, cur_touched, rev_id, LENGTH(cur_text)
669 FROM $cur,$revision
670 WHERE cur_id=rev_page AND rev_timestamp=cur_timestamp AND rev_id > {$maxold}", $fname );
671
672 wfOut( wfTimestamp( TS_DB ) );
673 wfOut( "......Unlocking tables.\n" );
674 $wgDatabase->query( "UNLOCK TABLES", $fname );
675
676 wfOut( wfTimestamp( TS_DB ) );
677 wfOut( "......Renaming old.\n" );
678 $wgDatabase->query( "ALTER TABLE $old RENAME TO $text", $fname );
679
680 wfOut( wfTimestamp( TS_DB ) );
681 wfOut( "...done.\n" );
682 }
683 }
684
685 function do_inverse_timestamp() {
686 global $wgDatabase;
687 if( $wgDatabase->fieldExists( 'revision', 'inverse_timestamp' ) ) {
688 wfOut( "Removing revision.inverse_timestamp and fixing indexes... " );
689 $wgDatabase->sourceFile( archive( 'patch-inverse_timestamp.sql' ) );
690 wfOut( "ok\n" );
691 } else {
692 wfOut( "revision timestamp indexes already up to 2005-03-13\n" );
693 }
694 }
695
696 function do_text_id() {
697 global $wgDatabase;
698 if( $wgDatabase->fieldExists( 'revision', 'rev_text_id' ) ) {
699 wfOut( "...rev_text_id already in place.\n" );
700 } else {
701 wfOut( "Adding rev_text_id field... " );
702 $wgDatabase->sourceFile( archive( 'patch-rev_text_id.sql' ) );
703 wfOut( "ok\n" );
704 }
705 }
706
707 function do_namespace_size() {
708 $tables = array(
709 'page' => 'page',
710 'archive' => 'ar',
711 'recentchanges' => 'rc',
712 'watchlist' => 'wl',
713 'querycache' => 'qc',
714 'logging' => 'log',
715 );
716 foreach( $tables as $table => $prefix ) {
717 do_namespace_size_on( $table, $prefix );
718 flush();
719 }
720 }
721
722 function do_namespace_size_on( $table, $prefix ) {
723 global $wgDatabase, $wgDBtype;
724 if ($wgDBtype != 'mysql')
725 return;
726 $field = $prefix . '_namespace';
727
728 $tablename = $wgDatabase->tableName( $table );
729 $result = $wgDatabase->query( "SHOW COLUMNS FROM $tablename LIKE '$field'" );
730 $info = $wgDatabase->fetchObject( $result );
731 $wgDatabase->freeResult( $result );
732
733 if( substr( $info->Type, 0, 3 ) == 'int' ) {
734 wfOut( "...$field is already a full int ($info->Type).\n" );
735 } else {
736 wfOut( "Promoting $field from $info->Type to int... " );
737
738 $sql = "ALTER TABLE $tablename MODIFY $field int NOT NULL";
739 $wgDatabase->query( $sql );
740
741 wfOut( "ok\n" );
742 }
743 }
744
745 function do_pagelinks_update() {
746 global $wgDatabase;
747 if( $wgDatabase->tableExists( 'pagelinks' ) ) {
748 wfOut( "...already have pagelinks table.\n" );
749 } else {
750 wfOut( "Converting links and brokenlinks tables to pagelinks... " );
751 $wgDatabase->sourceFile( archive( 'patch-pagelinks.sql' ) );
752 wfOut( "ok\n" );
753 flush();
754
755 global $wgCanonicalNamespaceNames;
756 foreach( $wgCanonicalNamespaceNames as $ns => $name ) {
757 if( $ns != 0 ) {
758 do_pagelinks_namespace( $ns );
759 }
760 }
761 }
762 }
763
764 function do_pagelinks_namespace( $namespace ) {
765 global $wgDatabase, $wgContLang;
766
767 $ns = intval( $namespace );
768 wfOut( "Cleaning up broken links for namespace $ns... " );
769
770 $pagelinks = $wgDatabase->tableName( 'pagelinks' );
771 $name = $wgContLang->getNsText( $ns );
772 $prefix = $wgDatabase->strencode( $name );
773 $likeprefix = str_replace( '_', '\\_', $prefix);
774
775 $sql = "UPDATE $pagelinks
776 SET pl_namespace=$ns,
777 pl_title=TRIM(LEADING '$prefix:' FROM pl_title)
778 WHERE pl_namespace=0
779 AND pl_title LIKE '$likeprefix:%'";
780
781 $wgDatabase->query( $sql, 'do_pagelinks_namespace' );
782 wfOut( "ok\n" );
783 }
784
785 function do_drop_img_type() {
786 global $wgDatabase;
787
788 if( $wgDatabase->fieldExists( 'image', 'img_type' ) ) {
789 wfOut( "Dropping unused img_type field in image table... " );
790 $wgDatabase->sourceFile( archive( 'patch-drop_img_type.sql' ) );
791 wfOut( "ok\n" );
792 } else {
793 wfOut( "No img_type field in image table; Good.\n" );
794 }
795 }
796
797 function do_old_links_update() {
798 global $wgDatabase;
799 if( $wgDatabase->tableExists( 'pagelinks' ) ) {
800 wfOut( "Already have pagelinks; skipping old links table updates.\n" );
801 } else {
802 convertLinks(); flush();
803 }
804 }
805
806 function fix_ancient_imagelinks() {
807 global $wgDatabase;
808 $info = $wgDatabase->fieldInfo( 'imagelinks', 'il_from' );
809 if ( $info && $info->type() === 'string' ) {
810 wfOut( "Fixing ancient broken imagelinks table.\n" );
811 wfOut( "NOTE: you will have to run maintenance/refreshLinks.php after this.\n" );
812 $wgDatabase->sourceFile( archive( 'patch-fix-il_from.sql' ) );
813 wfOut( "ok\n" );
814 } else {
815 wfOut( "...il_from OK\n" );
816 }
817 }
818
819 function do_user_unique_update() {
820 global $wgDatabase;
821 $duper = new UserDupes( $wgDatabase );
822 if( $duper->hasUniqueIndex() ) {
823 wfOut( "Already have unique user_name index.\n" );
824 } else {
825 if( !$duper->clearDupes() ) {
826 wfOut( "WARNING: This next step will probably fail due to unfixed duplicates...\n" );
827 }
828 wfOut( "Adding unique index on user_name... " );
829 $wgDatabase->sourceFile( archive( 'patch-user_nameindex.sql' ) );
830 wfOut( "ok\n" );
831 }
832 }
833
834 function do_user_groups_update() {
835 $fname = 'do_user_groups_update';
836 global $wgDatabase;
837
838 if( $wgDatabase->tableExists( 'user_groups' ) ) {
839 wfOut( "...user_groups table already exists.\n" );
840 return do_user_groups_reformat();
841 }
842
843 wfOut( "Adding user_groups table... " );
844 $wgDatabase->sourceFile( archive( 'patch-user_groups.sql' ) );
845 wfOut( "ok\n" );
846
847 if( !$wgDatabase->tableExists( 'user_rights' ) ) {
848 if( $wgDatabase->fieldExists( 'user', 'user_rights' ) ) {
849 wfOut( "Upgrading from a 1.3 or older database? Breaking out user_rights for conversion..." );
850 $wgDatabase->sourceFile( archive( 'patch-user_rights.sql' ) );
851 wfOut( "ok\n" );
852 } else {
853 wfOut( "*** WARNING: couldn't locate user_rights table or field for upgrade.\n" );
854 wfOut( "*** You may need to manually configure some sysops by manipulating\n" );
855 wfOut( "*** the user_groups table.\n" );
856 return;
857 }
858 }
859
860 wfOut( "Converting user_rights table to user_groups... " );
861 $result = $wgDatabase->select( 'user_rights',
862 array( 'ur_user', 'ur_rights' ),
863 array( "ur_rights != ''" ),
864 $fname );
865
866 while( $row = $wgDatabase->fetchObject( $result ) ) {
867 $groups = array_unique(
868 array_map( 'trim',
869 explode( ',', $row->ur_rights ) ) );
870
871 foreach( $groups as $group ) {
872 $wgDatabase->insert( 'user_groups',
873 array(
874 'ug_user' => $row->ur_user,
875 'ug_group' => $group ),
876 $fname );
877 }
878 }
879 $wgDatabase->freeResult( $result );
880 wfOut( "ok\n" );
881 }
882
883 function do_user_groups_reformat() {
884 # Check for bogus formats from previous 1.5 alpha code.
885 global $wgDatabase;
886 $info = $wgDatabase->fieldInfo( 'user_groups', 'ug_group' );
887
888 if( $info->type() == 'int' ) {
889 $oldug = $wgDatabase->tableName( 'user_groups' );
890 $newug = $wgDatabase->tableName( 'user_groups_bogus' );
891 wfOut( "user_groups is in bogus intermediate format. Renaming to $newug... " );
892 $wgDatabase->query( "ALTER TABLE $oldug RENAME TO $newug" );
893 wfOut( "ok\n" );
894
895 wfOut( "Re-adding fresh user_groups table... " );
896 $wgDatabase->sourceFile( archive( 'patch-user_groups.sql' ) );
897 wfOut( "ok\n" );
898
899 wfOut( "***\n" );
900 wfOut( "*** WARNING: You will need to manually fix up user permissions in the user_groups\n" );
901 wfOut( "*** table. Old 1.5 alpha versions did some pretty funky stuff...\n" );
902 wfOut( "***\n" );
903 } else {
904 wfOut( "...user_groups is in current format.\n" );
905 }
906
907 }
908
909 function do_watchlist_null() {
910 # Make sure wl_notificationtimestamp can be NULL,
911 # and update old broken items.
912 global $wgDatabase;
913 $info = $wgDatabase->fieldInfo( 'watchlist', 'wl_notificationtimestamp' );
914
915 if( !$info->nullable() ) {
916 wfOut( "Making wl_notificationtimestamp nullable... " );
917 $wgDatabase->sourceFile( archive( 'patch-watchlist-null.sql' ) );
918 wfOut( "ok\n" );
919 } else {
920 wfOut( "...wl_notificationtimestamp is already nullable.\n" );
921 }
922
923 }
924
925 /**
926 * @bug 3946
927 */
928 function do_page_random_update() {
929 global $wgDatabase;
930
931 wfOut( "Setting page_random to a random value on rows where it equals 0..." );
932
933 $page = $wgDatabase->tableName( 'page' );
934 $wgDatabase->query( "UPDATE $page SET page_random = RAND() WHERE page_random = 0", 'do_page_random_update' );
935 $rows = $wgDatabase->affectedRows();
936
937 wfOut( "changed $rows rows\n" );
938 }
939
940 function do_templatelinks_update() {
941 global $wgDatabase, $wgLoadBalancer;
942 $fname = 'do_templatelinks_update';
943
944 if ( $wgDatabase->tableExists( 'templatelinks' ) ) {
945 wfOut( "...templatelinks table already exists\n" );
946 return;
947 }
948 wfOut( "Creating templatelinks table...\n" );
949 $wgDatabase->sourceFile( archive('patch-templatelinks.sql') );
950 wfOut( "Populating...\n" );
951 if ( isset( $wgLoadBalancer ) && $wgLoadBalancer->getServerCount() > 1 ) {
952 // Slow, replication-friendly update
953 $res = $wgDatabase->select( 'pagelinks', array( 'pl_from', 'pl_namespace', 'pl_title' ),
954 array( 'pl_namespace' => NS_TEMPLATE ), $fname );
955 $count = 0;
956 while ( $row = $wgDatabase->fetchObject( $res ) ) {
957 $count = ($count + 1) % 100;
958 if ( $count == 0 ) {
959 if ( function_exists( 'wfWaitForSlaves' ) ) {
960 wfWaitForSlaves( 10 );
961 } else {
962 sleep( 1 );
963 }
964 }
965 $wgDatabase->insert( 'templatelinks',
966 array(
967 'tl_from' => $row->pl_from,
968 'tl_namespace' => $row->pl_namespace,
969 'tl_title' => $row->pl_title,
970 ), $fname
971 );
972
973 }
974 $wgDatabase->freeResult( $res );
975 } else {
976 // Fast update
977 $wgDatabase->insertSelect( 'templatelinks', 'pagelinks',
978 array(
979 'tl_from' => 'pl_from',
980 'tl_namespace' => 'pl_namespace',
981 'tl_title' => 'pl_title'
982 ), array(
983 'pl_namespace' => 10
984 ), $fname
985 );
986 }
987 wfOut( "Done. Please run maintenance/refreshLinks.php for a more thorough templatelinks update.\n" );
988 }
989
990 // Add index on ( rc_namespace, rc_user_text ) [Jul. 2006]
991 // Add index on ( rc_user_text, rc_timestamp ) [Nov. 2006]
992 function do_rc_indices_update() {
993 global $wgDatabase;
994 wfOut( "Checking for additional recent changes indices...\n" );
995
996 $indexes = array(
997 'rc_ns_usertext' => 'patch-recentchanges-utindex.sql',
998 'rc_user_text' => 'patch-rc_user_text-index.sql',
999 );
1000
1001 foreach( $indexes as $index => $patch ) {
1002 $info = $wgDatabase->indexInfo( 'recentchanges', $index, __METHOD__ );
1003 if( !$info ) {
1004 wfOut( "...index `{$index}` not found; adding..." );
1005 $wgDatabase->sourceFile( archive( $patch ) );
1006 wfOut( "done.\n" );
1007 } else {
1008 wfOut( "...index `{$index}` seems ok.\n" );
1009 }
1010 }
1011 }
1012
1013 function index_has_field($table, $index, $field) {
1014 global $wgDatabase;
1015 wfOut( "Checking if $table index $index includes field $field...\n" );
1016 $info = $wgDatabase->indexInfo( $table, $index, __METHOD__ );
1017 if( $info ) {
1018 foreach($info as $row) {
1019 if($row->Column_name == $field) {
1020 wfOut( "...index $index on table $table seems to be ok\n" );
1021 return true;
1022 }
1023 }
1024 }
1025 wfOut( "...index $index on table $table has no field $field; adding\n" );
1026 return false;
1027 }
1028
1029 function do_backlinking_indices_update() {
1030 global $wgDatabase;
1031 wfOut( "Checking for backlinking indices...\n" );
1032 if (!index_has_field('pagelinks', 'pl_namespace', 'pl_from') ||
1033 !index_has_field('templatelinks', 'tl_namespace', 'tl_from') ||
1034 !index_has_field('imagelinks', 'il_to', 'il_from'))
1035 {
1036 $wgDatabase->sourceFile( archive( 'patch-backlinkindexes.sql' ) );
1037 wfOut( "...backlinking indices updated\n" );
1038 }
1039 }
1040
1041 function do_categorylinks_indices_update() {
1042 global $wgDatabase;
1043 wfOut( "Checking for categorylinks indices...\n" );
1044 if (!index_has_field('categorylinks', 'cl_sortkey', 'cl_from'))
1045 {
1046 $wgDatabase->sourceFile( archive( 'patch-categorylinksindex.sql' ) );
1047 wfOut( "...categorylinks indices updated\n" );
1048 }
1049 }
1050
1051 function do_filearchive_indices_update() {
1052 global $wgDatabase;
1053 wfOut( "Checking filearchive indices...\n" );
1054 $info = $wgDatabase->indexInfo( 'filearchive', 'fa_user_timestamp', __METHOD__ );
1055 if ( !$info )
1056 {
1057 $wgDatabase->sourceFile( archive( 'patch-filearchive-user-index.sql' ) );
1058 wfOut( "...filearchive indices updated\n" );
1059 }
1060 }
1061
1062 function maybe_do_profiling_memory_update() {
1063 global $wgDatabase;
1064 if ( !$wgDatabase->tableExists( 'profiling' ) ) {
1065 // Simply ignore
1066 } elseif ( $wgDatabase->fieldExists( 'profiling', 'pf_memory' ) ) {
1067 wfOut( "profiling table has pf_memory field.\n" );
1068 } else {
1069 wfOut( "Adding pf_memory field to table profiling..." );
1070 $wgDatabase->sourceFile( archive( 'patch-profiling-memory.sql' ) );
1071 wfOut( "ok\n" );
1072 }
1073 }
1074
1075 function do_stats_init() {
1076 // Sometimes site_stats table is not properly populated.
1077 global $wgDatabase;
1078 wfOut( "Checking site_stats row..." );
1079 $row = $wgDatabase->selectRow( 'site_stats', '*', array( 'ss_row_id' => 1 ), __METHOD__ );
1080 if( $row === false ) {
1081 wfOut( "data is missing! rebuilding...\n" );
1082 } elseif ( isset( $row->site_stats ) && $row->ss_total_pages == -1 ) {
1083 wfOut( "missing ss_total_pages, rebuilding...\n" );
1084 } else {
1085 wfOut( "ok.\n" );
1086 return;
1087 }
1088 SiteStatsInit::doAllAndCommit( false );
1089 }
1090
1091 function do_active_users_init() {
1092 global $wgDatabase;
1093 $activeUsers = $wgDatabase->selectField( 'site_stats', 'ss_active_users', false, __METHOD__ );
1094 if( $activeUsers == -1 ) {
1095 $activeUsers = $wgDatabase->selectField( 'recentchanges',
1096 'COUNT( DISTINCT rc_user_text )',
1097 array( 'rc_user != 0', 'rc_bot' => 0, "rc_log_type != 'newusers'" ), __METHOD__
1098 );
1099 $wgDatabase->update( 'site_stats',
1100 array( 'ss_active_users' => intval($activeUsers) ),
1101 array( 'ss_row_id' => 1 ), __METHOD__, array( 'LIMIT' => 1 )
1102 );
1103 }
1104 wfOut( "...ss_active_users user count set...\n" );
1105 }
1106
1107 function purge_cache() {
1108 global $wgDatabase;
1109 # We can't guarantee that the user will be able to use TRUNCATE,
1110 # but we know that DELETE is available to us
1111 wfOut( "Purging caches..." );
1112 $wgDatabase->delete( 'objectcache', '*', __METHOD__ );
1113 wfOut( "done.\n" );
1114 }
1115
1116 function do_all_updates( $shared = false, $purge = true ) {
1117 global $wgNewTables, $wgExtModifiedFields, $wgNewFields, $wgRenamedTables, $wgSharedDB, $wgSharedTables, $wgDatabase, $wgDBtype, $IP;
1118
1119 wfRunHooks('LoadExtensionSchemaUpdates');
1120
1121 $doUser = $shared ? $wgSharedDB && in_array('user', $wgSharedTables) : !$wgSharedDB || !in_array('user', $wgSharedTables);
1122
1123 if ($wgDBtype === 'postgres') {
1124 do_postgres_updates();
1125 return;
1126 }
1127
1128 # Run core updates in sequence...
1129 global $wgUpdates;
1130 if ( isset( $wgUpdates[$wgDBtype] ) ) {
1131 foreach( $wgUpdates[$wgDBtype] as $params ) {
1132 $func = array_shift( $params );
1133 call_user_func_array( $func, $params );
1134 flush();
1135 }
1136 }
1137
1138 /// @fixme clean up this mess too!
1139 global $wgExtNewTables, $wgExtNewFields, $wgExtNewIndexes;
1140 # Add missing extension tables
1141 foreach ( $wgExtNewTables as $tableRecord ) {
1142 add_table( $tableRecord[0], $tableRecord[1], true );
1143 flush();
1144 }
1145 # Add missing extension fields
1146 foreach ( $wgExtNewFields as $fieldRecord ) {
1147 if ( $fieldRecord[0] != 'user' || $doUser ) {
1148 add_field( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
1149 }
1150 flush();
1151 }
1152 # Add missing extension indexes
1153 foreach ( $wgExtNewIndexes as $fieldRecord ) {
1154 add_index( $fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true );
1155 flush();
1156 }
1157 # Add modified extension fields
1158 foreach ( $wgExtModifiedFields as $fieldRecord ) {
1159 modify_field($fieldRecord[0], $fieldRecord[1], $fieldRecord[2], true);
1160 flush();
1161 }
1162
1163
1164 wfOut( "Deleting old default messages (this may take a long time!)..." );
1165 if( !defined( 'MW_NO_SETUP' ) ) {
1166 define( 'MW_NO_SETUP', true );
1167 }
1168 require_once 'deleteDefaultMessages.php';
1169 DeleteDefaultMessages::reallyExecute();
1170 wfOut( "Done\n" );
1171
1172 do_stats_init();
1173
1174 if( $purge ) {
1175 purge_cache();
1176 }
1177 }
1178
1179 function archive($name) {
1180 global $wgDBtype, $IP;
1181 if ( file_exists( "$IP/maintenance/$wgDBtype/archives/$name" ) ) {
1182 return "$IP/maintenance/$wgDBtype/archives/$name";
1183 } else {
1184 return "$IP/maintenance/archives/$name";
1185 }
1186 }
1187
1188 function do_restrictions_update() {
1189 # Adding page_restrictions table, obsoleting page.page_restrictions.
1190 # Migrating old restrictions to new table
1191 # -- Andrew Garrett, January 2007.
1192
1193 global $wgDatabase;
1194
1195 $name = 'page_restrictions';
1196 $patch = 'patch-page_restrictions.sql';
1197 $patch2 = 'patch-page_restrictions_sortkey.sql';
1198
1199 if ( $wgDatabase->tableExists( $name ) ) {
1200 wfOut( "...$name table already exists.\n" );
1201 } else {
1202 wfOut( "Creating $name table..." );
1203 $wgDatabase->sourceFile( archive($patch) );
1204 $wgDatabase->sourceFile( archive($patch2) );
1205 wfOut( "ok\n" );
1206
1207 wfOut( "Migrating old restrictions to new table..." );
1208
1209 $res = $wgDatabase->select( 'page', array( 'page_id', 'page_restrictions' ), array("page_restrictions!=''", "page_restrictions!='edit=:move='"), __METHOD__ );
1210
1211 $count = 0;
1212
1213 while ($row = $wgDatabase->fetchObject($res) ) {
1214 $count = ($count + 1) % 100;
1215
1216 if ($count == 0) {
1217 if ( function_exists( 'wfWaitForSlaves' ) ) {
1218 wfWaitForSlaves( 10 );
1219 } else {
1220 sleep( 1 );
1221 }
1222 }
1223
1224 # Figure out what the restrictions are..
1225 $id = $row->page_id;
1226 $flatrestrictions = explode( ':', $row->page_restrictions );
1227
1228 $restrictions = array ();
1229 foreach( $flatrestrictions as $restriction ) {
1230 $thisrestriction = explode( '=', $restriction, 2 );
1231 if( count( $thisrestriction ) == 1 ) {
1232 // Compatibility with old protections from before
1233 // separate move protection was added.
1234 list( $level ) = $thisrestriction;
1235 if( $level ) {
1236 $restrictions['edit'] = $level;
1237 $restrictions['move'] = $level;
1238 }
1239 } else {
1240 list( $type, $level ) = $thisrestriction;
1241 if( $level ) {
1242 $restrictions[$type] = $level;
1243 }
1244 }
1245
1246 $wgDatabase->update( 'page', array ( 'page_restrictions' => ''), array( 'page_id' => $id ), __METHOD__ );
1247
1248 }
1249
1250 foreach( $restrictions as $type => $level ) {
1251 $wgDatabase->insert( 'page_restrictions', array ( 'pr_page' => $id,
1252 'pr_type' => $type,
1253 'pr_level' => $level,
1254 'pr_cascade' => 0,
1255 'pr_expiry' => 'infinity' ),
1256 __METHOD__ );
1257 }
1258 }
1259 wfOut( "ok\n" );
1260 }
1261 }
1262
1263 function do_category_population() {
1264 if( update_row_exists( 'populate category' ) ) {
1265 wfOut( "...category table already populated.\n" );
1266 return;
1267 }
1268 require_once( 'populateCategory.php' );
1269 wfOut( "Populating category table, printing progress markers. " ).
1270 "For large databases, you\n".
1271 "may want to hit Ctrl-C and do this manually with maintenance/\n".
1272 "populateCategory.php.\n";
1273 $task = new PopulateCategory();
1274 $task->execute();
1275 wfOut( "Done populating category table.\n" );
1276 }
1277
1278 function do_populate_parent_id() {
1279 if( update_row_exists( 'populate rev_parent_id' ) ) {
1280 wfOut( "...rev_parent_id column already populated.\n" );
1281 return;
1282 }
1283 require_once( 'populateParentId.php' );
1284 $task = new PopulateParentId();
1285 $task->execute();
1286 }
1287
1288 function do_populate_rev_len() {
1289 if( update_row_exists( 'populate rev_len' ) ) {
1290 wfOut( "...rev_len column already populated.\n" );
1291 return;
1292 }
1293 require_once( 'populateRevisionLength.php' );
1294 $task = new PopulateRevisionLength();
1295 $task->execute();
1296 }
1297
1298 function sqlite_initial_indexes() {
1299 global $wgDatabase;
1300 // initial-indexes.sql fails if the indexes are already present, so we perform a quick check if our database is newer.
1301 if ( update_row_exists( 'initial_indexes' ) || $wgDatabase->indexExists( 'user', 'user_name' ) ) {
1302 wfOut( "...have initial indexes\n" );
1303 return;
1304 }
1305 wfOut( "Adding initial indexes..." );
1306 $wgDatabase->sourceFile( archive( 'initial-indexes.sql' ) );
1307 wfOut( "done\n" );
1308 }
1309
1310 function sqlite_setup_searchindex() {
1311 global $wgDatabase;
1312 $module = $wgDatabase->getFulltextSearchModule();
1313 $fts3tTable = update_row_exists( 'fts3' );
1314 if ( $fts3tTable && !$module ) {
1315 wfOut( '...PHP is missing FTS3 support, downgrading tables...' );
1316 $wgDatabase->sourceFile( archive( 'searchindex-no-fts.sql' ) );
1317 wfOut( "done\n" );
1318 } elseif ( !$fts3tTable && $module == 'FTS3' ) {
1319 wfOut( '...adding FTS3 search capabilities...' );
1320 $wgDatabase->sourceFile( archive( 'searchindex-fts3.sql' ) );
1321 wfOut( "done\n" );
1322 } else {
1323 wfOut( "...fulltext search table appears to be in order.\n" );
1324 }
1325 }
1326
1327 function do_unique_pl_tl_il() {
1328 global $wgDatabase;
1329 $info = $wgDatabase->indexInfo( 'pagelinks', 'pl_namespace' );
1330 if( is_array($info) && !$info[0]->Non_unique ) {
1331 wfOut( "...pl_namespace, tl_namespace, il_to indices are already UNIQUE.\n" );
1332 } else {
1333 wfOut( "Making pl_namespace, tl_namespace and il_to indices UNIQUE... " );
1334 $wgDatabase->sourceFile( archive( 'patch-pl-tl-il-unique.sql' ) );
1335 wfOut( "ok\n" );
1336 }
1337 }
1338
1339 function do_log_search_population() {
1340 global $wgDatabase;
1341 if( update_row_exists( 'populate log_search' ) ) {
1342 wfOut( "...log_search table already populated.\n" );
1343 return;
1344 }
1345 require_once( 'populateLogSearch.php' );
1346 wfOut(
1347 "Populating log_search table, printing progress markers. For large\n" .
1348 "databases, you may want to hit Ctrl-C and do this manually with\n" .
1349 "maintenance/populateLogSearch.php.\n" );
1350 $task = new PopulateLogSearch();
1351 $task->execute();
1352 wfOut( "Done populating log_search table.\n" );
1353 }
1354
1355 function rename_eu_wiki_id() {
1356 global $wgDatabase;
1357 wfOut( "Renaming eu_wiki_id -> eu_local_id... " );
1358 if ( $wgDatabase->fieldExists( 'external_user', 'eu_local_id' ) ) {
1359 wfOut( "already done.\n" );
1360 return;
1361 }
1362 $wgDatabase->sourceFile( archive( 'patch-eu_local_id.sql' ) );
1363 wfOut( "ok\n" );
1364 }
1365
1366 function do_update_transcache_field() {
1367 global $wgDatabase;
1368 if( update_row_exists( 'convert transcache field' ) ) {
1369 wfOut( "...transcache tc_time already converted.\n" );
1370 return;
1371 } else {
1372 wfOut( "Converting tc_time from UNIX epoch to MediaWiki timestamp... " );
1373 $wgDatabase->sourceFile( archive( 'patch-tc-timestamp.sql' ) );
1374 wfOut( "ok\n" );
1375 }
1376 }
1377
1378 function do_update_mime_minor_field() {
1379 if ( update_row_exists( 'mime_minor_length' ) ) {
1380 wfOut( "*_mime_minor fields are already long enough.\n" );
1381 } else {
1382 global $wgDatabase;
1383 wfOut( "Altering all *_mime_minor fields to 100 bytes in size ... " );
1384 $wgDatabase->sourceFile( archive( 'patch-mime_minor_length.sql' ) );
1385 wfOut( "ok\n" );
1386 }
1387 }
1388
1389
1390
1391 /***********************************************************************
1392 * Start PG stuff
1393 * TODO: merge with above
1394 ***********************************************************************/
1395
1396 function pg_describe_table($table) {
1397 global $wgDatabase, $wgDBmwschema;
1398 $q = <<<END
1399 SELECT attname, attnum FROM pg_namespace, pg_class, pg_attribute
1400 WHERE pg_class.relnamespace = pg_namespace.oid
1401 AND attrelid=pg_class.oid AND attnum > 0
1402 AND relname=%s AND nspname=%s
1403 END;
1404 $res = $wgDatabase->query(sprintf($q,
1405 $wgDatabase->addQuotes($table),
1406 $wgDatabase->addQuotes($wgDBmwschema)));
1407 if (!$res)
1408 return null;
1409
1410 $cols = array();
1411 while ($r = $wgDatabase->fetchRow($res)) {
1412 $cols[] = array(
1413 "name" => $r[0],
1414 "ord" => $r[1],
1415 );
1416 }
1417 return $cols;
1418 }
1419
1420 function pg_describe_index($idx) {
1421 global $wgDatabase, $wgDBmwschema;
1422
1423 // first fetch the key (which is a list of columns ords) and
1424 // the table the index applies to (an oid)
1425 $q = <<<END
1426 SELECT indkey, indrelid FROM pg_namespace, pg_class, pg_index
1427 WHERE nspname=%s
1428 AND pg_class.relnamespace = pg_namespace.oid
1429 AND relname=%s
1430 AND indexrelid=pg_class.oid
1431 END;
1432 $res = $wgDatabase->query(sprintf($q,
1433 $wgDatabase->addQuotes($wgDBmwschema),
1434 $wgDatabase->addQuotes($idx)));
1435 if (!$res)
1436 return null;
1437 if (!($r = $wgDatabase->fetchRow($res))) {
1438 $wgDatabase->freeResult($res);
1439 return null;
1440 }
1441
1442 $indkey = $r[0];
1443 $relid = intval($r[1]);
1444 $indkeys = explode(" ", $indkey);
1445 $wgDatabase->freeResult($res);
1446
1447 $colnames = array();
1448 foreach ($indkeys as $rid) {
1449 $query = <<<END
1450 SELECT attname FROM pg_class, pg_attribute
1451 WHERE attrelid=$relid
1452 AND attnum=%d
1453 AND attrelid=pg_class.oid
1454 END;
1455 $r2 = $wgDatabase->query(sprintf($query, $rid));
1456 if (!$r2)
1457 return null;
1458 if (!($row2 = $wgDatabase->fetchRow($r2))) {
1459 $wgDatabase->freeResult($r2);
1460 return null;
1461 }
1462 $colnames[] = $row2[0];
1463 $wgDatabase->freeResult($r2);
1464 }
1465
1466 return $colnames;
1467 }
1468
1469 function pg_index_exists($table, $index) {
1470 global $wgDatabase, $wgDBmwschema;
1471 $exists = $wgDatabase->selectField("pg_indexes", "indexname",
1472 array( "indexname" => $index,
1473 "tablename" => $table,
1474 "schemaname" => $wgDBmwschema));
1475 return $exists === $index;
1476 }
1477
1478 function pg_fkey_deltype($fkey) {
1479 global $wgDatabase, $wgDBmwschema;
1480 $q = <<<END
1481 SELECT confdeltype FROM pg_constraint, pg_namespace
1482 WHERE connamespace=pg_namespace.oid
1483 AND nspname=%s
1484 AND conname=%s;
1485 END;
1486 $r = $wgDatabase->query(sprintf($q,
1487 $wgDatabase->addQuotes($wgDBmwschema),
1488 $wgDatabase->addQuotes($fkey)));
1489 if (!($row = $wgDatabase->fetchRow($r)))
1490 return null;
1491 return $row[0];
1492 }
1493
1494 function pg_rule_def($table, $rule) {
1495 global $wgDatabase, $wgDBmwschema;
1496 $q = <<<END
1497 SELECT definition FROM pg_rules
1498 WHERE schemaname = %s
1499 AND tablename = %s
1500 AND rulename = %s
1501 END;
1502 $r = $wgDatabase->query(sprintf($q,
1503 $wgDatabase->addQuotes($wgDBmwschema),
1504 $wgDatabase->addQuotes($table),
1505 $wgDatabase->addQuotes($rule)));
1506 $row = $wgDatabase->fetchRow($r);
1507 if (!$row)
1508 return null;
1509 $d = $row[0];
1510 $wgDatabase->freeResult($r);
1511 return $d;
1512 }
1513
1514 function do_postgres_updates() {
1515 global $wgDatabase, $wgVersion, $wgDBmwschema, $wgDBts2schema, $wgShowExceptionDetails, $wgDBuser;
1516
1517 ## Gather version numbers in case we need them
1518 $version = $wgDatabase->getServerVersion(); ## long string
1519 $numver = $wgDatabase->numeric_version; ## X.Y e.g. 8.3
1520
1521 $wgShowExceptionDetails = 1;
1522
1523 # Just in case their LocalSettings.php does not have this:
1524 if ( !isset( $wgDBmwschema ))
1525 $wgDBmwschema = 'mediawiki';
1526
1527 # Verify that this user is configured correctly
1528 $safeuser = $wgDatabase->addQuotes($wgDBuser);
1529 $SQL = "SELECT array_to_string(useconfig,'*') FROM pg_catalog.pg_user WHERE usename = $safeuser";
1530 $config = pg_fetch_result( $wgDatabase->doQuery( $SQL ), 0, 0 );
1531 $conf = array();
1532 foreach( explode( '*', $config ) as $c ) {
1533 list( $x,$y ) = explode( '=', $c );
1534 $conf[$x] = $y;
1535 }
1536 if( !array_key_exists( 'search_path', $conf ) ) {
1537 $search_path = '';
1538 }
1539 else {
1540 $search_path = $conf['search_path'];
1541 }
1542 if( strpos( $search_path, $wgDBmwschema ) === false ) {
1543 wfOut( "Adding in schema \"$wgDBmwschema\" to search_path for user \"$wgDBuser\"\n" );
1544 $search_path = "$wgDBmwschema, $search_path";
1545 }
1546 if( strpos( $search_path, $wgDBts2schema ) === false ) {
1547 wfOut( "Adding in schema \"$wgDBts2schema\" to search_path for user \"$wgDBuser\"\n" );
1548 $search_path = "$search_path, $wgDBts2schema";
1549 }
1550 $search_path = str_replace( ', ,', ',', $search_path);
1551 if( array_key_exists( 'search_path', $conf ) === false || $search_path != $conf['search_path'] ) {
1552 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET search_path = $search_path" );
1553 $wgDatabase->doQuery( "SET search_path = $search_path" );
1554 }
1555 else {
1556 $path = $conf['search_path'];
1557 wfOut( "... search_path for user \"$wgDBuser\" looks correct ($path)\n" );
1558 }
1559 $goodconf = array(
1560 'client_min_messages' => 'error',
1561 'DateStyle' => 'ISO, YMD',
1562 'TimeZone' => 'GMT'
1563 );
1564 foreach( array_keys( $goodconf ) AS $key ) {
1565 $value = $goodconf[$key];
1566 if( !array_key_exists( $key, $conf ) or $conf[$key] !== $value ) {
1567 wfOut( "Setting $key to '$value' for user \"$wgDBuser\"\n" );
1568 $wgDatabase->doQuery( "ALTER USER $wgDBuser SET $key = '$value'" );
1569 $wgDatabase->doQuery( "SET $key = '$value'" );
1570 }
1571 else {
1572 wfOut( "... default value of \"$key\" is correctly set to \"$value\" for user \"$wgDBuser\"\n" );
1573 }
1574 }
1575
1576 $newsequences = array(
1577 "logging_log_id_seq",
1578 "page_restrictions_pr_id_seq",
1579 );
1580
1581 $newtables = array(
1582 array("category", "patch-category.sql"),
1583 array("mediawiki_version", "patch-mediawiki_version.sql"),
1584 array("mwuser", "patch-mwuser.sql"),
1585 array("pagecontent", "patch-pagecontent.sql"),
1586 array("querycachetwo", "patch-querycachetwo.sql"),
1587 array("page_props", "patch-page_props.sql"),
1588 array("page_restrictions", "patch-page_restrictions.sql"),
1589 array("profiling", "patch-profiling.sql"),
1590 array("protected_titles", "patch-protected_titles.sql"),
1591 array("redirect", "patch-redirect.sql"),
1592 array("updatelog", "patch-updatelog.sql"),
1593 array('change_tag', 'patch-change_tag.sql'),
1594 array('tag_summary', 'patch-change_tag.sql'),
1595 array('valid_tag', 'patch-change_tag.sql'),
1596 array('user_properties', 'patch-user_properties.sql'),
1597 array('log_search', 'patch-log_search.sql'),
1598 array('l10n_cache', 'patch-l10n_cache.sql'),
1599 // @fixme add iwlinks table
1600 );
1601
1602 $newcols = array(
1603 array("archive", "ar_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1604 array("archive", "ar_len", "INTEGER"),
1605 array("archive", "ar_page_id", "INTEGER"),
1606 array("archive", "ar_parent_id", "INTEGER"),
1607 array("image", "img_sha1", "TEXT NOT NULL DEFAULT ''"),
1608 array("ipblocks", "ipb_allow_usertalk", "SMALLINT NOT NULL DEFAULT 0"),
1609 array("ipblocks", "ipb_anon_only", "SMALLINT NOT NULL DEFAULT 0"),
1610 array("ipblocks", "ipb_by_text", "TEXT NOT NULL DEFAULT ''"),
1611 array("ipblocks", "ipb_block_email", "SMALLINT NOT NULL DEFAULT 0"),
1612 array("ipblocks", "ipb_create_account", "SMALLINT NOT NULL DEFAULT 1"),
1613 array("ipblocks", "ipb_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1614 array("ipblocks", "ipb_enable_autoblock", "SMALLINT NOT NULL DEFAULT 1"),
1615 array("filearchive", "fa_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1616 array("logging", "log_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1617 array("logging", "log_id", "INTEGER NOT NULL PRIMARY KEY DEFAULT nextval('logging_log_id_seq')"),
1618 array("logging", "log_params", "TEXT"),
1619 array("mwuser", "user_editcount", "INTEGER"),
1620 array("mwuser", "user_hidden", "SMALLINT NOT NULL DEFAULT 0"),
1621 array("mwuser", "user_newpass_time", "TIMESTAMPTZ"),
1622 array("oldimage", "oi_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1623 array("oldimage", "oi_major_mime", "TEXT NOT NULL DEFAULT 'unknown'"),
1624 array("oldimage", "oi_media_type", "TEXT"),
1625 array("oldimage", "oi_metadata", "BYTEA NOT NULL DEFAULT ''"),
1626 array("oldimage", "oi_minor_mime", "TEXT NOT NULL DEFAULT 'unknown'"),
1627 array("oldimage", "oi_sha1", "TEXT NOT NULL DEFAULT ''"),
1628 array("page_restrictions", "pr_id", "INTEGER NOT NULL UNIQUE DEFAULT nextval('page_restrictions_pr_id_val')"),
1629 array("profiling", "pf_memory", "NUMERIC(18,10) NOT NULL DEFAULT 0"),
1630 array("recentchanges", "rc_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1631 array("recentchanges", "rc_log_action", "TEXT"),
1632 array("recentchanges", "rc_log_type", "TEXT"),
1633 array("recentchanges", "rc_logid", "INTEGER NOT NULL DEFAULT 0"),
1634 array("recentchanges", "rc_new_len", "INTEGER"),
1635 array("recentchanges", "rc_old_len", "INTEGER"),
1636 array("recentchanges", "rc_params", "TEXT"),
1637 array("redirect", "rd_interwiki", "TEXT NULL"),
1638 array("redirect", "rd_fragment", "TEXT NULL"),
1639 array("revision", "rev_deleted", "SMALLINT NOT NULL DEFAULT 0"),
1640 array("revision", "rev_len", "INTEGER"),
1641 array("revision", "rev_parent_id", "INTEGER DEFAULT NULL"),
1642 array("site_stats", "ss_active_users", "INTEGER DEFAULT '-1'"),
1643 array("user_newtalk", "user_last_timestamp", "TIMESTAMPTZ"),
1644 array("logging", "log_user_text", "TEXT NOT NULL DEFAULT ''"),
1645 array("logging", "log_page", "INTEGER"),
1646 );
1647
1648
1649 # table, column, desired type, USING clause if needed (with new default if needed)
1650 $typechanges = array(
1651 array("archive", "ar_deleted", "smallint", ""),
1652 array("archive", "ar_minor_edit", "smallint", "ar_minor_edit::smallint DEFAULT 0"),
1653 array("filearchive", "fa_deleted", "smallint", ""),
1654 array("filearchive", "fa_height", "integer", ""),
1655 array("filearchive", "fa_metadata", "bytea", "decode(fa_metadata,'escape')"),
1656 array("filearchive", "fa_size", "integer", ""),
1657 array("filearchive", "fa_width", "integer", ""),
1658 array("filearchive", "fa_storage_group","text", ""),
1659 array("filearchive", "fa_storage_key", "text", ""),
1660 array("image", "img_metadata", "bytea", "decode(img_metadata,'escape')"),
1661 array("image", "img_size", "integer", ""),
1662 array("image", "img_width", "integer", ""),
1663 array("image", "img_height", "integer", ""),
1664 array("interwiki", "iw_local", "smallint", "iw_local::smallint DEFAULT 0"),
1665 array("interwiki", "iw_trans", "smallint", "iw_trans::smallint DEFAULT 0"),
1666 array("ipblocks", "ipb_auto", "smallint", "ipb_auto::smallint DEFAULT 0"),
1667 array("ipblocks", "ipb_anon_only", "smallint", "CASE WHEN ipb_anon_only=' ' THEN 0 ELSE ipb_anon_only::smallint END DEFAULT 0"),
1668 array("ipblocks", "ipb_create_account", "smallint", "CASE WHEN ipb_create_account=' ' THEN 0 ELSE ipb_create_account::smallint END DEFAULT 1"),
1669 array("ipblocks", "ipb_enable_autoblock", "smallint", "CASE WHEN ipb_enable_autoblock=' ' THEN 0 ELSE ipb_enable_autoblock::smallint END DEFAULT 1"),
1670 array("ipblocks", "ipb_block_email", "smallint", "CASE WHEN ipb_block_email=' ' THEN 0 ELSE ipb_block_email::smallint END DEFAULT 0"),
1671 array("ipblocks", "ipb_address", "text", "ipb_address::text"),
1672 array("ipblocks", "ipb_deleted", "smallint", "ipb_deleted::smallint DEFAULT 0"),
1673 array("math", "math_inputhash", "bytea", "decode(math_inputhash,'escape')"),
1674 array("math", "math_outputhash", "bytea", "decode(math_outputhash,'escape')"),
1675 array("mwuser", "user_token", "text", ""),
1676 array("mwuser", "user_email_token","text", ""),
1677 array("objectcache", "keyname", "text", ""),
1678 array("oldimage", "oi_height", "integer", ""),
1679 array("oldimage", "oi_metadata", "bytea", "decode(img_metadata,'escape')"),
1680 array("oldimage", "oi_size", "integer", ""),
1681 array("oldimage", "oi_width", "integer", ""),
1682 array("page", "page_is_redirect","smallint", "page_is_redirect::smallint DEFAULT 0"),
1683 array("page", "page_is_new", "smallint", "page_is_new::smallint DEFAULT 0"),
1684 array("querycache", "qc_value", "integer", ""),
1685 array("querycachetwo","qcc_value", "integer", ""),
1686 array("recentchanges","rc_bot", "smallint", "rc_bot::smallint DEFAULT 0"),
1687 array("recentchanges","rc_deleted", "smallint", ""),
1688 array("recentchanges","rc_minor", "smallint", "rc_minor::smallint DEFAULT 0"),
1689 array("recentchanges","rc_new", "smallint", "rc_new::smallint DEFAULT 0"),
1690 array("recentchanges","rc_type", "smallint", "rc_type::smallint DEFAULT 0"),
1691 array("recentchanges","rc_patrolled", "smallint", "rc_patrolled::smallint DEFAULT 0"),
1692 array("revision", "rev_deleted", "smallint", "rev_deleted::smallint DEFAULT 0"),
1693 array("revision", "rev_minor_edit", "smallint", "rev_minor_edit::smallint DEFAULT 0"),
1694 array("templatelinks","tl_namespace", "smallint", "tl_namespace::smallint"),
1695 array("user_newtalk", "user_ip", "text", "host(user_ip)"),
1696 );
1697
1698 # table, column, nullability
1699 $nullchanges = array(
1700 array("oldimage", "oi_bits", "NULL"),
1701 array("oldimage", "oi_timestamp", "NULL"),
1702 array("oldimage", "oi_major_mime", "NULL"),
1703 array("oldimage", "oi_minor_mime", "NULL"),
1704 );
1705
1706 $newindexes = array(
1707 array("archive", "archive_user_text", "(ar_user_text)"),
1708 array("image", "img_sha1", "(img_sha1)"),
1709 array("oldimage", "oi_sha1", "(oi_sha1)"),
1710 array("revision", "rev_text_id_idx", "(rev_text_id)"),
1711 array("recentchanges", "rc_timestamp_bot", "(rc_timestamp) WHERE rc_bot = 0"),
1712 array("templatelinks", "templatelinks_from", "(tl_from)"),
1713 array("watchlist", "wl_user", "(wl_user)"),
1714 array("logging", "logging_user_type_time", "(log_user, log_type, log_timestamp)"),
1715 array("logging", "logging_page_id_time", "(log_page,log_timestamp)"),
1716 );
1717
1718 $newrules = array(
1719 );
1720
1721 ## All FK columns should be deferred
1722 $deferredcols = array(
1723 array("archive", "ar_user", "mwuser(user_id) ON DELETE SET NULL"),
1724 array("categorylinks", "cl_from", "page(page_id) ON DELETE CASCADE"),
1725 array("externallinks", "el_from", "page(page_id) ON DELETE CASCADE"),
1726 array("filearchive", "fa_deleted_user", "mwuser(user_id) ON DELETE SET NULL"),
1727 array("filearchive", "fa_user", "mwuser(user_id) ON DELETE SET NULL"),
1728 array("image", "img_user", "mwuser(user_id) ON DELETE SET NULL"),
1729 array("imagelinks", "il_from", "page(page_id) ON DELETE CASCADE"),
1730 array("ipblocks", "ipb_by", "mwuser(user_id) ON DELETE CASCADE"),
1731 array("ipblocks", "ipb_user", "mwuser(user_id) ON DELETE SET NULL"),
1732 array("langlinks", "ll_from", "page(page_id) ON DELETE CASCADE"),
1733 array("logging", "log_user", "mwuser(user_id) ON DELETE SET NULL"),
1734 array("oldimage", "oi_name", "image(img_name) ON DELETE CASCADE ON UPDATE CASCADE"),
1735 array("oldimage", "oi_user", "mwuser(user_id) ON DELETE SET NULL"),
1736 array("pagelinks", "pl_from", "page(page_id) ON DELETE CASCADE"),
1737 array("page_props", "pp_page", "page (page_id) ON DELETE CASCADE"),
1738 array("page_restrictions","pr_page", "page(page_id) ON DELETE CASCADE"),
1739 array("protected_titles", "pt_user", "mwuser(user_id) ON DELETE SET NULL"),
1740 array("recentchanges", "rc_cur_id", "page(page_id) ON DELETE SET NULL"),
1741 array("recentchanges", "rc_user", "mwuser(user_id) ON DELETE SET NULL"),
1742 array("redirect", "rd_from", "page(page_id) ON DELETE CASCADE"),
1743 array("revision", "rev_page", "page (page_id) ON DELETE CASCADE"),
1744 array("revision", "rev_user", "mwuser(user_id) ON DELETE RESTRICT"),
1745 array("templatelinks", "tl_from", "page(page_id) ON DELETE CASCADE"),
1746 array("trackbacks", "tb_page", "page(page_id) ON DELETE CASCADE"),
1747 array("user_groups", "ug_user", "mwuser(user_id) ON DELETE CASCADE"),
1748 array("user_newtalk", "user_id", "mwuser(user_id) ON DELETE CASCADE"),
1749 array("user_properties", "up_user", "mwuser(user_id) ON DELETE CASCADE"),
1750 array("watchlist", "wl_user", "mwuser(user_id) ON DELETE CASCADE"),
1751 );
1752
1753 #Check new sequences, rename if needed
1754 foreach ($newsequences as $ns) {
1755 if( $wgDatabase->sequenceExists('pr_id_val') ) {
1756 wfOut( "Updating sequence names\n" );
1757 $wgDatabase->sourceFile(archive('patch-update_sequences.sql'));
1758 continue;
1759 } elseif ( $wgDatabase->sequenceExists('page_restrictions_pr_id_seq') ) {
1760 wfOut( "... sequences already updated\n" );
1761 continue;
1762 } else {
1763 wfOut( "Creating sequence \"$ns\"\n" );
1764 $wgDatabase->query("CREATE SEQUENCE $ns");
1765 }
1766 }
1767
1768 foreach ($newtables as $nt) {
1769 if ($wgDatabase->tableExists($nt[0])) {
1770 wfOut( "... table \"$nt[0]\" already exists\n" );
1771 continue;
1772 }
1773
1774 wfOut( "Creating table \"$nt[0]\"\n" );
1775 $wgDatabase->sourceFile(archive($nt[1]));
1776 }
1777
1778 ## Needed before newcols
1779 if ($wgDatabase->tableExists("archive2")) {
1780 wfOut( "Converting \"archive2\" back to normal archive table\n" );
1781 if ($wgDatabase->ruleExists("archive", "archive_insert")) {
1782 wfOut( "Dropping rule \"archive_insert\"\n" );
1783 $wgDatabase->query("DROP RULE archive_insert ON archive");
1784 }
1785 if ($wgDatabase->ruleExists("archive", "archive_delete")) {
1786 wfOut( "Dropping rule \"archive_delete\"\n" );
1787 $wgDatabase->query("DROP RULE archive_delete ON archive");
1788 }
1789 $wgDatabase->sourceFile(archive("patch-remove-archive2.sql"));
1790 }
1791 else
1792 wfOut( "... obsolete table \"archive2\" does not exist\n" );
1793
1794 foreach ($newcols as $nc) {
1795 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1796 if (!is_null($fi)) {
1797 wfOut( "... column \"$nc[0].$nc[1]\" already exists\n" );
1798 continue;
1799 }
1800
1801 wfOut( "Adding column \"$nc[0].$nc[1]\"\n" );
1802 $wgDatabase->query("ALTER TABLE $nc[0] ADD $nc[1] $nc[2]");
1803 }
1804
1805 foreach ($typechanges as $tc) {
1806 $fi = $wgDatabase->fieldInfo($tc[0], $tc[1]);
1807 if (is_null($fi)) {
1808 wfOut( "... error: expected column $tc[0].$tc[1] to exist\n" );
1809 exit(1);
1810 }
1811
1812 if ($fi->type() === $tc[2])
1813 wfOut( "... column \"$tc[0].$tc[1]\" is already of type \"$tc[2]\"\n" );
1814 else {
1815 wfOut( "Changing column type of \"$tc[0].$tc[1]\" from \"{$fi->type()}\" to \"$tc[2]\"\n" );
1816 $sql = "ALTER TABLE $tc[0] ALTER $tc[1] TYPE $tc[2]";
1817 if (strlen($tc[3])) {
1818 $default = array();
1819 if (preg_match( '/DEFAULT (.+)/', $tc[3], $default)) {
1820 $sqldef = "ALTER TABLE $tc[0] ALTER $tc[1] SET DEFAULT $default[1]";
1821 $wgDatabase->query($sqldef);
1822 $tc[3] = preg_replace( '/\s*DEFAULT .+/', '', $tc[3]);
1823 }
1824 $sql .= " USING $tc[3]";
1825 }
1826 $sql .= ";\nCOMMIT;\n";
1827 $wgDatabase->query($sql);
1828 }
1829 }
1830
1831 foreach ($nullchanges as $nc) {
1832 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1833 if (is_null($fi)) {
1834 wfOut( "... error: expected column $nc[0].$nc[1] to exist\n" );
1835 exit(1);
1836 }
1837 if ($fi->nullable()) {
1838 ## It's NULL - does it need to be NOT NULL?
1839 if ('NOT NULL' === $nc[2]) {
1840 wfOut( "Changing \"$nc[0].$nc[1]\" to not allow NULLs\n" );
1841 $wgDatabase->query( "ALTER TABLE $nc[0] ALTER $nc[1] SET NOT NULL" );
1842 }
1843 else {
1844 wfOut( "... column \"$nc[0].$nc[1]\" is already set as NULL\n" );
1845 }
1846 }
1847 else {
1848 ## It's NOT NULL - does it need to be NULL?
1849 if ('NULL' === $nc[2]) {
1850 wfOut( "Changing \"$nc[0].$nc[1]\" to allow NULLs\n" );
1851 $wgDatabase->query( "ALTER TABLE $nc[0] ALTER $nc[1] DROP NOT NULL" );
1852 }
1853 else {
1854 wfOut( "... column \"$nc[0].$nc[1]\" is already set as NOT NULL\n" );
1855 }
1856 }
1857 }
1858
1859 if ($wgDatabase->fieldInfo('oldimage','oi_deleted')->type() !== 'smallint') {
1860 wfOut( "Changing \"oldimage.oi_deleted\" to type \"smallint\"\n" );
1861 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted DROP DEFAULT" );
1862 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted TYPE SMALLINT USING (oi_deleted::smallint)" );
1863 $wgDatabase->query( "ALTER TABLE oldimage ALTER oi_deleted SET DEFAULT 0" );
1864 }
1865 else
1866 wfOut( "... column \"oldimage.oi_deleted\" is already of type \"smallint\"\n" );
1867
1868
1869 foreach ($newindexes as $ni) {
1870 if (pg_index_exists($ni[0], $ni[1])) {
1871 wfOut( "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n" );
1872 continue;
1873 }
1874 wfOut( "Creating index \"$ni[1]\" on table \"$ni[0]\" $ni[2]\n" );
1875 $wgDatabase->query( "CREATE INDEX $ni[1] ON $ni[0] $ni[2]" );
1876 }
1877
1878 foreach ($newrules as $nr) {
1879 if ($wgDatabase->ruleExists($nr[0], $nr[1])) {
1880 wfOut( "... rule \"$nr[1]\" on table \"$nr[0]\" already exists\n" );
1881 continue;
1882 }
1883 wfOut( "Adding rule \"$nr[1]\" to table \"$nr[0]\"\n" );
1884 $wgDatabase->sourceFile(archive($nr[2]));
1885 }
1886
1887 if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey_cascaded")) {
1888 wfOut( "... table \"oldimage\" has correct cascading delete/update foreign key to image\n" );
1889 }
1890 else {
1891 if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey")) {
1892 $wgDatabase->query( "ALTER TABLE oldimage DROP CONSTRAINT oldimage_oi_name_fkey" );
1893 }
1894 if ($wgDatabase->hasConstraint("oldimage_oi_name_fkey_cascade")) {
1895 $wgDatabase->query( "ALTER TABLE oldimage DROP CONSTRAINT oldimage_oi_name_fkey_cascade" );
1896 }
1897 wfOut( "Making foreign key on table \"oldimage\" (to image) a cascade delete/update\n" );
1898 $wgDatabase->query( "ALTER TABLE oldimage ADD CONSTRAINT oldimage_oi_name_fkey_cascaded ".
1899 "FOREIGN KEY (oi_name) REFERENCES image(img_name) ON DELETE CASCADE ON UPDATE CASCADE" );
1900 }
1901
1902 if (!$wgDatabase->triggerExists("page", "page_deleted")) {
1903 wfOut( "Adding function and trigger \"page_deleted\" to table \"page\"\n" );
1904 $wgDatabase->sourceFile(archive('patch-page_deleted.sql'));
1905 }
1906 else
1907 wfOut( "... table \"page\" has \"page_deleted\" trigger\n" );
1908
1909 $fi = $wgDatabase->fieldInfo("recentchanges", "rc_cur_id");
1910 if (!$fi->nullable()) {
1911 wfOut( "Removing NOT NULL constraint from \"recentchanges.rc_cur_id\"\n" );
1912 $wgDatabase->sourceFile(archive('patch-rc_cur_id-not-null.sql'));
1913 }
1914 else
1915 wfOut( "... column \"recentchanges.rc_cur_id\" has a NOT NULL constraint\n" );
1916
1917 $pu = pg_describe_index("pagelink_unique");
1918 if (!is_null($pu) && ($pu[0] != "pl_from" || $pu[1] != "pl_namespace" || $pu[2] != "pl_title")) {
1919 wfOut( "Dropping obsolete version of index \"pagelink_unique index\"\n" );
1920 $wgDatabase->query("DROP INDEX pagelink_unique");
1921 $pu = null;
1922 }
1923 else
1924 wfOut( "... obsolete version of index \"pagelink_unique index\" does not exist\n" );
1925
1926 if (is_null($pu)) {
1927 wfOut( "Creating index \"pagelink_unique index\"\n" );
1928 $wgDatabase->query("CREATE UNIQUE INDEX pagelink_unique ON pagelinks (pl_from,pl_namespace,pl_title)");
1929 }
1930 else
1931 wfOut( "... index \"pagelink_unique_index\" already exists\n" );
1932
1933 if (pg_fkey_deltype("revision_rev_user_fkey") == 'r') {
1934 wfOut( "... constraint \"revision_rev_user_fkey\" is ON DELETE RESTRICT\n" );
1935 }
1936 else {
1937 wfOut( "Changing constraint \"revision_rev_user_fkey\" to ON DELETE RESTRICT\n" );
1938 $wgDatabase->sourceFile(archive('patch-revision_rev_user_fkey.sql'));
1939 }
1940
1941 # Fix ipb_address index
1942 if (pg_index_exists('ipblocks', 'ipb_address' )) {
1943 wfOut( "Removing deprecated index 'ipb_address'...\n" );
1944 $wgDatabase->query('DROP INDEX ipb_address');
1945 }
1946 if (pg_index_exists('ipblocks', 'ipb_address_unique' )) {
1947 wfOut( "... have ipb_address_unique\n" );
1948 }
1949 else {
1950 wfOut( "Adding ipb_address_unique index\n" );
1951 $wgDatabase->sourceFile(archive('patch-ipb_address_unique.sql'));
1952 }
1953
1954 global $wgExtNewTables, $wgExtPGNewFields, $wgExtPGAlteredFields, $wgExtNewIndexes;
1955 # Add missing extension tables
1956 foreach ( $wgExtNewTables as $nt ) {
1957 if ($wgDatabase->tableExists($nt[0])) {
1958 wfOut( "... table \"$nt[0]\" already exists\n" );
1959 continue;
1960 }
1961 wfOut( "Creating table \"$nt[0]\"\n" );
1962 $wgDatabase->sourceFile($nt[1]);
1963 }
1964 # Add missing extension fields
1965 foreach ( $wgExtPGNewFields as $nc ) {
1966 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1967 if (!is_null($fi)) {
1968 wfOut( "... column \"$nc[0].$nc[1]\" already exists\n" );
1969 continue;
1970 }
1971 wfOut( "Adding column \"$nc[0].$nc[1]\"\n" );
1972 $wgDatabase->query( "ALTER TABLE $nc[0] ADD $nc[1] $nc[2]" );
1973 }
1974 # Change altered columns
1975 foreach ( $wgExtPGAlteredFields as $nc ) {
1976 $fi = $wgDatabase->fieldInfo($nc[0], $nc[1]);
1977 if (is_null($fi)) {
1978 wfOut( "WARNING! Column \"$nc[0].$nc[1]\" does not exist but had an alter request! Please report this.\n" );
1979 continue;
1980 }
1981 $oldtype = $fi->type();
1982 $newtype = strtolower( $nc[2] );
1983 if ($oldtype === $newtype) {
1984 wfOut( "... column \"$nc[0].$nc[1]\" has correct type of \"$newtype\"\n" );
1985 continue;
1986 }
1987 $command = "ALTER TABLE $nc[0] ALTER $nc[1] TYPE $nc[2]";
1988 if ( isset( $nc[3] ) ) {
1989 $command .= " USING $nc[3]";
1990 }
1991 wfOut( "Altering column \"$nc[0].$nc[1]\" from type \"$oldtype\" to \"$newtype\"\n" );
1992 $wgDatabase->query( $command );
1993 }
1994 # Add missing extension indexes
1995 foreach ( $wgExtNewIndexes as $ni ) {
1996 if (pg_index_exists($ni[0], $ni[1])) {
1997 wfOut( "... index \"$ni[1]\" on table \"$ni[0]\" already exists\n" );
1998 continue;
1999 }
2000 wfOut( "Creating index \"$ni[1]\" on table \"$ni[0]\"\n" );
2001 if ( preg_match( '/^\(/', $ni[2] ) ) {
2002 $wgDatabase->query( "CREATE INDEX $ni[1] ON $ni[0] $ni[2]" );
2003 }
2004 else {
2005 $wgDatabase->sourceFile($ni[2]);
2006 }
2007 }
2008
2009 foreach ( $deferredcols AS $dc ) {
2010 $fi = $wgDatabase->fieldInfo($dc[0], $dc[1]);
2011 if (is_null($fi)) {
2012 wfOut( "WARNING! Column \"$dc[0].$dc[1]\" does not exist but it should! Please report this.\n" );
2013 continue;
2014 }
2015 if ( $fi->is_deferred() && $fi->is_deferrable() ) {
2016 continue;
2017 }
2018 wfOut( "Altering column \"$dc[0].$dc[1]\" to be DEFERRABLE INITTALLY DEFERRED\n" );
2019 $conname = $fi->conname();
2020 $clause = $dc[2];
2021 $command = "ALTER TABLE $dc[0] DROP CONSTRAINT $conname";
2022 $wgDatabase->query( $command );
2023 $command = "ALTER TABLE $dc[0] ADD CONSTRAINT $conname FOREIGN KEY ($dc[1]) REFERENCES $clause DEFERRABLE INITIALLY DEFERRED";
2024 $wgDatabase->query( $command );
2025 }
2026
2027 # Tweak the page_title tsearch2 trigger to filter out slashes
2028 # This is create or replace, so harmless to call if not needed
2029 $wgDatabase->sourceFile(archive('patch-ts2pagetitle.sql'));
2030
2031 ## If the server is 8.3 or higher, rewrite the tsearch2 triggers
2032 ## in case they have the old 'default' versions
2033 if ( $numver >= 8.3 )
2034 $wgDatabase->sourceFile(archive('patch-tsearch2funcs.sql'));
2035
2036 ## Put a new row in the mediawiki_version table
2037 $wgDatabase->insert( 'mediawiki_version',
2038 array(
2039 'type' => 'Update',
2040 'ctype' => 'U',
2041 'mw_version' => $wgVersion,
2042 'pg_version' => $version,
2043 'sql_version' => '$LastChangedRevision$',
2044 'sql_date' => '$LastChangedDate$',
2045 ) );
2046 return;
2047 }