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