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