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