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