summaryrefslogtreecommitdiff
path: root/www/wiki/extensions/TitleBlacklist/TitleBlacklist.hooks.php
blob: fa8c1a8887bdf4f7a65f8111f0f0953e386666a2 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
<?php
/**
 * Hooks for Title Blacklist
 * @author Victor Vasiliev
 * @copyright © 2007-2010 Victor Vasiliev et al
 * @license GNU General Public License 2.0 or later
 */

use MediaWiki\Auth\AuthManager;

/**
 * Hooks for the TitleBlacklist class
 *
 * @ingroup Extensions
 */
class TitleBlacklistHooks {

	/**
	 * Called right after configuration variables have been set.
	 */
	public static function onRegistration() {
		global $wgDisableAuthManager, $wgAuthManagerAutoConfig;

		if ( class_exists( AuthManager::class ) && !$wgDisableAuthManager ) {
			$wgAuthManagerAutoConfig['preauth'][TitleBlacklistPreAuthenticationProvider::class] =
				[ 'class' => TitleBlacklistPreAuthenticationProvider::class ];
		} else {
			Hooks::register( 'AbortNewAccount', 'TitleBlacklistHooks::abortNewAccount' );
			Hooks::register( 'AbortAutoAccount', 'TitleBlacklistHooks::abortAutoAccount' );
			Hooks::register( 'UserCreateForm', 'TitleBlacklistHooks::addOverrideCheckbox' );
			Hooks::register( 'APIGetAllowedParams', 'TitleBlacklistHooks::onAPIGetAllowedParams' );
			Hooks::register( 'AddNewAccountApiForm',
				'TitleBlacklistHooks::onAddNewAccountApiForm' );
		}
	}

	/**
	 * getUserPermissionsErrorsExpensive hook
	 *
	 * @param Title $title
	 * @param User $user
	 * @param string $action
	 * @param array &$result
	 * @return bool
	 */
	public static function userCan( $title, $user, $action, &$result ) {
		# Some places check createpage, while others check create.
		# As it stands, upload does createpage, but normalize both
		# to the same action, to stop future similar bugs.
		if ( $action === 'createpage' || $action === 'createtalk' ) {
			$action = 'create';
		}
		if ( $action == 'create' || $action == 'edit' || $action == 'upload' ) {
			$blacklisted = TitleBlacklist::singleton()->userCannot( $title, $user, $action );
			if ( $blacklisted instanceof TitleBlacklistEntry ) {
				$errmsg = $blacklisted->getErrorMessage( 'edit' );
				$params = [
					$blacklisted->getRaw(),
					$title->getFullText()
				];
				ApiResult::setIndexedTagName( $params, 'param' );
				$result = ApiMessage::create(
					wfMessage(
						$errmsg,
						htmlspecialchars( $blacklisted->getRaw() ),
						$title->getFullText()
					),
					'titleblacklist-forbidden',
					[
						'message' => [
							'key' => $errmsg,
							'params' => $params,
						],
						'line' => $blacklisted->getRaw(),
						// As $errmsg usually represents a non-default message here, and ApiBase
						// uses ->inLanguage( 'en' )->useDatabase( false ) for all messages, it will
						// never result in useful 'info' text in the API. Try this, extra data seems
						// to override the default.
						'info' => 'TitleBlacklist prevents this title from being created',
					]
				);
				return false;
			}
		}
		return true;
	}

	/**
	 * Display a notice if a user is only able to create or edit a page
	 * because they have tboverride.
	 *
	 * @param Title $title
	 * @param int $oldid
	 * @param array &$notices
	 * @return true
	 */
	public static function displayBlacklistOverrideNotice( Title $title, $oldid, array &$notices ) {
		if ( !RequestContext::getMain()->getUser()->isAllowed( 'tboverride' ) ) {
			return true;
		}

		$blacklisted = TitleBlacklist::singleton()->isBlacklisted(
			$title,
			$title->exists() ? 'edit' : 'create'
		);
		if ( !$blacklisted ) {
			return true;
		}

		$params = $blacklisted->getParams();
		if ( isset( $params['autoconfirmed'] ) ) {
			return true;
		}

		$msg = wfMessage( 'titleblacklist-warning' );
		$notices['titleblacklist'] = $msg->rawParams(
			htmlspecialchars( $blacklisted->getRaw() ) )->parseAsBlock();
		return true;
	}

