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