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