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