Selenium: replace UserLoginPage with BlankPage where possible
[lhc/web/wiklou.git] / includes / Block.php
1 <?php
2 /**
3 * Class for blocks stored in the database.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use Wikimedia\Rdbms\Database;
24 use Wikimedia\Rdbms\IDatabase;
25 use MediaWiki\Block\AbstractBlock;
26 use MediaWiki\Block\BlockRestrictionStore;
27 use MediaWiki\Block\Restriction\Restriction;
28 use MediaWiki\Block\Restriction\NamespaceRestriction;
29 use MediaWiki\Block\Restriction\PageRestriction;
30 use MediaWiki\MediaWikiServices;
31
32 /**
33 * Blocks (as opposed to system blocks) are stored in the database, may
34 * give rise to autoblocks and may be tracked with cookies. Blocks are
35 * more customizable than system blocks: they may be hardblocks, and
36 * they may be sitewide or partial.
37 */
38 class Block extends AbstractBlock {
39 /** @var bool */
40 public $mAuto;
41
42 /** @var int */
43 public $mParentBlockId;
44
45 /** @var int */
46 private $mId;
47
48 /** @var bool */
49 private $mFromMaster;
50
51 /** @var int Hack for foreign blocking (CentralAuth) */
52 private $forcedTargetID;
53
54 /** @var bool */
55 private $isHardblock;
56
57 /** @var bool */
58 private $isAutoblocking;
59
60 /** @var Restriction[] */
61 private $restrictions;
62
63 /**
64 * Create a new block with specified option parameters on a user, IP or IP range.
65 *
66 * @param array $options Parameters of the block:
67 * user int Override target user ID (for foreign users)
68 * auto bool Is this an automatic block?
69 * expiry string Timestamp of expiration of the block or 'infinity'
70 * anonOnly bool Only disallow anonymous actions
71 * createAccount bool Disallow creation of new accounts
72 * enableAutoblock bool Enable automatic blocking
73 * hideName bool Hide the target user name
74 * blockEmail bool Disallow sending emails
75 * allowUsertalk bool Allow the target to edit its own talk page
76 * sitewide bool Disallow editing all pages and all contribution
77 * actions, except those specifically allowed by
78 * other block flags
79 *
80 * @since 1.26 $options array
81 */
82 public function __construct( array $options = [] ) {
83 parent::__construct( $options );
84
85 $defaults = [
86 'user' => null,
87 'auto' => false,
88 'expiry' => '',
89 'anonOnly' => false,
90 'createAccount' => false,
91 'enableAutoblock' => false,
92 'hideName' => false,
93 'blockEmail' => false,
94 'allowUsertalk' => false,
95 'sitewide' => true,
96 ];
97
98 $options += $defaults;
99
100 if ( $this->target instanceof User && $options['user'] ) {
101 # Needed for foreign users
102 $this->forcedTargetID = $options['user'];
103 }
104
105 $this->setExpiry( wfGetDB( DB_REPLICA )->decodeExpiry( $options['expiry'] ) );
106
107 # Boolean settings
108 $this->mAuto = (bool)$options['auto'];
109 $this->setHideName( (bool)$options['hideName'] );
110 $this->isHardblock( !$options['anonOnly'] );
111 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
112 $this->isSitewide( (bool)$options['sitewide'] );
113 $this->isEmailBlocked( (bool)$options['blockEmail'] );
114 $this->isCreateAccountBlocked( (bool)$options['createAccount'] );
115 $this->isUsertalkEditAllowed( (bool)$options['allowUsertalk'] );
116
117 $this->mFromMaster = false;
118 }
119
120 /**
121 * Load a block from the block id.
122 *
123 * @param int $id Block id to search for
124 * @return Block|null
125 */
126 public static function newFromID( $id ) {
127 $dbr = wfGetDB( DB_REPLICA );
128 $blockQuery = self::getQueryInfo();
129 $res = $dbr->selectRow(
130 $blockQuery['tables'],
131 $blockQuery['fields'],
132 [ 'ipb_id' => $id ],
133 __METHOD__,
134 [],
135 $blockQuery['joins']
136 );
137 if ( $res ) {
138 return self::newFromRow( $res );
139 } else {
140 return null;
141 }
142 }
143
144 /**
145 * Return the list of ipblocks fields that should be selected to create
146 * a new block.
147 * @deprecated since 1.31, use self::getQueryInfo() instead.
148 * @return array
149 */
150 public static function selectFields() {
151 global $wgActorTableSchemaMigrationStage;
152
153 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW ) {
154 // If code is using this instead of self::getQueryInfo(), there's a
155 // decent chance it's going to try to directly access
156 // $row->ipb_by or $row->ipb_by_text and we can't give it
157 // useful values here once those aren't being used anymore.
158 throw new BadMethodCallException(
159 'Cannot use ' . __METHOD__
160 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
161 );
162 }
163
164 wfDeprecated( __METHOD__, '1.31' );
165 return [
166 'ipb_id',
167 'ipb_address',
168 'ipb_by',
169 'ipb_by_text',
170 'ipb_by_actor' => 'NULL',
171 'ipb_timestamp',
172 'ipb_auto',
173 'ipb_anon_only',
174 'ipb_create_account',
175 'ipb_enable_autoblock',
176 'ipb_expiry',
177 'ipb_deleted',
178 'ipb_block_email',
179 'ipb_allow_usertalk',
180 'ipb_parent_block_id',
181 'ipb_sitewide',
182 ] + CommentStore::getStore()->getFields( 'ipb_reason' );
183 }
184
185 /**
186 * Return the tables, fields, and join conditions to be selected to create
187 * a new block object.
188 * @since 1.31
189 * @return array With three keys:
190 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
191 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
192 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
193 */
194 public static function getQueryInfo() {
195 $commentQuery = CommentStore::getStore()->getJoin( 'ipb_reason' );
196 $actorQuery = ActorMigration::newMigration()->getJoin( 'ipb_by' );
197 return [
198 'tables' => [ 'ipblocks' ] + $commentQuery['tables'] + $actorQuery['tables'],
199 'fields' => [
200 'ipb_id',
201 'ipb_address',
202 'ipb_timestamp',
203 'ipb_auto',
204 'ipb_anon_only',
205 'ipb_create_account',
206 'ipb_enable_autoblock',
207 'ipb_expiry',
208 'ipb_deleted',
209 'ipb_block_email',
210 'ipb_allow_usertalk',
211 'ipb_parent_block_id',
212 'ipb_sitewide',
213 ] + $commentQuery['fields'] + $actorQuery['fields'],
214 'joins' => $commentQuery['joins'] + $actorQuery['joins'],
215 ];
216 }
217
218 /**
219 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
220 * the blocking user or the block timestamp, only things which affect the blocked user
221 *
222 * @param Block $block
223 *
224 * @return bool
225 */
226 public function equals( Block $block ) {
227 return (
228 (string)$this->target == (string)$block->target
229 && $this->type == $block->type
230 && $this->mAuto == $block->mAuto
231 && $this->isHardblock() == $block->isHardblock()
232 && $this->isCreateAccountBlocked() == $block->isCreateAccountBlocked()
233 && $this->getExpiry() == $block->getExpiry()
234 && $this->isAutoblocking() == $block->isAutoblocking()
235 && $this->getHideName() == $block->getHideName()
236 && $this->isEmailBlocked() == $block->isEmailBlocked()
237 && $this->isUsertalkEditAllowed() == $block->isUsertalkEditAllowed()
238 && $this->getReason() == $block->getReason()
239 && $this->isSitewide() == $block->isSitewide()
240 // Block::getRestrictions() may perform a database query, so keep it at
241 // the end.
242 && $this->getBlockRestrictionStore()->equals(
243 $this->getRestrictions(), $block->getRestrictions()
244 )
245 );
246 }
247
248 /**
249 * Load a block from the database which affects the already-set $this->target:
250 * 1) A block directly on the given user or IP
251 * 2) A rangeblock encompassing the given IP (smallest first)
252 * 3) An autoblock on the given IP
253 * @param User|string|null $vagueTarget Also search for blocks affecting this target. Doesn't
254 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
255 * @throws MWException
256 * @return bool Whether a relevant block was found
257 */
258 protected function newLoad( $vagueTarget = null ) {
259 $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_REPLICA );
260
261 if ( $this->type !== null ) {
262 $conds = [
263 'ipb_address' => [ (string)$this->target ],
264 ];
265 } else {
266 $conds = [ 'ipb_address' => [] ];
267 }
268
269 # Be aware that the != '' check is explicit, since empty values will be
270 # passed by some callers (T31116)
271 if ( $vagueTarget != '' ) {
272 list( $target, $type ) = self::parseTarget( $vagueTarget );
273 switch ( $type ) {
274 case self::TYPE_USER:
275 # Slightly weird, but who are we to argue?
276 $conds['ipb_address'][] = (string)$target;
277 break;
278
279 case self::TYPE_IP:
280 $conds['ipb_address'][] = (string)$target;
281 $conds[] = self::getRangeCond( IP::toHex( $target ) );
282 $conds = $db->makeList( $conds, LIST_OR );
283 break;
284
285 case self::TYPE_RANGE:
286 list( $start, $end ) = IP::parseRange( $target );
287 $conds['ipb_address'][] = (string)$target;
288 $conds[] = self::getRangeCond( $start, $end );
289 $conds = $db->makeList( $conds, LIST_OR );
290 break;
291
292 default:
293 throw new MWException( "Tried to load block with invalid type" );
294 }
295 }
296
297 $blockQuery = self::getQueryInfo();
298 $res = $db->select(
299 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__, [], $blockQuery['joins']
300 );
301
302 # This result could contain a block on the user, a block on the IP, and a russian-doll
303 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
304 $bestRow = null;
305
306 # Lower will be better
307 $bestBlockScore = 100;
308
309 foreach ( $res as $row ) {
310 $block = self::newFromRow( $row );
311
312 # Don't use expired blocks
313 if ( $block->isExpired() ) {
314 continue;
315 }
316
317 # Don't use anon only blocks on users
318 if ( $this->type == self::TYPE_USER && !$block->isHardblock() ) {
319 continue;
320 }
321
322 if ( $block->getType() == self::TYPE_RANGE ) {
323 # This is the number of bits that are allowed to vary in the block, give
324 # or take some floating point errors
325 $target = $block->getTarget();
326 $max = IP::isIPv6( $target ) ? 128 : 32;
327 list( $network, $bits ) = IP::parseCIDR( $target );
328 $size = $max - $bits;
329
330 # Rank a range block covering a single IP equally with a single-IP block
331 $score = self::TYPE_RANGE - 1 + ( $size / $max );
332
333 } else {
334 $score = $block->getType();
335 }
336
337 if ( $score < $bestBlockScore ) {
338 $bestBlockScore = $score;
339 $bestRow = $row;
340 }
341 }
342
343 if ( $bestRow !== null ) {
344 $this->initFromRow( $bestRow );
345 return true;
346 } else {
347 return false;
348 }
349 }
350
351 /**
352 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
353 * @param string $start Hexadecimal IP representation
354 * @param string|null $end Hexadecimal IP representation, or null to use $start = $end
355 * @return string
356 */
357 public static function getRangeCond( $start, $end = null ) {
358 if ( $end === null ) {
359 $end = $start;
360 }
361 # Per T16634, we want to include relevant active rangeblocks; for
362 # rangeblocks, we want to include larger ranges which enclose the given
363 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
364 # so we can improve performance by filtering on a LIKE clause
365 $chunk = self::getIpFragment( $start );
366 $dbr = wfGetDB( DB_REPLICA );
367 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
368
369 # Fairly hard to make a malicious SQL statement out of hex characters,
370 # but stranger things have happened...
371 $safeStart = $dbr->addQuotes( $start );
372 $safeEnd = $dbr->addQuotes( $end );
373
374 return $dbr->makeList(
375 [
376 "ipb_range_start $like",
377 "ipb_range_start <= $safeStart",
378 "ipb_range_end >= $safeEnd",
379 ],
380 LIST_AND
381 );
382 }
383
384 /**
385 * Get the component of an IP address which is certain to be the same between an IP
386 * address and a rangeblock containing that IP address.
387 * @param string $hex Hexadecimal IP representation
388 * @return string
389 */
390 protected static function getIpFragment( $hex ) {
391 global $wgBlockCIDRLimit;
392 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
393 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
394 } else {
395 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
396 }
397 }
398
399 /**
400 * Given a database row from the ipblocks table, initialize
401 * member variables
402 * @param stdClass $row A row from the ipblocks table
403 */
404 protected function initFromRow( $row ) {
405 $this->setTarget( $row->ipb_address );
406 $this->setBlocker( User::newFromAnyId(
407 $row->ipb_by, $row->ipb_by_text, $row->ipb_by_actor ?? null
408 ) );
409
410 $this->setTimestamp( wfTimestamp( TS_MW, $row->ipb_timestamp ) );
411 $this->mAuto = $row->ipb_auto;
412 $this->setHideName( $row->ipb_deleted );
413 $this->mId = (int)$row->ipb_id;
414 $this->mParentBlockId = $row->ipb_parent_block_id;
415
416 // I wish I didn't have to do this
417 $db = wfGetDB( DB_REPLICA );
418 $this->setExpiry( $db->decodeExpiry( $row->ipb_expiry ) );
419 $this->setReason(
420 CommentStore::getStore()
421 // Legacy because $row may have come from self::selectFields()
422 ->getCommentLegacy( $db, 'ipb_reason', $row )->text
423 );
424
425 $this->isHardblock( !$row->ipb_anon_only );
426 $this->isAutoblocking( $row->ipb_enable_autoblock );
427 $this->isSitewide( (bool)$row->ipb_sitewide );
428
429 $this->isCreateAccountBlocked( $row->ipb_create_account );
430 $this->isEmailBlocked( $row->ipb_block_email );
431 $this->isUsertalkEditAllowed( $row->ipb_allow_usertalk );
432 }
433
434 /**
435 * Create a new Block object from a database row
436 * @param stdClass $row Row from the ipblocks table
437 * @return Block
438 */
439 public static function newFromRow( $row ) {
440 $block = new Block;
441 $block->initFromRow( $row );
442 return $block;
443 }
444
445 /**
446 * Delete the row from the IP blocks table.
447 *
448 * @throws MWException
449 * @return bool
450 */
451 public function delete() {
452 if ( wfReadOnly() ) {
453 return false;
454 }
455
456 if ( !$this->getId() ) {
457 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
458 }
459
460 $dbw = wfGetDB( DB_MASTER );
461
462 $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
463 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__ );
464
465 $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
466 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__ );
467
468 return $dbw->affectedRows() > 0;
469 }
470
471 /**
472 * Insert a block into the block table. Will fail if there is a conflicting
473 * block (same name and options) already in the database.
474 *
475 * @param IDatabase|null $dbw If you have one available
476 * @return bool|array False on failure, assoc array on success:
477 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
478 */
479 public function insert( $dbw = null ) {
480 global $wgBlockDisablesLogin;
481
482 if ( !$this->getBlocker() || $this->getBlocker()->getName() === '' ) {
483 throw new MWException( 'Cannot insert a block without a blocker set' );
484 }
485
486 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
487
488 if ( $dbw === null ) {
489 $dbw = wfGetDB( DB_MASTER );
490 }
491
492 self::purgeExpired();
493
494 $row = $this->getDatabaseArray( $dbw );
495
496 $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
497 $affected = $dbw->affectedRows();
498 if ( $affected ) {
499 $this->setId( $dbw->insertId() );
500 if ( $this->restrictions ) {
501 $this->getBlockRestrictionStore()->insert( $this->restrictions );
502 }
503 }
504
505 # Don't collide with expired blocks.
506 # Do this after trying to insert to avoid locking.
507 if ( !$affected ) {
508 # T96428: The ipb_address index uses a prefix on a field, so
509 # use a standard SELECT + DELETE to avoid annoying gap locks.
510 $ids = $dbw->selectFieldValues( 'ipblocks',
511 'ipb_id',
512 [
513 'ipb_address' => $row['ipb_address'],
514 'ipb_user' => $row['ipb_user'],
515 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
516 ],
517 __METHOD__
518 );
519 if ( $ids ) {
520 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__ );
521 $this->getBlockRestrictionStore()->deleteByBlockId( $ids );
522 $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
523 $affected = $dbw->affectedRows();
524 $this->setId( $dbw->insertId() );
525 if ( $this->restrictions ) {
526 $this->getBlockRestrictionStore()->insert( $this->restrictions );
527 }
528 }
529 }
530
531 if ( $affected ) {
532 $auto_ipd_ids = $this->doRetroactiveAutoblock();
533
534 if ( $wgBlockDisablesLogin && $this->target instanceof User ) {
535 // Change user login token to force them to be logged out.
536 $this->target->setToken();
537 $this->target->saveSettings();
538 }
539
540 return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
541 }
542
543 return false;
544 }
545
546 /**
547 * Update a block in the DB with new parameters.
548 * The ID field needs to be loaded first.
549 *
550 * @return bool|array False on failure, array on success:
551 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
552 */
553 public function update() {
554 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
555 $dbw = wfGetDB( DB_MASTER );
556
557 $dbw->startAtomic( __METHOD__ );
558
559 $result = $dbw->update(
560 'ipblocks',
561 $this->getDatabaseArray( $dbw ),
562 [ 'ipb_id' => $this->getId() ],
563 __METHOD__
564 );
565
566 // Only update the restrictions if they have been modified.
567 if ( $this->restrictions !== null ) {
568 // An empty array should remove all of the restrictions.
569 if ( empty( $this->restrictions ) ) {
570 $success = $this->getBlockRestrictionStore()->deleteByBlockId( $this->getId() );
571 } else {
572 $success = $this->getBlockRestrictionStore()->update( $this->restrictions );
573 }
574 // Update the result. The first false is the result, otherwise, true.
575 $result = $result && $success;
576 }
577
578 if ( $this->isAutoblocking() ) {
579 // update corresponding autoblock(s) (T50813)
580 $dbw->update(
581 'ipblocks',
582 $this->getAutoblockUpdateArray( $dbw ),
583 [ 'ipb_parent_block_id' => $this->getId() ],
584 __METHOD__
585 );
586
587 // Only update the restrictions if they have been modified.
588 if ( $this->restrictions !== null ) {
589 $this->getBlockRestrictionStore()->updateByParentBlockId( $this->getId(), $this->restrictions );
590 }
591 } else {
592 // autoblock no longer required, delete corresponding autoblock(s)
593 $this->getBlockRestrictionStore()->deleteByParentBlockId( $this->getId() );
594 $dbw->delete(
595 'ipblocks',
596 [ 'ipb_parent_block_id' => $this->getId() ],
597 __METHOD__
598 );
599 }
600
601 $dbw->endAtomic( __METHOD__ );
602
603 if ( $result ) {
604 $auto_ipd_ids = $this->doRetroactiveAutoblock();
605 return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
606 }
607
608 return $result;
609 }
610
611 /**
612 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
613 * @param IDatabase $dbw
614 * @return array
615 */
616 protected function getDatabaseArray( IDatabase $dbw ) {
617 $expiry = $dbw->encodeExpiry( $this->getExpiry() );
618
619 if ( $this->forcedTargetID ) {
620 $uid = $this->forcedTargetID;
621 } else {
622 $uid = $this->target instanceof User ? $this->target->getId() : 0;
623 }
624
625 $a = [
626 'ipb_address' => (string)$this->target,
627 'ipb_user' => $uid,
628 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
629 'ipb_auto' => $this->mAuto,
630 'ipb_anon_only' => !$this->isHardblock(),
631 'ipb_create_account' => $this->isCreateAccountBlocked(),
632 'ipb_enable_autoblock' => $this->isAutoblocking(),
633 'ipb_expiry' => $expiry,
634 'ipb_range_start' => $this->getRangeStart(),
635 'ipb_range_end' => $this->getRangeEnd(),
636 'ipb_deleted' => intval( $this->getHideName() ), // typecast required for SQLite
637 'ipb_block_email' => $this->isEmailBlocked(),
638 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
639 'ipb_parent_block_id' => $this->mParentBlockId,
640 'ipb_sitewide' => $this->isSitewide(),
641 ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
642 + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
643
644 return $a;
645 }
646
647 /**
648 * @param IDatabase $dbw
649 * @return array
650 */
651 protected function getAutoblockUpdateArray( IDatabase $dbw ) {
652 return [
653 'ipb_create_account' => $this->isCreateAccountBlocked(),
654 'ipb_deleted' => (int)$this->getHideName(), // typecast required for SQLite
655 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
656 'ipb_sitewide' => $this->isSitewide(),
657 ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->getReason() )
658 + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
659 }
660
661 /**
662 * Retroactively autoblocks the last IP used by the user (if it is a user)
663 * blocked by this Block.
664 *
665 * @return array Block IDs of retroactive autoblocks made
666 */
667 protected function doRetroactiveAutoblock() {
668 $blockIds = [];
669 # If autoblock is enabled, autoblock the LAST IP(s) used
670 if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
671 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
672
673 $continue = Hooks::run(
674 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
675
676 if ( $continue ) {
677 self::defaultRetroactiveAutoblock( $this, $blockIds );
678 }
679 }
680 return $blockIds;
681 }
682
683 /**
684 * Retroactively autoblocks the last IP used by the user (if it is a user)
685 * blocked by this Block. This will use the recentchanges table.
686 *
687 * @param Block $block
688 * @param array &$blockIds
689 */
690 protected static function defaultRetroactiveAutoblock( Block $block, array &$blockIds ) {
691 global $wgPutIPinRC;
692
693 // No IPs are in recentchanges table, so nothing to select
694 if ( !$wgPutIPinRC ) {
695 return;
696 }
697
698 // Autoblocks only apply to TYPE_USER
699 if ( $block->getType() !== self::TYPE_USER ) {
700 return;
701 }
702 $target = $block->getTarget(); // TYPE_USER => always a User object
703
704 $dbr = wfGetDB( DB_REPLICA );
705 $rcQuery = ActorMigration::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
706
707 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
708
709 // Just the last IP used.
710 $options['LIMIT'] = 1;
711
712 $res = $dbr->select(
713 [ 'recentchanges' ] + $rcQuery['tables'],
714 [ 'rc_ip' ],
715 $rcQuery['conds'],
716 __METHOD__,
717 $options,
718 $rcQuery['joins']
719 );
720
721 if ( !$res->numRows() ) {
722 # No results, don't autoblock anything
723 wfDebug( "No IP found to retroactively autoblock\n" );
724 } else {
725 foreach ( $res as $row ) {
726 if ( $row->rc_ip ) {
727 $id = $block->doAutoblock( $row->rc_ip );
728 if ( $id ) {
729 $blockIds[] = $id;
730 }
731 }
732 }
733 }
734 }
735
736 /**
737 * Checks whether a given IP is on the autoblock whitelist.
738 * TODO: this probably belongs somewhere else, but not sure where...
739 *
740 * @param string $ip The IP to check
741 * @return bool
742 */
743 public static function isWhitelistedFromAutoblocks( $ip ) {
744 // Try to get the autoblock_whitelist from the cache, as it's faster
745 // than getting the msg raw and explode()'ing it.
746 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
747 $lines = $cache->getWithSetCallback(
748 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
749 $cache::TTL_DAY,
750 function ( $curValue, &$ttl, array &$setOpts ) {
751 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
752
753 return explode( "\n",
754 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
755 }
756 );
757
758 wfDebug( "Checking the autoblock whitelist..\n" );
759
760 foreach ( $lines as $line ) {
761 # List items only
762 if ( substr( $line, 0, 1 ) !== '*' ) {
763 continue;
764 }
765
766 $wlEntry = substr( $line, 1 );
767 $wlEntry = trim( $wlEntry );
768
769 wfDebug( "Checking $ip against $wlEntry..." );
770
771 # Is the IP in this range?
772 if ( IP::isInRange( $ip, $wlEntry ) ) {
773 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
774 return true;
775 } else {
776 wfDebug( " No match\n" );
777 }
778 }
779
780 return false;
781 }
782
783 /**
784 * Autoblocks the given IP, referring to this Block.
785 *
786 * @param string $autoblockIP The IP to autoblock.
787 * @return int|bool Block ID if an autoblock was inserted, false if not.
788 */
789 public function doAutoblock( $autoblockIP ) {
790 # If autoblocks are disabled, go away.
791 if ( !$this->isAutoblocking() ) {
792 return false;
793 }
794
795 # Check for presence on the autoblock whitelist.
796 if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
797 return false;
798 }
799
800 // Avoid PHP 7.1 warning of passing $this by reference
801 $block = $this;
802 # Allow hooks to cancel the autoblock.
803 if ( !Hooks::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
804 wfDebug( "Autoblock aborted by hook.\n" );
805 return false;
806 }
807
808 # It's okay to autoblock. Go ahead and insert/update the block...
809
810 # Do not add a *new* block if the IP is already blocked.
811 $ipblock = self::newFromTarget( $autoblockIP );
812 if ( $ipblock ) {
813 # Check if the block is an autoblock and would exceed the user block
814 # if renewed. If so, do nothing, otherwise prolong the block time...
815 if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
816 $this->getExpiry() > self::getAutoblockExpiry( $ipblock->getTimestamp() )
817 ) {
818 # Reset block timestamp to now and its expiry to
819 # $wgAutoblockExpiry in the future
820 $ipblock->updateTimestamp();
821 }
822 return false;
823 }
824
825 # Make a new block object with the desired properties.
826 $autoblock = new Block;
827 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
828 $autoblock->setTarget( $autoblockIP );
829 $autoblock->setBlocker( $this->getBlocker() );
830 $autoblock->setReason(
831 wfMessage( 'autoblocker', $this->getTarget(), $this->getReason() )
832 ->inContentLanguage()->plain()
833 );
834 $timestamp = wfTimestampNow();
835 $autoblock->setTimestamp( $timestamp );
836 $autoblock->mAuto = 1;
837 $autoblock->isCreateAccountBlocked( $this->isCreateAccountBlocked() );
838 # Continue suppressing the name if needed
839 $autoblock->setHideName( $this->getHideName() );
840 $autoblock->isUsertalkEditAllowed( $this->isUsertalkEditAllowed() );
841 $autoblock->mParentBlockId = $this->mId;
842 $autoblock->isSitewide( $this->isSitewide() );
843 $autoblock->setRestrictions( $this->getRestrictions() );
844
845 if ( $this->getExpiry() == 'infinity' ) {
846 # Original block was indefinite, start an autoblock now
847 $autoblock->setExpiry( self::getAutoblockExpiry( $timestamp ) );
848 } else {
849 # If the user is already blocked with an expiry date, we don't
850 # want to pile on top of that.
851 $autoblock->setExpiry( min( $this->getExpiry(), self::getAutoblockExpiry( $timestamp ) ) );
852 }
853
854 # Insert the block...
855 $status = $autoblock->insert();
856 return $status
857 ? $status['id']
858 : false;
859 }
860
861 /**
862 * Check if a block has expired. Delete it if it is.
863 * @return bool
864 */
865 public function deleteIfExpired() {
866 if ( $this->isExpired() ) {
867 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
868 $this->delete();
869 $retVal = true;
870 } else {
871 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
872 $retVal = false;
873 }
874
875 return $retVal;
876 }
877
878 /**
879 * Has the block expired?
880 * @return bool
881 */
882 public function isExpired() {
883 $timestamp = wfTimestampNow();
884 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
885
886 if ( !$this->getExpiry() ) {
887 return false;
888 } else {
889 return $timestamp > $this->getExpiry();
890 }
891 }
892
893 /**
894 * Is the block address valid (i.e. not a null string?)
895 *
896 * @deprecated since 1.33 No longer needed in core.
897 * @return bool
898 */
899 public function isValid() {
900 wfDeprecated( __METHOD__, '1.33' );
901 return $this->getTarget() != null;
902 }
903
904 /**
905 * Update the timestamp on autoblocks.
906 */
907 public function updateTimestamp() {
908 if ( $this->mAuto ) {
909 $this->setTimestamp( wfTimestamp() );
910 $this->setExpiry( self::getAutoblockExpiry( $this->getTimestamp() ) );
911
912 $dbw = wfGetDB( DB_MASTER );
913 $dbw->update( 'ipblocks',
914 [ /* SET */
915 'ipb_timestamp' => $dbw->timestamp( $this->getTimestamp() ),
916 'ipb_expiry' => $dbw->timestamp( $this->getExpiry() ),
917 ],
918 [ /* WHERE */
919 'ipb_id' => $this->getId(),
920 ],
921 __METHOD__
922 );
923 }
924 }
925
926 /**
927 * Get the IP address at the start of the range in Hex form
928 * @throws MWException
929 * @return string IP in Hex form
930 */
931 public function getRangeStart() {
932 switch ( $this->type ) {
933 case self::TYPE_USER:
934 return '';
935 case self::TYPE_IP:
936 return IP::toHex( $this->target );
937 case self::TYPE_RANGE:
938 list( $start, /*...*/ ) = IP::parseRange( $this->target );
939 return $start;
940 default:
941 throw new MWException( "Block with invalid type" );
942 }
943 }
944
945 /**
946 * Get the IP address at the end of the range in Hex form
947 * @throws MWException
948 * @return string IP in Hex form
949 */
950 public function getRangeEnd() {
951 switch ( $this->type ) {
952 case self::TYPE_USER:
953 return '';
954 case self::TYPE_IP:
955 return IP::toHex( $this->target );
956 case self::TYPE_RANGE:
957 list( /*...*/, $end ) = IP::parseRange( $this->target );
958 return $end;
959 default:
960 throw new MWException( "Block with invalid type" );
961 }
962 }
963
964 /**
965 * @inheritDoc
966 */
967 public function getId() {
968 return $this->mId;
969 }
970
971 /**
972 * Set the block ID
973 *
974 * @param int $blockId
975 * @return int
976 */
977 private function setId( $blockId ) {
978 $this->mId = (int)$blockId;
979
980 if ( is_array( $this->restrictions ) ) {
981 $this->restrictions = $this->getBlockRestrictionStore()->setBlockId(
982 $blockId, $this->restrictions
983 );
984 }
985
986 return $this;
987 }
988
989 /**
990 * Get/set a flag determining whether the master is used for reads
991 *
992 * @param bool|null $x
993 * @return bool
994 */
995 public function fromMaster( $x = null ) {
996 return wfSetVar( $this->mFromMaster, $x );
997 }
998
999 /**
1000 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
1001 * @param bool|null $x
1002 * @return bool
1003 */
1004 public function isHardblock( $x = null ) {
1005 wfSetVar( $this->isHardblock, $x );
1006
1007 # You can't *not* hardblock a user
1008 return $this->getType() == self::TYPE_USER
1009 ? true
1010 : $this->isHardblock;
1011 }
1012
1013 /**
1014 * @param null|bool $x
1015 * @return bool
1016 */
1017 public function isAutoblocking( $x = null ) {
1018 wfSetVar( $this->isAutoblocking, $x );
1019
1020 # You can't put an autoblock on an IP or range as we don't have any history to
1021 # look over to get more IPs from
1022 return $this->getType() == self::TYPE_USER
1023 ? $this->isAutoblocking
1024 : false;
1025 }
1026
1027 /**
1028 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1029 * @return string Text is escaped
1030 */
1031 public function getRedactedName() {
1032 if ( $this->mAuto ) {
1033 return Html::element(
1034 'span',
1035 [ 'class' => 'mw-autoblockid' ],
1036 wfMessage( 'autoblockid', $this->mId )->text()
1037 );
1038 } else {
1039 return htmlspecialchars( $this->getTarget() );
1040 }
1041 }
1042
1043 /**
1044 * Get a timestamp of the expiry for autoblocks
1045 *
1046 * @param string|int $timestamp
1047 * @return string
1048 */
1049 public static function getAutoblockExpiry( $timestamp ) {
1050 global $wgAutoblockExpiry;
1051
1052 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
1053 }
1054
1055 /**
1056 * Purge expired blocks from the ipblocks table
1057 */
1058 public static function purgeExpired() {
1059 if ( wfReadOnly() ) {
1060 return;
1061 }
1062
1063 DeferredUpdates::addUpdate( new AutoCommitUpdate(
1064 wfGetDB( DB_MASTER ),
1065 __METHOD__,
1066 function ( IDatabase $dbw, $fname ) {
1067 $ids = $dbw->selectFieldValues( 'ipblocks',
1068 'ipb_id',
1069 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1070 $fname
1071 );
1072 if ( $ids ) {
1073 $blockRestrictionStore = MediaWikiServices::getInstance()->getBlockRestrictionStore();
1074 $blockRestrictionStore->deleteByBlockId( $ids );
1075
1076 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1077 }
1078 }
1079 ) );
1080 }
1081
1082 /**
1083 * Given a target and the target's type, get an existing Block object if possible.
1084 * @param string|User|int $specificTarget A block target, which may be one of several types:
1085 * * A user to block, in which case $target will be a User
1086 * * An IP to block, in which case $target will be a User generated by using
1087 * User::newFromName( $ip, false ) to turn off name validation
1088 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1089 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1090 * usernames
1091 * Calling this with a user, IP address or range will not select autoblocks, and will
1092 * only select a block where the targets match exactly (so looking for blocks on
1093 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1094 * @param string|User|int|null $vagueTarget As above, but we will search for *any* block which
1095 * affects that target (so for an IP address, get ranges containing that IP; and also
1096 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1097 * @param bool $fromMaster Whether to use the DB_MASTER database
1098 * @return Block|null (null if no relevant block could be found). The target and type
1099 * of the returned Block will refer to the actual block which was found, which might
1100 * not be the same as the target you gave if you used $vagueTarget!
1101 */
1102 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1103 list( $target, $type ) = self::parseTarget( $specificTarget );
1104 if ( $type == self::TYPE_ID || $type == self::TYPE_AUTO ) {
1105 return self::newFromID( $target );
1106
1107 } elseif ( $target === null && $vagueTarget == '' ) {
1108 # We're not going to find anything useful here
1109 # Be aware that the == '' check is explicit, since empty values will be
1110 # passed by some callers (T31116)
1111 return null;
1112
1113 } elseif ( in_array(
1114 $type,
1115 [ self::TYPE_USER, self::TYPE_IP, self::TYPE_RANGE, null ] )
1116 ) {
1117 $block = new Block();
1118 $block->fromMaster( $fromMaster );
1119
1120 if ( $type !== null ) {
1121 $block->setTarget( $target );
1122 }
1123
1124 if ( $block->newLoad( $vagueTarget ) ) {
1125 return $block;
1126 }
1127 }
1128 return null;
1129 }
1130
1131 /**
1132 * Get all blocks that match any IP from an array of IP addresses
1133 *
1134 * @param array $ipChain List of IPs (strings), usually retrieved from the
1135 * X-Forwarded-For header of the request
1136 * @param bool $isAnon Exclude anonymous-only blocks if false
1137 * @param bool $fromMaster Whether to query the master or replica DB
1138 * @return array Array of Blocks
1139 * @since 1.22
1140 */
1141 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1142 if ( $ipChain === [] ) {
1143 return [];
1144 }
1145
1146 $conds = [];
1147 $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1148 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1149 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1150 # necessarily trust the header given to us, make sure that we are only
1151 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1152 # Do not treat private IP spaces as special as it may be desirable for wikis
1153 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1154 if ( !IP::isValid( $ipaddr ) ) {
1155 continue;
1156 }
1157 # Don't check trusted IPs (includes local squids which will be in every request)
1158 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1159 continue;
1160 }
1161 # Check both the original IP (to check against single blocks), as well as build
1162 # the clause to check for rangeblocks for the given IP.
1163 $conds['ipb_address'][] = $ipaddr;
1164 $conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
1165 }
1166
1167 if ( $conds === [] ) {
1168 return [];
1169 }
1170
1171 if ( $fromMaster ) {
1172 $db = wfGetDB( DB_MASTER );
1173 } else {
1174 $db = wfGetDB( DB_REPLICA );
1175 }
1176 $conds = $db->makeList( $conds, LIST_OR );
1177 if ( !$isAnon ) {
1178 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1179 }
1180 $blockQuery = self::getQueryInfo();
1181 $rows = $db->select(
1182 $blockQuery['tables'],
1183 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1184 $conds,
1185 __METHOD__,
1186 [],
1187 $blockQuery['joins']
1188 );
1189
1190 $blocks = [];
1191 foreach ( $rows as $row ) {
1192 $block = self::newFromRow( $row );
1193 if ( !$block->isExpired() ) {
1194 $blocks[] = $block;
1195 }
1196 }
1197
1198 return $blocks;
1199 }
1200
1201 /**
1202 * From a list of multiple blocks, find the most exact and strongest Block.
1203 *
1204 * The logic for finding the "best" block is:
1205 * - Blocks that match the block's target IP are preferred over ones in a range
1206 * - Hardblocks are chosen over softblocks that prevent account creation
1207 * - Softblocks that prevent account creation are chosen over other softblocks
1208 * - Other softblocks are chosen over autoblocks
1209 * - If there are multiple exact or range blocks at the same level, the one chosen
1210 * is random
1211 * This should be used when $blocks where retrieved from the user's IP address
1212 * and $ipChain is populated from the same IP address information.
1213 *
1214 * @param array $blocks Array of Block objects
1215 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1216 * a block is to the server, and if a block matches exactly, or is in a range.
1217 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1218 * local-squid, ...)
1219 * @throws MWException
1220 * @return Block|null The "best" block from the list
1221 */
1222 public static function chooseBlock( array $blocks, array $ipChain ) {
1223 if ( $blocks === [] ) {
1224 return null;
1225 } elseif ( count( $blocks ) == 1 ) {
1226 return $blocks[0];
1227 }
1228
1229 // Sort hard blocks before soft ones and secondarily sort blocks
1230 // that disable account creation before those that don't.
1231 usort( $blocks, function ( Block $a, Block $b ) {
1232 $aWeight = (int)$a->isHardblock() . (int)$a->appliesToRight( 'createaccount' );
1233 $bWeight = (int)$b->isHardblock() . (int)$b->appliesToRight( 'createaccount' );
1234 return strcmp( $bWeight, $aWeight ); // highest weight first
1235 } );
1236
1237 $blocksListExact = [
1238 'hard' => false,
1239 'disable_create' => false,
1240 'other' => false,
1241 'auto' => false
1242 ];
1243 $blocksListRange = [
1244 'hard' => false,
1245 'disable_create' => false,
1246 'other' => false,
1247 'auto' => false
1248 ];
1249 $ipChain = array_reverse( $ipChain );
1250
1251 /** @var Block $block */
1252 foreach ( $blocks as $block ) {
1253 // Stop searching if we have already have a "better" block. This
1254 // is why the order of the blocks matters
1255 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1256 break;
1257 } elseif ( !$block->appliesToRight( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1258 break;
1259 }
1260
1261 foreach ( $ipChain as $checkip ) {
1262 $checkipHex = IP::toHex( $checkip );
1263 if ( (string)$block->getTarget() === $checkip ) {
1264 if ( $block->isHardblock() ) {
1265 $blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
1266 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1267 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
1268 } elseif ( $block->mAuto ) {
1269 $blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
1270 } else {
1271 $blocksListExact['other'] = $blocksListExact['other'] ?: $block;
1272 }
1273 // We found closest exact match in the ip list, so go to the next Block
1274 break;
1275 } elseif ( array_filter( $blocksListExact ) == []
1276 && $block->getRangeStart() <= $checkipHex
1277 && $block->getRangeEnd() >= $checkipHex
1278 ) {
1279 if ( $block->isHardblock() ) {
1280 $blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
1281 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1282 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
1283 } elseif ( $block->mAuto ) {
1284 $blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
1285 } else {
1286 $blocksListRange['other'] = $blocksListRange['other'] ?: $block;
1287 }
1288 break;
1289 }
1290 }
1291 }
1292
1293 if ( array_filter( $blocksListExact ) == [] ) {
1294 $blocksList = &$blocksListRange;
1295 } else {
1296 $blocksList = &$blocksListExact;
1297 }
1298
1299 $chosenBlock = null;
1300 if ( $blocksList['hard'] ) {
1301 $chosenBlock = $blocksList['hard'];
1302 } elseif ( $blocksList['disable_create'] ) {
1303 $chosenBlock = $blocksList['disable_create'];
1304 } elseif ( $blocksList['other'] ) {
1305 $chosenBlock = $blocksList['other'];
1306 } elseif ( $blocksList['auto'] ) {
1307 $chosenBlock = $blocksList['auto'];
1308 } else {
1309 throw new MWException( "Proxy block found, but couldn't be classified." );
1310 }
1311
1312 return $chosenBlock;
1313 }
1314
1315 /**
1316 * @inheritDoc
1317 *
1318 * Autoblocks have whichever type corresponds to their target, so to detect if a block is an
1319 * autoblock, we have to check the mAuto property instead.
1320 */
1321 public function getType() {
1322 return $this->mAuto
1323 ? self::TYPE_AUTO
1324 : parent::getType();
1325 }
1326
1327 /**
1328 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1329 * the same as the block's, to a maximum of 24 hours.
1330 *
1331 * @since 1.29
1332 *
1333 * @param WebResponse $response The response on which to set the cookie.
1334 */
1335 public function setCookie( WebResponse $response ) {
1336 // Calculate the default expiry time.
1337 $maxExpiryTime = wfTimestamp( TS_MW, wfTimestamp() + ( 24 * 60 * 60 ) );
1338
1339 // Use the Block's expiry time only if it's less than the default.
1340 $expiryTime = $this->getExpiry();
1341 if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
1342 $expiryTime = $maxExpiryTime;
1343 }
1344
1345 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1346 $expiryValue = DateTime::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1347 $cookieOptions = [ 'httpOnly' => false ];
1348 $cookieValue = $this->getCookieValue();
1349 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1350 }
1351
1352 /**
1353 * Unset the 'BlockID' cookie.
1354 *
1355 * @since 1.29
1356 *
1357 * @param WebResponse $response The response on which to unset the cookie.
1358 */
1359 public static function clearCookie( WebResponse $response ) {
1360 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1361 }
1362
1363 /**
1364 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1365 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1366 * be the block ID.
1367 *
1368 * @since 1.29
1369 *
1370 * @return string The block ID, probably concatenated with "!" and the HMAC.
1371 */
1372 public function getCookieValue() {
1373 $config = RequestContext::getMain()->getConfig();
1374 $id = $this->getId();
1375 $secretKey = $config->get( 'SecretKey' );
1376 if ( !$secretKey ) {
1377 // If there's no secret key, don't append a HMAC.
1378 return $id;
1379 }
1380 $hmac = MWCryptHash::hmac( $id, $secretKey, false );
1381 $cookieValue = $id . '!' . $hmac;
1382 return $cookieValue;
1383 }
1384
1385 /**
1386 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1387 * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
1388 *
1389 * @since 1.29
1390 *
1391 * @param string $cookieValue The string in which to find the ID.
1392 *
1393 * @return int|null The block ID, or null if the HMAC is present and invalid.
1394 */
1395 public static function getIdFromCookieValue( $cookieValue ) {
1396 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1397 $bangPos = strpos( $cookieValue, '!' );
1398 $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
1399 // Get the site-wide secret key.
1400 $config = RequestContext::getMain()->getConfig();
1401 $secretKey = $config->get( 'SecretKey' );
1402 if ( !$secretKey ) {
1403 // If there's no secret key, just use the ID as given.
1404 return $id;
1405 }
1406 $storedHmac = substr( $cookieValue, $bangPos + 1 );
1407 $calculatedHmac = MWCryptHash::hmac( $id, $secretKey, false );
1408 if ( $calculatedHmac === $storedHmac ) {
1409 return $id;
1410 } else {
1411 return null;
1412 }
1413 }
1414
1415 /**
1416 * @inheritDoc
1417 *
1418 * Build different messages for autoblocks and partial blocks.
1419 */
1420 public function getPermissionsError( IContextSource $context ) {
1421 $params = $this->getBlockErrorParams( $context );
1422
1423 $msg = 'blockedtext';
1424 if ( $this->mAuto ) {
1425 $msg = 'autoblockedtext';
1426 } elseif ( !$this->isSitewide() ) {
1427 $msg = 'blockedtext-partial';
1428 }
1429
1430 array_unshift( $params, $msg );
1431
1432 return $params;
1433 }
1434
1435 /**
1436 * Get Restrictions.
1437 *
1438 * Getting the restrictions will perform a database query if the restrictions
1439 * are not already loaded.
1440 *
1441 * @since 1.33
1442 * @return Restriction[]
1443 */
1444 public function getRestrictions() {
1445 if ( $this->restrictions === null ) {
1446 // If the block id has not been set, then do not attempt to load the
1447 // restrictions.
1448 if ( !$this->mId ) {
1449 return [];
1450 }
1451 $this->restrictions = $this->getBlockRestrictionStore()->loadByBlockId( $this->mId );
1452 }
1453
1454 return $this->restrictions;
1455 }
1456
1457 /**
1458 * Set Restrictions.
1459 *
1460 * @since 1.33
1461 * @param Restriction[] $restrictions
1462 * @return self
1463 */
1464 public function setRestrictions( array $restrictions ) {
1465 $this->restrictions = array_filter( $restrictions, function ( $restriction ) {
1466 return $restriction instanceof Restriction;
1467 } );
1468
1469 return $this;
1470 }
1471
1472 /**
1473 * @inheritDoc
1474 */
1475 public function appliesToTitle( Title $title ) {
1476 if ( $this->isSitewide() ) {
1477 return true;
1478 }
1479
1480 $restrictions = $this->getRestrictions();
1481 foreach ( $restrictions as $restriction ) {
1482 if ( $restriction->matches( $title ) ) {
1483 return true;
1484 }
1485 }
1486
1487 return false;
1488 }
1489
1490 /**
1491 * @inheritDoc
1492 */
1493 public function appliesToNamespace( $ns ) {
1494 if ( $this->isSitewide() ) {
1495 return true;
1496 }
1497
1498 // Blocks do not apply to virtual namespaces.
1499 if ( $ns < 0 ) {
1500 return false;
1501 }
1502
1503 $restriction = $this->findRestriction( NamespaceRestriction::TYPE, $ns );
1504
1505 return (bool)$restriction;
1506 }
1507
1508 /**
1509 * @inheritDoc
1510 */
1511 public function appliesToPage( $pageId ) {
1512 if ( $this->isSitewide() ) {
1513 return true;
1514 }
1515
1516 // If the pageId is not over zero, the block cannot apply to it.
1517 if ( $pageId <= 0 ) {
1518 return false;
1519 }
1520
1521 $restriction = $this->findRestriction( PageRestriction::TYPE, $pageId );
1522
1523 return (bool)$restriction;
1524 }
1525
1526 /**
1527 * Find Restriction by type and value.
1528 *
1529 * @param string $type
1530 * @param int $value
1531 * @return Restriction|null
1532 */
1533 private function findRestriction( $type, $value ) {
1534 $restrictions = $this->getRestrictions();
1535 foreach ( $restrictions as $restriction ) {
1536 if ( $restriction->getType() !== $type ) {
1537 continue;
1538 }
1539
1540 if ( $restriction->getValue() === $value ) {
1541 return $restriction;
1542 }
1543 }
1544
1545 return null;
1546 }
1547
1548 /**
1549 * @inheritDoc
1550 */
1551 public function shouldTrackWithCookie( $isAnon ) {
1552 $config = RequestContext::getMain()->getConfig();
1553 switch ( $this->getType() ) {
1554 case self::TYPE_IP:
1555 case self::TYPE_RANGE:
1556 return $isAnon && $config->get( 'CookieSetOnIpBlock' );
1557 case self::TYPE_USER:
1558 return !$isAnon && $config->get( 'CookieSetOnAutoblock' ) && $this->isAutoblocking();
1559 default:
1560 return false;
1561 }
1562 }
1563
1564 /**
1565 * Get a BlockRestrictionStore instance
1566 *
1567 * @return BlockRestrictionStore
1568 */
1569 private function getBlockRestrictionStore() : BlockRestrictionStore {
1570 return MediaWikiServices::getInstance()->getBlockRestrictionStore();
1571 }
1572 }