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