MediaWiki master
cleanupSpam.php
Go to the documentation of this file.
1<?php
20
21// @codeCoverageIgnoreStart
22require_once __DIR__ . '/Maintenance.php';
23// @codeCoverageIgnoreEnd
24
30class CleanupSpam extends Maintenance {
31
32 public function __construct() {
33 parent::__construct();
34 $this->addDescription( 'Cleanup all spam from a given hostname' );
35 $this->addOption( 'all', 'Check all wikis in $wgLocalDatabases' );
36 $this->addOption( 'delete', 'Delete pages containing only spam instead of blanking them' );
37 $this->addArg(
38 'hostname',
39 'Hostname that was spamming, single * wildcard in the beginning allowed'
40 );
41 }
42
43 public function execute() {
44 global $IP, $wgLocalDatabases;
45
46 $username = wfMessage( 'spambot_username' )->text();
47 $user = User::newSystemUser( $username );
48 if ( !$user ) {
49 $this->fatalError( "Invalid username specified in 'spambot_username' message: $username" );
50 }
51 // Hack: Grant bot rights so we don't flood RecentChanges
52 $this->getServiceContainer()->getUserGroupManager()->addUserToGroup( $user, 'bot' );
53 StubGlobalUser::setUser( $user );
54
55 $spec = $this->getArg( 0 );
56
57 $protConds = [];
58 foreach ( [ 'http://', 'https://' ] as $prot ) {
59 $conds = LinkFilter::getQueryConditions( $spec, [ 'protocol' => $prot ] );
60 if ( !$conds ) {
61 $this->fatalError( "Not a valid hostname specification: $spec" );
62 }
63 $protConds[$prot] = $conds;
64 }
65
66 if ( $this->hasOption( 'all' ) ) {
67 // Clean up spam on all wikis
68 $this->output( "Finding spam on " . count( $wgLocalDatabases ) . " wikis\n" );
69 $found = false;
70 foreach ( $wgLocalDatabases as $wikiId ) {
72 $dbr = $this->getDB( DB_REPLICA, [], $wikiId );
73
74 foreach ( $protConds as $conds ) {
75 $count = $dbr->newSelectQueryBuilder()
76 ->select( 'COUNT(*)' )
77 ->from( 'externallinks' )
78 ->where( $conds )
79 ->caller( __METHOD__ )
80 ->fetchField();
81 if ( $count ) {
82 $found = true;
83 $cmd = wfShellWikiCmd(
84 "$IP/maintenance/cleanupSpam.php",
85 [ '--wiki', $wikiId, $spec ]
86 );
87 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.passthru
88 passthru( "$cmd | sed 's/^/$wikiId: /'" );
89 }
90 }
91 }
92 if ( $found ) {
93 $this->output( "All done\n" );
94 } else {
95 $this->output( "None found\n" );
96 }
97 } else {
98 // Clean up spam on this wiki
99
100 $count = 0;
101 $dbr = $this->getServiceContainer()->getConnectionProvider()->getReplicaDatabase(
102 ExternalLinksTable::VIRTUAL_DOMAIN
103 );
104 foreach ( $protConds as $prot => $conds ) {
105 $res = $dbr->newSelectQueryBuilder()
106 ->select( 'el_from' )
107 ->distinct()
108 ->from( 'externallinks' )
109 ->where( $conds )
110 ->caller( __METHOD__ )
111 ->fetchResultSet();
112 $count += $res->numRows();
113 $this->output( "Found $count articles containing $spec so far...\n" );
114 foreach ( $res as $row ) {
115 $this->beginTransactionRound( __METHOD__ );
116 $this->cleanupArticle(
117 $row->el_from,
118 $spec,
119 $prot,
120 $user
121 );
122 $this->commitTransactionRound( __METHOD__ );
123 }
124 }
125 if ( $count ) {
126 $this->output( "Done\n" );
127 }
128 }
129 }
130
137 private function cleanupArticle( $id, $domain, $protocol, Authority $performer ) {
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 $services = $this->getServiceContainer();
148 $revLookup = $services->getRevisionLookup();
149 $rev = $revLookup->getRevisionByTitle( $title );
150 $currentRevId = $rev->getId();
151
152 while ( $rev && ( $rev->isDeleted( RevisionRecord::DELETED_TEXT ) ||
153 LinkFilter::matchEntry(
154 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable RAW never returns null
155 $rev->getContent( SlotRecord::MAIN, RevisionRecord::RAW ),
156 $domain,
157 $protocol
158 ) )
159 ) {
160 $rev = $revLookup->getPreviousRevision( $rev );
161 }
162
163 if ( $rev && $rev->getId() == $currentRevId ) {
164 // The regex didn't match the current article text
165 // This happens e.g. when a link comes from a template rather than the page itself
166 $this->output( "False match\n" );
167 } else {
168 $page = $services->getWikiPageFactory()->newFromTitle( $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->doUserEditContent(
175 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable RAW never returns null
176 $content,
177 $performer,
178 wfMessage( 'spam_reverting', $domain )->inContentLanguage()->text(),
180 $rev->getId()
181 );
182 } elseif ( $this->hasOption( 'delete' ) ) {
183 // Didn't find a non-spammy revision, blank the page
184 $this->output( "deleting\n" );
185 $deletePage = $services->getDeletePageFactory()->newDeletePage( $page, $performer );
186 $deletePage->deleteUnsafe( wfMessage( 'spam_deleting', $domain )->inContentLanguage()->text() );
187 } else {
188 // Didn't find a non-spammy revision, blank the page
189 $handler = $services->getContentHandlerFactory()
190 ->getContentHandler( $title->getContentModel() );
191 $content = $handler->makeEmptyContent();
192
193 $this->output( "blanking\n" );
194 $page->doUserEditContent(
195 $content,
196 $performer,
197 wfMessage( 'spam_blanking', $domain )->inContentLanguage()->text(),
199 );
200 }
201 }
202 }
203}
204
205// @codeCoverageIgnoreStart
206$maintClass = CleanupSpam::class;
207require_once RUN_MAINTENANCE_IF_MAIN;
208// @codeCoverageIgnoreEnd
const EDIT_FORCE_BOT
Mark the edit a "bot" edit regardless of user rights.
Definition Defines.php:129
const EDIT_UPDATE
Article is assumed to be pre-existing, fail if it doesn't exist.
Definition Defines.php:117
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.
const DB_REPLICA
Definition defines.php:26
if(!defined('MEDIAWIKI')) if(!defined( 'MW_ENTRY_POINT')) global $IP
Environment checks.
Definition Setup.php:90
Maintenance script to cleanup all spam from a given hostname.
__construct()
Default constructor.
execute()
Do the actual work.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
addArg( $arg, $description, $required=true, $multi=false)
Add some args that are needed.
getArg( $argId=0, $default=null)
Get an argument.
output( $out, $channel=null)
Throw some output to the user.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
getDB( $db, $groups=[], $dbDomain=false)
Returns a database to be used by current maintenance script.
hasOption( $name)
Checks to see if a particular option was set.
commitTransactionRound( $fname)
Commit a transactional batch of DB operations and wait for replica DB servers to catch up.
beginTransactionRound( $fname)
Start a transactional batch of DB operations.
error( $err, $die=0)
Throw an error to the user.
getServiceContainer()
Returns the main service container.
addDescription( $text)
Set the description text.
Page revision base class.
Value object representing a content slot associated with a page revision.
Stub object for the global user ($wgUser) that makes it possible to change the relevant underlying ob...
Represents a title within MediaWiki.
Definition Title.php:69
User class for the MediaWiki software.
Definition User.php:108
$maintClass
$wgLocalDatabases
Config variable stub for the LocalDatabases setting, for use by phpdoc and IDEs.
This interface represents the authority associated with the current execution context,...
Definition Authority.php:23