Merge "Preserve grapheme clusters in upper corner completion suggester highlighting"
[lhc/web/wiklou.git] / includes / block / AbstractBlock.php
1 <?php
2 /**
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.
7 *
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.
12 *
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
17 *
18 * @file
19 */
20
21 namespace MediaWiki\Block;
22
23 use IContextSource;
24 use InvalidArgumentException;
25 use IP;
26 use MediaWiki\MediaWikiServices;
27 use RequestContext;
28 use Title;
29 use User;
30
31 /**
32 * @since 1.34 Factored out from DatabaseBlock (previously Block).
33 */
34 abstract class AbstractBlock {
35 /**
36 * @deprecated since 1.34. Use getReason and setReason instead.
37 * @var string
38 */
39 public $mReason;
40
41 /**
42 * @deprecated since 1.34. Use getTimestamp and setTimestamp instead.
43 * @var string
44 */
45 public $mTimestamp;
46
47 /**
48 * @deprecated since 1.34. Use getExpiry and setExpiry instead.
49 * @var string
50 */
51 public $mExpiry = '';
52
53 /** @var bool */
54 protected $mBlockEmail = false;
55
56 /** @var bool */
57 protected $allowUsertalk = false;
58
59 /** @var bool */
60 protected $blockCreateAccount = false;
61
62 /**
63 * @deprecated since 1.34. Use getHideName and setHideName instead.
64 * @var bool
65 */
66 public $mHideName = false;
67
68 /** @var User|string */
69 protected $target;
70
71 /**
72 * @var int AbstractBlock::TYPE_ constant. After the block has been loaded
73 * from the database, this can only be USER, IP or RANGE.
74 */
75 protected $type;
76
77 /** @var User */
78 protected $blocker;
79
80 /** @var bool */
81 protected $isSitewide = true;
82
83 # TYPE constants
84 const TYPE_USER = 1;
85 const TYPE_IP = 2;
86 const TYPE_RANGE = 3;
87 const TYPE_AUTO = 4;
88 const TYPE_ID = 5;
89
90 /**
91 * Create a new block with specified parameters on a user, IP or IP range.
92 *
93 * @param array $options Parameters of the block:
94 * address string|User Target user name, User object, IP address or IP range
95 * by int User ID of the blocker
96 * reason string Reason of the block
97 * timestamp string The time at which the block comes into effect
98 * byText string Username of the blocker (for foreign users)
99 * hideName bool Hide the target user name
100 */
101 public function __construct( array $options = [] ) {
102 $defaults = [
103 'address' => '',
104 'by' => null,
105 'reason' => '',
106 'timestamp' => '',
107 'byText' => '',
108 'hideName' => false,
109 ];
110
111 $options += $defaults;
112
113 $this->setTarget( $options['address'] );
114
115 if ( $options['by'] ) {
116 # Local user
117 $this->setBlocker( User::newFromId( $options['by'] ) );
118 } else {
119 # Foreign user
120 $this->setBlocker( $options['byText'] );
121 }
122
123 $this->setReason( $options['reason'] );
124 $this->setTimestamp( wfTimestamp( TS_MW, $options['timestamp'] ) );
125 $this->setHideName( (bool)$options['hideName'] );
126 }
127
128 /**
129 * Get the user id of the blocking sysop
130 *
131 * @return int (0 for foreign users)
132 */
133 public function getBy() {
134 return $this->getBlocker()->getId();
135 }
136
137 /**
138 * Get the username of the blocking sysop
139 *
140 * @return string
141 */
142 public function getByName() {
143 return $this->getBlocker()->getName();
144 }
145
146 /**
147 * Get the block ID
148 * @return int|null
149 */
150 public function getId() {
151 return null;
152 }
153
154 /**
155 * Get the reason given for creating the block
156 *
157 * @since 1.33
158 * @return string
159 */
160 public function getReason() {
161 return $this->mReason;
162 }
163
164 /**
165 * Set the reason for creating the block
166 *
167 * @since 1.33
168 * @param string $reason
169 */
170 public function setReason( $reason ) {
171 $this->mReason = $reason;
172 }
173
174 /**
175 * Get whether the block hides the target's username
176 *
177 * @since 1.33
178 * @return bool The block hides the username
179 */
180 public function getHideName() {
181 return $this->mHideName;
182 }
183
184 /**
185 * Set whether ths block hides the target's username
186 *
187 * @since 1.33
188 * @param bool $hideName The block hides the username
189 */
190 public function setHideName( $hideName ) {
191 $this->mHideName = $hideName;
192 }
193
194 /**
195 * Indicates that the block is a sitewide block. This means the user is
196 * prohibited from editing any page on the site (other than their own talk
197 * page).
198 *
199 * @since 1.33
200 * @param null|bool $x
201 * @return bool
202 */
203 public function isSitewide( $x = null ) {
204 return wfSetVar( $this->isSitewide, $x );
205 }
206
207 /**
208 * Get or set the flag indicating whether this block blocks the target from
209 * creating an account. (Note that the flag may be overridden depending on
210 * global configs.)
211 *
212 * @since 1.33
213 * @param null|bool $x Value to set (if null, just get the property value)
214 * @return bool Value of the property
215 */
216 public function isCreateAccountBlocked( $x = null ) {
217 return wfSetVar( $this->blockCreateAccount, $x );
218 }
219
220 /**
221 * Get or set the flag indicating whether this block blocks the target from
222 * sending emails. (Note that the flag may be overridden depending on
223 * global configs.)
224 *
225 * @since 1.33
226 * @param null|bool $x Value to set (if null, just get the property value)
227 * @return bool Value of the property
228 */
229 public function isEmailBlocked( $x = null ) {
230 return wfSetVar( $this->mBlockEmail, $x );
231 }
232
233 /**
234 * Get or set the flag indicating whether this block blocks the target from
235 * editing their own user talk page. (Note that the flag may be overridden
236 * depending on global configs.)
237 *
238 * @since 1.33
239 * @param null|bool $x Value to set (if null, just get the property value)
240 * @return bool Value of the property
241 */
242 public function isUsertalkEditAllowed( $x = null ) {
243 return wfSetVar( $this->allowUsertalk, $x );
244 }
245
246 /**
247 * Determine whether the block prevents a given right. A right
248 * may be blacklisted or whitelisted, or determined from a
249 * property on the block object. For certain rights, the property
250 * may be overridden according to global configs.
251 *
252 * @since 1.33
253 * @param string $right Right to check
254 * @return bool|null null if unrecognized right or unset property
255 */
256 public function appliesToRight( $right ) {
257 $config = RequestContext::getMain()->getConfig();
258 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
259
260 $res = null;
261 switch ( $right ) {
262 case 'edit':
263 // TODO: fix this case to return proper value
264 $res = true;
265 break;
266 case 'createaccount':
267 $res = $this->isCreateAccountBlocked();
268 break;
269 case 'sendemail':
270 $res = $this->isEmailBlocked();
271 break;
272 case 'upload':
273 // Until T6995 is completed
274 $res = $this->isSitewide();
275 break;
276 case 'read':
277 $res = false;
278 break;
279 case 'purge':
280 $res = false;
281 break;
282 }
283 if ( !$res && $blockDisablesLogin ) {
284 // If a block would disable login, then it should
285 // prevent any right that all users cannot do
286 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
287 $anon = new User;
288 $res = $permissionManager->userHasRight( $anon, $right ) ? $res : true;
289 }
290
291 return $res;
292 }
293
294 /**
295 * Get/set whether the block prevents a given action
296 *
297 * @deprecated since 1.33, use appliesToRight to determine block
298 * behaviour, and specific methods to get/set properties
299 * @param string $action Action to check
300 * @param bool|null $x Value for set, or null to just get value
301 * @return bool|null Null for unrecognized rights.
302 */
303 public function prevents( $action, $x = null ) {
304 $config = RequestContext::getMain()->getConfig();
305 $blockDisablesLogin = $config->get( 'BlockDisablesLogin' );
306 $blockAllowsUTEdit = $config->get( 'BlockAllowsUTEdit' );
307
308 $res = null;
309 switch ( $action ) {
310 case 'edit':
311 # For now... <evil laugh>
312 $res = true;
313 break;
314 case 'createaccount':
315 $res = wfSetVar( $this->blockCreateAccount, $x );
316 break;
317 case 'sendemail':
318 $res = wfSetVar( $this->mBlockEmail, $x );
319 break;
320 case 'upload':
321 // Until T6995 is completed
322 $res = $this->isSitewide();
323 break;
324 case 'editownusertalk':
325 // NOTE: this check is not reliable on partial blocks
326 // since partially blocked users are always allowed to edit
327 // their own talk page unless a restriction exists on the
328 // page or User_talk: namespace
329 wfSetVar( $this->allowUsertalk, $x === null ? null : !$x );
330 $res = !$this->isUsertalkEditAllowed();
331
332 // edit own user talk can be disabled by config
333 if ( !$blockAllowsUTEdit ) {
334 $res = true;
335 }
336 break;
337 case 'read':
338 $res = false;
339 break;
340 case 'purge':
341 $res = false;
342 break;
343 }
344 if ( !$res && $blockDisablesLogin ) {
345 // If a block would disable login, then it should
346 // prevent any action that all users cannot do
347 $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
348 $anon = new User;
349 $res = $permissionManager->userHasRight( $anon, $action ) ? $res : true;
350 }
351
352 return $res;
353 }
354
355 /**
356 * From an existing block, get the target and the type of target.
357 * Note that, except for null, it is always safe to treat the target
358 * as a string; for User objects this will return User::__toString()
359 * which in turn gives User::getName().
360 *
361 * @param string|int|User|null $target
362 * @return array [ User|String|null, AbstractBlock::TYPE_ constant|null ]
363 */
364 public static function parseTarget( $target ) {
365 # We may have been through this before
366 if ( $target instanceof User ) {
367 if ( IP::isValid( $target->getName() ) ) {
368 return [ $target, self::TYPE_IP ];
369 } else {
370 return [ $target, self::TYPE_USER ];
371 }
372 } elseif ( $target === null ) {
373 return [ null, null ];
374 }
375
376 $target = trim( $target );
377
378 if ( IP::isValid( $target ) ) {
379 # We can still create a User if it's an IP address, but we need to turn
380 # off validation checking (which would exclude IP addresses)
381 return [
382 User::newFromName( IP::sanitizeIP( $target ), false ),
383 self::TYPE_IP
384 ];
385
386 } elseif ( IP::isValidRange( $target ) ) {
387 # Can't create a User from an IP range
388 return [ IP::sanitizeRange( $target ), self::TYPE_RANGE ];
389 }
390
391 # Consider the possibility that this is not a username at all
392 # but actually an old subpage (T31797)
393 if ( strpos( $target, '/' ) !== false ) {
394 # An old subpage, drill down to the user behind it
395 $target = explode( '/', $target )[0];
396 }
397
398 $userObj = User::newFromName( $target );
399 if ( $userObj instanceof User ) {
400 # Note that since numbers are valid usernames, a $target of "12345" will be
401 # considered a User. If you want to pass a block ID, prepend a hash "#12345",
402 # since hash characters are not valid in usernames or titles generally.
403 return [ $userObj, self::TYPE_USER ];
404
405 } elseif ( preg_match( '/^#\d+$/', $target ) ) {
406 # Autoblock reference in the form "#12345"
407 return [ substr( $target, 1 ), self::TYPE_AUTO ];
408
409 } else {
410 return [ null, null ];
411 }
412 }
413
414 /**
415 * Get the type of target for this particular block.
416 * @return int AbstractBlock::TYPE_ constant, will never be TYPE_ID
417 */
418 public function getType() {
419 return $this->type;
420 }
421
422 /**
423 * Get the target and target type for this particular block. Note that for autoblocks,
424 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
425 * in this situation.
426 * @return array [ User|String, AbstractBlock::TYPE_ constant ]
427 * @todo FIXME: This should be an integral part of the block member variables
428 */
429 public function getTargetAndType() {
430 return [ $this->getTarget(), $this->getType() ];
431 }
432
433 /**
434 * Get the target for this particular block. Note that for autoblocks,
435 * this returns the unredacted name; frontend functions need to call $block->getRedactedName()
436 * in this situation.
437 * @return User|string
438 */
439 public function getTarget() {
440 return $this->target;
441 }
442
443 /**
444 * Get the block expiry time
445 *
446 * @since 1.19
447 * @return string
448 */
449 public function getExpiry() {
450 return $this->mExpiry;
451 }
452
453 /**
454 * Set the block expiry time
455 *
456 * @since 1.33
457 * @param string $expiry
458 */
459 public function setExpiry( $expiry ) {
460 $this->mExpiry = $expiry;
461 }
462
463 /**
464 * Get the timestamp indicating when the block was created
465 *
466 * @since 1.33
467 * @return string
468 */
469 public function getTimestamp() {
470 return $this->mTimestamp;
471 }
472
473 /**
474 * Set the timestamp indicating when the block was created
475 *
476 * @since 1.33
477 * @param string $timestamp
478 */
479 public function setTimestamp( $timestamp ) {
480 $this->mTimestamp = $timestamp;
481 }
482
483 /**
484 * Set the target for this block, and update $this->type accordingly
485 * @param mixed $target
486 */
487 public function setTarget( $target ) {
488 list( $this->target, $this->type ) = static::parseTarget( $target );
489 }
490
491 /**
492 * Get the user who implemented this block
493 * @return User User object. May name a foreign user.
494 */
495 public function getBlocker() {
496 return $this->blocker;
497 }
498
499 /**
500 * Set the user who implemented (or will implement) this block
501 * @param User|string $user Local User object or username string
502 */
503 public function setBlocker( $user ) {
504 if ( is_string( $user ) ) {
505 $user = User::newFromName( $user, false );
506 }
507
508 if ( $user->isAnon() && User::isUsableName( $user->getName() ) ) {
509 throw new InvalidArgumentException(
510 'Blocker must be a local user or a name that cannot be a local user'
511 );
512 }
513
514 $this->blocker = $user;
515 }
516
517 /**
518 * Get the key and parameters for the corresponding error message.
519 *
520 * @since 1.22
521 * @param IContextSource $context
522 * @return array
523 */
524 abstract public function getPermissionsError( IContextSource $context );
525
526 /**
527 * Get block information used in different block error messages
528 *
529 * @since 1.33
530 * @param IContextSource $context
531 * @return array
532 */
533 public function getBlockErrorParams( IContextSource $context ) {
534 $lang = $context->getLanguage();
535
536 $blocker = $this->getBlocker();
537 if ( $blocker instanceof User ) { // local user
538 $blockerUserpage = $blocker->getUserPage();
539 $blockerText = $lang->embedBidi( $blockerUserpage->getText() );
540 $link = "[[{$blockerUserpage->getPrefixedText()}|{$blockerText}]]";
541 } else { // foreign user
542 $link = $blocker;
543 }
544
545 $reason = $this->getReason();
546 if ( $reason == '' ) {
547 $reason = $context->msg( 'blockednoreason' )->text();
548 }
549
550 /* $ip returns who *is* being blocked, $intended contains who was meant to be blocked.
551 * This could be a username, an IP range, or a single IP. */
552 $intended = (string)$this->getTarget();
553
554 return [
555 $link,
556 $reason,
557 $context->getRequest()->getIP(),
558 $lang->embedBidi( $this->getByName() ),
559 // TODO: SystemBlock replaces this with the system block type. Clean up
560 // error params so that this is not necessary.
561 $this->getId(),
562 $lang->formatExpiry( $this->getExpiry() ),
563 $lang->embedBidi( $intended ),
564 $lang->userTimeAndDate( $this->getTimestamp(), $context->getUser() ),
565 ];
566 }
567
568 /**
569 * Determine whether the block allows the user to edit their own
570 * user talk page. This is done separately from
571 * AbstractBlock::appliesToRight because there is no right for
572 * editing one's own user talk page and because the user's talk
573 * page needs to be passed into the block object, which is unaware
574 * of the user.
575 *
576 * The ipb_allow_usertalk flag (which corresponds to the property
577 * allowUsertalk) is used on sitewide blocks and partial blocks
578 * that contain a namespace restriction on the user talk namespace,
579 * but do not contain a page restriction on the user's talk page.
580 * For all other (i.e. most) partial blocks, the flag is ignored,
581 * and the user can always edit their user talk page unless there
582 * is a page restriction on their user talk page, in which case
583 * they can never edit it. (Ideally the flag would be stored as
584 * null in these cases, but the database field isn't nullable.)
585 *
586 * This method does not validate that the passed in talk page belongs to the
587 * block target since the target (an IP) might not be the same as the user's
588 * talk page (if they are logged in).
589 *
590 * @since 1.33
591 * @param Title|null $usertalk The user's user talk page. If null,
592 * and if the target is a User, the target's userpage is used
593 * @return bool The user can edit their talk page
594 */
595 public function appliesToUsertalk( Title $usertalk = null ) {
596 if ( !$usertalk ) {
597 if ( $this->target instanceof User ) {
598 $usertalk = $this->target->getTalkPage();
599 } else {
600 throw new InvalidArgumentException(
601 '$usertalk must be provided if block target is not a user/IP'
602 );
603 }
604 }
605
606 if ( $usertalk->getNamespace() !== NS_USER_TALK ) {
607 throw new InvalidArgumentException(
608 '$usertalk must be a user talk page'
609 );
610 }
611
612 if ( !$this->isSitewide() ) {
613 if ( $this->appliesToPage( $usertalk->getArticleID() ) ) {
614 return true;
615 }
616 if ( !$this->appliesToNamespace( NS_USER_TALK ) ) {
617 return false;
618 }
619 }
620
621 // This is a type of block which uses the ipb_allow_usertalk
622 // flag. The flag can still be overridden by global configs.
623 $config = RequestContext::getMain()->getConfig();
624 if ( !$config->get( 'BlockAllowsUTEdit' ) ) {
625 return true;
626 }
627 return !$this->isUsertalkEditAllowed();
628 }
629
630 /**
631 * Checks if a block applies to a particular title
632 *
633 * This check does not consider whether `$this->isUsertalkEditAllowed`
634 * returns false, as the identity of the user making the hypothetical edit
635 * isn't known here (particularly in the case of IP hardblocks, range
636 * blocks, and auto-blocks).
637 *
638 * @param Title $title
639 * @return bool
640 */
641 public function appliesToTitle( Title $title ) {
642 return $this->isSitewide();
643 }
644
645 /**
646 * Checks if a block applies to a particular namespace
647 *
648 * @since 1.33
649 *
650 * @param int $ns
651 * @return bool
652 */
653 public function appliesToNamespace( $ns ) {
654 return $this->isSitewide();
655 }
656
657 /**
658 * Checks if a block applies to a particular page
659 *
660 * This check does not consider whether `$this->isUsertalkEditAllowed`
661 * returns false, as the identity of the user making the hypothetical edit
662 * isn't known here (particularly in the case of IP hardblocks, range
663 * blocks, and auto-blocks).
664 *
665 * @since 1.33
666 *
667 * @param int $pageId
668 * @return bool
669 */
670 public function appliesToPage( $pageId ) {
671 return $this->isSitewide();
672 }
673
674 /**
675 * Check if the block should be tracked with a cookie.
676 *
677 * @since 1.33
678 * @deprecated since 1.34 Use BlockManager::trackBlockWithCookie instead
679 * of calling this directly.
680 * @param bool $isAnon The user is logged out
681 * @return bool The block should be tracked with a cookie
682 */
683 public function shouldTrackWithCookie( $isAnon ) {
684 wfDeprecated( __METHOD__, '1.34' );
685 return false;
686 }
687
688 /**
689 * Check if the block prevents a user from resetting their password
690 *
691 * @since 1.33
692 * @return bool The block blocks password reset
693 */
694 public function appliesToPasswordReset() {
695 return $this->isCreateAccountBlocked();
696 }
697
698 }