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