Debian Codegraph @

includes/specials/pagers/BlockListPager.php

raw symbols SCIP
1 <?php
2 /**
3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
17 *
18 * @file
19 * @ingroup Pager
20 */
21
22 namespace MediaWiki\Pager;
23
24 use MediaWiki\Block\Block;
25 use MediaWiki\Block\BlockActionInfo;
26 use MediaWiki\Block\BlockRestrictionStore;
27 use MediaWiki\Block\BlockUtils;
28 use MediaWiki\Block\HideUserUtils;
29 use MediaWiki\Block\Restriction\ActionRestriction;
30 use MediaWiki\Block\Restriction\NamespaceRestriction;
31 use MediaWiki\Block\Restriction\PageRestriction;
32 use MediaWiki\Block\Restriction\Restriction;
33 use MediaWiki\Cache\LinkBatchFactory;
34 use MediaWiki\CommentFormatter\RowCommentFormatter;
35 use MediaWiki\CommentStore\CommentStore;
36 use MediaWiki\Context\IContextSource;
37 use MediaWiki\Html\Html;
38 use MediaWiki\Linker\Linker;
39 use MediaWiki\Linker\LinkRenderer;
40 use MediaWiki\MainConfigNames;
41 use MediaWiki\SpecialPage\SpecialPageFactory;
42 use MediaWiki\User\UserIdentity;
43 use MediaWiki\Utils\MWTimestamp;
44 use stdClass;
45 use Wikimedia\Rdbms\IConnectionProvider;
46 use Wikimedia\Rdbms\IResultWrapper;
47
48 /**
49 * @ingroup Pager
50 */
51 class BlockListPager extends TablePager {
52
53 /** @var array */
54 protected $conds;
55
56 /**
57 * Array of restrictions.
58 *
59 * @var Restriction[]
60 */
61 protected $restrictions = [];
62
63 private BlockActionInfo $blockActionInfo;
64 private BlockRestrictionStore $blockRestrictionStore;
65 private BlockUtils $blockUtils;
66 private HideUserUtils $hideUserUtils;
67 private CommentStore $commentStore;
68 private LinkBatchFactory $linkBatchFactory;
69 private RowCommentFormatter $rowCommentFormatter;
70 private SpecialPageFactory $specialPageFactory;
71
72 /** @var string[] */
73 private $formattedComments = [];
74
75 /** @var string[] Cache of messages to avoid them being recreated for every row of the pager. */
76 private $messages = [];
77
78 /**
79 * @param IContextSource $context
80 * @param BlockActionInfo $blockActionInfo
81 * @param BlockRestrictionStore $blockRestrictionStore
82 * @param BlockUtils $blockUtils
83 * @param HideUserUtils $hideUserUtils
84 * @param CommentStore $commentStore
85 * @param LinkBatchFactory $linkBatchFactory
86 * @param LinkRenderer $linkRenderer
87 * @param IConnectionProvider $dbProvider
88 * @param RowCommentFormatter $rowCommentFormatter
89 * @param SpecialPageFactory $specialPageFactory
90 * @param array $conds
91 */
92 public function __construct(
93 IContextSource $context,
94 BlockActionInfo $blockActionInfo,
95 BlockRestrictionStore $blockRestrictionStore,
96 BlockUtils $blockUtils,
97 HideUserUtils $hideUserUtils,
98 CommentStore $commentStore,
99 LinkBatchFactory $linkBatchFactory,
100 LinkRenderer $linkRenderer,
101 IConnectionProvider $dbProvider,
102 RowCommentFormatter $rowCommentFormatter,
103 SpecialPageFactory $specialPageFactory,
104 $conds
105 ) {
106 // Set database before parent constructor to avoid setting it there
107 $this->mDb = $dbProvider->getReplicaDatabase();
108
109 parent::__construct( $context, $linkRenderer );
110
111 $this->blockActionInfo = $blockActionInfo;
112 $this->blockRestrictionStore = $blockRestrictionStore;
113 $this->blockUtils = $blockUtils;
114 $this->hideUserUtils = $hideUserUtils;
115 $this->commentStore = $commentStore;
116 $this->linkBatchFactory = $linkBatchFactory;
117 $this->rowCommentFormatter = $rowCommentFormatter;
118 $this->specialPageFactory = $specialPageFactory;
119 $this->conds = $conds;
120 $this->mDefaultDirection = IndexPager::DIR_DESCENDING;
121 }
122
123 protected function getFieldNames() {
124 static $headers = null;
125
126 if ( $headers === null ) {
127 $headers = [
128 'bl_timestamp' => 'blocklist-timestamp',
129 'target' => 'blocklist-target',
130 'bl_expiry' => 'blocklist-expiry',
131 'by' => 'blocklist-by',
132 'params' => 'blocklist-params',
133 'bl_reason' => 'blocklist-reason',
134 ];
135 foreach ( $headers as $key => $val ) {
136 $headers[$key] = $this->msg( $val )->text();
137 }
138 }
139
140 return $headers;
141 }
142
143 /**
144 * @param string $name
145 * @param string|null $value
146 * @return string
147 */
148 public function formatValue( $name, $value ) {
149 if ( $this->messages === [] ) {
150 $keys = [
151 'anononlyblock',
152 'blanknamespace',
153 'createaccountblock',
154 'noautoblockblock',
155 'emailblock',
156 'blocklist-nousertalk',
157 'unblocklink',
158 'change-blocklink',
159 'blocklist-editing',
160 'blocklist-editing-sitewide',
161 'blocklist-hidden-param',
162 'blocklist-hidden-placeholder',
163 ];
164
165 foreach ( $keys as $key ) {
166 $this->messages[$key] = $this->msg( $key )->text();
167 }
168 }
169
170 /** @var stdClass $row */
171 $row = $this->mCurrentRow;
172
173 $language = $this->getLanguage();
174
175 $linkRenderer = $this->getLinkRenderer();
176
177 switch ( $name ) {
178 case 'bl_timestamp':
179 // Link the timestamp to the block ID. This allows users without permissions to change blocks
180 // to be able to generate a link to a specific block.
181 $formatted = $linkRenderer->makeKnownLink(
182 $this->specialPageFactory->getTitleForAlias( 'BlockList' ),
183 $language->userTimeAndDate( $value, $this->getUser() ),
184 [],
185 [ 'wpTarget' => "#{$row->bl_id}" ],
186 );
187 break;
188
189 case 'target':
190 $formatted = $this->formatTarget( $row );
191 break;
192
193 case 'bl_expiry':
194 $formatted = htmlspecialchars( $language->formatExpiry(
195 $value,
196 /* User preference timezone */true,
197 'infinity',
198 $this->getUser()
199 ) );
200 if ( $this->getAuthority()->isAllowed( 'block' ) ) {
201 $links = [];
202 if ( $row->bt_auto ) {
203 $links[] = $linkRenderer->makeKnownLink(
204 $this->specialPageFactory->getTitleForAlias( 'Unblock' ),
205 $this->messages['unblocklink'],
206 [],
207 [ 'wpTarget' => "#{$row->bl_id}" ]
208 );
209 } else {
210 $target = $row->bt_address ?? $row->bt_user_text;
211 $links[] = $linkRenderer->makeKnownLink(
212 $this->specialPageFactory->getTitleForAlias( "Unblock/$target" ),
213 $this->messages['unblocklink']
214 );
215 $links[] = $linkRenderer->makeKnownLink(
216 $this->specialPageFactory->getTitleForAlias( "Block/$target" ),
217 $this->messages['change-blocklink']
218 );
219 }
220 $formatted .= ' ' . Html::rawElement(
221 'span',
222 [ 'class' => 'mw-blocklist-actions' ],
223 $this->msg( 'parentheses' )->rawParams(
224 $language->pipeList( $links ) )->escaped()
225 );
226 }
227 if ( $value !== 'infinity' ) {
228 $timestamp = new MWTimestamp( $value );
229 $formatted .= '<br />' . $this->msg(
230 'ipb-blocklist-duration-left',
231 $language->formatDurationBetweenTimestamps(
232 (int)$timestamp->getTimestamp( TS_UNIX ),
233 MWTimestamp::time(),
234 4
235 )
236 )->escaped();
237 }
238 break;
239
240 case 'by':
241 $formatted = Linker::userLink( (int)$value, $row->bl_by_text );
242 $formatted .= Linker::userToolLinks( (int)$value, $row->bl_by_text );
243 break;
244
245 case 'bl_reason':
246 $formatted = $this->formattedComments[$this->getResultOffset()];
247 break;
248
249 case 'params':
250 $properties = [];
251
252 if ( $row->bl_deleted ) {
253 $properties[] = htmlspecialchars( $this->messages['blocklist-hidden-param' ] );
254 }
255 if ( $row->bl_sitewide ) {
256 $properties[] = htmlspecialchars( $this->messages['blocklist-editing-sitewide'] );
257 }
258
259 if ( !$row->bl_sitewide && $this->restrictions ) {
260 $list = $this->getRestrictionListHTML( $row );
261 if ( $list ) {
262 $properties[] = htmlspecialchars( $this->messages['blocklist-editing'] ) . $list;
263 }
264 }
265
266 if ( $row->bl_anon_only ) {
267 $properties[] = htmlspecialchars( $this->messages['anononlyblock'] );
268 }
269 if ( $row->bl_create_account ) {
270 $properties[] = htmlspecialchars( $this->messages['createaccountblock'] );
271 }
272 if ( $row->bt_user && !$row->bl_enable_autoblock ) {
273 $properties[] = htmlspecialchars( $this->messages['noautoblockblock'] );
274 }
275
276 if ( $row->bl_block_email ) {
277 $properties[] = htmlspecialchars( $this->messages['emailblock'] );
278 }
279
280 if ( !$row->bl_allow_usertalk ) {
281 $properties[] = htmlspecialchars( $this->messages['blocklist-nousertalk'] );
282 }
283
284 $formatted = Html::rawElement(
285 'ul',
286 [],
287 implode( '', array_map( static function ( $prop ) {
288 return Html::rawElement(
289 'li',
290 [],
291 $prop
292 );
293 }, $properties ) )
294 );
295 break;
296
297 default:
298 $formatted = "Unable to format $name";
299 break;
300 }
301
302 return $formatted;
303 }
304
305 /**
306 * Format the target field
307 * @param stdClass $row
308 * @return string
309 */
310 private function formatTarget( $row ) {
311 if ( $row->bt_auto ) {
312 return $this->msg( 'autoblockid', $row->bl_id )->parse();
313 }
314
315 [ $target, $type ] = $this->blockUtils->parseBlockTargetRow( $row );
316
317 if ( $type === Block::TYPE_RANGE ) {
318 $userId = 0;
319 $userName = $target;
320 } elseif ( ( $row->hu_deleted ?? null )
321 && !$this->getAuthority()->isAllowed( 'hideuser' )
322 ) {
323 return Html::element(
324 'span',
325 [ 'class' => 'mw-blocklist-hidden' ],
326 $this->messages['blocklist-hidden-placeholder']
327 );
328 } elseif ( $target instanceof UserIdentity ) {
329 $userId = $target->getId();
330 $userName = $target->getName();
331 } elseif ( is_string( $target ) ) {
332 return htmlspecialchars( $target );
333 } else {
334 return $this->msg( 'empty-username' )->escaped();
335 }
336 return Linker::userLink( $userId, $userName ) .
337 Linker::userToolLinks(
338 $userId,
339 $userName,
340 false,
341 Linker::TOOL_LINKS_NOBLOCK
342 );
343 }
344
345 /**
346 * Get Restriction List HTML
347 *
348 * @param stdClass $row
349 *
350 * @return string
351 */
352 private function getRestrictionListHTML( stdClass $row ) {
353 $items = [];
354 $linkRenderer = $this->getLinkRenderer();
355
356 foreach ( $this->restrictions as $restriction ) {
357 if ( $restriction->getBlockId() !== (int)$row->bl_id ) {
358 continue;
359 }
360
361 switch ( $restriction->getType() ) {
362 case PageRestriction::TYPE:
363 '@phan-var PageRestriction $restriction';
364 if ( $restriction->getTitle() ) {
365 $items[$restriction->getType()][] = Html::rawElement(
366 'li',
367 [],
368 $linkRenderer->makeLink( $restriction->getTitle() )
369 );
370 }
371 break;
372 case NamespaceRestriction::TYPE:
373 $text = $restriction->getValue() === NS_MAIN
374 ? $this->messages['blanknamespace']
375 : $this->getLanguage()->getFormattedNsText(
376 $restriction->getValue()
377 );
378 if ( $text ) {
379 $items[$restriction->getType()][] = Html::rawElement(
380 'li',
381 [],
382 $linkRenderer->makeLink(
383 $this->specialPageFactory->getTitleForAlias( 'Allpages' ),
384 $text,
385 [],
386 [
387 'namespace' => $restriction->getValue()
388 ]
389 )
390 );
391 }
392 break;
393 case ActionRestriction::TYPE:
394 $actionName = $this->blockActionInfo->getActionFromId( $restriction->getValue() );
395 $enablePartialActionBlocks =
396 $this->getConfig()->get( MainConfigNames::EnablePartialActionBlocks );
397 if ( $actionName && $enablePartialActionBlocks ) {
398 $items[$restriction->getType()][] = Html::rawElement(
399 'li',
400 [],
401 // The following messages may be used here:
402 // * ipb-action-create
403 // * ipb-action-move
404 // * ipb-action-upload
405 $this->msg( 'ipb-action-' .
406 $this->blockActionInfo->getActionFromId( $restriction->getValue() ) )->escaped()
407 );
408 }
409 break;
410 }
411 }
412
413 if ( !$items ) {
414 return '';
415 }
416
417 $sets = [];
418 foreach ( $items as $key => $value ) {
419 $sets[] = Html::rawElement(
420 'li',
421 [],
422 // The following messages may be used here:
423 // * blocklist-editing-sitewide
424 // * blocklist-editing-page
425 // * blocklist-editing-ns
426 // * blocklist-editing-action
427 $this->msg( 'blocklist-editing-' . $key ) . Html::rawElement(
428 'ul',
429 [],
430 implode( '', $value )
431 )
432 );
433 }
434
435 return Html::rawElement(
436 'ul',
437 [],
438 implode( '', $sets )
439 );
440 }
441
442 public function getQueryInfo() {
443 $db = $this->getDatabase();
444 $commentQuery = $this->commentStore->getJoin( 'bl_reason' );
445 $info = [
446 'tables' => array_merge(
447 [
448 'block',
449 'block_by_actor' => 'actor',
450 'block_target',
451 ],
452 $commentQuery['tables']
453 ),
454 'fields' => [
455 // The target fields should be those accepted by BlockUtils::parseBlockTargetRow()
456 'bt_address',
457 'bt_user_text',
458 'bt_user',
459 'bt_auto',
460 'bt_range_start',
461 'bt_range_end',
462 // Block fields and aliases
463 'bl_id',
464 'bl_by' => 'block_by_actor.actor_user',
465 'bl_by_text' => 'block_by_actor.actor_name',
466 'bl_timestamp',
467 'bl_anon_only',
468 'bl_create_account',
469 'bl_enable_autoblock',
470 'bl_expiry',
471 'bl_deleted',
472 'bl_block_email',
473 'bl_allow_usertalk',
474 'bl_sitewide',
475 ] + $commentQuery['fields'],
476 'conds' => $this->conds,
477 'join_conds' => [
478 'block_by_actor' => [ 'JOIN', 'actor_id=bl_by_actor' ],
479 'block_target' => [ 'JOIN', 'bt_id=bl_target' ],
480 ] + $commentQuery['joins']
481 ];
482
483 # Filter out any expired blocks
484 $info['conds'][] = $db->expr( 'bl_expiry', '>', $db->timestamp() );
485
486 # Filter out blocks with the deleted option if the user doesn't
487 # have permission to see hidden users
488 # TODO: consider removing this -- we could just redact them instead.
489 # The mere fact that an admin has deleted a user does not need to
490 # be private and could be included in block lists and logs for
491 # transparency purposes. Previously, filtering out deleted blocks
492 # was a convenient way to avoid showing the target name.
493 if ( $this->getAuthority()->isAllowed( 'hideuser' ) ) {
494 $info['fields']['hu_deleted'] = $this->hideUserUtils->getExpression(
495 $db,
496 'block_target.bt_user',
497 HideUserUtils::HIDDEN_USERS
498 );
499 } else {
500 $info['fields']['hu_deleted'] = 0;
501 $info['conds'][] = $this->hideUserUtils->getExpression(
502 $db,
503 'block_target.bt_user',
504 HideUserUtils::SHOWN_USERS
505 );
506 $info['conds']['bl_deleted'] = 0;
507 }
508 return $info;
509 }
510
511 protected function getTableClass() {
512 return parent::getTableClass() . ' mw-blocklist';
513 }
514
515 public function getIndexField() {
516 return [ [ 'bl_timestamp', 'bl_id' ] ];
517 }
518
519 public function getDefaultSort() {
520 return '';
521 }
522
523 protected function isFieldSortable( $name ) {
524 return false;
525 }
526
527 /**
528 * Do a LinkBatch query to minimise database load when generating all these links
529 * @param IResultWrapper $result
530 */
531 public function preprocessResults( $result ) {
532 // Do a link batch query
533 $lb = $this->linkBatchFactory->newLinkBatch();
534 $lb->setCaller( __METHOD__ );
535
536 $partialBlocks = [];
537 foreach ( $result as $row ) {
538 $target = $row->bt_address ?? $row->bt_user_text;
539 if ( $target !== null ) {
540 $lb->add( NS_USER, $target );
541 $lb->add( NS_USER_TALK, $target );
542 }
543
544 if ( isset( $row->bl_by_text ) ) {
545 $lb->add( NS_USER, $row->bl_by_text );
546 $lb->add( NS_USER_TALK, $row->bl_by_text );
547 }
548
549 if ( !$row->bl_sitewide ) {
550 $partialBlocks[] = (int)$row->bl_id;
551 }
552 }
553
554 if ( $partialBlocks ) {
555 // Mutations to the $row object are not persisted. The restrictions will
556 // need be stored in a separate store.
557 $this->restrictions = $this->blockRestrictionStore->loadByBlockId( $partialBlocks );
558
559 foreach ( $this->restrictions as $restriction ) {
560 if ( $restriction->getType() === PageRestriction::TYPE ) {
561 '@phan-var PageRestriction $restriction';
562 $title = $restriction->getTitle();
563 if ( $title ) {
564 $lb->addObj( $title );
565 }
566 }
567 }
568 }
569
570 $lb->execute();
571
572 // Format comments
573 // The keys of formattedComments will be the corresponding offset into $result
574 $this->formattedComments = $this->rowCommentFormatter->formatRows( $result, 'bl_reason' );
575 }
576
577 }
578
579 /**
580 * Retain the old class name for backwards compatibility.
581 * @deprecated since 1.41
582 */
583 class_alias( BlockListPager::class, 'BlockListPager' );