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