Added concurrent HEAD request support for Swift
[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 $dbw->update(
456 'ipblocks',
457 $this->getAutoblockUpdateArray(),
458 array( 'ipb_parent_block_id' => $this->getId() ),
459 __METHOD__
460 );
461
462 $dbw->endAtomic( __METHOD__ );
463
464 if ( $affected ) {
465 $auto_ipd_ids = $this->doRetroactiveAutoblock();
466 return array( 'id' => $this->mId, 'autoIds' => $auto_ipd_ids );
467 }
468
469 return false;
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 if ( $this->forcedTargetID ) {
484 $uid = $this->forcedTargetID;
485 } else {
486 $uid = $this->target instanceof User ? $this->target->getID() : 0;
487 }
488
489 $a = array(
490 'ipb_address' => (string)$this->target,
491 'ipb_user' => $uid,
492 'ipb_by' => $this->getBy(),
493 'ipb_by_text' => $this->getByName(),
494 'ipb_reason' => $this->mReason,
495 'ipb_timestamp' => $db->timestamp( $this->mTimestamp ),
496 'ipb_auto' => $this->mAuto,
497 'ipb_anon_only' => !$this->isHardblock(),
498 'ipb_create_account' => $this->prevents( 'createaccount' ),
499 'ipb_enable_autoblock' => $this->isAutoblocking(),
500 'ipb_expiry' => $expiry,
501 'ipb_range_start' => $this->getRangeStart(),
502 'ipb_range_end' => $this->getRangeEnd(),
503 'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
504 'ipb_block_email' => $this->prevents( 'sendemail' ),
505 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
506 'ipb_parent_block_id' => $this->mParentBlockId
507 );
508
509 return $a;
510 }
511
512 /**
513 * @return Array
514 */
515 protected function getAutoblockUpdateArray() {
516 return array(
517 'ipb_by' => $this->getBy(),
518 'ipb_by_text' => $this->getByName(),
519 'ipb_reason' => $this->mReason,
520 'ipb_create_account' => $this->prevents( 'createaccount' ),
521 'ipb_deleted' => (int)$this->mHideName, // typecast required for SQLite
522 'ipb_allow_usertalk' => !$this->prevents( 'editownusertalk' ),
523 );
524 }
525
526 /**
527 * Retroactively autoblocks the last IP used by the user (if it is a user)
528 * blocked by this Block.
529 *
530 * @return Array: block IDs of retroactive autoblocks made
531 */
532 protected function doRetroactiveAutoblock() {
533 $blockIds = array();
534 # If autoblock is enabled, autoblock the LAST IP(s) used
535 if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
536 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
537
538 $continue = wfRunHooks(
539 'PerformRetroactiveAutoblock', array( $this, &$blockIds ) );
540
541 if ( $continue ) {
542 self::defaultRetroactiveAutoblock( $this, $blockIds );
543 }
544 }
545 return $blockIds;
546 }
547
548 /**
549 * Retroactively autoblocks the last IP used by the user (if it is a user)
550 * blocked by this Block. This will use the recentchanges table.
551 *
552 * @param Block $block
553 * @param array &$blockIds
554 * @return Array: block IDs of retroactive autoblocks made
555 */
556 protected static function defaultRetroactiveAutoblock( Block $block, array &$blockIds ) {
557 global $wgPutIPinRC;
558
559 // No IPs are in recentchanges table, so nothing to select
560 if ( !$wgPutIPinRC ) {
561 return;
562 }
563
564 $dbr = wfGetDB( DB_SLAVE );
565
566 $options = array( 'ORDER BY' => 'rc_timestamp DESC' );
567 $conds = array( 'rc_user_text' => (string)$block->getTarget() );
568
569 // Just the last IP used.
570 $options['LIMIT'] = 1;
571
572 $res = $dbr->select( 'recentchanges', array( 'rc_ip' ), $conds,
573 __METHOD__, $options );
574
575 if ( !$res->numRows() ) {
576 # No results, don't autoblock anything
577 wfDebug( "No IP found to retroactively autoblock\n" );
578 } else {
579 foreach ( $res as $row ) {
580 if ( $row->rc_ip ) {
581 $id = $block->doAutoblock( $row->rc_ip );
582 if ( $id ) {
583 $blockIds[] = $id;
584 }
585 }
586 }
587 }
588 }
589
590 /**
591 * Checks whether a given IP is on the autoblock whitelist.
592 * TODO: this probably belongs somewhere else, but not sure where...
593 *
594 * @param string $ip The IP to check
595 * @return Boolean
596 */
597 public static function isWhitelistedFromAutoblocks( $ip ) {
598 global $wgMemc;
599
600 // Try to get the autoblock_whitelist from the cache, as it's faster
601 // than getting the msg raw and explode()'ing it.
602 $key = wfMemcKey( 'ipb', 'autoblock', 'whitelist' );
603 $lines = $wgMemc->get( $key );
604 if ( !$lines ) {
605 $lines = explode( "\n", wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
606 $wgMemc->set( $key, $lines, 3600 * 24 );
607 }
608
609 wfDebug( "Checking the autoblock whitelist..\n" );
610
611 foreach ( $lines as $line ) {
612 # List items only
613 if ( substr( $line, 0, 1 ) !== '*' ) {
614 continue;
615 }
616
617 $wlEntry = substr( $line, 1 );
618 $wlEntry = trim( $wlEntry );
619
620 wfDebug( "Checking $ip against $wlEntry..." );
621
622 # Is the IP in this range?
623 if ( IP::isInRange( $ip, $wlEntry ) ) {
624 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
625 return true;
626 } else {
627 wfDebug( " No match\n" );
628 }
629 }
630
631 return false;
632 }
633
634 /**
635 * Autoblocks the given IP, referring to this Block.
636 *
637 * @param string $autoblockIP the IP to autoblock.
638 * @return mixed: block ID if an autoblock was inserted, false if not.
639 */
640 public function doAutoblock( $autoblockIP ) {
641 # If autoblocks are disabled, go away.
642 if ( !$this->isAutoblocking() ) {
643 return false;
644 }
645
646 # Check for presence on the autoblock whitelist.
647 if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
648 return false;
649 }
650
651 # Allow hooks to cancel the autoblock.
652 if ( !wfRunHooks( 'AbortAutoblock', array( $autoblockIP, &$this ) ) ) {
653 wfDebug( "Autoblock aborted by hook.\n" );
654 return false;
655 }
656
657 # It's okay to autoblock. Go ahead and insert/update the block...
658
659 # Do not add a *new* block if the IP is already blocked.
660 $ipblock = Block::newFromTarget( $autoblockIP );
661 if ( $ipblock ) {
662 # Check if the block is an autoblock and would exceed the user block
663 # if renewed. If so, do nothing, otherwise prolong the block time...
664 if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
665 $this->mExpiry > Block::getAutoblockExpiry( $ipblock->mTimestamp )
666 ) {
667 # Reset block timestamp to now and its expiry to
668 # $wgAutoblockExpiry in the future
669 $ipblock->updateTimestamp();
670 }
671 return false;
672 }
673
674 # Make a new block object with the desired properties.
675 $autoblock = new Block;
676 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
677 $autoblock->setTarget( $autoblockIP );
678 $autoblock->setBlocker( $this->getBlocker() );
679 $autoblock->mReason = wfMessage( 'autoblocker', $this->getTarget(), $this->mReason )->inContentLanguage()->plain();
680 $timestamp = wfTimestampNow();
681 $autoblock->mTimestamp = $timestamp;
682 $autoblock->mAuto = 1;
683 $autoblock->prevents( 'createaccount', $this->prevents( 'createaccount' ) );
684 # Continue suppressing the name if needed
685 $autoblock->mHideName = $this->mHideName;
686 $autoblock->prevents( 'editownusertalk', $this->prevents( 'editownusertalk' ) );
687 $autoblock->mParentBlockId = $this->mId;
688
689 if ( $this->mExpiry == 'infinity' ) {
690 # Original block was indefinite, start an autoblock now
691 $autoblock->mExpiry = Block::getAutoblockExpiry( $timestamp );
692 } else {
693 # If the user is already blocked with an expiry date, we don't
694 # want to pile on top of that.
695 $autoblock->mExpiry = min( $this->mExpiry, Block::getAutoblockExpiry( $timestamp ) );
696 }
697
698 # Insert the block...
699 $status = $autoblock->insert();
700 return $status
701 ? $status['id']
702 : false;
703 }
704
705 /**
706 * Check if a block has expired. Delete it if it is.
707 * @return Boolean
708 */
709 public function deleteIfExpired() {
710 wfProfileIn( __METHOD__ );
711
712 if ( $this->isExpired() ) {
713 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
714 $this->delete();
715 $retVal = true;
716 } else {
717 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
718 $retVal = false;
719 }
720
721 wfProfileOut( __METHOD__ );
722 return $retVal;
723 }
724
725 /**
726 * Has the block expired?
727 * @return Boolean
728 */
729 public function isExpired() {
730 $timestamp = wfTimestampNow();
731 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
732
733 if ( !$this->mExpiry ) {
734 return false;
735 } else {
736 return $timestamp > $this->mExpiry;
737 }
738 }
739
740 /**
741 * Is the block address valid (i.e. not a null string?)
742 * @return Boolean
743 */
744 public function isValid() {
745 return $this->getTarget() != null;
746 }
747
748 /**
749 * Update the timestamp on autoblocks.
750 */
751 public function updateTimestamp() {
752 if ( $this->mAuto ) {
753 $this->mTimestamp = wfTimestamp();
754 $this->mExpiry = Block::getAutoblockExpiry( $this->mTimestamp );
755
756 $dbw = wfGetDB( DB_MASTER );
757 $dbw->update( 'ipblocks',
758 array( /* SET */
759 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
760 'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
761 ),
762 array( /* WHERE */
763 'ipb_address' => (string)$this->getTarget()
764 ),
765 __METHOD__
766 );
767 }
768 }
769
770 /**
771 * Get the IP address at the start of the range in Hex form
772 * @throws MWException
773 * @return String IP in Hex form
774 */
775 public function getRangeStart() {
776 switch ( $this->type ) {
777 case self::TYPE_USER:
778 return '';
779 case self::TYPE_IP:
780 return IP::toHex( $this->target );
781 case self::TYPE_RANGE:
782 list( $start, /*...*/ ) = IP::parseRange( $this->target );
783 return $start;
784 default:
785 throw new MWException( "Block with invalid type" );
786 }
787 }
788
789 /**
790 * Get the IP address at the end of the range in Hex form
791 * @throws MWException
792 * @return String IP in Hex form
793 */
794 public function getRangeEnd() {
795 switch ( $this->type ) {
796 case self::TYPE_USER:
797 return '';
798 case self::TYPE_IP:
799 return IP::toHex( $this->target );
800 case self::TYPE_RANGE:
801 list( /*...*/, $end ) = IP::parseRange( $this->target );
802 return $end;
803 default:
804 throw new MWException( "Block with invalid type" );
805 }
806 }
807
808 /**
809 * Get the user id of the blocking sysop
810 *
811 * @return Integer (0 for foreign users)
812 */
813 public function getBy() {
814 $blocker = $this->getBlocker();
815 return ( $blocker instanceof User )
816 ? $blocker->getId()
817 : 0;
818 }
819
820 /**
821 * Get the username of the blocking sysop
822 *
823 * @return String
824 */
825 public function getByName() {
826 $blocker = $this->getBlocker();
827 return ( $blocker instanceof User )
828 ? $blocker->getName()
829 : (string)$blocker; // username
830 }
831
832 /**
833 * Get the block ID
834 * @return int
835 */
836 public function getId() {
837 return $this->mId;
838 }
839
840 /**
841 * Get/set a flag determining whether the master is used for reads
842 *
843 * @param $x Bool
844 * @return Bool
845 */
846 public function fromMaster( $x = null ) {
847 return wfSetVar( $this->mFromMaster, $x );
848 }
849
850 /**
851 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range
852 * @param $x Bool
853 * @return Bool
854 */
855 public function isHardblock( $x = null ) {
856 wfSetVar( $this->isHardblock, $x );
857
858 # You can't *not* hardblock a user
859 return $this->getType() == self::TYPE_USER
860 ? true
861 : $this->isHardblock;
862 }
863
864 public function isAutoblocking( $x = null ) {
865 wfSetVar( $this->isAutoblocking, $x );
866
867 # You can't put an autoblock on an IP or range as we don't have any history to
868 # look over to get more IPs from
869 return $this->getType() == self::TYPE_USER
870 ? $this->isAutoblocking
871 : false;
872 }
873
874 /**
875 * Get/set whether the Block prevents a given action
876 * @param $action String
877 * @param $x Bool
878 * @return Bool
879 */
880 public function prevents( $action, $x = null ) {
881 switch ( $action ) {
882 case 'edit':
883 # For now... <evil laugh>
884 return true;
885
886 case 'createaccount':
887 return wfSetVar( $this->mCreateAccount, $x );
888
889 case 'sendemail':
890 return wfSetVar( $this->mBlockEmail, $x );
891
892 case 'editownusertalk':
893 return wfSetVar( $this->mDisableUsertalk, $x );
894
895 default:
896 return null;
897 }
898 }
899
900 /**
901 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
902 * @return String, text is escaped
903 */
904 public function getRedactedName() {
905 if ( $this->mAuto ) {
906 return Html::rawElement(
907 'span',
908 array( 'class' => 'mw-autoblockid' ),
909 wfMessage( 'autoblockid', $this->mId )
910 );
911 } else {
912 return htmlspecialchars( $this->getTarget() );
913 }
914 }
915
916 /**
917 * Get a timestamp of the expiry for autoblocks
918 *
919 * @param $timestamp String|Int
920 * @return String
921 */
922 public static function getAutoblockExpiry( $timestamp ) {
923 global $wgAutoblockExpiry;
924
925 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
926 }
927
928 /**
929 * Purge expired blocks from the ipblocks table
930 */
931 public static function purgeExpired() {
932 if ( wfReadOnly() ) {
933 return;
934 }
935
936 $method = __METHOD__;
937 $dbw = wfGetDB( DB_MASTER );
938 $dbw->onTransactionIdle( function() use ( $dbw, $method ) {
939 $dbw->delete( 'ipblocks',
940 array( 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ), $method );
941 } );
942 }
943
944 /**
945 * Given a target and the target's type, get an existing Block object if possible.
946 * @param $specificTarget String|User|Int a block target, which may be one of several types:
947 * * A user to block, in which case $target will be a User
948 * * An IP to block, in which case $target will be a User generated by using
949 * User::newFromName( $ip, false ) to turn off name validation
950 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
951 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
952 * usernames
953 * Calling this with a user, IP address or range will not select autoblocks, and will
954 * only select a block where the targets match exactly (so looking for blocks on
955 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
956 * @param $vagueTarget String|User|Int as above, but we will search for *any* block which
957 * affects that target (so for an IP address, get ranges containing that IP; and also
958 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
959 * @param bool $fromMaster whether to use the DB_MASTER database
960 * @return Block|null (null if no relevant block could be found). The target and type
961 * of the returned Block will refer to the actual block which was found, which might
962 * not be the same as the target you gave if you used $vagueTarget!
963 */
964 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
965
966 list( $target, $type ) = self::parseTarget( $specificTarget );
967 if ( $type == Block::TYPE_ID || $type == Block::TYPE_AUTO ) {
968 return Block::newFromID( $target );
969
970 } elseif ( $target === null && $vagueTarget == '' ) {
971 # We're not going to find anything useful here
972 # Be aware that the == '' check is explicit, since empty values will be
973 # passed by some callers (bug 29116)
974 return null;
975
976 } elseif ( in_array( $type, array( Block::TYPE_USER, Block::TYPE_IP, Block::TYPE_RANGE, null ) ) ) {
977 $block = new Block();
978 $block->fromMaster( $fromMaster );
979
980 if ( $type !== null ) {
981 $block->setTarget( $target );
982 }
983
984 if ( $block->newLoad( $vagueTarget ) ) {
985 return $block;
986 }
987 }
988 return null;
989 }
990
991 /**
992 * Get all blocks that match any IP from an array of IP addresses
993 *
994 * @param Array $ipChain list of IPs (strings), usually retrieved from the
995 * X-Forwarded-For header of the request
996 * @param Bool $isAnon Exclude anonymous-only blocks if false
997 * @param Bool $fromMaster Whether to query the master or slave database
998 * @return Array of Blocks
999 * @since 1.22
1000 */
1001 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1002 if ( !count( $ipChain ) ) {
1003 return array();
1004 }
1005
1006 wfProfileIn( __METHOD__ );
1007 $conds = array();
1008 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1009 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1010 # necessarily trust the header given to us, make sure that we are only
1011 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1012 # Do not treat private IP spaces as special as it may be desirable for wikis
1013 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1014 if ( !IP::isValid( $ipaddr ) ) {
1015 continue;
1016 }
1017 # Don't check trusted IPs (includes local squids which will be in every request)
1018 if ( wfIsTrustedProxy( $ipaddr ) ) {
1019 continue;
1020 }
1021 # Check both the original IP (to check against single blocks), as well as build
1022 # the clause to check for rangeblocks for the given IP.
1023 $conds['ipb_address'][] = $ipaddr;
1024 $conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
1025 }
1026
1027 if ( !count( $conds ) ) {
1028 wfProfileOut( __METHOD__ );
1029 return array();
1030 }
1031
1032 if ( $fromMaster ) {
1033 $db = wfGetDB( DB_MASTER );
1034 } else {
1035 $db = wfGetDB( DB_SLAVE );
1036 }
1037 $conds = $db->makeList( $conds, LIST_OR );
1038 if ( !$isAnon ) {
1039 $conds = array( $conds, 'ipb_anon_only' => 0 );
1040 }
1041 $selectFields = array_merge(
1042 array( 'ipb_range_start', 'ipb_range_end' ),
1043 Block::selectFields()
1044 );
1045 $rows = $db->select( 'ipblocks',
1046 $selectFields,
1047 $conds,
1048 __METHOD__
1049 );
1050
1051 $blocks = array();
1052 foreach ( $rows as $row ) {
1053 $block = self::newFromRow( $row );
1054 if ( !$block->deleteIfExpired() ) {
1055 $blocks[] = $block;
1056 }
1057 }
1058
1059 wfProfileOut( __METHOD__ );
1060 return $blocks;
1061 }
1062
1063 /**
1064 * From a list of multiple blocks, find the most exact and strongest Block.
1065 * The logic for finding the "best" block is:
1066 * - Blocks that match the block's target IP are preferred over ones in a range
1067 * - Hardblocks are chosen over softblocks that prevent account creation
1068 * - Softblocks that prevent account creation are chosen over other softblocks
1069 * - Other softblocks are chosen over autoblocks
1070 * - If there are multiple exact or range blocks at the same level, the one chosen
1071 * is random
1072
1073 * @param Array $ipChain list of IPs (strings). This is used to determine how "close"
1074 * a block is to the server, and if a block matches exactly, or is in a range.
1075 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1076 * local-squid, ...)
1077 * @param Array $block Array of blocks
1078 * @return Block|null the "best" block from the list
1079 */
1080 public static function chooseBlock( array $blocks, array $ipChain ) {
1081 if ( !count( $blocks ) ) {
1082 return null;
1083 } elseif ( count( $blocks ) == 1 ) {
1084 return $blocks[0];
1085 }
1086
1087 wfProfileIn( __METHOD__ );
1088
1089 // Sort hard blocks before soft ones and secondarily sort blocks
1090 // that disable account creation before those that don't.
1091 usort( $blocks, function( Block $a, Block $b ) {
1092 $aWeight = (int)$a->isHardblock() . (int)$a->prevents( 'createaccount' );
1093 $bWeight = (int)$b->isHardblock() . (int)$b->prevents( 'createaccount' );
1094 return strcmp( $bWeight, $aWeight ); // highest weight first
1095 } );
1096
1097 $blocksListExact = array(
1098 'hard' => false,
1099 'disable_create' => false,
1100 'other' => false,
1101 'auto' => false
1102 );
1103 $blocksListRange = array(
1104 'hard' => false,
1105 'disable_create' => false,
1106 'other' => false,
1107 'auto' => false
1108 );
1109 $ipChain = array_reverse( $ipChain );
1110
1111 foreach ( $blocks as $block ) {
1112 // Stop searching if we have already have a "better" block. This
1113 // is why the order of the blocks matters
1114 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1115 break;
1116 } elseif ( !$block->prevents( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1117 break;
1118 }
1119
1120 foreach ( $ipChain as $checkip ) {
1121 $checkipHex = IP::toHex( $checkip );
1122 if ( (string)$block->getTarget() === $checkip ) {
1123 if ( $block->isHardblock() ) {
1124 $blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
1125 } elseif ( $block->prevents( 'createaccount' ) ) {
1126 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
1127 } elseif ( $block->mAuto ) {
1128 $blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
1129 } else {
1130 $blocksListExact['other'] = $blocksListExact['other'] ?: $block;
1131 }
1132 // We found closest exact match in the ip list, so go to the next Block
1133 break;
1134 } elseif ( array_filter( $blocksListExact ) == array()
1135 && $block->getRangeStart() <= $checkipHex
1136 && $block->getRangeEnd() >= $checkipHex
1137 ) {
1138 if ( $block->isHardblock() ) {
1139 $blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
1140 } elseif ( $block->prevents( 'createaccount' ) ) {
1141 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
1142 } elseif ( $block->mAuto ) {
1143 $blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
1144 } else {
1145 $blocksListRange['other'] = $blocksListRange['other'] ?: $block;
1146 }
1147 break;
1148 }
1149 }
1150 }
1151
1152 if ( array_filter( $blocksListExact ) == array() ) {
1153 $blocksList = &$blocksListRange;
1154 } else {
1155 $blocksList = &$blocksListExact;
1156 }
1157
1158 $chosenBlock = null;
1159 if ( $blocksList['hard'] ) {
1160 $chosenBlock = $blocksList['hard'];
1161 } elseif ( $blocksList['disable_create'] ) {
1162 $chosenBlock = $blocksList['disable_create'];
1163 } elseif ( $blocksList['other'] ) {
1164 $chosenBlock = $blocksList['other'];
1165 } elseif ( $blocksList['auto'] ) {
1166 $chosenBlock = $blocksList['auto'];
1167 } else {
1168 wfProfileOut( __METHOD__ );
1169 throw new MWException( "Proxy block found, but couldn't be classified." );
1170 }
1171
1172 wfProfileOut( __METHOD__ );
1173 return $chosenBlock;
1174 }
1175
1176 /**
1177 * From an existing Block, get the target and the type of target.
1178 * Note that, except for null, it is always safe to treat the target
1179 * as a string; for User objects this will return User::__toString()
1180 * which in turn gives User::getName().
1181 *
1182 * @param $target String|Int|User|null
1183 * @return array( User|String|null, Block::TYPE_ constant|null )
1184 */
1185 public static function parseTarget( $target ) {
1186 # We may have been through this before
1187 if ( $target instanceof User ) {
1188 if ( IP::isValid( $target->getName() ) ) {
1189 return array( $target, self::TYPE_IP );
1190 } else {
1191 return array( $target, self::TYPE_USER );
1192 }
1193 } elseif ( $target === null ) {
1194 return array( null, null );
1195 }
1196
1197 $target = trim( $target );
1198
1199 if ( IP::isValid( $target ) ) {
1200 # We can still create a User if it's an IP address, but we need to turn
1201 # off validation checking (which would exclude IP addresses)
1202 return array(
1203 User::newFromName( IP::sanitizeIP( $target ), false ),
1204 Block::TYPE_IP
1205 );
1206
1207 } elseif ( IP::isValidBlock( $target ) ) {
1208 # Can't create a User from an IP range
1209 return array( IP::sanitizeRange( $target ), Block::TYPE_RANGE );
1210 }
1211
1212 # Consider the possibility that this is not a username at all
1213 # but actually an old subpage (bug #29797)
1214 if ( strpos( $target, '/' ) !== false ) {
1215 # An old subpage, drill down to the user behind it
1216 $parts = explode( '/', $target );
1217 $target = $parts[0];
1218 }
1219
1220 $userObj = User::newFromName( $target );
1221 if ( $userObj instanceof User ) {
1222 # Note that since numbers are valid usernames, a $target of "12345" will be
1223 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1224 # since hash characters are not valid in usernames or titles generally.
1225 return array( $userObj, Block::TYPE_USER );
1226
1227 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1228 # Autoblock reference in the form "#12345"
1229 return array( substr( $target, 1 ), Block::TYPE_AUTO );
1230
1231 } else {
1232 # WTF?
1233 return array( null, null );
1234 }
1235 }
1236
1237 /**
1238 * Get the type of target for this particular block
1239 * @return Block::TYPE_ constant, will never be TYPE_ID
1240 */
1241 public function getType() {
1242 return $this->mAuto
1243 ? self::TYPE_AUTO
1244 : $this->type;
1245 }
1246
1247 /**
1248 * Get the target and target type for this particular Block. Note that for autoblocks,
1249 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1250 * in this situation.
1251 * @return array( User|String, Block::TYPE_ constant )
1252 * @todo FIXME: This should be an integral part of the Block member variables
1253 */
1254 public function getTargetAndType() {
1255 return array( $this->getTarget(), $this->getType() );
1256 }
1257
1258 /**
1259 * Get the target for this particular Block. Note that for autoblocks,
1260 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1261 * in this situation.
1262 * @return User|String
1263 */
1264 public function getTarget() {
1265 return $this->target;
1266 }
1267
1268 /**
1269 * @since 1.19
1270 *
1271 * @return Mixed|string
1272 */
1273 public function getExpiry() {
1274 return $this->mExpiry;
1275 }
1276
1277 /**
1278 * Set the target for this block, and update $this->type accordingly
1279 * @param $target Mixed
1280 */
1281 public function setTarget( $target ) {
1282 list( $this->target, $this->type ) = self::parseTarget( $target );
1283 }
1284
1285 /**
1286 * Get the user who implemented this block
1287 * @return User|string Local User object or string for a foreign user
1288 */
1289 public function getBlocker() {
1290 return $this->blocker;
1291 }
1292
1293 /**
1294 * Set the user who implemented (or will implement) this block
1295 * @param $user User|string Local User object or username string for foreign users
1296 */
1297 public function setBlocker( $user ) {
1298 $this->blocker = $user;
1299 }
1300
1301 /**
1302 * Get the key and parameters for the corresponding error message.
1303 *
1304 * @since 1.22
1305 * @param IContextSource $context
1306 * @return array
1307 */
1308 public function getPermissionsError( IContextSource $context ) {
1309 $blocker = $this->getBlocker();
1310 if ( $blocker instanceof User ) { // local user
1311 $blockerUserpage = $blocker->getUserPage();
1312 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1313 } else { // foreign user
1314 $link = $blocker;
1315 }
1316
1317 $reason = $this->mReason;
1318 if ( $reason == '' ) {
1319 $reason = $context->msg( 'blockednoreason' )->text();
1320 }
1321
1322 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1323 * This could be a username, an IP range, or a single IP. */
1324 $intended = $this->getTarget();
1325
1326 $lang = $context->getLanguage();
1327 return array(
1328 $this->mAuto ? 'autoblockedtext' : 'blockedtext',
1329 $link,
1330 $reason,
1331 $context->getRequest()->getIP(),
1332 $this->getByName(),
1333 $this->getId(),
1334 $lang->formatExpiry( $this->mExpiry ),
1335 (string)$intended,
1336 $lang->timeanddate( wfTimestamp( TS_MW, $this->mTimestamp ), true ),
1337 );
1338 }
1339 }