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