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