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