]> scripts.mit.edu Git - autoinstallsdev/mediawiki.git/blob - includes/Block.php
MediaWiki 1.15.0
[autoinstallsdev/mediawiki.git] / includes / Block.php
1 <?php
2 /**
3  * @file
4  * Blocks and bans object
5  */
6
7 /**
8  * The block class
9  * All the functions in this class assume the object is either explicitly
10  * loaded or filled. It is not load-on-demand. There are no accessors.
11  *
12  * Globals used: $wgAutoblockExpiry, $wgAntiLockFlags
13  *
14  * @todo This could be used everywhere, but it isn't.
15  */
16 class Block {
17         /* public*/ var $mAddress, $mUser, $mBy, $mReason, $mTimestamp, $mAuto, $mId, $mExpiry,
18                                 $mRangeStart, $mRangeEnd, $mAnonOnly, $mEnableAutoblock, $mHideName,
19                                 $mBlockEmail, $mByName, $mAngryAutoblock, $mAllowUsertalk;
20         /* private */ var $mNetworkBits, $mIntegerAddr, $mForUpdate, $mFromMaster;
21
22         const EB_KEEP_EXPIRED = 1;
23         const EB_FOR_UPDATE = 2;
24         const EB_RANGE_ONLY = 4;
25
26         function __construct( $address = '', $user = 0, $by = 0, $reason = '',
27                 $timestamp = '' , $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
28                 $hideName = 0, $blockEmail = 0, $allowUsertalk = 0 )
29         {
30                 $this->mId = 0;
31                 # Expand valid IPv6 addresses
32                 $address = IP::sanitizeIP( $address );
33                 $this->mAddress = $address;
34                 $this->mUser = $user;
35                 $this->mBy = $by;
36                 $this->mReason = $reason;
37                 $this->mTimestamp = wfTimestamp(TS_MW,$timestamp);
38                 $this->mAuto = $auto;
39                 $this->mAnonOnly = $anonOnly;
40                 $this->mCreateAccount = $createAccount;
41                 $this->mExpiry = self::decodeExpiry( $expiry );
42                 $this->mEnableAutoblock = $enableAutoblock;
43                 $this->mHideName = $hideName;
44                 $this->mBlockEmail = $blockEmail;
45                 $this->mAllowUsertalk = $allowUsertalk;
46                 $this->mForUpdate = false;
47                 $this->mFromMaster = false;
48                 $this->mByName = false;
49                 $this->mAngryAutoblock = false;
50                 $this->initialiseRange();
51         }
52
53         /**
54          * Load a block from the database, using either the IP address or
55          * user ID. Tries the user ID first, and if that doesn't work, tries
56          * the address.
57          * 
58          * @param $address String: IP address of user/anon
59          * @param $user Integer: user id of user
60          * @param $killExpired Boolean: delete expired blocks on load
61          * @return Block Object
62          */
63         public static function newFromDB( $address, $user = 0, $killExpired = true ) {
64                 $block = new Block;
65                 $block->load( $address, $user, $killExpired );
66                 if ( $block->isValid() ) {
67                         return $block;
68                 } else {
69                         return null;
70                 }
71         }
72
73         /**
74          * Load a blocked user from their block id.
75          *
76          * @param $id Integer: Block id to search for
77          * @return Block object
78          */
79         public static function newFromID( $id ) {
80                 $dbr = wfGetDB( DB_SLAVE );
81                 $res = $dbr->resultObject( $dbr->select( 'ipblocks', '*',
82                         array( 'ipb_id' => $id ), __METHOD__ ) );
83                 $block = new Block;
84                 if ( $block->loadFromResult( $res ) ) {
85                         return $block;
86                 } else {
87                         return null;
88                 }
89         }
90         
91         /**
92          * Check if two blocks are effectively equal
93          *
94          * @return Boolean
95          */
96         public function equals( Block $block ) {
97                 return ( 
98                         $this->mAddress == $block->mAddress
99                         && $this->mUser == $block->mUser
100                         && $this->mAuto == $block->mAuto
101                         && $this->mAnonOnly == $block->mAnonOnly
102                         && $this->mCreateAccount == $block->mCreateAccount
103                         && $this->mExpiry == $block->mExpiry
104                         && $this->mEnableAutoblock == $block->mEnableAutoblock
105                         && $this->mHideName == $block->mHideName
106                         && $this->mBlockEmail == $block->mBlockEmail
107                         && $this->mAllowUsertalk == $block->mAllowUsertalk
108                         && $this->mReason == $block->mReason
109                 );
110         }
111
112         /**
113          * Clear all member variables in the current object. Does not clear
114          * the block from the DB.
115          */
116         public function clear() {
117                 $this->mAddress = $this->mReason = $this->mTimestamp = '';
118                 $this->mId = $this->mAnonOnly = $this->mCreateAccount =
119                         $this->mEnableAutoblock = $this->mAuto = $this->mUser =
120                         $this->mBy = $this->mHideName = $this->mBlockEmail = $this->mAllowUsertalk = 0;
121                 $this->mByName = false;
122         }
123
124         /**
125          * Get the DB object and set the reference parameter to the select options.
126          * The options array will contain FOR UPDATE if appropriate.
127          *
128          * @param $options Array
129          * @return Database
130          */
131         protected function &getDBOptions( &$options ) {
132                 global $wgAntiLockFlags;
133                 if ( $this->mForUpdate || $this->mFromMaster ) {
134                         $db = wfGetDB( DB_MASTER );
135                         if ( !$this->mForUpdate || ($wgAntiLockFlags & ALF_NO_BLOCK_LOCK) ) {
136                                 $options = array();
137                         } else {
138                                 $options = array( 'FOR UPDATE' );
139                         }
140                 } else {
141                         $db = wfGetDB( DB_SLAVE );
142                         $options = array();
143                 }
144                 return $db;
145         }
146
147         /**
148          * Get a block from the DB, with either the given address or the given username
149          *
150          * @param $address string The IP address of the user, or blank to skip IP blocks
151          * @param $user int The user ID, or zero for anonymous users
152          * @param $killExpired bool Whether to delete expired rows while loading
153          * @return Boolean: the user is blocked from editing
154          *
155          */
156         public function load( $address = '', $user = 0, $killExpired = true ) {
157                 wfDebug( "Block::load: '$address', '$user', $killExpired\n" );
158
159                 $options = array();
160                 $db =& $this->getDBOptions( $options );
161
162                 if ( 0 == $user && $address == '' ) {
163                         # Invalid user specification, not blocked
164                         $this->clear();
165                         return false;
166                 }
167
168                 # Try user block
169                 if ( $user ) {
170                         $res = $db->resultObject( $db->select( 'ipblocks', '*', array( 'ipb_user' => $user ),
171                                 __METHOD__, $options ) );
172                         if ( $this->loadFromResult( $res, $killExpired ) ) {
173                                 return true;
174                         }
175                 }
176
177                 # Try IP block
178                 # TODO: improve performance by merging this query with the autoblock one
179                 # Slightly tricky while handling killExpired as well
180                 if ( $address ) {
181                         $conds = array( 'ipb_address' => $address, 'ipb_auto' => 0 );
182                         $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
183                         if ( $this->loadFromResult( $res, $killExpired ) ) {
184                                 if ( $user && $this->mAnonOnly ) {
185                                         # Block is marked anon-only
186                                         # Whitelist this IP address against autoblocks and range blocks
187                                         # (but not account creation blocks -- bug 13611)
188                                         if( !$this->mCreateAccount ) {
189                                                 $this->clear();
190                                         }
191                                         return false;
192                                 } else {
193                                         return true;
194                                 }
195                         }
196                 }
197
198                 # Try range block
199                 if ( $this->loadRange( $address, $killExpired, $user ) ) {
200                         if ( $user && $this->mAnonOnly ) {
201                                 # Respect account creation blocks on logged-in users -- bug 13611
202                                 if( !$this->mCreateAccount ) {
203                                         $this->clear();
204                                 }
205                                 return false;
206                         } else {
207                                 return true;
208                         }
209                 }
210
211                 # Try autoblock
212                 if ( $address ) {
213                         $conds = array( 'ipb_address' => $address, 'ipb_auto' => 1 );
214                         if ( $user ) {
215                                 $conds['ipb_anon_only'] = 0;
216                         }
217                         $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
218                         if ( $this->loadFromResult( $res, $killExpired ) ) {
219                                 return true;
220                         }
221                 }
222
223                 # Give up
224                 $this->clear();
225                 return false;
226         }
227
228         /**
229          * Fill in member variables from a result wrapper
230          *
231          * @param $res ResultWrapper: row from the ipblocks table
232          * @param $killExpired Boolean: whether to delete expired rows while loading
233          * @return Boolean
234          */
235         protected function loadFromResult( ResultWrapper $res, $killExpired = true ) {
236                 $ret = false;
237                 if ( 0 != $res->numRows() ) {
238                         # Get first block
239                         $row = $res->fetchObject();
240                         $this->initFromRow( $row );
241
242                         if ( $killExpired ) {
243                                 # If requested, delete expired rows
244                                 do {
245                                         $killed = $this->deleteIfExpired();
246                                         if ( $killed ) {
247                                                 $row = $res->fetchObject();
248                                                 if ( $row ) {
249                                                         $this->initFromRow( $row );
250                                                 }
251                                         }
252                                 } while ( $killed && $row );
253
254                                 # If there were any left after the killing finished, return true
255                                 if ( $row ) {
256                                         $ret = true;
257                                 }
258                         } else {
259                                 $ret = true;
260                         }
261                 }
262                 $res->free();
263                 return $ret;
264         }
265
266         /**
267          * Search the database for any range blocks matching the given address, and
268          * load the row if one is found.
269          *
270          * @param $address String: IP address range
271          * @param $killExpired Boolean: whether to delete expired rows while loading
272          * @param $userid Integer: if not 0, then sets ipb_anon_only
273          * @return Boolean
274          */
275         public function loadRange( $address, $killExpired = true, $user = 0 ) {
276                 $iaddr = IP::toHex( $address );
277                 if ( $iaddr === false ) {
278                         # Invalid address
279                         return false;
280                 }
281
282                 # Only scan ranges which start in this /16, this improves search speed
283                 # Blocks should not cross a /16 boundary.
284                 $range = substr( $iaddr, 0, 4 );
285
286                 $options = array();
287                 $db =& $this->getDBOptions( $options );
288                 $conds = array(
289                         "ipb_range_start LIKE '$range%'",
290                         "ipb_range_start <= '$iaddr'",
291                         "ipb_range_end >= '$iaddr'"
292                 );
293
294                 if ( $user ) {
295                         $conds['ipb_anon_only'] = 0;
296                 }
297
298                 $res = $db->resultObject( $db->select( 'ipblocks', '*', $conds, __METHOD__, $options ) );
299                 $success = $this->loadFromResult( $res, $killExpired );
300                 return $success;
301         }
302
303         /**
304          * Given a database row from the ipblocks table, initialize
305          * member variables
306          *
307          * @param $row ResultWrapper: a row from the ipblocks table
308          */
309         public function initFromRow( $row ) {
310                 $this->mAddress = $row->ipb_address;
311                 $this->mReason = $row->ipb_reason;
312                 $this->mTimestamp = wfTimestamp(TS_MW,$row->ipb_timestamp);
313                 $this->mUser = $row->ipb_user;
314                 $this->mBy = $row->ipb_by;
315                 $this->mAuto = $row->ipb_auto;
316                 $this->mAnonOnly = $row->ipb_anon_only;
317                 $this->mCreateAccount = $row->ipb_create_account;
318                 $this->mEnableAutoblock = $row->ipb_enable_autoblock;
319                 $this->mBlockEmail = $row->ipb_block_email;
320                 $this->mAllowUsertalk = $row->ipb_allow_usertalk;
321                 $this->mHideName = $row->ipb_deleted;
322                 $this->mId = $row->ipb_id;
323                 $this->mExpiry = self::decodeExpiry( $row->ipb_expiry );
324                 if ( isset( $row->user_name ) ) {
325                         $this->mByName = $row->user_name;
326                 } else {
327                         $this->mByName = $row->ipb_by_text;
328                 }
329                 $this->mRangeStart = $row->ipb_range_start;
330                 $this->mRangeEnd = $row->ipb_range_end;
331         }
332
333         /**
334          * Once $mAddress has been set, get the range they came from. 
335          * Wrapper for IP::parseRange
336          */
337         protected function initialiseRange() {
338                 $this->mRangeStart = '';
339                 $this->mRangeEnd = '';
340
341                 if ( $this->mUser == 0 ) {
342                         list( $this->mRangeStart, $this->mRangeEnd ) = IP::parseRange( $this->mAddress );
343                 }
344         }
345
346         /**
347          * Delete the row from the IP blocks table.
348          *
349          * @return Boolean
350          */
351         public function delete() {
352                 if ( wfReadOnly() ) {
353                         return false;
354                 }
355                 if ( !$this->mId ) {
356                         throw new MWException( "Block::delete() now requires that the mId member be filled\n" );
357                 }
358
359                 $dbw = wfGetDB( DB_MASTER );
360                 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->mId ), __METHOD__ );
361                 return $dbw->affectedRows() > 0;
362         }
363
364         /**
365          * Insert a block into the block table. Will fail if there is a conflicting
366          * block (same name and options) already in the database.
367          *
368          * @return Boolean: whether or not the insertion was successful.
369          */
370         public function insert() {
371                 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
372                 $dbw = wfGetDB( DB_MASTER );
373
374                 $this->validateBlockParams();
375                 $this->initialiseRange();
376
377                 # Don't collide with expired blocks
378                 Block::purgeExpired();
379
380                 $ipb_id = $dbw->nextSequenceValue('ipblocks_ipb_id_val');
381                 $dbw->insert( 'ipblocks',
382                         array(
383                                 'ipb_id' => $ipb_id,
384                                 'ipb_address' => $this->mAddress,
385                                 'ipb_user' => $this->mUser,
386                                 'ipb_by' => $this->mBy,
387                                 'ipb_by_text' => $this->mByName,
388                                 'ipb_reason' => $this->mReason,
389                                 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
390                                 'ipb_auto' => $this->mAuto,
391                                 'ipb_anon_only' => $this->mAnonOnly,
392                                 'ipb_create_account' => $this->mCreateAccount,
393                                 'ipb_enable_autoblock' => $this->mEnableAutoblock,
394                                 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
395                                 'ipb_range_start' => $this->mRangeStart,
396                                 'ipb_range_end' => $this->mRangeEnd,
397                                 'ipb_deleted'   => $this->mHideName,
398                                 'ipb_block_email' => $this->mBlockEmail,
399                                 'ipb_allow_usertalk' => $this->mAllowUsertalk
400                         ), 'Block::insert', array( 'IGNORE' )
401                 );
402                 $affected = $dbw->affectedRows();
403
404                 if ($affected)
405                         $this->doRetroactiveAutoblock();
406
407                 return (bool)$affected;
408         }
409
410         /**
411          * Update a block in the DB with new parameters.
412          * The ID field needs to be loaded first.
413          */
414         public function update() {
415                 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
416                 $dbw = wfGetDB( DB_MASTER );
417
418                 $this->validateBlockParams();
419
420                 $dbw->update( 'ipblocks',
421                         array(
422                                 'ipb_user' => $this->mUser,
423                                 'ipb_by' => $this->mBy,
424                                 'ipb_by_text' => $this->mByName,
425                                 'ipb_reason' => $this->mReason,
426                                 'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
427                                 'ipb_auto' => $this->mAuto,
428                                 'ipb_anon_only' => $this->mAnonOnly,
429                                 'ipb_create_account' => $this->mCreateAccount,
430                                 'ipb_enable_autoblock' => $this->mEnableAutoblock,
431                                 'ipb_expiry' => self::encodeExpiry( $this->mExpiry, $dbw ),
432                                 'ipb_range_start' => $this->mRangeStart,
433                                 'ipb_range_end' => $this->mRangeEnd,
434                                 'ipb_deleted'   => $this->mHideName,
435                                 'ipb_block_email' => $this->mBlockEmail,
436                                 'ipb_allow_usertalk' => $this->mAllowUsertalk ),
437                         array( 'ipb_id' => $this->mId ),
438                         'Block::update' );
439
440                 return $dbw->affectedRows();
441         }
442         
443         /**
444          * Make sure all the proper members are set to sane values
445          * before adding/updating a block
446          */
447         protected function validateBlockParams() {
448                 # Unset ipb_anon_only for user blocks, makes no sense
449                 if ( $this->mUser ) {
450                         $this->mAnonOnly = 0;
451                 }
452
453                 # Unset ipb_enable_autoblock for IP blocks, makes no sense
454                 if ( !$this->mUser ) {
455                         $this->mEnableAutoblock = 0;
456                         $this->mBlockEmail = 0; //Same goes for email...
457                 }
458
459                 if( !$this->mByName ) {
460                         if( $this->mBy ) {
461                                 $this->mByName = User::whoIs( $this->mBy );
462                         } else {
463                                 global $wgUser;
464                                 $this->mByName = $wgUser->getName();
465                         }
466                 }
467         }
468         
469         
470         /**
471         * Retroactively autoblocks the last IP used by the user (if it is a user)
472         * blocked by this Block.
473         *
474         * @return Boolean: whether or not a retroactive autoblock was made.
475         */
476         public function doRetroactiveAutoblock() {
477                 $dbr = wfGetDB( DB_SLAVE );
478                 #If autoblock is enabled, autoblock the LAST IP used
479                 # - stolen shamelessly from CheckUser_body.php
480
481                 if ($this->mEnableAutoblock && $this->mUser) {
482                         wfDebug("Doing retroactive autoblocks for " . $this->mAddress . "\n");
483                         
484                         $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
485                         $conds = array( 'rc_user_text' => $this->mAddress );
486                         
487                         if ($this->mAngryAutoblock) {
488                                 // Block any IP used in the last 7 days. Up to five IPs.
489                                 $conds[] = 'rc_timestamp < ' . $dbr->addQuotes( $dbr->timestamp( time() - (7*86400) ) );
490                                 $options['LIMIT'] = 5;
491                         } else {
492                                 // Just the last IP used.
493                                 $options['LIMIT'] = 1;
494                         }
495
496                         $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
497                                 __METHOD__ ,  $options);
498
499                         if ( !$dbr->numRows( $res ) ) {
500                                 #No results, don't autoblock anything
501                                 wfDebug("No IP found to retroactively autoblock\n");
502                         } else {
503                                 while ( $row = $dbr->fetchObject( $res ) ) {
504                                         if ( $row->rc_ip )
505                                                 $this->doAutoblock( $row->rc_ip );
506                                 }
507                         }
508                 }
509         }
510         
511         /**
512          * Checks whether a given IP is on the autoblock whitelist.
513          *
514          * @param $ip String: The IP to check
515          * @return Boolean
516          */
517         public static function isWhitelistedFromAutoblocks( $ip ) {
518                 global $wgMemc;
519                 
520                 // Try to get the autoblock_whitelist from the cache, as it's faster
521                 // than getting the msg raw and explode()'ing it.
522                 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
523                 $lines = $wgMemc->get( $key );
524                 if ( !$lines ) {
525                         $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
526                         $wgMemc->set( $key, $lines, 3600 * 24 );
527                 }
528
529                 wfDebug("Checking the autoblock whitelist..\n");
530
531                 foreach( $lines as $line ) {
532                         # List items only
533                         if ( substr( $line, 0, 1 ) !== '*' ) {
534                                 continue;
535                         }
536
537                         $wlEntry = substr($line, 1);
538                         $wlEntry = trim($wlEntry);
539
540                         wfDebug("Checking $ip against $wlEntry...");
541
542                         # Is the IP in this range?
543                         if (IP::isInRange( $ip, $wlEntry )) {
544                                 wfDebug(" IP $ip matches $wlEntry, not autoblocking\n");
545                                 return true;
546                         } else {
547                                 wfDebug( " No match\n" );
548                         }
549                 }
550                 
551                 return false;
552         }
553
554         /**
555          * Autoblocks the given IP, referring to this Block.
556          *
557          * @param $autoblockIP String: the IP to autoblock.
558          * @param $justInserted Boolean: the main block was just inserted
559          * @return Boolean: whether or not an autoblock was inserted.
560          */
561         public function doAutoblock( $autoblockIP, $justInserted = false ) {
562                 # If autoblocks are disabled, go away.
563                 if ( !$this->mEnableAutoblock ) {
564                         return;
565                 }
566
567                 # Check for presence on the autoblock whitelist
568                 if (Block::isWhitelistedFromAutoblocks($autoblockIP)) {
569                         return;
570                 }
571                 
572                 ## Allow hooks to cancel the autoblock.
573                 if (!wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) )) {
574                         wfDebug( "Autoblock aborted by hook.\n" );
575                         return false;
576                 }
577
578                 # It's okay to autoblock. Go ahead and create/insert the block.
579
580                 $ipblock = Block::newFromDB( $autoblockIP );
581                 if ( $ipblock ) {
582                         # If the user is already blocked. Then check if the autoblock would
583                         # exceed the user block. If it would exceed, then do nothing, else
584                         # prolong block time
585                         if ($this->mExpiry &&
586                         ($this->mExpiry < Block::getAutoblockExpiry($ipblock->mTimestamp))) {
587                                 return;
588                         }
589                         # Just update the timestamp
590                         if ( !$justInserted ) {
591                                 $ipblock->updateTimestamp();
592                         }
593                         return;
594                 } else {
595                         $ipblock = new Block;
596                 }
597
598                 # Make a new block object with the desired properties
599                 wfDebug( "Autoblocking {$this->mAddress}@" . $autoblockIP . "\n" );
600                 $ipblock->mAddress = $autoblockIP;
601                 $ipblock->mUser = 0;
602                 $ipblock->mBy = $this->mBy;
603                 $ipblock->mByName = $this->mByName;
604                 $ipblock->mReason = wfMsgForContent( 'autoblocker', $this->mAddress, $this->mReason );
605                 $ipblock->mTimestamp = wfTimestampNow();
606                 $ipblock->mAuto = 1;
607                 $ipblock->mCreateAccount = $this->mCreateAccount;
608                 # Continue suppressing the name if needed
609                 $ipblock->mHideName = $this->mHideName;
610                 $ipblock->mAllowUsertalk = $this->mAllowUsertalk;
611                 # If the user is already blocked with an expiry date, we don't
612                 # want to pile on top of that!
613                 if($this->mExpiry) {
614                         $ipblock->mExpiry = min ( $this->mExpiry, Block::getAutoblockExpiry( $this->mTimestamp ));
615                 } else {
616                         $ipblock->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
617                 }
618                 # Insert it
619                 return $ipblock->insert();
620         }
621
622         /**
623          * Check if a block has expired. Delete it if it is.
624          * @return Boolean
625          */
626         public function deleteIfExpired() {
627                 $fname = 'Block::deleteIfExpired';
628                 wfProfileIn( $fname );
629                 if ( $this->isExpired() ) {
630                         wfDebug( "Block::deleteIfExpired() -- deleting\n" );
631                         $this->delete();
632                         $retVal = true;
633                 } else {
634                         wfDebug( "Block::deleteIfExpired() -- not expired\n" );
635                         $retVal = false;
636                 }
637                 wfProfileOut( $fname );
638                 return $retVal;
639         }
640
641         /**
642          * Has the block expired?
643          * @return Boolean
644          */
645         public function isExpired() {
646                 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
647                 if ( !$this->mExpiry ) {
648                         return false;
649                 } else {
650                         return wfTimestampNow() > $this->mExpiry;
651                 }
652         }
653
654         /**
655          * Is the block address valid (i.e. not a null string?)
656          * @return Boolean
657          */
658         public function isValid() {
659                 return $this->mAddress != '';
660         }
661
662         /**
663          * Update the timestamp on autoblocks. 
664          */
665         public function updateTimestamp() {
666                 if ( $this->mAuto ) {
667                         $this->mTimestamp = wfTimestamp();
668                         $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
669
670                         $dbw = wfGetDB( DB_MASTER );
671                         $dbw->update( 'ipblocks',
672                                 array( /* SET */
673                                         'ipb_timestamp' => $dbw->timestamp($this->mTimestamp),
674                                         'ipb_expiry' => $dbw->timestamp($this->mExpiry),
675                                 ), array( /* WHERE */
676                                         'ipb_address' => $this->mAddress
677                                 ), 'Block::updateTimestamp'
678                         );
679                 }
680         }
681
682         /**
683          * Get the user id of the blocking sysop
684          *
685          * @return Integer
686          */
687         public function getBy() {
688                 return $this->mBy;
689         }
690
691         /**
692          * Get the username of the blocking sysop
693          *
694          * @return String
695          */
696         public function getByName() {
697                 return $this->mByName;
698         }
699
700         /**
701          * Get/set the SELECT ... FOR UPDATE flag
702          */
703         public function forUpdate( $x = NULL ) {
704                 return wfSetVar( $this->mForUpdate, $x );
705         }
706
707         /**
708          * Get/set a flag determining whether the master is used for reads
709          */
710         public function fromMaster( $x = NULL ) {
711                 return wfSetVar( $this->mFromMaster, $x );
712         }
713
714         /**
715          * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
716          * @return String
717          */
718         public function getRedactedName() {
719                 if ( $this->mAuto ) {
720                         return '#' . $this->mId;
721                 } else {
722                         return $this->mAddress;
723                 }
724         }
725
726         /**
727          * Encode expiry for DB
728          *
729          * @param $expiry String: timestamp for expiry, or 
730          * @param $db Database object
731          * @return String
732          */
733         public static function encodeExpiry( $expiry, $db ) {
734                 if ( $expiry == '' || $expiry == Block::infinity() ) {
735                         return Block::infinity();
736                 } else {
737                         return $db->timestamp( $expiry );
738                 }
739         }
740
741         /**
742          * Decode expiry which has come from the DB
743          *
744          * @param $expiry String: Database expiry format
745          * @param $timestampType Requested timestamp format
746          * @return String
747          */
748         public static function decodeExpiry( $expiry, $timestampType = TS_MW ) {
749                 if ( $expiry == '' || $expiry == Block::infinity() ) {
750                         return Block::infinity();
751                 } else {
752                         return wfTimestamp( $timestampType, $expiry );
753                 }
754         }
755
756         /**
757          * Get a timestamp of the expiry for autoblocks
758          *
759          * @return String
760          */
761         public static function getAutoblockExpiry( $timestamp ) {
762                 global $wgAutoblockExpiry;
763                 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
764         }
765
766         /**
767          * Gets rid of uneeded numbers in quad-dotted/octet IP strings
768          * For example, 127.111.113.151/24 -> 127.111.113.0/24
769          * @param $range String: IP address to normalize
770          * @return string
771          */
772         public static function normaliseRange( $range ) {
773                 $parts = explode( '/', $range );
774                 if ( count( $parts ) == 2 ) {
775                         // IPv6
776                         if ( IP::isIPv6($range) && $parts[1] >= 64 && $parts[1] <= 128 ) {
777                                 $bits = $parts[1];
778                                 $ipint = IP::toUnsigned6( $parts[0] );
779                                 # Native 32 bit functions WONT work here!!!
780                                 # Convert to a padded binary number
781                                 $network = wfBaseConvert( $ipint, 10, 2, 128 );
782                                 # Truncate the last (128-$bits) bits and replace them with zeros
783                                 $network = str_pad( substr( $network, 0, $bits ), 128, 0, STR_PAD_RIGHT );
784                                 # Convert back to an integer
785                                 $network = wfBaseConvert( $network, 2, 10 );
786                                 # Reform octet address
787                                 $newip = IP::toOctet( $network );
788                                 $range = "$newip/{$parts[1]}";
789                         } // IPv4
790                         else if ( IP::isIPv4($range) && $parts[1] >= 16 && $parts[1] <= 32 ) {
791                                 $shift = 32 - $parts[1];
792                                 $ipint = IP::toUnsigned( $parts[0] );
793                                 $ipint = $ipint >> $shift << $shift;
794                                 $newip = long2ip( $ipint );
795                                 $range = "$newip/{$parts[1]}";
796                         }
797                 }
798                 return $range;
799         }
800
801         /**
802          * Purge expired blocks from the ipblocks table
803          */
804         public static function purgeExpired() {
805                 $dbw = wfGetDB( DB_MASTER );
806                 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
807         }
808
809         /**
810          * Get a value to insert into expiry field of the database when infinite expiry
811          * is desired. In principle this could be DBMS-dependant, but currently all 
812          * supported DBMS's support the string "infinity", so we just use that.
813          *
814          * @return String
815          */
816         public static function infinity() {
817                 # This is a special keyword for timestamps in PostgreSQL, and
818                 # works with CHAR(14) as well because "i" sorts after all numbers.
819                 return 'infinity';
820         }
821         
822         /**
823          * Convert a DB-encoded expiry into a real string that humans can read.
824          *
825          * @param $encoded_expiry String: Database encoded expiry time
826          * @return String
827          */
828         public static function formatExpiry( $encoded_expiry ) {
829                 static $msg = null;
830                 
831                 if( is_null( $msg ) ) {
832                         $msg = array();
833                         $keys = array( 'infiniteblock', 'expiringblock' );
834                         foreach( $keys as $key ) {
835                                 $msg[$key] = wfMsgHtml( $key );
836                         }
837                 }
838                 
839                 $expiry = Block::decodeExpiry( $encoded_expiry );
840                 if ($expiry == 'infinity') {
841                         $expirystr = $msg['infiniteblock'];
842                 } else {
843                         global $wgLang;
844                         $expiretimestr = $wgLang->timeanddate( $expiry, true );
845                         $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array($expiretimestr) );
846                 }
847                 return $expirystr;
848         }
849         
850         /**
851          * Convert a typed-in expiry time into something we can put into the database.
852          * @param $expiry_input String: whatever was typed into the form
853          * @return String: more database friendly
854          */
855         public static function parseExpiryInput( $expiry_input ) {
856                 if ( $expiry_input == 'infinite' || $expiry_input == 'indefinite' ) {
857                         $expiry = 'infinity';
858                 } else {
859                         $expiry = strtotime( $expiry_input );
860                         if ($expiry < 0 || $expiry === false) {
861                                 return false;
862                         }
863                 }
864                 return $expiry;
865         }
866
867 }