MediaWiki  1.30.0
userDupes.inc
Go to the documentation of this file.
1 <?php
35 class UserDupes {
36  private $db;
37  private $reassigned;
38  private $trimmed;
39  private $failed;
40  private $outputCallback;
41 
42  function __construct( &$database, $outputCallback ) {
43  $this->db = $database;
44  $this->outputCallback = $outputCallback;
45  }
46 
51  private function out( $str ) {
52  call_user_func( $this->outputCallback, $str );
53  }
54 
60  function hasUniqueIndex() {
61  $info = $this->db->indexInfo( 'user', 'user_name', __METHOD__ );
62  if ( !$info ) {
63  $this->out( "WARNING: doesn't seem to have user_name index at all!\n" );
64 
65  return false;
66  }
67 
68  # Confusingly, 'Non_unique' is 0 for *unique* indexes,
69  # and 1 for *non-unique* indexes. Pass the crack, MySQL,
70  # it's obviously some good stuff!
71  return ( $info[0]->Non_unique == 0 );
72  }
73 
85  function clearDupes() {
86  return $this->checkDupes( true );
87  }
88 
103  function checkDupes( $doDelete = false ) {
104  if ( $this->hasUniqueIndex() ) {
105  echo wfWikiID() . " already has a unique index on its user table.\n";
106 
107  return true;
108  }
109 
110  $this->lock();
111 
112  $this->out( "Checking for duplicate accounts...\n" );
113  $dupes = $this->getDupes();
114  $count = count( $dupes );
115 
116  $this->out( "Found $count accounts with duplicate records on " . wfWikiID() . ".\n" );
117  $this->trimmed = 0;
118  $this->reassigned = 0;
119  $this->failed = 0;
120  foreach ( $dupes as $name ) {
121  $this->examine( $name, $doDelete );
122  }
123 
124  $this->unlock();
125 
126  $this->out( "\n" );
127 
128  if ( $this->reassigned > 0 ) {
129  if ( $doDelete ) {
130  $this->out( "$this->reassigned duplicate accounts had edits "
131  . "reassigned to a canonical record id.\n" );
132  } else {
133  $this->out( "$this->reassigned duplicate accounts need to have edits reassigned.\n" );
134  }
135  }
136 
137  if ( $this->trimmed > 0 ) {
138  if ( $doDelete ) {
139  $this->out( "$this->trimmed duplicate user records were deleted from "
140  . wfWikiID() . ".\n" );
141  } else {
142  $this->out( "$this->trimmed duplicate user accounts were found on "
143  . wfWikiID() . " which can be removed safely.\n" );
144  }
145  }
146 
147  if ( $this->failed > 0 ) {
148  $this->out( "Something terribly awry; $this->failed duplicate accounts were not removed.\n" );
149 
150  return false;
151  }
152 
153  if ( $this->trimmed == 0 || $doDelete ) {
154  $this->out( "It is now safe to apply the unique index on user_name.\n" );
155 
156  return true;
157  } else {
158  $this->out( "Run this script again with the --fix option to automatically delete them.\n" );
159 
160  return false;
161  }
162  }
163 
168  function lock() {
169  $set = [ 'user', 'revision' ];
170  $names = array_map( [ $this, 'lockTable' ], $set );
171  $tables = implode( ',', $names );
172 
173  $this->db->query( "LOCK TABLES $tables", __METHOD__ );
174  }
175 
176  function lockTable( $table ) {
177  return $this->db->tableName( $table ) . ' WRITE';
178  }
179 
183  function unlock() {
184  $this->db->query( "UNLOCK TABLES", __METHOD__ );
185  }
186 
192  function getDupes() {
193  $user = $this->db->tableName( 'user' );
194  $result = $this->db->query(
195  "SELECT user_name,COUNT(*) AS n
196  FROM $user
197  GROUP BY user_name
198  HAVING n > 1", __METHOD__ );
199 
200  $list = [];
201  foreach ( $result as $row ) {
202  $list[] = $row->user_name;
203  }
204 
205  return $list;
206  }
207 
216  function examine( $name, $doDelete ) {
217  $result = $this->db->select( 'user',
218  [ 'user_id' ],
219  [ 'user_name' => $name ],
220  __METHOD__ );
221 
222  $firstRow = $this->db->fetchObject( $result );
223  $firstId = $firstRow->user_id;
224  $this->out( "Record that will be used for '$name' is user_id=$firstId\n" );
225 
226  foreach ( $result as $row ) {
227  $dupeId = $row->user_id;
228  $this->out( "... dupe id $dupeId: " );
229  $edits = $this->editCount( $dupeId );
230  if ( $edits > 0 ) {
231  $this->reassigned++;
232  $this->out( "has $edits edits! " );
233  if ( $doDelete ) {
234  $this->reassignEdits( $dupeId, $firstId );
235  $newEdits = $this->editCount( $dupeId );
236  if ( $newEdits == 0 ) {
237  $this->out( "confirmed cleaned. " );
238  } else {
239  $this->failed++;
240  $this->out( "WARNING! $newEdits remaining edits for $dupeId; NOT deleting user.\n" );
241  continue;
242  }
243  } else {
244  $this->out( "(will need to reassign edits on fix)" );
245  }
246  } else {
247  $this->out( "ok, no edits. " );
248  }
249  $this->trimmed++;
250  if ( $doDelete ) {
251  $this->trimAccount( $dupeId );
252  }
253  $this->out( "\n" );
254  }
255  }
256 
265  function editCount( $userid ) {
266  return intval( $this->db->selectField(
267  'revision',
268  'COUNT(*)',
269  [ 'rev_user' => $userid ],
270  __METHOD__ ) );
271  }
272 
278  function reassignEdits( $from, $to ) {
279  $this->out( 'reassigning... ' );
280  $this->db->update( 'revision',
281  [ 'rev_user' => $to ],
282  [ 'rev_user' => $from ],
283  __METHOD__ );
284  $this->out( "ok. " );
285  }
286 
292  function trimAccount( $userid ) {
293  $this->out( "deleting..." );
294  $this->db->delete( 'user', [ 'user_id' => $userid ], __METHOD__ );
295  $this->out( " ok" );
296  }
297 }
$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:244
UserDupes\lock
lock()
We don't want anybody to mess with our stuff...
Definition: userDupes.inc:168
$tables
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 & $tables
Definition: hooks.txt:988
captcha-old.count
count
Definition: captcha-old.py:249
UserDupes\$reassigned
$reassigned
Definition: userDupes.inc:37
UserDupes\lockTable
lockTable( $table)
Definition: userDupes.inc:176
$result
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetMagic':DEPRECATED! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1963
$name
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:302
UserDupes\clearDupes
clearDupes()
Checks the database for duplicate user account records and remove them in preparation for application...
Definition: userDupes.inc:85
UserDupes\$trimmed
$trimmed
Definition: userDupes.inc:38
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
UserDupes\editCount
editCount( $userid)
Count the number of edits attributed to this user.
Definition: userDupes.inc:265
UserDupes\checkDupes
checkDupes( $doDelete=false)
Checks the database for duplicate user account records in preparation for application of a unique ind...
Definition: userDupes.inc:103
UserDupes\unlock
unlock()
Definition: userDupes.inc:183
UserDupes\examine
examine( $name, $doDelete)
Examine user records for the given name.
Definition: userDupes.inc:216
UserDupes\hasUniqueIndex
hasUniqueIndex()
Check if this database's user table has already had a unique user_name index applied.
Definition: userDupes.inc:60
wfWikiID
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
Definition: GlobalFunctions.php:2807
UserDupes\trimAccount
trimAccount( $userid)
Remove a user account line.
Definition: userDupes.inc:292
UserDupes\getDupes
getDupes()
Grab usernames for which multiple records are present in the database.
Definition: userDupes.inc:192
UserDupes\$outputCallback
$outputCallback
Definition: userDupes.inc:40
UserDupes\$failed
$failed
Definition: userDupes.inc:39
UserDupes\out
out( $str)
Output some text via the output callback provided.
Definition: userDupes.inc:51
UserDupes
Look for duplicate user table entries and optionally prune them.
Definition: userDupes.inc:35
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
UserDupes\reassignEdits
reassignEdits( $from, $to)
Definition: userDupes.inc:278
UserDupes\__construct
__construct(&$database, $outputCallback)
Definition: userDupes.inc:42
UserDupes\$db
$db
Definition: userDupes.inc:36