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