summaryrefslogtreecommitdiff
path: root/extensions/Renameuser/Renameuser_body.php
blob: 1e72aeaa885c1a85e00ecdd0495cca9e0222bf5a (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
<?php
if ( !defined( 'MEDIAWIKI' ) ) {
	echo "RenameUser extension\n";
	exit( 1 );
}

/**
 * Special page allows authorised users to rename
 * user accounts
 */
class SpecialRenameuser extends SpecialPage {
	/**
	 * Constructor
	 */
	public function __construct() {
		parent::__construct( 'Renameuser', 'renameuser' );
	}

	/**
	 * Show the special page
	 *
	 * @param mixed $par Parameter passed to the page
	 */
	public function execute( $par ) {
		global $wgOut, $wgUser, $wgRequest, $wgContLang, $wgLang;
		global $wgCapitalLinks;

		$this->setHeaders();
		$wgOut->addWikiMsg( 'renameuser-summary' );

		if ( !$wgUser->isAllowed( 'renameuser' ) ) {
			$wgOut->permissionRequired( 'renameuser' );
			return;
		}
		
		if ( wfReadOnly() ) {
			$wgOut->readOnlyPage();
			return;
		}

		if( $wgUser->isBlocked() ){
			$wgOut->blockedPage();
		}

		$showBlockLog = $wgRequest->getBool( 'submit-showBlockLog' );
		$oldnamePar = trim( str_replace( '_', ' ', $wgRequest->getText( 'oldusername', $par ) ) );
		$oldusername = Title::makeTitle( NS_USER, $oldnamePar );
		// Force uppercase of newusername, otherwise wikis with wgCapitalLinks=false can create lc usernames
		$newusername = Title::makeTitleSafe( NS_USER, $wgContLang->ucfirst( $wgRequest->getText( 'newusername' ) ) );
		$oun = is_object( $oldusername ) ? $oldusername->getText() : '';
		$nun = is_object( $newusername ) ? $newusername->getText() : '';
		$token = $wgUser->editToken();
		$reason = $wgRequest->getText( 'reason' );

		$move_checked = $wgRequest->getBool( 'movepages', !$wgRequest->wasPosted());
		$suppress_checked = $wgRequest->getCheck( 'suppressredirect' );

		$warnings = array();
		if ( $oun && $nun && !$wgRequest->getCheck( 'confirmaction' )  ) {
			wfRunHooks( 'RenameUserWarning', array( $oun, $nun, &$warnings ) );
		}

		$wgOut->addHTML(
			Xml::openElement( 'form', array( 'method' => 'post', 'action' => $this->getTitle()->getLocalUrl(), 'id' => 'renameuser' ) ) .
			Xml::openElement( 'fieldset' ) .
			Xml::element( 'legend', null, wfMsg( 'renameuser' ) ) .
			Xml::openElement( 'table', array( 'id' => 'mw-renameuser-table' ) ) .
			"<tr>
				<td class='mw-label'>" .
					Xml::label( wfMsg( 'renameuserold' ), 'oldusername' ) .
				"</td>
				<td class='mw-input'>" .
					Xml::input( 'oldusername', 20, $oun, array( 'type' => 'text', 'tabindex' => '1' ) ) . ' ' .
				"</td>
			</tr>
			<tr>
				<td class='mw-label'>" .
					Xml::label( wfMsg( 'renameusernew' ), 'newusername' ) .
				"</td>
				<td class='mw-input'>" .
					Xml::input( 'newusername', 20, $nun, array( 'type' => 'text', 'tabindex' => '2' ) ) .
				"</td>
			</tr>
			<tr>
				<td class='mw-label'>" .
					Xml::label( wfMsg( 'renameuserreason' ), 'reason' ) .
				"</td>
				<td class='mw-input'>" .
					Xml::input( 'reason', 40, $reason, array( 'type' => 'text', 'tabindex' => '3', 'maxlength' => 255 ) ) .
				"</td>
			</tr>"
		);
		if ( $wgUser->isAllowed( 'move' ) ) {
			$wgOut->addHTML( "
				<tr>
					<td>&#160;
					</td>
					<td class='mw-input'>" .
						Xml::checkLabel( wfMsg( 'renameusermove' ), 'movepages', 'movepages',
							$move_checked, array( 'tabindex' => '4' ) ) .
					"</td>
				</tr>"
			);
			
			if ( $wgUser->isAllowed( 'suppressredirect' ) ) {
				$wgOut->addHTML( "
					<tr>
						<td>&#160;
						</td>
						<td class='mw-input'>" .
							Xml::checkLabel( wfMsg( 'renameusersuppress' ), 'suppressredirect', 'suppressredirect',
								$suppress_checked, array( 'tabindex' => '5' ) ) .
						"</td>
					</tr>"
				);
			}
		}
		if ( $warnings ) {
			$warningsHtml = array();
			foreach ( $warnings as $warning )
				$warningsHtml[] = is_array( $warning ) ?
					call_user_func_array( 'wfMsgWikiHtml', $warning ) :
					wfMsgHtml( $warning );
			$wgOut->addHTML( "
				<tr>
					<td class='mw-label'>" . wfMsgWikiHtml( 'renameuserwarnings' ) . "
					</td>
					<td class='mw-input'>" .
						'<ul style="color: red; font-weight: bold"><li>' .
							implode( '</li><li>', $warningsHtml ) . '</li></ul>' .
					"</td>
				</tr>"
			);
			$wgOut->addHTML( "
				<tr>
					<td>&#160;
					</td>
					<td class='mw-input'>" .
						Xml::checkLabel( wfMsg( 'renameuserconfirm' ), 'confirmaction', 'confirmaction',
							false, array( 'tabindex' => '6' ) ) .
					"</td>
				</tr>"
			);
		}
		$wgOut->addHTML( "
			<tr>
				<td>&#160;
				</td>
				<td class='mw-submit'>" .
					Xml::submitButton( wfMsg( 'renameusersubmit' ), array( 'name' => 'submit',
						'tabindex' => '7', 'id' => 'submit' ) ) .
					' ' .
					Xml::submitButton( wfMsg( 'blocklogpage' ), array ( 'name' => 'submit-showBlockLog',
						'id' => 'submit-showBlockLog', 'tabindex' => '8' ) ) .
				"</td>
			</tr>" .
			Xml::closeElement( 'table' ) .
			Xml::closeElement( 'fieldset' ) .
			Html::hidden( 'token', $token ) .
			Xml::closeElement( 'form' ) . "\n"
		);

		// Show block log if requested
		if ( $showBlockLog && is_object( $oldusername ) ) {
			$this->showLogExtract( $oldusername, 'block', $wgOut ) ;
			return;
		}

		if ( $wgRequest->getText( 'token' ) === '' ) {
			# They probably haven't even submitted the form, so don't go further.
			return;
		} elseif ( $warnings ) {
			# Let user read warnings
			return;
		} elseif ( !$wgRequest->wasPosted() || !$wgUser->matchEditToken( $wgRequest->getVal( 'token' ) ) ) {
			$wgOut->wrapWikiMsg( "<div class=\"errorbox\">$1</div>", 'renameuser-error-request' );
			return;
		} elseif ( !is_object( $oldusername ) ) {
			$wgOut->wrapWikiMsg( "<div class=\"errorbox\">$1</div>",
				array( 'renameusererrorinvalid', $wgRequest->getText( 'oldusername' ) ) );
			return;
		} elseif ( !is_object( $newusername ) ) {
			$wgOut->wrapWikiMsg( "<div class=\"errorbox\">$1</div>",
				array( 'renameusererrorinvalid', $wgRequest->getText( 'newusername' ) ) );
			return;
		} elseif ( $oldusername->getText() == $newusername->getText() ) {
			$wgOut->wrapWikiMsg( "<div class=\"errorbox\">$1</div>", 'renameuser-error-same-user' );
			return;
		}

		// Suppress username validation of old username
		$olduser = User::newFromName( $oldusername->getText(), false );
		$newuser = User::newFromName( $newusername->getText(), 'creatable' );

		// It won't be an object if for instance "|" is supplied as a value
		if ( !is_object( $olduser ) ) {
			$wgOut->wrapWikiMsg( "<div class=\"errorbox\">$1</div>",
				array( 'renameusererrorinvalid', $oldusername->getText() ) );
			return;
		}
		if ( !is_object( $newuser ) || !User::isCreatableName( $newuser->getName() ) ) {
			$wgOut->wrapWikiMsg( "<div class=\"errorbox\">$1</div>",
				array( 'renameusererrorinvalid', $newusername->getText() ) );
			return;
		}

		// Check for the existence of lowercase oldusername in database.
		// Until r19631 it was possible to rename a user to a name with first character as lowercase
		if ( $oldusername->getText() !== $wgContLang->ucfirst( $oldusername->getText() ) ) {
			// oldusername was entered as lowercase -> check for existence in table 'user'
			$dbr = wfGetDB( DB_SLAVE );
			$uid = $dbr->selectField( 'user', 'user_id',
				array( 'user_name' => $oldusername->getText() ),
				__METHOD__ );
			if ( $uid === false ) {
				if ( !$wgCapitalLinks ) {
					$uid = 0; // We are on a lowercase wiki but lowercase username does not exists
				} else {
					// We are on a standard uppercase wiki, use normal
					$uid = $olduser->idForName();
					$oldusername = Title::makeTitleSafe( NS_USER, $olduser->getName() );
				}
			}
		} else {
			// oldusername was entered as upperase -> standard procedure
			$uid = $olduser->idForName();
		}

		if ( $uid == 0 ) {
			$wgOut->wrapWikiMsg( "<div class=\"errorbox\">$1</div>",
				array( 'renameusererrordoesnotexist', $oldusername->getText() ) );
			return;
		}

		if ( $newuser->idForName() != 0 ) {
			$wgOut->wrapWikiMsg( "<div class=\"errorbox\">$1</div>",
				array( 'renameusererrorexists', $newusername->getText() ) );
			return;
		}

		// Always get the edits count, it will be used for the log message
		$contribs = User::edits( $uid );

		// Give other affected extensions a chance to validate or abort
		if ( !wfRunHooks( 'RenameUserAbort', array( $uid, $oldusername->getText(), $newusername->getText() ) ) ) {
			return;
		}

		// Do the heavy lifting...
		$rename = new RenameuserSQL( $oldusername->getText(), $newusername->getText(), $uid );
		if ( !$rename->rename() ) {
			return;
		}

		// If this user is renaming his/herself, make sure that Title::moveTo()
		// doesn't make a bunch of null move edits under the old name!
		if ( $wgUser->getId() == $uid ) {
			$wgUser->setName( $newusername->getText() );
		}

		// Log this rename
		$log = new LogPage( 'renameuser' );
		$log->addEntry( 'renameuser', $oldusername, wfMsgExt( 'renameuser-log', array( 'parsemag', 'content' ),
			$wgContLang->formatNum( $contribs ), $reason ), $newusername->getText() );

		// Move any user pages
		if ( $wgRequest->getCheck( 'movepages' ) && $wgUser->isAllowed( 'move' ) ) {
			$dbr = wfGetDB( DB_SLAVE );

			$pages = $dbr->select(
				'page',
				array( 'page_namespace', 'page_title' ),
				array(
					'page_namespace IN (' . NS_USER . ',' . NS_USER_TALK . ')',
					'(page_title ' . $dbr->buildLike( $oldusername->getDBkey() . '/', $dbr->anyString() ) .
						' OR page_title = ' . $dbr->addQuotes( $oldusername->getDBkey() ) . ')'
				),
				__METHOD__
			);

			$suppressRedirect = false;

			if ( $wgRequest->getCheck( 'suppressredirect' ) && $wgUser->isAllowed( 'suppressredirect' ) ) {	
				$suppressRedirect = true;
			}

			$output = '';
			$skin = $wgUser->getSkin();
			foreach ( $pages as $row ) {
				$oldPage = Title::makeTitleSafe( $row->page_namespace, $row->page_title );
				$newPage = Title::makeTitleSafe( $row->page_namespace,
					preg_replace( '!^[^/]+!', $newusername->getDBkey(), $row->page_title ) );
				# Do not autodelete or anything, title must not exist
				if ( $newPage->exists() && !$oldPage->isValidMoveTarget( $newPage ) ) {
					$link = $skin->makeKnownLinkObj( $newPage );
					$output .= '<li class="mw-renameuser-pe">' . wfMsgHtml( 'renameuser-page-exists', $link ) . '</li>';
				} else {
					$success = $oldPage->moveTo( $newPage, false, wfMsgForContent( 'renameuser-move-log',
						$oldusername->getText(), $newusername->getText() ), !$suppressRedirect );
					if ( $success === true ) {
						$oldLink = $skin->makeKnownLinkObj( $oldPage, '', 'redirect=no' );
						$newLink = $skin->makeKnownLinkObj( $newPage );
						$output .= '<li class="mw-renameuser-pm">' . wfMsgHtml( 'renameuser-page-moved', $oldLink, $newLink ) . '</li>';
					} else {
						$oldLink = $skin->makeKnownLinkObj( $oldPage );
						$newLink = $skin->makeLinkObj( $newPage );
						$output .= '<li class="mw-renameuser-pu">' . wfMsgHtml( 'renameuser-page-unmoved', $oldLink, $newLink ) . '</li>';
					}
				}
			}
			if ( $output )
				$wgOut->addHTML( '<ul>' . $output . '</ul>' );
		}

		// Output success message stuff :)
		$wgOut->wrapWikiMsg( "<div class=\"successbox\">$1</div><br style=\"clear:both\" />",
			array( 'renameusersuccess', $oldusername->getText(), $newusername->getText() ) );
	}

	/**
	 * @param $username Title
	 * @param $type
	 * @param $out
	 * @return void
	 */
	function showLogExtract( $username, $type, &$out ) {
		# Show relevant lines from the logs:
		$out->addHTML( Xml::element( 'h2', null, LogPage::logName( $type ) ) . "\n" );
		LogEventsList::showLogExtract( $out, $type, $username->getPrefixedText() );
	}
}

class RenameuserSQL {
	/**
	  * The old username
	  *
	  * @var string
	  * @access private
	  */
	var $old;

	/**
	  * The new username
	  *
	  * @var string
	  * @access private
	  */
	var $new;

	/**
	  * The user ID
	  *
	  * @var integer
	  * @access private
	  */
	var $uid;

	/**
	  * The the tables => fields to be updated
	  *
	  * @var array
	  * @access private
	  */
	var $tables;

	/**
	 * Constructor
	 *
	 * @param string $old The old username
	 * @param string $new The new username
	 */
	function __construct( $old, $new, $uid ) {
		$this->old = $old;
		$this->new = $new;
		$this->uid = $uid;

		$this->tables = array(); // Immediate updates
		$this->tables['image'] = array( 'img_user_text', 'img_user' );
		$this->tables['oldimage'] = array( 'oi_user_text', 'oi_user' );
		$this->tables['filearchive'] = array('fa_user_text','fa_user');
		$this->tablesJob = array(); // Slow updates
		// If this user has a large number of edits, use the jobqueue
		if ( User::edits( $this->uid ) > RENAMEUSER_CONTRIBJOB ) {
			$this->tablesJob['revision'] = array( 'rev_user_text', 'rev_user', 'rev_timestamp' );
			$this->tablesJob['archive'] = array( 'ar_user_text', 'ar_user', 'ar_timestamp' );
			$this->tablesJob['logging'] = array( 'log_user_text', 'log_user', 'log_timestamp' );
		} else {
			$this->tables['revision'] = array( 'rev_user_text', 'rev_user' );
			$this->tables['archive'] = array( 'ar_user_text', 'ar_user' );
			$this->tables['logging'] = array( 'log_user_text', 'log_user' );
		}
		// Recent changes is pretty hot, deadlocks occur if done all at once
		if ( wfQueriesMustScale() ) {
			$this->tablesJob['recentchanges'] = array( 'rc_user_text', 'rc_user', 'rc_timestamp' );
		} else {
			$this->tables['recentchanges'] = array( 'rc_user_text', 'rc_user' );
		}

		wfRunHooks( 'RenameUserSQL', array( $this ) );
	}

	/**
	 * Do the rename operation
	 */
	function rename() {
		global $wgMemc, $wgAuth, $wgUpdateRowsPerJob;

		wfProfileIn( __METHOD__ );

		$dbw = wfGetDB( DB_MASTER );
		$dbw->begin();
		wfRunHooks( 'RenameUserPreRename', array( $this->uid, $this->old, $this->new ) );

		// Rename and touch the user before re-attributing edits,
		// this avoids users still being logged in and making new edits while
		// being renamed, which leaves edits at the old name.
		$dbw->update( 'user',
			array( 'user_name' => $this->new, 'user_touched' => $dbw->timestamp() ),
			array( 'user_name' => $this->old ),
			__METHOD__
		);
		if ( !$dbw->affectedRows() ) {
			return false;
		}
		// Reset token to break login with central auth systems.
		// Again, avoids user being logged in with old name.
		$user = User::newFromId( $this->uid );
		$authUser = $wgAuth->getUserInstance( $user );
		$authUser->resetAuthToken();

		// Delete from memcached.
		$wgMemc->delete( wfMemcKey( 'user', 'id', $this->uid ) );

		// Update ipblock list if this user has a block in there.
		$dbw->update( 'ipblocks',
			array( 'ipb_address' => $this->new ),
			array( 'ipb_user' => $this->uid, 'ipb_address' => $this->old ),
			__METHOD__ );
		// Update this users block/rights log. Ideally, the logs would be historical,
		// but it is really annoying when users have "clean" block logs by virtue of
		// being renamed, which makes admin tasks more of a pain...
		$oldTitle = Title::makeTitle( NS_USER, $this->old );
		$newTitle = Title::makeTitle( NS_USER, $this->new );
		$dbw->update( 'logging',
			array( 'log_title' => $newTitle->getDBkey() ),
			array( 'log_type' => array( 'block', 'rights' ),
				'log_namespace' => NS_USER,
				'log_title' => $oldTitle->getDBkey() ),
			__METHOD__ );
		// Do immediate updates!
		foreach ( $this->tables as $table => $fieldSet ) {
			list( $nameCol, $userCol ) = $fieldSet;
			$dbw->update( $table,
				array( $nameCol => $this->new ),
				array( $nameCol => $this->old, $userCol => $this->uid ),
				__METHOD__
			);
		}
		
		// Increase time limit (like CheckUser); this can take a while...
		if ( $this->tablesJob ) {
			wfSuppressWarnings();
			set_time_limit( 120 );
			wfRestoreWarnings();
		}
		
		$jobs = array(); // jobs for all tables
		// Construct jobqueue updates...
		// FIXME: if a bureaucrat renames a user in error, he/she
		// must be careful to wait until the rename finishes before
		// renaming back. This is due to the fact the the job "queue"
		// is not really FIFO, so we might end up with a bunch of edits
		// randomly mixed between the two new names. Some sort of rename
		// lock might be in order...
		foreach ( $this->tablesJob as $table => $params ) {
			$userTextC = $params[0]; // some *_user_text column
			$userIDC = $params[1]; // some *_user column
			$timestampC = $params[2]; // some *_timestamp column

			$res = $dbw->select( $table,
				array( $timestampC ),
				array( $userTextC => $this->old, $userIDC => $this->uid ),
				__METHOD__,
				array( 'ORDER BY' => "$timestampC ASC" )
			);

			$jobParams = array();
			$jobParams['table'] = $table;
			$jobParams['column'] = $userTextC;
			$jobParams['uidColumn'] = $userIDC;
			$jobParams['timestampColumn'] = $timestampC;
			$jobParams['oldname'] = $this->old;
			$jobParams['newname'] = $this->new;
			$jobParams['userID'] = $this->uid;
			// Timestamp column data for index optimizations
			$jobParams['minTimestamp'] = '0';
			$jobParams['maxTimestamp'] = '0';
			$jobParams['count'] = 0;

			// Insert jobs into queue!
			while ( true ) {
				$row = $dbw->fetchObject( $res );
				if ( !$row ) {
					# If there are any job rows left, add it to the queue as one job
					if ( $jobParams['count'] > 0 ) {
						$jobs[] = Job::factory( 'renameUser', $oldTitle, $jobParams );
					}
					break;
				}
				# Since the ORDER BY is ASC, set the min timestamp with first row
				if ( $jobParams['count'] == 0 ) {
					$jobParams['minTimestamp'] = $row->$timestampC;
				}
				# Keep updating the last timestamp, so it should be correct
				# when the last item is added.
				$jobParams['maxTimestamp'] = $row->$timestampC;
				# Update row counter
				$jobParams['count']++;
				# Once a job has $wgUpdateRowsPerJob rows, add it to the queue
				if ( $jobParams['count'] >= $wgUpdateRowsPerJob ) {
					$jobs[] = Job::factory( 'renameUser', $oldTitle, $jobParams );
					$jobParams['minTimestamp'] = '0';
					$jobParams['maxTimestamp'] = '0';
					$jobParams['count'] = 0;
				}
			}
			$dbw->freeResult( $res );
		}

		if ( count( $jobs ) > 0 ) {
			Job::safeBatchInsert( $jobs ); // don't commit yet
		}

		// Commit the transaction
		$dbw->commit();

		// Delete from memcached again to make sure
		$wgMemc->delete( wfMemcKey( 'user', 'id', $this->uid ) );

		// Clear caches and inform authentication plugins
		$user = User::newFromId( $this->uid );
		$wgAuth->updateExternalDB( $user );
		wfRunHooks( 'RenameUserComplete', array( $this->uid, $this->old, $this->new ) );

		wfProfileOut( __METHOD__ );
		return true;
	}
}