Merge "Don't fallback from uk to ru"
[lhc/web/wiklou.git] / includes / user / User.php
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
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 MediaWiki\MediaWikiServices;
24 use MediaWiki\Session\SessionManager;
25 use MediaWiki\Session\Token;
26 use MediaWiki\Auth\AuthManager;
27 use MediaWiki\Auth\AuthenticationResponse;
28 use MediaWiki\Auth\AuthenticationRequest;
29 use Wikimedia\ScopedCallback;
30
31 /**
32 * String Some punctuation to prevent editing from broken text-mangling proxies.
33 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
34 * @ingroup Constants
35 */
36 define( 'EDIT_TOKEN_SUFFIX', Token::SUFFIX );
37
38 /**
39 * The User object encapsulates all of the user-specific settings (user_id,
40 * name, rights, email address, options, last login time). Client
41 * classes use the getXXX() functions to access these fields. These functions
42 * do all the work of determining whether the user is logged in,
43 * whether the requested option can be satisfied from cookies or
44 * whether a database query is needed. Most of the settings needed
45 * for rendering normal pages are set in the cookie to minimize use
46 * of the database.
47 */
48 class User implements IDBAccessObject {
49 /**
50 * @const int Number of characters in user_token field.
51 */
52 const TOKEN_LENGTH = 32;
53
54 /**
55 * @const string An invalid value for user_token
56 */
57 const INVALID_TOKEN = '*** INVALID ***';
58
59 /**
60 * Global constant made accessible as class constants so that autoloader
61 * magic can be used.
62 * @deprecated since 1.27, use \MediaWiki\Session\Token::SUFFIX
63 */
64 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
65
66 /**
67 * @const int Serialized record version.
68 */
69 const VERSION = 10;
70
71 /**
72 * Exclude user options that are set to their default value.
73 * @since 1.25
74 */
75 const GETOPTIONS_EXCLUDE_DEFAULTS = 1;
76
77 /**
78 * @since 1.27
79 */
80 const CHECK_USER_RIGHTS = true;
81
82 /**
83 * @since 1.27
84 */
85 const IGNORE_USER_RIGHTS = false;
86
87 /**
88 * Array of Strings List of member variables which are saved to the
89 * shared cache (memcached). Any operation which changes the
90 * corresponding database fields must call a cache-clearing function.
91 * @showinitializer
92 */
93 protected static $mCacheVars = [
94 // user table
95 'mId',
96 'mName',
97 'mRealName',
98 'mEmail',
99 'mTouched',
100 'mToken',
101 'mEmailAuthenticated',
102 'mEmailToken',
103 'mEmailTokenExpires',
104 'mRegistration',
105 'mEditCount',
106 // user_groups table
107 'mGroups',
108 // user_properties table
109 'mOptionOverrides',
110 ];
111
112 /**
113 * Array of Strings Core rights.
114 * Each of these should have a corresponding message of the form
115 * "right-$right".
116 * @showinitializer
117 */
118 protected static $mCoreRights = [
119 'apihighlimits',
120 'applychangetags',
121 'autoconfirmed',
122 'autocreateaccount',
123 'autopatrol',
124 'bigdelete',
125 'block',
126 'blockemail',
127 'bot',
128 'browsearchive',
129 'changetags',
130 'createaccount',
131 'createpage',
132 'createtalk',
133 'delete',
134 'deletechangetags',
135 'deletedhistory',
136 'deletedtext',
137 'deletelogentry',
138 'deleterevision',
139 'edit',
140 'editcontentmodel',
141 'editinterface',
142 'editprotected',
143 'editmyoptions',
144 'editmyprivateinfo',
145 'editmyusercss',
146 'editmyuserjs',
147 'editmywatchlist',
148 'editsemiprotected',
149 'editusercssjs', # deprecated
150 'editusercss',
151 'edituserjs',
152 'hideuser',
153 'import',
154 'importupload',
155 'ipblock-exempt',
156 'managechangetags',
157 'markbotedits',
158 'mergehistory',
159 'minoredit',
160 'move',
161 'movefile',
162 'move-categorypages',
163 'move-rootuserpages',
164 'move-subpages',
165 'nominornewtalk',
166 'noratelimit',
167 'override-export-depth',
168 'pagelang',
169 'patrol',
170 'patrolmarks',
171 'protect',
172 'purge',
173 'read',
174 'reupload',
175 'reupload-own',
176 'reupload-shared',
177 'rollback',
178 'sendemail',
179 'siteadmin',
180 'suppressionlog',
181 'suppressredirect',
182 'suppressrevision',
183 'unblockself',
184 'undelete',
185 'unwatchedpages',
186 'upload',
187 'upload_by_url',
188 'userrights',
189 'userrights-interwiki',
190 'viewmyprivateinfo',
191 'viewmywatchlist',
192 'viewsuppressed',
193 'writeapi',
194 ];
195
196 /**
197 * String Cached results of getAllRights()
198 */
199 protected static $mAllRights = false;
200
201 /** Cache variables */
202 // @{
203 /** @var int */
204 public $mId;
205 /** @var string */
206 public $mName;
207 /** @var string */
208 public $mRealName;
209
210 /** @var string */
211 public $mEmail;
212 /** @var string TS_MW timestamp from the DB */
213 public $mTouched;
214 /** @var string TS_MW timestamp from cache */
215 protected $mQuickTouched;
216 /** @var string */
217 protected $mToken;
218 /** @var string */
219 public $mEmailAuthenticated;
220 /** @var string */
221 protected $mEmailToken;
222 /** @var string */
223 protected $mEmailTokenExpires;
224 /** @var string */
225 protected $mRegistration;
226 /** @var int */
227 protected $mEditCount;
228 /** @var array */
229 public $mGroups;
230 /** @var array */
231 protected $mOptionOverrides;
232 // @}
233
234 /**
235 * Bool Whether the cache variables have been loaded.
236 */
237 // @{
238 public $mOptionsLoaded;
239
240 /**
241 * Array with already loaded items or true if all items have been loaded.
242 */
243 protected $mLoadedItems = [];
244 // @}
245
246 /**
247 * String Initialization data source if mLoadedItems!==true. May be one of:
248 * - 'defaults' anonymous user initialised from class defaults
249 * - 'name' initialise from mName
250 * - 'id' initialise from mId
251 * - 'session' log in from session if possible
252 *
253 * Use the User::newFrom*() family of functions to set this.
254 */
255 public $mFrom;
256
257 /**
258 * Lazy-initialized variables, invalidated with clearInstanceCache
259 */
260 protected $mNewtalk;
261 /** @var string */
262 protected $mDatePreference;
263 /** @var string */
264 public $mBlockedby;
265 /** @var string */
266 protected $mHash;
267 /** @var array */
268 public $mRights;
269 /** @var string */
270 protected $mBlockreason;
271 /** @var array */
272 protected $mEffectiveGroups;
273 /** @var array */
274 protected $mImplicitGroups;
275 /** @var array */
276 protected $mFormerGroups;
277 /** @var Block */
278 protected $mGlobalBlock;
279 /** @var bool */
280 protected $mLocked;
281 /** @var bool */
282 public $mHideName;
283 /** @var array */
284 public $mOptions;
285
286 /**
287 * @var WebRequest
288 */
289 private $mRequest;
290
291 /** @var Block */
292 public $mBlock;
293
294 /** @var bool */
295 protected $mAllowUsertalk;
296
297 /** @var Block */
298 private $mBlockedFromCreateAccount = false;
299
300 /** @var integer User::READ_* constant bitfield used to load data */
301 protected $queryFlagsUsed = self::READ_NORMAL;
302
303 /** @var string Indicates type of block (used for eventlogging)
304 * Permitted values: 'cookie-block', 'proxy-block', 'openproxy-block', 'xff-block'
305 */
306 public $blockTrigger = false;
307
308 public static $idCacheByName = [];
309
310 /**
311 * Lightweight constructor for an anonymous user.
312 * Use the User::newFrom* factory functions for other kinds of users.
313 *
314 * @see newFromName()
315 * @see newFromId()
316 * @see newFromConfirmationCode()
317 * @see newFromSession()
318 * @see newFromRow()
319 */
320 public function __construct() {
321 $this->clearInstanceCache( 'defaults' );
322 }
323
324 /**
325 * @return string
326 */
327 public function __toString() {
328 return (string)$this->getName();
329 }
330
331 /**
332 * Test if it's safe to load this User object.
333 *
334 * You should typically check this before using $wgUser or
335 * RequestContext::getUser in a method that might be called before the
336 * system has been fully initialized. If the object is unsafe, you should
337 * use an anonymous user:
338 * \code
339 * $user = $wgUser->isSafeToLoad() ? $wgUser : new User;
340 * \endcode
341 *
342 * @since 1.27
343 * @return bool
344 */
345 public function isSafeToLoad() {
346 global $wgFullyInitialised;
347
348 // The user is safe to load if:
349 // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
350 // * mLoadedItems === true (already loaded)
351 // * mFrom !== 'session' (sessions not involved at all)
352
353 return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
354 $this->mLoadedItems === true || $this->mFrom !== 'session';
355 }
356
357 /**
358 * Load the user table data for this object from the source given by mFrom.
359 *
360 * @param integer $flags User::READ_* constant bitfield
361 */
362 public function load( $flags = self::READ_NORMAL ) {
363 global $wgFullyInitialised;
364
365 if ( $this->mLoadedItems === true ) {
366 return;
367 }
368
369 // Set it now to avoid infinite recursion in accessors
370 $oldLoadedItems = $this->mLoadedItems;
371 $this->mLoadedItems = true;
372 $this->queryFlagsUsed = $flags;
373
374 // If this is called too early, things are likely to break.
375 if ( !$wgFullyInitialised && $this->mFrom === 'session' ) {
376 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
377 ->warning( 'User::loadFromSession called before the end of Setup.php', [
378 'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
379 ] );
380 $this->loadDefaults();
381 $this->mLoadedItems = $oldLoadedItems;
382 return;
383 }
384
385 switch ( $this->mFrom ) {
386 case 'defaults':
387 $this->loadDefaults();
388 break;
389 case 'name':
390 // Make sure this thread sees its own changes
391 if ( wfGetLB()->hasOrMadeRecentMasterChanges() ) {
392 $flags |= self::READ_LATEST;
393 $this->queryFlagsUsed = $flags;
394 }
395
396 $this->mId = self::idFromName( $this->mName, $flags );
397 if ( !$this->mId ) {
398 // Nonexistent user placeholder object
399 $this->loadDefaults( $this->mName );
400 } else {
401 $this->loadFromId( $flags );
402 }
403 break;
404 case 'id':
405 $this->loadFromId( $flags );
406 break;
407 case 'session':
408 if ( !$this->loadFromSession() ) {
409 // Loading from session failed. Load defaults.
410 $this->loadDefaults();
411 }
412 Hooks::run( 'UserLoadAfterLoadFromSession', [ $this ] );
413 break;
414 default:
415 throw new UnexpectedValueException(
416 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
417 }
418 }
419
420 /**
421 * Load user table data, given mId has already been set.
422 * @param integer $flags User::READ_* constant bitfield
423 * @return bool False if the ID does not exist, true otherwise
424 */
425 public function loadFromId( $flags = self::READ_NORMAL ) {
426 if ( $this->mId == 0 ) {
427 // Anonymous users are not in the database (don't need cache)
428 $this->loadDefaults();
429 return false;
430 }
431
432 // Try cache (unless this needs data from the master DB).
433 // NOTE: if this thread called saveSettings(), the cache was cleared.
434 $latest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
435 if ( $latest ) {
436 if ( !$this->loadFromDatabase( $flags ) ) {
437 // Can't load from ID
438 return false;
439 }
440 } else {
441 $this->loadFromCache();
442 }
443
444 $this->mLoadedItems = true;
445 $this->queryFlagsUsed = $flags;
446
447 return true;
448 }
449
450 /**
451 * @since 1.27
452 * @param string $wikiId
453 * @param integer $userId
454 */
455 public static function purge( $wikiId, $userId ) {
456 $cache = ObjectCache::getMainWANInstance();
457 $key = $cache->makeGlobalKey( 'user', 'id', $wikiId, $userId );
458 $cache->delete( $key );
459 }
460
461 /**
462 * @since 1.27
463 * @param WANObjectCache $cache
464 * @return string
465 */
466 protected function getCacheKey( WANObjectCache $cache ) {
467 return $cache->makeGlobalKey( 'user', 'id', wfWikiID(), $this->mId );
468 }
469
470 /**
471 * Load user data from shared cache, given mId has already been set.
472 *
473 * @return bool True
474 * @since 1.25
475 */
476 protected function loadFromCache() {
477 $cache = ObjectCache::getMainWANInstance();
478 $data = $cache->getWithSetCallback(
479 $this->getCacheKey( $cache ),
480 $cache::TTL_HOUR,
481 function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) {
482 $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
483 wfDebug( "User: cache miss for user {$this->mId}\n" );
484
485 $this->loadFromDatabase( self::READ_NORMAL );
486 $this->loadGroups();
487 $this->loadOptions();
488
489 $data = [];
490 foreach ( self::$mCacheVars as $name ) {
491 $data[$name] = $this->$name;
492 }
493
494 $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX, $this->mTouched ), $ttl );
495
496 return $data;
497
498 },
499 [ 'pcTTL' => $cache::TTL_PROC_LONG, 'version' => self::VERSION ]
500 );
501
502 // Restore from cache
503 foreach ( self::$mCacheVars as $name ) {
504 $this->$name = $data[$name];
505 }
506
507 return true;
508 }
509
510 /** @name newFrom*() static factory methods */
511 // @{
512
513 /**
514 * Static factory method for creation from username.
515 *
516 * This is slightly less efficient than newFromId(), so use newFromId() if
517 * you have both an ID and a name handy.
518 *
519 * @param string $name Username, validated by Title::newFromText()
520 * @param string|bool $validate Validate username. Takes the same parameters as
521 * User::getCanonicalName(), except that true is accepted as an alias
522 * for 'valid', for BC.
523 *
524 * @return User|bool User object, or false if the username is invalid
525 * (e.g. if it contains illegal characters or is an IP address). If the
526 * username is not present in the database, the result will be a user object
527 * with a name, zero user ID and default settings.
528 */
529 public static function newFromName( $name, $validate = 'valid' ) {
530 if ( $validate === true ) {
531 $validate = 'valid';
532 }
533 $name = self::getCanonicalName( $name, $validate );
534 if ( $name === false ) {
535 return false;
536 } else {
537 // Create unloaded user object
538 $u = new User;
539 $u->mName = $name;
540 $u->mFrom = 'name';
541 $u->setItemLoaded( 'name' );
542 return $u;
543 }
544 }
545
546 /**
547 * Static factory method for creation from a given user ID.
548 *
549 * @param int $id Valid user ID
550 * @return User The corresponding User object
551 */
552 public static function newFromId( $id ) {
553 $u = new User;
554 $u->mId = $id;
555 $u->mFrom = 'id';
556 $u->setItemLoaded( 'id' );
557 return $u;
558 }
559
560 /**
561 * Factory method to fetch whichever user has a given email confirmation code.
562 * This code is generated when an account is created or its e-mail address
563 * has changed.
564 *
565 * If the code is invalid or has expired, returns NULL.
566 *
567 * @param string $code Confirmation code
568 * @param int $flags User::READ_* bitfield
569 * @return User|null
570 */
571 public static function newFromConfirmationCode( $code, $flags = 0 ) {
572 $db = ( $flags & self::READ_LATEST ) == self::READ_LATEST
573 ? wfGetDB( DB_MASTER )
574 : wfGetDB( DB_REPLICA );
575
576 $id = $db->selectField(
577 'user',
578 'user_id',
579 [
580 'user_email_token' => md5( $code ),
581 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
582 ]
583 );
584
585 return $id ? User::newFromId( $id ) : null;
586 }
587
588 /**
589 * Create a new user object using data from session. If the login
590 * credentials are invalid, the result is an anonymous user.
591 *
592 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
593 * @return User
594 */
595 public static function newFromSession( WebRequest $request = null ) {
596 $user = new User;
597 $user->mFrom = 'session';
598 $user->mRequest = $request;
599 return $user;
600 }
601
602 /**
603 * Create a new user object from a user row.
604 * The row should have the following fields from the user table in it:
605 * - either user_name or user_id to load further data if needed (or both)
606 * - user_real_name
607 * - all other fields (email, etc.)
608 * It is useless to provide the remaining fields if either user_id,
609 * user_name and user_real_name are not provided because the whole row
610 * will be loaded once more from the database when accessing them.
611 *
612 * @param stdClass $row A row from the user table
613 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
614 * @return User
615 */
616 public static function newFromRow( $row, $data = null ) {
617 $user = new User;
618 $user->loadFromRow( $row, $data );
619 return $user;
620 }
621
622 /**
623 * Static factory method for creation of a "system" user from username.
624 *
625 * A "system" user is an account that's used to attribute logged actions
626 * taken by MediaWiki itself, as opposed to a bot or human user. Examples
627 * might include the 'Maintenance script' or 'Conversion script' accounts
628 * used by various scripts in the maintenance/ directory or accounts such
629 * as 'MediaWiki message delivery' used by the MassMessage extension.
630 *
631 * This can optionally create the user if it doesn't exist, and "steal" the
632 * account if it does exist.
633 *
634 * "Stealing" an existing user is intended to make it impossible for normal
635 * authentication processes to use the account, effectively disabling the
636 * account for normal use:
637 * - Email is invalidated, to prevent account recovery by emailing a
638 * temporary password and to disassociate the account from the existing
639 * human.
640 * - The token is set to a magic invalid value, to kill existing sessions
641 * and to prevent $this->setToken() calls from resetting the token to a
642 * valid value.
643 * - SessionManager is instructed to prevent new sessions for the user, to
644 * do things like deauthorizing OAuth consumers.
645 * - AuthManager is instructed to revoke access, to invalidate or remove
646 * passwords and other credentials.
647 *
648 * @param string $name Username
649 * @param array $options Options are:
650 * - validate: As for User::getCanonicalName(), default 'valid'
651 * - create: Whether to create the user if it doesn't already exist, default true
652 * - steal: Whether to "disable" the account for normal use if it already
653 * exists, default false
654 * @return User|null
655 * @since 1.27
656 */
657 public static function newSystemUser( $name, $options = [] ) {
658 $options += [
659 'validate' => 'valid',
660 'create' => true,
661 'steal' => false,
662 ];
663
664 $name = self::getCanonicalName( $name, $options['validate'] );
665 if ( $name === false ) {
666 return null;
667 }
668
669 $fields = self::selectFields();
670
671 $dbw = wfGetDB( DB_MASTER );
672 $row = $dbw->selectRow(
673 'user',
674 $fields,
675 [ 'user_name' => $name ],
676 __METHOD__
677 );
678 if ( !$row ) {
679 // No user. Create it?
680 return $options['create'] ? self::createNew( $name ) : null;
681 }
682 $user = self::newFromRow( $row );
683
684 // A user is considered to exist as a non-system user if it can
685 // authenticate, or has an email set, or has a non-invalid token.
686 if ( $user->mEmail || $user->mToken !== self::INVALID_TOKEN ||
687 AuthManager::singleton()->userCanAuthenticate( $name )
688 ) {
689 // User exists. Steal it?
690 if ( !$options['steal'] ) {
691 return null;
692 }
693
694 AuthManager::singleton()->revokeAccessForUser( $name );
695
696 $user->invalidateEmail();
697 $user->mToken = self::INVALID_TOKEN;
698 $user->saveSettings();
699 SessionManager::singleton()->preventSessionsForUser( $user->getName() );
700 }
701
702 return $user;
703 }
704
705 // @}
706
707 /**
708 * Get the username corresponding to a given user ID
709 * @param int $id User ID
710 * @return string|bool The corresponding username
711 */
712 public static function whoIs( $id ) {
713 return UserCache::singleton()->getProp( $id, 'name' );
714 }
715
716 /**
717 * Get the real name of a user given their user ID
718 *
719 * @param int $id User ID
720 * @return string|bool The corresponding user's real name
721 */
722 public static function whoIsReal( $id ) {
723 return UserCache::singleton()->getProp( $id, 'real_name' );
724 }
725
726 /**
727 * Get database id given a user name
728 * @param string $name Username
729 * @param integer $flags User::READ_* constant bitfield
730 * @return int|null The corresponding user's ID, or null if user is nonexistent
731 */
732 public static function idFromName( $name, $flags = self::READ_NORMAL ) {
733 $nt = Title::makeTitleSafe( NS_USER, $name );
734 if ( is_null( $nt ) ) {
735 // Illegal name
736 return null;
737 }
738
739 if ( !( $flags & self::READ_LATEST ) && isset( self::$idCacheByName[$name] ) ) {
740 return self::$idCacheByName[$name];
741 }
742
743 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
744 $db = wfGetDB( $index );
745
746 $s = $db->selectRow(
747 'user',
748 [ 'user_id' ],
749 [ 'user_name' => $nt->getText() ],
750 __METHOD__,
751 $options
752 );
753
754 if ( $s === false ) {
755 $result = null;
756 } else {
757 $result = $s->user_id;
758 }
759
760 self::$idCacheByName[$name] = $result;
761
762 if ( count( self::$idCacheByName ) > 1000 ) {
763 self::$idCacheByName = [];
764 }
765
766 return $result;
767 }
768
769 /**
770 * Reset the cache used in idFromName(). For use in tests.
771 */
772 public static function resetIdByNameCache() {
773 self::$idCacheByName = [];
774 }
775
776 /**
777 * Does the string match an anonymous IP address?
778 *
779 * This function exists for username validation, in order to reject
780 * usernames which are similar in form to IP addresses. Strings such
781 * as 300.300.300.300 will return true because it looks like an IP
782 * address, despite not being strictly valid.
783 *
784 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
785 * address because the usemod software would "cloak" anonymous IP
786 * addresses like this, if we allowed accounts like this to be created
787 * new users could get the old edits of these anonymous users.
788 *
789 * @param string $name Name to match
790 * @return bool
791 */
792 public static function isIP( $name ) {
793 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
794 || IP::isIPv6( $name );
795 }
796
797 /**
798 * Is the input a valid username?
799 *
800 * Checks if the input is a valid username, we don't want an empty string,
801 * an IP address, anything that contains slashes (would mess up subpages),
802 * is longer than the maximum allowed username size or doesn't begin with
803 * a capital letter.
804 *
805 * @param string $name Name to match
806 * @return bool
807 */
808 public static function isValidUserName( $name ) {
809 global $wgContLang, $wgMaxNameChars;
810
811 if ( $name == ''
812 || User::isIP( $name )
813 || strpos( $name, '/' ) !== false
814 || strlen( $name ) > $wgMaxNameChars
815 || $name != $wgContLang->ucfirst( $name )
816 ) {
817 return false;
818 }
819
820 // Ensure that the name can't be misresolved as a different title,
821 // such as with extra namespace keys at the start.
822 $parsed = Title::newFromText( $name );
823 if ( is_null( $parsed )
824 || $parsed->getNamespace()
825 || strcmp( $name, $parsed->getPrefixedText() ) ) {
826 return false;
827 }
828
829 // Check an additional blacklist of troublemaker characters.
830 // Should these be merged into the title char list?
831 $unicodeBlacklist = '/[' .
832 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
833 '\x{00a0}' . # non-breaking space
834 '\x{2000}-\x{200f}' . # various whitespace
835 '\x{2028}-\x{202f}' . # breaks and control chars
836 '\x{3000}' . # ideographic space
837 '\x{e000}-\x{f8ff}' . # private use
838 ']/u';
839 if ( preg_match( $unicodeBlacklist, $name ) ) {
840 return false;
841 }
842
843 return true;
844 }
845
846 /**
847 * Usernames which fail to pass this function will be blocked
848 * from user login and new account registrations, but may be used
849 * internally by batch processes.
850 *
851 * If an account already exists in this form, login will be blocked
852 * by a failure to pass this function.
853 *
854 * @param string $name Name to match
855 * @return bool
856 */
857 public static function isUsableName( $name ) {
858 global $wgReservedUsernames;
859 // Must be a valid username, obviously ;)
860 if ( !self::isValidUserName( $name ) ) {
861 return false;
862 }
863
864 static $reservedUsernames = false;
865 if ( !$reservedUsernames ) {
866 $reservedUsernames = $wgReservedUsernames;
867 Hooks::run( 'UserGetReservedNames', [ &$reservedUsernames ] );
868 }
869
870 // Certain names may be reserved for batch processes.
871 foreach ( $reservedUsernames as $reserved ) {
872 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
873 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
874 }
875 if ( $reserved == $name ) {
876 return false;
877 }
878 }
879 return true;
880 }
881
882 /**
883 * Return the users who are members of the given group(s). In case of multiple groups,
884 * users who are members of at least one of them are returned.
885 *
886 * @param string|array $groups A single group name or an array of group names
887 * @param int $limit Max number of users to return. The actual limit will never exceed 5000
888 * records; larger values are ignored.
889 * @param int $after ID the user to start after
890 * @return UserArrayFromResult
891 */
892 public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
893 if ( $groups === [] ) {
894 return UserArrayFromResult::newFromIDs( [] );
895 }
896
897 $groups = array_unique( (array)$groups );
898 $limit = min( 5000, $limit );
899
900 $conds = [ 'ug_group' => $groups ];
901 if ( $after !== null ) {
902 $conds[] = 'ug_user > ' . (int)$after;
903 }
904
905 $dbr = wfGetDB( DB_REPLICA );
906 $ids = $dbr->selectFieldValues(
907 'user_groups',
908 'ug_user',
909 $conds,
910 __METHOD__,
911 [
912 'DISTINCT' => true,
913 'ORDER BY' => 'ug_user',
914 'LIMIT' => $limit,
915 ]
916 ) ?: [];
917 return UserArray::newFromIDs( $ids );
918 }
919
920 /**
921 * Usernames which fail to pass this function will be blocked
922 * from new account registrations, but may be used internally
923 * either by batch processes or by user accounts which have
924 * already been created.
925 *
926 * Additional blacklisting may be added here rather than in
927 * isValidUserName() to avoid disrupting existing accounts.
928 *
929 * @param string $name String to match
930 * @return bool
931 */
932 public static function isCreatableName( $name ) {
933 global $wgInvalidUsernameCharacters;
934
935 // Ensure that the username isn't longer than 235 bytes, so that
936 // (at least for the builtin skins) user javascript and css files
937 // will work. (bug 23080)
938 if ( strlen( $name ) > 235 ) {
939 wfDebugLog( 'username', __METHOD__ .
940 ": '$name' invalid due to length" );
941 return false;
942 }
943
944 // Preg yells if you try to give it an empty string
945 if ( $wgInvalidUsernameCharacters !== '' ) {
946 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
947 wfDebugLog( 'username', __METHOD__ .
948 ": '$name' invalid due to wgInvalidUsernameCharacters" );
949 return false;
950 }
951 }
952
953 return self::isUsableName( $name );
954 }
955
956 /**
957 * Is the input a valid password for this user?
958 *
959 * @param string $password Desired password
960 * @return bool
961 */
962 public function isValidPassword( $password ) {
963 // simple boolean wrapper for getPasswordValidity
964 return $this->getPasswordValidity( $password ) === true;
965 }
966
967 /**
968 * Given unvalidated password input, return error message on failure.
969 *
970 * @param string $password Desired password
971 * @return bool|string|array True on success, string or array of error message on failure
972 */
973 public function getPasswordValidity( $password ) {
974 $result = $this->checkPasswordValidity( $password );
975 if ( $result->isGood() ) {
976 return true;
977 } else {
978 $messages = [];
979 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
980 $messages[] = $error['message'];
981 }
982 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
983 $messages[] = $warning['message'];
984 }
985 if ( count( $messages ) === 1 ) {
986 return $messages[0];
987 }
988 return $messages;
989 }
990 }
991
992 /**
993 * Check if this is a valid password for this user
994 *
995 * Create a Status object based on the password's validity.
996 * The Status should be set to fatal if the user should not
997 * be allowed to log in, and should have any errors that
998 * would block changing the password.
999 *
1000 * If the return value of this is not OK, the password
1001 * should not be checked. If the return value is not Good,
1002 * the password can be checked, but the user should not be
1003 * able to set their password to this.
1004 *
1005 * @param string $password Desired password
1006 * @param string $purpose one of 'login', 'create', 'reset'
1007 * @return Status
1008 * @since 1.23
1009 */
1010 public function checkPasswordValidity( $password, $purpose = 'login' ) {
1011 global $wgPasswordPolicy;
1012
1013 $upp = new UserPasswordPolicy(
1014 $wgPasswordPolicy['policies'],
1015 $wgPasswordPolicy['checks']
1016 );
1017
1018 $status = Status::newGood();
1019 $result = false; // init $result to false for the internal checks
1020
1021 if ( !Hooks::run( 'isValidPassword', [ $password, &$result, $this ] ) ) {
1022 $status->error( $result );
1023 return $status;
1024 }
1025
1026 if ( $result === false ) {
1027 $status->merge( $upp->checkUserPassword( $this, $password, $purpose ) );
1028 return $status;
1029 } elseif ( $result === true ) {
1030 return $status;
1031 } else {
1032 $status->error( $result );
1033 return $status; // the isValidPassword hook set a string $result and returned true
1034 }
1035 }
1036
1037 /**
1038 * Given unvalidated user input, return a canonical username, or false if
1039 * the username is invalid.
1040 * @param string $name User input
1041 * @param string|bool $validate Type of validation to use:
1042 * - false No validation
1043 * - 'valid' Valid for batch processes
1044 * - 'usable' Valid for batch processes and login
1045 * - 'creatable' Valid for batch processes, login and account creation
1046 *
1047 * @throws InvalidArgumentException
1048 * @return bool|string
1049 */
1050 public static function getCanonicalName( $name, $validate = 'valid' ) {
1051 // Force usernames to capital
1052 global $wgContLang;
1053 $name = $wgContLang->ucfirst( $name );
1054
1055 # Reject names containing '#'; these will be cleaned up
1056 # with title normalisation, but then it's too late to
1057 # check elsewhere
1058 if ( strpos( $name, '#' ) !== false ) {
1059 return false;
1060 }
1061
1062 // Clean up name according to title rules,
1063 // but only when validation is requested (bug 12654)
1064 $t = ( $validate !== false ) ?
1065 Title::newFromText( $name, NS_USER ) : Title::makeTitle( NS_USER, $name );
1066 // Check for invalid titles
1067 if ( is_null( $t ) || $t->getNamespace() !== NS_USER || $t->isExternal() ) {
1068 return false;
1069 }
1070
1071 // Reject various classes of invalid names
1072 $name = AuthManager::callLegacyAuthPlugin(
1073 'getCanonicalName', [ $t->getText() ], $t->getText()
1074 );
1075
1076 switch ( $validate ) {
1077 case false:
1078 break;
1079 case 'valid':
1080 if ( !User::isValidUserName( $name ) ) {
1081 $name = false;
1082 }
1083 break;
1084 case 'usable':
1085 if ( !User::isUsableName( $name ) ) {
1086 $name = false;
1087 }
1088 break;
1089 case 'creatable':
1090 if ( !User::isCreatableName( $name ) ) {
1091 $name = false;
1092 }
1093 break;
1094 default:
1095 throw new InvalidArgumentException(
1096 'Invalid parameter value for $validate in ' . __METHOD__ );
1097 }
1098 return $name;
1099 }
1100
1101 /**
1102 * Count the number of edits of a user
1103 *
1104 * @param int $uid User ID to check
1105 * @return int The user's edit count
1106 *
1107 * @deprecated since 1.21 in favour of User::getEditCount
1108 */
1109 public static function edits( $uid ) {
1110 wfDeprecated( __METHOD__, '1.21' );
1111 $user = self::newFromId( $uid );
1112 return $user->getEditCount();
1113 }
1114
1115 /**
1116 * Return a random password.
1117 *
1118 * @deprecated since 1.27, use PasswordFactory::generateRandomPasswordString()
1119 * @return string New random password
1120 */
1121 public static function randomPassword() {
1122 global $wgMinimalPasswordLength;
1123 return PasswordFactory::generateRandomPasswordString( $wgMinimalPasswordLength );
1124 }
1125
1126 /**
1127 * Set cached properties to default.
1128 *
1129 * @note This no longer clears uncached lazy-initialised properties;
1130 * the constructor does that instead.
1131 *
1132 * @param string|bool $name
1133 */
1134 public function loadDefaults( $name = false ) {
1135 $this->mId = 0;
1136 $this->mName = $name;
1137 $this->mRealName = '';
1138 $this->mEmail = '';
1139 $this->mOptionOverrides = null;
1140 $this->mOptionsLoaded = false;
1141
1142 $loggedOut = $this->mRequest && !defined( 'MW_NO_SESSION' )
1143 ? $this->mRequest->getSession()->getLoggedOutTimestamp() : 0;
1144 if ( $loggedOut !== 0 ) {
1145 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1146 } else {
1147 $this->mTouched = '1'; # Allow any pages to be cached
1148 }
1149
1150 $this->mToken = null; // Don't run cryptographic functions till we need a token
1151 $this->mEmailAuthenticated = null;
1152 $this->mEmailToken = '';
1153 $this->mEmailTokenExpires = null;
1154 $this->mRegistration = wfTimestamp( TS_MW );
1155 $this->mGroups = [];
1156
1157 Hooks::run( 'UserLoadDefaults', [ $this, $name ] );
1158 }
1159
1160 /**
1161 * Return whether an item has been loaded.
1162 *
1163 * @param string $item Item to check. Current possibilities:
1164 * - id
1165 * - name
1166 * - realname
1167 * @param string $all 'all' to check if the whole object has been loaded
1168 * or any other string to check if only the item is available (e.g.
1169 * for optimisation)
1170 * @return bool
1171 */
1172 public function isItemLoaded( $item, $all = 'all' ) {
1173 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1174 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1175 }
1176
1177 /**
1178 * Set that an item has been loaded
1179 *
1180 * @param string $item
1181 */
1182 protected function setItemLoaded( $item ) {
1183 if ( is_array( $this->mLoadedItems ) ) {
1184 $this->mLoadedItems[$item] = true;
1185 }
1186 }
1187
1188 /**
1189 * Load user data from the session.
1190 *
1191 * @return bool True if the user is logged in, false otherwise.
1192 */
1193 private function loadFromSession() {
1194 // Deprecated hook
1195 $result = null;
1196 Hooks::run( 'UserLoadFromSession', [ $this, &$result ], '1.27' );
1197 if ( $result !== null ) {
1198 return $result;
1199 }
1200
1201 // MediaWiki\Session\Session already did the necessary authentication of the user
1202 // returned here, so just use it if applicable.
1203 $session = $this->getRequest()->getSession();
1204 $user = $session->getUser();
1205 if ( $user->isLoggedIn() ) {
1206 $this->loadFromUserObject( $user );
1207
1208 // If this user is autoblocked, set a cookie to track the Block. This has to be done on
1209 // every session load, because an autoblocked editor might not edit again from the same
1210 // IP address after being blocked.
1211 $config = RequestContext::getMain()->getConfig();
1212 if ( $config->get( 'CookieSetOnAutoblock' ) === true ) {
1213 $block = $this->getBlock();
1214 $shouldSetCookie = $this->getRequest()->getCookie( 'BlockID' ) === null
1215 && $block
1216 && $block->getType() === Block::TYPE_USER
1217 && $block->isAutoblocking();
1218 if ( $shouldSetCookie ) {
1219 wfDebug( __METHOD__ . ': User is autoblocked, setting cookie to track' );
1220 $block->setCookie( $this->getRequest()->response() );
1221 }
1222 }
1223
1224 // Other code expects these to be set in the session, so set them.
1225 $session->set( 'wsUserID', $this->getId() );
1226 $session->set( 'wsUserName', $this->getName() );
1227 $session->set( 'wsToken', $this->getToken() );
1228 return true;
1229 }
1230 return false;
1231 }
1232
1233 /**
1234 * Load user and user_group data from the database.
1235 * $this->mId must be set, this is how the user is identified.
1236 *
1237 * @param integer $flags User::READ_* constant bitfield
1238 * @return bool True if the user exists, false if the user is anonymous
1239 */
1240 public function loadFromDatabase( $flags = self::READ_LATEST ) {
1241 // Paranoia
1242 $this->mId = intval( $this->mId );
1243
1244 if ( !$this->mId ) {
1245 // Anonymous users are not in the database
1246 $this->loadDefaults();
1247 return false;
1248 }
1249
1250 list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
1251 $db = wfGetDB( $index );
1252
1253 $s = $db->selectRow(
1254 'user',
1255 self::selectFields(),
1256 [ 'user_id' => $this->mId ],
1257 __METHOD__,
1258 $options
1259 );
1260
1261 $this->queryFlagsUsed = $flags;
1262 Hooks::run( 'UserLoadFromDatabase', [ $this, &$s ] );
1263
1264 if ( $s !== false ) {
1265 // Initialise user table data
1266 $this->loadFromRow( $s );
1267 $this->mGroups = null; // deferred
1268 $this->getEditCount(); // revalidation for nulls
1269 return true;
1270 } else {
1271 // Invalid user_id
1272 $this->mId = 0;
1273 $this->loadDefaults();
1274 return false;
1275 }
1276 }
1277
1278 /**
1279 * Initialize this object from a row from the user table.
1280 *
1281 * @param stdClass $row Row from the user table to load.
1282 * @param array $data Further user data to load into the object
1283 *
1284 * user_groups Array with groups out of the user_groups table
1285 * user_properties Array with properties out of the user_properties table
1286 */
1287 protected function loadFromRow( $row, $data = null ) {
1288 $all = true;
1289
1290 $this->mGroups = null; // deferred
1291
1292 if ( isset( $row->user_name ) ) {
1293 $this->mName = $row->user_name;
1294 $this->mFrom = 'name';
1295 $this->setItemLoaded( 'name' );
1296 } else {
1297 $all = false;
1298 }
1299
1300 if ( isset( $row->user_real_name ) ) {
1301 $this->mRealName = $row->user_real_name;
1302 $this->setItemLoaded( 'realname' );
1303 } else {
1304 $all = false;
1305 }
1306
1307 if ( isset( $row->user_id ) ) {
1308 $this->mId = intval( $row->user_id );
1309 $this->mFrom = 'id';
1310 $this->setItemLoaded( 'id' );
1311 } else {
1312 $all = false;
1313 }
1314
1315 if ( isset( $row->user_id ) && isset( $row->user_name ) ) {
1316 self::$idCacheByName[$row->user_name] = $row->user_id;
1317 }
1318
1319 if ( isset( $row->user_editcount ) ) {
1320 $this->mEditCount = $row->user_editcount;
1321 } else {
1322 $all = false;
1323 }
1324
1325 if ( isset( $row->user_touched ) ) {
1326 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1327 } else {
1328 $all = false;
1329 }
1330
1331 if ( isset( $row->user_token ) ) {
1332 // The definition for the column is binary(32), so trim the NULs
1333 // that appends. The previous definition was char(32), so trim
1334 // spaces too.
1335 $this->mToken = rtrim( $row->user_token, " \0" );
1336 if ( $this->mToken === '' ) {
1337 $this->mToken = null;
1338 }
1339 } else {
1340 $all = false;
1341 }
1342
1343 if ( isset( $row->user_email ) ) {
1344 $this->mEmail = $row->user_email;
1345 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1346 $this->mEmailToken = $row->user_email_token;
1347 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1348 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1349 } else {
1350 $all = false;
1351 }
1352
1353 if ( $all ) {
1354 $this->mLoadedItems = true;
1355 }
1356
1357 if ( is_array( $data ) ) {
1358 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1359 $this->mGroups = $data['user_groups'];
1360 }
1361 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1362 $this->loadOptions( $data['user_properties'] );
1363 }
1364 }
1365 }
1366
1367 /**
1368 * Load the data for this user object from another user object.
1369 *
1370 * @param User $user
1371 */
1372 protected function loadFromUserObject( $user ) {
1373 $user->load();
1374 foreach ( self::$mCacheVars as $var ) {
1375 $this->$var = $user->$var;
1376 }
1377 }
1378
1379 /**
1380 * Load the groups from the database if they aren't already loaded.
1381 */
1382 private function loadGroups() {
1383 if ( is_null( $this->mGroups ) ) {
1384 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
1385 ? wfGetDB( DB_MASTER )
1386 : wfGetDB( DB_REPLICA );
1387 $res = $db->select( 'user_groups',
1388 [ 'ug_group' ],
1389 [ 'ug_user' => $this->mId ],
1390 __METHOD__ );
1391 $this->mGroups = [];
1392 foreach ( $res as $row ) {
1393 $this->mGroups[] = $row->ug_group;
1394 }
1395 }
1396 }
1397
1398 /**
1399 * Add the user to the group if he/she meets given criteria.
1400 *
1401 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1402 * possible to remove manually via Special:UserRights. In such case it
1403 * will not be re-added automatically. The user will also not lose the
1404 * group if they no longer meet the criteria.
1405 *
1406 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1407 *
1408 * @return array Array of groups the user has been promoted to.
1409 *
1410 * @see $wgAutopromoteOnce
1411 */
1412 public function addAutopromoteOnceGroups( $event ) {
1413 global $wgAutopromoteOnceLogInRC;
1414
1415 if ( wfReadOnly() || !$this->getId() ) {
1416 return [];
1417 }
1418
1419 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1420 if ( !count( $toPromote ) ) {
1421 return [];
1422 }
1423
1424 if ( !$this->checkAndSetTouched() ) {
1425 return []; // raced out (bug T48834)
1426 }
1427
1428 $oldGroups = $this->getGroups(); // previous groups
1429 foreach ( $toPromote as $group ) {
1430 $this->addGroup( $group );
1431 }
1432 // update groups in external authentication database
1433 Hooks::run( 'UserGroupsChanged', [ $this, $toPromote, [], false, false ] );
1434 AuthManager::callLegacyAuthPlugin( 'updateExternalDBGroups', [ $this, $toPromote ] );
1435
1436 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1437
1438 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1439 $logEntry->setPerformer( $this );
1440 $logEntry->setTarget( $this->getUserPage() );
1441 $logEntry->setParameters( [
1442 '4::oldgroups' => $oldGroups,
1443 '5::newgroups' => $newGroups,
1444 ] );
1445 $logid = $logEntry->insert();
1446 if ( $wgAutopromoteOnceLogInRC ) {
1447 $logEntry->publish( $logid );
1448 }
1449
1450 return $toPromote;
1451 }
1452
1453 /**
1454 * Builds update conditions. Additional conditions may be added to $conditions to
1455 * protected against race conditions using a compare-and-set (CAS) mechanism
1456 * based on comparing $this->mTouched with the user_touched field.
1457 *
1458 * @param Database $db
1459 * @param array $conditions WHERE conditions for use with Database::update
1460 * @return array WHERE conditions for use with Database::update
1461 */
1462 protected function makeUpdateConditions( Database $db, array $conditions ) {
1463 if ( $this->mTouched ) {
1464 // CAS check: only update if the row wasn't changed sicne it was loaded.
1465 $conditions['user_touched'] = $db->timestamp( $this->mTouched );
1466 }
1467
1468 return $conditions;
1469 }
1470
1471 /**
1472 * Bump user_touched if it didn't change since this object was loaded
1473 *
1474 * On success, the mTouched field is updated.
1475 * The user serialization cache is always cleared.
1476 *
1477 * @return bool Whether user_touched was actually updated
1478 * @since 1.26
1479 */
1480 protected function checkAndSetTouched() {
1481 $this->load();
1482
1483 if ( !$this->mId ) {
1484 return false; // anon
1485 }
1486
1487 // Get a new user_touched that is higher than the old one
1488 $newTouched = $this->newTouchedTimestamp();
1489
1490 $dbw = wfGetDB( DB_MASTER );
1491 $dbw->update( 'user',
1492 [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1493 $this->makeUpdateConditions( $dbw, [
1494 'user_id' => $this->mId,
1495 ] ),
1496 __METHOD__
1497 );
1498 $success = ( $dbw->affectedRows() > 0 );
1499
1500 if ( $success ) {
1501 $this->mTouched = $newTouched;
1502 $this->clearSharedCache();
1503 } else {
1504 // Clears on failure too since that is desired if the cache is stale
1505 $this->clearSharedCache( 'refresh' );
1506 }
1507
1508 return $success;
1509 }
1510
1511 /**
1512 * Clear various cached data stored in this object. The cache of the user table
1513 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1514 *
1515 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1516 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1517 */
1518 public function clearInstanceCache( $reloadFrom = false ) {
1519 $this->mNewtalk = -1;
1520 $this->mDatePreference = null;
1521 $this->mBlockedby = -1; # Unset
1522 $this->mHash = false;
1523 $this->mRights = null;
1524 $this->mEffectiveGroups = null;
1525 $this->mImplicitGroups = null;
1526 $this->mGroups = null;
1527 $this->mOptions = null;
1528 $this->mOptionsLoaded = false;
1529 $this->mEditCount = null;
1530
1531 if ( $reloadFrom ) {
1532 $this->mLoadedItems = [];
1533 $this->mFrom = $reloadFrom;
1534 }
1535 }
1536
1537 /**
1538 * Combine the language default options with any site-specific options
1539 * and add the default language variants.
1540 *
1541 * @return array Array of String options
1542 */
1543 public static function getDefaultOptions() {
1544 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1545
1546 static $defOpt = null;
1547 static $defOptLang = null;
1548
1549 if ( $defOpt !== null && $defOptLang === $wgContLang->getCode() ) {
1550 // $wgContLang does not change (and should not change) mid-request,
1551 // but the unit tests change it anyway, and expect this method to
1552 // return values relevant to the current $wgContLang.
1553 return $defOpt;
1554 }
1555
1556 $defOpt = $wgDefaultUserOptions;
1557 // Default language setting
1558 $defOptLang = $wgContLang->getCode();
1559 $defOpt['language'] = $defOptLang;
1560 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1561 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1562 }
1563
1564 // NOTE: don't use SearchEngineConfig::getSearchableNamespaces here,
1565 // since extensions may change the set of searchable namespaces depending
1566 // on user groups/permissions.
1567 foreach ( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
1568 $defOpt['searchNs' . $nsnum] = (boolean)$val;
1569 }
1570 $defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1571
1572 Hooks::run( 'UserGetDefaultOptions', [ &$defOpt ] );
1573
1574 return $defOpt;
1575 }
1576
1577 /**
1578 * Get a given default option value.
1579 *
1580 * @param string $opt Name of option to retrieve
1581 * @return string Default option value
1582 */
1583 public static function getDefaultOption( $opt ) {
1584 $defOpts = self::getDefaultOptions();
1585 if ( isset( $defOpts[$opt] ) ) {
1586 return $defOpts[$opt];
1587 } else {
1588 return null;
1589 }
1590 }
1591
1592 /**
1593 * Get blocking information
1594 * @param bool $bFromSlave Whether to check the replica DB first.
1595 * To improve performance, non-critical checks are done against replica DBs.
1596 * Check when actually saving should be done against master.
1597 */
1598 private function getBlockedStatus( $bFromSlave = true ) {
1599 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1600
1601 if ( -1 != $this->mBlockedby ) {
1602 return;
1603 }
1604
1605 wfDebug( __METHOD__ . ": checking...\n" );
1606
1607 // Initialize data...
1608 // Otherwise something ends up stomping on $this->mBlockedby when
1609 // things get lazy-loaded later, causing false positive block hits
1610 // due to -1 !== 0. Probably session-related... Nothing should be
1611 // overwriting mBlockedby, surely?
1612 $this->load();
1613
1614 # We only need to worry about passing the IP address to the Block generator if the
1615 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1616 # know which IP address they're actually coming from
1617 $ip = null;
1618 if ( !$this->isAllowed( 'ipblock-exempt' ) ) {
1619 // $wgUser->getName() only works after the end of Setup.php. Until
1620 // then, assume it's a logged-out user.
1621 $globalUserName = $wgUser->isSafeToLoad()
1622 ? $wgUser->getName()
1623 : IP::sanitizeIP( $wgUser->getRequest()->getIP() );
1624 if ( $this->getName() === $globalUserName ) {
1625 $ip = $this->getRequest()->getIP();
1626 }
1627 }
1628
1629 // User/IP blocking
1630 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1631
1632 // If no block has been found, check for a cookie indicating that the user is blocked.
1633 $blockCookieVal = (int)$this->getRequest()->getCookie( 'BlockID' );
1634 if ( !$block instanceof Block && $blockCookieVal > 0 ) {
1635 // Load the Block from the ID in the cookie.
1636 $tmpBlock = Block::newFromID( $blockCookieVal );
1637 if ( $tmpBlock instanceof Block ) {
1638 // Check the validity of the block.
1639 $blockIsValid = $tmpBlock->getType() == Block::TYPE_USER
1640 && !$tmpBlock->isExpired()
1641 && $tmpBlock->isAutoblocking();
1642 $config = RequestContext::getMain()->getConfig();
1643 $useBlockCookie = ( $config->get( 'CookieSetOnAutoblock' ) === true );
1644 if ( $blockIsValid && $useBlockCookie ) {
1645 // Use the block.
1646 $block = $tmpBlock;
1647 $this->blockTrigger = 'cookie-block';
1648 } else {
1649 // If the block is not valid, clear the block cookie (but don't delete it,
1650 // because it needs to be cleared from LocalStorage as well and an empty string
1651 // value is checked for in the mediawiki.user.blockcookie module).
1652 $tmpBlock->setCookie( $this->getRequest()->response(), true );
1653 }
1654 }
1655 }
1656
1657 // Proxy blocking
1658 if ( !$block instanceof Block && $ip !== null && !in_array( $ip, $wgProxyWhitelist ) ) {
1659 // Local list
1660 if ( self::isLocallyBlockedProxy( $ip ) ) {
1661 $block = new Block;
1662 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1663 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1664 $block->setTarget( $ip );
1665 $this->blockTrigger = 'proxy-block';
1666 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1667 $block = new Block;
1668 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1669 $block->mReason = wfMessage( 'sorbsreason' )->text();
1670 $block->setTarget( $ip );
1671 $this->blockTrigger = 'openproxy-block';
1672 }
1673 }
1674
1675 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1676 if ( !$block instanceof Block
1677 && $wgApplyIpBlocksToXff
1678 && $ip !== null
1679 && !in_array( $ip, $wgProxyWhitelist )
1680 ) {
1681 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1682 $xff = array_map( 'trim', explode( ',', $xff ) );
1683 $xff = array_diff( $xff, [ $ip ] );
1684 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1685 $block = Block::chooseBlock( $xffblocks, $xff );
1686 if ( $block instanceof Block ) {
1687 # Mangle the reason to alert the user that the block
1688 # originated from matching the X-Forwarded-For header.
1689 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1690 $this->blockTrigger = 'xff-block';
1691 }
1692 }
1693
1694 if ( $block instanceof Block ) {
1695 wfDebug( __METHOD__ . ": Found block.\n" );
1696 $this->mBlock = $block;
1697 $this->mBlockedby = $block->getByName();
1698 $this->mBlockreason = $block->mReason;
1699 $this->mHideName = $block->mHideName;
1700 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1701 } else {
1702 $this->mBlockedby = '';
1703 $this->mHideName = 0;
1704 $this->mAllowUsertalk = false;
1705 $this->blockTrigger = false;
1706 }
1707
1708 // Extensions
1709 Hooks::run( 'GetBlockedStatus', [ &$this ] );
1710 }
1711
1712 /**
1713 * Whether the given IP is in a DNS blacklist.
1714 *
1715 * @param string $ip IP to check
1716 * @param bool $checkWhitelist Whether to check the whitelist first
1717 * @return bool True if blacklisted.
1718 */
1719 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1720 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1721
1722 if ( !$wgEnableDnsBlacklist ) {
1723 return false;
1724 }
1725
1726 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1727 return false;
1728 }
1729
1730 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1731 }
1732
1733 /**
1734 * Whether the given IP is in a given DNS blacklist.
1735 *
1736 * @param string $ip IP to check
1737 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1738 * @return bool True if blacklisted.
1739 */
1740 public function inDnsBlacklist( $ip, $bases ) {
1741 $found = false;
1742 // @todo FIXME: IPv6 ??? (https://bugs.php.net/bug.php?id=33170)
1743 if ( IP::isIPv4( $ip ) ) {
1744 // Reverse IP, bug 21255
1745 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1746
1747 foreach ( (array)$bases as $base ) {
1748 // Make hostname
1749 // If we have an access key, use that too (ProjectHoneypot, etc.)
1750 $basename = $base;
1751 if ( is_array( $base ) ) {
1752 if ( count( $base ) >= 2 ) {
1753 // Access key is 1, base URL is 0
1754 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1755 } else {
1756 $host = "$ipReversed.{$base[0]}";
1757 }
1758 $basename = $base[0];
1759 } else {
1760 $host = "$ipReversed.$base";
1761 }
1762
1763 // Send query
1764 $ipList = gethostbynamel( $host );
1765
1766 if ( $ipList ) {
1767 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
1768 $found = true;
1769 break;
1770 } else {
1771 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $basename." );
1772 }
1773 }
1774 }
1775
1776 return $found;
1777 }
1778
1779 /**
1780 * Check if an IP address is in the local proxy list
1781 *
1782 * @param string $ip
1783 *
1784 * @return bool
1785 */
1786 public static function isLocallyBlockedProxy( $ip ) {
1787 global $wgProxyList;
1788
1789 if ( !$wgProxyList ) {
1790 return false;
1791 }
1792
1793 if ( !is_array( $wgProxyList ) ) {
1794 // Load from the specified file
1795 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1796 }
1797
1798 if ( !is_array( $wgProxyList ) ) {
1799 $ret = false;
1800 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1801 $ret = true;
1802 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1803 // Old-style flipped proxy list
1804 $ret = true;
1805 } else {
1806 $ret = false;
1807 }
1808 return $ret;
1809 }
1810
1811 /**
1812 * Is this user subject to rate limiting?
1813 *
1814 * @return bool True if rate limited
1815 */
1816 public function isPingLimitable() {
1817 global $wgRateLimitsExcludedIPs;
1818 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1819 // No other good way currently to disable rate limits
1820 // for specific IPs. :P
1821 // But this is a crappy hack and should die.
1822 return false;
1823 }
1824 return !$this->isAllowed( 'noratelimit' );
1825 }
1826
1827 /**
1828 * Primitive rate limits: enforce maximum actions per time period
1829 * to put a brake on flooding.
1830 *
1831 * The method generates both a generic profiling point and a per action one
1832 * (suffix being "-$action".
1833 *
1834 * @note When using a shared cache like memcached, IP-address
1835 * last-hit counters will be shared across wikis.
1836 *
1837 * @param string $action Action to enforce; 'edit' if unspecified
1838 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1839 * @return bool True if a rate limiter was tripped
1840 */
1841 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1842 // Call the 'PingLimiter' hook
1843 $result = false;
1844 if ( !Hooks::run( 'PingLimiter', [ &$this, $action, &$result, $incrBy ] ) ) {
1845 return $result;
1846 }
1847
1848 global $wgRateLimits;
1849 if ( !isset( $wgRateLimits[$action] ) ) {
1850 return false;
1851 }
1852
1853 $limits = array_merge(
1854 [ '&can-bypass' => true ],
1855 $wgRateLimits[$action]
1856 );
1857
1858 // Some groups shouldn't trigger the ping limiter, ever
1859 if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1860 return false;
1861 }
1862
1863 $keys = [];
1864 $id = $this->getId();
1865 $userLimit = false;
1866 $isNewbie = $this->isNewbie();
1867
1868 if ( $id == 0 ) {
1869 // limits for anons
1870 if ( isset( $limits['anon'] ) ) {
1871 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1872 }
1873 } else {
1874 // limits for logged-in users
1875 if ( isset( $limits['user'] ) ) {
1876 $userLimit = $limits['user'];
1877 }
1878 // limits for newbie logged-in users
1879 if ( $isNewbie && isset( $limits['newbie'] ) ) {
1880 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1881 }
1882 }
1883
1884 // limits for anons and for newbie logged-in users
1885 if ( $isNewbie ) {
1886 // ip-based limits
1887 if ( isset( $limits['ip'] ) ) {
1888 $ip = $this->getRequest()->getIP();
1889 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1890 }
1891 // subnet-based limits
1892 if ( isset( $limits['subnet'] ) ) {
1893 $ip = $this->getRequest()->getIP();
1894 $subnet = IP::getSubnet( $ip );
1895 if ( $subnet !== false ) {
1896 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1897 }
1898 }
1899 }
1900
1901 // Check for group-specific permissions
1902 // If more than one group applies, use the group with the highest limit ratio (max/period)
1903 foreach ( $this->getGroups() as $group ) {
1904 if ( isset( $limits[$group] ) ) {
1905 if ( $userLimit === false
1906 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1907 ) {
1908 $userLimit = $limits[$group];
1909 }
1910 }
1911 }
1912
1913 // Set the user limit key
1914 if ( $userLimit !== false ) {
1915 list( $max, $period ) = $userLimit;
1916 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1917 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1918 }
1919
1920 // ip-based limits for all ping-limitable users
1921 if ( isset( $limits['ip-all'] ) ) {
1922 $ip = $this->getRequest()->getIP();
1923 // ignore if user limit is more permissive
1924 if ( $isNewbie || $userLimit === false
1925 || $limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1926 $keys["mediawiki:limiter:$action:ip-all:$ip"] = $limits['ip-all'];
1927 }
1928 }
1929
1930 // subnet-based limits for all ping-limitable users
1931 if ( isset( $limits['subnet-all'] ) ) {
1932 $ip = $this->getRequest()->getIP();
1933 $subnet = IP::getSubnet( $ip );
1934 if ( $subnet !== false ) {
1935 // ignore if user limit is more permissive
1936 if ( $isNewbie || $userLimit === false
1937 || $limits['ip-all'][0] / $limits['ip-all'][1]
1938 > $userLimit[0] / $userLimit[1] ) {
1939 $keys["mediawiki:limiter:$action:subnet-all:$subnet"] = $limits['subnet-all'];
1940 }
1941 }
1942 }
1943
1944 $cache = ObjectCache::getLocalClusterInstance();
1945
1946 $triggered = false;
1947 foreach ( $keys as $key => $limit ) {
1948 list( $max, $period ) = $limit;
1949 $summary = "(limit $max in {$period}s)";
1950 $count = $cache->get( $key );
1951 // Already pinged?
1952 if ( $count ) {
1953 if ( $count >= $max ) {
1954 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1955 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1956 $triggered = true;
1957 } else {
1958 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1959 }
1960 } else {
1961 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1962 if ( $incrBy > 0 ) {
1963 $cache->add( $key, 0, intval( $period ) ); // first ping
1964 }
1965 }
1966 if ( $incrBy > 0 ) {
1967 $cache->incr( $key, $incrBy );
1968 }
1969 }
1970
1971 return $triggered;
1972 }
1973
1974 /**
1975 * Check if user is blocked
1976 *
1977 * @param bool $bFromSlave Whether to check the replica DB instead of
1978 * the master. Hacked from false due to horrible probs on site.
1979 * @return bool True if blocked, false otherwise
1980 */
1981 public function isBlocked( $bFromSlave = true ) {
1982 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1983 }
1984
1985 /**
1986 * Get the block affecting the user, or null if the user is not blocked
1987 *
1988 * @param bool $bFromSlave Whether to check the replica DB instead of the master
1989 * @return Block|null
1990 */
1991 public function getBlock( $bFromSlave = true ) {
1992 $this->getBlockedStatus( $bFromSlave );
1993 return $this->mBlock instanceof Block ? $this->mBlock : null;
1994 }
1995
1996 /**
1997 * Check if user is blocked from editing a particular article
1998 *
1999 * @param Title $title Title to check
2000 * @param bool $bFromSlave Whether to check the replica DB instead of the master
2001 * @return bool
2002 */
2003 public function isBlockedFrom( $title, $bFromSlave = false ) {
2004 global $wgBlockAllowsUTEdit;
2005
2006 $blocked = $this->isBlocked( $bFromSlave );
2007 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
2008 // If a user's name is suppressed, they cannot make edits anywhere
2009 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
2010 && $title->getNamespace() == NS_USER_TALK ) {
2011 $blocked = false;
2012 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
2013 }
2014
2015 Hooks::run( 'UserIsBlockedFrom', [ $this, $title, &$blocked, &$allowUsertalk ] );
2016
2017 return $blocked;
2018 }
2019
2020 /**
2021 * If user is blocked, return the name of the user who placed the block
2022 * @return string Name of blocker
2023 */
2024 public function blockedBy() {
2025 $this->getBlockedStatus();
2026 return $this->mBlockedby;
2027 }
2028
2029 /**
2030 * If user is blocked, return the specified reason for the block
2031 * @return string Blocking reason
2032 */
2033 public function blockedFor() {
2034 $this->getBlockedStatus();
2035 return $this->mBlockreason;
2036 }
2037
2038 /**
2039 * If user is blocked, return the ID for the block
2040 * @return int Block ID
2041 */
2042 public function getBlockId() {
2043 $this->getBlockedStatus();
2044 return ( $this->mBlock ? $this->mBlock->getId() : false );
2045 }
2046
2047 /**
2048 * Check if user is blocked on all wikis.
2049 * Do not use for actual edit permission checks!
2050 * This is intended for quick UI checks.
2051 *
2052 * @param string $ip IP address, uses current client if none given
2053 * @return bool True if blocked, false otherwise
2054 */
2055 public function isBlockedGlobally( $ip = '' ) {
2056 return $this->getGlobalBlock( $ip ) instanceof Block;
2057 }
2058
2059 /**
2060 * Check if user is blocked on all wikis.
2061 * Do not use for actual edit permission checks!
2062 * This is intended for quick UI checks.
2063 *
2064 * @param string $ip IP address, uses current client if none given
2065 * @return Block|null Block object if blocked, null otherwise
2066 * @throws FatalError
2067 * @throws MWException
2068 */
2069 public function getGlobalBlock( $ip = '' ) {
2070 if ( $this->mGlobalBlock !== null ) {
2071 return $this->mGlobalBlock ?: null;
2072 }
2073 // User is already an IP?
2074 if ( IP::isIPAddress( $this->getName() ) ) {
2075 $ip = $this->getName();
2076 } elseif ( !$ip ) {
2077 $ip = $this->getRequest()->getIP();
2078 }
2079 $blocked = false;
2080 $block = null;
2081 Hooks::run( 'UserIsBlockedGlobally', [ &$this, $ip, &$blocked, &$block ] );
2082
2083 if ( $blocked && $block === null ) {
2084 // back-compat: UserIsBlockedGlobally didn't have $block param first
2085 $block = new Block;
2086 $block->setTarget( $ip );
2087 }
2088
2089 $this->mGlobalBlock = $blocked ? $block : false;
2090 return $this->mGlobalBlock ?: null;
2091 }
2092
2093 /**
2094 * Check if user account is locked
2095 *
2096 * @return bool True if locked, false otherwise
2097 */
2098 public function isLocked() {
2099 if ( $this->mLocked !== null ) {
2100 return $this->mLocked;
2101 }
2102 $authUser = AuthManager::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2103 $this->mLocked = $authUser && $authUser->isLocked();
2104 Hooks::run( 'UserIsLocked', [ $this, &$this->mLocked ] );
2105 return $this->mLocked;
2106 }
2107
2108 /**
2109 * Check if user account is hidden
2110 *
2111 * @return bool True if hidden, false otherwise
2112 */
2113 public function isHidden() {
2114 if ( $this->mHideName !== null ) {
2115 return $this->mHideName;
2116 }
2117 $this->getBlockedStatus();
2118 if ( !$this->mHideName ) {
2119 $authUser = AuthManager::callLegacyAuthPlugin( 'getUserInstance', [ &$this ], null );
2120 $this->mHideName = $authUser && $authUser->isHidden();
2121 Hooks::run( 'UserIsHidden', [ $this, &$this->mHideName ] );
2122 }
2123 return $this->mHideName;
2124 }
2125
2126 /**
2127 * Get the user's ID.
2128 * @return int The user's ID; 0 if the user is anonymous or nonexistent
2129 */
2130 public function getId() {
2131 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
2132 // Special case, we know the user is anonymous
2133 return 0;
2134 } elseif ( !$this->isItemLoaded( 'id' ) ) {
2135 // Don't load if this was initialized from an ID
2136 $this->load();
2137 }
2138
2139 return (int)$this->mId;
2140 }
2141
2142 /**
2143 * Set the user and reload all fields according to a given ID
2144 * @param int $v User ID to reload
2145 */
2146 public function setId( $v ) {
2147 $this->mId = $v;
2148 $this->clearInstanceCache( 'id' );
2149 }
2150
2151 /**
2152 * Get the user name, or the IP of an anonymous user
2153 * @return string User's name or IP address
2154 */
2155 public function getName() {
2156 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2157 // Special case optimisation
2158 return $this->mName;
2159 } else {
2160 $this->load();
2161 if ( $this->mName === false ) {
2162 // Clean up IPs
2163 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
2164 }
2165 return $this->mName;
2166 }
2167 }
2168
2169 /**
2170 * Set the user name.
2171 *
2172 * This does not reload fields from the database according to the given
2173 * name. Rather, it is used to create a temporary "nonexistent user" for
2174 * later addition to the database. It can also be used to set the IP
2175 * address for an anonymous user to something other than the current
2176 * remote IP.
2177 *
2178 * @note User::newFromName() has roughly the same function, when the named user
2179 * does not exist.
2180 * @param string $str New user name to set
2181 */
2182 public function setName( $str ) {
2183 $this->load();
2184 $this->mName = $str;
2185 }
2186
2187 /**
2188 * Get the user's name escaped by underscores.
2189 * @return string Username escaped by underscores.
2190 */
2191 public function getTitleKey() {
2192 return str_replace( ' ', '_', $this->getName() );
2193 }
2194
2195 /**
2196 * Check if the user has new messages.
2197 * @return bool True if the user has new messages
2198 */
2199 public function getNewtalk() {
2200 $this->load();
2201
2202 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2203 if ( $this->mNewtalk === -1 ) {
2204 $this->mNewtalk = false; # reset talk page status
2205
2206 // Check memcached separately for anons, who have no
2207 // entire User object stored in there.
2208 if ( !$this->mId ) {
2209 global $wgDisableAnonTalk;
2210 if ( $wgDisableAnonTalk ) {
2211 // Anon newtalk disabled by configuration.
2212 $this->mNewtalk = false;
2213 } else {
2214 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
2215 }
2216 } else {
2217 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2218 }
2219 }
2220
2221 return (bool)$this->mNewtalk;
2222 }
2223
2224 /**
2225 * Return the data needed to construct links for new talk page message
2226 * alerts. If there are new messages, this will return an associative array
2227 * with the following data:
2228 * wiki: The database name of the wiki
2229 * link: Root-relative link to the user's talk page
2230 * rev: The last talk page revision that the user has seen or null. This
2231 * is useful for building diff links.
2232 * If there are no new messages, it returns an empty array.
2233 * @note This function was designed to accomodate multiple talk pages, but
2234 * currently only returns a single link and revision.
2235 * @return array
2236 */
2237 public function getNewMessageLinks() {
2238 $talks = [];
2239 if ( !Hooks::run( 'UserRetrieveNewTalks', [ &$this, &$talks ] ) ) {
2240 return $talks;
2241 } elseif ( !$this->getNewtalk() ) {
2242 return [];
2243 }
2244 $utp = $this->getTalkPage();
2245 $dbr = wfGetDB( DB_REPLICA );
2246 // Get the "last viewed rev" timestamp from the oldest message notification
2247 $timestamp = $dbr->selectField( 'user_newtalk',
2248 'MIN(user_last_timestamp)',
2249 $this->isAnon() ? [ 'user_ip' => $this->getName() ] : [ 'user_id' => $this->getId() ],
2250 __METHOD__ );
2251 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2252 return [ [ 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ] ];
2253 }
2254
2255 /**
2256 * Get the revision ID for the last talk page revision viewed by the talk
2257 * page owner.
2258 * @return int|null Revision ID or null
2259 */
2260 public function getNewMessageRevisionId() {
2261 $newMessageRevisionId = null;
2262 $newMessageLinks = $this->getNewMessageLinks();
2263 if ( $newMessageLinks ) {
2264 // Note: getNewMessageLinks() never returns more than a single link
2265 // and it is always for the same wiki, but we double-check here in
2266 // case that changes some time in the future.
2267 if ( count( $newMessageLinks ) === 1
2268 && $newMessageLinks[0]['wiki'] === wfWikiID()
2269 && $newMessageLinks[0]['rev']
2270 ) {
2271 /** @var Revision $newMessageRevision */
2272 $newMessageRevision = $newMessageLinks[0]['rev'];
2273 $newMessageRevisionId = $newMessageRevision->getId();
2274 }
2275 }
2276 return $newMessageRevisionId;
2277 }
2278
2279 /**
2280 * Internal uncached check for new messages
2281 *
2282 * @see getNewtalk()
2283 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2284 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2285 * @return bool True if the user has new messages
2286 */
2287 protected function checkNewtalk( $field, $id ) {
2288 $dbr = wfGetDB( DB_REPLICA );
2289
2290 $ok = $dbr->selectField( 'user_newtalk', $field, [ $field => $id ], __METHOD__ );
2291
2292 return $ok !== false;
2293 }
2294
2295 /**
2296 * Add or update the new messages flag
2297 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2298 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2299 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2300 * @return bool True if successful, false otherwise
2301 */
2302 protected function updateNewtalk( $field, $id, $curRev = null ) {
2303 // Get timestamp of the talk page revision prior to the current one
2304 $prevRev = $curRev ? $curRev->getPrevious() : false;
2305 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2306 // Mark the user as having new messages since this revision
2307 $dbw = wfGetDB( DB_MASTER );
2308 $dbw->insert( 'user_newtalk',
2309 [ $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2310 __METHOD__,
2311 'IGNORE' );
2312 if ( $dbw->affectedRows() ) {
2313 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2314 return true;
2315 } else {
2316 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2317 return false;
2318 }
2319 }
2320
2321 /**
2322 * Clear the new messages flag for the given user
2323 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2324 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2325 * @return bool True if successful, false otherwise
2326 */
2327 protected function deleteNewtalk( $field, $id ) {
2328 $dbw = wfGetDB( DB_MASTER );
2329 $dbw->delete( 'user_newtalk',
2330 [ $field => $id ],
2331 __METHOD__ );
2332 if ( $dbw->affectedRows() ) {
2333 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2334 return true;
2335 } else {
2336 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2337 return false;
2338 }
2339 }
2340
2341 /**
2342 * Update the 'You have new messages!' status.
2343 * @param bool $val Whether the user has new messages
2344 * @param Revision $curRev New, as yet unseen revision of the user talk
2345 * page. Ignored if null or !$val.
2346 */
2347 public function setNewtalk( $val, $curRev = null ) {
2348 if ( wfReadOnly() ) {
2349 return;
2350 }
2351
2352 $this->load();
2353 $this->mNewtalk = $val;
2354
2355 if ( $this->isAnon() ) {
2356 $field = 'user_ip';
2357 $id = $this->getName();
2358 } else {
2359 $field = 'user_id';
2360 $id = $this->getId();
2361 }
2362
2363 if ( $val ) {
2364 $changed = $this->updateNewtalk( $field, $id, $curRev );
2365 } else {
2366 $changed = $this->deleteNewtalk( $field, $id );
2367 }
2368
2369 if ( $changed ) {
2370 $this->invalidateCache();
2371 }
2372 }
2373
2374 /**
2375 * Generate a current or new-future timestamp to be stored in the
2376 * user_touched field when we update things.
2377 * @return string Timestamp in TS_MW format
2378 */
2379 private function newTouchedTimestamp() {
2380 global $wgClockSkewFudge;
2381
2382 $time = wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2383 if ( $this->mTouched && $time <= $this->mTouched ) {
2384 $time = wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $this->mTouched ) + 1 );
2385 }
2386
2387 return $time;
2388 }
2389
2390 /**
2391 * Clear user data from memcached
2392 *
2393 * Use after applying updates to the database; caller's
2394 * responsibility to update user_touched if appropriate.
2395 *
2396 * Called implicitly from invalidateCache() and saveSettings().
2397 *
2398 * @param string $mode Use 'refresh' to clear now; otherwise before DB commit
2399 */
2400 public function clearSharedCache( $mode = 'changed' ) {
2401 if ( !$this->getId() ) {
2402 return;
2403 }
2404
2405 $cache = ObjectCache::getMainWANInstance();
2406 $key = $this->getCacheKey( $cache );
2407 if ( $mode === 'refresh' ) {
2408 $cache->delete( $key, 1 );
2409 } else {
2410 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle(
2411 function() use ( $cache, $key ) {
2412 $cache->delete( $key );
2413 },
2414 __METHOD__
2415 );
2416 }
2417 }
2418
2419 /**
2420 * Immediately touch the user data cache for this account
2421 *
2422 * Calls touch() and removes account data from memcached
2423 */
2424 public function invalidateCache() {
2425 $this->touch();
2426 $this->clearSharedCache();
2427 }
2428
2429 /**
2430 * Update the "touched" timestamp for the user
2431 *
2432 * This is useful on various login/logout events when making sure that
2433 * a browser or proxy that has multiple tenants does not suffer cache
2434 * pollution where the new user sees the old users content. The value
2435 * of getTouched() is checked when determining 304 vs 200 responses.
2436 * Unlike invalidateCache(), this preserves the User object cache and
2437 * avoids database writes.
2438 *
2439 * @since 1.25
2440 */
2441 public function touch() {
2442 $id = $this->getId();
2443 if ( $id ) {
2444 $key = wfMemcKey( 'user-quicktouched', 'id', $id );
2445 ObjectCache::getMainWANInstance()->touchCheckKey( $key );
2446 $this->mQuickTouched = null;
2447 }
2448 }
2449
2450 /**
2451 * Validate the cache for this account.
2452 * @param string $timestamp A timestamp in TS_MW format
2453 * @return bool
2454 */
2455 public function validateCache( $timestamp ) {
2456 return ( $timestamp >= $this->getTouched() );
2457 }
2458
2459 /**
2460 * Get the user touched timestamp
2461 *
2462 * Use this value only to validate caches via inequalities
2463 * such as in the case of HTTP If-Modified-Since response logic
2464 *
2465 * @return string TS_MW Timestamp
2466 */
2467 public function getTouched() {
2468 $this->load();
2469
2470 if ( $this->mId ) {
2471 if ( $this->mQuickTouched === null ) {
2472 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId );
2473 $cache = ObjectCache::getMainWANInstance();
2474
2475 $this->mQuickTouched = wfTimestamp( TS_MW, $cache->getCheckKeyTime( $key ) );
2476 }
2477
2478 return max( $this->mTouched, $this->mQuickTouched );
2479 }
2480
2481 return $this->mTouched;
2482 }
2483
2484 /**
2485 * Get the user_touched timestamp field (time of last DB updates)
2486 * @return string TS_MW Timestamp
2487 * @since 1.26
2488 */
2489 public function getDBTouched() {
2490 $this->load();
2491
2492 return $this->mTouched;
2493 }
2494
2495 /**
2496 * @deprecated Removed in 1.27.
2497 * @return Password
2498 * @since 1.24
2499 */
2500 public function getPassword() {
2501 throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2502 }
2503
2504 /**
2505 * @deprecated Removed in 1.27.
2506 * @return Password
2507 * @since 1.24
2508 */
2509 public function getTemporaryPassword() {
2510 throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2511 }
2512
2513 /**
2514 * Set the password and reset the random token.
2515 * Calls through to authentication plugin if necessary;
2516 * will have no effect if the auth plugin refuses to
2517 * pass the change through or if the legal password
2518 * checks fail.
2519 *
2520 * As a special case, setting the password to null
2521 * wipes it, so the account cannot be logged in until
2522 * a new password is set, for instance via e-mail.
2523 *
2524 * @deprecated since 1.27, use AuthManager instead
2525 * @param string $str New password to set
2526 * @throws PasswordError On failure
2527 * @return bool
2528 */
2529 public function setPassword( $str ) {
2530 return $this->setPasswordInternal( $str );
2531 }
2532
2533 /**
2534 * Set the password and reset the random token unconditionally.
2535 *
2536 * @deprecated since 1.27, use AuthManager instead
2537 * @param string|null $str New password to set or null to set an invalid
2538 * password hash meaning that the user will not be able to log in
2539 * through the web interface.
2540 */
2541 public function setInternalPassword( $str ) {
2542 $this->setPasswordInternal( $str );
2543 }
2544
2545 /**
2546 * Actually set the password and such
2547 * @since 1.27 cannot set a password for a user not in the database
2548 * @param string|null $str New password to set or null to set an invalid
2549 * password hash meaning that the user will not be able to log in
2550 * through the web interface.
2551 * @return bool Success
2552 */
2553 private function setPasswordInternal( $str ) {
2554 $manager = AuthManager::singleton();
2555
2556 // If the user doesn't exist yet, fail
2557 if ( !$manager->userExists( $this->getName() ) ) {
2558 throw new LogicException( 'Cannot set a password for a user that is not in the database.' );
2559 }
2560
2561 $status = $this->changeAuthenticationData( [
2562 'username' => $this->getName(),
2563 'password' => $str,
2564 'retype' => $str,
2565 ] );
2566 if ( !$status->isGood() ) {
2567 \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
2568 ->info( __METHOD__ . ': Password change rejected: '
2569 . $status->getWikiText( null, null, 'en' ) );
2570 return false;
2571 }
2572
2573 $this->setOption( 'watchlisttoken', false );
2574 SessionManager::singleton()->invalidateSessionsForUser( $this );
2575
2576 return true;
2577 }
2578
2579 /**
2580 * Changes credentials of the user.
2581 *
2582 * This is a convenience wrapper around AuthManager::changeAuthenticationData.
2583 * Note that this can return a status that isOK() but not isGood() on certain types of failures,
2584 * e.g. when no provider handled the change.
2585 *
2586 * @param array $data A set of authentication data in fieldname => value format. This is the
2587 * same data you would pass the changeauthenticationdata API - 'username', 'password' etc.
2588 * @return Status
2589 * @since 1.27
2590 */
2591 public function changeAuthenticationData( array $data ) {
2592 $manager = AuthManager::singleton();
2593 $reqs = $manager->getAuthenticationRequests( AuthManager::ACTION_CHANGE, $this );
2594 $reqs = AuthenticationRequest::loadRequestsFromSubmission( $reqs, $data );
2595
2596 $status = Status::newGood( 'ignored' );
2597 foreach ( $reqs as $req ) {
2598 $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2599 }
2600 if ( $status->getValue() === 'ignored' ) {
2601 $status->warning( 'authenticationdatachange-ignored' );
2602 }
2603
2604 if ( $status->isGood() ) {
2605 foreach ( $reqs as $req ) {
2606 $manager->changeAuthenticationData( $req );
2607 }
2608 }
2609 return $status;
2610 }
2611
2612 /**
2613 * Get the user's current token.
2614 * @param bool $forceCreation Force the generation of a new token if the
2615 * user doesn't have one (default=true for backwards compatibility).
2616 * @return string|null Token
2617 */
2618 public function getToken( $forceCreation = true ) {
2619 global $wgAuthenticationTokenVersion;
2620
2621 $this->load();
2622 if ( !$this->mToken && $forceCreation ) {
2623 $this->setToken();
2624 }
2625
2626 if ( !$this->mToken ) {
2627 // The user doesn't have a token, return null to indicate that.
2628 return null;
2629 } elseif ( $this->mToken === self::INVALID_TOKEN ) {
2630 // We return a random value here so existing token checks are very
2631 // likely to fail.
2632 return MWCryptRand::generateHex( self::TOKEN_LENGTH );
2633 } elseif ( $wgAuthenticationTokenVersion === null ) {
2634 // $wgAuthenticationTokenVersion not in use, so return the raw secret
2635 return $this->mToken;
2636 } else {
2637 // $wgAuthenticationTokenVersion in use, so hmac it.
2638 $ret = MWCryptHash::hmac( $wgAuthenticationTokenVersion, $this->mToken, false );
2639
2640 // The raw hash can be overly long. Shorten it up.
2641 $len = max( 32, self::TOKEN_LENGTH );
2642 if ( strlen( $ret ) < $len ) {
2643 // Should never happen, even md5 is 128 bits
2644 throw new \UnexpectedValueException( 'Hmac returned less than 128 bits' );
2645 }
2646 return substr( $ret, -$len );
2647 }
2648 }
2649
2650 /**
2651 * Set the random token (used for persistent authentication)
2652 * Called from loadDefaults() among other places.
2653 *
2654 * @param string|bool $token If specified, set the token to this value
2655 */
2656 public function setToken( $token = false ) {
2657 $this->load();
2658 if ( $this->mToken === self::INVALID_TOKEN ) {
2659 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
2660 ->debug( __METHOD__ . ": Ignoring attempt to set token for system user \"$this\"" );
2661 } elseif ( !$token ) {
2662 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2663 } else {
2664 $this->mToken = $token;
2665 }
2666 }
2667
2668 /**
2669 * Set the password for a password reminder or new account email
2670 *
2671 * @deprecated Removed in 1.27. Use PasswordReset instead.
2672 * @param string $str New password to set or null to set an invalid
2673 * password hash meaning that the user will not be able to use it
2674 * @param bool $throttle If true, reset the throttle timestamp to the present
2675 */
2676 public function setNewpassword( $str, $throttle = true ) {
2677 throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2678 }
2679
2680 /**
2681 * Has password reminder email been sent within the last
2682 * $wgPasswordReminderResendTime hours?
2683 * @deprecated Removed in 1.27. See above.
2684 * @return bool
2685 */
2686 public function isPasswordReminderThrottled() {
2687 throw new BadMethodCallException( __METHOD__ . ' has been removed in 1.27' );
2688 }
2689
2690 /**
2691 * Get the user's e-mail address
2692 * @return string User's email address
2693 */
2694 public function getEmail() {
2695 $this->load();
2696 Hooks::run( 'UserGetEmail', [ $this, &$this->mEmail ] );
2697 return $this->mEmail;
2698 }
2699
2700 /**
2701 * Get the timestamp of the user's e-mail authentication
2702 * @return string TS_MW timestamp
2703 */
2704 public function getEmailAuthenticationTimestamp() {
2705 $this->load();
2706 Hooks::run( 'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
2707 return $this->mEmailAuthenticated;
2708 }
2709
2710 /**
2711 * Set the user's e-mail address
2712 * @param string $str New e-mail address
2713 */
2714 public function setEmail( $str ) {
2715 $this->load();
2716 if ( $str == $this->mEmail ) {
2717 return;
2718 }
2719 $this->invalidateEmail();
2720 $this->mEmail = $str;
2721 Hooks::run( 'UserSetEmail', [ $this, &$this->mEmail ] );
2722 }
2723
2724 /**
2725 * Set the user's e-mail address and a confirmation mail if needed.
2726 *
2727 * @since 1.20
2728 * @param string $str New e-mail address
2729 * @return Status
2730 */
2731 public function setEmailWithConfirmation( $str ) {
2732 global $wgEnableEmail, $wgEmailAuthentication;
2733
2734 if ( !$wgEnableEmail ) {
2735 return Status::newFatal( 'emaildisabled' );
2736 }
2737
2738 $oldaddr = $this->getEmail();
2739 if ( $str === $oldaddr ) {
2740 return Status::newGood( true );
2741 }
2742
2743 $type = $oldaddr != '' ? 'changed' : 'set';
2744 $notificationResult = null;
2745
2746 if ( $wgEmailAuthentication ) {
2747 // Send the user an email notifying the user of the change in registered
2748 // email address on their previous email address
2749 if ( $type == 'changed' ) {
2750 $change = $str != '' ? 'changed' : 'removed';
2751 $notificationResult = $this->sendMail(
2752 wfMessage( 'notificationemail_subject_' . $change )->text(),
2753 wfMessage( 'notificationemail_body_' . $change,
2754 $this->getRequest()->getIP(),
2755 $this->getName(),
2756 $str )->text()
2757 );
2758 }
2759 }
2760
2761 $this->setEmail( $str );
2762
2763 if ( $str !== '' && $wgEmailAuthentication ) {
2764 // Send a confirmation request to the new address if needed
2765 $result = $this->sendConfirmationMail( $type );
2766
2767 if ( $notificationResult !== null ) {
2768 $result->merge( $notificationResult );
2769 }
2770
2771 if ( $result->isGood() ) {
2772 // Say to the caller that a confirmation and notification mail has been sent
2773 $result->value = 'eauth';
2774 }
2775 } else {
2776 $result = Status::newGood( true );
2777 }
2778
2779 return $result;
2780 }
2781
2782 /**
2783 * Get the user's real name
2784 * @return string User's real name
2785 */
2786 public function getRealName() {
2787 if ( !$this->isItemLoaded( 'realname' ) ) {
2788 $this->load();
2789 }
2790
2791 return $this->mRealName;
2792 }
2793
2794 /**
2795 * Set the user's real name
2796 * @param string $str New real name
2797 */
2798 public function setRealName( $str ) {
2799 $this->load();
2800 $this->mRealName = $str;
2801 }
2802
2803 /**
2804 * Get the user's current setting for a given option.
2805 *
2806 * @param string $oname The option to check
2807 * @param string $defaultOverride A default value returned if the option does not exist
2808 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2809 * @return string User's current value for the option
2810 * @see getBoolOption()
2811 * @see getIntOption()
2812 */
2813 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2814 global $wgHiddenPrefs;
2815 $this->loadOptions();
2816
2817 # We want 'disabled' preferences to always behave as the default value for
2818 # users, even if they have set the option explicitly in their settings (ie they
2819 # set it, and then it was disabled removing their ability to change it). But
2820 # we don't want to erase the preferences in the database in case the preference
2821 # is re-enabled again. So don't touch $mOptions, just override the returned value
2822 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2823 return self::getDefaultOption( $oname );
2824 }
2825
2826 if ( array_key_exists( $oname, $this->mOptions ) ) {
2827 return $this->mOptions[$oname];
2828 } else {
2829 return $defaultOverride;
2830 }
2831 }
2832
2833 /**
2834 * Get all user's options
2835 *
2836 * @param int $flags Bitwise combination of:
2837 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2838 * to the default value. (Since 1.25)
2839 * @return array
2840 */
2841 public function getOptions( $flags = 0 ) {
2842 global $wgHiddenPrefs;
2843 $this->loadOptions();
2844 $options = $this->mOptions;
2845
2846 # We want 'disabled' preferences to always behave as the default value for
2847 # users, even if they have set the option explicitly in their settings (ie they
2848 # set it, and then it was disabled removing their ability to change it). But
2849 # we don't want to erase the preferences in the database in case the preference
2850 # is re-enabled again. So don't touch $mOptions, just override the returned value
2851 foreach ( $wgHiddenPrefs as $pref ) {
2852 $default = self::getDefaultOption( $pref );
2853 if ( $default !== null ) {
2854 $options[$pref] = $default;
2855 }
2856 }
2857
2858 if ( $flags & self::GETOPTIONS_EXCLUDE_DEFAULTS ) {
2859 $options = array_diff_assoc( $options, self::getDefaultOptions() );
2860 }
2861
2862 return $options;
2863 }
2864
2865 /**
2866 * Get the user's current setting for a given option, as a boolean value.
2867 *
2868 * @param string $oname The option to check
2869 * @return bool User's current value for the option
2870 * @see getOption()
2871 */
2872 public function getBoolOption( $oname ) {
2873 return (bool)$this->getOption( $oname );
2874 }
2875
2876 /**
2877 * Get the user's current setting for a given option, as an integer value.
2878 *
2879 * @param string $oname The option to check
2880 * @param int $defaultOverride A default value returned if the option does not exist
2881 * @return int User's current value for the option
2882 * @see getOption()
2883 */
2884 public function getIntOption( $oname, $defaultOverride = 0 ) {
2885 $val = $this->getOption( $oname );
2886 if ( $val == '' ) {
2887 $val = $defaultOverride;
2888 }
2889 return intval( $val );
2890 }
2891
2892 /**
2893 * Set the given option for a user.
2894 *
2895 * You need to call saveSettings() to actually write to the database.
2896 *
2897 * @param string $oname The option to set
2898 * @param mixed $val New value to set
2899 */
2900 public function setOption( $oname, $val ) {
2901 $this->loadOptions();
2902
2903 // Explicitly NULL values should refer to defaults
2904 if ( is_null( $val ) ) {
2905 $val = self::getDefaultOption( $oname );
2906 }
2907
2908 $this->mOptions[$oname] = $val;
2909 }
2910
2911 /**
2912 * Get a token stored in the preferences (like the watchlist one),
2913 * resetting it if it's empty (and saving changes).
2914 *
2915 * @param string $oname The option name to retrieve the token from
2916 * @return string|bool User's current value for the option, or false if this option is disabled.
2917 * @see resetTokenFromOption()
2918 * @see getOption()
2919 * @deprecated since 1.26 Applications should use the OAuth extension
2920 */
2921 public function getTokenFromOption( $oname ) {
2922 global $wgHiddenPrefs;
2923
2924 $id = $this->getId();
2925 if ( !$id || in_array( $oname, $wgHiddenPrefs ) ) {
2926 return false;
2927 }
2928
2929 $token = $this->getOption( $oname );
2930 if ( !$token ) {
2931 // Default to a value based on the user token to avoid space
2932 // wasted on storing tokens for all users. When this option
2933 // is set manually by the user, only then is it stored.
2934 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2935 }
2936
2937 return $token;
2938 }
2939
2940 /**
2941 * Reset a token stored in the preferences (like the watchlist one).
2942 * *Does not* save user's preferences (similarly to setOption()).
2943 *
2944 * @param string $oname The option name to reset the token in
2945 * @return string|bool New token value, or false if this option is disabled.
2946 * @see getTokenFromOption()
2947 * @see setOption()
2948 */
2949 public function resetTokenFromOption( $oname ) {
2950 global $wgHiddenPrefs;
2951 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2952 return false;
2953 }
2954
2955 $token = MWCryptRand::generateHex( 40 );
2956 $this->setOption( $oname, $token );
2957 return $token;
2958 }
2959
2960 /**
2961 * Return a list of the types of user options currently returned by
2962 * User::getOptionKinds().
2963 *
2964 * Currently, the option kinds are:
2965 * - 'registered' - preferences which are registered in core MediaWiki or
2966 * by extensions using the UserGetDefaultOptions hook.
2967 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2968 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2969 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2970 * be used by user scripts.
2971 * - 'special' - "preferences" that are not accessible via User::getOptions
2972 * or User::setOptions.
2973 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2974 * These are usually legacy options, removed in newer versions.
2975 *
2976 * The API (and possibly others) use this function to determine the possible
2977 * option types for validation purposes, so make sure to update this when a
2978 * new option kind is added.
2979 *
2980 * @see User::getOptionKinds
2981 * @return array Option kinds
2982 */
2983 public static function listOptionKinds() {
2984 return [
2985 'registered',
2986 'registered-multiselect',
2987 'registered-checkmatrix',
2988 'userjs',
2989 'special',
2990 'unused'
2991 ];
2992 }
2993
2994 /**
2995 * Return an associative array mapping preferences keys to the kind of a preference they're
2996 * used for. Different kinds are handled differently when setting or reading preferences.
2997 *
2998 * See User::listOptionKinds for the list of valid option types that can be provided.
2999 *
3000 * @see User::listOptionKinds
3001 * @param IContextSource $context
3002 * @param array $options Assoc. array with options keys to check as keys.
3003 * Defaults to $this->mOptions.
3004 * @return array The key => kind mapping data
3005 */
3006 public function getOptionKinds( IContextSource $context, $options = null ) {
3007 $this->loadOptions();
3008 if ( $options === null ) {
3009 $options = $this->mOptions;
3010 }
3011
3012 $prefs = Preferences::getPreferences( $this, $context );
3013 $mapping = [];
3014
3015 // Pull out the "special" options, so they don't get converted as
3016 // multiselect or checkmatrix.
3017 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
3018 foreach ( $specialOptions as $name => $value ) {
3019 unset( $prefs[$name] );
3020 }
3021
3022 // Multiselect and checkmatrix options are stored in the database with
3023 // one key per option, each having a boolean value. Extract those keys.
3024 $multiselectOptions = [];
3025 foreach ( $prefs as $name => $info ) {
3026 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
3027 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
3028 $opts = HTMLFormField::flattenOptions( $info['options'] );
3029 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
3030
3031 foreach ( $opts as $value ) {
3032 $multiselectOptions["$prefix$value"] = true;
3033 }
3034
3035 unset( $prefs[$name] );
3036 }
3037 }
3038 $checkmatrixOptions = [];
3039 foreach ( $prefs as $name => $info ) {
3040 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
3041 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
3042 $columns = HTMLFormField::flattenOptions( $info['columns'] );
3043 $rows = HTMLFormField::flattenOptions( $info['rows'] );
3044 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
3045
3046 foreach ( $columns as $column ) {
3047 foreach ( $rows as $row ) {
3048 $checkmatrixOptions["$prefix$column-$row"] = true;
3049 }
3050 }
3051
3052 unset( $prefs[$name] );
3053 }
3054 }
3055
3056 // $value is ignored
3057 foreach ( $options as $key => $value ) {
3058 if ( isset( $prefs[$key] ) ) {
3059 $mapping[$key] = 'registered';
3060 } elseif ( isset( $multiselectOptions[$key] ) ) {
3061 $mapping[$key] = 'registered-multiselect';
3062 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3063 $mapping[$key] = 'registered-checkmatrix';
3064 } elseif ( isset( $specialOptions[$key] ) ) {
3065 $mapping[$key] = 'special';
3066 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
3067 $mapping[$key] = 'userjs';
3068 } else {
3069 $mapping[$key] = 'unused';
3070 }
3071 }
3072
3073 return $mapping;
3074 }
3075
3076 /**
3077 * Reset certain (or all) options to the site defaults
3078 *
3079 * The optional parameter determines which kinds of preferences will be reset.
3080 * Supported values are everything that can be reported by getOptionKinds()
3081 * and 'all', which forces a reset of *all* preferences and overrides everything else.
3082 *
3083 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
3084 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
3085 * for backwards-compatibility.
3086 * @param IContextSource|null $context Context source used when $resetKinds
3087 * does not contain 'all', passed to getOptionKinds().
3088 * Defaults to RequestContext::getMain() when null.
3089 */
3090 public function resetOptions(
3091 $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
3092 IContextSource $context = null
3093 ) {
3094 $this->load();
3095 $defaultOptions = self::getDefaultOptions();
3096
3097 if ( !is_array( $resetKinds ) ) {
3098 $resetKinds = [ $resetKinds ];
3099 }
3100
3101 if ( in_array( 'all', $resetKinds ) ) {
3102 $newOptions = $defaultOptions;
3103 } else {
3104 if ( $context === null ) {
3105 $context = RequestContext::getMain();
3106 }
3107
3108 $optionKinds = $this->getOptionKinds( $context );
3109 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
3110 $newOptions = [];
3111
3112 // Use default values for the options that should be deleted, and
3113 // copy old values for the ones that shouldn't.
3114 foreach ( $this->mOptions as $key => $value ) {
3115 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3116 if ( array_key_exists( $key, $defaultOptions ) ) {
3117 $newOptions[$key] = $defaultOptions[$key];
3118 }
3119 } else {
3120 $newOptions[$key] = $value;
3121 }
3122 }
3123 }
3124
3125 Hooks::run( 'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions, $resetKinds ] );
3126
3127 $this->mOptions = $newOptions;
3128 $this->mOptionsLoaded = true;
3129 }
3130
3131 /**
3132 * Get the user's preferred date format.
3133 * @return string User's preferred date format
3134 */
3135 public function getDatePreference() {
3136 // Important migration for old data rows
3137 if ( is_null( $this->mDatePreference ) ) {
3138 global $wgLang;
3139 $value = $this->getOption( 'date' );
3140 $map = $wgLang->getDatePreferenceMigrationMap();
3141 if ( isset( $map[$value] ) ) {
3142 $value = $map[$value];
3143 }
3144 $this->mDatePreference = $value;
3145 }
3146 return $this->mDatePreference;
3147 }
3148
3149 /**
3150 * Determine based on the wiki configuration and the user's options,
3151 * whether this user must be over HTTPS no matter what.
3152 *
3153 * @return bool
3154 */
3155 public function requiresHTTPS() {
3156 global $wgSecureLogin;
3157 if ( !$wgSecureLogin ) {
3158 return false;
3159 } else {
3160 $https = $this->getBoolOption( 'prefershttps' );
3161 Hooks::run( 'UserRequiresHTTPS', [ $this, &$https ] );
3162 if ( $https ) {
3163 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
3164 }
3165 return $https;
3166 }
3167 }
3168
3169 /**
3170 * Get the user preferred stub threshold
3171 *
3172 * @return int
3173 */
3174 public function getStubThreshold() {
3175 global $wgMaxArticleSize; # Maximum article size, in Kb
3176 $threshold = $this->getIntOption( 'stubthreshold' );
3177 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3178 // If they have set an impossible value, disable the preference
3179 // so we can use the parser cache again.
3180 $threshold = 0;
3181 }
3182 return $threshold;
3183 }
3184
3185 /**
3186 * Get the permissions this user has.
3187 * @return array Array of String permission names
3188 */
3189 public function getRights() {
3190 if ( is_null( $this->mRights ) ) {
3191 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
3192 Hooks::run( 'UserGetRights', [ $this, &$this->mRights ] );
3193
3194 // Deny any rights denied by the user's session, unless this
3195 // endpoint has no sessions.
3196 if ( !defined( 'MW_NO_SESSION' ) ) {
3197 $allowedRights = $this->getRequest()->getSession()->getAllowedUserRights();
3198 if ( $allowedRights !== null ) {
3199 $this->mRights = array_intersect( $this->mRights, $allowedRights );
3200 }
3201 }
3202
3203 // Force reindexation of rights when a hook has unset one of them
3204 $this->mRights = array_values( array_unique( $this->mRights ) );
3205
3206 // If block disables login, we should also remove any
3207 // extra rights blocked users might have, in case the
3208 // blocked user has a pre-existing session (T129738).
3209 // This is checked here for cases where people only call
3210 // $user->isAllowed(). It is also checked in Title::checkUserBlock()
3211 // to give a better error message in the common case.
3212 $config = RequestContext::getMain()->getConfig();
3213 if (
3214 $this->isLoggedIn() &&
3215 $config->get( 'BlockDisablesLogin' ) &&
3216 $this->isBlocked()
3217 ) {
3218 $anon = new User;
3219 $this->mRights = array_intersect( $this->mRights, $anon->getRights() );
3220 }
3221 }
3222 return $this->mRights;
3223 }
3224
3225 /**
3226 * Get the list of explicit group memberships this user has.
3227 * The implicit * and user groups are not included.
3228 * @return array Array of String internal group names
3229 */
3230 public function getGroups() {
3231 $this->load();
3232 $this->loadGroups();
3233 return $this->mGroups;
3234 }
3235
3236 /**
3237 * Get the list of implicit group memberships this user has.
3238 * This includes all explicit groups, plus 'user' if logged in,
3239 * '*' for all accounts, and autopromoted groups
3240 * @param bool $recache Whether to avoid the cache
3241 * @return array Array of String internal group names
3242 */
3243 public function getEffectiveGroups( $recache = false ) {
3244 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
3245 $this->mEffectiveGroups = array_unique( array_merge(
3246 $this->getGroups(), // explicit groups
3247 $this->getAutomaticGroups( $recache ) // implicit groups
3248 ) );
3249 // Hook for additional groups
3250 Hooks::run( 'UserEffectiveGroups', [ &$this, &$this->mEffectiveGroups ] );
3251 // Force reindexation of groups when a hook has unset one of them
3252 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
3253 }
3254 return $this->mEffectiveGroups;
3255 }
3256
3257 /**
3258 * Get the list of implicit group memberships this user has.
3259 * This includes 'user' if logged in, '*' for all accounts,
3260 * and autopromoted groups
3261 * @param bool $recache Whether to avoid the cache
3262 * @return array Array of String internal group names
3263 */
3264 public function getAutomaticGroups( $recache = false ) {
3265 if ( $recache || is_null( $this->mImplicitGroups ) ) {
3266 $this->mImplicitGroups = [ '*' ];
3267 if ( $this->getId() ) {
3268 $this->mImplicitGroups[] = 'user';
3269
3270 $this->mImplicitGroups = array_unique( array_merge(
3271 $this->mImplicitGroups,
3272 Autopromote::getAutopromoteGroups( $this )
3273 ) );
3274 }
3275 if ( $recache ) {
3276 // Assure data consistency with rights/groups,
3277 // as getEffectiveGroups() depends on this function
3278 $this->mEffectiveGroups = null;
3279 }
3280 }
3281 return $this->mImplicitGroups;
3282 }
3283
3284 /**
3285 * Returns the groups the user has belonged to.
3286 *
3287 * The user may still belong to the returned groups. Compare with getGroups().
3288 *
3289 * The function will not return groups the user had belonged to before MW 1.17
3290 *
3291 * @return array Names of the groups the user has belonged to.
3292 */
3293 public function getFormerGroups() {
3294 $this->load();
3295
3296 if ( is_null( $this->mFormerGroups ) ) {
3297 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
3298 ? wfGetDB( DB_MASTER )
3299 : wfGetDB( DB_REPLICA );
3300 $res = $db->select( 'user_former_groups',
3301 [ 'ufg_group' ],
3302 [ 'ufg_user' => $this->mId ],
3303 __METHOD__ );
3304 $this->mFormerGroups = [];
3305 foreach ( $res as $row ) {
3306 $this->mFormerGroups[] = $row->ufg_group;
3307 }
3308 }
3309
3310 return $this->mFormerGroups;
3311 }
3312
3313 /**
3314 * Get the user's edit count.
3315 * @return int|null Null for anonymous users
3316 */
3317 public function getEditCount() {
3318 if ( !$this->getId() ) {
3319 return null;
3320 }
3321
3322 if ( $this->mEditCount === null ) {
3323 /* Populate the count, if it has not been populated yet */
3324 $dbr = wfGetDB( DB_REPLICA );
3325 // check if the user_editcount field has been initialized
3326 $count = $dbr->selectField(
3327 'user', 'user_editcount',
3328 [ 'user_id' => $this->mId ],
3329 __METHOD__
3330 );
3331
3332 if ( $count === null ) {
3333 // it has not been initialized. do so.
3334 $count = $this->initEditCount();
3335 }
3336 $this->mEditCount = $count;
3337 }
3338 return (int)$this->mEditCount;
3339 }
3340
3341 /**
3342 * Add the user to the given group.
3343 * This takes immediate effect.
3344 * @param string $group Name of the group to add
3345 * @return bool
3346 */
3347 public function addGroup( $group ) {
3348 $this->load();
3349
3350 if ( !Hooks::run( 'UserAddGroup', [ $this, &$group ] ) ) {
3351 return false;
3352 }
3353
3354 $dbw = wfGetDB( DB_MASTER );
3355 if ( $this->getId() ) {
3356 $dbw->insert( 'user_groups',
3357 [
3358 'ug_user' => $this->getId(),
3359 'ug_group' => $group,
3360 ],
3361 __METHOD__,
3362 [ 'IGNORE' ] );
3363 }
3364
3365 $this->loadGroups();
3366 $this->mGroups[] = $group;
3367 // In case loadGroups was not called before, we now have the right twice.
3368 // Get rid of the duplicate.
3369 $this->mGroups = array_unique( $this->mGroups );
3370
3371 // Refresh the groups caches, and clear the rights cache so it will be
3372 // refreshed on the next call to $this->getRights().
3373 $this->getEffectiveGroups( true );
3374 $this->mRights = null;
3375
3376 $this->invalidateCache();
3377
3378 return true;
3379 }
3380
3381 /**
3382 * Remove the user from the given group.
3383 * This takes immediate effect.
3384 * @param string $group Name of the group to remove
3385 * @return bool
3386 */
3387 public function removeGroup( $group ) {
3388 $this->load();
3389 if ( !Hooks::run( 'UserRemoveGroup', [ $this, &$group ] ) ) {
3390 return false;
3391 }
3392
3393 $dbw = wfGetDB( DB_MASTER );
3394 $dbw->delete( 'user_groups',
3395 [
3396 'ug_user' => $this->getId(),
3397 'ug_group' => $group,
3398 ], __METHOD__
3399 );
3400 // Remember that the user was in this group
3401 $dbw->insert( 'user_former_groups',
3402 [
3403 'ufg_user' => $this->getId(),
3404 'ufg_group' => $group,
3405 ],
3406 __METHOD__,
3407 [ 'IGNORE' ]
3408 );
3409
3410 $this->loadGroups();
3411 $this->mGroups = array_diff( $this->mGroups, [ $group ] );
3412
3413 // Refresh the groups caches, and clear the rights cache so it will be
3414 // refreshed on the next call to $this->getRights().
3415 $this->getEffectiveGroups( true );
3416 $this->mRights = null;
3417
3418 $this->invalidateCache();
3419
3420 return true;
3421 }
3422
3423 /**
3424 * Get whether the user is logged in
3425 * @return bool
3426 */
3427 public function isLoggedIn() {
3428 return $this->getId() != 0;
3429 }
3430
3431 /**
3432 * Get whether the user is anonymous
3433 * @return bool
3434 */
3435 public function isAnon() {
3436 return !$this->isLoggedIn();
3437 }
3438
3439 /**
3440 * @return bool Whether this user is flagged as being a bot role account
3441 * @since 1.28
3442 */
3443 public function isBot() {
3444 if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3445 return true;
3446 }
3447
3448 $isBot = false;
3449 Hooks::run( "UserIsBot", [ $this, &$isBot ] );
3450
3451 return $isBot;
3452 }
3453
3454 /**
3455 * Check if user is allowed to access a feature / make an action
3456 *
3457 * @param string ... Permissions to test
3458 * @return bool True if user is allowed to perform *any* of the given actions
3459 */
3460 public function isAllowedAny() {
3461 $permissions = func_get_args();
3462 foreach ( $permissions as $permission ) {
3463 if ( $this->isAllowed( $permission ) ) {
3464 return true;
3465 }
3466 }
3467 return false;
3468 }
3469
3470 /**
3471 *
3472 * @param string ... Permissions to test
3473 * @return bool True if the user is allowed to perform *all* of the given actions
3474 */
3475 public function isAllowedAll() {
3476 $permissions = func_get_args();
3477 foreach ( $permissions as $permission ) {
3478 if ( !$this->isAllowed( $permission ) ) {
3479 return false;
3480 }
3481 }
3482 return true;
3483 }
3484
3485 /**
3486 * Internal mechanics of testing a permission
3487 * @param string $action
3488 * @return bool
3489 */
3490 public function isAllowed( $action = '' ) {
3491 if ( $action === '' ) {
3492 return true; // In the spirit of DWIM
3493 }
3494 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3495 // by misconfiguration: 0 == 'foo'
3496 return in_array( $action, $this->getRights(), true );
3497 }
3498
3499 /**
3500 * Check whether to enable recent changes patrol features for this user
3501 * @return bool True or false
3502 */
3503 public function useRCPatrol() {
3504 global $wgUseRCPatrol;
3505 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3506 }
3507
3508 /**
3509 * Check whether to enable new pages patrol features for this user
3510 * @return bool True or false
3511 */
3512 public function useNPPatrol() {
3513 global $wgUseRCPatrol, $wgUseNPPatrol;
3514 return (
3515 ( $wgUseRCPatrol || $wgUseNPPatrol )
3516 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3517 );
3518 }
3519
3520 /**
3521 * Check whether to enable new files patrol features for this user
3522 * @return bool True or false
3523 */
3524 public function useFilePatrol() {
3525 global $wgUseRCPatrol, $wgUseFilePatrol;
3526 return (
3527 ( $wgUseRCPatrol || $wgUseFilePatrol )
3528 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3529 );
3530 }
3531
3532 /**
3533 * Get the WebRequest object to use with this object
3534 *
3535 * @return WebRequest
3536 */
3537 public function getRequest() {
3538 if ( $this->mRequest ) {
3539 return $this->mRequest;
3540 } else {
3541 global $wgRequest;
3542 return $wgRequest;
3543 }
3544 }
3545
3546 /**
3547 * Check the watched status of an article.
3548 * @since 1.22 $checkRights parameter added
3549 * @param Title $title Title of the article to look at
3550 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3551 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3552 * @return bool
3553 */
3554 public function isWatched( $title, $checkRights = self::CHECK_USER_RIGHTS ) {
3555 if ( $title->isWatchable() && ( !$checkRights || $this->isAllowed( 'viewmywatchlist' ) ) ) {
3556 return MediaWikiServices::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3557 }
3558 return false;
3559 }
3560
3561 /**
3562 * Watch an article.
3563 * @since 1.22 $checkRights parameter added
3564 * @param Title $title Title of the article to look at
3565 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3566 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3567 */
3568 public function addWatch( $title, $checkRights = self::CHECK_USER_RIGHTS ) {
3569 if ( !$checkRights || $this->isAllowed( 'editmywatchlist' ) ) {
3570 MediaWikiServices::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3571 $this,
3572 [ $title->getSubjectPage(), $title->getTalkPage() ]
3573 );
3574 }
3575 $this->invalidateCache();
3576 }
3577
3578 /**
3579 * Stop watching an article.
3580 * @since 1.22 $checkRights parameter added
3581 * @param Title $title Title of the article to look at
3582 * @param bool $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3583 * Pass User::CHECK_USER_RIGHTS or User::IGNORE_USER_RIGHTS.
3584 */
3585 public function removeWatch( $title, $checkRights = self::CHECK_USER_RIGHTS ) {
3586 if ( !$checkRights || $this->isAllowed( 'editmywatchlist' ) ) {
3587 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
3588 $store->removeWatch( $this, $title->getSubjectPage() );
3589 $store->removeWatch( $this, $title->getTalkPage() );
3590 }
3591 $this->invalidateCache();
3592 }
3593
3594 /**
3595 * Clear the user's notification timestamp for the given title.
3596 * If e-notif e-mails are on, they will receive notification mails on
3597 * the next change of the page if it's watched etc.
3598 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3599 * @param Title $title Title of the article to look at
3600 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3601 */
3602 public function clearNotification( &$title, $oldid = 0 ) {
3603 global $wgUseEnotif, $wgShowUpdatedMarker;
3604
3605 // Do nothing if the database is locked to writes
3606 if ( wfReadOnly() ) {
3607 return;
3608 }
3609
3610 // Do nothing if not allowed to edit the watchlist
3611 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3612 return;
3613 }
3614
3615 // If we're working on user's talk page, we should update the talk page message indicator
3616 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3617 if ( !Hooks::run( 'UserClearNewTalkNotification', [ &$this, $oldid ] ) ) {
3618 return;
3619 }
3620
3621 // Try to update the DB post-send and only if needed...
3622 DeferredUpdates::addCallableUpdate( function() use ( $title, $oldid ) {
3623 if ( !$this->getNewtalk() ) {
3624 return; // no notifications to clear
3625 }
3626
3627 // Delete the last notifications (they stack up)
3628 $this->setNewtalk( false );
3629
3630 // If there is a new, unseen, revision, use its timestamp
3631 $nextid = $oldid
3632 ? $title->getNextRevisionID( $oldid, Title::GAID_FOR_UPDATE )
3633 : null;
3634 if ( $nextid ) {
3635 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3636 }
3637 } );
3638 }
3639
3640 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3641 return;
3642 }
3643
3644 if ( $this->isAnon() ) {
3645 // Nothing else to do...
3646 return;
3647 }
3648
3649 // Only update the timestamp if the page is being watched.
3650 // The query to find out if it is watched is cached both in memcached and per-invocation,
3651 // and when it does have to be executed, it can be on a replica DB
3652 // If this is the user's newtalk page, we always update the timestamp
3653 $force = '';
3654 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3655 $force = 'force';
3656 }
3657
3658 MediaWikiServices::getInstance()->getWatchedItemStore()
3659 ->resetNotificationTimestamp( $this, $title, $force, $oldid );
3660 }
3661
3662 /**
3663 * Resets all of the given user's page-change notification timestamps.
3664 * If e-notif e-mails are on, they will receive notification mails on
3665 * the next change of any watched page.
3666 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3667 */
3668 public function clearAllNotifications() {
3669 global $wgUseEnotif, $wgShowUpdatedMarker;
3670 // Do nothing if not allowed to edit the watchlist
3671 if ( wfReadOnly() || !$this->isAllowed( 'editmywatchlist' ) ) {
3672 return;
3673 }
3674
3675 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3676 $this->setNewtalk( false );
3677 return;
3678 }
3679
3680 $id = $this->getId();
3681 if ( !$id ) {
3682 return;
3683 }
3684
3685 $dbw = wfGetDB( DB_MASTER );
3686 $asOfTimes = array_unique( $dbw->selectFieldValues(
3687 'watchlist',
3688 'wl_notificationtimestamp',
3689 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3690 __METHOD__,
3691 [ 'ORDER BY' => 'wl_notificationtimestamp DESC', 'LIMIT' => 500 ]
3692 ) );
3693 if ( !$asOfTimes ) {
3694 return;
3695 }
3696 // Immediately update the most recent touched rows, which hopefully covers what
3697 // the user sees on the watchlist page before pressing "mark all pages visited"....
3698 $dbw->update(
3699 'watchlist',
3700 [ 'wl_notificationtimestamp' => null ],
3701 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimes ],
3702 __METHOD__
3703 );
3704 // ...and finish the older ones in a post-send update with lag checks...
3705 DeferredUpdates::addUpdate( new AutoCommitUpdate(
3706 $dbw,
3707 __METHOD__,
3708 function () use ( $dbw, $id ) {
3709 global $wgUpdateRowsPerQuery;
3710
3711 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
3712 $ticket = $lbFactory->getEmptyTransactionTicket( __METHOD__ );
3713 $asOfTimes = array_unique( $dbw->selectFieldValues(
3714 'watchlist',
3715 'wl_notificationtimestamp',
3716 [ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ],
3717 __METHOD__
3718 ) );
3719 foreach ( array_chunk( $asOfTimes, $wgUpdateRowsPerQuery ) as $asOfTimeBatch ) {
3720 $dbw->update(
3721 'watchlist',
3722 [ 'wl_notificationtimestamp' => null ],
3723 [ 'wl_user' => $id, 'wl_notificationtimestamp' => $asOfTimeBatch ],
3724 __METHOD__
3725 );
3726 $lbFactory->commitAndWaitForReplication( __METHOD__, $ticket );
3727 }
3728 }
3729 ) );
3730 // We also need to clear here the "you have new message" notification for the own
3731 // user_talk page; it's cleared one page view later in WikiPage::doViewUpdates().
3732 }
3733
3734 /**
3735 * Set a cookie on the user's client. Wrapper for
3736 * WebResponse::setCookie
3737 * @deprecated since 1.27
3738 * @param string $name Name of the cookie to set
3739 * @param string $value Value to set
3740 * @param int $exp Expiration time, as a UNIX time value;
3741 * if 0 or not specified, use the default $wgCookieExpiration
3742 * @param bool $secure
3743 * true: Force setting the secure attribute when setting the cookie
3744 * false: Force NOT setting the secure attribute when setting the cookie
3745 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3746 * @param array $params Array of options sent passed to WebResponse::setcookie()
3747 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3748 * is passed.
3749 */
3750 protected function setCookie(
3751 $name, $value, $exp = 0, $secure = null, $params = [], $request = null
3752 ) {
3753 wfDeprecated( __METHOD__, '1.27' );
3754 if ( $request === null ) {
3755 $request = $this->getRequest();
3756 }
3757 $params['secure'] = $secure;
3758 $request->response()->setCookie( $name, $value, $exp, $params );
3759 }
3760
3761 /**
3762 * Clear a cookie on the user's client
3763 * @deprecated since 1.27
3764 * @param string $name Name of the cookie to clear
3765 * @param bool $secure
3766 * true: Force setting the secure attribute when setting the cookie
3767 * false: Force NOT setting the secure attribute when setting the cookie
3768 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3769 * @param array $params Array of options sent passed to WebResponse::setcookie()
3770 */
3771 protected function clearCookie( $name, $secure = null, $params = [] ) {
3772 wfDeprecated( __METHOD__, '1.27' );
3773 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3774 }
3775
3776 /**
3777 * Set an extended login cookie on the user's client. The expiry of the cookie
3778 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3779 * variable.
3780 *
3781 * @see User::setCookie
3782 *
3783 * @deprecated since 1.27
3784 * @param string $name Name of the cookie to set
3785 * @param string $value Value to set
3786 * @param bool $secure
3787 * true: Force setting the secure attribute when setting the cookie
3788 * false: Force NOT setting the secure attribute when setting the cookie
3789 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3790 */
3791 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3792 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3793
3794 wfDeprecated( __METHOD__, '1.27' );
3795
3796 $exp = time();
3797 $exp += $wgExtendedLoginCookieExpiration !== null
3798 ? $wgExtendedLoginCookieExpiration
3799 : $wgCookieExpiration;
3800
3801 $this->setCookie( $name, $value, $exp, $secure );
3802 }
3803
3804 /**
3805 * Persist this user's session (e.g. set cookies)
3806 *
3807 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3808 * is passed.
3809 * @param bool $secure Whether to force secure/insecure cookies or use default
3810 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3811 */
3812 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3813 $this->load();
3814 if ( 0 == $this->mId ) {
3815 return;
3816 }
3817
3818 $session = $this->getRequest()->getSession();
3819 if ( $request && $session->getRequest() !== $request ) {
3820 $session = $session->sessionWithRequest( $request );
3821 }
3822 $delay = $session->delaySave();
3823
3824 if ( !$session->getUser()->equals( $this ) ) {
3825 if ( !$session->canSetUser() ) {
3826 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3827 ->warning( __METHOD__ .
3828 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3829 );
3830 return;
3831 }
3832 $session->setUser( $this );
3833 }
3834
3835 $session->setRememberUser( $rememberMe );
3836 if ( $secure !== null ) {
3837 $session->setForceHTTPS( $secure );
3838 }
3839
3840 $session->persist();
3841
3842 ScopedCallback::consume( $delay );
3843 }
3844
3845 /**
3846 * Log this user out.
3847 */
3848 public function logout() {
3849 if ( Hooks::run( 'UserLogout', [ &$this ] ) ) {
3850 $this->doLogout();
3851 }
3852 }
3853
3854 /**
3855 * Clear the user's session, and reset the instance cache.
3856 * @see logout()
3857 */
3858 public function doLogout() {
3859 $session = $this->getRequest()->getSession();
3860 if ( !$session->canSetUser() ) {
3861 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3862 ->warning( __METHOD__ . ": Cannot log out of an immutable session" );
3863 $error = 'immutable';
3864 } elseif ( !$session->getUser()->equals( $this ) ) {
3865 \MediaWiki\Logger\LoggerFactory::getInstance( 'session' )
3866 ->warning( __METHOD__ .
3867 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3868 );
3869 // But we still may as well make this user object anon
3870 $this->clearInstanceCache( 'defaults' );
3871 $error = 'wronguser';
3872 } else {
3873 $this->clearInstanceCache( 'defaults' );
3874 $delay = $session->delaySave();
3875 $session->unpersist(); // Clear cookies (T127436)
3876 $session->setLoggedOutTimestamp( time() );
3877 $session->setUser( new User );
3878 $session->set( 'wsUserID', 0 ); // Other code expects this
3879 $session->resetAllTokens();
3880 ScopedCallback::consume( $delay );
3881 $error = false;
3882 }
3883 \MediaWiki\Logger\LoggerFactory::getInstance( 'authevents' )->info( 'Logout', [
3884 'event' => 'logout',
3885 'successful' => $error === false,
3886 'status' => $error ?: 'success',
3887 ] );
3888 }
3889
3890 /**
3891 * Save this user's settings into the database.
3892 * @todo Only rarely do all these fields need to be set!
3893 */
3894 public function saveSettings() {
3895 if ( wfReadOnly() ) {
3896 // @TODO: caller should deal with this instead!
3897 // This should really just be an exception.
3898 MWExceptionHandler::logException( new DBExpectedError(
3899 null,
3900 "Could not update user with ID '{$this->mId}'; DB is read-only."
3901 ) );
3902 return;
3903 }
3904
3905 $this->load();
3906 if ( 0 == $this->mId ) {
3907 return; // anon
3908 }
3909
3910 // Get a new user_touched that is higher than the old one.
3911 // This will be used for a CAS check as a last-resort safety
3912 // check against race conditions and replica DB lag.
3913 $newTouched = $this->newTouchedTimestamp();
3914
3915 $dbw = wfGetDB( DB_MASTER );
3916 $dbw->update( 'user',
3917 [ /* SET */
3918 'user_name' => $this->mName,
3919 'user_real_name' => $this->mRealName,
3920 'user_email' => $this->mEmail,
3921 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3922 'user_touched' => $dbw->timestamp( $newTouched ),
3923 'user_token' => strval( $this->mToken ),
3924 'user_email_token' => $this->mEmailToken,
3925 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3926 ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3927 'user_id' => $this->mId,
3928 ] ), __METHOD__
3929 );
3930
3931 if ( !$dbw->affectedRows() ) {
3932 // Maybe the problem was a missed cache update; clear it to be safe
3933 $this->clearSharedCache( 'refresh' );
3934 // User was changed in the meantime or loaded with stale data
3935 $from = ( $this->queryFlagsUsed & self::READ_LATEST ) ? 'master' : 'replica';
3936 throw new MWException(
3937 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3938 " the version of the user to be saved is older than the current version."
3939 );
3940 }
3941
3942 $this->mTouched = $newTouched;
3943 $this->saveOptions();
3944
3945 Hooks::run( 'UserSaveSettings', [ $this ] );
3946 $this->clearSharedCache();
3947 $this->getUserPage()->invalidateCache();
3948 }
3949
3950 /**
3951 * If only this user's username is known, and it exists, return the user ID.
3952 *
3953 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3954 * @return int
3955 */
3956 public function idForName( $flags = 0 ) {
3957 $s = trim( $this->getName() );
3958 if ( $s === '' ) {
3959 return 0;
3960 }
3961
3962 $db = ( ( $flags & self::READ_LATEST ) == self::READ_LATEST )
3963 ? wfGetDB( DB_MASTER )
3964 : wfGetDB( DB_REPLICA );
3965
3966 $options = ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING )
3967 ? [ 'LOCK IN SHARE MODE' ]
3968 : [];
3969
3970 $id = $db->selectField( 'user',
3971 'user_id', [ 'user_name' => $s ], __METHOD__, $options );
3972
3973 return (int)$id;
3974 }
3975
3976 /**
3977 * Add a user to the database, return the user object
3978 *
3979 * @param string $name Username to add
3980 * @param array $params Array of Strings Non-default parameters to save to
3981 * the database as user_* fields:
3982 * - email: The user's email address.
3983 * - email_authenticated: The email authentication timestamp.
3984 * - real_name: The user's real name.
3985 * - options: An associative array of non-default options.
3986 * - token: Random authentication token. Do not set.
3987 * - registration: Registration timestamp. Do not set.
3988 *
3989 * @return User|null User object, or null if the username already exists.
3990 */
3991 public static function createNew( $name, $params = [] ) {
3992 foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3993 if ( isset( $params[$field] ) ) {
3994 wfDeprecated( __METHOD__ . " with param '$field'", '1.27' );
3995 unset( $params[$field] );
3996 }
3997 }
3998
3999 $user = new User;
4000 $user->load();
4001 $user->setToken(); // init token
4002 if ( isset( $params['options'] ) ) {
4003 $user->mOptions = $params['options'] + (array)$user->mOptions;
4004 unset( $params['options'] );
4005 }
4006 $dbw = wfGetDB( DB_MASTER );
4007 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4008
4009 $noPass = PasswordFactory::newInvalidPassword()->toString();
4010
4011 $fields = [
4012 'user_id' => $seqVal,
4013 'user_name' => $name,
4014 'user_password' => $noPass,
4015 'user_newpassword' => $noPass,
4016 'user_email' => $user->mEmail,
4017 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
4018 'user_real_name' => $user->mRealName,
4019 'user_token' => strval( $user->mToken ),
4020 'user_registration' => $dbw->timestamp( $user->mRegistration ),
4021 'user_editcount' => 0,
4022 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
4023 ];
4024 foreach ( $params as $name => $value ) {
4025 $fields["user_$name"] = $value;
4026 }
4027 $dbw->insert( 'user', $fields, __METHOD__, [ 'IGNORE' ] );
4028 if ( $dbw->affectedRows() ) {
4029 $newUser = User::newFromId( $dbw->insertId() );
4030 } else {
4031 $newUser = null;
4032 }
4033 return $newUser;
4034 }
4035
4036 /**
4037 * Add this existing user object to the database. If the user already
4038 * exists, a fatal status object is returned, and the user object is
4039 * initialised with the data from the database.
4040 *
4041 * Previously, this function generated a DB error due to a key conflict
4042 * if the user already existed. Many extension callers use this function
4043 * in code along the lines of:
4044 *
4045 * $user = User::newFromName( $name );
4046 * if ( !$user->isLoggedIn() ) {
4047 * $user->addToDatabase();
4048 * }
4049 * // do something with $user...
4050 *
4051 * However, this was vulnerable to a race condition (bug 16020). By
4052 * initialising the user object if the user exists, we aim to support this
4053 * calling sequence as far as possible.
4054 *
4055 * Note that if the user exists, this function will acquire a write lock,
4056 * so it is still advisable to make the call conditional on isLoggedIn(),
4057 * and to commit the transaction after calling.
4058 *
4059 * @throws MWException
4060 * @return Status
4061 */
4062 public function addToDatabase() {
4063 $this->load();
4064 if ( !$this->mToken ) {
4065 $this->setToken(); // init token
4066 }
4067
4068 $this->mTouched = $this->newTouchedTimestamp();
4069
4070 $noPass = PasswordFactory::newInvalidPassword()->toString();
4071
4072 $dbw = wfGetDB( DB_MASTER );
4073 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
4074 $dbw->insert( 'user',
4075 [
4076 'user_id' => $seqVal,
4077 'user_name' => $this->mName,
4078 'user_password' => $noPass,
4079 'user_newpassword' => $noPass,
4080 'user_email' => $this->mEmail,
4081 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
4082 'user_real_name' => $this->mRealName,
4083 'user_token' => strval( $this->mToken ),
4084 'user_registration' => $dbw->timestamp( $this->mRegistration ),
4085 'user_editcount' => 0,
4086 'user_touched' => $dbw->timestamp( $this->mTouched ),
4087 ], __METHOD__,
4088 [ 'IGNORE' ]
4089 );
4090 if ( !$dbw->affectedRows() ) {
4091 // Use locking reads to bypass any REPEATABLE-READ snapshot.
4092 $this->mId = $dbw->selectField(
4093 'user',
4094 'user_id',
4095 [ 'user_name' => $this->mName ],
4096 __METHOD__,
4097 [ 'LOCK IN SHARE MODE' ]
4098 );
4099 $loaded = false;
4100 if ( $this->mId ) {
4101 if ( $this->loadFromDatabase( self::READ_LOCKING ) ) {
4102 $loaded = true;
4103 }
4104 }
4105 if ( !$loaded ) {
4106 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
4107 "to insert user '{$this->mName}' row, but it was not present in select!" );
4108 }
4109 return Status::newFatal( 'userexists' );
4110 }
4111 $this->mId = $dbw->insertId();
4112 self::$idCacheByName[$this->mName] = $this->mId;
4113
4114 // Clear instance cache other than user table data, which is already accurate
4115 $this->clearInstanceCache();
4116
4117 $this->saveOptions();
4118 return Status::newGood();
4119 }
4120
4121 /**
4122 * If this user is logged-in and blocked,
4123 * block any IP address they've successfully logged in from.
4124 * @return bool A block was spread
4125 */
4126 public function spreadAnyEditBlock() {
4127 if ( $this->isLoggedIn() && $this->isBlocked() ) {
4128 return $this->spreadBlock();
4129 }
4130
4131 return false;
4132 }
4133
4134 /**
4135 * If this (non-anonymous) user is blocked,
4136 * block the IP address they've successfully logged in from.
4137 * @return bool A block was spread
4138 */
4139 protected function spreadBlock() {
4140 wfDebug( __METHOD__ . "()\n" );
4141 $this->load();
4142 if ( $this->mId == 0 ) {
4143 return false;
4144 }
4145
4146 $userblock = Block::newFromTarget( $this->getName() );
4147 if ( !$userblock ) {
4148 return false;
4149 }
4150
4151 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
4152 }
4153
4154 /**
4155 * Get whether the user is explicitly blocked from account creation.
4156 * @return bool|Block
4157 */
4158 public function isBlockedFromCreateAccount() {
4159 $this->getBlockedStatus();
4160 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
4161 return $this->mBlock;
4162 }
4163
4164 # bug 13611: if the IP address the user is trying to create an account from is
4165 # blocked with createaccount disabled, prevent new account creation there even
4166 # when the user is logged in
4167 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
4168 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
4169 }
4170 return $this->mBlockedFromCreateAccount instanceof Block
4171 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
4172 ? $this->mBlockedFromCreateAccount
4173 : false;
4174 }
4175
4176 /**
4177 * Get whether the user is blocked from using Special:Emailuser.
4178 * @return bool
4179 */
4180 public function isBlockedFromEmailuser() {
4181 $this->getBlockedStatus();
4182 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
4183 }
4184
4185 /**
4186 * Get whether the user is allowed to create an account.
4187 * @return bool
4188 */
4189 public function isAllowedToCreateAccount() {
4190 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
4191 }
4192
4193 /**
4194 * Get this user's personal page title.
4195 *
4196 * @return Title User's personal page title
4197 */
4198 public function getUserPage() {
4199 return Title::makeTitle( NS_USER, $this->getName() );
4200 }
4201
4202 /**
4203 * Get this user's talk page title.
4204 *
4205 * @return Title User's talk page title
4206 */
4207 public function getTalkPage() {
4208 $title = $this->getUserPage();
4209 return $title->getTalkPage();
4210 }
4211
4212 /**
4213 * Determine whether the user is a newbie. Newbies are either
4214 * anonymous IPs, or the most recently created accounts.
4215 * @return bool
4216 */
4217 public function isNewbie() {
4218 return !$this->isAllowed( 'autoconfirmed' );
4219 }
4220
4221 /**
4222 * Check to see if the given clear-text password is one of the accepted passwords
4223 * @deprecated since 1.27, use AuthManager instead
4224 * @param string $password User password
4225 * @return bool True if the given password is correct, otherwise False
4226 */
4227 public function checkPassword( $password ) {
4228 $manager = AuthManager::singleton();
4229 $reqs = AuthenticationRequest::loadRequestsFromSubmission(
4230 $manager->getAuthenticationRequests( AuthManager::ACTION_LOGIN ),
4231 [
4232 'username' => $this->getName(),
4233 'password' => $password,
4234 ]
4235 );
4236 $res = AuthManager::singleton()->beginAuthentication( $reqs, 'null:' );
4237 switch ( $res->status ) {
4238 case AuthenticationResponse::PASS:
4239 return true;
4240 case AuthenticationResponse::FAIL:
4241 // Hope it's not a PreAuthenticationProvider that failed...
4242 \MediaWiki\Logger\LoggerFactory::getInstance( 'authentication' )
4243 ->info( __METHOD__ . ': Authentication failed: ' . $res->message->plain() );
4244 return false;
4245 default:
4246 throw new BadMethodCallException(
4247 'AuthManager returned a response unsupported by ' . __METHOD__
4248 );
4249 }
4250 }
4251
4252 /**
4253 * Check if the given clear-text password matches the temporary password
4254 * sent by e-mail for password reset operations.
4255 *
4256 * @deprecated since 1.27, use AuthManager instead
4257 * @param string $plaintext
4258 * @return bool True if matches, false otherwise
4259 */
4260 public function checkTemporaryPassword( $plaintext ) {
4261 // Can't check the temporary password individually.
4262 return $this->checkPassword( $plaintext );
4263 }
4264
4265 /**
4266 * Initialize (if necessary) and return a session token value
4267 * which can be used in edit forms to show that the user's
4268 * login credentials aren't being hijacked with a foreign form
4269 * submission.
4270 *
4271 * @since 1.27
4272 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4273 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4274 * @return MediaWiki\Session\Token The new edit token
4275 */
4276 public function getEditTokenObject( $salt = '', $request = null ) {
4277 if ( $this->isAnon() ) {
4278 return new LoggedOutEditToken();
4279 }
4280
4281 if ( !$request ) {
4282 $request = $this->getRequest();
4283 }
4284 return $request->getSession()->getToken( $salt );
4285 }
4286
4287 /**
4288 * Initialize (if necessary) and return a session token value
4289 * which can be used in edit forms to show that the user's
4290 * login credentials aren't being hijacked with a foreign form
4291 * submission.
4292 *
4293 * The $salt for 'edit' and 'csrf' tokens is the default (empty string).
4294 *
4295 * @since 1.19
4296 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4297 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4298 * @return string The new edit token
4299 */
4300 public function getEditToken( $salt = '', $request = null ) {
4301 return $this->getEditTokenObject( $salt, $request )->toString();
4302 }
4303
4304 /**
4305 * Get the embedded timestamp from a token.
4306 * @deprecated since 1.27, use \MediaWiki\Session\Token::getTimestamp instead.
4307 * @param string $val Input token
4308 * @return int|null
4309 */
4310 public static function getEditTokenTimestamp( $val ) {
4311 wfDeprecated( __METHOD__, '1.27' );
4312 return MediaWiki\Session\Token::getTimestamp( $val );
4313 }
4314
4315 /**
4316 * Check given value against the token value stored in the session.
4317 * A match should confirm that the form was submitted from the
4318 * user's own login session, not a form submission from a third-party
4319 * site.
4320 *
4321 * @param string $val Input value to compare
4322 * @param string $salt Optional function-specific data for hashing
4323 * @param WebRequest|null $request Object to use or null to use $wgRequest
4324 * @param int $maxage Fail tokens older than this, in seconds
4325 * @return bool Whether the token matches
4326 */
4327 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4328 return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
4329 }
4330
4331 /**
4332 * Check given value against the token value stored in the session,
4333 * ignoring the suffix.
4334 *
4335 * @param string $val Input value to compare
4336 * @param string $salt Optional function-specific data for hashing
4337 * @param WebRequest|null $request Object to use or null to use $wgRequest
4338 * @param int $maxage Fail tokens older than this, in seconds
4339 * @return bool Whether the token matches
4340 */
4341 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4342 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token::SUFFIX;
4343 return $this->matchEditToken( $val, $salt, $request, $maxage );
4344 }
4345
4346 /**
4347 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4348 * mail to the user's given address.
4349 *
4350 * @param string $type Message to send, either "created", "changed" or "set"
4351 * @return Status
4352 */
4353 public function sendConfirmationMail( $type = 'created' ) {
4354 global $wgLang;
4355 $expiration = null; // gets passed-by-ref and defined in next line.
4356 $token = $this->confirmationToken( $expiration );
4357 $url = $this->confirmationTokenUrl( $token );
4358 $invalidateURL = $this->invalidationTokenUrl( $token );
4359 $this->saveSettings();
4360
4361 if ( $type == 'created' || $type === false ) {
4362 $message = 'confirmemail_body';
4363 } elseif ( $type === true ) {
4364 $message = 'confirmemail_body_changed';
4365 } else {
4366 // Messages: confirmemail_body_changed, confirmemail_body_set
4367 $message = 'confirmemail_body_' . $type;
4368 }
4369
4370 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4371 wfMessage( $message,
4372 $this->getRequest()->getIP(),
4373 $this->getName(),
4374 $url,
4375 $wgLang->userTimeAndDate( $expiration, $this ),
4376 $invalidateURL,
4377 $wgLang->userDate( $expiration, $this ),
4378 $wgLang->userTime( $expiration, $this ) )->text() );
4379 }
4380
4381 /**
4382 * Send an e-mail to this user's account. Does not check for
4383 * confirmed status or validity.
4384 *
4385 * @param string $subject Message subject
4386 * @param string $body Message body
4387 * @param User|null $from Optional sending user; if unspecified, default
4388 * $wgPasswordSender will be used.
4389 * @param string $replyto Reply-To address
4390 * @return Status
4391 */
4392 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4393 global $wgPasswordSender;
4394
4395 if ( $from instanceof User ) {
4396 $sender = MailAddress::newFromUser( $from );
4397 } else {
4398 $sender = new MailAddress( $wgPasswordSender,
4399 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4400 }
4401 $to = MailAddress::newFromUser( $this );
4402
4403 return UserMailer::send( $to, $sender, $subject, $body, [
4404 'replyTo' => $replyto,
4405 ] );
4406 }
4407
4408 /**
4409 * Generate, store, and return a new e-mail confirmation code.
4410 * A hash (unsalted, since it's used as a key) is stored.
4411 *
4412 * @note Call saveSettings() after calling this function to commit
4413 * this change to the database.
4414 *
4415 * @param string &$expiration Accepts the expiration time
4416 * @return string New token
4417 */
4418 protected function confirmationToken( &$expiration ) {
4419 global $wgUserEmailConfirmationTokenExpiry;
4420 $now = time();
4421 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4422 $expiration = wfTimestamp( TS_MW, $expires );
4423 $this->load();
4424 $token = MWCryptRand::generateHex( 32 );
4425 $hash = md5( $token );
4426 $this->mEmailToken = $hash;
4427 $this->mEmailTokenExpires = $expiration;
4428 return $token;
4429 }
4430
4431 /**
4432 * Return a URL the user can use to confirm their email address.
4433 * @param string $token Accepts the email confirmation token
4434 * @return string New token URL
4435 */
4436 protected function confirmationTokenUrl( $token ) {
4437 return $this->getTokenUrl( 'ConfirmEmail', $token );
4438 }
4439
4440 /**
4441 * Return a URL the user can use to invalidate their email address.
4442 * @param string $token Accepts the email confirmation token
4443 * @return string New token URL
4444 */
4445 protected function invalidationTokenUrl( $token ) {
4446 return $this->getTokenUrl( 'InvalidateEmail', $token );
4447 }
4448
4449 /**
4450 * Internal function to format the e-mail validation/invalidation URLs.
4451 * This uses a quickie hack to use the
4452 * hardcoded English names of the Special: pages, for ASCII safety.
4453 *
4454 * @note Since these URLs get dropped directly into emails, using the
4455 * short English names avoids insanely long URL-encoded links, which
4456 * also sometimes can get corrupted in some browsers/mailers
4457 * (bug 6957 with Gmail and Internet Explorer).
4458 *
4459 * @param string $page Special page
4460 * @param string $token Token
4461 * @return string Formatted URL
4462 */
4463 protected function getTokenUrl( $page, $token ) {
4464 // Hack to bypass localization of 'Special:'
4465 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4466 return $title->getCanonicalURL();
4467 }
4468
4469 /**
4470 * Mark the e-mail address confirmed.
4471 *
4472 * @note Call saveSettings() after calling this function to commit the change.
4473 *
4474 * @return bool
4475 */
4476 public function confirmEmail() {
4477 // Check if it's already confirmed, so we don't touch the database
4478 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4479 if ( !$this->isEmailConfirmed() ) {
4480 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4481 Hooks::run( 'ConfirmEmailComplete', [ $this ] );
4482 }
4483 return true;
4484 }
4485
4486 /**
4487 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4488 * address if it was already confirmed.
4489 *
4490 * @note Call saveSettings() after calling this function to commit the change.
4491 * @return bool Returns true
4492 */
4493 public function invalidateEmail() {
4494 $this->load();
4495 $this->mEmailToken = null;
4496 $this->mEmailTokenExpires = null;
4497 $this->setEmailAuthenticationTimestamp( null );
4498 $this->mEmail = '';
4499 Hooks::run( 'InvalidateEmailComplete', [ $this ] );
4500 return true;
4501 }
4502
4503 /**
4504 * Set the e-mail authentication timestamp.
4505 * @param string $timestamp TS_MW timestamp
4506 */
4507 public function setEmailAuthenticationTimestamp( $timestamp ) {
4508 $this->load();
4509 $this->mEmailAuthenticated = $timestamp;
4510 Hooks::run( 'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
4511 }
4512
4513 /**
4514 * Is this user allowed to send e-mails within limits of current
4515 * site configuration?
4516 * @return bool
4517 */
4518 public function canSendEmail() {
4519 global $wgEnableEmail, $wgEnableUserEmail;
4520 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4521 return false;
4522 }
4523 $canSend = $this->isEmailConfirmed();
4524 Hooks::run( 'UserCanSendEmail', [ &$this, &$canSend ] );
4525 return $canSend;
4526 }
4527
4528 /**
4529 * Is this user allowed to receive e-mails within limits of current
4530 * site configuration?
4531 * @return bool
4532 */
4533 public function canReceiveEmail() {
4534 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4535 }
4536
4537 /**
4538 * Is this user's e-mail address valid-looking and confirmed within
4539 * limits of the current site configuration?
4540 *
4541 * @note If $wgEmailAuthentication is on, this may require the user to have
4542 * confirmed their address by returning a code or using a password
4543 * sent to the address from the wiki.
4544 *
4545 * @return bool
4546 */
4547 public function isEmailConfirmed() {
4548 global $wgEmailAuthentication;
4549 $this->load();
4550 $confirmed = true;
4551 if ( Hooks::run( 'EmailConfirmed', [ &$this, &$confirmed ] ) ) {
4552 if ( $this->isAnon() ) {
4553 return false;
4554 }
4555 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4556 return false;
4557 }
4558 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4559 return false;
4560 }
4561 return true;
4562 } else {
4563 return $confirmed;
4564 }
4565 }
4566
4567 /**
4568 * Check whether there is an outstanding request for e-mail confirmation.
4569 * @return bool
4570 */
4571 public function isEmailConfirmationPending() {
4572 global $wgEmailAuthentication;
4573 return $wgEmailAuthentication &&
4574 !$this->isEmailConfirmed() &&
4575 $this->mEmailToken &&
4576 $this->mEmailTokenExpires > wfTimestamp();
4577 }
4578
4579 /**
4580 * Get the timestamp of account creation.
4581 *
4582 * @return string|bool|null Timestamp of account creation, false for
4583 * non-existent/anonymous user accounts, or null if existing account
4584 * but information is not in database.
4585 */
4586 public function getRegistration() {
4587 if ( $this->isAnon() ) {
4588 return false;
4589 }
4590 $this->load();
4591 return $this->mRegistration;
4592 }
4593
4594 /**
4595 * Get the timestamp of the first edit
4596 *
4597 * @return string|bool Timestamp of first edit, or false for
4598 * non-existent/anonymous user accounts.
4599 */
4600 public function getFirstEditTimestamp() {
4601 if ( $this->getId() == 0 ) {
4602 return false; // anons
4603 }
4604 $dbr = wfGetDB( DB_REPLICA );
4605 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4606 [ 'rev_user' => $this->getId() ],
4607 __METHOD__,
4608 [ 'ORDER BY' => 'rev_timestamp ASC' ]
4609 );
4610 if ( !$time ) {
4611 return false; // no edits
4612 }
4613 return wfTimestamp( TS_MW, $time );
4614 }
4615
4616 /**
4617 * Get the permissions associated with a given list of groups
4618 *
4619 * @param array $groups Array of Strings List of internal group names
4620 * @return array Array of Strings List of permission key names for given groups combined
4621 */
4622 public static function getGroupPermissions( $groups ) {
4623 global $wgGroupPermissions, $wgRevokePermissions;
4624 $rights = [];
4625 // grant every granted permission first
4626 foreach ( $groups as $group ) {
4627 if ( isset( $wgGroupPermissions[$group] ) ) {
4628 $rights = array_merge( $rights,
4629 // array_filter removes empty items
4630 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4631 }
4632 }
4633 // now revoke the revoked permissions
4634 foreach ( $groups as $group ) {
4635 if ( isset( $wgRevokePermissions[$group] ) ) {
4636 $rights = array_diff( $rights,
4637 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4638 }
4639 }
4640 return array_unique( $rights );
4641 }
4642
4643 /**
4644 * Get all the groups who have a given permission
4645 *
4646 * @param string $role Role to check
4647 * @return array Array of Strings List of internal group names with the given permission
4648 */
4649 public static function getGroupsWithPermission( $role ) {
4650 global $wgGroupPermissions;
4651 $allowedGroups = [];
4652 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4653 if ( self::groupHasPermission( $group, $role ) ) {
4654 $allowedGroups[] = $group;
4655 }
4656 }
4657 return $allowedGroups;
4658 }
4659
4660 /**
4661 * Check, if the given group has the given permission
4662 *
4663 * If you're wanting to check whether all users have a permission, use
4664 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4665 * from anyone.
4666 *
4667 * @since 1.21
4668 * @param string $group Group to check
4669 * @param string $role Role to check
4670 * @return bool
4671 */
4672 public static function groupHasPermission( $group, $role ) {
4673 global $wgGroupPermissions, $wgRevokePermissions;
4674 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4675 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4676 }
4677
4678 /**
4679 * Check if all users may be assumed to have the given permission
4680 *
4681 * We generally assume so if the right is granted to '*' and isn't revoked
4682 * on any group. It doesn't attempt to take grants or other extension
4683 * limitations on rights into account in the general case, though, as that
4684 * would require it to always return false and defeat the purpose.
4685 * Specifically, session-based rights restrictions (such as OAuth or bot
4686 * passwords) are applied based on the current session.
4687 *
4688 * @since 1.22
4689 * @param string $right Right to check
4690 * @return bool
4691 */
4692 public static function isEveryoneAllowed( $right ) {
4693 global $wgGroupPermissions, $wgRevokePermissions;
4694 static $cache = [];
4695
4696 // Use the cached results, except in unit tests which rely on
4697 // being able change the permission mid-request
4698 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4699 return $cache[$right];
4700 }
4701
4702 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4703 $cache[$right] = false;
4704 return false;
4705 }
4706
4707 // If it's revoked anywhere, then everyone doesn't have it
4708 foreach ( $wgRevokePermissions as $rights ) {
4709 if ( isset( $rights[$right] ) && $rights[$right] ) {
4710 $cache[$right] = false;
4711 return false;
4712 }
4713 }
4714
4715 // Remove any rights that aren't allowed to the global-session user,
4716 // unless there are no sessions for this endpoint.
4717 if ( !defined( 'MW_NO_SESSION' ) ) {
4718 $allowedRights = SessionManager::getGlobalSession()->getAllowedUserRights();
4719 if ( $allowedRights !== null && !in_array( $right, $allowedRights, true ) ) {
4720 $cache[$right] = false;
4721 return false;
4722 }
4723 }
4724
4725 // Allow extensions to say false
4726 if ( !Hooks::run( 'UserIsEveryoneAllowed', [ $right ] ) ) {
4727 $cache[$right] = false;
4728 return false;
4729 }
4730
4731 $cache[$right] = true;
4732 return true;
4733 }
4734
4735 /**
4736 * Get the localized descriptive name for a group, if it exists
4737 *
4738 * @param string $group Internal group name
4739 * @return string Localized descriptive group name
4740 */
4741 public static function getGroupName( $group ) {
4742 $msg = wfMessage( "group-$group" );
4743 return $msg->isBlank() ? $group : $msg->text();
4744 }
4745
4746 /**
4747 * Get the localized descriptive name for a member of a group, if it exists
4748 *
4749 * @param string $group Internal group name
4750 * @param string $username Username for gender (since 1.19)
4751 * @return string Localized name for group member
4752 */
4753 public static function getGroupMember( $group, $username = '#' ) {
4754 $msg = wfMessage( "group-$group-member", $username );
4755 return $msg->isBlank() ? $group : $msg->text();
4756 }
4757
4758 /**
4759 * Return the set of defined explicit groups.
4760 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4761 * are not included, as they are defined automatically, not in the database.
4762 * @return array Array of internal group names
4763 */
4764 public static function getAllGroups() {
4765 global $wgGroupPermissions, $wgRevokePermissions;
4766 return array_diff(
4767 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4768 self::getImplicitGroups()
4769 );
4770 }
4771
4772 /**
4773 * Get a list of all available permissions.
4774 * @return string[] Array of permission names
4775 */
4776 public static function getAllRights() {
4777 if ( self::$mAllRights === false ) {
4778 global $wgAvailableRights;
4779 if ( count( $wgAvailableRights ) ) {
4780 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4781 } else {
4782 self::$mAllRights = self::$mCoreRights;
4783 }
4784 Hooks::run( 'UserGetAllRights', [ &self::$mAllRights ] );
4785 }
4786 return self::$mAllRights;
4787 }
4788
4789 /**
4790 * Get a list of implicit groups
4791 * @return array Array of Strings Array of internal group names
4792 */
4793 public static function getImplicitGroups() {
4794 global $wgImplicitGroups;
4795
4796 $groups = $wgImplicitGroups;
4797 # Deprecated, use $wgImplicitGroups instead
4798 Hooks::run( 'UserGetImplicitGroups', [ &$groups ], '1.25' );
4799
4800 return $groups;
4801 }
4802
4803 /**
4804 * Get the title of a page describing a particular group
4805 *
4806 * @param string $group Internal group name
4807 * @return Title|bool Title of the page if it exists, false otherwise
4808 */
4809 public static function getGroupPage( $group ) {
4810 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4811 if ( $msg->exists() ) {
4812 $title = Title::newFromText( $msg->text() );
4813 if ( is_object( $title ) ) {
4814 return $title;
4815 }
4816 }
4817 return false;
4818 }
4819
4820 /**
4821 * Create a link to the group in HTML, if available;
4822 * else return the group name.
4823 *
4824 * @param string $group Internal name of the group
4825 * @param string $text The text of the link
4826 * @return string HTML link to the group
4827 */
4828 public static function makeGroupLinkHTML( $group, $text = '' ) {
4829 if ( $text == '' ) {
4830 $text = self::getGroupName( $group );
4831 }
4832 $title = self::getGroupPage( $group );
4833 if ( $title ) {
4834 return Linker::link( $title, htmlspecialchars( $text ) );
4835 } else {
4836 return htmlspecialchars( $text );
4837 }
4838 }
4839
4840 /**
4841 * Create a link to the group in Wikitext, if available;
4842 * else return the group name.
4843 *
4844 * @param string $group Internal name of the group
4845 * @param string $text The text of the link
4846 * @return string Wikilink to the group
4847 */
4848 public static function makeGroupLinkWiki( $group, $text = '' ) {
4849 if ( $text == '' ) {
4850 $text = self::getGroupName( $group );
4851 }
4852 $title = self::getGroupPage( $group );
4853 if ( $title ) {
4854 $page = $title->getFullText();
4855 return "[[$page|$text]]";
4856 } else {
4857 return $text;
4858 }
4859 }
4860
4861 /**
4862 * Returns an array of the groups that a particular group can add/remove.
4863 *
4864 * @param string $group The group to check for whether it can add/remove
4865 * @return array Array( 'add' => array( addablegroups ),
4866 * 'remove' => array( removablegroups ),
4867 * 'add-self' => array( addablegroups to self),
4868 * 'remove-self' => array( removable groups from self) )
4869 */
4870 public static function changeableByGroup( $group ) {
4871 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4872
4873 $groups = [
4874 'add' => [],
4875 'remove' => [],
4876 'add-self' => [],
4877 'remove-self' => []
4878 ];
4879
4880 if ( empty( $wgAddGroups[$group] ) ) {
4881 // Don't add anything to $groups
4882 } elseif ( $wgAddGroups[$group] === true ) {
4883 // You get everything
4884 $groups['add'] = self::getAllGroups();
4885 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4886 $groups['add'] = $wgAddGroups[$group];
4887 }
4888
4889 // Same thing for remove
4890 if ( empty( $wgRemoveGroups[$group] ) ) {
4891 // Do nothing
4892 } elseif ( $wgRemoveGroups[$group] === true ) {
4893 $groups['remove'] = self::getAllGroups();
4894 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4895 $groups['remove'] = $wgRemoveGroups[$group];
4896 }
4897
4898 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4899 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4900 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4901 if ( is_int( $key ) ) {
4902 $wgGroupsAddToSelf['user'][] = $value;
4903 }
4904 }
4905 }
4906
4907 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4908 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4909 if ( is_int( $key ) ) {
4910 $wgGroupsRemoveFromSelf['user'][] = $value;
4911 }
4912 }
4913 }
4914
4915 // Now figure out what groups the user can add to him/herself
4916 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4917 // Do nothing
4918 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4919 // No idea WHY this would be used, but it's there
4920 $groups['add-self'] = User::getAllGroups();
4921 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4922 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4923 }
4924
4925 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4926 // Do nothing
4927 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4928 $groups['remove-self'] = User::getAllGroups();
4929 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4930 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4931 }
4932
4933 return $groups;
4934 }
4935
4936 /**
4937 * Returns an array of groups that this user can add and remove
4938 * @return array Array( 'add' => array( addablegroups ),
4939 * 'remove' => array( removablegroups ),
4940 * 'add-self' => array( addablegroups to self),
4941 * 'remove-self' => array( removable groups from self) )
4942 */
4943 public function changeableGroups() {
4944 if ( $this->isAllowed( 'userrights' ) ) {
4945 // This group gives the right to modify everything (reverse-
4946 // compatibility with old "userrights lets you change
4947 // everything")
4948 // Using array_merge to make the groups reindexed
4949 $all = array_merge( User::getAllGroups() );
4950 return [
4951 'add' => $all,
4952 'remove' => $all,
4953 'add-self' => [],
4954 'remove-self' => []
4955 ];
4956 }
4957
4958 // Okay, it's not so simple, we will have to go through the arrays
4959 $groups = [
4960 'add' => [],
4961 'remove' => [],
4962 'add-self' => [],
4963 'remove-self' => []
4964 ];
4965 $addergroups = $this->getEffectiveGroups();
4966
4967 foreach ( $addergroups as $addergroup ) {
4968 $groups = array_merge_recursive(
4969 $groups, $this->changeableByGroup( $addergroup )
4970 );
4971 $groups['add'] = array_unique( $groups['add'] );
4972 $groups['remove'] = array_unique( $groups['remove'] );
4973 $groups['add-self'] = array_unique( $groups['add-self'] );
4974 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4975 }
4976 return $groups;
4977 }
4978
4979 /**
4980 * Deferred version of incEditCountImmediate()
4981 */
4982 public function incEditCount() {
4983 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle(
4984 function () {
4985 $this->incEditCountImmediate();
4986 },
4987 __METHOD__
4988 );
4989 }
4990
4991 /**
4992 * Increment the user's edit-count field.
4993 * Will have no effect for anonymous users.
4994 * @since 1.26
4995 */
4996 public function incEditCountImmediate() {
4997 if ( $this->isAnon() ) {
4998 return;
4999 }
5000
5001 $dbw = wfGetDB( DB_MASTER );
5002 // No rows will be "affected" if user_editcount is NULL
5003 $dbw->update(
5004 'user',
5005 [ 'user_editcount=user_editcount+1' ],
5006 [ 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ],
5007 __METHOD__
5008 );
5009 // Lazy initialization check...
5010 if ( $dbw->affectedRows() == 0 ) {
5011 // Now here's a goddamn hack...
5012 $dbr = wfGetDB( DB_REPLICA );
5013 if ( $dbr !== $dbw ) {
5014 // If we actually have a replica DB server, the count is
5015 // at least one behind because the current transaction
5016 // has not been committed and replicated.
5017 $this->mEditCount = $this->initEditCount( 1 );
5018 } else {
5019 // But if DB_REPLICA is selecting the master, then the
5020 // count we just read includes the revision that was
5021 // just added in the working transaction.
5022 $this->mEditCount = $this->initEditCount();
5023 }
5024 } else {
5025 if ( $this->mEditCount === null ) {
5026 $this->getEditCount();
5027 $dbr = wfGetDB( DB_REPLICA );
5028 $this->mEditCount += ( $dbr !== $dbw ) ? 1 : 0;
5029 } else {
5030 $this->mEditCount++;
5031 }
5032 }
5033 // Edit count in user cache too
5034 $this->invalidateCache();
5035 }
5036
5037 /**
5038 * Initialize user_editcount from data out of the revision table
5039 *
5040 * @param int $add Edits to add to the count from the revision table
5041 * @return int Number of edits
5042 */
5043 protected function initEditCount( $add = 0 ) {
5044 // Pull from a replica DB to be less cruel to servers
5045 // Accuracy isn't the point anyway here
5046 $dbr = wfGetDB( DB_REPLICA );
5047 $count = (int)$dbr->selectField(
5048 'revision',
5049 'COUNT(rev_user)',
5050 [ 'rev_user' => $this->getId() ],
5051 __METHOD__
5052 );
5053 $count = $count + $add;
5054
5055 $dbw = wfGetDB( DB_MASTER );
5056 $dbw->update(
5057 'user',
5058 [ 'user_editcount' => $count ],
5059 [ 'user_id' => $this->getId() ],
5060 __METHOD__
5061 );
5062
5063 return $count;
5064 }
5065
5066 /**
5067 * Get the description of a given right
5068 *
5069 * @param string $right Right to query
5070 * @return string Localized description of the right
5071 */
5072 public static function getRightDescription( $right ) {
5073 $key = "right-$right";
5074 $msg = wfMessage( $key );
5075 return $msg->isBlank() ? $right : $msg->text();
5076 }
5077
5078 /**
5079 * Make a new-style password hash
5080 *
5081 * @param string $password Plain-text password
5082 * @param bool|string $salt Optional salt, may be random or the user ID.
5083 * If unspecified or false, will generate one automatically
5084 * @return string Password hash
5085 * @deprecated since 1.24, use Password class
5086 */
5087 public static function crypt( $password, $salt = false ) {
5088 wfDeprecated( __METHOD__, '1.24' );
5089 $passwordFactory = new PasswordFactory();
5090 $passwordFactory->init( RequestContext::getMain()->getConfig() );
5091 $hash = $passwordFactory->newFromPlaintext( $password );
5092 return $hash->toString();
5093 }
5094
5095 /**
5096 * Compare a password hash with a plain-text password. Requires the user
5097 * ID if there's a chance that the hash is an old-style hash.
5098 *
5099 * @param string $hash Password hash
5100 * @param string $password Plain-text password to compare
5101 * @param string|bool $userId User ID for old-style password salt
5102 *
5103 * @return bool
5104 * @deprecated since 1.24, use Password class
5105 */
5106 public static function comparePasswords( $hash, $password, $userId = false ) {
5107 wfDeprecated( __METHOD__, '1.24' );
5108
5109 // Check for *really* old password hashes that don't even have a type
5110 // The old hash format was just an md5 hex hash, with no type information
5111 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
5112 global $wgPasswordSalt;
5113 if ( $wgPasswordSalt ) {
5114 $password = ":B:{$userId}:{$hash}";
5115 } else {
5116 $password = ":A:{$hash}";
5117 }
5118 }
5119
5120 $passwordFactory = new PasswordFactory();
5121 $passwordFactory->init( RequestContext::getMain()->getConfig() );
5122 $hash = $passwordFactory->newFromCiphertext( $hash );
5123 return $hash->equals( $password );
5124 }
5125
5126 /**
5127 * Add a newuser log entry for this user.
5128 * Before 1.19 the return value was always true.
5129 *
5130 * @deprecated since 1.27, AuthManager handles logging
5131 * @param string|bool $action Account creation type.
5132 * - String, one of the following values:
5133 * - 'create' for an anonymous user creating an account for himself.
5134 * This will force the action's performer to be the created user itself,
5135 * no matter the value of $wgUser
5136 * - 'create2' for a logged in user creating an account for someone else
5137 * - 'byemail' when the created user will receive its password by e-mail
5138 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5139 * - Boolean means whether the account was created by e-mail (deprecated):
5140 * - true will be converted to 'byemail'
5141 * - false will be converted to 'create' if this object is the same as
5142 * $wgUser and to 'create2' otherwise
5143 * @param string $reason User supplied reason
5144 * @return bool true
5145 */
5146 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5147 return true; // disabled
5148 }
5149
5150 /**
5151 * Add an autocreate newuser log entry for this user
5152 * Used by things like CentralAuth and perhaps other authplugins.
5153 * Consider calling addNewUserLogEntry() directly instead.
5154 *
5155 * @deprecated since 1.27, AuthManager handles logging
5156 * @return bool
5157 */
5158 public function addNewUserLogEntryAutoCreate() {
5159 $this->addNewUserLogEntry( 'autocreate' );
5160
5161 return true;
5162 }
5163
5164 /**
5165 * Load the user options either from cache, the database or an array
5166 *
5167 * @param array $data Rows for the current user out of the user_properties table
5168 */
5169 protected function loadOptions( $data = null ) {
5170 global $wgContLang;
5171
5172 $this->load();
5173
5174 if ( $this->mOptionsLoaded ) {
5175 return;
5176 }
5177
5178 $this->mOptions = self::getDefaultOptions();
5179
5180 if ( !$this->getId() ) {
5181 // For unlogged-in users, load language/variant options from request.
5182 // There's no need to do it for logged-in users: they can set preferences,
5183 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5184 // so don't override user's choice (especially when the user chooses site default).
5185 $variant = $wgContLang->getDefaultVariant();
5186 $this->mOptions['variant'] = $variant;
5187 $this->mOptions['language'] = $variant;
5188 $this->mOptionsLoaded = true;
5189 return;
5190 }
5191
5192 // Maybe load from the object
5193 if ( !is_null( $this->mOptionOverrides ) ) {
5194 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5195 foreach ( $this->mOptionOverrides as $key => $value ) {
5196 $this->mOptions[$key] = $value;
5197 }
5198 } else {
5199 if ( !is_array( $data ) ) {
5200 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5201 // Load from database
5202 $dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
5203 ? wfGetDB( DB_MASTER )
5204 : wfGetDB( DB_REPLICA );
5205
5206 $res = $dbr->select(
5207 'user_properties',
5208 [ 'up_property', 'up_value' ],
5209 [ 'up_user' => $this->getId() ],
5210 __METHOD__
5211 );
5212
5213 $this->mOptionOverrides = [];
5214 $data = [];
5215 foreach ( $res as $row ) {
5216 $data[$row->up_property] = $row->up_value;
5217 }
5218 }
5219 foreach ( $data as $property => $value ) {
5220 $this->mOptionOverrides[$property] = $value;
5221 $this->mOptions[$property] = $value;
5222 }
5223 }
5224
5225 $this->mOptionsLoaded = true;
5226
5227 Hooks::run( 'UserLoadOptions', [ $this, &$this->mOptions ] );
5228 }
5229
5230 /**
5231 * Saves the non-default options for this user, as previously set e.g. via
5232 * setOption(), in the database's "user_properties" (preferences) table.
5233 * Usually used via saveSettings().
5234 */
5235 protected function saveOptions() {
5236 $this->loadOptions();
5237
5238 // Not using getOptions(), to keep hidden preferences in database
5239 $saveOptions = $this->mOptions;
5240
5241 // Allow hooks to abort, for instance to save to a global profile.
5242 // Reset options to default state before saving.
5243 if ( !Hooks::run( 'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5244 return;
5245 }
5246
5247 $userId = $this->getId();
5248
5249 $insert_rows = []; // all the new preference rows
5250 foreach ( $saveOptions as $key => $value ) {
5251 // Don't bother storing default values
5252 $defaultOption = self::getDefaultOption( $key );
5253 if ( ( $defaultOption === null && $value !== false && $value !== null )
5254 || $value != $defaultOption
5255 ) {
5256 $insert_rows[] = [
5257 'up_user' => $userId,
5258 'up_property' => $key,
5259 'up_value' => $value,
5260 ];
5261 }
5262 }
5263
5264 $dbw = wfGetDB( DB_MASTER );
5265
5266 $res = $dbw->select( 'user_properties',
5267 [ 'up_property', 'up_value' ], [ 'up_user' => $userId ], __METHOD__ );
5268
5269 // Find prior rows that need to be removed or updated. These rows will
5270 // all be deleted (the latter so that INSERT IGNORE applies the new values).
5271 $keysDelete = [];
5272 foreach ( $res as $row ) {
5273 if ( !isset( $saveOptions[$row->up_property] )
5274 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
5275 ) {
5276 $keysDelete[] = $row->up_property;
5277 }
5278 }
5279
5280 if ( count( $keysDelete ) ) {
5281 // Do the DELETE by PRIMARY KEY for prior rows.
5282 // In the past a very large portion of calls to this function are for setting
5283 // 'rememberpassword' for new accounts (a preference that has since been removed).
5284 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5285 // caused gap locks on [max user ID,+infinity) which caused high contention since
5286 // updates would pile up on each other as they are for higher (newer) user IDs.
5287 // It might not be necessary these days, but it shouldn't hurt either.
5288 $dbw->delete( 'user_properties',
5289 [ 'up_user' => $userId, 'up_property' => $keysDelete ], __METHOD__ );
5290 }
5291 // Insert the new preference rows
5292 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, [ 'IGNORE' ] );
5293 }
5294
5295 /**
5296 * Lazily instantiate and return a factory object for making passwords
5297 *
5298 * @deprecated since 1.27, create a PasswordFactory directly instead
5299 * @return PasswordFactory
5300 */
5301 public static function getPasswordFactory() {
5302 wfDeprecated( __METHOD__, '1.27' );
5303 $ret = new PasswordFactory();
5304 $ret->init( RequestContext::getMain()->getConfig() );
5305 return $ret;
5306 }
5307
5308 /**
5309 * Provide an array of HTML5 attributes to put on an input element
5310 * intended for the user to enter a new password. This may include
5311 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5312 *
5313 * Do *not* use this when asking the user to enter his current password!
5314 * Regardless of configuration, users may have invalid passwords for whatever
5315 * reason (e.g., they were set before requirements were tightened up).
5316 * Only use it when asking for a new password, like on account creation or
5317 * ResetPass.
5318 *
5319 * Obviously, you still need to do server-side checking.
5320 *
5321 * NOTE: A combination of bugs in various browsers means that this function
5322 * actually just returns array() unconditionally at the moment. May as
5323 * well keep it around for when the browser bugs get fixed, though.
5324 *
5325 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5326 *
5327 * @deprecated since 1.27
5328 * @return array Array of HTML attributes suitable for feeding to
5329 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5330 * That will get confused by the boolean attribute syntax used.)
5331 */
5332 public static function passwordChangeInputAttribs() {
5333 global $wgMinimalPasswordLength;
5334
5335 if ( $wgMinimalPasswordLength == 0 ) {
5336 return [];
5337 }
5338
5339 # Note that the pattern requirement will always be satisfied if the
5340 # input is empty, so we need required in all cases.
5341
5342 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5343 # if e-mail confirmation is being used. Since HTML5 input validation
5344 # is b0rked anyway in some browsers, just return nothing. When it's
5345 # re-enabled, fix this code to not output required for e-mail
5346 # registration.
5347 # $ret = array( 'required' );
5348 $ret = [];
5349
5350 # We can't actually do this right now, because Opera 9.6 will print out
5351 # the entered password visibly in its error message! When other
5352 # browsers add support for this attribute, or Opera fixes its support,
5353 # we can add support with a version check to avoid doing this on Opera
5354 # versions where it will be a problem. Reported to Opera as
5355 # DSK-262266, but they don't have a public bug tracker for us to follow.
5356 /*
5357 if ( $wgMinimalPasswordLength > 1 ) {
5358 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5359 $ret['title'] = wfMessage( 'passwordtooshort' )
5360 ->numParams( $wgMinimalPasswordLength )->text();
5361 }
5362 */
5363
5364 return $ret;
5365 }
5366
5367 /**
5368 * Return the list of user fields that should be selected to create
5369 * a new user object.
5370 * @return array
5371 */
5372 public static function selectFields() {
5373 return [
5374 'user_id',
5375 'user_name',
5376 'user_real_name',
5377 'user_email',
5378 'user_touched',
5379 'user_token',
5380 'user_email_authenticated',
5381 'user_email_token',
5382 'user_email_token_expires',
5383 'user_registration',
5384 'user_editcount',
5385 ];
5386 }
5387
5388 /**
5389 * Factory function for fatal permission-denied errors
5390 *
5391 * @since 1.22
5392 * @param string $permission User right required
5393 * @return Status
5394 */
5395 static function newFatalPermissionDeniedStatus( $permission ) {
5396 global $wgLang;
5397
5398 $groups = array_map(
5399 [ 'User', 'makeGroupLinkWiki' ],
5400 User::getGroupsWithPermission( $permission )
5401 );
5402
5403 if ( $groups ) {
5404 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5405 } else {
5406 return Status::newFatal( 'badaccess-group0' );
5407 }
5408 }
5409
5410 /**
5411 * Get a new instance of this user that was loaded from the master via a locking read
5412 *
5413 * Use this instead of the main context User when updating that user. This avoids races
5414 * where that user was loaded from a replica DB or even the master but without proper locks.
5415 *
5416 * @return User|null Returns null if the user was not found in the DB
5417 * @since 1.27
5418 */
5419 public function getInstanceForUpdate() {
5420 if ( !$this->getId() ) {
5421 return null; // anon
5422 }
5423
5424 $user = self::newFromId( $this->getId() );
5425 if ( !$user->loadFromId( self::READ_EXCLUSIVE ) ) {
5426 return null;
5427 }
5428
5429 return $user;
5430 }
5431
5432 /**
5433 * Checks if two user objects point to the same user.
5434 *
5435 * @since 1.25
5436 * @param User $user
5437 * @return bool
5438 */
5439 public function equals( User $user ) {
5440 return $this->getName() === $user->getName();
5441 }
5442 }