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