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