MediaWiki master
findMissingActors.php
Go to the documentation of this file.
1<?php
27
28// @codeCoverageIgnoreStart
29require_once __DIR__ . '/Maintenance.php';
30// @codeCoverageIgnoreEnd
31
38
39 private UserFactory $userFactory;
40 private UserNameUtils $userNameUtils;
41 private ActorNormalization $actorNormalization;
42
43 public function __construct() {
44 parent::__construct();
45
46 $this->addDescription( 'Find and fix invalid actor IDs.' );
47 $this->addOption( 'field', 'The name of a database field to process',
48 true, true );
49 $this->addOption( 'type', 'Which type of invalid actors to find or fix, '
50 . 'missing or broken (with empty actor_name which can\'t be associated '
51 . 'with an existing user).',
52 false, true );
53 $this->addOption( 'skip', 'A comma-separated list of actor IDs to skip.',
54 false, true );
55 $this->addOption( 'overwrite-with', 'Replace invalid actors with this user. '
56 . 'Typically, this would be "Unknown user", but it could be any reserved '
57 . 'system user (per $wgReservedUsernames) or locally registered user. '
58 . 'If not given, invalid actors will only be listed, not fixed. '
59 . 'You will be prompted for confirmation before data is written. ',
60 false, true );
61
62 $this->setBatchSize( 1000 );
63 }
64
68 private function getTables() {
69 return [
70 'ar_actor' => [ 'archive', 'ar_actor', 'ar_id' ],
71 'img_actor' => [ 'image', 'img_actor', 'img_name' ],
72 'oi_actor' => [ 'oldimage', 'oi_actor', 'oi_archive_name' ], // no index on oi_archive_name!
73 'fa_actor' => [ 'filearchive', 'fa_actor', 'fa_id' ],
74 'fr_actor' => [ 'filerevision', 'fr_actor', 'fr_id' ],
75 'rc_actor' => [ 'recentchanges', 'rc_actor', 'rc_id' ],
76 'log_actor' => [ 'logging', 'log_actor', 'log_id' ],
77 'rev_actor' => [ 'revision', 'rev_actor', 'rev_id' ],
78 'bl_by_actor' => [ 'block', 'bl_by_actor', 'bl_id' ], // no index on bl_by_actor!
79 ];
80 }
81
86 private function getTableInfo( $field ) {
87 $tables = $this->getTables();
88 return $tables[$field] ?? null;
89 }
90
100 private function getNewActorId() {
101 $name = $this->getOption( 'overwrite-with' );
102
103 if ( $name === null ) {
104 return null;
105 }
106
107 $user = $this->userFactory->newFromName( $name );
108
109 if ( !$user ) {
110 $this->fatalError( "Not a valid user name: '$name'" );
111 }
112
113 if ( $user->isRegistered() ) {
114 $this->output( "Using existing user: '$user'\n" );
115 } elseif ( !$this->userNameUtils->isUsable( $user->getName() ) ) {
116 $this->output( "Using system user: '{$user->getName()}'\n" );
117 } else {
118 $this->fatalError( "Unknown user: '{$user->getName()}'" );
119 }
120
121 $dbw = $this->getPrimaryDB();
122
123 try {
124 $actorId = $this->actorNormalization->acquireActorId( $user, $dbw );
125 } catch ( CannotCreateActorException ) {
126 $this->fatalError( "Failed to acquire an actor ID for user '$user'" );
127 }
128
129 $this->output( "Replacement actor ID is $actorId.\n" );
130 return $actorId;
131 }
132
133 public function execute() {
134 $services = $this->getServiceContainer();
135 $this->userFactory = $services->getUserFactory();
136 $this->userNameUtils = $services->getUserNameUtils();
137 $this->actorNormalization = $services->getActorNormalization();
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 = static::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// @codeCoverageIgnoreStart
273$maintClass = FindMissingActors::class;
274require_once RUN_MAINTENANCE_IF_MAIN;
275// @codeCoverageIgnoreEnd
Maintenance script for finding and replacing invalid actor IDs, see T261325 and T307738.
execute()
Do the actual work.
__construct()
Default constructor.
Exception thrown when an actor can't be created.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
getBatchSize()
Returns batch size.
output( $out, $channel=null)
Throw some output to the user.
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.
waitForReplication()
Wait for replica DB servers to catch up.
getOption( $name, $default=null)
Get an option, or return the default.
parseIntList( $text)
Utility function to parse a string (perhaps from a command line option) into a list of integers (perh...
getServiceContainer()
Returns the main service container.
addDescription( $text)
Set the description text.
Create User objects.
UserNameUtils service.
Service for dealing with the actor table.
const DB_REPLICA
Definition defines.php:26