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