MediaWiki  master
cleanupSpam.php
Go to the documentation of this file.
1 <?php
24 require_once __DIR__ . '/Maintenance.php';
25 
31 class 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() {
45  global $IP, $wgLocalDatabases, $wgUser;
46 
47  $username = wfMessage( 'spambot_username' )->text();
48  $wgUser = User::newSystemUser( $username );
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( 0 );
56 
57  $protConds = [];
58  foreach ( [ 'http://', 'https://' ] as $prot ) {
59  $conds = LinkFilter::getQueryConditions( $spec, [ 'protocol' => $prot ] );
60  if ( !$conds ) {
61  $this->fatalError( "Not a valid hostname specification: $spec" );
62  }
63  $protConds[$prot] = $conds;
64  }
65 
66  if ( $this->hasOption( 'all' ) ) {
67  // Clean up spam on all wikis
68  $this->output( "Finding spam on " . count( $wgLocalDatabases ) . " wikis\n" );
69  $found = false;
70  foreach ( $wgLocalDatabases as $wikiID ) {
72  $dbr = $this->getDB( DB_REPLICA, [], $wikiID );
73 
74  foreach ( $protConds as $conds ) {
75  $count = $dbr->selectField(
76  'externallinks',
77  'COUNT(*)',
78  $conds,
79  __METHOD__
80  );
81  if ( $count ) {
82  $found = true;
83  $cmd = wfShellWikiCmd(
84  "$IP/maintenance/cleanupSpam.php",
85  [ '--wiki', $wikiID, $spec ]
86  );
87  passthru( "$cmd | sed 's/^/$wikiID: /'" );
88  }
89  }
90  }
91  if ( $found ) {
92  $this->output( "All done\n" );
93  } else {
94  $this->output( "None found\n" );
95  }
96  } else {
97  // Clean up spam on this wiki
98 
99  $count = 0;
101  $dbr = $this->getDB( DB_REPLICA );
102  foreach ( $protConds as $prot => $conds ) {
103  $res = $dbr->select(
104  'externallinks',
105  [ 'DISTINCT el_from' ],
106  $conds,
107  __METHOD__
108  );
109  $count = $dbr->numRows( $res );
110  $this->output( "Found $count articles containing $spec\n" );
111  foreach ( $res as $row ) {
112  $this->cleanupArticle( $row->el_from, $spec, $prot );
113  }
114  }
115  if ( $count ) {
116  $this->output( "Done\n" );
117  }
118  }
119  }
120 
127  private function cleanupArticle( $id, $domain, $protocol ) {
128  $title = Title::newFromID( $id );
129  if ( !$title ) {
130  $this->error( "Internal error: no page for ID $id" );
131 
132  return;
133  }
134 
135  $this->output( $title->getPrefixedDBkey() . " ..." );
137  $currentRevId = $rev->getId();
138 
139  while ( $rev && ( $rev->isDeleted( Revision::DELETED_TEXT )
140  || LinkFilter::matchEntry( $rev->getContent( Revision::RAW ), $domain, $protocol ) )
141  ) {
142  $rev = $rev->getPrevious();
143  }
144 
145  if ( $rev && $rev->getId() == $currentRevId ) {
146  // The regex didn't match the current article text
147  // This happens e.g. when a link comes from a template rather than the page itself
148  $this->output( "False match\n" );
149  } else {
150  $dbw = $this->getDB( DB_MASTER );
151  $this->beginTransaction( $dbw, __METHOD__ );
152  $page = WikiPage::factory( $title );
153  if ( $rev ) {
154  // Revert to this revision
155  $content = $rev->getContent( Revision::RAW );
156 
157  $this->output( "reverting\n" );
158  $page->doEditContent(
159  $content,
160  wfMessage( 'spam_reverting', $domain )->inContentLanguage()->text(),
162  $rev->getId()
163  );
164  } elseif ( $this->hasOption( 'delete' ) ) {
165  // Didn't find a non-spammy revision, blank the page
166  $this->output( "deleting\n" );
167  $page->doDeleteArticle(
168  wfMessage( 'spam_deleting', $domain )->inContentLanguage()->text()
169  );
170  } else {
171  // Didn't find a non-spammy revision, blank the page
173  $content = $handler->makeEmptyContent();
174 
175  $this->output( "blanking\n" );
176  $page->doEditContent(
177  $content,
178  wfMessage( 'spam_blanking', $domain )->inContentLanguage()->text(),
180  );
181  }
182  $this->commitTransaction( $dbw, __METHOD__ );
183  }
184  }
185 }
186 
188 require_once RUN_MAINTENANCE_IF_MAIN;
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:138
commitTransaction(IDatabase $dbw, $fname)
Commit the transcation on a DB handle and wait for replica DBs to catch up.
getArg( $argId=0, $default=null)
Get an argument.
static newFromID( $id, $flags=0)
Create a new Title from an article ID.
Definition: Title.php:470
error( $err, $die=0)
Throw an error to the user.
$IP
Definition: WebStart.php:41
wfShellWikiCmd( $script, array $parameters=[], array $options=[])
Generate a shell-escaped command line string to run a MediaWiki cli script.
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
cleanupArticle( $id, $domain, $protocol)
hasOption( $name)
Checks to see if a particular option exists.
const EDIT_UPDATE
Definition: Defines.php:149
require_once RUN_MAINTENANCE_IF_MAIN
Definition: maintenance.txt:50
Maintenance script to cleanup all spam from a given hostname.
Definition: cleanupSpam.php:31
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that&#39;s attached to a given link target...
Definition: Revision.php:137
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
const DB_MASTER
Definition: defines.php:26
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password 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:780
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 use $formDescriptor instead 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
$maintClass
const EDIT_FORCE_BOT
Definition: Defines.php:152
$res
Definition: database.txt:21
addDescription( $text)
Set the description text.
addArg( $arg, $description, $required=true)
Add some args that are needed.
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:925
getDB( $db, $groups=[], $wiki=false)
Returns a database to be used by current maintenance script.
static matchEntry(Content $content, $filterEntry, $protocol='http://')
Check whether $content contains a link to $filterEntry.
Definition: LinkFilter.php:49
output( $out, $channel=null)
Throw some output to the user.
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:1766
const RAW
Definition: Revision.php:56
static getForTitle(Title $title)
Returns the appropriate ContentHandler singleton for the given title.
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
const DELETED_TEXT
Definition: Revision.php:46
static getQueryConditions( $filterEntry, array $options=[])
Return query conditions which will match the specified string.
Definition: LinkFilter.php:254
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:780
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
Definition: maintenance.txt:52
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
const DB_REPLICA
Definition: defines.php:25
string [] $wgLocalDatabases
Other wikis on this site, can be administered from a single developer account.
fatalError( $msg, $exitCode=1)
Output a message and terminate the current script.
$content
Definition: pageupdater.txt:72
static newSystemUser( $name, $options=[])
Static factory method for creation of a "system" user from username.
Definition: User.php:831
beginTransaction(IDatabase $dbw, $fname)
Begin a transcation on a DB.