Updating composer/semver (1.5.1 => 1.5.2)
[mediawiki.git] / maintenance / removeInvalidEmails.php
blob0162a9a55bc38152d192cfca4e63d962ea3403cc
1 <?php
3 require_once __DIR__ . '/Maintenance.php';
5 use MediaWiki\MediaWikiServices;
7 /**
8 * A script to remove emails that are invalid from
9 * the user_email column of the user table. Emails
10 * are validated before users can add them, but
11 * this was not always the case so older users may
12 * have invalid ones.
14 * By default it does a dry-run, pass --commit
15 * to actually update the database.
17 class RemoveInvalidEmails extends Maintenance {
19 private $commit = false;
21 public function __construct() {
22 parent::__construct();
23 $this->addOption( 'commit', 'Whether to actually update the database', false, false );
24 $this->setBatchSize( 500 );
27 public function execute() {
28 $this->commit = $this->hasOption( 'commit' );
29 $dbr = $this->getDB( DB_REPLICA );
30 $dbw = $this->getDB( DB_MASTER );
31 $lastId = 0;
32 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
33 do {
34 $rows = $dbr->select(
35 'user',
36 [ 'user_id', 'user_email' ],
38 'user_id > ' . $dbr->addQuotes( $lastId ),
39 'user_email != ""',
40 'user_email_authenticated IS NULL'
42 __METHOD__,
43 [ 'LIMIT' => $this->getBatchSize() ]
45 $count = $rows->numRows();
46 $badIds = [];
47 foreach ( $rows as $row ) {
48 if ( !Sanitizer::validateEmail( trim( $row->user_email ) ) ) {
49 $this->output( "Found bad email: {$row->user_email} for user #{$row->user_id}\n" );
50 $badIds[] = $row->user_id;
52 if ( $row->user_id > $lastId ) {
53 $lastId = $row->user_id;
57 if ( $badIds ) {
58 $badCount = count( $badIds );
59 if ( $this->commit ) {
60 $this->output( "Removing $badCount emails from the database.\n" );
61 $dbw->update(
62 'user',
63 [ 'user_email' => '' ],
64 [ 'user_id' => $badIds ],
65 __METHOD__
67 foreach ( $badIds as $badId ) {
68 User::newFromId( $badId )->invalidateCache();
70 $lbFactory->waitForReplication();
71 } else {
72 $this->output( "Would have removed $badCount emails from the database.\n" );
76 } while ( $count !== 0 );
77 $this->output( "Done.\n" );
81 $maintClass = RemoveInvalidEmails::class;
82 require_once RUN_MAINTENANCE_IF_MAIN;