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