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 bool|array False on failure, array on success: ('id' => block ID, 'autoIds' => array of autoblock IDs)
493 public function update() {
494 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
495 $dbw = wfGetDB( DB_MASTER
);
497 $dbw->startAtomic( __METHOD__
);
501 $this->getDatabaseArray( $dbw ),
502 array( 'ipb_id' => $this->getId() ),
506 $affected = $dbw->affectedRows();
510 $this->getAutoblockUpdateArray(),
511 array( 'ipb_parent_block_id' => $this->getId() ),
515 $dbw->endAtomic( __METHOD__
);
518 $auto_ipd_ids = $this->doRetroactiveAutoblock();
519 return array( 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids );
526 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
527 * @param $db DatabaseBase
530 protected function getDatabaseArray( $db = null ) {
532 $db = wfGetDB( DB_SLAVE
);
534 $expiry = $db->encodeExpiry( $this->mExpiry
);
536 if ( $this->forcedTargetID
) {
537 $uid = $this->forcedTargetID
;
539 $uid = $this->target
instanceof User ?
$this->target
->getID() : 0;
543 'ipb_address' => (string)$this->target
,
545 'ipb_by' => $this->getBy(),
546 'ipb_by_text' => $this->getByName(),
547 'ipb_reason' => $this->mReason
,
548 'ipb_timestamp' => $db->timestamp( $this->mTimestamp
),
549 'ipb_auto' => $this->mAuto
,
550 'ipb_anon_only' => !$this->isHardblock(),
551 'ipb_create_account' => $this->prevents( 'createaccount' ),
552 'ipb_enable_autoblock' => $this->isAutoblocking(),
553 'ipb_expiry' => $expiry,
554 'ipb_range_start' => $this->getRangeStart(),
555 'ipb_range_end' => $this->getRangeEnd(),
556 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
557 'ipb_block_email' => $this->prevents( 'sendemail' ),
558 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
559 'ipb_parent_block_id' => $this->mParentBlockId
568 protected function getAutoblockUpdateArray() {
570 'ipb_by' => $this->getBy(),
571 'ipb_by_text' => $this->getByName(),
572 'ipb_reason' => $this->mReason
,
573 'ipb_create_account' => $this->prevents( 'createaccount' ),
574 'ipb_deleted' => (int)$this->mHideName
, // typecast required for SQLite
575 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
580 * Retroactively autoblocks the last IP used by the user (if it is a user)
581 * blocked by this Block.
583 * @return Array: block IDs of retroactive autoblocks made
585 protected function doRetroactiveAutoblock() {
587 # If autoblock is enabled, autoblock the LAST IP(s) used
588 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
589 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
591 $continue = wfRunHooks(
592 'PerformRetroactiveAutoblock', array( $this, &$blockIds ) );
595 self
::defaultRetroactiveAutoblock( $this, $blockIds );
602 * Retroactively autoblocks the last IP used by the user (if it is a user)
603 * blocked by this Block. This will use the recentchanges table.
605 * @param Block $block
606 * @param array &$blockIds
607 * @return Array: block IDs of retroactive autoblocks made
609 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
612 // No IPs are in recentchanges table, so nothing to select
613 if ( !$wgPutIPinRC ) {
617 $dbr = wfGetDB( DB_SLAVE
);
619 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
620 $conds = array( 'rc_user_text' => (string)$block->getTarget() );
622 // Just the last IP used.
623 $options['LIMIT'] = 1;
625 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
626 __METHOD__
, $options );
628 if ( !$res->numRows() ) {
629 # No results, don't autoblock anything
630 wfDebug( "No IP found to retroactively autoblock\n" );
632 foreach ( $res as $row ) {
634 $id = $block->doAutoblock( $row->rc_ip
);
644 * Checks whether a given IP is on the autoblock whitelist.
645 * TODO: this probably belongs somewhere else, but not sure where...
647 * @param string $ip The IP to check
650 public static function isWhitelistedFromAutoblocks( $ip ) {
653 // Try to get the autoblock_whitelist from the cache, as it's faster
654 // than getting the msg raw and explode()'ing it.
655 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
656 $lines = $wgMemc->get( $key );
658 $lines = explode( "\n", wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
659 $wgMemc->set( $key, $lines, 3600 * 24 );
662 wfDebug( "Checking the autoblock whitelist..\n" );
664 foreach ( $lines as $line ) {
666 if ( substr( $line, 0, 1 ) !== '*' ) {
670 $wlEntry = substr( $line, 1 );
671 $wlEntry = trim( $wlEntry );
673 wfDebug( "Checking $ip against $wlEntry..." );
675 # Is the IP in this range?
676 if ( IP
::isInRange( $ip, $wlEntry ) ) {
677 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
680 wfDebug( " No match\n" );
688 * Autoblocks the given IP, referring to this Block.
690 * @param string $autoblockIP the IP to autoblock.
691 * @return mixed: block ID if an autoblock was inserted, false if not.
693 public function doAutoblock( $autoblockIP ) {
694 # If autoblocks are disabled, go away.
695 if ( !$this->isAutoblocking() ) {
699 # Check for presence on the autoblock whitelist.
700 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
704 # Allow hooks to cancel the autoblock.
705 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
706 wfDebug( "Autoblock aborted by hook.\n" );
710 # It's okay to autoblock. Go ahead and insert/update the block...
712 # Do not add a *new* block if the IP is already blocked.
713 $ipblock = Block
::newFromTarget( $autoblockIP );
715 # Check if the block is an autoblock and would exceed the user block
716 # if renewed. If so, do nothing, otherwise prolong the block time...
717 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
718 $this->mExpiry
> Block
::getAutoblockExpiry( $ipblock->mTimestamp
)
720 # Reset block timestamp to now and its expiry to
721 # $wgAutoblockExpiry in the future
722 $ipblock->updateTimestamp();
727 # Make a new block object with the desired properties.
728 $autoblock = new Block
;
729 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
730 $autoblock->setTarget( $autoblockIP );
731 $autoblock->setBlocker( $this->getBlocker() );
732 $autoblock->mReason
= wfMessage( 'autoblocker', $this->getTarget(), $this->mReason
)->inContentLanguage()->plain();
733 $timestamp = wfTimestampNow();
734 $autoblock->mTimestamp
= $timestamp;
735 $autoblock->mAuto
= 1;
736 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
737 # Continue suppressing the name if needed
738 $autoblock->mHideName
= $this->mHideName
;
739 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
740 $autoblock->mParentBlockId
= $this->mId
;
742 if ( $this->mExpiry
== 'infinity' ) {
743 # Original block was indefinite, start an autoblock now
744 $autoblock->mExpiry
= Block
::getAutoblockExpiry( $timestamp );
746 # If the user is already blocked with an expiry date, we don't
747 # want to pile on top of that.
748 $autoblock->mExpiry
= min( $this->mExpiry
, Block
::getAutoblockExpiry( $timestamp ) );
751 # Insert the block...
752 $status = $autoblock->insert();
759 * Check if a block has expired. Delete it if it is.
762 public function deleteIfExpired() {
763 wfProfileIn( __METHOD__
);
765 if ( $this->isExpired() ) {
766 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
770 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
774 wfProfileOut( __METHOD__
);
779 * Has the block expired?
782 public function isExpired() {
783 $timestamp = wfTimestampNow();
784 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
786 if ( !$this->mExpiry
) {
789 return $timestamp > $this->mExpiry
;
794 * Is the block address valid (i.e. not a null string?)
797 public function isValid() {
798 return $this->getTarget() != null;
802 * Update the timestamp on autoblocks.
804 public function updateTimestamp() {
805 if ( $this->mAuto
) {
806 $this->mTimestamp
= wfTimestamp();
807 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
809 $dbw = wfGetDB( DB_MASTER
);
810 $dbw->update( 'ipblocks',
812 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
813 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
816 'ipb_address' => (string)$this->getTarget()
824 * Get the IP address at the start of the range in Hex form
825 * @throws MWException
826 * @return String IP in Hex form
828 public function getRangeStart() {
829 switch ( $this->type
) {
830 case self
::TYPE_USER
:
833 return IP
::toHex( $this->target
);
834 case self
::TYPE_RANGE
:
835 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
838 throw new MWException( "Block with invalid type" );
843 * Get the IP address at the end of the range in Hex form
844 * @throws MWException
845 * @return String IP in Hex form
847 public function getRangeEnd() {
848 switch ( $this->type
) {
849 case self
::TYPE_USER
:
852 return IP
::toHex( $this->target
);
853 case self
::TYPE_RANGE
:
854 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
857 throw new MWException( "Block with invalid type" );
862 * Get the user id of the blocking sysop
864 * @return Integer (0 for foreign users)
866 public function getBy() {
867 $blocker = $this->getBlocker();
868 return ( $blocker instanceof User
)
874 * Get the username of the blocking sysop
878 public function getByName() {
879 $blocker = $this->getBlocker();
880 return ( $blocker instanceof User
)
881 ?
$blocker->getName()
882 : (string)$blocker; // username
889 public function getId() {
894 * Get/set the SELECT ... FOR UPDATE flag
895 * @deprecated since 1.18
899 public function forUpdate( $x = null ) {
900 wfDeprecated( __METHOD__
, '1.18' );
905 * Get/set a flag determining whether the master is used for reads
910 public function fromMaster( $x = null ) {
911 return wfSetVar( $this->mFromMaster
, $x );
915 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range
919 public function isHardblock( $x = null ) {
920 wfSetVar( $this->isHardblock
, $x );
922 # You can't *not* hardblock a user
923 return $this->getType() == self
::TYPE_USER
925 : $this->isHardblock
;
928 public function isAutoblocking( $x = null ) {
929 wfSetVar( $this->isAutoblocking
, $x );
931 # You can't put an autoblock on an IP or range as we don't have any history to
932 # look over to get more IPs from
933 return $this->getType() == self
::TYPE_USER
934 ?
$this->isAutoblocking
939 * Get/set whether the Block prevents a given action
940 * @param $action String
944 public function prevents( $action, $x = null ) {
947 # For now... <evil laugh>
950 case 'createaccount':
951 return wfSetVar( $this->mCreateAccount
, $x );
954 return wfSetVar( $this->mBlockEmail
, $x );
956 case 'editownusertalk':
957 return wfSetVar( $this->mDisableUsertalk
, $x );
965 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
966 * @return String, text is escaped
968 public function getRedactedName() {
969 if ( $this->mAuto
) {
970 return Html
::rawElement(
972 array( 'class' => 'mw-autoblockid' ),
973 wfMessage( 'autoblockid', $this->mId
)
976 return htmlspecialchars( $this->getTarget() );
981 * Encode expiry for DB
983 * @param string $expiry timestamp for expiry, or
984 * @param $db DatabaseBase object
986 * @deprecated since 1.18; use $dbw->encodeExpiry() instead
988 public static function encodeExpiry( $expiry, $db ) {
989 wfDeprecated( __METHOD__
, '1.18' );
990 return $db->encodeExpiry( $expiry );
994 * Decode expiry which has come from the DB
996 * @param string $expiry Database expiry format
997 * @param int $timestampType Requested timestamp format
999 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
1001 public static function decodeExpiry( $expiry, $timestampType = TS_MW
) {
1002 wfDeprecated( __METHOD__
, '1.18' );
1004 return $wgContLang->formatExpiry( $expiry, $timestampType );
1008 * Get a timestamp of the expiry for autoblocks
1010 * @param $timestamp String|Int
1013 public static function getAutoblockExpiry( $timestamp ) {
1014 global $wgAutoblockExpiry;
1016 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1020 * Gets rid of unneeded numbers in quad-dotted/octet IP strings
1021 * For example, 127.111.113.151/24 -> 127.111.113.0/24
1022 * @param string $range IP address to normalize
1024 * @deprecated since 1.18, call IP::sanitizeRange() directly
1026 public static function normaliseRange( $range ) {
1027 wfDeprecated( __METHOD__
, '1.18' );
1028 return IP
::sanitizeRange( $range );
1032 * Purge expired blocks from the ipblocks table
1034 public static function purgeExpired() {
1035 if ( wfReadOnly() ) {
1039 $method = __METHOD__
;
1040 $dbw = wfGetDB( DB_MASTER
);
1041 $dbw->onTransactionIdle( function() use ( $dbw, $method ) {
1042 $dbw->delete( 'ipblocks',
1043 array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), $method );
1048 * Get a value to insert into expiry field of the database when infinite expiry
1050 * @deprecated since 1.18, call $dbr->getInfinity() directly
1053 public static function infinity() {
1054 wfDeprecated( __METHOD__
, '1.18' );
1055 return wfGetDB( DB_SLAVE
)->getInfinity();
1059 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
1060 * ("24 May 2034"), into an absolute timestamp we can put into the database.
1061 * @param string $expiry whatever was typed into the form
1062 * @return String: timestamp or "infinity" string for th DB implementation
1063 * @deprecated since 1.18 moved to SpecialBlock::parseExpiryInput()
1065 public static function parseExpiryInput( $expiry ) {
1066 wfDeprecated( __METHOD__
, '1.18' );
1067 return SpecialBlock
::parseExpiryInput( $expiry );
1071 * Given a target and the target's type, get an existing Block object if possible.
1072 * @param $specificTarget String|User|Int a block target, which may be one of several types:
1073 * * A user to block, in which case $target will be a User
1074 * * An IP to block, in which case $target will be a User generated by using
1075 * User::newFromName( $ip, false ) to turn off name validation
1076 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1077 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1079 * Calling this with a user, IP address or range will not select autoblocks, and will
1080 * only select a block where the targets match exactly (so looking for blocks on
1081 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1082 * @param $vagueTarget String|User|Int as above, but we will search for *any* block which
1083 * affects that target (so for an IP address, get ranges containing that IP; and also
1084 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1085 * @param bool $fromMaster whether to use the DB_MASTER database
1086 * @return Block|null (null if no relevant block could be found). The target and type
1087 * of the returned Block will refer to the actual block which was found, which might
1088 * not be the same as the target you gave if you used $vagueTarget!
1090 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1092 list( $target, $type ) = self
::parseTarget( $specificTarget );
1093 if ( $type == Block
::TYPE_ID ||
$type == Block
::TYPE_AUTO
) {
1094 return Block
::newFromID( $target );
1096 } elseif ( $target === null && $vagueTarget == '' ) {
1097 # We're not going to find anything useful here
1098 # Be aware that the == '' check is explicit, since empty values will be
1099 # passed by some callers (bug 29116)
1102 } elseif ( in_array( $type, array( Block
::TYPE_USER
, Block
::TYPE_IP
, Block
::TYPE_RANGE
, null ) ) ) {
1103 $block = new Block();
1104 $block->fromMaster( $fromMaster );
1106 if ( $type !== null ) {
1107 $block->setTarget( $target );
1110 if ( $block->newLoad( $vagueTarget ) ) {
1119 * Get all blocks that match any IP from an array of IP addresses
1121 * @param Array $ipChain list of IPs (strings), usually retrieved from the
1122 * X-Forwarded-For header of the request
1123 * @param Bool $isAnon Exclude anonymous-only blocks if false
1124 * @param Bool $fromMaster Whether to query the master or slave database
1125 * @return Array of Blocks
1128 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1129 if ( !count( $ipChain ) ) {
1133 wfProfileIn( __METHOD__
);
1135 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1136 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1137 # necessarily trust the header given to us, make sure that we are only
1138 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1139 # Do not treat private IP spaces as special as it may be desirable for wikis
1140 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1141 if ( !IP
::isValid( $ipaddr ) ) {
1144 # Don't check trusted IPs (includes local squids which will be in every request)
1145 if ( wfIsTrustedProxy( $ipaddr ) ) {
1148 # Check both the original IP (to check against single blocks), as well as build
1149 # the clause to check for rangeblocks for the given IP.
1150 $conds['ipb_address'][] = $ipaddr;
1151 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1154 if ( !count( $conds ) ) {
1155 wfProfileOut( __METHOD__
);
1159 if ( $fromMaster ) {
1160 $db = wfGetDB( DB_MASTER
);
1162 $db = wfGetDB( DB_SLAVE
);
1164 $conds = $db->makeList( $conds, LIST_OR
);
1166 $conds = array( $conds, 'ipb_anon_only' => 0 );
1168 $selectFields = array_merge(
1169 array( 'ipb_range_start', 'ipb_range_end' ),
1170 Block
::selectFields()
1172 $rows = $db->select( 'ipblocks',
1179 foreach ( $rows as $row ) {
1180 $block = self
::newFromRow( $row );
1181 if ( !$block->deleteIfExpired() ) {
1186 wfProfileOut( __METHOD__
);
1191 * From a list of multiple blocks, find the most exact and strongest Block.
1192 * The logic for finding the "best" block is:
1193 * - Blocks that match the block's target IP are preferred over ones in a range
1194 * - Hardblocks are chosen over softblocks that prevent account creation
1195 * - Softblocks that prevent account creation are chosen over other softblocks
1196 * - Other softblocks are chosen over autoblocks
1197 * - If there are multiple exact or range blocks at the same level, the one chosen
1200 * @param Array $ipChain list of IPs (strings). This is used to determine how "close"
1201 * a block is to the server, and if a block matches exactly, or is in a range.
1202 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1204 * @param Array $block Array of blocks
1205 * @return Block|null the "best" block from the list
1207 public static function chooseBlock( array $blocks, array $ipChain ) {
1208 if ( !count( $blocks ) ) {
1210 } elseif ( count( $blocks ) == 1 ) {
1214 wfProfileIn( __METHOD__
);
1216 // Sort hard blocks before soft ones and secondarily sort blocks
1217 // that disable account creation before those that don't.
1218 usort( $blocks, function( Block
$a, Block
$b ) {
1219 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1220 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1221 return strcmp( $bWeight, $aWeight ); // highest weight first
1224 $blocksListExact = array(
1226 'disable_create' => false,
1230 $blocksListRange = array(
1232 'disable_create' => false,
1236 $ipChain = array_reverse( $ipChain );
1238 foreach ( $blocks as $block ) {
1239 // Stop searching if we have already have a "better" block. This
1240 // is why the order of the blocks matters
1241 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1243 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1247 foreach ( $ipChain as $checkip ) {
1248 $checkipHex = IP
::toHex( $checkip );
1249 if ( (string)$block->getTarget() === $checkip ) {
1250 if ( $block->isHardblock() ) {
1251 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1252 } elseif ( $block->prevents( 'createaccount' ) ) {
1253 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1254 } elseif ( $block->mAuto
) {
1255 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1257 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1259 // We found closest exact match in the ip list, so go to the next Block
1261 } elseif ( array_filter( $blocksListExact ) == array()
1262 && $block->getRangeStart() <= $checkipHex
1263 && $block->getRangeEnd() >= $checkipHex
1265 if ( $block->isHardblock() ) {
1266 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1267 } elseif ( $block->prevents( 'createaccount' ) ) {
1268 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1269 } elseif ( $block->mAuto
) {
1270 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1272 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1279 if ( array_filter( $blocksListExact ) == array() ) {
1280 $blocksList = &$blocksListRange;
1282 $blocksList = &$blocksListExact;
1285 $chosenBlock = null;
1286 if ( $blocksList['hard'] ) {
1287 $chosenBlock = $blocksList['hard'];
1288 } elseif ( $blocksList['disable_create'] ) {
1289 $chosenBlock = $blocksList['disable_create'];
1290 } elseif ( $blocksList['other'] ) {
1291 $chosenBlock = $blocksList['other'];
1292 } elseif ( $blocksList['auto'] ) {
1293 $chosenBlock = $blocksList['auto'];
1295 wfProfileOut( __METHOD__
);
1296 throw new MWException( "Proxy block found, but couldn't be classified." );
1299 wfProfileOut( __METHOD__
);
1300 return $chosenBlock;
1304 * From an existing Block, get the target and the type of target.
1305 * Note that, except for null, it is always safe to treat the target
1306 * as a string; for User objects this will return User::__toString()
1307 * which in turn gives User::getName().
1309 * @param $target String|Int|User|null
1310 * @return array( User|String|null, Block::TYPE_ constant|null )
1312 public static function parseTarget( $target ) {
1313 # We may have been through this before
1314 if ( $target instanceof User
) {
1315 if ( IP
::isValid( $target->getName() ) ) {
1316 return array( $target, self
::TYPE_IP
);
1318 return array( $target, self
::TYPE_USER
);
1320 } elseif ( $target === null ) {
1321 return array( null, null );
1324 $target = trim( $target );
1326 if ( IP
::isValid( $target ) ) {
1327 # We can still create a User if it's an IP address, but we need to turn
1328 # off validation checking (which would exclude IP addresses)
1330 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1334 } elseif ( IP
::isValidBlock( $target ) ) {
1335 # Can't create a User from an IP range
1336 return array( IP
::sanitizeRange( $target ), Block
::TYPE_RANGE
);
1339 # Consider the possibility that this is not a username at all
1340 # but actually an old subpage (bug #29797)
1341 if ( strpos( $target, '/' ) !== false ) {
1342 # An old subpage, drill down to the user behind it
1343 $parts = explode( '/', $target );
1344 $target = $parts[0];
1347 $userObj = User
::newFromName( $target );
1348 if ( $userObj instanceof User
) {
1349 # Note that since numbers are valid usernames, a $target of "12345" will be
1350 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1351 # since hash characters are not valid in usernames or titles generally.
1352 return array( $userObj, Block
::TYPE_USER
);
1354 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1355 # Autoblock reference in the form "#12345"
1356 return array( substr( $target, 1 ), Block
::TYPE_AUTO
);
1360 return array( null, null );
1365 * Get the type of target for this particular block
1366 * @return Block::TYPE_ constant, will never be TYPE_ID
1368 public function getType() {
1375 * Get the target and target type for this particular Block. Note that for autoblocks,
1376 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1377 * in this situation.
1378 * @return array( User|String, Block::TYPE_ constant )
1379 * @todo FIXME: This should be an integral part of the Block member variables
1381 public function getTargetAndType() {
1382 return array( $this->getTarget(), $this->getType() );
1386 * Get the target for this particular Block. Note that for autoblocks,
1387 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1388 * in this situation.
1389 * @return User|String
1391 public function getTarget() {
1392 return $this->target
;
1398 * @return Mixed|string
1400 public function getExpiry() {
1401 return $this->mExpiry
;
1405 * Set the target for this block, and update $this->type accordingly
1406 * @param $target Mixed
1408 public function setTarget( $target ) {
1409 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1413 * Get the user who implemented this block
1414 * @return User|string Local User object or string for a foreign user
1416 public function getBlocker() {
1417 return $this->blocker
;
1421 * Set the user who implemented (or will implement) this block
1422 * @param $user User|string Local User object or username string for foreign users
1424 public function setBlocker( $user ) {
1425 $this->blocker
= $user;
1429 * Get the key and parameters for the corresponding error message.
1432 * @param IContextSource $context
1435 public function getPermissionsError( IContextSource
$context ) {
1436 $blocker = $this->getBlocker();
1437 if ( $blocker instanceof User
) { // local user
1438 $blockerUserpage = $blocker->getUserPage();
1439 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1440 } else { // foreign user
1444 $reason = $this->mReason
;
1445 if ( $reason == '' ) {
1446 $reason = $context->msg( 'blockednoreason' )->text();
1449 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1450 * This could be a username, an IP range, or a single IP. */
1451 $intended = $this->getTarget();
1453 $lang = $context->getLanguage();
1455 $this->mAuto ?
'autoblockedtext' : 'blockedtext',
1458 $context->getRequest()->getIP(),
1461 $lang->formatExpiry( $this->mExpiry
),
1463 $lang->timeanddate( wfTimestamp( TS_MW
, $this->mTimestamp
), true ),