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