3 * This program is free software; you can redistribute it and/or modify
4 * it under the terms of the GNU General Public License as published by
5 * the Free Software Foundation; either version 2 of the License, or
6 * (at your option) any later version.
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
13 * You should have received a copy of the GNU General Public License along
14 * with this program; if not, write to the Free Software Foundation, Inc.,
15 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
16 * http://www.gnu.org/copyleft/gpl.html
21 namespace MediaWiki\Block
;
24 use InvalidArgumentException
;
31 * @since 1.34 Factored out from Block.
33 abstract class AbstractBlock
{
44 protected $mBlockEmail = false;
47 protected $allowUsertalk = false;
50 protected $blockCreateAccount = false;
53 public $mHideName = false;
55 /** @var User|string */
59 * @var int Block::TYPE_ constant. After the block has been loaded
60 * from the database, this can only be USER, IP or RANGE.
68 protected $isSitewide = true;
78 * Create a new block with specified parameters on a user, IP or IP range.
80 * @param array $options Parameters of the block:
81 * address string|User Target user name, User object, IP address or IP range
82 * by int User ID of the blocker
83 * reason string Reason of the block
84 * timestamp string The time at which the block comes into effect
85 * byText string Username of the blocker (for foreign users)
87 function __construct( $options = [] ) {
96 $options +
= $defaults;
98 $this->setTarget( $options['address'] );
100 if ( $options['by'] ) {
102 $this->setBlocker( User
::newFromId( $options['by'] ) );
105 $this->setBlocker( $options['byText'] );
108 $this->setReason( $options['reason'] );
109 $this->setTimestamp( wfTimestamp( TS_MW
, $options['timestamp'] ) );
113 * Get the user id of the blocking sysop
115 * @return int (0 for foreign users)
117 public function getBy() {
118 return $this->getBlocker()->getId();
122 * Get the username of the blocking sysop
126 public function getByName() {
127 return $this->getBlocker()->getName();
134 public function getId() {
139 * Get the reason given for creating the block
144 public function getReason() {
145 return $this->mReason
;
149 * Set the reason for creating the block
152 * @param string $reason
154 public function setReason( $reason ) {
155 $this->mReason
= $reason;
159 * Get whether the block hides the target's username
162 * @return bool The block hides the username
164 public function getHideName() {
165 return $this->mHideName
;
169 * Set whether ths block hides the target's username
172 * @param bool $hideName The block hides the username
174 public function setHideName( $hideName ) {
175 $this->mHideName
= $hideName;
179 * Indicates that the block is a sitewide block. This means the user is
180 * prohibited from editing any page on the site (other than their own talk
184 * @param null|bool $x
187 public function isSitewide( $x = null ) {
188 return wfSetVar( $this->isSitewide
, $x );
192 * Get or set the flag indicating whether this block blocks the target from
193 * creating an account. (Note that the flag may be overridden depending on
197 * @param null|bool $x Value to set (if null, just get the property value)
198 * @return bool Value of the property
200 public function isCreateAccountBlocked( $x = null ) {
201 return wfSetVar( $this->blockCreateAccount
, $x );
205 * Get or set the flag indicating whether this block blocks the target from
206 * sending emails. (Note that the flag may be overridden depending on
210 * @param null|bool $x Value to set (if null, just get the property value)
211 * @return bool Value of the property
213 public function isEmailBlocked( $x = null ) {
214 return wfSetVar( $this->mBlockEmail
, $x );
218 * Get or set the flag indicating whether this block blocks the target from
219 * editing their own user talk page. (Note that the flag may be overridden
220 * depending on global configs.)
223 * @param null|bool $x Value to set (if null, just get the property value)
224 * @return bool Value of the property
226 public function isUsertalkEditAllowed( $x = null ) {
227 return wfSetVar( $this->allowUsertalk
, $x );
231 * Determine whether the Block prevents a given right. A right
232 * may be blacklisted or whitelisted, or determined from a
233 * property on the Block object. For certain rights, the property
234 * may be overridden according to global configs.
237 * @param string $right Right to check
238 * @return bool|null null if unrecognized right or unset property
240 public function appliesToRight( $right ) {
241 $config = RequestContext
::getMain()->getConfig();
242 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
247 // TODO: fix this case to return proper value
250 case 'createaccount':
251 $res = $this->isCreateAccountBlocked();
254 $res = $this->isEmailBlocked();
257 // Until T6995 is completed
258 $res = $this->isSitewide();
267 if ( !$res && $blockDisablesLogin ) {
268 // If a block would disable login, then it should
269 // prevent any right that all users cannot do
271 $res = $anon->isAllowed( $right ) ?
$res : true;
278 * Get/set whether the Block prevents a given action
280 * @deprecated since 1.33, use appliesToRight to determine block
281 * behaviour, and specific methods to get/set properties
282 * @param string $action Action to check
283 * @param bool|null $x Value for set, or null to just get value
284 * @return bool|null Null for unrecognized rights.
286 public function prevents( $action, $x = null ) {
287 $config = RequestContext
::getMain()->getConfig();
288 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
289 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
294 # For now... <evil laugh>
297 case 'createaccount':
298 $res = wfSetVar( $this->blockCreateAccount
, $x );
301 $res = wfSetVar( $this->mBlockEmail
, $x );
304 // Until T6995 is completed
305 $res = $this->isSitewide();
307 case 'editownusertalk':
308 // NOTE: this check is not reliable on partial blocks
309 // since partially blocked users are always allowed to edit
310 // their own talk page unless a restriction exists on the
311 // page or User_talk: namespace
312 wfSetVar( $this->allowUsertalk
, $x === null ?
null : !$x );
313 $res = !$this->isUsertalkEditAllowed();
315 // edit own user talk can be disabled by config
316 if ( !$blockAllowsUTEdit ) {
327 if ( !$res && $blockDisablesLogin ) {
328 // If a block would disable login, then it should
329 // prevent any action that all users cannot do
331 $res = $anon->isAllowed( $action ) ?
$res : true;
338 * From an existing Block, get the target and the type of target.
339 * Note that, except for null, it is always safe to treat the target
340 * as a string; for User objects this will return User::__toString()
341 * which in turn gives User::getName().
343 * @param string|int|User|null $target
344 * @return array [ User|String|null, Block::TYPE_ constant|null ]
346 public static function parseTarget( $target ) {
347 # We may have been through this before
348 if ( $target instanceof User
) {
349 if ( IP
::isValid( $target->getName() ) ) {
350 return [ $target, self
::TYPE_IP
];
352 return [ $target, self
::TYPE_USER
];
354 } elseif ( $target === null ) {
355 return [ null, null ];
358 $target = trim( $target );
360 if ( IP
::isValid( $target ) ) {
361 # We can still create a User if it's an IP address, but we need to turn
362 # off validation checking (which would exclude IP addresses)
364 User
::newFromName( IP
::sanitizeIP( $target ), false ),
368 } elseif ( IP
::isValidRange( $target ) ) {
369 # Can't create a User from an IP range
370 return [ IP
::sanitizeRange( $target ), self
::TYPE_RANGE
];
373 # Consider the possibility that this is not a username at all
374 # but actually an old subpage (T31797)
375 if ( strpos( $target, '/' ) !== false ) {
376 # An old subpage, drill down to the user behind it
377 $target = explode( '/', $target )[0];
380 $userObj = User
::newFromName( $target );
381 if ( $userObj instanceof User
) {
382 # Note that since numbers are valid usernames, a $target of "12345" will be
383 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
384 # since hash characters are not valid in usernames or titles generally.
385 return [ $userObj, self
::TYPE_USER
];
387 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
388 # Autoblock reference in the form "#12345"
389 return [ substr( $target, 1 ), self
::TYPE_AUTO
];
392 return [ null, null ];
397 * Get the type of target for this particular block.
398 * @return int Block::TYPE_ constant, will never be TYPE_ID
400 public function getType() {
405 * Get the target and target type for this particular Block. Note that for autoblocks,
406 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
408 * @return array [ User|String, Block::TYPE_ constant ]
409 * @todo FIXME: This should be an integral part of the Block member variables
411 public function getTargetAndType() {
412 return [ $this->getTarget(), $this->getType() ];
416 * Get the target for this particular Block. Note that for autoblocks,
417 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
419 * @return User|string
421 public function getTarget() {
422 return $this->target
;
426 * Get the block expiry time
431 public function getExpiry() {
432 return $this->mExpiry
;
436 * Set the block expiry time
439 * @param string $expiry
441 public function setExpiry( $expiry ) {
442 $this->mExpiry
= $expiry;
446 * Get the timestamp indicating when the block was created
451 public function getTimestamp() {
452 return $this->mTimestamp
;
456 * Set the timestamp indicating when the block was created
459 * @param string $timestamp
461 public function setTimestamp( $timestamp ) {
462 $this->mTimestamp
= $timestamp;
466 * Set the target for this block, and update $this->type accordingly
467 * @param mixed $target
469 public function setTarget( $target ) {
470 list( $this->target
, $this->type
) = static::parseTarget( $target );
474 * Get the user who implemented this block
475 * @return User User object. May name a foreign user.
477 public function getBlocker() {
478 return $this->blocker
;
482 * Set the user who implemented (or will implement) this block
483 * @param User|string $user Local User object or username string
485 public function setBlocker( $user ) {
486 if ( is_string( $user ) ) {
487 $user = User
::newFromName( $user, false );
490 if ( $user->isAnon() && User
::isUsableName( $user->getName() ) ) {
491 throw new InvalidArgumentException(
492 'Blocker must be a local user or a name that cannot be a local user'
496 $this->blocker
= $user;
500 * Get the key and parameters for the corresponding error message.
503 * @param IContextSource $context
506 abstract public function getPermissionsError( IContextSource
$context );
509 * Get block information used in different block error messages
512 * @param IContextSource $context
515 public function getBlockErrorParams( IContextSource
$context ) {
516 $blocker = $this->getBlocker();
517 if ( $blocker instanceof User
) { // local user
518 $blockerUserpage = $blocker->getUserPage();
519 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerUserpage->getText()}]]";
520 } else { // foreign user
524 $reason = $this->getReason();
525 if ( $reason == '' ) {
526 $reason = $context->msg( 'blockednoreason' )->text();
529 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
530 * This could be a username, an IP range, or a single IP. */
531 $intended = $this->getTarget();
532 $lang = $context->getLanguage();
537 $context->getRequest()->getIP(),
539 // TODO: SystemBlock replaces this with the system block type. Clean up
540 // error params so that this is not necessary.
542 $lang->formatExpiry( $this->getExpiry() ),
544 $lang->userTimeAndDate( $this->getTimestamp(), $context->getUser() ),
549 * Determine whether the block allows the user to edit their own
550 * user talk page. This is done separately from Block::appliesToRight
551 * because there is no right for editing one's own user talk page
552 * and because the user's talk page needs to be passed into the
553 * Block object, which is unaware of the user.
555 * The ipb_allow_usertalk flag (which corresponds to the property
556 * allowUsertalk) is used on sitewide blocks and partial blocks
557 * that contain a namespace restriction on the user talk namespace,
558 * but do not contain a page restriction on the user's talk page.
559 * For all other (i.e. most) partial blocks, the flag is ignored,
560 * and the user can always edit their user talk page unless there
561 * is a page restriction on their user talk page, in which case
562 * they can never edit it. (Ideally the flag would be stored as
563 * null in these cases, but the database field isn't nullable.)
565 * This method does not validate that the passed in talk page belongs to the
566 * block target since the target (an IP) might not be the same as the user's
567 * talk page (if they are logged in).
570 * @param Title|null $usertalk The user's user talk page. If null,
571 * and if the target is a User, the target's userpage is used
572 * @return bool The user can edit their talk page
574 public function appliesToUsertalk( Title
$usertalk = null ) {
576 if ( $this->target
instanceof User
) {
577 $usertalk = $this->target
->getTalkPage();
579 throw new InvalidArgumentException(
580 '$usertalk must be provided if block target is not a user/IP'
585 if ( $usertalk->getNamespace() !== NS_USER_TALK
) {
586 throw new InvalidArgumentException(
587 '$usertalk must be a user talk page'
591 if ( !$this->isSitewide() ) {
592 if ( $this->appliesToPage( $usertalk->getArticleID() ) ) {
595 if ( !$this->appliesToNamespace( NS_USER_TALK
) ) {
600 // This is a type of block which uses the ipb_allow_usertalk
601 // flag. The flag can still be overridden by global configs.
602 $config = RequestContext
::getMain()->getConfig();
603 if ( !$config->get( 'BlockAllowsUTEdit' ) ) {
606 return !$this->isUsertalkEditAllowed();
610 * Checks if a block applies to a particular title
612 * This check does not consider whether `$this->isUsertalkEditAllowed`
613 * returns false, as the identity of the user making the hypothetical edit
614 * isn't known here (particularly in the case of IP hardblocks, range
615 * blocks, and auto-blocks).
617 * @param Title $title
620 public function appliesToTitle( Title
$title ) {
621 return $this->isSitewide();
625 * Checks if a block applies to a particular namespace
632 public function appliesToNamespace( $ns ) {
633 return $this->isSitewide();
637 * Checks if a block applies to a particular page
639 * This check does not consider whether `$this->isUsertalkEditAllowed`
640 * returns false, as the identity of the user making the hypothetical edit
641 * isn't known here (particularly in the case of IP hardblocks, range
642 * blocks, and auto-blocks).
649 public function appliesToPage( $pageId ) {
650 return $this->isSitewide();
654 * Check if the block should be tracked with a cookie.
657 * @param bool $isAnon The user is logged out
658 * @return bool The block should be tracked with a cookie
660 public function shouldTrackWithCookie( $isAnon ) {
665 * Check if the block prevents a user from resetting their password
668 * @return bool The block blocks password reset
670 public function appliesToPasswordReset() {
671 return $this->isCreateAccountBlocked();