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