Merge "Add support for 'hu-formal'"
[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\MediaWikiServices;
26
27 class Block {
28 /** @var string */
29 public $mReason;
30
31 /** @var string */
32 public $mTimestamp;
33
34 /** @var bool */
35 public $mAuto;
36
37 /** @var string */
38 public $mExpiry;
39
40 /** @var bool */
41 public $mHideName;
42
43 /** @var int */
44 public $mParentBlockId;
45
46 /** @var int */
47 private $mId;
48
49 /** @var bool */
50 private $mFromMaster;
51
52 /** @var bool */
53 private $mBlockEmail;
54
55 /** @var bool */
56 private $mDisableUsertalk;
57
58 /** @var bool */
59 private $mCreateAccount;
60
61 /** @var User|string */
62 private $target;
63
64 /** @var int Hack for foreign blocking (CentralAuth) */
65 private $forcedTargetID;
66
67 /** @var int Block::TYPE_ constant. Can only be USER, IP or RANGE internally */
68 private $type;
69
70 /** @var User */
71 private $blocker;
72
73 /** @var bool */
74 private $isHardblock;
75
76 /** @var bool */
77 private $isAutoblocking;
78
79 /** @var string|null */
80 private $systemBlockType;
81
82 # TYPE constants
83 const TYPE_USER = 1;
84 const TYPE_IP = 2;
85 const TYPE_RANGE = 3;
86 const TYPE_AUTO = 4;
87 const TYPE_ID = 5;
88
89 /**
90 * Create a new block with specified parameters on a user, IP or IP range.
91 *
92 * @param array $options Parameters of the block:
93 * address string|User Target user name, User object, IP address or IP range
94 * user int Override target user ID (for foreign users)
95 * by int User ID of the blocker
96 * reason string Reason of the block
97 * timestamp string The time at which the block comes into effect
98 * auto bool Is this an automatic block?
99 * expiry string Timestamp of expiration of the block or 'infinity'
100 * anonOnly bool Only disallow anonymous actions
101 * createAccount bool Disallow creation of new accounts
102 * enableAutoblock bool Enable automatic blocking
103 * hideName bool Hide the target user name
104 * blockEmail bool Disallow sending emails
105 * allowUsertalk bool Allow the target to edit its own talk page
106 * byText string Username of the blocker (for foreign users)
107 * systemBlock string Indicate that this block is automatically
108 * created by MediaWiki rather than being stored
109 * in the database. Value is a string to return
110 * from self::getSystemBlockType().
111 *
112 * @since 1.26 accepts $options array instead of individual parameters; order
113 * of parameters above reflects the original order
114 */
115 function __construct( $options = [] ) {
116 $defaults = [
117 'address' => '',
118 'user' => null,
119 'by' => null,
120 'reason' => '',
121 'timestamp' => '',
122 'auto' => false,
123 'expiry' => '',
124 'anonOnly' => false,
125 'createAccount' => false,
126 'enableAutoblock' => false,
127 'hideName' => false,
128 'blockEmail' => false,
129 'allowUsertalk' => false,
130 'byText' => '',
131 'systemBlock' => null,
132 ];
133
134 if ( func_num_args() > 1 || !is_array( $options ) ) {
135 $options = array_combine(
136 array_slice( array_keys( $defaults ), 0, func_num_args() ),
137 func_get_args()
138 );
139 wfDeprecated( __METHOD__ . ' with multiple arguments', '1.26' );
140 }
141
142 $options += $defaults;
143
144 $this->setTarget( $options['address'] );
145
146 if ( $this->target instanceof User && $options['user'] ) {
147 # Needed for foreign users
148 $this->forcedTargetID = $options['user'];
149 }
150
151 if ( $options['by'] ) {
152 # Local user
153 $this->setBlocker( User::newFromId( $options['by'] ) );
154 } else {
155 # Foreign user
156 $this->setBlocker( $options['byText'] );
157 }
158
159 $this->mReason = $options['reason'];
160 $this->mTimestamp = wfTimestamp( TS_MW, $options['timestamp'] );
161 $this->mExpiry = wfGetDB( DB_REPLICA )->decodeExpiry( $options['expiry'] );
162
163 # Boolean settings
164 $this->mAuto = (bool)$options['auto'];
165 $this->mHideName = (bool)$options['hideName'];
166 $this->isHardblock( !$options['anonOnly'] );
167 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
168
169 # Prevention measures
170 $this->prevents( 'sendemail', (bool)$options['blockEmail'] );
171 $this->prevents( 'editownusertalk', !$options['allowUsertalk'] );
172 $this->prevents( 'createaccount', (bool)$options['createAccount'] );
173
174 $this->mFromMaster = false;
175 $this->systemBlockType = $options['systemBlock'];
176 }
177
178 /**
179 * Load a blocked user from their block id.
180 *
181 * @param int $id Block id to search for
182 * @return Block|null
183 */
184 public static function newFromID( $id ) {
185 $dbr = wfGetDB( DB_REPLICA );
186 $blockQuery = self::getQueryInfo();
187 $res = $dbr->selectRow(
188 $blockQuery['tables'],
189 $blockQuery['fields'],
190 [ 'ipb_id' => $id ],
191 __METHOD__,
192 [],
193 $blockQuery['joins']
194 );
195 if ( $res ) {
196 return self::newFromRow( $res );
197 } else {
198 return null;
199 }
200 }
201
202 /**
203 * Return the list of ipblocks fields that should be selected to create
204 * a new block.
205 * @deprecated since 1.31, use self::getQueryInfo() instead.
206 * @return array
207 */
208 public static function selectFields() {
209 global $wgActorTableSchemaMigrationStage;
210
211 if ( $wgActorTableSchemaMigrationStage > MIGRATION_WRITE_BOTH ) {
212 // If code is using this instead of self::getQueryInfo(), there's a
213 // decent chance it's going to try to directly access
214 // $row->ipb_by or $row->ipb_by_text and we can't give it
215 // useful values here once those aren't being written anymore.
216 throw new BadMethodCallException(
217 'Cannot use ' . __METHOD__ . ' when $wgActorTableSchemaMigrationStage > MIGRATION_WRITE_BOTH'
218 );
219 }
220
221 wfDeprecated( __METHOD__, '1.31' );
222 return [
223 'ipb_id',
224 'ipb_address',
225 'ipb_by',
226 'ipb_by_text',
227 'ipb_by_actor' => $wgActorTableSchemaMigrationStage > MIGRATION_OLD ? 'ipb_by_actor' : null,
228 'ipb_timestamp',
229 'ipb_auto',
230 'ipb_anon_only',
231 'ipb_create_account',
232 'ipb_enable_autoblock',
233 'ipb_expiry',
234 'ipb_deleted',
235 'ipb_block_email',
236 'ipb_allow_usertalk',
237 'ipb_parent_block_id',
238 ] + CommentStore::getStore()->getFields( 'ipb_reason' );
239 }
240
241 /**
242 * Return the tables, fields, and join conditions to be selected to create
243 * a new block object.
244 * @since 1.31
245 * @return array With three keys:
246 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
247 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
248 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
249 */
250 public static function getQueryInfo() {
251 $commentQuery = CommentStore::getStore()->getJoin( 'ipb_reason' );
252 $actorQuery = ActorMigration::newMigration()->getJoin( 'ipb_by' );
253 return [
254 'tables' => [ 'ipblocks' ] + $commentQuery['tables'] + $actorQuery['tables'],
255 'fields' => [
256 'ipb_id',
257 'ipb_address',
258 'ipb_timestamp',
259 'ipb_auto',
260 'ipb_anon_only',
261 'ipb_create_account',
262 'ipb_enable_autoblock',
263 'ipb_expiry',
264 'ipb_deleted',
265 'ipb_block_email',
266 'ipb_allow_usertalk',
267 'ipb_parent_block_id',
268 ] + $commentQuery['fields'] + $actorQuery['fields'],
269 'joins' => $commentQuery['joins'] + $actorQuery['joins'],
270 ];
271 }
272
273 /**
274 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
275 * the blocking user or the block timestamp, only things which affect the blocked user
276 *
277 * @param Block $block
278 *
279 * @return bool
280 */
281 public function equals( Block $block ) {
282 return (
283 (string)$this->target == (string)$block->target
284 && $this->type == $block->type
285 && $this->mAuto == $block->mAuto
286 && $this->isHardblock() == $block->isHardblock()
287 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
288 && $this->mExpiry == $block->mExpiry
289 && $this->isAutoblocking() == $block->isAutoblocking()
290 && $this->mHideName == $block->mHideName
291 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
292 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
293 && $this->mReason == $block->mReason
294 );
295 }
296
297 /**
298 * Load a block from the database which affects the already-set $this->target:
299 * 1) A block directly on the given user or IP
300 * 2) A rangeblock encompassing the given IP (smallest first)
301 * 3) An autoblock on the given IP
302 * @param User|string $vagueTarget Also search for blocks affecting this target. Doesn't
303 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
304 * @throws MWException
305 * @return bool Whether a relevant block was found
306 */
307 protected function newLoad( $vagueTarget = null ) {
308 $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_REPLICA );
309
310 if ( $this->type !== null ) {
311 $conds = [
312 'ipb_address' => [ (string)$this->target ],
313 ];
314 } else {
315 $conds = [ 'ipb_address' => [] ];
316 }
317
318 # Be aware that the != '' check is explicit, since empty values will be
319 # passed by some callers (T31116)
320 if ( $vagueTarget != '' ) {
321 list( $target, $type ) = self::parseTarget( $vagueTarget );
322 switch ( $type ) {
323 case self::TYPE_USER:
324 # Slightly weird, but who are we to argue?
325 $conds['ipb_address'][] = (string)$target;
326 break;
327
328 case self::TYPE_IP:
329 $conds['ipb_address'][] = (string)$target;
330 $conds[] = self::getRangeCond( IP::toHex( $target ) );
331 $conds = $db->makeList( $conds, LIST_OR );
332 break;
333
334 case self::TYPE_RANGE:
335 list( $start, $end ) = IP::parseRange( $target );
336 $conds['ipb_address'][] = (string)$target;
337 $conds[] = self::getRangeCond( $start, $end );
338 $conds = $db->makeList( $conds, LIST_OR );
339 break;
340
341 default:
342 throw new MWException( "Tried to load block with invalid type" );
343 }
344 }
345
346 $blockQuery = self::getQueryInfo();
347 $res = $db->select(
348 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__, [], $blockQuery['joins']
349 );
350
351 # This result could contain a block on the user, a block on the IP, and a russian-doll
352 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
353 $bestRow = null;
354
355 # Lower will be better
356 $bestBlockScore = 100;
357
358 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
359 $bestBlockPreventsEdit = null;
360
361 foreach ( $res as $row ) {
362 $block = self::newFromRow( $row );
363
364 # Don't use expired blocks
365 if ( $block->isExpired() ) {
366 continue;
367 }
368
369 # Don't use anon only blocks on users
370 if ( $this->type == self::TYPE_USER && !$block->isHardblock() ) {
371 continue;
372 }
373
374 if ( $block->getType() == self::TYPE_RANGE ) {
375 # This is the number of bits that are allowed to vary in the block, give
376 # or take some floating point errors
377 $end = Wikimedia\base_convert( $block->getRangeEnd(), 16, 10 );
378 $start = Wikimedia\base_convert( $block->getRangeStart(), 16, 10 );
379 $size = log( $end - $start + 1, 2 );
380
381 # This has the nice property that a /32 block is ranked equally with a
382 # single-IP block, which is exactly what it is...
383 $score = self::TYPE_RANGE - 1 + ( $size / 128 );
384
385 } else {
386 $score = $block->getType();
387 }
388
389 if ( $score < $bestBlockScore ) {
390 $bestBlockScore = $score;
391 $bestRow = $row;
392 $bestBlockPreventsEdit = $block->prevents( 'edit' );
393 }
394 }
395
396 if ( $bestRow !== null ) {
397 $this->initFromRow( $bestRow );
398 $this->prevents( 'edit', $bestBlockPreventsEdit );
399 return true;
400 } else {
401 return false;
402 }
403 }
404
405 /**
406 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
407 * @param string $start Hexadecimal IP representation
408 * @param string $end Hexadecimal IP representation, or null to use $start = $end
409 * @return string
410 */
411 public static function getRangeCond( $start, $end = null ) {
412 if ( $end === null ) {
413 $end = $start;
414 }
415 # Per T16634, we want to include relevant active rangeblocks; for
416 # rangeblocks, we want to include larger ranges which enclose the given
417 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
418 # so we can improve performance by filtering on a LIKE clause
419 $chunk = self::getIpFragment( $start );
420 $dbr = wfGetDB( DB_REPLICA );
421 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
422
423 # Fairly hard to make a malicious SQL statement out of hex characters,
424 # but stranger things have happened...
425 $safeStart = $dbr->addQuotes( $start );
426 $safeEnd = $dbr->addQuotes( $end );
427
428 return $dbr->makeList(
429 [
430 "ipb_range_start $like",
431 "ipb_range_start <= $safeStart",
432 "ipb_range_end >= $safeEnd",
433 ],
434 LIST_AND
435 );
436 }
437
438 /**
439 * Get the component of an IP address which is certain to be the same between an IP
440 * address and a rangeblock containing that IP address.
441 * @param string $hex Hexadecimal IP representation
442 * @return string
443 */
444 protected static function getIpFragment( $hex ) {
445 global $wgBlockCIDRLimit;
446 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
447 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
448 } else {
449 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
450 }
451 }
452
453 /**
454 * Given a database row from the ipblocks table, initialize
455 * member variables
456 * @param stdClass $row A row from the ipblocks table
457 */
458 protected function initFromRow( $row ) {
459 $this->setTarget( $row->ipb_address );
460 $this->setBlocker( User::newFromAnyId(
461 $row->ipb_by, $row->ipb_by_text, isset( $row->ipb_by_actor ) ? $row->ipb_by_actor : null
462 ) );
463
464 $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
465 $this->mAuto = $row->ipb_auto;
466 $this->mHideName = $row->ipb_deleted;
467 $this->mId = (int)$row->ipb_id;
468 $this->mParentBlockId = $row->ipb_parent_block_id;
469
470 // I wish I didn't have to do this
471 $db = wfGetDB( DB_REPLICA );
472 $this->mExpiry = $db->decodeExpiry( $row->ipb_expiry );
473 $this->mReason = CommentStore::getStore()
474 // Legacy because $row may have come from self::selectFields()
475 ->getCommentLegacy( $db, 'ipb_reason', $row )->text;
476
477 $this->isHardblock( !$row->ipb_anon_only );
478 $this->isAutoblocking( $row->ipb_enable_autoblock );
479
480 $this->prevents( 'createaccount', $row->ipb_create_account );
481 $this->prevents( 'sendemail', $row->ipb_block_email );
482 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk );
483 }
484
485 /**
486 * Create a new Block object from a database row
487 * @param stdClass $row Row from the ipblocks table
488 * @return Block
489 */
490 public static function newFromRow( $row ) {
491 $block = new Block;
492 $block->initFromRow( $row );
493 return $block;
494 }
495
496 /**
497 * Delete the row from the IP blocks table.
498 *
499 * @throws MWException
500 * @return bool
501 */
502 public function delete() {
503 if ( wfReadOnly() ) {
504 return false;
505 }
506
507 if ( !$this->getId() ) {
508 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
509 }
510
511 $dbw = wfGetDB( DB_MASTER );
512 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__ );
513 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__ );
514
515 return $dbw->affectedRows() > 0;
516 }
517
518 /**
519 * Insert a block into the block table. Will fail if there is a conflicting
520 * block (same name and options) already in the database.
521 *
522 * @param IDatabase $dbw If you have one available
523 * @return bool|array False on failure, assoc array on success:
524 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
525 */
526 public function insert( $dbw = null ) {
527 global $wgBlockDisablesLogin;
528
529 if ( $this->getSystemBlockType() !== null ) {
530 throw new MWException( 'Cannot insert a system block into the database' );
531 }
532 if ( !$this->getBlocker() || $this->getBlocker()->getName() === '' ) {
533 throw new MWException( 'Cannot insert a block without a blocker set' );
534 }
535
536 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
537
538 if ( $dbw === null ) {
539 $dbw = wfGetDB( DB_MASTER );
540 }
541
542 self::purgeExpired();
543
544 $row = $this->getDatabaseArray( $dbw );
545
546 $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
547 $affected = $dbw->affectedRows();
548 $this->mId = $dbw->insertId();
549
550 # Don't collide with expired blocks.
551 # Do this after trying to insert to avoid locking.
552 if ( !$affected ) {
553 # T96428: The ipb_address index uses a prefix on a field, so
554 # use a standard SELECT + DELETE to avoid annoying gap locks.
555 $ids = $dbw->selectFieldValues( 'ipblocks',
556 'ipb_id',
557 [
558 'ipb_address' => $row['ipb_address'],
559 'ipb_user' => $row['ipb_user'],
560 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
561 ],
562 __METHOD__
563 );
564 if ( $ids ) {
565 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__ );
566 $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
567 $affected = $dbw->affectedRows();
568 $this->mId = $dbw->insertId();
569 }
570 }
571
572 if ( $affected ) {
573 $auto_ipd_ids = $this->doRetroactiveAutoblock();
574
575 if ( $wgBlockDisablesLogin && $this->target instanceof User ) {
576 // Change user login token to force them to be logged out.
577 $this->target->setToken();
578 $this->target->saveSettings();
579 }
580
581 return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
582 }
583
584 return false;
585 }
586
587 /**
588 * Update a block in the DB with new parameters.
589 * The ID field needs to be loaded first.
590 *
591 * @return bool|array False on failure, array on success:
592 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
593 */
594 public function update() {
595 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
596 $dbw = wfGetDB( DB_MASTER );
597
598 $dbw->startAtomic( __METHOD__ );
599
600 $dbw->update(
601 'ipblocks',
602 $this->getDatabaseArray( $dbw ),
603 [ 'ipb_id' => $this->getId() ],
604 __METHOD__
605 );
606
607 $affected = $dbw->affectedRows();
608
609 if ( $this->isAutoblocking() ) {
610 // update corresponding autoblock(s) (T50813)
611 $dbw->update(
612 'ipblocks',
613 $this->getAutoblockUpdateArray( $dbw ),
614 [ 'ipb_parent_block_id' => $this->getId() ],
615 __METHOD__
616 );
617 } else {
618 // autoblock no longer required, delete corresponding autoblock(s)
619 $dbw->delete(
620 'ipblocks',
621 [ 'ipb_parent_block_id' => $this->getId() ],
622 __METHOD__
623 );
624 }
625
626 $dbw->endAtomic( __METHOD__ );
627
628 if ( $affected ) {
629 $auto_ipd_ids = $this->doRetroactiveAutoblock();
630 return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
631 }
632
633 return false;
634 }
635
636 /**
637 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
638 * @param IDatabase $dbw
639 * @return array
640 */
641 protected function getDatabaseArray( IDatabase $dbw ) {
642 $expiry = $dbw->encodeExpiry( $this->mExpiry );
643
644 if ( $this->forcedTargetID ) {
645 $uid = $this->forcedTargetID;
646 } else {
647 $uid = $this->target instanceof User ? $this->target->getId() : 0;
648 }
649
650 $a = [
651 'ipb_address' => (string)$this->target,
652 'ipb_user' => $uid,
653 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
654 'ipb_auto' => $this->mAuto,
655 'ipb_anon_only' => !$this->isHardblock(),
656 'ipb_create_account' => $this->prevents( 'createaccount' ),
657 'ipb_enable_autoblock' => $this->isAutoblocking(),
658 'ipb_expiry' => $expiry,
659 'ipb_range_start' => $this->getRangeStart(),
660 'ipb_range_end' => $this->getRangeEnd(),
661 'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
662 'ipb_block_email' => $this->prevents( 'sendemail' ),
663 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
664 'ipb_parent_block_id' => $this->mParentBlockId
665 ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->mReason )
666 + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
667
668 return $a;
669 }
670
671 /**
672 * @param IDatabase $dbw
673 * @return array
674 */
675 protected function getAutoblockUpdateArray( IDatabase $dbw ) {
676 return [
677 'ipb_create_account' => $this->prevents( 'createaccount' ),
678 'ipb_deleted' => (int)$this->mHideName, // typecast required for SQLite
679 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
680 ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->mReason )
681 + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
682 }
683
684 /**
685 * Retroactively autoblocks the last IP used by the user (if it is a user)
686 * blocked by this Block.
687 *
688 * @return array Block IDs of retroactive autoblocks made
689 */
690 protected function doRetroactiveAutoblock() {
691 $blockIds = [];
692 # If autoblock is enabled, autoblock the LAST IP(s) used
693 if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
694 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
695
696 $continue = Hooks::run(
697 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
698
699 if ( $continue ) {
700 self::defaultRetroactiveAutoblock( $this, $blockIds );
701 }
702 }
703 return $blockIds;
704 }
705
706 /**
707 * Retroactively autoblocks the last IP used by the user (if it is a user)
708 * blocked by this Block. This will use the recentchanges table.
709 *
710 * @param Block $block
711 * @param array &$blockIds
712 */
713 protected static function defaultRetroactiveAutoblock( Block $block, array &$blockIds ) {
714 global $wgPutIPinRC;
715
716 // No IPs are in recentchanges table, so nothing to select
717 if ( !$wgPutIPinRC ) {
718 return;
719 }
720
721 $target = $block->getTarget();
722 if ( is_string( $target ) ) {
723 $target = User::newFromName( $target, false );
724 }
725
726 $dbr = wfGetDB( DB_REPLICA );
727 $rcQuery = ActorMigration::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
728
729 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
730
731 // Just the last IP used.
732 $options['LIMIT'] = 1;
733
734 $res = $dbr->select(
735 [ 'recentchanges' ] + $rcQuery['tables'],
736 [ 'rc_ip' ],
737 $rcQuery['conds'],
738 __METHOD__,
739 $options,
740 $rcQuery['joins']
741 );
742
743 if ( !$res->numRows() ) {
744 # No results, don't autoblock anything
745 wfDebug( "No IP found to retroactively autoblock\n" );
746 } else {
747 foreach ( $res as $row ) {
748 if ( $row->rc_ip ) {
749 $id = $block->doAutoblock( $row->rc_ip );
750 if ( $id ) {
751 $blockIds[] = $id;
752 }
753 }
754 }
755 }
756 }
757
758 /**
759 * Checks whether a given IP is on the autoblock whitelist.
760 * TODO: this probably belongs somewhere else, but not sure where...
761 *
762 * @param string $ip The IP to check
763 * @return bool
764 */
765 public static function isWhitelistedFromAutoblocks( $ip ) {
766 // Try to get the autoblock_whitelist from the cache, as it's faster
767 // than getting the msg raw and explode()'ing it.
768 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
769 $lines = $cache->getWithSetCallback(
770 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
771 $cache::TTL_DAY,
772 function ( $curValue, &$ttl, array &$setOpts ) {
773 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
774
775 return explode( "\n",
776 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
777 }
778 );
779
780 wfDebug( "Checking the autoblock whitelist..\n" );
781
782 foreach ( $lines as $line ) {
783 # List items only
784 if ( substr( $line, 0, 1 ) !== '*' ) {
785 continue;
786 }
787
788 $wlEntry = substr( $line, 1 );
789 $wlEntry = trim( $wlEntry );
790
791 wfDebug( "Checking $ip against $wlEntry..." );
792
793 # Is the IP in this range?
794 if ( IP::isInRange( $ip, $wlEntry ) ) {
795 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
796 return true;
797 } else {
798 wfDebug( " No match\n" );
799 }
800 }
801
802 return false;
803 }
804
805 /**
806 * Autoblocks the given IP, referring to this Block.
807 *
808 * @param string $autoblockIP The IP to autoblock.
809 * @return int|bool Block ID if an autoblock was inserted, false if not.
810 */
811 public function doAutoblock( $autoblockIP ) {
812 # If autoblocks are disabled, go away.
813 if ( !$this->isAutoblocking() ) {
814 return false;
815 }
816
817 # Don't autoblock for system blocks
818 if ( $this->getSystemBlockType() !== null ) {
819 throw new MWException( 'Cannot autoblock from a system block' );
820 }
821
822 # Check for presence on the autoblock whitelist.
823 if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
824 return false;
825 }
826
827 // Avoid PHP 7.1 warning of passing $this by reference
828 $block = $this;
829 # Allow hooks to cancel the autoblock.
830 if ( !Hooks::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
831 wfDebug( "Autoblock aborted by hook.\n" );
832 return false;
833 }
834
835 # It's okay to autoblock. Go ahead and insert/update the block...
836
837 # Do not add a *new* block if the IP is already blocked.
838 $ipblock = self::newFromTarget( $autoblockIP );
839 if ( $ipblock ) {
840 # Check if the block is an autoblock and would exceed the user block
841 # if renewed. If so, do nothing, otherwise prolong the block time...
842 if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
843 $this->mExpiry > self::getAutoblockExpiry( $ipblock->mTimestamp )
844 ) {
845 # Reset block timestamp to now and its expiry to
846 # $wgAutoblockExpiry in the future
847 $ipblock->updateTimestamp();
848 }
849 return false;
850 }
851
852 # Make a new block object with the desired properties.
853 $autoblock = new Block;
854 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
855 $autoblock->setTarget( $autoblockIP );
856 $autoblock->setBlocker( $this->getBlocker() );
857 $autoblock->mReason = wfMessage( 'autoblocker', $this->getTarget(), $this->mReason )
858 ->inContentLanguage()->plain();
859 $timestamp = wfTimestampNow();
860 $autoblock->mTimestamp = $timestamp;
861 $autoblock->mAuto = 1;
862 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
863 # Continue suppressing the name if needed
864 $autoblock->mHideName = $this->mHideName;
865 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
866 $autoblock->mParentBlockId = $this->mId;
867
868 if ( $this->mExpiry == 'infinity' ) {
869 # Original block was indefinite, start an autoblock now
870 $autoblock->mExpiry = self::getAutoblockExpiry( $timestamp );
871 } else {
872 # If the user is already blocked with an expiry date, we don't
873 # want to pile on top of that.
874 $autoblock->mExpiry = min( $this->mExpiry, self::getAutoblockExpiry( $timestamp ) );
875 }
876
877 # Insert the block...
878 $status = $autoblock->insert();
879 return $status
880 ? $status['id']
881 : false;
882 }
883
884 /**
885 * Check if a block has expired. Delete it if it is.
886 * @return bool
887 */
888 public function deleteIfExpired() {
889 if ( $this->isExpired() ) {
890 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
891 $this->delete();
892 $retVal = true;
893 } else {
894 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
895 $retVal = false;
896 }
897
898 return $retVal;
899 }
900
901 /**
902 * Has the block expired?
903 * @return bool
904 */
905 public function isExpired() {
906 $timestamp = wfTimestampNow();
907 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
908
909 if ( !$this->mExpiry ) {
910 return false;
911 } else {
912 return $timestamp > $this->mExpiry;
913 }
914 }
915
916 /**
917 * Is the block address valid (i.e. not a null string?)
918 * @return bool
919 */
920 public function isValid() {
921 return $this->getTarget() != null;
922 }
923
924 /**
925 * Update the timestamp on autoblocks.
926 */
927 public function updateTimestamp() {
928 if ( $this->mAuto ) {
929 $this->mTimestamp = wfTimestamp();
930 $this->mExpiry = self::getAutoblockExpiry( $this->mTimestamp );
931
932 $dbw = wfGetDB( DB_MASTER );
933 $dbw->update( 'ipblocks',
934 [ /* SET */
935 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
936 'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
937 ],
938 [ /* WHERE */
939 'ipb_id' => $this->getId(),
940 ],
941 __METHOD__
942 );
943 }
944 }
945
946 /**
947 * Get the IP address at the start of the range in Hex form
948 * @throws MWException
949 * @return string IP in Hex form
950 */
951 public function getRangeStart() {
952 switch ( $this->type ) {
953 case self::TYPE_USER:
954 return '';
955 case self::TYPE_IP:
956 return IP::toHex( $this->target );
957 case self::TYPE_RANGE:
958 list( $start, /*...*/ ) = IP::parseRange( $this->target );
959 return $start;
960 default:
961 throw new MWException( "Block with invalid type" );
962 }
963 }
964
965 /**
966 * Get the IP address at the end of the range in Hex form
967 * @throws MWException
968 * @return string IP in Hex form
969 */
970 public function getRangeEnd() {
971 switch ( $this->type ) {
972 case self::TYPE_USER:
973 return '';
974 case self::TYPE_IP:
975 return IP::toHex( $this->target );
976 case self::TYPE_RANGE:
977 list( /*...*/, $end ) = IP::parseRange( $this->target );
978 return $end;
979 default:
980 throw new MWException( "Block with invalid type" );
981 }
982 }
983
984 /**
985 * Get the user id of the blocking sysop
986 *
987 * @return int (0 for foreign users)
988 */
989 public function getBy() {
990 $blocker = $this->getBlocker();
991 return ( $blocker instanceof User )
992 ? $blocker->getId()
993 : 0;
994 }
995
996 /**
997 * Get the username of the blocking sysop
998 *
999 * @return string
1000 */
1001 public function getByName() {
1002 $blocker = $this->getBlocker();
1003 return ( $blocker instanceof User )
1004 ? $blocker->getName()
1005 : (string)$blocker; // username
1006 }
1007
1008 /**
1009 * Get the block ID
1010 * @return int
1011 */
1012 public function getId() {
1013 return $this->mId;
1014 }
1015
1016 /**
1017 * Get the system block type, if any
1018 * @since 1.29
1019 * @return string|null
1020 */
1021 public function getSystemBlockType() {
1022 return $this->systemBlockType;
1023 }
1024
1025 /**
1026 * Get/set a flag determining whether the master is used for reads
1027 *
1028 * @param bool|null $x
1029 * @return bool
1030 */
1031 public function fromMaster( $x = null ) {
1032 return wfSetVar( $this->mFromMaster, $x );
1033 }
1034
1035 /**
1036 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
1037 * @param bool|null $x
1038 * @return bool
1039 */
1040 public function isHardblock( $x = null ) {
1041 wfSetVar( $this->isHardblock, $x );
1042
1043 # You can't *not* hardblock a user
1044 return $this->getType() == self::TYPE_USER
1045 ? true
1046 : $this->isHardblock;
1047 }
1048
1049 /**
1050 * @param null|bool $x
1051 * @return bool
1052 */
1053 public function isAutoblocking( $x = null ) {
1054 wfSetVar( $this->isAutoblocking, $x );
1055
1056 # You can't put an autoblock on an IP or range as we don't have any history to
1057 # look over to get more IPs from
1058 return $this->getType() == self::TYPE_USER
1059 ? $this->isAutoblocking
1060 : false;
1061 }
1062
1063 /**
1064 * Get/set whether the Block prevents a given action
1065 *
1066 * @param string $action Action to check
1067 * @param bool|null $x Value for set, or null to just get value
1068 * @return bool|null Null for unrecognized rights.
1069 */
1070 public function prevents( $action, $x = null ) {
1071 global $wgBlockDisablesLogin;
1072 $res = null;
1073 switch ( $action ) {
1074 case 'edit':
1075 # For now... <evil laugh>
1076 $res = true;
1077 break;
1078 case 'createaccount':
1079 $res = wfSetVar( $this->mCreateAccount, $x );
1080 break;
1081 case 'sendemail':
1082 $res = wfSetVar( $this->mBlockEmail, $x );
1083 break;
1084 case 'editownusertalk':
1085 $res = wfSetVar( $this->mDisableUsertalk, $x );
1086 break;
1087 case 'read':
1088 $res = false;
1089 break;
1090 }
1091 if ( !$res && $wgBlockDisablesLogin ) {
1092 // If a block would disable login, then it should
1093 // prevent any action that all users cannot do
1094 $anon = new User;
1095 $res = $anon->isAllowed( $action ) ? $res : true;
1096 }
1097
1098 return $res;
1099 }
1100
1101 /**
1102 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1103 * @return string Text is escaped
1104 */
1105 public function getRedactedName() {
1106 if ( $this->mAuto ) {
1107 return Html::rawElement(
1108 'span',
1109 [ 'class' => 'mw-autoblockid' ],
1110 wfMessage( 'autoblockid', $this->mId )
1111 );
1112 } else {
1113 return htmlspecialchars( $this->getTarget() );
1114 }
1115 }
1116
1117 /**
1118 * Get a timestamp of the expiry for autoblocks
1119 *
1120 * @param string|int $timestamp
1121 * @return string
1122 */
1123 public static function getAutoblockExpiry( $timestamp ) {
1124 global $wgAutoblockExpiry;
1125
1126 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
1127 }
1128
1129 /**
1130 * Purge expired blocks from the ipblocks table
1131 */
1132 public static function purgeExpired() {
1133 if ( wfReadOnly() ) {
1134 return;
1135 }
1136
1137 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
1138 wfGetDB( DB_MASTER ),
1139 __METHOD__,
1140 function ( IDatabase $dbw, $fname ) {
1141 $ids = $dbw->selectFieldValues( 'ipblocks',
1142 'ipb_id',
1143 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1144 $fname
1145 );
1146 if ( $ids ) {
1147 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1148 }
1149 }
1150 ) );
1151 }
1152
1153 /**
1154 * Given a target and the target's type, get an existing Block object if possible.
1155 * @param string|User|int $specificTarget A block target, which may be one of several types:
1156 * * A user to block, in which case $target will be a User
1157 * * An IP to block, in which case $target will be a User generated by using
1158 * User::newFromName( $ip, false ) to turn off name validation
1159 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1160 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1161 * usernames
1162 * Calling this with a user, IP address or range will not select autoblocks, and will
1163 * only select a block where the targets match exactly (so looking for blocks on
1164 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1165 * @param string|User|int $vagueTarget As above, but we will search for *any* block which
1166 * affects that target (so for an IP address, get ranges containing that IP; and also
1167 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1168 * @param bool $fromMaster Whether to use the DB_MASTER database
1169 * @return Block|null (null if no relevant block could be found). The target and type
1170 * of the returned Block will refer to the actual block which was found, which might
1171 * not be the same as the target you gave if you used $vagueTarget!
1172 */
1173 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1174 list( $target, $type ) = self::parseTarget( $specificTarget );
1175 if ( $type == self::TYPE_ID || $type == self::TYPE_AUTO ) {
1176 return self::newFromID( $target );
1177
1178 } elseif ( $target === null && $vagueTarget == '' ) {
1179 # We're not going to find anything useful here
1180 # Be aware that the == '' check is explicit, since empty values will be
1181 # passed by some callers (T31116)
1182 return null;
1183
1184 } elseif ( in_array(
1185 $type,
1186 [ self::TYPE_USER, self::TYPE_IP, self::TYPE_RANGE, null ] )
1187 ) {
1188 $block = new Block();
1189 $block->fromMaster( $fromMaster );
1190
1191 if ( $type !== null ) {
1192 $block->setTarget( $target );
1193 }
1194
1195 if ( $block->newLoad( $vagueTarget ) ) {
1196 return $block;
1197 }
1198 }
1199 return null;
1200 }
1201
1202 /**
1203 * Get all blocks that match any IP from an array of IP addresses
1204 *
1205 * @param array $ipChain List of IPs (strings), usually retrieved from the
1206 * X-Forwarded-For header of the request
1207 * @param bool $isAnon Exclude anonymous-only blocks if false
1208 * @param bool $fromMaster Whether to query the master or replica DB
1209 * @return array Array of Blocks
1210 * @since 1.22
1211 */
1212 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1213 if ( !count( $ipChain ) ) {
1214 return [];
1215 }
1216
1217 $conds = [];
1218 $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1219 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1220 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1221 # necessarily trust the header given to us, make sure that we are only
1222 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1223 # Do not treat private IP spaces as special as it may be desirable for wikis
1224 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1225 if ( !IP::isValid( $ipaddr ) ) {
1226 continue;
1227 }
1228 # Don't check trusted IPs (includes local squids which will be in every request)
1229 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1230 continue;
1231 }
1232 # Check both the original IP (to check against single blocks), as well as build
1233 # the clause to check for rangeblocks for the given IP.
1234 $conds['ipb_address'][] = $ipaddr;
1235 $conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
1236 }
1237
1238 if ( !count( $conds ) ) {
1239 return [];
1240 }
1241
1242 if ( $fromMaster ) {
1243 $db = wfGetDB( DB_MASTER );
1244 } else {
1245 $db = wfGetDB( DB_REPLICA );
1246 }
1247 $conds = $db->makeList( $conds, LIST_OR );
1248 if ( !$isAnon ) {
1249 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1250 }
1251 $blockQuery = self::getQueryInfo();
1252 $rows = $db->select(
1253 $blockQuery['tables'],
1254 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1255 $conds,
1256 __METHOD__,
1257 [],
1258 $blockQuery['joins']
1259 );
1260
1261 $blocks = [];
1262 foreach ( $rows as $row ) {
1263 $block = self::newFromRow( $row );
1264 if ( !$block->isExpired() ) {
1265 $blocks[] = $block;
1266 }
1267 }
1268
1269 return $blocks;
1270 }
1271
1272 /**
1273 * From a list of multiple blocks, find the most exact and strongest Block.
1274 *
1275 * The logic for finding the "best" block is:
1276 * - Blocks that match the block's target IP are preferred over ones in a range
1277 * - Hardblocks are chosen over softblocks that prevent account creation
1278 * - Softblocks that prevent account creation are chosen over other softblocks
1279 * - Other softblocks are chosen over autoblocks
1280 * - If there are multiple exact or range blocks at the same level, the one chosen
1281 * is random
1282 * This should be used when $blocks where retrieved from the user's IP address
1283 * and $ipChain is populated from the same IP address information.
1284 *
1285 * @param array $blocks Array of Block objects
1286 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1287 * a block is to the server, and if a block matches exactly, or is in a range.
1288 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1289 * local-squid, ...)
1290 * @throws MWException
1291 * @return Block|null The "best" block from the list
1292 */
1293 public static function chooseBlock( array $blocks, array $ipChain ) {
1294 if ( !count( $blocks ) ) {
1295 return null;
1296 } elseif ( count( $blocks ) == 1 ) {
1297 return $blocks[0];
1298 }
1299
1300 // Sort hard blocks before soft ones and secondarily sort blocks
1301 // that disable account creation before those that don't.
1302 usort( $blocks, function ( Block $a, Block $b ) {
1303 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1304 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1305 return strcmp( $bWeight, $aWeight ); // highest weight first
1306 } );
1307
1308 $blocksListExact = [
1309 'hard' => false,
1310 'disable_create' => false,
1311 'other' => false,
1312 'auto' => false
1313 ];
1314 $blocksListRange = [
1315 'hard' => false,
1316 'disable_create' => false,
1317 'other' => false,
1318 'auto' => false
1319 ];
1320 $ipChain = array_reverse( $ipChain );
1321
1322 /** @var Block $block */
1323 foreach ( $blocks as $block ) {
1324 // Stop searching if we have already have a "better" block. This
1325 // is why the order of the blocks matters
1326 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1327 break;
1328 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1329 break;
1330 }
1331
1332 foreach ( $ipChain as $checkip ) {
1333 $checkipHex = IP::toHex( $checkip );
1334 if ( (string)$block->getTarget() === $checkip ) {
1335 if ( $block->isHardblock() ) {
1336 $blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
1337 } elseif ( $block->prevents( 'createaccount' ) ) {
1338 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
1339 } elseif ( $block->mAuto ) {
1340 $blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
1341 } else {
1342 $blocksListExact['other'] = $blocksListExact['other'] ?: $block;
1343 }
1344 // We found closest exact match in the ip list, so go to the next Block
1345 break;
1346 } elseif ( array_filter( $blocksListExact ) == []
1347 && $block->getRangeStart() <= $checkipHex
1348 && $block->getRangeEnd() >= $checkipHex
1349 ) {
1350 if ( $block->isHardblock() ) {
1351 $blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
1352 } elseif ( $block->prevents( 'createaccount' ) ) {
1353 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
1354 } elseif ( $block->mAuto ) {
1355 $blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
1356 } else {
1357 $blocksListRange['other'] = $blocksListRange['other'] ?: $block;
1358 }
1359 break;
1360 }
1361 }
1362 }
1363
1364 if ( array_filter( $blocksListExact ) == [] ) {
1365 $blocksList = &$blocksListRange;
1366 } else {
1367 $blocksList = &$blocksListExact;
1368 }
1369
1370 $chosenBlock = null;
1371 if ( $blocksList['hard'] ) {
1372 $chosenBlock = $blocksList['hard'];
1373 } elseif ( $blocksList['disable_create'] ) {
1374 $chosenBlock = $blocksList['disable_create'];
1375 } elseif ( $blocksList['other'] ) {
1376 $chosenBlock = $blocksList['other'];
1377 } elseif ( $blocksList['auto'] ) {
1378 $chosenBlock = $blocksList['auto'];
1379 } else {
1380 throw new MWException( "Proxy block found, but couldn't be classified." );
1381 }
1382
1383 return $chosenBlock;
1384 }
1385
1386 /**
1387 * From an existing Block, get the target and the type of target.
1388 * Note that, except for null, it is always safe to treat the target
1389 * as a string; for User objects this will return User::__toString()
1390 * which in turn gives User::getName().
1391 *
1392 * @param string|int|User|null $target
1393 * @return array [ User|String|null, Block::TYPE_ constant|null ]
1394 */
1395 public static function parseTarget( $target ) {
1396 # We may have been through this before
1397 if ( $target instanceof User ) {
1398 if ( IP::isValid( $target->getName() ) ) {
1399 return [ $target, self::TYPE_IP ];
1400 } else {
1401 return [ $target, self::TYPE_USER ];
1402 }
1403 } elseif ( $target === null ) {
1404 return [ null, null ];
1405 }
1406
1407 $target = trim( $target );
1408
1409 if ( IP::isValid( $target ) ) {
1410 # We can still create a User if it's an IP address, but we need to turn
1411 # off validation checking (which would exclude IP addresses)
1412 return [
1413 User::newFromName( IP::sanitizeIP( $target ), false ),
1414 self::TYPE_IP
1415 ];
1416
1417 } elseif ( IP::isValidRange( $target ) ) {
1418 # Can't create a User from an IP range
1419 return [ IP::sanitizeRange( $target ), self::TYPE_RANGE ];
1420 }
1421
1422 # Consider the possibility that this is not a username at all
1423 # but actually an old subpage (bug #29797)
1424 if ( strpos( $target, '/' ) !== false ) {
1425 # An old subpage, drill down to the user behind it
1426 $target = explode( '/', $target )[0];
1427 }
1428
1429 $userObj = User::newFromName( $target );
1430 if ( $userObj instanceof User ) {
1431 # Note that since numbers are valid usernames, a $target of "12345" will be
1432 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1433 # since hash characters are not valid in usernames or titles generally.
1434 return [ $userObj, self::TYPE_USER ];
1435
1436 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1437 # Autoblock reference in the form "#12345"
1438 return [ substr( $target, 1 ), self::TYPE_AUTO ];
1439
1440 } else {
1441 # WTF?
1442 return [ null, null ];
1443 }
1444 }
1445
1446 /**
1447 * Get the type of target for this particular block
1448 * @return int Block::TYPE_ constant, will never be TYPE_ID
1449 */
1450 public function getType() {
1451 return $this->mAuto
1452 ? self::TYPE_AUTO
1453 : $this->type;
1454 }
1455
1456 /**
1457 * Get the target and target type for this particular Block. Note that for autoblocks,
1458 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1459 * in this situation.
1460 * @return array [ User|String, Block::TYPE_ constant ]
1461 * @todo FIXME: This should be an integral part of the Block member variables
1462 */
1463 public function getTargetAndType() {
1464 return [ $this->getTarget(), $this->getType() ];
1465 }
1466
1467 /**
1468 * Get the target for this particular Block. Note that for autoblocks,
1469 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1470 * in this situation.
1471 * @return User|string
1472 */
1473 public function getTarget() {
1474 return $this->target;
1475 }
1476
1477 /**
1478 * @since 1.19
1479 *
1480 * @return mixed|string
1481 */
1482 public function getExpiry() {
1483 return $this->mExpiry;
1484 }
1485
1486 /**
1487 * Set the target for this block, and update $this->type accordingly
1488 * @param mixed $target
1489 */
1490 public function setTarget( $target ) {
1491 list( $this->target, $this->type ) = self::parseTarget( $target );
1492 }
1493
1494 /**
1495 * Get the user who implemented this block
1496 * @return User User object. May name a foreign user.
1497 */
1498 public function getBlocker() {
1499 return $this->blocker;
1500 }
1501
1502 /**
1503 * Set the user who implemented (or will implement) this block
1504 * @param User|string $user Local User object or username string
1505 */
1506 public function setBlocker( $user ) {
1507 if ( is_string( $user ) ) {
1508 $user = User::newFromName( $user, false );
1509 }
1510
1511 if ( $user->isAnon() && User::isUsableName( $user->getName() ) ) {
1512 throw new InvalidArgumentException(
1513 'Blocker must be a local user or a name that cannot be a local user'
1514 );
1515 }
1516
1517 $this->blocker = $user;
1518 }
1519
1520 /**
1521 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1522 * the same as the block's, to a maximum of 24 hours.
1523 *
1524 * @since 1.29
1525 *
1526 * @param WebResponse $response The response on which to set the cookie.
1527 */
1528 public function setCookie( WebResponse $response ) {
1529 // Calculate the default expiry time.
1530 $maxExpiryTime = wfTimestamp( TS_MW, wfTimestamp() + ( 24 * 60 * 60 ) );
1531
1532 // Use the Block's expiry time only if it's less than the default.
1533 $expiryTime = $this->getExpiry();
1534 if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
1535 $expiryTime = $maxExpiryTime;
1536 }
1537
1538 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1539 $expiryValue = DateTime::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1540 $cookieOptions = [ 'httpOnly' => false ];
1541 $cookieValue = $this->getCookieValue();
1542 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1543 }
1544
1545 /**
1546 * Unset the 'BlockID' cookie.
1547 *
1548 * @since 1.29
1549 *
1550 * @param WebResponse $response The response on which to unset the cookie.
1551 */
1552 public static function clearCookie( WebResponse $response ) {
1553 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1554 }
1555
1556 /**
1557 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1558 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1559 * be the block ID.
1560 *
1561 * @since 1.29
1562 *
1563 * @return string The block ID, probably concatenated with "!" and the HMAC.
1564 */
1565 public function getCookieValue() {
1566 $config = RequestContext::getMain()->getConfig();
1567 $id = $this->getId();
1568 $secretKey = $config->get( 'SecretKey' );
1569 if ( !$secretKey ) {
1570 // If there's no secret key, don't append a HMAC.
1571 return $id;
1572 }
1573 $hmac = MWCryptHash::hmac( $id, $secretKey, false );
1574 $cookieValue = $id . '!' . $hmac;
1575 return $cookieValue;
1576 }
1577
1578 /**
1579 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1580 * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
1581 *
1582 * @since 1.29
1583 *
1584 * @param string $cookieValue The string in which to find the ID.
1585 *
1586 * @return int|null The block ID, or null if the HMAC is present and invalid.
1587 */
1588 public static function getIdFromCookieValue( $cookieValue ) {
1589 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1590 $bangPos = strpos( $cookieValue, '!' );
1591 $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
1592 // Get the site-wide secret key.
1593 $config = RequestContext::getMain()->getConfig();
1594 $secretKey = $config->get( 'SecretKey' );
1595 if ( !$secretKey ) {
1596 // If there's no secret key, just use the ID as given.
1597 return $id;
1598 }
1599 $storedHmac = substr( $cookieValue, $bangPos + 1 );
1600 $calculatedHmac = MWCryptHash::hmac( $id, $secretKey, false );
1601 if ( $calculatedHmac === $storedHmac ) {
1602 return $id;
1603 } else {
1604 return null;
1605 }
1606 }
1607
1608 /**
1609 * Get the key and parameters for the corresponding error message.
1610 *
1611 * @since 1.22
1612 * @param IContextSource $context
1613 * @return array
1614 */
1615 public function getPermissionsError( IContextSource $context ) {
1616 $blocker = $this->getBlocker();
1617 if ( $blocker instanceof User ) { // local user
1618 $blockerUserpage = $blocker->getUserPage();
1619 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1620 } else { // foreign user
1621 $link = $blocker;
1622 }
1623
1624 $reason = $this->mReason;
1625 if ( $reason == '' ) {
1626 $reason = $context->msg( 'blockednoreason' )->text();
1627 }
1628
1629 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1630 * This could be a username, an IP range, or a single IP. */
1631 $intended = $this->getTarget();
1632
1633 $systemBlockType = $this->getSystemBlockType();
1634
1635 $lang = $context->getLanguage();
1636 return [
1637 $systemBlockType !== null
1638 ? 'systemblockedtext'
1639 : ( $this->mAuto ? 'autoblockedtext' : 'blockedtext' ),
1640 $link,
1641 $reason,
1642 $context->getRequest()->getIP(),
1643 $this->getByName(),
1644 $systemBlockType !== null ? $systemBlockType : $this->getId(),
1645 $lang->formatExpiry( $this->mExpiry ),
1646 (string)$intended,
1647 $lang->userTimeAndDate( $this->mTimestamp, $context->getUser() ),
1648 ];
1649 }
1650 }