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