MediaWiki master
removeUnusedAccounts.php
Go to the documentation of this file.
1<?php
14use Wikimedia\Timestamp\TimestampFormat as TS;
15
16// @codeCoverageIgnoreStart
17require_once __DIR__ . '/Maintenance.php';
18// @codeCoverageIgnoreEnd
19
26 public function __construct() {
27 parent::__construct();
28 $this->addOption( 'delete', 'Actually delete the account' );
29 $this->addOption( 'ignore-groups', 'List of comma-separated groups to exclude', false, true );
30 $this->addOption( 'ignore-touched', 'Skip accounts touched in last N days', false, true );
31 }
32
33 public function execute() {
34 $services = $this->getServiceContainer();
35 $userFactory = $services->getUserFactory();
36 $userGroupManager = $services->getUserGroupManager();
37 $this->output( "Remove unused accounts\n\n" );
38
39 # Do an initial scan for inactive accounts and report the result
40 $this->output( "Checking for unused user accounts...\n" );
41 $delUser = [];
42 $delActor = [];
43 $dbr = $this->getReplicaDB();
44 $res = $dbr->newSelectQueryBuilder()
45 ->select( [ 'user_id', 'user_name', 'user_touched', 'actor_id' ] )
46 ->from( 'user' )
47 ->leftJoin( 'actor', null, 'user_id = actor_user' )
48 ->caller( __METHOD__ )->fetchResultSet();
49 if ( $this->hasOption( 'ignore-groups' ) ) {
50 $excludedGroups = explode( ',', $this->getOption( 'ignore-groups' ) );
51 } else {
52 $excludedGroups = [];
53 }
54 $touched = $this->getOption( 'ignore-touched', "1" );
55 if ( !ctype_digit( $touched ) ) {
56 $this->fatalError( "Please put a valid positive integer on the --ignore-touched parameter." );
57 }
58 $touchedSeconds = 86400 * $touched;
59 foreach ( $res as $row ) {
60 # Check the account, but ignore it if it's within a $excludedGroups
61 # group or if it's touched within the $touchedSeconds seconds.
62 $instance = $userFactory->newFromId( $row->user_id );
63 if ( count(
64 array_intersect( $userGroupManager->getUserEffectiveGroups( $instance ), $excludedGroups ) ) == 0
65 && $this->isInactiveAccount( $instance, $row->actor_id ?? null, true )
66 && wfTimestamp( TS::UNIX, $row->user_touched ) < wfTimestamp( TS::UNIX, time() - $touchedSeconds
67 )
68 ) {
69 # Inactive; print out the name and flag it
70 $delUser[] = $row->user_id;
71 if ( isset( $row->actor_id ) && $row->actor_id ) {
72 $delActor[] = $row->actor_id;
73 }
74 $this->output( $row->user_name . "\n" );
75 }
76 }
77 $count = count( $delUser );
78 $this->output( "...found {$count}.\n" );
79
80 # If required, go back and delete each marked account
81 if ( $count > 0 && $this->hasOption( 'delete' ) ) {
82 $this->output( "\nDeleting unused accounts..." );
83 $dbw = $this->getPrimaryDB();
84 $dbw->newDeleteQueryBuilder()
85 ->deleteFrom( 'user' )
86 ->where( [ 'user_id' => $delUser ] )
87 ->caller( __METHOD__ )->execute();
88 # Keep actor rows referenced from block
89 $keep = $dbw->newSelectQueryBuilder()
90 ->select( 'bl_by_actor' )
91 ->from( 'block' )
92 ->where( [ 'bl_by_actor' => $delActor ] )
93 ->caller( __METHOD__ )->fetchFieldValues();
94 $del = array_diff( $delActor, $keep );
95 if ( $del ) {
96 $dbw->newDeleteQueryBuilder()
97 ->deleteFrom( 'actor' )
98 ->where( [ 'actor_id' => $del ] )
99 ->caller( __METHOD__ )->execute();
100 }
101 $dbw->newDeleteQueryBuilder()
102 ->deleteFrom( 'user_groups' )
103 ->where( [ 'ug_user' => $delUser ] )
104 ->caller( __METHOD__ )->execute();
105 $dbw->newDeleteQueryBuilder()
106 ->deleteFrom( 'user_former_groups' )
107 ->where( [ 'ufg_user' => $delUser ] )
108 ->caller( __METHOD__ )->execute();
109 $dbw->newDeleteQueryBuilder()
110 ->deleteFrom( 'user_properties' )
111 ->where( [ 'up_user' => $delUser ] )
112 ->caller( __METHOD__ )->execute();
113 $dbw->newDeleteQueryBuilder()
114 ->deleteFrom( 'logging' )
115 ->where( [ 'log_actor' => $delActor ] )
116 ->caller( __METHOD__ )->execute();
117 $dbw->newDeleteQueryBuilder()
118 ->deleteFrom( 'recentchanges' )
119 ->where( [ 'rc_actor' => $delActor ] )
120 ->caller( __METHOD__ )->execute();
121 $this->output( "done.\n" );
122 # Update the site_stats.ss_users field
123 $users = $dbw->newSelectQueryBuilder()
124 ->select( 'COUNT(*)' )
125 ->from( 'user' )
126 ->caller( __METHOD__ )->fetchField();
127 $dbw->newUpdateQueryBuilder()
128 ->update( 'site_stats' )
129 ->set( [ 'ss_users' => $users ] )
130 ->where( [ 'ss_row_id' => 1 ] )
131 ->caller( __METHOD__ )
132 ->execute();
133 } elseif ( $count > 0 ) {
134 $this->output( "\nRun the script again with --delete to remove them from the database.\n" );
135 }
136 $this->output( "\n" );
137 }
138
148 private function isInactiveAccount( $user, $actor, $primary = false ) {
149 if ( $actor === null ) {
150 // There's no longer a way for a user to be active in any of
151 // these tables without having an actor ID. The only way to link
152 // to a user row is via an actor row.
153 return true;
154 }
155
156 $dbo = $primary ? $this->getPrimaryDB() : $this->getReplicaDB();
157 $checks = [
158 'archive' => 'ar',
159 'image' => 'img',
160 'oldimage' => 'oi',
161 'filearchive' => 'fa',
162 'revision' => 'rev',
163 ];
164 $count = 0;
165
166 $this->beginTransaction( $dbo, __METHOD__ );
167 foreach ( $checks as $table => $prefix ) {
168 $count += (int)$dbo->newSelectQueryBuilder()
169 ->select( 'COUNT(*)' )
170 ->from( $table )
171 ->where( [ "{$prefix}_actor" => $actor ] )
172 ->caller( __METHOD__ )
173 ->fetchField();
174 }
175
176 $count += (int)$dbo->newSelectQueryBuilder()
177 ->select( 'COUNT(*)' )
178 ->from( 'logging' )
179 ->where( [ 'log_actor' => $actor, $dbo->expr( 'log_type', '!=', 'newusers' ) ] )
180 ->caller( __METHOD__ )->fetchField();
181
182 $this->commitTransaction( $dbo, __METHOD__ );
183
184 return $count == 0;
185 }
186}
187
188// @codeCoverageIgnoreStart
189$maintClass = RemoveUnusedAccounts::class;
190require_once RUN_MAINTENANCE_IF_MAIN;
191// @codeCoverageIgnoreEnd
wfTimestamp( $outputtype=TS::UNIX, $ts=0)
Get a timestamp string in one of various formats.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
output( $out, $channel=null)
Throw some output to the user.
commitTransaction(IDatabase $dbw, $fname)
Commit the transaction on a DB handle and wait for replica DB servers to catch up.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
hasOption( $name)
Checks to see if a particular option was set.
getOption( $name, $default=null)
Get an option, or return the default.
getReplicaDB(string|false $virtualDomain=false)
beginTransaction(IDatabase $dbw, $fname)
Begin a transaction on a DB handle.
getServiceContainer()
Returns the main service container.
getPrimaryDB(string|false $virtualDomain=false)
Maintenance script that removes unused user accounts from the database.
execute()
Do the actual work.
__construct()
Default constructor.
Interface for objects representing user identity.