Go to the documentation of this file.
31 use Wikimedia\Assert\Assert;
33 use Wikimedia\ScopedCallback;
94 'mEmailAuthenticated',
161 'move-categorypages',
162 'move-rootuserpages',
166 'override-export-depth',
188 'userrights-interwiki',
324 return (
string)$this->
getName();
350 $this->mLoadedItems ===
true || $this->mFrom !==
'session';
358 public function load( $flags = self::READ_NORMAL ) {
361 if ( $this->mLoadedItems ===
true ) {
367 $this->mLoadedItems =
true;
368 $this->queryFlagsUsed = $flags;
373 ->warning(
'User::loadFromSession called before the end of Setup.php', [
374 'exception' =>
new Exception(
'User::loadFromSession called before the end of Setup.php' ),
377 $this->mLoadedItems = $oldLoadedItems;
381 switch ( $this->mFrom ) {
387 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
388 if ( $lb->hasOrMadeRecentMasterChanges() ) {
389 $flags |= self::READ_LATEST;
390 $this->queryFlagsUsed = $flags;
403 if ( $this->mId != 0 ) {
404 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
405 if ( $lb->hasOrMadeRecentMasterChanges() ) {
406 $flags |= self::READ_LATEST;
407 $this->queryFlagsUsed = $flags;
415 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
416 if ( $lb->hasOrMadeRecentMasterChanges() ) {
417 $flags |= self::READ_LATEST;
418 $this->queryFlagsUsed = $flags;
422 $row =
wfGetDB( $index )->selectRow(
424 [
'actor_user',
'actor_name' ],
425 [
'actor_id' => $this->mActorId ],
433 } elseif ( $row->actor_user ) {
434 $this->mId = $row->actor_user;
445 Hooks::run(
'UserLoadAfterLoadFromSession', [ $this ] );
448 throw new UnexpectedValueException(
449 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
459 if ( $this->mId == 0 ) {
477 $this->mLoadedItems =
true;
478 $this->queryFlagsUsed = $flags;
488 public static function purge( $wikiId, $userId ) {
489 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
490 $key =
$cache->makeGlobalKey(
'user',
'id', $wikiId, $userId );
500 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
502 return $cache->makeGlobalKey(
'user',
'id', $lbFactory->getLocalDomainID(),
$this->mId );
511 $id = $this->
getId();
513 return $id ? [ $this->
getCacheKey( $cache ) ] : [];
523 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
529 wfDebug(
"User: cache miss for user {$this->mId}\n" );
536 foreach ( self::$mCacheVars
as $name ) {
544 foreach ( $this->mGroupMemberships
as $ugm ) {
545 if ( $ugm->getExpiry() ) {
546 $secondsUntilExpiry =
wfTimestamp( TS_UNIX, $ugm->getExpiry() ) - time();
547 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
548 $ttl = $secondsUntilExpiry;
555 [
'pcTTL' => $cache::TTL_PROC_LONG,
'version' =>
self::VERSION ]
559 foreach ( self::$mCacheVars
as $name ) {
586 if ( $validate ===
true ) {
590 if (
$name ===
false ) {
598 $u->setItemLoaded(
'name' );
613 $u->setItemLoaded(
'id' );
630 throw new BadMethodCallException(
631 'Cannot use ' . __METHOD__
632 .
' when $wgActorTableSchemaMigrationStage lacks SCHEMA_COMPAT_NEW'
639 $u->setItemLoaded(
'actor' );
653 if ( $identity instanceof
User ) {
680 $user->mFrom =
'defaults';
685 $user->mActorId = (int)$actorId;
686 if (
$user->mActorId !== 0 ) {
687 $user->mFrom =
'actor';
689 $user->setItemLoaded(
'actor' );
692 if ( $userName !==
null && $userName !==
'' ) {
693 $user->mName = $userName;
694 $user->mFrom =
'name';
695 $user->setItemLoaded(
'name' );
698 if ( $userId !==
null ) {
699 $user->mId = (int)$userId;
700 if (
$user->mId !== 0 ) {
703 $user->setItemLoaded(
'id' );
706 if (
$user->mFrom ===
'defaults' ) {
707 throw new InvalidArgumentException(
708 'Cannot create a user with no name, no ID, and no actor ID'
727 $db = ( $flags & self::READ_LATEST ) == self::READ_LATEST
731 $id = $db->selectField(
735 'user_email_token' => md5(
$code ),
736 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
752 $user->mFrom =
'session';
815 'validate' =>
'valid',
821 if (
$name ===
false ) {
827 $row =
$dbr->selectRow(
828 $userQuery[
'tables'],
829 $userQuery[
'fields'],
830 [
'user_name' =>
$name ],
838 $row = $dbw->selectRow(
839 $userQuery[
'tables'],
840 $userQuery[
'fields'],
841 [
'user_name' =>
$name ],
859 if (
$user->mEmail ||
$user->mToken !== self::INVALID_TOKEN ||
860 AuthManager::singleton()->userCanAuthenticate(
$name )
867 AuthManager::singleton()->revokeAccessForUser(
$name );
869 $user->invalidateEmail();
871 $user->saveSettings();
872 SessionManager::singleton()->preventSessionsForUser(
$user->getName() );
885 public static function whoIs( $id ) {
909 if ( is_null( $nt ) ) {
914 if ( !( $flags & self::READ_LATEST ) && array_key_exists(
$name, self::$idCacheByName ) ) {
915 return self::$idCacheByName[
$name];
924 [
'user_name' => $nt->getText() ],
929 if (
$s ===
false ) {
937 if (
count( self::$idCacheByName ) > 1000 ) {
938 self::$idCacheByName = [];
948 self::$idCacheByName = [];
968 return preg_match(
'/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',
$name )
997 || self::isIP(
$name )
998 || strpos(
$name,
'/' ) !==
false
1000 ||
$name != MediaWikiServices::getInstance()->getContentLanguage()->ucfirst(
$name )
1008 if ( is_null( $parsed )
1009 || $parsed->getNamespace()
1010 || strcmp(
$name, $parsed->getPrefixedText() ) ) {
1016 $unicodeBlacklist =
'/[' .
1017 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
1018 '\x{00a0}' . # non-breaking space
1019 '\x{2000}-\x{200f}' . # various whitespace
1020 '\x{2028}-\x{202f}' . # breaks
and control chars
1021 '\x{3000}' . # ideographic space
1022 '\x{e000}-\x{f8ff}' . #
private use
1024 if ( preg_match( $unicodeBlacklist,
$name ) ) {
1045 if ( !self::isValidUserName(
$name ) ) {
1049 static $reservedUsernames =
false;
1050 if ( !$reservedUsernames ) {
1052 Hooks::run(
'UserGetReservedNames', [ &$reservedUsernames ] );
1056 foreach ( $reservedUsernames
as $reserved ) {
1057 if ( substr( $reserved, 0, 4 ) ==
'msg:' ) {
1058 $reserved =
wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->plain();
1060 if ( $reserved ==
$name ) {
1078 if ( $groups === [] ) {
1082 $groups = array_unique( (
array)$groups );
1083 $limit = min( 5000, $limit );
1085 $conds = [
'ug_group' => $groups ];
1086 if ( $after !==
null ) {
1087 $conds[] =
'ug_user > ' . (int)$after;
1091 $ids =
$dbr->selectFieldValues(
1098 'ORDER BY' =>
'ug_user',
1123 if ( strlen(
$name ) > 235 ) {
1125 ": '$name' invalid due to length" );
1134 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1168 foreach (
$result->getErrorsByType(
'error' )
as $error ) {
1171 foreach (
$result->getErrorsByType(
'warning' )
as $warning ) {
1219 $status->merge( $upp->checkUserPassword( $this, $password ),
true );
1246 $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst(
$name );
1248 # Reject names containing '#'; these will be cleaned up
1249 # with title normalisation, but then it's too late to
1251 if ( strpos(
$name,
'#' ) !==
false ) {
1257 $t = ( $validate !==
false ) ?
1260 if ( is_null(
$t ) ||
$t->getNamespace() !==
NS_USER ||
$t->isExternal() ) {
1266 switch ( $validate ) {
1270 if ( !self::isValidUserName(
$name ) ) {
1275 if ( !self::isUsableName(
$name ) ) {
1280 if ( !self::isCreatableName(
$name ) ) {
1285 throw new InvalidArgumentException(
1286 'Invalid parameter value for $validate in ' . __METHOD__ );
1312 $this->mName =
$name;
1313 $this->mActorId =
null;
1314 $this->mRealName =
'';
1316 $this->mOptionOverrides =
null;
1317 $this->mOptionsLoaded =
false;
1319 $loggedOut = $this->mRequest && !defined(
'MW_NO_SESSION' )
1320 ? $this->mRequest->getSession()->getLoggedOutTimestamp() : 0;
1321 if ( $loggedOut !== 0 ) {
1322 $this->mTouched =
wfTimestamp( TS_MW, $loggedOut );
1324 $this->mTouched =
'1'; # Allow
any pages to be cached
1327 $this->mToken =
null;
1328 $this->mEmailAuthenticated =
null;
1329 $this->mEmailToken =
'';
1330 $this->mEmailTokenExpires =
null;
1332 $this->mGroupMemberships = [];
1350 return ( $this->mLoadedItems ===
true && $all ===
'all' ) ||
1351 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] ===
true );
1360 if ( is_array( $this->mLoadedItems ) ) {
1361 $this->mLoadedItems[$item] =
true;
1380 $session = $this->
getRequest()->getSession();
1381 $user = $session->getUser();
1382 if (
$user->isLoggedIn() ) {
1384 if (
$user->isBlocked() ) {
1392 $session->set(
'wsUserID', $this->
getId() );
1393 $session->set(
'wsUserName', $this->
getName() );
1394 $session->set(
'wsToken', $this->
getToken() );
1408 if ( $block && $this->
getRequest()->getCookie(
'BlockID' ) ===
null
1409 && $block->shouldTrackWithCookie( $this->isAnon() )
1411 $block->setCookie( $this->
getRequest()->response() );
1424 $this->mId = intval( $this->mId );
1426 if ( !$this->mId ) {
1436 $s = $db->selectRow(
1437 $userQuery[
'tables'],
1438 $userQuery[
'fields'],
1439 [
'user_id' => $this->mId ],
1445 $this->queryFlagsUsed = $flags;
1448 if (
$s !==
false ) {
1451 $this->mGroupMemberships =
null;
1478 if ( !is_object( $row ) ) {
1479 throw new InvalidArgumentException(
'$row must be an object' );
1484 $this->mGroupMemberships =
null;
1489 if ( isset( $row->actor_id ) ) {
1490 $this->mActorId = (int)$row->actor_id;
1491 if ( $this->mActorId !== 0 ) {
1492 $this->mFrom =
'actor';
1500 if ( isset( $row->user_name ) && $row->user_name !==
'' ) {
1501 $this->mName = $row->user_name;
1502 $this->mFrom =
'name';
1508 if ( isset( $row->user_real_name ) ) {
1509 $this->mRealName = $row->user_real_name;
1515 if ( isset( $row->user_id ) ) {
1516 $this->mId = intval( $row->user_id );
1517 if ( $this->mId !== 0 ) {
1518 $this->mFrom =
'id';
1525 if ( isset( $row->user_id ) && isset( $row->user_name ) && $row->user_name !==
'' ) {
1526 self::$idCacheByName[$row->user_name] = $row->user_id;
1529 if ( isset( $row->user_editcount ) ) {
1530 $this->mEditCount = $row->user_editcount;
1535 if ( isset( $row->user_touched ) ) {
1536 $this->mTouched =
wfTimestamp( TS_MW, $row->user_touched );
1541 if ( isset( $row->user_token ) ) {
1545 $this->mToken = rtrim( $row->user_token,
" \0" );
1546 if ( $this->mToken ===
'' ) {
1547 $this->mToken =
null;
1553 if ( isset( $row->user_email ) ) {
1554 $this->mEmail = $row->user_email;
1555 $this->mEmailAuthenticated =
wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1556 $this->mEmailToken = $row->user_email_token;
1557 $this->mEmailTokenExpires =
wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1564 $this->mLoadedItems =
true;
1567 if ( is_array(
$data ) ) {
1568 if ( isset(
$data[
'user_groups'] ) && is_array(
$data[
'user_groups'] ) ) {
1569 if (
$data[
'user_groups'] === [] ) {
1570 $this->mGroupMemberships = [];
1572 $firstGroup = reset(
$data[
'user_groups'] );
1573 if ( is_array( $firstGroup ) || is_object( $firstGroup ) ) {
1574 $this->mGroupMemberships = [];
1575 foreach (
$data[
'user_groups']
as $row ) {
1577 $this->mGroupMemberships[$ugm->getGroup()] = $ugm;
1582 if ( isset(
$data[
'user_properties'] ) && is_array(
$data[
'user_properties'] ) ) {
1595 foreach ( self::$mCacheVars
as $var ) {
1596 $this->$var =
$user->$var;
1604 if ( is_null( $this->mGroupMemberships ) ) {
1605 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
1635 if ( $toPromote === [] ) {
1645 foreach ( $toPromote
as $group ) {
1648 $newGroups = array_merge( $oldGroups, $toPromote );
1652 Hooks::run(
'UserGroupsChanged', [ $this, $toPromote, [],
false,
false, $oldUGMs, $newUGMs ] );
1655 $logEntry->setPerformer( $this );
1657 $logEntry->setParameters( [
1658 '4::oldgroups' => $oldGroups,
1659 '5::newgroups' => $newGroups,
1661 $logid = $logEntry->insert();
1663 $logEntry->publish( $logid );
1679 if ( $this->mTouched ) {
1681 $conditions[
'user_touched'] = $db->
timestamp( $this->mTouched );
1699 if ( !$this->mId ) {
1707 $dbw->update(
'user',
1708 [
'user_touched' => $dbw->timestamp( $newTouched ) ],
1710 'user_id' => $this->mId,
1714 $success = ( $dbw->affectedRows() > 0 );
1717 $this->mTouched = $newTouched;
1735 $this->mNewtalk = -1;
1736 $this->mDatePreference =
null;
1737 $this->mBlockedby = -1; # Unset
1738 $this->mHash =
false;
1739 $this->mRights =
null;
1740 $this->mEffectiveGroups =
null;
1741 $this->mImplicitGroups =
null;
1742 $this->mGroupMemberships =
null;
1743 $this->mOptions =
null;
1744 $this->mOptionsLoaded =
false;
1745 $this->mEditCount =
null;
1747 if ( $reloadFrom ) {
1748 $this->mLoadedItems = [];
1749 $this->mFrom = $reloadFrom;
1765 Assert::invariant( defined(
'MW_PHPUNIT_TEST' ),
'Unit tests only' );
1766 self::$defOpt =
null;
1767 self::$defOptLang =
null;
1779 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
1780 if ( self::$defOpt !==
null && self::$defOptLang === $contLang->getCode() ) {
1789 self::$defOptLang = $contLang->getCode();
1791 foreach ( LanguageConverter::$languagesWithVariants
as $langCode ) {
1792 if ( $langCode === $contLang->getCode() ) {
1793 self::$defOpt[
'variant'] = $langCode;
1795 self::$defOpt[
"variant-$langCode"] = $langCode;
1803 self::$defOpt[
'searchNs' . $nsnum] = (bool)$val;
1807 Hooks::run(
'UserGetDefaultOptions', [ &self::$defOpt ] );
1820 return $defOpts[
$opt] ??
null;
1832 if ( $this->mBlockedby != -1 ) {
1836 wfDebug( __METHOD__ .
": checking...\n" );
1845 # We only need to worry about passing the IP address to the Block generator if the
1846 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1847 # know which IP address they're actually coming from
1852 $globalUserName = $sessionUser->isSafeToLoad()
1853 ? $sessionUser->getName()
1855 if ( $this->
getName() === $globalUserName && !$this->
isAllowed(
'ipblock-exempt' ) ) {
1863 if ( !$block instanceof
Block ) {
1870 if ( self::isLocallyBlockedProxy( $ip ) ) {
1871 $block =
new Block( [
1875 'systemBlock' =>
'proxy',
1878 $block =
new Block( [
1882 'systemBlock' =>
'dnsbl',
1888 if ( !$block instanceof
Block
1893 $xff = $this->
getRequest()->getHeader(
'X-Forwarded-For' );
1894 $xff = array_map(
'trim', explode(
',', $xff ) );
1895 $xff = array_diff( $xff, [ $ip ] );
1898 if ( $block instanceof
Block ) {
1899 # Mangle the reason to alert the user that the block
1900 # originated from matching the X-Forwarded-For header.
1901 $block->setReason(
wfMessage(
'xffblockreason', $block->getReason() )->
plain() );
1905 if ( !$block instanceof
Block
1910 $block =
new Block( [
1912 'byText' =>
'MediaWiki default',
1915 'systemBlock' =>
'wgSoftBlockRanges',
1919 if ( $block instanceof
Block ) {
1920 wfDebug( __METHOD__ .
": Found block.\n" );
1921 $this->mBlock = $block;
1922 $this->mBlockedby = $block->getByName();
1923 $this->mBlockreason = $block->getReason();
1924 $this->mHideName = $block->getHideName();
1925 $this->mAllowUsertalk = $block->isUsertalkEditAllowed();
1927 $this->mBlock =
null;
1928 $this->mBlockedby =
'';
1929 $this->mBlockreason =
'';
1930 $this->mHideName = 0;
1931 $this->mAllowUsertalk =
false;
1937 Hooks::run(
'GetBlockedStatus', [ &$thisUser ] );
1947 if ( strlen( $blockCookieVal ) < 1 || !is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1952 if ( $blockCookieId !==
null ) {
1955 if ( $tmpBlock instanceof
Block ) {
1958 switch ( $tmpBlock->getType() ) {
1960 $blockIsValid = !$tmpBlock->isExpired() && $tmpBlock->isAutoblocking();
1961 $useBlockCookie = ( $config->get(
'CookieSetOnAutoblock' ) ===
true );
1966 $blockIsValid = !$tmpBlock->isExpired() && !$this->
isLoggedIn();
1967 $useBlockCookie = ( $config->get(
'CookieSetOnIpBlock' ) ===
true );
1970 $blockIsValid =
false;
1971 $useBlockCookie =
false;
1974 if ( $blockIsValid && $useBlockCookie ) {
2020 $ipReversed = implode(
'.', array_reverse( explode(
'.', $ip ) ) );
2026 if ( is_array(
$base ) ) {
2029 $host =
"{$base[1]}.$ipReversed.{$base[0]}";
2031 $host =
"$ipReversed.{$base[0]}";
2033 $basename =
$base[0];
2035 $host =
"$ipReversed.$base";
2039 $ipList = gethostbynamel( $host );
2042 wfDebugLog(
'dnsblacklist',
"Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
2047 wfDebugLog(
'dnsblacklist',
"Requested $host, not found in $basename." );
2073 $resultProxyList = [];
2074 $deprecatedIPEntries = [];
2080 if ( $keyIsIP && !$valueIsIP ) {
2081 $deprecatedIPEntries[] = $key;
2082 $resultProxyList[] = $key;
2083 } elseif ( $keyIsIP && $valueIsIP ) {
2084 $deprecatedIPEntries[] = $key;
2085 $resultProxyList[] = $key;
2086 $resultProxyList[] =
$value;
2088 $resultProxyList[] =
$value;
2092 if ( $deprecatedIPEntries ) {
2094 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
2095 implode(
', ', $deprecatedIPEntries ) .
', please move them to values)',
'1.30' );
2098 $proxyListIPSet =
new IPSet( $resultProxyList );
2099 return $proxyListIPSet->match( $ip );
2115 return !$this->
isAllowed(
'noratelimit' );
2146 $limits = array_merge(
2147 [
'&can-bypass' =>
true ],
2157 $id = $this->
getId();
2164 if ( isset( $limits[
'anon'] ) ) {
2165 $keys[
$cache->makeKey(
'limiter', $action,
'anon' )] = $limits[
'anon'];
2167 } elseif ( isset( $limits[
'user'] ) ) {
2169 $userLimit = $limits[
'user'];
2175 if ( isset( $limits[
'ip'] ) ) {
2177 $keys[
"mediawiki:limiter:$action:ip:$ip"] = $limits[
'ip'];
2180 if ( isset( $limits[
'subnet'] ) ) {
2183 if ( $subnet !==
false ) {
2184 $keys[
"mediawiki:limiter:$action:subnet:$subnet"] = $limits[
'subnet'];
2192 if ( isset( $limits[$group] ) ) {
2193 if ( $userLimit ===
false
2194 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
2196 $userLimit = $limits[$group];
2202 if ( $id !== 0 && $isNewbie && isset( $limits[
'newbie'] ) ) {
2203 $userLimit = $limits[
'newbie'];
2207 if ( $userLimit !==
false ) {
2211 list( $max, $period ) = $userLimit;
2212 wfDebug( __METHOD__ .
": effective user limit: $max in {$period}s\n" );
2213 $keys[
$cache->makeKey(
'limiter', $action,
'user', $id )] = $userLimit;
2217 if ( isset( $limits[
'ip-all'] ) ) {
2220 if ( $isNewbie || $userLimit ===
false
2221 || $limits[
'ip-all'][0] / $limits[
'ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2222 $keys[
"mediawiki:limiter:$action:ip-all:$ip"] = $limits[
'ip-all'];
2227 if ( isset( $limits[
'subnet-all'] ) ) {
2230 if ( $subnet !==
false ) {
2232 if ( $isNewbie || $userLimit ===
false
2233 || $limits[
'ip-all'][0] / $limits[
'ip-all'][1]
2234 > $userLimit[0] / $userLimit[1] ) {
2235 $keys[
"mediawiki:limiter:$action:subnet-all:$subnet"] = $limits[
'subnet-all'];
2241 foreach (
$keys as $key => $limit ) {
2245 list( $max, $period ) = $limit;
2246 $summary =
"(limit $max in {$period}s)";
2247 $count =
$cache->get( $key );
2250 if ( $count >= $max ) {
2251 wfDebugLog(
'ratelimit',
"User '{$this->getName()}' " .
2252 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2255 wfDebug( __METHOD__ .
": ok. $key at $count $summary\n" );
2258 wfDebug( __METHOD__ .
": adding record for $key $summary\n" );
2259 if ( $incrBy > 0 ) {
2260 $cache->add( $key, 0, intval( $period ) );
2263 if ( $incrBy > 0 ) {
2264 $cache->incr( $key, $incrBy );
2280 $this->
getBlock()->appliesToRight(
'edit' );
2291 return $this->mBlock instanceof
Block ? $this->mBlock :
null;
2307 return MediaWikiServices::getInstance()->getPermissionManager()
2308 ->isBlockedFrom( $this,
$title, $fromReplica );
2335 return ( $this->mBlock ? $this->mBlock->getId() :
false );
2361 if ( $this->mGlobalBlock !==
null ) {
2362 return $this->mGlobalBlock ?:
null;
2374 Hooks::run(
'UserIsBlockedGlobally', [ &
$user, $ip, &$blocked, &$block ] );
2376 if ( $blocked && $block ===
null ) {
2378 $block =
new Block( [
2380 'systemBlock' =>
'global-block'
2384 $this->mGlobalBlock = $blocked ? $block :
false;
2385 return $this->mGlobalBlock ?:
null;
2394 if ( $this->mLocked !==
null ) {
2398 $this->mLocked =
false;
2399 Hooks::run(
'UserIsLocked', [ $this, &$this->mLocked ] );
2409 if ( $this->mHideName !==
null ) {
2413 if ( !$this->mHideName ) {
2415 $this->mHideName =
false;
2416 Hooks::run(
'UserIsHidden', [ $this, &$this->mHideName ] );
2426 if ( $this->mId ===
null && $this->mName !==
null && self::isIP( $this->mName ) ) {
2459 if ( $this->mName ===
false ) {
2482 $this->mName = $str;
2509 if ( $this->mActorId ===
null || !$this->mActorId && $dbw ) {
2511 'actor_user' => $this->
getId() ?:
null,
2515 if ( $q[
'actor_user'] ===
null && self::isUsableName( $q[
'actor_name'] ) ) {
2517 'Cannot create an actor for a usable name that is not an existing user'
2520 if ( $q[
'actor_name'] ===
'' ) {
2523 $dbw->insert(
'actor', $q, __METHOD__, [
'IGNORE' ] );
2524 if ( $dbw->affectedRows() ) {
2525 $this->mActorId = (int)$dbw->insertId();
2529 $this->mActorId = (int)$dbw->selectField(
2534 [
'LOCK IN SHARE MODE' ]
2536 if ( !$this->mActorId ) {
2538 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2546 $this->mActorId = (int)$db->selectField(
'actor',
'actor_id', $q, __METHOD__,
$options );
2559 return str_replace(
' ',
'_', $this->
getName() );
2570 if ( $this->mNewtalk === -1 ) {
2571 $this->mNewtalk =
false; # reset talk
page status
2575 if ( !$this->mId ) {
2579 $this->mNewtalk =
false;
2584 $this->mNewtalk = $this->
checkNewtalk(
'user_id', $this->mId );
2618 $timestamp =
$dbr->selectField(
'user_newtalk',
2619 'MIN(user_last_timestamp)',
2620 $this->
isAnon() ? [
'user_ip' => $this->
getName() ] : [
'user_id' => $this->
getId() ],
2626 'link' => $utp->getLocalURL(),
2638 $newMessageRevisionId =
null;
2644 if ( $newMessageLinks &&
count( $newMessageLinks ) === 1
2646 && $newMessageLinks[0][
'rev']
2649 $newMessageRevision = $newMessageLinks[0][
'rev'];
2650 $newMessageRevisionId = $newMessageRevision->getId();
2653 return $newMessageRevisionId;
2667 $ok =
$dbr->selectField(
'user_newtalk', $field, [ $field => $id ], __METHOD__ );
2669 return $ok !==
false;
2681 $prevRev = $curRev ? $curRev->getPrevious() :
false;
2682 $ts = $prevRev ? $prevRev->getTimestamp() :
null;
2685 $dbw->insert(
'user_newtalk',
2686 [ $field => $id,
'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2689 if ( $dbw->affectedRows() ) {
2690 wfDebug( __METHOD__ .
": set on ($field, $id)\n" );
2694 wfDebug( __METHOD__ .
" already set ($field, $id)\n" );
2706 $dbw->delete(
'user_newtalk',
2709 if ( $dbw->affectedRows() ) {
2710 wfDebug( __METHOD__ .
": killed on ($field, $id)\n" );
2714 wfDebug( __METHOD__ .
": already gone ($field, $id)\n" );
2730 $this->mNewtalk = $val;
2737 $id = $this->
getId();
2759 if ( $this->mTouched ) {
2777 if ( !$this->
getId() ) {
2781 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2783 if ( $mode ===
'refresh' ) {
2784 $cache->delete( $key, 1 );
2786 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
2787 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2788 $lb->getConnection(
DB_MASTER )->onTransactionPreCommitOrIdle(
2823 $id = $this->
getId();
2825 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2826 $key =
$cache->makeKey(
'user-quicktouched',
'id', $id );
2827 $cache->touchCheckKey( $key );
2828 $this->mQuickTouched =
null;
2838 return ( $timestamp >= $this->
getTouched() );
2853 if ( $this->mQuickTouched ===
null ) {
2854 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2855 $key =
$cache->makeKey(
'user-quicktouched',
'id', $this->mId );
2860 return max( $this->mTouched, $this->mQuickTouched );
2920 $manager = AuthManager::singleton();
2923 if ( !$manager->userExists( $this->getName() ) ) {
2924 throw new LogicException(
'Cannot set a password for a user that is not in the database.' );
2928 'username' => $this->
getName(),
2934 ->info( __METHOD__ .
': Password change rejected: '
2935 .
$status->getWikiText(
null,
null,
'en' ) );
2939 $this->
setOption(
'watchlisttoken',
false );
2940 SessionManager::singleton()->invalidateSessionsForUser( $this );
2958 $manager = AuthManager::singleton();
2959 $reqs = $manager->getAuthenticationRequests( AuthManager::ACTION_CHANGE, $this );
2960 $reqs = AuthenticationRequest::loadRequestsFromSubmission( $reqs,
$data );
2963 foreach ( $reqs
as $req ) {
2964 $status->merge( $manager->allowsAuthenticationDataChange(
$req ),
true );
2966 if (
$status->getValue() ===
'ignored' ) {
2967 $status->warning(
'authenticationdatachange-ignored' );
2971 foreach ( $reqs
as $req ) {
2972 $manager->changeAuthenticationData(
$req );
2988 if ( !$this->mToken && $forceCreation ) {
2992 if ( !$this->mToken ) {
2997 if ( $this->mToken === self::INVALID_TOKEN ) {
3012 $len = max( 32, self::TOKEN_LENGTH );
3013 if ( strlen(
$ret ) < $len ) {
3015 throw new \UnexpectedValueException(
'Hmac returned less than 128 bits' );
3018 return substr(
$ret, -$len );
3029 if ( $this->mToken === self::INVALID_TOKEN ) {
3031 ->debug( __METHOD__ .
": Ignoring attempt to set token for system user \"$this\"" );
3032 } elseif ( !$token ) {
3035 $this->mToken = $token;
3048 throw new BadMethodCallException( __METHOD__ .
' has been removed in 1.27' );
3057 Hooks::run(
'UserGetEmail', [ $this, &$this->mEmail ] );
3067 Hooks::run(
'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
3077 if ( $str == $this->mEmail ) {
3081 $this->mEmail = $str;
3082 Hooks::run(
'UserSetEmail', [ $this, &$this->mEmail ] );
3100 if ( $str === $oldaddr ) {
3104 $type = $oldaddr !=
'' ?
'changed' :
'set';
3105 $notificationResult =
null;
3110 $change = $str !=
'' ?
'changed' :
'removed';
3111 $notificationResult = $this->
sendMail(
3112 wfMessage(
'notificationemail_subject_' . $change )->
text(),
3113 wfMessage(
'notificationemail_body_' . $change,
3126 if ( $notificationResult !==
null ) {
3127 $result->merge( $notificationResult );
3159 $this->mRealName = $str;
3172 public function getOption( $oname, $defaultOverride =
null, $ignoreHidden =
false ) {
3176 # We want 'disabled' preferences to always behave as the default value for
3177 # users, even if they have set the option explicitly in their settings (ie they
3178 # set it, and then it was disabled removing their ability to change it). But
3179 # we don't want to erase the preferences in the database in case the preference
3180 # is re-enabled again. So don't touch $mOptions, just override the returned value
3185 if ( array_key_exists( $oname, $this->mOptions ) ) {
3186 return $this->mOptions[$oname];
3189 return $defaultOverride;
3205 # We want 'disabled' preferences to always behave as the default value for
3206 # users, even if they have set the option explicitly in their settings (ie they
3207 # set it, and then it was disabled removing their ability to change it). But
3208 # we don't want to erase the preferences in the database in case the preference
3209 # is re-enabled again. So don't touch $mOptions, just override the returned value
3210 foreach ( $wgHiddenPrefs
as $pref ) {
3212 if ( $default !==
null ) {
3217 if ( $flags & self::GETOPTIONS_EXCLUDE_DEFAULTS ) {
3232 return (
bool)$this->
getOption( $oname );
3246 $val = $defaultOverride;
3248 return intval( $val );
3263 if ( is_null( $val ) ) {
3267 $this->mOptions[$oname] = $val;
3283 $id = $this->
getId();
3293 $token = hash_hmac(
'sha1',
"$oname:$id", $this->
getToken() );
3345 'registered-multiselect',
3346 'registered-checkmatrix',
3371 $preferencesFactory = MediaWikiServices::getInstance()->getPreferencesFactory();
3372 $prefs = $preferencesFactory->getFormDescriptor( $this,
$context );
3377 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(),
true );
3379 unset( $prefs[
$name] );
3384 $multiselectOptions = [];
3385 foreach ( $prefs
as $name => $info ) {
3386 if ( ( isset( $info[
'type'] ) && $info[
'type'] ==
'multiselect' ) ||
3389 $prefix = $info[
'prefix'] ??
$name;
3392 $multiselectOptions[
"$prefix$value"] =
true;
3395 unset( $prefs[
$name] );
3398 $checkmatrixOptions = [];
3399 foreach ( $prefs
as $name => $info ) {
3400 if ( ( isset( $info[
'type'] ) && $info[
'type'] ==
'checkmatrix' ) ||
3404 $prefix = $info[
'prefix'] ??
$name;
3406 foreach ( $columns
as $column ) {
3408 $checkmatrixOptions[
"$prefix$column-$row"] =
true;
3412 unset( $prefs[
$name] );
3418 if ( isset( $prefs[$key] ) ) {
3419 $mapping[$key] =
'registered';
3420 } elseif ( isset( $multiselectOptions[$key] ) ) {
3421 $mapping[$key] =
'registered-multiselect';
3422 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3423 $mapping[$key] =
'registered-checkmatrix';
3424 } elseif ( isset( $specialOptions[$key] ) ) {
3425 $mapping[$key] =
'special';
3426 } elseif ( substr( $key, 0, 7 ) ===
'userjs-' ) {
3427 $mapping[$key] =
'userjs';
3429 $mapping[$key] =
'unused';
3451 $resetKinds = [
'registered',
'registered-multiselect',
'registered-checkmatrix',
'unused' ],
3457 if ( !is_array( $resetKinds ) ) {
3458 $resetKinds = [ $resetKinds ];
3461 if ( in_array(
'all', $resetKinds ) ) {
3462 $newOptions = $defaultOptions;
3469 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
3474 foreach ( $this->mOptions
as $key =>
$value ) {
3475 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3476 if ( array_key_exists( $key, $defaultOptions ) ) {
3477 $newOptions[$key] = $defaultOptions[$key];
3480 $newOptions[$key] =
$value;
3485 Hooks::run(
'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions, $resetKinds ] );
3487 $this->mOptions = $newOptions;
3488 $this->mOptionsLoaded =
true;
3497 if ( is_null( $this->mDatePreference ) ) {
3500 $map =
$wgLang->getDatePreferenceMigrationMap();
3501 if ( isset( $map[
$value] ) ) {
3504 $this->mDatePreference =
$value;
3522 Hooks::run(
'UserRequiresHTTPS', [ $this, &$https ] );
3551 if ( is_null( $this->mRights ) ) {
3553 Hooks::run(
'UserGetRights', [ $this, &$this->mRights ] );
3557 if ( !defined(
'MW_NO_SESSION' ) ) {
3558 $allowedRights = $this->
getRequest()->getSession()->getAllowedUserRights();
3559 if ( $allowedRights !==
null ) {
3560 $this->mRights = array_intersect( $this->mRights, $allowedRights );
3564 Hooks::run(
'UserGetRightsRemove', [ $this, &$this->mRights ] );
3566 $this->mRights = array_values( array_unique( $this->mRights ) );
3577 $config->get(
'BlockDisablesLogin' ) &&
3581 $this->mRights = array_intersect( $this->mRights, $anon->getRights() );
3596 return array_keys( $this->mGroupMemberships );
3620 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
3621 $this->mEffectiveGroups = array_unique( array_merge(
3628 Hooks::run(
'UserEffectiveGroups', [ &
$user, &$this->mEffectiveGroups ] );
3630 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
3643 if ( $recache || is_null( $this->mImplicitGroups ) ) {
3644 $this->mImplicitGroups = [
'*' ];
3645 if ( $this->
getId() ) {
3646 $this->mImplicitGroups[] =
'user';
3648 $this->mImplicitGroups = array_unique( array_merge(
3649 $this->mImplicitGroups,
3656 $this->mEffectiveGroups =
null;
3674 if ( is_null( $this->mFormerGroups ) ) {
3675 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
3678 $res = $db->select(
'user_former_groups',
3680 [
'ufg_user' => $this->mId ],
3682 $this->mFormerGroups = [];
3683 foreach (
$res as $row ) {
3684 $this->mFormerGroups[] = $row->ufg_group;
3696 if ( !$this->
getId() ) {
3700 if ( $this->mEditCount ===
null ) {
3704 $count =
$dbr->selectField(
3705 'user',
'user_editcount',
3706 [
'user_id' => $this->mId ],
3710 if ( $count ===
null ) {
3714 $this->mEditCount = $count;
3738 if ( !
Hooks::run(
'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3744 if ( !$ugm->insert(
true ) ) {
3748 $this->mGroupMemberships[$group] = $ugm;
3753 $this->mRights =
null;
3769 if ( !
Hooks::run(
'UserRemoveGroup', [ $this, &$group ] ) ) {
3775 if ( !$ugm || !$ugm->delete() ) {
3780 unset( $this->mGroupMemberships[$group] );
3785 $this->mRights =
null;
3797 return $this->
getId() != 0;
3818 Hooks::run(
"UserIsBot", [ $this, &$isBot ] );
3830 $permissions = func_get_args();
3831 foreach ( $permissions
as $permission ) {
3832 if ( $this->
isAllowed( $permission ) ) {
3845 $permissions = func_get_args();
3846 foreach ( $permissions
as $permission ) {
3847 if ( !$this->
isAllowed( $permission ) ) {
3860 if ( $action ===
'' ) {
3865 return in_array( $action, $this->
getRights(),
true );
3907 if ( $this->mRequest ) {
3924 if (
$title->isWatchable() && ( !$checkRights || $this->
isAllowed(
'viewmywatchlist' ) ) ) {
3925 return MediaWikiServices::getInstance()->getWatchedItemStore()->isWatched( $this,
$title );
3938 if ( !$checkRights || $this->
isAllowed(
'editmywatchlist' ) ) {
3939 MediaWikiServices::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3955 if ( !$checkRights || $this->
isAllowed(
'editmywatchlist' ) ) {
3956 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
3957 $store->removeWatch( $this,
$title->getSubjectPage() );
3958 $store->removeWatch( $this,
$title->getTalkPage() );
3980 if ( !$this->
isAllowed(
'editmywatchlist' ) ) {
3988 if ( !
Hooks::run(
'UserClearNewTalkNotification', [ &
$user, $oldid ] ) ) {
4029 MediaWikiServices::getInstance()->getWatchedItemStore()
4030 ->resetNotificationTimestamp( $this,
$title, $force, $oldid );
4051 $id = $this->
getId();
4056 $watchedItemStore = MediaWikiServices::getInstance()->getWatchedItemStore();
4057 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
4085 $registration > $learnerRegistration ) {
4090 $registration <= $experiencedRegistration
4092 return 'experienced';
4108 if ( $this->mId == 0 ) {
4112 $session = $this->
getRequest()->getSession();
4114 $session = $session->sessionWithRequest(
$request );
4116 $delay = $session->delaySave();
4118 if ( !$session->getUser()->equals( $this ) ) {
4119 if ( !$session->canSetUser() ) {
4121 ->warning( __METHOD__ .
4122 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
4126 $session->setUser( $this );
4129 $session->setRememberUser( $rememberMe );
4130 if ( $secure !==
null ) {
4131 $session->setForceHTTPS( $secure );
4134 $session->persist();
4136 ScopedCallback::consume( $delay );
4155 $session = $this->
getRequest()->getSession();
4156 if ( !$session->canSetUser() ) {
4158 ->warning( __METHOD__ .
": Cannot log out of an immutable session" );
4159 $error =
'immutable';
4160 } elseif ( !$session->getUser()->equals( $this ) ) {
4162 ->warning( __METHOD__ .
4163 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
4167 $error =
'wronguser';
4170 $delay = $session->delaySave();
4171 $session->unpersist();
4172 $session->setLoggedOutTimestamp( time() );
4173 $session->setUser(
new User );
4174 $session->set(
'wsUserID', 0 );
4175 $session->resetAllTokens();
4176 ScopedCallback::consume( $delay );
4180 'event' =>
'logout',
4181 'successful' => $error ===
false,
4182 'status' => $error ?:
'success',
4196 "Could not update user with ID '{$this->mId}'; DB is read-only."
4202 if ( $this->mId == 0 ) {
4212 $dbw->doAtomicSection( __METHOD__,
function ( $dbw,
$fname )
use ( $newTouched ) {
4215 $dbw->update(
'user',
4217 'user_name' => $this->mName,
4218 'user_real_name' => $this->mRealName,
4219 'user_email' => $this->mEmail,
4220 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
4221 'user_touched' => $dbw->timestamp( $newTouched ),
4222 'user_token' => strval( $this->mToken ),
4224 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
4226 'user_id' => $this->mId,
4230 if ( !$dbw->affectedRows() ) {
4234 $from = ( $this->queryFlagsUsed & self::READ_LATEST ) ?
'master' :
'replica';
4235 LoggerFactory::getInstance(
'preferences' )->warning(
4236 "CAS update failed on user_touched for user ID '{user_id}' ({db_flag} read)",
4237 [
'user_id' => $this->mId,
'db_flag' => $from ]
4239 throw new MWException(
"CAS update failed on user_touched. " .
4240 "The version of the user to be saved is older than the current version."
4247 [
'actor_name' => $this->mName ],
4248 [
'actor_user' => $this->mId ],
4254 $this->mTouched = $newTouched;
4274 $db = ( ( $flags & self::READ_LATEST ) == self::READ_LATEST )
4279 ? [
'LOCK IN SHARE MODE' ]
4282 $id = $db->selectField(
'user',
4283 'user_id', [
'user_name' =>
$s ], __METHOD__,
$options );
4304 foreach ( [
'password',
'newpassword',
'newpass_time',
'password_expires' ]
as $field ) {
4305 if ( isset(
$params[$field] ) ) {
4306 wfDeprecated( __METHOD__ .
" with param '$field'",
'1.27' );
4314 if ( isset(
$params[
'options'] ) ) {
4323 'user_name' =>
$name,
4324 'user_password' => $noPass,
4325 'user_newpassword' => $noPass,
4326 'user_email' =>
$user->mEmail,
4327 'user_email_authenticated' => $dbw->timestampOrNull(
$user->mEmailAuthenticated ),
4328 'user_real_name' =>
$user->mRealName,
4329 'user_token' => strval(
$user->mToken ),
4330 'user_registration' => $dbw->timestamp(
$user->mRegistration ),
4331 'user_editcount' => 0,
4332 'user_touched' => $dbw->timestamp(
$user->newTouchedTimestamp() ),
4335 $fields[
"user_$name"] =
$value;
4338 return $dbw->doAtomicSection( __METHOD__,
function ( $dbw,
$fname )
use ( $fields ) {
4339 $dbw->insert(
'user', $fields,
$fname, [
'IGNORE' ] );
4340 if ( $dbw->affectedRows() ) {
4342 $newUser->mName = $fields[
'user_name'];
4343 $newUser->updateActorId( $dbw );
4345 $newUser->load( self::READ_LATEST );
4381 if ( !$this->mToken ) {
4385 if ( !is_string( $this->mName ) ) {
4386 throw new RuntimeException(
"User name field is not set." );
4392 $status = $dbw->doAtomicSection( __METHOD__,
function ( $dbw,
$fname ) {
4394 $dbw->insert(
'user',
4396 'user_name' => $this->mName,
4397 'user_password' => $noPass,
4398 'user_newpassword' => $noPass,
4399 'user_email' => $this->mEmail,
4400 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
4402 'user_token' => strval( $this->mToken ),
4403 'user_registration' => $dbw->timestamp( $this->mRegistration ),
4404 'user_editcount' => 0,
4405 'user_touched' => $dbw->timestamp( $this->mTouched ),
4409 if ( !$dbw->affectedRows() ) {
4411 $this->mId = $dbw->selectField(
4414 [
'user_name' => $this->mName ],
4416 [
'LOCK IN SHARE MODE' ]
4424 "to insert user '{$this->mName}' row, but it was not present in select!" );
4428 $this->mId = $dbw->insertId();
4455 [
'actor_user' => $this->mId,
'actor_name' => $this->mName ],
4458 $this->mActorId = (int)$dbw->
insertId();
4481 wfDebug( __METHOD__ .
"()\n" );
4483 if ( $this->mId == 0 ) {
4488 if ( !$userblock ) {
4492 return (
bool)$userblock->doAutoblock( $this->
getRequest()->getIP() );
4501 if ( $this->mBlock && $this->mBlock->appliesToRight(
'createaccount' ) ) {
4505 # T15611: if the IP address the user is trying to create an account from is
4506 # blocked with createaccount disabled, prevent new account creation there even
4507 # when the user is logged in
4508 if ( $this->mBlockedFromCreateAccount ===
false && !$this->
isAllowed(
'ipblock-exempt' ) ) {
4511 return $this->mBlockedFromCreateAccount instanceof
Block
4512 && $this->mBlockedFromCreateAccount->
appliesToRight(
'createaccount' )
4513 ? $this->mBlockedFromCreateAccount
4523 return $this->mBlock && $this->mBlock->appliesToRight(
'sendemail' );
4534 return $this->mBlock && $this->mBlock->appliesToRight(
'upload' );
4561 return $title->getTalkPage();
4570 return !$this->
isAllowed(
'autoconfirmed' );
4582 $manager = AuthManager::singleton();
4583 $reqs = AuthenticationRequest::loadRequestsFromSubmission(
4584 $manager->getAuthenticationRequests( AuthManager::ACTION_LOGIN ),
4586 'username' => $this->
getName(),
4587 'password' => $password,
4590 $res = AuthManager::singleton()->beginAuthentication( $reqs,
'null:' );
4591 switch (
$res->status ) {
4592 case AuthenticationResponse::PASS:
4594 case AuthenticationResponse::FAIL:
4597 ->info( __METHOD__ .
': Authentication failed: ' .
$res->message->plain() );
4600 throw new BadMethodCallException(
4601 'AuthManager returned a response unsupported by ' . __METHOD__
4639 return $request->getSession()->getToken( $salt );
4686 $val = substr( $val, 0, strspn( $val,
'0123456789abcdef' ) ) . Token::SUFFIX;
4705 if (
$type ==
'created' ||
$type ===
false ) {
4706 $message =
'confirmemail_body';
4708 } elseif (
$type ===
true ) {
4709 $message =
'confirmemail_body_changed';
4713 $message =
'confirmemail_body_' .
$type;
4717 'subject' =>
wfMessage(
'confirmemail_subject' )->text(),
4722 $wgLang->userTimeAndDate( $expiration, $this ),
4724 $wgLang->userDate( $expiration, $this ),
4725 $wgLang->userTime( $expiration, $this ) )->
text(),
4732 'confirmURL' => $url,
4733 'invalidateURL' => $invalidateURL,
4734 'expiration' => $expiration
4737 Hooks::run(
'UserSendConfirmationMail', [ $this, &$mail, $info ] );
4738 return $this->
sendMail( $mail[
'subject'], $mail[
'body'], $mail[
'from'], $mail[
'replyTo'] );
4752 public function sendMail( $subject, $body, $from =
null, $replyto =
null ) {
4755 if ( $from instanceof
User ) {
4764 'replyTo' => $replyto,
4785 $hash = md5( $token );
4786 $this->mEmailToken = $hash;
4787 $this->mEmailTokenExpires = $expiration;
4797 return $this->
getTokenUrl(
'ConfirmEmail', $token );
4806 return $this->
getTokenUrl(
'InvalidateEmail', $token );
4826 return $title->getCanonicalURL();
4841 Hooks::run(
'ConfirmEmailComplete', [ $this ] );
4855 $this->mEmailToken =
null;
4856 $this->mEmailTokenExpires =
null;
4859 Hooks::run(
'InvalidateEmailComplete', [ $this ] );
4869 $this->mEmailAuthenticated = $timestamp;
4870 Hooks::run(
'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
4919 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4939 $this->mEmailToken &&
4987 if ( $this->
getId() == 0 ) {
4992 $tsField = isset( $actorWhere[
'tables'][
'temp_rev_user'] )
4993 ?
'revactor_timestamp' :
'rev_timestamp';
4994 $sortOrder = $first ?
'ASC' :
'DESC';
4996 [
'revision' ] + $actorWhere[
'tables'],
4998 [ $actorWhere[
'conds'] ],
5000 [
'ORDER BY' =>
"$tsField $sortOrder" ],
5001 $actorWhere[
'joins']
5019 foreach ( $groups
as $group ) {
5021 $rights = array_merge( $rights,
5027 foreach ( $groups
as $group ) {
5029 $rights = array_diff( $rights,
5033 return array_unique( $rights );
5044 $allowedGroups = [];
5046 if ( self::groupHasPermission( $group, $role ) ) {
5047 $allowedGroups[] = $group;
5050 return $allowedGroups;
5091 if ( isset(
$cache[$right] ) && !defined(
'MW_PHPUNIT_TEST' ) ) {
5102 if ( isset( $rights[$right] ) && $rights[$right] ) {
5110 if ( !defined(
'MW_NO_SESSION' ) ) {
5111 $allowedRights = SessionManager::getGlobalSession()->getAllowedUserRights();
5112 if ( $allowedRights !==
null && !in_array( $right, $allowedRights,
true ) ) {
5119 if ( !
Hooks::run(
'UserIsEveryoneAllowed', [ $right ] ) ) {
5136 return array_values( array_diff(
5138 self::getImplicitGroups()
5147 if ( self::$mAllRights ===
false ) {
5150 self::$mAllRights = array_unique( array_merge( self::$mCoreRights,
$wgAvailableRights ) );
5154 Hooks::run(
'UserGetAllRights', [ &self::$mAllRights ] );
5195 if ( $text ==
'' ) {
5200 return MediaWikiServices::getInstance()
5201 ->getLinkRenderer()->makeLink(
$title, $text );
5204 return htmlspecialchars( $text );
5220 if ( $text ==
'' ) {
5225 $page =
$title->getFullText();
5226 return "[[$page|$text]]";
5272 if ( is_int( $key ) ) {
5280 if ( is_int( $key ) ) {
5315 if ( $this->
isAllowed(
'userrights' ) ) {
5320 $all = array_merge( self::getAllGroups() );
5338 foreach ( $addergroups
as $addergroup ) {
5339 $groups = array_merge_recursive(
5342 $groups[
'add'] = array_unique( $groups[
'add'] );
5343 $groups[
'remove'] = array_unique( $groups[
'remove'] );
5344 $groups[
'add-self'] = array_unique( $groups[
'add-self'] );
5345 $groups[
'remove-self'] = array_unique( $groups[
'remove-self'] );
5370 $this->mEditCount = $count;
5385 $count = (int)
$dbr->selectField(
5386 [
'revision' ] + $actorWhere[
'tables'],
5388 [ $actorWhere[
'conds'] ],
5391 $actorWhere[
'joins']
5397 [
'user_editcount' => $count ],
5399 'user_id' => $this->
getId(),
5400 'user_editcount IS NULL OR user_editcount < ' . (
int)$count
5416 $key =
"right-$right";
5418 return $msg->isDisabled() ? $right : $msg->text();
5429 $key =
"grant-$grant";
5431 return $msg->isDisabled() ? $grant : $msg->text();
5480 if ( $this->mOptionsLoaded ) {
5486 if ( !$this->
getId() ) {
5491 $variant = MediaWikiServices::getInstance()->getContentLanguage()->getDefaultVariant();
5492 $this->mOptions[
'variant'] = $variant;
5493 $this->mOptions[
'language'] = $variant;
5494 $this->mOptionsLoaded =
true;
5499 if ( !is_null( $this->mOptionOverrides ) ) {
5500 wfDebug(
"User: loading options for user " . $this->
getId() .
" from override cache.\n" );
5501 foreach ( $this->mOptionOverrides
as $key =>
$value ) {
5502 $this->mOptions[$key] =
$value;
5505 if ( !is_array(
$data ) ) {
5506 wfDebug(
"User: loading options for user " . $this->
getId() .
" from database.\n" );
5508 $dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
5514 [
'up_property',
'up_value' ],
5515 [
'up_user' => $this->
getId() ],
5519 $this->mOptionOverrides = [];
5521 foreach (
$res as $row ) {
5526 if ( $row->up_value ===
'0' ) {
5529 $data[$row->up_property] = $row->up_value;
5541 $this->mOptions[
'language']
5544 $this->mOptionsLoaded =
true;
5546 Hooks::run(
'UserLoadOptions', [ $this, &$this->mOptions ] );
5562 if ( !
Hooks::run(
'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5566 $userId = $this->
getId();
5569 foreach ( $saveOptions
as $key =>
$value ) {
5572 if ( ( $defaultOption ===
null &&
$value !==
false &&
$value !==
null )
5573 ||
$value != $defaultOption
5576 'up_user' => $userId,
5577 'up_property' => $key,
5585 $res = $dbw->select(
'user_properties',
5586 [
'up_property',
'up_value' ], [
'up_user' => $userId ], __METHOD__ );
5591 foreach (
$res as $row ) {
5592 if ( !isset( $saveOptions[$row->up_property] )
5593 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
5595 $keysDelete[] = $row->up_property;
5599 if (
count( $keysDelete ) ) {
5607 $dbw->delete(
'user_properties',
5608 [
'up_user' => $userId,
'up_property' => $keysDelete ], __METHOD__ );
5611 $dbw->insert(
'user_properties', $insert_rows, __METHOD__, [
'IGNORE' ] );
5629 'user_email_authenticated',
5631 'user_email_token_expires',
5632 'user_registration',
5650 'tables' => [
'user' ],
5658 'user_email_authenticated',
5660 'user_email_token_expires',
5661 'user_registration',
5670 $ret[
'tables'][
'user_actor'] =
'actor';
5671 $ret[
'fields'][] =
'user_actor.actor_id';
5672 $ret[
'joins'][
'user_actor'] = [
5674 [
'user_actor.actor_user = user_id' ]
5692 foreach ( self::getGroupsWithPermission( $permission )
as $group ) {
5713 if ( !$this->
getId() ) {
5718 if ( !
$user->loadFromId( self::READ_EXCLUSIVE ) ) {
static getDefaultOption( $opt)
Get a given default option value.
saveOptions()
Saves the non-default options for this user, as previously set e.g.
$wgHiddenPrefs
An array of preferences to not show for the user.
static replaceDeprecatedCodes( $code)
Replace deprecated language codes that were used in previous versions of MediaWiki to up-to-date,...
updateNewtalk( $field, $id, $curRev=null)
Add or update the new messages flag.
Status::newGood()` to allow deletion, and then `return false` from the hook function. Ensure you consume the 'ChangeTagAfterDelete' hook to carry out custom deletion actions. $tag:name of the tag $user:user initiating the action & $status:Status object. See above. 'ChangeTagsListActive':Allows you to nominate which of the tags your extension uses are in active use. & $tags:list of all active tags. Append to this array. 'ChangeTagsAfterUpdateTags':Called after tags have been updated with the ChangeTags::updateTags function. Params:$addedTags:tags effectively added in the update $removedTags:tags effectively removed in the update $prevTags:tags that were present prior to the update $rc_id:recentchanges table id $rev_id:revision table id $log_id:logging table id $params:tag params $rc:RecentChange being tagged when the tagging accompanies the action, or null $user:User who performed the tagging when the tagging is subsequent to the action, or null 'ChangeTagsAllowedAdd':Called when checking if a user can add tags to a change. & $allowedTags:List of all the tags the user is allowed to add. Any tags the user wants to add( $addTags) that are not in this array will cause it to fail. You may add or remove tags to this array as required. $addTags:List of tags user intends to add. $user:User who is adding the tags. 'ChangeUserGroups':Called before user groups are changed. $performer:The User who will perform the change $user:The User whose groups will be changed & $add:The groups that will be added & $remove:The groups that will be removed 'Collation::factory':Called if $wgCategoryCollation is an unknown collation. $collationName:Name of the collation in question & $collationObject:Null. Replace with a subclass of the Collation class that implements the collation given in $collationName. 'ConfirmEmailComplete':Called after a user 's email has been confirmed successfully. $user:user(object) whose email is being confirmed 'ContentAlterParserOutput':Modify parser output for a given content object. Called by Content::getParserOutput after parsing has finished. Can be used for changes that depend on the result of the parsing but have to be done before LinksUpdate is called(such as adding tracking categories based on the rendered HTML). $content:The Content to render $title:Title of the page, as context $parserOutput:ParserOutput to manipulate 'ContentGetParserOutput':Customize parser output for a given content object, called by AbstractContent::getParserOutput. May be used to override the normal model-specific rendering of page content. $content:The Content to render $title:Title of the page, as context $revId:The revision ID, as context $options:ParserOptions for rendering. To avoid confusing the parser cache, the output can only depend on parameters provided to this hook function, not on global state. $generateHtml:boolean, indicating whether full HTML should be generated. If false, generation of HTML may be skipped, but other information should still be present in the ParserOutput object. & $output:ParserOutput, to manipulate or replace 'ContentHandlerDefaultModelFor':Called when the default content model is determined for a given title. May be used to assign a different model for that title. $title:the Title in question & $model:the model name. Use with CONTENT_MODEL_XXX constants. 'ContentHandlerForModelID':Called when a ContentHandler is requested for a given content model name, but no entry for that model exists in $wgContentHandlers. Note:if your extension implements additional models via this hook, please use GetContentModels hook to make them known to core. $modeName:the requested content model name & $handler:set this to a ContentHandler object, if desired. 'ContentModelCanBeUsedOn':Called to determine whether that content model can be used on a given page. This is especially useful to prevent some content models to be used in some special location. $contentModel:ID of the content model in question $title:the Title in question. & $ok:Output parameter, whether it is OK to use $contentModel on $title. Handler functions that modify $ok should generally return false to prevent further hooks from further modifying $ok. 'ContribsPager::getQueryInfo':Before the contributions query is about to run & $pager:Pager object for contributions & $queryInfo:The query for the contribs Pager 'ContribsPager::reallyDoQuery':Called before really executing the query for My Contributions & $data:an array of results of all contribs queries $pager:The ContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'ContributionsLineEnding':Called before a contributions HTML line is finished $page:SpecialPage object for contributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'ContributionsToolLinks':Change tool links above Special:Contributions $id:User identifier $title:User page title & $tools:Array of tool links $specialPage:SpecialPage instance for context and services. Can be either SpecialContributions or DeletedContributionsPage. Extensions should type hint against a generic SpecialPage though. 'ConvertContent':Called by AbstractContent::convert when a conversion to another content model is requested. Handler functions that modify $result should generally return false to disable further attempts at conversion. $content:The Content object to be converted. $toModel:The ID of the content model to convert to. $lossy:boolean indicating whether lossy conversion is allowed. & $result:Output parameter, in case the handler function wants to provide a converted Content object. Note that $result->getContentModel() must return $toModel. 'ContentSecurityPolicyDefaultSource':Modify the allowed CSP load sources. This affects all directives except for the script directive. If you want to add a script source, see ContentSecurityPolicyScriptSource hook. & $defaultSrc:Array of Content-Security-Policy allowed sources $policyConfig:Current configuration for the Content-Security-Policy header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyDirectives':Modify the content security policy directives. Use this only if ContentSecurityPolicyDefaultSource and ContentSecurityPolicyScriptSource do not meet your needs. & $directives:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'ContentSecurityPolicyScriptSource':Modify the allowed CSP script sources. Note that you also have to use ContentSecurityPolicyDefaultSource if you want non-script sources to be loaded from whatever you add. & $scriptSrc:Array of CSP directives $policyConfig:Current configuration for the CSP header $mode:ContentSecurityPolicy::REPORT_ONLY_MODE or ContentSecurityPolicy::FULL_MODE depending on type of header 'CustomEditor':When invoking the page editor Return true to allow the normal editor to be used, or false if implementing a custom editor, e.g. for a special namespace, etc. $article:Article being edited $user:User performing the edit 'DatabaseOraclePostInit':Called after initialising an Oracle database $db:the DatabaseOracle object 'DeletedContribsPager::reallyDoQuery':Called before really executing the query for Special:DeletedContributions Similar to ContribsPager::reallyDoQuery & $data:an array of results of all contribs queries $pager:The DeletedContribsPager object hooked into $offset:Index offset, inclusive $limit:Exact query limit $descending:Query direction, false for ascending, true for descending 'DeletedContributionsLineEnding':Called before a DeletedContributions HTML line is finished. Similar to ContributionsLineEnding $page:SpecialPage object for DeletedContributions & $ret:the HTML line $row:the DB row for this line & $classes:the classes to add to the surrounding< li > & $attribs:associative array of other HTML attributes for the< li > element. Currently only data attributes reserved to MediaWiki are allowed(see Sanitizer::isReservedDataAttribute). 'DeleteUnknownPreferences':Called by the cleanupPreferences.php maintenance script to build a WHERE clause with which to delete preferences that are not known about. This hook is used by extensions that have dynamically-named preferences that should not be deleted in the usual cleanup process. For example, the Gadgets extension creates preferences prefixed with 'gadget-', and so anything with that prefix is excluded from the deletion. &where:An array that will be passed as the $cond parameter to IDatabase::select() to determine what will be deleted from the user_properties table. $db:The IDatabase object, useful for accessing $db->buildLike() etc. 'DifferenceEngineAfterLoadNewText':called in DifferenceEngine::loadNewText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before returning true from this function. $differenceEngine:DifferenceEngine object 'DifferenceEngineLoadTextAfterNewContentIsLoaded':called in DifferenceEngine::loadText() after the new revision 's content has been loaded into the class member variable $differenceEngine->mNewContent but before checking if the variable 's value is null. This hook can be used to inject content into said class member variable. $differenceEngine:DifferenceEngine object 'DifferenceEngineMarkPatrolledLink':Allows extensions to change the "mark as patrolled" link which is shown both on the diff header as well as on the bottom of a page, usually wrapped in a span element which has class="patrollink". $differenceEngine:DifferenceEngine object & $markAsPatrolledLink:The "mark as patrolled" link HTML(string) $rcid:Recent change ID(rc_id) for this change(int) 'DifferenceEngineMarkPatrolledRCID':Allows extensions to possibly change the rcid parameter. For example the rcid might be set to zero due to the user being the same as the performer of the change but an extension might still want to show it under certain conditions. & $rcid:rc_id(int) of the change or 0 $differenceEngine:DifferenceEngine object $change:RecentChange object $user:User object representing the current user 'DifferenceEngineNewHeader':Allows extensions to change the $newHeader variable, which contains information about the new revision, such as the revision 's author, whether the revision was marked as a minor edit or not, etc. $differenceEngine:DifferenceEngine object & $newHeader:The string containing the various #mw-diff-otitle[1-5] divs, which include things like revision author info, revision comment, RevisionDelete link and more $formattedRevisionTools:Array containing revision tools, some of which may have been injected with the DiffRevisionTools hook $nextlink:String containing the link to the next revision(if any) $status
loadFromId( $flags=self::READ_NORMAL)
Load user table data, given mId has already been set.
load( $flags=self::READ_NORMAL)
Load the user table data for this object from the source given by mFrom.
getNewtalk()
Check if the user has new messages.
$mOptionsLoaded
Bool Whether the cache variables have been loaded.
$wgProxyWhitelist
Proxy whitelist, list of addresses that are assumed to be non-proxy despite what the other methods mi...
inDnsBlacklist( $ip, $bases)
Whether the given IP is in a given DNS blacklist.
return true to allow those checks to and false if checking is done & $user
static newFromId( $id)
Static factory method for creation from a given user ID.
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
confirmationTokenUrl( $token)
Return a URL the user can use to confirm their email address.
Using a hook running we can avoid having all this option specific stuff in our mainline code Using the function We ve cleaned up the code here by removing clumps of infrequently used code and moving them off somewhere else It s much easier for someone working with this code to see what s _really_ going and make changes or fix bugs In we can take all the code that deals with the little used title reversing we can concentrate it all in an extension file
$wgProxyList
Big list of banned IP addresses.
clearSharedCache( $mode='changed')
Clear user data from memcached.
const SCHEMA_COMPAT_READ_NEW
static getCurrentWikiDbDomain()
wfCanIPUseHTTPS( $ip)
Determine whether the client at a given source IP is likely to be able to access the wiki via HTTPS.
processing should stop and the error should be shown to the user * false
static getLocalClusterInstance()
Get the main cluster-local cache object.
static resetGetDefaultOptionsForTestsOnly()
Reset the process cache of default user options.
isValidPassword( $password)
Is the input a valid password for this user?
getId()
Get the user's ID.
static newFromId( $id, $flags=0)
Load a page revision from a given revision ID number.
static makeGroupLinkWiki( $group, $text='')
Create a link to the group in Wikitext, if available; else return the group name.
useFilePatrol()
Check whether to enable new files patrol features for this user.
$wgMaxArticleSize
Maximum article size in kilobytes.
static hmac( $data, $key, $raw=true)
Generate an acceptably unstable one-way-hmac of some text making use of the best hash algorithm that ...
isAnon()
Get whether the user is anonymous.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on and they can depend only on the ResourceLoaderContext $context
static clearCookie(WebResponse $response)
Unset the 'BlockID' cookie.
getTokenUrl( $page, $token)
Internal function to format the e-mail validation/invalidation URLs.
getActorId(IDatabase $dbw=null)
Get the user's actor ID.
static isLocallyBlockedProxy( $ip)
Check if an IP address is in the local proxy list.
$wgRevokePermissions
Permission keys revoked from users in each group.
resetTokenFromOption( $oname)
Reset a token stored in the preferences (like the watchlist one).
isBlockedFrom( $title, $fromReplica=false)
Check if user is blocked from editing a particular article.
loadFromUserObject( $user)
Load the data for this user object from another user object.
static isCurrentWikiId( $wikiId)
static newFatalPermissionDeniedStatus( $permission)
Factory function for fatal permission-denied errors.
getEditTokenObject( $salt='', $request=null)
Initialize (if necessary) and return a session token value which can be used in edit forms to show th...
$wgShowUpdatedMarker
Show "Updated (since my last visit)" marker in RC view, watchlist and history view for watched pages ...
static isInRanges( $ip, $ranges)
Determines if an IP address is a list of CIDR a.b.c.d/n ranges.
static newFromID( $id)
Load a block from the block id.
newTouchedTimestamp()
Generate a current or new-future timestamp to be stored in the user_touched field when we update thin...
$wgExperiencedUserMemberSince
Name of the external diff engine to use.
getEditCount()
Get the user's edit count.
spreadBlock()
If this (non-anonymous) user is blocked, block the IP address they've successfully logged in from.
incEditCount()
Schedule a deferred update to update the user's edit count.
static newFromSession(WebRequest $request=null)
Create a new user object using data from session.
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...
getOptionKinds(IContextSource $context, $options=null)
Return an associative array mapping preferences keys to the kind of a preference they're used for.
static chooseBlock(array $blocks, array $ipChain)
From a list of multiple blocks, find the most exact and strongest Block.
isEmailConfirmationPending()
Check whether there is an outstanding request for e-mail confirmation.
getBlockId()
If user is blocked, return the ID for the block.
getIntOption( $oname, $defaultOverride=0)
Get the user's current setting for a given option, as an integer value.
getOptions( $flags=0)
Get all user's options.
static getGroupName( $group)
Gets the localized friendly name for a group, if it exists.
string $mTouched
TS_MW timestamp from the DB.
__construct()
Lightweight constructor for an anonymous user.
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
getToken( $forceCreation=true)
Get the user's current token.
spreadAnyEditBlock()
If this user is logged-in and blocked, block any IP address they've successfully logged in from.
string[] $wgSoftBlockRanges
IP ranges that should be considered soft-blocked (anon-only, account creation allowed).
getNewMessageRevisionId()
Get the revision ID for the last talk page revision viewed by the talk page owner.
loadDefaults( $name=false)
Set cached properties to default.
$wgEmailAuthentication
Require email authentication before sending mail to an email address.
$mNewtalk
Lazy-initialized variables, invalidated with clearInstanceCache.
loadOptions( $data=null)
Load the user options either from cache, the database or an array.
static makeGroupLinkHTML( $group, $text='')
Create a link to the group in HTML, if available; else return the group name.
$wgDefaultUserOptions
Settings added to this array will override the default globals for the user preferences used by anony...
this hook is for auditing only $req
setNewpassword( $str, $throttle=true)
Set the password for a password reminder or new account email.
static addUpdate(DeferrableUpdate $update, $stage=self::POSTSEND)
Add an update to the deferred list to be run later by execute()
static newFatal( $message)
Factory function for fatal errors.
setEmailWithConfirmation( $str)
Set the user's e-mail address and a confirmation mail if needed.
$wgEnableUserEmail
Set to true to enable user-to-user e-mail.
getStubThreshold()
Get the user preferred stub threshold.
static newFromTarget( $specificTarget, $vagueTarget=null, $fromMaster=false)
Given a target and the target's type, get an existing Block object if possible.
wfReadOnly()
Check whether the wiki is in read-only mode.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
loadFromRow( $row, $data=null)
Initialize this object from a row from the user table.
setEmailAuthenticationTimestamp( $timestamp)
Set the e-mail authentication timestamp.
static isIPv6( $ip)
Given a string, determine if it as valid IP in IPv6 only.
getUserPage()
Get this user's personal page title.
getGroups()
Get the list of explicit group memberships this user has.
static newFromAnyId( $userId, $userName, $actorId)
Static factory method for creation from an ID, name, and/or actor ID.
getBlockFromCookieValue( $blockCookieVal)
Try to load a Block from an ID given in a cookie value.
static generateRandomPasswordString( $minLength=10)
Generate a random string suitable for a password.
static newFromIdentity(UserIdentity $identity)
Returns a User object corresponding to the given UserIdentity.
useNPPatrol()
Check whether to enable new pages patrol features for this user.
static getDBOptions( $bitfield)
Get an appropriate DB index, options, and fallback DB index for a query.
getDatePreference()
Get the user's preferred date format.
isSafeToLoad()
Test if it's safe to load this User object.
setEmail( $str)
Set the user's e-mail address.
idForName( $flags=0)
If only this user's username is known, and it exists, return the user ID.
static isValidUserName( $name)
Is the input a valid username?
sendConfirmationMail( $type='created')
Generate a new e-mail confirmation token and send a confirmation/invalidation mail to the user's give...
static groupHasPermission( $group, $role)
Check, if the given group has the given permission.
getEmailAuthenticationTimestamp()
Get the timestamp of the user's e-mail authentication.
pingLimiter( $action='edit', $incrBy=1)
Primitive rate limits: enforce maximum actions per time period to put a brake on flooding.
$mFrom
String Initialization data source if mLoadedItems!==true.
Handles increment the edit count for a given set of users.
Interface for database access objects.
useRCPatrol()
Check whether to enable recent changes patrol features for this user.
invalidateEmail()
Invalidate the user's e-mail confirmation, and unauthenticate the e-mail address if it was already co...
static getGroupPage( $group)
Gets the title of a page describing a particular user group.
static newFromRow( $row, $data=null)
Create a new user object from a user row.
$wgUseRCPatrol
Use RC Patrolling to check for vandalism (from recent changes and watchlists) New pages and new files...
loadGroups()
Load the groups from the database if they aren't already loaded.
$wgUseNPPatrol
Use new page patrolling to check new pages on Special:Newpages.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
isIPRange()
Is the user an IP range?
deleteNewtalk( $field, $id)
Clear the new messages flag for the given user.
static newMigration()
Static constructor.
static newFromUser(User $user)
Create a new MailAddress object for the given user.
static $mCacheVars
Array of Strings List of member variables which are saved to the shared cache (memcached).
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
The ContentHandler facility adds support for arbitrary content types on wiki pages
getRights()
Get the permissions this user has.
static createNew( $name, $params=[])
Add a user to the database, return the user object.
getRequest()
Get the WebRequest object to use with this object.
getAutomaticGroups( $recache=false)
Get the list of implicit group memberships this user has.
const INVALID_TOKEN
@const string An invalid value for user_token
setPassword( $str)
Set the password and reset the random token.
static getDefaultOptions()
Combine the language default options with any site-specific options and add the default language vari...
getInstanceForUpdate()
Get a new instance of this user that was loaded from the master via a locking read.
$wgMaxNameChars
Maximum number of bytes in username.
const READ_LOCKING
Constants for object loading bitfield flags (higher => higher QoS)
$wgExperiencedUserEdits
Name of the external diff engine to use.
static newSystemUser( $name, $options=[])
Static factory method for creation of a "system" user from username.
static getMembershipsForUser( $userId, IDatabase $db=null)
Returns UserGroupMembership objects for all the groups a user currently belongs to.
addGroup( $group, $expiry=null)
Add the user to the given group.
Stores a single person's name and email address.
Value object representing a logged-out user's edit token.
matchEditToken( $val, $salt='', $request=null, $maxage=null)
Check given value against the token value stored in the session.
getEmail()
Get the user's e-mail address.
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
getTalkPage()
Get this user's talk page title.
addToDatabase()
Add this existing user object to the database.
static isValidRange( $ipRange)
Validate an IP range (valid address with a valid CIDR prefix).
invalidateCache()
Immediately touch the user data cache for this account.
setInternalPassword( $str)
Set the password and reset the random token unconditionally.
invalidationTokenUrl( $token)
Return a URL the user can use to invalidate their email address.
namespace and then decline to actually register it file or subcat img or subcat $title
isLocked()
Check if user account is locked.
string null $wgAuthenticationTokenVersion
Versioning for authentication tokens.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
checkPasswordValidity( $password)
Check if this is a valid password for this user.
static normalizeKey( $key)
Normalize a skin preference value to a form that can be loaded.
confirmEmail()
Mark the e-mail address confirmed.
setItemLoaded( $item)
Set that an item has been loaded.
static getLink( $ugm, IContextSource $context, $format, $userName=null)
Gets a link for a user group, possibly including the expiry date if relevant.
blockedFor()
If user is blocked, return the specified reason for the block.
static getWikiIdFromDbDomain( $domain)
Get the wiki ID of a database domain.
setNewtalk( $val, $curRev=null)
Update the 'You have new messages!' status.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
Block $mBlockedFromCreateAccount
null for the wiki Added in
isAllowedToCreateAccount()
Get whether the user is allowed to create an account.
logout()
Log this user out.
confirmationToken(&$expiration)
Generate, store, and return a new e-mail confirmation code.
getCacheKey(WANObjectCache $cache)
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
static getImplicitGroups()
Get a list of implicit groups TODO: Should we deprecate this? It's trivial, but we don't want to enco...
isHidden()
Check if user account is hidden.
static randomPassword()
Return a random password.
static newFromRow( $row)
Creates a new UserGroupMembership object from a database row.
static getSubnet( $ip)
Returns the subnet of a given IP.
isBlockedFromEmailuser()
Get whether the user is blocked from using Special:Emailuser.
static isIP( $name)
Does the string match an anonymous IP address?
validateCache( $timestamp)
Validate the cache for this account.
as see the revision history and available at free of to any person obtaining a copy of this software and associated documentation to deal in the Software without including without limitation the rights to use
getEffectiveGroups( $recache=false)
Get the list of implicit group memberships this user has.
isPingLimitable()
Is this user subject to rate limiting?
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
removeGroup( $group)
Remove the user from the given group.
canReceiveEmail()
Is this user allowed to receive e-mails within limits of current site configuration?
initEditCountInternal()
Initialize user_editcount from data out of the revision table.
$wgImplicitGroups
Implicit groups, aren't shown on Special:Listusers or somewhere else.
isNewbie()
Determine whether the user is a newbie.
touch()
Update the "touched" timestamp for the user.
clearInstanceCache( $reloadFrom=false)
Clear various cached data stored in this object.
$wgEnableEmail
Set to true to enable the e-mail basic features: Password reminders, etc.
$wgEnableDnsBlacklist
Whether to use DNS blacklists in $wgDnsBlacklistUrls to check for open proxies.
const TOKEN_LENGTH
@const int Number of characters in user_token field.
$wgDefaultSkin
Default skin, for new users and anonymous visitors.
$wgReservedUsernames
Array of usernames which may not be registered or logged in from Maintenance scripts can still use th...
static makeTitle( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
addWatch( $title, $checkRights=self::CHECK_USER_RIGHTS)
Watch an article.
string $mQuickTouched
TS_MW timestamp from cache.
getBlock( $fromReplica=true)
Get the block affecting the user, or null if the user is not blocked.
setName( $str)
Set the user name.
resetOptions( $resetKinds=[ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused'], IContextSource $context=null)
Reset certain (or all) options to the site defaults.
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
UserGroupMembership[] $mGroupMemberships
Associative array of (group name => UserGroupMembership object)
Check if a user's password complies with any password policies that apply to that user,...
$wgUseFilePatrol
Use file patrolling to check new files on Special:Newfiles.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
This code would result in ircNotify being run twice when an article is and once for brion Hooks can return three possible true was required This is the default since MediaWiki *some string
$mLoadedItems
Array with already loaded items or true if all items have been loaded.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
clearNotification(&$title, $oldid=0)
Clear the user's notification timestamp for the given title.
saveSettings()
Save this user's settings into the database.
addNewUserLogEntry( $action=false, $reason='')
Add a newuser log entry for this user.
static array null $defOpt
Is the user an IP range?
static getBlocksForIPList(array $ipChain, $isAnon, $fromMaster=false)
Get all blocks that match any IP from an array of IP addresses.
static string null $defOptLang
Is the user an IP range?
static $mCoreRights
Array of Strings Core rights.
foreach( $wgExtensionFunctions as $func) if(!defined( 'MW_NO_SESSION') &&! $wgCommandLineMode) if(! $wgCommandLineMode) $wgFullyInitialised
getFirstEditTimestamp()
Get the timestamp of the first edit.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not null
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
$wgAutopromoteOnceLogInRC
Put user rights log entries for autopromotion in recent changes?
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction you ll probably need to make sure the header is varied on $request
const GETOPTIONS_EXCLUDE_DEFAULTS
Exclude user options that are set to their default value.
setRealName( $str)
Set the user's real name.
Allows to change the fields on the form that will be generated $name
getNewMessageLinks()
Return the data needed to construct links for new talk page message alerts.
they could even be mouse clicks or menu items whatever suits your program You should also get your if any
static makeTitleSafe( $ns, $title, $fragment='', $interwiki='')
Create a new Title from a namespace index and a DB key.
getFormerGroups()
Returns the groups the user has belonged to.
static whoIs( $id)
Get the username corresponding to a given user ID.
static getIdFromCookieValue( $cookieValue)
Get the stored ID from the 'BlockID' cookie.
static hasFlags( $bitfield, $flags)
loadFromSession()
Load user data from the session.
$wgRateLimits
Simple rate limiter options to brake edit floods.
isBlockedGlobally( $ip='')
Check if user is blocked on all wikis.
getOption( $oname, $defaultOverride=null, $ignoreHidden=false)
Get the user's current setting for a given option.
static newGood( $value=null)
Factory function for good results.
isDnsBlacklisted( $ip, $checkWhitelist=false)
Whether the given IP is in a DNS blacklist.
getTouched()
Get the user touched timestamp.
getGlobalBlock( $ip='')
Check if user is blocked on all wikis.
const GAID_FOR_UPDATE
Used to be GAID_FOR_UPDATE define.
Exception thrown when an actor can't be created.
checkAndSetTouched()
Bump user_touched if it didn't change since this object was loaded.
Multi-datacenter aware caching interface.
getRealName()
Get the user's real name.
updateActorId(IDatabase $dbw)
Update the actor ID after an insert.
setCookies( $request=null, $secure=null, $rememberMe=false)
Persist this user's session (e.g.
static getGroupPermissions( $groups)
Get the permissions associated with a given list of groups.
static getGroupPage( $group)
Get the title of a page describing a particular group.
changeableGroups()
Returns an array of groups that this user can add and remove.
clearAllNotifications()
Resets all of the given user's page-change notification timestamps.
const VERSION
@const int Serialized record version.
const SCHEMA_COMPAT_WRITE_NEW
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
matchEditTokenNoSuffix( $val, $salt='', $request=null, $maxage=null)
Check given value against the token value stored in the session, ignoring the suffix.
$wgAddGroups
$wgAddGroups and $wgRemoveGroups can be used to give finer control over who can assign which groups a...
checkPassword( $password)
Check to see if the given clear-text password is one of the accepted passwords.
static getAllGroups()
Return the set of defined explicit groups.
removeWatch( $title, $checkRights=self::CHECK_USER_RIGHTS)
Stop watching an article.
static getAllRights()
Get a list of all available permissions.
static generateHex( $chars)
Generate a run of cryptographically random data and return it in hexadecimal string format.
isBlockedFromUpload()
Get whether the user is blocked from using Special:Upload.
$wgInvalidUsernameCharacters
Characters to prevent during new account creations.
static getMain()
Get the RequestContext object associated with the main request.
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new user object.
blockedBy()
If user is blocked, return the name of the user who placed the block.
$wgLearnerEdits
The following variables define 3 user experience levels:
getDBTouched()
Get the user_touched timestamp field (time of last DB updates)
static isIPv4( $ip)
Given a string, determine if it as valid IP in IPv4 only.
Interface for objects which can provide a MediaWiki context on request.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
getEditTimestamp( $first)
Get the timestamp of the first or latest edit.
static changeableByGroup( $group)
Returns an array of the groups that a particular group can add/remove.
This list may contain false positives That usually means there is additional text with links below the first Each row contains links to the first and second as well as the first line of the second redirect text
setId( $v)
Set the user and reload all fields according to a given ID.
getExperienceLevel()
Compute experienced level based on edit count and registration date.
and how to run hooks for an and one after Each event has a preferably in CamelCase For ArticleDelete hook A clump of code and data that should be run when an event happens This can be either a function and a chunk of or an object and a method hook function The function part of a third party developers and administrators to define code that will be run at certain points in the mainline and to modify the data run by that mainline code Hooks can keep mainline code and make it easier to write extensions Hooks are a principled alternative to patches for two options in MediaWiki One reverses the order of a title before displaying the article
$wgUserEmailConfirmationTokenExpiry
The time, in seconds, when an email confirmation email expires.
getRegistration()
Get the timestamp of account creation.
appliesToRight( $right)
Determine whether the Block prevents a given right.
static newInvalidPassword()
Create an InvalidPassword.
static sanitizeIP( $ip)
Convert an IP into a verbose, uppercase, normalized form.
static isEveryoneAllowed( $right)
Check if all users may be assumed to have the given permission.
and that you know you can do these things To protect your we need to make restrictions that forbid anyone to deny you these rights or to ask you to surrender the rights These restrictions translate to certain responsibilities for you if you distribute copies of the or if you modify it For if you distribute copies of such a whether gratis or for a you must give the recipients all the rights that you have You must make sure that receive or can get the source code And you must show them these terms so they know their rights We protect your rights with two and(2) offer you this license which gives you legal permission to copy
isAllowedAny()
Check if user is allowed to access a feature / make an action.
static getRightDescription( $right)
Get the description of a given right.
changeAuthenticationData(array $data)
Changes credentials of the user.
do that in ParserLimitReportFormat instead use this to modify the parameters of the image all existing parser cache entries will be invalid To avoid you ll need to handle that somehow(e.g. with the RejectParserCacheValue hook) because MediaWiki won 't do it for you. & $defaults also a ContextSource after deleting those rows but within the same transaction $rows
$wgRateLimitsExcludedIPs
Array of IPs / CIDR ranges which should be excluded from rate limits.
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped & $options
$wgApplyIpBlocksToXff
Whether to look at the X-Forwarded-For header's list of (potentially spoofed) IPs and apply IP blocks...
isLoggedIn()
Get whether the user is logged in.
checkTemporaryPassword( $plaintext)
Check if the given clear-text password matches the temporary password sent by e-mail for password res...
getTitleKey()
Get the user's name escaped by underscores.
setToken( $token=false)
Set the random token (used for persistent authentication) Called from loadDefaults() among other plac...
static idFromName( $name, $flags=self::READ_NORMAL)
Get database id given a user name.
static resetIdByNameCache()
Reset the cache used in idFromName().
string $mEmailTokenExpires
static findUsersByGroup( $groups, $limit=5000, $after=null)
Return the users who are members of the given group(s).
static getCanonicalName( $name, $validate='valid')
Given unvalidated user input, return a canonical username, or false if the username is invalid.
isEmailConfirmed()
Is this user's e-mail address valid-looking and confirmed within limits of the current site configura...
isAllowUsertalk()
Checks if usertalk is allowed.
presenting them properly to the user as errors is done by the caller return true use this to change the list i e etc $rev
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
getBlockedStatus( $fromReplica=true)
Get blocking information.
static getGrantName( $grant)
Get the name of a given grant.
isBlocked( $fromReplica=true)
Check if user is blocked.
static loadFromTimestamp( $db, $title, $timestamp)
Load the revision for the given title with the given timestamp.
static newFromActorId( $id)
Static factory method for creation from a given actor ID.
$wgDnsBlacklistUrls
List of DNS blacklists to use, if $wgEnableDnsBlacklist is true.
loadFromCache()
Load user data from shared cache, given mId has already been set.
$wgLearnerMemberSince
Name of the external diff engine to use.
addAutopromoteOnceGroups( $event)
Add the user to the group if he/she meets given criteria.
sendMail( $subject, $body, $from=null, $replyto=null)
Send an e-mail to this user's account.
MediaWiki Logger LoggerFactory implements a PSR[0] compatible message logging system Named Psr Log LoggerInterface instances can be obtained from the MediaWiki Logger LoggerFactory::getInstance() static method. MediaWiki\Logger\LoggerFactory expects a class implementing the MediaWiki\Logger\Spi interface to act as a factory for new Psr\Log\LoggerInterface instances. The "Spi" in MediaWiki\Logger\Spi stands for "service provider interface". An SPI is an API intended to be implemented or extended by a third party. This software design pattern is intended to enable framework extension and replaceable components. It is specifically used in the MediaWiki\Logger\LoggerFactory service to allow alternate PSR-3 logging implementations to be easily integrated with MediaWiki. The service provider interface allows the backend logging library to be implemented in multiple ways. The $wgMWLoggerDefaultSpi global provides the classname of the default MediaWiki\Logger\Spi implementation to be loaded at runtime. This can either be the name of a class implementing the MediaWiki\Logger\Spi with a zero argument const ructor or a callable that will return an MediaWiki\Logger\Spi instance. Alternately the MediaWiki\Logger\LoggerFactory MediaWiki Logger LoggerFactory
getTokenFromOption( $oname)
Get a token stored in the preferences (like the watchlist one), resetting it if it's empty (and savin...
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses just before the function returns a value If you return true
Class for creating new log entries and inserting them into the database.
equals(UserIdentity $user)
Checks if two user objects point to the same user.
checkNewtalk( $field, $id)
Internal uncached check for new messages.
loadFromDatabase( $flags=self::READ_LATEST)
Load user and user_group data from the database.
static selectFields()
Return the list of user fields that should be selected to create a new user object.
$wgGroupPermissions['sysop']['replacetext']
you have access to all of the normal MediaWiki so you can get a DB use the etc For full docs on the Maintenance class
see documentation in includes Linker php for Linker::makeImageLink & $time
$wgPasswordPolicy
Password policy for the wiki.
addNewUserLogEntryAutoCreate()
Add an autocreate newuser log entry for this user Used by things like CentralAuth and perhaps other a...
static newFromConfirmationCode( $code, $flags=0)
Factory method to fetch whichever user has a given email confirmation code.
if(! $wgDBerrorLogTZ) $wgRequest
isWatched( $title, $checkRights=self::CHECK_USER_RIGHTS)
Check the watched status of an article.
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency MediaWikiServices
static getMembership( $userId, $group, IDatabase $db=null)
Returns a UserGroupMembership object that pertains to the given user and group, or false if the user ...
getBoolOption( $oname)
Get the user's current setting for a given option, as a boolean value.
$wgMinimalPasswordLength
Specifies the minimal length of a user password.
$wgGroupsAddToSelf
A map of group names that the user is in, to group names that those users are allowed to add or revok...
static isUsableName( $name)
Usernames which fail to pass this function will be blocked from user login and new account registrati...
either a unescaped string or a HtmlArmor object after in associative array form externallinks including delete and has completed for all link tables whether this was an auto creation use $formDescriptor instead default is conds Array Extra conditions for the No matching items in log is displayed if loglist is empty msgKey Array If you want a nice box with a set this to the key of the message First element is the message additional optional elements are parameters for the key that are processed with wfMessage() -> params() ->parseAsBlock() - offset Set to overwrite offset parameter in $wgRequest set to '' to unset offset - wrap String Wrap the message in html(usually something like "<
makeUpdateConditions(IDatabase $db, array $conditions)
Builds update conditions.
$wgPasswordSender
Sender email address for e-mail notifications.
isBlockedFromCreateAccount()
Get whether the user is explicitly blocked from account creation.
getEditToken( $salt='', $request=null)
Initialize (if necessary) and return a session token value which can be used in edit forms to show th...
requiresHTTPS()
Determine based on the wiki configuration and the user's options, whether this user must be over HTTP...
static $mAllRights
String Cached results of getAllRights()
isItemLoaded( $item, $all='all')
Return whether an item has been loaded.
static purge( $wikiId, $userId)
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
static addCallableUpdate( $callable, $stage=self::POSTSEND, $dbw=null)
Add a callable update.
static run( $event, array $args=[], $deprecatedVersion=null)
Call hook functions defined in Hooks::register and $wgHooks.
setOption( $oname, $val)
Set the given option for a user.
int $queryFlagsUsed
User::READ_* constant bitfield used to load data.
getPasswordValidity( $password)
Given unvalidated password input, return error message on failure.
static whoIsReal( $id)
Get the real name of a user given their user ID.
getName()
Get the user name, or the IP of an anonymous user.
$wgSecureLogin
This is to let user authenticate using https when they come from http.
doLogout()
Clear the user's session, and reset the instance cache.
getGroupMemberships()
Get the list of explicit group memberships this user has, stored as UserGroupMembership objects.
canSendEmail()
Is this user allowed to send e-mails within limits of current site configuration?
static isCreatableName( $name)
Usernames which fail to pass this function will be blocked from new account registrations,...
$wgNamespacesToBeSearchedDefault
List of namespaces which are searched by default.
getMutableCacheKeys(WANObjectCache $cache)
getLatestEditTimestamp()
Get the timestamp of the latest edit.
setEditCountInternal( $count)
This method should not be called outside User/UserEditCountUpdate.
setPasswordInternal( $str)
Actually set the password and such.
$wgDisableAnonTalk
Disable links to talk pages of anonymous users (IPs) in listings on special pages like page history,...
Represents a "user group membership" – a specific instance of a user belonging to a group.
static isIPAddress( $ip)
Determine if a string is as valid IP address or network (CIDR prefix).
string $mEmailAuthenticated
static getGroupsWithPermission( $role)
Get all the groups who have a given permission.
isAllowed( $action='')
Internal mechanics of testing a permission.
static logException( $e, $catcher=self::CAUGHT_BY_OTHER)
Log an exception to the exception log (if enabled).
static listOptionKinds()
Return a list of the types of user options currently returned by User::getOptionKinds().
int $wgActorTableSchemaMigrationStage
Actor table schema migration stage.
trackBlockWithCookie()
Set the 'BlockID' cookie depending on block type and user authentication status.