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