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