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