befc50c8894f7098e6ea2d569f0268444698c337
[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 $target = $block->getTarget();
770 if ( is_string( $target ) ) {
771 $target = User::newFromName( $target, false );
772 }
773
774 $dbr = wfGetDB( DB_REPLICA );
775 $rcQuery = ActorMigration::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
776
777 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
778
779 // Just the last IP used.
780 $options['LIMIT'] = 1;
781
782 $res = $dbr->select(
783 [ 'recentchanges' ] + $rcQuery['tables'],
784 [ 'rc_ip' ],
785 $rcQuery['conds'],
786 __METHOD__,
787 $options,
788 $rcQuery['joins']
789 );
790
791 if ( !$res->numRows() ) {
792 # No results, don't autoblock anything
793 wfDebug( "No IP found to retroactively autoblock\n" );
794 } else {
795 foreach ( $res as $row ) {
796 if ( $row->rc_ip ) {
797 $id = $block->doAutoblock( $row->rc_ip );
798 if ( $id ) {
799 $blockIds[] = $id;
800 }
801 }
802 }
803 }
804 }
805
806 /**
807 * Checks whether a given IP is on the autoblock whitelist.
808 * TODO: this probably belongs somewhere else, but not sure where...
809 *
810 * @param string $ip The IP to check
811 * @return bool
812 */
813 public static function isWhitelistedFromAutoblocks( $ip ) {
814 // Try to get the autoblock_whitelist from the cache, as it's faster
815 // than getting the msg raw and explode()'ing it.
816 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
817 $lines = $cache->getWithSetCallback(
818 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
819 $cache::TTL_DAY,
820 function ( $curValue, &$ttl, array &$setOpts ) {
821 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
822
823 return explode( "\n",
824 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
825 }
826 );
827
828 wfDebug( "Checking the autoblock whitelist..\n" );
829
830 foreach ( $lines as $line ) {
831 # List items only
832 if ( substr( $line, 0, 1 ) !== '*' ) {
833 continue;
834 }
835
836 $wlEntry = substr( $line, 1 );
837 $wlEntry = trim( $wlEntry );
838
839 wfDebug( "Checking $ip against $wlEntry..." );
840
841 # Is the IP in this range?
842 if ( IP::isInRange( $ip, $wlEntry ) ) {
843 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
844 return true;
845 } else {
846 wfDebug( " No match\n" );
847 }
848 }
849
850 return false;
851 }
852
853 /**
854 * Autoblocks the given IP, referring to this Block.
855 *
856 * @param string $autoblockIP The IP to autoblock.
857 * @return int|bool Block ID if an autoblock was inserted, false if not.
858 */
859 public function doAutoblock( $autoblockIP ) {
860 # If autoblocks are disabled, go away.
861 if ( !$this->isAutoblocking() ) {
862 return false;
863 }
864
865 # Don't autoblock for system blocks
866 if ( $this->getSystemBlockType() !== null ) {
867 throw new MWException( 'Cannot autoblock from a system block' );
868 }
869
870 # Check for presence on the autoblock whitelist.
871 if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
872 return false;
873 }
874
875 // Avoid PHP 7.1 warning of passing $this by reference
876 $block = $this;
877 # Allow hooks to cancel the autoblock.
878 if ( !Hooks::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
879 wfDebug( "Autoblock aborted by hook.\n" );
880 return false;
881 }
882
883 # It's okay to autoblock. Go ahead and insert/update the block...
884
885 # Do not add a *new* block if the IP is already blocked.
886 $ipblock = self::newFromTarget( $autoblockIP );
887 if ( $ipblock ) {
888 # Check if the block is an autoblock and would exceed the user block
889 # if renewed. If so, do nothing, otherwise prolong the block time...
890 if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
891 $this->mExpiry > self::getAutoblockExpiry( $ipblock->mTimestamp )
892 ) {
893 # Reset block timestamp to now and its expiry to
894 # $wgAutoblockExpiry in the future
895 $ipblock->updateTimestamp();
896 }
897 return false;
898 }
899
900 # Make a new block object with the desired properties.
901 $autoblock = new Block;
902 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
903 $autoblock->setTarget( $autoblockIP );
904 $autoblock->setBlocker( $this->getBlocker() );
905 $autoblock->mReason = wfMessage( 'autoblocker', $this->getTarget(), $this->mReason )
906 ->inContentLanguage()->plain();
907 $timestamp = wfTimestampNow();
908 $autoblock->mTimestamp = $timestamp;
909 $autoblock->mAuto = 1;
910 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
911 # Continue suppressing the name if needed
912 $autoblock->mHideName = $this->mHideName;
913 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
914 $autoblock->mParentBlockId = $this->mId;
915 $autoblock->isSitewide( $this->isSitewide() );
916 $autoblock->setRestrictions( $this->getRestrictions() );
917
918 if ( $this->mExpiry == 'infinity' ) {
919 # Original block was indefinite, start an autoblock now
920 $autoblock->mExpiry = self::getAutoblockExpiry( $timestamp );
921 } else {
922 # If the user is already blocked with an expiry date, we don't
923 # want to pile on top of that.
924 $autoblock->mExpiry = min( $this->mExpiry, self::getAutoblockExpiry( $timestamp ) );
925 }
926
927 # Insert the block...
928 $status = $autoblock->insert();
929 return $status
930 ? $status['id']
931 : false;
932 }
933
934 /**
935 * Check if a block has expired. Delete it if it is.
936 * @return bool
937 */
938 public function deleteIfExpired() {
939 if ( $this->isExpired() ) {
940 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
941 $this->delete();
942 $retVal = true;
943 } else {
944 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
945 $retVal = false;
946 }
947
948 return $retVal;
949 }
950
951 /**
952 * Has the block expired?
953 * @return bool
954 */
955 public function isExpired() {
956 $timestamp = wfTimestampNow();
957 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
958
959 if ( !$this->mExpiry ) {
960 return false;
961 } else {
962 return $timestamp > $this->mExpiry;
963 }
964 }
965
966 /**
967 * Is the block address valid (i.e. not a null string?)
968 * @return bool
969 */
970 public function isValid() {
971 return $this->getTarget() != null;
972 }
973
974 /**
975 * Update the timestamp on autoblocks.
976 */
977 public function updateTimestamp() {
978 if ( $this->mAuto ) {
979 $this->mTimestamp = wfTimestamp();
980 $this->mExpiry = self::getAutoblockExpiry( $this->mTimestamp );
981
982 $dbw = wfGetDB( DB_MASTER );
983 $dbw->update( 'ipblocks',
984 [ /* SET */
985 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
986 'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
987 ],
988 [ /* WHERE */
989 'ipb_id' => $this->getId(),
990 ],
991 __METHOD__
992 );
993 }
994 }
995
996 /**
997 * Get the IP address at the start of the range in Hex form
998 * @throws MWException
999 * @return string IP in Hex form
1000 */
1001 public function getRangeStart() {
1002 switch ( $this->type ) {
1003 case self::TYPE_USER:
1004 return '';
1005 case self::TYPE_IP:
1006 return IP::toHex( $this->target );
1007 case self::TYPE_RANGE:
1008 list( $start, /*...*/ ) = IP::parseRange( $this->target );
1009 return $start;
1010 default:
1011 throw new MWException( "Block with invalid type" );
1012 }
1013 }
1014
1015 /**
1016 * Get the IP address at the end of the range in Hex form
1017 * @throws MWException
1018 * @return string IP in Hex form
1019 */
1020 public function getRangeEnd() {
1021 switch ( $this->type ) {
1022 case self::TYPE_USER:
1023 return '';
1024 case self::TYPE_IP:
1025 return IP::toHex( $this->target );
1026 case self::TYPE_RANGE:
1027 list( /*...*/, $end ) = IP::parseRange( $this->target );
1028 return $end;
1029 default:
1030 throw new MWException( "Block with invalid type" );
1031 }
1032 }
1033
1034 /**
1035 * Get the user id of the blocking sysop
1036 *
1037 * @return int (0 for foreign users)
1038 */
1039 public function getBy() {
1040 $blocker = $this->getBlocker();
1041 return ( $blocker instanceof User )
1042 ? $blocker->getId()
1043 : 0;
1044 }
1045
1046 /**
1047 * Get the username of the blocking sysop
1048 *
1049 * @return string
1050 */
1051 public function getByName() {
1052 $blocker = $this->getBlocker();
1053 return ( $blocker instanceof User )
1054 ? $blocker->getName()
1055 : (string)$blocker; // username
1056 }
1057
1058 /**
1059 * Get the block ID
1060 * @return int
1061 */
1062 public function getId() {
1063 return $this->mId;
1064 }
1065
1066 /**
1067 * Set the block ID
1068 *
1069 * @param int $blockId
1070 * @return int
1071 */
1072 private function setId( $blockId ) {
1073 $this->mId = (int)$blockId;
1074
1075 if ( is_array( $this->restrictions ) ) {
1076 $this->restrictions = BlockRestriction::setBlockId( $blockId, $this->restrictions );
1077 }
1078
1079 return $this;
1080 }
1081
1082 /**
1083 * Get the system block type, if any
1084 * @since 1.29
1085 * @return string|null
1086 */
1087 public function getSystemBlockType() {
1088 return $this->systemBlockType;
1089 }
1090
1091 /**
1092 * Get/set a flag determining whether the master is used for reads
1093 *
1094 * @param bool|null $x
1095 * @return bool
1096 */
1097 public function fromMaster( $x = null ) {
1098 return wfSetVar( $this->mFromMaster, $x );
1099 }
1100
1101 /**
1102 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
1103 * @param bool|null $x
1104 * @return bool
1105 */
1106 public function isHardblock( $x = null ) {
1107 wfSetVar( $this->isHardblock, $x );
1108
1109 # You can't *not* hardblock a user
1110 return $this->getType() == self::TYPE_USER
1111 ? true
1112 : $this->isHardblock;
1113 }
1114
1115 /**
1116 * @param null|bool $x
1117 * @return bool
1118 */
1119 public function isAutoblocking( $x = null ) {
1120 wfSetVar( $this->isAutoblocking, $x );
1121
1122 # You can't put an autoblock on an IP or range as we don't have any history to
1123 # look over to get more IPs from
1124 return $this->getType() == self::TYPE_USER
1125 ? $this->isAutoblocking
1126 : false;
1127 }
1128
1129 /**
1130 * Indicates that the block is a sitewide block. This means the user is
1131 * prohibited from editing any page on the site (other than their own talk
1132 * page).
1133 *
1134 * @param null|bool $x
1135 * @return bool
1136 */
1137 public function isSitewide( $x = null ) {
1138 return wfSetVar( $this->isSitewide, $x );
1139 }
1140
1141 /**
1142 * Get/set whether the Block prevents a given action
1143 *
1144 * @param string $action Action to check
1145 * @param bool|null $x Value for set, or null to just get value
1146 * @return bool|null Null for unrecognized rights.
1147 */
1148 public function prevents( $action, $x = null ) {
1149 $config = RequestContext::getMain()->getConfig();
1150 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1151 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1152
1153 $res = null;
1154 switch ( $action ) {
1155 case 'edit':
1156 # For now... <evil laugh>
1157 $res = true;
1158 break;
1159 case 'createaccount':
1160 $res = wfSetVar( $this->mCreateAccount, $x );
1161 break;
1162 case 'sendemail':
1163 $res = wfSetVar( $this->mBlockEmail, $x );
1164 break;
1165 case 'upload':
1166 // Until T6995 is completed
1167 $res = $this->isSitewide();
1168 break;
1169 case 'editownusertalk':
1170 $res = wfSetVar( $this->mDisableUsertalk, $x );
1171 // edit own user talk can be disabled by config
1172 if ( !$blockAllowsUTEdit ) {
1173 $res = true;
1174 }
1175 break;
1176 case 'read':
1177 $res = false;
1178 break;
1179 }
1180 if ( !$res && $blockDisablesLogin ) {
1181 // If a block would disable login, then it should
1182 // prevent any action that all users cannot do
1183 $anon = new User;
1184 $res = $anon->isAllowed( $action ) ? $res : true;
1185 }
1186
1187 return $res;
1188 }
1189
1190 /**
1191 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1192 * @return string Text is escaped
1193 */
1194 public function getRedactedName() {
1195 if ( $this->mAuto ) {
1196 return Html::rawElement(
1197 'span',
1198 [ 'class' => 'mw-autoblockid' ],
1199 wfMessage( 'autoblockid', $this->mId )
1200 );
1201 } else {
1202 return htmlspecialchars( $this->getTarget() );
1203 }
1204 }
1205
1206 /**
1207 * Get a timestamp of the expiry for autoblocks
1208 *
1209 * @param string|int $timestamp
1210 * @return string
1211 */
1212 public static function getAutoblockExpiry( $timestamp ) {
1213 global $wgAutoblockExpiry;
1214
1215 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
1216 }
1217
1218 /**
1219 * Purge expired blocks from the ipblocks table
1220 */
1221 public static function purgeExpired() {
1222 if ( wfReadOnly() ) {
1223 return;
1224 }
1225
1226 DeferredUpdates::addUpdate( new AutoCommitUpdate(
1227 wfGetDB( DB_MASTER ),
1228 __METHOD__,
1229 function ( IDatabase $dbw, $fname ) {
1230 $ids = $dbw->selectFieldValues( 'ipblocks',
1231 'ipb_id',
1232 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1233 $fname
1234 );
1235 if ( $ids ) {
1236 BlockRestriction::deleteByBlockId( $ids );
1237 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1238 }
1239 }
1240 ) );
1241 }
1242
1243 /**
1244 * Given a target and the target's type, get an existing Block object if possible.
1245 * @param string|User|int $specificTarget A block target, which may be one of several types:
1246 * * A user to block, in which case $target will be a User
1247 * * An IP to block, in which case $target will be a User generated by using
1248 * User::newFromName( $ip, false ) to turn off name validation
1249 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1250 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1251 * usernames
1252 * Calling this with a user, IP address or range will not select autoblocks, and will
1253 * only select a block where the targets match exactly (so looking for blocks on
1254 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1255 * @param string|User|int|null $vagueTarget As above, but we will search for *any* block which
1256 * affects that target (so for an IP address, get ranges containing that IP; and also
1257 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1258 * @param bool $fromMaster Whether to use the DB_MASTER database
1259 * @return Block|null (null if no relevant block could be found). The target and type
1260 * of the returned Block will refer to the actual block which was found, which might
1261 * not be the same as the target you gave if you used $vagueTarget!
1262 */
1263 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1264 list( $target, $type ) = self::parseTarget( $specificTarget );
1265 if ( $type == self::TYPE_ID || $type == self::TYPE_AUTO ) {
1266 return self::newFromID( $target );
1267
1268 } elseif ( $target === null && $vagueTarget == '' ) {
1269 # We're not going to find anything useful here
1270 # Be aware that the == '' check is explicit, since empty values will be
1271 # passed by some callers (T31116)
1272 return null;
1273
1274 } elseif ( in_array(
1275 $type,
1276 [ self::TYPE_USER, self::TYPE_IP, self::TYPE_RANGE, null ] )
1277 ) {
1278 $block = new Block();
1279 $block->fromMaster( $fromMaster );
1280
1281 if ( $type !== null ) {
1282 $block->setTarget( $target );
1283 }
1284
1285 if ( $block->newLoad( $vagueTarget ) ) {
1286 return $block;
1287 }
1288 }
1289 return null;
1290 }
1291
1292 /**
1293 * Get all blocks that match any IP from an array of IP addresses
1294 *
1295 * @param array $ipChain List of IPs (strings), usually retrieved from the
1296 * X-Forwarded-For header of the request
1297 * @param bool $isAnon Exclude anonymous-only blocks if false
1298 * @param bool $fromMaster Whether to query the master or replica DB
1299 * @return array Array of Blocks
1300 * @since 1.22
1301 */
1302 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1303 if ( !count( $ipChain ) ) {
1304 return [];
1305 }
1306
1307 $conds = [];
1308 $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1309 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1310 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1311 # necessarily trust the header given to us, make sure that we are only
1312 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1313 # Do not treat private IP spaces as special as it may be desirable for wikis
1314 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1315 if ( !IP::isValid( $ipaddr ) ) {
1316 continue;
1317 }
1318 # Don't check trusted IPs (includes local squids which will be in every request)
1319 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1320 continue;
1321 }
1322 # Check both the original IP (to check against single blocks), as well as build
1323 # the clause to check for rangeblocks for the given IP.
1324 $conds['ipb_address'][] = $ipaddr;
1325 $conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
1326 }
1327
1328 if ( !count( $conds ) ) {
1329 return [];
1330 }
1331
1332 if ( $fromMaster ) {
1333 $db = wfGetDB( DB_MASTER );
1334 } else {
1335 $db = wfGetDB( DB_REPLICA );
1336 }
1337 $conds = $db->makeList( $conds, LIST_OR );
1338 if ( !$isAnon ) {
1339 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1340 }
1341 $blockQuery = self::getQueryInfo();
1342 $rows = $db->select(
1343 $blockQuery['tables'],
1344 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1345 $conds,
1346 __METHOD__,
1347 [],
1348 $blockQuery['joins']
1349 );
1350
1351 $blocks = [];
1352 foreach ( $rows as $row ) {
1353 $block = self::newFromRow( $row );
1354 if ( !$block->isExpired() ) {
1355 $blocks[] = $block;
1356 }
1357 }
1358
1359 return $blocks;
1360 }
1361
1362 /**
1363 * From a list of multiple blocks, find the most exact and strongest Block.
1364 *
1365 * The logic for finding the "best" block is:
1366 * - Blocks that match the block's target IP are preferred over ones in a range
1367 * - Hardblocks are chosen over softblocks that prevent account creation
1368 * - Softblocks that prevent account creation are chosen over other softblocks
1369 * - Other softblocks are chosen over autoblocks
1370 * - If there are multiple exact or range blocks at the same level, the one chosen
1371 * is random
1372 * This should be used when $blocks where retrieved from the user's IP address
1373 * and $ipChain is populated from the same IP address information.
1374 *
1375 * @param array $blocks Array of Block objects
1376 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1377 * a block is to the server, and if a block matches exactly, or is in a range.
1378 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1379 * local-squid, ...)
1380 * @throws MWException
1381 * @return Block|null The "best" block from the list
1382 */
1383 public static function chooseBlock( array $blocks, array $ipChain ) {
1384 if ( !count( $blocks ) ) {
1385 return null;
1386 } elseif ( count( $blocks ) == 1 ) {
1387 return $blocks[0];
1388 }
1389
1390 // Sort hard blocks before soft ones and secondarily sort blocks
1391 // that disable account creation before those that don't.
1392 usort( $blocks, function ( Block $a, Block $b ) {
1393 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1394 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1395 return strcmp( $bWeight, $aWeight ); // highest weight first
1396 } );
1397
1398 $blocksListExact = [
1399 'hard' => false,
1400 'disable_create' => false,
1401 'other' => false,
1402 'auto' => false
1403 ];
1404 $blocksListRange = [
1405 'hard' => false,
1406 'disable_create' => false,
1407 'other' => false,
1408 'auto' => false
1409 ];
1410 $ipChain = array_reverse( $ipChain );
1411
1412 /** @var Block $block */
1413 foreach ( $blocks as $block ) {
1414 // Stop searching if we have already have a "better" block. This
1415 // is why the order of the blocks matters
1416 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1417 break;
1418 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1419 break;
1420 }
1421
1422 foreach ( $ipChain as $checkip ) {
1423 $checkipHex = IP::toHex( $checkip );
1424 if ( (string)$block->getTarget() === $checkip ) {
1425 if ( $block->isHardblock() ) {
1426 $blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
1427 } elseif ( $block->prevents( 'createaccount' ) ) {
1428 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
1429 } elseif ( $block->mAuto ) {
1430 $blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
1431 } else {
1432 $blocksListExact['other'] = $blocksListExact['other'] ?: $block;
1433 }
1434 // We found closest exact match in the ip list, so go to the next Block
1435 break;
1436 } elseif ( array_filter( $blocksListExact ) == []
1437 && $block->getRangeStart() <= $checkipHex
1438 && $block->getRangeEnd() >= $checkipHex
1439 ) {
1440 if ( $block->isHardblock() ) {
1441 $blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
1442 } elseif ( $block->prevents( 'createaccount' ) ) {
1443 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
1444 } elseif ( $block->mAuto ) {
1445 $blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
1446 } else {
1447 $blocksListRange['other'] = $blocksListRange['other'] ?: $block;
1448 }
1449 break;
1450 }
1451 }
1452 }
1453
1454 if ( array_filter( $blocksListExact ) == [] ) {
1455 $blocksList = &$blocksListRange;
1456 } else {
1457 $blocksList = &$blocksListExact;
1458 }
1459
1460 $chosenBlock = null;
1461 if ( $blocksList['hard'] ) {
1462 $chosenBlock = $blocksList['hard'];
1463 } elseif ( $blocksList['disable_create'] ) {
1464 $chosenBlock = $blocksList['disable_create'];
1465 } elseif ( $blocksList['other'] ) {
1466 $chosenBlock = $blocksList['other'];
1467 } elseif ( $blocksList['auto'] ) {
1468 $chosenBlock = $blocksList['auto'];
1469 } else {
1470 throw new MWException( "Proxy block found, but couldn't be classified." );
1471 }
1472
1473 return $chosenBlock;
1474 }
1475
1476 /**
1477 * From an existing Block, get the target and the type of target.
1478 * Note that, except for null, it is always safe to treat the target
1479 * as a string; for User objects this will return User::__toString()
1480 * which in turn gives User::getName().
1481 *
1482 * @param string|int|User|null $target
1483 * @return array [ User|String|null, Block::TYPE_ constant|null ]
1484 */
1485 public static function parseTarget( $target ) {
1486 # We may have been through this before
1487 if ( $target instanceof User ) {
1488 if ( IP::isValid( $target->getName() ) ) {
1489 return [ $target, self::TYPE_IP ];
1490 } else {
1491 return [ $target, self::TYPE_USER ];
1492 }
1493 } elseif ( $target === null ) {
1494 return [ null, null ];
1495 }
1496
1497 $target = trim( $target );
1498
1499 if ( IP::isValid( $target ) ) {
1500 # We can still create a User if it's an IP address, but we need to turn
1501 # off validation checking (which would exclude IP addresses)
1502 return [
1503 User::newFromName( IP::sanitizeIP( $target ), false ),
1504 self::TYPE_IP
1505 ];
1506
1507 } elseif ( IP::isValidRange( $target ) ) {
1508 # Can't create a User from an IP range
1509 return [ IP::sanitizeRange( $target ), self::TYPE_RANGE ];
1510 }
1511
1512 # Consider the possibility that this is not a username at all
1513 # but actually an old subpage (T31797)
1514 if ( strpos( $target, '/' ) !== false ) {
1515 # An old subpage, drill down to the user behind it
1516 $target = explode( '/', $target )[0];
1517 }
1518
1519 $userObj = User::newFromName( $target );
1520 if ( $userObj instanceof User ) {
1521 # Note that since numbers are valid usernames, a $target of "12345" will be
1522 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1523 # since hash characters are not valid in usernames or titles generally.
1524 return [ $userObj, self::TYPE_USER ];
1525
1526 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1527 # Autoblock reference in the form "#12345"
1528 return [ substr( $target, 1 ), self::TYPE_AUTO ];
1529
1530 } else {
1531 # WTF?
1532 return [ null, null ];
1533 }
1534 }
1535
1536 /**
1537 * Get the type of target for this particular block
1538 * @return int Block::TYPE_ constant, will never be TYPE_ID
1539 */
1540 public function getType() {
1541 return $this->mAuto
1542 ? self::TYPE_AUTO
1543 : $this->type;
1544 }
1545
1546 /**
1547 * Get the target and target type for this particular Block. Note that for autoblocks,
1548 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1549 * in this situation.
1550 * @return array [ User|String, Block::TYPE_ constant ]
1551 * @todo FIXME: This should be an integral part of the Block member variables
1552 */
1553 public function getTargetAndType() {
1554 return [ $this->getTarget(), $this->getType() ];
1555 }
1556
1557 /**
1558 * Get the target for this particular Block. Note that for autoblocks,
1559 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1560 * in this situation.
1561 * @return User|string
1562 */
1563 public function getTarget() {
1564 return $this->target;
1565 }
1566
1567 /**
1568 * @since 1.19
1569 *
1570 * @return mixed|string
1571 */
1572 public function getExpiry() {
1573 return $this->mExpiry;
1574 }
1575
1576 /**
1577 * Set the target for this block, and update $this->type accordingly
1578 * @param mixed $target
1579 */
1580 public function setTarget( $target ) {
1581 list( $this->target, $this->type ) = self::parseTarget( $target );
1582 }
1583
1584 /**
1585 * Get the user who implemented this block
1586 * @return User User object. May name a foreign user.
1587 */
1588 public function getBlocker() {
1589 return $this->blocker;
1590 }
1591
1592 /**
1593 * Set the user who implemented (or will implement) this block
1594 * @param User|string $user Local User object or username string
1595 */
1596 public function setBlocker( $user ) {
1597 if ( is_string( $user ) ) {
1598 $user = User::newFromName( $user, false );
1599 }
1600
1601 if ( $user->isAnon() && User::isUsableName( $user->getName() ) ) {
1602 throw new InvalidArgumentException(
1603 'Blocker must be a local user or a name that cannot be a local user'
1604 );
1605 }
1606
1607 $this->blocker = $user;
1608 }
1609
1610 /**
1611 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1612 * the same as the block's, to a maximum of 24 hours.
1613 *
1614 * @since 1.29
1615 *
1616 * @param WebResponse $response The response on which to set the cookie.
1617 */
1618 public function setCookie( WebResponse $response ) {
1619 // Calculate the default expiry time.
1620 $maxExpiryTime = wfTimestamp( TS_MW, wfTimestamp() + ( 24 * 60 * 60 ) );
1621
1622 // Use the Block's expiry time only if it's less than the default.
1623 $expiryTime = $this->getExpiry();
1624 if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
1625 $expiryTime = $maxExpiryTime;
1626 }
1627
1628 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1629 $expiryValue = DateTime::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1630 $cookieOptions = [ 'httpOnly' => false ];
1631 $cookieValue = $this->getCookieValue();
1632 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1633 }
1634
1635 /**
1636 * Unset the 'BlockID' cookie.
1637 *
1638 * @since 1.29
1639 *
1640 * @param WebResponse $response The response on which to unset the cookie.
1641 */
1642 public static function clearCookie( WebResponse $response ) {
1643 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1644 }
1645
1646 /**
1647 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1648 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1649 * be the block ID.
1650 *
1651 * @since 1.29
1652 *
1653 * @return string The block ID, probably concatenated with "!" and the HMAC.
1654 */
1655 public function getCookieValue() {
1656 $config = RequestContext::getMain()->getConfig();
1657 $id = $this->getId();
1658 $secretKey = $config->get( 'SecretKey' );
1659 if ( !$secretKey ) {
1660 // If there's no secret key, don't append a HMAC.
1661 return $id;
1662 }
1663 $hmac = MWCryptHash::hmac( $id, $secretKey, false );
1664 $cookieValue = $id . '!' . $hmac;
1665 return $cookieValue;
1666 }
1667
1668 /**
1669 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1670 * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
1671 *
1672 * @since 1.29
1673 *
1674 * @param string $cookieValue The string in which to find the ID.
1675 *
1676 * @return int|null The block ID, or null if the HMAC is present and invalid.
1677 */
1678 public static function getIdFromCookieValue( $cookieValue ) {
1679 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1680 $bangPos = strpos( $cookieValue, '!' );
1681 $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
1682 // Get the site-wide secret key.
1683 $config = RequestContext::getMain()->getConfig();
1684 $secretKey = $config->get( 'SecretKey' );
1685 if ( !$secretKey ) {
1686 // If there's no secret key, just use the ID as given.
1687 return $id;
1688 }
1689 $storedHmac = substr( $cookieValue, $bangPos + 1 );
1690 $calculatedHmac = MWCryptHash::hmac( $id, $secretKey, false );
1691 if ( $calculatedHmac === $storedHmac ) {
1692 return $id;
1693 } else {
1694 return null;
1695 }
1696 }
1697
1698 /**
1699 * Get the key and parameters for the corresponding error message.
1700 *
1701 * @since 1.22
1702 * @param IContextSource $context
1703 * @return array
1704 */
1705 public function getPermissionsError( IContextSource $context ) {
1706 $params = $this->getBlockErrorParams( $context );
1707
1708 $msg = 'blockedtext';
1709 if ( $this->getSystemBlockType() !== null ) {
1710 $msg = 'systemblockedtext';
1711 } elseif ( $this->mAuto ) {
1712 $msg = 'autoblockedtext';
1713 } elseif ( !$this->isSitewide() ) {
1714 $msg = 'blockedtext-partial';
1715 }
1716
1717 array_unshift( $params, $msg );
1718
1719 return $params;
1720 }
1721
1722 /**
1723 * Get block information used in different block error messages
1724 *
1725 * @param IContextSource $context
1726 * @return array
1727 */
1728 public function getBlockErrorParams( IContextSource $context ) {
1729 $blocker = $this->getBlocker();
1730 if ( $blocker instanceof User ) { // local user
1731 $blockerUserpage = $blocker->getUserPage();
1732 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1733 } else { // foreign user
1734 $link = $blocker;
1735 }
1736
1737 $reason = $this->mReason;
1738 if ( $reason == '' ) {
1739 $reason = $context->msg( 'blockednoreason' )->text();
1740 }
1741
1742 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1743 * This could be a username, an IP range, or a single IP. */
1744 $intended = $this->getTarget();
1745 $systemBlockType = $this->getSystemBlockType();
1746 $lang = $context->getLanguage();
1747
1748 return [
1749 $link,
1750 $reason,
1751 $context->getRequest()->getIP(),
1752 $this->getByName(),
1753 $systemBlockType ?? $this->getId(),
1754 $lang->formatExpiry( $this->mExpiry ),
1755 (string)$intended,
1756 $lang->userTimeAndDate( $this->mTimestamp, $context->getUser() ),
1757 ];
1758 }
1759
1760 /**
1761 * Get Restrictions.
1762 *
1763 * Getting the restrictions will perform a database query if the restrictions
1764 * are not already loaded.
1765 *
1766 * @return Restriction[]
1767 */
1768 public function getRestrictions() {
1769 if ( $this->restrictions === null ) {
1770 // If the block id has not been set, then do not attempt to load the
1771 // restrictions.
1772 if ( !$this->mId ) {
1773 return [];
1774 }
1775 $this->restrictions = BlockRestriction::loadByBlockId( $this->mId );
1776 }
1777
1778 return $this->restrictions;
1779 }
1780
1781 /**
1782 * Set Restrictions.
1783 *
1784 * @param Restriction[] $restrictions
1785 *
1786 * @return self
1787 */
1788 public function setRestrictions( array $restrictions ) {
1789 $this->restrictions = array_filter( $restrictions, function ( $restriction ) {
1790 return $restriction instanceof Restriction;
1791 } );
1792
1793 return $this;
1794 }
1795
1796 /**
1797 * Checks if a block prevents an edit on a given article
1798 *
1799 * @param \Title $title
1800 * @return bool
1801 */
1802 public function preventsEdit( \Title $title ) {
1803 $blocked = $this->isSitewide();
1804
1805 // user talk page has it's own rules
1806 // This check happens before partial blocks because the flag
1807 // to allow user to edit their user talk page could be
1808 // overwritten by a partial block restriction (E.g. user talk namespace)
1809 $user = $this->getTarget();
1810 if ( $title->equals( $user->getTalkPage() ) ) {
1811 $blocked = $this->prevents( 'editownusertalk' );
1812 }
1813
1814 if ( !$this->isSitewide() ) {
1815 $restrictions = $this->getRestrictions();
1816 foreach ( $restrictions as $restriction ) {
1817 if ( $restriction->matches( $title ) ) {
1818 $blocked = true;
1819 }
1820 }
1821 }
1822
1823 return $blocked;
1824 }
1825 }