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