MediaWiki  master
cleanupSpam.php
Go to the documentation of this file.
1 <?php
28 
29 require_once __DIR__ . '/Maintenance.php';
30 
36 class CleanupSpam extends Maintenance {
37 
38  public function __construct() {
39  parent::__construct();
40  $this->addDescription( 'Cleanup all spam from a given hostname' );
41  $this->addOption( 'all', 'Check all wikis in $wgLocalDatabases' );
42  $this->addOption( 'delete', 'Delete pages containing only spam instead of blanking them' );
43  $this->addArg(
44  'hostname',
45  'Hostname that was spamming, single * wildcard in the beginning allowed'
46  );
47  }
48 
49  public function execute() {
50  global $IP, $wgLocalDatabases, $wgUser;
51 
52  $username = wfMessage( 'spambot_username' )->text();
53  $user = User::newSystemUser( $username );
54  if ( !$user ) {
55  $this->fatalError( "Invalid username specified in 'spambot_username' message: $username" );
56  }
57  // Hack: Grant bot rights so we don't flood RecentChanges
58  MediaWikiServices::getInstance()->getUserGroupManager()->addUserToGroup( $user, 'bot' );
59  $wgUser = $user;
60 
61  $spec = $this->getArg( 0 );
62 
63  $protConds = [];
64  foreach ( [ 'http://', 'https://' ] as $prot ) {
65  $conds = LinkFilter::getQueryConditions( $spec, [ 'protocol' => $prot ] );
66  if ( !$conds ) {
67  $this->fatalError( "Not a valid hostname specification: $spec" );
68  }
69  $protConds[$prot] = $conds;
70  }
71 
72  if ( $this->hasOption( 'all' ) ) {
73  // Clean up spam on all wikis
74  $this->output( "Finding spam on " . count( $wgLocalDatabases ) . " wikis\n" );
75  $found = false;
76  foreach ( $wgLocalDatabases as $wikiId ) {
78  $dbr = $this->getDB( DB_REPLICA, [], $wikiId );
79 
80  foreach ( $protConds as $conds ) {
81  $count = $dbr->selectField(
82  'externallinks',
83  'COUNT(*)',
84  $conds,
85  __METHOD__
86  );
87  if ( $count ) {
88  $found = true;
89  $cmd = wfShellWikiCmd(
90  "$IP/maintenance/cleanupSpam.php",
91  [ '--wiki', $wikiId, $spec ]
92  );
93  passthru( "$cmd | sed 's/^/$wikiId: /'" );
94  }
95  }
96  }
97  if ( $found ) {
98  $this->output( "All done\n" );
99  } else {
100  $this->output( "None found\n" );
101  }
102  } else {
103  // Clean up spam on this wiki
104 
105  $count = 0;
107  $dbr = $this->getDB( DB_REPLICA );
108  foreach ( $protConds as $prot => $conds ) {
109  $res = $dbr->select(
110  'externallinks',
111  [ 'DISTINCT el_from' ],
112  $conds,
113  __METHOD__
114  );
115  $count = $dbr->numRows( $res );
116  $this->output( "Found $count articles containing $spec\n" );
117  foreach ( $res as $row ) {
118  $this->cleanupArticle(
119  $row->el_from,
120  $spec,
121  $prot,
122  $user
123  );
124  }
125  }
126  if ( $count ) {
127  $this->output( "Done\n" );
128  }
129  }
130  }
131 
139  private function cleanupArticle( $id, $domain, $protocol, Authority $performer ) {
140  $title = Title::newFromID( $id );
141  if ( !$title ) {
142  $this->error( "Internal error: no page for ID $id" );
143 
144  return;
145  }
146 
147  $this->output( $title->getPrefixedDBkey() . " ..." );
148 
149  $services = MediaWikiServices::getInstance();
150  $revLookup = $services->getRevisionLookup();
151  $rev = $revLookup->getRevisionByTitle( $title );
152  $currentRevId = $rev->getId();
153 
154  while ( $rev && ( $rev->isDeleted( RevisionRecord::DELETED_TEXT ) ||
156  $rev->getContent( SlotRecord::MAIN, RevisionRecord::RAW ),
157  $domain,
158  $protocol
159  ) )
160  ) {
161  $rev = $revLookup->getPreviousRevision( $rev );
162  }
163 
164  if ( $rev && $rev->getId() == $currentRevId ) {
165  // The regex didn't match the current article text
166  // This happens e.g. when a link comes from a template rather than the page itself
167  $this->output( "False match\n" );
168  } else {
169  $dbw = $this->getDB( DB_PRIMARY );
170  $this->beginTransaction( $dbw, __METHOD__ );
171  $page = $services->getWikiPageFactory()->newFromTitle( $title );
172  if ( $rev ) {
173  // Revert to this revision
174  $content = $rev->getContent( SlotRecord::MAIN, RevisionRecord::RAW );
175 
176  $this->output( "reverting\n" );
177  $page->doUserEditContent(
178  $content,
179  $performer,
180  wfMessage( 'spam_reverting', $domain )->inContentLanguage()->text(),
182  $rev->getId()
183  );
184  } elseif ( $this->hasOption( 'delete' ) ) {
185  // Didn't find a non-spammy revision, blank the page
186  $this->output( "deleting\n" );
187  $page->doDeleteArticleReal(
188  wfMessage( 'spam_deleting', $domain )->inContentLanguage()->text(),
189  $performer->getUser()
190  );
191  } else {
192  // Didn't find a non-spammy revision, blank the page
193  $handler = $services->getContentHandlerFactory()
194  ->getContentHandler( $title->getContentModel() );
195  $content = $handler->makeEmptyContent();
196 
197  $this->output( "blanking\n" );
198  $page->doUserEditContent(
199  $content,
200  $performer,
201  wfMessage( 'spam_blanking', $domain )->inContentLanguage()->text(),
203  );
204  }
205  $this->commitTransaction( $dbw, __METHOD__ );
206  }
207  }
208 }
209 
210 $maintClass = CleanupSpam::class;
211 require_once RUN_MAINTENANCE_IF_MAIN;
$wgLocalDatabases
string[] $wgLocalDatabases
Other wikis on this site, can be administered from a single developer account.
Definition: DefaultSettings.php:2352
MediaWiki\Revision\RevisionRecord
Page revision base class.
Definition: RevisionRecord.php:47
CleanupSpam
Maintenance script to cleanup all spam from a given hostname.
Definition: cleanupSpam.php:36
CleanupSpam\cleanupArticle
cleanupArticle( $id, $domain, $protocol, Authority $performer)
Definition: cleanupSpam.php:139
LinkFilter\getQueryConditions
static getQueryConditions( $filterEntry, array $options=[])
Return query conditions which will match the specified string.
Definition: LinkFilter.php:256
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:186
LinkFilter\matchEntry
static matchEntry(Content $content, $filterEntry, $protocol='http://')
Check whether $content contains a link to $filterEntry.
Definition: LinkFilter.php:51
Maintenance\fatalError
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
Definition: Maintenance.php:488
Maintenance\addDescription
addDescription( $text)
Set the description text.
Definition: Maintenance.php:329
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1182
Maintenance
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: Maintenance.php:59
$maintClass
$maintClass
Definition: cleanupSpam.php:210
$res
$res
Definition: testCompression.php:57
MediaWiki\Permissions\Authority\getUser
getUser()
Returns the performer of the actions associated with this authority.
wfShellWikiCmd
wfShellWikiCmd( $script, array $parameters=[], array $options=[])
Generate a shell-escaped command line string to run a MediaWiki cli script.
Definition: GlobalFunctions.php:2009
$dbr
$dbr
Definition: testCompression.php:54
User\newSystemUser
static newSystemUser( $name, $options=[])
Static factory method for creation of a "system" user from username.
Definition: User.php:805
Maintenance\beginTransaction
beginTransaction(IDatabase $dbw, $fname)
Begin a transaction on a DB.
Definition: Maintenance.php:1392
Maintenance\addOption
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:249
$title
$title
Definition: testCompression.php:38
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
MediaWiki\Permissions\Authority
This interface represents the authority associated the current execution context, such as a web reque...
Definition: Authority.php:37
$content
$content
Definition: router.php:76
DB_PRIMARY
const DB_PRIMARY
Definition: defines.php:27
Maintenance\commitTransaction
commitTransaction(IDatabase $dbw, $fname)
Commit the transaction on a DB handle and wait for replica DBs to catch up.
Definition: Maintenance.php:1407
Maintenance\getDB
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1361
CleanupSpam\__construct
__construct()
Default constructor.
Definition: cleanupSpam.php:38
EDIT_UPDATE
const EDIT_UPDATE
Definition: Defines.php:126
Maintenance\addArg
addArg( $arg, $description, $required=true)
Add some args that are needed.
Definition: Maintenance.php:300
Maintenance\error
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:464
Maintenance\output
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:435
EDIT_FORCE_BOT
const EDIT_FORCE_BOT
Definition: Defines.php:129
Maintenance\hasOption
hasOption( $name)
Checks to see if a particular option was set.
Definition: Maintenance.php:271
CleanupSpam\execute
execute()
Do the actual work.
Definition: cleanupSpam.php:49
Maintenance\getArg
getArg( $argId=0, $default=null)
Get an argument.
Definition: Maintenance.php:353
$IP
$IP
Definition: WebStart.php:49
Title\newFromID
static newFromID( $id, $flags=0)
Create a new Title from an article ID.
Definition: Title.php:561
MediaWiki\Revision\SlotRecord
Value object representing a content slot associated with a page revision.
Definition: SlotRecord.php:40