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