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