MediaWiki REL1_31
cleanupSpam.php
Go to the documentation of this file.
1<?php
24require_once __DIR__ . '/Maintenance.php';
25
31class CleanupSpam extends Maintenance {
32
33 public function __construct() {
34 parent::__construct();
35 $this->addDescription( 'Cleanup all spam from a given hostname' );
36 $this->addOption( 'all', 'Check all wikis in $wgLocalDatabases' );
37 $this->addOption( 'delete', 'Delete pages containing only spam instead of blanking them' );
38 $this->addArg(
39 'hostname',
40 'Hostname that was spamming, single * wildcard in the beginning allowed'
41 );
42 }
43
44 public function execute() {
46
47 $username = wfMessage( 'spambot_username' )->text();
49 if ( !$wgUser ) {
50 $this->fatalError( "Invalid username specified in 'spambot_username' message: $username" );
51 }
52 // Hack: Grant bot rights so we don't flood RecentChanges
53 $wgUser->addGroup( 'bot' );
54
55 $spec = $this->getArg();
56 $like = LinkFilter::makeLikeArray( $spec );
57 if ( !$like ) {
58 $this->fatalError( "Not a valid hostname specification: $spec" );
59 }
60
61 if ( $this->hasOption( 'all' ) ) {
62 // Clean up spam on all wikis
63 $this->output( "Finding spam on " . count( $wgLocalDatabases ) . " wikis\n" );
64 $found = false;
65 foreach ( $wgLocalDatabases as $wikiID ) {
66 $dbr = $this->getDB( DB_REPLICA, [], $wikiID );
67
68 $count = $dbr->selectField( 'externallinks', 'COUNT(*)',
69 [ 'el_index' . $dbr->buildLike( $like ) ], __METHOD__ );
70 if ( $count ) {
71 $found = true;
72 $cmd = wfShellWikiCmd( "$IP/maintenance/cleanupSpam.php",
73 [ '--wiki', $wikiID, $spec ] );
74 passthru( "$cmd | sed 's/^/$wikiID: /'" );
75 }
76 }
77 if ( $found ) {
78 $this->output( "All done\n" );
79 } else {
80 $this->output( "None found\n" );
81 }
82 } else {
83 // Clean up spam on this wiki
84
85 $dbr = $this->getDB( DB_REPLICA );
86 $res = $dbr->select( 'externallinks', [ 'DISTINCT el_from' ],
87 [ 'el_index' . $dbr->buildLike( $like ) ], __METHOD__ );
88 $count = $dbr->numRows( $res );
89 $this->output( "Found $count articles containing $spec\n" );
90 foreach ( $res as $row ) {
91 $this->cleanupArticle( $row->el_from, $spec );
92 }
93 if ( $count ) {
94 $this->output( "Done\n" );
95 }
96 }
97 }
98
99 private function cleanupArticle( $id, $domain ) {
100 $title = Title::newFromID( $id );
101 if ( !$title ) {
102 $this->error( "Internal error: no page for ID $id" );
103
104 return;
105 }
106
107 $this->output( $title->getPrefixedDBkey() . " ..." );
108 $rev = Revision::newFromTitle( $title );
109 $currentRevId = $rev->getId();
110
111 while ( $rev && ( $rev->isDeleted( Revision::DELETED_TEXT )
112 || LinkFilter::matchEntry( $rev->getContent( Revision::RAW ), $domain ) )
113 ) {
114 $rev = $rev->getPrevious();
115 }
116
117 if ( $rev && $rev->getId() == $currentRevId ) {
118 // The regex didn't match the current article text
119 // This happens e.g. when a link comes from a template rather than the page itself
120 $this->output( "False match\n" );
121 } else {
122 $dbw = $this->getDB( DB_MASTER );
123 $this->beginTransaction( $dbw, __METHOD__ );
124 $page = WikiPage::factory( $title );
125 if ( $rev ) {
126 // Revert to this revision
127 $content = $rev->getContent( Revision::RAW );
128
129 $this->output( "reverting\n" );
130 $page->doEditContent(
131 $content,
132 wfMessage( 'spam_reverting', $domain )->inContentLanguage()->text(),
134 $rev->getId()
135 );
136 } elseif ( $this->hasOption( 'delete' ) ) {
137 // Didn't find a non-spammy revision, blank the page
138 $this->output( "deleting\n" );
139 $page->doDeleteArticle(
140 wfMessage( 'spam_deleting', $domain )->inContentLanguage()->text()
141 );
142 } else {
143 // Didn't find a non-spammy revision, blank the page
144 $handler = ContentHandler::getForTitle( $title );
145 $content = $handler->makeEmptyContent();
146
147 $this->output( "blanking\n" );
148 $page->doEditContent(
149 $content,
150 wfMessage( 'spam_blanking', $domain )->inContentLanguage()->text(),
152 );
153 }
154 $this->commitTransaction( $dbw, __METHOD__ );
155 }
156 }
157}
158
159$maintClass = CleanupSpam::class;
160require_once RUN_MAINTENANCE_IF_MAIN;
$wgLocalDatabases
Other wikis on this site, can be administered from a single developer account.
wfShellWikiCmd( $script, array $parameters=[], array $options=[])
Generate a shell-escaped command line string to run a MediaWiki cli script.
$wgUser
Definition Setup.php:902
Maintenance script to cleanup all spam from a given hostname.
cleanupArticle( $id, $domain)
__construct()
Default constructor.
execute()
Do the actual work.
static makeLikeArray( $filterEntry, $protocol='http://')
Make an array to be used for calls to Database::buildLike(), which will match the specified string.
static matchEntry(Content $content, $filterEntry)
Check whether $content contains a link to $filterEntry.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
addArg( $arg, $description, $required=true)
Add some args that are needed.
beginTransaction(IDatabase $dbw, $fname)
Begin a transcation on a DB.
commitTransaction(IDatabase $dbw, $fname)
Commit the transcation on a DB handle and wait for replica DBs to catch up.
getDB( $db, $groups=[], $wiki=false)
Returns a database to be used by current maintenance script.
hasOption( $name)
Checks to see if a particular param exists.
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.
static newSystemUser( $name, $options=[])
Static factory method for creation of a "system" user from username.
Definition User.php:791
$maintClass
$res
Definition database.txt:21
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add in any and then calling output() to send it all. It could be easily changed to send incrementally if that becomes useful
design txt This is a brief overview of the new design More thorough and up to date information is available on the documentation wiki at etc Handles the details of getting and saving to the user table of the and dealing with sessions and cookies OutputPage Encapsulates the entire HTML page that will be sent in response to any server request It is used by calling its functions to add text
Definition design.txt:18
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults error
Definition hooks.txt:2612
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "&lt;div ...>$1&lt;/div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
this hook is for auditing only or null if authentication failed before getting that far $username
Definition hooks.txt:785
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable modifiable after all normalizations have been except for the $wgMaxImageArea check set to true or false to override the $wgMaxImageArea check result gives extension the possibility to transform it themselves $handler
Definition hooks.txt:903
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
Definition hooks.txt:1777
$IP
Definition update.php:3
const EDIT_FORCE_BOT
Definition Defines.php:166
const EDIT_UPDATE
Definition Defines.php:163
require_once RUN_MAINTENANCE_IF_MAIN
const DB_REPLICA
Definition defines.php:25
const DB_MASTER
Definition defines.php:29