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