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