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