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