Debian Codegraph @

extensions/TitleBlacklist/includes/TitleBlacklist.php

raw symbols SCIP
1 <?php
2 /**
3 * Title Blacklist class
4 * @author Victor Vasiliev
5 * @copyright © 2007-2010 Victor Vasiliev et al
6 * @license GPL-2.0-or-later
7 * @file
8 */
9
10 namespace MediaWiki\Extension\TitleBlacklist;
11
12 use BadMethodCallException;
13 use MediaWiki\Content\TextContent;
14 use MediaWiki\MediaWikiServices;
15 use MediaWiki\Title\Title;
16 use MediaWiki\User\User;
17 use Wikimedia\AtEase\AtEase;
18 use Wikimedia\ObjectCache\WANObjectCache;
19
20 /**
21 * @ingroup Extensions
22 */
23
24 /**
25 * Implements a title blacklist for MediaWiki
26 */
27 class TitleBlacklist {
28 /** @var TitleBlacklistEntry[]|null */
29 private $mBlacklist = null;
30
31 /** @var TitleBlacklistEntry[]|null */
32 private $mWhitelist = null;
33
34 /** @var TitleBlacklist|null */
35 protected static $instance = null;
36
37 /** Increase this to invalidate the cached copies of both blacklist and whitelist */
38 public const VERSION = 4;
39
40 /**
41 * Get an instance of this class
42 */
43 public static function singleton(): self {
44 self::$instance ??= new self();
45 return self::$instance;
46 }
47
48 /**
49 * Destroy/reset the current singleton instance.
50 *
51 * This is solely for testing and will fail unless MW_PHPUNIT_TEST is
52 * defined.
53 */
54 public static function destroySingleton() {
55 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
56 throw new BadMethodCallException(
57 'Can not invoke ' . __METHOD__ . '() ' .
58 'out of tests (MW_PHPUNIT_TEST not set).'
59 );
60 }
61
62 self::$instance = null;
63 }
64
65 /**
66 * Load all configured blacklist sources
67 */
68 public function load() {
69 global $wgTitleBlacklistSources, $wgTitleBlacklistCaching;
70
71 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
72 $this->mBlacklist = $cache->getWithSetCallback(
73 $cache->makeKey( 'title_blacklist_entries' ),
74 $wgTitleBlacklistCaching['expiry'],
75 static function () use ( $wgTitleBlacklistSources ) {
76 $sources = $wgTitleBlacklistSources;
77 $sources['local'] = [ 'type' => 'message' ];
78 $blacklist = [];
79 foreach ( $sources as $sourceName => $source ) {
80 $blacklist = array_merge(
81 $blacklist,
82 self::parseBlacklist(
83 self::getBlacklistText( $source ),
84 $sourceName
85 )
86 );
87 }
88
89 wfDebugLog( 'TitleBlacklist-cache',
90 'Regenerated blacklist with ' . count( $blacklist ) . ' entries.' );
91 return $blacklist;
92 },
93 [
94 'version' => self::VERSION,
95 'lockTSE' => 30,
96 'staleTTL' => WANObjectCache::TTL_DAY,
97 ]
98 );
99 }
100
101 /**
102 * Load local whitelist
103 */
104 public function loadWhitelist() {
105 global $wgTitleBlacklistCaching;
106
107 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
108 $this->mWhitelist = $cache->getWithSetCallback(
109 $cache->makeKey( 'title_whitelist_entries' ),
110 $wgTitleBlacklistCaching['expiry'],
111 static function () {
112 return self::parseBlacklist(
113 wfMessage( 'titlewhitelist' )->inContentLanguage()->text(),
114 'whitelist'
115 );
116 },
117 [
118 'version' => self::VERSION,
119 'lockTSE' => 30,
120 'staleTTL' => WANObjectCache::TTL_DAY,
121 ]
122 );
123 }
124
125 /**
126 * Get the text of a blacklist from a specified source
127 *
128 * @param array{type: string, src: ?string} $source A blacklist source from $wgTitleBlacklistSources
129 * @return string The content of the blacklist source as a string
130 */
131 private static function getBlacklistText( $source ) {
132 if ( !is_array( $source ) || !isset( $source['type'] ) ) {
133 // Return empty string in error case
134 return '';
135 }
136
137 if ( $source['type'] === 'message' ) {
138 return wfMessage( 'titleblacklist' )->inContentLanguage()->text();
139 }
140
141 $src = $source['src'] ?? null;
142 // All following types require the "src" element in the array
143 if ( !$src ) {
144 return '';
145 }
146
147 if ( $source['type'] === 'localpage' ) {
148 $title = Title::newFromText( $src );
149 if ( !$title ) {
150 return '';
151 }
152 if ( $title->inNamespace( NS_MEDIAWIKI ) ) {
153 $msg = wfMessage( $title->getText() )->inContentLanguage();
154 return $msg->isDisabled() ? '' : $msg->text();
155 } else {
156 $page = MediaWikiServices::getInstance()->getWikiPageFactory()->newFromTitle( $title );
157 if ( $page->exists() ) {
158 $content = $page->getContent();
159 return ( $content instanceof TextContent ) ? $content->getText() : "";
160 }
161 }
162 } elseif ( $source['type'] === 'url' ) {
163 return self::getHttp( $src );
164 } elseif ( $source['type'] === 'file' ) {
165 return file_exists( $src ) ? file_get_contents( $src ) : '';
166 }
167
168 return '';
169 }
170
171 /**
172 * Parse blacklist from a string
173 *
174 * @param string $list Text of a blacklist source
175 * @param string $sourceName
176 * @return TitleBlacklistEntry[]
177 */
178 public static function parseBlacklist( $list, $sourceName ) {
179 $lines = preg_split( "/\r?\n/", $list );
180 $result = [];
181 foreach ( $lines as $line ) {
182 $entry = TitleBlacklistEntry::newFromString( $line, $sourceName );
183 if ( $entry ) {
184 $result[] = $entry;
185 }
186 }
187
188 return $result;
189 }
190
191 /**
192 * Check whether the blacklist restricts given user
193 * performing a specific action on the given Title
194 *
195 * @param Title $title Title to check
196 * @param User $user User to check
197 * @param string $action Action to check; 'edit' if unspecified
198 * @param bool $override If set to true, overrides work
199 * @return TitleBlacklistEntry|bool The corresponding TitleBlacklistEntry if
200 * blacklisted; otherwise false
201 */
202 public function userCannot( $title, $user, $action = 'edit', $override = true ) {
203 $entry = $this->isBlacklisted( $title, $action );
204 if ( !$entry ) {
205 return false;
206 }
207 $params = $entry->getParams();
208 if ( isset( $params['autoconfirmed'] ) && $user->isAllowed( 'autoconfirmed' ) ) {
209 return false;
210 }
211 if ( $override && self::userCanOverride( $user, $action ) ) {
212 return false;
213 }
214 return $entry;
215 }
216
217 /**
218 * Check whether the blacklist restricts
219 * performing a specific action on the given Title
220 *
221 * @param Title $title Title to check
222 * @param string $action Action to check; 'edit' if unspecified
223 * @return TitleBlacklistEntry|bool The corresponding TitleBlacklistEntry if blacklisted;
224 * otherwise FALSE
225 */
226 public function isBlacklisted( $title, $action = 'edit' ) {
227 if ( !( $title instanceof Title ) ) {
228 $title = Title::newFromText( $title );
229 if ( !$title ) {
230 // The fact that the page name is invalid will stop whatever
231 // action is going through. No sense in doing more work here.
232 return false;
233 }
234 }
235
236 $autoconfirmedItem = null;
237 foreach ( $this->getBlacklist() as $item ) {
238 if ( $item->matches( $title->getFullText(), $action ) ) {
239 if ( $this->isWhitelisted( $title, $action ) ) {
240 return false;
241 }
242 if ( !isset( $item->getParams()['autoconfirmed'] ) ) {
243 return $item;
244 }
245 $autoconfirmedItem ??= $item;
246 }
247 }
248 return $autoconfirmedItem ?? false;
249 }
250
251 /**
252 * Check whether it has been explicitly whitelisted that the
253 * current User may perform a specific action on the given Title
254 *
255 * @param Title $title Title to check
256 * @param string $action Action to check; 'edit' if unspecified
257 * @return bool True if whitelisted; otherwise false
258 */
259 public function isWhitelisted( $title, $action = 'edit' ) {
260 if ( !( $title instanceof Title ) ) {
261 $title = Title::newFromText( $title );
262 if ( !$title ) {
263 return false;
264 }
265 }
266 $whitelist = $this->getWhitelist();
267 foreach ( $whitelist as $item ) {
268 if ( $item->matches( $title->getFullText(), $action ) ) {
269 return true;
270 }
271 }
272 return false;
273 }
274
275 /**
276 * Get the current blacklist
277 *
278 * @return TitleBlacklistEntry[]
279 */
280 public function getBlacklist() {
281 if ( $this->mBlacklist === null ) {
282 $this->load();
283 }
284 return $this->mBlacklist;
285 }
286
287 /**
288 * Get the current whitelist
289 *
290 * @return TitleBlacklistEntry[]
291 */
292 public function getWhitelist() {
293 if ( $this->mWhitelist === null ) {
294 $this->loadWhitelist();
295 }
296 return $this->mWhitelist;
297 }
298
299 /**
300 * Get the text of a blacklist source via HTTP
301 *
302 * @param string $url URL of the blacklist source
303 * @return string The content of the blacklist source as a string
304 */
305 private static function getHttp( $url ) {
306 global $wgTitleBlacklistCaching;
307
308 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
309 $key = $cache->makeGlobalKey( 'title_blacklist_source', md5( $url ) );
310 $caller = __METHOD__;
311
312 return $cache->getWithSetCallback(
313 $key,
314 $wgTitleBlacklistCaching['expiry'],
315 static function ( $oldValue, &$ttl ) use ( $url, $caller ) {
316 $httpRequestFactory = MediaWikiServices::getInstance()
317 ->getHttpRequestFactory();
318
319 $result = $httpRequestFactory->get( $url, [], $caller );
320
321 // Retry once on transient failure (T423162)
322 if ( $result === null ) {
323 usleep( 50_000 );
324 $result = $httpRequestFactory->get( $url, [], $caller );
325 }
326
327 if ( is_string( $result ) ) {
328 return $result;
329 }
330
331 // All attempts failed
332 wfDebugLog( 'TitleBlacklist-cache',
333 "Error loading title blacklist from $url" );
334
335 // If we have a previous cached value, keep using it
336 if ( is_string( $oldValue ) ) {
337 $ttl = WANObjectCache::TTL_MINUTE;
338 wfDebugLog( 'TitleBlacklist-cache',
339 "Using previously cached value for $url" );
340 return $oldValue;
341 }
342
343 // No previous value at all
344 return '';
345 },
346 [
347 'lockTSE' => 30,
348 'staleTTL' => WANObjectCache::TTL_DAY,
349 'busyValue' => '',
350 ]
351 );
352 }
353
354 /**
355 * Invalidate the blacklist cache
356 */
357 public function invalidate() {
358 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
359 $cache->delete( $cache->makeKey( 'title_blacklist_entries' ) );
360 }
361
362 /**
363 * Validate a new blacklist
364 *
365 * @suppress PhanParamSuspiciousOrder The preg_match() params are in the correct order
366 * @param TitleBlacklistEntry[] $blacklist
367 * @return string[] List of invalid entries; empty array means blacklist is valid
368 */
369 public function validate( array $blacklist ) {
370 $badEntries = [];
371 foreach ( $blacklist as $e ) {
372 AtEase::suppressWarnings();
373 $regex = $e->getRegex();
374 // @phan-suppress-next-line SecurityCheck-ReDoS
375 if ( preg_match( "/{$regex}/u", '' ) === false ) {
376 $badEntries[] = $e->getRaw();
377 }
378 AtEase::restoreWarnings();
379 }
380 return $badEntries;
381 }
382
383 /**
384 * Indicates whether user can override blacklist on certain action.
385 *
386 * @param User $user
387 * @param string $action
388 *
389 * @return bool
390 */
391 public static function userCanOverride( $user, $action ) {
392 return $user->isAllowed( 'tboverride' ) ||
393 ( $action == 'new-account' && $user->isAllowed( 'tboverride-account' ) );
394 }
395 }