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