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