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, $mAngryAutoblock;
36 /// @var Block::TYPE_ constant. Can only be USER, IP or RANGE internally
43 protected $isHardblock = true;
46 protected $isAutoblocking = true;
57 * @todo FIXME: Don't know what the best format to have for this constructor is, but fourteen
58 * optional parameters certainly isn't it.
60 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
61 $timestamp = 0, $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
62 $hideName = 0, $blockEmail = 0, $allowUsertalk = 0 )
64 if( $timestamp === 0 ){
65 $timestamp = wfTimestampNow();
68 if( count( func_get_args() ) > 0 ){
70 # wfDeprecated( __METHOD__ . " with arguments" );
73 $this->setTarget( $address );
74 $this->setBlocker( User
::newFromID( $by ) );
75 $this->mReason
= $reason;
76 $this->mTimestamp
= wfTimestamp( TS_MW
, $timestamp );
78 $this->isHardblock( !$anonOnly );
79 $this->prevents( 'createaccount', $createAccount );
80 $this->mExpiry
= $expiry;
81 $this->isAutoblocking( $enableAutoblock );
82 $this->mHideName
= $hideName;
83 $this->prevents( 'sendemail', $blockEmail );
84 $this->prevents( 'editownusertalk', !$allowUsertalk );
86 $this->mFromMaster
= false;
87 $this->mAngryAutoblock
= false;
91 * Load a block from the database, using either the IP address or
92 * user ID. Tries the user ID first, and if that doesn't work, tries
95 * @param $address String: IP address of user/anon
96 * @param $user Integer: user id of user
97 * @return Block Object
98 * @deprecated since 1.18
100 public static function newFromDB( $address, $user = 0 ) {
101 return self
::newFromTarget( User
::whoIs( $user ), $address );
105 * Load a blocked user from their block id.
107 * @param $id Integer: Block id to search for
108 * @return Block object
110 public static function newFromID( $id ) {
111 $dbr = wfGetDB( DB_SLAVE
);
112 $res = $dbr->selectRow(
115 array( 'ipb_id' => $id ),
118 return Block
::newFromRow( $res );
122 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
123 * the blocking user or the block timestamp, only things which affect the blocked user *
125 * @param $block Block
129 public function equals( Block
$block ) {
131 (string)$this->target
== (string)$block->target
132 && $this->type
== $block->type
133 && $this->mAuto
== $block->mAuto
134 && $this->isHardblock() == $block->isHardblock()
135 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
136 && $this->mExpiry
== $block->mExpiry
137 && $this->isAutoblocking() == $block->isAutoblocking()
138 && $this->mHideName
== $block->mHideName
139 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
140 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
141 && $this->mReason
== $block->mReason
146 * Clear all member variables in the current object. Does not clear
147 * the block from the DB.
148 * @deprecated since 1.18
150 public function clear() {
155 * Get a block from the DB, with either the given address or the given username
157 * @param $address string The IP address of the user, or blank to skip IP blocks
158 * @param $user int The user ID, or zero for anonymous users
159 * @param $killExpired bool Whether to delete expired rows while loading
160 * @return Boolean: the user is blocked from editing
161 * @deprecated since 1.18
163 public function load( $address = '', $user = 0 ) {
164 wfDeprecated( __METHOD__
);
166 $username = User
::whoIs( $user );
167 $block = self
::newFromTarget( $username, $address );
169 $block = self
::newFromTarget( null, $address );
172 if( $block instanceof Block
){
173 # This is mildly evil, but hey, it's B/C :D
174 foreach( $block as $variable => $value ){
175 $this->$variable = $value;
184 * Load a block from the database which affects the already-set $this->target:
185 * 1) A block directly on the given user or IP
186 * 2) A rangeblock encompasing the given IP (smallest first)
187 * 3) An autoblock on the given IP
188 * @param $vagueTarget User|String also search for blocks affecting this target. Doesn't
189 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
190 * @return Bool whether a relevant block was found
192 protected function newLoad( $vagueTarget = null ) {
193 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_SLAVE
);
195 if( $this->type
!== null ){
197 'ipb_address' => array( (string)$this->target
),
200 $conds = array( 'ipb_address' => array() );
203 # Be aware that the != '' check is explicit, since empty values will be passed by some callers.
204 if( $vagueTarget != ''){
205 list( $target, $type ) = self
::parseTarget( $vagueTarget );
207 case self
::TYPE_USER
:
208 # Slightly wierd, but who are we to argue?
209 $conds['ipb_address'][] = (string)$target;
213 $conds['ipb_address'][] = (string)$target;
214 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
215 $conds = $db->makeList( $conds, LIST_OR
);
218 case self
::TYPE_RANGE
:
219 list( $start, $end ) = IP
::parseRange( $target );
220 $conds['ipb_address'][] = (string)$target;
221 $conds[] = self
::getRangeCond( $start, $end );
222 $conds = $db->makeList( $conds, LIST_OR
);
226 throw new MWException( "Tried to load block with invalid type" );
230 $res = $db->select( 'ipblocks', '*', $conds, __METHOD__
);
232 # This result could contain a block on the user, a block on the IP, and a russian-doll
233 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
236 # Lower will be better
237 $bestBlockScore = 100;
239 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
240 $bestBlockPreventsEdit = null;
242 foreach( $res as $row ){
243 $block = Block
::newFromRow( $row );
245 # Don't use expired blocks
246 if( $block->deleteIfExpired() ){
250 # Don't use anon only blocks on users
251 if( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ){
255 if( $block->getType() == self
::TYPE_RANGE
){
256 # This is the number of bits that are allowed to vary in the block, give
257 # or take some floating point errors
258 $end = wfBaseconvert( $block->getRangeEnd(), 16, 10 );
259 $start = wfBaseconvert( $block->getRangeStart(), 16, 10 );
260 $size = log( $end - $start +
1, 2 );
262 # This has the nice property that a /32 block is ranked equally with a
263 # single-IP block, which is exactly what it is...
264 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
267 $score = $block->getType();
270 if( $score < $bestBlockScore ){
271 $bestBlockScore = $score;
273 $bestBlockPreventsEdit = $block->prevents( 'edit' );
277 if( $bestRow !== null ){
278 $this->initFromRow( $bestRow );
279 $this->prevents( 'edit', $bestBlockPreventsEdit );
287 * Get a set of SQL conditions which will select rangeblocks encompasing a given range
288 * @param $start String Hexadecimal IP representation
289 * @param $end String Hexadecimal IP represenation, or null to use $start = $end
292 public static function getRangeCond( $start, $end = null ) {
293 if ( $end === null ) {
296 # Per bug 14634, we want to include relevant active rangeblocks; for
297 # rangeblocks, we want to include larger ranges which enclose the given
298 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
299 # so we can improve performance by filtering on a LIKE clause
300 $chunk = self
::getIpFragment( $start );
301 $dbr = wfGetDB( DB_SLAVE
);
302 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
304 # Fairly hard to make a malicious SQL statement out of hex characters,
305 # but stranger things have happened...
306 $safeStart = $dbr->addQuotes( $start );
307 $safeEnd = $dbr->addQuotes( $end );
309 return $dbr->makeList(
311 "ipb_range_start $like",
312 "ipb_range_start <= $safeStart",
313 "ipb_range_end >= $safeEnd",
320 * Get the component of an IP address which is certain to be the same between an IP
321 * address and a rangeblock containing that IP address.
322 * @param $hex String Hexadecimal IP representation
325 protected static function getIpFragment( $hex ) {
326 global $wgBlockCIDRLimit;
327 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
328 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
330 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
335 * Given a database row from the ipblocks table, initialize
337 * @param $row ResultWrapper: a row from the ipblocks table
339 protected function initFromRow( $row ) {
340 $this->setTarget( $row->ipb_address
);
341 $this->setBlocker( User
::newFromId( $row->ipb_by
) );
343 $this->mReason
= $row->ipb_reason
;
344 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
345 $this->mAuto
= $row->ipb_auto
;
346 $this->mHideName
= $row->ipb_deleted
;
347 $this->mId
= $row->ipb_id
;
348 $this->mExpiry
= $row->ipb_expiry
;
350 $this->isHardblock( !$row->ipb_anon_only
);
351 $this->isAutoblocking( $row->ipb_enable_autoblock
);
353 $this->prevents( 'createaccount', $row->ipb_create_account
);
354 $this->prevents( 'sendemail', $row->ipb_block_email
);
355 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk
);
359 * Create a new Block object from a database row
360 * @param $row ResultWrapper row from the ipblocks table
363 public static function newFromRow( $row ){
365 $block->initFromRow( $row );
370 * Delete the row from the IP blocks table.
374 public function delete() {
375 if ( wfReadOnly() ) {
379 if ( !$this->getId() ) {
380 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
383 $dbw = wfGetDB( DB_MASTER
);
384 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->getId() ), __METHOD__
);
386 return $dbw->affectedRows() > 0;
390 * Insert a block into the block table. Will fail if there is a conflicting
391 * block (same name and options) already in the database.
393 * @return mixed: false on failure, assoc array on success:
394 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
396 public function insert( $dbw = null ) {
397 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
399 if ( $dbw === null ) {
400 $dbw = wfGetDB( DB_MASTER
);
403 # Don't collide with expired blocks
404 Block
::purgeExpired();
406 $ipb_id = $dbw->nextSequenceValue( 'ipblocks_ipb_id_seq' );
409 $this->getDatabaseArray(),
413 $affected = $dbw->affectedRows();
416 $auto_ipd_ids = $this->doRetroactiveAutoblock();
417 return array( 'id' => $ipb_id, 'autoIds' => $auto_ipd_ids );
424 * Update a block in the DB with new parameters.
425 * The ID field needs to be loaded first.
427 public function update() {
428 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
429 $dbw = wfGetDB( DB_MASTER
);
433 $this->getDatabaseArray( $dbw ),
434 array( 'ipb_id' => $this->getId() ),
438 return $dbw->affectedRows();
442 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
443 * @param $db DatabaseBase
446 protected function getDatabaseArray( $db = null ){
448 $db = wfGetDB( DB_SLAVE
);
450 $this->mExpiry
= $db->encodeExpiry( $this->mExpiry
);
453 'ipb_address' => (string)$this->target
,
454 'ipb_user' => $this->target
instanceof User ?
$this->target
->getID() : 0,
455 'ipb_by' => $this->getBlocker()->getId(),
456 'ipb_by_text' => $this->getBlocker()->getName(),
457 'ipb_reason' => $this->mReason
,
458 'ipb_timestamp' => $db->timestamp( $this->mTimestamp
),
459 'ipb_auto' => $this->mAuto
,
460 'ipb_anon_only' => !$this->isHardblock(),
461 'ipb_create_account' => $this->prevents( 'createaccount' ),
462 'ipb_enable_autoblock' => $this->isAutoblocking(),
463 'ipb_expiry' => $this->mExpiry
,
464 'ipb_range_start' => $this->getRangeStart(),
465 'ipb_range_end' => $this->getRangeEnd(),
466 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
467 'ipb_block_email' => $this->prevents( 'sendemail' ),
468 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' )
475 * Retroactively autoblocks the last IP used by the user (if it is a user)
476 * blocked by this Block.
478 * @return Array: block IDs of retroactive autoblocks made
480 protected function doRetroactiveAutoblock() {
483 $dbr = wfGetDB( DB_SLAVE
);
484 # If autoblock is enabled, autoblock the LAST IP used
485 # - stolen shamelessly from CheckUser_body.php
487 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
488 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
490 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
491 $conds = array( 'rc_user_text' => (string)$this->getTarget() );
493 if ( $this->mAngryAutoblock
) {
494 // Block any IP used in the last 7 days. Up to five IPs.
495 $conds[] = 'rc_timestamp < ' .
496 $dbr->addQuotes( $dbr->timestamp( time() - ( 7 * 86400 ) ) );
497 $options['LIMIT'] = 5;
499 // Just the last IP used.
500 $options['LIMIT'] = 1;
503 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
504 __METHOD__
, $options );
506 if ( !$dbr->numRows( $res ) ) {
507 # No results, don't autoblock anything
508 wfDebug( "No IP found to retroactively autoblock\n" );
510 foreach ( $res as $row ) {
512 $id = $this->doAutoblock( $row->rc_ip
);
513 if ( $id ) $blockIds[] = $id;
522 * Checks whether a given IP is on the autoblock whitelist.
523 * TODO: this probably belongs somewhere else, but not sure where...
525 * @param $ip String: The IP to check
528 public static function isWhitelistedFromAutoblocks( $ip ) {
531 // Try to get the autoblock_whitelist from the cache, as it's faster
532 // than getting the msg raw and explode()'ing it.
533 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
534 $lines = $wgMemc->get( $key );
536 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
537 $wgMemc->set( $key, $lines, 3600 * 24 );
540 wfDebug( "Checking the autoblock whitelist..\n" );
542 foreach ( $lines as $line ) {
544 if ( substr( $line, 0, 1 ) !== '*' ) {
548 $wlEntry = substr( $line, 1 );
549 $wlEntry = trim( $wlEntry );
551 wfDebug( "Checking $ip against $wlEntry..." );
553 # Is the IP in this range?
554 if ( IP
::isInRange( $ip, $wlEntry ) ) {
555 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
558 wfDebug( " No match\n" );
566 * Autoblocks the given IP, referring to this Block.
568 * @param $autoblockIP String: the IP to autoblock.
569 * @return mixed: block ID if an autoblock was inserted, false if not.
571 public function doAutoblock( $autoblockIP ) {
572 # If autoblocks are disabled, go away.
573 if ( !$this->isAutoblocking() ) {
577 # Check for presence on the autoblock whitelist
578 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
582 # # Allow hooks to cancel the autoblock.
583 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
584 wfDebug( "Autoblock aborted by hook.\n" );
588 # It's okay to autoblock. Go ahead and create/insert the block.
590 $ipblock = Block
::newFromTarget( $autoblockIP );
592 # If the user is already blocked. Then check if the autoblock would
593 # exceed the user block. If it would exceed, then do nothing, else
595 if ( $this->mExpiry
> Block
::getAutoblockExpiry( $ipblock->mTimestamp
)
597 # If the block is an autoblock, reset its timestamp to now and its expiry
598 # to an $wgAutoblockExpiry in the future; otherwise do nothing
599 $ipblock->updateTimestamp();
605 # Make a new block object with the desired properties
606 $autoblock = new Block
;
607 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
608 $autoblock->setTarget( $autoblockIP );
609 $autoblock->setBlocker( $this->getBlocker() );
610 $autoblock->mReason
= wfMsgForContent( 'autoblocker', $this->getTarget(), $this->mReason
);
611 $autoblock->mTimestamp
= wfTimestampNow();
612 $autoblock->mAuto
= 1;
613 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
614 # Continue suppressing the name if needed
615 $autoblock->mHideName
= $this->mHideName
;
616 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
618 $dbr = wfGetDB( DB_SLAVE
);
619 if ( $this->mTimestamp
== $dbr->getInfinity() ) {
620 # Original block was indefinite, start an autoblock now
621 $autoblock->mExpiry
= Block
::getAutoblockExpiry( wfTimestampNow() );
623 # If the user is already blocked with an expiry date, we don't
624 # want to pile on top of that.
625 $autoblock->mExpiry
= min( $this->mExpiry
, Block
::getAutoblockExpiry( wfTimestampNow() ) );
629 $status = $autoblock->insert();
636 * Check if a block has expired. Delete it if it is.
639 public function deleteIfExpired() {
640 wfProfileIn( __METHOD__
);
642 if ( $this->isExpired() ) {
643 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
647 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
651 wfProfileOut( __METHOD__
);
656 * Has the block expired?
659 public function isExpired() {
660 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
662 if ( !$this->mExpiry
) {
665 return wfTimestampNow() > $this->mExpiry
;
670 * Is the block address valid (i.e. not a null string?)
673 public function isValid() {
674 return $this->getTarget() != null;
678 * Update the timestamp on autoblocks.
680 public function updateTimestamp() {
681 if ( $this->mAuto
) {
682 $this->mTimestamp
= wfTimestamp();
683 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
685 $dbw = wfGetDB( DB_MASTER
);
686 $dbw->update( 'ipblocks',
688 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
689 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
692 'ipb_address' => (string)$this->getTarget()
700 * Get the IP address at the start of the range in Hex form
701 * @return String IP in Hex form
703 public function getRangeStart() {
704 switch( $this->type
) {
705 case self
::TYPE_USER
:
708 return IP
::toHex( $this->target
);
709 case self
::TYPE_RANGE
:
710 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
712 default: throw new MWException( "Block with invalid type" );
717 * Get the IP address at the start of the range in Hex form
718 * @return String IP in Hex form
720 public function getRangeEnd() {
721 switch( $this->type
) {
722 case self
::TYPE_USER
:
725 return IP
::toHex( $this->target
);
726 case self
::TYPE_RANGE
:
727 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
729 default: throw new MWException( "Block with invalid type" );
734 * Get the user id of the blocking sysop
738 public function getBy() {
739 return $this->getBlocker() instanceof User
740 ?
$this->getBlocker()->getId()
745 * Get the username of the blocking sysop
749 public function getByName() {
750 return $this->getBlocker() instanceof User
751 ?
$this->getBlocker()->getName()
759 public function getId() {
764 * Get/set the SELECT ... FOR UPDATE flag
765 * @deprecated since 1.18
767 public function forUpdate( $x = null ) {
772 * Get/set a flag determining whether the master is used for reads
774 public function fromMaster( $x = null ) {
775 return wfSetVar( $this->mFromMaster
, $x );
779 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range
783 public function isHardblock( $x = null ) {
784 wfSetVar( $this->isHardblock
, $x );
786 # You can't *not* hardblock a user
787 return $this->getType() == self
::TYPE_USER
789 : $this->isHardblock
;
792 public function isAutoblocking( $x = null ) {
793 wfSetVar( $this->isAutoblocking
, $x );
795 # You can't put an autoblock on an IP or range as we don't have any history to
796 # look over to get more IPs from
797 return $this->getType() == self
::TYPE_USER
798 ?
$this->isAutoblocking
803 * Get/set whether the Block prevents a given action
804 * @param $action String
808 public function prevents( $action, $x = null ) {
811 # For now... <evil laugh>
814 case 'createaccount':
815 return wfSetVar( $this->mCreateAccount
, $x );
818 return wfSetVar( $this->mBlockEmail
, $x );
820 case 'editownusertalk':
821 return wfSetVar( $this->mDisableUsertalk
, $x );
829 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
830 * @return String, text is escaped
832 public function getRedactedName() {
833 if ( $this->mAuto
) {
834 return Html
::rawElement(
836 array( 'class' => 'mw-autoblockid' ),
837 wfMessage( 'autoblockid', $this->mId
)
840 return htmlspecialchars( $this->getTarget() );
845 * Encode expiry for DB
847 * @param $expiry String: timestamp for expiry, or
848 * @param $db Database object
850 * @deprecated since 1.18; use $dbw->encodeExpiry() instead
852 public static function encodeExpiry( $expiry, $db ) {
853 return $db->encodeExpiry( $expiry );
857 * Decode expiry which has come from the DB
859 * @param $expiry String: Database expiry format
860 * @param $timestampType Requested timestamp format
862 * @deprecated since 1.18; use $wgLang->decodeExpiry() instead
864 public static function decodeExpiry( $expiry, $timestampType = TS_MW
) {
866 return $wgContLang->formatExpiry( $expiry, $timestampType );
870 * Get a timestamp of the expiry for autoblocks
874 public static function getAutoblockExpiry( $timestamp ) {
875 global $wgAutoblockExpiry;
877 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
881 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
882 * For example, 127.111.113.151/24 -> 127.111.113.0/24
883 * @param $range String: IP address to normalize
885 * @deprecated since 1.18, call IP::sanitizeRange() directly
887 public static function normaliseRange( $range ) {
888 return IP
::sanitizeRange( $range );
892 * Purge expired blocks from the ipblocks table
894 public static function purgeExpired() {
895 $dbw = wfGetDB( DB_MASTER
);
896 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
900 * Get a value to insert into expiry field of the database when infinite expiry
902 * @deprecated since 1.18, call $dbr->getInfinity() directly
905 public static function infinity() {
906 return wfGetDB( DB_SLAVE
)->getInfinity();
910 * Convert a DB-encoded expiry into a real string that humans can read.
912 * @param $encoded_expiry String: Database encoded expiry time
913 * @return Html-escaped String
914 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
916 public static function formatExpiry( $encoded_expiry ) {
920 if ( is_null( $msg ) ) {
922 $keys = array( 'infiniteblock', 'expiringblock' );
924 foreach ( $keys as $key ) {
925 $msg[$key] = wfMsgHtml( $key );
929 $expiry = $wgContLang->formatExpiry( $encoded_expiry, TS_MW
);
930 if ( $expiry == wfGetDB( DB_SLAVE
)->getInfinity() ) {
931 $expirystr = $msg['infiniteblock'];
934 $expiredatestr = htmlspecialchars( $wgLang->date( $expiry, true ) );
935 $expiretimestr = htmlspecialchars( $wgLang->time( $expiry, true ) );
936 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array( $expiredatestr, $expiretimestr ) );
943 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
944 * ("24 May 2034"), into an absolute timestamp we can put into the database.
945 * @param $expiry String: whatever was typed into the form
946 * @return String: timestamp or "infinity" string for th DB implementation
947 * @deprecated since 1.18 moved to SpecialBlock::parseExpiryInput()
949 public static function parseExpiryInput( $expiry ) {
950 wfDeprecated( __METHOD__
);
951 return SpecialBlock
::parseExpiryInput( $expiry );
955 * Given a target and the target's type, get an existing Block object if possible.
956 * @param $specificTarget String|User|Int a block target, which may be one of several types:
957 * * A user to block, in which case $target will be a User
958 * * An IP to block, in which case $target will be a User generated by using
959 * User::newFromName( $ip, false ) to turn off name validation
960 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
961 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
963 * Calling this with a user, IP address or range will not select autoblocks, and will
964 * only select a block where the targets match exactly (so looking for blocks on
965 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
966 * @param $vagueTarget String|User|Int as above, but we will search for *any* block which
967 * affects that target (so for an IP address, get ranges containing that IP; and also
968 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
969 * @param $fromMaster Bool whether to use the DB_MASTER database
970 * @return Block|null (null if no relevant block could be found). The target and type
971 * of the returned Block will refer to the actual block which was found, which might
972 * not be the same as the target you gave if you used $vagueTarget!
974 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
975 # (bug 29116) passing $vagueTarget = '' is not unreasonable here, but int(0)
976 # is a valid username, so we can't just use weak comparisons.
977 if( $vagueTarget === '' ){
981 list( $target, $type ) = self
::parseTarget( $specificTarget );
982 if( $type == Block
::TYPE_ID ||
$type == Block
::TYPE_AUTO
){
983 return Block
::newFromID( $target );
985 } elseif( $target === null && $vagueTarget == '' ){
986 # We're not going to find anything useful here
987 # Be aware that the == '' check is explicit, since empty values will be passed by some callers.
990 } elseif( in_array( $type, array( Block
::TYPE_USER
, Block
::TYPE_IP
, Block
::TYPE_RANGE
, null ) ) ) {
991 $block = new Block();
992 $block->fromMaster( $fromMaster );
994 if( $type !== null ){
995 $block->setTarget( $target );
998 if( $block->newLoad( $vagueTarget ) ){
1009 * From an existing Block, get the target and the type of target. Note that it is
1010 * always safe to treat the target as a string; for User objects this will return
1011 * User::__toString() which in turn gives User::getName().
1012 * @return array( User|String, Block::TYPE_ constant )
1014 public static function parseTarget( $target ) {
1015 $target = trim( $target );
1017 # We may have been through this before
1018 if( $target instanceof User
){
1019 if( IP
::isValid( $target->getName() ) ){
1020 return array( $target, self
::TYPE_IP
);
1022 return array( $target, self
::TYPE_USER
);
1024 } elseif( $target === null ){
1025 return array( null, null );
1028 $userObj = User
::newFromName( $target );
1029 if ( $userObj instanceof User
) {
1030 # Note that since numbers are valid usernames, a $target of "12345" will be
1031 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1032 # since hash characters are not valid in usernames or titles generally.
1033 return array( $userObj, Block
::TYPE_USER
);
1035 } elseif ( IP
::isValid( $target ) ) {
1036 # We can still create a User if it's an IP address, but we need to turn
1037 # off validation checking (which would exclude IP addresses)
1039 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1043 } elseif ( IP
::isValidBlock( $target ) ) {
1044 # Can't create a User from an IP range
1045 return array( IP
::sanitizeRange( $target ), Block
::TYPE_RANGE
);
1047 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1048 # Autoblock reference in the form "#12345"
1049 return array( substr( $target, 1 ), Block
::TYPE_AUTO
);
1053 return array( null, null );
1058 * Get the type of target for this particular block
1059 * @return Block::TYPE_ constant, will never be TYPE_ID
1061 public function getType() {
1068 * Get the target and target type for this particular Block. Note that for autoblocks,
1069 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1070 * in this situation.
1071 * @return array( User|String, Block::TYPE_ constant )
1072 * @todo FIXME: This should be an integral part of the Block member variables
1074 public function getTargetAndType() {
1075 return array( $this->getTarget(), $this->getType() );
1079 * Get the target for this particular Block. Note that for autoblocks,
1080 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1081 * in this situation.
1082 * @return User|String
1084 public function getTarget() {
1085 return $this->target
;
1089 * Set the target for this block, and update $this->type accordingly
1090 * @param $target Mixed
1092 public function setTarget( $target ){
1093 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1097 * Get the user who implemented this block
1100 public function getBlocker(){
1101 return $this->blocker
;
1105 * Set the user who implemented (or will implement) this block
1108 public function setBlocker( User
$user ){
1109 $this->blocker
= $user;