	/**
	 * MovePageCheckPermissions hook (1.25+)
	 *
	 * @param Title $oldTitle
	 * @param Title $newTitle
	 * @param User $user
	 * @param string $reason
	 * @param Status $status
	 * @return bool
	 */
	public static function onMovePageCheckPermissions(
		Title $oldTitle, Title $newTitle, User $user, $reason, Status $status
	) {
		$titleBlacklist = TitleBlacklist::singleton();
		$blacklisted = $titleBlacklist->userCannot( $newTitle, $user, 'move' );
		if ( !$blacklisted ) {
			$blacklisted = $titleBlacklist->userCannot( $oldTitle, $user, 'edit' );
		}
		if ( $blacklisted instanceof TitleBlacklistEntry ) {
			$status->fatal( ApiMessage::create( [
				$blacklisted->getErrorMessage( 'move' ),
				$blacklisted->getRaw(),
				$oldTitle->getFullText(),
				$newTitle->getFullText()
			] ) );
			return false;
		}

		return true;
	}

	/**
	 * Check whether a user name is acceptable,
	 * and set a message if unacceptable.
	 *
	 * Used by abortNewAccount and centralAuthAutoCreate.
	 * May also be called externally to vet alternate account names.
	 *
	 * @param string $userName
	 * @param User $permissionsUser
	 * @param string &$err
	 * @param bool $override
	 * @param bool $log
	 * @return bool Acceptable
	 */
	public static function acceptNewUserName(
		$userName, $permissionsUser, &$err, $override = true, $log = false
	) {
		$sv = self::testUserName( $userName, $permissionsUser, $override, $log );
		if ( !$sv->isGood() ) {
			$err = Status::wrap( $sv )->getMessage()->parse();
		}
		return $sv->isGood();
	}

	/**
	 * Check whether a user name is acceptable for account creation or autocreation, and explain
	 * why not if that's the case.
	 *
	 * @param string $userName
	 * @param User $creatingUser
	 * @param bool $override Should the test be skipped, if the user has sufficient privileges?
	 * @param bool $log Log blacklist hits to Special:Log
	 * @return StatusValue
	 */
	public static function testUserName(
		$userName, User $creatingUser, $override = true, $log = false
	) {
		$title = Title::makeTitleSafe( NS_USER, $userName );
		$blacklisted = TitleBlacklist::singleton()->userCannot( $title, $creatingUser,
			'new-account', $override );
		if ( $blacklisted instanceof TitleBlacklistEntry ) {
			if ( $log ) {
				self::logFilterHitUsername( $creatingUser, $title, $blacklisted->getRaw() );
			}
			$message = $blacklisted->getErrorMessage( 'new-account' );
			$params = [
				$blacklisted->getRaw(),
				$userName,
			];
			ApiResult::setIndexedTagName( $params, 'param' );
			return StatusValue::newFatal( ApiMessage::create(
				[ $message, $blacklisted->getRaw(), $userName ],
				'titleblacklist-forbidden',
				[
					'message' => [
						'key' => $message,
						'params' => $params,
					],
					'line' => $blacklisted->getRaw(),
					// The text of the message probably isn't useful API info, so do this instead
					'info' => 'TitleBlacklist prevents this username from being created',
				]
			) );
		}
		return StatusValue::newGood();
	}

	/**
	 * AbortNewAccount hook
	 *
	 * @param User $user
	 * @param string &$message
	 * @param Status &$status
	 * @return bool
	 */
	public static function abortNewAccount( $user, &$message, &$status ) {
		global $wgUser, $wgRequest;
		$override = $wgRequest->getCheck( 'wpIgnoreTitleBlacklist' );
		$sv = self::testUserName( $user->getName(), $wgUser, $override, true );
		if ( !$sv->isGood() ) {
			$status = Status::wrap( $sv );
			$message = $status->getMessage()->parse();
		}
		return $sv->isGood();
	}

	/**
	 * AbortAutoAccount hook
	 *
	 * @param User $user
	 * @param string &$message
	 * @return bool
	 */
	public static function abortAutoAccount( $user, &$message ) {
		global $wgTitleBlacklistBlockAutoAccountCreation;
		if ( $wgTitleBlacklistBlockAutoAccountCreation ) {
			return self::abortNewAccount( $user, $message );
		}
		return true;
	}

