MediaWiki  1.29.1
RenameuserSQL.php
Go to the documentation of this file.
1 <?php
2 
5 
9 class RenameuserSQL {
16  public $old;
17 
24  public $new;
25 
32  public $uid;
33 
40  public $tables;
41 
50 
56  private $renamer;
57 
63  private $reason = '';
64 
70  private $debugPrefix = '';
71 
76  const CONTRIB_JOB = 500;
77 
78  // B/C constants for tablesJob field
79  const NAME_COL = 0;
80  const UID_COL = 1;
81  const TIME_COL = 2;
82 
95  public function __construct( $old, $new, $uid, User $renamer, $options = [] ) {
96  $this->old = $old;
97  $this->new = $new;
98  $this->uid = $uid;
99  $this->renamer = $renamer;
100  $this->checkIfUserExists = true;
101 
102  if ( isset ( $options['checkIfUserExists'] ) ) {
103  $this->checkIfUserExists = $options['checkIfUserExists'];
104  }
105 
106  if ( isset( $options['debugPrefix'] ) ) {
107  $this->debugPrefix = $options['debugPrefix'];
108  }
109 
110  if ( isset( $options['reason'] ) ) {
111  $this->reason = $options['reason'];
112  }
113 
114  $this->tables = []; // Immediate updates
115  $this->tables['image'] = [ 'img_user_text', 'img_user' ];
116  $this->tables['oldimage'] = [ 'oi_user_text', 'oi_user' ];
117  $this->tables['filearchive'] = [ 'fa_user_text', 'fa_user' ];
118  $this->tablesJob = []; // Slow updates
119  // If this user has a large number of edits, use the jobqueue
120  // T134136: if this is for user_id=0, then use the queue as the edit count is unknown.
121  if ( !$uid || User::newFromId( $uid )->getEditCount() > self::CONTRIB_JOB ) {
122  $this->tablesJob['revision'] = [
123  self::NAME_COL => 'rev_user_text',
124  self::UID_COL => 'rev_user',
125  self::TIME_COL => 'rev_timestamp',
126  'uniqueKey' => 'rev_id'
127  ];
128  $this->tablesJob['archive'] = [
129  self::NAME_COL => 'ar_user_text',
130  self::UID_COL => 'ar_user',
131  self::TIME_COL => 'ar_timestamp',
132  'uniqueKey' => 'ar_id'
133  ];
134  $this->tablesJob['logging'] = [
135  self::NAME_COL => 'log_user_text',
136  self::UID_COL => 'log_user',
137  self::TIME_COL => 'log_timestamp',
138  'uniqueKey' => 'log_id'
139  ];
140  } else {
141  $this->tables['revision'] = [ 'rev_user_text', 'rev_user' ];
142  $this->tables['archive'] = [ 'ar_user_text', 'ar_user' ];
143  $this->tables['logging'] = [ 'log_user_text', 'log_user' ];
144  }
145  // Recent changes is pretty hot, deadlocks occur if done all at once
146  if ( wfQueriesMustScale() ) {
147  $this->tablesJob['recentchanges'] = [ 'rc_user_text', 'rc_user', 'rc_timestamp' ];
148  } else {
149  $this->tables['recentchanges'] = [ 'rc_user_text', 'rc_user' ];
150  }
151 
152  Hooks::run( 'RenameUserSQL', [ $this ] );
153  }
154 
155  protected function debug( $msg ) {
156  if ( $this->debugPrefix ) {
157  $msg = "{$this->debugPrefix}: $msg";
158  }
159  wfDebugLog( 'Renameuser', $msg );
160  }
161 
165  public function rename() {
166  global $wgAuth, $wgUpdateRowsPerJob;
167 
168  // Grab the user's edit count first, used in log entry
169  $contribs = User::newFromId( $this->uid )->getEditCount();
170 
171  $dbw = wfGetDB( DB_MASTER );
172  $dbw->startAtomic( __METHOD__ );
173 
174  Hooks::run( 'RenameUserPreRename', [ $this->uid, $this->old, $this->new ] );
175 
176  // Make sure the user exists if needed
177  if ( $this->checkIfUserExists && !self::lockUserAndGetId( $this->old ) ) {
178  $this->debug( "User {$this->old} does not exist, bailing out" );
179 
180  return false;
181  }
182 
183  // Rename and touch the user before re-attributing edits to avoid users still being
184  // logged in and making new edits (under the old name) while being renamed.
185  $this->debug( "Starting rename of {$this->old} to {$this->new}" );
186  $dbw->update( 'user',
187  [ 'user_name' => $this->new, 'user_touched' => $dbw->timestamp() ],
188  [ 'user_name' => $this->old, 'user_id' => $this->uid ],
189  __METHOD__
190  );
191 
192  // Reset token to break login with central auth systems.
193  // Again, avoids user being logged in with old name.
194  $user = User::newFromId( $this->uid );
195 
196  if ( class_exists( SessionManager::class ) &&
197  is_callable( [ SessionManager::singleton(), 'invalidateSessionsForUser' ] )
198  ) {
199  $user->load( User::READ_LATEST );
200  SessionManager::singleton()->invalidateSessionsForUser( $user );
201  } else {
202  $authUser = $wgAuth->getUserInstance( $user );
203  $authUser->resetAuthToken();
204  }
205 
206  // Purge user cache
207  $user->invalidateCache();
208 
209  // Update ipblock list if this user has a block in there.
210  $dbw->update( 'ipblocks',
211  [ 'ipb_address' => $this->new ],
212  [ 'ipb_user' => $this->uid, 'ipb_address' => $this->old ],
213  __METHOD__
214  );
215  // Update this users block/rights log. Ideally, the logs would be historical,
216  // but it is really annoying when users have "clean" block logs by virtue of
217  // being renamed, which makes admin tasks more of a pain...
218  $oldTitle = Title::makeTitle( NS_USER, $this->old );
219  $newTitle = Title::makeTitle( NS_USER, $this->new );
220  $this->debug( "Updating logging table for {$this->old} to {$this->new}" );
221 
222  $logTypesOnUser = SpecialLog::getLogTypesOnUser();
223 
224  $dbw->update( 'logging',
225  [ 'log_title' => $newTitle->getDBkey() ],
226  [ 'log_type' => $logTypesOnUser,
227  'log_namespace' => NS_USER,
228  'log_title' => $oldTitle->getDBkey() ],
229  __METHOD__
230  );
231 
232  // Do immediate re-attribution table updates...
233  foreach ( $this->tables as $table => $fieldSet ) {
234  list( $nameCol, $userCol ) = $fieldSet;
235  $dbw->update( $table,
236  [ $nameCol => $this->new ],
237  [ $nameCol => $this->old, $userCol => $this->uid ],
238  __METHOD__
239  );
240  }
241 
243  $jobs = []; // jobs for all tables
244  // Construct jobqueue updates...
245  // FIXME: if a bureaucrat renames a user in error, he/she
246  // must be careful to wait until the rename finishes before
247  // renaming back. This is due to the fact the the job "queue"
248  // is not really FIFO, so we might end up with a bunch of edits
249  // randomly mixed between the two new names. Some sort of rename
250  // lock might be in order...
251  foreach ( $this->tablesJob as $table => $params ) {
252  $userTextC = $params[self::NAME_COL]; // some *_user_text column
253  $userIDC = $params[self::UID_COL]; // some *_user column
254  $timestampC = $params[self::TIME_COL]; // some *_timestamp column
255 
256  $res = $dbw->select( $table,
257  [ $timestampC ],
258  [ $userTextC => $this->old, $userIDC => $this->uid ],
259  __METHOD__,
260  [ 'ORDER BY' => "$timestampC ASC" ]
261  );
262 
263  $jobParams = [];
264  $jobParams['table'] = $table;
265  $jobParams['column'] = $userTextC;
266  $jobParams['uidColumn'] = $userIDC;
267  $jobParams['timestampColumn'] = $timestampC;
268  $jobParams['oldname'] = $this->old;
269  $jobParams['newname'] = $this->new;
270  $jobParams['userID'] = $this->uid;
271  // Timestamp column data for index optimizations
272  $jobParams['minTimestamp'] = '0';
273  $jobParams['maxTimestamp'] = '0';
274  $jobParams['count'] = 0;
275  // Unique column for slave lag avoidance
276  if ( isset( $params['uniqueKey'] ) ) {
277  $jobParams['uniqueKey'] = $params['uniqueKey'];
278  }
279 
280  // Insert jobs into queue!
281  while ( true ) {
282  $row = $dbw->fetchObject( $res );
283  if ( !$row ) {
284  # If there are any job rows left, add it to the queue as one job
285  if ( $jobParams['count'] > 0 ) {
286  $jobs[] = Job::factory( 'renameUser', $oldTitle, $jobParams );
287  }
288  break;
289  }
290  # Since the ORDER BY is ASC, set the min timestamp with first row
291  if ( $jobParams['count'] === 0 ) {
292  $jobParams['minTimestamp'] = $row->$timestampC;
293  }
294  # Keep updating the last timestamp, so it should be correct
295  # when the last item is added.
296  $jobParams['maxTimestamp'] = $row->$timestampC;
297  # Update row counter
298  $jobParams['count']++;
299  # Once a job has $wgUpdateRowsPerJob rows, add it to the queue
300  if ( $jobParams['count'] >= $wgUpdateRowsPerJob ) {
301  $jobs[] = Job::factory( 'renameUser', $oldTitle, $jobParams );
302  $jobParams['minTimestamp'] = '0';
303  $jobParams['maxTimestamp'] = '0';
304  $jobParams['count'] = 0;
305  }
306  }
307  $dbw->freeResult( $res );
308  }
309 
310  // Log it!
311  $logEntry = new ManualLogEntry( 'renameuser', 'renameuser' );
312  $logEntry->setPerformer( $this->renamer );
313  $logEntry->setTarget( $oldTitle );
314  $logEntry->setComment( $this->reason );
315  $logEntry->setParameters( [
316  '4::olduser' => $this->old,
317  '5::newuser' => $this->new,
318  '6::edits' => $contribs
319  ] );
320  $logid = $logEntry->insert();
321  // Include the log_id in the jobs as a DB commit marker
322  foreach ( $jobs as $job ) {
323  $job->params['logId'] = $logid;
324  }
325 
326  // Insert any jobs as needed. If this fails, then an exception will be thrown and the
327  // DB transaction will be rolled back. If it succeeds but the DB commit fails, then the
328  // jobs will see that the transaction was not committed and will cancel themselves.
329  $count = count( $jobs );
330  if ( $count > 0 ) {
332  $this->debug( "Queued $count jobs for {$this->old} to {$this->new}" );
333  }
334 
335  // Commit the transaction
336  $dbw->endAtomic( __METHOD__ );
337 
338  $that = $this;
339  $dbw->onTransactionIdle( function() use ( $that, $dbw, $logEntry, $logid ) {
340  // Keep any updates here in a transaction
341  $dbw->setFlag( DBO_TRX );
342  // Clear caches and inform authentication plugins
343  $user = User::newFromId( $that->uid );
344  $user->load( User::READ_LATEST );
345  // Call $wgAuth for backwards compatibility
346  if ( class_exists( AuthManager::class ) ) {
347  AuthManager::callLegacyAuthPlugin( 'updateExternalDB', [ $user ] );
348  } else {
349  global $wgAuth;
350  $wgAuth->updateExternalDB( $user );
351  }
352  // Trigger the UserSaveSettings hook, which is the replacement for
353  // $wgAuth->updateExternalDB()
354  $user->saveSettings();
355  Hooks::run( 'RenameUserComplete', [ $that->uid, $that->old, $that->new ] );
356  // Publish to RC
357  $logEntry->publish( $logid );
358  } );
359 
360  $this->debug( "Finished rename for {$this->old} to {$this->new}" );
361 
362  return true;
363  }
364 
369  private static function lockUserAndGetId( $name ) {
370  return (int)wfGetDB( DB_MASTER )->selectField(
371  'user',
372  'user_id',
373  [ 'user_name' => $name ],
374  __METHOD__,
375  [ 'FOR UPDATE' ]
376  );
377  }
378 }
RenameuserSQL\$new
string $new
The new username.
Definition: RenameuserSQL.php:24
User\newFromId
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:579
RenameuserSQL\debug
debug( $msg)
Definition: RenameuserSQL.php:155
RenameuserSQL\$checkIfUserExists
bool $checkIfUserExists
Flag that can be set to false, in case another process has already started the updates and the old us...
Definition: RenameuserSQL.php:49
captcha-old.count
count
Definition: captcha-old.py:225
RenameuserSQL\rename
rename()
Do the rename operation.
Definition: RenameuserSQL.php:165
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:246
wfQueriesMustScale
wfQueriesMustScale()
Should low-performance queries be disabled?
Definition: GlobalFunctions.php:3122
$params
$params
Definition: styleTest.css.php:40
$res
$res
Definition: database.txt:21
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:304
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1092
DBO_TRX
const DBO_TRX
Definition: defines.php:12
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
RenameuserSQL\__construct
__construct( $old, $new, $uid, User $renamer, $options=[])
Constructor.
Definition: RenameuserSQL.php:95
RenameuserSQL\$tables
array $tables
The the tables => fields to be updated.
Definition: RenameuserSQL.php:40
RenameuserSQL\$renamer
User $renamer
User object of the user performing the rename, for logging purposes.
Definition: RenameuserSQL.php:56
Job\factory
static factory( $command, Title $title, $params=[])
Create the appropriate object to handle a specific job.
Definition: Job.php:68
RenameuserSQL
Class which performs the actual renaming of users.
Definition: RenameuserSQL.php:9
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:3060
SpecialLog\getLogTypesOnUser
static getLogTypesOnUser()
List log type for which the target is a user Thus if the given target is in NS_MAIN we can alter it t...
Definition: SpecialLog.php:122
$oldTitle
versus $oldTitle
Definition: globals.txt:16
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:514
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
DB_MASTER
const DB_MASTER
Definition: defines.php:26
list
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
MediaWiki\Session\SessionManager
This serves as the entry point to the MediaWiki session handling system.
Definition: SessionManager.php:49
RenameuserSQL\UID_COL
const UID_COL
Definition: RenameuserSQL.php:80
RenameuserSQL\CONTRIB_JOB
const CONTRIB_JOB
Users with more than this number of edits will have their rename operation deferred via the job queue...
Definition: RenameuserSQL.php:76
RenameuserSQL\$debugPrefix
string $debugPrefix
A prefix to use in all debug log messages.
Definition: RenameuserSQL.php:70
MediaWiki\Auth\AuthManager
This serves as the entry point to the authentication system.
Definition: AuthManager.php:82
RenameuserSQL\$uid
integer $uid
The user ID.
Definition: RenameuserSQL.php:32
reason
c Accompany it with the information you received as to the offer to distribute corresponding source complete source code means all the source code for all modules it plus any associated interface definition plus the scripts used to control compilation and installation of the executable as a special the source code distributed need not include anything that is normally and so on of the operating system on which the executable unless that component itself accompanies the executable If distribution of executable or object code is made by offering access to copy from a designated then offering equivalent access to copy the source code from the same place counts as distribution of the source even though third parties are not compelled to copy the source along with the object code You may not or distribute the Program except as expressly provided under this License Any attempt otherwise to sublicense or distribute the Program is and will automatically terminate your rights under this License parties who have received or from you under this License will not have their licenses terminated so long as such parties remain in full compliance You are not required to accept this since you have not signed it nothing else grants you permission to modify or distribute the Program or its derivative works These actions are prohibited by law if you do not accept this License by modifying or distributing the you indicate your acceptance of this License to do and all its terms and conditions for distributing or modifying the Program or works based on it Each time you redistribute the the recipient automatically receives a license from the original licensor to distribute or modify the Program subject to these terms and conditions You may not impose any further restrictions on the recipients exercise of the rights granted herein You are not responsible for enforcing compliance by third parties to this License as a consequence of a court judgment or allegation of patent infringement or for any other reason(not limited to patent issues)
RenameuserSQL\$old
string $old
The old username.
Definition: RenameuserSQL.php:16
RenameuserSQL\$reason
string $reason
Reason to be used in the log entry.
Definition: RenameuserSQL.php:63
RenameuserSQL\NAME_COL
const NAME_COL
Definition: RenameuserSQL.php:79
RenameuserSQL\TIME_COL
const TIME_COL
Definition: RenameuserSQL.php:81
$job
if(count( $args)< 1) $job
Definition: recompressTracked.php:47
JobQueueGroup\singleton
static singleton( $wiki=false)
Definition: JobQueueGroup.php:71
as
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
NS_USER
const NS_USER
Definition: Defines.php:64
JobQueue\QOS_ATOMIC
const QOS_ATOMIC
Definition: JobQueue.php:51
ManualLogEntry
Class for creating log entries manually, to inject them into the database.
Definition: LogEntry.php:396
class
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
RenameuserSQL\lockUserAndGetId
static lockUserAndGetId( $name)
Definition: RenameuserSQL.php:369
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:50
Hooks\run
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
Definition: Hooks.php:131
$options
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content as context as context $options
Definition: hooks.txt:1049
array
the array() calling protocol came about after MediaWiki 1.4rc1.