aboutsummaryrefslogtreecommitdiffstats
path: root/includes/RenameUser/RenameUser.php
blob: 4b022b0ad4b3fe833b510bf29bfee194290ea91d (plain) (blame)
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
<?php

namespace MediaWiki\RenameUser;

use LogicException;
use MediaWiki\Config\ServiceOptions;
use MediaWiki\Context\RequestContext;
use MediaWiki\JobQueue\JobQueueGroupFactory;
use MediaWiki\JobQueue\JobSpecification;
use MediaWiki\Logger\LoggerFactory;
use MediaWiki\MainConfigNames;
use MediaWiki\Page\MovePageFactory;
use MediaWiki\Permissions\PermissionManager;
use MediaWiki\Status\Status;
use MediaWiki\Title\Title;
use MediaWiki\Title\TitleFactory;
use MediaWiki\User\CentralId\CentralIdLookupFactory;
use MediaWiki\User\User;
use MediaWiki\User\UserFactory;
use MediaWiki\User\UserNameUtils;
use MediaWiki\WikiMap\WikiMap;
use Psr\Log\LoggerInterface;

/**
 * Handles the backend logic of renaming users.
 *
 * @since 1.44
 */
class RenameUser {

	/** @var User */
	private $performer;
	/** @var User */
	private $target;
	/** @var string */
	private $oldName;
	/** @var string */
	private $newName;
	/** @var string */
	private $reason;

	/** @var bool */
	private $forceGlobalDetach = false;
	/** @var bool */
	private $movePages = true;
	/** @var bool */
	private $suppressRedirect = false;
	/** @var bool */
	private $derived = false;

	private CentralIdLookupFactory $centralIdLookupFactory;
	private JobQueueGroupFactory $jobQueueGroupFactory;
	private MovePageFactory $movePageFactory;
	private UserFactory $userFactory;
	private UserNameUtils $userNameUtils;
	private PermissionManager $permissionManager;
	private TitleFactory $titleFactory;
	private LoggerInterface $logger;

	/**
	 * @internal For use by RenameUserFactory
	 */
	public const CONSTRUCTOR_OPTIONS = [
		MainConfigNames::LocalDatabases,
	];

	private array $localDatabases;

	/**
	 * @param ServiceOptions $options
	 * @param CentralIdLookupFactory $centralIdLookupFactory
	 * @param JobQueueGroupFactory $jobQueueGroupFactory
	 * @param MovePageFactory $movePageFactory
	 * @param UserFactory $userFactory
	 * @param UserNameUtils $userNameUtils
	 * @param PermissionManager $permissionManager
	 * @param TitleFactory $titleFactory
	 * @param User $performer
	 * @param User $target
	 * @param string $oldName
	 * @param string $newName
	 * @param string $reason
	 * @param array $renameOptions
	 *    Valid options:
	 *    - forceGlobalDetach      : Force to detach from CentralAuth
	 *    - movePages              : Whether user pages should be moved
	 *    - suppressRedirect       : Whether to suppress redirects for user pages
	 *    - derived                : Whether shared tables should be updated
	 *        If derived is true, it is assumed that all shared tables have been updated.
	 */
	public function __construct(
		ServiceOptions $options,
		CentralIdLookupFactory $centralIdLookupFactory,
		JobQueueGroupFactory $jobQueueGroupFactory,
		MovePageFactory $movePageFactory,
		UserFactory $userFactory,
		UserNameUtils $userNameUtils,
		PermissionManager $permissionManager,
		TitleFactory $titleFactory,
		User $performer,
		User $target,
		string $oldName,
		string $newName,
		string $reason,
		array $renameOptions
	) {
		$options->assertRequiredOptions( self::CONSTRUCTOR_OPTIONS );
		$this->localDatabases = $options->get( MainConfigNames::LocalDatabases );

		$this->centralIdLookupFactory = $centralIdLookupFactory;
		$this->movePageFactory = $movePageFactory;
		$this->jobQueueGroupFactory = $jobQueueGroupFactory;
		$this->userFactory = $userFactory;
		$this->userNameUtils = $userNameUtils;
		$this->permissionManager = $permissionManager;
		$this->titleFactory = $titleFactory;
		$this->logger = LoggerFactory::getInstance( 'RenameUser' );

		foreach ( [
			'forceGlobalDetach',
			'movePages',
			'suppressRedirect',
			'derived',
		] as $possibleOption ) {
			if ( isset( $renameOptions[ $possibleOption ] ) ) {
				$this->$possibleOption = $renameOptions[ $possibleOption ];
			}
		}

		$this->performer = $performer;
		$this->target = $target;
		$this->oldName = $oldName;
		$this->newName = $newName;
		$this->reason = $reason;
	}

