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