Debian Codegraph @

extensions/AbuseFilter/includes/Special/SpecialAbuseLog.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\AbuseFilter\Special;
4
5 use DifferenceEngine;
6 use InvalidArgumentException;
7 use ManualLogEntry;
8 use MediaWiki\Cache\LinkBatchFactory;
9 use MediaWiki\Extension\AbuseFilter\AbuseFilterPermissionManager;
10 use MediaWiki\Extension\AbuseFilter\AbuseFilterServices;
11 use MediaWiki\Extension\AbuseFilter\AbuseLoggerFactory;
12 use MediaWiki\Extension\AbuseFilter\CentralDBNotAvailableException;
13 use MediaWiki\Extension\AbuseFilter\Consequences\ConsequencesRegistry;
14 use MediaWiki\Extension\AbuseFilter\Filter\FilterNotFoundException;
15 use MediaWiki\Extension\AbuseFilter\Filter\Flags;
16 use MediaWiki\Extension\AbuseFilter\FilterUtils;
17 use MediaWiki\Extension\AbuseFilter\GlobalNameUtils;
18 use MediaWiki\Extension\AbuseFilter\Pager\AbuseLogPager;
19 use MediaWiki\Extension\AbuseFilter\SpecsFormatter;
20 use MediaWiki\Extension\AbuseFilter\Variables\UnsetVariableException;
21 use MediaWiki\Extension\AbuseFilter\Variables\VariableHolder;
22 use MediaWiki\Extension\AbuseFilter\Variables\VariablesBlobStore;
23 use MediaWiki\Extension\AbuseFilter\Variables\VariablesFormatter;
24 use MediaWiki\Extension\AbuseFilter\Variables\VariablesManager;
25 use MediaWiki\Extension\AbuseFilter\View\HideAbuseLog;
26 use MediaWiki\Html\Html;
27 use MediaWiki\Html\ListToggle;
28 use MediaWiki\HTMLForm\HTMLForm;
29 use MediaWiki\Linker\Linker;
30 use MediaWiki\MediaWikiServices;
31 use MediaWiki\Permissions\Authority;
32 use MediaWiki\Permissions\PermissionManager;
33 use MediaWiki\Registration\ExtensionRegistry;
34 use MediaWiki\SpecialPage\SpecialPage;
35 use MediaWiki\Status\Status;
36 use MediaWiki\Title\Title;
37 use MediaWiki\User\UserIdentity;
38 use MediaWiki\User\UserIdentityLookup;
39 use MediaWiki\WikiMap\WikiMap;
40 use OOUI\ButtonInputWidget;
41 use stdClass;
42 use Wikimedia\Rdbms\IExpression;
43 use Wikimedia\Rdbms\LBFactory;
44 use Wikimedia\Rdbms\LikeValue;
45
46 class SpecialAbuseLog extends AbuseFilterSpecialPage {
47 public const PAGE_NAME = 'AbuseLog';
48
49 /** Visible entry */
50 public const VISIBILITY_VISIBLE = 'visible';
51 /** Explicitly hidden entry */
52 public const VISIBILITY_HIDDEN = 'hidden';
53 /** Visible entry but the associated revision is hidden */
54 public const VISIBILITY_HIDDEN_IMPLICIT = 'implicit';
55
56 /**
57 * @var string|null The user whose AbuseLog entries are being searched
58 */
59 private $mSearchUser;
60
61 /**
62 * @var string The start time of the search period
63 */
64 private $mSearchPeriodStart;
65
66 /**
67 * @var string The end time of the search period
68 */
69 private $mSearchPeriodEnd;
70
71 /**
72 * @var string The page of which AbuseLog entries are being searched
73 */
74 private $mSearchTitle;
75
76 /**
77 * @var string The action performed by the user
78 */
79 private $mSearchAction;
80
81 /**
82 * @var string The action taken by AbuseFilter
83 */
84 private $mSearchActionTaken;
85
86 /**
87 * @var string The wiki name where we're performing the search
88 */
89 private $mSearchWiki;
90
91 /**
92 * @var string|null The filter IDs we're looking for. Either a single one, or a pipe-separated list
93 */
94 private $mSearchFilter;
95
96 /**
97 * @var string The visibility of entries we're interested in
98 */
99 private $mSearchEntries;
100
101 /**
102 * @var string The impact of the user action, i.e. if the change has been saved
103 */
104 private $mSearchImpact;
105
106 /** @var string|null The filter group to search, as defined in $wgAbuseFilterValidGroups */
107 private $mSearchGroup;
108
109 /** @var LBFactory */
110 private $lbFactory;
111
112 /** @var LinkBatchFactory */
113 private $linkBatchFactory;
114
115 /** @var PermissionManager */
116 private $permissionManager;
117
118 /** @var UserIdentityLookup */
119 private $userIdentityLookup;
120
121 /** @var ConsequencesRegistry */
122 private $consequencesRegistry;
123
124 /** @var VariablesBlobStore */
125 private $varBlobStore;
126
127 /** @var SpecsFormatter */
128 private $specsFormatter;
129
130 /** @var VariablesFormatter */
131 private $variablesFormatter;
132
133 /** @var VariablesManager */
134 private $varManager;
135
136 private AbuseLoggerFactory $abuseLoggerFactory;
137
138 /**
139 * @param LBFactory $lbFactory
140 * @param LinkBatchFactory $linkBatchFactory
141 * @param PermissionManager $permissionManager
142 * @param UserIdentityLookup $userIdentityLookup
143 * @param AbuseFilterPermissionManager $afPermissionManager
144 * @param ConsequencesRegistry $consequencesRegistry
145 * @param VariablesBlobStore $varBlobStore
146 * @param SpecsFormatter $specsFormatter
147 * @param VariablesFormatter $variablesFormatter
148 * @param VariablesManager $varManager
149 * @param AbuseLoggerFactory $abuseLoggerFactory
150 */
151 public function __construct(
152 LBFactory $lbFactory,
153 LinkBatchFactory $linkBatchFactory,
154 PermissionManager $permissionManager,
155 UserIdentityLookup $userIdentityLookup,
156 AbuseFilterPermissionManager $afPermissionManager,
157 ConsequencesRegistry $consequencesRegistry,
158 VariablesBlobStore $varBlobStore,
159 SpecsFormatter $specsFormatter,
160 VariablesFormatter $variablesFormatter,
161 VariablesManager $varManager,
162 AbuseLoggerFactory $abuseLoggerFactory
163 ) {
164 parent::__construct( self::PAGE_NAME, 'abusefilter-log', $afPermissionManager );
165 $this->lbFactory = $lbFactory;
166 $this->linkBatchFactory = $linkBatchFactory;
167 $this->permissionManager = $permissionManager;
168 $this->userIdentityLookup = $userIdentityLookup;
169 $this->consequencesRegistry = $consequencesRegistry;
170 $this->varBlobStore = $varBlobStore;
171 $this->specsFormatter = $specsFormatter;
172 $this->specsFormatter->setMessageLocalizer( $this );
173 $this->variablesFormatter = $variablesFormatter;
174 $this->variablesFormatter->setMessageLocalizer( $this );
175 $this->varManager = $varManager;
176 $this->abuseLoggerFactory = $abuseLoggerFactory;
177 }
178
179 /**
180 * @codeCoverageIgnore Merely declarative
181 * @inheritDoc
182 */
183 public function doesWrites() {
184 return true;
185 }
186
187 /**
188 * @codeCoverageIgnore Merely declarative
189 * @inheritDoc
190 */
191 protected function getGroupName() {
192 return 'changes';
193 }
194
195 /**
196 * Main routine
197 *
198 * $parameter string is converted into the $args array, which can come in
199 * three shapes:
200 *
201 * An array of size 2: only if the URL is like Special:AbuseLog/private/id
202 * where id is the log identifier. In this case, the private details of the
203 * log (e.g. IP address) will be shown.
204 *
205 * An array of size 1: either the URL is like Special:AbuseLog/id where
206 * the id is log identifier, in which case the details of the log except for
207 * private bits (e.g. IP address) are shown, or Special:AbuseLog/hide for hiding entries,
208 * or the URL is incomplete as in Special:AbuseLog/private (without specifying id),
209 * in which case a warning is shown to the user
210 *
211 * An array of size 0 when URL is like Special:AbuseLog or an array of size
212 * 1 when the URL is like Special:AbuseFilter/ (i.e. without anything after
213 * the slash). Otherwise, the abuse logs are shown as a list, with a search form above the list.
214 *
215 * @param string|null $parameter URL parameters
216 */
217 public function execute( $parameter ) {
218 $out = $this->getOutput();
219
220 $this->addNavigationLinks( 'log' );
221
222 $this->setHeaders();
223 $this->addHelpLink( 'Extension:AbuseFilter' );
224 $this->loadParameters();
225
226 $out->disableClientCache();
227
228 $out->addModuleStyles( 'ext.abuseFilter' );
229
230 $this->checkPermissions();
231
232 $args = $parameter !== null ? explode( '/', $parameter ) : [];
233
234 if ( count( $args ) === 2 && $args[0] === 'private' ) {
235 $this->showPrivateDetails( (int)$args[1] );
236 } elseif ( count( $args ) === 1 && $args[0] !== '' ) {
237 if ( $args[0] === 'private' ) {
238 $out->addWikiMsg( 'abusefilter-invalid-request-noid' );
239 } elseif ( $args[0] === 'hide' ) {
240 $this->showHideView();
241 } else {
242 $this->showDetails( $args[0] );
243 }
244 } else {
245 $this->outputHeader( 'abusefilter-log-summary' );
246 $this->searchForm();
247 $this->showList();
248 }
249 }
250
251 /**
252 * @inheritDoc
253 */
254 public function getShortDescription( string $path = '' ): string {
255 return $this->msg( 'abusefilter-topnav-log' )->text();
256 }
257
258 /**
259 * Loads parameters from request
260 */
261 public function loadParameters() {
262 $request = $this->getRequest();
263
264 $searchUsername = trim( $request->getText( 'wpSearchUser' ) );
265 $userTitle = Title::newFromText( $searchUsername, NS_USER );
266 $this->mSearchUser = $userTitle ? $userTitle->getText() : null;
267 if ( $this->getConfig()->get( 'AbuseFilterIsCentral' ) ) {
268 $this->mSearchWiki = $request->getText( 'wpSearchWiki' );
269 }
270
271 $this->mSearchPeriodStart = $request->getText( 'wpSearchPeriodStart' );
272 $this->mSearchPeriodEnd = $request->getText( 'wpSearchPeriodEnd' );
273 $this->mSearchTitle = $request->getText( 'wpSearchTitle' );
274
275 $this->mSearchFilter = null;
276 $this->mSearchGroup = null;
277 if ( $this->afPermissionManager->canSeeLogDetails( $this->getAuthority() ) ) {
278 $this->mSearchFilter = $request->getText( 'wpSearchFilter' );
279 if ( count( $this->getConfig()->get( 'AbuseFilterValidGroups' ) ) > 1 ) {
280 $this->mSearchGroup = $request->getText( 'wpSearchGroup' );
281 }
282 }
283
284 $this->mSearchAction = $request->getText( 'wpSearchAction' );
285 $this->mSearchActionTaken = $request->getText( 'wpSearchActionTaken' );
286 $this->mSearchEntries = $request->getText( 'wpSearchEntries' );
287 $this->mSearchImpact = $request->getText( 'wpSearchImpact' );
288 }
289
290 /**
291 * @return string[]
292 */
293 private function getAllFilterableActions() {
294 return [
295 'edit',
296 'move',
297 'upload',
298 'stashupload',
299 'delete',
300 'createaccount',
301 'autocreateaccount',
302 ];
303 }
304
305 /**
306 * Builds the search form
307 */
308 public function searchForm() {
309 $performer = $this->getAuthority();
310 $formDescriptor = [
311 'SearchUser' => [
312 'label-message' => 'abusefilter-log-search-user',
313 'type' => 'user',
314 'ipallowed' => true,
315 'default' => $this->mSearchUser,
316 ],
317 'SearchPeriodStart' => [
318 'label-message' => 'abusefilter-test-period-start',
319 'type' => 'datetime',
320 'default' => $this->mSearchPeriodStart
321 ],
322 'SearchPeriodEnd' => [
323 'label-message' => 'abusefilter-test-period-end',
324 'type' => 'datetime',
325 'default' => $this->mSearchPeriodEnd
326 ],
327 'SearchTitle' => [
328 'label-message' => 'abusefilter-log-search-title',
329 'type' => 'title',
330 'interwiki' => false,
331 'default' => $this->mSearchTitle,
332 'required' => false
333 ],
334 'SearchImpact' => [
335 'label-message' => 'abusefilter-log-search-impact',
336 'type' => 'select',
337 'options' => [
338 $this->msg( 'abusefilter-log-search-impact-all' )->text() => 0,
339 $this->msg( 'abusefilter-log-search-impact-saved' )->text() => 1,
340 $this->msg( 'abusefilter-log-search-impact-not-saved' )->text() => 2,
341 ],
342 ],
343 ];
344 $filterableActions = $this->getAllFilterableActions();
345 $actions = array_combine( $filterableActions, $filterableActions );
346 ksort( $actions );
347 $actions = array_merge(
348 [ $this->msg( 'abusefilter-log-search-action-any' )->text() => 'any' ],
349 $actions,
350 [ $this->msg( 'abusefilter-log-search-action-other' )->text() => 'other' ]
351 );
352 $formDescriptor['SearchAction'] = [
353 'label-message' => 'abusefilter-log-search-action-label',
354 'type' => 'select',
355 'options' => $actions,
356 'default' => 'any',
357 ];
358 $options = [];
359 foreach ( $this->consequencesRegistry->getAllActionNames() as $action ) {
360 $key = $this->specsFormatter->getActionDisplay( $action );
361 $options[$key] = $action;
362 }
363 ksort( $options );
364 $options = array_merge(
365 [ $this->msg( 'abusefilter-log-search-action-taken-any' )->text() => '' ],
366 $options,
367 [ $this->msg( 'abusefilter-log-noactions-filter' )->text() => 'noactions' ]
368 );
369 $formDescriptor['SearchActionTaken'] = [
370 'label-message' => 'abusefilter-log-search-action-taken-label',
371 'type' => 'select',
372 'options' => $options,
373 ];
374 if ( $this->afPermissionManager->canSeeHiddenLogEntries( $performer ) ) {
375 $formDescriptor['SearchEntries'] = [
376 'type' => 'select',
377 'label-message' => 'abusefilter-log-search-entries-label',
378 'options' => [
379 $this->msg( 'abusefilter-log-search-entries-all' )->text() => 0,
380 $this->msg( 'abusefilter-log-search-entries-hidden' )->text() => 1,
381 $this->msg( 'abusefilter-log-search-entries-visible' )->text() => 2,
382 ],
383 ];
384 }
385
386 if ( $this->afPermissionManager->canSeeLogDetails( $performer ) ) {
387 $groups = $this->getConfig()->get( 'AbuseFilterValidGroups' );
388 if ( count( $groups ) > 1 ) {
389 $options = array_merge(
390 [ $this->msg( 'abusefilter-log-search-group-any' )->text() => 0 ],
391 array_combine( $groups, $groups )
392 );
393 $formDescriptor['SearchGroup'] = [
394 'label-message' => 'abusefilter-log-search-group',
395 'type' => 'select',
396 'options' => $options
397 ];
398 }
399 $helpmsg = $this->getConfig()->get( 'AbuseFilterIsCentral' )
400 ? $this->msg( 'abusefilter-log-search-filter-help-central' )->escaped()
401 : $this->msg( 'abusefilter-log-search-filter-help' )
402 ->params( GlobalNameUtils::GLOBAL_FILTER_PREFIX )->escaped();
403 $formDescriptor['SearchFilter'] = [
404 'label-message' => 'abusefilter-log-search-filter',
405 'type' => 'text',
406 'default' => $this->mSearchFilter,
407 'help' => $helpmsg
408 ];
409 }
410 if ( $this->getConfig()->get( 'AbuseFilterIsCentral' ) ) {
411 // @todo Add free form input for wiki name. Would be nice to generate
412 // a select with unique names in the db at some point.
413 $formDescriptor['SearchWiki'] = [
414 'label-message' => 'abusefilter-log-search-wiki',
415 'type' => 'text',
416 'default' => $this->mSearchWiki,
417 ];
418 }
419
420 HTMLForm::factory( 'ooui', $formDescriptor, $this->getContext() )
421 ->setWrapperLegendMsg( 'abusefilter-log-search' )
422 ->setSubmitTextMsg( 'abusefilter-log-search-submit' )
423 ->setMethod( 'get' )
424 ->setCollapsibleOptions( true )
425 ->prepareForm()
426 ->displayForm( false );
427 }
428
429 private function showHideView() {
430 $view = new HideAbuseLog(
431 $this->lbFactory,
432 $this->afPermissionManager,
433 $this->getContext(),
434 $this->getLinkRenderer(),
435 self::PAGE_NAME
436 );
437 $view->show();
438 }
439
440 /**
441 * Shows the results list
442 */
443 public function showList() {
444 $out = $this->getOutput();
445 $performer = $this->getAuthority();
446
447 // Generate conditions list.
448 $conds = [];
449
450 if ( $this->mSearchUser !== null ) {
451 $searchedUser = $this->userIdentityLookup->getUserIdentityByName( $this->mSearchUser );
452
453 if ( !$searchedUser ) {
454 $conds['afl_user'] = 0;
455 $conds['afl_user_text'] = $this->mSearchUser;
456 } else {
457 $conds['afl_user'] = $searchedUser->getId();
458 $conds['afl_user_text'] = $searchedUser->getName();
459 }
460 }
461
462 $dbr = $this->lbFactory->getReplicaDatabase();
463 if ( $this->mSearchPeriodStart ) {
464 $conds[] = $dbr->expr( 'afl_timestamp', '>=',
465 $dbr->timestamp( strtotime( $this->mSearchPeriodStart ) ) );
466 }
467
468 if ( $this->mSearchPeriodEnd ) {
469 $conds[] = $dbr->expr( 'afl_timestamp', '<=',
470 $dbr->timestamp( strtotime( $this->mSearchPeriodEnd ) ) );
471 }
472
473 if ( $this->mSearchWiki ) {
474 if ( $this->mSearchWiki === WikiMap::getCurrentWikiDbDomain()->getId() ) {
475 $conds['afl_wiki'] = null;
476 } else {
477 $conds['afl_wiki'] = $this->mSearchWiki;
478 }
479 }
480
481 $groupFilters = [];
482 if ( $this->mSearchGroup ) {
483 $groupFilters = $dbr->newSelectQueryBuilder()
484 ->select( 'af_id' )
485 ->from( 'abuse_filter' )
486 ->where( [ 'af_group' => $this->mSearchGroup ] )
487 ->caller( __METHOD__ )
488 ->fetchFieldValues();
489 }
490
491 $searchFilters = [];
492 if ( $this->mSearchFilter ) {
493 $rawFilters = array_map( 'trim', explode( '|', $this->mSearchFilter ) );
494 // Map of [ [ id, global ], ... ]
495 $filtersList = [];
496 $foundInvalid = false;
497 foreach ( $rawFilters as $filter ) {
498 try {
499 $filtersList[] = GlobalNameUtils::splitGlobalName( $filter );
500 } catch ( InvalidArgumentException $e ) {
501 $foundInvalid = true;
502 continue;
503 }
504 }
505
506 // if a filter is hidden, users who can't view private filters should
507 // not be able to find log entries generated by it.
508 if ( !$this->afPermissionManager->canViewPrivateFiltersLogs( $performer ) ) {
509 $searchedForPrivate = false;
510 foreach ( $filtersList as $index => $filterData ) {
511 try {
512 $filter = AbuseFilterServices::getFilterLookup()->getFilter( ...$filterData );
513 } catch ( FilterNotFoundException $_ ) {
514 unset( $filtersList[$index] );
515 $foundInvalid = true;
516 continue;
517 }
518 if ( $filter->isHidden() ) {
519 unset( $filtersList[$index] );
520 $searchedForPrivate = true;
521 }
522 }
523 if ( $searchedForPrivate ) {
524 $out->addWikiMsg( 'abusefilter-log-private-not-included' );
525 }
526 }
527
528 // if a filter is protected, users who can't view protected filters should
529 // not be able to find log entries generated by it.
530 if ( !$this->afPermissionManager->canViewProtectedVariables( $performer ) ) {
531 $searchedForProtected = false;
532 foreach ( $filtersList as $index => $filterData ) {
533 try {
534 $filter = AbuseFilterServices::getFilterLookup()->getFilter( ...$filterData );
535 } catch ( FilterNotFoundException $_ ) {
536 unset( $filtersList[$index] );
537 $foundInvalid = true;
538 continue;
539 }
540 if ( $filter->isProtected() ) {
541 unset( $filtersList[$index] );
542 $searchedForProtected = true;
543 }
544 }
545 if ( $searchedForProtected ) {
546 $out->addWikiMsg( 'abusefilter-log-protected-not-included' );
547 }
548 }
549
550 if ( $foundInvalid ) {
551 // @todo Tell what the invalid IDs are
552 $out->addHTML(
553 Html::rawElement(
554 'p',
555 [],
556 Html::warningBox( $this->msg( 'abusefilter-log-invalid-filter' )->escaped() )
557 )
558 );
559 }
560
561 foreach ( $filtersList as $filterData ) {
562 $searchFilters[] = GlobalNameUtils::buildGlobalName( ...$filterData );
563 }
564 }
565
566 $searchIDs = null;
567 if ( $this->mSearchGroup && !$this->mSearchFilter ) {
568 $searchIDs = $groupFilters;
569 } elseif ( !$this->mSearchGroup && $this->mSearchFilter ) {
570 $searchIDs = $searchFilters;
571 } elseif ( $this->mSearchGroup && $this->mSearchFilter ) {
572 $searchIDs = array_intersect( $groupFilters, $searchFilters );
573 }
574
575 if ( $searchIDs !== null ) {
576 if ( !count( $searchIDs ) ) {
577 $out->addWikiMsg( 'abusefilter-log-noresults' );
578 return;
579 }
580
581 $filterConds = [ 'local' => [], 'global' => [] ];
582 foreach ( $searchIDs as $filter ) {
583 [ $filterID, $isGlobal ] = GlobalNameUtils::splitGlobalName( $filter );
584 $key = $isGlobal ? 'global' : 'local';
585 $filterConds[$key][] = $filterID;
586 }
587 $filterWhere = [];
588 if ( $filterConds['local'] ) {
589 $filterWhere[] = $dbr->andExpr( [
590 'afl_global' => 0,
591 // @phan-suppress-previous-line PhanTypeMismatchArgument Array is non-empty
592 'afl_filter_id' => $filterConds['local'],
593 ] );
594 }
595 if ( $filterConds['global'] ) {
596 $filterWhere[] = $dbr->andExpr( [
597 'afl_global' => 1,
598 // @phan-suppress-previous-line PhanTypeMismatchArgument Array is non-empty
599 'afl_filter_id' => $filterConds['global'],
600 ] );
601 }
602 $conds[] = $dbr->orExpr( $filterWhere );
603 }
604
605 $searchTitle = Title::newFromText( $this->mSearchTitle );
606 if ( $searchTitle ) {
607 $conds['afl_namespace'] = $searchTitle->getNamespace();
608 $conds['afl_title'] = $searchTitle->getDBkey();
609 }
610
611 if ( $this->afPermissionManager->canSeeHiddenLogEntries( $performer ) ) {
612 if ( $this->mSearchEntries === '1' ) {
613 $conds['afl_deleted'] = 1;
614 } elseif ( $this->mSearchEntries === '2' ) {
615 $conds['afl_deleted'] = 0;
616 }
617 }
618
619 if ( $this->mSearchImpact === '1' ) {
620 $conds[] = $dbr->expr( 'afl_rev_id', '!=', null );
621 } elseif ( $this->mSearchImpact === '2' ) {
622 $conds[] = $dbr->expr( 'afl_rev_id', '=', null );
623 }
624
625 if ( $this->mSearchActionTaken ) {
626 if ( in_array( $this->mSearchActionTaken, $this->consequencesRegistry->getAllActionNames() ) ) {
627 $conds[] = $dbr->expr( 'afl_actions', '=', $this->mSearchActionTaken )
628 ->or( 'afl_actions', IExpression::LIKE, new LikeValue(
629 $this->mSearchActionTaken, ',', $dbr->anyString()
630 ) )
631 ->or( 'afl_actions', IExpression::LIKE, new LikeValue(
632 $dbr->anyString(), ',', $this->mSearchActionTaken
633 ) )
634 ->or( 'afl_actions', IExpression::LIKE, new LikeValue(
635 $dbr->anyString(),
636 ',', $this->mSearchActionTaken, ',',
637 $dbr->anyString()
638 ) );
639 } elseif ( $this->mSearchActionTaken === 'noactions' ) {
640 $conds['afl_actions'] = '';
641 }
642 }
643
644 if ( $this->mSearchAction ) {
645 $filterableActions = $this->getAllFilterableActions();
646 if ( in_array( $this->mSearchAction, $filterableActions ) ) {
647 $conds['afl_action'] = $this->mSearchAction;
648 } elseif ( $this->mSearchAction === 'other' ) {
649 $conds[] = $dbr->expr( 'afl_action', '!=', $filterableActions );
650 }
651 }
652
653 $pager = new AbuseLogPager(
654 $this->getContext(),
655 $this->getLinkRenderer(),
656 $conds,
657 $this->linkBatchFactory,
658 $this->permissionManager,
659 $this->afPermissionManager,
660 $this->getName()
661 );
662 $pager->doQuery();
663 $result = $pager->getResult();
664
665 $form = Html::rawElement(
666 'form',
667 [
668 'method' => 'GET',
669 'action' => $this->getPageTitle( 'hide' )->getLocalURL()
670 ],
671 $this->getDeleteButton() . $this->getListToggle() .
672 Html::rawElement( 'ul', [ 'class' => 'plainlinks' ], $pager->getBody() ) .
673 $this->getListToggle() . $this->getDeleteButton()
674 );
675
676 if ( $result && $result->numRows() !== 0 ) {
677 $out->addModuleStyles( 'mediawiki.interface.helpers.styles' );
678 $out->addHTML( $pager->getNavigationBar() . $form . $pager->getNavigationBar() );
679 } else {
680 $out->addWikiMsg( 'abusefilter-log-noresults' );
681 }
682 }
683
684 /**
685 * Returns the HTML for a button to hide selected entries
686 *
687 * @return string|ButtonInputWidget
688 */
689 private function getDeleteButton() {
690 if ( !$this->afPermissionManager->canHideAbuseLog( $this->getAuthority() ) ) {
691 return '';
692 }
693 return new ButtonInputWidget( [
694 'label' => $this->msg( 'abusefilter-log-hide-entries' )->text(),
695 'type' => 'submit'
696 ] );
697 }
698
699 /**
700 * Get the All / Invert / None options provided by
701 * ToggleList.php to mass select the checkboxes.
702 *
703 * @return string
704 */
705 private function getListToggle() {
706 if ( !$this->afPermissionManager->canHideAbuseLog( $this->getUser() ) ) {
707 return '';
708 }
709 return ( new ListToggle( $this->getOutput() ) )->getHtml();
710 }
711
712 /**
713 * @param string|int $id
714 * @suppress SecurityCheck-SQLInjection
715 */
716 public function showDetails( $id ) {
717 $out = $this->getOutput();
718 $performer = $this->getAuthority();
719
720 $pager = new AbuseLogPager(
721 $this->getContext(),
722 $this->getLinkRenderer(),
723 [],
724 $this->linkBatchFactory,
725 $this->permissionManager,
726 $this->afPermissionManager,
727 $this->getName()
728 );
729
730 [
731 'tables' => $tables,
732 'fields' => $fields,
733 'join_conds' => $join_conds,
734 ] = $pager->getQueryInfo();
735
736 $dbr = $this->lbFactory->getReplicaDatabase();
737 $row = $dbr->newSelectQueryBuilder()
738 ->tables( $tables )
739 ->fields( $fields )
740 ->where( [ 'afl_id' => $id ] )
741 ->caller( __METHOD__ )
742 ->joinConds( $join_conds )
743 ->fetchRow();
744
745 $error = null;
746 $privacyLevel = Flags::FILTER_PUBLIC;
747 if ( !$row ) {
748 $error = 'abusefilter-log-nonexistent';
749 } else {
750 $filterID = $row->afl_filter_id;
751 $global = $row->afl_global;
752
753 $privacyLevel = $row->af_hidden;
754 if ( $global ) {
755 try {
756 $privacyLevel = AbuseFilterServices::getFilterLookup()->getFilter( $filterID, $global )
757 ->getPrivacyLevel();
758 } catch ( CentralDBNotAvailableException $_ ) {
759 // Conservatively assume that it's hidden and protected, like in AbuseLogPager::doFormatRow
760 $privacyLevel = Flags::FILTER_HIDDEN | Flags::FILTER_USES_PROTECTED_VARS;
761 }
762 }
763
764 if ( !$this->afPermissionManager->canSeeLogDetailsForFilter( $performer, $privacyLevel ) ) {
765 $error = 'abusefilter-log-cannot-see-details';
766 } else {
767 $visibility = self::getEntryVisibilityForUser( $row, $performer, $this->afPermissionManager );
768 if ( $visibility === self::VISIBILITY_HIDDEN ) {
769 $error = 'abusefilter-log-details-hidden';
770 } elseif ( $visibility === self::VISIBILITY_HIDDEN_IMPLICIT ) {
771 $error = 'abusefilter-log-details-hidden-implicit';
772 }
773 }
774
775 // Only show the preference error if another error isn't already set
776 // as this error shouldn't take precedence over a view permission error
777 if (
778 FilterUtils::isProtected( $privacyLevel ) &&
779 !$this->afPermissionManager->canViewProtectedVariableValues( $performer ) &&
780 !$error
781 ) {
782 $error = 'abusefilter-examine-protected-vars-permission';
783 }
784 }
785
786 if ( $error ) {
787 $out->addWikiMsg( $error );
788 return;
789 }
790
791 $output = Html::element(
792 'legend',
793 [],
794 $this->msg( 'abusefilter-log-details-legend' )
795 ->params( $this->getLanguage()->formatNumNoSeparators( $id ) )
796 ->text()
797 );
798 $output .= Html::rawElement( 'p', [], $pager->doFormatRow( $row, false ) );
799
800 // Load data
801 $vars = $this->varBlobStore->loadVarDump( $row );
802 $varsArray = $this->varManager->dumpAllVars( $vars, $this->afPermissionManager->getProtectedVariables() );
803 $shouldLogProtectedVarAccess = false;
804
805 // If a non-protected filter and a protected filter have overlapping conditions,
806 // it's possible for a hit to contain a protected variable and for that variable
807 // to be dumped and displayed on a detail page that wouldn't be considered
808 // protected (because it caught on the public filter).
809 // We shouldn't block access to the details of an otherwise public filter hit so
810 // instead only check for access to the protected variables and redact them if the user
811 // shouldn't see them.
812 $userAuthority = $this->getAuthority();
813 $canViewProtectedVars = $this->afPermissionManager->canViewProtectedVariableValues( $userAuthority );
814 foreach ( $this->afPermissionManager->getProtectedVariables() as $protectedVariable ) {
815 if ( isset( $varsArray[$protectedVariable] ) ) {
816 if ( !$canViewProtectedVars ) {
817 $varsArray[$protectedVariable] = '';
818 } else {
819 // Protected variables in protected filters logs access in the general permission check
820 // Log access to non-protected filters that happen to expose protected variables here
821 if ( !FilterUtils::isProtected( $privacyLevel ) ) {
822 $shouldLogProtectedVarAccess = true;
823 }
824 }
825 }
826 }
827 $vars = VariableHolder::newFromArray( $varsArray );
828
829 // Log if protected variables are accessed
830 if (
831 FilterUtils::isProtected( $privacyLevel ) &&
832 $canViewProtectedVars
833 ) {
834 $shouldLogProtectedVarAccess = true;
835 }
836
837 if ( $shouldLogProtectedVarAccess ) {
838 $logger = $this->abuseLoggerFactory->getProtectedVarsAccessLogger();
839 $logger->logViewProtectedVariableValue(
840 $userAuthority->getUser(),
841 $varsArray['user_name'] ?? $varsArray['accountname']
842 );
843 }
844
845 $out->addJsConfigVars( 'wgAbuseFilterVariables', $varsArray );
846 $out->addModuleStyles( 'mediawiki.interface.helpers.styles' );
847
848 // Diff, if available
849 if ( $row->afl_action === 'edit' ) {
850 // Guard for exception because these variables may be unset in case of data corruption (T264513)
851 // No need to lazy-load as these come from a DB dump.
852 try {
853 $old_wikitext = $vars->getComputedVariable( 'old_wikitext' )->toString();
854 } catch ( UnsetVariableException $_ ) {
855 $old_wikitext = '';
856 }
857 try {
858 $new_wikitext = $vars->getComputedVariable( 'new_wikitext' )->toString();
859 } catch ( UnsetVariableException $_ ) {
860 $new_wikitext = '';
861 }
862
863 $diffEngine = new DifferenceEngine( $this->getContext() );
864
865 $diffEngine->showDiffStyle();
866
867 $formattedDiff = $diffEngine->addHeader(
868 $diffEngine->generateTextDiffBody( $old_wikitext, $new_wikitext ),
869 '', ''
870 );
871
872 $output .=
873 Html::rawElement(
874 'h3',
875 [],
876 $this->msg( 'abusefilter-log-details-diff' )->parse()
877 );
878
879 $output .= $formattedDiff;
880 }
881
882 $output .= Html::element( 'h3', [], $this->msg( 'abusefilter-log-details-vars' )->text() );
883
884 // Build a table.
885 $output .= $this->variablesFormatter->buildVarDumpTable( $vars );
886
887 if ( $this->afPermissionManager->canSeePrivateDetails( $performer ) ) {
888 $formDescriptor = [
889 'Reason' => [
890 'label-message' => 'abusefilter-view-privatedetails-reason',
891 'type' => 'text',
892 'size' => 45,
893 ],
894 ];
895
896 $htmlForm = HTMLForm::factory( 'ooui', $formDescriptor, $this->getContext() );
897 $htmlForm->setTitle( $this->getPageTitle( 'private/' . $id ) )
898 ->setWrapperLegendMsg( 'abusefilter-view-privatedetails-legend' )
899 ->setSubmitTextMsg( 'abusefilter-view-privatedetails-submit' )
900 ->prepareForm();
901
902 $output .= $htmlForm->getHTML( false );
903 }
904
905 $out->addHTML( Html::rawElement( 'fieldset', [], $output ) );
906 }
907
908 /**
909 * Helper function to select a row with private details and some more context
910 * for an AbuseLog entry.
911 * @todo Create a service for this
912 *
913 * @param Authority $authority The user who's trying to view the row
914 * @param int $id The ID of the log entry
915 * @return Status A status object with the requested row stored in the value property,
916 * or an error and no row.
917 */
918 public static function getPrivateDetailsRow( Authority $authority, $id ) {
919 $afPermissionManager = AbuseFilterServices::getPermissionManager();
920 $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
921
922 $row = $dbr->newSelectQueryBuilder()
923 ->select( [ 'afl_id', 'afl_user_text', 'afl_filter_id', 'afl_global', 'afl_timestamp', 'afl_ip',
924 'af_id', 'af_public_comments', 'af_hidden' ] )
925 ->from( 'abuse_filter_log' )
926 ->leftJoin( 'abuse_filter', null, [ 'af_id=afl_filter_id', 'afl_global' => 0 ] )
927 ->where( [ 'afl_id' => $id ] )
928 ->caller( __METHOD__ )
929 ->fetchRow();
930
931 $status = Status::newGood();
932 if ( !$row ) {
933 $status->fatal( 'abusefilter-log-nonexistent' );
934 return $status;
935 }
936
937 $filterID = $row->afl_filter_id;
938 $global = $row->afl_global;
939
940 if ( $global ) {
941 $lookup = AbuseFilterServices::getFilterLookup();
942 $privacyLevel = $lookup->getFilter( $filterID, $global )->getPrivacyLevel();
943 } else {
944 $privacyLevel = $row->af_hidden;
945 }
946
947 if ( !$afPermissionManager->canSeeLogDetailsForFilter( $authority, $privacyLevel ) ) {
948 $status->fatal( 'abusefilter-log-cannot-see-details' );
949 return $status;
950 }
951 $status->setResult( true, $row );
952 return $status;
953 }
954
955 /**
956 * Builds an HTML table with the private details for a given abuseLog entry.
957 *
958 * @param stdClass $row The row, as returned by self::getPrivateDetailsRow()
959 * @return string The HTML output
960 */
961 private function buildPrivateDetailsTable( $row ) {
962 $output = '';
963
964 // Log ID
965 $linkRenderer = $this->getLinkRenderer();
966 $output .=
967 Html::rawElement( 'tr', [],
968 Html::element( 'td',
969 [ 'style' => 'width: 30%;' ],
970 $this->msg( 'abusefilter-log-details-id' )->text()
971 ) .
972 Html::rawElement( 'td', [], $linkRenderer->makeKnownLink(
973 $this->getPageTitle( $row->afl_id ),
974 $this->getLanguage()->formatNumNoSeparators( $row->afl_id )
975 ) )
976 );
977
978 // Timestamp
979 $output .=
980 Html::rawElement( 'tr', [],
981 Html::element( 'td',
982 [ 'style' => 'width: 30%;' ],
983 $this->msg( 'abusefilter-edit-builder-vars-timestamp-expanded' )->text()
984 ) .
985 Html::element( 'td',
986 [],
987 $this->getLanguage()->userTimeAndDate( $row->afl_timestamp, $this->getUser() )
988 )
989 );
990
991 // User
992 $output .=
993 Html::rawElement( 'tr', [],
994 Html::element( 'td',
995 [ 'style' => 'width: 30%;' ],
996 $this->msg( 'abusefilter-edit-builder-vars-user-name' )->text()
997 ) .
998 Html::element( 'td',
999 [],
1000 $row->afl_user_text
1001 )
1002 );
1003
1004 // Filter ID
1005 $output .=
1006 Html::rawElement( 'tr', [],
1007 Html::element( 'td',
1008 [ 'style' => 'width: 30%;' ],
1009 $this->msg( 'abusefilter-list-id' )->text()
1010 ) .
1011 Html::rawElement( 'td', [], $linkRenderer->makeKnownLink(
1012 SpecialPage::getTitleFor( 'AbuseFilter', $row->af_id ),
1013 $this->getLanguage()->formatNum( $row->af_id )
1014 ) )
1015 );
1016
1017 // Filter description
1018 $output .=
1019 Html::rawElement( 'tr', [],
1020 Html::element( 'td',
1021 [ 'style' => 'width: 30%;' ],
1022 $this->msg( 'abusefilter-list-public' )->text()
1023 ) .
1024 Html::element( 'td',
1025 [],
1026 $row->af_public_comments
1027 )
1028 );
1029
1030 // IP address
1031 if ( $row->afl_ip !== '' ) {
1032 if ( ExtensionRegistry::getInstance()->isLoaded( 'CheckUser' ) &&
1033 $this->permissionManager->userHasRight( $this->getUser(), 'checkuser' )
1034 ) {
1035 $CULink = '&nbsp;&middot;&nbsp;' . $linkRenderer->makeKnownLink(
1036 SpecialPage::getTitleFor(
1037 'CheckUser',
1038 $row->afl_ip
1039 ),
1040 $this->msg( 'abusefilter-log-details-checkuser' )->text()
1041 );
1042 } else {
1043 $CULink = '';
1044 }
1045 $output .=
1046 Html::rawElement( 'tr', [],
1047 Html::element( 'td',
1048 [ 'style' => 'width: 30%;' ],
1049 $this->msg( 'abusefilter-log-details-ip' )->text()
1050 ) .
1051 Html::rawElement(
1052 'td',
1053 [],
1054 self::getUserLinks( 0, $row->afl_ip ) . $CULink
1055 )
1056 );
1057 } else {
1058 $output .=
1059 Html::rawElement( 'tr', [],
1060 Html::element( 'td',
1061 [ 'style' => 'width: 30%;' ],
1062 $this->msg( 'abusefilter-log-details-ip' )->text()
1063 ) .
1064 Html::element(
1065 'td',
1066 [],
1067 $this->msg( 'abusefilter-log-ip-not-available' )->text()
1068 )
1069 );
1070 }
1071
1072 return Html::rawElement( 'fieldset', [],
1073 Html::element( 'legend', [],
1074 $this->msg( 'abusefilter-log-details-privatedetails' )->text()
1075 ) .
1076 Html::rawElement( 'table',
1077 [
1078 'class' => 'wikitable mw-abuselog-private',
1079 'style' => 'width: 80%;'
1080 ],
1081 Html::rawElement( 'thead', [],
1082 Html::rawElement( 'tr', [],
1083 Html::element( 'th', [],
1084 $this->msg( 'abusefilter-log-details-var' )->text()
1085 ) .
1086 Html::element( 'th', [],
1087 $this->msg( 'abusefilter-log-details-val' )->text()
1088 )
1089 )
1090 ) .
1091 Html::rawElement( 'tbody', [], $output )
1092 )
1093 );
1094 }
1095
1096 /**
1097 * @param int $id
1098 * @return void
1099 */
1100 public function showPrivateDetails( $id ) {
1101 $out = $this->getOutput();
1102 $user = $this->getUser();
1103
1104 if ( !$this->afPermissionManager->canSeePrivateDetails( $user ) ) {
1105 $out->addWikiMsg( 'abusefilter-log-cannot-see-privatedetails' );
1106
1107 return;
1108 }
1109 $request = $this->getRequest();
1110
1111 // Make sure it is a valid request
1112 $token = $request->getVal( 'wpEditToken' );
1113 if ( !$request->wasPosted() || !$user->matchEditToken( $token ) ) {
1114 $out->addHTML(
1115 Html::rawElement(
1116 'p',
1117 [],
1118 Html::errorBox( $this->msg( 'abusefilter-invalid-request' )->params( $id )->parse() )
1119 )
1120 );
1121
1122 return;
1123 }
1124
1125 $reason = $request->getText( 'wpReason' );
1126 if ( !self::checkPrivateDetailsAccessReason( $reason ) ) {
1127 $out->addWikiMsg( 'abusefilter-noreason' );
1128 $this->showDetails( $id );
1129 return;
1130 }
1131
1132 $status = self::getPrivateDetailsRow( $user, $id );
1133 if ( !$status->isGood() ) {
1134 $out->addWikiMsg( $status->getMessages()[0] );
1135 return;
1136 }
1137 $row = $status->getValue();
1138
1139 // Log accessing private details
1140 if ( $this->getConfig()->get( 'AbuseFilterLogPrivateDetailsAccess' ) ) {
1141 self::addPrivateDetailsAccessLogEntry( $id, $reason, $user );
1142 }
1143
1144 // Show private details (IP).
1145 $table = $this->buildPrivateDetailsTable( $row );
1146 $out->addHTML( $table );
1147 }
1148
1149 /**
1150 * If specifying a reason for viewing private details of abuse log is required
1151 * then it makes sure that a reason is provided.
1152 *
1153 * @param string $reason
1154 * @return bool
1155 */
1156 public static function checkPrivateDetailsAccessReason( $reason ) {
1157 global $wgAbuseFilterPrivateDetailsForceReason;
1158 return ( !$wgAbuseFilterPrivateDetailsForceReason || strlen( $reason ) > 0 );
1159 }
1160
1161 /**
1162 * @param int $logID int The ID of the AbuseFilter log that was accessed
1163 * @param string $reason The reason provided for accessing private details
1164 * @param UserIdentity $userIdentity The user who accessed the private details
1165 * @return void
1166 */
1167 public static function addPrivateDetailsAccessLogEntry( $logID, $reason, UserIdentity $userIdentity ) {
1168 $target = self::getTitleFor( self::PAGE_NAME, (string)$logID );
1169
1170 $logEntry = new ManualLogEntry( 'abusefilterprivatedetails', 'access' );
1171 $logEntry->setPerformer( $userIdentity );
1172 $logEntry->setTarget( $target );
1173 $logEntry->setParameters( [
1174 '4::logid' => $logID,
1175 ] );
1176 $logEntry->setComment( $reason );
1177
1178 $logEntry->insert();
1179 }
1180
1181 /**
1182 * @param int $userId
1183 * @param string $userName
1184 * @return string
1185 */
1186 public static function getUserLinks( $userId, $userName ) {
1187 static $cache = [];
1188
1189 if ( !isset( $cache[$userName][$userId] ) ) {
1190 $cache[$userName][$userId] = Linker::userLink( $userId, $userName ) .
1191 Linker::userToolLinks( $userId, $userName, true );
1192 }
1193
1194 return $cache[$userName][$userId];
1195 }
1196
1197 /**
1198 * @param stdClass $row
1199 * @param Authority $authority
1200 * @param AbuseFilterPermissionManager $afPermissionManager
1201 * @return string One of the self::VISIBILITY_* constants
1202 */
1203 public static function getEntryVisibilityForUser(
1204 stdClass $row,
1205 Authority $authority,
1206 AbuseFilterPermissionManager $afPermissionManager
1207 ): string {
1208 if ( $row->afl_deleted && !$afPermissionManager->canSeeHiddenLogEntries( $authority ) ) {
1209 return self::VISIBILITY_HIDDEN;
1210 }
1211 if ( !$row->afl_rev_id ) {
1212 return self::VISIBILITY_VISIBLE;
1213 }
1214 $vis = (int)MediaWikiServices::getInstance()
1215 ->getRevisionLookup()
1216 ->getRevisionById( (int)$row->afl_rev_id )
1217 ?->getVisibility();
1218 if ( $vis === 0 ) {
1219 return self::VISIBILITY_VISIBLE;
1220 }
1221
1222 return AbuseFilterPermissionManager::hasRevisionAccess( $vis, $authority )
1223 ? self::VISIBILITY_VISIBLE
1224 : self::VISIBILITY_HIDDEN_IMPLICIT;
1225 }
1226 }