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