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