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