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
23 /* public*/ var $mReason, $mTimestamp, $mAuto, $mExpiry, $mHideName;
37 // @var Integer Hack for foreign blocking (CentralAuth)
38 protected $forcedTargetID;
40 /// @var Block::TYPE_ constant. Can only be USER, IP or RANGE internally
47 protected $isHardblock = true;
50 protected $isAutoblocking = true;
61 * @todo FIXME: Don't know what the best format to have for this constructor is, but fourteen
62 * optional parameters certainly isn't it.
64 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
65 $timestamp = 0, $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
66 $hideName = 0, $blockEmail = 0, $allowUsertalk = 0, $byText = '' )
68 if ( $timestamp === 0 ) {
69 $timestamp = wfTimestampNow();
72 if ( count( func_get_args() ) > 0 ) {
74 # wfDeprecated( __METHOD__ . " with arguments" );
77 $this->setTarget( $address );
78 if ( $this->target
instanceof User
&& $user ) {
79 $this->forcedTargetID
= $user; // needed for foreign users
81 if ( $by ) { // local user
82 $this->setBlocker( User
::newFromID( $by ) );
83 } else { // foreign user
84 $this->setBlocker( $byText );
86 $this->mReason
= $reason;
87 $this->mTimestamp
= wfTimestamp( TS_MW
, $timestamp );
89 $this->isHardblock( !$anonOnly );
90 $this->prevents( 'createaccount', $createAccount );
91 if ( $expiry == 'infinity' ||
$expiry == wfGetDB( DB_SLAVE
)->getInfinity() ) {
92 $this->mExpiry
= 'infinity';
94 $this->mExpiry
= wfTimestamp( TS_MW
, $expiry );
96 $this->isAutoblocking( $enableAutoblock );
97 $this->mHideName
= $hideName;
98 $this->prevents( 'sendemail', $blockEmail );
99 $this->prevents( 'editownusertalk', !$allowUsertalk );
101 $this->mFromMaster
= false;
105 * Load a block from the database, using either the IP address or
106 * user ID. Tries the user ID first, and if that doesn't work, tries
109 * @param string $address IP address of user/anon
110 * @param $user Integer: user id of user
111 * @return Block Object
112 * @deprecated since 1.18
114 public static function newFromDB( $address, $user = 0 ) {
115 wfDeprecated( __METHOD__
, '1.18' );
116 return self
::newFromTarget( User
::whoIs( $user ), $address );
120 * Load a blocked user from their block id.
122 * @param $id Integer: Block id to search for
123 * @return Block object or null
125 public static function newFromID( $id ) {
126 $dbr = wfGetDB( DB_SLAVE
);
127 $res = $dbr->selectRow(
129 self
::selectFields(),
130 array( 'ipb_id' => $id ),
134 return self
::newFromRow( $res );
141 * Return the list of ipblocks fields that should be selected to create
145 public static function selectFields() {
155 'ipb_create_account',
156 'ipb_enable_autoblock',
160 'ipb_allow_usertalk',
161 'ipb_parent_block_id',
166 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
167 * the blocking user or the block timestamp, only things which affect the blocked user
169 * @param $block Block
173 public function equals( Block
$block ) {
175 (string)$this->target
== (string)$block->target
176 && $this->type
== $block->type
177 && $this->mAuto
== $block->mAuto
178 && $this->isHardblock() == $block->isHardblock()
179 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
180 && $this->mExpiry
== $block->mExpiry
181 && $this->isAutoblocking() == $block->isAutoblocking()
182 && $this->mHideName
== $block->mHideName
183 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
184 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
185 && $this->mReason
== $block->mReason
190 * Clear all member variables in the current object. Does not clear
191 * the block from the DB.
192 * @deprecated since 1.18
194 public function clear() {
195 wfDeprecated( __METHOD__
, '1.18' );
200 * Get a block from the DB, with either the given address or the given username
202 * @param string $address The IP address of the user, or blank to skip IP blocks
203 * @param int $user The user ID, or zero for anonymous users
204 * @return Boolean: the user is blocked from editing
205 * @deprecated since 1.18
207 public function load( $address = '', $user = 0 ) {
208 wfDeprecated( __METHOD__
, '1.18' );
210 $username = User
::whoIs( $user );
211 $block = self
::newFromTarget( $username, $address );
213 $block = self
::newFromTarget( null, $address );
216 if ( $block instanceof Block
) {
217 # This is mildly evil, but hey, it's B/C :D
218 foreach ( $block as $variable => $value ) {
219 $this->$variable = $value;
228 * Load a block from the database which affects the already-set $this->target:
229 * 1) A block directly on the given user or IP
230 * 2) A rangeblock encompassing the given IP (smallest first)
231 * 3) An autoblock on the given IP
232 * @param $vagueTarget User|String also search for blocks affecting this target. Doesn't
233 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
234 * @throws MWException
235 * @return Bool whether a relevant block was found
237 protected function newLoad( $vagueTarget = null ) {
238 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_SLAVE
);
240 if ( $this->type
!== null ) {
242 'ipb_address' => array( (string)$this->target
),
245 $conds = array( 'ipb_address' => array() );
248 # Be aware that the != '' check is explicit, since empty values will be
249 # passed by some callers (bug 29116)
250 if ( $vagueTarget != '' ) {
251 list( $target, $type ) = self
::parseTarget( $vagueTarget );
253 case self
::TYPE_USER
:
254 # Slightly weird, but who are we to argue?
255 $conds['ipb_address'][] = (string)$target;
259 $conds['ipb_address'][] = (string)$target;
260 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
261 $conds = $db->makeList( $conds, LIST_OR
);
264 case self
::TYPE_RANGE
:
265 list( $start, $end ) = IP
::parseRange( $target );
266 $conds['ipb_address'][] = (string)$target;
267 $conds[] = self
::getRangeCond( $start, $end );
268 $conds = $db->makeList( $conds, LIST_OR
);
272 throw new MWException( "Tried to load block with invalid type" );
276 $res = $db->select( 'ipblocks', self
::selectFields(), $conds, __METHOD__
);
278 # This result could contain a block on the user, a block on the IP, and a russian-doll
279 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
282 # Lower will be better
283 $bestBlockScore = 100;
285 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
286 $bestBlockPreventsEdit = null;
288 foreach ( $res as $row ) {
289 $block = self
::newFromRow( $row );
291 # Don't use expired blocks
292 if ( $block->deleteIfExpired() ) {
296 # Don't use anon only blocks on users
297 if ( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ) {
301 if ( $block->getType() == self
::TYPE_RANGE
) {
302 # This is the number of bits that are allowed to vary in the block, give
303 # or take some floating point errors
304 $end = wfBaseconvert( $block->getRangeEnd(), 16, 10 );
305 $start = wfBaseconvert( $block->getRangeStart(), 16, 10 );
306 $size = log( $end - $start +
1, 2 );
308 # This has the nice property that a /32 block is ranked equally with a
309 # single-IP block, which is exactly what it is...
310 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
313 $score = $block->getType();
316 if ( $score < $bestBlockScore ) {
317 $bestBlockScore = $score;
319 $bestBlockPreventsEdit = $block->prevents( 'edit' );
323 if ( $bestRow !== null ) {
324 $this->initFromRow( $bestRow );
325 $this->prevents( 'edit', $bestBlockPreventsEdit );
333 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
334 * @param string $start Hexadecimal IP representation
335 * @param string $end Hexadecimal IP representation, or null to use $start = $end
338 public static function getRangeCond( $start, $end = null ) {
339 if ( $end === null ) {
342 # Per bug 14634, we want to include relevant active rangeblocks; for
343 # rangeblocks, we want to include larger ranges which enclose the given
344 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
345 # so we can improve performance by filtering on a LIKE clause
346 $chunk = self
::getIpFragment( $start );
347 $dbr = wfGetDB( DB_SLAVE
);
348 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
350 # Fairly hard to make a malicious SQL statement out of hex characters,
351 # but stranger things have happened...
352 $safeStart = $dbr->addQuotes( $start );
353 $safeEnd = $dbr->addQuotes( $end );
355 return $dbr->makeList(
357 "ipb_range_start $like",
358 "ipb_range_start <= $safeStart",
359 "ipb_range_end >= $safeEnd",
366 * Get the component of an IP address which is certain to be the same between an IP
367 * address and a rangeblock containing that IP address.
368 * @param $hex String Hexadecimal IP representation
371 protected static function getIpFragment( $hex ) {
372 global $wgBlockCIDRLimit;
373 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
374 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
376 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
381 * Given a database row from the ipblocks table, initialize
383 * @param $row ResultWrapper: a row from the ipblocks table
385 protected function initFromRow( $row ) {
386 $this->setTarget( $row->ipb_address
);
387 if ( $row->ipb_by
) { // local user
388 $this->setBlocker( User
::newFromID( $row->ipb_by
) );
389 } else { // foreign user
390 $this->setBlocker( $row->ipb_by_text
);
393 $this->mReason
= $row->ipb_reason
;
394 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
395 $this->mAuto
= $row->ipb_auto
;
396 $this->mHideName
= $row->ipb_deleted
;
397 $this->mId
= $row->ipb_id
;
398 $this->mParentBlockId
= $row->ipb_parent_block_id
;
400 // I wish I didn't have to do this
401 $db = wfGetDB( DB_SLAVE
);
402 if ( $row->ipb_expiry
== $db->getInfinity() ) {
403 $this->mExpiry
= 'infinity';
405 $this->mExpiry
= wfTimestamp( TS_MW
, $row->ipb_expiry
);
408 $this->isHardblock( !$row->ipb_anon_only
);
409 $this->isAutoblocking( $row->ipb_enable_autoblock
);
411 $this->prevents( 'createaccount', $row->ipb_create_account
);
412 $this->prevents( 'sendemail', $row->ipb_block_email
);
413 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk
);
417 * Create a new Block object from a database row
418 * @param $row ResultWrapper row from the ipblocks table
421 public static function newFromRow( $row ) {
423 $block->initFromRow( $row );
428 * Delete the row from the IP blocks table.
430 * @throws MWException
433 public function delete() {
434 if ( wfReadOnly() ) {
438 if ( !$this->getId() ) {
439 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
442 $dbw = wfGetDB( DB_MASTER
);
443 $dbw->delete( 'ipblocks', array( 'ipb_parent_block_id' => $this->getId() ), __METHOD__
);
444 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->getId() ), __METHOD__
);
446 return $dbw->affectedRows() > 0;
450 * Insert a block into the block table. Will fail if there is a conflicting
451 * block (same name and options) already in the database.
453 * @param $dbw DatabaseBase if you have one available
454 * @return mixed: false on failure, assoc array on success:
455 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
457 public function insert( $dbw = null ) {
458 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
460 if ( $dbw === null ) {
461 $dbw = wfGetDB( DB_MASTER
);
464 # Don't collide with expired blocks
465 Block
::purgeExpired();
467 $row = $this->getDatabaseArray();
468 $row['ipb_id'] = $dbw->nextSequenceValue( "ipblocks_ipb_id_seq" );
476 $affected = $dbw->affectedRows();
477 $this->mId
= $dbw->insertId();
480 $auto_ipd_ids = $this->doRetroactiveAutoblock();
481 return array( 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids );
488 * Update a block in the DB with new parameters.
489 * The ID field needs to be loaded first.
491 * @return Int number of affected rows, which should probably be 1 or something has
494 public function update() {
495 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
496 $dbw = wfGetDB( DB_MASTER
);
500 $this->getDatabaseArray( $dbw ),
501 array( 'ipb_id' => $this->getId() ),
505 return $dbw->affectedRows();
509 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
510 * @param $db DatabaseBase
513 protected function getDatabaseArray( $db = null ) {
515 $db = wfGetDB( DB_SLAVE
);
517 $expiry = $db->encodeExpiry( $this->mExpiry
);
519 if ( $this->forcedTargetID
) {
520 $uid = $this->forcedTargetID
;
522 $uid = $this->target
instanceof User ?
$this->target
->getID() : 0;
526 'ipb_address' => (string)$this->target
,
528 'ipb_by' => $this->getBy(),
529 'ipb_by_text' => $this->getByName(),
530 'ipb_reason' => $this->mReason
,
531 'ipb_timestamp' => $db->timestamp( $this->mTimestamp
),
532 'ipb_auto' => $this->mAuto
,
533 'ipb_anon_only' => !$this->isHardblock(),
534 'ipb_create_account' => $this->prevents( 'createaccount' ),
535 'ipb_enable_autoblock' => $this->isAutoblocking(),
536 'ipb_expiry' => $expiry,
537 'ipb_range_start' => $this->getRangeStart(),
538 'ipb_range_end' => $this->getRangeEnd(),
539 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
540 'ipb_block_email' => $this->prevents( 'sendemail' ),
541 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
542 'ipb_parent_block_id' => $this->mParentBlockId
549 * Retroactively autoblocks the last IP used by the user (if it is a user)
550 * blocked by this Block.
552 * @return Array: block IDs of retroactive autoblocks made
554 protected function doRetroactiveAutoblock() {
556 # If autoblock is enabled, autoblock the LAST IP(s) used
557 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
558 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
560 $continue = wfRunHooks(
561 'PerformRetroactiveAutoblock', array( $this, &$blockIds ) );
564 self
::defaultRetroactiveAutoblock( $this, $blockIds );
571 * Retroactively autoblocks the last IP used by the user (if it is a user)
572 * blocked by this Block. This will use the recentchanges table.
574 * @param Block $block
575 * @param array &$blockIds
576 * @return Array: block IDs of retroactive autoblocks made
578 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
581 // No IPs are in recentchanges table, so nothing to select
582 if ( !$wgPutIPinRC ) {
586 $dbr = wfGetDB( DB_SLAVE
);
588 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
589 $conds = array( 'rc_user_text' => (string)$block->getTarget() );
591 // Just the last IP used.
592 $options['LIMIT'] = 1;
594 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
595 __METHOD__
, $options );
597 if ( !$res->numRows() ) {
598 # No results, don't autoblock anything
599 wfDebug( "No IP found to retroactively autoblock\n" );
601 foreach ( $res as $row ) {
603 $id = $block->doAutoblock( $row->rc_ip
);
613 * Checks whether a given IP is on the autoblock whitelist.
614 * TODO: this probably belongs somewhere else, but not sure where...
616 * @param string $ip The IP to check
619 public static function isWhitelistedFromAutoblocks( $ip ) {
622 // Try to get the autoblock_whitelist from the cache, as it's faster
623 // than getting the msg raw and explode()'ing it.
624 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
625 $lines = $wgMemc->get( $key );
627 $lines = explode( "\n", wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
628 $wgMemc->set( $key, $lines, 3600 * 24 );
631 wfDebug( "Checking the autoblock whitelist..\n" );
633 foreach ( $lines as $line ) {
635 if ( substr( $line, 0, 1 ) !== '*' ) {
639 $wlEntry = substr( $line, 1 );
640 $wlEntry = trim( $wlEntry );
642 wfDebug( "Checking $ip against $wlEntry..." );
644 # Is the IP in this range?
645 if ( IP
::isInRange( $ip, $wlEntry ) ) {
646 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
649 wfDebug( " No match\n" );
657 * Autoblocks the given IP, referring to this Block.
659 * @param string $autoblockIP the IP to autoblock.
660 * @return mixed: block ID if an autoblock was inserted, false if not.
662 public function doAutoblock( $autoblockIP ) {
663 # If autoblocks are disabled, go away.
664 if ( !$this->isAutoblocking() ) {
668 # Check for presence on the autoblock whitelist.
669 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
673 # Allow hooks to cancel the autoblock.
674 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
675 wfDebug( "Autoblock aborted by hook.\n" );
679 # It's okay to autoblock. Go ahead and insert/update the block...
681 # Do not add a *new* block if the IP is already blocked.
682 $ipblock = Block
::newFromTarget( $autoblockIP );
684 # Check if the block is an autoblock and would exceed the user block
685 # if renewed. If so, do nothing, otherwise prolong the block time...
686 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
687 $this->mExpiry
> Block
::getAutoblockExpiry( $ipblock->mTimestamp
)
689 # Reset block timestamp to now and its expiry to
690 # $wgAutoblockExpiry in the future
691 $ipblock->updateTimestamp();
696 # Make a new block object with the desired properties.
697 $autoblock = new Block
;
698 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
699 $autoblock->setTarget( $autoblockIP );
700 $autoblock->setBlocker( $this->getBlocker() );
701 $autoblock->mReason
= wfMessage( 'autoblocker', $this->getTarget(), $this->mReason
)->inContentLanguage()->plain();
702 $timestamp = wfTimestampNow();
703 $autoblock->mTimestamp
= $timestamp;
704 $autoblock->mAuto
= 1;
705 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
706 # Continue suppressing the name if needed
707 $autoblock->mHideName
= $this->mHideName
;
708 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
709 $autoblock->mParentBlockId
= $this->mId
;
711 if ( $this->mExpiry
== 'infinity' ) {
712 # Original block was indefinite, start an autoblock now
713 $autoblock->mExpiry
= Block
::getAutoblockExpiry( $timestamp );
715 # If the user is already blocked with an expiry date, we don't
716 # want to pile on top of that.
717 $autoblock->mExpiry
= min( $this->mExpiry
, Block
::getAutoblockExpiry( $timestamp ) );
720 # Insert the block...
721 $status = $autoblock->insert();
728 * Check if a block has expired. Delete it if it is.
731 public function deleteIfExpired() {
732 wfProfileIn( __METHOD__
);
734 if ( $this->isExpired() ) {
735 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
739 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
743 wfProfileOut( __METHOD__
);
748 * Has the block expired?
751 public function isExpired() {
752 $timestamp = wfTimestampNow();
753 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
755 if ( !$this->mExpiry
) {
758 return $timestamp > $this->mExpiry
;
763 * Is the block address valid (i.e. not a null string?)
766 public function isValid() {
767 return $this->getTarget() != null;
771 * Update the timestamp on autoblocks.
773 public function updateTimestamp() {
774 if ( $this->mAuto
) {
775 $this->mTimestamp
= wfTimestamp();
776 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
778 $dbw = wfGetDB( DB_MASTER
);
779 $dbw->update( 'ipblocks',
781 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
782 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
785 'ipb_address' => (string)$this->getTarget()
793 * Get the IP address at the start of the range in Hex form
794 * @throws MWException
795 * @return String IP in Hex form
797 public function getRangeStart() {
798 switch ( $this->type
) {
799 case self
::TYPE_USER
:
802 return IP
::toHex( $this->target
);
803 case self
::TYPE_RANGE
:
804 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
807 throw new MWException( "Block with invalid type" );
812 * Get the IP address at the end of the range in Hex form
813 * @throws MWException
814 * @return String IP in Hex form
816 public function getRangeEnd() {
817 switch ( $this->type
) {
818 case self
::TYPE_USER
:
821 return IP
::toHex( $this->target
);
822 case self
::TYPE_RANGE
:
823 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
826 throw new MWException( "Block with invalid type" );
831 * Get the user id of the blocking sysop
833 * @return Integer (0 for foreign users)
835 public function getBy() {
836 $blocker = $this->getBlocker();
837 return ( $blocker instanceof User
)
843 * Get the username of the blocking sysop
847 public function getByName() {
848 $blocker = $this->getBlocker();
849 return ( $blocker instanceof User
)
850 ?
$blocker->getName()
851 : (string)$blocker; // username
858 public function getId() {
863 * Get/set the SELECT ... FOR UPDATE flag
864 * @deprecated since 1.18
868 public function forUpdate( $x = null ) {
869 wfDeprecated( __METHOD__
, '1.18' );
874 * Get/set a flag determining whether the master is used for reads
879 public function fromMaster( $x = null ) {
880 return wfSetVar( $this->mFromMaster
, $x );
884 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range
888 public function isHardblock( $x = null ) {
889 wfSetVar( $this->isHardblock
, $x );
891 # You can't *not* hardblock a user
892 return $this->getType() == self
::TYPE_USER
894 : $this->isHardblock
;
897 public function isAutoblocking( $x = null ) {
898 wfSetVar( $this->isAutoblocking
, $x );
900 # You can't put an autoblock on an IP or range as we don't have any history to
901 # look over to get more IPs from
902 return $this->getType() == self
::TYPE_USER
903 ?
$this->isAutoblocking
908 * Get/set whether the Block prevents a given action
909 * @param $action String
913 public function prevents( $action, $x = null ) {
916 # For now... <evil laugh>
919 case 'createaccount':
920 return wfSetVar( $this->mCreateAccount
, $x );
923 return wfSetVar( $this->mBlockEmail
, $x );
925 case 'editownusertalk':
926 return wfSetVar( $this->mDisableUsertalk
, $x );
934 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
935 * @return String, text is escaped
937 public function getRedactedName() {
938 if ( $this->mAuto
) {
939 return Html
::rawElement(
941 array( 'class' => 'mw-autoblockid' ),
942 wfMessage( 'autoblockid', $this->mId
)
945 return htmlspecialchars( $this->getTarget() );
950 * Encode expiry for DB
952 * @param string $expiry timestamp for expiry, or
953 * @param $db DatabaseBase object
955 * @deprecated since 1.18; use $dbw->encodeExpiry() instead
957 public static function encodeExpiry( $expiry, $db ) {
958 wfDeprecated( __METHOD__
, '1.18' );
959 return $db->encodeExpiry( $expiry );
963 * Decode expiry which has come from the DB
965 * @param string $expiry Database expiry format
966 * @param int $timestampType Requested timestamp format
968 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
970 public static function decodeExpiry( $expiry, $timestampType = TS_MW
) {
971 wfDeprecated( __METHOD__
, '1.18' );
973 return $wgContLang->formatExpiry( $expiry, $timestampType );
977 * Get a timestamp of the expiry for autoblocks
979 * @param $timestamp String|Int
982 public static function getAutoblockExpiry( $timestamp ) {
983 global $wgAutoblockExpiry;
985 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
989 * Gets rid of unneeded numbers in quad-dotted/octet IP strings
990 * For example, 127.111.113.151/24 -> 127.111.113.0/24
991 * @param string $range IP address to normalize
993 * @deprecated since 1.18, call IP::sanitizeRange() directly
995 public static function normaliseRange( $range ) {
996 wfDeprecated( __METHOD__
, '1.18' );
997 return IP
::sanitizeRange( $range );
1001 * Purge expired blocks from the ipblocks table
1003 public static function purgeExpired() {
1004 if ( wfReadOnly() ) {
1008 $method = __METHOD__
;
1009 $dbw = wfGetDB( DB_MASTER
);
1010 $dbw->onTransactionIdle( function() use ( $dbw, $method ) {
1011 $dbw->delete( 'ipblocks',
1012 array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), $method );
1017 * Get a value to insert into expiry field of the database when infinite expiry
1019 * @deprecated since 1.18, call $dbr->getInfinity() directly
1022 public static function infinity() {
1023 wfDeprecated( __METHOD__
, '1.18' );
1024 return wfGetDB( DB_SLAVE
)->getInfinity();
1028 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
1029 * ("24 May 2034"), into an absolute timestamp we can put into the database.
1030 * @param string $expiry whatever was typed into the form
1031 * @return String: timestamp or "infinity" string for th DB implementation
1032 * @deprecated since 1.18 moved to SpecialBlock::parseExpiryInput()
1034 public static function parseExpiryInput( $expiry ) {
1035 wfDeprecated( __METHOD__
, '1.18' );
1036 return SpecialBlock
::parseExpiryInput( $expiry );
1040 * Given a target and the target's type, get an existing Block object if possible.
1041 * @param $specificTarget String|User|Int a block target, which may be one of several types:
1042 * * A user to block, in which case $target will be a User
1043 * * An IP to block, in which case $target will be a User generated by using
1044 * User::newFromName( $ip, false ) to turn off name validation
1045 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1046 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1048 * Calling this with a user, IP address or range will not select autoblocks, and will
1049 * only select a block where the targets match exactly (so looking for blocks on
1050 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1051 * @param $vagueTarget String|User|Int as above, but we will search for *any* block which
1052 * affects that target (so for an IP address, get ranges containing that IP; and also
1053 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1054 * @param bool $fromMaster whether to use the DB_MASTER database
1055 * @return Block|null (null if no relevant block could be found). The target and type
1056 * of the returned Block will refer to the actual block which was found, which might
1057 * not be the same as the target you gave if you used $vagueTarget!
1059 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1061 list( $target, $type ) = self
::parseTarget( $specificTarget );
1062 if ( $type == Block
::TYPE_ID ||
$type == Block
::TYPE_AUTO
) {
1063 return Block
::newFromID( $target );
1065 } elseif ( $target === null && $vagueTarget == '' ) {
1066 # We're not going to find anything useful here
1067 # Be aware that the == '' check is explicit, since empty values will be
1068 # passed by some callers (bug 29116)
1071 } elseif ( in_array( $type, array( Block
::TYPE_USER
, Block
::TYPE_IP
, Block
::TYPE_RANGE
, null ) ) ) {
1072 $block = new Block();
1073 $block->fromMaster( $fromMaster );
1075 if ( $type !== null ) {
1076 $block->setTarget( $target );
1079 if ( $block->newLoad( $vagueTarget ) ) {
1088 * Get all blocks that match any IP from an array of IP addresses
1090 * @param Array $ipChain list of IPs (strings), usually retrieved from the
1091 * X-Forwarded-For header of the request
1092 * @param Bool $isAnon Exclude anonymous-only blocks if false
1093 * @param Bool $fromMaster Whether to query the master or slave database
1094 * @return Array of Blocks
1097 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1098 if ( !count( $ipChain ) ) {
1102 wfProfileIn( __METHOD__
);
1104 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1105 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1106 # necessarily trust the header given to us, make sure that we are only
1107 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1108 # Do not treat private IP spaces as special as it may be desirable for wikis
1109 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1110 if ( !IP
::isValid( $ipaddr ) ) {
1113 # Don't check trusted IPs (includes local squids which will be in every request)
1114 if ( wfIsTrustedProxy( $ipaddr ) ) {
1117 # Check both the original IP (to check against single blocks), as well as build
1118 # the clause to check for rangeblocks for the given IP.
1119 $conds['ipb_address'][] = $ipaddr;
1120 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1123 if ( !count( $conds ) ) {
1124 wfProfileOut( __METHOD__
);
1128 if ( $fromMaster ) {
1129 $db = wfGetDB( DB_MASTER
);
1131 $db = wfGetDB( DB_SLAVE
);
1133 $conds = $db->makeList( $conds, LIST_OR
);
1135 $conds = array( $conds, 'ipb_anon_only' => 0 );
1137 $selectFields = array_merge(
1138 array( 'ipb_range_start', 'ipb_range_end' ),
1139 Block
::selectFields()
1141 $rows = $db->select( 'ipblocks',
1148 foreach ( $rows as $row ) {
1149 $block = self
::newFromRow( $row );
1150 if ( !$block->deleteIfExpired() ) {
1155 wfProfileOut( __METHOD__
);
1160 * From a list of multiple blocks, find the most exact and strongest Block.
1161 * The logic for finding the "best" block is:
1162 * - Blocks that match the block's target IP are preferred over ones in a range
1163 * - Hardblocks are chosen over softblocks that prevent account creation
1164 * - Softblocks that prevent account creation are chosen over other softblocks
1165 * - Other softblocks are chosen over autoblocks
1166 * - If there are multiple exact or range blocks at the same level, the one chosen
1169 * @param Array $ipChain list of IPs (strings). This is used to determine how "close"
1170 * a block is to the server, and if a block matches exactly, or is in a range.
1171 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1173 * @param Array $block Array of blocks
1174 * @return Block|null the "best" block from the list
1176 public static function chooseBlock( array $blocks, array $ipChain ) {
1177 if ( !count( $blocks ) ) {
1179 } elseif ( count( $blocks ) == 1 ) {
1183 wfProfileIn( __METHOD__
);
1185 // Sort hard blocks before soft ones and secondarily sort blocks
1186 // that disable account creation before those that don't.
1187 usort( $blocks, function( Block
$a, Block
$b ) {
1188 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1189 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1190 return strcmp( $bWeight, $aWeight ); // highest weight first
1193 $blocksListExact = array(
1195 'disable_create' => false,
1199 $blocksListRange = array(
1201 'disable_create' => false,
1205 $ipChain = array_reverse( $ipChain );
1207 foreach ( $blocks as $block ) {
1208 // Stop searching if we have already have a "better" block. This
1209 // is why the order of the blocks matters
1210 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1212 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1216 foreach ( $ipChain as $checkip ) {
1217 $checkipHex = IP
::toHex( $checkip );
1218 if ( (string)$block->getTarget() === $checkip ) {
1219 if ( $block->isHardblock() ) {
1220 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1221 } elseif ( $block->prevents( 'createaccount' ) ) {
1222 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1223 } elseif ( $block->mAuto
) {
1224 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1226 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1228 // We found closest exact match in the ip list, so go to the next Block
1230 } elseif ( array_filter( $blocksListExact ) == array()
1231 && $block->getRangeStart() <= $checkipHex
1232 && $block->getRangeEnd() >= $checkipHex
1234 if ( $block->isHardblock() ) {
1235 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1236 } elseif ( $block->prevents( 'createaccount' ) ) {
1237 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1238 } elseif ( $block->mAuto
) {
1239 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1241 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1248 if ( array_filter( $blocksListExact ) == array() ) {
1249 $blocksList = &$blocksListRange;
1251 $blocksList = &$blocksListExact;
1254 $chosenBlock = null;
1255 if ( $blocksList['hard'] ) {
1256 $chosenBlock = $blocksList['hard'];
1257 } elseif ( $blocksList['disable_create'] ) {
1258 $chosenBlock = $blocksList['disable_create'];
1259 } elseif ( $blocksList['other'] ) {
1260 $chosenBlock = $blocksList['other'];
1261 } elseif ( $blocksList['auto'] ) {
1262 $chosenBlock = $blocksList['auto'];
1264 wfProfileOut( __METHOD__
);
1265 throw new MWException( "Proxy block found, but couldn't be classified." );
1268 wfProfileOut( __METHOD__
);
1269 return $chosenBlock;
1273 * From an existing Block, get the target and the type of target.
1274 * Note that, except for null, it is always safe to treat the target
1275 * as a string; for User objects this will return User::__toString()
1276 * which in turn gives User::getName().
1278 * @param $target String|Int|User|null
1279 * @return array( User|String|null, Block::TYPE_ constant|null )
1281 public static function parseTarget( $target ) {
1282 # We may have been through this before
1283 if ( $target instanceof User
) {
1284 if ( IP
::isValid( $target->getName() ) ) {
1285 return array( $target, self
::TYPE_IP
);
1287 return array( $target, self
::TYPE_USER
);
1289 } elseif ( $target === null ) {
1290 return array( null, null );
1293 $target = trim( $target );
1295 if ( IP
::isValid( $target ) ) {
1296 # We can still create a User if it's an IP address, but we need to turn
1297 # off validation checking (which would exclude IP addresses)
1299 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1303 } elseif ( IP
::isValidBlock( $target ) ) {
1304 # Can't create a User from an IP range
1305 return array( IP
::sanitizeRange( $target ), Block
::TYPE_RANGE
);
1308 # Consider the possibility that this is not a username at all
1309 # but actually an old subpage (bug #29797)
1310 if ( strpos( $target, '/' ) !== false ) {
1311 # An old subpage, drill down to the user behind it
1312 $parts = explode( '/', $target );
1313 $target = $parts[0];
1316 $userObj = User
::newFromName( $target );
1317 if ( $userObj instanceof User
) {
1318 # Note that since numbers are valid usernames, a $target of "12345" will be
1319 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1320 # since hash characters are not valid in usernames or titles generally.
1321 return array( $userObj, Block
::TYPE_USER
);
1323 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1324 # Autoblock reference in the form "#12345"
1325 return array( substr( $target, 1 ), Block
::TYPE_AUTO
);
1329 return array( null, null );
1334 * Get the type of target for this particular block
1335 * @return Block::TYPE_ constant, will never be TYPE_ID
1337 public function getType() {
1344 * Get the target and target type for this particular Block. Note that for autoblocks,
1345 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1346 * in this situation.
1347 * @return array( User|String, Block::TYPE_ constant )
1348 * @todo FIXME: This should be an integral part of the Block member variables
1350 public function getTargetAndType() {
1351 return array( $this->getTarget(), $this->getType() );
1355 * Get the target for this particular Block. Note that for autoblocks,
1356 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1357 * in this situation.
1358 * @return User|String
1360 public function getTarget() {
1361 return $this->target
;
1367 * @return Mixed|string
1369 public function getExpiry() {
1370 return $this->mExpiry
;
1374 * Set the target for this block, and update $this->type accordingly
1375 * @param $target Mixed
1377 public function setTarget( $target ) {
1378 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1382 * Get the user who implemented this block
1383 * @return User|string Local User object or string for a foreign user
1385 public function getBlocker() {
1386 return $this->blocker
;
1390 * Set the user who implemented (or will implement) this block
1391 * @param $user User|string Local User object or username string for foreign users
1393 public function setBlocker( $user ) {
1394 $this->blocker
= $user;
1398 * Get the key and parameters for the corresponding error message.
1401 * @param IContextSource $context
1404 public function getPermissionsError( IContextSource
$context ) {
1405 $blocker = $this->getBlocker();
1406 if ( $blocker instanceof User
) { // local user
1407 $blockerUserpage = $blocker->getUserPage();
1408 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1409 } else { // foreign user
1413 $reason = $this->mReason
;
1414 if ( $reason == '' ) {
1415 $reason = $context->msg( 'blockednoreason' )->text();
1418 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1419 * This could be a username, an IP range, or a single IP. */
1420 $intended = $this->getTarget();
1422 $lang = $context->getLanguage();
1424 $this->mAuto ?
'autoblockedtext' : 'blockedtext',
1427 $context->getRequest()->getIP(),
1430 $lang->formatExpiry( $this->mExpiry
),
1432 $lang->timeanddate( wfTimestamp( TS_MW
, $this->mTimestamp
), true ),