* (bug 29116) Fix regression breaking CheckUser extension
[lhc/web/wiklou.git] / includes / Block.php
1 <?php
2 /**
3 * Blocks and bans object
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22 class Block {
23 /* public*/ var $mReason, $mTimestamp, $mAuto, $mExpiry, $mHideName, $mAngryAutoblock;
24
25 protected
26 $mId,
27 $mFromMaster,
28
29 $mBlockEmail,
30 $mDisableUsertalk,
31 $mCreateAccount;
32
33 /// @var User|String
34 protected $target;
35
36 /// @var Block::TYPE_ constant. Can only be USER, IP or RANGE internally
37 protected $type;
38
39 /// @var User
40 protected $blocker;
41
42 /// @var Bool
43 protected $isHardblock = true;
44
45 /// @var Bool
46 protected $isAutoblocking = true;
47
48 # TYPE constants
49 const TYPE_USER = 1;
50 const TYPE_IP = 2;
51 const TYPE_RANGE = 3;
52 const TYPE_AUTO = 4;
53 const TYPE_ID = 5;
54
55 /**
56 * Constructor
57 * @todo FIXME: Don't know what the best format to have for this constructor is, but fourteen
58 * optional parameters certainly isn't it.
59 */
60 function __construct( $address = '', $user = 0, $by = 0, $reason = '',
61 $timestamp = 0, $auto = 0, $expiry = '', $anonOnly = 0, $createAccount = 0, $enableAutoblock = 0,
62 $hideName = 0, $blockEmail = 0, $allowUsertalk = 0 )
63 {
64 if( $timestamp === 0 ){
65 $timestamp = wfTimestampNow();
66 }
67
68 if( count( func_get_args() ) > 0 ){
69 # Soon... :D
70 # wfDeprecated( __METHOD__ . " with arguments" );
71 }
72
73 $this->setTarget( $address );
74 $this->setBlocker( User::newFromID( $by ) );
75 $this->mReason = $reason;
76 $this->mTimestamp = wfTimestamp( TS_MW, $timestamp );
77 $this->mAuto = $auto;
78 $this->isHardblock( !$anonOnly );
79 $this->prevents( 'createaccount', $createAccount );
80 $this->mExpiry = $expiry;
81 $this->isAutoblocking( $enableAutoblock );
82 $this->mHideName = $hideName;
83 $this->prevents( 'sendemail', $blockEmail );
84 $this->prevents( 'editownusertalk', !$allowUsertalk );
85
86 $this->mFromMaster = false;
87 $this->mAngryAutoblock = false;
88 }
89
90 /**
91 * Load a block from the database, using either the IP address or
92 * user ID. Tries the user ID first, and if that doesn't work, tries
93 * the address.
94 *
95 * @param $address String: IP address of user/anon
96 * @param $user Integer: user id of user
97 * @param $killExpired Boolean: delete expired blocks on load
98 * @return Block Object
99 * @deprecated since 1.18
100 */
101 public static function newFromDB( $address, $user = 0 ) {
102 return self::newFromTarget( User::whoIs( $user ), $address );
103 }
104
105 /**
106 * Load a blocked user from their block id.
107 *
108 * @param $id Integer: Block id to search for
109 * @return Block object
110 */
111 public static function newFromID( $id ) {
112 $dbr = wfGetDB( DB_SLAVE );
113 $res = $dbr->selectRow(
114 'ipblocks',
115 '*',
116 array( 'ipb_id' => $id ),
117 __METHOD__
118 );
119 return Block::newFromRow( $res );
120 }
121
122 /**
123 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
124 * the blocking user or the block timestamp, only things which affect the blocked user *
125 * @return Boolean
126 */
127 public function equals( Block $block ) {
128 return (
129 (string)$this->target == (string)$block->target
130 && $this->type == $block->type
131 && $this->mAuto == $block->mAuto
132 && $this->isHardblock() == $block->isHardblock()
133 && $this->prevents( 'createaccount' ) == $block->prevents( 'createaccount' )
134 && $this->mExpiry == $block->mExpiry
135 && $this->isAutoblocking() == $block->isAutoblocking()
136 && $this->mHideName == $block->mHideName
137 && $this->prevents( 'sendemail' ) == $block->prevents( 'sendemail' )
138 && $this->prevents( 'editownusertalk' ) == $block->prevents( 'editownusertalk' )
139 && $this->mReason == $block->mReason
140 );
141 }
142
143 /**
144 * Clear all member variables in the current object. Does not clear
145 * the block from the DB.
146 * @deprecated since 1.18
147 */
148 public function clear() {
149 # Noop
150 }
151
152 /**
153 * Get a block from the DB, with either the given address or the given username
154 *
155 * @param $address string The IP address of the user, or blank to skip IP blocks
156 * @param $user int The user ID, or zero for anonymous users
157 * @param $killExpired bool Whether to delete expired rows while loading
158 * @return Boolean: the user is blocked from editing
159 * @deprecated since 1.18
160 */
161 public function load( $address = '', $user = 0 ) {
162 wfDeprecated( __METHOD__ );
163 if( $user ){
164 $username = User::whoIs( $user );
165 $block = self::newFromTarget( $username, $address );
166 } else {
167 $block = self::newFromTarget( null, $address );
168 }
169
170 if( $block instanceof Block ){
171 # This is mildly evil, but hey, it's B/C :D
172 foreach( $block as $variable => $value ){
173 $this->$variable = $value;
174 }
175 return true;
176 } else {
177 return false;
178 }
179 }
180
181 /**
182 * Load a block from the database which affects the already-set $this->target:
183 * 1) A block directly on the given user or IP
184 * 2) A rangeblock encompasing the given IP (smallest first)
185 * 3) An autoblock on the given IP
186 * @param $vagueTarget User|String also search for blocks affecting this target. Doesn't
187 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
188 * @return Bool whether a relevant block was found
189 */
190 protected function newLoad( $vagueTarget = null ) {
191 $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_SLAVE );
192
193 if( $this->type !== null ){
194 $conds = array(
195 'ipb_address' => array( (string)$this->target ),
196 );
197 } else {
198 $conds = array( 'ipb_address' => array() );
199 }
200
201 # Be aware that the != '' check is explicit, since empty values will be passed by some callers.
202 if( $vagueTarget != ''){
203 list( $target, $type ) = self::parseTarget( $vagueTarget );
204 switch( $type ) {
205 case self::TYPE_USER:
206 # Slightly wierd, but who are we to argue?
207 $conds['ipb_address'][] = (string)$target;
208 break;
209
210 case self::TYPE_IP:
211 $conds['ipb_address'][] = (string)$target;
212 $conds[] = self::getRangeCond( IP::toHex( $target ) );
213 $conds = $db->makeList( $conds, LIST_OR );
214 break;
215
216 case self::TYPE_RANGE:
217 list( $start, $end ) = IP::parseRange( $target );
218 $conds['ipb_address'][] = (string)$target;
219 $conds[] = self::getRangeCond( $start, $end );
220 $conds = $db->makeList( $conds, LIST_OR );
221 break;
222
223 default:
224 throw new MWException( "Tried to load block with invalid type" );
225 }
226 }
227
228 $res = $db->select( 'ipblocks', '*', $conds, __METHOD__ );
229
230 # This result could contain a block on the user, a block on the IP, and a russian-doll
231 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
232 $bestRow = null;
233
234 # Lower will be better
235 $bestBlockScore = 100;
236
237 # This is begging for $this = $bestBlock, but that's not allowed in PHP :(
238 $bestBlockPreventsEdit = null;
239
240 foreach( $res as $row ){
241 $block = Block::newFromRow( $row );
242
243 # Don't use expired blocks
244 if( $block->deleteIfExpired() ){
245 continue;
246 }
247
248 # Don't use anon only blocks on users
249 if( $this->type == self::TYPE_USER && !$block->isHardblock() ){
250 continue;
251 }
252
253 if( $block->getType() == self::TYPE_RANGE ){
254 # This is the number of bits that are allowed to vary in the block, give
255 # or take some floating point errors
256 $end = wfBaseconvert( $block->getRangeEnd(), 16, 10 );
257 $start = wfBaseconvert( $block->getRangeStart(), 16, 10 );
258 $size = log( $end - $start + 1, 2 );
259
260 # This has the nice property that a /32 block is ranked equally with a
261 # single-IP block, which is exactly what it is...
262 $score = self::TYPE_RANGE - 1 + ( $size / 128 );
263
264 } else {
265 $score = $block->getType();
266 }
267
268 if( $score < $bestBlockScore ){
269 $bestBlockScore = $score;
270 $bestRow = $row;
271 $bestBlockPreventsEdit = $block->prevents( 'edit' );
272 }
273 }
274
275 if( $bestRow !== null ){
276 $this->initFromRow( $bestRow );
277 $this->prevents( 'edit', $bestBlockPreventsEdit );
278 return true;
279 } else {
280 return false;
281 }
282 }
283
284 /**
285 * Get a set of SQL conditions which will select rangeblocks encompasing a given range
286 * @param $start String Hexadecimal IP representation
287 * @param $end String Hexadecimal IP represenation, or null to use $start = $end
288 * @return String
289 */
290 public static function getRangeCond( $start, $end = null ) {
291 if ( $end === null ) {
292 $end = $start;
293 }
294 # Per bug 14634, we want to include relevant active rangeblocks; for
295 # rangeblocks, we want to include larger ranges which enclose the given
296 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
297 # so we can improve performance by filtering on a LIKE clause
298 $chunk = self::getIpFragment( $start );
299 $dbr = wfGetDB( DB_SLAVE );
300 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
301
302 # Fairly hard to make a malicious SQL statement out of hex characters,
303 # but stranger things have happened...
304 $safeStart = $dbr->addQuotes( $start );
305 $safeEnd = $dbr->addQuotes( $end );
306
307 return $dbr->makeList(
308 array(
309 "ipb_range_start $like",
310 "ipb_range_start <= $safeStart",
311 "ipb_range_end >= $safeEnd",
312 ),
313 LIST_AND
314 );
315 }
316
317 /**
318 * Get the component of an IP address which is certain to be the same between an IP
319 * address and a rangeblock containing that IP address.
320 * @param $hex String Hexadecimal IP representation
321 * @return String
322 */
323 protected static function getIpFragment( $hex ) {
324 global $wgBlockCIDRLimit;
325 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
326 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
327 } else {
328 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
329 }
330 }
331
332 /**
333 * Given a database row from the ipblocks table, initialize
334 * member variables
335 * @param $row ResultWrapper: a row from the ipblocks table
336 */
337 protected function initFromRow( $row ) {
338 $this->setTarget( $row->ipb_address );
339 $this->setBlocker( User::newFromId( $row->ipb_by ) );
340
341 $this->mReason = $row->ipb_reason;
342 $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
343 $this->mAuto = $row->ipb_auto;
344 $this->mHideName = $row->ipb_deleted;
345 $this->mId = $row->ipb_id;
346 $this->mExpiry = $row->ipb_expiry;
347
348 $this->isHardblock( !$row->ipb_anon_only );
349 $this->isAutoblocking( $row->ipb_enable_autoblock );
350
351 $this->prevents( 'createaccount', $row->ipb_create_account );
352 $this->prevents( 'sendemail', $row->ipb_block_email );
353 $this->prevents( 'editownusertalk', !$row->ipb_allow_usertalk );
354 }
355
356 /**
357 * Create a new Block object from a database row
358 * @param $row ResultWrapper row from the ipblocks table
359 * @return Block
360 */
361 public static function newFromRow( $row ){
362 $block = new Block;
363 $block->initFromRow( $row );
364 return $block;
365 }
366
367 /**
368 * Delete the row from the IP blocks table.
369 *
370 * @return Boolean
371 */
372 public function delete() {
373 if ( wfReadOnly() ) {
374 return false;
375 }
376
377 if ( !$this->getId() ) {
378 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
379 }
380
381 $dbw = wfGetDB( DB_MASTER );
382 $dbw->delete( 'ipblocks', array( 'ipb_id' => $this->getId() ), __METHOD__ );
383
384 return $dbw->affectedRows() > 0;
385 }
386
387 /**
388 * Insert a block into the block table. Will fail if there is a conflicting
389 * block (same name and options) already in the database.
390 *
391 * @return mixed: false on failure, assoc array on success:
392 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
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
401 # Don't collide with expired blocks
402 Block::purgeExpired();
403
404 $ipb_id = $dbw->nextSequenceValue( 'ipblocks_ipb_id_seq' );
405 $dbw->insert(
406 'ipblocks',
407 $this->getDatabaseArray(),
408 __METHOD__,
409 array( 'IGNORE' )
410 );
411 $affected = $dbw->affectedRows();
412
413 if ( $affected ) {
414 $auto_ipd_ids = $this->doRetroactiveAutoblock();
415 return array( 'id' => $ipb_id, 'autoIds' => $auto_ipd_ids );
416 }
417
418 return false;
419 }
420
421 /**
422 * Update a block in the DB with new parameters.
423 * The ID field needs to be loaded first.
424 */
425 public function update() {
426 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
427 $dbw = wfGetDB( DB_MASTER );
428
429 $dbw->update(
430 'ipblocks',
431 $this->getDatabaseArray( $dbw ),
432 array( 'ipb_id' => $this->getId() ),
433 __METHOD__
434 );
435
436 return $dbw->affectedRows();
437 }
438
439 /**
440 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
441 * @param $db DatabaseBase
442 * @return Array
443 */
444 protected function getDatabaseArray( $db = null ){
445 if( !$db ){
446 $db = wfGetDB( DB_SLAVE );
447 }
448 $this->mExpiry = $db->encodeExpiry( $this->mExpiry );
449
450 $a = array(
451 'ipb_address' => (string)$this->target,
452 'ipb_user' => $this->target instanceof User ? $this->target->getID() : 0,
453 'ipb_by' => $this->getBlocker()->getId(),
454 'ipb_by_text' => $this->getBlocker()->getName(),
455 'ipb_reason' => $this->mReason,
456 'ipb_timestamp' => $db->timestamp( $this->mTimestamp ),
457 'ipb_auto' => $this->mAuto,
458 'ipb_anon_only' => !$this->isHardblock(),
459 'ipb_create_account' => $this->prevents( 'createaccount' ),
460 'ipb_enable_autoblock' => $this->isAutoblocking(),
461 'ipb_expiry' => $this->mExpiry,
462 'ipb_range_start' => $this->getRangeStart(),
463 'ipb_range_end' => $this->getRangeEnd(),
464 'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
465 'ipb_block_email' => $this->prevents( 'sendemail' ),
466 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' )
467 );
468
469 return $a;
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 Array: block IDs of retroactive autoblocks made
477 */
478 protected function doRetroactiveAutoblock() {
479 $blockIds = array();
480
481 $dbr = wfGetDB( DB_SLAVE );
482 # If autoblock is enabled, autoblock the LAST IP used
483 # - stolen shamelessly from CheckUser_body.php
484
485 if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
486 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
487
488 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
489 $conds = array( 'rc_user_text' => (string)$this->getTarget() );
490
491 if ( $this->mAngryAutoblock ) {
492 // Block any IP used in the last 7 days. Up to five IPs.
493 $conds[] = 'rc_timestamp < ' .
494 $dbr->addQuotes( $dbr->timestamp( time() - ( 7 * 86400 ) ) );
495 $options['LIMIT'] = 5;
496 } else {
497 // Just the last IP used.
498 $options['LIMIT'] = 1;
499 }
500
501 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
502 __METHOD__ , $options );
503
504 if ( !$dbr->numRows( $res ) ) {
505 # No results, don't autoblock anything
506 wfDebug( "No IP found to retroactively autoblock\n" );
507 } else {
508 foreach ( $res as $row ) {
509 if ( $row->rc_ip ) {
510 $id = $this->doAutoblock( $row->rc_ip );
511 if ( $id ) $blockIds[] = $id;
512 }
513 }
514 }
515 }
516 return $blockIds;
517 }
518
519 /**
520 * Checks whether a given IP is on the autoblock whitelist.
521 * TODO: this probably belongs somewhere else, but not sure where...
522 *
523 * @param $ip String: The IP to check
524 * @return Boolean
525 */
526 public static function isWhitelistedFromAutoblocks( $ip ) {
527 global $wgMemc;
528
529 // Try to get the autoblock_whitelist from the cache, as it's faster
530 // than getting the msg raw and explode()'ing it.
531 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
532 $lines = $wgMemc->get( $key );
533 if ( !$lines ) {
534 $lines = explode( "\n", wfMsgForContentNoTrans( 'autoblock_whitelist' ) );
535 $wgMemc->set( $key, $lines, 3600 * 24 );
536 }
537
538 wfDebug( "Checking the autoblock whitelist..\n" );
539
540 foreach ( $lines as $line ) {
541 # List items only
542 if ( substr( $line, 0, 1 ) !== '*' ) {
543 continue;
544 }
545
546 $wlEntry = substr( $line, 1 );
547 $wlEntry = trim( $wlEntry );
548
549 wfDebug( "Checking $ip against $wlEntry..." );
550
551 # Is the IP in this range?
552 if ( IP::isInRange( $ip, $wlEntry ) ) {
553 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
554 return true;
555 } else {
556 wfDebug( " No match\n" );
557 }
558 }
559
560 return false;
561 }
562
563 /**
564 * Autoblocks the given IP, referring to this Block.
565 *
566 * @param $autoblockIP String: the IP to autoblock.
567 * @return mixed: block ID if an autoblock was inserted, false if not.
568 */
569 public function doAutoblock( $autoblockIP ) {
570 # If autoblocks are disabled, go away.
571 if ( !$this->isAutoblocking() ) {
572 return false;
573 }
574
575 # Check for presence on the autoblock whitelist
576 if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
577 return false;
578 }
579
580 # # Allow hooks to cancel the autoblock.
581 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
582 wfDebug( "Autoblock aborted by hook.\n" );
583 return false;
584 }
585
586 # It's okay to autoblock. Go ahead and create/insert the block.
587
588 $ipblock = Block::newFromTarget( $autoblockIP );
589 if ( $ipblock ) {
590 # If the user is already blocked. Then check if the autoblock would
591 # exceed the user block. If it would exceed, then do nothing, else
592 # prolong block time
593 if ( $this->mExpiry > Block::getAutoblockExpiry( $ipblock->mTimestamp )
594 ) {
595 # If the block is an autoblock, reset its timestamp to now and its expiry
596 # to an $wgAutoblockExpiry in the future; otherwise do nothing
597 $ipblock->updateTimestamp();
598 }
599 return false;
600
601 }
602
603 # Make a new block object with the desired properties
604 $autoblock = new Block;
605 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
606 $autoblock->setTarget( $autoblockIP );
607 $autoblock->setBlocker( $this->getBlocker() );
608 $autoblock->mReason = wfMsgForContent( 'autoblocker', $this->getTarget(), $this->mReason );
609 $autoblock->mTimestamp = wfTimestampNow();
610 $autoblock->mAuto = 1;
611 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
612 # Continue suppressing the name if needed
613 $autoblock->mHideName = $this->mHideName;
614 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
615
616 $dbr = wfGetDB( DB_SLAVE );
617 if ( $this->mTimestamp == $dbr->getInfinity() ) {
618 # Original block was indefinite, start an autoblock now
619 $autoblock->mExpiry = Block::getAutoblockExpiry( wfTimestampNow() );
620 } else {
621 # If the user is already blocked with an expiry date, we don't
622 # want to pile on top of that.
623 $autoblock->mExpiry = min( $this->mExpiry, Block::getAutoblockExpiry( wfTimestampNow() ) );
624 }
625
626 # Insert it
627 $status = $autoblock->insert();
628 return $status
629 ? $status['id']
630 : false;
631 }
632
633 /**
634 * Check if a block has expired. Delete it if it is.
635 * @return Boolean
636 */
637 public function deleteIfExpired() {
638 wfProfileIn( __METHOD__ );
639
640 if ( $this->isExpired() ) {
641 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
642 $this->delete();
643 $retVal = true;
644 } else {
645 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
646 $retVal = false;
647 }
648
649 wfProfileOut( __METHOD__ );
650 return $retVal;
651 }
652
653 /**
654 * Has the block expired?
655 * @return Boolean
656 */
657 public function isExpired() {
658 wfDebug( "Block::isExpired() checking current " . wfTimestampNow() . " vs $this->mExpiry\n" );
659
660 if ( !$this->mExpiry ) {
661 return false;
662 } else {
663 return wfTimestampNow() > $this->mExpiry;
664 }
665 }
666
667 /**
668 * Is the block address valid (i.e. not a null string?)
669 * @return Boolean
670 */
671 public function isValid() {
672 return $this->getTarget() != null;
673 }
674
675 /**
676 * Update the timestamp on autoblocks.
677 */
678 public function updateTimestamp() {
679 if ( $this->mAuto ) {
680 $this->mTimestamp = wfTimestamp();
681 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
682
683 $dbw = wfGetDB( DB_MASTER );
684 $dbw->update( 'ipblocks',
685 array( /* SET */
686 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
687 'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
688 ),
689 array( /* WHERE */
690 'ipb_address' => (string)$this->getTarget()
691 ),
692 __METHOD__
693 );
694 }
695 }
696
697 /**
698 * Get the IP address at the start of the range in Hex form
699 * @return String IP in Hex form
700 */
701 public function getRangeStart() {
702 switch( $this->type ) {
703 case self::TYPE_USER:
704 return null;
705 case self::TYPE_IP:
706 return IP::toHex( $this->target );
707 case self::TYPE_RANGE:
708 list( $start, /*...*/ ) = IP::parseRange( $this->target );
709 return $start;
710 default: throw new MWException( "Block with invalid type" );
711 }
712 }
713
714 /**
715 * Get the IP address at the start of the range in Hex form
716 * @return String IP in Hex form
717 */
718 public function getRangeEnd() {
719 switch( $this->type ) {
720 case self::TYPE_USER:
721 return null;
722 case self::TYPE_IP:
723 return IP::toHex( $this->target );
724 case self::TYPE_RANGE:
725 list( /*...*/, $end ) = IP::parseRange( $this->target );
726 return $end;
727 default: throw new MWException( "Block with invalid type" );
728 }
729 }
730
731 /**
732 * Get the user id of the blocking sysop
733 *
734 * @return Integer
735 */
736 public function getBy() {
737 return $this->getBlocker() instanceof User
738 ? $this->getBlocker()->getId()
739 : 0;
740 }
741
742 /**
743 * Get the username of the blocking sysop
744 *
745 * @return String
746 */
747 public function getByName() {
748 return $this->getBlocker() instanceof User
749 ? $this->getBlocker()->getName()
750 : null;
751 }
752
753 /**
754 * Get the block ID
755 * @return int
756 */
757 public function getId() {
758 return $this->mId;
759 }
760
761 /**
762 * Get/set the SELECT ... FOR UPDATE flag
763 * @deprecated since 1.18
764 */
765 public function forUpdate( $x = null ) {
766 # noop
767 }
768
769 /**
770 * Get/set a flag determining whether the master is used for reads
771 */
772 public function fromMaster( $x = null ) {
773 return wfSetVar( $this->mFromMaster, $x );
774 }
775
776 /**
777 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range
778 * @param $x Bool
779 * @return Bool
780 */
781 public function isHardblock( $x = null ) {
782 wfSetVar( $this->isHardblock, $x );
783
784 # You can't *not* hardblock a user
785 return $this->getType() == self::TYPE_USER
786 ? true
787 : $this->isHardblock;
788 }
789
790 public function isAutoblocking( $x = null ) {
791 wfSetVar( $this->isAutoblocking, $x );
792
793 # You can't put an autoblock on an IP or range as we don't have any history to
794 # look over to get more IPs from
795 return $this->getType() == self::TYPE_USER
796 ? $this->isAutoblocking
797 : false;
798 }
799
800 /**
801 * Get/set whether the Block prevents a given action
802 * @param $action String
803 * @param $x Bool
804 * @return Bool
805 */
806 public function prevents( $action, $x = null ) {
807 switch( $action ) {
808 case 'edit':
809 # For now... <evil laugh>
810 return true;
811
812 case 'createaccount':
813 return wfSetVar( $this->mCreateAccount, $x );
814
815 case 'sendemail':
816 return wfSetVar( $this->mBlockEmail, $x );
817
818 case 'editownusertalk':
819 return wfSetVar( $this->mDisableUsertalk, $x );
820
821 default:
822 return null;
823 }
824 }
825
826 /**
827 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
828 * @return String, text is escaped
829 */
830 public function getRedactedName() {
831 if ( $this->mAuto ) {
832 return Html::rawElement(
833 'span',
834 array( 'class' => 'mw-autoblockid' ),
835 wfMessage( 'autoblockid', $this->mId )
836 );
837 } else {
838 return htmlspecialchars( $this->getTarget() );
839 }
840 }
841
842 /**
843 * Encode expiry for DB
844 *
845 * @param $expiry String: timestamp for expiry, or
846 * @param $db Database object
847 * @return String
848 * @deprecated since 1.18; use $dbw->encodeExpiry() instead
849 */
850 public static function encodeExpiry( $expiry, $db ) {
851 return $db->encodeExpiry( $expiry );
852 }
853
854 /**
855 * Decode expiry which has come from the DB
856 *
857 * @param $expiry String: Database expiry format
858 * @param $timestampType Requested timestamp format
859 * @return String
860 * @deprecated since 1.18; use $wgLang->decodeExpiry() instead
861 */
862 public static function decodeExpiry( $expiry, $timestampType = TS_MW ) {
863 global $wgContLang;
864 return $wgContLang->formatExpiry( $expiry, $timestampType );
865 }
866
867 /**
868 * Get a timestamp of the expiry for autoblocks
869 *
870 * @return String
871 */
872 public static function getAutoblockExpiry( $timestamp ) {
873 global $wgAutoblockExpiry;
874
875 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
876 }
877
878 /**
879 * Gets rid of uneeded numbers in quad-dotted/octet IP strings
880 * For example, 127.111.113.151/24 -> 127.111.113.0/24
881 * @param $range String: IP address to normalize
882 * @return string
883 * @deprecated since 1.18, call IP::sanitizeRange() directly
884 */
885 public static function normaliseRange( $range ) {
886 return IP::sanitizeRange( $range );
887 }
888
889 /**
890 * Purge expired blocks from the ipblocks table
891 */
892 public static function purgeExpired() {
893 $dbw = wfGetDB( DB_MASTER );
894 $dbw->delete( 'ipblocks', array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), __METHOD__ );
895 }
896
897 /**
898 * Get a value to insert into expiry field of the database when infinite expiry
899 * is desired
900 * @deprecated since 1.18, call $dbr->getInfinity() directly
901 * @return String
902 */
903 public static function infinity() {
904 return wfGetDB( DB_SLAVE )->getInfinity();
905 }
906
907 /**
908 * Convert a DB-encoded expiry into a real string that humans can read.
909 *
910 * @param $encoded_expiry String: Database encoded expiry time
911 * @return Html-escaped String
912 * @deprecated since 1.18; use $wgLang->formatExpiry() instead
913 */
914 public static function formatExpiry( $encoded_expiry ) {
915 global $wgContLang;
916 static $msg = null;
917
918 if ( is_null( $msg ) ) {
919 $msg = array();
920 $keys = array( 'infiniteblock', 'expiringblock' );
921
922 foreach ( $keys as $key ) {
923 $msg[$key] = wfMsgHtml( $key );
924 }
925 }
926
927 $expiry = $wgContLang->formatExpiry( $encoded_expiry, TS_MW );
928 if ( $expiry == wfGetDB( DB_SLAVE )->getInfinity() ) {
929 $expirystr = $msg['infiniteblock'];
930 } else {
931 global $wgLang;
932 $expiredatestr = htmlspecialchars( $wgLang->date( $expiry, true ) );
933 $expiretimestr = htmlspecialchars( $wgLang->time( $expiry, true ) );
934 $expirystr = wfMsgReplaceArgs( $msg['expiringblock'], array( $expiredatestr, $expiretimestr ) );
935 }
936
937 return $expirystr;
938 }
939
940 /**
941 * Convert a submitted expiry time, which may be relative ("2 weeks", etc) or absolute
942 * ("24 May 2034"), into an absolute timestamp we can put into the database.
943 * @param $expiry String: whatever was typed into the form
944 * @return String: timestamp or "infinity" string for th DB implementation
945 * @deprecated since 1.18 moved to SpecialBlock::parseExpiryInput()
946 */
947 public static function parseExpiryInput( $expiry ) {
948 wfDeprecated( __METHOD__ );
949 return SpecialBlock::parseExpiryInput( $expiry );
950 }
951
952 /**
953 * Given a target and the target's type, get an existing Block object if possible.
954 * @param $specificTarget String|User|Int a block target, which may be one of several types:
955 * * A user to block, in which case $target will be a User
956 * * An IP to block, in which case $target will be a User generated by using
957 * User::newFromName( $ip, false ) to turn off name validation
958 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
959 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
960 * usernames
961 * Calling this with a user, IP address or range will not select autoblocks, and will
962 * only select a block where the targets match exactly (so looking for blocks on
963 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
964 * @param $vagueTarget String|User|Int as above, but we will search for *any* block which
965 * affects that target (so for an IP address, get ranges containing that IP; and also
966 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
967 * @param $fromMaster Bool whether to use the DB_MASTER database
968 * @return Block|null (null if no relevant block could be found). The target and type
969 * of the returned Block will refer to the actual block which was found, which might
970 * not be the same as the target you gave if you used $vagueTarget!
971 */
972 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
973 # (bug 29116) passing $vagueTarget = '' is not unreasonable here, but int(0)
974 # is a valid username, so we can't just use weak comparisons.
975 if( $vagueTarget === '' ){
976 $vagueTarget = null;
977 }
978
979 list( $target, $type ) = self::parseTarget( $specificTarget );
980 if( $type == Block::TYPE_ID || $type == Block::TYPE_AUTO ){
981 return Block::newFromID( $target );
982
983 } elseif( $target === null && $vagueTarget == '' ){
984 # We're not going to find anything useful here
985 # Be aware that the == '' check is explicit, since empty values will be passed by some callers.
986 return null;
987
988 } elseif( in_array( $type, array( Block::TYPE_USER, Block::TYPE_IP, Block::TYPE_RANGE, null ) ) ) {
989 $block = new Block();
990 $block->fromMaster( $fromMaster );
991
992 if( $type !== null ){
993 $block->setTarget( $target );
994 }
995
996 if( $block->newLoad( $vagueTarget ) ){
997 return $block;
998 } else {
999 return null;
1000 }
1001 } else {
1002 return null;
1003 }
1004 }
1005
1006 /**
1007 * From an existing Block, get the target and the type of target. Note that it is
1008 * always safe to treat the target as a string; for User objects this will return
1009 * User::__toString() which in turn gives User::getName().
1010 * @return array( User|String, Block::TYPE_ constant )
1011 */
1012 public static function parseTarget( $target ) {
1013 $target = trim( $target );
1014
1015 # We may have been through this before
1016 if( $target instanceof User ){
1017 if( IP::isValid( $target->getName() ) ){
1018 return array( $target, self::TYPE_IP );
1019 } else {
1020 return array( $target, self::TYPE_USER );
1021 }
1022 } elseif( $target === null ){
1023 return array( null, null );
1024 }
1025
1026 $userObj = User::newFromName( $target );
1027 if ( $userObj instanceof User ) {
1028 # Note that since numbers are valid usernames, a $target of "12345" will be
1029 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1030 # since hash characters are not valid in usernames or titles generally.
1031 return array( $userObj, Block::TYPE_USER );
1032
1033 } elseif ( IP::isValid( $target ) ) {
1034 # We can still create a User if it's an IP address, but we need to turn
1035 # off validation checking (which would exclude IP addresses)
1036 return array(
1037 User::newFromName( IP::sanitizeIP( $target ), false ),
1038 Block::TYPE_IP
1039 );
1040
1041 } elseif ( IP::isValidBlock( $target ) ) {
1042 # Can't create a User from an IP range
1043 return array( IP::sanitizeRange( $target ), Block::TYPE_RANGE );
1044
1045 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1046 # Autoblock reference in the form "#12345"
1047 return array( substr( $target, 1 ), Block::TYPE_AUTO );
1048
1049 } else {
1050 # WTF?
1051 return array( null, null );
1052 }
1053 }
1054
1055 /**
1056 * Get the type of target for this particular block
1057 * @return Block::TYPE_ constant, will never be TYPE_ID
1058 */
1059 public function getType() {
1060 return $this->mAuto
1061 ? self::TYPE_AUTO
1062 : $this->type;
1063 }
1064
1065 /**
1066 * Get the target and target type for this particular Block. Note that for autoblocks,
1067 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1068 * in this situation.
1069 * @return array( User|String, Block::TYPE_ constant )
1070 * @todo FIXME: This should be an integral part of the Block member variables
1071 */
1072 public function getTargetAndType() {
1073 return array( $this->getTarget(), $this->getType() );
1074 }
1075
1076 /**
1077 * Get the target for this particular Block. Note that for autoblocks,
1078 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1079 * in this situation.
1080 * @return User|String
1081 */
1082 public function getTarget() {
1083 return $this->target;
1084 }
1085
1086 /**
1087 * Set the target for this block, and update $this->type accordingly
1088 * @param $target Mixed
1089 */
1090 public function setTarget( $target ){
1091 list( $this->target, $this->type ) = self::parseTarget( $target );
1092 }
1093
1094 /**
1095 * Get the user who implemented this block
1096 * @return User
1097 */
1098 public function getBlocker(){
1099 return $this->blocker;
1100 }
1101
1102 /**
1103 * Set the user who implemented (or will implement) this block
1104 * @param $user User
1105 */
1106 public function setBlocker( User $user ){
1107 $this->blocker = $user;
1108 }
1109 }