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;
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  StubGlobalUser::setUser( $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 = $res->numRows();
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  // @phan-suppress-next-line PhanTypeMismatchArgumentNullable RAW never returns null
157  $rev->getContent( SlotRecord::MAIN, RevisionRecord::RAW ),
158  $domain,
159  $protocol
160  ) )
161  ) {
162  $rev = $revLookup->getPreviousRevision( $rev );
163  }
164 
165  if ( $rev && $rev->getId() == $currentRevId ) {
166  // The regex didn't match the current article text
167  // This happens e.g. when a link comes from a template rather than the page itself
168  $this->output( "False match\n" );
169  } else {
170  $dbw = $this->getDB( DB_PRIMARY );
171  $this->beginTransaction( $dbw, __METHOD__ );
172  $page = $services->getWikiPageFactory()->newFromTitle( $title );
173  if ( $rev ) {
174  // Revert to this revision
175  $content = $rev->getContent( SlotRecord::MAIN, RevisionRecord::RAW );
176 
177  $this->output( "reverting\n" );
178  $page->doUserEditContent(
179  // @phan-suppress-next-line PhanTypeMismatchArgumentNullable RAW never returns null
180  $content,
181  $performer,
182  wfMessage( 'spam_reverting', $domain )->inContentLanguage()->text(),
184  $rev->getId()
185  );
186  } elseif ( $this->hasOption( 'delete' ) ) {
187  // Didn't find a non-spammy revision, blank the page
188  $this->output( "deleting\n" );
189  $page->doDeleteArticleReal(
190  wfMessage( 'spam_deleting', $domain )->inContentLanguage()->text(),
191  $performer->getUser()
192  );
193  } else {
194  // Didn't find a non-spammy revision, blank the page
195  $handler = $services->getContentHandlerFactory()
196  ->getContentHandler( $title->getContentModel() );
197  $content = $handler->makeEmptyContent();
198 
199  $this->output( "blanking\n" );
200  $page->doUserEditContent(
201  $content,
202  $performer,
203  wfMessage( 'spam_blanking', $domain )->inContentLanguage()->text(),
205  );
206  }
207  $this->commitTransaction( $dbw, __METHOD__ );
208  }
209  }
210 }
211 
212 $maintClass = CleanupSpam::class;
213 require_once RUN_MAINTENANCE_IF_MAIN;
const EDIT_FORCE_BOT
Definition: Defines.php:129
const EDIT_UPDATE
Definition: Defines.php:126
wfShellWikiCmd( $script, array $parameters=[], array $options=[])
Generate a shell-escaped command line string to run a MediaWiki cli script.
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
if(!defined( 'MEDIAWIKI')) if(ini_get( 'mbstring.func_overload')) if(!defined( 'MW_ENTRY_POINT')) global $IP
Environment checks.
Definition: Setup.php:90
Maintenance script to cleanup all spam from a given hostname.
Definition: cleanupSpam.php:36
__construct()
Default constructor.
Definition: cleanupSpam.php:38
cleanupArticle( $id, $domain, $protocol, Authority $performer)
execute()
Do the actual work.
Definition: cleanupSpam.php:49
static getQueryConditions( $filterEntry, array $options=[])
Return query conditions which will match the specified string.
Definition: LinkFilter.php:256
static matchEntry(Content $content, $filterEntry, $protocol='http://')
Check whether $content contains a link to $filterEntry.
Definition: LinkFilter.php:51
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: Maintenance.php:67
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
error( $err, $die=0)
Throw an error to the user.
addArg( $arg, $description, $required=true)
Add some args that are needed.
beginTransaction(IDatabase $dbw, $fname)
Begin a transaction on a DB.
commitTransaction(IDatabase $dbw, $fname)
Commit the transaction on a DB handle and wait for replica DBs to catch up.
output( $out, $channel=null)
Throw some output to the user.
hasOption( $name)
Checks to see if a particular option was set.
getArg( $argId=0, $default=null)
Get an argument.
addDescription( $text)
Set the description text.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
MediaWikiServices is the service locator for the application scope of MediaWiki.
Page revision base class.
Value object representing a content slot associated with a page revision.
Definition: SlotRecord.php:40
static setUser( $user)
Reset the stub global user to a different "real" user object, while ensuring that any method calls on...
static newFromID( $id, $flags=0)
Create a new Title from an article ID.
Definition: Title.php:518
static newSystemUser( $name, $options=[])
Static factory method for creation of a "system" user from username.
Definition: User.php:807
$maintClass
$wgLocalDatabases
Config variable stub for the LocalDatabases setting, for use by phpdoc and IDEs.
This interface represents the authority associated the current execution context, such as a web reque...
Definition: Authority.php:37
getUser()
Returns the performer of the actions associated with this authority.
const DB_REPLICA
Definition: defines.php:26
const DB_PRIMARY
Definition: defines.php:28
$content
Definition: router.php:76