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