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