Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
0.00% covered (danger)
0.00%
0 / 114
0.00% covered (danger)
0.00%
0 / 3
CRAP
0.00% covered (danger)
0.00%
0 / 1
CleanupSpam
0.00% covered (danger)
0.00%
0 / 111
0.00% covered (danger)
0.00%
0 / 3
506
0.00% covered (danger)
0.00%
0 / 1
 __construct
0.00% covered (danger)
0.00%
0 / 8
0.00% covered (danger)
0.00%
0 / 1
2
 execute
0.00% covered (danger)
0.00%
0 / 57
0.00% covered (danger)
0.00%
0 / 1
156
 cleanupArticle
0.00% covered (danger)
0.00%
0 / 46
0.00% covered (danger)
0.00%
0 / 1
90
1<?php
2/**
3 * Cleanup all spam from a given hostname.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Maintenance
22 */
23
24use MediaWiki\ExternalLinks\LinkFilter;
25use MediaWiki\Permissions\Authority;
26use MediaWiki\Revision\RevisionRecord;
27use MediaWiki\Revision\SlotRecord;
28use MediaWiki\StubObject\StubGlobalUser;
29use MediaWiki\Title\Title;
30use MediaWiki\User\User;
31use Wikimedia\Rdbms\Database;
32
33require_once __DIR__ . '/Maintenance.php';
34
35/**
36 * Maintenance script to cleanup all spam from a given hostname.
37 *
38 * @ingroup Maintenance
39 */
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 ) {
81                /** @var Database $dbr */
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;
111            /** @var Database $dbr */
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
138    /**
139     * @param int $id
140     * @param string $domain
141     * @param string $protocol
142     * @param Authority $performer
143     */
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(),
188                    EDIT_UPDATE | EDIT_FORCE_BOT,
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(),
207                    EDIT_UPDATE | EDIT_FORCE_BOT
208                );
209            }
210            $this->commitTransaction( $dbw, __METHOD__ );
211        }
212    }
213}
214
215$maintClass = CleanupSpam::class;
216require_once RUN_MAINTENANCE_IF_MAIN;