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