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