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