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