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