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