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