	/**
	 * Checks if the rename operation is valid.
	 * @note This method doesn't check user permissions. Use 'rename' for that.
	 * @return Status Validation result.
	 *   If status is Ok with no errors, the rename can be performed.
	 *   If status is Ok with some errors,
	 */
	private function check(): Status {
		// Check if the user has a proper name
		// The wiki triggering a global rename across a wiki family using virtual domains
		// may not have the same user database as this wiki
		$expectedName = $this->oldName;
		if ( $this->derived && $this->userFactory->isUserTableShared() ) {
			$expectedName = $this->newName;
		}
		if ( $this->target->getName() !== $expectedName ) {
			return Status::newFatal( 'renameuser-error-unexpected-name' );
		}

		// Check user names valid
		$newRigor = $this->derived ? UserFactory::RIGOR_NONE : UserFactory::RIGOR_CREATABLE;
		$oldUser = $this->userFactory->newFromName( $this->oldName, UserFactory::RIGOR_NONE );
		$newUser = $this->userFactory->newFromName( $this->newName, $newRigor );
		if ( !$oldUser ) {
			return Status::newFatal( 'renameusererrorinvalid', $this->oldName );
		}
		if ( !$newUser ) {
			return Status::newFatal( 'renameusererrorinvalid', $this->newName );
		}
		$currentUser = $this->derived ? $newUser : $oldUser;
		if ( !$currentUser->isRegistered() ) {
			return Status::newFatal( 'renameusererrordoesnotexist', $currentUser->getName() );
		}
		if ( !$this->derived && $newUser->isRegistered() ) {
			return Status::newFatal( 'renameusererrorexists', $this->newName );
		}

		// Do not act on temp users
		if ( $this->userNameUtils->isTemp( $this->oldName ) ) {
			return Status::newFatal( 'renameuser-error-temp-user', $this->oldName );
		}
		if (
			$this->userNameUtils->isTemp( $this->newName ) ||
			$this->userNameUtils->isTempReserved( $this->newName )
		) {
			return Status::newFatal( 'renameuser-error-temp-user-reserved', $this->newName );
		}

		// Check global detaching
		$centralIdLookup = $this->centralIdLookupFactory->getNonLocalLookup();
		$userCentralAttached = $centralIdLookup && $centralIdLookup->isAttached( $this->target );
		if ( !$this->forceGlobalDetach && $userCentralAttached ) {
			return Status::newFatal( 'renameuser-error-global-detaching' );
		}

		return Status::newGood();
	}

	/**
	 * Performs the rename in local domain.
	 * @return Status
	 */
	public function renameLocal(): Status {
		$status = $this->check();
		if ( !$status->isOK() ) {
			return $status;
		}

		$user = $this->target;
		$performer = $this->performer;
		$oldName = $this->oldName;
		$newName = $this->newName;

		$options = [
			'reason' => $this->reason,
			'derived' => $this->derived,
		];

		// Do the heavy lifting ...
		$rename = new RenameuserSQL(
			$oldName,
			$newName,
			$user->getId(),
			$performer,
			$options
		);
		$status->merge( $rename->renameUser() );
		if ( !$status->isOK() ) {
			return $status;
		}

		// If the user is renaming themself, make sure that code below uses a proper name
		if ( $performer->getId() === $user->getId() ) {
			$performer->setName( $newName );
			$this->performer->setName( $newName );
		}

		// Move any user pages
		$status->merge( $this->moveUserPages() );

		return $status;
	}

	/**
	 * Attempts to move local user pages.
	 * @return Status
	 */
	public function moveUserPages(): Status {
		if ( $this->movePages && $this->permissionManager->userHasRight( $this->performer, 'move' ) ) {
			$suppressRedirect = $this->suppressRedirect
				&& $this->permissionManager->userHasRight( $this->performer, 'suppressredirect' );
			$oldTitle = $this->titleFactory->makeTitle( NS_USER, $this->oldName );
			$newTitle = $this->titleFactory->makeTitle( NS_USER, $this->newName );

			$status = $this->movePagesAndSubPages( $this->performer, $oldTitle, $newTitle, $suppressRedirect );
			if ( !$status->isOK() ) {
				return $status;
			}

			$oldTalkTitle = $oldTitle->getTalkPageIfDefined();
			$newTalkTitle = $newTitle->getTalkPageIfDefined();
			if ( $oldTalkTitle && $newTalkTitle ) {
				$status = $this->movePagesAndSubPages(
					$this->performer,
					$oldTalkTitle,
					$newTalkTitle,
					$suppressRedirect
				);
				if ( !$status->isOK() ) {
					return $status;
				}
			}
		}
		return Status::newGood();
	}

