MediaWiki  master
AbstractBlock.php
Go to the documentation of this file.
1 <?php
21 namespace MediaWiki\Block;
22 
25 use IP;
27 use Title;
28 use User;
29 
33 abstract class AbstractBlock {
38  public $mReason;
39 
44  public $mTimestamp;
45 
50  public $mExpiry = '';
51 
53  protected $mBlockEmail = false;
54 
56  protected $allowUsertalk = false;
57 
59  protected $blockCreateAccount = false;
60 
65  public $mHideName = false;
66 
68  protected $target;
69 
74  protected $type;
75 
77  protected $blocker;
78 
80  protected $isSitewide = true;
81 
82  # TYPE constants
83  const TYPE_USER = 1;
84  const TYPE_IP = 2;
85  const TYPE_RANGE = 3;
86  const TYPE_AUTO = 4;
87  const TYPE_ID = 5;
88 
99  public function __construct( array $options = [] ) {
100  $defaults = [
101  'address' => '',
102  'by' => null,
103  'reason' => '',
104  'timestamp' => '',
105  'byText' => '',
106  ];
107 
108  $options += $defaults;
109 
110  $this->setTarget( $options['address'] );
111 
112  if ( $options['by'] ) {
113  # Local user
114  $this->setBlocker( User::newFromId( $options['by'] ) );
115  } else {
116  # Foreign user
117  $this->setBlocker( $options['byText'] );
118  }
119 
120  $this->setReason( $options['reason'] );
121  $this->setTimestamp( wfTimestamp( TS_MW, $options['timestamp'] ) );
122  }
123 
129  public function getBy() {
130  return $this->getBlocker()->getId();
131  }
132 
138  public function getByName() {
139  return $this->getBlocker()->getName();
140  }
141 
146  public function getId() {
147  return null;
148  }
149 
156  public function getReason() {
157  return $this->mReason;
158  }
159 
166  public function setReason( $reason ) {
167  $this->mReason = $reason;
168  }
169 
176  public function getHideName() {
177  return $this->mHideName;
178  }
179 
186  public function setHideName( $hideName ) {
187  $this->mHideName = $hideName;
188  }
189 
199  public function isSitewide( $x = null ) {
200  return wfSetVar( $this->isSitewide, $x );
201  }
202 
212  public function isCreateAccountBlocked( $x = null ) {
213  return wfSetVar( $this->blockCreateAccount, $x );
214  }
215 
225  public function isEmailBlocked( $x = null ) {
226  return wfSetVar( $this->mBlockEmail, $x );
227  }
228 
238  public function isUsertalkEditAllowed( $x = null ) {
239  return wfSetVar( $this->allowUsertalk, $x );
240  }
241 
252  public function appliesToRight( $right ) {
253  $config = RequestContext::getMain()->getConfig();
254  $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
255 
256  $res = null;
257  switch ( $right ) {
258  case 'edit':
259  // TODO: fix this case to return proper value
260  $res = true;
261  break;
262  case 'createaccount':
263  $res = $this->isCreateAccountBlocked();
264  break;
265  case 'sendemail':
266  $res = $this->isEmailBlocked();
267  break;
268  case 'upload':
269  // Until T6995 is completed
270  $res = $this->isSitewide();
271  break;
272  case 'read':
273  $res = false;
274  break;
275  case 'purge':
276  $res = false;
277  break;
278  }
279  if ( !$res && $blockDisablesLogin ) {
280  // If a block would disable login, then it should
281  // prevent any right that all users cannot do
282  $anon = new User;
283  $res = $anon->isAllowed( $right ) ? $res : true;
284  }
285 
286  return $res;
287  }
288 
298  public function prevents( $action, $x = null ) {
299  $config = RequestContext::getMain()->getConfig();
300  $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
301  $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
302 
303  $res = null;
304  switch ( $action ) {
305  case 'edit':
306  # For now... <evil laugh>
307  $res = true;
308  break;
309  case 'createaccount':
310  $res = wfSetVar( $this->blockCreateAccount, $x );
311  break;
312  case 'sendemail':
313  $res = wfSetVar( $this->mBlockEmail, $x );
314  break;
315  case 'upload':
316  // Until T6995 is completed
317  $res = $this->isSitewide();
318  break;
319  case 'editownusertalk':
320  // NOTE: this check is not reliable on partial blocks
321  // since partially blocked users are always allowed to edit
322  // their own talk page unless a restriction exists on the
323  // page or User_talk: namespace
324  wfSetVar( $this->allowUsertalk, $x === null ? null : !$x );
325  $res = !$this->isUsertalkEditAllowed();
326 
327  // edit own user talk can be disabled by config
328  if ( !$blockAllowsUTEdit ) {
329  $res = true;
330  }
331  break;
332  case 'read':
333  $res = false;
334  break;
335  case 'purge':
336  $res = false;
337  break;
338  }
339  if ( !$res && $blockDisablesLogin ) {
340  // If a block would disable login, then it should
341  // prevent any action that all users cannot do
342  $anon = new User;
343  $res = $anon->isAllowed( $action ) ? $res : true;
344  }
345 
346  return $res;
347  }
348 
358  public static function parseTarget( $target ) {
359  # We may have been through this before
360  if ( $target instanceof User ) {
361  if ( IP::isValid( $target->getName() ) ) {
362  return [ $target, self::TYPE_IP ];
363  } else {
364  return [ $target, self::TYPE_USER ];
365  }
366  } elseif ( $target === null ) {
367  return [ null, null ];
368  }
369 
370  $target = trim( $target );
371 
372  if ( IP::isValid( $target ) ) {
373  # We can still create a User if it's an IP address, but we need to turn
374  # off validation checking (which would exclude IP addresses)
375  return [
377  self::TYPE_IP
378  ];
379 
380  } elseif ( IP::isValidRange( $target ) ) {
381  # Can't create a User from an IP range
382  return [ IP::sanitizeRange( $target ), self::TYPE_RANGE ];
383  }
384 
385  # Consider the possibility that this is not a username at all
386  # but actually an old subpage (T31797)
387  if ( strpos( $target, '/' ) !== false ) {
388  # An old subpage, drill down to the user behind it
389  $target = explode( '/', $target )[0];
390  }
391 
392  $userObj = User::newFromName( $target );
393  if ( $userObj instanceof User ) {
394  # Note that since numbers are valid usernames, a $target of "12345" will be
395  # considered a User. If you want to pass a block ID, prepend a hash "#12345",
396  # since hash characters are not valid in usernames or titles generally.
397  return [ $userObj, self::TYPE_USER ];
398 
399  } elseif ( preg_match( '/^#\d+$/', $target ) ) {
400  # Autoblock reference in the form "#12345"
401  return [ substr( $target, 1 ), self::TYPE_AUTO ];
402 
403  } else {
404  return [ null, null ];
405  }
406  }
407 
412  public function getType() {
413  return $this->type;
414  }
415 
423  public function getTargetAndType() {
424  return [ $this->getTarget(), $this->getType() ];
425  }
426 
433  public function getTarget() {
434  return $this->target;
435  }
436 
443  public function getExpiry() {
444  return $this->mExpiry;
445  }
446 
453  public function setExpiry( $expiry ) {
454  $this->mExpiry = $expiry;
455  }
456 
463  public function getTimestamp() {
464  return $this->mTimestamp;
465  }
466 
473  public function setTimestamp( $timestamp ) {
474  $this->mTimestamp = $timestamp;
475  }
476 
481  public function setTarget( $target ) {
482  list( $this->target, $this->type ) = static::parseTarget( $target );
483  }
484 
489  public function getBlocker() {
490  return $this->blocker;
491  }
492 
497  public function setBlocker( $user ) {
498  if ( is_string( $user ) ) {
499  $user = User::newFromName( $user, false );
500  }
501 
502  if ( $user->isAnon() && User::isUsableName( $user->getName() ) ) {
503  throw new InvalidArgumentException(
504  'Blocker must be a local user or a name that cannot be a local user'
505  );
506  }
507 
508  $this->blocker = $user;
509  }
510 
518  abstract public function getPermissionsError( IContextSource $context );
519 
527  public function getBlockErrorParams( IContextSource $context ) {
528  $lang = $context->getLanguage();
529 
530  $blocker = $this->getBlocker();
531  if ( $blocker instanceof User ) { // local user
532  $blockerUserpage = $blocker->getUserPage();
533  $blockerText = $lang->embedBidi( $blockerUserpage->getText() );
534  $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerText}]]";
535  } else { // foreign user
536  $link = $blocker;
537  }
538 
539  $reason = $this->getReason();
540  if ( $reason == '' ) {
541  $reason = $context->msg( 'blockednoreason' )->text();
542  }
543 
544  /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
545  * This could be a username, an IP range, or a single IP. */
546  $intended = (string)$this->getTarget();
547 
548  return [
549  $link,
550  $reason,
551  $context->getRequest()->getIP(),
552  $lang->embedBidi( $this->getByName() ),
553  // TODO: SystemBlock replaces this with the system block type. Clean up
554  // error params so that this is not necessary.
555  $this->getId(),
556  $lang->formatExpiry( $this->getExpiry() ),
557  $lang->embedBidi( $intended ),
558  $lang->userTimeAndDate( $this->getTimestamp(), $context->getUser() ),
559  ];
560  }
561 
589  public function appliesToUsertalk( Title $usertalk = null ) {
590  if ( !$usertalk ) {
591  if ( $this->target instanceof User ) {
592  $usertalk = $this->target->getTalkPage();
593  } else {
594  throw new InvalidArgumentException(
595  '$usertalk must be provided if block target is not a user/IP'
596  );
597  }
598  }
599 
600  if ( $usertalk->getNamespace() !== NS_USER_TALK ) {
601  throw new InvalidArgumentException(
602  '$usertalk must be a user talk page'
603  );
604  }
605 
606  if ( !$this->isSitewide() ) {
607  if ( $this->appliesToPage( $usertalk->getArticleID() ) ) {
608  return true;
609  }
610  if ( !$this->appliesToNamespace( NS_USER_TALK ) ) {
611  return false;
612  }
613  }
614 
615  // This is a type of block which uses the ipb_allow_usertalk
616  // flag. The flag can still be overridden by global configs.
617  $config = RequestContext::getMain()->getConfig();
618  if ( !$config->get( 'BlockAllowsUTEdit' ) ) {
619  return true;
620  }
621  return !$this->isUsertalkEditAllowed();
622  }
623 
635  public function appliesToTitle( Title $title ) {
636  return $this->isSitewide();
637  }
638 
647  public function appliesToNamespace( $ns ) {
648  return $this->isSitewide();
649  }
650 
664  public function appliesToPage( $pageId ) {
665  return $this->isSitewide();
666  }
667 
677  public function shouldTrackWithCookie( $isAnon ) {
678  wfDeprecated( __METHOD__, '1.34' );
679  return false;
680  }
681 
688  public function appliesToPasswordReset() {
689  return $this->isCreateAccountBlocked();
690  }
691 
692 }
isUsertalkEditAllowed( $x=null)
Get or set the flag indicating whether this block blocks the target from editing their own user talk ...
Config $config
Definition: MediaWiki.php:43
static isValidRange( $ipRange)
Validate an IP range (valid address with a valid CIDR prefix).
Definition: IP.php:125
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
isCreateAccountBlocked( $x=null)
Get or set the flag indicating whether this block blocks the target from creating an account...
getBy()
Get the user id of the blocking sysop.
int $type
AbstractBlock::TYPE_ constant.
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
if(!isset( $args[0])) $lang
appliesToUsertalk(Title $usertalk=null)
Determine whether the block allows the user to edit their own user talk page.
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
Definition: hooks.txt:175
string $action
Cache what action this request is.
Definition: MediaWiki.php:48
setBlocker( $user)
Set the user who implemented (or will implement) this block.
static sanitizeRange( $range)
Gets rid of unneeded numbers in quad-dotted/octet IP strings For example, 127.111.113.151/24 -> 127.111.113.0/24.
Definition: IP.php:712
get( $name)
Get a configuration variable such as "Sitename" or "UploadMaintenance.".
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2251
usually copyright or history_copyright This message must be in HTML not wikitext & $link
Definition: hooks.txt:3039
The User object encapsulates all of the user-specific settings (user_id, name, rights, email address, options, last login time).
Definition: User.php:51
getTargetAndType()
Get the target and target type for this particular block.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
static getMain()
Get the RequestContext object associated with the main request.
IContextSource $context
Definition: MediaWiki.php:38
shouldTrackWithCookie( $isAnon)
Check if the block should be tracked with a cookie.
static sanitizeIP( $ip)
Convert an IP into a verbose, uppercase, normalized form.
Definition: IP.php:139
appliesToPasswordReset()
Check if the block prevents a user from resetting their password.
isSitewide( $x=null)
Indicates that the block is a sitewide block.
$res
Definition: database.txt:21
static isValid( $ip)
Validate an IP address.
Definition: IP.php:111
appliesToTitle(Title $title)
Checks if a block applies to a particular title.
getPermissionsError(IContextSource $context)
Get the key and parameters for the corresponding error message.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
Definition: hooks.txt:1972
__construct(array $options=[])
Create a new block with specified parameters on a user, IP or IP range.
getBlockErrorParams(IContextSource $context)
Get block information used in different block error messages.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
Definition: hooks.txt:767
static isUsableName( $name)
Usernames which fail to pass this function will be blocked from user login and new account registrati...
Definition: User.php:1001
isEmailBlocked( $x=null)
Get or set the flag indicating whether this block blocks the target from sending emails.
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:912
prevents( $action, $x=null)
Get/set whether the block prevents a given action.
getType()
Get the type of target for this particular block.
appliesToRight( $right)
Determine whether the block prevents a given right.
msg( $key)
This is the method for getting translated interface messages.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
getTimestamp()
Get the timestamp indicating when the block was created.
wfSetVar(&$dest, $source, $force=false)
Sets dest to source and returns the original value of dest If source is NULL, it just returns the val...
setTimestamp( $timestamp)
Set the timestamp indicating when the block was created.
getBlocker()
Get the user who implemented this block.
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:559
This document describes the state of Postgres support in and is fairly well maintained The main code is very well while extensions are very hit and miss it is probably the most supported database after MySQL Much of the work in making MediaWiki database agnostic came about through the work of creating Postgres as and are nearing end of but without copying over all the usage comments General notes on the but these can almost always be programmed around *Although Postgres has a true BOOLEAN type
Definition: postgres.txt:22
getHideName()
Get whether the block hides the target&#39;s username.
static parseTarget( $target)
From an existing block, get the target and the type of target.
appliesToPage( $pageId)
Checks if a block applies to a particular page.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
getUserPage()
Get this user&#39;s personal page title.
Definition: User.php:4331
setHideName( $hideName)
Set whether ths block hides the target&#39;s username.
setTarget( $target)
Set the target for this block, and update $this->type accordingly.
setExpiry( $expiry)
Set the block expiry time.
getExpiry()
Get the block expiry time.
getTarget()
Get the target for this particular block.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
Definition: User.php:535
setReason( $reason)
Set the reason for creating the block.
const NS_USER_TALK
Definition: Defines.php:63
getReason()
Get the reason given for creating the block.
appliesToNamespace( $ns)
Checks if a block applies to a particular namespace.
return true to allow those checks to and false if checking is done & $user
Definition: hooks.txt:1454
getByName()
Get the username of the blocking sysop.