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