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