3 use MediaWiki\Maintenance\Maintenance
;
4 use MediaWiki\Parser\Sanitizer
;
5 use MediaWiki\User\User
;
7 // @codeCoverageIgnoreStart
8 require_once __DIR__
. '/Maintenance.php';
9 // @codeCoverageIgnoreEnd
12 * A script to remove emails that are invalid from
13 * the user_email column of the user table. Emails
14 * are validated before users can add them, but
15 * this was not always the case so older users may
18 * By default it does a dry-run, pass --commit
19 * to actually update the database.
21 class RemoveInvalidEmails
extends Maintenance
{
24 private $commit = false;
26 public function __construct() {
27 parent
::__construct();
28 $this->addOption( 'commit', 'Whether to actually update the database', false, false );
29 $this->setBatchSize( 500 );
32 public function execute() {
33 $this->commit
= $this->hasOption( 'commit' );
34 $dbr = $this->getReplicaDB();
35 $dbw = $this->getPrimaryDB();
38 $rows = $dbr->newSelectQueryBuilder()
39 ->select( [ 'user_id', 'user_email' ] )
42 $dbr->expr( 'user_id', '>', $lastId ),
43 $dbr->expr( 'user_email', '!=', '' ),
44 'user_email_authenticated' => null,
46 ->limit( $this->getBatchSize() )
47 ->caller( __METHOD__
)->fetchResultSet();
48 $count = $rows->numRows();
50 foreach ( $rows as $row ) {
51 if ( !Sanitizer
::validateEmail( trim( $row->user_email
) ) ) {
52 $this->output( "Found bad email: {$row->user_email} for user #{$row->user_id}\n" );
53 $badIds[] = $row->user_id
;
55 if ( $row->user_id
> $lastId ) {
56 $lastId = $row->user_id
;
61 $badCount = count( $badIds );
62 if ( $this->commit
) {
63 $this->output( "Removing $badCount emails from the database.\n" );
64 $dbw->newUpdateQueryBuilder()
66 ->set( [ 'user_email' => '' ] )
67 ->where( [ 'user_id' => $badIds ] )
68 ->caller( __METHOD__
)
70 foreach ( $badIds as $badId ) {
71 User
::newFromId( $badId )->invalidateCache();
73 $this->waitForReplication();
75 $this->output( "Would have removed $badCount emails from the database.\n" );
79 } while ( $count !== 0 );
80 $this->output( "Done.\n" );
84 // @codeCoverageIgnoreStart
85 $maintClass = RemoveInvalidEmails
::class;
86 require_once RUN_MAINTENANCE_IF_MAIN
;
87 // @codeCoverageIgnoreEnd