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