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