3 * Blocks and bans object
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.
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.
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
26 /** @var bool|string */
32 /** @var bool|string */
38 public $mParentBlockId;
44 protected $mFromMaster;
47 protected $mBlockEmail;
50 protected $mDisableUsertalk;
53 protected $mCreateAccount;
55 /** @var User|string */
58 /** @var int Hack for foreign blocking (CentralAuth) */
59 protected $forcedTargetID;
61 /** @var int Block::TYPE_ constant. Can only be USER, IP or RANGE internally */
68 protected $isHardblock = true;
71 protected $isAutoblocking = true;
81 * @todo FIXME: Don't know what the best format to have for this constructor
82 * is, but fourteen optional parameters certainly isn't it.
83 * @param string $address
86 * @param string $reason
87 * @param mixed $timestamp
89 * @param string $expiry
90 * @param int $anonOnly
91 * @param int $createAccount
92 * @param int $enableAutoblock
93 * @param int $hideName
94 * @param int $blockEmail
95 * @param int $allowUsertalk
96 * @param string $byText
98 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
99 $timestamp = 0, $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
100 $hideName = 0, $blockEmail = 0, $allowUsertalk = 0, $byText = ''
102 if ( $timestamp === 0 ) {
103 $timestamp = wfTimestampNow();
106 if ( count( func_get_args() ) > 0 ) {
108 # wfDeprecated( __METHOD__ . " with arguments" );
111 $this->setTarget( $address );
112 if ( $this->target
instanceof User
&& $user ) {
113 $this->forcedTargetID
= $user; // needed for foreign users
115 if ( $by ) { // local user
116 $this->setBlocker( User
::newFromId( $by ) );
117 } else { // foreign user
118 $this->setBlocker( $byText );
120 $this->mReason
= $reason;
121 $this->mTimestamp
= wfTimestamp( TS_MW
, $timestamp );
122 $this->mAuto
= $auto;
123 $this->isHardblock( !$anonOnly );
124 $this->prevents( 'createaccount', $createAccount );
125 if ( $expiry == 'infinity' ||
$expiry == wfGetDB( DB_SLAVE
)->getInfinity() ) {
126 $this->mExpiry
= 'infinity';
128 $this->mExpiry
= wfTimestamp( TS_MW
, $expiry );
130 $this->isAutoblocking( $enableAutoblock );
131 $this->mHideName
= $hideName;
132 $this->prevents( 'sendemail', $blockEmail );
133 $this->prevents( 'editownusertalk', !$allowUsertalk );
135 $this->mFromMaster
= false;
139 * Load a blocked user from their block id.
141 * @param int $id Block id to search for
144 public static function newFromID( $id ) {
145 $dbr = wfGetDB( DB_SLAVE
);
146 $res = $dbr->selectRow(
148 self
::selectFields(),
149 array( 'ipb_id' => $id ),
153 return self
::newFromRow( $res );
160 * Return the list of ipblocks fields that should be selected to create
164 public static function selectFields() {
174 'ipb_create_account',
175 'ipb_enable_autoblock',
179 'ipb_allow_usertalk',
180 'ipb_parent_block_id',
185 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
186 * the blocking user or the block timestamp, only things which affect the blocked user
188 * @param Block $block
192 public function equals( Block
$block ) {
194 (string)$this->target
== (string)$block->target
195 && $this->type
== $block->type
196 && $this->mAuto
== $block->mAuto
197 && $this->isHardblock() == $block->isHardblock()
198 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
199 && $this->mExpiry
== $block->mExpiry
200 && $this->isAutoblocking() == $block->isAutoblocking()
201 && $this->mHideName
== $block->mHideName
202 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
203 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
204 && $this->mReason
== $block->mReason
209 * Load a block from the database which affects the already-set $this->target:
210 * 1) A block directly on the given user or IP
211 * 2) A rangeblock encompassing the given IP (smallest first)
212 * 3) An autoblock on the given IP
213 * @param User|string $vagueTarget Also search for blocks affecting this target. Doesn't
214 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
215 * @throws MWException
216 * @return bool Whether a relevant block was found
218 protected function newLoad( $vagueTarget = null ) {
219 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_SLAVE
);
221 if ( $this->type
!== null ) {
223 'ipb_address' => array( (string)$this->target
),
226 $conds = array( 'ipb_address' => array() );
229 # Be aware that the != '' check is explicit, since empty values will be
230 # passed by some callers (bug 29116)
231 if ( $vagueTarget != '' ) {
232 list( $target, $type ) = self
::parseTarget( $vagueTarget );
234 case self
::TYPE_USER
:
235 # Slightly weird, but who are we to argue?
236 $conds['ipb_address'][] = (string)$target;
240 $conds['ipb_address'][] = (string)$target;
241 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
242 $conds = $db->makeList( $conds, LIST_OR
);
245 case self
::TYPE_RANGE
:
246 list( $start, $end ) = IP
::parseRange( $target );
247 $conds['ipb_address'][] = (string)$target;
248 $conds[] = self
::getRangeCond( $start, $end );
249 $conds = $db->makeList( $conds, LIST_OR
);
253 throw new MWException( "Tried to load block with invalid type" );
257 $res = $db->select( 'ipblocks', self
::selectFields(), $conds, __METHOD__
);
259 # This result could contain a block on the user, a block on the IP, and a russian-doll
260 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
263 # Lower will be better
264 $bestBlockScore = 100;
266 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
267 $bestBlockPreventsEdit = null;
269 foreach ( $res as $row ) {
270 $block = self
::newFromRow( $row );
272 # Don't use expired blocks
273 if ( $block->deleteIfExpired() ) {
277 # Don't use anon only blocks on users
278 if ( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ) {
282 if ( $block->getType() == self
::TYPE_RANGE
) {
283 # This is the number of bits that are allowed to vary in the block, give
284 # or take some floating point errors
285 $end = wfBaseconvert( $block->getRangeEnd(), 16, 10 );
286 $start = wfBaseconvert( $block->getRangeStart(), 16, 10 );
287 $size = log( $end - $start +
1, 2 );
289 # This has the nice property that a /32 block is ranked equally with a
290 # single-IP block, which is exactly what it is...
291 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
294 $score = $block->getType();
297 if ( $score < $bestBlockScore ) {
298 $bestBlockScore = $score;
300 $bestBlockPreventsEdit = $block->prevents( 'edit' );
304 if ( $bestRow !== null ) {
305 $this->initFromRow( $bestRow );
306 $this->prevents( 'edit', $bestBlockPreventsEdit );
314 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
315 * @param string $start Hexadecimal IP representation
316 * @param string $end Hexadecimal IP representation, or null to use $start = $end
319 public static function getRangeCond( $start, $end = null ) {
320 if ( $end === null ) {
323 # Per bug 14634, we want to include relevant active rangeblocks; for
324 # rangeblocks, we want to include larger ranges which enclose the given
325 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
326 # so we can improve performance by filtering on a LIKE clause
327 $chunk = self
::getIpFragment( $start );
328 $dbr = wfGetDB( DB_SLAVE
);
329 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
331 # Fairly hard to make a malicious SQL statement out of hex characters,
332 # but stranger things have happened...
333 $safeStart = $dbr->addQuotes( $start );
334 $safeEnd = $dbr->addQuotes( $end );
336 return $dbr->makeList(
338 "ipb_range_start $like",
339 "ipb_range_start <= $safeStart",
340 "ipb_range_end >= $safeEnd",
347 * Get the component of an IP address which is certain to be the same between an IP
348 * address and a rangeblock containing that IP address.
349 * @param string $hex Hexadecimal IP representation
352 protected static function getIpFragment( $hex ) {
353 global $wgBlockCIDRLimit;
354 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
355 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
357 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
362 * Given a database row from the ipblocks table, initialize
364 * @param stdClass $row A row from the ipblocks table
366 protected function initFromRow( $row ) {
367 $this->setTarget( $row->ipb_address
);
368 if ( $row->ipb_by
) { // local user
369 $this->setBlocker( User
::newFromId( $row->ipb_by
) );
370 } else { // foreign user
371 $this->setBlocker( $row->ipb_by_text
);
374 $this->mReason
= $row->ipb_reason
;
375 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
376 $this->mAuto
= $row->ipb_auto
;
377 $this->mHideName
= $row->ipb_deleted
;
378 $this->mId
= $row->ipb_id
;
379 $this->mParentBlockId
= $row->ipb_parent_block_id
;
381 // I wish I didn't have to do this
382 $db = wfGetDB( DB_SLAVE
);
383 if ( $row->ipb_expiry
== $db->getInfinity() ) {
384 $this->mExpiry
= 'infinity';
386 $this->mExpiry
= wfTimestamp( TS_MW
, $row->ipb_expiry
);
389 $this->isHardblock( !$row->ipb_anon_only
);
390 $this->isAutoblocking( $row->ipb_enable_autoblock
);
392 $this->prevents( 'createaccount', $row->ipb_create_account
);
393 $this->prevents( 'sendemail', $row->ipb_block_email
);
394 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk
);
398 * Create a new Block object from a database row
399 * @param stdClass $row Row from the ipblocks table
402 public static function newFromRow( $row ) {
404 $block->initFromRow( $row );
409 * Delete the row from the IP blocks table.
411 * @throws MWException
414 public function delete() {
415 if ( wfReadOnly() ) {
419 if ( !$this->getId() ) {
420 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
423 $dbw = wfGetDB( DB_MASTER
);
424 $dbw->delete( 'ipblocks', array( 'ipb_parent_block_id' => $this->getId() ), __METHOD__
);
425 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->getId() ), __METHOD__
);
427 return $dbw->affectedRows() > 0;
431 * Insert a block into the block table. Will fail if there is a conflicting
432 * block (same name and options) already in the database.
434 * @param DatabaseBase $dbw If you have one available
435 * @return bool|array False on failure, assoc array on success:
436 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
438 public function insert( $dbw = null ) {
439 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
441 if ( $dbw === null ) {
442 $dbw = wfGetDB( DB_MASTER
);
445 # Periodic purge via commit hooks
446 if ( mt_rand( 0, 9 ) == 0 ) {
447 Block
::purgeExpired();
450 $row = $this->getDatabaseArray();
451 $row['ipb_id'] = $dbw->nextSequenceValue( "ipblocks_ipb_id_seq" );
453 $dbw->insert( 'ipblocks', $row, __METHOD__
, array( 'IGNORE' ) );
454 $affected = $dbw->affectedRows();
456 # Don't collide with expired blocks.
457 # Do this after trying to insert to avoid pointless gap locks.
459 $dbw->delete( 'ipblocks',
461 'ipb_address' => $row['ipb_address'],
462 'ipb_user' => $row['ipb_user'],
463 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
468 $dbw->insert( 'ipblocks', $row, __METHOD__
, array( 'IGNORE' ) );
469 $affected = $dbw->affectedRows();
472 $this->mId
= $dbw->insertId();
475 $auto_ipd_ids = $this->doRetroactiveAutoblock();
476 return array( 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids );
483 * Update a block in the DB with new parameters.
484 * The ID field needs to be loaded first.
486 * @return bool|array False on failure, array on success:
487 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
489 public function update() {
490 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
491 $dbw = wfGetDB( DB_MASTER
);
493 $dbw->startAtomic( __METHOD__
);
497 $this->getDatabaseArray( $dbw ),
498 array( 'ipb_id' => $this->getId() ),
502 $affected = $dbw->affectedRows();
504 if ( $this->isAutoblocking() ) {
505 // update corresponding autoblock(s) (bug 48813)
508 $this->getAutoblockUpdateArray(),
509 array( 'ipb_parent_block_id' => $this->getId() ),
513 // autoblock no longer required, delete corresponding autoblock(s)
516 array( 'ipb_parent_block_id' => $this->getId() ),
521 $dbw->endAtomic( __METHOD__
);
524 $auto_ipd_ids = $this->doRetroactiveAutoblock();
525 return array( 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids );
532 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
533 * @param DatabaseBase $db
536 protected function getDatabaseArray( $db = null ) {
538 $db = wfGetDB( DB_SLAVE
);
540 $expiry = $db->encodeExpiry( $this->mExpiry
);
542 if ( $this->forcedTargetID
) {
543 $uid = $this->forcedTargetID
;
545 $uid = $this->target
instanceof User ?
$this->target
->getID() : 0;
549 'ipb_address' => (string)$this->target
,
551 'ipb_by' => $this->getBy(),
552 'ipb_by_text' => $this->getByName(),
553 'ipb_reason' => $this->mReason
,
554 'ipb_timestamp' => $db->timestamp( $this->mTimestamp
),
555 'ipb_auto' => $this->mAuto
,
556 'ipb_anon_only' => !$this->isHardblock(),
557 'ipb_create_account' => $this->prevents( 'createaccount' ),
558 'ipb_enable_autoblock' => $this->isAutoblocking(),
559 'ipb_expiry' => $expiry,
560 'ipb_range_start' => $this->getRangeStart(),
561 'ipb_range_end' => $this->getRangeEnd(),
562 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
563 'ipb_block_email' => $this->prevents( 'sendemail' ),
564 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
565 'ipb_parent_block_id' => $this->mParentBlockId
574 protected function getAutoblockUpdateArray() {
576 'ipb_by' => $this->getBy(),
577 'ipb_by_text' => $this->getByName(),
578 'ipb_reason' => $this->mReason
,
579 'ipb_create_account' => $this->prevents( 'createaccount' ),
580 'ipb_deleted' => (int)$this->mHideName
, // typecast required for SQLite
581 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
586 * Retroactively autoblocks the last IP used by the user (if it is a user)
587 * blocked by this Block.
589 * @return array Block IDs of retroactive autoblocks made
591 protected function doRetroactiveAutoblock() {
593 # If autoblock is enabled, autoblock the LAST IP(s) used
594 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
595 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
597 $continue = Hooks
::run(
598 'PerformRetroactiveAutoblock', array( $this, &$blockIds ) );
601 self
::defaultRetroactiveAutoblock( $this, $blockIds );
608 * Retroactively autoblocks the last IP used by the user (if it is a user)
609 * blocked by this Block. This will use the recentchanges table.
611 * @param Block $block
612 * @param array &$blockIds
614 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
617 // No IPs are in recentchanges table, so nothing to select
618 if ( !$wgPutIPinRC ) {
622 $dbr = wfGetDB( DB_SLAVE
);
624 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
625 $conds = array( 'rc_user_text' => (string)$block->getTarget() );
627 // Just the last IP used.
628 $options['LIMIT'] = 1;
630 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
631 __METHOD__
, $options );
633 if ( !$res->numRows() ) {
634 # No results, don't autoblock anything
635 wfDebug( "No IP found to retroactively autoblock\n" );
637 foreach ( $res as $row ) {
639 $id = $block->doAutoblock( $row->rc_ip
);
649 * Checks whether a given IP is on the autoblock whitelist.
650 * TODO: this probably belongs somewhere else, but not sure where...
652 * @param string $ip The IP to check
655 public static function isWhitelistedFromAutoblocks( $ip ) {
658 // Try to get the autoblock_whitelist from the cache, as it's faster
659 // than getting the msg raw and explode()'ing it.
660 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
661 $lines = $wgMemc->get( $key );
663 $lines = explode( "\n", wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
664 $wgMemc->set( $key, $lines, 3600 * 24 );
667 wfDebug( "Checking the autoblock whitelist..\n" );
669 foreach ( $lines as $line ) {
671 if ( substr( $line, 0, 1 ) !== '*' ) {
675 $wlEntry = substr( $line, 1 );
676 $wlEntry = trim( $wlEntry );
678 wfDebug( "Checking $ip against $wlEntry..." );
680 # Is the IP in this range?
681 if ( IP
::isInRange( $ip, $wlEntry ) ) {
682 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
685 wfDebug( " No match\n" );
693 * Autoblocks the given IP, referring to this Block.
695 * @param string $autoblockIP The IP to autoblock.
696 * @return int|bool Block ID if an autoblock was inserted, false if not.
698 public function doAutoblock( $autoblockIP ) {
699 # If autoblocks are disabled, go away.
700 if ( !$this->isAutoblocking() ) {
704 # Check for presence on the autoblock whitelist.
705 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
709 # Allow hooks to cancel the autoblock.
710 if ( !Hooks
::run( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
711 wfDebug( "Autoblock aborted by hook.\n" );
715 # It's okay to autoblock. Go ahead and insert/update the block...
717 # Do not add a *new* block if the IP is already blocked.
718 $ipblock = Block
::newFromTarget( $autoblockIP );
720 # Check if the block is an autoblock and would exceed the user block
721 # if renewed. If so, do nothing, otherwise prolong the block time...
722 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
723 $this->mExpiry
> Block
::getAutoblockExpiry( $ipblock->mTimestamp
)
725 # Reset block timestamp to now and its expiry to
726 # $wgAutoblockExpiry in the future
727 $ipblock->updateTimestamp();
732 # Make a new block object with the desired properties.
733 $autoblock = new Block
;
734 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
735 $autoblock->setTarget( $autoblockIP );
736 $autoblock->setBlocker( $this->getBlocker() );
737 $autoblock->mReason
= wfMessage( 'autoblocker', $this->getTarget(), $this->mReason
)
738 ->inContentLanguage()->plain();
739 $timestamp = wfTimestampNow();
740 $autoblock->mTimestamp
= $timestamp;
741 $autoblock->mAuto
= 1;
742 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
743 # Continue suppressing the name if needed
744 $autoblock->mHideName
= $this->mHideName
;
745 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
746 $autoblock->mParentBlockId
= $this->mId
;
748 if ( $this->mExpiry
== 'infinity' ) {
749 # Original block was indefinite, start an autoblock now
750 $autoblock->mExpiry
= Block
::getAutoblockExpiry( $timestamp );
752 # If the user is already blocked with an expiry date, we don't
753 # want to pile on top of that.
754 $autoblock->mExpiry
= min( $this->mExpiry
, Block
::getAutoblockExpiry( $timestamp ) );
757 # Insert the block...
758 $status = $autoblock->insert();
765 * Check if a block has expired. Delete it if it is.
768 public function deleteIfExpired() {
770 if ( $this->isExpired() ) {
771 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
775 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
783 * Has the block expired?
786 public function isExpired() {
787 $timestamp = wfTimestampNow();
788 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
790 if ( !$this->mExpiry
) {
793 return $timestamp > $this->mExpiry
;
798 * Is the block address valid (i.e. not a null string?)
801 public function isValid() {
802 return $this->getTarget() != null;
806 * Update the timestamp on autoblocks.
808 public function updateTimestamp() {
809 if ( $this->mAuto
) {
810 $this->mTimestamp
= wfTimestamp();
811 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
813 $dbw = wfGetDB( DB_MASTER
);
814 $dbw->update( 'ipblocks',
816 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
817 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
820 'ipb_address' => (string)$this->getTarget()
828 * Get the IP address at the start of the range in Hex form
829 * @throws MWException
830 * @return string IP in Hex form
832 public function getRangeStart() {
833 switch ( $this->type
) {
834 case self
::TYPE_USER
:
837 return IP
::toHex( $this->target
);
838 case self
::TYPE_RANGE
:
839 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
842 throw new MWException( "Block with invalid type" );
847 * Get the IP address at the end of the range in Hex form
848 * @throws MWException
849 * @return string IP in Hex form
851 public function getRangeEnd() {
852 switch ( $this->type
) {
853 case self
::TYPE_USER
:
856 return IP
::toHex( $this->target
);
857 case self
::TYPE_RANGE
:
858 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
861 throw new MWException( "Block with invalid type" );
866 * Get the user id of the blocking sysop
868 * @return int (0 for foreign users)
870 public function getBy() {
871 $blocker = $this->getBlocker();
872 return ( $blocker instanceof User
)
878 * Get the username of the blocking sysop
882 public function getByName() {
883 $blocker = $this->getBlocker();
884 return ( $blocker instanceof User
)
885 ?
$blocker->getName()
886 : (string)$blocker; // username
893 public function getId() {
898 * Get/set a flag determining whether the master is used for reads
900 * @param bool|null $x
903 public function fromMaster( $x = null ) {
904 return wfSetVar( $this->mFromMaster
, $x );
908 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
909 * @param bool|null $x
912 public function isHardblock( $x = null ) {
913 wfSetVar( $this->isHardblock
, $x );
915 # You can't *not* hardblock a user
916 return $this->getType() == self
::TYPE_USER
918 : $this->isHardblock
;
922 * @param null|bool $x
925 public function isAutoblocking( $x = null ) {
926 wfSetVar( $this->isAutoblocking
, $x );
928 # You can't put an autoblock on an IP or range as we don't have any history to
929 # look over to get more IPs from
930 return $this->getType() == self
::TYPE_USER
931 ?
$this->isAutoblocking
936 * Get/set whether the Block prevents a given action
937 * @param string $action
938 * @param bool|null $x
941 public function prevents( $action, $x = null ) {
944 # For now... <evil laugh>
947 case 'createaccount':
948 return wfSetVar( $this->mCreateAccount
, $x );
951 return wfSetVar( $this->mBlockEmail
, $x );
953 case 'editownusertalk':
954 return wfSetVar( $this->mDisableUsertalk
, $x );
962 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
963 * @return string Text is escaped
965 public function getRedactedName() {
966 if ( $this->mAuto
) {
967 return Html
::rawElement(
969 array( 'class' => 'mw-autoblockid' ),
970 wfMessage( 'autoblockid', $this->mId
)
973 return htmlspecialchars( $this->getTarget() );
978 * Get a timestamp of the expiry for autoblocks
980 * @param string|int $timestamp
983 public static function getAutoblockExpiry( $timestamp ) {
984 global $wgAutoblockExpiry;
986 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
990 * Purge expired blocks from the ipblocks table
992 public static function purgeExpired() {
993 if ( wfReadOnly() ) {
997 $method = __METHOD__
;
998 $dbw = wfGetDB( DB_MASTER
);
999 $dbw->onTransactionIdle( function () use ( $dbw, $method ) {
1000 $dbw->delete( 'ipblocks',
1001 array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), $method );
1006 * Given a target and the target's type, get an existing Block object if possible.
1007 * @param string|User|int $specificTarget A block target, which may be one of several types:
1008 * * A user to block, in which case $target will be a User
1009 * * An IP to block, in which case $target will be a User generated by using
1010 * User::newFromName( $ip, false ) to turn off name validation
1011 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1012 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1014 * Calling this with a user, IP address or range will not select autoblocks, and will
1015 * only select a block where the targets match exactly (so looking for blocks on
1016 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1017 * @param string|User|int $vagueTarget As above, but we will search for *any* block which
1018 * affects that target (so for an IP address, get ranges containing that IP; and also
1019 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1020 * @param bool $fromMaster Whether to use the DB_MASTER database
1021 * @return Block|null (null if no relevant block could be found). The target and type
1022 * of the returned Block will refer to the actual block which was found, which might
1023 * not be the same as the target you gave if you used $vagueTarget!
1025 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1027 list( $target, $type ) = self
::parseTarget( $specificTarget );
1028 if ( $type == Block
::TYPE_ID ||
$type == Block
::TYPE_AUTO
) {
1029 return Block
::newFromID( $target );
1031 } elseif ( $target === null && $vagueTarget == '' ) {
1032 # We're not going to find anything useful here
1033 # Be aware that the == '' check is explicit, since empty values will be
1034 # passed by some callers (bug 29116)
1037 } elseif ( in_array(
1039 array( Block
::TYPE_USER
, Block
::TYPE_IP
, Block
::TYPE_RANGE
, null ) )
1041 $block = new Block();
1042 $block->fromMaster( $fromMaster );
1044 if ( $type !== null ) {
1045 $block->setTarget( $target );
1048 if ( $block->newLoad( $vagueTarget ) ) {
1056 * Get all blocks that match any IP from an array of IP addresses
1058 * @param array $ipChain List of IPs (strings), usually retrieved from the
1059 * X-Forwarded-For header of the request
1060 * @param bool $isAnon Exclude anonymous-only blocks if false
1061 * @param bool $fromMaster Whether to query the master or slave database
1062 * @return array Array of Blocks
1065 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1066 if ( !count( $ipChain ) ) {
1071 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1072 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1073 # necessarily trust the header given to us, make sure that we are only
1074 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1075 # Do not treat private IP spaces as special as it may be desirable for wikis
1076 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1077 if ( !IP
::isValid( $ipaddr ) ) {
1080 # Don't check trusted IPs (includes local squids which will be in every request)
1081 if ( IP
::isTrustedProxy( $ipaddr ) ) {
1084 # Check both the original IP (to check against single blocks), as well as build
1085 # the clause to check for rangeblocks for the given IP.
1086 $conds['ipb_address'][] = $ipaddr;
1087 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1090 if ( !count( $conds ) ) {
1094 if ( $fromMaster ) {
1095 $db = wfGetDB( DB_MASTER
);
1097 $db = wfGetDB( DB_SLAVE
);
1099 $conds = $db->makeList( $conds, LIST_OR
);
1101 $conds = array( $conds, 'ipb_anon_only' => 0 );
1103 $selectFields = array_merge(
1104 array( 'ipb_range_start', 'ipb_range_end' ),
1105 Block
::selectFields()
1107 $rows = $db->select( 'ipblocks',
1114 foreach ( $rows as $row ) {
1115 $block = self
::newFromRow( $row );
1116 if ( !$block->deleteIfExpired() ) {
1125 * From a list of multiple blocks, find the most exact and strongest Block.
1127 * The logic for finding the "best" block is:
1128 * - Blocks that match the block's target IP are preferred over ones in a range
1129 * - Hardblocks are chosen over softblocks that prevent account creation
1130 * - Softblocks that prevent account creation are chosen over other softblocks
1131 * - Other softblocks are chosen over autoblocks
1132 * - If there are multiple exact or range blocks at the same level, the one chosen
1134 * This should be used when $blocks where retrieved from the user's IP address
1135 * and $ipChain is populated from the same IP address information.
1137 * @param array $blocks Array of Block objects
1138 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1139 * a block is to the server, and if a block matches exactly, or is in a range.
1140 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1142 * @throws MWException
1143 * @return Block|null The "best" block from the list
1145 public static function chooseBlock( array $blocks, array $ipChain ) {
1146 if ( !count( $blocks ) ) {
1148 } elseif ( count( $blocks ) == 1 ) {
1152 // Sort hard blocks before soft ones and secondarily sort blocks
1153 // that disable account creation before those that don't.
1154 usort( $blocks, function ( Block
$a, Block
$b ) {
1155 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1156 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1157 return strcmp( $bWeight, $aWeight ); // highest weight first
1160 $blocksListExact = array(
1162 'disable_create' => false,
1166 $blocksListRange = array(
1168 'disable_create' => false,
1172 $ipChain = array_reverse( $ipChain );
1174 /** @var Block $block */
1175 foreach ( $blocks as $block ) {
1176 // Stop searching if we have already have a "better" block. This
1177 // is why the order of the blocks matters
1178 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1180 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1184 foreach ( $ipChain as $checkip ) {
1185 $checkipHex = IP
::toHex( $checkip );
1186 if ( (string)$block->getTarget() === $checkip ) {
1187 if ( $block->isHardblock() ) {
1188 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1189 } elseif ( $block->prevents( 'createaccount' ) ) {
1190 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1191 } elseif ( $block->mAuto
) {
1192 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1194 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1196 // We found closest exact match in the ip list, so go to the next Block
1198 } elseif ( array_filter( $blocksListExact ) == array()
1199 && $block->getRangeStart() <= $checkipHex
1200 && $block->getRangeEnd() >= $checkipHex
1202 if ( $block->isHardblock() ) {
1203 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1204 } elseif ( $block->prevents( 'createaccount' ) ) {
1205 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1206 } elseif ( $block->mAuto
) {
1207 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1209 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1216 if ( array_filter( $blocksListExact ) == array() ) {
1217 $blocksList = &$blocksListRange;
1219 $blocksList = &$blocksListExact;
1222 $chosenBlock = null;
1223 if ( $blocksList['hard'] ) {
1224 $chosenBlock = $blocksList['hard'];
1225 } elseif ( $blocksList['disable_create'] ) {
1226 $chosenBlock = $blocksList['disable_create'];
1227 } elseif ( $blocksList['other'] ) {
1228 $chosenBlock = $blocksList['other'];
1229 } elseif ( $blocksList['auto'] ) {
1230 $chosenBlock = $blocksList['auto'];
1232 throw new MWException( "Proxy block found, but couldn't be classified." );
1235 return $chosenBlock;
1239 * From an existing Block, get the target and the type of target.
1240 * Note that, except for null, it is always safe to treat the target
1241 * as a string; for User objects this will return User::__toString()
1242 * which in turn gives User::getName().
1244 * @param string|int|User|null $target
1245 * @return array( User|String|null, Block::TYPE_ constant|null )
1247 public static function parseTarget( $target ) {
1248 # We may have been through this before
1249 if ( $target instanceof User
) {
1250 if ( IP
::isValid( $target->getName() ) ) {
1251 return array( $target, self
::TYPE_IP
);
1253 return array( $target, self
::TYPE_USER
);
1255 } elseif ( $target === null ) {
1256 return array( null, null );
1259 $target = trim( $target );
1261 if ( IP
::isValid( $target ) ) {
1262 # We can still create a User if it's an IP address, but we need to turn
1263 # off validation checking (which would exclude IP addresses)
1265 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1269 } elseif ( IP
::isValidBlock( $target ) ) {
1270 # Can't create a User from an IP range
1271 return array( IP
::sanitizeRange( $target ), Block
::TYPE_RANGE
);
1274 # Consider the possibility that this is not a username at all
1275 # but actually an old subpage (bug #29797)
1276 if ( strpos( $target, '/' ) !== false ) {
1277 # An old subpage, drill down to the user behind it
1278 $parts = explode( '/', $target );
1279 $target = $parts[0];
1282 $userObj = User
::newFromName( $target );
1283 if ( $userObj instanceof User
) {
1284 # Note that since numbers are valid usernames, a $target of "12345" will be
1285 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1286 # since hash characters are not valid in usernames or titles generally.
1287 return array( $userObj, Block
::TYPE_USER
);
1289 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1290 # Autoblock reference in the form "#12345"
1291 return array( substr( $target, 1 ), Block
::TYPE_AUTO
);
1295 return array( null, null );
1300 * Get the type of target for this particular block
1301 * @return int Block::TYPE_ constant, will never be TYPE_ID
1303 public function getType() {
1310 * Get the target and target type for this particular Block. Note that for autoblocks,
1311 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1312 * in this situation.
1313 * @return array( User|String, Block::TYPE_ constant )
1314 * @todo FIXME: This should be an integral part of the Block member variables
1316 public function getTargetAndType() {
1317 return array( $this->getTarget(), $this->getType() );
1321 * Get the target for this particular Block. Note that for autoblocks,
1322 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1323 * in this situation.
1324 * @return User|string
1326 public function getTarget() {
1327 return $this->target
;
1333 * @return mixed|string
1335 public function getExpiry() {
1336 return $this->mExpiry
;
1340 * Set the target for this block, and update $this->type accordingly
1341 * @param mixed $target
1343 public function setTarget( $target ) {
1344 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1348 * Get the user who implemented this block
1349 * @return User|string Local User object or string for a foreign user
1351 public function getBlocker() {
1352 return $this->blocker
;
1356 * Set the user who implemented (or will implement) this block
1357 * @param User|string $user Local User object or username string for foreign users
1359 public function setBlocker( $user ) {
1360 $this->blocker
= $user;
1364 * Get the key and parameters for the corresponding error message.
1367 * @param IContextSource $context
1370 public function getPermissionsError( IContextSource
$context ) {
1371 $blocker = $this->getBlocker();
1372 if ( $blocker instanceof User
) { // local user
1373 $blockerUserpage = $blocker->getUserPage();
1374 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1375 } else { // foreign user
1379 $reason = $this->mReason
;
1380 if ( $reason == '' ) {
1381 $reason = $context->msg( 'blockednoreason' )->text();
1384 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1385 * This could be a username, an IP range, or a single IP. */
1386 $intended = $this->getTarget();
1388 $lang = $context->getLanguage();
1390 $this->mAuto ?
'autoblockedtext' : 'blockedtext',
1393 $context->getRequest()->getIP(),
1396 $lang->formatExpiry( $this->mExpiry
),
1398 $lang->userTimeAndDate( $this->mTimestamp
, $context->getUser() ),