MediaWiki REL1_39
cleanupSpam.php
Go to the documentation of this file.
1<?php
28
29require_once __DIR__ . '/Maintenance.php';
30
36class 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' );
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->newSelectQueryBuilder()
82 ->select( 'COUNT(*)' )
83 ->from( 'externallinks' )
84 ->where( $conds )
85 ->caller( __METHOD__ )
86 ->fetchField();
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->newSelectQueryBuilder()
110 ->select( 'el_from' )
111 ->distinct()
112 ->from( 'externallinks' )
113 ->where( $conds )
114 ->caller( __METHOD__ )
115 ->fetchResultSet();
116 $count = $res->numRows();
117 $this->output( "Found $count articles containing $spec\n" );
118 foreach ( $res as $row ) {
119 $this->cleanupArticle(
120 $row->el_from,
121 $spec,
122 $prot,
123 $user
124 );
125 }
126 }
127 if ( $count ) {
128 $this->output( "Done\n" );
129 }
130 }
131 }
132
140 private function cleanupArticle( $id, $domain, $protocol, Authority $performer ) {
141 $title = Title::newFromID( $id );
142 if ( !$title ) {
143 $this->error( "Internal error: no page for ID $id" );
144
145 return;
146 }
147
148 $this->output( $title->getPrefixedDBkey() . " ..." );
149
150 $services = MediaWikiServices::getInstance();
151 $revLookup = $services->getRevisionLookup();
152 $rev = $revLookup->getRevisionByTitle( $title );
153 $currentRevId = $rev->getId();
154
155 while ( $rev && ( $rev->isDeleted( RevisionRecord::DELETED_TEXT ) ||
156 LinkFilter::matchEntry(
157 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable RAW never returns null
158 $rev->getContent( SlotRecord::MAIN, RevisionRecord::RAW ),
159 $domain,
160 $protocol
161 ) )
162 ) {
163 $rev = $revLookup->getPreviousRevision( $rev );
164 }
165
166 if ( $rev && $rev->getId() == $currentRevId ) {
167 // The regex didn't match the current article text
168 // This happens e.g. when a link comes from a template rather than the page itself
169 $this->output( "False match\n" );
170 } else {
171 $dbw = $this->getDB( DB_PRIMARY );
172 $this->beginTransaction( $dbw, __METHOD__ );
173 $page = $services->getWikiPageFactory()->newFromTitle( $title );
174 if ( $rev ) {
175 // Revert to this revision
176 $content = $rev->getContent( SlotRecord::MAIN, RevisionRecord::RAW );
177
178 $this->output( "reverting\n" );
179 $page->doUserEditContent(
180 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable RAW never returns null
181 $content,
182 $performer,
183 wfMessage( 'spam_reverting', $domain )->inContentLanguage()->text(),
185 $rev->getId()
186 );
187 } elseif ( $this->hasOption( 'delete' ) ) {
188 // Didn't find a non-spammy revision, blank the page
189 $this->output( "deleting\n" );
190 $page->doDeleteArticleReal(
191 wfMessage( 'spam_deleting', $domain )->inContentLanguage()->text(),
192 $performer->getUser()
193 );
194 } else {
195 // Didn't find a non-spammy revision, blank the page
196 $handler = $services->getContentHandlerFactory()
197 ->getContentHandler( $title->getContentModel() );
198 $content = $handler->makeEmptyContent();
199
200 $this->output( "blanking\n" );
201 $page->doUserEditContent(
202 $content,
203 $performer,
204 wfMessage( 'spam_blanking', $domain )->inContentLanguage()->text(),
206 );
207 }
208 $this->commitTransaction( $dbw, __METHOD__ );
209 }
210 }
211}
212
213$maintClass = CleanupSpam::class;
214require_once RUN_MAINTENANCE_IF_MAIN;
getDB()
const EDIT_FORCE_BOT
Definition Defines.php:130
const EDIT_UPDATE
Definition Defines.php:127
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:91
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)
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.
Service locator for MediaWiki core services.
Page revision base class.
Value object representing a content slot associated with a page revision.
static setUser( $user)
Reset the stub global user to a different "real" user object, while ensuring that any method calls on...
static newSystemUser( $name, $options=[])
Static factory method for creation of a "system" user from username.
Definition User.php:806
$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