Merge "don't die producing xml files if rev text export conversion fails"
[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
23 use Wikimedia\Rdbms\Database;
24 use Wikimedia\Rdbms\IDatabase;
25 use MediaWiki\Block\BlockRestriction;
26 use MediaWiki\Block\Restriction\Restriction;
27 use MediaWiki\Block\Restriction\NamespaceRestriction;
28 use MediaWiki\Block\Restriction\PageRestriction;
29 use MediaWiki\MediaWikiServices;
30
31 class Block {
32 /** @var string */
33 public $mReason;
34
35 /** @var string */
36 public $mTimestamp;
37
38 /** @var bool */
39 public $mAuto;
40
41 /** @var string */
42 public $mExpiry;
43
44 /** @var bool */
45 public $mHideName;
46
47 /** @var int */
48 public $mParentBlockId;
49
50 /** @var int */
51 private $mId;
52
53 /** @var bool */
54 private $mFromMaster;
55
56 /** @var bool */
57 private $mBlockEmail;
58
59 /** @var bool */
60 private $allowUsertalk;
61
62 /** @var bool */
63 private $blockCreateAccount;
64
65 /** @var User|string */
66 private $target;
67
68 /** @var int Hack for foreign blocking (CentralAuth) */
69 private $forcedTargetID;
70
71 /**
72 * @var int Block::TYPE_ constant. After the block has been loaded
73 * from the database, this can only be USER, IP or RANGE.
74 */
75 private $type;
76
77 /** @var User */
78 private $blocker;
79
80 /** @var bool */
81 private $isHardblock;
82
83 /** @var bool */
84 private $isAutoblocking;
85
86 /** @var string|null */
87 private $systemBlockType;
88
89 /** @var bool */
90 private $isSitewide;
91
92 /** @var Restriction[] */
93 private $restrictions;
94
95 # TYPE constants
96 const TYPE_USER = 1;
97 const TYPE_IP = 2;
98 const TYPE_RANGE = 3;
99 const TYPE_AUTO = 4;
100 const TYPE_ID = 5;
101
102 /**
103 * Create a new block with specified parameters on a user, IP or IP range.
104 *
105 * @param array $options Parameters of the block:
106 * address string|User Target user name, User object, IP address or IP range
107 * user int Override target user ID (for foreign users)
108 * by int User ID of the blocker
109 * reason string Reason of the block
110 * timestamp string The time at which the block comes into effect
111 * auto bool Is this an automatic block?
112 * expiry string Timestamp of expiration of the block or 'infinity'
113 * anonOnly bool Only disallow anonymous actions
114 * createAccount bool Disallow creation of new accounts
115 * enableAutoblock bool Enable automatic blocking
116 * hideName bool Hide the target user name
117 * blockEmail bool Disallow sending emails
118 * allowUsertalk bool Allow the target to edit its own talk page
119 * byText string Username of the blocker (for foreign users)
120 * systemBlock string Indicate that this block is automatically
121 * created by MediaWiki rather than being stored
122 * in the database. Value is a string to return
123 * from self::getSystemBlockType().
124 * sitewide bool Disallow editing all pages and all contribution
125 * actions, except those specifically allowed by
126 * other block flags
127 *
128 * @since 1.26 accepts $options array instead of individual parameters; order
129 * of parameters above reflects the original order
130 */
131 function __construct( $options = [] ) {
132 $defaults = [
133 'address' => '',
134 'user' => null,
135 'by' => null,
136 'reason' => '',
137 'timestamp' => '',
138 'auto' => false,
139 'expiry' => '',
140 'anonOnly' => false,
141 'createAccount' => false,
142 'enableAutoblock' => false,
143 'hideName' => false,
144 'blockEmail' => false,
145 'allowUsertalk' => false,
146 'byText' => '',
147 'systemBlock' => null,
148 'sitewide' => true,
149 ];
150
151 $options += $defaults;
152
153 $this->setTarget( $options['address'] );
154
155 if ( $this->target instanceof User && $options['user'] ) {
156 # Needed for foreign users
157 $this->forcedTargetID = $options['user'];
158 }
159
160 if ( $options['by'] ) {
161 # Local user
162 $this->setBlocker( User::newFromId( $options['by'] ) );
163 } else {
164 # Foreign user
165 $this->setBlocker( $options['byText'] );
166 }
167
168 $this->mReason = $options['reason'];
169 $this->mTimestamp = wfTimestamp( TS_MW, $options['timestamp'] );
170 $this->mExpiry = wfGetDB( DB_REPLICA )->decodeExpiry( $options['expiry'] );
171
172 # Boolean settings
173 $this->mAuto = (bool)$options['auto'];
174 $this->mHideName = (bool)$options['hideName'];
175 $this->isHardblock( !$options['anonOnly'] );
176 $this->isAutoblocking( (bool)$options['enableAutoblock'] );
177 $this->isSitewide( (bool)$options['sitewide'] );
178 $this->isEmailBlocked( (bool)$options['blockEmail'] );
179 $this->isCreateAccountBlocked( (bool)$options['createAccount'] );
180 $this->isUsertalkEditAllowed( (bool)$options['allowUsertalk'] );
181
182 $this->mFromMaster = false;
183 $this->systemBlockType = $options['systemBlock'];
184 }
185
186 /**
187 * Load a block from the block id.
188 *
189 * @param int $id Block id to search for
190 * @return Block|null
191 */
192 public static function newFromID( $id ) {
193 $dbr = wfGetDB( DB_REPLICA );
194 $blockQuery = self::getQueryInfo();
195 $res = $dbr->selectRow(
196 $blockQuery['tables'],
197 $blockQuery['fields'],
198 [ 'ipb_id' => $id ],
199 __METHOD__,
200 [],
201 $blockQuery['joins']
202 );
203 if ( $res ) {
204 return self::newFromRow( $res );
205 } else {
206 return null;
207 }
208 }
209
210 /**
211 * Return the list of ipblocks fields that should be selected to create
212 * a new block.
213 * @deprecated since 1.31, use self::getQueryInfo() instead.
214 * @return array
215 */
216 public static function selectFields() {
217 global $wgActorTableSchemaMigrationStage;
218
219 if ( $wgActorTableSchemaMigrationStage & SCHEMA_COMPAT_READ_NEW ) {
220 // If code is using this instead of self::getQueryInfo(), there's a
221 // decent chance it's going to try to directly access
222 // $row->ipb_by or $row->ipb_by_text and we can't give it
223 // useful values here once those aren't being used anymore.
224 throw new BadMethodCallException(
225 'Cannot use ' . __METHOD__
226 . ' when $wgActorTableSchemaMigrationStage has SCHEMA_COMPAT_READ_NEW'
227 );
228 }
229
230 wfDeprecated( __METHOD__, '1.31' );
231 return [
232 'ipb_id',
233 'ipb_address',
234 'ipb_by',
235 'ipb_by_text',
236 'ipb_by_actor' => 'NULL',
237 'ipb_timestamp',
238 'ipb_auto',
239 'ipb_anon_only',
240 'ipb_create_account',
241 'ipb_enable_autoblock',
242 'ipb_expiry',
243 'ipb_deleted',
244 'ipb_block_email',
245 'ipb_allow_usertalk',
246 'ipb_parent_block_id',
247 'ipb_sitewide',
248 ] + CommentStore::getStore()->getFields( 'ipb_reason' );
249 }
250
251 /**
252 * Return the tables, fields, and join conditions to be selected to create
253 * a new block object.
254 * @since 1.31
255 * @return array With three keys:
256 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
257 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
258 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
259 */
260 public static function getQueryInfo() {
261 $commentQuery = CommentStore::getStore()->getJoin( 'ipb_reason' );
262 $actorQuery = ActorMigration::newMigration()->getJoin( 'ipb_by' );
263 return [
264 'tables' => [ 'ipblocks' ] + $commentQuery['tables'] + $actorQuery['tables'],
265 'fields' => [
266 'ipb_id',
267 'ipb_address',
268 'ipb_timestamp',
269 'ipb_auto',
270 'ipb_anon_only',
271 'ipb_create_account',
272 'ipb_enable_autoblock',
273 'ipb_expiry',
274 'ipb_deleted',
275 'ipb_block_email',
276 'ipb_allow_usertalk',
277 'ipb_parent_block_id',
278 'ipb_sitewide',
279 ] + $commentQuery['fields'] + $actorQuery['fields'],
280 'joins' => $commentQuery['joins'] + $actorQuery['joins'],
281 ];
282 }
283
284 /**
285 * Check if two blocks are effectively equal. Doesn't check irrelevant things like
286 * the blocking user or the block timestamp, only things which affect the blocked user
287 *
288 * @param Block $block
289 *
290 * @return bool
291 */
292 public function equals( Block $block ) {
293 return (
294 (string)$this->target == (string)$block->target
295 && $this->type == $block->type
296 && $this->mAuto == $block->mAuto
297 && $this->isHardblock() == $block->isHardblock()
298 && $this->isCreateAccountBlocked() == $block->isCreateAccountBlocked()
299 && $this->mExpiry == $block->mExpiry
300 && $this->isAutoblocking() == $block->isAutoblocking()
301 && $this->mHideName == $block->mHideName
302 && $this->isEmailBlocked() == $block->isEmailBlocked()
303 && $this->isUsertalkEditAllowed() == $block->isUsertalkEditAllowed()
304 && $this->mReason == $block->mReason
305 && $this->isSitewide() == $block->isSitewide()
306 // Block::getRestrictions() may perform a database query, so keep it at
307 // the end.
308 && BlockRestriction::equals( $this->getRestrictions(), $block->getRestrictions() )
309 );
310 }
311
312 /**
313 * Load a block from the database which affects the already-set $this->target:
314 * 1) A block directly on the given user or IP
315 * 2) A rangeblock encompassing the given IP (smallest first)
316 * 3) An autoblock on the given IP
317 * @param User|string|null $vagueTarget Also search for blocks affecting this target. Doesn't
318 * make any sense to use TYPE_AUTO / TYPE_ID here. Leave blank to skip IP lookups.
319 * @throws MWException
320 * @return bool Whether a relevant block was found
321 */
322 protected function newLoad( $vagueTarget = null ) {
323 $db = wfGetDB( $this->mFromMaster ? DB_MASTER : DB_REPLICA );
324
325 if ( $this->type !== null ) {
326 $conds = [
327 'ipb_address' => [ (string)$this->target ],
328 ];
329 } else {
330 $conds = [ 'ipb_address' => [] ];
331 }
332
333 # Be aware that the != '' check is explicit, since empty values will be
334 # passed by some callers (T31116)
335 if ( $vagueTarget != '' ) {
336 list( $target, $type ) = self::parseTarget( $vagueTarget );
337 switch ( $type ) {
338 case self::TYPE_USER:
339 # Slightly weird, but who are we to argue?
340 $conds['ipb_address'][] = (string)$target;
341 break;
342
343 case self::TYPE_IP:
344 $conds['ipb_address'][] = (string)$target;
345 $conds[] = self::getRangeCond( IP::toHex( $target ) );
346 $conds = $db->makeList( $conds, LIST_OR );
347 break;
348
349 case self::TYPE_RANGE:
350 list( $start, $end ) = IP::parseRange( $target );
351 $conds['ipb_address'][] = (string)$target;
352 $conds[] = self::getRangeCond( $start, $end );
353 $conds = $db->makeList( $conds, LIST_OR );
354 break;
355
356 default:
357 throw new MWException( "Tried to load block with invalid type" );
358 }
359 }
360
361 $blockQuery = self::getQueryInfo();
362 $res = $db->select(
363 $blockQuery['tables'], $blockQuery['fields'], $conds, __METHOD__, [], $blockQuery['joins']
364 );
365
366 # This result could contain a block on the user, a block on the IP, and a russian-doll
367 # set of rangeblocks. We want to choose the most specific one, so keep a leader board.
368 $bestRow = null;
369
370 # Lower will be better
371 $bestBlockScore = 100;
372
373 foreach ( $res as $row ) {
374 $block = self::newFromRow( $row );
375
376 # Don't use expired blocks
377 if ( $block->isExpired() ) {
378 continue;
379 }
380
381 # Don't use anon only blocks on users
382 if ( $this->type == self::TYPE_USER && !$block->isHardblock() ) {
383 continue;
384 }
385
386 if ( $block->getType() == self::TYPE_RANGE ) {
387 # This is the number of bits that are allowed to vary in the block, give
388 # or take some floating point errors
389 $end = Wikimedia\base_convert( $block->getRangeEnd(), 16, 10 );
390 $start = Wikimedia\base_convert( $block->getRangeStart(), 16, 10 );
391 $size = log( $end - $start + 1, 2 );
392
393 # This has the nice property that a /32 block is ranked equally with a
394 # single-IP block, which is exactly what it is...
395 $score = self::TYPE_RANGE - 1 + ( $size / 128 );
396
397 } else {
398 $score = $block->getType();
399 }
400
401 if ( $score < $bestBlockScore ) {
402 $bestBlockScore = $score;
403 $bestRow = $row;
404 }
405 }
406
407 if ( $bestRow !== null ) {
408 $this->initFromRow( $bestRow );
409 return true;
410 } else {
411 return false;
412 }
413 }
414
415 /**
416 * Get a set of SQL conditions which will select rangeblocks encompassing a given range
417 * @param string $start Hexadecimal IP representation
418 * @param string|null $end Hexadecimal IP representation, or null to use $start = $end
419 * @return string
420 */
421 public static function getRangeCond( $start, $end = null ) {
422 if ( $end === null ) {
423 $end = $start;
424 }
425 # Per T16634, we want to include relevant active rangeblocks; for
426 # rangeblocks, we want to include larger ranges which enclose the given
427 # range. We know that all blocks must be smaller than $wgBlockCIDRLimit,
428 # so we can improve performance by filtering on a LIKE clause
429 $chunk = self::getIpFragment( $start );
430 $dbr = wfGetDB( DB_REPLICA );
431 $like = $dbr->buildLike( $chunk, $dbr->anyString() );
432
433 # Fairly hard to make a malicious SQL statement out of hex characters,
434 # but stranger things have happened...
435 $safeStart = $dbr->addQuotes( $start );
436 $safeEnd = $dbr->addQuotes( $end );
437
438 return $dbr->makeList(
439 [
440 "ipb_range_start $like",
441 "ipb_range_start <= $safeStart",
442 "ipb_range_end >= $safeEnd",
443 ],
444 LIST_AND
445 );
446 }
447
448 /**
449 * Get the component of an IP address which is certain to be the same between an IP
450 * address and a rangeblock containing that IP address.
451 * @param string $hex Hexadecimal IP representation
452 * @return string
453 */
454 protected static function getIpFragment( $hex ) {
455 global $wgBlockCIDRLimit;
456 if ( substr( $hex, 0, 3 ) == 'v6-' ) {
457 return 'v6-' . substr( substr( $hex, 3 ), 0, floor( $wgBlockCIDRLimit['IPv6'] / 4 ) );
458 } else {
459 return substr( $hex, 0, floor( $wgBlockCIDRLimit['IPv4'] / 4 ) );
460 }
461 }
462
463 /**
464 * Given a database row from the ipblocks table, initialize
465 * member variables
466 * @param stdClass $row A row from the ipblocks table
467 */
468 protected function initFromRow( $row ) {
469 $this->setTarget( $row->ipb_address );
470 $this->setBlocker( User::newFromAnyId(
471 $row->ipb_by, $row->ipb_by_text, $row->ipb_by_actor ?? null
472 ) );
473
474 $this->mTimestamp = wfTimestamp( TS_MW, $row->ipb_timestamp );
475 $this->mAuto = $row->ipb_auto;
476 $this->mHideName = $row->ipb_deleted;
477 $this->mId = (int)$row->ipb_id;
478 $this->mParentBlockId = $row->ipb_parent_block_id;
479
480 // I wish I didn't have to do this
481 $db = wfGetDB( DB_REPLICA );
482 $this->mExpiry = $db->decodeExpiry( $row->ipb_expiry );
483 $this->mReason = CommentStore::getStore()
484 // Legacy because $row may have come from self::selectFields()
485 ->getCommentLegacy( $db, 'ipb_reason', $row )->text;
486
487 $this->isHardblock( !$row->ipb_anon_only );
488 $this->isAutoblocking( $row->ipb_enable_autoblock );
489 $this->isSitewide( (bool)$row->ipb_sitewide );
490
491 $this->isCreateAccountBlocked( $row->ipb_create_account );
492 $this->isEmailBlocked( $row->ipb_block_email );
493 $this->isUsertalkEditAllowed( $row->ipb_allow_usertalk );
494 }
495
496 /**
497 * Create a new Block object from a database row
498 * @param stdClass $row Row from the ipblocks table
499 * @return Block
500 */
501 public static function newFromRow( $row ) {
502 $block = new Block;
503 $block->initFromRow( $row );
504 return $block;
505 }
506
507 /**
508 * Delete the row from the IP blocks table.
509 *
510 * @throws MWException
511 * @return bool
512 */
513 public function delete() {
514 if ( wfReadOnly() ) {
515 return false;
516 }
517
518 if ( !$this->getId() ) {
519 throw new MWException( "Block::delete() requires that the mId member be filled\n" );
520 }
521
522 $dbw = wfGetDB( DB_MASTER );
523
524 BlockRestriction::deleteByParentBlockId( $this->getId() );
525 $dbw->delete( 'ipblocks', [ 'ipb_parent_block_id' => $this->getId() ], __METHOD__ );
526
527 BlockRestriction::deleteByBlockId( $this->getId() );
528 $dbw->delete( 'ipblocks', [ 'ipb_id' => $this->getId() ], __METHOD__ );
529
530 return $dbw->affectedRows() > 0;
531 }
532
533 /**
534 * Insert a block into the block table. Will fail if there is a conflicting
535 * block (same name and options) already in the database.
536 *
537 * @param IDatabase|null $dbw If you have one available
538 * @return bool|array False on failure, assoc array on success:
539 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
540 */
541 public function insert( $dbw = null ) {
542 global $wgBlockDisablesLogin;
543
544 if ( $this->getSystemBlockType() !== null ) {
545 throw new MWException( 'Cannot insert a system block into the database' );
546 }
547 if ( !$this->getBlocker() || $this->getBlocker()->getName() === '' ) {
548 throw new MWException( 'Cannot insert a block without a blocker set' );
549 }
550
551 wfDebug( "Block::insert; timestamp {$this->mTimestamp}\n" );
552
553 if ( $dbw === null ) {
554 $dbw = wfGetDB( DB_MASTER );
555 }
556
557 self::purgeExpired();
558
559 $row = $this->getDatabaseArray( $dbw );
560
561 $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
562 $affected = $dbw->affectedRows();
563 if ( $affected ) {
564 $this->setId( $dbw->insertId() );
565 if ( $this->restrictions ) {
566 BlockRestriction::insert( $this->restrictions );
567 }
568 }
569
570 # Don't collide with expired blocks.
571 # Do this after trying to insert to avoid locking.
572 if ( !$affected ) {
573 # T96428: The ipb_address index uses a prefix on a field, so
574 # use a standard SELECT + DELETE to avoid annoying gap locks.
575 $ids = $dbw->selectFieldValues( 'ipblocks',
576 'ipb_id',
577 [
578 'ipb_address' => $row['ipb_address'],
579 'ipb_user' => $row['ipb_user'],
580 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() )
581 ],
582 __METHOD__
583 );
584 if ( $ids ) {
585 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], __METHOD__ );
586 BlockRestriction::deleteByBlockId( $ids );
587 $dbw->insert( 'ipblocks', $row, __METHOD__, [ 'IGNORE' ] );
588 $affected = $dbw->affectedRows();
589 $this->setId( $dbw->insertId() );
590 if ( $this->restrictions ) {
591 BlockRestriction::insert( $this->restrictions );
592 }
593 }
594 }
595
596 if ( $affected ) {
597 $auto_ipd_ids = $this->doRetroactiveAutoblock();
598
599 if ( $wgBlockDisablesLogin && $this->target instanceof User ) {
600 // Change user login token to force them to be logged out.
601 $this->target->setToken();
602 $this->target->saveSettings();
603 }
604
605 return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
606 }
607
608 return false;
609 }
610
611 /**
612 * Update a block in the DB with new parameters.
613 * The ID field needs to be loaded first.
614 *
615 * @return bool|array False on failure, array on success:
616 * ('id' => block ID, 'autoIds' => array of autoblock IDs)
617 */
618 public function update() {
619 wfDebug( "Block::update; timestamp {$this->mTimestamp}\n" );
620 $dbw = wfGetDB( DB_MASTER );
621
622 $dbw->startAtomic( __METHOD__ );
623
624 $result = $dbw->update(
625 'ipblocks',
626 $this->getDatabaseArray( $dbw ),
627 [ 'ipb_id' => $this->getId() ],
628 __METHOD__
629 );
630
631 // Only update the restrictions if they have been modified.
632 if ( $this->restrictions !== null ) {
633 // An empty array should remove all of the restrictions.
634 if ( empty( $this->restrictions ) ) {
635 $success = BlockRestriction::deleteByBlockId( $this->getId() );
636 } else {
637 $success = BlockRestriction::update( $this->restrictions );
638 }
639 // Update the result. The first false is the result, otherwise, true.
640 $result = $result && $success;
641 }
642
643 if ( $this->isAutoblocking() ) {
644 // update corresponding autoblock(s) (T50813)
645 $dbw->update(
646 'ipblocks',
647 $this->getAutoblockUpdateArray( $dbw ),
648 [ 'ipb_parent_block_id' => $this->getId() ],
649 __METHOD__
650 );
651
652 // Only update the restrictions if they have been modified.
653 if ( $this->restrictions !== null ) {
654 BlockRestriction::updateByParentBlockId( $this->getId(), $this->restrictions );
655 }
656 } else {
657 // autoblock no longer required, delete corresponding autoblock(s)
658 BlockRestriction::deleteByParentBlockId( $this->getId() );
659 $dbw->delete(
660 'ipblocks',
661 [ 'ipb_parent_block_id' => $this->getId() ],
662 __METHOD__
663 );
664 }
665
666 $dbw->endAtomic( __METHOD__ );
667
668 if ( $result ) {
669 $auto_ipd_ids = $this->doRetroactiveAutoblock();
670 return [ 'id' => $this->mId, 'autoIds' => $auto_ipd_ids ];
671 }
672
673 return $result;
674 }
675
676 /**
677 * Get an array suitable for passing to $dbw->insert() or $dbw->update()
678 * @param IDatabase $dbw
679 * @return array
680 */
681 protected function getDatabaseArray( IDatabase $dbw ) {
682 $expiry = $dbw->encodeExpiry( $this->mExpiry );
683
684 if ( $this->forcedTargetID ) {
685 $uid = $this->forcedTargetID;
686 } else {
687 $uid = $this->target instanceof User ? $this->target->getId() : 0;
688 }
689
690 $a = [
691 'ipb_address' => (string)$this->target,
692 'ipb_user' => $uid,
693 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
694 'ipb_auto' => $this->mAuto,
695 'ipb_anon_only' => !$this->isHardblock(),
696 'ipb_create_account' => $this->isCreateAccountBlocked(),
697 'ipb_enable_autoblock' => $this->isAutoblocking(),
698 'ipb_expiry' => $expiry,
699 'ipb_range_start' => $this->getRangeStart(),
700 'ipb_range_end' => $this->getRangeEnd(),
701 'ipb_deleted' => intval( $this->mHideName ), // typecast required for SQLite
702 'ipb_block_email' => $this->isEmailBlocked(),
703 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
704 'ipb_parent_block_id' => $this->mParentBlockId,
705 'ipb_sitewide' => $this->isSitewide(),
706 ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->mReason )
707 + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
708
709 return $a;
710 }
711
712 /**
713 * @param IDatabase $dbw
714 * @return array
715 */
716 protected function getAutoblockUpdateArray( IDatabase $dbw ) {
717 return [
718 'ipb_create_account' => $this->isCreateAccountBlocked(),
719 'ipb_deleted' => (int)$this->mHideName, // typecast required for SQLite
720 'ipb_allow_usertalk' => $this->isUsertalkEditAllowed(),
721 'ipb_sitewide' => $this->isSitewide(),
722 ] + CommentStore::getStore()->insert( $dbw, 'ipb_reason', $this->mReason )
723 + ActorMigration::newMigration()->getInsertValues( $dbw, 'ipb_by', $this->getBlocker() );
724 }
725
726 /**
727 * Retroactively autoblocks the last IP used by the user (if it is a user)
728 * blocked by this Block.
729 *
730 * @return array Block IDs of retroactive autoblocks made
731 */
732 protected function doRetroactiveAutoblock() {
733 $blockIds = [];
734 # If autoblock is enabled, autoblock the LAST IP(s) used
735 if ( $this->isAutoblocking() && $this->getType() == self::TYPE_USER ) {
736 wfDebug( "Doing retroactive autoblocks for " . $this->getTarget() . "\n" );
737
738 $continue = Hooks::run(
739 'PerformRetroactiveAutoblock', [ $this, &$blockIds ] );
740
741 if ( $continue ) {
742 self::defaultRetroactiveAutoblock( $this, $blockIds );
743 }
744 }
745 return $blockIds;
746 }
747
748 /**
749 * Retroactively autoblocks the last IP used by the user (if it is a user)
750 * blocked by this Block. This will use the recentchanges table.
751 *
752 * @param Block $block
753 * @param array &$blockIds
754 */
755 protected static function defaultRetroactiveAutoblock( Block $block, array &$blockIds ) {
756 global $wgPutIPinRC;
757
758 // No IPs are in recentchanges table, so nothing to select
759 if ( !$wgPutIPinRC ) {
760 return;
761 }
762
763 // Autoblocks only apply to TYPE_USER
764 if ( $block->getType() !== self::TYPE_USER ) {
765 return;
766 }
767 $target = $block->getTarget(); // TYPE_USER => always a User object
768
769 $dbr = wfGetDB( DB_REPLICA );
770 $rcQuery = ActorMigration::newMigration()->getWhere( $dbr, 'rc_user', $target, false );
771
772 $options = [ 'ORDER BY' => 'rc_timestamp DESC' ];
773
774 // Just the last IP used.
775 $options['LIMIT'] = 1;
776
777 $res = $dbr->select(
778 [ 'recentchanges' ] + $rcQuery['tables'],
779 [ 'rc_ip' ],
780 $rcQuery['conds'],
781 __METHOD__,
782 $options,
783 $rcQuery['joins']
784 );
785
786 if ( !$res->numRows() ) {
787 # No results, don't autoblock anything
788 wfDebug( "No IP found to retroactively autoblock\n" );
789 } else {
790 foreach ( $res as $row ) {
791 if ( $row->rc_ip ) {
792 $id = $block->doAutoblock( $row->rc_ip );
793 if ( $id ) {
794 $blockIds[] = $id;
795 }
796 }
797 }
798 }
799 }
800
801 /**
802 * Checks whether a given IP is on the autoblock whitelist.
803 * TODO: this probably belongs somewhere else, but not sure where...
804 *
805 * @param string $ip The IP to check
806 * @return bool
807 */
808 public static function isWhitelistedFromAutoblocks( $ip ) {
809 // Try to get the autoblock_whitelist from the cache, as it's faster
810 // than getting the msg raw and explode()'ing it.
811 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
812 $lines = $cache->getWithSetCallback(
813 $cache->makeKey( 'ip-autoblock', 'whitelist' ),
814 $cache::TTL_DAY,
815 function ( $curValue, &$ttl, array &$setOpts ) {
816 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
817
818 return explode( "\n",
819 wfMessage( 'autoblock_whitelist' )->inContentLanguage()->plain() );
820 }
821 );
822
823 wfDebug( "Checking the autoblock whitelist..\n" );
824
825 foreach ( $lines as $line ) {
826 # List items only
827 if ( substr( $line, 0, 1 ) !== '*' ) {
828 continue;
829 }
830
831 $wlEntry = substr( $line, 1 );
832 $wlEntry = trim( $wlEntry );
833
834 wfDebug( "Checking $ip against $wlEntry..." );
835
836 # Is the IP in this range?
837 if ( IP::isInRange( $ip, $wlEntry ) ) {
838 wfDebug( " IP $ip matches $wlEntry, not autoblocking\n" );
839 return true;
840 } else {
841 wfDebug( " No match\n" );
842 }
843 }
844
845 return false;
846 }
847
848 /**
849 * Autoblocks the given IP, referring to this Block.
850 *
851 * @param string $autoblockIP The IP to autoblock.
852 * @return int|bool Block ID if an autoblock was inserted, false if not.
853 */
854 public function doAutoblock( $autoblockIP ) {
855 # If autoblocks are disabled, go away.
856 if ( !$this->isAutoblocking() ) {
857 return false;
858 }
859
860 # Don't autoblock for system blocks
861 if ( $this->getSystemBlockType() !== null ) {
862 throw new MWException( 'Cannot autoblock from a system block' );
863 }
864
865 # Check for presence on the autoblock whitelist.
866 if ( self::isWhitelistedFromAutoblocks( $autoblockIP ) ) {
867 return false;
868 }
869
870 // Avoid PHP 7.1 warning of passing $this by reference
871 $block = $this;
872 # Allow hooks to cancel the autoblock.
873 if ( !Hooks::run( 'AbortAutoblock', [ $autoblockIP, &$block ] ) ) {
874 wfDebug( "Autoblock aborted by hook.\n" );
875 return false;
876 }
877
878 # It's okay to autoblock. Go ahead and insert/update the block...
879
880 # Do not add a *new* block if the IP is already blocked.
881 $ipblock = self::newFromTarget( $autoblockIP );
882 if ( $ipblock ) {
883 # Check if the block is an autoblock and would exceed the user block
884 # if renewed. If so, do nothing, otherwise prolong the block time...
885 if ( $ipblock->mAuto && // @todo Why not compare $ipblock->mExpiry?
886 $this->mExpiry > self::getAutoblockExpiry( $ipblock->mTimestamp )
887 ) {
888 # Reset block timestamp to now and its expiry to
889 # $wgAutoblockExpiry in the future
890 $ipblock->updateTimestamp();
891 }
892 return false;
893 }
894
895 # Make a new block object with the desired properties.
896 $autoblock = new Block;
897 wfDebug( "Autoblocking {$this->getTarget()}@" . $autoblockIP . "\n" );
898 $autoblock->setTarget( $autoblockIP );
899 $autoblock->setBlocker( $this->getBlocker() );
900 $autoblock->mReason = wfMessage( 'autoblocker', $this->getTarget(), $this->mReason )
901 ->inContentLanguage()->plain();
902 $timestamp = wfTimestampNow();
903 $autoblock->mTimestamp = $timestamp;
904 $autoblock->mAuto = 1;
905 $autoblock->isCreateAccountBlocked( $this->isCreateAccountBlocked() );
906 # Continue suppressing the name if needed
907 $autoblock->mHideName = $this->mHideName;
908 $autoblock->isUsertalkEditAllowed( $this->isUsertalkEditAllowed() );
909 $autoblock->mParentBlockId = $this->mId;
910 $autoblock->isSitewide( $this->isSitewide() );
911 $autoblock->setRestrictions( $this->getRestrictions() );
912
913 if ( $this->mExpiry == 'infinity' ) {
914 # Original block was indefinite, start an autoblock now
915 $autoblock->mExpiry = self::getAutoblockExpiry( $timestamp );
916 } else {
917 # If the user is already blocked with an expiry date, we don't
918 # want to pile on top of that.
919 $autoblock->mExpiry = min( $this->mExpiry, self::getAutoblockExpiry( $timestamp ) );
920 }
921
922 # Insert the block...
923 $status = $autoblock->insert();
924 return $status
925 ? $status['id']
926 : false;
927 }
928
929 /**
930 * Check if a block has expired. Delete it if it is.
931 * @return bool
932 */
933 public function deleteIfExpired() {
934 if ( $this->isExpired() ) {
935 wfDebug( "Block::deleteIfExpired() -- deleting\n" );
936 $this->delete();
937 $retVal = true;
938 } else {
939 wfDebug( "Block::deleteIfExpired() -- not expired\n" );
940 $retVal = false;
941 }
942
943 return $retVal;
944 }
945
946 /**
947 * Has the block expired?
948 * @return bool
949 */
950 public function isExpired() {
951 $timestamp = wfTimestampNow();
952 wfDebug( "Block::isExpired() checking current " . $timestamp . " vs $this->mExpiry\n" );
953
954 if ( !$this->mExpiry ) {
955 return false;
956 } else {
957 return $timestamp > $this->mExpiry;
958 }
959 }
960
961 /**
962 * Is the block address valid (i.e. not a null string?)
963 * @return bool
964 */
965 public function isValid() {
966 return $this->getTarget() != null;
967 }
968
969 /**
970 * Update the timestamp on autoblocks.
971 */
972 public function updateTimestamp() {
973 if ( $this->mAuto ) {
974 $this->mTimestamp = wfTimestamp();
975 $this->mExpiry = self::getAutoblockExpiry( $this->mTimestamp );
976
977 $dbw = wfGetDB( DB_MASTER );
978 $dbw->update( 'ipblocks',
979 [ /* SET */
980 'ipb_timestamp' => $dbw->timestamp( $this->mTimestamp ),
981 'ipb_expiry' => $dbw->timestamp( $this->mExpiry ),
982 ],
983 [ /* WHERE */
984 'ipb_id' => $this->getId(),
985 ],
986 __METHOD__
987 );
988 }
989 }
990
991 /**
992 * Get the IP address at the start of the range in Hex form
993 * @throws MWException
994 * @return string IP in Hex form
995 */
996 public function getRangeStart() {
997 switch ( $this->type ) {
998 case self::TYPE_USER:
999 return '';
1000 case self::TYPE_IP:
1001 return IP::toHex( $this->target );
1002 case self::TYPE_RANGE:
1003 list( $start, /*...*/ ) = IP::parseRange( $this->target );
1004 return $start;
1005 default:
1006 throw new MWException( "Block with invalid type" );
1007 }
1008 }
1009
1010 /**
1011 * Get the IP address at the end of the range in Hex form
1012 * @throws MWException
1013 * @return string IP in Hex form
1014 */
1015 public function getRangeEnd() {
1016 switch ( $this->type ) {
1017 case self::TYPE_USER:
1018 return '';
1019 case self::TYPE_IP:
1020 return IP::toHex( $this->target );
1021 case self::TYPE_RANGE:
1022 list( /*...*/, $end ) = IP::parseRange( $this->target );
1023 return $end;
1024 default:
1025 throw new MWException( "Block with invalid type" );
1026 }
1027 }
1028
1029 /**
1030 * Get the user id of the blocking sysop
1031 *
1032 * @return int (0 for foreign users)
1033 */
1034 public function getBy() {
1035 $blocker = $this->getBlocker();
1036 return ( $blocker instanceof User )
1037 ? $blocker->getId()
1038 : 0;
1039 }
1040
1041 /**
1042 * Get the username of the blocking sysop
1043 *
1044 * @return string
1045 */
1046 public function getByName() {
1047 $blocker = $this->getBlocker();
1048 return ( $blocker instanceof User )
1049 ? $blocker->getName()
1050 : (string)$blocker; // username
1051 }
1052
1053 /**
1054 * Get the block ID
1055 * @return int
1056 */
1057 public function getId() {
1058 return $this->mId;
1059 }
1060
1061 /**
1062 * Set the block ID
1063 *
1064 * @param int $blockId
1065 * @return int
1066 */
1067 private function setId( $blockId ) {
1068 $this->mId = (int)$blockId;
1069
1070 if ( is_array( $this->restrictions ) ) {
1071 $this->restrictions = BlockRestriction::setBlockId( $blockId, $this->restrictions );
1072 }
1073
1074 return $this;
1075 }
1076
1077 /**
1078 * Get the system block type, if any
1079 * @since 1.29
1080 * @return string|null
1081 */
1082 public function getSystemBlockType() {
1083 return $this->systemBlockType;
1084 }
1085
1086 /**
1087 * Get/set a flag determining whether the master is used for reads
1088 *
1089 * @param bool|null $x
1090 * @return bool
1091 */
1092 public function fromMaster( $x = null ) {
1093 return wfSetVar( $this->mFromMaster, $x );
1094 }
1095
1096 /**
1097 * Get/set whether the Block is a hardblock (affects logged-in users on a given IP/range)
1098 * @param bool|null $x
1099 * @return bool
1100 */
1101 public function isHardblock( $x = null ) {
1102 wfSetVar( $this->isHardblock, $x );
1103
1104 # You can't *not* hardblock a user
1105 return $this->getType() == self::TYPE_USER
1106 ? true
1107 : $this->isHardblock;
1108 }
1109
1110 /**
1111 * @param null|bool $x
1112 * @return bool
1113 */
1114 public function isAutoblocking( $x = null ) {
1115 wfSetVar( $this->isAutoblocking, $x );
1116
1117 # You can't put an autoblock on an IP or range as we don't have any history to
1118 # look over to get more IPs from
1119 return $this->getType() == self::TYPE_USER
1120 ? $this->isAutoblocking
1121 : false;
1122 }
1123
1124 /**
1125 * Indicates that the block is a sitewide block. This means the user is
1126 * prohibited from editing any page on the site (other than their own talk
1127 * page).
1128 *
1129 * @since 1.33
1130 * @param null|bool $x
1131 * @return bool
1132 */
1133 public function isSitewide( $x = null ) {
1134 return wfSetVar( $this->isSitewide, $x );
1135 }
1136
1137 /**
1138 * Get or set the flag indicating whether this block blocks the target from
1139 * creating an account. (Note that the flag may be overridden depending on
1140 * global configs.)
1141 *
1142 * @since 1.33
1143 * @param null|bool $x Value to set (if null, just get the property value)
1144 * @return bool Value of the property
1145 */
1146 public function isCreateAccountBlocked( $x = null ) {
1147 return wfSetVar( $this->blockCreateAccount, $x );
1148 }
1149
1150 /**
1151 * Get or set the flag indicating whether this block blocks the target from
1152 * sending emails. (Note that the flag may be overridden depending on
1153 * global configs.)
1154 *
1155 * @since 1.33
1156 * @param null|bool $x Value to set (if null, just get the property value)
1157 * @return bool Value of the property
1158 */
1159 public function isEmailBlocked( $x = null ) {
1160 return wfSetVar( $this->mBlockEmail, $x );
1161 }
1162
1163 /**
1164 * Get or set the flag indicating whether this block blocks the target from
1165 * editing their own user talk page. (Note that the flag may be overridden
1166 * depending on global configs.)
1167 *
1168 * @since 1.33
1169 * @param null|bool $x Value to set (if null, just get the property value)
1170 * @return bool Value of the property
1171 */
1172 public function isUsertalkEditAllowed( $x = null ) {
1173 return wfSetVar( $this->allowUsertalk, $x );
1174 }
1175
1176 /**
1177 * Determine whether the Block prevents a given right. A right
1178 * may be blacklisted or whitelisted, or determined from a
1179 * property on the Block object. For certain rights, the property
1180 * may be overridden according to global configs.
1181 *
1182 * @since 1.33
1183 * @param string $right Right to check
1184 * @return bool|null null if unrecognized right or unset property
1185 */
1186 public function appliesToRight( $right ) {
1187 $config = RequestContext::getMain()->getConfig();
1188 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1189
1190 $res = null;
1191 switch ( $right ) {
1192 case 'edit':
1193 // TODO: fix this case to return proper value
1194 $res = true;
1195 break;
1196 case 'createaccount':
1197 $res = $this->isCreateAccountBlocked();
1198 break;
1199 case 'sendemail':
1200 $res = $this->isEmailBlocked();
1201 break;
1202 case 'upload':
1203 // Until T6995 is completed
1204 $res = $this->isSitewide();
1205 break;
1206 case 'read':
1207 $res = false;
1208 break;
1209 case 'purge':
1210 $res = false;
1211 break;
1212 }
1213 if ( !$res && $blockDisablesLogin ) {
1214 // If a block would disable login, then it should
1215 // prevent any right that all users cannot do
1216 $anon = new User;
1217 $res = $anon->isAllowed( $right ) ? $res : true;
1218 }
1219
1220 return $res;
1221 }
1222
1223 /**
1224 * Get/set whether the Block prevents a given action
1225 *
1226 * @deprecated since 1.33, use appliesToRight to determine block
1227 * behaviour, and specific methods to get/set properties
1228 * @param string $action Action to check
1229 * @param bool|null $x Value for set, or null to just get value
1230 * @return bool|null Null for unrecognized rights.
1231 */
1232 public function prevents( $action, $x = null ) {
1233 $config = RequestContext::getMain()->getConfig();
1234 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
1235 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
1236
1237 $res = null;
1238 switch ( $action ) {
1239 case 'edit':
1240 # For now... <evil laugh>
1241 $res = true;
1242 break;
1243 case 'createaccount':
1244 $res = wfSetVar( $this->blockCreateAccount, $x );
1245 break;
1246 case 'sendemail':
1247 $res = wfSetVar( $this->mBlockEmail, $x );
1248 break;
1249 case 'upload':
1250 // Until T6995 is completed
1251 $res = $this->isSitewide();
1252 break;
1253 case 'editownusertalk':
1254 // NOTE: this check is not reliable on partial blocks
1255 // since partially blocked users are always allowed to edit
1256 // their own talk page unless a restriction exists on the
1257 // page or User_talk: namespace
1258 wfSetVar( $this->allowUsertalk, $x === null ? null : !$x );
1259 $res = !$this->isUserTalkEditAllowed();
1260
1261 // edit own user talk can be disabled by config
1262 if ( !$blockAllowsUTEdit ) {
1263 $res = true;
1264 }
1265 break;
1266 case 'read':
1267 $res = false;
1268 break;
1269 case 'purge':
1270 $res = false;
1271 break;
1272 }
1273 if ( !$res && $blockDisablesLogin ) {
1274 // If a block would disable login, then it should
1275 // prevent any action that all users cannot do
1276 $anon = new User;
1277 $res = $anon->isAllowed( $action ) ? $res : true;
1278 }
1279
1280 return $res;
1281 }
1282
1283 /**
1284 * Get the block name, but with autoblocked IPs hidden as per standard privacy policy
1285 * @return string Text is escaped
1286 */
1287 public function getRedactedName() {
1288 if ( $this->mAuto ) {
1289 return Html::element(
1290 'span',
1291 [ 'class' => 'mw-autoblockid' ],
1292 wfMessage( 'autoblockid', $this->mId )->text()
1293 );
1294 } else {
1295 return htmlspecialchars( $this->getTarget() );
1296 }
1297 }
1298
1299 /**
1300 * Get a timestamp of the expiry for autoblocks
1301 *
1302 * @param string|int $timestamp
1303 * @return string
1304 */
1305 public static function getAutoblockExpiry( $timestamp ) {
1306 global $wgAutoblockExpiry;
1307
1308 return wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $timestamp ) + $wgAutoblockExpiry );
1309 }
1310
1311 /**
1312 * Purge expired blocks from the ipblocks table
1313 */
1314 public static function purgeExpired() {
1315 if ( wfReadOnly() ) {
1316 return;
1317 }
1318
1319 DeferredUpdates::addUpdate( new AutoCommitUpdate(
1320 wfGetDB( DB_MASTER ),
1321 __METHOD__,
1322 function ( IDatabase $dbw, $fname ) {
1323 $ids = $dbw->selectFieldValues( 'ipblocks',
1324 'ipb_id',
1325 [ 'ipb_expiry < ' . $dbw->addQuotes( $dbw->timestamp() ) ],
1326 $fname
1327 );
1328 if ( $ids ) {
1329 BlockRestriction::deleteByBlockId( $ids );
1330 $dbw->delete( 'ipblocks', [ 'ipb_id' => $ids ], $fname );
1331 }
1332 }
1333 ) );
1334 }
1335
1336 /**
1337 * Given a target and the target's type, get an existing Block object if possible.
1338 * @param string|User|int $specificTarget A block target, which may be one of several types:
1339 * * A user to block, in which case $target will be a User
1340 * * An IP to block, in which case $target will be a User generated by using
1341 * User::newFromName( $ip, false ) to turn off name validation
1342 * * An IP range, in which case $target will be a String "123.123.123.123/18" etc
1343 * * The ID of an existing block, in the format "#12345" (since pure numbers are valid
1344 * usernames
1345 * Calling this with a user, IP address or range will not select autoblocks, and will
1346 * only select a block where the targets match exactly (so looking for blocks on
1347 * 1.2.3.4 will not select 1.2.0.0/16 or even 1.2.3.4/32)
1348 * @param string|User|int|null $vagueTarget As above, but we will search for *any* block which
1349 * affects that target (so for an IP address, get ranges containing that IP; and also
1350 * get any relevant autoblocks). Leave empty or blank to skip IP-based lookups.
1351 * @param bool $fromMaster Whether to use the DB_MASTER database
1352 * @return Block|null (null if no relevant block could be found). The target and type
1353 * of the returned Block will refer to the actual block which was found, which might
1354 * not be the same as the target you gave if you used $vagueTarget!
1355 */
1356 public static function newFromTarget( $specificTarget, $vagueTarget = null, $fromMaster = false ) {
1357 list( $target, $type ) = self::parseTarget( $specificTarget );
1358 if ( $type == self::TYPE_ID || $type == self::TYPE_AUTO ) {
1359 return self::newFromID( $target );
1360
1361 } elseif ( $target === null && $vagueTarget == '' ) {
1362 # We're not going to find anything useful here
1363 # Be aware that the == '' check is explicit, since empty values will be
1364 # passed by some callers (T31116)
1365 return null;
1366
1367 } elseif ( in_array(
1368 $type,
1369 [ self::TYPE_USER, self::TYPE_IP, self::TYPE_RANGE, null ] )
1370 ) {
1371 $block = new Block();
1372 $block->fromMaster( $fromMaster );
1373
1374 if ( $type !== null ) {
1375 $block->setTarget( $target );
1376 }
1377
1378 if ( $block->newLoad( $vagueTarget ) ) {
1379 return $block;
1380 }
1381 }
1382 return null;
1383 }
1384
1385 /**
1386 * Get all blocks that match any IP from an array of IP addresses
1387 *
1388 * @param array $ipChain List of IPs (strings), usually retrieved from the
1389 * X-Forwarded-For header of the request
1390 * @param bool $isAnon Exclude anonymous-only blocks if false
1391 * @param bool $fromMaster Whether to query the master or replica DB
1392 * @return array Array of Blocks
1393 * @since 1.22
1394 */
1395 public static function getBlocksForIPList( array $ipChain, $isAnon, $fromMaster = false ) {
1396 if ( $ipChain === [] ) {
1397 return [];
1398 }
1399
1400 $conds = [];
1401 $proxyLookup = MediaWikiServices::getInstance()->getProxyLookup();
1402 foreach ( array_unique( $ipChain ) as $ipaddr ) {
1403 # Discard invalid IP addresses. Since XFF can be spoofed and we do not
1404 # necessarily trust the header given to us, make sure that we are only
1405 # checking for blocks on well-formatted IP addresses (IPv4 and IPv6).
1406 # Do not treat private IP spaces as special as it may be desirable for wikis
1407 # to block those IP ranges in order to stop misbehaving proxies that spoof XFF.
1408 if ( !IP::isValid( $ipaddr ) ) {
1409 continue;
1410 }
1411 # Don't check trusted IPs (includes local squids which will be in every request)
1412 if ( $proxyLookup->isTrustedProxy( $ipaddr ) ) {
1413 continue;
1414 }
1415 # Check both the original IP (to check against single blocks), as well as build
1416 # the clause to check for rangeblocks for the given IP.
1417 $conds['ipb_address'][] = $ipaddr;
1418 $conds[] = self::getRangeCond( IP::toHex( $ipaddr ) );
1419 }
1420
1421 if ( $conds === [] ) {
1422 return [];
1423 }
1424
1425 if ( $fromMaster ) {
1426 $db = wfGetDB( DB_MASTER );
1427 } else {
1428 $db = wfGetDB( DB_REPLICA );
1429 }
1430 $conds = $db->makeList( $conds, LIST_OR );
1431 if ( !$isAnon ) {
1432 $conds = [ $conds, 'ipb_anon_only' => 0 ];
1433 }
1434 $blockQuery = self::getQueryInfo();
1435 $rows = $db->select(
1436 $blockQuery['tables'],
1437 array_merge( [ 'ipb_range_start', 'ipb_range_end' ], $blockQuery['fields'] ),
1438 $conds,
1439 __METHOD__,
1440 [],
1441 $blockQuery['joins']
1442 );
1443
1444 $blocks = [];
1445 foreach ( $rows as $row ) {
1446 $block = self::newFromRow( $row );
1447 if ( !$block->isExpired() ) {
1448 $blocks[] = $block;
1449 }
1450 }
1451
1452 return $blocks;
1453 }
1454
1455 /**
1456 * From a list of multiple blocks, find the most exact and strongest Block.
1457 *
1458 * The logic for finding the "best" block is:
1459 * - Blocks that match the block's target IP are preferred over ones in a range
1460 * - Hardblocks are chosen over softblocks that prevent account creation
1461 * - Softblocks that prevent account creation are chosen over other softblocks
1462 * - Other softblocks are chosen over autoblocks
1463 * - If there are multiple exact or range blocks at the same level, the one chosen
1464 * is random
1465 * This should be used when $blocks where retrieved from the user's IP address
1466 * and $ipChain is populated from the same IP address information.
1467 *
1468 * @param array $blocks Array of Block objects
1469 * @param array $ipChain List of IPs (strings). This is used to determine how "close"
1470 * a block is to the server, and if a block matches exactly, or is in a range.
1471 * The order is furthest from the server to nearest e.g., (Browser, proxy1, proxy2,
1472 * local-squid, ...)
1473 * @throws MWException
1474 * @return Block|null The "best" block from the list
1475 */
1476 public static function chooseBlock( array $blocks, array $ipChain ) {
1477 if ( $blocks === [] ) {
1478 return null;
1479 } elseif ( count( $blocks ) == 1 ) {
1480 return $blocks[0];
1481 }
1482
1483 // Sort hard blocks before soft ones and secondarily sort blocks
1484 // that disable account creation before those that don't.
1485 usort( $blocks, function ( Block $a, Block $b ) {
1486 $aWeight = (int)$a->isHardblock() . (int)$a->appliesToRight( 'createaccount' );
1487 $bWeight = (int)$b->isHardblock() . (int)$b->appliesToRight( 'createaccount' );
1488 return strcmp( $bWeight, $aWeight ); // highest weight first
1489 } );
1490
1491 $blocksListExact = [
1492 'hard' => false,
1493 'disable_create' => false,
1494 'other' => false,
1495 'auto' => false
1496 ];
1497 $blocksListRange = [
1498 'hard' => false,
1499 'disable_create' => false,
1500 'other' => false,
1501 'auto' => false
1502 ];
1503 $ipChain = array_reverse( $ipChain );
1504
1505 /** @var Block $block */
1506 foreach ( $blocks as $block ) {
1507 // Stop searching if we have already have a "better" block. This
1508 // is why the order of the blocks matters
1509 if ( !$block->isHardblock() && $blocksListExact['hard'] ) {
1510 break;
1511 } elseif ( !$block->appliesToRight( 'createaccount' ) && $blocksListExact['disable_create'] ) {
1512 break;
1513 }
1514
1515 foreach ( $ipChain as $checkip ) {
1516 $checkipHex = IP::toHex( $checkip );
1517 if ( (string)$block->getTarget() === $checkip ) {
1518 if ( $block->isHardblock() ) {
1519 $blocksListExact['hard'] = $blocksListExact['hard'] ?: $block;
1520 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1521 $blocksListExact['disable_create'] = $blocksListExact['disable_create'] ?: $block;
1522 } elseif ( $block->mAuto ) {
1523 $blocksListExact['auto'] = $blocksListExact['auto'] ?: $block;
1524 } else {
1525 $blocksListExact['other'] = $blocksListExact['other'] ?: $block;
1526 }
1527 // We found closest exact match in the ip list, so go to the next Block
1528 break;
1529 } elseif ( array_filter( $blocksListExact ) == []
1530 && $block->getRangeStart() <= $checkipHex
1531 && $block->getRangeEnd() >= $checkipHex
1532 ) {
1533 if ( $block->isHardblock() ) {
1534 $blocksListRange['hard'] = $blocksListRange['hard'] ?: $block;
1535 } elseif ( $block->appliesToRight( 'createaccount' ) ) {
1536 $blocksListRange['disable_create'] = $blocksListRange['disable_create'] ?: $block;
1537 } elseif ( $block->mAuto ) {
1538 $blocksListRange['auto'] = $blocksListRange['auto'] ?: $block;
1539 } else {
1540 $blocksListRange['other'] = $blocksListRange['other'] ?: $block;
1541 }
1542 break;
1543 }
1544 }
1545 }
1546
1547 if ( array_filter( $blocksListExact ) == [] ) {
1548 $blocksList = &$blocksListRange;
1549 } else {
1550 $blocksList = &$blocksListExact;
1551 }
1552
1553 $chosenBlock = null;
1554 if ( $blocksList['hard'] ) {
1555 $chosenBlock = $blocksList['hard'];
1556 } elseif ( $blocksList['disable_create'] ) {
1557 $chosenBlock = $blocksList['disable_create'];
1558 } elseif ( $blocksList['other'] ) {
1559 $chosenBlock = $blocksList['other'];
1560 } elseif ( $blocksList['auto'] ) {
1561 $chosenBlock = $blocksList['auto'];
1562 } else {
1563 throw new MWException( "Proxy block found, but couldn't be classified." );
1564 }
1565
1566 return $chosenBlock;
1567 }
1568
1569 /**
1570 * From an existing Block, get the target and the type of target.
1571 * Note that, except for null, it is always safe to treat the target
1572 * as a string; for User objects this will return User::__toString()
1573 * which in turn gives User::getName().
1574 *
1575 * @param string|int|User|null $target
1576 * @return array [ User|String|null, Block::TYPE_ constant|null ]
1577 */
1578 public static function parseTarget( $target ) {
1579 # We may have been through this before
1580 if ( $target instanceof User ) {
1581 if ( IP::isValid( $target->getName() ) ) {
1582 return [ $target, self::TYPE_IP ];
1583 } else {
1584 return [ $target, self::TYPE_USER ];
1585 }
1586 } elseif ( $target === null ) {
1587 return [ null, null ];
1588 }
1589
1590 $target = trim( $target );
1591
1592 if ( IP::isValid( $target ) ) {
1593 # We can still create a User if it's an IP address, but we need to turn
1594 # off validation checking (which would exclude IP addresses)
1595 return [
1596 User::newFromName( IP::sanitizeIP( $target ), false ),
1597 self::TYPE_IP
1598 ];
1599
1600 } elseif ( IP::isValidRange( $target ) ) {
1601 # Can't create a User from an IP range
1602 return [ IP::sanitizeRange( $target ), self::TYPE_RANGE ];
1603 }
1604
1605 # Consider the possibility that this is not a username at all
1606 # but actually an old subpage (T31797)
1607 if ( strpos( $target, '/' ) !== false ) {
1608 # An old subpage, drill down to the user behind it
1609 $target = explode( '/', $target )[0];
1610 }
1611
1612 $userObj = User::newFromName( $target );
1613 if ( $userObj instanceof User ) {
1614 # Note that since numbers are valid usernames, a $target of "12345" will be
1615 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
1616 # since hash characters are not valid in usernames or titles generally.
1617 return [ $userObj, self::TYPE_USER ];
1618
1619 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
1620 # Autoblock reference in the form "#12345"
1621 return [ substr( $target, 1 ), self::TYPE_AUTO ];
1622
1623 } else {
1624 # WTF?
1625 return [ null, null ];
1626 }
1627 }
1628
1629 /**
1630 * Get the type of target for this particular block. Autoblocks have whichever type
1631 * corresponds to their target, so to detect if a block is an autoblock, we have to
1632 * check the mAuto property instead.
1633 * @return int Block::TYPE_ constant, will never be TYPE_ID
1634 */
1635 public function getType() {
1636 return $this->mAuto
1637 ? self::TYPE_AUTO
1638 : $this->type;
1639 }
1640
1641 /**
1642 * Get the target and target type for this particular Block. Note that for autoblocks,
1643 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1644 * in this situation.
1645 * @return array [ User|String, Block::TYPE_ constant ]
1646 * @todo FIXME: This should be an integral part of the Block member variables
1647 */
1648 public function getTargetAndType() {
1649 return [ $this->getTarget(), $this->getType() ];
1650 }
1651
1652 /**
1653 * Get the target for this particular Block. Note that for autoblocks,
1654 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
1655 * in this situation.
1656 * @return User|string
1657 */
1658 public function getTarget() {
1659 return $this->target;
1660 }
1661
1662 /**
1663 * @since 1.19
1664 *
1665 * @return mixed|string
1666 */
1667 public function getExpiry() {
1668 return $this->mExpiry;
1669 }
1670
1671 /**
1672 * Set the target for this block, and update $this->type accordingly
1673 * @param mixed $target
1674 */
1675 public function setTarget( $target ) {
1676 list( $this->target, $this->type ) = self::parseTarget( $target );
1677 }
1678
1679 /**
1680 * Get the user who implemented this block
1681 * @return User User object. May name a foreign user.
1682 */
1683 public function getBlocker() {
1684 return $this->blocker;
1685 }
1686
1687 /**
1688 * Set the user who implemented (or will implement) this block
1689 * @param User|string $user Local User object or username string
1690 */
1691 public function setBlocker( $user ) {
1692 if ( is_string( $user ) ) {
1693 $user = User::newFromName( $user, false );
1694 }
1695
1696 if ( $user->isAnon() && User::isUsableName( $user->getName() ) ) {
1697 throw new InvalidArgumentException(
1698 'Blocker must be a local user or a name that cannot be a local user'
1699 );
1700 }
1701
1702 $this->blocker = $user;
1703 }
1704
1705 /**
1706 * Set the 'BlockID' cookie to this block's ID and expiry time. The cookie's expiry will be
1707 * the same as the block's, to a maximum of 24 hours.
1708 *
1709 * @since 1.29
1710 *
1711 * @param WebResponse $response The response on which to set the cookie.
1712 */
1713 public function setCookie( WebResponse $response ) {
1714 // Calculate the default expiry time.
1715 $maxExpiryTime = wfTimestamp( TS_MW, wfTimestamp() + ( 24 * 60 * 60 ) );
1716
1717 // Use the Block's expiry time only if it's less than the default.
1718 $expiryTime = $this->getExpiry();
1719 if ( $expiryTime === 'infinity' || $expiryTime > $maxExpiryTime ) {
1720 $expiryTime = $maxExpiryTime;
1721 }
1722
1723 // Set the cookie. Reformat the MediaWiki datetime as a Unix timestamp for the cookie.
1724 $expiryValue = DateTime::createFromFormat( 'YmdHis', $expiryTime )->format( 'U' );
1725 $cookieOptions = [ 'httpOnly' => false ];
1726 $cookieValue = $this->getCookieValue();
1727 $response->setCookie( 'BlockID', $cookieValue, $expiryValue, $cookieOptions );
1728 }
1729
1730 /**
1731 * Unset the 'BlockID' cookie.
1732 *
1733 * @since 1.29
1734 *
1735 * @param WebResponse $response The response on which to unset the cookie.
1736 */
1737 public static function clearCookie( WebResponse $response ) {
1738 $response->clearCookie( 'BlockID', [ 'httpOnly' => false ] );
1739 }
1740
1741 /**
1742 * Get the BlockID cookie's value for this block. This is usually the block ID concatenated
1743 * with an HMAC in order to avoid spoofing (T152951), but if wgSecretKey is not set will just
1744 * be the block ID.
1745 *
1746 * @since 1.29
1747 *
1748 * @return string The block ID, probably concatenated with "!" and the HMAC.
1749 */
1750 public function getCookieValue() {
1751 $config = RequestContext::getMain()->getConfig();
1752 $id = $this->getId();
1753 $secretKey = $config->get( 'SecretKey' );
1754 if ( !$secretKey ) {
1755 // If there's no secret key, don't append a HMAC.
1756 return $id;
1757 }
1758 $hmac = MWCryptHash::hmac( $id, $secretKey, false );
1759 $cookieValue = $id . '!' . $hmac;
1760 return $cookieValue;
1761 }
1762
1763 /**
1764 * Get the stored ID from the 'BlockID' cookie. The cookie's value is usually a combination of
1765 * the ID and a HMAC (see Block::setCookie), but will sometimes only be the ID.
1766 *
1767 * @since 1.29
1768 *
1769 * @param string $cookieValue The string in which to find the ID.
1770 *
1771 * @return int|null The block ID, or null if the HMAC is present and invalid.
1772 */
1773 public static function getIdFromCookieValue( $cookieValue ) {
1774 // Extract the ID prefix from the cookie value (may be the whole value, if no bang found).
1775 $bangPos = strpos( $cookieValue, '!' );
1776 $id = ( $bangPos === false ) ? $cookieValue : substr( $cookieValue, 0, $bangPos );
1777 // Get the site-wide secret key.
1778 $config = RequestContext::getMain()->getConfig();
1779 $secretKey = $config->get( 'SecretKey' );
1780 if ( !$secretKey ) {
1781 // If there's no secret key, just use the ID as given.
1782 return $id;
1783 }
1784 $storedHmac = substr( $cookieValue, $bangPos + 1 );
1785 $calculatedHmac = MWCryptHash::hmac( $id, $secretKey, false );
1786 if ( $calculatedHmac === $storedHmac ) {
1787 return $id;
1788 } else {
1789 return null;
1790 }
1791 }
1792
1793 /**
1794 * Get the key and parameters for the corresponding error message.
1795 *
1796 * @since 1.22
1797 * @param IContextSource $context
1798 * @return array
1799 */
1800 public function getPermissionsError( IContextSource $context ) {
1801 $params = $this->getBlockErrorParams( $context );
1802
1803 $msg = 'blockedtext';
1804 if ( $this->getSystemBlockType() !== null ) {
1805 $msg = 'systemblockedtext';
1806 } elseif ( $this->mAuto ) {
1807 $msg = 'autoblockedtext';
1808 } elseif ( !$this->isSitewide() ) {
1809 $msg = 'blockedtext-partial';
1810 }
1811
1812 array_unshift( $params, $msg );
1813
1814 return $params;
1815 }
1816
1817 /**
1818 * Get block information used in different block error messages
1819 *
1820 * @since 1.33
1821 * @param IContextSource $context
1822 * @return array
1823 */
1824 public function getBlockErrorParams( IContextSource $context ) {
1825 $blocker = $this->getBlocker();
1826 if ( $blocker instanceof User ) { // local user
1827 $blockerUserpage = $blocker->getUserPage();
1828 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
1829 } else { // foreign user
1830 $link = $blocker;
1831 }
1832
1833 $reason = $this->mReason;
1834 if ( $reason == '' ) {
1835 $reason = $context->msg( 'blockednoreason' )->text();
1836 }
1837
1838 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
1839 * This could be a username, an IP range, or a single IP. */
1840 $intended = $this->getTarget();
1841 $systemBlockType = $this->getSystemBlockType();
1842 $lang = $context->getLanguage();
1843
1844 return [
1845 $link,
1846 $reason,
1847 $context->getRequest()->getIP(),
1848 $this->getByName(),
1849 $systemBlockType ?? $this->getId(),
1850 $lang->formatExpiry( $this->mExpiry ),
1851 (string)$intended,
1852 $lang->userTimeAndDate( $this->mTimestamp, $context->getUser() ),
1853 ];
1854 }
1855
1856 /**
1857 * Get Restrictions.
1858 *
1859 * Getting the restrictions will perform a database query if the restrictions
1860 * are not already loaded.
1861 *
1862 * @since 1.33
1863 * @return Restriction[]
1864 */
1865 public function getRestrictions() {
1866 if ( $this->restrictions === null ) {
1867 // If the block id has not been set, then do not attempt to load the
1868 // restrictions.
1869 if ( !$this->mId ) {
1870 return [];
1871 }
1872 $this->restrictions = BlockRestriction::loadByBlockId( $this->mId );
1873 }
1874
1875 return $this->restrictions;
1876 }
1877
1878 /**
1879 * Set Restrictions.
1880 *
1881 * @since 1.33
1882 * @param Restriction[] $restrictions
1883 * @return self
1884 */
1885 public function setRestrictions( array $restrictions ) {
1886 $this->restrictions = array_filter( $restrictions, function ( $restriction ) {
1887 return $restriction instanceof Restriction;
1888 } );
1889
1890 return $this;
1891 }
1892
1893 /**
1894 * Determine whether the block allows the user to edit their own
1895 * user talk page. This is done separately from Block::appliesToRight
1896 * because there is no right for editing one's own user talk page
1897 * and because the user's talk page needs to be passed into the
1898 * Block object, which is unaware of the user.
1899 *
1900 * The ipb_allow_usertalk flag (which corresponds to the property
1901 * allowUsertalk) is used on sitewide blocks and partial blocks
1902 * that contain a namespace restriction on the user talk namespace,
1903 * but do not contain a page restriction on the user's talk page.
1904 * For all other (i.e. most) partial blocks, the flag is ignored,
1905 * and the user can always edit their user talk page unless there
1906 * is a page restriction on their user talk page, in which case
1907 * they can never edit it. (Ideally the flag would be stored as
1908 * null in these cases, but the database field isn't nullable.)
1909 *
1910 * This method does not validate that the passed in talk page belongs to the
1911 * block target since the target (an IP) might not be the same as the user's
1912 * talk page (if they are logged in).
1913 *
1914 * @since 1.33
1915 * @param Title|null $usertalk The user's user talk page. If null,
1916 * and if the target is a User, the target's userpage is used
1917 * @return bool The user can edit their talk page
1918 */
1919 public function appliesToUsertalk( Title $usertalk = null ) {
1920 if ( !$usertalk ) {
1921 if ( $this->target instanceof User ) {
1922 $usertalk = $this->target->getTalkPage();
1923 } else {
1924 throw new InvalidArgumentException(
1925 '$usertalk must be provided if block target is not a user/IP'
1926 );
1927 }
1928 }
1929
1930 if ( $usertalk->getNamespace() !== NS_USER_TALK ) {
1931 throw new InvalidArgumentException(
1932 '$usertalk must be a user talk page'
1933 );
1934 }
1935
1936 if ( !$this->isSitewide() ) {
1937 if ( $this->appliesToPage( $usertalk->getArticleID() ) ) {
1938 return true;
1939 }
1940 if ( !$this->appliesToNamespace( NS_USER_TALK ) ) {
1941 return false;
1942 }
1943 }
1944
1945 // This is a type of block which uses the ipb_allow_usertalk
1946 // flag. The flag can still be overridden by global configs.
1947 $config = RequestContext::getMain()->getConfig();
1948 if ( !$config->get( 'BlockAllowsUTEdit' ) ) {
1949 return true;
1950 }
1951 return !$this->isUsertalkEditAllowed();
1952 }
1953
1954 /**
1955 * Checks if a block applies to a particular title
1956 *
1957 * This check does not consider whether `$this->isUsertalkEditAllowed`
1958 * returns false, as the identity of the user making the hypothetical edit
1959 * isn't known here (particularly in the case of IP hardblocks, range
1960 * blocks, and auto-blocks).
1961 *
1962 * @param Title $title
1963 * @return bool
1964 */
1965 public function appliesToTitle( Title $title ) {
1966 if ( $this->isSitewide() ) {
1967 return true;
1968 }
1969
1970 $restrictions = $this->getRestrictions();
1971 foreach ( $restrictions as $restriction ) {
1972 if ( $restriction->matches( $title ) ) {
1973 return true;
1974 }
1975 }
1976
1977 return false;
1978 }
1979
1980 /**
1981 * Checks if a block applies to a particular namespace
1982 *
1983 * @since 1.33
1984 *
1985 * @param int $ns
1986 * @return bool
1987 */
1988 public function appliesToNamespace( $ns ) {
1989 if ( $this->isSitewide() ) {
1990 return true;
1991 }
1992
1993 // Blocks do not apply to virtual namespaces.
1994 if ( $ns < 0 ) {
1995 return false;
1996 }
1997
1998 $restriction = $this->findRestriction( NamespaceRestriction::TYPE, $ns );
1999
2000 return (bool)$restriction;
2001 }
2002
2003 /**
2004 * Checks if a block applies to a particular page
2005 *
2006 * This check does not consider whether `$this->isUsertalkEditAllowed`
2007 * returns false, as the identity of the user making the hypothetical edit
2008 * isn't known here (particularly in the case of IP hardblocks, range
2009 * blocks, and auto-blocks).
2010 *
2011 * @since 1.33
2012 *
2013 * @param int $pageId
2014 * @return bool
2015 */
2016 public function appliesToPage( $pageId ) {
2017 if ( $this->isSitewide() ) {
2018 return true;
2019 }
2020
2021 // If the pageId is not over zero, the block cannot apply to it.
2022 if ( $pageId <= 0 ) {
2023 return false;
2024 }
2025
2026 $restriction = $this->findRestriction( PageRestriction::TYPE, $pageId );
2027
2028 return (bool)$restriction;
2029 }
2030
2031 /**
2032 * Find Restriction by type and value.
2033 *
2034 * @param string $type
2035 * @param int $value
2036 * @return Restriction|null
2037 */
2038 private function findRestriction( $type, $value ) {
2039 $restrictions = $this->getRestrictions();
2040 foreach ( $restrictions as $restriction ) {
2041 if ( $restriction->getType() !== $type ) {
2042 continue;
2043 }
2044
2045 if ( $restriction->getValue() === $value ) {
2046 return $restriction;
2047 }
2048 }
2049
2050 return null;
2051 }
2052 }