Merge "Make Title::getFirstRevision() ignore the rev_timestamp index"
[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\IDatabase;
24 use MediaWiki\MediaWikiServices;
25
26 class Block {
27 /** @var string */
28 public $mReason;
29
30 /** @var string */
31 public $mTimestamp;
32
33 /** @var bool */
34 public $mAuto;
35
36 /** @var string */
37 public $mExpiry;
38
39 /** @var bool */
40 public $mHideName;
41
42 /** @var int */
43 public $mParentBlockId;
44
45 /** @var int */
46 protected $mId;
47
48 /** @var bool */
49 protected $mFromMaster;
50
51 /** @var bool */
52 protected $mBlockEmail;
53
54 /** @var bool */
55 protected $mDisableUsertalk;
56
57 /** @var bool */
58 protected $mCreateAccount;
59
60 /** @var User|string */
61 protected $target;
62
63 /** @var int Hack for foreign blocking (CentralAuth) */
64 protected $forcedTargetID;
65
66 /** @var int Block::TYPE_ constant. Can only be USER, IP or RANGE internally */
67 protected $type;
68
69 /** @var User */
70 protected $blocker;
71
72 /** @var bool */
73 protected $isHardblock;
74
75 /** @var bool */
76 protected $isAutoblocking;
77
78 /** @var string|null */
79 protected $systemBlockType;
80
81 # TYPE constants
82 const TYPE_USER = 1;
83 const TYPE_IP = 2;
84 const TYPE_RANGE = 3;
85 const TYPE_AUTO = 4;
86 const TYPE_ID = 5;
87
88 /**
89 * Create a new block with specified parameters on a user, IP or IP range.
90 *
91 * @param array $options Parameters of the block:
92 * address string|User Target user name, User object, IP address or IP range
93 * user int Override target user ID (for foreign users)
94 * by int User ID of the blocker
95 * reason string Reason of the block
96 * timestamp string The time at which the block comes into effect
97 * auto bool Is this an automatic block?
98 * expiry string Timestamp of expiration of the block or 'infinity'
99 * anonOnly bool Only disallow anonymous actions
100 * createAccount bool Disallow creation of new accounts
101 * enableAutoblock bool Enable automatic blocking
102 * hideName bool Hide the target user name
103 * blockEmail bool Disallow sending emails
104 * allowUsertalk bool Allow the target to edit its own talk page
105 * byText string Username of the blocker (for foreign users)
106 * systemBlock string Indicate that this block is automatically
107 * created by MediaWiki rather than being stored
108 * in the database. Value is a string to return
109 * from self::getSystemBlockType().
110 *
111 * @since 1.26 accepts $options array instead of individual parameters; order
112 * of parameters above reflects the original order
113 */
114 function __construct( $options = [] ) {
115 $defaults = [
116 'address' => '',
117 'user' => null,
118 'by' => null,
119 'reason' => '',
120 'timestamp' => '',
121 'auto' => false,
122 'expiry' => '',
123 'anonOnly' => false,
124 'createAccount' => false,
125 'enableAutoblock' => false,
126 'hideName' => false,
127 'blockEmail' => false,
128 'allowUsertalk' => false,
129 'byText' => '',
130 'systemBlock' => null,
131 ];
132
133 if ( func_num_args() > 1 || !is_array( $options ) ) {
134 $options = array_combine(
135 array_slice( array_keys( $defaults ), 0, func_num_args() ),
136 func_get_args()
137 );
138 wfDeprecated( __METHOD__ . ' with multiple arguments', '1.26' );
139 }
140
141 $options += $defaults;
142
143 $this->setTarget( $options['address'] );
144
145 if ( $this->target instanceof User && $options['user'] ) {
146 # Needed for foreign users
147 $this->forcedTargetID = $options['user'];
148 }
149
150 if ( $options['by'] ) {
151 # Local user
152 $this->setBlocker( User::newFromId( $options['by'] ) );
153 } else {
154 # Foreign user
155 $this->setBlocker( $options['byText'] );
156 }
157
158 $this->mReason = $options['reason'];
159 $this->mTimestamp = wfTimestamp( TS_MW, $options['timestamp'] );
160 $this->mExpiry = wfGetDB( DB_REPLICA )->decodeExpiry( $options['expiry'] );
161
162 # Boolean settings
163 $this->mAuto = (bool)$options['auto'];
164 $this->mHideName = (bool)$options['hideName'];
165 $this->isHardblock( !$options['anonOnly'] );
166 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
167
168 # Prevention measures
169 $this->prevents( 'sendemail', (bool)$options['blockEmail'] );
170 $this->prevents( 'editownusertalk', !$options['allowUsertalk'] );
171 $this->prevents( 'createaccount', (bool)$options['createAccount'] );
172
173 $this->mFromMaster = false;
174 $this->systemBlockType = $options['systemBlock'];
175 }
176
177 /**
178 * Load a blocked user from their block id.
179 *
180 * @param int $id Block id to search for
181 * @return Block|null
182 */
183 public static function newFromID( $id ) {
184 $dbr = wfGetDB( DB_REPLICA );
185 $res = $dbr->selectRow(
186 'ipblocks',
187 self::selectFields(),
188 [ 'ipb_id' => $id ],
189 __METHOD__
190 );
191 if ( $res ) {
192 return self::newFromRow( $res );
193 } else {
194 return null;
195 }
196 }
197
198 /**
199 * Return the list of ipblocks fields that should be selected to create
200 * a new block.
201 * @return array
202 */
203 public static function selectFields() {
204 return [
205 'ipb_id',
206 'ipb_address',
207 'ipb_by',
208 'ipb_by_text',
209 'ipb_reason',
210 'ipb_timestamp',
211 'ipb_auto',
212 'ipb_anon_only',
213 'ipb_create_account',
214 'ipb_enable_autoblock',
215 'ipb_expiry',
216 'ipb_deleted',
217 'ipb_block_email',
218 'ipb_allow_usertalk',
219 'ipb_parent_block_id',
220 ];
221 }
222
223 /**
224 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
225 * the blocking user or the block timestamp, only things which affect the blocked user
226 *
227 * @param Block $block
228 *
229 * @return bool
230 */
231 public function equals( Block $block ) {
232 return (
233 (string)$this->target == (string)$block->target
234 && $this->type == $block->type
235 && $this->mAuto == $block->mAuto
236 && $this->isHardblock() == $block->isHardblock()
237 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
238 && $this->mExpiry == $block->mExpiry
239 && $this->isAutoblocking() == $block->isAutoblocking()
240 && $this->mHideName == $block->mHideName
241 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
242 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
243 && $this->mReason == $block->mReason
244 );
245 }
246
247 /**
248 * Load a block from the database which affects the already-set $this->target:
249 * 1) A block directly on the given user or IP
250 * 2) A rangeblock encompassing the given IP (smallest first)
251 * 3) An autoblock on the given IP
252 * @param User|string $vagueTarget Also search for blocks affecting this target. Doesn't
253 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
254 * @throws MWException
255 * @return bool Whether a relevant block was found
256 */
257 protected function newLoad( $vagueTarget = null ) {
258 $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_REPLICA );
259
260 if ( $this->type !== null ) {
261 $conds = [
262 'ipb_address' => [ (string)$this->target ],
263 ];
264 } else {
265 $conds = [ 'ipb_address' => [] ];
266 }
267
268 # Be aware that the != '' check is explicit, since empty values will be
269 # passed by some callers (T31116)
270 if ( $vagueTarget != '' ) {
271 list( $target, $type ) = self::parseTarget( $vagueTarget );
272 switch ( $type ) {
273 case self::TYPE_USER:
274 # Slightly weird, but who are we to argue?
275 $conds['ipb_address'][] = (string)$target;
276 break;
277
278 case self::TYPE_IP:
279 $conds['ipb_address'][] = (string)$target;
280 $conds[] = self::getRangeCond( IP::toHex( $target ) );
281 $conds = $db->makeList( $conds, LIST_OR );
282 break;
283
284 case self::TYPE_RANGE:
285 list( $start, $end ) = IP::parseRange( $target );
286 $conds['ipb_address'][] = (string)$target;
287 $conds[] = self::getRangeCond( $start, $end );
288 $conds = $db->makeList( $conds, LIST_OR );
289 break;
290
291 default:
292 throw new MWException( "Tried to load block with invalid type" );
293 }
294 }
295
296 $res = $db->select( 'ipblocks', self::selectFields(), $conds, __METHOD__ );
297
298 # This result could contain a block on the user, a block on the IP, and a russian-doll
299 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
300 $bestRow = null;
301
302 # Lower will be better
303 $bestBlockScore = 100;
304
305 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
306 $bestBlockPreventsEdit = null;
307
308 foreach ( $res as $row ) {
309 $block = self::newFromRow( $row );
310
311 # Don't use expired blocks
312 if ( $block->isExpired() ) {
313 continue;
314 }
315
316 # Don't use anon only blocks on users
317 if ( $this->type == self::TYPE_USER && !$block->isHardblock() ) {
318 continue;
319 }
320
321 if ( $block->getType() == self::TYPE_RANGE ) {
322 # This is the number of bits that are allowed to vary in the block, give
323 # or take some floating point errors
324 $end = Wikimedia\base_convert( $block->getRangeEnd(), 16, 10 );
325 $start = Wikimedia\base_convert( $block->getRangeStart(), 16, 10 );
326 $size = log( $end - $start + 1, 2 );
327
328 # This has the nice property that a /32 block is ranked equally with a
329 # single-IP block, which is exactly what it is...
330 $score = self::TYPE_RANGE - 1 + ( $size / 128 );
331
332 } else {
333 $score = $block->getType();
334 }
335
336 if ( $score < $bestBlockScore ) {
337 $bestBlockScore = $score;
338 $bestRow = $row;
339 $bestBlockPreventsEdit = $block->prevents( 'edit' );
340 }
341 }
342
343 if ( $bestRow !== null ) {
344 $this->initFromRow( $bestRow );
345 $this->prevents( 'edit', $bestBlockPreventsEdit );
346 return true;
347 } else {
348 return false;
349 }
350 }
351
352 /**
353 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
354 * @param string $start Hexadecimal IP representation
355 * @param string $end Hexadecimal IP representation, or null to use $start = $end
356 * @return string
357 */
358 public static function getRangeCond( $start, $end = null ) {
359 if ( $end === null ) {
360 $end = $start;
361 }
362 # Per T16634, we want to include relevant active rangeblocks; for
363 # rangeblocks, we want to include larger ranges which enclose the given
364 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
365 # so we can improve performance by filtering on a LIKE clause
366 $chunk = self::getIpFragment( $start );
367 $dbr = wfGetDB( DB_REPLICA );
368 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
369
370 # Fairly hard to make a malicious SQL statement out of hex characters,
371 # but stranger things have happened...
372 $safeStart = $dbr->addQuotes( $start );
373 $safeEnd = $dbr->addQuotes( $end );
374
375 return $dbr->makeList(
376 [
377 "ipb_range_start $like",
378 "ipb_range_start <= $safeStart",
379 "ipb_range_end >= $safeEnd",
380 ],
381 LIST_AND
382 );
383 }
384
385 /**
386 * Get the component of an IP address which is certain to be the same between an IP
387 * address and a rangeblock containing that IP address.
388 * @param string $hex Hexadecimal IP representation
389 * @return string
390 */
391 protected static function getIpFragment( $hex ) {
392 global $wgBlockCIDRLimit;
393 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
394 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
395 } else {
396 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
397 }
398 }
399
400 /**
401 * Given a database row from the ipblocks table, initialize
402 * member variables
403 * @param stdClass $row A row from the ipblocks table
404 */
405 protected function initFromRow( $row ) {
406 $this->setTarget( $row->ipb_address );
407 if ( $row->ipb_by ) { // local user
408 $this->setBlocker( User::newFromId( $row->ipb_by ) );
409 } else { // foreign user
410 $this->setBlocker( $row->ipb_by_text );
411 }
412
413 $this->mReason = $row->ipb_reason;
414 $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
415 $this->mAuto = $row->ipb_auto;
416 $this->mHideName = $row->ipb_deleted;
417 $this->mId = (int)$row->ipb_id;
418 $this->mParentBlockId = $row->ipb_parent_block_id;
419
420 // I wish I didn't have to do this
421 $this->mExpiry = wfGetDB( DB_REPLICA )->decodeExpiry( $row->ipb_expiry );
422
423 $this->isHardblock( !$row->ipb_anon_only );
424 $this->isAutoblocking( $row->ipb_enable_autoblock );
425
426 $this->prevents( 'createaccount', $row->ipb_create_account );
427 $this->prevents( 'sendemail', $row->ipb_block_email );
428 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk );
429 }
430
431 /**
432 * Create a new Block object from a database row
433 * @param stdClass $row Row from the ipblocks table
434 * @return Block
435 */
436 public static function newFromRow( $row ) {
437 $block = new Block;
438 $block->initFromRow( $row );
439 return $block;
440 }
441
442 /**
443 * Delete the row from the IP blocks table.
444 *
445 * @throws MWException
446 * @return bool
447 */
448 public function delete() {
449 if ( wfReadOnly() ) {
450 return false;
451 }
452
453 if ( !$this->getId() ) {
454 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
455 }
456
457 $dbw = wfGetDB( DB_MASTER );
458 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__ );
459 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__ );
460
461 return $dbw->affectedRows() > 0;
462 }
463
464 /**
465 * Insert a block into the block table. Will fail if there is a conflicting
466 * block (same name and options) already in the database.
467 *
468 * @param IDatabase $dbw If you have one available
469 * @return bool|array False on failure, assoc array on success:
470 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
471 */
472 public function insert( $dbw = null ) {
473 global $wgBlockDisablesLogin;
474
475 if ( $this->getSystemBlockType() !== null ) {
476 throw new MWException( 'Cannot insert a system block into the database' );
477 }
478
479 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
480
481 if ( $dbw === null ) {
482 $dbw = wfGetDB( DB_MASTER );
483 }
484
485 # Periodic purge via commit hooks
486 if ( mt_rand( 0, 9 ) == 0 ) {
487 Block::purgeExpired();
488 }
489
490 $row = $this->getDatabaseArray();
491 $row['ipb_id'] = $dbw->nextSequenceValue( "ipblocks_ipb_id_seq" );
492
493 $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
494 $affected = $dbw->affectedRows();
495 $this->mId = $dbw->insertId();
496
497 # Don't collide with expired blocks.
498 # Do this after trying to insert to avoid locking.
499 if ( !$affected ) {
500 # T96428: The ipb_address index uses a prefix on a field, so
501 # use a standard SELECT + DELETE to avoid annoying gap locks.
502 $ids = $dbw->selectFieldValues( 'ipblocks',
503 'ipb_id',
504 [
505 'ipb_address' => $row['ipb_address'],
506 'ipb_user' => $row['ipb_user'],
507 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
508 ],
509 __METHOD__
510 );
511 if ( $ids ) {
512 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__ );
513 $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
514 $affected = $dbw->affectedRows();
515 $this->mId = $dbw->insertId();
516 }
517 }
518
519 if ( $affected ) {
520 $auto_ipd_ids = $this->doRetroactiveAutoblock();
521
522 if ( $wgBlockDisablesLogin && $this->target instanceof User ) {
523 // Change user login token to force them to be logged out.
524 $this->target->setToken();
525 $this->target->saveSettings();
526 }
527
528 return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
529 }
530
531 return false;
532 }
533
534 /**
535 * Update a block in the DB with new parameters.
536 * The ID field needs to be loaded first.
537 *
538 * @return bool|array False on failure, array on success:
539 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
540 */
541 public function update() {
542 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
543 $dbw = wfGetDB( DB_MASTER );
544
545 $dbw->startAtomic( __METHOD__ );
546
547 $dbw->update(
548 'ipblocks',
549 $this->getDatabaseArray( $dbw ),
550 [ 'ipb_id' => $this->getId() ],
551 __METHOD__
552 );
553
554 $affected = $dbw->affectedRows();
555
556 if ( $this->isAutoblocking() ) {
557 // update corresponding autoblock(s) (T50813)
558 $dbw->update(
559 'ipblocks',
560 $this->getAutoblockUpdateArray(),
561 [ 'ipb_parent_block_id' => $this->getId() ],
562 __METHOD__
563 );
564 } else {
565 // autoblock no longer required, delete corresponding autoblock(s)
566 $dbw->delete(
567 'ipblocks',
568 [ 'ipb_parent_block_id' => $this->getId() ],
569 __METHOD__
570 );
571 }
572
573 $dbw->endAtomic( __METHOD__ );
574
575 if ( $affected ) {
576 $auto_ipd_ids = $this->doRetroactiveAutoblock();
577 return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
578 }
579
580 return false;
581 }
582
583 /**
584 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
585 * @param IDatabase $db
586 * @return array
587 */
588 protected function getDatabaseArray( $db = null ) {
589 if ( !$db ) {
590 $db = wfGetDB( DB_REPLICA );
591 }
592 $expiry = $db->encodeExpiry( $this->mExpiry );
593
594 if ( $this->forcedTargetID ) {
595 $uid = $this->forcedTargetID;
596 } else {
597 $uid = $this->target instanceof User ? $this->target->getId() : 0;
598 }
599
600 $a = [
601 'ipb_address' => (string)$this->target,
602 'ipb_user' => $uid,
603 'ipb_by' => $this->getBy(),
604 'ipb_by_text' => $this->getByName(),
605 'ipb_reason' => $this->mReason,
606 'ipb_timestamp' => $db->timestamp( $this->mTimestamp ),
607 'ipb_auto' => $this->mAuto,
608 'ipb_anon_only' => !$this->isHardblock(),
609 'ipb_create_account' => $this->prevents( 'createaccount' ),
610 'ipb_enable_autoblock' => $this->isAutoblocking(),
611 'ipb_expiry' => $expiry,
612 'ipb_range_start' => $this->getRangeStart(),
613 'ipb_range_end' => $this->getRangeEnd(),
614 'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
615 'ipb_block_email' => $this->prevents( 'sendemail' ),
616 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
617 'ipb_parent_block_id' => $this->mParentBlockId
618 ];
619
620 return $a;
621 }
622
623 /**
624 * @return array
625 */
626 protected function getAutoblockUpdateArray() {
627 return [
628 'ipb_by' => $this->getBy(),
629 'ipb_by_text' => $this->getByName(),
630 'ipb_reason' => $this->mReason,
631 'ipb_create_account' => $this->prevents( 'createaccount' ),
632 'ipb_deleted' => (int)$this->mHideName, // typecast required for SQLite
633 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
634 ];
635 }
636
637 /**
638 * Retroactively autoblocks the last IP used by the user (if it is a user)
639 * blocked by this Block.
640 *
641 * @return array Block IDs of retroactive autoblocks made
642 */
643 protected function doRetroactiveAutoblock() {
644 $blockIds = [];
645 # If autoblock is enabled, autoblock the LAST IP(s) used
646 if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
647 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
648
649 $continue = Hooks::run(
650 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
651
652 if ( $continue ) {
653 self::defaultRetroactiveAutoblock( $this, $blockIds );
654 }
655 }
656 return $blockIds;
657 }
658
659 /**
660 * Retroactively autoblocks the last IP used by the user (if it is a user)
661 * blocked by this Block. This will use the recentchanges table.
662 *
663 * @param Block $block
664 * @param array &$blockIds
665 */
666 protected static function defaultRetroactiveAutoblock( Block $block, array &$blockIds ) {
667 global $wgPutIPinRC;
668
669 // No IPs are in recentchanges table, so nothing to select
670 if ( !$wgPutIPinRC ) {
671 return;
672 }
673
674 $dbr = wfGetDB( DB_REPLICA );
675
676 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
677 $conds = [ 'rc_user_text' => (string)$block->getTarget() ];
678
679 // Just the last IP used.
680 $options['LIMIT'] = 1;
681
682 $res = $dbr->select( 'recentchanges', [ 'rc_ip' ], $conds,
683 __METHOD__, $options );
684
685 if ( !$res->numRows() ) {
686 # No results, don't autoblock anything
687 wfDebug( "No IP found to retroactively autoblock\n" );
688 } else {
689 foreach ( $res as $row ) {
690 if ( $row->rc_ip ) {
691 $id = $block->doAutoblock( $row->rc_ip );
692 if ( $id ) {
693 $blockIds[] = $id;
694 }
695 }
696 }
697 }
698 }
699
700 /**
701 * Checks whether a given IP is on the autoblock whitelist.
702 * TODO: this probably belongs somewhere else, but not sure where...
703 *
704 * @param string $ip The IP to check
705 * @return bool
706 */
707 public static function isWhitelistedFromAutoblocks( $ip ) {
708 // Try to get the autoblock_whitelist from the cache, as it's faster
709 // than getting the msg raw and explode()'ing it.
710 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
711 $lines = $cache->getWithSetCallback(
712 wfMemcKey( 'ipb', 'autoblock', 'whitelist' ),
713 $cache::TTL_DAY,
714 function ( $curValue, &$ttl, array &$setOpts ) {
715 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
716
717 return explode( "\n",
718 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
719 }
720 );
721
722 wfDebug( "Checking the autoblock whitelist..\n" );
723
724 foreach ( $lines as $line ) {
725 # List items only
726 if ( substr( $line, 0, 1 ) !== '*' ) {
727 continue;
728 }
729
730 $wlEntry = substr( $line, 1 );
731 $wlEntry = trim( $wlEntry );
732
733 wfDebug( "Checking $ip against $wlEntry..." );
734
735 # Is the IP in this range?
736 if ( IP::isInRange( $ip, $wlEntry ) ) {
737 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
738 return true;
739 } else {
740 wfDebug( " No match\n" );
741 }
742 }
743
744 return false;
745 }
746
747 /**
748 * Autoblocks the given IP, referring to this Block.
749 *
750 * @param string $autoblockIP The IP to autoblock.
751 * @return int|bool Block ID if an autoblock was inserted, false if not.
752 */
753 public function doAutoblock( $autoblockIP ) {
754 # If autoblocks are disabled, go away.
755 if ( !$this->isAutoblocking() ) {
756 return false;
757 }
758
759 # Don't autoblock for system blocks
760 if ( $this->getSystemBlockType() !== null ) {
761 throw new MWException( 'Cannot autoblock from a system block' );
762 }
763
764 # Check for presence on the autoblock whitelist.
765 if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
766 return false;
767 }
768
769 // Avoid PHP 7.1 warning of passing $this by reference
770 $block = $this;
771 # Allow hooks to cancel the autoblock.
772 if ( !Hooks::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
773 wfDebug( "Autoblock aborted by hook.\n" );
774 return false;
775 }
776
777 # It's okay to autoblock. Go ahead and insert/update the block...
778
779 # Do not add a *new* block if the IP is already blocked.
780 $ipblock = Block::newFromTarget( $autoblockIP );
781 if ( $ipblock ) {
782 # Check if the block is an autoblock and would exceed the user block
783 # if renewed. If so, do nothing, otherwise prolong the block time...
784 if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
785 $this->mExpiry > Block::getAutoblockExpiry( $ipblock->mTimestamp )
786 ) {
787 # Reset block timestamp to now and its expiry to
788 # $wgAutoblockExpiry in the future
789 $ipblock->updateTimestamp();
790 }
791 return false;
792 }
793
794 # Make a new block object with the desired properties.
795 $autoblock = new Block;
796 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
797 $autoblock->setTarget( $autoblockIP );
798 $autoblock->setBlocker( $this->getBlocker() );
799 $autoblock->mReason = wfMessage( 'autoblocker', $this->getTarget(), $this->mReason )
800 ->inContentLanguage()->plain();
801 $timestamp = wfTimestampNow();
802 $autoblock->mTimestamp = $timestamp;
803 $autoblock->mAuto = 1;
804 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
805 # Continue suppressing the name if needed
806 $autoblock->mHideName = $this->mHideName;
807 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
808 $autoblock->mParentBlockId = $this->mId;
809
810 if ( $this->mExpiry == 'infinity' ) {
811 # Original block was indefinite, start an autoblock now
812 $autoblock->mExpiry = Block::getAutoblockExpiry( $timestamp );
813 } else {
814 # If the user is already blocked with an expiry date, we don't
815 # want to pile on top of that.
816 $autoblock->mExpiry = min( $this->mExpiry, Block::getAutoblockExpiry( $timestamp ) );
817 }
818
819 # Insert the block...
820 $status = $autoblock->insert();
821 return $status
822 ? $status['id']
823 : false;
824 }
825
826 /**
827 * Check if a block has expired. Delete it if it is.
828 * @return bool
829 */
830 public function deleteIfExpired() {
831
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 = Block::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 * @return string|null
962 */
963 public function getSystemBlockType() {
964 return $this->systemBlockType;
965 }
966
967 /**
968 * Get/set a flag determining whether the master is used for reads
969 *
970 * @param bool|null $x
971 * @return bool
972 */
973 public function fromMaster( $x = null ) {
974 return wfSetVar( $this->mFromMaster, $x );
975 }
976
977 /**
978 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
979 * @param bool|null $x
980 * @return bool
981 */
982 public function isHardblock( $x = null ) {
983 wfSetVar( $this->isHardblock, $x );
984
985 # You can't *not* hardblock a user
986 return $this->getType() == self::TYPE_USER
987 ? true
988 : $this->isHardblock;
989 }
990
991 /**
992 * @param null|bool $x
993 * @return bool
994 */
995 public function isAutoblocking( $x = null ) {
996 wfSetVar( $this->isAutoblocking, $x );
997
998 # You can't put an autoblock on an IP or range as we don't have any history to
999 # look over to get more IPs from
1000 return $this->getType() == self::TYPE_USER
1001 ? $this->isAutoblocking
1002 : false;
1003 }
1004
1005 /**
1006 * Get/set whether the Block prevents a given action
1007 *
1008 * @param string $action Action to check
1009 * @param bool|null $x Value for set, or null to just get value
1010 * @return bool|null Null for unrecognized rights.
1011 */
1012 public function prevents( $action, $x = null ) {
1013 global $wgBlockDisablesLogin;
1014 $res = null;
1015 switch ( $action ) {
1016 case 'edit':
1017 # For now... <evil laugh>
1018 $res = true;
1019 break;
1020 case 'createaccount':
1021 $res = wfSetVar( $this->mCreateAccount, $x );
1022 break;
1023 case 'sendemail':
1024 $res = wfSetVar( $this->mBlockEmail, $x );
1025 break;
1026 case 'editownusertalk':
1027 $res = wfSetVar( $this->mDisableUsertalk, $x );
1028 break;
1029 case 'read':
1030 $res = false;
1031 break;
1032 }
1033 if ( !$res && $wgBlockDisablesLogin ) {
1034 // If a block would disable login, then it should
1035 // prevent any action that all users cannot do
1036 $anon = new User;
1037 $res = $anon->isAllowed( $action ) ? $res : true;
1038 }
1039
1040 return $res;
1041 }
1042
1043 /**
1044 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1045 * @return string Text is escaped
1046 */
1047 public function getRedactedName() {
1048 if ( $this->mAuto ) {
1049 return Html::rawElement(
1050 'span',
1051 [ 'class' => 'mw-autoblockid' ],
1052 wfMessage( 'autoblockid', $this->mId )
1053 );
1054 } else {
1055 return htmlspecialchars( $this->getTarget() );
1056 }
1057 }
1058
1059 /**
1060 * Get a timestamp of the expiry for autoblocks
1061 *
1062 * @param string|int $timestamp
1063 * @return string
1064 */
1065 public static function getAutoblockExpiry( $timestamp ) {
1066 global $wgAutoblockExpiry;
1067
1068 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
1069 }
1070
1071 /**
1072 * Purge expired blocks from the ipblocks table
1073 */
1074 public static function purgeExpired() {
1075 if ( wfReadOnly() ) {
1076 return;
1077 }
1078
1079 DeferredUpdates::addUpdate( new AtomicSectionUpdate(
1080 wfGetDB( DB_MASTER ),
1081 __METHOD__,
1082 function ( IDatabase $dbw, $fname ) {
1083 $dbw->delete(
1084 'ipblocks',
1085 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1086 $fname
1087 );
1088 }
1089 ) );
1090 }
1091
1092 /**
1093 * Given a target and the target's type, get an existing Block object if possible.
1094 * @param string|User|int $specificTarget A block target, which may be one of several types:
1095 * * A user to block, in which case $target will be a User
1096 * * An IP to block, in which case $target will be a User generated by using
1097 * User::newFromName( $ip, false ) to turn off name validation
1098 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1099 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1100 * usernames
1101 * Calling this with a user, IP address or range will not select autoblocks, and will
1102 * only select a block where the targets match exactly (so looking for blocks on
1103 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1104 * @param string|User|int $vagueTarget As above, but we will search for *any* block which
1105 * affects that target (so for an IP address, get ranges containing that IP; and also
1106 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1107 * @param bool $fromMaster Whether to use the DB_MASTER database
1108 * @return Block|null (null if no relevant block could be found). The target and type
1109 * of the returned Block will refer to the actual block which was found, which might
1110 * not be the same as the target you gave if you used $vagueTarget!
1111 */
1112 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1113
1114 list( $target, $type ) = self::parseTarget( $specificTarget );
1115 if ( $type == Block::TYPE_ID || $type == Block::TYPE_AUTO ) {
1116 return Block::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 [ Block::TYPE_USER, Block::TYPE_IP, Block::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 Block::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 Block::TYPE_IP
1355 ];
1356
1357 } elseif ( IP::isValidBlock( $target ) ) {
1358 # Can't create a User from an IP range
1359 return [ IP::sanitizeRange( $target ), Block::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, Block::TYPE_USER ];
1375
1376 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1377 # Autoblock reference in the form "#12345"
1378 return [ substr( $target, 1 ), Block::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 * @param WebResponse $response The response on which to set the cookie.
1455 */
1456 public function setCookie( WebResponse $response ) {
1457 // Calculate the default expiry time.
1458 $maxExpiryTime = wfTimestamp( TS_MW, wfTimestamp() + ( 24 * 60 * 60 ) );
1459
1460 // Use the Block's expiry time only if it's less than the default.
1461 $expiryTime = $this->getExpiry();
1462 if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
1463 $expiryTime = $maxExpiryTime;
1464 }
1465
1466 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1467 $expiryValue = DateTime::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1468 $cookieOptions = [ 'httpOnly' => false ];
1469 $cookieValue = $this->getCookieValue();
1470 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1471 }
1472
1473 /**
1474 * Unset the 'BlockID' cookie.
1475 *
1476 * @param WebResponse $response The response on which to unset the cookie.
1477 */
1478 public static function clearCookie( WebResponse $response ) {
1479 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1480 }
1481
1482 /**
1483 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1484 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1485 * be the block ID.
1486 * @return string The block ID, probably concatenated with "!" and the HMAC.
1487 */
1488 public function getCookieValue() {
1489 $config = RequestContext::getMain()->getConfig();
1490 $id = $this->getId();
1491 $secretKey = $config->get( 'SecretKey' );
1492 if ( !$secretKey ) {
1493 // If there's no secret key, don't append a HMAC.
1494 return $id;
1495 }
1496 $hmac = MWCryptHash::hmac( $id, $secretKey, false );
1497 $cookieValue = $id . '!' . $hmac;
1498 return $cookieValue;
1499 }
1500
1501 /**
1502 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1503 * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
1504 * @param string $cookieValue The string in which to find the ID.
1505 * @return integer|null The block ID, or null if the HMAC is present and invalid.
1506 */
1507 public static function getIdFromCookieValue( $cookieValue ) {
1508 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1509 $bangPos = strpos( $cookieValue, '!' );
1510 $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
1511 // Get the site-wide secret key.
1512 $config = RequestContext::getMain()->getConfig();
1513 $secretKey = $config->get( 'SecretKey' );
1514 if ( !$secretKey ) {
1515 // If there's no secret key, just use the ID as given.
1516 return $id;
1517 }
1518 $storedHmac = substr( $cookieValue, $bangPos + 1 );
1519 $calculatedHmac = MWCryptHash::hmac( $id, $secretKey, false );
1520 if ( $calculatedHmac === $storedHmac ) {
1521 return $id;
1522 } else {
1523 return null;
1524 }
1525 }
1526
1527 /**
1528 * Get the key and parameters for the corresponding error message.
1529 *
1530 * @since 1.22
1531 * @param IContextSource $context
1532 * @return array
1533 */
1534 public function getPermissionsError( IContextSource $context ) {
1535 $blocker = $this->getBlocker();
1536 if ( $blocker instanceof User ) { // local user
1537 $blockerUserpage = $blocker->getUserPage();
1538 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1539 } else { // foreign user
1540 $link = $blocker;
1541 }
1542
1543 $reason = $this->mReason;
1544 if ( $reason == '' ) {
1545 $reason = $context->msg( 'blockednoreason' )->text();
1546 }
1547
1548 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1549 * This could be a username, an IP range, or a single IP. */
1550 $intended = $this->getTarget();
1551
1552 $systemBlockType = $this->getSystemBlockType();
1553
1554 $lang = $context->getLanguage();
1555 return [
1556 $systemBlockType !== null
1557 ? 'systemblockedtext'
1558 : ( $this->mAuto ? 'autoblockedtext' : 'blockedtext' ),
1559 $link,
1560 $reason,
1561 $context->getRequest()->getIP(),
1562 $this->getByName(),
1563 $systemBlockType !== null ? $systemBlockType : $this->getId(),
1564 $lang->formatExpiry( $this->mExpiry ),
1565 (string)$intended,
1566 $lang->userTimeAndDate( $this->mTimestamp, $context->getUser() ),
1567 ];
1568 }
1569 }