Merge "Remove deprecated wgEnableParserCache"
[lhc/web/wiklou.git] / includes / Block.php
1 <?php
2 /**
3 * Blocks and bans object
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 use Wikimedia\Rdbms\Database;
24 use Wikimedia\Rdbms\IDatabase;
25 use MediaWiki\Block\BlockRestriction;
26 use MediaWiki\Block\Restriction\Restriction;
27 use MediaWiki\Block\Restriction\NamespaceRestriction;
28 use MediaWiki\Block\Restriction\PageRestriction;
29 use MediaWiki\MediaWikiServices;
30
31 class Block {
32 /** @var string */
33 public $mReason;
34
35 /** @var string */
36 public $mTimestamp;
37
38 /** @var bool */
39 public $mAuto;
40
41 /** @var string */
42 public $mExpiry;
43
44 /** @var bool */
45 public $mHideName;
46
47 /** @var int */
48 public $mParentBlockId;
49
50 /** @var int */
51 private $mId;
52
53 /** @var bool */
54 private $mFromMaster;
55
56 /** @var bool */
57 private $mBlockEmail;
58
59 /** @var bool */
60 private $mDisableUsertalk;
61
62 /** @var bool */
63 private $mCreateAccount;
64
65 /** @var User|string */
66 private $target;
67
68 /** @var int Hack for foreign blocking (CentralAuth) */
69 private $forcedTargetID;
70
71 /** @var int Block::TYPE_ constant. Can only be USER, IP or RANGE internally */
72 private $type;
73
74 /** @var User */
75 private $blocker;
76
77 /** @var bool */
78 private $isHardblock;
79
80 /** @var bool */
81 private $isAutoblocking;
82
83 /** @var string|null */
84 private $systemBlockType;
85
86 /** @var bool */
87 private $isSitewide;
88
89 /** @var Restriction[] */
90 private $restrictions;
91
92 # TYPE constants
93 const TYPE_USER = 1;
94 const TYPE_IP = 2;
95 const TYPE_RANGE = 3;
96 const TYPE_AUTO = 4;
97 const TYPE_ID = 5;
98
99 /**
100 * Create a new block with specified parameters on a user, IP or IP range.
101 *
102 * @param array $options Parameters of the block:
103 * address string|User Target user name, User object, IP address or IP range
104 * user int Override target user ID (for foreign users)
105 * by int User ID of the blocker
106 * reason string Reason of the block
107 * timestamp string The time at which the block comes into effect
108 * auto bool Is this an automatic block?
109 * expiry string Timestamp of expiration of the block or 'infinity'
110 * anonOnly bool Only disallow anonymous actions
111 * createAccount bool Disallow creation of new accounts
112 * enableAutoblock bool Enable automatic blocking
113 * hideName bool Hide the target user name
114 * blockEmail bool Disallow sending emails
115 * allowUsertalk bool Allow the target to edit its own talk page
116 * byText string Username of the blocker (for foreign users)
117 * systemBlock string Indicate that this block is automatically
118 * created by MediaWiki rather than being stored
119 * in the database. Value is a string to return
120 * from self::getSystemBlockType().
121 *
122 * @since 1.26 accepts $options array instead of individual parameters; order
123 * of parameters above reflects the original order
124 */
125 function __construct( $options = [] ) {
126 $defaults = [
127 'address' => '',
128 'user' => null,
129 'by' => null,
130 'reason' => '',
131 'timestamp' => '',
132 'auto' => false,
133 'expiry' => '',
134 'anonOnly' => false,
135 'createAccount' => false,
136 'enableAutoblock' => false,
137 'hideName' => false,
138 'blockEmail' => false,
139 'allowUsertalk' => false,
140 'byText' => '',
141 'systemBlock' => null,
142 'sitewide' => true,
143 ];
144
145 if ( func_num_args() > 1 || !is_array( $options ) ) {
146 $options = array_combine(
147 array_slice( array_keys( $defaults ), 0, func_num_args() ),
148 func_get_args()
149 );
150 wfDeprecated( __METHOD__ . ' with multiple arguments', '1.26' );
151 }
152
153 $options += $defaults;
154
155 $this->setTarget( $options['address'] );
156
157 if ( $this->target instanceof User && $options['user'] ) {
158 # Needed for foreign users
159 $this->forcedTargetID = $options['user'];
160 }
161
162 if ( $options['by'] ) {
163 # Local user
164 $this->setBlocker( User::newFromId( $options['by'] ) );
165 } else {
166 # Foreign user
167 $this->setBlocker( $options['byText'] );
168 }
169
170 $this->mReason = $options['reason'];
171 $this->mTimestamp = wfTimestamp( TS_MW, $options['timestamp'] );
172 $this->mExpiry = wfGetDB( DB_REPLICA )->decodeExpiry( $options['expiry'] );
173
174 # Boolean settings
175 $this->mAuto = (bool)$options['auto'];
176 $this->mHideName = (bool)$options['hideName'];
177 $this->isHardblock( !$options['anonOnly'] );
178 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
179 $this->isSitewide( (bool)$options['sitewide'] );
180
181 # Prevention measures
182 $this->prevents( 'sendemail', (bool)$options['blockEmail'] );
183 $this->prevents( 'editownusertalk', !$options['allowUsertalk'] );
184 $this->prevents( 'createaccount', (bool)$options['createAccount'] );
185
186 $this->mFromMaster = false;
187 $this->systemBlockType = $options['systemBlock'];
188 }
189
190 /**
191 * Load a blocked user from their block id.
192 *
193 * @param int $id Block id to search for
194 * @return Block|null
195 */
196 public static function newFromID( $id ) {
197 $dbr = wfGetDB( DB_REPLICA );
198 $blockQuery = self::getQueryInfo();
199 $res = $dbr->selectRow(
200 $blockQuery['tables'],
201 $blockQuery['fields'],
202 [ 'ipb_id' => $id ],
203 __METHOD__,
204 [],
205 $blockQuery['joins']
206 );
207 if ( $res ) {
208 return self::newFromRow( $res );
209 } else {
210 return null;
211 }
212 }
213
214 /**
215 * Return the list of ipblocks fields that should be selected to create
216 * a new block.
217 * @deprecated since 1.31, use self::getQueryInfo() instead.
218 * @return array
219 */
220 public static function selectFields() {
221 global $wgActorTableSchemaMigrationStage;
222
223 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW ) {
224 // If code is using this instead of self::getQueryInfo(), there's a
225 // decent chance it's going to try to directly access
226 // $row->ipb_by or $row->ipb_by_text and we can't give it
227 // useful values here once those aren't being used anymore.
228 throw new BadMethodCallException(
229 'Cannot use ' . __METHOD__
230 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
231 );
232 }
233
234 wfDeprecated( __METHOD__, '1.31' );
235 return [
236 'ipb_id',
237 'ipb_address',
238 'ipb_by',
239 'ipb_by_text',
240 'ipb_by_actor' => 'NULL',
241 'ipb_timestamp',
242 'ipb_auto',
243 'ipb_anon_only',
244 'ipb_create_account',
245 'ipb_enable_autoblock',
246 'ipb_expiry',
247 'ipb_deleted',
248 'ipb_block_email',
249 'ipb_allow_usertalk',
250 'ipb_parent_block_id',
251 'ipb_sitewide',
252 ] + CommentStore::getStore()->getFields( 'ipb_reason' );
253 }
254
255 /**
256 * Return the tables, fields, and join conditions to be selected to create
257 * a new block object.
258 * @since 1.31
259 * @return array With three keys:
260 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
261 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
262 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
263 */
264 public static function getQueryInfo() {
265 $commentQuery = CommentStore::getStore()->getJoin( 'ipb_reason' );
266 $actorQuery = ActorMigration::newMigration()->getJoin( 'ipb_by' );
267 return [
268 'tables' => [ 'ipblocks' ] + $commentQuery['tables'] + $actorQuery['tables'],
269 'fields' => [
270 'ipb_id',
271 'ipb_address',
272 'ipb_timestamp',
273 'ipb_auto',
274 'ipb_anon_only',
275 'ipb_create_account',
276 'ipb_enable_autoblock',
277 'ipb_expiry',
278 'ipb_deleted',
279 'ipb_block_email',
280 'ipb_allow_usertalk',
281 'ipb_parent_block_id',
282 'ipb_sitewide',
283 ] + $commentQuery['fields'] + $actorQuery['fields'],
284 'joins' => $commentQuery['joins'] + $actorQuery['joins'],
285 ];
286 }
287
288 /**
289 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
290 * the blocking user or the block timestamp, only things which affect the blocked user
291 *
292 * @param Block $block
293 *
294 * @return bool
295 */
296 public function equals( Block $block ) {
297 return (
298 (string)$this->target == (string)$block->target
299 && $this->type == $block->type
300 && $this->mAuto == $block->mAuto
301 && $this->isHardblock() == $block->isHardblock()
302 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
303 && $this->mExpiry == $block->mExpiry
304 && $this->isAutoblocking() == $block->isAutoblocking()
305 && $this->mHideName == $block->mHideName
306 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
307 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
308 && $this->mReason == $block->mReason
309 && $this->isSitewide() == $block->isSitewide()
310 // Block::getRestrictions() may perform a database query, so keep it at
311 // the end.
312 && BlockRestriction::equals( $this->getRestrictions(), $block->getRestrictions() )
313 );
314 }
315
316 /**
317 * Load a block from the database which affects the already-set $this->target:
318 * 1) A block directly on the given user or IP
319 * 2) A rangeblock encompassing the given IP (smallest first)
320 * 3) An autoblock on the given IP
321 * @param User|string|null $vagueTarget Also search for blocks affecting this target. Doesn't
322 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
323 * @throws MWException
324 * @return bool Whether a relevant block was found
325 */
326 protected function newLoad( $vagueTarget = null ) {
327 $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_REPLICA );
328
329 if ( $this->type !== null ) {
330 $conds = [
331 'ipb_address' => [ (string)$this->target ],
332 ];
333 } else {
334 $conds = [ 'ipb_address' => [] ];
335 }
336
337 # Be aware that the != '' check is explicit, since empty values will be
338 # passed by some callers (T31116)
339 if ( $vagueTarget != '' ) {
340 list( $target, $type ) = self::parseTarget( $vagueTarget );
341 switch ( $type ) {
342 case self::TYPE_USER:
343 # Slightly weird, but who are we to argue?
344 $conds['ipb_address'][] = (string)$target;
345 break;
346
347 case self::TYPE_IP:
348 $conds['ipb_address'][] = (string)$target;
349 $conds[] = self::getRangeCond( IP::toHex( $target ) );
350 $conds = $db->makeList( $conds, LIST_OR );
351 break;
352
353 case self::TYPE_RANGE:
354 list( $start, $end ) = IP::parseRange( $target );
355 $conds['ipb_address'][] = (string)$target;
356 $conds[] = self::getRangeCond( $start, $end );
357 $conds = $db->makeList( $conds, LIST_OR );
358 break;
359
360 default:
361 throw new MWException( "Tried to load block with invalid type" );
362 }
363 }
364
365 $blockQuery = self::getQueryInfo();
366 $res = $db->select(
367 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__, [], $blockQuery['joins']
368 );
369
370 # This result could contain a block on the user, a block on the IP, and a russian-doll
371 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
372 $bestRow = null;
373
374 # Lower will be better
375 $bestBlockScore = 100;
376
377 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
378 $bestBlockPreventsEdit = null;
379
380 foreach ( $res as $row ) {
381 $block = self::newFromRow( $row );
382
383 # Don't use expired blocks
384 if ( $block->isExpired() ) {
385 continue;
386 }
387
388 # Don't use anon only blocks on users
389 if ( $this->type == self::TYPE_USER && !$block->isHardblock() ) {
390 continue;
391 }
392
393 if ( $block->getType() == self::TYPE_RANGE ) {
394 # This is the number of bits that are allowed to vary in the block, give
395 # or take some floating point errors
396 $end = Wikimedia\base_convert( $block->getRangeEnd(), 16, 10 );
397 $start = Wikimedia\base_convert( $block->getRangeStart(), 16, 10 );
398 $size = log( $end - $start + 1, 2 );
399
400 # This has the nice property that a /32 block is ranked equally with a
401 # single-IP block, which is exactly what it is...
402 $score = self::TYPE_RANGE - 1 + ( $size / 128 );
403
404 } else {
405 $score = $block->getType();
406 }
407
408 if ( $score < $bestBlockScore ) {
409 $bestBlockScore = $score;
410 $bestRow = $row;
411 $bestBlockPreventsEdit = $block->prevents( 'edit' );
412 }
413 }
414
415 if ( $bestRow !== null ) {
416 $this->initFromRow( $bestRow );
417 $this->prevents( 'edit', $bestBlockPreventsEdit );
418 return true;
419 } else {
420 return false;
421 }
422 }
423
424 /**
425 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
426 * @param string $start Hexadecimal IP representation
427 * @param string|null $end Hexadecimal IP representation, or null to use $start = $end
428 * @return string
429 */
430 public static function getRangeCond( $start, $end = null ) {
431 if ( $end === null ) {
432 $end = $start;
433 }
434 # Per T16634, we want to include relevant active rangeblocks; for
435 # rangeblocks, we want to include larger ranges which enclose the given
436 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
437 # so we can improve performance by filtering on a LIKE clause
438 $chunk = self::getIpFragment( $start );
439 $dbr = wfGetDB( DB_REPLICA );
440 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
441
442 # Fairly hard to make a malicious SQL statement out of hex characters,
443 # but stranger things have happened...
444 $safeStart = $dbr->addQuotes( $start );
445 $safeEnd = $dbr->addQuotes( $end );
446
447 return $dbr->makeList(
448 [
449 "ipb_range_start $like",
450 "ipb_range_start <= $safeStart",
451 "ipb_range_end >= $safeEnd",
452 ],
453 LIST_AND
454 );
455 }
456
457 /**
458 * Get the component of an IP address which is certain to be the same between an IP
459 * address and a rangeblock containing that IP address.
460 * @param string $hex Hexadecimal IP representation
461 * @return string
462 */
463 protected static function getIpFragment( $hex ) {
464 global $wgBlockCIDRLimit;
465 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
466 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
467 } else {
468 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
469 }
470 }
471
472 /**
473 * Given a database row from the ipblocks table, initialize
474 * member variables
475 * @param stdClass $row A row from the ipblocks table
476 */
477 protected function initFromRow( $row ) {
478 $this->setTarget( $row->ipb_address );
479 $this->setBlocker( User::newFromAnyId(
480 $row->ipb_by, $row->ipb_by_text, $row->ipb_by_actor ?? null
481 ) );
482
483 $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
484 $this->mAuto = $row->ipb_auto;
485 $this->mHideName = $row->ipb_deleted;
486 $this->mId = (int)$row->ipb_id;
487 $this->mParentBlockId = $row->ipb_parent_block_id;
488
489 // I wish I didn't have to do this
490 $db = wfGetDB( DB_REPLICA );
491 $this->mExpiry = $db->decodeExpiry( $row->ipb_expiry );
492 $this->mReason = CommentStore::getStore()
493 // Legacy because $row may have come from self::selectFields()
494 ->getCommentLegacy( $db, 'ipb_reason', $row )->text;
495
496 $this->isHardblock( !$row->ipb_anon_only );
497 $this->isAutoblocking( $row->ipb_enable_autoblock );
498 $this->isSitewide( (bool)$row->ipb_sitewide );
499
500 $this->prevents( 'createaccount', $row->ipb_create_account );
501 $this->prevents( 'sendemail', $row->ipb_block_email );
502 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk );
503 }
504
505 /**
506 * Create a new Block object from a database row
507 * @param stdClass $row Row from the ipblocks table
508 * @return Block
509 */
510 public static function newFromRow( $row ) {
511 $block = new Block;
512 $block->initFromRow( $row );
513 return $block;
514 }
515
516 /**
517 * Delete the row from the IP blocks table.
518 *
519 * @throws MWException
520 * @return bool
521 */
522 public function delete() {
523 if ( wfReadOnly() ) {
524 return false;
525 }
526
527 if ( !$this->getId() ) {
528 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
529 }
530
531 $dbw = wfGetDB( DB_MASTER );
532
533 BlockRestriction::deleteByParentBlockId( $this->getId() );
534 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__ );
535
536 BlockRestriction::deleteByBlockId( $this->getId() );
537 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__ );
538
539 return $dbw->affectedRows() > 0;
540 }
541
542 /**
543 * Insert a block into the block table. Will fail if there is a conflicting
544 * block (same name and options) already in the database.
545 *
546 * @param IDatabase|null $dbw If you have one available
547 * @return bool|array False on failure, assoc array on success:
548 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
549 */
550 public function insert( $dbw = null ) {
551 global $wgBlockDisablesLogin;
552
553 if ( $this->getSystemBlockType() !== null ) {
554 throw new MWException( 'Cannot insert a system block into the database' );
555 }
556 if ( !$this->getBlocker() || $this->getBlocker()->getName() === '' ) {
557 throw new MWException( 'Cannot insert a block without a blocker set' );
558 }
559
560 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
561
562 if ( $dbw === null ) {
563 $dbw = wfGetDB( DB_MASTER );
564 }
565
566 self::purgeExpired();
567
568 $row = $this->getDatabaseArray( $dbw );
569
570 $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
571 $affected = $dbw->affectedRows();
572 if ( $affected ) {
573 $this->setId( $dbw->insertId() );
574 if ( $this->restrictions ) {
575 BlockRestriction::insert( $this->restrictions );
576 }
577 }
578
579 # Don't collide with expired blocks.
580 # Do this after trying to insert to avoid locking.
581 if ( !$affected ) {
582 # T96428: The ipb_address index uses a prefix on a field, so
583 # use a standard SELECT + DELETE to avoid annoying gap locks.
584 $ids = $dbw->selectFieldValues( 'ipblocks',
585 'ipb_id',
586 [
587 'ipb_address' => $row['ipb_address'],
588 'ipb_user' => $row['ipb_user'],
589 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
590 ],
591 __METHOD__
592 );
593 if ( $ids ) {
594 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__ );
595 BlockRestriction::deleteByBlockId( $ids );
596 $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
597 $affected = $dbw->affectedRows();
598 $this->setId( $dbw->insertId() );
599 if ( $this->restrictions ) {
600 BlockRestriction::insert( $this->restrictions );
601 }
602 }
603 }
604
605 if ( $affected ) {
606 $auto_ipd_ids = $this->doRetroactiveAutoblock();
607
608 if ( $wgBlockDisablesLogin && $this->target instanceof User ) {
609 // Change user login token to force them to be logged out.
610 $this->target->setToken();
611 $this->target->saveSettings();
612 }
613
614 return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
615 }
616
617 return false;
618 }
619
620 /**
621 * Update a block in the DB with new parameters.
622 * The ID field needs to be loaded first.
623 *
624 * @return bool|array False on failure, array on success:
625 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
626 */
627 public function update() {
628 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
629 $dbw = wfGetDB( DB_MASTER );
630
631 $dbw->startAtomic( __METHOD__ );
632
633 $result = $dbw->update(
634 'ipblocks',
635 $this->getDatabaseArray( $dbw ),
636 [ 'ipb_id' => $this->getId() ],
637 __METHOD__
638 );
639
640 // Only update the restrictions if they have been modified.
641 if ( $this->restrictions !== null ) {
642 // An empty array should remove all of the restrictions.
643 if ( empty( $this->restrictions ) ) {
644 $success = BlockRestriction::deleteByBlockId( $this->getId() );
645 } else {
646 $success = BlockRestriction::update( $this->restrictions );
647 }
648 // Update the result. The first false is the result, otherwise, true.
649 $result = $result && $success;
650 }
651
652 if ( $this->isAutoblocking() ) {
653 // update corresponding autoblock(s) (T50813)
654 $dbw->update(
655 'ipblocks',
656 $this->getAutoblockUpdateArray( $dbw ),
657 [ 'ipb_parent_block_id' => $this->getId() ],
658 __METHOD__
659 );
660
661 // Only update the restrictions if they have been modified.
662 if ( $this->restrictions !== null ) {
663 BlockRestriction::updateByParentBlockId( $this->getId(), $this->restrictions );
664 }
665 } else {
666 // autoblock no longer required, delete corresponding autoblock(s)
667 BlockRestriction::deleteByParentBlockId( $this->getId() );
668 $dbw->delete(
669 'ipblocks',
670 [ 'ipb_parent_block_id' => $this->getId() ],
671 __METHOD__
672 );
673 }
674
675 $dbw->endAtomic( __METHOD__ );
676
677 if ( $result ) {
678 $auto_ipd_ids = $this->doRetroactiveAutoblock();
679 return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
680 }
681
682 return $result;
683 }
684
685 /**
686 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
687 * @param IDatabase $dbw
688 * @return array
689 */
690 protected function getDatabaseArray( IDatabase $dbw ) {
691 $expiry = $dbw->encodeExpiry( $this->mExpiry );
692
693 if ( $this->forcedTargetID ) {
694 $uid = $this->forcedTargetID;
695 } else {
696 $uid = $this->target instanceof User ? $this->target->getId() : 0;
697 }
698
699 $a = [
700 'ipb_address' => (string)$this->target,
701 'ipb_user' => $uid,
702 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
703 'ipb_auto' => $this->mAuto,
704 'ipb_anon_only' => !$this->isHardblock(),
705 'ipb_create_account' => $this->prevents( 'createaccount' ),
706 'ipb_enable_autoblock' => $this->isAutoblocking(),
707 'ipb_expiry' => $expiry,
708 'ipb_range_start' => $this->getRangeStart(),
709 'ipb_range_end' => $this->getRangeEnd(),
710 'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
711 'ipb_block_email' => $this->prevents( 'sendemail' ),
712 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
713 'ipb_parent_block_id' => $this->mParentBlockId,
714 'ipb_sitewide' => $this->isSitewide(),
715 ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->mReason )
716 + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
717
718 return $a;
719 }
720
721 /**
722 * @param IDatabase $dbw
723 * @return array
724 */
725 protected function getAutoblockUpdateArray( IDatabase $dbw ) {
726 return [
727 'ipb_create_account' => $this->prevents( 'createaccount' ),
728 'ipb_deleted' => (int)$this->mHideName, // typecast required for SQLite
729 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
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->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
914 # Continue suppressing the name if needed
915 $autoblock->mHideName = $this->mHideName;
916 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
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/set whether the Block prevents a given action
1147 *
1148 * @param string $action Action to check
1149 * @param bool|null $x Value for set, or null to just get value
1150 * @return bool|null Null for unrecognized rights.
1151 */
1152 public function prevents( $action, $x = null ) {
1153 $config = RequestContext::getMain()->getConfig();
1154 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1155 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1156
1157 $res = null;
1158 switch ( $action ) {
1159 case 'edit':
1160 # For now... <evil laugh>
1161 $res = true;
1162 break;
1163 case 'createaccount':
1164 $res = wfSetVar( $this->mCreateAccount, $x );
1165 break;
1166 case 'sendemail':
1167 $res = wfSetVar( $this->mBlockEmail, $x );
1168 break;
1169 case 'upload':
1170 // Until T6995 is completed
1171 $res = $this->isSitewide();
1172 break;
1173 case 'editownusertalk':
1174 // NOTE: this check is not reliable on partial blocks
1175 // since partially blocked users are always allowed to edit
1176 // their own talk page unless a restriction exists on the
1177 // page or User_talk: namespace
1178 $res = wfSetVar( $this->mDisableUsertalk, $x );
1179
1180 // edit own user talk can be disabled by config
1181 if ( !$blockAllowsUTEdit ) {
1182 $res = true;
1183 }
1184 break;
1185 case 'read':
1186 $res = false;
1187 break;
1188 }
1189 if ( !$res && $blockDisablesLogin ) {
1190 // If a block would disable login, then it should
1191 // prevent any action that all users cannot do
1192 $anon = new User;
1193 $res = $anon->isAllowed( $action ) ? $res : true;
1194 }
1195
1196 return $res;
1197 }
1198
1199 /**
1200 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1201 * @return string Text is escaped
1202 */
1203 public function getRedactedName() {
1204 if ( $this->mAuto ) {
1205 return Html::rawElement(
1206 'span',
1207 [ 'class' => 'mw-autoblockid' ],
1208 wfMessage( 'autoblockid', $this->mId )
1209 );
1210 } else {
1211 return htmlspecialchars( $this->getTarget() );
1212 }
1213 }
1214
1215 /**
1216 * Get a timestamp of the expiry for autoblocks
1217 *
1218 * @param string|int $timestamp
1219 * @return string
1220 */
1221 public static function getAutoblockExpiry( $timestamp ) {
1222 global $wgAutoblockExpiry;
1223
1224 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
1225 }
1226
1227 /**
1228 * Purge expired blocks from the ipblocks table
1229 */
1230 public static function purgeExpired() {
1231 if ( wfReadOnly() ) {
1232 return;
1233 }
1234
1235 DeferredUpdates::addUpdate( new AutoCommitUpdate(
1236 wfGetDB( DB_MASTER ),
1237 __METHOD__,
1238 function ( IDatabase $dbw, $fname ) {
1239 $ids = $dbw->selectFieldValues( 'ipblocks',
1240 'ipb_id',
1241 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1242 $fname
1243 );
1244 if ( $ids ) {
1245 BlockRestriction::deleteByBlockId( $ids );
1246 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1247 }
1248 }
1249 ) );
1250 }
1251
1252 /**
1253 * Given a target and the target's type, get an existing Block object if possible.
1254 * @param string|User|int $specificTarget A block target, which may be one of several types:
1255 * * A user to block, in which case $target will be a User
1256 * * An IP to block, in which case $target will be a User generated by using
1257 * User::newFromName( $ip, false ) to turn off name validation
1258 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1259 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1260 * usernames
1261 * Calling this with a user, IP address or range will not select autoblocks, and will
1262 * only select a block where the targets match exactly (so looking for blocks on
1263 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1264 * @param string|User|int|null $vagueTarget As above, but we will search for *any* block which
1265 * affects that target (so for an IP address, get ranges containing that IP; and also
1266 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1267 * @param bool $fromMaster Whether to use the DB_MASTER database
1268 * @return Block|null (null if no relevant block could be found). The target and type
1269 * of the returned Block will refer to the actual block which was found, which might
1270 * not be the same as the target you gave if you used $vagueTarget!
1271 */
1272 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1273 list( $target, $type ) = self::parseTarget( $specificTarget );
1274 if ( $type == self::TYPE_ID || $type == self::TYPE_AUTO ) {
1275 return self::newFromID( $target );
1276
1277 } elseif ( $target === null && $vagueTarget == '' ) {
1278 # We're not going to find anything useful here
1279 # Be aware that the == '' check is explicit, since empty values will be
1280 # passed by some callers (T31116)
1281 return null;
1282
1283 } elseif ( in_array(
1284 $type,
1285 [ self::TYPE_USER, self::TYPE_IP, self::TYPE_RANGE, null ] )
1286 ) {
1287 $block = new Block();
1288 $block->fromMaster( $fromMaster );
1289
1290 if ( $type !== null ) {
1291 $block->setTarget( $target );
1292 }
1293
1294 if ( $block->newLoad( $vagueTarget ) ) {
1295 return $block;
1296 }
1297 }
1298 return null;
1299 }
1300
1301 /**
1302 * Get all blocks that match any IP from an array of IP addresses
1303 *
1304 * @param array $ipChain List of IPs (strings), usually retrieved from the
1305 * X-Forwarded-For header of the request
1306 * @param bool $isAnon Exclude anonymous-only blocks if false
1307 * @param bool $fromMaster Whether to query the master or replica DB
1308 * @return array Array of Blocks
1309 * @since 1.22
1310 */
1311 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1312 if ( $ipChain === [] ) {
1313 return [];
1314 }
1315
1316 $conds = [];
1317 $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1318 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1319 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1320 # necessarily trust the header given to us, make sure that we are only
1321 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1322 # Do not treat private IP spaces as special as it may be desirable for wikis
1323 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1324 if ( !IP::isValid( $ipaddr ) ) {
1325 continue;
1326 }
1327 # Don't check trusted IPs (includes local squids which will be in every request)
1328 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1329 continue;
1330 }
1331 # Check both the original IP (to check against single blocks), as well as build
1332 # the clause to check for rangeblocks for the given IP.
1333 $conds['ipb_address'][] = $ipaddr;
1334 $conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
1335 }
1336
1337 if ( $conds === [] ) {
1338 return [];
1339 }
1340
1341 if ( $fromMaster ) {
1342 $db = wfGetDB( DB_MASTER );
1343 } else {
1344 $db = wfGetDB( DB_REPLICA );
1345 }
1346 $conds = $db->makeList( $conds, LIST_OR );
1347 if ( !$isAnon ) {
1348 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1349 }
1350 $blockQuery = self::getQueryInfo();
1351 $rows = $db->select(
1352 $blockQuery['tables'],
1353 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1354 $conds,
1355 __METHOD__,
1356 [],
1357 $blockQuery['joins']
1358 );
1359
1360 $blocks = [];
1361 foreach ( $rows as $row ) {
1362 $block = self::newFromRow( $row );
1363 if ( !$block->isExpired() ) {
1364 $blocks[] = $block;
1365 }
1366 }
1367
1368 return $blocks;
1369 }
1370
1371 /**
1372 * From a list of multiple blocks, find the most exact and strongest Block.
1373 *
1374 * The logic for finding the "best" block is:
1375 * - Blocks that match the block's target IP are preferred over ones in a range
1376 * - Hardblocks are chosen over softblocks that prevent account creation
1377 * - Softblocks that prevent account creation are chosen over other softblocks
1378 * - Other softblocks are chosen over autoblocks
1379 * - If there are multiple exact or range blocks at the same level, the one chosen
1380 * is random
1381 * This should be used when $blocks where retrieved from the user's IP address
1382 * and $ipChain is populated from the same IP address information.
1383 *
1384 * @param array $blocks Array of Block objects
1385 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1386 * a block is to the server, and if a block matches exactly, or is in a range.
1387 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1388 * local-squid, ...)
1389 * @throws MWException
1390 * @return Block|null The "best" block from the list
1391 */
1392 public static function chooseBlock( array $blocks, array $ipChain ) {
1393 if ( $blocks === [] ) {
1394 return null;
1395 } elseif ( count( $blocks ) == 1 ) {
1396 return $blocks[0];
1397 }
1398
1399 // Sort hard blocks before soft ones and secondarily sort blocks
1400 // that disable account creation before those that don't.
1401 usort( $blocks, function ( Block $a, Block $b ) {
1402 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1403 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1404 return strcmp( $bWeight, $aWeight ); // highest weight first
1405 } );
1406
1407 $blocksListExact = [
1408 'hard' => false,
1409 'disable_create' => false,
1410 'other' => false,
1411 'auto' => false
1412 ];
1413 $blocksListRange = [
1414 'hard' => false,
1415 'disable_create' => false,
1416 'other' => false,
1417 'auto' => false
1418 ];
1419 $ipChain = array_reverse( $ipChain );
1420
1421 /** @var Block $block */
1422 foreach ( $blocks as $block ) {
1423 // Stop searching if we have already have a "better" block. This
1424 // is why the order of the blocks matters
1425 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1426 break;
1427 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1428 break;
1429 }
1430
1431 foreach ( $ipChain as $checkip ) {
1432 $checkipHex = IP::toHex( $checkip );
1433 if ( (string)$block->getTarget() === $checkip ) {
1434 if ( $block->isHardblock() ) {
1435 $blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
1436 } elseif ( $block->prevents( 'createaccount' ) ) {
1437 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
1438 } elseif ( $block->mAuto ) {
1439 $blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
1440 } else {
1441 $blocksListExact['other'] = $blocksListExact['other'] ?: $block;
1442 }
1443 // We found closest exact match in the ip list, so go to the next Block
1444 break;
1445 } elseif ( array_filter( $blocksListExact ) == []
1446 && $block->getRangeStart() <= $checkipHex
1447 && $block->getRangeEnd() >= $checkipHex
1448 ) {
1449 if ( $block->isHardblock() ) {
1450 $blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
1451 } elseif ( $block->prevents( 'createaccount' ) ) {
1452 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
1453 } elseif ( $block->mAuto ) {
1454 $blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
1455 } else {
1456 $blocksListRange['other'] = $blocksListRange['other'] ?: $block;
1457 }
1458 break;
1459 }
1460 }
1461 }
1462
1463 if ( array_filter( $blocksListExact ) == [] ) {
1464 $blocksList = &$blocksListRange;
1465 } else {
1466 $blocksList = &$blocksListExact;
1467 }
1468
1469 $chosenBlock = null;
1470 if ( $blocksList['hard'] ) {
1471 $chosenBlock = $blocksList['hard'];
1472 } elseif ( $blocksList['disable_create'] ) {
1473 $chosenBlock = $blocksList['disable_create'];
1474 } elseif ( $blocksList['other'] ) {
1475 $chosenBlock = $blocksList['other'];
1476 } elseif ( $blocksList['auto'] ) {
1477 $chosenBlock = $blocksList['auto'];
1478 } else {
1479 throw new MWException( "Proxy block found, but couldn't be classified." );
1480 }
1481
1482 return $chosenBlock;
1483 }
1484
1485 /**
1486 * From an existing Block, get the target and the type of target.
1487 * Note that, except for null, it is always safe to treat the target
1488 * as a string; for User objects this will return User::__toString()
1489 * which in turn gives User::getName().
1490 *
1491 * @param string|int|User|null $target
1492 * @return array [ User|String|null, Block::TYPE_ constant|null ]
1493 */
1494 public static function parseTarget( $target ) {
1495 # We may have been through this before
1496 if ( $target instanceof User ) {
1497 if ( IP::isValid( $target->getName() ) ) {
1498 return [ $target, self::TYPE_IP ];
1499 } else {
1500 return [ $target, self::TYPE_USER ];
1501 }
1502 } elseif ( $target === null ) {
1503 return [ null, null ];
1504 }
1505
1506 $target = trim( $target );
1507
1508 if ( IP::isValid( $target ) ) {
1509 # We can still create a User if it's an IP address, but we need to turn
1510 # off validation checking (which would exclude IP addresses)
1511 return [
1512 User::newFromName( IP::sanitizeIP( $target ), false ),
1513 self::TYPE_IP
1514 ];
1515
1516 } elseif ( IP::isValidRange( $target ) ) {
1517 # Can't create a User from an IP range
1518 return [ IP::sanitizeRange( $target ), self::TYPE_RANGE ];
1519 }
1520
1521 # Consider the possibility that this is not a username at all
1522 # but actually an old subpage (T31797)
1523 if ( strpos( $target, '/' ) !== false ) {
1524 # An old subpage, drill down to the user behind it
1525 $target = explode( '/', $target )[0];
1526 }
1527
1528 $userObj = User::newFromName( $target );
1529 if ( $userObj instanceof User ) {
1530 # Note that since numbers are valid usernames, a $target of "12345" will be
1531 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1532 # since hash characters are not valid in usernames or titles generally.
1533 return [ $userObj, self::TYPE_USER ];
1534
1535 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1536 # Autoblock reference in the form "#12345"
1537 return [ substr( $target, 1 ), self::TYPE_AUTO ];
1538
1539 } else {
1540 # WTF?
1541 return [ null, null ];
1542 }
1543 }
1544
1545 /**
1546 * Get the type of target for this particular block
1547 * @return int Block::TYPE_ constant, will never be TYPE_ID
1548 */
1549 public function getType() {
1550 return $this->mAuto
1551 ? self::TYPE_AUTO
1552 : $this->type;
1553 }
1554
1555 /**
1556 * Get the target and target type for this particular Block. Note that for autoblocks,
1557 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1558 * in this situation.
1559 * @return array [ User|String, Block::TYPE_ constant ]
1560 * @todo FIXME: This should be an integral part of the Block member variables
1561 */
1562 public function getTargetAndType() {
1563 return [ $this->getTarget(), $this->getType() ];
1564 }
1565
1566 /**
1567 * Get the target for this particular Block. Note that for autoblocks,
1568 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1569 * in this situation.
1570 * @return User|string
1571 */
1572 public function getTarget() {
1573 return $this->target;
1574 }
1575
1576 /**
1577 * @since 1.19
1578 *
1579 * @return mixed|string
1580 */
1581 public function getExpiry() {
1582 return $this->mExpiry;
1583 }
1584
1585 /**
1586 * Set the target for this block, and update $this->type accordingly
1587 * @param mixed $target
1588 */
1589 public function setTarget( $target ) {
1590 list( $this->target, $this->type ) = self::parseTarget( $target );
1591 }
1592
1593 /**
1594 * Get the user who implemented this block
1595 * @return User User object. May name a foreign user.
1596 */
1597 public function getBlocker() {
1598 return $this->blocker;
1599 }
1600
1601 /**
1602 * Set the user who implemented (or will implement) this block
1603 * @param User|string $user Local User object or username string
1604 */
1605 public function setBlocker( $user ) {
1606 if ( is_string( $user ) ) {
1607 $user = User::newFromName( $user, false );
1608 }
1609
1610 if ( $user->isAnon() && User::isUsableName( $user->getName() ) ) {
1611 throw new InvalidArgumentException(
1612 'Blocker must be a local user or a name that cannot be a local user'
1613 );
1614 }
1615
1616 $this->blocker = $user;
1617 }
1618
1619 /**
1620 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1621 * the same as the block's, to a maximum of 24 hours.
1622 *
1623 * @since 1.29
1624 *
1625 * @param WebResponse $response The response on which to set the cookie.
1626 */
1627 public function setCookie( WebResponse $response ) {
1628 // Calculate the default expiry time.
1629 $maxExpiryTime = wfTimestamp( TS_MW, wfTimestamp() + ( 24 * 60 * 60 ) );
1630
1631 // Use the Block's expiry time only if it's less than the default.
1632 $expiryTime = $this->getExpiry();
1633 if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
1634 $expiryTime = $maxExpiryTime;
1635 }
1636
1637 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1638 $expiryValue = DateTime::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1639 $cookieOptions = [ 'httpOnly' => false ];
1640 $cookieValue = $this->getCookieValue();
1641 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1642 }
1643
1644 /**
1645 * Unset the 'BlockID' cookie.
1646 *
1647 * @since 1.29
1648 *
1649 * @param WebResponse $response The response on which to unset the cookie.
1650 */
1651 public static function clearCookie( WebResponse $response ) {
1652 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1653 }
1654
1655 /**
1656 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1657 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1658 * be the block ID.
1659 *
1660 * @since 1.29
1661 *
1662 * @return string The block ID, probably concatenated with "!" and the HMAC.
1663 */
1664 public function getCookieValue() {
1665 $config = RequestContext::getMain()->getConfig();
1666 $id = $this->getId();
1667 $secretKey = $config->get( 'SecretKey' );
1668 if ( !$secretKey ) {
1669 // If there's no secret key, don't append a HMAC.
1670 return $id;
1671 }
1672 $hmac = MWCryptHash::hmac( $id, $secretKey, false );
1673 $cookieValue = $id . '!' . $hmac;
1674 return $cookieValue;
1675 }
1676
1677 /**
1678 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1679 * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
1680 *
1681 * @since 1.29
1682 *
1683 * @param string $cookieValue The string in which to find the ID.
1684 *
1685 * @return int|null The block ID, or null if the HMAC is present and invalid.
1686 */
1687 public static function getIdFromCookieValue( $cookieValue ) {
1688 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1689 $bangPos = strpos( $cookieValue, '!' );
1690 $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
1691 // Get the site-wide secret key.
1692 $config = RequestContext::getMain()->getConfig();
1693 $secretKey = $config->get( 'SecretKey' );
1694 if ( !$secretKey ) {
1695 // If there's no secret key, just use the ID as given.
1696 return $id;
1697 }
1698 $storedHmac = substr( $cookieValue, $bangPos + 1 );
1699 $calculatedHmac = MWCryptHash::hmac( $id, $secretKey, false );
1700 if ( $calculatedHmac === $storedHmac ) {
1701 return $id;
1702 } else {
1703 return null;
1704 }
1705 }
1706
1707 /**
1708 * Get the key and parameters for the corresponding error message.
1709 *
1710 * @since 1.22
1711 * @param IContextSource $context
1712 * @return array
1713 */
1714 public function getPermissionsError( IContextSource $context ) {
1715 $params = $this->getBlockErrorParams( $context );
1716
1717 $msg = 'blockedtext';
1718 if ( $this->getSystemBlockType() !== null ) {
1719 $msg = 'systemblockedtext';
1720 } elseif ( $this->mAuto ) {
1721 $msg = 'autoblockedtext';
1722 } elseif ( !$this->isSitewide() ) {
1723 $msg = 'blockedtext-partial';
1724 }
1725
1726 array_unshift( $params, $msg );
1727
1728 return $params;
1729 }
1730
1731 /**
1732 * Get block information used in different block error messages
1733 *
1734 * @since 1.33
1735 * @param IContextSource $context
1736 * @return array
1737 */
1738 public function getBlockErrorParams( IContextSource $context ) {
1739 $blocker = $this->getBlocker();
1740 if ( $blocker instanceof User ) { // local user
1741 $blockerUserpage = $blocker->getUserPage();
1742 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1743 } else { // foreign user
1744 $link = $blocker;
1745 }
1746
1747 $reason = $this->mReason;
1748 if ( $reason == '' ) {
1749 $reason = $context->msg( 'blockednoreason' )->text();
1750 }
1751
1752 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1753 * This could be a username, an IP range, or a single IP. */
1754 $intended = $this->getTarget();
1755 $systemBlockType = $this->getSystemBlockType();
1756 $lang = $context->getLanguage();
1757
1758 return [
1759 $link,
1760 $reason,
1761 $context->getRequest()->getIP(),
1762 $this->getByName(),
1763 $systemBlockType ?? $this->getId(),
1764 $lang->formatExpiry( $this->mExpiry ),
1765 (string)$intended,
1766 $lang->userTimeAndDate( $this->mTimestamp, $context->getUser() ),
1767 ];
1768 }
1769
1770 /**
1771 * Get Restrictions.
1772 *
1773 * Getting the restrictions will perform a database query if the restrictions
1774 * are not already loaded.
1775 *
1776 * @since 1.33
1777 * @return Restriction[]
1778 */
1779 public function getRestrictions() {
1780 if ( $this->restrictions === null ) {
1781 // If the block id has not been set, then do not attempt to load the
1782 // restrictions.
1783 if ( !$this->mId ) {
1784 return [];
1785 }
1786 $this->restrictions = BlockRestriction::loadByBlockId( $this->mId );
1787 }
1788
1789 return $this->restrictions;
1790 }
1791
1792 /**
1793 * Set Restrictions.
1794 *
1795 * @since 1.33
1796 * @param Restriction[] $restrictions
1797 * @return self
1798 */
1799 public function setRestrictions( array $restrictions ) {
1800 $this->restrictions = array_filter( $restrictions, function ( $restriction ) {
1801 return $restriction instanceof Restriction;
1802 } );
1803
1804 return $this;
1805 }
1806
1807 /**
1808 * Checks if a block applies to a particular title
1809 *
1810 * This check does not consider whether `$this->prevents( 'editownusertalk' )`
1811 * returns false, as the identity of the user making the hypothetical edit
1812 * isn't known here (particularly in the case of IP hardblocks, range
1813 * blocks, and auto-blocks).
1814 *
1815 * @param Title $title
1816 * @return bool
1817 */
1818 public function appliesToTitle( Title $title ) {
1819 if ( $this->isSitewide() ) {
1820 return true;
1821 }
1822
1823 $restrictions = $this->getRestrictions();
1824 foreach ( $restrictions as $restriction ) {
1825 if ( $restriction->matches( $title ) ) {
1826 return true;
1827 }
1828 }
1829
1830 return false;
1831 }
1832
1833 /**
1834 * Checks if a block applies to a particular namespace
1835 *
1836 * @since 1.33
1837 *
1838 * @param int $ns
1839 * @return bool
1840 */
1841 public function appliesToNamespace( $ns ) {
1842 if ( $this->isSitewide() ) {
1843 return true;
1844 }
1845
1846 // Blocks do not apply to virtual namespaces.
1847 if ( $ns < 0 ) {
1848 return false;
1849 }
1850
1851 $restriction = $this->findRestriction( NamespaceRestriction::TYPE, $ns );
1852
1853 return (bool)$restriction;
1854 }
1855
1856 /**
1857 * Checks if a block applies to a particular page
1858 *
1859 * This check does not consider whether `$this->prevents( 'editownusertalk' )`
1860 * returns false, as the identity of the user making the hypothetical edit
1861 * isn't known here (particularly in the case of IP hardblocks, range
1862 * blocks, and auto-blocks).
1863 *
1864 * @since 1.33
1865 *
1866 * @param int $pageId
1867 * @return bool
1868 */
1869 public function appliesToPage( $pageId ) {
1870 if ( $this->isSitewide() ) {
1871 return true;
1872 }
1873
1874 // If the pageId is not over zero, the block cannot apply to it.
1875 if ( $pageId <= 0 ) {
1876 return false;
1877 }
1878
1879 $restriction = $this->findRestriction( PageRestriction::TYPE, $pageId );
1880
1881 return (bool)$restriction;
1882 }
1883
1884 /**
1885 * Find Restriction by type and value.
1886 *
1887 * @param string $type
1888 * @param int $value
1889 * @return Restriction|null
1890 */
1891 private function findRestriction( $type, $value ) {
1892 $restrictions = $this->getRestrictions();
1893 foreach ( $restrictions as $restriction ) {
1894 if ( $restriction->getType() !== $type ) {
1895 continue;
1896 }
1897
1898 if ( $restriction->getValue() === $value ) {
1899 return $restriction;
1900 }
1901 }
1902
1903 return null;
1904 }
1905 }