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 * 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 * @param $killExpired Boolean: delete expired blocks on load
98 * @return Block Object
99 * @deprecated since 1.18
101 public static function newFromDB( $address, $user = 0 ) {
102 return self
::newFromTarget( User
::whoIs( $user ), $address );
106 * Load a blocked user from their block id.
108 * @param $id Integer: Block id to search for
109 * @return Block object
111 public static function newFromID( $id ) {
112 $dbr = wfGetDB( DB_SLAVE
);
113 $res = $dbr->selectRow(
116 array( 'ipb_id' => $id ),
119 return Block
::newFromRow( $res );
123 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
124 * the blocking user or the block timestamp, only things which affect the blocked user *
127 public function equals( Block
$block ) {
129 (string)$this->target
== (string)$block->target
130 && $this->type
== $block->type
131 && $this->mAuto
== $block->mAuto
132 && $this->isHardblock() == $block->isHardblock()
133 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
134 && $this->mExpiry
== $block->mExpiry
135 && $this->isAutoblocking() == $block->isAutoblocking()
136 && $this->mHideName
== $block->mHideName
137 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
138 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
139 && $this->mReason
== $block->mReason
144 * Clear all member variables in the current object. Does not clear
145 * the block from the DB.
146 * @deprecated since 1.18
148 public function clear() {
153 * Get a block from the DB, with either the given address or the given username
155 * @param $address string The IP address of the user, or blank to skip IP blocks
156 * @param $user int The user ID, or zero for anonymous users
157 * @param $killExpired bool Whether to delete expired rows while loading
158 * @return Boolean: the user is blocked from editing
159 * @deprecated since 1.18
161 public function load( $address = '', $user = 0 ) {
162 wfDeprecated( __METHOD__
);
164 $username = User
::whoIs( $user );
165 $block = self
::newFromTarget( $username, $address );
167 $block = self
::newFromTarget( null, $address );
170 if( $block instanceof Block
){
171 # This is mildly evil, but hey, it's B/C :D
172 foreach( $block as $variable => $value ){
173 $this->$variable = $value;
182 * Load a block from the database which affects the already-set $this->target:
183 * 1) A block directly on the given user or IP
184 * 2) A rangeblock encompasing the given IP (smallest first)
185 * 3) An autoblock on the given IP
186 * @param $vagueTarget User|String also search for blocks affecting this target. Doesn't
187 * make any sense to use TYPE_AUTO / TYPE_ID here
188 * @return Bool whether a relevant block was found
190 protected function newLoad( $vagueTarget = null ) {
191 $db = wfGetDB( $this->mFromMaster ? DB_MASTER
: DB_SLAVE
);
193 if( $this->type
!== null ){
195 'ipb_address' => array( (string)$this->target
),
198 $conds = array( 'ipb_address' => array() );
201 if( $vagueTarget !== null ){
202 list( $target, $type ) = self
::parseTarget( $vagueTarget );
204 case self
::TYPE_USER
:
205 # Slightly wierd, but who are we to argue?
206 $conds['ipb_address'][] = (string)$target;
210 $conds['ipb_address'][] = (string)$target;
211 $conds[] = self
::getRangeCond( IP
::toHex( $target ) );
212 $conds = $db->makeList( $conds, LIST_OR
);
215 case self
::TYPE_RANGE
:
216 list( $start, $end ) = IP
::parseRange( $target );
217 $conds['ipb_address'][] = (string)$target;
218 $conds[] = self
::getRangeCond( $start, $end );
219 $conds = $db->makeList( $conds, LIST_OR
);
223 throw new MWException( "Tried to load block with invalid type" );
227 $res = $db->select( 'ipblocks', '*', $conds, __METHOD__
);
229 # This result could contain a block on the user, a block on the IP, and a russian-doll
230 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
233 # Lower will be better
234 $bestBlockScore = 100;
236 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
237 $bestBlockPreventsEdit = null;
239 foreach( $res as $row ){
240 $block = Block
::newFromRow( $row );
242 # Don't use expired blocks
243 if( $block->deleteIfExpired() ){
247 # Don't use anon only blocks on users
248 if( $this->type
== self
::TYPE_USER
&& !$block->isHardblock() ){
252 if( $block->getType() == self
::TYPE_RANGE
){
253 # This is the number of bits that are allowed to vary in the block, give
254 # or take some floating point errors
255 $end = wfBaseconvert( $block->getRangeEnd(), 16, 10 );
256 $start = wfBaseconvert( $block->getRangeStart(), 16, 10 );
257 $size = log( $end - $start +
1, 2 );
259 # This has the nice property that a /32 block is ranked equally with a
260 # single-IP block, which is exactly what it is...
261 $score = self
::TYPE_RANGE
- 1 +
( $size / 128 );
264 $score = $block->getType();
267 if( $score < $bestBlockScore ){
268 $bestBlockScore = $score;
270 $bestBlockPreventsEdit = $block->prevents( 'edit' );
274 if( $bestRow !== null ){
275 $this->initFromRow( $bestRow );
276 $this->prevents( 'edit', $bestBlockPreventsEdit );
284 * Get a set of SQL conditions which will select rangeblocks encompasing a given range
285 * @param $start String Hexadecimal IP representation
286 * @param $end String Hexadecimal IP represenation, or null to use $start = $end
289 public static function getRangeCond( $start, $end = null ) {
290 if ( $end === null ) {
293 # Per bug 14634, we want to include relevant active rangeblocks; for
294 # rangeblocks, we want to include larger ranges which enclose the given
295 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
296 # so we can improve performance by filtering on a LIKE clause
297 $chunk = self
::getIpFragment( $start );
298 $dbr = wfGetDB( DB_SLAVE
);
299 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
301 # Fairly hard to make a malicious SQL statement out of hex characters,
302 # but stranger things have happened...
303 $safeStart = $dbr->addQuotes( $start );
304 $safeEnd = $dbr->addQuotes( $end );
306 return $dbr->makeList(
308 "ipb_range_start $like",
309 "ipb_range_start <= $safeStart",
310 "ipb_range_end >= $safeEnd",
317 * Get the component of an IP address which is certain to be the same between an IP
318 * address and a rangeblock containing that IP address.
319 * @param $hex String Hexadecimal IP representation
322 protected static function getIpFragment( $hex ) {
323 global $wgBlockCIDRLimit;
324 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
325 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
327 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
332 * Given a database row from the ipblocks table, initialize
334 * @param $row ResultWrapper: a row from the ipblocks table
336 protected function initFromRow( $row ) {
337 $this->setTarget( $row->ipb_address
);
338 $this->setBlocker( User
::newFromId( $row->ipb_by
) );
340 $this->mReason
= $row->ipb_reason
;
341 $this->mTimestamp
= wfTimestamp( TS_MW
, $row->ipb_timestamp
);
342 $this->mAuto
= $row->ipb_auto
;
343 $this->mHideName
= $row->ipb_deleted
;
344 $this->mId
= $row->ipb_id
;
345 $this->mExpiry
= $row->ipb_expiry
;
347 $this->isHardblock( !$row->ipb_anon_only
);
348 $this->isAutoblocking( $row->ipb_enable_autoblock
);
350 $this->prevents( 'createaccount', $row->ipb_create_account
);
351 $this->prevents( 'sendemail', $row->ipb_block_email
);
352 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk
);
356 * Create a new Block object from a database row
357 * @param $row ResultWrapper row from the ipblocks table
360 public static function newFromRow( $row ){
362 $block->initFromRow( $row );
367 * Delete the row from the IP blocks table.
371 public function delete() {
372 if ( wfReadOnly() ) {
376 if ( !$this->getId() ) {
377 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
380 $dbw = wfGetDB( DB_MASTER
);
381 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->getId() ), __METHOD__
);
383 return $dbw->affectedRows() > 0;
387 * Insert a block into the block table. Will fail if there is a conflicting
388 * block (same name and options) already in the database.
390 * @return mixed: false on failure, assoc array on success:
391 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
393 public function insert( $dbw = null ) {
394 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
396 if ( $dbw === null ) {
397 $dbw = wfGetDB( DB_MASTER
);
400 # Don't collide with expired blocks
401 Block
::purgeExpired();
403 $ipb_id = $dbw->nextSequenceValue( 'ipblocks_ipb_id_seq' );
406 $this->getDatabaseArray(),
410 $affected = $dbw->affectedRows();
413 $auto_ipd_ids = $this->doRetroactiveAutoblock();
414 return array( 'id' => $ipb_id, 'autoIds' => $auto_ipd_ids );
421 * Update a block in the DB with new parameters.
422 * The ID field needs to be loaded first.
424 public function update() {
425 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
426 $dbw = wfGetDB( DB_MASTER
);
430 $this->getDatabaseArray( $dbw ),
431 array( 'ipb_id' => $this->getId() ),
435 return $dbw->affectedRows();
439 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
440 * @param $db DatabaseBase
443 protected function getDatabaseArray( $db = null ){
445 $db = wfGetDB( DB_SLAVE
);
449 'ipb_address' => (string)$this->target
,
450 'ipb_user' => $this->target
instanceof User ?
$this->target
->getID() : 0,
451 'ipb_by' => $this->getBlocker()->getId(),
452 'ipb_by_text' => $this->getBlocker()->getName(),
453 'ipb_reason' => $this->mReason
,
454 'ipb_timestamp' => $db->timestamp( $this->mTimestamp
),
455 'ipb_auto' => $this->mAuto
,
456 'ipb_anon_only' => !$this->isHardblock(),
457 'ipb_create_account' => $this->prevents( 'createaccount' ),
458 'ipb_enable_autoblock' => $this->isAutoblocking(),
459 'ipb_expiry' => $db->encodeExpiry( $this->mExpiry
),
460 'ipb_range_start' => $this->getRangeStart(),
461 'ipb_range_end' => $this->getRangeEnd(),
462 'ipb_deleted' => intval( $this->mHideName
), // typecast required for SQLite
463 'ipb_block_email' => $this->prevents( 'sendemail' ),
464 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' )
471 * Retroactively autoblocks the last IP used by the user (if it is a user)
472 * blocked by this Block.
474 * @return Array: block IDs of retroactive autoblocks made
476 protected function doRetroactiveAutoblock() {
479 $dbr = wfGetDB( DB_SLAVE
);
480 # If autoblock is enabled, autoblock the LAST IP used
481 # - stolen shamelessly from CheckUser_body.php
483 if ( $this->isAutoblocking() && $this->getType() == self
::TYPE_USER
) {
484 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
486 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
487 $conds = array( 'rc_user_text' => (string)$this->getTarget() );
489 if ( $this->mAngryAutoblock
) {
490 // Block any IP used in the last 7 days. Up to five IPs.
491 $conds[] = 'rc_timestamp < ' .
492 $dbr->addQuotes( $dbr->timestamp( time() - ( 7 * 86400 ) ) );
493 $options['LIMIT'] = 5;
495 // Just the last IP used.
496 $options['LIMIT'] = 1;
499 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
500 __METHOD__
, $options );
502 if ( !$dbr->numRows( $res ) ) {
503 # No results, don't autoblock anything
504 wfDebug( "No IP found to retroactively autoblock\n" );
506 foreach ( $res as $row ) {
508 $id = $this->doAutoblock( $row->rc_ip
);
509 if ( $id ) $blockIds[] = $id;
518 * Checks whether a given IP is on the autoblock whitelist.
519 * TODO: this probably belongs somewhere else, but not sure where...
521 * @param $ip String: The IP to check
524 public static function isWhitelistedFromAutoblocks( $ip ) {
527 // Try to get the autoblock_whitelist from the cache, as it's faster
528 // than getting the msg raw and explode()'ing it.
529 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
530 $lines = $wgMemc->get( $key );
532 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
533 $wgMemc->set( $key, $lines, 3600 * 24 );
536 wfDebug( "Checking the autoblock whitelist..\n" );
538 foreach ( $lines as $line ) {
540 if ( substr( $line, 0, 1 ) !== '*' ) {
544 $wlEntry = substr( $line, 1 );
545 $wlEntry = trim( $wlEntry );
547 wfDebug( "Checking $ip against $wlEntry..." );
549 # Is the IP in this range?
550 if ( IP
::isInRange( $ip, $wlEntry ) ) {
551 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
554 wfDebug( " No match\n" );
562 * Autoblocks the given IP, referring to this Block.
564 * @param $autoblockIP String: the IP to autoblock.
565 * @return mixed: block ID if an autoblock was inserted, false if not.
567 public function doAutoblock( $autoblockIP ) {
568 # If autoblocks are disabled, go away.
569 if ( !$this->isAutoblocking() ) {
573 # Check for presence on the autoblock whitelist
574 if ( self
::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
578 # # Allow hooks to cancel the autoblock.
579 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
580 wfDebug( "Autoblock aborted by hook.\n" );
584 # It's okay to autoblock. Go ahead and create/insert the block.
586 $ipblock = Block
::newFromTarget( $autoblockIP );
588 # If the user is already blocked. Then check if the autoblock would
589 # exceed the user block. If it would exceed, then do nothing, else
591 if ( $this->mExpiry
> Block
::getAutoblockExpiry( $ipblock->mTimestamp
)
593 # If the block is an autoblock, reset its timestamp to now and its expiry
594 # to an $wgAutoblockExpiry in the future; otherwise do nothing
595 $ipblock->updateTimestamp();
601 # Make a new block object with the desired properties
602 $autoblock = new Block
;
603 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
604 $autoblock->setTarget( $autoblockIP );
605 $autoblock->setBlocker( $this->getBlocker() );
606 $autoblock->mReason
= wfMsgForContent( 'autoblocker', $this->getTarget(), $this->mReason
);
607 $autoblock->mTimestamp
= wfTimestampNow();
608 $autoblock->mAuto
= 1;
609 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
610 # Continue suppressing the name if needed
611 $autoblock->mHideName
= $this->mHideName
;
612 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
614 $dbr = wfGetDB( DB_READ
);
615 if ( $this->mTimestamp
== $dbr->getInfinity() ) {
616 # Original block was indefinite, start an autoblock now
617 $autoblock->mExpiry
= Block
::getAutoblockExpiry( wfTimestampNow() );
619 # If the user is already blocked with an expiry date, we don't
620 # want to pile on top of that.
621 $autoblock->mExpiry
= min( $this->mExpiry
, Block
::getAutoblockExpiry( wfTimestampNow() ) );
625 $status = $autoblock->insert();
632 * Check if a block has expired. Delete it if it is.
635 public function deleteIfExpired() {
636 wfProfileIn( __METHOD__
);
638 if ( $this->isExpired() ) {
639 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
643 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
647 wfProfileOut( __METHOD__
);
652 * Has the block expired?
655 public function isExpired() {
656 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
658 if ( !$this->mExpiry
) {
661 return wfTimestampNow() > $this->mExpiry
;
666 * Is the block address valid (i.e. not a null string?)
669 public function isValid() {
670 return $this->getTarget() != null;
674 * Update the timestamp on autoblocks.
676 public function updateTimestamp() {
677 if ( $this->mAuto
) {
678 $this->mTimestamp
= wfTimestamp();
679 $this->mExpiry
= Block
::getAutoblockExpiry( $this->mTimestamp
);
681 $dbw = wfGetDB( DB_MASTER
);
682 $dbw->update( 'ipblocks',
684 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp
),
685 'ipb_expiry' => $dbw->timestamp( $this->mExpiry
),
688 'ipb_address' => (string)$this->getTarget()
696 * Get the IP address at the start of the range in Hex form
697 * @return String IP in Hex form
699 public function getRangeStart() {
700 switch( $this->type
) {
701 case self
::TYPE_USER
:
704 return IP
::toHex( $this->target
);
705 case self
::TYPE_RANGE
:
706 list( $start, /*...*/ ) = IP
::parseRange( $this->target
);
708 default: throw new MWException( "Block with invalid type" );
713 * Get the IP address at the start of the range in Hex form
714 * @return String IP in Hex form
716 public function getRangeEnd() {
717 switch( $this->type
) {
718 case self
::TYPE_USER
:
721 return IP
::toHex( $this->target
);
722 case self
::TYPE_RANGE
:
723 list( /*...*/, $end ) = IP
::parseRange( $this->target
);
725 default: throw new MWException( "Block with invalid type" );
730 * Get the user id of the blocking sysop
734 public function getBy() {
735 return $this->getBlocker() instanceof User
736 ?
$this->getBlocker()->getId()
741 * Get the username of the blocking sysop
745 public function getByName() {
746 return $this->getBlocker() instanceof User
747 ?
$this->getBlocker()->getName()
755 public function getId() {
760 * Get/set the SELECT ... FOR UPDATE flag
761 * @deprecated since 1.18
763 public function forUpdate( $x = null ) {
768 * Get/set a flag determining whether the master is used for reads
770 public function fromMaster( $x = null ) {
771 return wfSetVar( $this->mFromMaster
, $x );
775 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range
779 public function isHardblock( $x = null ) {
780 wfSetVar( $this->isHardblock
, $x );
782 # You can't *not* hardblock a user
783 return $this->getType() == self
::TYPE_USER
785 : $this->isHardblock
;
788 public function isAutoblocking( $x = null ) {
789 wfSetVar( $this->isAutoblocking
, $x );
791 # You can't put an autoblock on an IP or range as we don't have any history to
792 # look over to get more IPs from
793 return $this->getType() == self
::TYPE_USER
794 ?
$this->isAutoblocking
799 * Get/set whether the Block prevents a given action
800 * @param $action String
804 public function prevents( $action, $x = null ) {
807 # For now... <evil laugh>
810 case 'createaccount':
811 return wfSetVar( $this->mCreateAccount
, $x );
814 return wfSetVar( $this->mBlockEmail
, $x );
816 case 'editownusertalk':
817 return wfSetVar( $this->mDisableUsertalk
, $x );
825 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
826 * @return String, text is escaped
828 public function getRedactedName() {
829 if ( $this->mAuto
) {
830 return HTML
::rawElement(
832 array( 'class' => 'mw-autoblockid' ),
833 wfMessage( 'autoblockid', $this->mId
)
836 return htmlspecialchars( $this->getTarget() );
841 * Encode expiry for DB
843 * @param $expiry String: timestamp for expiry, or
844 * @param $db Database object
846 * @deprecated since 1.18; use $dbw->encodeExpiry() instead
848 public static function encodeExpiry( $expiry, $db ) {
849 return $db->encodeExpiry( $expiry );
853 * Decode expiry which has come from the DB
855 * @param $expiry String: Database expiry format
856 * @param $timestampType Requested timestamp format
858 * @deprecated since 1.18; use $wgLang->decodeExpiry() instead
860 public static function decodeExpiry( $expiry, $timestampType = TS_MW
) {
862 return $wgContLang->formatExpiry( $expiry, $timestampType );
866 * Get a timestamp of the expiry for autoblocks
870 public static function getAutoblockExpiry( $timestamp ) {
871 global $wgAutoblockExpiry;
873 return wfTimestamp( TS_MW
, wfTimestamp( TS_UNIX
, $timestamp ) +
$wgAutoblockExpiry );
877 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
878 * For example, 127.111.113.151/24 -> 127.111.113.0/24
879 * @param $range String: IP address to normalize
881 * @deprecated since 1.18, call IP::sanitizeRange() directly
883 public static function normaliseRange( $range ) {
884 return IP
::sanitizeRange( $range );
888 * Purge expired blocks from the ipblocks table
890 public static function purgeExpired() {
891 $dbw = wfGetDB( DB_MASTER
);
892 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__
);
896 * Get a value to insert into expiry field of the database when infinite expiry
898 * @deprecated since 1.18, call $dbr->getInfinity() directly
901 public static function infinity() {
902 return wfGetDB( DB_SLAVE
)->getInfinity();
906 * Convert a DB-encoded expiry into a real string that humans can read.
908 * @param $encoded_expiry String: Database encoded expiry time
909 * @return Html-escaped String
910 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
912 public static function formatExpiry( $encoded_expiry ) {
916 if ( is_null( $msg ) ) {
918 $keys = array( 'infiniteblock', 'expiringblock' );
920 foreach ( $keys as $key ) {
921 $msg[$key] = wfMsgHtml( $key );
925 $expiry = $wgContLang->formatExpiry( $encoded_expiry, TS_MW
);
926 if ( $expiry == wfGetDB( DB_SLAVE
)->getInfinity() ) {
927 $expirystr = $msg['infiniteblock'];
930 $expiredatestr = htmlspecialchars( $wgLang->date( $expiry, true ) );
931 $expiretimestr = htmlspecialchars( $wgLang->time( $expiry, true ) );
932 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array( $expiredatestr, $expiretimestr ) );
939 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
940 * ("24 May 2034"), into an absolute timestamp we can put into the database.
941 * @param $expiry String: whatever was typed into the form
942 * @return String: timestamp or "infinity" string for th DB implementation
943 * @deprecated since 1.18 moved to SpecialBlock::parseExpiryInput()
945 public static function parseExpiryInput( $expiry ) {
946 wfDeprecated( __METHOD__
);
947 return SpecialBlock
::parseExpiryInput( $expiry );
951 * Given a target and the target's type, get an existing Block object if possible.
952 * @param $specificTarget String|User|Int a block target, which may be one of several types:
953 * * A user to block, in which case $target will be a User
954 * * An IP to block, in which case $target will be a User generated by using
955 * User::newFromName( $ip, false ) to turn off name validation
956 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
957 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
959 * Calling this with a user, IP address or range will not select autoblocks, and will
960 * only select a block where the targets match exactly (so looking for blocks on
961 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
962 * @param $vagueTarget String|User|Int as above, but we will search for *any* block which
963 * affects that target (so for an IP address, get ranges containing that IP; and also
964 * get any relevant autoblocks)
965 * @param $fromMaster Bool whether to use the DB_MASTER database
966 * @return Block|null (null if no relevant block could be found). The target and type
967 * of the returned Block will refer to the actual block which was found, which might
968 * not be the same as the target you gave if you used $vagueTarget!
970 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
971 list( $target, $type ) = self
::parseTarget( $specificTarget );
972 if( $type == Block
::TYPE_ID ||
$type == Block
::TYPE_AUTO
){
973 return Block
::newFromID( $target );
975 } elseif( $target === null && $vagueTarget === null ){
976 # We're not going to find anything useful here
979 } elseif( in_array( $type, array( Block
::TYPE_USER
, Block
::TYPE_IP
, Block
::TYPE_RANGE
, null ) ) ) {
980 $block = new Block();
981 $block->fromMaster( $fromMaster );
983 if( $type !== null ){
984 $block->setTarget( $target );
987 if( $block->newLoad( $vagueTarget ) ){
998 * From an existing Block, get the target and the type of target. Note that it is
999 * always safe to treat the target as a string; for User objects this will return
1000 * User::__toString() which in turn gives User::getName().
1001 * @return array( User|String, Block::TYPE_ constant )
1003 public static function parseTarget( $target ) {
1004 $target = trim( $target );
1006 # We may have been through this before
1007 if( $target instanceof User
){
1008 if( IP
::isValid( $target->getName() ) ){
1009 return self
::TYPE_IP
;
1011 return self
::TYPE_USER
;
1013 } elseif( $target === null ){
1014 return array( null, null );
1017 $userObj = User
::newFromName( $target );
1018 if ( $userObj instanceof User
) {
1019 # Note that since numbers are valid usernames, a $target of "12345" will be
1020 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1021 # since hash characters are not valid in usernames or titles generally.
1022 return array( $userObj, Block
::TYPE_USER
);
1024 } elseif ( IP
::isValid( $target ) ) {
1025 # We can still create a User if it's an IP address, but we need to turn
1026 # off validation checking (which would exclude IP addresses)
1028 User
::newFromName( IP
::sanitizeIP( $target ), false ),
1032 } elseif ( IP
::isValidBlock( $target ) ) {
1033 # Can't create a User from an IP range
1034 return array( IP
::sanitizeRange( $target ), Block
::TYPE_RANGE
);
1036 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1037 # Autoblock reference in the form "#12345"
1038 return array( substr( $target, 1 ), Block
::TYPE_AUTO
);
1042 return array( null, null );
1047 * Get the type of target for this particular block
1048 * @return Block::TYPE_ constant, will never be TYPE_ID
1050 public function getType() {
1057 * Get the target and target type for this particular Block. Note that for autoblocks,
1058 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1059 * in this situation.
1060 * @return array( User|String, Block::TYPE_ constant )
1061 * FIXME: this should be an integral part of the Block member variables
1063 public function getTargetAndType() {
1064 return array( $this->getTarget(), $this->getType() );
1068 * Get the target 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 User|String
1073 public function getTarget() {
1074 return $this->target
;
1078 * Set the target for this block, and update $this->type accordingly
1079 * @param $target Mixed
1081 public function setTarget( $target ){
1082 list( $this->target
, $this->type
) = self
::parseTarget( $target );
1086 * Get the user who implemented this block
1089 public function getBlocker(){
1090 return $this->blocker
;
1094 * Set the user who implemented (or will implement) this block
1097 public function setBlocker( User
$user ){
1098 $this->blocker
= $user;