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