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