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