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