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