MediaWiki  1.29.1
Go to the documentation of this file.
1 <?php
24 require_once __DIR__ . '/Maintenance.php';
31 class CleanupSpam extends Maintenance {
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  }
44  public function execute() {
47  $username = wfMessage( 'spambot_username' )->text();
48  $wgUser = User::newSystemUser( $username );
49  if ( !$wgUser ) {
50  $this->error( "Invalid username specified in 'spambot_username' message: $username", true );
51  }
52  // Create the user if necessary
53  if ( !$wgUser->getId() ) {
54  $wgUser->addToDatabase();
55  }
56  $spec = $this->getArg();
57  $like = LinkFilter::makeLikeArray( $spec );
58  if ( !$like ) {
59  $this->error( "Not a valid hostname specification: $spec", true );
60  }
62  if ( $this->hasOption( 'all' ) ) {
63  // Clean up spam on all wikis
64  $this->output( "Finding spam on " . count( $wgLocalDatabases ) . " wikis\n" );
65  $found = false;
66  foreach ( $wgLocalDatabases as $wikiID ) {
67  $dbr = $this->getDB( DB_REPLICA, [], $wikiID );
69  $count = $dbr->selectField( 'externallinks', 'COUNT(*)',
70  [ 'el_index' . $dbr->buildLike( $like ) ], __METHOD__ );
71  if ( $count ) {
72  $found = true;
73  $cmd = wfShellWikiCmd( "$IP/maintenance/cleanupSpam.php",
74  [ '--wiki', $wikiID, $spec ] );
75  passthru( "$cmd | sed 's/^/$wikiID: /'" );
76  }
77  }
78  if ( $found ) {
79  $this->output( "All done\n" );
80  } else {
81  $this->output( "None found\n" );
82  }
83  } else {
84  // Clean up spam on this wiki
86  $dbr = $this->getDB( DB_REPLICA );
87  $res = $dbr->select( 'externallinks', [ 'DISTINCT el_from' ],
88  [ 'el_index' . $dbr->buildLike( $like ) ], __METHOD__ );
89  $count = $dbr->numRows( $res );
90  $this->output( "Found $count articles containing $spec\n" );
91  foreach ( $res as $row ) {
92  $this->cleanupArticle( $row->el_from, $spec );
93  }
94  if ( $count ) {
95  $this->output( "Done\n" );
96  }
97  }
98  }
100  private function cleanupArticle( $id, $domain ) {
101  $title = Title::newFromID( $id );
102  if ( !$title ) {
103  $this->error( "Internal error: no page for ID $id" );
105  return;
106  }
108  $this->output( $title->getPrefixedDBkey() . " ..." );
110  $currentRevId = $rev->getId();
112  while ( $rev && ( $rev->isDeleted( Revision::DELETED_TEXT )
113  || LinkFilter::matchEntry( $rev->getContent( Revision::RAW ), $domain ) )
114  ) {
115  $rev = $rev->getPrevious();
116  }
118  if ( $rev && $rev->getId() == $currentRevId ) {
119  // The regex didn't match the current article text
120  // This happens e.g. when a link comes from a template rather than the page itself
121  $this->output( "False match\n" );
122  } else {
123  $dbw = $this->getDB( DB_MASTER );
124  $this->beginTransaction( $dbw, __METHOD__ );
126  if ( $rev ) {
127  // Revert to this revision
128  $content = $rev->getContent( Revision::RAW );
130  $this->output( "reverting\n" );
131  $page->doEditContent(
132  $content,
133  wfMessage( 'spam_reverting', $domain )->inContentLanguage()->text(),
135  $rev->getId()
136  );
137  } elseif ( $this->hasOption( 'delete' ) ) {
138  // Didn't find a non-spammy revision, blank the page
139  $this->output( "deleting\n" );
140  $page->doDeleteArticle(
141  wfMessage( 'spam_deleting', $domain )->inContentLanguage()->text()
142  );
143  } else {
144  // Didn't find a non-spammy revision, blank the page
146  $content = $handler->makeEmptyContent();
148  $this->output( "blanking\n" );
149  $page->doEditContent(
150  $content,
151  wfMessage( 'spam_blanking', $domain )->inContentLanguage()->text()
152  );
153  }
154  $this->commitTransaction( $dbw, __METHOD__ );
155  }
156  }
157 }
159 $maintClass = "CleanupSpam";
160 require_once RUN_MAINTENANCE_IF_MAIN;
Definition: Setup.php:781
Maintenance script to cleanup all spam from a given hostname.
Definition: cleanupSpam.php:31
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:12
addDescription( $text)
Set the description text.
Definition: Maintenance.php:287
static matchEntry(Content $content, $filterEntry)
Check whether $content contains a link to $filterEntry.
Definition: LinkFilter.php:43
Definition: maintenance.txt:50
static getForTitle(Title $title)
Returns the appropriate ContentHandler singleton for the given title.
Definition: ContentHandler.php:240
Definition: database.txt:21
Abstract maintenance class for quickly writing and churning out maintenance scripts with minimal effo...
Definition: maintenance.txt:39
Definition: cleanupSpam.php:159
wfShellWikiCmd( $script, array $parameters=[], array $options=[])
Generate a shell-escaped command line string to run a MediaWiki cli script.
Definition: GlobalFunctions.php:2563
cleanupArticle( $id, $domain)
Definition: cleanupSpam.php:100
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
static newSystemUser( $name, $options=[])
Static factory method for creation of a "system" user from username.
Definition: User.php:684
beginTransaction(IDatabase $dbw, $fname)
Begin a transcation on a DB.
Definition: Maintenance.php:1278
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target.
Definition: Revision.php:134
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:934
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:120
this hook is for auditing only RecentChangesLinked and Watchlist RecentChangesLinked and Watchlist Do not use this to implement individual filters if they are compatible with the ChangesListFilter and ChangesListFilterGroup structure use sub classes of those in conjunction with the ChangesListSpecialPageStructuredFilters hook This hook can be used to implement filters that do not implement that or custom behavior that is not an individual filter e g Watchlist and Watchlist you will want to construct new ChangesListBooleanFilter or ChangesListStringOptionsFilter objects When constructing you specify which group they belong to You can reuse existing or create your you must register them with $special registerFilterGroup removed from all revisions and log entries to which it was applied This gives extensions a chance to take it off their books as the deletion has already been partly carried out by this point or something similar the user will be unable to create the tag set and then return false from the hook function Ensure you consume the ChangeTagAfterDelete hook to carry out custom deletion actions as context called by AbstractContent::getParserOutput May be used to override the normal model specific rendering of page content $content
Definition: hooks.txt:1049
do that in ParserLimitReportFormat instead use this to modify the parameters of the image and a DIV can begin in one section and end in another Make sure your code can handle that case gracefully See the EditSectionClearerLink extension for an example zero but section is usually empty its values are the globals values before the output is cached $page
Definition: hooks.txt:2536
addOption( $name, $description, $required=false, $withArg=false, $shortName=false, $multiOccurrence=false)
Add a parameter to the script.
Definition: Maintenance.php:215
Definition: update.php:3
static makeLikeArray( $filterEntry, $protocol='http://')
Make an array to be used for calls to Database::buildLike(), which will match the specified string.
Definition: LinkFilter.php:95
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
Definition: defines.php:25
Definition: defines.php:26
Other wikis on this site, can be administered from a single developer account.
Definition: DefaultSettings.php:2047
Definition: Defines.php:151
commitTransaction(IDatabase $dbw, $fname)
Commit the transcation on a DB handle and wait for replica DBs to catch up.
Definition: Maintenance.php:1293
const RAW
Definition: Revision.php:100
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:783
Default constructor.
Definition: cleanupSpam.php:33
if(! $regexes) $dbr
Definition: cleanup.php:94
addArg( $arg, $description, $required=true)
Add some args that are needed.
Definition: Maintenance.php:267
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:1741
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
getDB( $db, $groups=[], $wiki=false)
Returns a database to be used by current maintenance script.
Definition: Maintenance.php:1251
error( $err, $die=0)
Throw an error to the user.
Definition: Maintenance.php:392
output( $out, $channel=null)
Throw some output to the user.
Definition: Maintenance.php:373
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
hasOption( $name)
Checks to see if a particular param exists.
Definition: Maintenance.php:236
Do the actual work.
Definition: cleanupSpam.php:44
getArg( $argId=0, $default=null)
Get an argument.
Definition: Maintenance.php:306
static newFromID( $id, $flags=0)
Create a new Title from an article ID.
Definition: Title.php:405
this hook is for auditing only or null if authentication failed before getting that far $username
Definition: hooks.txt:783
Definition: Revision.php:90