	/**
	 * EditFilter hook
	 *
	 * @param EditPage $editor
	 * @param string $text
	 * @param string $section
	 * @param string &$error
	 * @return true
	 */
	public static function validateBlacklist( $editor, $text, $section, &$error ) {
		$title = $editor->getTitle();

		if ( $title->getNamespace() == NS_MEDIAWIKI && $title->getDBkey() == 'Titleblacklist' ) {
			$blackList = TitleBlacklist::singleton();
			$bl = $blackList->parseBlacklist( $text, 'page' );
			$ok = $blackList->validate( $bl );
			if ( count( $ok ) == 0 ) {
				return true;
			}

			$errmsg = wfMessage( 'titleblacklist-invalid' )->numParams( count( $ok ) )->text();
			$errlines = '* <code>' .
				implode( "</code>\n* <code>", array_map( 'wfEscapeWikiText', $ok ) ) .
				'</code>';
			$error = Html::openElement( 'div', [ 'class' => 'errorbox' ] ) .
				$errmsg .
				"\n" .
				$errlines .
				Html::closeElement( 'div' ) . "\n" .
				Html::element( 'br', [ 'clear' => 'all' ] ) . "\n";

			// $error will be displayed by the edit class
		}
		return true;
	}

	/**
	 * PageContentSaveComplete hook
	 *
	 * @param Article &$article
	 * @param User &$user
	 * @param Content $content
	 * @param string $summary
	 * @param bool $isminor
	 * @param bool $iswatch
	 * @param string $section
	 * @return true
	 */
	public static function clearBlacklist( &$article, &$user,
		$content, $summary, $isminor, $iswatch, $section
	) {
		$title = $article->getTitle();
		if ( $title->getNamespace() == NS_MEDIAWIKI && $title->getDBkey() == 'Titleblacklist' ) {
			TitleBlacklist::singleton()->invalidate();
		}
		return true;
	}

	/**
	 * UserCreateForm hook based on the one from AntiSpoof extension
	 * @param UsercreateTemplate &$template
	 * @return true
	 */
	public static function addOverrideCheckbox( &$template ) {
		global $wgRequest, $wgUser;

		if ( TitleBlacklist::userCanOverride( $wgUser, 'new-account' ) ) {
			$template->addInputItem( 'wpIgnoreTitleBlacklist',
				$wgRequest->getCheck( 'wpIgnoreTitleBlacklist' ),
				'checkbox', 'titleblacklist-override' );
		}
		return true;
	}

	/**
	 * @param ApiBase &$module
	 * @param array &$params
	 * @return bool
	 */
	public static function onAPIGetAllowedParams( ApiBase &$module, array &$params ) {
		if ( $module instanceof ApiCreateAccount ) {
			$params['ignoretitleblacklist'] = [
				ApiBase::PARAM_TYPE => 'boolean',
				ApiBase::PARAM_DFLT => false
			];
		}

		return true;
	}

	/**
	 * Pass API parameter on to the login form when using
	 * API account creation.
	 *
	 * @param ApiBase $apiModule
	 * @param LoginForm $loginForm
	 * @return bool Always true
	 */
	public static function onAddNewAccountApiForm( ApiBase $apiModule, LoginForm $loginForm ) {
		global $wgRequest;
		$main = $apiModule->getMain();

		if ( $main->getVal( 'ignoretitleblacklist' ) !== null ) {
			$wgRequest->setVal( 'wpIgnoreTitleBlacklist', '1' );

			// Suppress "unrecognized parameter" warning:
			$main->getVal( 'wpIgnoreTitleBlacklist' );
		}

		return true;
	}

	/**
	 * Logs the filter username hit to Special:Log if
	 * $wgTitleBlacklistLogHits is enabled.
	 *
	 * @param User $user
	 * @param Title $title
	 * @param string $entry
	 */
	public static function logFilterHitUsername( $user, $title, $entry ) {
		global $wgTitleBlacklistLogHits;
		if ( $wgTitleBlacklistLogHits ) {
			$logEntry = new ManualLogEntry( 'titleblacklist', 'hit-username' );
			$logEntry->setPerformer( $user );
			$logEntry->setTarget( $title );
			$logEntry->setParameters( [
				'4::entry' => $entry,
			] );
			$logid = $logEntry->insert();
			$logEntry->publish( $logid );
		}
	}

	/**
	 * External Lua library for Scribunto
	 *
	 * @param string $engine
	 * @param array &$extraLibraries
	 * @return bool
	 */
	public static function scribuntoExternalLibraries( $engine, array &$extraLibraries ) {
		if ( $engine == 'lua' ) {
			$extraLibraries['mw.ext.TitleBlacklist'] = 'Scribunto_LuaTitleBlacklistLibrary';
		}
		return true;
	}
}