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