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