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