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