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