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