MediaWiki master
findMissingActors.php
Go to the documentation of this file.
1<?php
26
27require_once __DIR__ . '/Maintenance.php';
28
35
36 private UserFactory $userFactory;
37 private UserNameUtils $userNameUtils;
38 private ActorNormalization $actorNormalization;
39
40 public function __construct() {
41 parent::__construct();
42
43 $this->addDescription( 'Find and fix invalid actor IDs.' );
44 $this->addOption( 'field', 'The name of a database field to process',
45 true, true );
46 $this->addOption( 'type', 'Which type of invalid actors to find or fix, '
47 . 'missing or broken (with empty actor_name which can\'t be associated '
48 . 'with an existing user).',
49 false, true );
50 $this->addOption( 'skip', 'A comma-separated list of actor IDs to skip.',
51 false, true );
52 $this->addOption( 'overwrite-with', 'Replace invalid actors with this user. '
53 . 'Typically, this would be "Unknown user", but it could be any reserved '
54 . 'system user (per $wgReservedUsernames) or locally registered user. '
55 . 'If not given, invalid actors will only be listed, not fixed. '
56 . 'You will be prompted for confirmation before data is written. ',
57 false, true );
58
59 $this->setBatchSize( 1000 );
60 }
61
65 private function getTables() {
66 return [
67 'ar_actor' => [ 'archive', 'ar_actor', 'ar_id' ],
68 'img_actor' => [ 'image', 'img_actor', 'img_name' ],
69 'oi_actor' => [ 'oldimage', 'oi_actor', 'oi_archive_name' ], // no index on oi_archive_name!
70 'fa_actor' => [ 'filearchive', 'fa_actor', 'fa_id' ],
71 'rc_actor' => [ 'recentchanges', 'rc_actor', 'rc_id' ],
72 'log_actor' => [ 'logging', 'log_actor', 'log_id' ],
73 'rev_actor' => [ 'revision', 'rev_actor', 'rev_id' ],
74 'bl_by_actor' => [ 'block', 'bl_by_actor', 'bl_id' ], // no index on bl_by_actor!
75 ];
76 }
77
82 private function getTableInfo( $field ) {
83 $tables = $this->getTables();
84 return $tables[$field] ?? null;
85 }
86
96 private function getNewActorId() {
97 $name = $this->getOption( 'overwrite-with' );
98
99 if ( $name === null ) {
100 return null;
101 }
102
103 $user = $this->userFactory->newFromName( $name );
104
105 if ( !$user ) {
106 $this->fatalError( "Not a valid user name: '$name'" );
107 }
108
109 $name = $this->userNameUtils->getCanonical( $name, UserRigorOptions::RIGOR_NONE );
110
111 if ( $user->isRegistered() ) {
112 $this->output( "Using existing user: '$user'\n" );
113 } elseif ( !$this->userNameUtils->isValid( $name ) ) {
114 $this->fatalError( "Not a valid user name: '$name'" );
115 } elseif ( !$this->userNameUtils->isUsable( $name ) ) {
116 $this->output( "Using system user: '$name'\n" );
117 } else {
118 $this->fatalError( "Unknown user: '$name'" );
119 }
120
121 $dbw = $this->getPrimaryDB();
122 $actorId = $this->actorNormalization->acquireActorId( $user, $dbw );
123
124 if ( !$actorId ) {
125 $this->fatalError( "Failed to acquire an actor ID for user '$user'" );
126 }
127
128 $this->output( "Replacement actor ID is $actorId.\n" );
129 return $actorId;
130 }
131
132 public function execute() {
133 $services = $this->getServiceContainer();
134 $this->userFactory = $services->getUserFactory();
135 $this->userNameUtils = $services->getUserNameUtils();
136 $this->actorNormalization = $services->getActorNormalization();
137 $this->setDBProvider( $services->getConnectionProvider() );
138
139 $field = $this->getOption( 'field' );
140 if ( !$this->getTableInfo( $field ) ) {
141 $this->fatalError( "Unknown field: $field.\n" );
142 }
143
144 $type = $this->getOption( 'type', 'missing' );
145 if ( $type !== 'missing' && $type !== 'broken' ) {
146 $this->fatalError( "Unknown type: $type.\n" );
147 }
148
149 $skip = $this->parseIntList( $this->getOption( 'skip', '' ) );
150 $overwrite = $this->getNewActorId();
151
152 $bad = $this->findBadActors( $field, $type, $skip );
153
154 if ( $bad && $overwrite ) {
155 $this->output( "\n" );
156 $this->output( "Do you want to OVERWRITE the listed actor IDs?\n" );
157 $this->output( "Information about the invalid IDs will be lost!\n" );
158 $this->output( "\n" );
159 $confirm = self::readconsole( 'Type "yes" to continue: ' );
160
161 if ( $confirm === 'yes' ) {
162 $this->overwriteActorIDs( $field, array_keys( $bad ), $overwrite );
163 } else {
164 $this->fatalError( 'Aborted.' );
165 }
166 }
167
168 $this->output( "Done.\n" );
169 }
170
180 private function findBadActors( $field, $type, $skip ) {
181 [ $table, $actorField, $idField ] = $this->getTableInfo( $field );
182 $this->output( "Finding invalid actor IDs in $table.$actorField...\n" );
183
184 $dbr = $this->getServiceContainer()->getDBLoadBalancer()->getConnection( DB_REPLICA, 'vslow' );
185
186 /*
187 We are building an SQL query like this one here, performing a left join
188 to detect rows in $table that lack a matching row in the actor table.
189
190 In this example, $field is 'log_actor', so $table is 'logging',
191 $actorField is 'log_actor', and $idField is 'log_id'.
192 Further, $skip is [ 1, 2, 3, 4 ] and the batch size is 1000.
193
194 SELECT log_id
195 FROM logging
196 LEFT JOIN actor ON log_actor = actor_id
197 WHERE actor_id IS NULL
198 AND log_actor NOT IN (1, 2, 3, 4)
199 LIMIT 1000;
200 */
201
202 $queryBuilder = $dbr->newSelectQueryBuilder()
203 ->select( [ $actorField, $idField ] )
204 ->from( $table )
205 ->leftJoin( 'actor', null, [ "$actorField = actor_id" ] )
206 ->where( $type == 'missing' ? [ 'actor_id' => null ] : [ 'actor_name' => '' ] )
207 ->limit( $this->getBatchSize() );
208
209 if ( $skip ) {
210 $queryBuilder->andWhere( $dbr->expr( $actorField, '!=', $skip ) );
211 }
212
213 $res = $queryBuilder->caller( __METHOD__ )->fetchResultSet();
214 $count = $res->numRows();
215
216 $bad = [];
217
218 if ( $count ) {
219 $this->output( "\t\tID\tACTOR\n" );
220 }
221
222 foreach ( $res as $row ) {
223 $id = $row->$idField;
224 $actor = (int)( $row->$actorField );
225
226 $bad[$id] = $actor;
227 $this->output( "\t\t$id\t$actor\n" );
228 }
229
230 $this->output( "\tFound $count invalid actor IDs.\n" );
231
232 if ( $count >= $this->getBatchSize() ) {
233 $this->output( "\tBatch size reached, run again after fixing the current batch.\n" );
234 }
235
236 return $bad;
237 }
238
248 private function overwriteActorIDs( $field, array $ids, int $overwrite ) {
249 [ $table, $actorField, $idField ] = $this->getTableInfo( $field );
250
251 $count = count( $ids );
252 $this->output( "OVERWRITING $count actor IDs in $table.$actorField with $overwrite...\n" );
253
254 $dbw = $this->getPrimaryDB();
255
256 $dbw->newUpdateQueryBuilder()
257 ->update( $table )
258 ->set( [ $actorField => $overwrite ] )
259 ->where( [ $idField => $ids ] )
260 ->caller( __METHOD__ )->execute();
261
262 $count = $dbw->affectedRows();
263
264 $this->waitForReplication();
265 $this->output( "\tUpdated $count rows.\n" );
266
267 return $count;
268 }
269
270}
271
272$maintClass = FindMissingActors::class;
273require_once RUN_MAINTENANCE_IF_MAIN;
Maintenance script for finding and replacing invalid actor IDs, see T261325 and T307738.
execute()
Do the actual work.
__construct()
Default constructor.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
output( $out, $channel=null)
Throw some output to the user.
waitForReplication()
Wait for replica DBs to catch up.
static readconsole( $prompt='> ')
Prompt the console for input.
getServiceContainer()
Returns the main service container.
getBatchSize()
Returns batch size.
parseIntList( $text)
Utility function to parse a string (perhaps from a command line option) into a list of integers (perh...
addDescription( $text)
Set the description text.
setDBProvider(IConnectionProvider $dbProvider)
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.
setBatchSize( $s=0)
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Creates User objects.
UserNameUtils service.
Service for dealing with the actor table.
Shared interface for rigor levels when dealing with User methods.
const DB_REPLICA
Definition defines.php:26