correct typo in r102393
[mediawiki.git] / includes / Block.php
blob7aa1bc1dc81190cdfaaedeec76b5cc983d3f5f30
1 <?php
2 /**
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
20 * @file
22 class Block {
23 /* public*/ var $mReason, $mTimestamp, $mAuto, $mExpiry, $mHideName;
25 protected
26 $mId,
27 $mFromMaster,
29 $mBlockEmail,
30 $mDisableUsertalk,
31 $mCreateAccount;
33 /// @var User|String
34 protected $target;
36 /// @var Block::TYPE_ constant. Can only be USER, IP or RANGE internally
37 protected $type;
39 /// @var User
40 protected $blocker;
42 /// @var Bool
43 protected $isHardblock = true;
45 /// @var Bool
46 protected $isAutoblocking = true;
48 # TYPE constants
49 const TYPE_USER = 1;
50 const TYPE_IP = 2;
51 const TYPE_RANGE = 3;
52 const TYPE_AUTO = 4;
53 const TYPE_ID = 5;
55 /**
56 * Constructor
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, $byText = '' )
64 if( $timestamp === 0 ){
65 $timestamp = wfTimestampNow();
68 if( count( func_get_args() ) > 0 ){
69 # Soon... :D
70 # wfDeprecated( __METHOD__ . " with arguments" );
73 $this->setTarget( $address );
74 if ( $by ) { // local user
75 $this->setBlocker( User::newFromID( $by ) );
76 } else { // foreign user
77 $this->setBlocker( $byText );
79 $this->mReason = $reason;
80 $this->mTimestamp = wfTimestamp( TS_MW, $timestamp );
81 $this->mAuto = $auto;
82 $this->isHardblock( !$anonOnly );
83 $this->prevents( 'createaccount', $createAccount );
84 if ( $expiry == 'infinity' || $expiry == wfGetDB( DB_SLAVE )->getInfinity() ) {
85 $this->mExpiry = 'infinity';
86 } else {
87 $this->mExpiry = wfTimestamp( TS_MW, $expiry );
89 $this->isAutoblocking( $enableAutoblock );
90 $this->mHideName = $hideName;
91 $this->prevents( 'sendemail', $blockEmail );
92 $this->prevents( 'editownusertalk', !$allowUsertalk );
94 $this->mFromMaster = false;
97 /**
98 * Load a block from the database, using either the IP address or
99 * user ID. Tries the user ID first, and if that doesn't work, tries
100 * the address.
102 * @param $address String: IP address of user/anon
103 * @param $user Integer: user id of user
104 * @return Block Object
105 * @deprecated since 1.18
107 public static function newFromDB( $address, $user = 0 ) {
108 return self::newFromTarget( User::whoIs( $user ), $address );
112 * Load a blocked user from their block id.
114 * @param $id Integer: Block id to search for
115 * @return Block object or null
117 public static function newFromID( $id ) {
118 $dbr = wfGetDB( DB_SLAVE );
119 $res = $dbr->selectRow(
120 'ipblocks',
121 '*',
122 array( 'ipb_id' => $id ),
123 __METHOD__
125 if ( $res ) {
126 return Block::newFromRow( $res );
127 } else {
128 return null;
133 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
134 * the blocking user or the block timestamp, only things which affect the blocked user *
136 * @param $block Block
138 * @return bool
140 public function equals( Block $block ) {
141 return (
142 (string)$this->target == (string)$block->target
143 && $this->type == $block->type
144 && $this->mAuto == $block->mAuto
145 && $this->isHardblock() == $block->isHardblock()
146 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
147 && $this->mExpiry == $block->mExpiry
148 && $this->isAutoblocking() == $block->isAutoblocking()
149 && $this->mHideName == $block->mHideName
150 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
151 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
152 && $this->mReason == $block->mReason
157 * Clear all member variables in the current object. Does not clear
158 * the block from the DB.
159 * @deprecated since 1.18
161 public function clear() {
162 # Noop
166 * Get a block from the DB, with either the given address or the given username
168 * @param $address string The IP address of the user, or blank to skip IP blocks
169 * @param $user int The user ID, or zero for anonymous users
170 * @return Boolean: the user is blocked from editing
171 * @deprecated since 1.18
173 public function load( $address = '', $user = 0 ) {
174 wfDeprecated( __METHOD__ );
175 if( $user ){
176 $username = User::whoIs( $user );
177 $block = self::newFromTarget( $username, $address );
178 } else {
179 $block = self::newFromTarget( null, $address );
182 if( $block instanceof Block ){
183 # This is mildly evil, but hey, it's B/C :D
184 foreach( $block as $variable => $value ){
185 $this->$variable = $value;
187 return true;
188 } else {
189 return false;
194 * Load a block from the database which affects the already-set $this->target:
195 * 1) A block directly on the given user or IP
196 * 2) A rangeblock encompasing the given IP (smallest first)
197 * 3) An autoblock on the given IP
198 * @param $vagueTarget User|String also search for blocks affecting this target. Doesn't
199 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
200 * @return Bool whether a relevant block was found
202 protected function newLoad( $vagueTarget = null ) {
203 $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_SLAVE );
205 if( $this->type !== null ){
206 $conds = array(
207 'ipb_address' => array( (string)$this->target ),
209 } else {
210 $conds = array( 'ipb_address' => array() );
213 # Be aware that the != '' check is explicit, since empty values will be
214 # passed by some callers (bug 29116)
215 if( $vagueTarget != ''){
216 list( $target, $type ) = self::parseTarget( $vagueTarget );
217 switch( $type ) {
218 case self::TYPE_USER:
219 # Slightly wierd, but who are we to argue?
220 $conds['ipb_address'][] = (string)$target;
221 break;
223 case self::TYPE_IP:
224 $conds['ipb_address'][] = (string)$target;
225 $conds[] = self::getRangeCond( IP::toHex( $target ) );
226 $conds = $db->makeList( $conds, LIST_OR );
227 break;
229 case self::TYPE_RANGE:
230 list( $start, $end ) = IP::parseRange( $target );
231 $conds['ipb_address'][] = (string)$target;
232 $conds[] = self::getRangeCond( $start, $end );
233 $conds = $db->makeList( $conds, LIST_OR );
234 break;
236 default:
237 throw new MWException( "Tried to load block with invalid type" );
241 $res = $db->select( 'ipblocks', '*', $conds, __METHOD__ );
243 # This result could contain a block on the user, a block on the IP, and a russian-doll
244 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
245 $bestRow = null;
247 # Lower will be better
248 $bestBlockScore = 100;
250 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
251 $bestBlockPreventsEdit = null;
253 foreach( $res as $row ){
254 $block = Block::newFromRow( $row );
256 # Don't use expired blocks
257 if( $block->deleteIfExpired() ){
258 continue;
261 # Don't use anon only blocks on users
262 if( $this->type == self::TYPE_USER && !$block->isHardblock() ){
263 continue;
266 if( $block->getType() == self::TYPE_RANGE ){
267 # This is the number of bits that are allowed to vary in the block, give
268 # or take some floating point errors
269 $end = wfBaseconvert( $block->getRangeEnd(), 16, 10 );
270 $start = wfBaseconvert( $block->getRangeStart(), 16, 10 );
271 $size = log( $end - $start + 1, 2 );
273 # This has the nice property that a /32 block is ranked equally with a
274 # single-IP block, which is exactly what it is...
275 $score = self::TYPE_RANGE - 1 + ( $size / 128 );
277 } else {
278 $score = $block->getType();
281 if( $score < $bestBlockScore ){
282 $bestBlockScore = $score;
283 $bestRow = $row;
284 $bestBlockPreventsEdit = $block->prevents( 'edit' );
288 if( $bestRow !== null ){
289 $this->initFromRow( $bestRow );
290 $this->prevents( 'edit', $bestBlockPreventsEdit );
291 return true;
292 } else {
293 return false;
298 * Get a set of SQL conditions which will select rangeblocks encompasing a given range
299 * @param $start String Hexadecimal IP representation
300 * @param $end String Hexadecimal IP represenation, or null to use $start = $end
301 * @return String
303 public static function getRangeCond( $start, $end = null ) {
304 if ( $end === null ) {
305 $end = $start;
307 # Per bug 14634, we want to include relevant active rangeblocks; for
308 # rangeblocks, we want to include larger ranges which enclose the given
309 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
310 # so we can improve performance by filtering on a LIKE clause
311 $chunk = self::getIpFragment( $start );
312 $dbr = wfGetDB( DB_SLAVE );
313 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
315 # Fairly hard to make a malicious SQL statement out of hex characters,
316 # but stranger things have happened...
317 $safeStart = $dbr->addQuotes( $start );
318 $safeEnd = $dbr->addQuotes( $end );
320 return $dbr->makeList(
321 array(
322 "ipb_range_start $like",
323 "ipb_range_start <= $safeStart",
324 "ipb_range_end >= $safeEnd",
326 LIST_AND
331 * Get the component of an IP address which is certain to be the same between an IP
332 * address and a rangeblock containing that IP address.
333 * @param $hex String Hexadecimal IP representation
334 * @return String
336 protected static function getIpFragment( $hex ) {
337 global $wgBlockCIDRLimit;
338 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
339 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
340 } else {
341 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
346 * Given a database row from the ipblocks table, initialize
347 * member variables
348 * @param $row ResultWrapper: a row from the ipblocks table
350 protected function initFromRow( $row ) {
351 $this->setTarget( $row->ipb_address );
352 if ( $row->ipb_by ) { // local user
353 $this->setBlocker( User::newFromID( $row->ipb_by ) );
354 } else { // foreign user
355 $this->setBlocker( $row->ipb_by_text );
358 $this->mReason = $row->ipb_reason;
359 $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
360 $this->mAuto = $row->ipb_auto;
361 $this->mHideName = $row->ipb_deleted;
362 $this->mId = $row->ipb_id;
364 // I wish I didn't have to do this
365 $db = wfGetDB( DB_SLAVE );
366 if ( $row->ipb_expiry == $db->getInfinity() ) {
367 $this->mExpiry = 'infinity';
368 } else {
369 $this->mExpiry = wfTimestamp( TS_MW, $row->ipb_expiry );
372 $this->isHardblock( !$row->ipb_anon_only );
373 $this->isAutoblocking( $row->ipb_enable_autoblock );
375 $this->prevents( 'createaccount', $row->ipb_create_account );
376 $this->prevents( 'sendemail', $row->ipb_block_email );
377 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk );
381 * Create a new Block object from a database row
382 * @param $row ResultWrapper row from the ipblocks table
383 * @return Block
385 public static function newFromRow( $row ){
386 $block = new Block;
387 $block->initFromRow( $row );
388 return $block;
392 * Delete the row from the IP blocks table.
394 * @return Boolean
396 public function delete() {
397 if ( wfReadOnly() ) {
398 return false;
401 if ( !$this->getId() ) {
402 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
405 $dbw = wfGetDB( DB_MASTER );
406 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->getId() ), __METHOD__ );
408 return $dbw->affectedRows() > 0;
412 * Insert a block into the block table. Will fail if there is a conflicting
413 * block (same name and options) already in the database.
415 * @param $dbw DatabaseBase if you have one available
416 * @return mixed: false on failure, assoc array on success:
417 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
419 public function insert( $dbw = null ) {
420 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
422 if ( $dbw === null ) {
423 $dbw = wfGetDB( DB_MASTER );
426 # Don't collide with expired blocks
427 Block::purgeExpired();
429 $row = $this->getDatabaseArray();
430 $row['ipb_id'] = $dbw->nextSequenceValue("ipblocks_ipb_id_seq");
432 $dbw->insert(
433 'ipblocks',
434 $row,
435 __METHOD__,
436 array( 'IGNORE' )
438 $affected = $dbw->affectedRows();
439 $this->mId = $dbw->insertId();
441 if ( $affected ) {
442 $auto_ipd_ids = $this->doRetroactiveAutoblock();
443 return array( 'id' => $this->mId, 'autoIds' => $auto_ipd_ids );
446 return false;
450 * Update a block in the DB with new parameters.
451 * The ID field needs to be loaded first.
453 * @return Int number of affected rows, which should probably be 1 or something's
454 * gone slightly awry
456 public function update() {
457 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
458 $dbw = wfGetDB( DB_MASTER );
460 $dbw->update(
461 'ipblocks',
462 $this->getDatabaseArray( $dbw ),
463 array( 'ipb_id' => $this->getId() ),
464 __METHOD__
467 return $dbw->affectedRows();
471 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
472 * @param $db DatabaseBase
473 * @return Array
475 protected function getDatabaseArray( $db = null ){
476 if( !$db ){
477 $db = wfGetDB( DB_SLAVE );
479 $expiry = $db->encodeExpiry( $this->mExpiry );
481 $a = array(
482 'ipb_address' => (string)$this->target,
483 'ipb_user' => $this->target instanceof User ? $this->target->getID() : 0,
484 'ipb_by' => $this->getBy(),
485 'ipb_by_text' => $this->getByName(),
486 'ipb_reason' => $this->mReason,
487 'ipb_timestamp' => $db->timestamp( $this->mTimestamp ),
488 'ipb_auto' => $this->mAuto,
489 'ipb_anon_only' => !$this->isHardblock(),
490 'ipb_create_account' => $this->prevents( 'createaccount' ),
491 'ipb_enable_autoblock' => $this->isAutoblocking(),
492 'ipb_expiry' => $expiry,
493 'ipb_range_start' => $this->getRangeStart(),
494 'ipb_range_end' => $this->getRangeEnd(),
495 'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
496 'ipb_block_email' => $this->prevents( 'sendemail' ),
497 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' )
500 return $a;
504 * Retroactively autoblocks the last IP used by the user (if it is a user)
505 * blocked by this Block.
507 * @return Array: block IDs of retroactive autoblocks made
509 protected function doRetroactiveAutoblock() {
510 $blockIds = array();
511 # If autoblock is enabled, autoblock the LAST IP(s) used
512 if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
513 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
515 $continue = wfRunHooks(
516 'PerformRetroactiveAutoblock', array( $this, &$blockIds ) );
518 if ( $continue ) {
519 self::defaultRetroactiveAutoblock( $this, $blockIds );
522 return $blockIds;
526 * Retroactively autoblocks the last IP used by the user (if it is a user)
527 * blocked by this Block. This will use the recentchanges table.
529 * @param Block $block
530 * @param Array &$blockIds
531 * @return Array: block IDs of retroactive autoblocks made
533 protected static function defaultRetroactiveAutoblock( Block $block, array &$blockIds ) {
534 $dbr = wfGetDB( DB_SLAVE );
536 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
537 $conds = array( 'rc_user_text' => (string)$block->getTarget() );
539 // Just the last IP used.
540 $options['LIMIT'] = 1;
542 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
543 __METHOD__ , $options );
545 if ( !$dbr->numRows( $res ) ) {
546 # No results, don't autoblock anything
547 wfDebug( "No IP found to retroactively autoblock\n" );
548 } else {
549 foreach ( $res as $row ) {
550 if ( $row->rc_ip ) {
551 $id = $block->doAutoblock( $row->rc_ip );
552 if ( $id ) $blockIds[] = $id;
559 * Checks whether a given IP is on the autoblock whitelist.
560 * TODO: this probably belongs somewhere else, but not sure where...
562 * @param $ip String: The IP to check
563 * @return Boolean
565 public static function isWhitelistedFromAutoblocks( $ip ) {
566 global $wgMemc;
568 // Try to get the autoblock_whitelist from the cache, as it's faster
569 // than getting the msg raw and explode()'ing it.
570 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
571 $lines = $wgMemc->get( $key );
572 if ( !$lines ) {
573 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
574 $wgMemc->set( $key, $lines, 3600 * 24 );
577 wfDebug( "Checking the autoblock whitelist..\n" );
579 foreach ( $lines as $line ) {
580 # List items only
581 if ( substr( $line, 0, 1 ) !== '*' ) {
582 continue;
585 $wlEntry = substr( $line, 1 );
586 $wlEntry = trim( $wlEntry );
588 wfDebug( "Checking $ip against $wlEntry..." );
590 # Is the IP in this range?
591 if ( IP::isInRange( $ip, $wlEntry ) ) {
592 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
593 return true;
594 } else {
595 wfDebug( " No match\n" );
599 return false;
603 * Autoblocks the given IP, referring to this Block.
605 * @param $autoblockIP String: the IP to autoblock.
606 * @return mixed: block ID if an autoblock was inserted, false if not.
608 public function doAutoblock( $autoblockIP ) {
609 # If autoblocks are disabled, go away.
610 if ( !$this->isAutoblocking() ) {
611 return false;
614 # Check for presence on the autoblock whitelist.
615 if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
616 return false;
619 # Allow hooks to cancel the autoblock.
620 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
621 wfDebug( "Autoblock aborted by hook.\n" );
622 return false;
625 # It's okay to autoblock. Go ahead and insert/update the block...
627 # Do not add a *new* block if the IP is already blocked.
628 $ipblock = Block::newFromTarget( $autoblockIP );
629 if ( $ipblock ) {
630 # Check if the block is an autoblock and would exceed the user block
631 # if renewed. If so, do nothing, otherwise prolong the block time...
632 if ( $ipblock->mAuto && // @TODO: why not compare $ipblock->mExpiry?
633 $this->mExpiry > Block::getAutoblockExpiry( $ipblock->mTimestamp )
635 # Reset block timestamp to now and its expiry to
636 # $wgAutoblockExpiry in the future
637 $ipblock->updateTimestamp();
639 return false;
642 # Make a new block object with the desired properties.
643 $autoblock = new Block;
644 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
645 $autoblock->setTarget( $autoblockIP );
646 $autoblock->setBlocker( $this->getBlocker() );
647 $autoblock->mReason = wfMsgForContent( 'autoblocker', $this->getTarget(), $this->mReason );
648 $timestamp = wfTimestampNow();
649 $autoblock->mTimestamp = $timestamp;
650 $autoblock->mAuto = 1;
651 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
652 # Continue suppressing the name if needed
653 $autoblock->mHideName = $this->mHideName;
654 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
656 if ( $this->mExpiry == 'infinity' ) {
657 # Original block was indefinite, start an autoblock now
658 $autoblock->mExpiry = Block::getAutoblockExpiry( $timestamp );
659 } else {
660 # If the user is already blocked with an expiry date, we don't
661 # want to pile on top of that.
662 $autoblock->mExpiry = min( $this->mExpiry, Block::getAutoblockExpiry( $timestamp ) );
665 # Insert the block...
666 $status = $autoblock->insert();
667 return $status
668 ? $status['id']
669 : false;
673 * Check if a block has expired. Delete it if it is.
674 * @return Boolean
676 public function deleteIfExpired() {
677 wfProfileIn( __METHOD__ );
679 if ( $this->isExpired() ) {
680 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
681 $this->delete();
682 $retVal = true;
683 } else {
684 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
685 $retVal = false;
688 wfProfileOut( __METHOD__ );
689 return $retVal;
693 * Has the block expired?
694 * @return Boolean
696 public function isExpired() {
697 $timestamp = wfTimestampNow();
698 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
700 if ( !$this->mExpiry ) {
701 return false;
702 } else {
703 return $timestamp > $this->mExpiry;
708 * Is the block address valid (i.e. not a null string?)
709 * @return Boolean
711 public function isValid() {
712 return $this->getTarget() != null;
716 * Update the timestamp on autoblocks.
718 public function updateTimestamp() {
719 if ( $this->mAuto ) {
720 $this->mTimestamp = wfTimestamp();
721 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
723 $dbw = wfGetDB( DB_MASTER );
724 $dbw->update( 'ipblocks',
725 array( /* SET */
726 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
727 'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
729 array( /* WHERE */
730 'ipb_address' => (string)$this->getTarget()
732 __METHOD__
738 * Get the IP address at the start of the range in Hex form
739 * @return String IP in Hex form
741 public function getRangeStart() {
742 switch( $this->type ) {
743 case self::TYPE_USER:
744 return '';
745 case self::TYPE_IP:
746 return IP::toHex( $this->target );
747 case self::TYPE_RANGE:
748 list( $start, /*...*/ ) = IP::parseRange( $this->target );
749 return $start;
750 default: throw new MWException( "Block with invalid type" );
755 * Get the IP address at the start of the range in Hex form
756 * @return String IP in Hex form
758 public function getRangeEnd() {
759 switch( $this->type ) {
760 case self::TYPE_USER:
761 return '';
762 case self::TYPE_IP:
763 return IP::toHex( $this->target );
764 case self::TYPE_RANGE:
765 list( /*...*/, $end ) = IP::parseRange( $this->target );
766 return $end;
767 default: throw new MWException( "Block with invalid type" );
772 * Get the user id of the blocking sysop
774 * @return Integer (0 for foreign users)
776 public function getBy() {
777 $blocker = $this->getBlocker();
778 return ( $blocker instanceof User )
779 ? $blocker->getId()
780 : 0;
784 * Get the username of the blocking sysop
786 * @return String
788 public function getByName() {
789 $blocker = $this->getBlocker();
790 return ( $blocker instanceof User )
791 ? $blocker->getName()
792 : (string)$blocker; // username
796 * Get the block ID
797 * @return int
799 public function getId() {
800 return $this->mId;
804 * Get/set the SELECT ... FOR UPDATE flag
805 * @deprecated since 1.18
807 * @param $x Bool
809 public function forUpdate( $x = null ) {
810 # noop
814 * Get/set a flag determining whether the master is used for reads
816 * @param $x Bool
817 * @return Bool
819 public function fromMaster( $x = null ) {
820 return wfSetVar( $this->mFromMaster, $x );
824 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range
825 * @param $x Bool
826 * @return Bool
828 public function isHardblock( $x = null ) {
829 wfSetVar( $this->isHardblock, $x );
831 # You can't *not* hardblock a user
832 return $this->getType() == self::TYPE_USER
833 ? true
834 : $this->isHardblock;
837 public function isAutoblocking( $x = null ) {
838 wfSetVar( $this->isAutoblocking, $x );
840 # You can't put an autoblock on an IP or range as we don't have any history to
841 # look over to get more IPs from
842 return $this->getType() == self::TYPE_USER
843 ? $this->isAutoblocking
844 : false;
848 * Get/set whether the Block prevents a given action
849 * @param $action String
850 * @param $x Bool
851 * @return Bool
853 public function prevents( $action, $x = null ) {
854 switch( $action ) {
855 case 'edit':
856 # For now... <evil laugh>
857 return true;
859 case 'createaccount':
860 return wfSetVar( $this->mCreateAccount, $x );
862 case 'sendemail':
863 return wfSetVar( $this->mBlockEmail, $x );
865 case 'editownusertalk':
866 return wfSetVar( $this->mDisableUsertalk, $x );
868 default:
869 return null;
874 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
875 * @return String, text is escaped
877 public function getRedactedName() {
878 if ( $this->mAuto ) {
879 return Html::rawElement(
880 'span',
881 array( 'class' => 'mw-autoblockid' ),
882 wfMessage( 'autoblockid', $this->mId )
884 } else {
885 return htmlspecialchars( $this->getTarget() );
890 * Encode expiry for DB
892 * @param $expiry String: timestamp for expiry, or
893 * @param $db Database object
894 * @return String
895 * @deprecated since 1.18; use $dbw->encodeExpiry() instead
897 public static function encodeExpiry( $expiry, $db ) {
898 return $db->encodeExpiry( $expiry );
902 * Decode expiry which has come from the DB
904 * @param $expiry String: Database expiry format
905 * @param $timestampType Int Requested timestamp format
906 * @return String
907 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
909 public static function decodeExpiry( $expiry, $timestampType = TS_MW ) {
910 global $wgContLang;
911 return $wgContLang->formatExpiry( $expiry, $timestampType );
915 * Get a timestamp of the expiry for autoblocks
917 * @param $timestamp String|Int
918 * @return String
920 public static function getAutoblockExpiry( $timestamp ) {
921 global $wgAutoblockExpiry;
923 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
927 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
928 * For example, 127.111.113.151/24 -> 127.111.113.0/24
929 * @param $range String: IP address to normalize
930 * @return string
931 * @deprecated since 1.18, call IP::sanitizeRange() directly
933 public static function normaliseRange( $range ) {
934 return IP::sanitizeRange( $range );
938 * Purge expired blocks from the ipblocks table
940 public static function purgeExpired() {
941 $dbw = wfGetDB( DB_MASTER );
942 $dbw->delete( 'ipblocks',
943 array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
947 * Get a value to insert into expiry field of the database when infinite expiry
948 * is desired
949 * @deprecated since 1.18, call $dbr->getInfinity() directly
950 * @return String
952 public static function infinity() {
953 return wfGetDB( DB_SLAVE )->getInfinity();
957 * Convert a DB-encoded expiry into a real string that humans can read.
959 * @param $encoded_expiry String: Database encoded expiry time
960 * @return Html-escaped String
961 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
963 public static function formatExpiry( $encoded_expiry ) {
964 global $wgContLang;
965 static $msg = null;
967 if ( is_null( $msg ) ) {
968 $msg = array();
969 $keys = array( 'infiniteblock', 'expiringblock' );
971 foreach ( $keys as $key ) {
972 $msg[$key] = wfMsgHtml( $key );
976 $expiry = $wgContLang->formatExpiry( $encoded_expiry, TS_MW );
977 if ( $expiry == wfGetDB( DB_SLAVE )->getInfinity() ) {
978 $expirystr = $msg['infiniteblock'];
979 } else {
980 global $wgLang;
981 $expiredatestr = htmlspecialchars( $wgLang->date( $expiry, true ) );
982 $expiretimestr = htmlspecialchars( $wgLang->time( $expiry, true ) );
983 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array( $expiredatestr, $expiretimestr ) );
986 return $expirystr;
990 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
991 * ("24 May 2034"), into an absolute timestamp we can put into the database.
992 * @param $expiry String: whatever was typed into the form
993 * @return String: timestamp or "infinity" string for th DB implementation
994 * @deprecated since 1.18 moved to SpecialBlock::parseExpiryInput()
996 public static function parseExpiryInput( $expiry ) {
997 wfDeprecated( __METHOD__ );
998 return SpecialBlock::parseExpiryInput( $expiry );
1002 * Given a target and the target's type, get an existing Block object if possible.
1003 * @param $specificTarget String|User|Int a block target, which may be one of several types:
1004 * * A user to block, in which case $target will be a User
1005 * * An IP to block, in which case $target will be a User generated by using
1006 * User::newFromName( $ip, false ) to turn off name validation
1007 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1008 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1009 * usernames
1010 * Calling this with a user, IP address or range will not select autoblocks, and will
1011 * only select a block where the targets match exactly (so looking for blocks on
1012 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1013 * @param $vagueTarget String|User|Int as above, but we will search for *any* block which
1014 * affects that target (so for an IP address, get ranges containing that IP; and also
1015 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1016 * @param $fromMaster Bool whether to use the DB_MASTER database
1017 * @return Block|null (null if no relevant block could be found). The target and type
1018 * of the returned Block will refer to the actual block which was found, which might
1019 * not be the same as the target you gave if you used $vagueTarget!
1021 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1023 list( $target, $type ) = self::parseTarget( $specificTarget );
1024 if( $type == Block::TYPE_ID || $type == Block::TYPE_AUTO ){
1025 return Block::newFromID( $target );
1027 } elseif( $target === null && $vagueTarget == '' ){
1028 # We're not going to find anything useful here
1029 # Be aware that the == '' check is explicit, since empty values will be
1030 # passed by some callers (bug 29116)
1031 return null;
1033 } elseif( in_array( $type, array( Block::TYPE_USER, Block::TYPE_IP, Block::TYPE_RANGE, null ) ) ) {
1034 $block = new Block();
1035 $block->fromMaster( $fromMaster );
1037 if( $type !== null ){
1038 $block->setTarget( $target );
1041 if( $block->newLoad( $vagueTarget ) ){
1042 return $block;
1043 } else {
1044 return null;
1046 } else {
1047 return null;
1052 * From an existing Block, get the target and the type of target. Note that it is
1053 * always safe to treat the target as a string; for User objects this will return
1054 * User::__toString() which in turn gives User::getName().
1056 * @param $target String|Int|User
1057 * @return array( User|String, Block::TYPE_ constant )
1059 public static function parseTarget( $target ) {
1060 $target = trim( $target );
1062 # We may have been through this before
1063 if( $target instanceof User ){
1064 if( IP::isValid( $target->getName() ) ){
1065 return array( $target, self::TYPE_IP );
1066 } else {
1067 return array( $target, self::TYPE_USER );
1069 } elseif( $target === null ){
1070 return array( null, null );
1073 if ( IP::isValid( $target ) ) {
1074 # We can still create a User if it's an IP address, but we need to turn
1075 # off validation checking (which would exclude IP addresses)
1076 return array(
1077 User::newFromName( IP::sanitizeIP( $target ), false ),
1078 Block::TYPE_IP
1081 } elseif ( IP::isValidBlock( $target ) ) {
1082 # Can't create a User from an IP range
1083 return array( IP::sanitizeRange( $target ), Block::TYPE_RANGE );
1086 # Consider the possibility that this is not a username at all
1087 # but actually an old subpage (bug #29797)
1088 if( strpos( $target, '/' ) !== false ){
1089 # An old subpage, drill down to the user behind it
1090 $parts = explode( '/', $target );
1091 $target = $parts[0];
1094 $userObj = User::newFromName( $target );
1095 if ( $userObj instanceof User ) {
1096 # Note that since numbers are valid usernames, a $target of "12345" will be
1097 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1098 # since hash characters are not valid in usernames or titles generally.
1099 return array( $userObj, Block::TYPE_USER );
1101 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1102 # Autoblock reference in the form "#12345"
1103 return array( substr( $target, 1 ), Block::TYPE_AUTO );
1105 } else {
1106 # WTF?
1107 return array( null, null );
1112 * Get the type of target for this particular block
1113 * @return Block::TYPE_ constant, will never be TYPE_ID
1115 public function getType() {
1116 return $this->mAuto
1117 ? self::TYPE_AUTO
1118 : $this->type;
1122 * Get the target and target type for this particular Block. Note that for autoblocks,
1123 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1124 * in this situation.
1125 * @return array( User|String, Block::TYPE_ constant )
1126 * @todo FIXME: This should be an integral part of the Block member variables
1128 public function getTargetAndType() {
1129 return array( $this->getTarget(), $this->getType() );
1133 * Get the target for this particular Block. Note that for autoblocks,
1134 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1135 * in this situation.
1136 * @return User|String
1138 public function getTarget() {
1139 return $this->target;
1143 * Set the target for this block, and update $this->type accordingly
1144 * @param $target Mixed
1146 public function setTarget( $target ){
1147 list( $this->target, $this->type ) = self::parseTarget( $target );
1151 * Get the user who implemented this block
1152 * @return User|string Local User object or string for a foreign user
1154 public function getBlocker(){
1155 return $this->blocker;
1159 * Set the user who implemented (or will implement) this block
1160 * @param $user User|string Local User object or username string for foriegn users
1162 public function setBlocker( $user ){
1163 $this->blocker = $user;