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