	private function movePagesAndSubPages( User $performer, Title $oldTitle, Title $newTitle, bool $suppressRedirect ) {
		$status = Status::newGood();

		$movePage = $this->movePageFactory->newMovePage(
			$oldTitle,
			$newTitle,
		);
		$movePage->setMaximumMovedPages( -1 );
		$logMessage = RequestContext::getMain()->msg(
			'renameuser-move-log',
			$oldTitle->getText(),
			$newTitle->getText()
		)->inContentLanguage()->text();

		if ( $oldTitle->exists() ) {
			$status->merge( $movePage->moveIfAllowed( $performer, $logMessage, !$suppressRedirect ) );
			if ( !$status->isGood() ) {
				return $status;
			}
		}

		$batchStatus = $movePage->moveSubpagesIfAllowed( $performer, $logMessage, !$suppressRedirect );
		foreach ( $batchStatus->getValue() as $titleText => $moveStatus ) {
			$status->merge( $moveStatus );
		}
		return $status;
	}

	/**
	 * Attempts to perform the rename globally.
	 * @note This method doesn't check user permissions. Use 'rename' for that.
	 *
	 * This will first call renameLocal to complete local renaming,
	 * then enqueue RenameUserDerivedJob for all other wikis in the same
	 * wiki family.
	 *
	 * @return Status
	 */
	public function renameGlobal(): Status {
		if ( $this->derived ) {
			throw new LogicException( "Can't rename globally with a command created with newDerivedRenameUser()" );
		}
		$status = $this->renameLocal();
		if ( !$status->isGood() ) {
			return $status;
		}

		// Create jobs for other wikis if needed
		if ( $this->userFactory->isUserTableShared() ) {
			foreach ( $this->localDatabases as $database ) {
				if ( $database == WikiMap::getCurrentWikiDbDomain()->getId() ) {
					continue;
				}
				$status->merge( $this->enqueueRemoteRename( $database ) );
			}
		}

		return $status;
	}

	/**
	 * Enqueues a job to perform local rename on another wiki.
	 *
	 * Checks will not be performed during enqueuing operation.
	 *
	 * @param string $database
	 * @return Status
	 */
	private function enqueueRemoteRename( string $database ): Status {
		$jobParams = [
			'oldname' => $this->oldName,
			'newname' => $this->newName,
			'uid' => $this->target->getId(),
			'performer' => $this->performer->getId(),
			'reason' => $this->reason,
			'movePages' => $this->movePages,
			'suppressRedirect' => $this->suppressRedirect,
		];
		$oldTitle = $this->titleFactory->makeTitle( NS_USER, $this->oldName );
		$this->logger->info( "Enqueuing a rename job for domain {$database}" );
		$job = new JobSpecification( 'renameUserDerived', $jobParams, [], $oldTitle );
		$this->jobQueueGroupFactory->makeJobQueueGroup( $database )->push( $job );
		return Status::newGood();
	}

	/**
	 * Attempts to perform the rename smartly.
	 * @note This method doesn't check user permissions. Use 'rename' for that.
	 *
	 * This decides whether renameGlobal or renameLocal should be used and call the proper
	 * function.
	 *
	 * @return Status
	 */
	public function renameUnsafe(): Status {
		if ( !$this->derived && $this->userFactory->isUserTableShared() ) {
			return $this->renameGlobal();
		} else {
			return $this->renameLocal();
		}
	}

	/**
	 * Attempts to perform the rename smartly after checking the performer's rights.
	 *
	 * This decides whether renameGlobal or renameLocal should be used and call the proper
	 * function.
	 *
	 * @return Status
	 */
	public function rename(): Status {
		// renameuser is always required
		if ( !$this->permissionManager->userHasRight( $this->performer, 'renameuser' ) ) {
			return Status::newFatal( 'badaccess-groups', 'renameuser' );
		}

		// for global renames, renameuser-global is also required
		$centralIdLookup = $this->centralIdLookupFactory->getNonLocalLookup();
		$userCentralAttached = $centralIdLookup && $centralIdLookup->isAttached( $this->target );
		if ( ( $this->userFactory->isUserTableShared() || $userCentralAttached )
			&& !$this->permissionManager->userHasRight( $this->performer, 'renameuser-global' ) ) {
			return Status::newFatal( 'badaccess-groups', 'renameuser-global' );
		}

		return $this->renameUnsafe();
	}
}