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