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