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