MediaWiki REL1_39
removeUnusedAccounts.php
Go to the documentation of this file.
1<?php
28
29require_once __DIR__ . '/Maintenance.php';
30
37 public function __construct() {
38 parent::__construct();
39 $this->addOption( 'delete', 'Actually delete the account' );
40 $this->addOption( 'ignore-groups', 'List of comma-separated groups to exclude', false, true );
41 $this->addOption( 'ignore-touched', 'Skip accounts touched in last N days', false, true );
42 }
43
44 public function execute() {
45 $services = MediaWikiServices::getInstance();
46 $userFactory = $services->getUserFactory();
47 $userGroupManager = $services->getUserGroupManager();
48 $this->output( "Remove unused accounts\n\n" );
49
50 # Do an initial scan for inactive accounts and report the result
51 $this->output( "Checking for unused user accounts...\n" );
52 $delUser = [];
53 $delActor = [];
54 $dbr = $this->getDB( DB_REPLICA );
55 $res = $dbr->select(
56 [ 'user', 'actor' ],
57 [ 'user_id', 'user_name', 'user_touched', 'actor_id' ],
58 '',
59 __METHOD__,
60 [],
61 [ 'actor' => [ 'LEFT JOIN', 'user_id = actor_user' ] ]
62 );
63 if ( $this->hasOption( 'ignore-groups' ) ) {
64 $excludedGroups = explode( ',', $this->getOption( 'ignore-groups' ) );
65 } else {
66 $excludedGroups = [];
67 }
68 $touched = $this->getOption( 'ignore-touched', "1" );
69 if ( !ctype_digit( $touched ) ) {
70 $this->fatalError( "Please put a valid positive integer on the --ignore-touched parameter." );
71 }
72 $touchedSeconds = 86400 * $touched;
73 foreach ( $res as $row ) {
74 # Check the account, but ignore it if it's within a $excludedGroups
75 # group or if it's touched within the $touchedSeconds seconds.
76 $instance = $userFactory->newFromId( $row->user_id );
77 if ( count(
78 array_intersect( $userGroupManager->getUserEffectiveGroups( $instance ), $excludedGroups ) ) == 0
79 && $this->isInactiveAccount( $instance, $row->actor_id ?? null, true )
80 && wfTimestamp( TS_UNIX, $row->user_touched ) < wfTimestamp( TS_UNIX, time() - $touchedSeconds
81 )
82 ) {
83 # Inactive; print out the name and flag it
84 $delUser[] = $row->user_id;
85 if ( isset( $row->actor_id ) && $row->actor_id ) {
86 $delActor[] = $row->actor_id;
87 }
88 $this->output( $row->user_name . "\n" );
89 }
90 }
91 $count = count( $delUser );
92 $this->output( "...found {$count}.\n" );
93
94 # If required, go back and delete each marked account
95 if ( $count > 0 && $this->hasOption( 'delete' ) ) {
96 $this->output( "\nDeleting unused accounts..." );
97 $dbw = $this->getDB( DB_PRIMARY );
98 $dbw->delete( 'user', [ 'user_id' => $delUser ], __METHOD__ );
99 # Keep actor rows referenced from ipblocks
100 $keep = $dbw->selectFieldValues(
101 'ipblocks', 'ipb_by_actor', [ 'ipb_by_actor' => $delActor ], __METHOD__
102 );
103 $del = array_diff( $delActor, $keep );
104 if ( $del ) {
105 $dbw->delete( 'actor', [ 'actor_id' => $del ], __METHOD__ );
106 }
107 if ( $keep ) {
108 $dbw->update( 'actor', [ 'actor_user' => null ], [ 'actor_id' => $keep ], __METHOD__ );
109 }
110 $dbw->delete( 'user_groups', [ 'ug_user' => $delUser ], __METHOD__ );
111 $dbw->delete( 'user_former_groups', [ 'ufg_user' => $delUser ], __METHOD__ );
112 $dbw->delete( 'user_properties', [ 'up_user' => $delUser ], __METHOD__ );
113 $dbw->delete( 'logging', [ 'log_actor' => $delActor ], __METHOD__ );
114 $dbw->delete( 'recentchanges', [ 'rc_actor' => $delActor ], __METHOD__ );
115 $this->output( "done.\n" );
116 # Update the site_stats.ss_users field
117 $users = $dbw->selectField( 'user', 'COUNT(*)', [], __METHOD__ );
118 $dbw->update(
119 'site_stats',
120 [ 'ss_users' => $users ],
121 [ 'ss_row_id' => 1 ],
122 __METHOD__
123 );
124 } elseif ( $count > 0 ) {
125 $this->output( "\nRun the script again with --delete to remove them from the database.\n" );
126 }
127 $this->output( "\n" );
128 }
129
139 private function isInactiveAccount( $user, $actor, $primary = false ) {
140 if ( $actor === null ) {
141 // There's no longer a way for a user to be active in any of
142 // these tables without having an actor ID. The only way to link
143 // to a user row is via an actor row.
144 return true;
145 }
146
147 $dbo = $this->getDB( $primary ? DB_PRIMARY : DB_REPLICA );
148 $checks = [
149 'archive' => 'ar',
150 'image' => 'img',
151 'oldimage' => 'oi',
152 'filearchive' => 'fa'
153 // re-add when actor migration is complete
154 // 'revision' => 'rev'
155 ];
156 $count = 0;
157
158 $this->beginTransaction( $dbo, __METHOD__ );
159 foreach ( $checks as $table => $prefix ) {
160 $count += (int)$dbo->selectField(
161 $table,
162 'COUNT(*)',
163 [ "{$prefix}_actor" => $actor ],
164 __METHOD__
165 );
166 }
167
168 // Delete this special case when the actor migration is complete
169 $actorQuery = ActorMigration::newMigration()->getWhere( $dbo, 'rev_user', $user );
170 $count += (int)$dbo->selectField(
171 [ 'revision' ] + $actorQuery['tables'],
172 'COUNT(*)',
173 $actorQuery['conds'],
174 __METHOD__,
175 [],
176 $actorQuery['joins']
177 );
178
179 $count += (int)$dbo->selectField(
180 [ 'logging' ],
181 'COUNT(*)',
182 [
183 'log_actor' => $actor,
184 'log_type != ' . $dbo->addQuotes( 'newusers' )
185 ],
186 __METHOD__
187 );
188
189 $this->commitTransaction( $dbo, __METHOD__ );
190
191 return $count == 0;
192 }
193}
194
195$maintClass = RemoveUnusedAccounts::class;
196require_once RUN_MAINTENANCE_IF_MAIN;
getDB()
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static newMigration()
Static constructor.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
beginTransaction(IDatabase $dbw, $fname)
Begin a transaction on a DB.
commitTransaction(IDatabase $dbw, $fname)
Commit the transaction on a DB handle and wait for replica DBs to catch up.
output( $out, $channel=null)
Throw some output to the user.
hasOption( $name)
Checks to see if a particular option was set.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getOption( $name, $default=null)
Get an option, or return the default.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Service locator for MediaWiki core services.
Maintenance script that removes unused user accounts from the database.
execute()
Do the actual work.
__construct()
Default constructor.
Interface for objects representing user identity.
const DB_REPLICA
Definition defines.php:26
const DB_PRIMARY
Definition defines.php:28