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
39 public $mParentBlockId;
45 protected $mFromMaster;
48 protected $mBlockEmail;
51 protected $mDisableUsertalk;
54 protected $mCreateAccount;
56 /** @var User|string */
59 /** @var int Hack for foreign blocking (CentralAuth) */
60 protected $forcedTargetID;
62 /** @var int Block::TYPE_ constant. Can only be USER, IP or RANGE internally */
69 protected $isHardblock;
72 protected $isAutoblocking;
82 * Create a new block with specified parameters on a user, IP or IP range.
84 * @param array $options Parameters of the block:
85 * address string|User Target user name, User object, IP address or IP range
86 * user int Override target user ID (for foreign users)
87 * by int User ID of the blocker
88 * reason string Reason of the block
89 * timestamp string The time at which the block comes into effect
90 * auto bool Is this an automatic block?
91 * expiry string Timestamp of expiration of the block or 'infinity'
92 * anonOnly bool Only disallow anonymous actions
93 * createAccount bool Disallow creation of new accounts
94 * enableAutoblock bool Enable automatic blocking
95 * hideName bool Hide the target user name
96 * blockEmail bool Disallow sending emails
97 * allowUsertalk bool Allow the target to edit its own talk page
98 * byText string Username of the blocker (for foreign users)
100 * @since 1.26 accepts $options array instead of individual parameters; order
101 * of parameters above reflects the original order
103 function __construct( $options = array() ) {
113 'createAccount' => false,
114 'enableAutoblock' => false,
116 'blockEmail' => false,
117 'allowUsertalk' => false,
121 if ( func_num_args() > 1 ||
!is_array( $options ) ) {
122 $options = array_combine(
123 array_slice( array_keys( $defaults ), 0, func_num_args() ),
126 wfDeprecated( __METHOD__
. ' with multiple arguments', '1.26' );
129 $options +
= $defaults;
131 $this->setTarget( $options['address'] );
133 if ( $this->target
instanceof User
&& $options['user'] ) {
134 # Needed for foreign users
135 $this->forcedTargetID
= $options['user'];
138 if ( $options['by'] ) {
140 $this->setBlocker( User
::newFromID( $options['by'] ) );
143 $this->setBlocker( $options['byText'] );
146 $this->mReason
= $options['reason'];
147 $this->mTimestamp
= wfTimestamp( TS_MW
, $options['timestamp'] );
148 $this->mExpiry
= wfGetDB( DB_SLAVE
)->decodeExpiry( $options['expiry'] );
151 $this->mAuto
= (bool)$options['auto'];
152 $this->mHideName
= (bool)$options['hideName'];
153 $this->isHardblock( !$options['anonOnly'] );
154 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
156 # Prevention measures
157 $this->prevents( 'sendemail', (bool)$options['blockEmail'] );
158 $this->prevents( 'editownusertalk', !$options['allowUsertalk'] );
159 $this->prevents( 'createaccount', (bool)$options['createAccount'] );
161 $this->mFromMaster
= false;
165 * Load a blocked user from their block id.
167 * @param int $id Block id to search for
170 public static function newFromID( $id ) {
171 $dbr = wfGetDB( DB_SLAVE
);
172 $res = $dbr->selectRow(
174 self
::selectFields(),
175 array( 'ipb_id' => $id ),
179 return self
::newFromRow( $res );
186 * Return the list of ipblocks fields that should be selected to create
190 public static function selectFields() {
200 'ipb_create_account',
201 'ipb_enable_autoblock',
205 'ipb_allow_usertalk',
206 'ipb_parent_block_id',
211 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
212 * the blocking user or the block timestamp, only things which affect the blocked user
214 * @param Block $block
218 public function equals( Block
$block ) {
220 (string)$this->target
== (string)$block->target
221 && $this->type
== $block->type
222 && $this->mAuto
== $block->mAuto
223 && $this->isHardblock() == $block->isHardblock()
224 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
225 && $this->mExpiry
== $block->mExpiry
226 && $this->isAutoblocking() == $block->isAutoblocking()
227 && $this->mHideName
== $block->mHideName
228 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
229 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
230 && $this->mReason
== $block->mReason
235 * Load a block from the database which affects the already-set $this->target:
236 * 1) A block directly on the given user or IP
237 * 2) A rangeblock encompassing the given IP (smallest first)
238 * 3) An autoblock on the given IP
239 * @param User|string $vagueTarget Also search for blocks affecting this target. Doesn't
240 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
241 * @throws MWException
242 * @return bool Whether a relevant block was found
244 protected function newLoad( $vagueTarget = null ) {
245 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_SLAVE
);
247 if ( $this->type
!== null ) {
249 'ipb_address' => array( (string)$this->target
),
252 $conds = array( 'ipb_address' => array() );
255 # Be aware that the != '' check is explicit, since empty values will be
256 # passed by some callers (bug 29116)
257 if ( $vagueTarget != '' ) {
258 list( $target, $type ) = self
::parseTarget( $vagueTarget );
260 case self
::TYPE_USER
:
261 # Slightly weird, but who are we to argue?
262 $conds['ipb_address'][] = (string)$target;
266 $conds['ipb_address'][] = (string)$target;
267 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
268 $conds = $db->makeList( $conds, LIST_OR
);
271 case self
::TYPE_RANGE
:
272 list( $start, $end ) = IP
::parseRange( $target );
273 $conds['ipb_address'][] = (string)$target;
274 $conds[] = self
::getRangeCond( $start, $end );
275 $conds = $db->makeList( $conds, LIST_OR
);
279 throw new MWException( "Tried to load block with invalid type" );
283 $res = $db->select( 'ipblocks', self
::selectFields(), $conds, __METHOD__
);
285 # This result could contain a block on the user, a block on the IP, and a russian-doll
286 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
289 # Lower will be better
290 $bestBlockScore = 100;
292 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
293 $bestBlockPreventsEdit = null;
295 foreach ( $res as $row ) {
296 $block = self
::newFromRow( $row );
298 # Don't use expired blocks
299 if ( $block->deleteIfExpired() ) {
303 # Don't use anon only blocks on users
304 if ( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ) {
308 if ( $block->getType() == self
::TYPE_RANGE
) {
309 # This is the number of bits that are allowed to vary in the block, give
310 # or take some floating point errors
311 $end = Wikimedia\base_convert
( $block->getRangeEnd(), 16, 10 );
312 $start = Wikimedia\base_convert
( $block->getRangeStart(), 16, 10 );
313 $size = log( $end - $start +
1, 2 );
315 # This has the nice property that a /32 block is ranked equally with a
316 # single-IP block, which is exactly what it is...
317 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
320 $score = $block->getType();
323 if ( $score < $bestBlockScore ) {
324 $bestBlockScore = $score;
326 $bestBlockPreventsEdit = $block->prevents( 'edit' );
330 if ( $bestRow !== null ) {
331 $this->initFromRow( $bestRow );
332 $this->prevents( 'edit', $bestBlockPreventsEdit );
340 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
341 * @param string $start Hexadecimal IP representation
342 * @param string $end Hexadecimal IP representation, or null to use $start = $end
345 public static function getRangeCond( $start, $end = null ) {
346 if ( $end === null ) {
349 # Per bug 14634, we want to include relevant active rangeblocks; for
350 # rangeblocks, we want to include larger ranges which enclose the given
351 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
352 # so we can improve performance by filtering on a LIKE clause
353 $chunk = self
::getIpFragment( $start );
354 $dbr = wfGetDB( DB_SLAVE
);
355 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
357 # Fairly hard to make a malicious SQL statement out of hex characters,
358 # but stranger things have happened...
359 $safeStart = $dbr->addQuotes( $start );
360 $safeEnd = $dbr->addQuotes( $end );
362 return $dbr->makeList(
364 "ipb_range_start $like",
365 "ipb_range_start <= $safeStart",
366 "ipb_range_end >= $safeEnd",
373 * Get the component of an IP address which is certain to be the same between an IP
374 * address and a rangeblock containing that IP address.
375 * @param string $hex Hexadecimal IP representation
378 protected static function getIpFragment( $hex ) {
379 global $wgBlockCIDRLimit;
380 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
381 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
383 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
388 * Given a database row from the ipblocks table, initialize
390 * @param stdClass $row A row from the ipblocks table
392 protected function initFromRow( $row ) {
393 $this->setTarget( $row->ipb_address
);
394 if ( $row->ipb_by
) { // local user
395 $this->setBlocker( User
::newFromId( $row->ipb_by
) );
396 } else { // foreign user
397 $this->setBlocker( $row->ipb_by_text
);
400 $this->mReason
= $row->ipb_reason
;
401 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
402 $this->mAuto
= $row->ipb_auto
;
403 $this->mHideName
= $row->ipb_deleted
;
404 $this->mId
= (int)$row->ipb_id
;
405 $this->mParentBlockId
= $row->ipb_parent_block_id
;
407 // I wish I didn't have to do this
408 $this->mExpiry
= wfGetDB( DB_SLAVE
)->decodeExpiry( $row->ipb_expiry
);
410 $this->isHardblock( !$row->ipb_anon_only
);
411 $this->isAutoblocking( $row->ipb_enable_autoblock
);
413 $this->prevents( 'createaccount', $row->ipb_create_account
);
414 $this->prevents( 'sendemail', $row->ipb_block_email
);
415 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk
);
419 * Create a new Block object from a database row
420 * @param stdClass $row Row from the ipblocks table
423 public static function newFromRow( $row ) {
425 $block->initFromRow( $row );
430 * Delete the row from the IP blocks table.
432 * @throws MWException
435 public function delete() {
436 if ( wfReadOnly() ) {
440 if ( !$this->getId() ) {
441 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
444 $dbw = wfGetDB( DB_MASTER
);
445 $dbw->delete( 'ipblocks', array( 'ipb_parent_block_id' => $this->getId() ), __METHOD__
);
446 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->getId() ), __METHOD__
);
448 return $dbw->affectedRows() > 0;
452 * Insert a block into the block table. Will fail if there is a conflicting
453 * block (same name and options) already in the database.
455 * @param IDatabase $dbw If you have one available
456 * @return bool|array False on failure, assoc array on success:
457 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
459 public function insert( $dbw = null ) {
460 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
462 if ( $dbw === null ) {
463 $dbw = wfGetDB( DB_MASTER
);
466 # Periodic purge via commit hooks
467 if ( mt_rand( 0, 9 ) == 0 ) {
468 Block
::purgeExpired();
471 $row = $this->getDatabaseArray();
472 $row['ipb_id'] = $dbw->nextSequenceValue( "ipblocks_ipb_id_seq" );
474 $dbw->insert( 'ipblocks', $row, __METHOD__
, array( 'IGNORE' ) );
475 $affected = $dbw->affectedRows();
476 $this->mId
= $dbw->insertId();
478 # Don't collide with expired blocks.
479 # Do this after trying to insert to avoid locking.
481 # T96428: The ipb_address index uses a prefix on a field, so
482 # use a standard SELECT + DELETE to avoid annoying gap locks.
483 $ids = $dbw->selectFieldValues( 'ipblocks',
486 'ipb_address' => $row['ipb_address'],
487 'ipb_user' => $row['ipb_user'],
488 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
493 $dbw->delete( 'ipblocks', array( 'ipb_id' => $ids ), __METHOD__
);
494 $dbw->insert( 'ipblocks', $row, __METHOD__
, array( 'IGNORE' ) );
495 $affected = $dbw->affectedRows();
496 $this->mId
= $dbw->insertId();
501 $auto_ipd_ids = $this->doRetroactiveAutoblock();
502 return array( 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids );
509 * Update a block in the DB with new parameters.
510 * The ID field needs to be loaded first.
512 * @return bool|array False on failure, array on success:
513 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
515 public function update() {
516 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
517 $dbw = wfGetDB( DB_MASTER
);
519 $dbw->startAtomic( __METHOD__
);
523 $this->getDatabaseArray( $dbw ),
524 array( 'ipb_id' => $this->getId() ),
528 $affected = $dbw->affectedRows();
530 if ( $this->isAutoblocking() ) {
531 // update corresponding autoblock(s) (bug 48813)
534 $this->getAutoblockUpdateArray(),
535 array( 'ipb_parent_block_id' => $this->getId() ),
539 // autoblock no longer required, delete corresponding autoblock(s)
542 array( 'ipb_parent_block_id' => $this->getId() ),
547 $dbw->endAtomic( __METHOD__
);
550 $auto_ipd_ids = $this->doRetroactiveAutoblock();
551 return array( 'id' => $this->mId
, 'autoIds' => $auto_ipd_ids );
558 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
559 * @param IDatabase $db
562 protected function getDatabaseArray( $db = null ) {
564 $db = wfGetDB( DB_SLAVE
);
566 $expiry = $db->encodeExpiry( $this->mExpiry
);
568 if ( $this->forcedTargetID
) {
569 $uid = $this->forcedTargetID
;
571 $uid = $this->target
instanceof User ?
$this->target
->getID() : 0;
575 'ipb_address' => (string)$this->target
,
577 'ipb_by' => $this->getBy(),
578 'ipb_by_text' => $this->getByName(),
579 'ipb_reason' => $this->mReason
,
580 'ipb_timestamp' => $db->timestamp( $this->mTimestamp
),
581 'ipb_auto' => $this->mAuto
,
582 'ipb_anon_only' => !$this->isHardblock(),
583 'ipb_create_account' => $this->prevents( 'createaccount' ),
584 'ipb_enable_autoblock' => $this->isAutoblocking(),
585 'ipb_expiry' => $expiry,
586 'ipb_range_start' => $this->getRangeStart(),
587 'ipb_range_end' => $this->getRangeEnd(),
588 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
589 'ipb_block_email' => $this->prevents( 'sendemail' ),
590 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
591 'ipb_parent_block_id' => $this->mParentBlockId
600 protected function getAutoblockUpdateArray() {
602 'ipb_by' => $this->getBy(),
603 'ipb_by_text' => $this->getByName(),
604 'ipb_reason' => $this->mReason
,
605 'ipb_create_account' => $this->prevents( 'createaccount' ),
606 'ipb_deleted' => (int)$this->mHideName
, // typecast required for SQLite
607 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
612 * Retroactively autoblocks the last IP used by the user (if it is a user)
613 * blocked by this Block.
615 * @return array Block IDs of retroactive autoblocks made
617 protected function doRetroactiveAutoblock() {
619 # If autoblock is enabled, autoblock the LAST IP(s) used
620 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
621 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
623 $continue = Hooks
::run(
624 'PerformRetroactiveAutoblock', array( $this, &$blockIds ) );
627 self
::defaultRetroactiveAutoblock( $this, $blockIds );
634 * Retroactively autoblocks the last IP used by the user (if it is a user)
635 * blocked by this Block. This will use the recentchanges table.
637 * @param Block $block
638 * @param array &$blockIds
640 protected static function defaultRetroactiveAutoblock( Block
$block, array &$blockIds ) {
643 // No IPs are in recentchanges table, so nothing to select
644 if ( !$wgPutIPinRC ) {
648 $dbr = wfGetDB( DB_SLAVE
);
650 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
651 $conds = array( 'rc_user_text' => (string)$block->getTarget() );
653 // Just the last IP used.
654 $options['LIMIT'] = 1;
656 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
657 __METHOD__
, $options );
659 if ( !$res->numRows() ) {
660 # No results, don't autoblock anything
661 wfDebug( "No IP found to retroactively autoblock\n" );
663 foreach ( $res as $row ) {
665 $id = $block->doAutoblock( $row->rc_ip
);
675 * Checks whether a given IP is on the autoblock whitelist.
676 * TODO: this probably belongs somewhere else, but not sure where...
678 * @param string $ip The IP to check
681 public static function isWhitelistedFromAutoblocks( $ip ) {
682 // Try to get the autoblock_whitelist from the cache, as it's faster
683 // than getting the msg raw and explode()'ing it.
684 $cache = ObjectCache
::getMainWANInstance();
685 $lines = $cache->getWithSetCallback(
686 wfMemcKey( 'ipb', 'autoblock', 'whitelist' ),
689 return explode( "\n",
690 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
694 wfDebug( "Checking the autoblock whitelist..\n" );
696 foreach ( $lines as $line ) {
698 if ( substr( $line, 0, 1 ) !== '*' ) {
702 $wlEntry = substr( $line, 1 );
703 $wlEntry = trim( $wlEntry );
705 wfDebug( "Checking $ip against $wlEntry..." );
707 # Is the IP in this range?
708 if ( IP
::isInRange( $ip, $wlEntry ) ) {
709 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
712 wfDebug( " No match\n" );
720 * Autoblocks the given IP, referring to this Block.
722 * @param string $autoblockIP The IP to autoblock.
723 * @return int|bool Block ID if an autoblock was inserted, false if not.
725 public function doAutoblock( $autoblockIP ) {
726 # If autoblocks are disabled, go away.
727 if ( !$this->isAutoblocking() ) {
731 # Check for presence on the autoblock whitelist.
732 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
736 # Allow hooks to cancel the autoblock.
737 if ( !Hooks
::run( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
738 wfDebug( "Autoblock aborted by hook.\n" );
742 # It's okay to autoblock. Go ahead and insert/update the block...
744 # Do not add a *new* block if the IP is already blocked.
745 $ipblock = Block
::newFromTarget( $autoblockIP );
747 # Check if the block is an autoblock and would exceed the user block
748 # if renewed. If so, do nothing, otherwise prolong the block time...
749 if ( $ipblock->mAuto
&& // @todo Why not compare $ipblock->mExpiry?
750 $this->mExpiry
> Block
::getAutoblockExpiry( $ipblock->mTimestamp
)
752 # Reset block timestamp to now and its expiry to
753 # $wgAutoblockExpiry in the future
754 $ipblock->updateTimestamp();
759 # Make a new block object with the desired properties.
760 $autoblock = new Block
;
761 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
762 $autoblock->setTarget( $autoblockIP );
763 $autoblock->setBlocker( $this->getBlocker() );
764 $autoblock->mReason
= wfMessage( 'autoblocker', $this->getTarget(), $this->mReason
)
765 ->inContentLanguage()->plain();
766 $timestamp = wfTimestampNow();
767 $autoblock->mTimestamp
= $timestamp;
768 $autoblock->mAuto
= 1;
769 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
770 # Continue suppressing the name if needed
771 $autoblock->mHideName
= $this->mHideName
;
772 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
773 $autoblock->mParentBlockId
= $this->mId
;
775 if ( $this->mExpiry
== 'infinity' ) {
776 # Original block was indefinite, start an autoblock now
777 $autoblock->mExpiry
= Block
::getAutoblockExpiry( $timestamp );
779 # If the user is already blocked with an expiry date, we don't
780 # want to pile on top of that.
781 $autoblock->mExpiry
= min( $this->mExpiry
, Block
::getAutoblockExpiry( $timestamp ) );
784 # Insert the block...
785 $status = $autoblock->insert();
792 * Check if a block has expired. Delete it if it is.
795 public function deleteIfExpired() {
797 if ( $this->isExpired() ) {
798 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
802 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
810 * Has the block expired?
813 public function isExpired() {
814 $timestamp = wfTimestampNow();
815 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
817 if ( !$this->mExpiry
) {
820 return $timestamp > $this->mExpiry
;
825 * Is the block address valid (i.e. not a null string?)
828 public function isValid() {
829 return $this->getTarget() != null;
833 * Update the timestamp on autoblocks.
835 public function updateTimestamp() {
836 if ( $this->mAuto
) {
837 $this->mTimestamp
= wfTimestamp();
838 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
840 $dbw = wfGetDB( DB_MASTER
);
841 $dbw->update( 'ipblocks',
843 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
844 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
847 'ipb_address' => (string)$this->getTarget()
855 * Get the IP address at the start of the range in Hex form
856 * @throws MWException
857 * @return string IP in Hex form
859 public function getRangeStart() {
860 switch ( $this->type
) {
861 case self
::TYPE_USER
:
864 return IP
::toHex( $this->target
);
865 case self
::TYPE_RANGE
:
866 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
869 throw new MWException( "Block with invalid type" );
874 * Get the IP address at the end of the range in Hex form
875 * @throws MWException
876 * @return string IP in Hex form
878 public function getRangeEnd() {
879 switch ( $this->type
) {
880 case self
::TYPE_USER
:
883 return IP
::toHex( $this->target
);
884 case self
::TYPE_RANGE
:
885 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
888 throw new MWException( "Block with invalid type" );
893 * Get the user id of the blocking sysop
895 * @return int (0 for foreign users)
897 public function getBy() {
898 $blocker = $this->getBlocker();
899 return ( $blocker instanceof User
)
905 * Get the username of the blocking sysop
909 public function getByName() {
910 $blocker = $this->getBlocker();
911 return ( $blocker instanceof User
)
912 ?
$blocker->getName()
913 : (string)$blocker; // username
920 public function getId() {
925 * Get/set a flag determining whether the master is used for reads
927 * @param bool|null $x
930 public function fromMaster( $x = null ) {
931 return wfSetVar( $this->mFromMaster
, $x );
935 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
936 * @param bool|null $x
939 public function isHardblock( $x = null ) {
940 wfSetVar( $this->isHardblock
, $x );
942 # You can't *not* hardblock a user
943 return $this->getType() == self
::TYPE_USER
945 : $this->isHardblock
;
949 * @param null|bool $x
952 public function isAutoblocking( $x = null ) {
953 wfSetVar( $this->isAutoblocking
, $x );
955 # You can't put an autoblock on an IP or range as we don't have any history to
956 # look over to get more IPs from
957 return $this->getType() == self
::TYPE_USER
958 ?
$this->isAutoblocking
963 * Get/set whether the Block prevents a given action
964 * @param string $action
965 * @param bool|null $x
968 public function prevents( $action, $x = null ) {
971 # For now... <evil laugh>
974 case 'createaccount':
975 return wfSetVar( $this->mCreateAccount
, $x );
978 return wfSetVar( $this->mBlockEmail
, $x );
980 case 'editownusertalk':
981 return wfSetVar( $this->mDisableUsertalk
, $x );
989 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
990 * @return string Text is escaped
992 public function getRedactedName() {
993 if ( $this->mAuto
) {
994 return Html
::rawElement(
996 array( 'class' => 'mw-autoblockid' ),
997 wfMessage( 'autoblockid', $this->mId
)
1000 return htmlspecialchars( $this->getTarget() );
1005 * Get a timestamp of the expiry for autoblocks
1007 * @param string|int $timestamp
1010 public static function getAutoblockExpiry( $timestamp ) {
1011 global $wgAutoblockExpiry;
1013 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
1017 * Purge expired blocks from the ipblocks table
1019 public static function purgeExpired() {
1020 if ( wfReadOnly() ) {
1024 $method = __METHOD__
;
1025 $dbw = wfGetDB( DB_MASTER
);
1026 $dbw->onTransactionIdle( function () use ( $dbw, $method ) {
1027 $dbw->delete( 'ipblocks',
1028 array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), $method );
1033 * Given a target and the target's type, get an existing Block object if possible.
1034 * @param string|User|int $specificTarget A block target, which may be one of several types:
1035 * * A user to block, in which case $target will be a User
1036 * * An IP to block, in which case $target will be a User generated by using
1037 * User::newFromName( $ip, false ) to turn off name validation
1038 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1039 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1041 * Calling this with a user, IP address or range will not select autoblocks, and will
1042 * only select a block where the targets match exactly (so looking for blocks on
1043 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1044 * @param string|User|int $vagueTarget As above, but we will search for *any* block which
1045 * affects that target (so for an IP address, get ranges containing that IP; and also
1046 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1047 * @param bool $fromMaster Whether to use the DB_MASTER database
1048 * @return Block|null (null if no relevant block could be found). The target and type
1049 * of the returned Block will refer to the actual block which was found, which might
1050 * not be the same as the target you gave if you used $vagueTarget!
1052 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1054 list( $target, $type ) = self
::parseTarget( $specificTarget );
1055 if ( $type == Block
::TYPE_ID ||
$type == Block
::TYPE_AUTO
) {
1056 return Block
::newFromID( $target );
1058 } elseif ( $target === null && $vagueTarget == '' ) {
1059 # We're not going to find anything useful here
1060 # Be aware that the == '' check is explicit, since empty values will be
1061 # passed by some callers (bug 29116)
1064 } elseif ( in_array(
1066 array( Block
::TYPE_USER
, Block
::TYPE_IP
, Block
::TYPE_RANGE
, null ) )
1068 $block = new Block();
1069 $block->fromMaster( $fromMaster );
1071 if ( $type !== null ) {
1072 $block->setTarget( $target );
1075 if ( $block->newLoad( $vagueTarget ) ) {
1083 * Get all blocks that match any IP from an array of IP addresses
1085 * @param array $ipChain List of IPs (strings), usually retrieved from the
1086 * X-Forwarded-For header of the request
1087 * @param bool $isAnon Exclude anonymous-only blocks if false
1088 * @param bool $fromMaster Whether to query the master or slave database
1089 * @return array Array of Blocks
1092 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1093 if ( !count( $ipChain ) ) {
1098 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1099 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1100 # necessarily trust the header given to us, make sure that we are only
1101 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1102 # Do not treat private IP spaces as special as it may be desirable for wikis
1103 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1104 if ( !IP
::isValid( $ipaddr ) ) {
1107 # Don't check trusted IPs (includes local squids which will be in every request)
1108 if ( IP
::isTrustedProxy( $ipaddr ) ) {
1111 # Check both the original IP (to check against single blocks), as well as build
1112 # the clause to check for rangeblocks for the given IP.
1113 $conds['ipb_address'][] = $ipaddr;
1114 $conds[] = self
::getRangeCond( IP
::toHex( $ipaddr ) );
1117 if ( !count( $conds ) ) {
1121 if ( $fromMaster ) {
1122 $db = wfGetDB( DB_MASTER
);
1124 $db = wfGetDB( DB_SLAVE
);
1126 $conds = $db->makeList( $conds, LIST_OR
);
1128 $conds = array( $conds, 'ipb_anon_only' => 0 );
1130 $selectFields = array_merge(
1131 array( 'ipb_range_start', 'ipb_range_end' ),
1132 Block
::selectFields()
1134 $rows = $db->select( 'ipblocks',
1141 foreach ( $rows as $row ) {
1142 $block = self
::newFromRow( $row );
1143 if ( !$block->deleteIfExpired() ) {
1152 * From a list of multiple blocks, find the most exact and strongest Block.
1154 * The logic for finding the "best" block is:
1155 * - Blocks that match the block's target IP are preferred over ones in a range
1156 * - Hardblocks are chosen over softblocks that prevent account creation
1157 * - Softblocks that prevent account creation are chosen over other softblocks
1158 * - Other softblocks are chosen over autoblocks
1159 * - If there are multiple exact or range blocks at the same level, the one chosen
1161 * This should be used when $blocks where retrieved from the user's IP address
1162 * and $ipChain is populated from the same IP address information.
1164 * @param array $blocks Array of Block objects
1165 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1166 * a block is to the server, and if a block matches exactly, or is in a range.
1167 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1169 * @throws MWException
1170 * @return Block|null The "best" block from the list
1172 public static function chooseBlock( array $blocks, array $ipChain ) {
1173 if ( !count( $blocks ) ) {
1175 } elseif ( count( $blocks ) == 1 ) {
1179 // Sort hard blocks before soft ones and secondarily sort blocks
1180 // that disable account creation before those that don't.
1181 usort( $blocks, function ( Block
$a, Block
$b ) {
1182 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1183 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1184 return strcmp( $bWeight, $aWeight ); // highest weight first
1187 $blocksListExact = array(
1189 'disable_create' => false,
1193 $blocksListRange = array(
1195 'disable_create' => false,
1199 $ipChain = array_reverse( $ipChain );
1201 /** @var Block $block */
1202 foreach ( $blocks as $block ) {
1203 // Stop searching if we have already have a "better" block. This
1204 // is why the order of the blocks matters
1205 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1207 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1211 foreach ( $ipChain as $checkip ) {
1212 $checkipHex = IP
::toHex( $checkip );
1213 if ( (string)$block->getTarget() === $checkip ) {
1214 if ( $block->isHardblock() ) {
1215 $blocksListExact['hard'] = $blocksListExact['hard'] ?
: $block;
1216 } elseif ( $block->prevents( 'createaccount' ) ) {
1217 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?
: $block;
1218 } elseif ( $block->mAuto
) {
1219 $blocksListExact['auto'] = $blocksListExact['auto'] ?
: $block;
1221 $blocksListExact['other'] = $blocksListExact['other'] ?
: $block;
1223 // We found closest exact match in the ip list, so go to the next Block
1225 } elseif ( array_filter( $blocksListExact ) == array()
1226 && $block->getRangeStart() <= $checkipHex
1227 && $block->getRangeEnd() >= $checkipHex
1229 if ( $block->isHardblock() ) {
1230 $blocksListRange['hard'] = $blocksListRange['hard'] ?
: $block;
1231 } elseif ( $block->prevents( 'createaccount' ) ) {
1232 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?
: $block;
1233 } elseif ( $block->mAuto
) {
1234 $blocksListRange['auto'] = $blocksListRange['auto'] ?
: $block;
1236 $blocksListRange['other'] = $blocksListRange['other'] ?
: $block;
1243 if ( array_filter( $blocksListExact ) == array() ) {
1244 $blocksList = &$blocksListRange;
1246 $blocksList = &$blocksListExact;
1249 $chosenBlock = null;
1250 if ( $blocksList['hard'] ) {
1251 $chosenBlock = $blocksList['hard'];
1252 } elseif ( $blocksList['disable_create'] ) {
1253 $chosenBlock = $blocksList['disable_create'];
1254 } elseif ( $blocksList['other'] ) {
1255 $chosenBlock = $blocksList['other'];
1256 } elseif ( $blocksList['auto'] ) {
1257 $chosenBlock = $blocksList['auto'];
1259 throw new MWException( "Proxy block found, but couldn't be classified." );
1262 return $chosenBlock;
1266 * From an existing Block, get the target and the type of target.
1267 * Note that, except for null, it is always safe to treat the target
1268 * as a string; for User objects this will return User::__toString()
1269 * which in turn gives User::getName().
1271 * @param string|int|User|null $target
1272 * @return array( User|String|null, Block::TYPE_ constant|null )
1274 public static function parseTarget( $target ) {
1275 # We may have been through this before
1276 if ( $target instanceof User
) {
1277 if ( IP
::isValid( $target->getName() ) ) {
1278 return array( $target, self
::TYPE_IP
);
1280 return array( $target, self
::TYPE_USER
);
1282 } elseif ( $target === null ) {
1283 return array( null, null );
1286 $target = trim( $target );
1288 if ( IP
::isValid( $target ) ) {
1289 # We can still create a User if it's an IP address, but we need to turn
1290 # off validation checking (which would exclude IP addresses)
1292 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1296 } elseif ( IP
::isValidBlock( $target ) ) {
1297 # Can't create a User from an IP range
1298 return array( IP
::sanitizeRange( $target ), Block
::TYPE_RANGE
);
1301 # Consider the possibility that this is not a username at all
1302 # but actually an old subpage (bug #29797)
1303 if ( strpos( $target, '/' ) !== false ) {
1304 # An old subpage, drill down to the user behind it
1305 $parts = explode( '/', $target );
1306 $target = $parts[0];
1309 $userObj = User
::newFromName( $target );
1310 if ( $userObj instanceof User
) {
1311 # Note that since numbers are valid usernames, a $target of "12345" will be
1312 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1313 # since hash characters are not valid in usernames or titles generally.
1314 return array( $userObj, Block
::TYPE_USER
);
1316 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1317 # Autoblock reference in the form "#12345"
1318 return array( substr( $target, 1 ), Block
::TYPE_AUTO
);
1322 return array( null, null );
1327 * Get the type of target for this particular block
1328 * @return int Block::TYPE_ constant, will never be TYPE_ID
1330 public function getType() {
1337 * Get the target and target type for this particular Block. Note that for autoblocks,
1338 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1339 * in this situation.
1340 * @return array( User|String, Block::TYPE_ constant )
1341 * @todo FIXME: This should be an integral part of the Block member variables
1343 public function getTargetAndType() {
1344 return array( $this->getTarget(), $this->getType() );
1348 * Get the target for this particular Block. Note that for autoblocks,
1349 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1350 * in this situation.
1351 * @return User|string
1353 public function getTarget() {
1354 return $this->target
;
1360 * @return mixed|string
1362 public function getExpiry() {
1363 return $this->mExpiry
;
1367 * Set the target for this block, and update $this->type accordingly
1368 * @param mixed $target
1370 public function setTarget( $target ) {
1371 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1375 * Get the user who implemented this block
1376 * @return User|string Local User object or string for a foreign user
1378 public function getBlocker() {
1379 return $this->blocker
;
1383 * Set the user who implemented (or will implement) this block
1384 * @param User|string $user Local User object or username string for foreign users
1386 public function setBlocker( $user ) {
1387 $this->blocker
= $user;
1391 * Get the key and parameters for the corresponding error message.
1394 * @param IContextSource $context
1397 public function getPermissionsError( IContextSource
$context ) {
1398 $blocker = $this->getBlocker();
1399 if ( $blocker instanceof User
) { // local user
1400 $blockerUserpage = $blocker->getUserPage();
1401 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1402 } else { // foreign user
1406 $reason = $this->mReason
;
1407 if ( $reason == '' ) {
1408 $reason = $context->msg( 'blockednoreason' )->text();
1411 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1412 * This could be a username, an IP range, or a single IP. */
1413 $intended = $this->getTarget();
1415 $lang = $context->getLanguage();
1417 $this->mAuto ?
'autoblockedtext' : 'blockedtext',
1420 $context->getRequest()->getIP(),
1423 $lang->formatExpiry( $this->mExpiry
),
1425 $lang->userTimeAndDate( $this->mTimestamp
, $context->getUser() ),