MediaWiki  1.29.2
SpamBlacklistHooks.php
Go to the documentation of this file.
1 <?php
2 
4 
9 
10  public static function registerExtension() {
11  global $wgDisableAuthManager, $wgAuthManagerAutoConfig;
12 
13  if ( class_exists( AuthManager::class ) && !$wgDisableAuthManager ) {
14  $wgAuthManagerAutoConfig['preauth'][SpamBlacklistPreAuthenticationProvider::class] =
16  } else {
17  Hooks::register( 'AbortNewAccount', 'SpamBlacklistHooks::abortNewAccount' );
18  }
19  }
20 
33  static function filterMergedContent( IContextSource $context, Content $content, Status $status, $summary, User $user, $minoredit ) {
35 
36  // get the link from the not-yet-saved page content.
37  $editInfo = $context->getWikiPage()->prepareContentForEdit( $content );
38  $pout = $editInfo->output;
39  $links = array_keys( $pout->getExternalLinks() );
40 
41  // HACK: treat the edit summary as a link if it contains anything
42  // that looks like it could be a URL or e-mail address.
43  if ( preg_match( '/\S(\.[^\s\d]{2,}|[\/@]\S)/', $summary ) ) {
44  $links[] = $summary;
45  }
46 
47  $spamObj = BaseBlacklist::getInstance( 'spam' );
48  $matches = $spamObj->filter( $links, $title );
49 
50  if ( $matches !== false ) {
51  $status->fatal( 'spamprotectiontext' );
52 
53  foreach ( $matches as $match ) {
54  $status->fatal( 'spamprotectionmatch', $match );
55  }
56 
57  $status->apiHookResult = [
58  'spamblacklist' => implode( '|', $matches ),
59  ];
60  }
61 
62  // Always return true, EditPage will look at $status->isOk().
63  return true;
64  }
65 
66  public static function onParserOutputStashForEdit(
68  ) {
69  $links = array_keys( $output->getExternalLinks() );
70  $spamObj = BaseBlacklist::getInstance( 'spam' );
71  $spamObj->warmCachesForFilter( $page->getTitle(), $links );
72  }
73 
81  public static function userCanSendEmail( &$user, &$hookErr ) {
83  $blacklist = BaseBlacklist::getInstance( 'email' );
84  if ( $blacklist->checkUser( $user ) ) {
85  return true;
86  }
87 
88  $hookErr = array( 'spam-blacklisted-email', 'spam-blacklisted-email-text', null );
89 
90  return false;
91  }
92 
100  public static function abortNewAccount( $user, &$abortError ) {
102  $blacklist = BaseBlacklist::getInstance( 'email' );
103  if ( $blacklist->checkUser( $user ) ) {
104  return true;
105  }
106 
107  $abortError = wfMessage( 'spam-blacklisted-email-signup' )->escaped();
108  return false;
109  }
110 
122  static function validate( $editPage, $text, $section, &$hookError ) {
123  $thisPageName = $editPage->mTitle->getPrefixedDBkey();
124 
125  if( !BaseBlacklist::isLocalSource( $editPage->mTitle ) ) {
126  wfDebugLog( 'SpamBlacklist', "Spam blacklist validator: [[$thisPageName]] not a local blacklist\n" );
127  return true;
128  }
129 
130  $type = BaseBlacklist::getTypeFromTitle( $editPage->mTitle );
131  if ( $type === false ) {
132  return true;
133  }
134 
135  $lines = explode( "\n", $text );
136 
138  if( $badLines ) {
139  wfDebugLog( 'SpamBlacklist', "Spam blacklist validator: [[$thisPageName]] given invalid input lines: " .
140  implode( ', ', $badLines ) . "\n" );
141 
142  $badList = "*<code>" .
143  implode( "</code>\n*<code>",
144  array_map( 'wfEscapeWikiText', $badLines ) ) .
145  "</code>\n";
146  $hookError =
147  "<div class='errorbox'>" .
148  wfMessage( 'spam-invalid-lines' )->numParams( $badLines )->text() . "<br />" .
149  $badList .
150  "</div>\n" .
151  "<br clear='all' />\n";
152  } else {
153  wfDebugLog( 'SpamBlacklist', "Spam blacklist validator: [[$thisPageName]] ok or empty blacklist\n" );
154  }
155 
156  return true;
157  }
158 
177  static function pageSaveContent(
178  Page $wikiPage,
179  User $user,
181  $summary,
182  $isMinor,
183  $isWatch,
184  $section,
185  $flags,
186  $revision,
187  Status $status,
188  $baseRevId
189  ) {
190  if ( $revision ) {
192  ->doLogging( $user, $wikiPage->getTitle(), $revision->getId() );
193  }
194 
195  if ( !BaseBlacklist::isLocalSource( $wikiPage->getTitle() ) ) {
196  return true;
197  }
198 
199  // This sucks because every Blacklist needs to be cleared
200  foreach ( BaseBlacklist::getBlacklistTypes() as $type => $class ) {
201  $blacklist = BaseBlacklist::getInstance( $type );
202  $blacklist->clearCache();
203  }
204 
205 
206  return true;
207  }
208 
218  public static function onUploadVerifyUpload( UploadBase $upload, User $user, array $props, $comment, $pageText, &$error ) {
219  $title = $upload->getTitle();
220 
221  // get the link from the not-yet-saved page content.
223  $parserOptions = $content->getContentHandler()->makeParserOptions( 'canonical' );
224  $output = $content->getParserOutput( $title, null, $parserOptions );
225  $links = array_keys( $output->getExternalLinks() );
226 
227  // HACK: treat comment as a link if it contains anything
228  // that looks like it could be a URL or e-mail address.
229  if ( preg_match( '/\S(\.[^\s\d]{2,}|[\/@]\S)/', $comment ) ) {
230  $links[] = $comment;
231  }
232  if ( !$links ) {
233  return true;
234  }
235 
236  $spamObj = BaseBlacklist::getInstance( 'spam' );
237  $matches = $spamObj->filter( $links, $title );
238 
239  if ( $matches !== false ) {
240  $error = new ApiMessage(
241  wfMessage( 'spamprotectiontext' ),
242  'spamblacklist',
243  array(
244  'spamblacklist' => array( 'matches' => $matches ),
245  'message' => array(
246  'key' => 'spamprotectionmatch',
247  'params' => $matches[0],
248  ),
249  )
250  );
251  }
252 
253  return true;
254  }
255 
262  public static function onArticleDelete( WikiPage &$article, User &$user, &$reason, &$error ) {
264  $spam = BaseBlacklist::getInstance( 'spam' );
265  if ( !$spam->isLoggingEnabled() ) {
266  return;
267  }
268 
269  // Log the changes, but we only commit them once the deletion has happened.
270  // We do that since the external links table could get cleared before the
271  // ArticleDeleteComplete hook runs
272  $spam->logUrlChanges( $spam->getCurrentLinks( $article->getTitle() ), [], [] );
273  }
274 
283  public static function onArticleDeleteComplete( &$page, User &$user, $reason,
284  $id, Content $content = null, LogEntry $logEntry
285  ) {
287  $spam = BaseBlacklist::getInstance( 'spam' );
288  $spam->doLogging( $user, $page->getTitle(), $page->getLatest() );
289  }
290 }
BaseBlacklist\getBlacklistTypes
static getBlacklistTypes()
Return the array of blacklist types currently defined.
Definition: BaseBlacklist.php:89
Page
Interface for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
Definition: Page.php:24
$context
error also a ContextSource you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
Definition: hooks.txt:2612
SpamBlacklistHooks\onArticleDeleteComplete
static onArticleDeleteComplete(&$page, User &$user, $reason, $id, Content $content=null, LogEntry $logEntry)
Definition: SpamBlacklistHooks.php:283
BaseBlacklist\getInstance
static getInstance( $type)
Returns an instance of the given blacklist.
Definition: BaseBlacklist.php:100
ParserOutput
Definition: ParserOutput.php:24
SpamBlacklistHooks\validate
static validate( $editPage, $text, $section, &$hookError)
Hook function for EditFilter Confirm that a local blacklist page being saved is valid,...
Definition: SpamBlacklistHooks.php:122
SpamBlacklistHooks\pageSaveContent
static pageSaveContent(Page $wikiPage, User $user, Content $content, $summary, $isMinor, $isWatch, $section, $flags, $revision, Status $status, $baseRevId)
Hook function for PageContentSaveComplete Clear local spam blacklist caches on page save.
Definition: SpamBlacklistHooks.php:177
$status
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 $status
Definition: hooks.txt:1049
use
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
Definition: MIT-LICENSE.txt:10
$user
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a account $user
Definition: hooks.txt:246
WikiPage
Class representing a MediaWiki article and history.
Definition: WikiPage.php:36
BaseBlacklist\isLocalSource
static isLocalSource(Title $title)
Check if the given local page title is a spam regex source.
Definition: BaseBlacklist.php:133
BaseBlacklist\getTypeFromTitle
static getTypeFromTitle(Title $title)
Returns the type of blacklist from the given title.
Definition: BaseBlacklist.php:185
$type
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 my talk my contributions etc etc otherwise the built in rate limiting checks are if enabled allows for interception of redirect as a string mapping parameter names to values & $type
Definition: hooks.txt:2536
SpamRegexBatch\getBadLines
static getBadLines( $lines, BaseBlacklist $blacklist)
Returns an array of invalid lines.
Definition: SpamRegexBatch.php:118
ContextSource\getTitle
getTitle()
Get the Title object.
Definition: ContextSource.php:88
wfDebugLog
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
Definition: GlobalFunctions.php:1092
SpamBlacklistHooks\filterMergedContent
static filterMergedContent(IContextSource $context, Content $content, Status $status, $summary, User $user, $minoredit)
Hook function for EditFilterMergedContent.
Definition: SpamBlacklistHooks.php:33
php
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
SpamBlacklistHooks\onArticleDelete
static onArticleDelete(WikiPage &$article, User &$user, &$reason, &$error)
Definition: SpamBlacklistHooks.php:262
ApiMessage
Extension of Message implementing IApiMessage.
Definition: ApiMessage.php:198
Status
Generic operation result class Has warning/error list, boolean status and arbitrary value.
Definition: Status.php:40
$title
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:934
LogEntry
Interface for log entries.
Definition: LogEntry.php:38
$content
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
$page
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
$matches
$matches
Definition: NoLocalSettings.php:24
ContextSource\getWikiPage
getWikiPage()
Get the WikiPage object.
Definition: ContextSource.php:113
SpamBlacklistHooks\onParserOutputStashForEdit
static onParserOutputStashForEdit(WikiPage $page, Content $content, ParserOutput $output)
Definition: SpamBlacklistHooks.php:66
$lines
$lines
Definition: router.php:67
$output
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 as context as context the output can only depend on parameters provided to this hook not on global state indicating whether full HTML should be generated If generation of HTML may be but other information should still be present in the ParserOutput object & $output
Definition: hooks.txt:1049
global
when a variable name is used in a it is silently declared as a new masking the global
Definition: design.txt:93
ContentHandler\makeContent
static makeContent( $text, Title $title=null, $modelId=null, $format=null)
Convenience function for creating a Content object from a given textual representation.
Definition: ContentHandler.php:129
Hooks\register
static register( $name, $callback)
Attach an event handler to a given hook.
Definition: Hooks.php:49
SpamBlacklistHooks\abortNewAccount
static abortNewAccount( $user, &$abortError)
Processes new accounts for valid email addresses.
Definition: SpamBlacklistHooks.php:100
SpamBlacklistHooks\onUploadVerifyUpload
static onUploadVerifyUpload(UploadBase $upload, User $user, array $props, $comment, $pageText, &$error)
Definition: SpamBlacklistHooks.php:218
MediaWiki\Auth\AuthManager
This serves as the entry point to the authentication system.
Definition: AuthManager.php:82
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:55
Content
Base interface for content objects.
Definition: Content.php:34
SpamBlacklistHooks
Hooks for the spam blacklist extension.
Definition: SpamBlacklistHooks.php:8
$section
usually copyright or history_copyright This message must be in HTML not wikitext if the section is included from a template $section
Definition: hooks.txt:2929
as
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
$article
Using a hook running we can avoid having all this option specific stuff in our mainline code Using the function array $article
Definition: hooks.txt:78
wfMessage
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
class
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
SpamBlacklistHooks\userCanSendEmail
static userCanSendEmail(&$user, &$hookErr)
Verify that the user can send emails.
Definition: SpamBlacklistHooks.php:81
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:50
$flags
it s the revision text itself In either if gzip is the revision text is gzipped $flags
Definition: hooks.txt:2749
array
the array() calling protocol came about after MediaWiki 1.4rc1.
SpamBlacklistHooks\registerExtension
static registerExtension()
Definition: SpamBlacklistHooks.php:10