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