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