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