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