32use Wikimedia\ScopedCallback;
100 'mEmailAuthenticated',
102 'mEmailTokenExpires',
167 'move-categorypages',
168 'move-rootuserpages',
172 'override-export-depth',
194 'userrights-interwiki',
330 return (
string)$this->
getName();
356 $this->mLoadedItems ===
true || $this->mFrom !==
'session';
364 public function load( $flags = self::READ_NORMAL ) {
367 if ( $this->mLoadedItems ===
true ) {
373 $this->mLoadedItems =
true;
374 $this->queryFlagsUsed = $flags;
378 \MediaWiki\Logger\LoggerFactory::getInstance(
'session' )
379 ->warning(
'User::loadFromSession called before the end of Setup.php', [
380 'exception' =>
new Exception(
'User::loadFromSession called before the end of Setup.php' ),
383 $this->mLoadedItems = $oldLoadedItems;
387 switch ( $this->mFrom ) {
393 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
394 if ( $lb->hasOrMadeRecentMasterChanges() ) {
395 $flags |= self::READ_LATEST;
396 $this->queryFlagsUsed = $flags;
409 if ( $this->mId != 0 ) {
410 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
411 if ( $lb->hasOrMadeRecentMasterChanges() ) {
412 $flags |= self::READ_LATEST;
413 $this->queryFlagsUsed = $flags;
421 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
422 if ( $lb->hasOrMadeRecentMasterChanges() ) {
423 $flags |= self::READ_LATEST;
424 $this->queryFlagsUsed = $flags;
427 list( $index,
$options ) = DBAccessObjectUtils::getDBOptions( $flags );
428 $row =
wfGetDB( $index )->selectRow(
430 [
'actor_user',
'actor_name' ],
431 [
'actor_id' => $this->mActorId ],
439 } elseif ( $row->actor_user ) {
440 $this->mId = $row->actor_user;
451 Hooks::run(
'UserLoadAfterLoadFromSession', [ $this ] );
454 throw new UnexpectedValueException(
455 "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
465 if ( $this->mId == 0 ) {
473 $latest = DBAccessObjectUtils::hasFlags( $flags, self::READ_LATEST );
483 $this->mLoadedItems =
true;
484 $this->queryFlagsUsed = $flags;
494 public static function purge( $wikiId, $userId ) {
495 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
496 $key =
$cache->makeGlobalKey(
'user',
'id', $wikiId, $userId );
506 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
507 $lbFactory = MediaWikiServices::getInstance()->getDBLoadBalancerFactory();
509 return $cache->makeGlobalKey(
'user',
'id', $lbFactory->getLocalDomainID(), $this->mId );
518 $id = $this->
getId();
520 return $id ? [ $this->
getCacheKey( $cache ) ] : [];
530 $cache = ObjectCache::getMainWANInstance();
531 $data =
$cache->getWithSetCallback(
536 wfDebug(
"User: cache miss for user {$this->mId}\n" );
543 foreach ( self::$mCacheVars
as $name ) {
544 $data[
$name] = $this->$name;
551 foreach ( $this->mGroupMemberships
as $ugm ) {
552 if ( $ugm->getExpiry() ) {
553 $secondsUntilExpiry =
wfTimestamp( TS_UNIX, $ugm->getExpiry() ) - time();
554 if ( $secondsUntilExpiry > 0 && $secondsUntilExpiry < $ttl ) {
555 $ttl = $secondsUntilExpiry;
562 [
'pcTTL' => $cache::TTL_PROC_LONG,
'version' =>
self::VERSION ]
566 foreach ( self::$mCacheVars
as $name ) {
567 $this->$name = $data[
$name];
592 public static function newFromName( $name, $validate =
'valid' ) {
593 if ( $validate ===
true ) {
597 if (
$name ===
false ) {
604 $u->setItemLoaded(
'name' );
636 throw new BadMethodCallException(
637 'Cannot use ' . __METHOD__
638 .
' when $wgActorTableSchemaMigrationStage lacks SCHEMA_COMPAT_NEW'
659 if ( $identity instanceof
User ) {
664 $identity->
getId() === 0 ?
null : $identity->
getId(),
686 $user->mFrom =
'defaults';
691 $user->mActorId = (int)$actorId;
692 if (
$user->mActorId !== 0 ) {
693 $user->mFrom =
'actor';
695 $user->setItemLoaded(
'actor' );
698 if ( $userName !==
null && $userName !==
'' ) {
699 $user->mName = $userName;
700 $user->mFrom =
'name';
701 $user->setItemLoaded(
'name' );
704 if ( $userId !==
null ) {
705 $user->mId = (int)$userId;
706 if (
$user->mId !== 0 ) {
709 $user->setItemLoaded(
'id' );
712 if (
$user->mFrom ===
'defaults' ) {
713 throw new InvalidArgumentException(
714 'Cannot create a user with no name, no ID, and no actor ID'
733 $db = ( $flags & self::READ_LATEST ) == self::READ_LATEST
737 $id = $db->selectField(
741 'user_email_token' => md5(
$code ),
742 'user_email_token_expires > ' . $db->addQuotes( $db->timestamp() ),
758 $user->mFrom =
'session';
780 $user->loadFromRow( $row, $data );
821 'validate' =>
'valid',
827 if (
$name ===
false ) {
833 $row =
$dbr->selectRow(
834 $userQuery[
'tables'],
835 $userQuery[
'fields'],
836 [
'user_name' =>
$name ],
844 $row = $dbw->selectRow(
845 $userQuery[
'tables'],
846 $userQuery[
'fields'],
847 [
'user_name' =>
$name ],
865 if (
$user->mEmail ||
$user->mToken !== self::INVALID_TOKEN ||
866 AuthManager::singleton()->userCanAuthenticate(
$name )
873 AuthManager::singleton()->revokeAccessForUser(
$name );
875 $user->invalidateEmail();
877 $user->saveSettings();
878 SessionManager::singleton()->preventSessionsForUser(
$user->getName() );
891 public static function whoIs( $id ) {
911 public static function idFromName( $name, $flags = self::READ_NORMAL ) {
913 if ( is_null( $nt ) ) {
918 if ( !( $flags & self::READ_LATEST ) && array_key_exists(
$name, self::$idCacheByName ) ) {
919 return self::$idCacheByName[
$name];
922 list( $index,
$options ) = DBAccessObjectUtils::getDBOptions( $flags );
928 [
'user_name' => $nt->getText() ],
933 if (
$s ===
false ) {
941 if ( count( self::$idCacheByName ) > 1000 ) {
942 self::$idCacheByName = [];
952 self::$idCacheByName = [];
971 public static function isIP( $name ) {
972 return preg_match(
'/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',
$name )
973 || IP::isIPv6(
$name );
983 return IP::isValidRange( $this->mName );
1001 || self::isIP(
$name )
1002 || strpos(
$name,
'/' ) !==
false
1004 ||
$name != MediaWikiServices::getInstance()->getContentLanguage()->ucfirst(
$name )
1011 $parsed = Title::newFromText(
$name );
1012 if ( is_null( $parsed )
1013 || $parsed->getNamespace()
1014 || strcmp(
$name, $parsed->getPrefixedText() ) ) {
1020 $unicodeBlacklist =
'/[' .
1021 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
1022 '\x{00a0}' . # non-breaking space
1023 '\x{2000}-\x{200f}' . # various whitespace
1024 '\x{2028}-\x{202f}' . # breaks
and control chars
1025 '\x{3000}' . # ideographic space
1026 '\x{e000}-\x{f8ff}' . #
private use
1028 if ( preg_match( $unicodeBlacklist,
$name ) ) {
1049 if ( !self::isValidUserName(
$name ) ) {
1053 static $reservedUsernames =
false;
1054 if ( !$reservedUsernames ) {
1056 Hooks::run(
'UserGetReservedNames', [ &$reservedUsernames ] );
1060 foreach ( $reservedUsernames
as $reserved ) {
1061 if ( substr( $reserved, 0, 4 ) ==
'msg:' ) {
1062 $reserved =
wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->plain();
1064 if ( $reserved ==
$name ) {
1082 if ( $groups === [] ) {
1086 $groups = array_unique( (
array)$groups );
1087 $limit = min( 5000, $limit );
1089 $conds = [
'ug_group' => $groups ];
1090 if ( $after !==
null ) {
1091 $conds[] =
'ug_user > ' . (int)$after;
1095 $ids =
$dbr->selectFieldValues(
1102 'ORDER BY' =>
'ug_user',
1127 if ( strlen(
$name ) > 235 ) {
1129 ": '$name' invalid due to length" );
1137 ": '$name' invalid due to wgInvalidUsernameCharacters" );
1168 foreach (
$result->getErrorsByType(
'error' )
as $error ) {
1171 foreach (
$result->getErrorsByType(
'warning' )
as $warning ) {
1209 if ( !Hooks::run(
'isValidPassword', [ $password, &
$result, $this ] ) ) {
1215 $status->merge( $upp->checkUserPassword( $this, $password ) );
1217 } elseif (
$result ===
true ) {
1240 $name = MediaWikiServices::getInstance()->getContentLanguage()->ucfirst(
$name );
1242 # Reject names containing '#'; these will be cleaned up
1243 # with title normalisation, but then it's too late to
1245 if ( strpos(
$name,
'#' ) !==
false ) {
1251 $t = ( $validate !==
false ) ?
1254 if ( is_null(
$t ) ||
$t->getNamespace() !==
NS_USER ||
$t->isExternal() ) {
1259 $name = AuthManager::callLegacyAuthPlugin(
1260 'getCanonicalName', [
$t->getText() ],
$t->getText()
1263 switch ( $validate ) {
1267 if ( !self::isValidUserName(
$name ) ) {
1272 if ( !self::isUsableName(
$name ) ) {
1277 if ( !self::isCreatableName(
$name ) ) {
1282 throw new InvalidArgumentException(
1283 'Invalid parameter value for $validate in ' . __METHOD__ );
1309 $this->mName =
$name;
1310 $this->mActorId =
null;
1311 $this->mRealName =
'';
1313 $this->mOptionOverrides =
null;
1314 $this->mOptionsLoaded =
false;
1316 $loggedOut = $this->mRequest && !defined(
'MW_NO_SESSION' )
1317 ? $this->mRequest->getSession()->getLoggedOutTimestamp() : 0;
1318 if ( $loggedOut !== 0 ) {
1319 $this->mTouched =
wfTimestamp( TS_MW, $loggedOut );
1321 $this->mTouched =
'1'; # Allow any
pages to be cached
1324 $this->mToken =
null;
1325 $this->mEmailAuthenticated =
null;
1326 $this->mEmailToken =
'';
1327 $this->mEmailTokenExpires =
null;
1329 $this->mGroupMemberships = [];
1331 Hooks::run(
'UserLoadDefaults', [ $this,
$name ] );
1347 return ( $this->mLoadedItems ===
true && $all ===
'all' ) ||
1348 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] ===
true );
1357 if ( is_array( $this->mLoadedItems ) ) {
1358 $this->mLoadedItems[$item] =
true;
1370 Hooks::run(
'UserLoadFromSession', [ $this, &
$result ],
'1.27' );
1377 $session = $this->
getRequest()->getSession();
1378 $user = $session->getUser();
1379 if (
$user->isLoggedIn() ) {
1381 if (
$user->isBlocked() ) {
1389 $session->set(
'wsUserID', $this->
getId() );
1390 $session->set(
'wsUserName', $this->
getName() );
1391 $session->set(
'wsToken', $this->
getToken() );
1404 if ( $block && $this->
getRequest()->getCookie(
'BlockID' ) ===
null ) {
1405 $config = RequestContext::getMain()->getConfig();
1406 $shouldSetCookie =
false;
1408 if ( $this->
isAnon() && $config->get(
'CookieSetOnIpBlock' ) ) {
1410 $shouldSetCookie = in_array( $block->getType(), [
1413 if ( $shouldSetCookie ) {
1414 $block->setCookie( $this->
getRequest()->response() );
1417 $stats = MediaWikiServices::getInstance()->getStatsdDataFactory();
1418 $stats->increment(
'block.ipblock.setCookie.success' );
1420 } elseif ( $this->
isLoggedIn() && $config->get(
'CookieSetOnAutoblock' ) ) {
1421 $shouldSetCookie = $block->getType() ===
Block::TYPE_USER && $block->isAutoblocking();
1422 if ( $shouldSetCookie ) {
1423 $block->setCookie( $this->
getRequest()->response() );
1438 $this->mId = intval( $this->mId );
1440 if ( !$this->mId ) {
1446 list( $index,
$options ) = DBAccessObjectUtils::getDBOptions( $flags );
1450 $s = $db->selectRow(
1451 $userQuery[
'tables'],
1452 $userQuery[
'fields'],
1453 [
'user_id' => $this->mId ],
1459 $this->queryFlagsUsed = $flags;
1460 Hooks::run(
'UserLoadFromDatabase', [ $this, &
$s ] );
1462 if (
$s !==
false ) {
1465 $this->mGroupMemberships =
null;
1491 if ( !is_object( $row ) ) {
1492 throw new InvalidArgumentException(
'$row must be an object' );
1497 $this->mGroupMemberships =
null;
1502 if ( isset( $row->actor_id ) ) {
1503 $this->mActorId = (int)$row->actor_id;
1504 if ( $this->mActorId !== 0 ) {
1505 $this->mFrom =
'actor';
1513 if ( isset( $row->user_name ) && $row->user_name !==
'' ) {
1514 $this->mName = $row->user_name;
1515 $this->mFrom =
'name';
1521 if ( isset( $row->user_real_name ) ) {
1522 $this->mRealName = $row->user_real_name;
1528 if ( isset( $row->user_id ) ) {
1529 $this->mId = intval( $row->user_id );
1530 if ( $this->mId !== 0 ) {
1531 $this->mFrom =
'id';
1538 if ( isset( $row->user_id ) && isset( $row->user_name ) && $row->user_name !==
'' ) {
1539 self::$idCacheByName[$row->user_name] = $row->user_id;
1542 if ( isset( $row->user_editcount ) ) {
1543 $this->mEditCount = $row->user_editcount;
1548 if ( isset( $row->user_touched ) ) {
1549 $this->mTouched =
wfTimestamp( TS_MW, $row->user_touched );
1554 if ( isset( $row->user_token ) ) {
1558 $this->mToken = rtrim( $row->user_token,
" \0" );
1559 if ( $this->mToken ===
'' ) {
1560 $this->mToken =
null;
1566 if ( isset( $row->user_email ) ) {
1567 $this->mEmail = $row->user_email;
1568 $this->mEmailAuthenticated =
wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1569 $this->mEmailToken = $row->user_email_token;
1570 $this->mEmailTokenExpires =
wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1577 $this->mLoadedItems =
true;
1580 if ( is_array( $data ) ) {
1581 if ( isset( $data[
'user_groups'] ) && is_array( $data[
'user_groups'] ) ) {
1582 if ( !count( $data[
'user_groups'] ) ) {
1583 $this->mGroupMemberships = [];
1585 $firstGroup = reset( $data[
'user_groups'] );
1586 if ( is_array( $firstGroup ) || is_object( $firstGroup ) ) {
1587 $this->mGroupMemberships = [];
1588 foreach ( $data[
'user_groups']
as $row ) {
1589 $ugm = UserGroupMembership::newFromRow( (
object)$row );
1590 $this->mGroupMemberships[$ugm->getGroup()] = $ugm;
1595 if ( isset( $data[
'user_properties'] ) && is_array( $data[
'user_properties'] ) ) {
1608 foreach ( self::$mCacheVars
as $var ) {
1609 $this->$var =
$user->$var;
1617 if ( is_null( $this->mGroupMemberships ) ) {
1618 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
1621 $this->mGroupMemberships = UserGroupMembership::getMembershipsForUser(
1648 if ( !count( $toPromote ) ) {
1658 foreach ( $toPromote
as $group ) {
1661 $newGroups = array_merge( $oldGroups, $toPromote );
1665 Hooks::run(
'UserGroupsChanged', [ $this, $toPromote, [],
false,
false, $oldUGMs, $newUGMs ] );
1666 AuthManager::callLegacyAuthPlugin(
'updateExternalDBGroups', [ $this, $toPromote ] );
1669 $logEntry->setPerformer( $this );
1671 $logEntry->setParameters( [
1672 '4::oldgroups' => $oldGroups,
1673 '5::newgroups' => $newGroups,
1675 $logid = $logEntry->insert();
1677 $logEntry->publish( $logid );
1693 if ( $this->mTouched ) {
1695 $conditions[
'user_touched'] = $db->
timestamp( $this->mTouched );
1713 if ( !$this->mId ) {
1721 $dbw->update(
'user',
1722 [
'user_touched' => $dbw->timestamp( $newTouched ) ],
1723 $this->makeUpdateConditions( $dbw, [
1724 'user_id' => $this->mId,
1728 $success = ( $dbw->affectedRows() > 0 );
1731 $this->mTouched = $newTouched;
1749 $this->mNewtalk = -1;
1750 $this->mDatePreference =
null;
1751 $this->mBlockedby = -1; # Unset
1752 $this->mHash =
false;
1753 $this->mRights =
null;
1754 $this->mEffectiveGroups =
null;
1755 $this->mImplicitGroups =
null;
1756 $this->mGroupMemberships =
null;
1757 $this->mOptions =
null;
1758 $this->mOptionsLoaded =
false;
1759 $this->mEditCount =
null;
1761 if ( $reloadFrom ) {
1762 $this->mLoadedItems = [];
1763 $this->mFrom = $reloadFrom;
1776 static $defOpt =
null;
1777 static $defOptLang =
null;
1779 $contLang = MediaWikiServices::getInstance()->getContentLanguage();
1780 if ( $defOpt !==
null && $defOptLang === $contLang->getCode() ) {
1789 $defOptLang = $contLang->getCode();
1790 $defOpt[
'language'] = $defOptLang;
1791 foreach ( LanguageConverter::$languagesWithVariants
as $langCode ) {
1792 if ( $langCode === $contLang->getCode() ) {
1793 $defOpt[
'variant'] = $langCode;
1795 $defOpt[
"variant-$langCode"] = $langCode;
1803 $defOpt[
'searchNs' . $nsnum] = (bool)$val;
1807 Hooks::run(
'UserGetDefaultOptions', [ &$defOpt ] );
1820 if ( isset( $defOpts[
$opt] ) ) {
1821 return $defOpts[
$opt];
1836 if ( -1 != $this->mBlockedby ) {
1840 wfDebug( __METHOD__ .
": checking...\n" );
1849 # We only need to worry about passing the IP address to the Block generator if the
1850 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1851 # know which IP address they're actually coming from
1853 $sessionUser = RequestContext::getMain()->getUser();
1856 $globalUserName = $sessionUser->isSafeToLoad()
1857 ? $sessionUser->getName()
1858 : IP::sanitizeIP( $sessionUser->getRequest()->getIP() );
1859 if ( $this->
getName() === $globalUserName && !$this->
isAllowed(
'ipblock-exempt' ) ) {
1867 if ( !$block instanceof
Block ) {
1874 if ( self::isLocallyBlockedProxy( $ip ) ) {
1875 $block =
new Block( [
1879 'systemBlock' =>
'proxy',
1882 $block =
new Block( [
1886 'systemBlock' =>
'dnsbl',
1892 if ( !$block instanceof
Block
1897 $xff = $this->
getRequest()->getHeader(
'X-Forwarded-For' );
1898 $xff = array_map(
'trim', explode(
',', $xff ) );
1899 $xff = array_diff( $xff, [ $ip ] );
1902 if ( $block instanceof
Block ) {
1903 # Mangle the reason to alert the user that the block
1904 # originated from matching the X-Forwarded-For header.
1905 $block->mReason =
wfMessage(
'xffblockreason', $block->mReason )->plain();
1909 if ( !$block instanceof
Block
1914 $block =
new Block( [
1916 'byText' =>
'MediaWiki default',
1919 'systemBlock' =>
'wgSoftBlockRanges',
1923 if ( $block instanceof
Block ) {
1924 wfDebug( __METHOD__ .
": Found block.\n" );
1925 $this->mBlock = $block;
1926 $this->mBlockedby = $block->getByName();
1927 $this->mBlockreason = $block->mReason;
1928 $this->mHideName = $block->mHideName;
1929 $this->mAllowUsertalk = !$block->prevents(
'editownusertalk' );
1931 $this->mBlock =
null;
1932 $this->mBlockedby =
'';
1933 $this->mBlockreason =
'';
1934 $this->mHideName = 0;
1935 $this->mAllowUsertalk =
false;
1941 Hooks::run(
'GetBlockedStatus', [ &$thisUser ] );
1951 if ( strlen( $blockCookieVal ) < 1 || !is_numeric( substr( $blockCookieVal, 0, 1 ) ) ) {
1956 if ( $blockCookieId !==
null ) {
1959 if ( $tmpBlock instanceof
Block ) {
1960 $config = RequestContext::getMain()->getConfig();
1962 switch ( $tmpBlock->getType() ) {
1964 $blockIsValid = !$tmpBlock->isExpired() && $tmpBlock->isAutoblocking();
1965 $useBlockCookie = ( $config->get(
'CookieSetOnAutoblock' ) ===
true );
1970 $blockIsValid = !$tmpBlock->isExpired() && !$this->
isLoggedIn();
1971 $useBlockCookie = ( $config->get(
'CookieSetOnIpBlock' ) ===
true );
1974 $blockIsValid =
false;
1975 $useBlockCookie =
false;
1978 if ( $blockIsValid && $useBlockCookie ) {
2024 if ( IP::isIPv4( $ip ) ) {
2026 $ipReversed = implode(
'.', array_reverse( explode(
'.', $ip ) ) );
2032 if ( is_array(
$base ) ) {
2033 if ( count(
$base ) >= 2 ) {
2035 $host =
"{$base[1]}.$ipReversed.{$base[0]}";
2037 $host =
"$ipReversed.{$base[0]}";
2039 $basename =
$base[0];
2041 $host =
"$ipReversed.$base";
2045 $ipList = gethostbynamel( $host );
2048 wfDebugLog(
'dnsblacklist',
"Hostname $host is {$ipList[0]}, it's a proxy says $basename!" );
2052 wfDebugLog(
'dnsblacklist',
"Requested $host, not found in $basename." );
2079 $resultProxyList = [];
2080 $deprecatedIPEntries = [];
2084 $keyIsIP = IP::isIPAddress( $key );
2085 $valueIsIP = IP::isIPAddress(
$value );
2086 if ( $keyIsIP && !$valueIsIP ) {
2087 $deprecatedIPEntries[] = $key;
2088 $resultProxyList[] = $key;
2089 } elseif ( $keyIsIP && $valueIsIP ) {
2090 $deprecatedIPEntries[] = $key;
2091 $resultProxyList[] = $key;
2092 $resultProxyList[] =
$value;
2094 $resultProxyList[] =
$value;
2098 if ( $deprecatedIPEntries ) {
2100 'IP addresses in the keys of $wgProxyList (found the following IP addresses in keys: ' .
2101 implode(
', ', $deprecatedIPEntries ) .
', please move them to values)',
'1.30' );
2104 $proxyListIPSet =
new IPSet( $resultProxyList );
2105 return $proxyListIPSet->match( $ip );
2121 return !$this->
isAllowed(
'noratelimit' );
2143 if ( !Hooks::run(
'PingLimiter', [ &
$user, $action, &
$result, $incrBy ] ) ) {
2152 $limits = array_merge(
2153 [
'&can-bypass' =>
true ],
2163 $id = $this->
getId();
2166 $cache = ObjectCache::getLocalClusterInstance();
2170 if ( isset( $limits[
'anon'] ) ) {
2171 $keys[
$cache->makeKey(
'limiter', $action,
'anon' )] = $limits[
'anon'];
2175 if ( isset( $limits[
'user'] ) ) {
2176 $userLimit = $limits[
'user'];
2183 if ( isset( $limits[
'ip'] ) ) {
2185 $keys[
"mediawiki:limiter:$action:ip:$ip"] = $limits[
'ip'];
2188 if ( isset( $limits[
'subnet'] ) ) {
2190 $subnet = IP::getSubnet( $ip );
2191 if ( $subnet !==
false ) {
2192 $keys[
"mediawiki:limiter:$action:subnet:$subnet"] = $limits[
'subnet'];
2200 if ( isset( $limits[$group] ) ) {
2201 if ( $userLimit ===
false
2202 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
2204 $userLimit = $limits[$group];
2210 if ( $id !== 0 && $isNewbie && isset( $limits[
'newbie'] ) ) {
2211 $userLimit = $limits[
'newbie'];
2215 if ( $userLimit !==
false ) {
2216 list( $max, $period ) = $userLimit;
2217 wfDebug( __METHOD__ .
": effective user limit: $max in {$period}s\n" );
2218 $keys[
$cache->makeKey(
'limiter', $action,
'user', $id )] = $userLimit;
2222 if ( isset( $limits[
'ip-all'] ) ) {
2225 if ( $isNewbie || $userLimit ===
false
2226 || $limits[
'ip-all'][0] / $limits[
'ip-all'][1] > $userLimit[0] / $userLimit[1] ) {
2227 $keys[
"mediawiki:limiter:$action:ip-all:$ip"] = $limits[
'ip-all'];
2232 if ( isset( $limits[
'subnet-all'] ) ) {
2234 $subnet = IP::getSubnet( $ip );
2235 if ( $subnet !==
false ) {
2237 if ( $isNewbie || $userLimit ===
false
2238 || $limits[
'ip-all'][0] / $limits[
'ip-all'][1]
2239 > $userLimit[0] / $userLimit[1] ) {
2240 $keys[
"mediawiki:limiter:$action:subnet-all:$subnet"] = $limits[
'subnet-all'];
2246 foreach (
$keys as $key => $limit ) {
2247 list( $max, $period ) = $limit;
2248 $summary =
"(limit $max in {$period}s)";
2249 $count =
$cache->get( $key );
2252 if ( $count >= $max ) {
2253 wfDebugLog(
'ratelimit',
"User '{$this->getName()}' " .
2254 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
2257 wfDebug( __METHOD__ .
": ok. $key at $count $summary\n" );
2260 wfDebug( __METHOD__ .
": adding record for $key $summary\n" );
2261 if ( $incrBy > 0 ) {
2262 $cache->add( $key, 0, intval( $period ) );
2265 if ( $incrBy > 0 ) {
2266 $cache->incr( $key, $incrBy );
2292 return $this->mBlock instanceof
Block ? $this->mBlock :
null;
2305 $blocked = $this->
isBlocked( $bFromSlave );
2308 if ( !$this->mHideName && $allowUsertalk &&
$title->getText() === $this->
getName()
2311 wfDebug( __METHOD__ .
": self-talk page, ignoring any blocks\n" );
2314 Hooks::run(
'UserIsBlockedFrom', [ $this,
$title, &$blocked, &$allowUsertalk ] );
2343 return ( $this->mBlock ? $this->mBlock->getId() :
false );
2369 if ( $this->mGlobalBlock !==
null ) {
2370 return $this->mGlobalBlock ?:
null;
2373 if ( IP::isIPAddress( $this->
getName() ) ) {
2382 Hooks::run(
'UserIsBlockedGlobally', [ &
$user, $ip, &$blocked, &$block ] );
2384 if ( $blocked && $block ===
null ) {
2386 $block =
new Block( [
2388 'systemBlock' =>
'global-block'
2392 $this->mGlobalBlock = $blocked ? $block :
false;
2393 return $this->mGlobalBlock ?:
null;
2402 if ( $this->mLocked !==
null ) {
2407 $authUser = AuthManager::callLegacyAuthPlugin(
'getUserInstance', [ &
$user ],
null );
2408 $this->mLocked = $authUser && $authUser->isLocked();
2409 Hooks::run(
'UserIsLocked', [ $this, &$this->mLocked ] );
2419 if ( $this->mHideName !==
null ) {
2423 if ( !$this->mHideName ) {
2426 $authUser = AuthManager::callLegacyAuthPlugin(
'getUserInstance', [ &
$user ],
null );
2427 $this->mHideName = $authUser && $authUser->isHidden();
2428 Hooks::run(
'UserIsHidden', [ $this, &$this->mHideName ] );
2438 if ( $this->mId ===
null && $this->mName !==
null && self::isIP( $this->mName ) ) {
2468 if ( $this->mName ===
false ) {
2470 $this->mName = IP::sanitizeIP( $this->
getRequest()->getIP() );
2491 $this->mName = $str;
2518 if ( $this->mActorId ===
null || !$this->mActorId && $dbw ) {
2520 'actor_user' => $this->
getId() ?:
null,
2524 if ( $q[
'actor_user'] ===
null && self::isUsableName( $q[
'actor_name'] ) ) {
2526 'Cannot create an actor for a usable name that is not an existing user'
2529 if ( $q[
'actor_name'] ===
'' ) {
2532 $dbw->insert(
'actor', $q, __METHOD__, [
'IGNORE' ] );
2533 if ( $dbw->affectedRows() ) {
2534 $this->mActorId = (int)$dbw->insertId();
2538 $this->mActorId = (int)$dbw->selectField(
2543 [
'LOCK IN SHARE MODE' ]
2545 if ( !$this->mActorId ) {
2547 "Cannot create actor ID for user_id={$this->getId()} user_name={$this->getName()}"
2553 list( $index,
$options ) = DBAccessObjectUtils::getDBOptions( $this->queryFlagsUsed );
2555 $this->mActorId = (int)$db->selectField(
'actor',
'actor_id', $q, __METHOD__,
$options );
2568 return str_replace(
' ',
'_', $this->
getName() );
2579 if ( $this->mNewtalk === -1 ) {
2580 $this->mNewtalk =
false; # reset talk
page status
2584 if ( !$this->mId ) {
2588 $this->mNewtalk =
false;
2593 $this->mNewtalk = $this->
checkNewtalk(
'user_id', $this->mId );
2617 if ( !Hooks::run(
'UserRetrieveNewTalks', [ &
$user, &$talks ] ) ) {
2625 $timestamp =
$dbr->selectField(
'user_newtalk',
2626 'MIN(user_last_timestamp)',
2627 $this->
isAnon() ? [
'user_ip' => $this->
getName() ] : [
'user_id' => $this->
getId() ],
2630 return [ [
'wiki' =>
wfWikiID(),
'link' => $utp->getLocalURL(),
'rev' =>
$rev ] ];
2639 $newMessageRevisionId =
null;
2641 if ( $newMessageLinks ) {
2645 if ( count( $newMessageLinks ) === 1
2646 && $newMessageLinks[0][
'wiki'] ===
wfWikiID()
2647 && $newMessageLinks[0][
'rev']
2650 $newMessageRevision = $newMessageLinks[0][
'rev'];
2651 $newMessageRevisionId = $newMessageRevision->getId();
2654 return $newMessageRevisionId;
2668 $ok =
$dbr->selectField(
'user_newtalk', $field, [ $field => $id ], __METHOD__ );
2670 return $ok !==
false;
2682 $prevRev = $curRev ? $curRev->getPrevious() :
false;
2683 $ts = $prevRev ? $prevRev->getTimestamp() :
null;
2686 $dbw->insert(
'user_newtalk',
2687 [ $field => $id,
'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ],
2690 if ( $dbw->affectedRows() ) {
2691 wfDebug( __METHOD__ .
": set on ($field, $id)\n" );
2694 wfDebug( __METHOD__ .
" already set ($field, $id)\n" );
2707 $dbw->delete(
'user_newtalk',
2710 if ( $dbw->affectedRows() ) {
2711 wfDebug( __METHOD__ .
": killed on ($field, $id)\n" );
2714 wfDebug( __METHOD__ .
": already gone ($field, $id)\n" );
2731 $this->mNewtalk = $val;
2738 $id = $this->
getId();
2761 if ( $this->mTouched && $time <= $this->mTouched ) {
2779 if ( !$this->
getId() ) {
2783 $cache = ObjectCache::getMainWANInstance();
2785 if ( $mode ===
'refresh' ) {
2786 $cache->delete( $key, 1 );
2788 $lb = MediaWikiServices::getInstance()->getDBLoadBalancer();
2789 if ( $lb->hasOrMadeRecentMasterChanges() ) {
2790 $lb->getConnection(
DB_MASTER )->onTransactionPreCommitOrIdle(
2825 $id = $this->
getId();
2827 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2828 $key =
$cache->makeKey(
'user-quicktouched',
'id', $id );
2829 $cache->touchCheckKey( $key );
2830 $this->mQuickTouched =
null;
2840 return ( $timestamp >= $this->
getTouched() );
2855 if ( $this->mQuickTouched ===
null ) {
2856 $cache = MediaWikiServices::getInstance()->getMainWANObjectCache();
2857 $key =
$cache->makeKey(
'user-quicktouched',
'id', $this->mId );
2862 return max( $this->mTouched, $this->mQuickTouched );
2922 $manager = AuthManager::singleton();
2925 if ( !$manager->userExists( $this->getName() ) ) {
2926 throw new LogicException(
'Cannot set a password for a user that is not in the database.' );
2930 'username' => $this->
getName(),
2935 \MediaWiki\Logger\LoggerFactory::getInstance(
'authentication' )
2936 ->info( __METHOD__ .
': Password change rejected: '
2937 .
$status->getWikiText(
null,
null,
'en' ) );
2941 $this->
setOption(
'watchlisttoken',
false );
2942 SessionManager::singleton()->invalidateSessionsForUser( $this );
2960 $manager = AuthManager::singleton();
2961 $reqs = $manager->getAuthenticationRequests( AuthManager::ACTION_CHANGE, $this );
2962 $reqs = AuthenticationRequest::loadRequestsFromSubmission( $reqs, $data );
2964 $status = Status::newGood(
'ignored' );
2965 foreach ( $reqs
as $req ) {
2966 $status->merge( $manager->allowsAuthenticationDataChange(
$req ),
true );
2968 if (
$status->getValue() ===
'ignored' ) {
2969 $status->warning(
'authenticationdatachange-ignored' );
2973 foreach ( $reqs
as $req ) {
2974 $manager->changeAuthenticationData(
$req );
2990 if ( !$this->mToken && $forceCreation ) {
2994 if ( !$this->mToken ) {
2997 } elseif ( $this->mToken === self::INVALID_TOKEN ) {
3009 $len = max( 32, self::TOKEN_LENGTH );
3010 if ( strlen(
$ret ) < $len ) {
3012 throw new \UnexpectedValueException(
'Hmac returned less than 128 bits' );
3014 return substr(
$ret, -$len );
3026 if ( $this->mToken === self::INVALID_TOKEN ) {
3027 \MediaWiki\Logger\LoggerFactory::getInstance(
'session' )
3028 ->debug( __METHOD__ .
": Ignoring attempt to set token for system user \"$this\"" );
3029 } elseif ( !$token ) {
3032 $this->mToken = $token;
3045 throw new BadMethodCallException( __METHOD__ .
' has been removed in 1.27' );
3054 Hooks::run(
'UserGetEmail', [ $this, &$this->mEmail ] );
3064 Hooks::run(
'UserGetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
3074 if ( $str == $this->mEmail ) {
3078 $this->mEmail = $str;
3079 Hooks::run(
'UserSetEmail', [ $this, &$this->mEmail ] );
3093 return Status::newFatal(
'emaildisabled' );
3097 if ( $str === $oldaddr ) {
3098 return Status::newGood(
true );
3101 $type = $oldaddr !=
'' ?
'changed' :
'set';
3102 $notificationResult =
null;
3107 if (
$type ==
'changed' ) {
3108 $change = $str !=
'' ?
'changed' :
'removed';
3109 $notificationResult = $this->
sendMail(
3110 wfMessage(
'notificationemail_subject_' . $change )->
text(),
3111 wfMessage(
'notificationemail_body_' . $change,
3125 if ( $notificationResult !==
null ) {
3126 $result->merge( $notificationResult );
3134 $result = Status::newGood(
true );
3158 $this->mRealName = $str;
3171 public function getOption( $oname, $defaultOverride =
null, $ignoreHidden =
false ) {
3175 # We want 'disabled' preferences to always behave as the default value for
3176 # users, even if they have set the option explicitly in their settings (ie they
3177 # set it, and then it was disabled removing their ability to change it). But
3178 # we don't want to erase the preferences in the database in case the preference
3179 # is re-enabled again. So don't touch $mOptions, just override the returned value
3184 if ( array_key_exists( $oname, $this->mOptions ) ) {
3185 return $this->mOptions[$oname];
3187 return $defaultOverride;
3204 # We want 'disabled' preferences to always behave as the default value for
3205 # users, even if they have set the option explicitly in their settings (ie they
3206 # set it, and then it was disabled removing their ability to change it). But
3207 # we don't want to erase the preferences in the database in case the preference
3208 # is re-enabled again. So don't touch $mOptions, just override the returned value
3209 foreach ( $wgHiddenPrefs
as $pref ) {
3211 if ( $default !==
null ) {
3216 if ( $flags & self::GETOPTIONS_EXCLUDE_DEFAULTS ) {
3231 return (
bool)$this->
getOption( $oname );
3245 $val = $defaultOverride;
3247 return intval( $val );
3262 if ( is_null( $val ) ) {
3266 $this->mOptions[$oname] = $val;
3282 $id = $this->
getId();
3292 $token = hash_hmac(
'sha1',
"$oname:$id", $this->
getToken() );
3344 'registered-multiselect',
3345 'registered-checkmatrix',
3370 $preferencesFactory = MediaWikiServices::getInstance()->getPreferencesFactory();
3371 $prefs = $preferencesFactory->getFormDescriptor( $this,
$context );
3376 $specialOptions = array_fill_keys( $preferencesFactory->getSaveBlacklist(),
true );
3378 unset( $prefs[
$name] );
3383 $multiselectOptions = [];
3384 foreach ( $prefs
as $name => $info ) {
3385 if ( ( isset( $info[
'type'] ) && $info[
'type'] ==
'multiselect' ) ||
3386 ( isset( $info[
'class'] ) && $info[
'class'] == HTMLMultiSelectField::class ) ) {
3387 $opts = HTMLFormField::flattenOptions( $info[
'options'] );
3388 $prefix = $info[
'prefix'] ??
$name;
3391 $multiselectOptions[
"$prefix$value"] =
true;
3394 unset( $prefs[
$name] );
3397 $checkmatrixOptions = [];
3398 foreach ( $prefs
as $name => $info ) {
3399 if ( ( isset( $info[
'type'] ) && $info[
'type'] ==
'checkmatrix' ) ||
3400 ( isset( $info[
'class'] ) && $info[
'class'] == HTMLCheckMatrix::class ) ) {
3401 $columns = HTMLFormField::flattenOptions( $info[
'columns'] );
3402 $rows = HTMLFormField::flattenOptions( $info[
'rows'] );
3403 $prefix = $info[
'prefix'] ??
$name;
3405 foreach ( $columns
as $column ) {
3407 $checkmatrixOptions[
"$prefix$column-$row"] =
true;
3411 unset( $prefs[
$name] );
3417 if ( isset( $prefs[$key] ) ) {
3418 $mapping[$key] =
'registered';
3419 } elseif ( isset( $multiselectOptions[$key] ) ) {
3420 $mapping[$key] =
'registered-multiselect';
3421 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
3422 $mapping[$key] =
'registered-checkmatrix';
3423 } elseif ( isset( $specialOptions[$key] ) ) {
3424 $mapping[$key] =
'special';
3425 } elseif ( substr( $key, 0, 7 ) ===
'userjs-' ) {
3426 $mapping[$key] =
'userjs';
3428 $mapping[$key] =
'unused';
3450 $resetKinds = [
'registered',
'registered-multiselect',
'registered-checkmatrix',
'unused' ],
3456 if ( !is_array( $resetKinds ) ) {
3457 $resetKinds = [ $resetKinds ];
3460 if ( in_array(
'all', $resetKinds ) ) {
3461 $newOptions = $defaultOptions;
3464 $context = RequestContext::getMain();
3468 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
3473 foreach ( $this->mOptions
as $key =>
$value ) {
3474 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
3475 if ( array_key_exists( $key, $defaultOptions ) ) {
3476 $newOptions[$key] = $defaultOptions[$key];
3479 $newOptions[$key] =
$value;
3484 Hooks::run(
'UserResetAllOptions', [ $this, &$newOptions, $this->mOptions, $resetKinds ] );
3486 $this->mOptions = $newOptions;
3487 $this->mOptionsLoaded =
true;
3496 if ( is_null( $this->mDatePreference ) ) {
3499 $map =
$wgLang->getDatePreferenceMigrationMap();
3500 if ( isset( $map[
$value] ) ) {
3503 $this->mDatePreference =
$value;
3520 Hooks::run(
'UserRequiresHTTPS', [ $this, &$https ] );
3549 if ( is_null( $this->mRights ) ) {
3551 Hooks::run(
'UserGetRights', [ $this, &$this->mRights ] );
3555 if ( !defined(
'MW_NO_SESSION' ) ) {
3556 $allowedRights = $this->
getRequest()->getSession()->getAllowedUserRights();
3557 if ( $allowedRights !==
null ) {
3558 $this->mRights = array_intersect( $this->mRights, $allowedRights );
3562 Hooks::run(
'UserGetRightsRemove', [ $this, &$this->mRights ] );
3564 $this->mRights = array_values( array_unique( $this->mRights ) );
3572 $config = RequestContext::getMain()->getConfig();
3575 $config->get(
'BlockDisablesLogin' ) &&
3579 $this->mRights = array_intersect( $this->mRights, $anon->getRights() );
3593 return array_keys( $this->mGroupMemberships );
3617 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
3618 $this->mEffectiveGroups = array_unique( array_merge(
3625 Hooks::run(
'UserEffectiveGroups', [ &
$user, &$this->mEffectiveGroups ] );
3627 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
3640 if ( $recache || is_null( $this->mImplicitGroups ) ) {
3641 $this->mImplicitGroups = [
'*' ];
3642 if ( $this->
getId() ) {
3643 $this->mImplicitGroups[] =
'user';
3645 $this->mImplicitGroups = array_unique( array_merge(
3646 $this->mImplicitGroups,
3653 $this->mEffectiveGroups =
null;
3671 if ( is_null( $this->mFormerGroups ) ) {
3672 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
3675 $res = $db->select(
'user_former_groups',
3677 [
'ufg_user' => $this->mId ],
3679 $this->mFormerGroups = [];
3680 foreach (
$res as $row ) {
3681 $this->mFormerGroups[] = $row->ufg_group;
3693 if ( !$this->
getId() ) {
3697 if ( $this->mEditCount ===
null ) {
3701 $count =
$dbr->selectField(
3702 'user',
'user_editcount',
3703 [
'user_id' => $this->mId ],
3707 if ( $count ===
null ) {
3711 $this->mEditCount = $count;
3735 if ( !Hooks::run(
'UserAddGroup', [ $this, &$group, &$expiry ] ) ) {
3741 if ( !$ugm->insert(
true ) ) {
3745 $this->mGroupMemberships[$group] = $ugm;
3750 $this->mRights =
null;
3766 if ( !Hooks::run(
'UserRemoveGroup', [ $this, &$group ] ) ) {
3770 $ugm = UserGroupMembership::getMembership( $this->mId, $group );
3772 if ( !$ugm || !$ugm->delete() ) {
3777 unset( $this->mGroupMemberships[$group] );
3782 $this->mRights =
null;
3794 return $this->
getId() != 0;
3815 Hooks::run(
"UserIsBot", [ $this, &$isBot ] );
3827 $permissions = func_get_args();
3828 foreach ( $permissions
as $permission ) {
3829 if ( $this->
isAllowed( $permission ) ) {
3842 $permissions = func_get_args();
3843 foreach ( $permissions
as $permission ) {
3844 if ( !$this->
isAllowed( $permission ) ) {
3857 if ( $action ===
'' ) {
3862 return in_array( $action, $this->
getRights(),
true );
3904 if ( $this->mRequest ) {
3920 public function isWatched( $title, $checkRights = self::CHECK_USER_RIGHTS ) {
3921 if (
$title->isWatchable() && ( !$checkRights || $this->isAllowed(
'viewmywatchlist' ) ) ) {
3922 return MediaWikiServices::getInstance()->getWatchedItemStore()->isWatched( $this,
$title );
3934 public function addWatch( $title, $checkRights = self::CHECK_USER_RIGHTS ) {
3935 if ( !$checkRights || $this->
isAllowed(
'editmywatchlist' ) ) {
3936 MediaWikiServices::getInstance()->getWatchedItemStore()->addWatchBatchForUser(
3951 public function removeWatch( $title, $checkRights = self::CHECK_USER_RIGHTS ) {
3952 if ( !$checkRights || $this->
isAllowed(
'editmywatchlist' ) ) {
3953 $store = MediaWikiServices::getInstance()->getWatchedItemStore();
3954 $store->removeWatch( $this,
$title->getSubjectPage() );
3955 $store->removeWatch( $this,
$title->getTalkPage() );
3977 if ( !$this->
isAllowed(
'editmywatchlist' ) ) {
3985 if ( !Hooks::run(
'UserClearNewTalkNotification', [ &
$user, $oldid ] ) ) {
3990 DeferredUpdates::addCallableUpdate(
function ()
use (
$title, $oldid ) {
4000 ?
$title->getNextRevisionID( $oldid, Title::GAID_FOR_UPDATE )
4026 MediaWikiServices::getInstance()->getWatchedItemStore()
4027 ->resetNotificationTimestamp( $this,
$title, $force, $oldid );
4048 $id = $this->
getId();
4053 $watchedItemStore = MediaWikiServices::getInstance()->getWatchedItemStore();
4054 $watchedItemStore->resetAllNotificationTimestampsForUser( $this );
4083 $registration > $learnerRegistration
4088 $registration <= $experiencedRegistration
4090 return 'experienced';
4106 if ( 0 == $this->mId ) {
4110 $session = $this->
getRequest()->getSession();
4112 $session = $session->sessionWithRequest(
$request );
4114 $delay = $session->delaySave();
4116 if ( !$session->getUser()->equals( $this ) ) {
4117 if ( !$session->canSetUser() ) {
4118 \MediaWiki\Logger\LoggerFactory::getInstance(
'session' )
4119 ->warning( __METHOD__ .
4120 ": Cannot save user \"$this\" to a user \"{$session->getUser()}\"'s immutable session"
4124 $session->setUser( $this );
4127 $session->setRememberUser( $rememberMe );
4128 if ( $secure !==
null ) {
4129 $session->setForceHTTPS( $secure );
4132 $session->persist();
4134 ScopedCallback::consume( $delay );
4143 if ( Hooks::run(
'UserLogout', [ &
$user ] ) ) {
4153 $session = $this->
getRequest()->getSession();
4154 if ( !$session->canSetUser() ) {
4155 \MediaWiki\Logger\LoggerFactory::getInstance(
'session' )
4156 ->warning( __METHOD__ .
": Cannot log out of an immutable session" );
4157 $error =
'immutable';
4158 } elseif ( !$session->getUser()->equals( $this ) ) {
4159 \MediaWiki\Logger\LoggerFactory::getInstance(
'session' )
4160 ->warning( __METHOD__ .
4161 ": Cannot log user \"$this\" out of a user \"{$session->getUser()}\"'s session"
4165 $error =
'wronguser';
4168 $delay = $session->delaySave();
4169 $session->unpersist();
4170 $session->setLoggedOutTimestamp( time() );
4171 $session->setUser(
new User );
4172 $session->set(
'wsUserID', 0 );
4173 $session->resetAllTokens();
4174 ScopedCallback::consume( $delay );
4177 \MediaWiki\Logger\LoggerFactory::getInstance(
'authevents' )->info(
'Logout', [
4178 'event' =>
'logout',
4179 'successful' => $error ===
false,
4180 'status' => $error ?:
'success',
4194 "Could not update user with ID '{$this->mId}'; DB is read-only."
4200 if ( 0 == $this->mId ) {
4210 $dbw->doAtomicSection( __METHOD__,
function ( $dbw,
$fname )
use ( $newTouched ) {
4213 $dbw->update(
'user',
4215 'user_name' => $this->mName,
4216 'user_real_name' => $this->mRealName,
4217 'user_email' => $this->mEmail,
4218 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
4219 'user_touched' => $dbw->timestamp( $newTouched ),
4220 'user_token' => strval( $this->mToken ),
4221 'user_email_token' => $this->mEmailToken,
4222 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
4223 ], $this->makeUpdateConditions( $dbw, [
4224 'user_id' => $this->mId,
4228 if ( !$dbw->affectedRows() ) {
4232 $from = ( $this->queryFlagsUsed & self::READ_LATEST ) ?
'master' :
'replica';
4233 LoggerFactory::getInstance(
'preferences' )->warning(
4234 "CAS update failed on user_touched for user ID '{user_id}' ({db_flag} read)",
4235 [
'user_id' => $this->mId,
'db_flag' => $from ]
4237 throw new MWException(
"CAS update failed on user_touched. " .
4238 "The version of the user to be saved is older than the current version."
4245 [
'actor_name' => $this->mName ],
4246 [
'actor_user' => $this->mId ],
4252 $this->mTouched = $newTouched;
4255 Hooks::run(
'UserSaveSettings', [ $this ] );
4272 $db = ( ( $flags & self::READ_LATEST ) == self::READ_LATEST )
4277 ? [
'LOCK IN SHARE MODE' ]
4280 $id = $db->selectField(
'user',
4281 'user_id', [
'user_name' =>
$s ], __METHOD__,
$options );
4302 foreach ( [
'password',
'newpassword',
'newpass_time',
'password_expires' ]
as $field ) {
4303 if ( isset(
$params[$field] ) ) {
4304 wfDeprecated( __METHOD__ .
" with param '$field'",
'1.27' );
4312 if ( isset(
$params[
'options'] ) ) {
4318 $noPass = PasswordFactory::newInvalidPassword()->toString();
4321 'user_name' =>
$name,
4322 'user_password' => $noPass,
4323 'user_newpassword' => $noPass,
4324 'user_email' =>
$user->mEmail,
4325 'user_email_authenticated' => $dbw->timestampOrNull(
$user->mEmailAuthenticated ),
4326 'user_real_name' =>
$user->mRealName,
4327 'user_token' => strval(
$user->mToken ),
4328 'user_registration' => $dbw->timestamp(
$user->mRegistration ),
4329 'user_editcount' => 0,
4330 'user_touched' => $dbw->timestamp(
$user->newTouchedTimestamp() ),
4333 $fields[
"user_$name"] =
$value;
4336 return $dbw->doAtomicSection( __METHOD__,
function ( $dbw,
$fname )
use ( $fields ) {
4337 $dbw->insert(
'user', $fields,
$fname, [
'IGNORE' ] );
4338 if ( $dbw->affectedRows() ) {
4339 $newUser = self::newFromId( $dbw->insertId() );
4340 $newUser->mName = $fields[
'user_name'];
4341 $newUser->updateActorId( $dbw );
4343 $newUser->load( self::READ_LATEST );
4379 if ( !$this->mToken ) {
4383 if ( !is_string( $this->mName ) ) {
4384 throw new RuntimeException(
"User name field is not set." );
4390 $status = $dbw->doAtomicSection( __METHOD__,
function ( $dbw,
$fname ) {
4391 $noPass = PasswordFactory::newInvalidPassword()->toString();
4392 $dbw->insert(
'user',
4394 'user_name' => $this->mName,
4395 'user_password' => $noPass,
4396 'user_newpassword' => $noPass,
4397 'user_email' => $this->mEmail,
4398 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
4399 'user_real_name' => $this->mRealName,
4400 'user_token' => strval( $this->mToken ),
4401 'user_registration' => $dbw->timestamp( $this->mRegistration ),
4402 'user_editcount' => 0,
4403 'user_touched' => $dbw->timestamp( $this->mTouched ),
4407 if ( !$dbw->affectedRows() ) {
4409 $this->mId = $dbw->selectField(
4412 [
'user_name' => $this->mName ],
4414 [
'LOCK IN SHARE MODE' ]
4424 "to insert user '{$this->mName}' row, but it was not present in select!" );
4426 return Status::newFatal(
'userexists' );
4428 $this->mId = $dbw->insertId();
4432 return Status::newGood();
4442 return Status::newGood();
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->prevents(
'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->
prevents(
'createaccount' )
4513 ? $this->mBlockedFromCreateAccount
4523 return $this->mBlock && $this->mBlock->prevents(
'sendemail' );
4550 return $title->getTalkPage();
4559 return !$this->
isAllowed(
'autoconfirmed' );
4571 $manager = AuthManager::singleton();
4572 $reqs = AuthenticationRequest::loadRequestsFromSubmission(
4573 $manager->getAuthenticationRequests( AuthManager::ACTION_LOGIN ),
4575 'username' => $this->getName(),
4576 'password' => $password,
4579 $res = AuthManager::singleton()->beginAuthentication( $reqs,
'null:' );
4580 switch (
$res->status ) {
4581 case AuthenticationResponse::PASS:
4583 case AuthenticationResponse::FAIL:
4585 \MediaWiki\Logger\LoggerFactory::getInstance(
'authentication' )
4586 ->info( __METHOD__ .
': Authentication failed: ' .
$res->message->plain() );
4589 throw new BadMethodCallException(
4590 'AuthManager returned a response unsupported by ' . __METHOD__
4628 return $request->getSession()->getToken( $salt );
4675 $val = substr( $val, 0, strspn( $val,
'0123456789abcdef' ) ) . Token::SUFFIX;
4694 if (
$type ==
'created' ||
$type ===
false ) {
4695 $message =
'confirmemail_body';
4696 } elseif (
$type ===
true ) {
4697 $message =
'confirmemail_body_changed';
4700 $message =
'confirmemail_body_' .
$type;
4708 $wgLang->userTimeAndDate( $expiration, $this ),
4710 $wgLang->userDate( $expiration, $this ),
4711 $wgLang->userTime( $expiration, $this ) )->text() );
4725 public function sendMail( $subject, $body, $from =
null, $replyto =
null ) {
4728 if ( $from instanceof
User ) {
4737 'replyTo' => $replyto,
4758 $hash = md5( $token );
4759 $this->mEmailToken = $hash;
4760 $this->mEmailTokenExpires = $expiration;
4770 return $this->
getTokenUrl(
'ConfirmEmail', $token );
4779 return $this->
getTokenUrl(
'InvalidateEmail', $token );
4798 $title = Title::makeTitle(
NS_MAIN,
"Special:$page/$token" );
4799 return $title->getCanonicalURL();
4814 Hooks::run(
'ConfirmEmailComplete', [ $this ] );
4828 $this->mEmailToken =
null;
4829 $this->mEmailTokenExpires =
null;
4832 Hooks::run(
'InvalidateEmailComplete', [ $this ] );
4842 $this->mEmailAuthenticated = $timestamp;
4843 Hooks::run(
'UserSetEmailAuthenticationTimestamp', [ $this, &$this->mEmailAuthenticated ] );
4859 Hooks::run(
'UserCanSendEmail', [ &
$user, &$canSend ] );
4888 if ( Hooks::run(
'EmailConfirmed', [ &
$user, &$confirmed ] ) ) {
4892 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4912 $this->mEmailToken &&
4938 if ( $this->
getId() == 0 ) {
4942 $actorWhere = ActorMigration::newMigration()->getWhere(
$dbr,
'rev_user', $this );
4944 [
'revision' ] + $actorWhere[
'tables'],
4946 [ $actorWhere[
'conds'] ],
4948 [
'ORDER BY' =>
'rev_timestamp ASC' ],
4949 $actorWhere[
'joins']
4967 foreach ( $groups
as $group ) {
4969 $rights = array_merge( $rights,
4975 foreach ( $groups
as $group ) {
4977 $rights = array_diff( $rights,
4981 return array_unique( $rights );
4992 $allowedGroups = [];
4994 if ( self::groupHasPermission( $group, $role ) ) {
4995 $allowedGroups[] = $group;
4998 return $allowedGroups;
5039 if ( isset(
$cache[$right] ) && !defined(
'MW_PHPUNIT_TEST' ) ) {
5050 if ( isset( $rights[$right] ) && $rights[$right] ) {
5058 if ( !defined(
'MW_NO_SESSION' ) ) {
5059 $allowedRights = SessionManager::getGlobalSession()->getAllowedUserRights();
5060 if ( $allowedRights !==
null && !in_array( $right, $allowedRights,
true ) ) {
5067 if ( !Hooks::run(
'UserIsEveryoneAllowed', [ $right ] ) ) {
5085 return UserGroupMembership::getGroupName( $group );
5098 return UserGroupMembership::getGroupMemberName( $group,
$username );
5109 return array_values( array_diff(
5111 self::getImplicitGroups()
5120 if ( self::$mAllRights ===
false ) {
5123 self::$mAllRights = array_unique( array_merge( self::$mCoreRights,
$wgAvailableRights ) );
5127 Hooks::run(
'UserGetAllRights', [ &self::$mAllRights ] );
5152 return UserGroupMembership::getGroupPage( $group );
5168 if ( $text ==
'' ) {
5169 $text = UserGroupMembership::getGroupName( $group );
5171 $title = UserGroupMembership::getGroupPage( $group );
5173 return MediaWikiServices::getInstance()
5174 ->getLinkRenderer()->makeLink(
$title, $text );
5176 return htmlspecialchars( $text );
5193 if ( $text ==
'' ) {
5194 $text = UserGroupMembership::getGroupName( $group );
5196 $title = UserGroupMembership::getGroupPage( $group );
5198 $page =
$title->getFullText();
5199 return "[[$page|$text]]";
5245 if ( is_int( $key ) ) {
5253 if ( is_int( $key ) ) {
5288 if ( $this->
isAllowed(
'userrights' ) ) {
5293 $all = array_merge( self::getAllGroups() );
5311 foreach ( $addergroups
as $addergroup ) {
5312 $groups = array_merge_recursive(
5315 $groups[
'add'] = array_unique( $groups[
'add'] );
5316 $groups[
'remove'] = array_unique( $groups[
'remove'] );
5317 $groups[
'add-self'] = array_unique( $groups[
'add-self'] );
5318 $groups[
'remove-self'] = array_unique( $groups[
'remove-self'] );
5352 [
'user_editcount=user_editcount+1' ],
5353 [
'user_id' => $this->
getId(),
'user_editcount IS NOT NULL' ],
5357 if ( $dbw->affectedRows() == 0 ) {
5360 if (
$dbr !== $dbw ) {
5372 if ( $this->mEditCount ===
null ) {
5375 $this->mEditCount += (
$dbr !== $dbw ) ? 1 : 0;
5377 $this->mEditCount++;
5394 $actorWhere = ActorMigration::newMigration()->getWhere(
$dbr,
'rev_user', $this );
5395 $count = (int)
$dbr->selectField(
5396 [
'revision' ] + $actorWhere[
'tables'],
5398 [ $actorWhere[
'conds'] ],
5401 $actorWhere[
'joins']
5403 $count = $count + $add;
5408 [
'user_editcount' => $count ],
5409 [
'user_id' => $this->
getId() ],
5424 $key =
"right-$right";
5426 return $msg->isDisabled() ? $right : $msg->text();
5437 $key =
"grant-$grant";
5439 return $msg->isDisabled() ? $grant : $msg->text();
5488 if ( $this->mOptionsLoaded ) {
5494 if ( !$this->
getId() ) {
5499 $variant = MediaWikiServices::getInstance()->getContentLanguage()->getDefaultVariant();
5500 $this->mOptions[
'variant'] = $variant;
5501 $this->mOptions[
'language'] = $variant;
5502 $this->mOptionsLoaded =
true;
5507 if ( !is_null( $this->mOptionOverrides ) ) {
5508 wfDebug(
"User: loading options for user " . $this->
getId() .
" from override cache.\n" );
5509 foreach ( $this->mOptionOverrides
as $key =>
$value ) {
5510 $this->mOptions[$key] =
$value;
5513 if ( !is_array( $data ) ) {
5514 wfDebug(
"User: loading options for user " . $this->
getId() .
" from database.\n" );
5516 $dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
5522 [
'up_property',
'up_value' ],
5523 [
'up_user' => $this->
getId() ],
5527 $this->mOptionOverrides = [];
5529 foreach (
$res as $row ) {
5534 if ( $row->up_value ===
'0' ) {
5537 $data[$row->up_property] = $row->up_value;
5548 $this->mOptions[
'language'] = LanguageCode::replaceDeprecatedCodes(
5549 $this->mOptions[
'language']
5552 $this->mOptionsLoaded =
true;
5554 Hooks::run(
'UserLoadOptions', [ $this, &$this->mOptions ] );
5570 if ( !Hooks::run(
'UserSaveOptions', [ $this, &$saveOptions ] ) ) {
5574 $userId = $this->
getId();
5577 foreach ( $saveOptions
as $key =>
$value ) {
5580 if ( ( $defaultOption ===
null &&
$value !==
false &&
$value !==
null )
5581 ||
$value != $defaultOption
5584 'up_user' => $userId,
5585 'up_property' => $key,
5593 $res = $dbw->select(
'user_properties',
5594 [
'up_property',
'up_value' ], [
'up_user' => $userId ], __METHOD__ );
5599 foreach (
$res as $row ) {
5600 if ( !isset( $saveOptions[$row->up_property] )
5601 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
5603 $keysDelete[] = $row->up_property;
5607 if ( count( $keysDelete ) ) {
5615 $dbw->delete(
'user_properties',
5616 [
'up_user' => $userId,
'up_property' => $keysDelete ], __METHOD__ );
5619 $dbw->insert(
'user_properties', $insert_rows, __METHOD__, [
'IGNORE' ] );
5637 'user_email_authenticated',
5639 'user_email_token_expires',
5640 'user_registration',
5658 'tables' => [
'user' ],
5666 'user_email_authenticated',
5668 'user_email_token_expires',
5669 'user_registration',
5678 $ret[
'tables'][
'user_actor'] =
'actor';
5679 $ret[
'fields'][] =
'user_actor.actor_id';
5680 $ret[
'joins'][
'user_actor'] = [
5682 [
'user_actor.actor_user = user_id' ]
5700 foreach ( self::getGroupsWithPermission( $permission )
as $group ) {
5701 $groups[] = UserGroupMembership::getLink( $group, RequestContext::getMain(),
'wiki' );
5705 return Status::newFatal(
'badaccess-groups',
$wgLang->commaList( $groups ), count( $groups ) );
5707 return Status::newFatal(
'badaccess-group0' );
5721 if ( !$this->
getId() ) {
5726 if ( !
$user->loadFromId( self::READ_EXCLUSIVE ) ) {
and(b) You must cause any modified files to carry prominent notices stating that You changed the files
Apache License January AND DISTRIBUTION Definitions License shall mean the terms and conditions for use
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
$wgRateLimitsExcludedIPs
Array of IPs / CIDR ranges which should be excluded from rate limits.
$wgApplyIpBlocksToXff
Whether to look at the X-Forwarded-For header's list of (potentially spoofed) IPs and apply IP blocks...
$wgUserEmailConfirmationTokenExpiry
The time, in seconds, when an email confirmation email expires.
$wgMaxArticleSize
Maximum article size in kilobytes.
$wgLearnerMemberSince
Name of the external diff engine to use.
$wgProxyList
Big list of banned IP addresses.
$wgHiddenPrefs
An array of preferences to not show for the user.
$wgDefaultUserOptions
Settings added to this array will override the default globals for the user preferences used by anony...
$wgDisableAnonTalk
Disable links to talk pages of anonymous users (IPs) in listings on special pages like page history,...
$wgAutopromoteOnceLogInRC
Put user rights log entries for autopromotion in recent changes?
$wgEnableUserEmail
Set to true to enable user-to-user e-mail.
$wgPasswordPolicy
Password policy for local wiki users.
$wgExperiencedUserMemberSince
Name of the external diff engine to use.
$wgUseFilePatrol
Use file patrolling to check new files on Special:Newfiles.
string null $wgAuthenticationTokenVersion
Versioning for authentication tokens.
string[] $wgSoftBlockRanges
IP ranges that should be considered soft-blocked (anon-only, account creation allowed).
$wgProxyWhitelist
Proxy whitelist, list of addresses that are assumed to be non-proxy despite what the other methods mi...
$wgClockSkewFudge
Clock skew or the one-second resolution of time() can occasionally cause cache problems when the user...
$wgGroupsAddToSelf
A map of group names that the user is in, to group names that those users are allowed to add or revok...
$wgAvailableRights
A list of available rights, in addition to the ones defined by the core.
$wgShowUpdatedMarker
Show "Updated (since my last visit)" marker in RC view, watchlist and history view for watched pages ...
$wgUseRCPatrol
Use RC Patrolling to check for vandalism (from recent changes and watchlists) New pages and new files...
$wgLearnerEdits
The following variables define 3 user experience levels:
$wgUseNPPatrol
Use new page patrolling to check new pages on Special:Newpages.
$wgInvalidUsernameCharacters
Characters to prevent during new account creations.
$wgEnableEmail
Set to true to enable the e-mail basic features: Password reminders, etc.
$wgMaxNameChars
Maximum number of bytes in username.
$wgSecureLogin
This is to let user authenticate using https when they come from http.
$wgImplicitGroups
Implicit groups, aren't shown on Special:Listusers or somewhere else.
$wgAddGroups
$wgAddGroups and $wgRemoveGroups can be used to give finer control over who can assign which groups a...
$wgBlockAllowsUTEdit
Set this to true to allow blocked users to edit their own user talk page.
$wgGroupPermissions
Permission keys given to users in each group.
$wgExperiencedUserEdits
Name of the external diff engine to use.
$wgReservedUsernames
Array of usernames which may not be registered or logged in from Maintenance scripts can still use th...
$wgDefaultSkin
Default skin, for new users and anonymous visitors.
$wgRevokePermissions
Permission keys revoked from users in each group.
$wgEnableDnsBlacklist
Whether to use DNS blacklists in $wgDnsBlacklistUrls to check for open proxies.
$wgDnsBlacklistUrls
List of DNS blacklists to use, if $wgEnableDnsBlacklist is true.
$wgMinimalPasswordLength
Specifies the minimal length of a user password.
$wgEmailAuthentication
Require email authentication before sending mail to an email address.
$wgPasswordSender
Sender email address for e-mail notifications.
$wgRateLimits
Simple rate limiter options to brake edit floods.
$wgNamespacesToBeSearchedDefault
List of namespaces which are searched by default.
int $wgActorTableSchemaMigrationStage
Actor table schema migration stage.
wfDebug( $text, $dest='all', array $context=[])
Sends a line to the debug log if enabled or, optionally, to a comment in output.
wfTimestampOrNull( $outputtype=TS_UNIX, $ts=null)
Return a formatted timestamp, or null if input is null.
wfTimestampNow()
Convenience function; returns MediaWiki timestamp for the present time.
wfReadOnly()
Check whether the wiki is in read-only mode.
wfGetDB( $db, $groups=[], $wiki=false)
Get a Database object.
wfCanIPUseHTTPS( $ip)
Determine whether the client at a given source IP is likely to be able to access the wiki via HTTPS.
wfDebugLog( $logGroup, $text, $dest='all', array $context=[])
Send a line to a supplementary debug log file, if configured, or main debug log if not.
wfTimestamp( $outputtype=TS_UNIX, $ts=0)
Get a timestamp string in one of various formats.
wfDeprecated( $function, $version=false, $component=false, $callerOffset=2)
Throws a warning that $function is deprecated.
wfWikiID()
Get an ASCII string identifying this wiki This is used as a prefix in memcached keys.
if(defined( 'MW_SETUP_CALLBACK')) $fname
Customization point after all loading (constants, functions, classes, DefaultSettings,...
foreach( $wgExtensionFunctions as $func) if(!defined('MW_NO_SESSION') &&! $wgCommandLineMode) if(! $wgCommandLineMode) $wgFullyInitialised
if(! $wgDBerrorLogTZ) $wgRequest
static clearCookie(WebResponse $response)
Unset the 'BlockID' cookie.
prevents( $action, $x=null)
Get/set whether the Block prevents a given action.
static newFromID( $id)
Load a blocked user from their block id.
static getBlocksForIPList(array $ipChain, $isAnon, $fromMaster=false)
Get all blocks that match any IP from an array of IP addresses.
static chooseBlock(array $blocks, array $ipChain)
From a list of multiple blocks, find the most exact and strongest Block.
static getIdFromCookieValue( $cookieValue)
Get the stored ID from the 'BlockID' cookie.
static newFromTarget( $specificTarget, $vagueTarget=null, $fromMaster=false)
Given a target and the target's type, get an existing Block object if possible.
Exception thrown when an actor can't be created.
Value object representing a logged-out user's edit token.
static hmac( $data, $key, $raw=true)
Generate an acceptably unstable one-way-hmac of some text making use of the best hash algorithm that ...
static generateHex( $chars)
Generate a run of cryptographically random data and return it in hexadecimal string format.
Stores a single person's name and email address.
static newFromUser(User $user)
Create a new MailAddress object for the given user.
Class for creating new log entries and inserting them into the database.
static loadFromTimestamp( $db, $title, $timestamp)
Load the revision for the given title with the given timestamp.
static newFromId( $id, $flags=0)
Load a page revision from a given revision ID number.
Represents a "user group membership" – a specific instance of a user belonging to a group.
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...
Check if a user's password complies with any password policies that apply to that user,...
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
loadFromSession()
Load user data from the session.
addWatch( $title, $checkRights=self::CHECK_USER_RIGHTS)
Watch an article.
string $mTouched
TS_MW timestamp from the DB.
logout()
Log this user out.
getOptions( $flags=0)
Get all user's options.
getRequest()
Get the WebRequest object to use with this object.
getPasswordValidity( $password)
Given unvalidated password input, return error message on failure.
Block $mBlockedFromCreateAccount
getName()
Get the user name, or the IP of an anonymous user.
addToDatabase()
Add this existing user object to the database.
requiresHTTPS()
Determine based on the wiki configuration and the user's options, whether this user must be over HTTP...
isBlocked( $bFromSlave=true)
Check if user is blocked.
updateActorId(IDatabase $dbw)
Update the actor ID after an insert.
getExperienceLevel()
Compute experienced level based on edit count and registration date.
static isEveryoneAllowed( $right)
Check if all users may be assumed to have the given permission.
static newFromName( $name, $validate='valid')
Static factory method for creation from username.
resetOptions( $resetKinds=[ 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused'], IContextSource $context=null)
Reset certain (or all) options to the site defaults.
static whoIsReal( $id)
Get the real name of a user given their user ID.
invalidateCache()
Immediately touch the user data cache for this account.
static $mCacheVars
Array of Strings List of member variables which are saved to the shared cache (memcached).
getEmailAuthenticationTimestamp()
Get the timestamp of the user's e-mail authentication.
isBlockedFromEmailuser()
Get whether the user is blocked from using Special:Emailuser.
static getQueryInfo()
Return the tables, fields, and join conditions to be selected to create a new user object.
$mOptionsLoaded
Bool Whether the cache variables have been loaded.
static isCreatableName( $name)
Usernames which fail to pass this function will be blocked from new account registrations,...
getFirstEditTimestamp()
Get the timestamp of the first edit.
getOptionKinds(IContextSource $context, $options=null)
Return an associative array mapping preferences keys to the kind of a preference they're used for.
getBlockedStatus( $bFromSlave=true)
Get blocking information.
static changeableByGroup( $group)
Returns an array of the groups that a particular group can add/remove.
const VERSION
@const int Serialized record version.
getEditTokenObject( $salt='', $request=null)
Initialize (if necessary) and return a session token value which can be used in edit forms to show th...
static getAllGroups()
Return the set of defined explicit groups.
string $mEmailTokenExpires
setCookies( $request=null, $secure=null, $rememberMe=false)
Persist this user's session (e.g.
getEditToken( $salt='', $request=null)
Initialize (if necessary) and return a session token value which can be used in edit forms to show th...
isDnsBlacklisted( $ip, $checkWhitelist=false)
Whether the given IP is in a DNS blacklist.
int $queryFlagsUsed
User::READ_* constant bitfield used to load data.
static $mAllRights
String Cached results of getAllRights()
equals(UserIdentity $user)
Checks if two user objects point to the same user.
getTokenUrl( $page, $token)
Internal function to format the e-mail validation/invalidation URLs.
addGroup( $group, $expiry=null)
Add the user to the given group.
isBlockedGlobally( $ip='')
Check if user is blocked on all wikis.
string $mQuickTouched
TS_MW timestamp from cache.
const INVALID_TOKEN
@const string An invalid value for user_token
isSafeToLoad()
Test if it's safe to load this User object.
static groupHasPermission( $group, $role)
Check, if the given group has the given permission.
isEmailConfirmed()
Is this user's e-mail address valid-looking and confirmed within limits of the current site configura...
spreadAnyEditBlock()
If this user is logged-in and blocked, block any IP address they've successfully logged in from.
useFilePatrol()
Check whether to enable new files patrol features for this user.
loadFromId( $flags=self::READ_NORMAL)
Load user table data, given mId has already been set.
isAllowed( $action='')
Internal mechanics of testing a permission.
getDBTouched()
Get the user_touched timestamp field (time of last DB updates)
setName( $str)
Set the user name.
changeAuthenticationData(array $data)
Changes credentials of the user.
static $mCoreRights
Array of Strings Core rights.
getId()
Get the user's ID.
getRealName()
Get the user's real name.
loadOptions( $data=null)
Load the user options either from cache, the database or an array.
getBoolOption( $oname)
Get the user's current setting for a given option, as a boolean value.
getRegistration()
Get the timestamp of account creation.
static isLocallyBlockedProxy( $ip)
Check if an IP address is in the local proxy list.
getGlobalBlock( $ip='')
Check if user is blocked on all wikis.
static newFromAnyId( $userId, $userName, $actorId)
Static factory method for creation from an ID, name, and/or actor ID.
isItemLoaded( $item, $all='all')
Return whether an item has been loaded.
getMutableCacheKeys(WANObjectCache $cache)
getTokenFromOption( $oname)
Get a token stored in the preferences (like the watchlist one), resetting it if it's empty (and savin...
isNewbie()
Determine whether the user is a newbie.
clearNotification(&$title, $oldid=0)
Clear the user's notification timestamp for the given title.
static resetIdByNameCache()
Reset the cache used in idFromName().
deleteNewtalk( $field, $id)
Clear the new messages flag for the given user.
loadFromDatabase( $flags=self::READ_LATEST)
Load user and user_group data from the database.
invalidationTokenUrl( $token)
Return a URL the user can use to invalidate their email address.
useNPPatrol()
Check whether to enable new pages patrol features for this user.
static randomPassword()
Return a random password.
static purge( $wikiId, $userId)
getIntOption( $oname, $defaultOverride=0)
Get the user's current setting for a given option, as an integer value.
clearInstanceCache( $reloadFrom=false)
Clear various cached data stored in this object.
canReceiveEmail()
Is this user allowed to receive e-mails within limits of current site configuration?
loadDefaults( $name=false)
Set cached properties to default.
trackBlockWithCookie()
Set the 'BlockID' cookie depending on block type and user authentication status.
getOption( $oname, $defaultOverride=null, $ignoreHidden=false)
Get the user's current setting for a given option.
touch()
Update the "touched" timestamp for the user.
checkTemporaryPassword( $plaintext)
Check if the given clear-text password matches the temporary password sent by e-mail for password res...
isPingLimitable()
Is this user subject to rate limiting?
clearSharedCache( $mode='changed')
Clear user data from memcached.
static getCanonicalName( $name, $validate='valid')
Given unvalidated user input, return a canonical username, or false if the username is invalid.
static newFromRow( $row, $data=null)
Create a new user object from a user row.
getToken( $forceCreation=true)
Get the user's current token.
static newFromId( $id)
Static factory method for creation from a given user ID.
setInternalPassword( $str)
Set the password and reset the random token unconditionally.
confirmEmail()
Mark the e-mail address confirmed.
static getGroupsWithPermission( $role)
Get all the groups who have a given permission.
setId( $v)
Set the user and reload all fields according to a given ID.
static getGroupPermissions( $groups)
Get the permissions associated with a given list of groups.
$mNewtalk
Lazy-initialized variables, invalidated with clearInstanceCache.
static getDefaultOptions()
Combine the language default options with any site-specific options and add the default language vari...
static findUsersByGroup( $groups, $limit=5000, $after=null)
Return the users who are members of the given group(s).
getEffectiveGroups( $recache=false)
Get the list of implicit group memberships this user has.
static selectFields()
Return the list of user fields that should be selected to create a new user object.
isHidden()
Check if user account is hidden.
static newFromConfirmationCode( $code, $flags=0)
Factory method to fetch whichever user has a given email confirmation code.
setEmailWithConfirmation( $str)
Set the user's e-mail address and a confirmation mail if needed.
newTouchedTimestamp()
Generate a current or new-future timestamp to be stored in the user_touched field when we update thin...
inDnsBlacklist( $ip, $bases)
Whether the given IP is in a given DNS blacklist.
loadFromUserObject( $user)
Load the data for this user object from another user object.
static isUsableName( $name)
Usernames which fail to pass this function will be blocked from user login and new account registrati...
static getDefaultOption( $opt)
Get a given default option value.
getDatePreference()
Get the user's preferred date format.
checkPasswordValidity( $password)
Check if this is a valid password for this user.
static getGroupPage( $group)
Get the title of a page describing a particular group.
idForName( $flags=0)
If only this user's username is known, and it exists, return the user ID.
getGroupMemberships()
Get the list of explicit group memberships this user has, stored as UserGroupMembership objects.
matchEditTokenNoSuffix( $val, $salt='', $request=null, $maxage=null)
Check given value against the token value stored in the session, ignoring the suffix.
isWatched( $title, $checkRights=self::CHECK_USER_RIGHTS)
Check the watched status of an article.
loadFromRow( $row, $data=null)
Initialize this object from a row from the user table.
setPassword( $str)
Set the password and reset the random token.
confirmationTokenUrl( $token)
Return a URL the user can use to confirm their email address.
isAllowedToCreateAccount()
Get whether the user is allowed to create an account.
static newFromSession(WebRequest $request=null)
Create a new user object using data from session.
incEditCountImmediate()
Increment the user's edit-count field.
static getAllRights()
Get a list of all available permissions.
getNewtalk()
Check if the user has new messages.
getGroups()
Get the list of explicit group memberships this user has.
addNewUserLogEntry( $action=false, $reason='')
Add a newuser log entry for this user.
validateCache( $timestamp)
Validate the cache for this account.
useRCPatrol()
Check whether to enable recent changes patrol features for this user.
loadGroups()
Load the groups from the database if they aren't already loaded.
static whoIs( $id)
Get the username corresponding to a given user ID.
invalidateEmail()
Invalidate the user's e-mail confirmation, and unauthenticate the e-mail address if it was already co...
setEmailAuthenticationTimestamp( $timestamp)
Set the e-mail authentication timestamp.
static newSystemUser( $name, $options=[])
Static factory method for creation of a "system" user from username.
setOption( $oname, $val)
Set the given option for a user.
saveOptions()
Saves the non-default options for this user, as previously set e.g.
static getRightDescription( $right)
Get the description of a given right.
getEditCount()
Get the user's edit count.
getActorId(IDatabase $dbw=null)
Get the user's actor ID.
UserGroupMembership[] $mGroupMemberships
Associative array of (group name => UserGroupMembership object)
addAutopromoteOnceGroups( $event)
Add the user to the group if he/she meets given criteria.
isValidPassword( $password)
Is the input a valid password for this user?
getBlock( $bFromSlave=true)
Get the block affecting the user, or null if the user is not blocked.
isBlockedFromCreateAccount()
Get whether the user is explicitly blocked from account creation.
spreadBlock()
If this (non-anonymous) user is blocked, block the IP address they've successfully logged in from.
getFormerGroups()
Returns the groups the user has belonged to.
setRealName( $str)
Set the user's real name.
static newFromIdentity(UserIdentity $identity)
Returns a User object corresponding to the given UserIdentity.
getTitleKey()
Get the user's name escaped by underscores.
static isIP( $name)
Does the string match an anonymous IP address?
static makeGroupLinkWiki( $group, $text='')
Create a link to the group in Wikitext, if available; else return the group name.
getTouched()
Get the user touched timestamp.
sendMail( $subject, $body, $from=null, $replyto=null)
Send an e-mail to this user's account.
isLocked()
Check if user account is locked.
checkAndSetTouched()
Bump user_touched if it didn't change since this object was loaded.
removeWatch( $title, $checkRights=self::CHECK_USER_RIGHTS)
Stop watching an article.
setPasswordInternal( $str)
Actually set the password and such.
isEmailConfirmationPending()
Check whether there is an outstanding request for e-mail confirmation.
checkNewtalk( $field, $id)
Internal uncached check for new messages.
isBlockedFrom( $title, $bFromSlave=false)
Check if user is blocked from editing a particular article.
getUserPage()
Get this user's personal page title.
isIPRange()
Is the user an IP range?
$mFrom
String Initialization data source if mLoadedItems!==true.
confirmationToken(&$expiration)
Generate, store, and return a new e-mail confirmation code.
canSendEmail()
Is this user allowed to send e-mails within limits of current site configuration?
getBlockId()
If user is blocked, return the ID for the block.
__construct()
Lightweight constructor for an anonymous user.
setNewtalk( $val, $curRev=null)
Update the 'You have new messages!' status.
getStubThreshold()
Get the user preferred stub threshold.
pingLimiter( $action='edit', $incrBy=1)
Primitive rate limits: enforce maximum actions per time period to put a brake on flooding.
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...
getTalkPage()
Get this user's talk page title.
isLoggedIn()
Get whether the user is logged in.
static idFromName( $name, $flags=self::READ_NORMAL)
Get database id given a user name.
loadFromCache()
Load user data from shared cache, given mId has already been set.
getCacheKey(WANObjectCache $cache)
initEditCount( $add=0)
Initialize user_editcount from data out of the revision table.
saveSettings()
Save this user's settings into the database.
getNewMessageRevisionId()
Get the revision ID for the last talk page revision viewed by the talk page owner.
getBlockFromCookieValue( $blockCookieVal)
Try to load a Block from an ID given in a cookie value.
static getGrantName( $grant)
Get the name of a given grant.
isAllowedAny()
Check if user is allowed to access a feature / make an action.
getEmail()
Get the user's e-mail address.
static newFatalPermissionDeniedStatus( $permission)
Factory function for fatal permission-denied errors.
setNewpassword( $str, $throttle=true)
Set the password for a password reminder or new account email.
getAutomaticGroups( $recache=false)
Get the list of implicit group memberships this user has.
load( $flags=self::READ_NORMAL)
Load the user table data for this object from the source given by mFrom.
blockedBy()
If user is blocked, return the name of the user who placed the block.
getRights()
Get the permissions this user has.
matchEditToken( $val, $salt='', $request=null, $maxage=null)
Check given value against the token value stored in the session.
string $mEmailAuthenticated
const GETOPTIONS_EXCLUDE_DEFAULTS
Exclude user options that are set to their default value.
const TOKEN_LENGTH
@const int Number of characters in user_token field.
setToken( $token=false)
Set the random token (used for persistent authentication) Called from loadDefaults() among other plac...
updateNewtalk( $field, $id, $curRev=null)
Add or update the new messages flag.
static createNew( $name, $params=[])
Add a user to the database, return the user object.
static getGroupMember( $group, $username='#')
Get the localized descriptive name for a member of a group, if it exists.
addNewUserLogEntryAutoCreate()
Add an autocreate newuser log entry for this user Used by things like CentralAuth and perhaps other a...
doLogout()
Clear the user's session, and reset the instance cache.
setItemLoaded( $item)
Set that an item has been loaded.
incEditCount()
Deferred version of incEditCountImmediate()
$mLoadedItems
Array with already loaded items or true if all items have been loaded.
blockedFor()
If user is blocked, return the specified reason for the block.
static getGroupName( $group)
Get the localized descriptive name for a group, if it exists.
static listOptionKinds()
Return a list of the types of user options currently returned by User::getOptionKinds().
resetTokenFromOption( $oname)
Reset a token stored in the preferences (like the watchlist one).
static makeGroupLinkHTML( $group, $text='')
Create a link to the group in HTML, if available; else return the group name.
static getImplicitGroups()
Get a list of implicit groups TODO: Should we deprecate this? It's trivial, but we don't want to enco...
changeableGroups()
Returns an array of groups that this user can add and remove.
getNewMessageLinks()
Return the data needed to construct links for new talk page message alerts.
isAnon()
Get whether the user is anonymous.
setEmail( $str)
Set the user's e-mail address.
checkPassword( $password)
Check to see if the given clear-text password is one of the accepted passwords.
getInstanceForUpdate()
Get a new instance of this user that was loaded from the master via a locking read.
makeUpdateConditions(Database $db, array $conditions)
Builds update conditions.
const EDIT_TOKEN_SUFFIX
Global constant made accessible as class constants so that autoloader magic can be used.
static newFromActorId( $id)
Static factory method for creation from a given actor ID.
clearAllNotifications()
Resets all of the given user's page-change notification timestamps.
removeGroup( $group)
Remove the user from the given group.
Multi-datacenter aware caching interface.
The WebRequest class encapsulates getting at data passed in the URL or via a POSTed form stripping il...
The ContentHandler facility adds support for arbitrary content types on wiki pages
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
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
const SCHEMA_COMPAT_READ_NEW
const SCHEMA_COMPAT_WRITE_NEW
this hook is for auditing only $req
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
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
see documentation in includes Linker php for Linker::makeImageLink & $time
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. 'ImgAuthModifyHeaders':Executed just before a file is streamed to a user via img_auth.php, allowing headers to be modified beforehand. $title:LinkTarget object & $headers:HTTP headers(name=> value, names are case insensitive). Two headers get special handling:If-Modified-Since(value must be a valid HTTP date) and Range(must be of the form "bytes=(\d*-\d*)") will be honored when streaming the file. '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. 'LanguageGetMagic':DEPRECATED since 1.16! Use $magicWords in a file listed in $wgExtensionMessagesFiles instead. Use this to define synonyms of magic words depending of the language & $magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED! Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead. Use to define aliases of special pages names depending of the language & $specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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
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
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
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
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
namespace and then decline to actually register it file or subcat img or subcat $title
null for the local wiki Added in
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub 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
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
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
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 "<div ...>$1</div>"). - flags Integer display flags(NO_ACTION_LINK, NO_EXTRA_USER_LINKS) 'LogException':Called before an exception(or PHP error) is logged. This is meant for integration with external error aggregation services
Allows to change the fields on the form that will be generated $name
this hook is for auditing only or null if authentication failed before getting that far $username
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
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 local 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 local patches for two options in MediaWiki One reverses the order of a title before displaying the article
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
processing should stop and the error should be shown to the user * false
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account $user
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
Interface for objects which can provide a MediaWiki context on request.
Interface for database access objects.
const READ_LOCKING
Constants for object loading bitfield flags (higher => higher QoS)
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))
MediaWiki has optional support for a high distributed memory object caching system For general information on but for a larger site with heavy load