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