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