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