MediaWiki master
cleanupSpam.php
Go to the documentation of this file.
1<?php
31
32require_once __DIR__ . '/Maintenance.php';
33
39class CleanupSpam extends Maintenance {
40
41 public function __construct() {
42 parent::__construct();
43 $this->addDescription( 'Cleanup all spam from a given hostname' );
44 $this->addOption( 'all', 'Check all wikis in $wgLocalDatabases' );
45 $this->addOption( 'delete', 'Delete pages containing only spam instead of blanking them' );
46 $this->addArg(
47 'hostname',
48 'Hostname that was spamming, single * wildcard in the beginning allowed'
49 );
50 }
51
52 public function execute() {
53 global $IP, $wgLocalDatabases;
54
55 $username = wfMessage( 'spambot_username' )->text();
56 $user = User::newSystemUser( $username );
57 if ( !$user ) {
58 $this->fatalError( "Invalid username specified in 'spambot_username' message: $username" );
59 }
60 // Hack: Grant bot rights so we don't flood RecentChanges
61 $this->getServiceContainer()->getUserGroupManager()->addUserToGroup( $user, 'bot' );
62 StubGlobalUser::setUser( $user );
63
64 $spec = $this->getArg( 0 );
65
66 $protConds = [];
67 foreach ( [ 'http://', 'https://' ] as $prot ) {
68 $conds = LinkFilter::getQueryConditions( $spec, [ 'protocol' => $prot ] );
69 if ( !$conds ) {
70 $this->fatalError( "Not a valid hostname specification: $spec" );
71 }
72 $protConds[$prot] = $conds;
73 }
74
75 if ( $this->hasOption( 'all' ) ) {
76 // Clean up spam on all wikis
77 $this->output( "Finding spam on " . count( $wgLocalDatabases ) . " wikis\n" );
78 $found = false;
79 foreach ( $wgLocalDatabases as $wikiId ) {
81 $dbr = $this->getDB( DB_REPLICA, [], $wikiId );
82
83 foreach ( $protConds as $conds ) {
84 $count = $dbr->newSelectQueryBuilder()
85 ->select( 'COUNT(*)' )
86 ->from( 'externallinks' )
87 ->where( $conds )
88 ->caller( __METHOD__ )
89 ->fetchField();
90 if ( $count ) {
91 $found = true;
92 $cmd = wfShellWikiCmd(
93 "$IP/maintenance/cleanupSpam.php",
94 [ '--wiki', $wikiId, $spec ]
95 );
96 // phpcs:ignore MediaWiki.Usage.ForbiddenFunctions.passthru
97 passthru( "$cmd | sed 's/^/$wikiId: /'" );
98 }
99 }
100 }
101 if ( $found ) {
102 $this->output( "All done\n" );
103 } else {
104 $this->output( "None found\n" );
105 }
106 } else {
107 // Clean up spam on this wiki
108
109 $count = 0;
111 $dbr = $this->getReplicaDB();
112 foreach ( $protConds as $prot => $conds ) {
113 $res = $dbr->newSelectQueryBuilder()
114 ->select( 'el_from' )
115 ->distinct()
116 ->from( 'externallinks' )
117 ->where( $conds )
118 ->caller( __METHOD__ )
119 ->fetchResultSet();
120 $count += $res->numRows();
121 $this->output( "Found $count articles containing $spec so far...\n" );
122 foreach ( $res as $row ) {
123 $this->cleanupArticle(
124 $row->el_from,
125 $spec,
126 $prot,
127 $user
128 );
129 }
130 }
131 if ( $count ) {
132 $this->output( "Done\n" );
133 }
134 }
135 }
136
143 private function cleanupArticle( $id, $domain, $protocol, Authority $performer ) {
144 $title = Title::newFromID( $id );
145 if ( !$title ) {
146 $this->error( "Internal error: no page for ID $id" );
147
148 return;
149 }
150
151 $this->output( $title->getPrefixedDBkey() . " ..." );
152
153 $services = $this->getServiceContainer();
154 $revLookup = $services->getRevisionLookup();
155 $rev = $revLookup->getRevisionByTitle( $title );
156 $currentRevId = $rev->getId();
157
158 while ( $rev && ( $rev->isDeleted( RevisionRecord::DELETED_TEXT ) ||
159 LinkFilter::matchEntry(
160 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable RAW never returns null
161 $rev->getContent( SlotRecord::MAIN, RevisionRecord::RAW ),
162 $domain,
163 $protocol
164 ) )
165 ) {
166 $rev = $revLookup->getPreviousRevision( $rev );
167 }
168
169 if ( $rev && $rev->getId() == $currentRevId ) {
170 // The regex didn't match the current article text
171 // This happens e.g. when a link comes from a template rather than the page itself
172 $this->output( "False match\n" );
173 } else {
174 $dbw = $this->getPrimaryDB();
175 $this->beginTransaction( $dbw, __METHOD__ );
176 $page = $services->getWikiPageFactory()->newFromTitle( $title );
177 if ( $rev ) {
178 // Revert to this revision
179 $content = $rev->getContent( SlotRecord::MAIN, RevisionRecord::RAW );
180
181 $this->output( "reverting\n" );
182 $page->doUserEditContent(
183 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable RAW never returns null
184 $content,
185 $performer,
186 wfMessage( 'spam_reverting', $domain )->inContentLanguage()->text(),
188 $rev->getId()
189 );
190 } elseif ( $this->hasOption( 'delete' ) ) {
191 // Didn't find a non-spammy revision, blank the page
192 $this->output( "deleting\n" );
193 $deletePage = $services->getDeletePageFactory()->newDeletePage( $page, $performer );
194 $deletePage->deleteUnsafe( wfMessage( 'spam_deleting', $domain )->inContentLanguage()->text() );
195 } else {
196 // Didn't find a non-spammy revision, blank the page
197 $handler = $services->getContentHandlerFactory()
198 ->getContentHandler( $title->getContentModel() );
199 $content = $handler->makeEmptyContent();
200
201 $this->output( "blanking\n" );
202 $page->doUserEditContent(
203 $content,
204 $performer,
205 wfMessage( 'spam_blanking', $domain )->inContentLanguage()->text(),
207 );
208 }
209 $this->commitTransaction( $dbw, __METHOD__ );
210 }
211 }
212}
213
214$maintClass = CleanupSpam::class;
215require_once RUN_MAINTENANCE_IF_MAIN;
getDB()
const EDIT_FORCE_BOT
Definition Defines.php:131
const EDIT_UPDATE
Definition Defines.php:128
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:99
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...
error( $err, $die=0)
Throw an error to the user.
addArg( $arg, $description, $required=true, $multi=false)
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.
getServiceContainer()
Returns the main service container.
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.
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:78
internal since 1.36
Definition User.php:93
$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:37
const DB_REPLICA
Definition defines.php:26