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