removeInvalidEmails.php 2.0 KB

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