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