MediaWiki  master
User.php
Go to the documentation of this file.
1 <?php
29 use MediaWiki\HookContainer\ProtectedHookAccessorTrait;
43 use Wikimedia\Assert\Assert;
44 use Wikimedia\Assert\PreconditionException;
45 use Wikimedia\IPUtils;
49 use Wikimedia\ScopedCallback;
50 
67  use ProtectedHookAccessorTrait;
69 
73  public const TOKEN_LENGTH = 32;
74 
78  public const INVALID_TOKEN = '*** INVALID ***';
79 
84  private const VERSION = 16;
85 
91  public const GETOPTIONS_EXCLUDE_DEFAULTS = UserOptionsLookup::EXCLUDE_DEFAULTS;
92 
96  public const CHECK_USER_RIGHTS = true;
97 
101  public const IGNORE_USER_RIGHTS = false;
102 
110  protected static $mCacheVars = [
111  // user table
112  'mId',
113  'mName',
114  'mRealName',
115  'mEmail',
116  'mTouched',
117  'mToken',
118  'mEmailAuthenticated',
119  'mEmailToken',
120  'mEmailTokenExpires',
121  'mRegistration',
122  'mEditCount',
123  // actor table
124  'mActorId',
125  ];
126 
128  // Some of these are public, including for use by the UserFactory, but they generally
129  // should not be set manually
130  // @{
132  public $mId;
134  public $mName;
140  public $mActorId;
142  public $mRealName;
143 
145  public $mEmail;
147  public $mTouched;
149  protected $mQuickTouched;
151  protected $mToken;
155  protected $mEmailToken;
159  protected $mRegistration;
161  protected $mEditCount;
162  // @}
163 
164  // @{
168  protected $mLoadedItems = [];
169  // @}
170 
181  public $mFrom;
182 
187  protected $mDatePreference;
194  public $mBlockedby;
196  protected $mHash;
202  protected $mBlockreason;
204  protected $mGlobalBlock;
206  protected $mLocked;
213  public $mHideName;
214 
216  private $mRequest;
217 
223  public $mBlock;
224 
226  protected $mAllowUsertalk;
227 
229  private $mBlockedFromCreateAccount = false;
230 
232  protected $queryFlagsUsed = self::READ_NORMAL;
233 
236 
238  public static $idCacheByName = [];
239 
255  public function __construct() {
256  $this->clearInstanceCache( 'defaults' );
257  }
258 
265  public function getWikiId() {
266  return self::LOCAL;
267  }
268 
272  public function __toString() {
273  return $this->getName();
274  }
275 
276  public function &__get( $name ) {
277  // A shortcut for $mRights deprecation phase
278  if ( $name === 'mRights' ) {
279  $copy = $this->getRights();
280  return $copy;
281  } elseif ( $name === 'mOptions' ) {
282  wfDeprecated( 'User::$mOptions', '1.35' );
283  $options = $this->getOptions();
284  return $options;
285  } elseif ( !property_exists( $this, $name ) ) {
286  // T227688 - do not break $u->foo['bar'] = 1
287  wfLogWarning( 'tried to get non-existent property' );
288  $this->$name = null;
289  return $this->$name;
290  } else {
291  wfLogWarning( 'tried to get non-visible property' );
292  $null = null;
293  return $null;
294  }
295  }
296 
297  public function __set( $name, $value ) {
298  // A shortcut for $mRights deprecation phase, only known legitimate use was for
299  // testing purposes, other uses seem bad in principle
300  if ( $name === 'mRights' ) {
301  MediaWikiServices::getInstance()->getPermissionManager()->overrideUserRightsForTesting(
302  $this,
303  $value === null ? [] : $value
304  );
305  } elseif ( $name === 'mOptions' ) {
306  wfDeprecated( 'User::$mOptions', '1.35' );
307  MediaWikiServices::getInstance()->getUserOptionsManager()->clearUserOptionsCache( $this );
308  foreach ( $value as $key => $val ) {
309  $this->setOption( $key, $val );
310  }
311  } elseif ( !property_exists( $this, $name ) ) {
312  $this->$name = $value;
313  } else {
314  wfLogWarning( 'tried to set non-visible property' );
315  }
316  }
317 
318  public function __sleep(): array {
319  return array_diff(
320  array_keys( get_object_vars( $this ) ),
321  [
322  'mThisAsAuthority' // memoization, will be recreated on demand.
323  ]
324  );
325  }
326 
341  public function isSafeToLoad() {
342  global $wgFullyInitialised;
343 
344  // The user is safe to load if:
345  // * MW_NO_SESSION is undefined AND $wgFullyInitialised is true (safe to use session data)
346  // * mLoadedItems === true (already loaded)
347  // * mFrom !== 'session' (sessions not involved at all)
348 
349  return ( !defined( 'MW_NO_SESSION' ) && $wgFullyInitialised ) ||
350  $this->mLoadedItems === true || $this->mFrom !== 'session';
351  }
352 
358  public function load( $flags = self::READ_NORMAL ) {
359  global $wgFullyInitialised;
360 
361  if ( $this->mLoadedItems === true ) {
362  return;
363  }
364 
365  // Set it now to avoid infinite recursion in accessors
366  $oldLoadedItems = $this->mLoadedItems;
367  $this->mLoadedItems = true;
368  $this->queryFlagsUsed = $flags;
369 
370  // If this is called too early, things are likely to break.
371  if ( !$wgFullyInitialised && $this->mFrom === 'session' ) {
372  LoggerFactory::getInstance( 'session' )
373  ->warning( 'User::loadFromSession called before the end of Setup.php', [
374  'exception' => new Exception( 'User::loadFromSession called before the end of Setup.php' ),
375  ] );
376  $this->loadDefaults();
377  $this->mLoadedItems = $oldLoadedItems;
378  return;
379  }
380 
381  switch ( $this->mFrom ) {
382  case 'defaults':
383  $this->loadDefaults();
384  break;
385  case 'id':
386  // Make sure this thread sees its own changes, if the ID isn't 0
387  if ( $this->mId != 0 ) {
388  $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
389  if ( $lb->hasOrMadeRecentMasterChanges() ) {
390  $flags |= self::READ_LATEST;
391  $this->queryFlagsUsed = $flags;
392  }
393  }
394 
395  $this->loadFromId( $flags );
396  break;
397  case 'actor':
398  case 'name':
399  // Make sure this thread sees its own changes
400  $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
401  if ( $lb->hasOrMadeRecentMasterChanges() ) {
402  $flags |= self::READ_LATEST;
403  $this->queryFlagsUsed = $flags;
404  }
405 
406  list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
407  $row = wfGetDB( $index )->selectRow(
408  'actor',
409  [ 'actor_id', 'actor_user', 'actor_name' ],
410  $this->mFrom === 'name'
411  // make sure to use normalized form of IP for anonymous users
412  ? [ 'actor_name' => IPUtils::sanitizeIP( $this->mName ) ]
413  : [ 'actor_id' => $this->mActorId ],
414  __METHOD__,
415  $options
416  );
417 
418  if ( !$row ) {
419  // Ugh.
420  $this->loadDefaults( $this->mFrom === 'name' ? $this->mName : false );
421  } elseif ( $row->actor_user ) {
422  $this->mId = $row->actor_user;
423  $this->loadFromId( $flags );
424  } else {
425  $this->loadDefaults( $row->actor_name, $row->actor_id );
426  }
427  break;
428  case 'session':
429  if ( !$this->loadFromSession() ) {
430  // Loading from session failed. Load defaults.
431  $this->loadDefaults();
432  }
433  $this->getHookRunner()->onUserLoadAfterLoadFromSession( $this );
434  break;
435  default:
436  throw new UnexpectedValueException(
437  "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
438  }
439  }
440 
446  public function loadFromId( $flags = self::READ_NORMAL ) {
447  if ( $this->mId == 0 ) {
448  // Anonymous users are not in the database (don't need cache)
449  $this->loadDefaults();
450  return false;
451  }
452 
453  // Try cache (unless this needs data from the master DB).
454  // NOTE: if this thread called saveSettings(), the cache was cleared.
455  $latest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
456  if ( $latest ) {
457  if ( !$this->loadFromDatabase( $flags ) ) {
458  // Can't load from ID
459  return false;
460  }
461  } else {
462  $this->loadFromCache();
463  }
464 
465  $this->mLoadedItems = true;
466  $this->queryFlagsUsed = $flags;
467 
468  return true;
469  }
470 
476  public static function purge( $dbDomain, $userId ) {
477  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
478  $key = $cache->makeGlobalKey( 'user', 'id', $dbDomain, $userId );
479  $cache->delete( $key );
480  }
481 
487  protected function getCacheKey( WANObjectCache $cache ) {
488  $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
489 
490  return $cache->makeGlobalKey( 'user', 'id', $lbFactory->getLocalDomainID(), $this->mId );
491  }
492 
499  $id = $this->getId();
500 
501  return $id ? [ $this->getCacheKey( $cache ) ] : [];
502  }
503 
510  protected function loadFromCache() {
511  global $wgFullyInitialised;
512 
513  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
514  $data = $cache->getWithSetCallback(
515  $this->getCacheKey( $cache ),
516  $cache::TTL_HOUR,
517  function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache, $wgFullyInitialised ) {
518  $setOpts += Database::getCacheSetOptions( wfGetDB( DB_REPLICA ) );
519  wfDebug( "User: cache miss for user {$this->mId}" );
520 
521  $this->loadFromDatabase( self::READ_NORMAL );
522 
523  $data = [];
524  foreach ( self::$mCacheVars as $name ) {
525  $data[$name] = $this->$name;
526  }
527 
528  $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX, $this->mTouched ), $ttl );
529 
530  if ( $wgFullyInitialised ) {
531  $groupMemberships = MediaWikiServices::getInstance()
532  ->getUserGroupManager()
533  ->getUserGroupMemberships( $this, $this->queryFlagsUsed );
534 
535  // if a user group membership is about to expire, the cache needs to
536  // expire at that time (T163691)
537  foreach ( $groupMemberships as $ugm ) {
538  if ( $ugm->getExpiry() ) {
539  $secondsUntilExpiry =
540  wfTimestamp( TS_UNIX, $ugm->getExpiry() ) - time();
541 
542  if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
543  $ttl = $secondsUntilExpiry;
544  }
545  }
546  }
547  }
548 
549  return $data;
550  },
551  [ 'pcTTL' => $cache::TTL_PROC_LONG, 'version' => self::VERSION ]
552  );
553 
554  // Restore from cache
555  foreach ( self::$mCacheVars as $name ) {
556  $this->$name = $data[$name];
557  }
558 
559  return true;
560  }
561 
562  /***************************************************************************/
563  // region newFrom*() static factory methods
586  public static function newFromName( $name, $validate = 'valid' ) {
587  // Backwards compatibility with strings / false
588  $validationLevels = [
589  'valid' => UserFactory::RIGOR_VALID,
590  'usable' => UserFactory::RIGOR_USABLE,
591  'creatable' => UserFactory::RIGOR_CREATABLE
592  ];
593  if ( $validate === true ) {
594  $validate = 'valid';
595  }
596  if ( $validate === false ) {
597  $validation = UserFactory::RIGOR_NONE;
598  } elseif ( array_key_exists( $validate, $validationLevels ) ) {
599  $validation = $validationLevels[ $validate ];
600  } else {
601  // Not a recognized value, probably a test for unsupported validation
602  // levels, regardless, just pass it along
603  $validation = $validate;
604  }
605 
606  $user = MediaWikiServices::getInstance()
607  ->getUserFactory()
608  ->newFromName( (string)$name, $validation );
609 
610  // UserFactory returns null instead of false
611  if ( $user === null ) {
612  $user = false;
613  }
614  return $user;
615  }
616 
627  public static function newFromId( $id ) {
628  return MediaWikiServices::getInstance()
629  ->getUserFactory()
630  ->newFromId( (int)$id );
631  }
632 
644  public static function newFromActorId( $id ) {
645  return MediaWikiServices::getInstance()
646  ->getUserFactory()
647  ->newFromActorId( (int)$id );
648  }
649 
663  public static function newFromIdentity( UserIdentity $identity ) {
664  // Don't use the service if we already have a User object,
665  // so that User::newFromIdentity calls don't break things in unit tests.
666  if ( $identity instanceof User ) {
667  return $identity;
668  }
669 
670  return MediaWikiServices::getInstance()
671  ->getUserFactory()
672  ->newFromUserIdentity( $identity );
673  }
674 
692  public static function newFromAnyId( $userId, $userName, $actorId, $dbDomain = false ) {
693  return MediaWikiServices::getInstance()
694  ->getUserFactory()
695  ->newFromAnyId( $userId, $userName, $actorId, $dbDomain );
696  }
697 
713  public static function newFromConfirmationCode( $code, $flags = self::READ_NORMAL ) {
714  return MediaWikiServices::getInstance()
715  ->getUserFactory()
716  ->newFromConfirmationCode( (string)$code, $flags );
717  }
718 
726  public static function newFromSession( WebRequest $request = null ) {
727  $user = new User;
728  $user->mFrom = 'session';
729  $user->mRequest = $request;
730  return $user;
731  }
732 
748  public static function newFromRow( $row, $data = null ) {
749  $user = new User;
750  $user->loadFromRow( $row, $data );
751  return $user;
752  }
753 
789  public static function newSystemUser( $name, $options = [] ) {
790  $options += [
791  'validate' => UserNameUtils::RIGOR_VALID,
792  'create' => true,
793  'steal' => false,
794  ];
795 
796  // Username validation
797  // Backwards compatibility with strings / false
798  $validationLevels = [
799  'valid' => UserNameUtils::RIGOR_VALID,
800  'usable' => UserNameUtils::RIGOR_USABLE,
801  'creatable' => UserNameUtils::RIGOR_CREATABLE
802  ];
803  $validate = $options['validate'];
804 
805  // @phan-suppress-next-line PhanSuspiciousValueComparison
806  if ( $validate === false ) {
807  $validation = UserNameUtils::RIGOR_NONE;
808  } elseif ( array_key_exists( $validate, $validationLevels ) ) {
809  $validation = $validationLevels[ $validate ];
810  } else {
811  // Not a recognized value, probably a test for unsupported validation
812  // levels, regardless, just pass it along
813  $validation = $validate;
814  }
815 
816  if ( $validation !== UserNameUtils::RIGOR_VALID ) {
818  __METHOD__ . ' options["validation"] parameter must be omitted or set to "valid".',
819  '1.36'
820  );
821  }
822  $services = MediaWikiServices::getInstance();
823  $userNameUtils = $services->getUserNameUtils();
824 
825  $name = $userNameUtils->getCanonical( (string)$name, $validation );
826  if ( $name === false ) {
827  return null;
828  }
829 
830  $loadBalancer = $services->getDBLoadBalancer();
831  $dbr = $loadBalancer->getConnectionRef( DB_REPLICA );
832 
833  $userQuery = self::getQueryInfo();
834  $row = $dbr->selectRow(
835  $userQuery['tables'],
836  $userQuery['fields'],
837  [ 'user_name' => $name ],
838  __METHOD__,
839  [],
840  $userQuery['joins']
841  );
842  if ( !$row ) {
843  // Try the master database...
844  $dbw = $loadBalancer->getConnectionRef( DB_MASTER );
845  $row = $dbw->selectRow(
846  $userQuery['tables'],
847  $userQuery['fields'],
848  [ 'user_name' => $name ],
849  __METHOD__,
850  [],
851  $userQuery['joins']
852  );
853  }
854 
855  if ( !$row ) {
856  // No user. Create it?
857  if ( !$options['create'] ) {
858  // No.
859  return null;
860  }
861 
862  // If it's a reserved user that had an anonymous actor created for it at
863  // some point, we need special handling.
864  if ( !$userNameUtils->isValid( $name ) || $userNameUtils->isUsable( $name ) ) {
865  // Not reserved, so just create it.
866  return self::createNew( $name, [ 'token' => self::INVALID_TOKEN ] );
867  }
868 
869  // It is reserved. Check for an anonymous actor row.
870  $dbw = $loadBalancer->getConnectionRef( DB_MASTER );
871  return $dbw->doAtomicSection( __METHOD__, function ( IDatabase $dbw, $fname ) use ( $name ) {
872  $row = $dbw->selectRow(
873  'actor',
874  [ 'actor_id' ],
875  [ 'actor_name' => $name, 'actor_user' => null ],
876  $fname,
877  [ 'FOR UPDATE' ]
878  );
879  if ( !$row ) {
880  // No anonymous actor.
881  return self::createNew( $name, [ 'token' => self::INVALID_TOKEN ] );
882  }
883 
884  // There is an anonymous actor. Delete the actor row so we can create the user,
885  // then restore the old actor_id so as to not break existing references.
886  // @todo If MediaWiki ever starts using foreign keys for `actor`, this will break things.
887  $dbw->delete( 'actor', [ 'actor_id' => $row->actor_id ], $fname );
888  $user = self::createNew( $name, [ 'token' => self::INVALID_TOKEN ] );
889  $dbw->update(
890  'actor',
891  [ 'actor_id' => $row->actor_id ],
892  [ 'actor_id' => $user->getActorId() ],
893  $fname
894  );
895  $user->clearInstanceCache( 'id' );
896  $user->invalidateCache();
897  return $user;
898  } );
899  }
900 
901  $user = self::newFromRow( $row );
902 
903  if ( !$user->isSystemUser() ) {
904  // User exists. Steal it?
905  if ( !$options['steal'] ) {
906  return null;
907  }
908 
909  $services->getAuthManager()->revokeAccessForUser( $name );
910 
911  $user->invalidateEmail();
912  $user->mToken = self::INVALID_TOKEN;
913  $user->saveSettings();
914  SessionManager::singleton()->preventSessionsForUser( $user->getName() );
915  }
916 
917  return $user;
918  }
919 
921  // endregion -- end of newFrom*() static factory methods
922 
928  public static function whoIs( $id ) {
929  return UserCache::singleton()->getProp( $id, 'name' );
930  }
931 
938  public static function whoIsReal( $id ) {
939  return UserCache::singleton()->getProp( $id, 'real_name' );
940  }
941 
948  public static function idFromName( $name, $flags = self::READ_NORMAL ) {
949  // Don't explode on self::$idCacheByName[$name] if $name is not a string but e.g. a User object
950  $name = (string)$name;
951  $nt = Title::makeTitleSafe( NS_USER, $name );
952  if ( $nt === null ) {
953  // Illegal name
954  return null;
955  }
956 
957  if ( !( $flags & self::READ_LATEST ) && array_key_exists( $name, self::$idCacheByName ) ) {
958  return self::$idCacheByName[$name] === null ? null : (int)self::$idCacheByName[$name];
959  }
960 
961  list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
962  $db = wfGetDB( $index );
963 
964  $s = $db->selectRow(
965  'user',
966  [ 'user_id' ],
967  [ 'user_name' => $nt->getText() ],
968  __METHOD__,
969  $options
970  );
971 
972  if ( $s === false ) {
973  $result = null;
974  } else {
975  $result = (int)$s->user_id;
976  }
977 
978  if ( count( self::$idCacheByName ) >= 1000 ) {
979  self::$idCacheByName = [];
980  }
981 
982  self::$idCacheByName[$name] = $result;
983 
984  return $result;
985  }
986 
990  public static function resetIdByNameCache() {
991  self::$idCacheByName = [];
992  }
993 
1012  public static function isIP( $name ) {
1013  return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
1014  || IPUtils::isIPv6( $name );
1015  }
1016 
1024  public function isIPRange() {
1025  return IPUtils::isValidRange( $this->mName );
1026  }
1027 
1040  public static function isValidUserName( $name ) {
1041  return MediaWikiServices::getInstance()->getUserNameUtils()->isValid( $name );
1042  }
1043 
1056  public static function isUsableName( $name ) {
1057  return MediaWikiServices::getInstance()->getUserNameUtils()->isUsable( $name );
1058  }
1059 
1070  public static function findUsersByGroup( $groups, $limit = 5000, $after = null ) {
1071  if ( $groups === [] ) {
1072  return UserArrayFromResult::newFromIDs( [] );
1073  }
1074 
1075  $groups = array_unique( (array)$groups );
1076  $limit = min( 5000, $limit );
1077 
1078  $conds = [ 'ug_group' => $groups ];
1079  if ( $after !== null ) {
1080  $conds[] = 'ug_user > ' . (int)$after;
1081  }
1082 
1083  $dbr = wfGetDB( DB_REPLICA );
1084  $ids = $dbr->selectFieldValues(
1085  'user_groups',
1086  'ug_user',
1087  $conds,
1088  __METHOD__,
1089  [
1090  'DISTINCT' => true,
1091  'ORDER BY' => 'ug_user',
1092  'LIMIT' => $limit,
1093  ]
1094  ) ?: [];
1095  return UserArray::newFromIDs( $ids );
1096  }
1097 
1111  public static function isCreatableName( $name ) {
1112  return MediaWikiServices::getInstance()->getUserNameUtils()->isCreatable( $name );
1113  }
1114 
1121  public function isValidPassword( $password ) {
1122  // simple boolean wrapper for checkPasswordValidity
1123  return $this->checkPasswordValidity( $password )->isGood();
1124  }
1125 
1147  public function checkPasswordValidity( $password ) {
1148  global $wgPasswordPolicy;
1149 
1150  $upp = new UserPasswordPolicy(
1151  $wgPasswordPolicy['policies'],
1152  $wgPasswordPolicy['checks']
1153  );
1154 
1155  $status = Status::newGood( [] );
1156  $result = false; // init $result to false for the internal checks
1157 
1158  if ( !$this->getHookRunner()->onIsValidPassword( $password, $result, $this ) ) {
1159  $status->error( $result );
1160  return $status;
1161  }
1162 
1163  if ( $result === false ) {
1164  $status->merge( $upp->checkUserPassword( $this, $password ), true );
1165  return $status;
1166  }
1167 
1168  if ( $result === true ) {
1169  return $status;
1170  }
1171 
1172  $status->error( $result );
1173  return $status; // the isValidPassword hook set a string $result and returned true
1174  }
1175 
1191  public static function getCanonicalName( $name, $validate = 'valid' ) {
1192  // Backwards compatibility with strings / false
1193  $validationLevels = [
1194  'valid' => UserNameUtils::RIGOR_VALID,
1195  'usable' => UserNameUtils::RIGOR_USABLE,
1196  'creatable' => UserNameUtils::RIGOR_CREATABLE
1197  ];
1198 
1199  if ( $validate === false ) {
1200  $validation = UserNameUtils::RIGOR_NONE;
1201  } elseif ( array_key_exists( $validate, $validationLevels ) ) {
1202  $validation = $validationLevels[ $validate ];
1203  } else {
1204  // Not a recognized value, probably a test for unsupported validation
1205  // levels, regardless, just pass it along
1206  $validation = $validate;
1207  }
1208 
1209  return MediaWikiServices::getInstance()
1210  ->getUserNameUtils()
1211  ->getCanonical( (string)$name, $validation );
1212  }
1213 
1223  public function loadDefaults( $name = false, $actorId = null ) {
1224  $this->mId = 0;
1225  $this->mName = $name;
1226  $this->mActorId = $actorId;
1227  $this->mRealName = '';
1228  $this->mEmail = '';
1229 
1230  $loggedOut = $this->mRequest && !defined( 'MW_NO_SESSION' )
1231  ? $this->mRequest->getSession()->getLoggedOutTimestamp() : 0;
1232  if ( $loggedOut !== 0 ) {
1233  $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1234  } else {
1235  $this->mTouched = '1'; # Allow any pages to be cached
1236  }
1237 
1238  $this->mToken = null; // Don't run cryptographic functions till we need a token
1239  $this->mEmailAuthenticated = null;
1240  $this->mEmailToken = '';
1241  $this->mEmailTokenExpires = null;
1242  $this->mRegistration = wfTimestamp( TS_MW );
1243 
1244  $this->getHookRunner()->onUserLoadDefaults( $this, $name );
1245  }
1246 
1259  public function isItemLoaded( $item, $all = 'all' ) {
1260  return ( $this->mLoadedItems === true && $all === 'all' ) ||
1261  ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1262  }
1263 
1271  public function setItemLoaded( $item ) {
1272  if ( is_array( $this->mLoadedItems ) ) {
1273  $this->mLoadedItems[$item] = true;
1274  }
1275  }
1276 
1282  private function loadFromSession() {
1283  // MediaWiki\Session\Session already did the necessary authentication of the user
1284  // returned here, so just use it if applicable.
1285  $session = $this->getRequest()->getSession();
1286  $user = $session->getUser();
1287  if ( $user->isRegistered() ) {
1288  $this->loadFromUserObject( $user );
1289 
1290  // Other code expects these to be set in the session, so set them.
1291  $session->set( 'wsUserID', $this->getId() );
1292  $session->set( 'wsUserName', $this->getName() );
1293  $session->set( 'wsToken', $this->getToken() );
1294 
1295  return true;
1296  }
1297 
1298  return false;
1299  }
1300 
1308  public function loadFromDatabase( $flags = self::READ_LATEST ) {
1309  // Paranoia
1310  $this->mId = intval( $this->mId );
1311 
1312  if ( !$this->mId ) {
1313  // Anonymous users are not in the database
1314  $this->loadDefaults();
1315  return false;
1316  }
1317 
1318  list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
1319  $db = wfGetDB( $index );
1320 
1321  $userQuery = self::getQueryInfo();
1322  $s = $db->selectRow(
1323  $userQuery['tables'],
1324  $userQuery['fields'],
1325  [ 'user_id' => $this->mId ],
1326  __METHOD__,
1327  $options,
1328  $userQuery['joins']
1329  );
1330 
1331  $this->queryFlagsUsed = $flags;
1332  $this->getHookRunner()->onUserLoadFromDatabase( $this, $s );
1333 
1334  if ( $s !== false ) {
1335  // Initialise user table data
1336  $this->loadFromRow( $s );
1337  $this->getEditCount(); // revalidation for nulls
1338  return true;
1339  }
1340 
1341  // Invalid user_id
1342  $this->mId = 0;
1343  $this->loadDefaults( 'Unknown user' );
1344 
1345  return false;
1346  }
1347 
1360  protected function loadFromRow( $row, $data = null ) {
1361  if ( !is_object( $row ) ) {
1362  throw new InvalidArgumentException( '$row must be an object' );
1363  }
1364 
1365  $all = true;
1366 
1367  if ( isset( $row->actor_id ) ) {
1368  $this->mActorId = (int)$row->actor_id;
1369  if ( $this->mActorId !== 0 ) {
1370  $this->mFrom = 'actor';
1371  }
1372  $this->setItemLoaded( 'actor' );
1373  } else {
1374  $all = false;
1375  }
1376 
1377  if ( isset( $row->user_name ) && $row->user_name !== '' ) {
1378  $this->mName = $row->user_name;
1379  $this->mFrom = 'name';
1380  $this->setItemLoaded( 'name' );
1381  } else {
1382  $all = false;
1383  }
1384 
1385  if ( isset( $row->user_real_name ) ) {
1386  $this->mRealName = $row->user_real_name;
1387  $this->setItemLoaded( 'realname' );
1388  } else {
1389  $all = false;
1390  }
1391 
1392  if ( isset( $row->user_id ) ) {
1393  $this->mId = intval( $row->user_id );
1394  if ( $this->mId !== 0 ) {
1395  $this->mFrom = 'id';
1396  }
1397  $this->setItemLoaded( 'id' );
1398  } else {
1399  $all = false;
1400  }
1401 
1402  if ( isset( $row->user_id ) && isset( $row->user_name ) && $row->user_name !== '' ) {
1403  self::$idCacheByName[$row->user_name] = $row->user_id;
1404  }
1405 
1406  if ( isset( $row->user_editcount ) ) {
1407  $this->mEditCount = $row->user_editcount;
1408  } else {
1409  $all = false;
1410  }
1411 
1412  if ( isset( $row->user_touched ) ) {
1413  $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1414  } else {
1415  $all = false;
1416  }
1417 
1418  if ( isset( $row->user_token ) ) {
1419  // The definition for the column is binary(32), so trim the NULs
1420  // that appends. The previous definition was char(32), so trim
1421  // spaces too.
1422  $this->mToken = rtrim( $row->user_token, " \0" );
1423  if ( $this->mToken === '' ) {
1424  $this->mToken = null;
1425  }
1426  } else {
1427  $all = false;
1428  }
1429 
1430  if ( isset( $row->user_email ) ) {
1431  $this->mEmail = $row->user_email;
1432  $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1433  $this->mEmailToken = $row->user_email_token;
1434  $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1435  $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1436  } else {
1437  $all = false;
1438  }
1439 
1440  if ( $all ) {
1441  $this->mLoadedItems = true;
1442  }
1443 
1444  if ( is_array( $data ) ) {
1445 
1446  if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1447  MediaWikiServices::getInstance()
1448  ->getUserGroupManager()
1449  ->loadGroupMembershipsFromArray(
1450  $this,
1451  $data['user_groups'],
1452  $this->queryFlagsUsed
1453  );
1454  }
1455  if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1456  MediaWikiServices::getInstance()
1457  ->getUserOptionsManager()
1458  ->loadUserOptions( $this, $this->queryFlagsUsed, $data['user_properties'] );
1459  }
1460  }
1461  }
1462 
1468  protected function loadFromUserObject( $user ) {
1469  $user->load();
1470  foreach ( self::$mCacheVars as $var ) {
1471  $this->$var = $user->$var;
1472  }
1473  }
1474 
1490  public function addAutopromoteOnceGroups( $event ) {
1491  return MediaWikiServices::getInstance()
1492  ->getUserGroupManager()
1493  ->addUserToAutopromoteOnceGroups( $this, $event );
1494  }
1495 
1505  protected function makeUpdateConditions( IDatabase $db, array $conditions ) {
1506  if ( $this->mTouched ) {
1507  // CAS check: only update if the row wasn't changed sicne it was loaded.
1508  $conditions['user_touched'] = $db->timestamp( $this->mTouched );
1509  }
1510 
1511  return $conditions;
1512  }
1513 
1524  public function checkAndSetTouched() {
1525  $this->load();
1526 
1527  if ( !$this->mId ) {
1528  return false; // anon
1529  }
1530 
1531  // Get a new user_touched that is higher than the old one
1532  $newTouched = $this->newTouchedTimestamp();
1533 
1534  $dbw = wfGetDB( DB_MASTER );
1535  $dbw->update( 'user',
1536  [ 'user_touched' => $dbw->timestamp( $newTouched ) ],
1537  $this->makeUpdateConditions( $dbw, [
1538  'user_id' => $this->mId,
1539  ] ),
1540  __METHOD__
1541  );
1542  $success = ( $dbw->affectedRows() > 0 );
1543 
1544  if ( $success ) {
1545  $this->mTouched = $newTouched;
1546  $this->clearSharedCache( 'changed' );
1547  } else {
1548  // Clears on failure too since that is desired if the cache is stale
1549  $this->clearSharedCache( 'refresh' );
1550  }
1551 
1552  return $success;
1553  }
1554 
1562  public function clearInstanceCache( $reloadFrom = false ) {
1563  global $wgFullyInitialised;
1564 
1565  $this->mDatePreference = null;
1566  $this->mBlockedby = -1; # Unset
1567  $this->mHash = false;
1568  $this->mEditCount = null;
1569  $this->mThisAsAuthority = null;
1570 
1571  if ( $wgFullyInitialised && $this->mFrom ) {
1572  $services = MediaWikiServices::getInstance();
1573  $services->getPermissionManager()->invalidateUsersRightsCache( $this );
1574  $services->getUserOptionsManager()->clearUserOptionsCache( $this );
1575  $services->getTalkPageNotificationManager()->clearInstanceCache( $this );
1576  $services->getUserGroupManager()->clearCache( $this );
1577  $services->getUserEditTracker()->clearUserEditCache( $this );
1578  }
1579 
1580  if ( $reloadFrom ) {
1581  $this->mLoadedItems = [];
1582  $this->mFrom = $reloadFrom;
1583  }
1584  }
1585 
1593  public static function getDefaultOptions() {
1594  wfDeprecated( __METHOD__, '1.35' );
1595  return MediaWikiServices::getInstance()
1596  ->getUserOptionsLookup()
1597  ->getDefaultOptions();
1598  }
1599 
1607  public static function getDefaultOption( $opt ) {
1608  wfDeprecated( __METHOD__, '1.35' );
1609  return MediaWikiServices::getInstance()
1610  ->getUserOptionsLookup()
1611  ->getDefaultOption( $opt );
1612  }
1613 
1625  private function getBlockedStatus( $fromReplica = true, $disableIpBlockExemptChecking = false ) {
1626  if ( $this->mBlockedby != -1 ) {
1627  return;
1628  }
1629 
1630  wfDebug( __METHOD__ . ": checking blocked status for " . $this->getName() );
1631 
1632  // Initialize data...
1633  // Otherwise something ends up stomping on $this->mBlockedby when
1634  // things get lazy-loaded later, causing false positive block hits
1635  // due to -1 !== 0. Probably session-related... Nothing should be
1636  // overwriting mBlockedby, surely?
1637  $this->load();
1638 
1639  // TODO: Block checking shouldn't really be done from the User object. Block
1640  // checking can involve checking for IP blocks, cookie blocks, and/or XFF blocks,
1641  // which need more knowledge of the request context than the User should have.
1642  // Since we do currently check blocks from the User, we have to do the following
1643  // here:
1644  // - Check if this is the user associated with the main request
1645  // - If so, pass the relevant request information to the block manager
1646  $request = null;
1647  if ( $this->isGlobalSessionUser() ) {
1648  // This is the global user, so we need to pass the request
1649  $request = $this->getRequest();
1650  }
1651 
1652  $block = MediaWikiServices::getInstance()->getBlockManager()->getUserBlock(
1653  $this,
1654  $request,
1655  $fromReplica,
1656  $disableIpBlockExemptChecking
1657  );
1658 
1659  if ( $block ) {
1660  $this->mBlock = $block;
1661  $this->mBlockedby = $block->getByName();
1662  $this->mBlockreason = $block->getReason();
1663  $this->mHideName = $block->getHideName();
1664  $this->mAllowUsertalk = $block->isUsertalkEditAllowed();
1665  } else {
1666  $this->mBlock = null;
1667  $this->mBlockedby = '';
1668  $this->mBlockreason = '';
1669  $this->mHideName = 0;
1670  $this->mAllowUsertalk = false;
1671  }
1672  }
1673 
1679  public function isPingLimitable() {
1680  global $wgRateLimitsExcludedIPs;
1681  if ( IPUtils::isInRanges( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1682  // No other good way currently to disable rate limits
1683  // for specific IPs. :P
1684  // But this is a crappy hack and should die.
1685  return false;
1686  }
1687  return !$this->isAllowed( 'noratelimit' );
1688  }
1689 
1706  public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1707  $logger = LoggerFactory::getInstance( 'ratelimit' );
1708 
1709  // Call the 'PingLimiter' hook
1710  $result = false;
1711  if ( !$this->getHookRunner()->onPingLimiter( $this, $action, $result, $incrBy ) ) {
1712  return $result;
1713  }
1714 
1715  global $wgRateLimits;
1716  if ( !isset( $wgRateLimits[$action] ) ) {
1717  return false;
1718  }
1719 
1720  $limits = array_merge(
1721  [ '&can-bypass' => true ],
1722  $wgRateLimits[$action]
1723  );
1724 
1725  // Some groups shouldn't trigger the ping limiter, ever
1726  if ( $limits['&can-bypass'] && !$this->isPingLimitable() ) {
1727  return false;
1728  }
1729 
1730  $logger->debug( __METHOD__ . ": limiting $action rate for {$this->getName()}" );
1731 
1732  $keys = [];
1733  $id = $this->getId();
1734  $isNewbie = $this->isNewbie();
1736 
1737  if ( $id == 0 ) {
1738  // "shared anon" limit, for all anons combined
1739  if ( isset( $limits['anon'] ) ) {
1740  $keys[$cache->makeKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1741  }
1742  } else {
1743  // "global per name" limit, across sites
1744  if ( isset( $limits['user-global'] ) ) {
1746 
1747  $centralId = $lookup
1748  ? $lookup->centralIdFromLocalUser( $this, CentralIdLookup::AUDIENCE_RAW )
1749  : 0;
1750 
1751  if ( $centralId ) {
1752  // We don't have proper realms, use provider ID.
1753  $realm = $lookup->getProviderId();
1754 
1755  $globalKey = $cache->makeGlobalKey( 'limiter', $action, 'user-global',
1756  $realm, $centralId );
1757  } else {
1758  // Fall back to a local key for a local ID
1759  $globalKey = $cache->makeKey( 'limiter', $action, 'user-global',
1760  'local', $id );
1761  }
1762  $keys[$globalKey] = $limits['user-global'];
1763  }
1764  }
1765 
1766  if ( $isNewbie ) {
1767  // "per ip" limit for anons and newbie users
1768  if ( isset( $limits['ip'] ) ) {
1769  $ip = $this->getRequest()->getIP();
1770  $keys[$cache->makeGlobalKey( 'limiter', $action, 'ip', $ip )] = $limits['ip'];
1771  }
1772  // "per subnet" limit for anons and newbie users
1773  if ( isset( $limits['subnet'] ) ) {
1774  $ip = $this->getRequest()->getIP();
1775  $subnet = IPUtils::getSubnet( $ip );
1776  if ( $subnet !== false ) {
1777  $keys[$cache->makeGlobalKey( 'limiter', $action, 'subnet', $subnet )] = $limits['subnet'];
1778  }
1779  }
1780  }
1781 
1782  // determine the "per user account" limit
1783  $userLimit = false;
1784  if ( $id !== 0 && isset( $limits['user'] ) ) {
1785  // default limit for logged-in users
1786  $userLimit = $limits['user'];
1787  }
1788  // limits for newbie logged-in users (overrides all the normal user limits)
1789  if ( $id !== 0 && $isNewbie && isset( $limits['newbie'] ) ) {
1790  $userLimit = $limits['newbie'];
1791  } else {
1792  // Check for group-specific limits
1793  // If more than one group applies, use the highest allowance (if higher than the default)
1794  foreach ( $this->getGroups() as $group ) {
1795  if ( isset( $limits[$group] ) ) {
1796  if ( $userLimit === false
1797  || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1798  ) {
1799  $userLimit = $limits[$group];
1800  }
1801  }
1802  }
1803  }
1804 
1805  // Set the user limit key
1806  if ( $userLimit !== false ) {
1807  // phan is confused because &can-bypass's value is a bool, so it assumes
1808  // that $userLimit is also a bool here.
1809  // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
1810  list( $max, $period ) = $userLimit;
1811  $logger->debug( __METHOD__ . ": effective user limit: $max in {$period}s" );
1812  $keys[$cache->makeKey( 'limiter', $action, 'user', $id )] = $userLimit;
1813  }
1814 
1815  // ip-based limits for all ping-limitable users
1816  if ( isset( $limits['ip-all'] ) ) {
1817  $ip = $this->getRequest()->getIP();
1818  // ignore if user limit is more permissive
1819  if ( $isNewbie || $userLimit === false
1820  || $limits['ip-all'][0] / $limits['ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
1821  $keys[$cache->makeGlobalKey( 'limiter', $action, 'ip-all', $ip )] = $limits['ip-all'];
1822  }
1823  }
1824 
1825  // subnet-based limits for all ping-limitable users
1826  if ( isset( $limits['subnet-all'] ) ) {
1827  $ip = $this->getRequest()->getIP();
1828  $subnet = IPUtils::getSubnet( $ip );
1829  if ( $subnet !== false ) {
1830  // ignore if user limit is more permissive
1831  if ( $isNewbie || $userLimit === false
1832  || $limits['ip-all'][0] / $limits['ip-all'][1]
1833  > $userLimit[0] / $userLimit[1] ) {
1834  $keys[$cache->makeGlobalKey( 'limiter', $action, 'subnet-all', $subnet )] = $limits['subnet-all'];
1835  }
1836  }
1837  }
1838 
1839  // XXX: We may want to use $cache->getCurrentTime() here, but that would make it
1840  // harder to test for T246991. Also $cache->getCurrentTime() is documented
1841  // as being for testing only, so it apparently should not be called here.
1842  $now = MWTimestamp::time();
1843  $clockFudge = 3; // avoid log spam when a clock is slightly off
1844 
1845  $triggered = false;
1846  foreach ( $keys as $key => $limit ) {
1847 
1848  // Do the update in a merge callback, for atomicity.
1849  // To use merge(), we need to explicitly track the desired expiry timestamp.
1850  // This tracking was introduced to investigate T246991. Once it is no longer needed,
1851  // we could go back to incrWithInit(), though that has more potential for race
1852  // conditions between the get() and incrWithInit() calls.
1853  $cache->merge(
1854  $key,
1855  function ( $cache, $key, $data, &$expiry )
1856  use ( $action, $logger, &$triggered, $now, $clockFudge, $limit, $incrBy )
1857  {
1858  // phan is confused because &can-bypass's value is a bool, so it assumes
1859  // that $userLimit is also a bool here.
1860  // @phan-suppress-next-line PhanTypeInvalidExpressionArrayDestructuring
1861  list( $max, $period ) = $limit;
1862 
1863  $expiry = $now + (int)$period;
1864  $count = 0;
1865 
1866  // Already pinged?
1867  if ( $data ) {
1868  // NOTE: in order to investigate T246991, we write the expiry time
1869  // into the payload, along with the count.
1870  $fields = explode( '|', $data );
1871  $storedCount = (int)( $fields[0] ?? 0 );
1872  $storedExpiry = (int)( $fields[1] ?? PHP_INT_MAX );
1873 
1874  // Found a stale entry. This should not happen!
1875  if ( $storedExpiry < ( $now + $clockFudge ) ) {
1876  $logger->info(
1877  'User::pingLimiter: '
1878  . 'Stale rate limit entry, cache key failed to expire (T246991)',
1879  [
1880  'action' => $action,
1881  'user' => $this->getName(),
1882  'limit' => $max,
1883  'period' => $period,
1884  'count' => $storedCount,
1885  'key' => $key,
1886  'expiry' => MWTimestamp::convert( TS_DB, $storedExpiry ),
1887  ]
1888  );
1889  } else {
1890  // NOTE: We'll keep the original expiry when bumping counters,
1891  // resulting in a kind of fixed-window throttle.
1892  $expiry = min( $storedExpiry, $now + (int)$period );
1893  $count = $storedCount;
1894  }
1895  }
1896 
1897  // Limit exceeded!
1898  if ( $count >= $max ) {
1899  if ( !$triggered ) {
1900  $logger->info(
1901  'User::pingLimiter: User tripped rate limit',
1902  [
1903  'action' => $action,
1904  'user' => $this->getName(),
1905  'ip' => $this->getRequest()->getIP(),
1906  'limit' => $max,
1907  'period' => $period,
1908  'count' => $count,
1909  'key' => $key
1910  ]
1911  );
1912  }
1913 
1914  $triggered = true;
1915  }
1916 
1917  $count += $incrBy;
1918  $data = "$count|$expiry";
1919  return $data;
1920  }
1921  );
1922  }
1923 
1924  return $triggered;
1925  }
1926 
1938  public function isBlocked( $fromReplica = true ) {
1939  return $this->getBlock( $fromReplica ) instanceof AbstractBlock;
1940  }
1941 
1950  public function getBlock( $fromReplica = true, $disableIpBlockExemptChecking = false ) {
1951  $this->getBlockedStatus( $fromReplica, $disableIpBlockExemptChecking );
1952  return $this->mBlock instanceof AbstractBlock ? $this->mBlock : null;
1953  }
1954 
1966  public function isBlockedFrom( $title, $fromReplica = false ) {
1967  return MediaWikiServices::getInstance()->getPermissionManager()
1968  ->isBlockedFrom( $this, $title, $fromReplica );
1969  }
1970 
1975  public function blockedBy() {
1976  $this->getBlockedStatus();
1977  return $this->mBlockedby;
1978  }
1979 
1986  public function blockedFor() {
1987  $this->getBlockedStatus();
1988  return $this->mBlockreason;
1989  }
1990 
1995  public function getBlockId() {
1996  $this->getBlockedStatus();
1997  return ( $this->mBlock ? $this->mBlock->getId() : false );
1998  }
1999 
2008  public function isBlockedGlobally( $ip = '' ) {
2009  return $this->getGlobalBlock( $ip ) instanceof AbstractBlock;
2010  }
2011 
2022  public function getGlobalBlock( $ip = '' ) {
2023  if ( $this->mGlobalBlock !== null ) {
2024  return $this->mGlobalBlock ?: null;
2025  }
2026  // User is already an IP?
2027  if ( IPUtils::isIPAddress( $this->getName() ) ) {
2028  $ip = $this->getName();
2029  } elseif ( !$ip ) {
2030  $ip = $this->getRequest()->getIP();
2031  }
2032  $blocked = false;
2033  $block = null;
2034  $this->getHookRunner()->onUserIsBlockedGlobally( $this, $ip, $blocked, $block );
2035 
2036  if ( $blocked && $block === null ) {
2037  // back-compat: UserIsBlockedGlobally didn't have $block param first
2038  $block = new SystemBlock( [
2039  'address' => $ip,
2040  'systemBlock' => 'global-block'
2041  ] );
2042  }
2043 
2044  $this->mGlobalBlock = $blocked ? $block : false;
2045  return $this->mGlobalBlock ?: null;
2046  }
2047 
2053  public function isLocked() {
2054  if ( $this->mLocked !== null ) {
2055  return $this->mLocked;
2056  }
2057  // Reset for hook
2058  $this->mLocked = false;
2059  $this->getHookRunner()->onUserIsLocked( $this, $this->mLocked );
2060  return $this->mLocked;
2061  }
2062 
2068  public function isHidden() {
2069  if ( $this->mHideName !== null ) {
2070  return (bool)$this->mHideName;
2071  }
2072  $this->getBlockedStatus();
2073  return (bool)$this->mHideName;
2074  }
2075 
2081  public function getId( $wikiId = self::LOCAL ) : int {
2082  $this->deprecateInvalidCrossWiki( $wikiId, '1.36' );
2083  if ( $this->mId === null && $this->mName !== null &&
2084  ( self::isIP( $this->mName ) || ExternalUserNames::isExternal( $this->mName ) )
2085  ) {
2086  // Special case, we know the user is anonymous
2087  // Note that "external" users are "local" (they have an actor ID that is relative to
2088  // the local wiki).
2089  return 0;
2090  }
2091 
2092  if ( !$this->isItemLoaded( 'id' ) ) {
2093  // Don't load if this was initialized from an ID
2094  $this->load();
2095  }
2096 
2097  return (int)$this->mId;
2098  }
2099 
2104  public function setId( $v ) {
2105  $this->mId = $v;
2106  $this->clearInstanceCache( 'id' );
2107  }
2108 
2113  public function getName() : string {
2114  if ( $this->isItemLoaded( 'name', 'only' ) ) {
2115  // Special case optimisation
2116  return $this->mName;
2117  }
2118 
2119  $this->load();
2120  if ( $this->mName === false ) {
2121  // Clean up IPs
2122  $this->mName = IPUtils::sanitizeIP( $this->getRequest()->getIP() );
2123  }
2124 
2125  return $this->mName;
2126  }
2127 
2141  public function setName( $str ) {
2142  $this->load();
2143  $this->mName = $str;
2144  }
2145 
2159  public function getActorId( $dbwOrWikiId = self::LOCAL ) : int {
2160  if ( $dbwOrWikiId instanceof IDatabase ) {
2161  wfDeprecatedMsg( 'Passing parameter of type IDatabase', '1.36' );
2162  } else {
2163  $this->assertWiki( $dbwOrWikiId );
2164  }
2165 
2166  if ( !$this->isItemLoaded( 'actor' ) ) {
2167  $this->load();
2168  }
2169 
2170  if ( !$this->mActorId && $dbwOrWikiId instanceof IDatabase ) {
2171  MediaWikiServices::getInstance()
2172  ->getActorStoreFactory()
2173  ->getActorNormalization( $dbwOrWikiId->getDomainID() )
2174  ->acquireActorId( $this, $dbwOrWikiId );
2175  // acquireActorId will call setActorId on $this
2176  Assert::postcondition(
2177  $this->mActorId !== null,
2178  "Failed to acquire actor ID for user id {$this->mId} name {$this->mName}"
2179  );
2180  }
2181 
2182  return (int)$this->mActorId;
2183  }
2184 
2195  public function setActorId( int $actorId ) {
2196  $this->mActorId = $actorId;
2197  $this->invalidateCache();
2198  $this->setItemLoaded( 'actor' );
2199  }
2200 
2205  public function getTitleKey() {
2206  return str_replace( ' ', '_', $this->getName() );
2207  }
2208 
2214  public function getNewtalk() {
2215  wfDeprecated( __METHOD__, '1.35' );
2216  return MediaWikiServices::getInstance()
2217  ->getTalkPageNotificationManager()
2218  ->userHasNewMessages( $this );
2219  }
2220 
2237  public function getNewMessageLinks() {
2238  wfDeprecated( __METHOD__, '1.35' );
2239  $talks = [];
2240  if ( !$this->getHookRunner()->onUserRetrieveNewTalks( $this, $talks ) ) {
2241  return $talks;
2242  }
2243 
2244  $services = MediaWikiServices::getInstance();
2245  $userHasNewMessages = $services->getTalkPageNotificationManager()
2246  ->userHasNewMessages( $this );
2247  if ( !$userHasNewMessages ) {
2248  return [];
2249  }
2250  $utp = $this->getTalkPage();
2251  $timestamp = $services->getTalkPageNotificationManager()
2252  ->getLatestSeenMessageTimestamp( $this );
2253  $rev = null;
2254  if ( $timestamp ) {
2255  $revRecord = $services->getRevisionLookup()
2256  ->getRevisionByTimestamp( $utp, $timestamp );
2257  if ( $revRecord ) {
2258  $rev = new Revision( $revRecord );
2259  }
2260  }
2261  return [
2262  [
2263  'wiki' => WikiMap::getCurrentWikiId(),
2264  'link' => $utp->getLocalURL(),
2265  'rev' => $rev
2266  ]
2267  ];
2268  }
2269 
2276  public function getNewMessageRevisionId() {
2277  wfDeprecated( __METHOD__, '1.35' );
2278  $newMessageRevisionId = null;
2279  $newMessageLinks = $this->getNewMessageLinks();
2280 
2281  // Note: getNewMessageLinks() never returns more than a single link
2282  // and it is always for the same wiki, but we double-check here in
2283  // case that changes some time in the future.
2284  if ( $newMessageLinks && count( $newMessageLinks ) === 1
2285  && WikiMap::isCurrentWikiId( $newMessageLinks[0]['wiki'] )
2286  && $newMessageLinks[0]['rev']
2287  ) {
2289  $newMessageRevision = $newMessageLinks[0]['rev'];
2290  $newMessageRevisionId = $newMessageRevision->getId();
2291  }
2292 
2293  return $newMessageRevisionId;
2294  }
2295 
2304  public function setNewtalk( $val, $curRev = null ) {
2305  wfDeprecated( __METHOD__, '1.35' );
2306  if ( $curRev && $curRev instanceof Revision ) {
2307  $curRev = $curRev->getRevisionRecord();
2308  }
2309  if ( $val ) {
2310  MediaWikiServices::getInstance()
2311  ->getTalkPageNotificationManager()
2312  ->setUserHasNewMessages( $this, $curRev );
2313  } else {
2314  MediaWikiServices::getInstance()
2315  ->getTalkPageNotificationManager()
2316  ->removeUserHasNewMessages( $this );
2317  }
2318  }
2319 
2326  private function newTouchedTimestamp() {
2327  $time = time();
2328  if ( $this->mTouched ) {
2329  $time = max( $time, wfTimestamp( TS_UNIX, $this->mTouched ) + 1 );
2330  }
2331 
2332  return wfTimestamp( TS_MW, $time );
2333  }
2334 
2345  public function clearSharedCache( $mode = 'refresh' ) {
2346  if ( !$this->getId() ) {
2347  return;
2348  }
2349 
2350  $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
2351  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2352  $key = $this->getCacheKey( $cache );
2353 
2354  if ( $mode === 'refresh' ) {
2355  $cache->delete( $key, 1 ); // low tombstone/"hold-off" TTL
2356  } else {
2357  $lb->getConnectionRef( DB_MASTER )->onTransactionPreCommitOrIdle(
2358  static function () use ( $cache, $key ) {
2359  $cache->delete( $key );
2360  },
2361  __METHOD__
2362  );
2363  }
2364  }
2365 
2371  public function invalidateCache() {
2372  $this->touch();
2373  $this->clearSharedCache( 'changed' );
2374  }
2375 
2388  public function touch() {
2389  $id = $this->getId();
2390  if ( $id ) {
2391  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2392  $key = $cache->makeKey( 'user-quicktouched', 'id', $id );
2393  $cache->touchCheckKey( $key );
2394  $this->mQuickTouched = null;
2395  }
2396  }
2397 
2403  public function validateCache( $timestamp ) {
2404  return ( $timestamp >= $this->getTouched() );
2405  }
2406 
2415  public function getTouched() {
2416  $this->load();
2417 
2418  if ( $this->mId ) {
2419  if ( $this->mQuickTouched === null ) {
2420  $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2421  $key = $cache->makeKey( 'user-quicktouched', 'id', $this->mId );
2422 
2423  $this->mQuickTouched = wfTimestamp( TS_MW, $cache->getCheckKeyTime( $key ) );
2424  }
2425 
2426  return max( $this->mTouched, $this->mQuickTouched );
2427  }
2428 
2429  return $this->mTouched;
2430  }
2431 
2437  public function getDBTouched() {
2438  $this->load();
2439 
2440  return $this->mTouched;
2441  }
2442 
2455  public function changeAuthenticationData( array $data ) {
2456  $manager = MediaWikiServices::getInstance()->getAuthManager();
2457  $reqs = $manager->getAuthenticationRequests( AuthManager::ACTION_CHANGE, $this );
2458  $reqs = AuthenticationRequest::loadRequestsFromSubmission( $reqs, $data );
2459 
2460  $status = Status::newGood( 'ignored' );
2461  foreach ( $reqs as $req ) {
2462  $status->merge( $manager->allowsAuthenticationDataChange( $req ), true );
2463  }
2464  if ( $status->getValue() === 'ignored' ) {
2465  $status->warning( 'authenticationdatachange-ignored' );
2466  }
2467 
2468  if ( $status->isGood() ) {
2469  foreach ( $reqs as $req ) {
2470  $manager->changeAuthenticationData( $req );
2471  }
2472  }
2473  return $status;
2474  }
2475 
2482  public function getToken( $forceCreation = true ) {
2484 
2485  $this->load();
2486  if ( !$this->mToken && $forceCreation ) {
2487  $this->setToken();
2488  }
2489 
2490  if ( !$this->mToken ) {
2491  // The user doesn't have a token, return null to indicate that.
2492  return null;
2493  }
2494 
2495  if ( $this->mToken === self::INVALID_TOKEN ) {
2496  // We return a random value here so existing token checks are very
2497  // likely to fail.
2498  return MWCryptRand::generateHex( self::TOKEN_LENGTH );
2499  }
2500 
2501  if ( $wgAuthenticationTokenVersion === null ) {
2502  // $wgAuthenticationTokenVersion not in use, so return the raw secret
2503  return $this->mToken;
2504  }
2505 
2506  // $wgAuthenticationTokenVersion in use, so hmac it.
2507  $ret = MWCryptHash::hmac( $wgAuthenticationTokenVersion, $this->mToken, false );
2508 
2509  // The raw hash can be overly long. Shorten it up.
2510  $len = max( 32, self::TOKEN_LENGTH );
2511  if ( strlen( $ret ) < $len ) {
2512  // Should never happen, even md5 is 128 bits
2513  throw new \UnexpectedValueException( 'Hmac returned less than 128 bits' );
2514  }
2515 
2516  return substr( $ret, -$len );
2517  }
2518 
2525  public function setToken( $token = false ) {
2526  $this->load();
2527  if ( $this->mToken === self::INVALID_TOKEN ) {
2528  LoggerFactory::getInstance( 'session' )
2529  ->debug( __METHOD__ . ": Ignoring attempt to set token for system user \"$this\"" );
2530  } elseif ( !$token ) {
2531  $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2532  } else {
2533  $this->mToken = $token;
2534  }
2535  }
2536 
2541  public function getEmail() {
2542  $this->load();
2543  $this->getHookRunner()->onUserGetEmail( $this, $this->mEmail );
2544  return $this->mEmail;
2545  }
2546 
2552  $this->load();
2553  $this->getHookRunner()->onUserGetEmailAuthenticationTimestamp(
2554  $this, $this->mEmailAuthenticated );
2556  }
2557 
2562  public function setEmail( $str ) {
2563  $this->load();
2564  if ( $str == $this->getEmail() ) {
2565  return;
2566  }
2567  $this->invalidateEmail();
2568  $this->mEmail = $str;
2569  $this->getHookRunner()->onUserSetEmail( $this, $this->mEmail );
2570  }
2571 
2579  public function setEmailWithConfirmation( $str ) {
2581 
2582  if ( !$wgEnableEmail ) {
2583  return Status::newFatal( 'emaildisabled' );
2584  }
2585 
2586  $oldaddr = $this->getEmail();
2587  if ( $str === $oldaddr ) {
2588  return Status::newGood( true );
2589  }
2590 
2591  $type = $oldaddr != '' ? 'changed' : 'set';
2592  $notificationResult = null;
2593 
2594  if ( $wgEmailAuthentication && $type === 'changed' ) {
2595  // Send the user an email notifying the user of the change in registered
2596  // email address on their previous email address
2597  $change = $str != '' ? 'changed' : 'removed';
2598  $notificationResult = $this->sendMail(
2599  wfMessage( 'notificationemail_subject_' . $change )->text(),
2600  wfMessage( 'notificationemail_body_' . $change,
2601  $this->getRequest()->getIP(),
2602  $this->getName(),
2603  $str )->text()
2604  );
2605  }
2606 
2607  $this->setEmail( $str );
2608 
2609  if ( $str !== '' && $wgEmailAuthentication ) {
2610  // Send a confirmation request to the new address if needed
2611  $result = $this->sendConfirmationMail( $type );
2612 
2613  if ( $notificationResult !== null ) {
2614  $result->merge( $notificationResult );
2615  }
2616 
2617  if ( $result->isGood() ) {
2618  // Say to the caller that a confirmation and notification mail has been sent
2619  $result->value = 'eauth';
2620  }
2621  } else {
2622  $result = Status::newGood( true );
2623  }
2624 
2625  return $result;
2626  }
2627 
2632  public function getRealName() {
2633  if ( !$this->isItemLoaded( 'realname' ) ) {
2634  $this->load();
2635  }
2636 
2637  return $this->mRealName;
2638  }
2639 
2644  public function setRealName( $str ) {
2645  $this->load();
2646  $this->mRealName = $str;
2647  }
2648 
2661  public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2662  if ( $oname === null ) {
2663  return null; // b/c
2664  }
2665  return MediaWikiServices::getInstance()
2666  ->getUserOptionsLookup()
2667  ->getOption( $this, $oname, $defaultOverride, $ignoreHidden );
2668  }
2669 
2679  public function getOptions( $flags = 0 ) {
2680  return MediaWikiServices::getInstance()
2681  ->getUserOptionsLookup()
2682  ->getOptions( $this, $flags );
2683  }
2684 
2693  public function getBoolOption( $oname ) {
2694  return MediaWikiServices::getInstance()
2695  ->getUserOptionsLookup()
2696  ->getBoolOption( $this, $oname );
2697  }
2698 
2708  public function getIntOption( $oname, $defaultOverride = 0 ) {
2709  if ( $oname === null ) {
2710  return null; // b/c
2711  }
2712  return MediaWikiServices::getInstance()
2713  ->getUserOptionsLookup()
2714  ->getIntOption( $this, $oname, $defaultOverride );
2715  }
2716 
2726  public function setOption( $oname, $val ) {
2727  MediaWikiServices::getInstance()
2728  ->getUserOptionsManager()
2729  ->setOption( $this, $oname, $val );
2730  }
2731 
2742  public function getTokenFromOption( $oname ) {
2743  global $wgHiddenPrefs;
2744 
2745  $id = $this->getId();
2746  if ( !$id || in_array( $oname, $wgHiddenPrefs ) ) {
2747  return false;
2748  }
2749 
2750  $token = $this->getOption( $oname );
2751  if ( !$token ) {
2752  // Default to a value based on the user token to avoid space
2753  // wasted on storing tokens for all users. When this option
2754  // is set manually by the user, only then is it stored.
2755  $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2756  }
2757 
2758  return $token;
2759  }
2760 
2770  public function resetTokenFromOption( $oname ) {
2771  global $wgHiddenPrefs;
2772  if ( in_array( $oname, $wgHiddenPrefs ) ) {
2773  return false;
2774  }
2775 
2776  $token = MWCryptRand::generateHex( 40 );
2777  $this->setOption( $oname, $token );
2778  return $token;
2779  }
2780 
2805  public static function listOptionKinds() {
2806  return MediaWikiServices::getInstance()
2807  ->getUserOptionsManager()
2808  ->listOptionKinds();
2809  }
2810 
2824  public function getOptionKinds( IContextSource $context, $options = null ) {
2825  return MediaWikiServices::getInstance()
2826  ->getUserOptionsManager()
2827  ->getOptionKinds( $this, $context, $options );
2828  }
2829 
2845  public function resetOptions(
2846  $resetKinds = [ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ],
2847  IContextSource $context = null
2848  ) {
2849  MediaWikiServices::getInstance()
2850  ->getUserOptionsManager()
2851  ->resetOptions(
2852  $this,
2853  $context ?? RequestContext::getMain(),
2854  $resetKinds
2855  );
2856  }
2857 
2862  public function getDatePreference() {
2863  // Important migration for old data rows
2864  if ( $this->mDatePreference === null ) {
2865  global $wgLang;
2866  $value = $this->getOption( 'date' );
2867  $map = $wgLang->getDatePreferenceMigrationMap();
2868  if ( isset( $map[$value] ) ) {
2869  $value = $map[$value];
2870  }
2871  $this->mDatePreference = $value;
2872  }
2873  return $this->mDatePreference;
2874  }
2875 
2882  public function requiresHTTPS() {
2883  global $wgForceHTTPS, $wgSecureLogin;
2884  if ( $wgForceHTTPS ) {
2885  return true;
2886  }
2887  if ( !$wgSecureLogin ) {
2888  return false;
2889  }
2890  $https = $this->getBoolOption( 'prefershttps' );
2891  $this->getHookRunner()->onUserRequiresHTTPS( $this, $https );
2892  if ( $https ) {
2893  $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2894  }
2895 
2896  return $https;
2897  }
2898 
2904  public function getStubThreshold() {
2905  global $wgMaxArticleSize; # Maximum article size, in Kb
2906  $threshold = $this->getIntOption( 'stubthreshold' );
2907  if ( $threshold > $wgMaxArticleSize * 1024 ) {
2908  // If they have set an impossible value, disable the preference
2909  // so we can use the parser cache again.
2910  $threshold = 0;
2911  }
2912  return $threshold;
2913  }
2914 
2923  public function getRights() {
2924  return MediaWikiServices::getInstance()->getPermissionManager()->getUserPermissions( $this );
2925  }
2926 
2935  public function getGroups() {
2936  return MediaWikiServices::getInstance()
2937  ->getUserGroupManager()
2938  ->getUserGroups( $this, $this->queryFlagsUsed );
2939  }
2940 
2950  public function getGroupMemberships() {
2951  return MediaWikiServices::getInstance()
2952  ->getUserGroupManager()
2953  ->getUserGroupMemberships( $this, $this->queryFlagsUsed );
2954  }
2955 
2966  public function getEffectiveGroups( $recache = false ) {
2967  return MediaWikiServices::getInstance()
2968  ->getUserGroupManager()
2969  ->getUserEffectiveGroups( $this, $this->queryFlagsUsed, $recache );
2970  }
2971 
2982  public function getAutomaticGroups( $recache = false ) {
2983  return MediaWikiServices::getInstance()
2984  ->getUserGroupManager()
2985  ->getUserImplicitGroups( $this, $this->queryFlagsUsed, $recache );
2986  }
2987 
2999  public function getFormerGroups() {
3000  return MediaWikiServices::getInstance()
3001  ->getUserGroupManager()
3002  ->getUserFormerGroups( $this, $this->queryFlagsUsed );
3003  }
3004 
3009  public function getEditCount() {
3010  if ( !$this->getId() ) {
3011  return null;
3012  }
3013 
3014  if ( $this->mEditCount === null ) {
3015  $this->mEditCount = MediaWikiServices::getInstance()
3016  ->getUserEditTracker()
3017  ->getUserEditCount( $this );
3018  }
3019  return (int)$this->mEditCount;
3020  }
3021 
3035  public function addGroup( $group, $expiry = null ) {
3036  return MediaWikiServices::getInstance()
3037  ->getUserGroupManager()
3038  ->addUserToGroup( $this, $group, $expiry, true );
3039  }
3040 
3050  public function removeGroup( $group ) {
3051  return MediaWikiServices::getInstance()
3052  ->getUserGroupManager()
3053  ->removeUserFromGroup( $this, $group );
3054  }
3055 
3064  public function isRegistered() : bool {
3065  return $this->getId() != 0;
3066  }
3067 
3074  public function isLoggedIn() {
3075  return $this->isRegistered();
3076  }
3077 
3082  public function isAnon() {
3083  return !$this->isRegistered();
3084  }
3085 
3090  public function isBot() {
3091  if ( in_array( 'bot', $this->getGroups() ) && $this->isAllowed( 'bot' ) ) {
3092  return true;
3093  }
3094 
3095  $isBot = false;
3096  $this->getHookRunner()->onUserIsBot( $this, $isBot );
3097 
3098  return $isBot;
3099  }
3100 
3110  public function isSystemUser() {
3111  $this->load();
3112  if ( $this->getEmail() || $this->mToken !== self::INVALID_TOKEN ||
3113  MediaWikiServices::getInstance()->getAuthManager()->userCanAuthenticate( $this->mName )
3114  ) {
3115  return false;
3116  }
3117  return true;
3118  }
3119 
3120  public function isAllowedAny( ...$permissions ): bool {
3121  return $this->getThisAsAuthority()->isAllowedAny( ...$permissions );
3122  }
3123 
3124  public function isAllowedAll( ...$permissions ): bool {
3125  return $this->getThisAsAuthority()->isAllowedAll( ...$permissions );
3126  }
3127 
3128  public function isAllowed( string $permission ): bool {
3129  return $this->getThisAsAuthority()->isAllowed( $permission );
3130  }
3131 
3136  public function useRCPatrol() {
3137  global $wgUseRCPatrol;
3138  return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3139  }
3140 
3145  public function useNPPatrol() {
3147  return (
3149  && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3150  );
3151  }
3152 
3157  public function useFilePatrol() {
3159  return (
3161  && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3162  );
3163  }
3164 
3170  public function getRequest() {
3171  if ( $this->mRequest ) {
3172  return $this->mRequest;
3173  }
3174  return RequestContext::getMain()->getRequest();
3175  }
3176 
3185  public function isWatched( $title, $checkRights = self::CHECK_USER_RIGHTS ) {
3186  if ( $title->isWatchable() && ( !$checkRights || $this->isAllowed( 'viewmywatchlist' ) ) ) {
3187  return MediaWikiServices::getInstance()->getWatchedItemStore()->isWatched( $this, $title );
3188  }
3189  return false;
3190  }
3191 
3202  public function isTempWatched( $title, $checkRights = self::CHECK_USER_RIGHTS ): bool {
3203  if ( $title->isWatchable() && ( !$checkRights || $this->isAllowed( 'viewmywatchlist' ) ) ) {
3204  return MediaWikiServices::getInstance()->getWatchedItemStore()
3205  ->isTempWatched( $this, $title );
3206  }
3207  return false;
3208  }
3209 
3219  public function addWatch(
3220  $title,
3221  $checkRights = self::CHECK_USER_RIGHTS,
3222  ?string $expiry = null
3223  ) {
3224  if ( !$title->isWatchable() ) {
3225  return;
3226  }
3227 
3228  if ( !$checkRights || $this->isAllowed( 'editmywatchlist' ) ) {
3229  $store = MediaWikiServices::getInstance()->getWatchedItemStore();
3230  $store->addWatch( $this, $title->getSubjectPage(), $expiry );
3231  if ( $title->canHaveTalkPage() ) {
3232  $store->addWatch( $this, $title->getTalkPage(), $expiry );
3233  }
3234  }
3235  $this->invalidateCache();
3236  }
3237 
3245  public function removeWatch( $title, $checkRights = self::CHECK_USER_RIGHTS ) {
3246  if ( !$title->isWatchable() ) {
3247  return;
3248  }
3249 
3250  if ( !$checkRights || $this->isAllowed( 'editmywatchlist' ) ) {
3251  $store = MediaWikiServices::getInstance()->getWatchedItemStore();
3252  $store->removeWatch( $this, $title->getSubjectPage() );
3253  if ( $title->canHaveTalkPage() ) {
3254  $store->removeWatch( $this, $title->getTalkPage() );
3255  }
3256  }
3257  $this->invalidateCache();
3258  }
3259 
3272  public function clearNotification( &$title, $oldid = 0 ) {
3273  wfDeprecated( __METHOD__, '1.35' );
3274  MediaWikiServices::getInstance()
3275  ->getWatchlistNotificationManager()
3276  ->clearTitleUserNotifications( $this, $title, $oldid );
3277  }
3278 
3284  public function getExperienceLevel() {
3285  global $wgLearnerEdits,
3289 
3290  if ( $this->isAnon() ) {
3291  return false;
3292  }
3293 
3294  $editCount = $this->getEditCount();
3295  $registration = $this->getRegistration();
3296  $now = time();
3297  $learnerRegistration = wfTimestamp( TS_MW, $now - $wgLearnerMemberSince * 86400 );
3298  $experiencedRegistration = wfTimestamp( TS_MW, $now - $wgExperiencedUserMemberSince * 86400 );
3299  if ( $registration === null ) {
3300  // for some very old accounts, this information is missing in the database
3301  // treat them as old enough to be 'experienced'
3302  $registration = $experiencedRegistration;
3303  }
3304 
3305  if ( $editCount < $wgLearnerEdits ||
3306  $registration > $learnerRegistration ) {
3307  return 'newcomer';
3308  }
3309 
3310  if ( $editCount > $wgExperiencedUserEdits &&
3311  $registration <= $experiencedRegistration
3312  ) {
3313  return 'experienced';
3314  }
3315 
3316  return 'learner';
3317  }
3318 
3327  public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3328  $this->load();
3329  if ( $this->mId == 0 ) {
3330  return;
3331  }
3332 
3333  $session = $this->getRequest()->getSession();
3334  if ( $request && $session->getRequest() !== $request ) {
3335  $session = $session->sessionWithRequest( $request );
3336  }
3337  $delay = $session->delaySave();
3338 
3339  if ( !$session->getUser()->equals( $this ) ) {
3340  if ( !$session->canSetUser() ) {
3341  LoggerFactory::getInstance( 'session' )
3342  ->warning( __METHOD__ .
3343  ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
3344  );
3345  return;
3346  }
3347  $session->setUser( $this );
3348  }
3349 
3350  $session->setRememberUser( $rememberMe );
3351  if ( $secure !== null ) {
3352  $session->setForceHTTPS( $secure );
3353  }
3354 
3355  $session->persist();
3356 
3357  ScopedCallback::consume( $delay );
3358  }
3359 
3363  public function logout() {
3364  // Avoid PHP 7.1 warning of passing $this by reference
3365  $user = $this;
3366  if ( $this->getHookRunner()->onUserLogout( $user ) ) {
3367  $this->doLogout();
3368  }
3369  }
3370 
3375  public function doLogout() {
3376  $session = $this->getRequest()->getSession();
3377  if ( !$session->canSetUser() ) {
3378  LoggerFactory::getInstance( 'session' )
3379  ->warning( __METHOD__ . ": Cannot log out of an immutable session" );
3380  $error = 'immutable';
3381  } elseif ( !$session->getUser()->equals( $this ) ) {
3382  LoggerFactory::getInstance( 'session' )
3383  ->warning( __METHOD__ .
3384  ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
3385  );
3386  // But we still may as well make this user object anon
3387  $this->clearInstanceCache( 'defaults' );
3388  $error = 'wronguser';
3389  } else {
3390  $this->clearInstanceCache( 'defaults' );
3391  $delay = $session->delaySave();
3392  $session->unpersist(); // Clear cookies (T127436)
3393  $session->setLoggedOutTimestamp( time() );
3394  $session->setUser( new User );
3395  $session->set( 'wsUserID', 0 ); // Other code expects this
3396  $session->resetAllTokens();
3397  ScopedCallback::consume( $delay );
3398  $error = false;
3399  }
3400  LoggerFactory::getInstance( 'authevents' )->info( 'Logout', [
3401  'event' => 'logout',
3402  'successful' => $error === false,
3403  'status' => $error ?: 'success',
3404  ] );
3405  }
3406 
3411  public function saveSettings() {
3412  if ( wfReadOnly() ) {
3413  // @TODO: caller should deal with this instead!
3414  // This should really just be an exception.
3416  null,
3417  "Could not update user with ID '{$this->mId}'; DB is read-only."
3418  ) );
3419  return;
3420  }
3421 
3422  $this->load();
3423  if ( $this->mId == 0 ) {
3424  return; // anon
3425  }
3426 
3427  // Get a new user_touched that is higher than the old one.
3428  // This will be used for a CAS check as a last-resort safety
3429  // check against race conditions and replica DB lag.
3430  $newTouched = $this->newTouchedTimestamp();
3431 
3432  $dbw = wfGetDB( DB_MASTER );
3433  $dbw->doAtomicSection( __METHOD__, function ( IDatabase $dbw, $fname ) use ( $newTouched ) {
3434  $dbw->update( 'user',
3435  [ /* SET */
3436  'user_name' => $this->mName,
3437  'user_real_name' => $this->mRealName,
3438  'user_email' => $this->mEmail,
3439  'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3440  'user_touched' => $dbw->timestamp( $newTouched ),
3441  'user_token' => strval( $this->mToken ),
3442  'user_email_token' => $this->mEmailToken,
3443  'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3444  ], $this->makeUpdateConditions( $dbw, [ /* WHERE */
3445  'user_id' => $this->mId,
3446  ] ), $fname
3447  );
3448 
3449  if ( !$dbw->affectedRows() ) {
3450  // Maybe the problem was a missed cache update; clear it to be safe
3451  $this->clearSharedCache( 'refresh' );
3452  // User was changed in the meantime or loaded with stale data
3453  $from = ( $this->queryFlagsUsed & self::READ_LATEST ) ? 'master' : 'replica';
3454  LoggerFactory::getInstance( 'preferences' )->warning(
3455  "CAS update failed on user_touched for user ID '{user_id}' ({db_flag} read)",
3456  [ 'user_id' => $this->mId, 'db_flag' => $from ]
3457  );
3458  throw new MWException( "CAS update failed on user_touched. " .
3459  "The version of the user to be saved is older than the current version."
3460  );
3461  }
3462 
3463  $dbw->update(
3464  'actor',
3465  [ 'actor_name' => $this->mName ],
3466  [ 'actor_user' => $this->mId ],
3467  $fname
3468  );
3469  } );
3470 
3471  $this->mTouched = $newTouched;
3472  MediaWikiServices::getInstance()->getUserOptionsManager()->saveOptions( $this );
3473 
3474  $this->getHookRunner()->onUserSaveSettings( $this );
3475  $this->clearSharedCache( 'changed' );
3476  $hcu = MediaWikiServices::getInstance()->getHtmlCacheUpdater();
3477  $hcu->purgeTitleUrls( $this->getUserPage(), $hcu::PURGE_INTENT_TXROUND_REFLECTED );
3478  }
3479 
3486  public function idForName( $flags = self::READ_NORMAL ) {
3487  $s = trim( $this->getName() );
3488  if ( $s === '' ) {
3489  return 0;
3490  }
3491 
3492  list( $index, $options ) = DBAccessObjectUtils::getDBOptions( $flags );
3493  $db = wfGetDB( $index );
3494 
3495  $id = $db->selectField( 'user',
3496  'user_id', [ 'user_name' => $s ], __METHOD__, $options );
3497 
3498  return (int)$id;
3499  }
3500 
3516  public static function createNew( $name, $params = [] ) {
3517  foreach ( [ 'password', 'newpassword', 'newpass_time', 'password_expires' ] as $field ) {
3518  if ( isset( $params[$field] ) ) {
3519  wfDeprecated( __METHOD__ . " with param '$field'", '1.27' );
3520  unset( $params[$field] );
3521  }
3522  }
3523 
3524  $user = new User;
3525  $user->load();
3526  $user->setToken(); // init token
3527  if ( isset( $params['options'] ) ) {
3528  MediaWikiServices::getInstance()
3529  ->getUserOptionsManager()
3530  ->loadUserOptions( $user, $user->queryFlagsUsed, $params['options'] );
3531  unset( $params['options'] );
3532  }
3533  $dbw = wfGetDB( DB_MASTER );
3534 
3535  $noPass = PasswordFactory::newInvalidPassword()->toString();
3536 
3537  $fields = [
3538  'user_name' => $name,
3539  'user_password' => $noPass,
3540  'user_newpassword' => $noPass,
3541  'user_email' => $user->mEmail,
3542  'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3543  'user_real_name' => $user->mRealName,
3544  'user_token' => strval( $user->mToken ),
3545  'user_registration' => $dbw->timestamp( $user->mRegistration ),
3546  'user_editcount' => 0,
3547  'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3548  ];
3549  foreach ( $params as $name => $value ) {
3550  $fields["user_$name"] = $value;
3551  }
3552 
3553  return $dbw->doAtomicSection( __METHOD__, function ( IDatabase $dbw, $fname ) use ( $fields ) {
3554  $dbw->insert( 'user', $fields, $fname, [ 'IGNORE' ] );
3555  if ( $dbw->affectedRows() ) {
3556  $newUser = self::newFromId( $dbw->insertId() );
3557  $newUser->mName = $fields['user_name'];
3558  $newUser->updateActorId( $dbw );
3559  // Load the user from master to avoid replica lag
3560  $newUser->load( self::READ_LATEST );
3561  } else {
3562  $newUser = null;
3563  }
3564  return $newUser;
3565  } );
3566  }
3567 
3594  public function addToDatabase() {
3595  $this->load();
3596  if ( !$this->mToken ) {
3597  $this->setToken(); // init token
3598  }
3599 
3600  if ( !is_string( $this->mName ) ) {
3601  throw new RuntimeException( "User name field is not set." );
3602  }
3603 
3604  $this->mTouched = $this->newTouchedTimestamp();
3605 
3606  $dbw = wfGetDB( DB_MASTER );
3607  $status = $dbw->doAtomicSection( __METHOD__, function ( IDatabase $dbw, $fname ) {
3608  $noPass = PasswordFactory::newInvalidPassword()->toString();
3609  $dbw->insert( 'user',
3610  [
3611  'user_name' => $this->mName,
3612  'user_password' => $noPass,
3613  'user_newpassword' => $noPass,
3614  'user_email' => $this->mEmail,
3615  'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3616  'user_real_name' => $this->mRealName,
3617  'user_token' => strval( $this->mToken ),
3618  'user_registration' => $dbw->timestamp( $this->mRegistration ),
3619  'user_editcount' => 0,
3620  'user_touched' => $dbw->timestamp( $this->mTouched ),
3621  ], $fname,
3622  [ 'IGNORE' ]
3623  );
3624  if ( !$dbw->affectedRows() ) {
3625  // Use locking reads to bypass any REPEATABLE-READ snapshot.
3626  $this->mId = $dbw->selectField(
3627  'user',
3628  'user_id',
3629  [ 'user_name' => $this->mName ],
3630  $fname,
3631  [ 'LOCK IN SHARE MODE' ]
3632  );
3633  $loaded = false;
3634  if ( $this->mId && $this->loadFromDatabase( self::READ_LOCKING ) ) {
3635  $loaded = true;
3636  }
3637  if ( !$loaded ) {
3638  throw new MWException( $fname . ": hit a key conflict attempting " .
3639  "to insert user '{$this->mName}' row, but it was not present in select!" );
3640  }
3641  return Status::newFatal( 'userexists' );
3642  }
3643  $this->mId = $dbw->insertId();
3644  self::$idCacheByName[$this->mName] = $this->mId;
3645  $this->updateActorId( $dbw );
3646 
3647  return Status::newGood();
3648  } );
3649  if ( !$status->isGood() ) {
3650  return $status;
3651  }
3652 
3653  // Clear instance cache other than user table data and actor, which is already accurate
3654  $this->clearInstanceCache();
3655 
3656  MediaWikiServices::getInstance()->getUserOptionsManager()->saveOptions( $this );
3657  return Status::newGood();
3658  }
3659 
3664  private function updateActorId( IDatabase $dbw ) {
3665  $dbw->insert(
3666  'actor',
3667  [ 'actor_user' => $this->mId, 'actor_name' => $this->mName ],
3668  __METHOD__
3669  );
3670  $this->mActorId = (int)$dbw->insertId();
3671  }
3672 
3678  public function spreadAnyEditBlock() {
3679  if ( $this->isRegistered() && $this->getBlock() ) {
3680  return $this->spreadBlock();
3681  }
3682 
3683  return false;
3684  }
3685 
3691  protected function spreadBlock() {
3692  wfDebug( __METHOD__ . "()" );
3693  $this->load();
3694  if ( $this->mId == 0 ) {
3695  return false;
3696  }
3697 
3698  $userblock = DatabaseBlock::newFromTarget( $this->getName() );
3699  if ( !$userblock ) {
3700  return false;
3701  }
3702 
3703  return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3704  }
3705 
3710  public function isBlockedFromCreateAccount() {
3711  $this->getBlockedStatus();
3712  if ( $this->mBlock && $this->mBlock->appliesToRight( 'createaccount' ) ) {
3713  return $this->mBlock;
3714  }
3715 
3716  # T15611: if the IP address the user is trying to create an account from is
3717  # blocked with createaccount disabled, prevent new account creation there even
3718  # when the user is logged in
3719  if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3720  $this->mBlockedFromCreateAccount = DatabaseBlock::newFromTarget(
3721  null, $this->getRequest()->getIP()
3722  );
3723  }
3724  return $this->mBlockedFromCreateAccount instanceof AbstractBlock
3725  && $this->mBlockedFromCreateAccount->appliesToRight( 'createaccount' )
3726  ? $this->mBlockedFromCreateAccount
3727  : false;
3728  }
3729 
3734  public function isBlockedFromEmailuser() {
3735  $this->getBlockedStatus();
3736  return $this->mBlock && $this->mBlock->appliesToRight( 'sendemail' );
3737  }
3738 
3745  public function isBlockedFromUpload() {
3746  $this->getBlockedStatus();
3747  return $this->mBlock && $this->mBlock->appliesToRight( 'upload' );
3748  }
3749 
3754  public function isAllowedToCreateAccount() {
3755  return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3756  }
3757 
3763  public function getUserPage() {
3764  return Title::makeTitle( NS_USER, $this->getName() );
3765  }
3766 
3772  public function getTalkPage() {
3773  $title = $this->getUserPage();
3774  return $title->getTalkPage();
3775  }
3776 
3782  public function isNewbie() {
3783  return !$this->isAllowed( 'autoconfirmed' );
3784  }
3785 
3797  public function getEditTokenObject( $salt = '', $request = null ) {
3798  if ( $this->isAnon() ) {
3799  return new LoggedOutEditToken();
3800  }
3801 
3802  if ( !$request ) {
3803  $request = $this->getRequest();
3804  }
3805  return $request->getSession()->getToken( $salt );
3806  }
3807 
3821  public function getEditToken( $salt = '', $request = null ) {
3822  return $this->getEditTokenObject( $salt, $request )->toString();
3823  }
3824 
3837  public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
3838  return $this->getEditTokenObject( $salt, $request )->match( $val, $maxage );
3839  }
3840 
3851  public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
3852  $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . Token::SUFFIX;
3853  return $this->matchEditToken( $val, $salt, $request, $maxage );
3854  }
3855 
3863  public function sendConfirmationMail( $type = 'created' ) {
3864  global $wgLang;
3865  $expiration = null; // gets passed-by-ref and defined in next line.
3866  $token = $this->confirmationToken( $expiration );
3867  $url = $this->confirmationTokenUrl( $token );
3868  $invalidateURL = $this->invalidationTokenUrl( $token );
3869  $this->saveSettings();
3870 
3871  if ( $type == 'created' || $type === false ) {
3872  $message = 'confirmemail_body';
3873  $type = 'created';
3874  } elseif ( $type === true ) {
3875  $message = 'confirmemail_body_changed';
3876  $type = 'changed';
3877  } else {
3878  // Messages: confirmemail_body_changed, confirmemail_body_set
3879  $message = 'confirmemail_body_' . $type;
3880  }
3881 
3882  $mail = [
3883  'subject' => wfMessage( 'confirmemail_subject' )->text(),
3884  'body' => wfMessage( $message,
3885  $this->getRequest()->getIP(),
3886  $this->getName(),
3887  $url,
3888  $wgLang->userTimeAndDate( $expiration, $this ),
3889  $invalidateURL,
3890  $wgLang->userDate( $expiration, $this ),
3891  $wgLang->userTime( $expiration, $this ) )->text(),
3892  'from' => null,
3893  'replyTo' => null,
3894  ];
3895  $info = [
3896  'type' => $type,
3897  'ip' => $this->getRequest()->getIP(),
3898  'confirmURL' => $url,
3899  'invalidateURL' => $invalidateURL,
3900  'expiration' => $expiration
3901  ];
3902 
3903  $this->getHookRunner()->onUserSendConfirmationMail( $this, $mail, $info );
3904  return $this->sendMail( $mail['subject'], $mail['body'], $mail['from'], $mail['replyTo'] );
3905  }
3906 
3918  public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3919  global $wgPasswordSender;
3920 
3921  if ( $from instanceof User ) {
3922  $sender = MailAddress::newFromUser( $from );
3923  } else {
3924  $sender = new MailAddress( $wgPasswordSender,
3925  wfMessage( 'emailsender' )->inContentLanguage()->text() );
3926  }
3927  $to = MailAddress::newFromUser( $this );
3928 
3929  return UserMailer::send( $to, $sender, $subject, $body, [
3930  'replyTo' => $replyto,
3931  ] );
3932  }
3933 
3944  protected function confirmationToken( &$expiration ) {
3946  $now = time();
3947  $expires = $now + $wgUserEmailConfirmationTokenExpiry;
3948  $expiration = wfTimestamp( TS_MW, $expires );
3949  $this->load();
3950  $token = MWCryptRand::generateHex( 32 );
3951  $hash = md5( $token );
3952  $this->mEmailToken = $hash;
3953  $this->mEmailTokenExpires = $expiration;
3954  return $token;
3955  }
3956 
3962  protected function confirmationTokenUrl( $token ) {
3963  return $this->getTokenUrl( 'ConfirmEmail', $token );
3964  }
3965 
3971  protected function invalidationTokenUrl( $token ) {
3972  return $this->getTokenUrl( 'InvalidateEmail', $token );
3973  }
3974 
3989  protected function getTokenUrl( $page, $token ) {
3990  // Hack to bypass localization of 'Special:'
3991  $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
3992  return $title->getCanonicalURL();
3993  }
3994 
4002  public function confirmEmail() {
4003  // Check if it's already confirmed, so we don't touch the database
4004  // and fire the ConfirmEmailComplete hook on redundant confirmations.
4005  if ( !$this->isEmailConfirmed() ) {
4007  $this->getHookRunner()->onConfirmEmailComplete( $this );
4008  }
4009  return true;
4010  }
4011 
4019  public function invalidateEmail() {
4020  $this->load();
4021  $this->mEmailToken = null;
4022  $this->mEmailTokenExpires = null;
4023  $this->setEmailAuthenticationTimestamp( null );
4024  $this->mEmail = '';
4025  $this->getHookRunner()->onInvalidateEmailComplete( $this );
4026  return true;
4027  }
4028 
4033  public function setEmailAuthenticationTimestamp( $timestamp ) {
4034  $this->load();
4035  $this->mEmailAuthenticated = $timestamp;
4036  $this->getHookRunner()->onUserSetEmailAuthenticationTimestamp(
4037  $this, $this->mEmailAuthenticated );
4038  }
4039 
4045  public function canSendEmail() {
4047  if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4048  return false;
4049  }
4050  $hookErr = $this->isEmailConfirmed();
4051  $this->getHookRunner()->onUserCanSendEmail( $this, $hookErr );
4052  return $hookErr;
4053  }
4054 
4060  public function canReceiveEmail() {
4061  return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4062  }
4063 
4074  public function isEmailConfirmed() {
4075  global $wgEmailAuthentication;
4076  $this->load();
4077  // Avoid PHP 7.1 warning of passing $this by reference
4078  $user = $this;
4079  $confirmed = true;
4080  if ( $this->getHookRunner()->onEmailConfirmed( $user, $confirmed ) ) {
4081  if ( $this->isAnon() ) {
4082  return false;
4083  }
4084  if ( !Sanitizer::validateEmail( $this->getEmail() ) ) {
4085  return false;
4086  }
4087  if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4088  return false;
4089  }
4090  return true;
4091  }
4092 
4093  return $confirmed;
4094  }
4095 
4100  public function isEmailConfirmationPending() {
4101  global $wgEmailAuthentication;
4102  return $wgEmailAuthentication &&
4103  !$this->isEmailConfirmed() &&
4104  $this->mEmailToken &&
4105  $this->mEmailTokenExpires > wfTimestamp();
4106  }
4107 
4115  public function getRegistration() {
4116  if ( $this->isAnon() ) {
4117  return false;
4118  }
4119  $this->load();
4120  return $this->mRegistration;
4121  }
4122 
4131  public function getFirstEditTimestamp() {
4132  return MediaWikiServices::getInstance()
4133  ->getUserEditTracker()
4134  ->getFirstEditTimestamp( $this );
4135  }
4136 
4146  public function getLatestEditTimestamp() {
4147  return MediaWikiServices::getInstance()
4148  ->getUserEditTracker()
4149  ->getLatestEditTimestamp( $this );
4150  }
4151 
4161  public static function getGroupPermissions( $groups ) {
4162  return MediaWikiServices::getInstance()->getPermissionManager()->getGroupPermissions( $groups );
4163  }
4164 
4174  public static function getGroupsWithPermission( $role ) {
4175  return MediaWikiServices::getInstance()->getPermissionManager()->getGroupsWithPermission( $role );
4176  }
4177 
4193  public static function groupHasPermission( $group, $role ) {
4194  return MediaWikiServices::getInstance()->getPermissionManager()
4195  ->groupHasPermission( $group, $role );
4196  }
4197 
4205  public static function getAllGroups() {
4206  return MediaWikiServices::getInstance()
4207  ->getUserGroupManager()
4208  ->listAllGroups();
4209  }
4210 
4215  public static function getImplicitGroups() {
4216  return MediaWikiServices::getInstance()
4217  ->getUserGroupManager()
4218  ->listAllImplicitGroups();
4219  }
4220 
4231  public static function changeableByGroup( $group ) {
4233 
4234  $groups = [
4235  'add' => [],
4236  'remove' => [],
4237  'add-self' => [],
4238  'remove-self' => []
4239  ];
4240 
4241  if ( empty( $wgAddGroups[$group] ) ) {
4242  // Don't add anything to $groups
4243  } elseif ( $wgAddGroups[$group] === true ) {
4244  // You get everything
4245  $groups['add'] = self::getAllGroups();
4246  } elseif ( is_array( $wgAddGroups[$group] ) ) {
4247  $groups['add'] = $wgAddGroups[$group];
4248  }
4249 
4250  // Same thing for remove
4251  if ( empty( $wgRemoveGroups[$group] ) ) {
4252  // Do nothing
4253  } elseif ( $wgRemoveGroups[$group] === true ) {
4254  $groups['remove'] = self::getAllGroups();
4255  } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4256  $groups['remove'] = $wgRemoveGroups[$group];
4257  }
4258 
4259  // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4260  if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4261  foreach ( $wgGroupsAddToSelf as $key => $value ) {
4262  if ( is_int( $key ) ) {
4263  $wgGroupsAddToSelf['user'][] = $value;
4264  }
4265  }
4266  }
4267 
4268  if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4269  foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4270  if ( is_int( $key ) ) {
4271  $wgGroupsRemoveFromSelf['user'][] = $value;
4272  }
4273  }
4274  }
4275 
4276  // Now figure out what groups the user can add to him/herself
4277  if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4278  // Do nothing
4279  } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4280  // No idea WHY this would be used, but it's there
4281  $groups['add-self'] = self::getAllGroups();
4282  } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4283  $groups['add-self'] = $wgGroupsAddToSelf[$group];
4284  }
4285 
4286  if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4287  // Do nothing
4288  } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4289  $groups['remove-self'] = self::getAllGroups();
4290  } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4291  $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4292  }
4293 
4294  return $groups;
4295  }
4296 
4304  public function changeableGroups() {
4305  if ( $this->isAllowed( 'userrights' ) ) {
4306  // This group gives the right to modify everything (reverse-
4307  // compatibility with old "userrights lets you change
4308  // everything")
4309  // Using array_merge to make the groups reindexed
4310  $all = array_merge( self::getAllGroups() );
4311  return [
4312  'add' => $all,
4313  'remove' => $all,
4314  'add-self' => [],
4315  'remove-self' => []
4316  ];
4317  }
4318 
4319  // Okay, it's not so simple, we will have to go through the arrays
4320  $groups = [
4321  'add' => [],
4322  'remove' => [],
4323  'add-self' => [],
4324  'remove-self' => []
4325  ];
4326  $addergroups = $this->getEffectiveGroups();
4327 
4328  foreach ( $addergroups as $addergroup ) {
4329  $groups = array_merge_recursive(
4330  $groups, $this->changeableByGroup( $addergroup )
4331  );
4332  $groups['add'] = array_unique( $groups['add'] );
4333  $groups['remove'] = array_unique( $groups['remove'] );
4334  $groups['add-self'] = array_unique( $groups['add-self'] );
4335  $groups['remove-self'] = array_unique( $groups['remove-self'] );
4336  }
4337  return $groups;
4338  }
4339 
4343  public function incEditCount() {
4344  if ( $this->isAnon() ) {
4345  return; // sanity
4346  }
4347 
4349  new UserEditCountUpdate( $this, 1 ),
4350  DeferredUpdates::POSTSEND
4351  );
4352  }
4353 
4359  public function setEditCountInternal( $count ) {
4360  $this->mEditCount = $count;
4361  }
4362 
4370  public function initEditCountInternal( IDatabase $dbr ) {
4371  return MediaWikiServices::getInstance()
4372  ->getUserEditTracker()
4373  ->initializeUserEditCount( $this );
4374  }
4375 
4383  public static function getRightDescription( $right ) {
4384  $key = "right-$right";
4385  $msg = wfMessage( $key );
4386  return $msg->isDisabled() ? $right : $msg->text();
4387  }
4388 
4397  public static function getGrantName( $grant ) {
4398  wfDeprecated( __METHOD__, '1.36' );
4399  return MWGrants::grantName( $grant );
4400  }
4401 
4411  public static function getQueryInfo() {
4412  $ret = [
4413  'tables' => [ 'user', 'user_actor' => 'actor' ],
4414  'fields' => [
4415  'user_id',
4416  'user_name',
4417  'user_real_name',
4418  'user_email',
4419  'user_touched',
4420  'user_token',
4421  'user_email_authenticated',
4422  'user_email_token',
4423  'user_email_token_expires',
4424  'user_registration',
4425  'user_editcount',
4426  'user_actor.actor_id',
4427  ],
4428  'joins' => [
4429  'user_actor' => [ 'JOIN', 'user_actor.actor_user = user_id' ],
4430  ],
4431  ];
4432 
4433  return $ret;
4434  }
4435 
4443  public static function newFatalPermissionDeniedStatus( $permission ) {
4444  global $wgLang;
4445 
4446  $groups = [];
4447  foreach ( MediaWikiServices::getInstance()
4448  ->getPermissionManager()
4449  ->getGroupsWithPermission( $permission ) as $group ) {
4450  $groups[] = UserGroupMembership::getLink( $group, RequestContext::getMain(), 'wiki' );
4451  }
4452 
4453  if ( $groups ) {
4454  return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4455  }
4456 
4457  return Status::newFatal( 'badaccess-group0' );
4458  }
4459 
4469  public function getInstanceForUpdate() {
4470  if ( !$this->getId() ) {
4471  return null; // anon
4472  }
4473 
4474  $user = self::newFromId( $this->getId() );
4475  if ( !$user->loadFromId( self::READ_EXCLUSIVE ) ) {
4476  return null;
4477  }
4478 
4479  return $user;
4480  }
4481 
4489  public function equals( UserIdentity $user ) : bool {
4490  // XXX it's not clear whether central ID providers are supposed to obey this
4491  return $this->getName() === $user->getName();
4492  }
4493 
4499  public function isAllowUsertalk() {
4500  return $this->mAllowUsertalk;
4501  }
4502 
4507  public function getUser(): UserIdentity {
4508  return $this;
4509  }
4510 
4518  public function probablyCan( string $action, PageIdentity $target, PermissionStatus $status = null ): bool {
4519  return $this->getThisAsAuthority()->probablyCan( $action, $target, $status );
4520  }
4521 
4529  public function definitelyCan( string $action, PageIdentity $target, PermissionStatus $status = null ): bool {
4530  return $this->getThisAsAuthority()->definitelyCan( $action, $target, $status );
4531  }
4532 
4540  public function authorizeRead( string $action, PageIdentity $target, PermissionStatus $status = null
4541  ): bool {
4542  return $this->getThisAsAuthority()->authorizeRead( $action, $target, $status );
4543  }
4544 
4552  public function authorizeWrite( string $action, PageIdentity $target, PermissionStatus $status = null ): bool {
4553  return $this->getThisAsAuthority()->authorizeWrite( $action, $target, $status );
4554  }
4555 
4561  private function getThisAsAuthority(): Authority {
4562  if ( !$this->mThisAsAuthority ) {
4563  // TODO: For users that are not User::isGlobalSessionUser,
4564  // creating a UserAuthority here is incorrect, since it depends
4565  // on global WebRequest, but that is what we've used to do before Authority.
4566  // When PermissionManager is refactored into Authority, we need
4567  // to provide base implementation, based on just user groups/rights,
4568  // and use it here.
4569  $this->mThisAsAuthority = new UserAuthority(
4570  $this,
4571  MediaWikiServices::getInstance()->getPermissionManager()
4572  );
4573  }
4574  return $this->mThisAsAuthority;
4575  }
4576 
4581  private function isGlobalSessionUser(): bool {
4582  // The session user is set up towards the end of Setup.php. Until then,
4583  // assume it's a logged-out user.
4584  $sessionUser = RequestContext::getMain()->getUser();
4585  $globalUserName = $sessionUser->isSafeToLoad()
4586  ? $sessionUser->getName()
4587  : IPUtils::sanitizeIP( $sessionUser->getRequest()->getIP() );
4588 
4589  return $this->getName() === $globalUserName;
4590  }
4591 }
User\getDefaultOption
static getDefaultOption( $opt)
Get a given default option value.
Definition: User.php:1607
User\newFromConfirmationCode
static newFromConfirmationCode( $code, $flags=self::READ_NORMAL)
Factory method to fetch whichever user has a given email confirmation code.
Definition: User.php:713
$wgHiddenPrefs
$wgHiddenPrefs
An array of preferences to not show for the user.
Definition: DefaultSettings.php:5426
Page\PageIdentity
Interface for objects (potentially) representing an editable wiki page.
Definition: PageIdentity.php:65
User\loadFromId
loadFromId( $flags=self::READ_NORMAL)
Load user table data, given mId has already been set.
Definition: User.php:446
User\load
load( $flags=self::READ_NORMAL)
Load the user table data for this object from the source given by mFrom.
Definition: User.php:358
User\getNewtalk
getNewtalk()
Check if the user has new messages.
Definition: User.php:2214
MediaWiki\DAO\WikiAwareEntityTrait
trait WikiAwareEntityTrait
Definition: WikiAwareEntityTrait.php:32
Wikimedia\Rdbms\Database
Relational database abstraction object.
Definition: Database.php:50
User\newFromId
static newFromId( $id)
Static factory method for creation from a given user ID.
Definition: User.php:627
Wikimedia\Rdbms\IDatabase\affectedRows
affectedRows()
Get the number of rows affected by the last write query.
User\confirmationTokenUrl
confirmationTokenUrl( $token)
Return a URL the user can use to confirm their email address.
Definition: User.php:3962
User\__set
__set( $name, $value)
Definition: User.php:297
Revision\RevisionRecord
Page revision base class.
Definition: RevisionRecord.php:47
MediaWiki\DAO\deprecateInvalidCrossWiki
deprecateInvalidCrossWiki( $wikiId, string $since)
Emits a deprecation warning $since version if $wikiId is not the same as this wiki.
Definition: WikiAwareEntityTrait.php:70
wfCanIPUseHTTPS
wfCanIPUseHTTPS( $ip)
Determine whether the client at a given source IP is likely to be able to access the wiki via HTTPS.
Definition: GlobalFunctions.php:2760
User\$mToken
string $mToken
Definition: User.php:151
User\$mBlockedby
string int $mBlockedby
Definition: User.php:194
StatusValue\newFatal
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:70
ObjectCache\getLocalClusterInstance
static getLocalClusterInstance()
Get the main cluster-local cache object.
Definition: ObjectCache.php:272
User\isValidPassword
isValidPassword( $password)
Is the input a valid password for this user?
Definition: User.php:1121
User\useFilePatrol
useFilePatrol()
Check whether to enable new files patrol features for this user.
Definition: User.php:3157
$wgMaxArticleSize
$wgMaxArticleSize
Maximum article size in kilobytes.
Definition: DefaultSettings.php:2488
MWCryptHash\hmac
static hmac( $data, $key, $raw=true)
Generate an acceptably unstable one-way-hmac of some text making use of the best hash algorithm that ...
Definition: MWCryptHash.php:106
User\isAnon
isAnon()
Get whether the user is anonymous.
Definition: User.php:3082
User\$mBlockedFromCreateAccount
AbstractBlock bool $mBlockedFromCreateAccount
Definition: User.php:229
User\$mBlockreason
string $mBlockreason
TODO: This should be removed when User::BlockedFor and AbstractBlock::getReason are hard deprecated.
Definition: User.php:202
User\getTokenUrl
getTokenUrl( $page, $token)
Internal function to format the e-mail validation/invalidation URLs.
Definition: User.php:3989
User\isRegistered
isRegistered()
Get whether the user is registered.
Definition: User.php:3064
User\$mCacheVars
static string[] $mCacheVars
List of member variables which are saved to the shared cache (memcached).
Definition: User.php:110
User\resetTokenFromOption
resetTokenFromOption( $oname)
Reset a token stored in the preferences (like the watchlist one).
Definition: User.php:2770
User\isBlockedFrom
isBlockedFrom( $title, $fromReplica=false)
Check if user is blocked from editing a particular article.
Definition: User.php:1966
User\loadFromUserObject
loadFromUserObject( $user)
Load the data for this user object from another user object.
Definition: User.php:1468
WikiMap\isCurrentWikiId
static isCurrentWikiId( $wikiId)
Definition: WikiMap.php:321
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:173
User\newFatalPermissionDeniedStatus
static newFatalPermissionDeniedStatus( $permission)
Factory function for fatal permission-denied errors.
Definition: User.php:4443
User\getEditTokenObject
getEditTokenObject( $salt='', $request=null)
Initialize (if necessary) and return a session token value which can be used in edit forms to show th...
Definition: User.php:3797
User\isBot
isBot()
Definition: User.php:3090
User\newTouchedTimestamp
newTouchedTimestamp()
Generate a current or new-future timestamp to be stored in the user_touched field when we update thin...
Definition: User.php:2326
$wgExperiencedUserMemberSince
$wgExperiencedUserMemberSince
Specify the difference engine to use.
Definition: DefaultSettings.php:9491
User\getEditCount
getEditCount()
Get the user's edit count.
Definition: User.php:3009
User\spreadBlock
spreadBlock()
If this (non-anonymous) user is blocked, block the IP address they've successfully logged in from.
Definition: User.php:3691
if
if(ini_get( 'mbstring.func_overload')) if(!defined('MW_ENTRY_POINT'))
Pre-config setup: Before loading LocalSettings.php.
Definition: Setup.php:87
User\incEditCount
incEditCount()
Schedule a deferred update to update the user's edit count.
Definition: User.php:4343
User\newFromSession
static newFromSession(WebRequest $request=null)
Create a new user object using data from session.
Definition: User.php:726
UserMailer\send
static send( $to, $from, $subject, $body, $options=[])
This function will perform a direct (authenticated) login to a SMTP Server to use for mail relaying i...
Definition: UserMailer.php:115
User\getOptionKinds
getOptionKinds(IContextSource $context, $options=null)
Return an associative array mapping preferences keys to the kind of a preference they're used for.
Definition: User.php:2824
User\isEmailConfirmationPending
isEmailConfirmationPending()
Check whether there is an outstanding request for e-mail confirmation.
Definition: User.php:4100
User\getBlockId
getBlockId()
If user is blocked, return the ID for the block.
Definition: User.php:1995
User\getIntOption
getIntOption( $oname, $defaultOverride=0)
Get the user's current setting for a given option, as an integer value.
Definition: User.php:2708
true
return true
Definition: router.php:90
User\getOptions
getOptions( $flags=0)
Get all user's options.
Definition: User.php:2679
User\$mTouched
string $mTouched
TS_MW timestamp from the DB.
Definition: User.php:147
User\__construct
__construct()
Lightweight constructor for an anonymous user.
Definition: User.php:255
wfTimestamp
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
Definition: GlobalFunctions.php:1832
User\getToken
getToken( $forceCreation=true)
Get the user's current token.
Definition: User.php:2482
User\spreadAnyEditBlock
spreadAnyEditBlock()
If this user is logged-in and blocked, block any IP address they've successfully logged in from.
Definition: User.php:3678
User\getNewMessageRevisionId
getNewMessageRevisionId()
Get the revision ID for the last talk page revision viewed by the talk page owner.
Definition: User.php:2276
User\$mAllowUsertalk
bool $mAllowUsertalk
Definition: User.php:226
$wgEmailAuthentication
$wgEmailAuthentication
Require email authentication before sending mail to an email address.
Definition: DefaultSettings.php:1949
MediaWiki\Permissions\UserAuthority
Represents the authority of a given User.
Definition: UserAuthority.php:42
DeferredUpdates\addUpdate
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the pending update queue for execution at the appropriate time.
Definition: DeferredUpdates.php:119
User\setEmailWithConfirmation
setEmailWithConfirmation( $str)
Set the user's e-mail address and a confirmation mail if needed.
Definition: User.php:2579
$wgEnableUserEmail
$wgEnableUserEmail
Set to true to enable user-to-user e-mail.
Definition: DefaultSettings.php:1837
User\$mHideName
bool $mHideName
Definition: User.php:213
User\getStubThreshold
getStubThreshold()
Get the user preferred stub threshold.
Definition: User.php:2904
Sanitizer\validateEmail
static validateEmail( $addr)
Does a string look like an e-mail address?
Definition: Sanitizer.php:1707
wfReadOnly
wfReadOnly()
Check whether the wiki is in read-only mode.
Definition: GlobalFunctions.php:1135
User\$mLocked
bool $mLocked
Definition: User.php:206
User\newFromName
static newFromName( $name, $validate='valid')
Definition: User.php:586
User\loadFromRow
loadFromRow( $row, $data=null)
Initialize this object from a row from the user table.
Definition: User.php:1360
wfMessage
wfMessage( $key,... $params)
This is the function for getting translated interface messages.
Definition: GlobalFunctions.php:1231
User\setEmailAuthenticationTimestamp
setEmailAuthenticationTimestamp( $timestamp)
Set the e-mail authentication timestamp.
Definition: User.php:4033
User\$mEmail
string $mEmail
Definition: User.php:145
User\getUserPage
getUserPage()
Get this user's personal page title.
Definition: User.php:3763
User\getGroups
getGroups()
Get the list of explicit group memberships this user has.
Definition: User.php:2935
User\newFromIdentity
static newFromIdentity(UserIdentity $identity)
Returns a User object corresponding to the given UserIdentity.
Definition: User.php:663
wfLogWarning
wfLogWarning( $msg, $callerOffset=1, $level=E_USER_WARNING)
Send a warning as a PHP error and the debug log.
Definition: GlobalFunctions.php:1094
User\useNPPatrol
useNPPatrol()
Check whether to enable new pages patrol features for this user.
Definition: User.php:3145
DBAccessObjectUtils\getDBOptions
static getDBOptions( $bitfield)
Get an appropriate DB index, options, and fallback DB index for a query.
Definition: DBAccessObjectUtils.php:52
User\getDatePreference
getDatePreference()
Get the user's preferred date format.
Definition: User.php:2862
User\isSafeToLoad
isSafeToLoad()
Test if it's safe to load this User object.
Definition: User.php:341
User\setEmail
setEmail( $str)
Set the user's e-mail address.
Definition: User.php:2562
$success
$success
Definition: NoLocalSettings.php:42
User\isValidUserName
static isValidUserName( $name)
Is the input a valid username?
Definition: User.php:1040
Wikimedia\Rdbms\IDatabase\selectField
selectField( $table, $var, $cond='', $fname=__METHOD__, $options=[], $join_conds=[])
A SELECT wrapper which returns a single field from a single result row.
User\sendConfirmationMail
sendConfirmationMail( $type='created')
Generate a new e-mail confirmation token and send a confirmation/invalidation mail to the user's give...
Definition: User.php:3863
User\groupHasPermission
static groupHasPermission( $group, $role)
Check, if the given group has the given permission.
Definition: User.php:4193
User\getEmailAuthenticationTimestamp
getEmailAuthenticationTimestamp()
Get the timestamp of the user's e-mail authentication.
Definition: User.php:2551
User\pingLimiter
pingLimiter( $action='edit', $incrBy=1)
Primitive rate limits: enforce maximum actions per time period to put a brake on flooding.
Definition: User.php:1706
User\getActorId
getActorId( $dbwOrWikiId=self::LOCAL)
Get the user's actor ID.
Definition: User.php:2159
UserEditCountUpdate
Handles increment the edit count for a given set of users.
Definition: UserEditCountUpdate.php:29
IDBAccessObject
Interface for database access objects.
Definition: IDBAccessObject.php:57
User\useRCPatrol
useRCPatrol()
Check whether to enable recent changes patrol features for this user.
Definition: User.php:3136
WikiMap\getCurrentWikiId
static getCurrentWikiId()
Definition: WikiMap.php:303
User\invalidateEmail
invalidateEmail()
Invalidate the user's e-mail confirmation, and unauthenticate the e-mail address if it was already co...
Definition: User.php:4019
User\newFromRow
static newFromRow( $row, $data=null)
Create a new user object from a user row.
Definition: User.php:748
$wgUseRCPatrol
$wgUseRCPatrol
Use RC Patrolling to check for vandalism (from recent changes and watchlists) New pages and new files...
Definition: DefaultSettings.php:7427
User\$mHash
string $mHash
Definition: User.php:196
$wgUseNPPatrol
$wgUseNPPatrol
Use new page patrolling to check new pages on Special:Newpages.
Definition: DefaultSettings.php:7443
$wgLang
$wgLang
Definition: Setup.php:782
MediaWiki\User\UserIdentity
Interface for objects representing user identity.
Definition: UserIdentity.php:39
User\isIPRange
isIPRange()
Is the user an IP range?
Definition: User.php:1024
User\probablyCan
probablyCan(string $action, PageIdentity $target, PermissionStatus $status=null)
Definition: User.php:4518
MailAddress\newFromUser
static newFromUser(User $user)
Create a new MailAddress object for the given user.
Definition: MailAddress.php:70
User\getRights
getRights()
Get the permissions this user has.
Definition: User.php:2923
User\createNew
static createNew( $name, $params=[])
Add a user to the database, return the user object.
Definition: User.php:3516
User\getRequest
getRequest()
Get the WebRequest object to use with this object.
Definition: User.php:3170
Wikimedia\Rdbms\IDatabase
Basic database interface for live and lazy-loaded relation database handles.
Definition: IDatabase.php:38
User\getWikiId
getWikiId()
Returns self::LOCAL to indicate the user is associated with the local wiki.
Definition: User.php:265
User\getAutomaticGroups
getAutomaticGroups( $recache=false)
Get the list of implicit group memberships this user has.
Definition: User.php:2982
User\INVALID_TOKEN
const INVALID_TOKEN
An invalid string value for the user_token field.
Definition: User.php:78
NS_MAIN
const NS_MAIN
Definition: Defines.php:64
User\getDefaultOptions
static getDefaultOptions()
Combine the language default options with any site-specific options and add the default language vari...
Definition: User.php:1593
User\getInstanceForUpdate
getInstanceForUpdate()
Get a new instance of this user that was loaded from the master via a locking read.
Definition: User.php:4469
$dbr
$dbr
Definition: testCompression.php:54
$wgExperiencedUserEdits
$wgExperiencedUserEdits
Specify the difference engine to use.
Definition: DefaultSettings.php:9490
User\newSystemUser
static newSystemUser( $name, $options=[])
Static factory method for creation of a "system" user from username.
Definition: User.php:789
Wikimedia\Rdbms\IDatabase\update
update( $table, $set, $conds, $fname=__METHOD__, $options=[])
Update all rows in a table that match a given condition.
Revision
Definition: Revision.php:40
User\addGroup
addGroup( $group, $expiry=null)
Add the user to the given group.
Definition: User.php:3035
MailAddress
Stores a single person's name and email address.
Definition: MailAddress.php:34
MWExceptionHandler\logException
static logException(Throwable $e, $catcher=self::CAUGHT_BY_OTHER, $extraData=[])
Log a throwable to the exception log (if enabled).
Definition: MWExceptionHandler.php:666
LoggedOutEditToken
Value object representing a logged-out user's edit token.
Definition: LoggedOutEditToken.php:37
User\matchEditToken
matchEditToken( $val, $salt='', $request=null, $maxage=null)
Check given value against the token value stored in the session.
Definition: User.php:3837
User\getEmail
getEmail()
Get the user's e-mail address.
Definition: User.php:2541
MediaWiki\Block\DatabaseBlock
A DatabaseBlock (unlike a SystemBlock) is stored in the database, may give rise to autoblocks and may...
Definition: DatabaseBlock.php:53
User\getTalkPage
getTalkPage()
Get this user's talk page title.
Definition: User.php:3772
User\addToDatabase
addToDatabase()
Add this existing user object to the database.
Definition: User.php:3594
Wikimedia\Rdbms\IDatabase\timestamp
timestamp( $ts=0)
Convert a timestamp in one of the formats accepted by ConvertibleTimestamp to the format used for ins...
User\invalidateCache
invalidateCache()
Immediately touch the user data cache for this account.
Definition: User.php:2371
wfDeprecatedMsg
wfDeprecatedMsg( $msg, $version=false, $component=false, $callerOffset=2)
Log a deprecation warning with arbitrary message text.
Definition: GlobalFunctions.php:1066
MWException
MediaWiki exception.
Definition: MWException.php:29
User\invalidationTokenUrl
invalidationTokenUrl( $token)
Return a URL the user can use to invalidate their email address.
Definition: User.php:3971
User\isLocked
isLocked()
Check if user account is locked.
Definition: User.php:2053
User\$mDatePreference
string $mDatePreference
Lazy-initialized variables, invalidated with clearInstanceCache.
Definition: User.php:187
$wgAuthenticationTokenVersion
string null $wgAuthenticationTokenVersion
Versioning for authentication tokens.
Definition: DefaultSettings.php:5464
wfDeprecated
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Logs a warning that $function is deprecated.
Definition: GlobalFunctions.php:1034
User\authorizeWrite
authorizeWrite(string $action, PageIdentity $target, PermissionStatus $status=null)
Definition: User.php:4552
MediaWiki\Logger\LoggerFactory
PSR-3 logger instance factory.
Definition: LoggerFactory.php:45
User\checkPasswordValidity
checkPasswordValidity( $password)
Check if this is a valid password for this user.
Definition: User.php:1147
User\confirmEmail
confirmEmail()
Mark the e-mail address confirmed.
Definition: User.php:4002
User\setItemLoaded
setItemLoaded( $item)
Set that an item has been loaded.
Definition: User.php:1271
UserGroupMembership\getLink
static getLink( $ugm, IContextSource $context, $format, $userName=null)
Gets a link for a user group, possibly including the expiry date if relevant.
Definition: UserGroupMembership.php:121
User\blockedFor
blockedFor()
If user is blocked, return the specified reason for the block.
Definition: User.php:1986
User\setNewtalk
setNewtalk( $val, $curRev=null)
Update the 'You have new messages!' status.
Definition: User.php:2304
wfGetDB
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Definition: GlobalFunctions.php:2467
$wgFullyInitialised
if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) if(! $wgCommandLineMode) $wgFullyInitialised
Definition: Setup.php:836
User\isTempWatched
isTempWatched( $title, $checkRights=self::CHECK_USER_RIGHTS)
Check if the article is temporarily watched.
Definition: User.php:3202
User\isAllowedToCreateAccount
isAllowedToCreateAccount()
Get whether the user is allowed to create an account.
Definition: User.php:3754
User\logout
logout()
Log this user out.
Definition: User.php:3363
User\confirmationToken
confirmationToken(&$expiration)
Generate, store, and return a new e-mail confirmation code.
Definition: User.php:3944
User\initEditCountInternal
initEditCountInternal(IDatabase $dbr)
Initialize user_editcount from data out of the revision table.
Definition: User.php:4370
User\getCacheKey
getCacheKey(WANObjectCache $cache)
Definition: User.php:487
wfTimestampOrNull
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
Definition: GlobalFunctions.php:1848
User\getImplicitGroups
static getImplicitGroups()
Definition: User.php:4215
User\isHidden
isHidden()
Check if user account is hidden.
Definition: User.php:2068
User\definitelyCan
definitelyCan(string $action, PageIdentity $target, PermissionStatus $status=null)
Definition: User.php:4529
MWGrants\grantName
static grantName( $grant, $lang=null)
Fetch the display name of the grant.
Definition: MWGrants.php:57
User\isBlockedFromEmailuser
isBlockedFromEmailuser()
Get whether the user is blocked from using Special:Emailuser.
Definition: User.php:3734
User\$mBlock
AbstractBlock null $mBlock
Definition: User.php:223
User\loadDefaults
loadDefaults( $name=false, $actorId=null)
Set cached properties to default.
Definition: User.php:1223
User\isIP
static isIP( $name)
Does the string match an anonymous IP address?
Definition: User.php:1012
User\validateCache
validateCache( $timestamp)
Validate the cache for this account.
Definition: User.php:2403
User\getEffectiveGroups
getEffectiveGroups( $recache=false)
Get the list of implicit group memberships this user has.
Definition: User.php:2966
User\isPingLimitable
isPingLimitable()
Is this user subject to rate limiting?
Definition: User.php:1679
User\removeGroup
removeGroup( $group)
Remove the user from the given group.
Definition: User.php:3050
User\canReceiveEmail
canReceiveEmail()
Is this user allowed to receive e-mails within limits of current site configuration?
Definition: User.php:4060
User\isNewbie
isNewbie()
Determine whether the user is a newbie.
Definition: User.php:3782
User\touch
touch()
Update the "touched" timestamp for the user.
Definition: User.php:2388
MediaWiki\User\UserIdentity\getName
getName()
$title
$title
Definition: testCompression.php:38
User\clearInstanceCache
clearInstanceCache( $reloadFrom=false)
Clear various cached data stored in this object.
Definition: User.php:1562
$wgEnableEmail
$wgEnableEmail
Set to true to enable the e-mail basic features: Password reminders, etc.
Definition: DefaultSettings.php:1831
User\CHECK_USER_RIGHTS
const CHECK_USER_RIGHTS
Definition: User.php:96
User\TOKEN_LENGTH
const TOKEN_LENGTH
Number of characters required for the user_token field.
Definition: User.php:73
Title\makeTitle
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:626
DB_REPLICA
const DB_REPLICA
Definition: defines.php:25
wfTimestampNow
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
Definition: GlobalFunctions.php:1861
User\$mQuickTouched
string $mQuickTouched
TS_MW timestamp from cache.
Definition: User.php:149
User\newFromAnyId
static newFromAnyId( $userId, $userName, $actorId, $dbDomain=false)
Static factory method for creation from an ID, name, and/or actor ID.
Definition: User.php:692
User\getId
getId( $wikiId=self::LOCAL)
Get the user's ID.
Definition: User.php:2081
User\setName
setName( $str)
Set the user name.
Definition: User.php:2141
DB_MASTER
const DB_MASTER
Definition: defines.php:26
User\$mRealName
string $mRealName
Definition: User.php:142
User\resetOptions
resetOptions( $resetKinds=[ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused'], IContextSource $context=null)
Reset certain (or all) options to the site defaults.
Definition: User.php:2845
UserArray\newFromIDs
static newFromIDs( $ids)
Definition: UserArray.php:52
User\getBlockedStatus
getBlockedStatus( $fromReplica=true, $disableIpBlockExemptChecking=false)
Get blocking information.
Definition: User.php:1625
UserPasswordPolicy
Check if a user's password complies with any password policies that apply to that user,...
Definition: UserPasswordPolicy.php:28
$wgUseFilePatrol
$wgUseFilePatrol
Use file patrolling to check new files on Special:Newfiles.
Definition: DefaultSettings.php:7454
wfDebug
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
Definition: GlobalFunctions.php:915
User\__get
& __get( $name)
Definition: User.php:276
$wgRemoveGroups
$wgRemoveGroups
Definition: DefaultSettings.php:6039
User\clearNotification
clearNotification(&$title, $oldid=0)
Clear the user's notification timestamp for the given title.
Definition: User.php:3272
User\saveSettings
saveSettings()
Save this user's settings into the database.
Definition: User.php:3411
User\isAllowedAll
isAllowedAll(... $permissions)
Checks whether this authority has any of the given permissions in general.
Definition: User.php:3124
User\getFirstEditTimestamp
getFirstEditTimestamp()
Get the timestamp of the first edit.
Definition: User.php:4131
User\authorizeRead
authorizeRead(string $action, PageIdentity $target, PermissionStatus $status=null)
Definition: User.php:4540
User\GETOPTIONS_EXCLUDE_DEFAULTS
const GETOPTIONS_EXCLUDE_DEFAULTS
Exclude user options that are set to their default value.
Definition: User.php:91
MediaWiki\Permissions\Authority
Definition: Authority.php:30
User\setRealName
setRealName( $str)
Set the user's real name.
Definition: User.php:2644
User\getNewMessageLinks
getNewMessageLinks()
Return the data needed to construct links for new talk page message alerts.
Definition: User.php:2237
User\getBlock
getBlock( $fromReplica=true, $disableIpBlockExemptChecking=false)
Get the block affecting the user, or null if the user is not blocked.
Definition: User.php:1950
Title\makeTitleSafe
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
Definition: Title.php:652
User\getFormerGroups
getFormerGroups()
Returns the groups the user has belonged to.
Definition: User.php:2999
MediaWiki\DAO\WikiAwareEntity\assertWiki
assertWiki( $wikiId)
Throws if $wikiId is different from the return value of getWikiId().
$s
foreach( $mmfl['setupFiles'] as $fileName) if( $queue) if(empty( $mmfl['quiet'])) $s
Definition: mergeMessageFileList.php:206
User\whoIs
static whoIs( $id)
Get the username corresponding to a given user ID.
Definition: User.php:928
DBAccessObjectUtils\hasFlags
static hasFlags( $bitfield, $flags)
Definition: DBAccessObjectUtils.php:35
User\isAllowedAny
isAllowedAny(... $permissions)
Checks whether this authority has any of the given permissions in general.
Definition: User.php:3120
User\loadFromSession
loadFromSession()
Load user data from the session.
Definition: User.php:1282
$wgRateLimits
$wgRateLimits
Simple rate limiter options to brake edit floods.
Definition: DefaultSettings.php:6204
User\isBlockedGlobally
isBlockedGlobally( $ip='')
Check if user is blocked on all wikis.
Definition: User.php:2008
$wgForceHTTPS
bool $wgForceHTTPS
If this is true, when an insecure HTTP request is received, always redirect to HTTPS.
Definition: DefaultSettings.php:165
User\getOption
getOption( $oname, $defaultOverride=null, $ignoreHidden=false)
Get the user's current setting for a given option.
Definition: User.php:2661
User\idForName
idForName( $flags=self::READ_NORMAL)
If only this user's username is known, and it exists, return the user ID.
Definition: User.php:3486
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:82
Wikimedia\Rdbms\IDatabase\selectRow
selectRow( $table, $vars, $conds, $fname=__METHOD__, $options=[], $join_conds=[])
Wrapper to IDatabase::select() that only fetches one row (via LIMIT)
User\getTouched
getTouched()
Get the user touched timestamp.
Definition: User.php:2415
User\$mId
int $mId
Cache variables.
Definition: User.php:132
User\isSystemUser
isSystemUser()
Get whether the user is a system user.
Definition: User.php:3110
User\getGlobalBlock
getGlobalBlock( $ip='')
Check if user is blocked on all wikis.
Definition: User.php:2022
User\__toString
__toString()
Definition: User.php:272
MediaWiki\Block\SystemBlock
System blocks are temporary blocks that are created on enforcement (e.g.
Definition: SystemBlock.php:33
MediaWiki\Session\SessionManager
This serves as the entry point to the MediaWiki session handling system.
Definition: SessionManager.php:53
User\checkAndSetTouched
checkAndSetTouched()
Bump user_touched if it didn't change since this object was loaded.
Definition: User.php:1524
WANObjectCache
Multi-datacenter aware caching interface.
Definition: WANObjectCache.php:125
User\getRealName
getRealName()
Get the user's real name.
Definition: User.php:2632
User\updateActorId
updateActorId(IDatabase $dbw)
Update the actor ID after an insert.
Definition: User.php:3664
User\setCookies
setCookies( $request=null, $secure=null, $rememberMe=false)
Persist this user's session (e.g.
Definition: User.php:3327
User\getGroupPermissions
static getGroupPermissions( $groups)
Get the permissions associated with a given list of groups.
Definition: User.php:4161
User\changeableGroups
changeableGroups()
Returns an array of groups that this user can add and remove.
Definition: User.php:4304
User\addWatch
addWatch( $title, $checkRights=self::CHECK_USER_RIGHTS, ?string $expiry=null)
Watch an article.
Definition: User.php:3219
User\VERSION
const VERSION
Version number to tag cached versions of serialized User objects.
Definition: User.php:84
User\matchEditTokenNoSuffix
matchEditTokenNoSuffix( $val, $salt='', $request=null, $maxage=null)
Check given value against the token value stored in the session, ignoring the suffix.
Definition: User.php:3851
$wgAddGroups
$wgAddGroups
$wgAddGroups and $wgRemoveGroups can be used to give finer control over who can assign which groups a...
Definition: DefaultSettings.php:6034
User\getAllGroups
static getAllGroups()
Return the set of defined explicit groups.
Definition: User.php:4205
User\removeWatch
removeWatch( $title, $checkRights=self::CHECK_USER_RIGHTS)
Stop watching an article.
Definition: User.php:3245
NS_USER
const NS_USER
Definition: Defines.php:66
MWCryptRand\generateHex
static generateHex( $chars)
Generate a run of cryptographically random data and return it in hexadecimal string format.
Definition: MWCryptRand.php:36
User\isBlockedFromUpload
isBlockedFromUpload()
Get whether the user is blocked from using Special:Upload.
Definition: User.php:3745
User\setActorId
setActorId(int $actorId)
Sets the actor id.
Definition: User.php:2195
RequestContext\getMain
static getMain()
Get the RequestContext object associated with the main request.
Definition: RequestContext.php:476
User\getQueryInfo
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new user object.
Definition: User.php:4411
MediaWiki\User\UserOptionsLookup
Provides access to user options.
Definition: UserOptionsLookup.php:29
User\blockedBy
blockedBy()
If user is blocked, return the name of the user who placed the block.
Definition: User.php:1975
User\$mLoadedItems
array bool $mLoadedItems
Array with already loaded items or true if all items have been loaded.
Definition: User.php:168
$wgLearnerEdits
$wgLearnerEdits
The following variables define 3 user experience levels:
Definition: DefaultSettings.php:9488
User\getDBTouched
getDBTouched()
Get the user_touched timestamp field (time of last DB updates)
Definition: User.php:2437
Wikimedia\Rdbms\IDatabase\insert
insert( $table, $rows, $fname=__METHOD__, $options=[])
Insert the given row(s) into a table.
MediaWiki\Auth\AuthManager
This serves as the entry point to the authentication system.
Definition: AuthManager.php:93
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:57
WebRequest
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
Definition: WebRequest.php:42
MediaWiki\Permissions\PermissionStatus
A StatusValue for permission errors.
Definition: PermissionStatus.php:34
User\changeableByGroup
static changeableByGroup( $group)
Returns an array of the groups that a particular group can add/remove.
Definition: User.php:4231
User\setId
setId( $v)
Set the user and reload all fields according to a given ID.
Definition: User.php:2104
User\getExperienceLevel
getExperienceLevel()
Compute experienced level based on edit count and registration date.
Definition: User.php:3284
$wgUserEmailConfirmationTokenExpiry
$wgUserEmailConfirmationTokenExpiry
The time, in seconds, when an email confirmation email expires.
Definition: DefaultSettings.php:1881
User\getRegistration
getRegistration()
Get the timestamp of account creation.
Definition: User.php:4115
User\isAllowed
isAllowed(string $permission)
Checks whether this authority has the given permission in general.
Definition: User.php:3128
PasswordFactory\newInvalidPassword
static newInvalidPassword()
Create an InvalidPassword.
Definition: PasswordFactory.php:242
MediaWiki\Block\AbstractBlock\appliesToRight
appliesToRight( $right)
Determine whether the block prevents a given right.
Definition: AbstractBlock.php:291
User\getRightDescription
static getRightDescription( $right)
Get the description of a given right.
Definition: User.php:4383
User\changeAuthenticationData
changeAuthenticationData(array $data)
Changes credentials of the user.
Definition: User.php:2455
$cache
$cache
Definition: mcc.php:33
$wgRateLimitsExcludedIPs
$wgRateLimitsExcludedIPs
Array of IPs / CIDR ranges which should be excluded from rate limits.
Definition: DefaultSettings.php:6286
User\isLoggedIn
isLoggedIn()
Get whether the user is registered.
Definition: User.php:3074
Wikimedia\Rdbms\DBExpectedError
Base class for the more common types of database errors.
Definition: DBExpectedError.php:34
User\$mActorId
int null $mActorId
Switched from protected to public for use in UserFactory.
Definition: User.php:140
User\getTitleKey
getTitleKey()
Get the user's name escaped by underscores.
Definition: User.php:2205
User\purge
static purge( $dbDomain, $userId)
Definition: User.php:476
User\setToken
setToken( $token=false)
Set the random token (used for persistent authentication) Called from loadDefaults() among other plac...
Definition: User.php:2525
User\idFromName
static idFromName( $name, $flags=self::READ_NORMAL)
Get database id given a user name.
Definition: User.php:948
MediaWiki\User\UserNameUtils
UserNameUtils service.
Definition: UserNameUtils.php:42
User\resetIdByNameCache
static resetIdByNameCache()
Reset the cache used in idFromName().
Definition: User.php:990
User\$mEmailTokenExpires
string $mEmailTokenExpires
Definition: User.php:157
User\findUsersByGroup
static findUsersByGroup( $groups, $limit=5000, $after=null)
Return the users who are members of the given group(s).
Definition: User.php:1070
User\getCanonicalName
static getCanonicalName( $name, $validate='valid')
Given unvalidated user input, return a canonical username, or false if the username is invalid.
Definition: User.php:1191
User\isEmailConfirmed
isEmailConfirmed()
Is this user's e-mail address valid-looking and confirmed within limits of the current site configura...
Definition: User.php:4074
User\$mGlobalBlock
AbstractBlock $mGlobalBlock
Definition: User.php:204
User\isAllowUsertalk
isAllowUsertalk()
Checks if usertalk is allowed.
Definition: User.php:4499
User\$idCacheByName
static int[] $idCacheByName
Definition: User.php:238
User\getGrantName
static getGrantName( $grant)
Get the name of a given grant.
Definition: User.php:4397
UserCache\singleton
static singleton()
Definition: UserCache.php:48
User\clearSharedCache
clearSharedCache( $mode='refresh')
Clear user data from memcached.
Definition: User.php:2345
User\isBlocked
isBlocked( $fromReplica=true)
Check if user is blocked.
Definition: User.php:1938
User\newFromActorId
static newFromActorId( $id)
Static factory method for creation from a given actor ID.
Definition: User.php:644
User\$mThisAsAuthority
Authority null $mThisAsAuthority
lazy-initialized Authority of this user
Definition: User.php:235
$keys
$keys
Definition: testCompression.php:72
User\loadFromCache
loadFromCache()
Load user data from shared cache, given mId has already been set.
Definition: User.php:510
$wgLearnerMemberSince
$wgLearnerMemberSince
Specify the difference engine to use.
Definition: DefaultSettings.php:9489
User\addAutopromoteOnceGroups
addAutopromoteOnceGroups( $event)
Add the user to the group if he/she meets given criteria.
Definition: User.php:1490
User\sendMail
sendMail( $subject, $body, $from=null, $replyto=null)
Send an e-mail to this user's account.
Definition: User.php:3918
User\getTokenFromOption
getTokenFromOption( $oname)
Get a token stored in the preferences (like the watchlist one), resetting it if it's empty (and savin...
Definition: User.php:2742
User\$mEmailToken
string $mEmailToken
Definition: User.php:155
Wikimedia\Rdbms\IDatabase\timestampOrNull
timestampOrNull( $ts=null)
Convert a timestamp in one of the formats accepted by ConvertibleTimestamp to the format used for ins...
$wgGroupsRemoveFromSelf
$wgGroupsRemoveFromSelf
Definition: DefaultSettings.php:5818
User\equals
equals(UserIdentity $user)
Checks if two user objects point to the same user.
Definition: User.php:4489
User\loadFromDatabase
loadFromDatabase( $flags=self::READ_LATEST)
Load user data from the database.
Definition: User.php:1308
User\$mName
string $mName
Definition: User.php:134
User\$mRegistration
string $mRegistration
Definition: User.php:159
MediaWiki\Block\AbstractBlock
Definition: AbstractBlock.php:37
$wgPasswordPolicy
$wgPasswordPolicy
Password policy for the wiki.
Definition: DefaultSettings.php:4964
User\IGNORE_USER_RIGHTS
const IGNORE_USER_RIGHTS
Definition: User.php:101
User\$mRequest
WebRequest $mRequest
Definition: User.php:216
MediaWiki\Session\Token
Value object representing a CSRF token.
Definition: Token.php:32
CentralIdLookup\AUDIENCE_RAW
const AUDIENCE_RAW
Definition: CentralIdLookup.php:34
User\isWatched
isWatched( $title, $checkRights=self::CHECK_USER_RIGHTS)
Check the watched status of an article.
Definition: User.php:3185
User\getBoolOption
getBoolOption( $oname)
Get the user's current setting for a given option, as a boolean value.
Definition: User.php:2693
Wikimedia\Rdbms\IDatabase\insertId
insertId()
Get the inserted value of an auto-increment row.
$wgGroupsAddToSelf
$wgGroupsAddToSelf
A map of group names that the user is in, to group names that those users are allowed to add or revok...
Definition: DefaultSettings.php:5813
User\isUsableName
static isUsableName( $name)
Usernames which fail to pass this function will be blocked from user login and new account registrati...
Definition: User.php:1056
User\makeUpdateConditions
makeUpdateConditions(IDatabase $db, array $conditions)
Builds update conditions.
Definition: User.php:1505
$wgPasswordSender
$wgPasswordSender
Sender email address for e-mail notifications.
Definition: DefaultSettings.php:1817
User\__sleep
__sleep()
Definition: User.php:318
User\isBlockedFromCreateAccount
isBlockedFromCreateAccount()
Get whether the user is explicitly blocked from account creation.
Definition: User.php:3710
User\getEditToken
getEditToken( $salt='', $request=null)
Initialize (if necessary) and return a session token value which can be used in edit forms to show th...
Definition: User.php:3821
User\requiresHTTPS
requiresHTTPS()
Determine based on the wiki configuration and the user's options, whether this user must be over HTTP...
Definition: User.php:2882
User\isItemLoaded
isItemLoaded( $item, $all='all')
Return whether an item has been loaded.
Definition: User.php:1259
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:66
User\setOption
setOption( $oname, $val)
Set the given option for a user.
Definition: User.php:2726
User\$queryFlagsUsed
int $queryFlagsUsed
User::READ_* constant bitfield used to load data.
Definition: User.php:232
User\whoIsReal
static whoIsReal( $id)
Get the real name of a user given their user ID.
Definition: User.php:938
ExternalUserNames\isExternal
static isExternal( $username)
Tells whether the username is external or not.
Definition: ExternalUserNames.php:147
User\getName
getName()
Get the user name, or the IP of an anonymous user.
Definition: User.php:2113
$wgSecureLogin
$wgSecureLogin
This is to let user authenticate using https when they come from http.
Definition: DefaultSettings.php:5452
User\doLogout
doLogout()
Clear the user's session, and reset the instance cache.
Definition: User.php:3375
MediaWiki\User\UserFactory
Creates User objects.
Definition: UserFactory.php:41
User\getGroupMemberships
getGroupMemberships()
Get the list of explicit group memberships this user has, stored as UserGroupMembership objects.
Definition: User.php:2950
User\canSendEmail
canSendEmail()
Is this user allowed to send e-mails within limits of current site configuration?
Definition: User.php:4045
User\isCreatableName
static isCreatableName( $name)
Usernames which fail to pass this function will be blocked from new account registrations,...
Definition: User.php:1111
Wikimedia\Rdbms\IDatabase\delete
delete( $table, $conds, $fname=__METHOD__)
Delete all rows in a table that match a condition.
User\isGlobalSessionUser
isGlobalSessionUser()
Check whether this is the global session user.
Definition: User.php:4581
User\getUser
getUser()
Definition: User.php:4507
CentralIdLookup\factoryNonLocal
static factoryNonLocal()
Returns a CentralIdLookup that is guaranteed to be non-local.
Definition: CentralIdLookup.php:83
User\getMutableCacheKeys
getMutableCacheKeys(WANObjectCache $cache)
Definition: User.php:498
MediaWiki\Auth\AuthenticationRequest
This is a value object for authentication requests.
Definition: AuthenticationRequest.php:38
User\getLatestEditTimestamp
getLatestEditTimestamp()
Get the timestamp of the latest edit.
Definition: User.php:4146
User\setEditCountInternal
setEditCountInternal( $count)
This method should not be called outside User/UserEditCountUpdate.
Definition: User.php:4359
User\$mEditCount
int $mEditCount
Definition: User.php:161
User\$mEmailAuthenticated
string $mEmailAuthenticated
Definition: User.php:153
User\getGroupsWithPermission
static getGroupsWithPermission( $role)
Get all the groups who have a given permission.
Definition: User.php:4174
User\$mFrom
string $mFrom
Initialization data source if mLoadedItems!==true.
Definition: User.php:181
User\listOptionKinds
static listOptionKinds()
Return a list of the types of user options currently returned by User::getOptionKinds().
Definition: User.php:2805
User\getThisAsAuthority
getThisAsAuthority()
Returns the Authority of this User if it's the main request context user.
Definition: User.php:4561
$type
$type
Definition: testCompression.php:52