7 # Number of characters in user_token field
8 define( 'USER_TOKEN_LENGTH', 32 );
10 # Serialized record version
11 define( 'MW_USER_VERSION', 6 );
13 # Some punctuation to prevent editing from broken text-mangling proxies.
14 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
17 * Thrown by User::setPassword() on error
20 class PasswordError
extends MWException
{
25 * The User object encapsulates all of the user-specific settings (user_id,
26 * name, rights, password, email address, options, last login time). Client
27 * classes use the getXXX() functions to access these fields. These functions
28 * do all the work of determining whether the user is logged in,
29 * whether the requested option can be satisfied from cookies or
30 * whether a database query is needed. Most of the settings needed
31 * for rendering normal pages are set in the cookie to minimize use
37 * A list of default user toggles, i.e. boolean user preferences that are
38 * displayed by Special:Preferences as checkboxes. This list can be
39 * extended via the UserToggles hook or $wgContLang->getExtraUserToggles().
41 static public $mToggles = array(
51 'editsectiononrightclick',
63 'enotifwatchlistpages',
64 'enotifusertalkpages',
67 'shownumberswatching',
83 * List of member variables which are saved to the shared cache (memcached).
84 * Any operation which changes the corresponding database fields must
85 * call a cache-clearing function.
87 static $mCacheVars = array(
99 'mEmailAuthenticated',
101 'mEmailTokenExpires',
110 * Each of these should have a corresponding message of the form "right-$right"
112 static $mCoreRights = array(
152 static $mAllRights = false;
155 * The cache variable declarations
157 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
158 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
159 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
162 * Whether the cache variables have been loaded
167 * Initialisation data source if mDataLoaded==false. May be one of:
168 * defaults anonymous user initialised from class defaults
169 * name initialise from mName
170 * id initialise from mId
171 * session log in from cookies or session if possible
173 * Use the User::newFrom*() family of functions to set this.
178 * Lazy-initialised variables, invalidated with clearInstanceCache
180 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
181 $mBlockreason, $mBlock, $mEffectiveGroups;
184 * Lightweight constructor for anonymous user
185 * Use the User::newFrom* factory functions for other kinds of users
188 $this->clearInstanceCache( 'defaults' );
192 * Load the user table data for this object from the source given by mFrom
195 if ( $this->mDataLoaded
) {
198 wfProfileIn( __METHOD__
);
200 # Set it now to avoid infinite recursion in accessors
201 $this->mDataLoaded
= true;
203 switch ( $this->mFrom
) {
205 $this->loadDefaults();
208 $this->mId
= self
::idFromName( $this->mName
);
210 # Nonexistent user placeholder object
211 $this->loadDefaults( $this->mName
);
220 $this->loadFromSession();
223 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
225 wfProfileOut( __METHOD__
);
229 * Load user table data given mId
230 * @return false if the ID does not exist, true otherwise
233 function loadFromId() {
235 if ( $this->mId
== 0 ) {
236 $this->loadDefaults();
241 $key = wfMemcKey( 'user', 'id', $this->mId
);
242 $data = $wgMemc->get( $key );
243 if ( !is_array( $data ) ||
$data['mVersion'] < MW_USER_VERSION
) {
244 # Object is expired, load from DB
249 wfDebug( "Cache miss for user {$this->mId}\n" );
251 if ( !$this->loadFromDatabase() ) {
252 # Can't load from ID, user is anonymous
255 $this->saveToCache();
257 wfDebug( "Got user {$this->mId} from cache\n" );
259 foreach ( self
::$mCacheVars as $name ) {
260 $this->$name = $data[$name];
267 * Save user data to the shared cache
269 function saveToCache() {
272 if ( $this->isAnon() ) {
273 // Anonymous users are uncached
277 foreach ( self
::$mCacheVars as $name ) {
278 $data[$name] = $this->$name;
280 $data['mVersion'] = MW_USER_VERSION
;
281 $key = wfMemcKey( 'user', 'id', $this->mId
);
283 $wgMemc->set( $key, $data );
287 * Static factory method for creation from username.
289 * This is slightly less efficient than newFromId(), so use newFromId() if
290 * you have both an ID and a name handy.
292 * @param string $name Username, validated by Title:newFromText()
293 * @param mixed $validate Validate username. Takes the same parameters as
294 * User::getCanonicalName(), except that true is accepted as an alias
295 * for 'valid', for BC.
297 * @return User object, or null if the username is invalid. If the username
298 * is not present in the database, the result will be a user object with
299 * a name, zero user ID and default settings.
302 static function newFromName( $name, $validate = 'valid' ) {
303 if ( $validate === true ) {
306 $name = self
::getCanonicalName( $name, $validate );
307 if ( $name === false ) {
310 # Create unloaded user object
318 static function newFromId( $id ) {
326 * Factory method to fetch whichever user has a given email confirmation code.
327 * This code is generated when an account is created or its e-mail address
330 * If the code is invalid or has expired, returns NULL.
332 * @param string $code
336 static function newFromConfirmationCode( $code ) {
337 $dbr = wfGetDB( DB_SLAVE
);
338 $id = $dbr->selectField( 'user', 'user_id', array(
339 'user_email_token' => md5( $code ),
340 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
342 if( $id !== false ) {
343 return User
::newFromId( $id );
350 * Create a new user object using data from session or cookies. If the
351 * login credentials are invalid, the result is an anonymous user.
356 static function newFromSession() {
358 $user->mFrom
= 'session';
363 * Create a new user object from a user row.
364 * The row should have all fields from the user table in it.
366 static function newFromRow( $row ) {
368 $user->loadFromRow( $row );
373 * Get username given an id.
374 * @param integer $id Database user id
375 * @return string Nickname of a user
378 static function whoIs( $id ) {
379 $dbr = wfGetDB( DB_SLAVE
);
380 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
384 * Get the real name of a user given their identifier
386 * @param int $id Database user id
387 * @return string Real name of a user
389 static function whoIsReal( $id ) {
390 $dbr = wfGetDB( DB_SLAVE
);
391 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__
);
395 * Get database id given a user name
396 * @param string $name Nickname of a user
397 * @return integer|null Database user id (null: if non existent
400 static function idFromName( $name ) {
401 $nt = Title
::newFromText( $name );
402 if( is_null( $nt ) ) {
406 $dbr = wfGetDB( DB_SLAVE
);
407 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__
);
409 if ( $s === false ) {
417 * Does the string match an anonymous IPv4 address?
419 * This function exists for username validation, in order to reject
420 * usernames which are similar in form to IP addresses. Strings such
421 * as 300.300.300.300 will return true because it looks like an IP
422 * address, despite not being strictly valid.
424 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
425 * address because the usemod software would "cloak" anonymous IP
426 * addresses like this, if we allowed accounts like this to be created
427 * new users could get the old edits of these anonymous users.
430 * @param string $name Nickname of a user
433 static function isIP( $name ) {
434 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || User
::isIPv6($name);
435 /*return preg_match("/^
436 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
437 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
438 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
439 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
444 * Check if $name is an IPv6 IP.
446 static function isIPv6($name) {
448 * if it has any non-valid characters, it can't be a valid IPv6
451 if (preg_match("/[^:a-fA-F0-9]/", $name))
454 $parts = explode(":", $name);
455 if (count($parts) < 3)
457 foreach ($parts as $part) {
458 if (!preg_match("/^[0-9a-fA-F]{0,4}$/", $part))
465 * Is the input a valid username?
467 * Checks if the input is a valid username, we don't want an empty string,
468 * an IP address, anything that containins slashes (would mess up subpages),
469 * is longer than the maximum allowed username size or doesn't begin with
472 * @param string $name
476 static function isValidUserName( $name ) {
477 global $wgContLang, $wgMaxNameChars;
480 || User
::isIP( $name )
481 ||
strpos( $name, '/' ) !== false
482 ||
strlen( $name ) > $wgMaxNameChars
483 ||
$name != $wgContLang->ucfirst( $name ) ) {
484 wfDebugLog( 'username', __METHOD__
.
485 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
489 // Ensure that the name can't be misresolved as a different title,
490 // such as with extra namespace keys at the start.
491 $parsed = Title
::newFromText( $name );
492 if( is_null( $parsed )
493 ||
$parsed->getNamespace()
494 ||
strcmp( $name, $parsed->getPrefixedText() ) ) {
495 wfDebugLog( 'username', __METHOD__
.
496 ": '$name' invalid due to ambiguous prefixes" );
500 // Check an additional blacklist of troublemaker characters.
501 // Should these be merged into the title char list?
502 $unicodeBlacklist = '/[' .
503 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
504 '\x{00a0}' . # non-breaking space
505 '\x{2000}-\x{200f}' . # various whitespace
506 '\x{2028}-\x{202f}' . # breaks and control chars
507 '\x{3000}' . # ideographic space
508 '\x{e000}-\x{f8ff}' . # private use
510 if( preg_match( $unicodeBlacklist, $name ) ) {
511 wfDebugLog( 'username', __METHOD__
.
512 ": '$name' invalid due to blacklisted characters" );
520 * Usernames which fail to pass this function will be blocked
521 * from user login and new account registrations, but may be used
522 * internally by batch processes.
524 * If an account already exists in this form, login will be blocked
525 * by a failure to pass this function.
527 * @param string $name
530 static function isUsableName( $name ) {
531 global $wgReservedUsernames;
533 // Must be a valid username, obviously ;)
534 self
::isValidUserName( $name ) &&
536 // Certain names may be reserved for batch processes.
537 !in_array( $name, $wgReservedUsernames );
541 * Usernames which fail to pass this function will be blocked
542 * from new account registrations, but may be used internally
543 * either by batch processes or by user accounts which have
544 * already been created.
546 * Additional character blacklisting may be added here
547 * rather than in isValidUserName() to avoid disrupting
550 * @param string $name
553 static function isCreatableName( $name ) {
555 self
::isUsableName( $name ) &&
557 // Registration-time character blacklisting...
558 strpos( $name, '@' ) === false;
562 * Is the input a valid password for this user?
564 * @param string $password Desired password
567 function isValidPassword( $password ) {
568 global $wgMinimalPasswordLength, $wgContLang;
571 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
573 if( $result === false )
576 // Password needs to be long enough, and can't be the same as the username
577 return strlen( $password ) >= $wgMinimalPasswordLength
578 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName
);
582 * Does a string look like an email address?
584 * There used to be a regular expression here, it got removed because it
585 * rejected valid addresses. Actually just check if there is '@' somewhere
586 * in the given address.
588 * @todo Check for RFC 2822 compilance (bug 959)
590 * @param string $addr email address
593 public static function isValidEmailAddr( $addr ) {
595 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
599 return strpos( $addr, '@' ) !== false;
603 * Given unvalidated user input, return a canonical username, or false if
604 * the username is invalid.
605 * @param string $name
606 * @param mixed $validate Type of validation to use:
607 * false No validation
608 * 'valid' Valid for batch processes
609 * 'usable' Valid for batch processes and login
610 * 'creatable' Valid for batch processes, login and account creation
612 static function getCanonicalName( $name, $validate = 'valid' ) {
613 # Force usernames to capital
615 $name = $wgContLang->ucfirst( $name );
617 # Reject names containing '#'; these will be cleaned up
618 # with title normalisation, but then it's too late to
620 if( strpos( $name, '#' ) !== false )
623 # Clean up name according to title rules
624 $t = Title
::newFromText( $name );
625 if( is_null( $t ) ) {
629 # Reject various classes of invalid names
630 $name = $t->getText();
632 $name = $wgAuth->getCanonicalName( $t->getText() );
634 switch ( $validate ) {
638 if ( !User
::isValidUserName( $name ) ) {
643 if ( !User
::isUsableName( $name ) ) {
648 if ( !User
::isCreatableName( $name ) ) {
653 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__
);
659 * Count the number of edits of a user
661 * It should not be static and some day should be merged as proper member function / deprecated -- domas
663 * @param int $uid The user ID to check
667 static function edits( $uid ) {
668 wfProfileIn( __METHOD__
);
669 $dbr = wfGetDB( DB_SLAVE
);
670 // check if the user_editcount field has been initialized
671 $field = $dbr->selectField(
672 'user', 'user_editcount',
673 array( 'user_id' => $uid ),
677 if( $field === null ) { // it has not been initialized. do so.
678 $dbw = wfGetDB( DB_MASTER
);
679 $count = $dbr->selectField(
680 'revision', 'count(*)',
681 array( 'rev_user' => $uid ),
686 array( 'user_editcount' => $count ),
687 array( 'user_id' => $uid ),
693 wfProfileOut( __METHOD__
);
698 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
699 * @todo hash random numbers to improve security, like generateToken()
704 static function randomPassword() {
705 global $wgMinimalPasswordLength;
706 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
707 $l = strlen( $pwchars ) - 1;
709 $pwlength = max( 7, $wgMinimalPasswordLength );
710 $digit = mt_rand(0, $pwlength - 1);
712 for ( $i = 0; $i < $pwlength; $i++
) {
713 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
719 * Set cached properties to default. Note: this no longer clears
720 * uncached lazy-initialised properties. The constructor does that instead.
724 function loadDefaults( $name = false ) {
725 wfProfileIn( __METHOD__
);
727 global $wgCookiePrefix;
730 $this->mName
= $name;
731 $this->mRealName
= '';
732 $this->mPassword
= $this->mNewpassword
= '';
733 $this->mNewpassTime
= null;
735 $this->mOptions
= null; # Defer init
737 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
738 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
740 $this->mTouched
= '0'; # Allow any pages to be cached
743 $this->setToken(); # Random
744 $this->mEmailAuthenticated
= null;
745 $this->mEmailToken
= '';
746 $this->mEmailTokenExpires
= null;
747 $this->mRegistration
= wfTimestamp( TS_MW
);
748 $this->mGroups
= array();
750 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
752 wfProfileOut( __METHOD__
);
756 * Initialise php session
757 * @deprecated use wfSetupSession()
759 function SetupSession() {
760 wfDeprecated( __METHOD__
);
765 * Load user data from the session or login cookie. If there are no valid
766 * credentials, initialises the user as an anon.
767 * @return true if the user is logged in, false otherwise
769 private function loadFromSession() {
770 global $wgMemc, $wgCookiePrefix;
773 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
774 if ( $result !== null ) {
778 if ( isset( $_SESSION['wsUserID'] ) ) {
779 if ( 0 != $_SESSION['wsUserID'] ) {
780 $sId = $_SESSION['wsUserID'];
782 $this->loadDefaults();
785 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
786 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
787 $_SESSION['wsUserID'] = $sId;
789 $this->loadDefaults();
792 if ( isset( $_SESSION['wsUserName'] ) ) {
793 $sName = $_SESSION['wsUserName'];
794 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
795 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
796 $_SESSION['wsUserName'] = $sName;
798 $this->loadDefaults();
802 $passwordCorrect = FALSE;
804 if ( !$this->loadFromId() ) {
805 # Not a valid ID, loadFromId has switched the object to anon for us
809 if ( isset( $_SESSION['wsToken'] ) ) {
810 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken
;
812 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
813 $passwordCorrect = $this->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
816 # No session or persistent login cookie
817 $this->loadDefaults();
821 if ( ( $sName == $this->mName
) && $passwordCorrect ) {
822 $_SESSION['wsToken'] = $this->mToken
;
823 wfDebug( "Logged in from $from\n" );
826 # Invalid credentials
827 wfDebug( "Can't log in from $from, invalid credentials\n" );
828 $this->loadDefaults();
834 * Load user and user_group data from the database
835 * $this->mId must be set, this is how the user is identified.
837 * @return true if the user exists, false if the user is anonymous
840 function loadFromDatabase() {
842 $this->mId
= intval( $this->mId
);
844 /** Anonymous user */
846 $this->loadDefaults();
850 $dbr = wfGetDB( DB_MASTER
);
851 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId
), __METHOD__
);
853 if ( $s !== false ) {
854 # Initialise user table data
855 $this->loadFromRow( $s );
856 $this->mGroups
= null; // deferred
857 $this->getEditCount(); // revalidation for nulls
862 $this->loadDefaults();
868 * Initialise the user object from a row from the user table
870 function loadFromRow( $row ) {
871 $this->mDataLoaded
= true;
873 if ( isset( $row->user_id
) ) {
874 $this->mId
= $row->user_id
;
876 $this->mName
= $row->user_name
;
877 $this->mRealName
= $row->user_real_name
;
878 $this->mPassword
= $row->user_password
;
879 $this->mNewpassword
= $row->user_newpassword
;
880 $this->mNewpassTime
= wfTimestampOrNull( TS_MW
, $row->user_newpass_time
);
881 $this->mEmail
= $row->user_email
;
882 $this->decodeOptions( $row->user_options
);
883 $this->mTouched
= wfTimestamp(TS_MW
,$row->user_touched
);
884 $this->mToken
= $row->user_token
;
885 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $row->user_email_authenticated
);
886 $this->mEmailToken
= $row->user_email_token
;
887 $this->mEmailTokenExpires
= wfTimestampOrNull( TS_MW
, $row->user_email_token_expires
);
888 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $row->user_registration
);
889 $this->mEditCount
= $row->user_editcount
;
893 * Load the groups from the database if they aren't already loaded
896 function loadGroups() {
897 if ( is_null( $this->mGroups
) ) {
898 $dbr = wfGetDB( DB_MASTER
);
899 $res = $dbr->select( 'user_groups',
901 array( 'ug_user' => $this->mId
),
903 $this->mGroups
= array();
904 while( $row = $dbr->fetchObject( $res ) ) {
905 $this->mGroups
[] = $row->ug_group
;
911 * Clear various cached data stored in this object.
912 * @param string $reloadFrom Reload user and user_groups table data from a
913 * given source. May be "name", "id", "defaults", "session" or false for
916 function clearInstanceCache( $reloadFrom = false ) {
917 $this->mNewtalk
= -1;
918 $this->mDatePreference
= null;
919 $this->mBlockedby
= -1; # Unset
920 $this->mHash
= false;
922 $this->mRights
= null;
923 $this->mEffectiveGroups
= null;
926 $this->mDataLoaded
= false;
927 $this->mFrom
= $reloadFrom;
932 * Combine the language default options with any site-specific options
933 * and add the default language variants.
934 * Not really private cause it's called by Language class
939 static function getDefaultOptions() {
940 global $wgNamespacesToBeSearchedDefault;
942 * Site defaults will override the global/language defaults
944 global $wgDefaultUserOptions, $wgContLang;
945 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptionOverrides();
948 * default language setting
950 $variant = $wgContLang->getPreferredVariant( false );
951 $defOpt['variant'] = $variant;
952 $defOpt['language'] = $variant;
954 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
955 $defOpt['searchNs'.$nsnum] = $val;
961 * Get a given default option value.
968 function getDefaultOption( $opt ) {
969 $defOpts = User
::getDefaultOptions();
970 if( isset( $defOpts[$opt] ) ) {
971 return $defOpts[$opt];
978 * Get a list of user toggle names
981 static function getToggles() {
983 $extraToggles = array();
984 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
985 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
990 * Get blocking information
992 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
993 * non-critical checks are done against slaves. Check when actually saving should be done against
996 function getBlockedStatus( $bFromSlave = true ) {
997 global $wgEnableSorbs, $wgProxyWhitelist;
999 if ( -1 != $this->mBlockedby
) {
1000 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1004 wfProfileIn( __METHOD__
);
1005 wfDebug( __METHOD__
.": checking...\n" );
1007 // Initialize data...
1008 // Otherwise something ends up stomping on $this->mBlockedby when
1009 // things get lazy-loaded later, causing false positive block hits
1010 // due to -1 !== 0. Probably session-related... Nothing should be
1011 // overwriting mBlockedby, surely?
1014 $this->mBlockedby
= 0;
1015 $this->mHideName
= 0;
1018 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1019 # Exempt from all types of IP-block
1024 $this->mBlock
= new Block();
1025 $this->mBlock
->fromMaster( !$bFromSlave );
1026 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
1027 wfDebug( __METHOD__
.": Found block.\n" );
1028 $this->mBlockedby
= $this->mBlock
->mBy
;
1029 $this->mBlockreason
= $this->mBlock
->mReason
;
1030 $this->mHideName
= $this->mBlock
->mHideName
;
1031 if ( $this->isLoggedIn() ) {
1032 $this->spreadBlock();
1035 $this->mBlock
= null;
1036 wfDebug( __METHOD__
.": No block.\n" );
1040 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1042 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1043 $this->mBlockedby
= wfMsg( 'proxyblocker' );
1044 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
1048 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
1049 if ( $this->inSorbsBlacklist( $ip ) ) {
1050 $this->mBlockedby
= wfMsg( 'sorbs' );
1051 $this->mBlockreason
= wfMsg( 'sorbsreason' );
1057 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1059 wfProfileOut( __METHOD__
);
1062 function inSorbsBlacklist( $ip ) {
1063 global $wgEnableSorbs, $wgSorbsUrl;
1065 return $wgEnableSorbs &&
1066 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1069 function inDnsBlacklist( $ip, $base ) {
1070 wfProfileIn( __METHOD__
);
1076 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
1078 for ( $i=4; $i>=1; $i-- ) {
1079 $host .= $m[$i] . '.';
1084 $ipList = gethostbynamel( $host );
1087 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1090 wfDebug( "Requested $host, not found in $base.\n" );
1094 wfProfileOut( __METHOD__
);
1099 * Is this user subject to rate limiting?
1103 public function isPingLimitable() {
1104 global $wgRateLimitsExcludedGroups;
1105 return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) == array();
1109 * Primitive rate limits: enforce maximum actions per time period
1110 * to put a brake on flooding.
1112 * Note: when using a shared cache like memcached, IP-address
1113 * last-hit counters will be shared across wikis.
1115 * @return bool true if a rate limiter was tripped
1118 function pingLimiter( $action='edit' ) {
1120 # Call the 'PingLimiter' hook
1122 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1126 global $wgRateLimits;
1127 if( !isset( $wgRateLimits[$action] ) ) {
1131 # Some groups shouldn't trigger the ping limiter, ever
1132 if( !$this->isPingLimitable() )
1135 global $wgMemc, $wgRateLimitLog;
1136 wfProfileIn( __METHOD__
);
1138 $limits = $wgRateLimits[$action];
1140 $id = $this->getId();
1144 if( isset( $limits['anon'] ) && $id == 0 ) {
1145 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1148 if( isset( $limits['user'] ) && $id != 0 ) {
1149 $userLimit = $limits['user'];
1151 if( $this->isNewbie() ) {
1152 if( isset( $limits['newbie'] ) && $id != 0 ) {
1153 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1155 if( isset( $limits['ip'] ) ) {
1156 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1159 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1160 $subnet = $matches[1];
1161 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1164 // Check for group-specific permissions
1165 // If more than one group applies, use the group with the highest limit
1166 foreach ( $this->getGroups() as $group ) {
1167 if ( isset( $limits[$group] ) ) {
1168 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1169 $userLimit = $limits[$group];
1173 // Set the user limit key
1174 if ( $userLimit !== false ) {
1175 wfDebug( __METHOD__
.": effective user limit: $userLimit\n" );
1176 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1180 foreach( $keys as $key => $limit ) {
1181 list( $max, $period ) = $limit;
1182 $summary = "(limit $max in {$period}s)";
1183 $count = $wgMemc->get( $key );
1185 if( $count > $max ) {
1186 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1187 if( $wgRateLimitLog ) {
1188 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1192 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1195 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1196 $wgMemc->add( $key, 1, intval( $period ) );
1198 $wgMemc->incr( $key );
1201 wfProfileOut( __METHOD__
);
1206 * Check if user is blocked
1207 * @return bool True if blocked, false otherwise
1209 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1210 wfDebug( "User::isBlocked: enter\n" );
1211 $this->getBlockedStatus( $bFromSlave );
1212 return $this->mBlockedby
!== 0;
1216 * Check if user is blocked from editing a particular article
1218 function isBlockedFrom( $title, $bFromSlave = false ) {
1219 global $wgBlockAllowsUTEdit;
1220 wfProfileIn( __METHOD__
);
1221 wfDebug( __METHOD__
.": enter\n" );
1223 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1224 $blocked = $this->isBlocked( $bFromSlave );
1225 # If a user's name is suppressed, they cannot make edits anywhere
1226 if ( !$this->mHideName
&& $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1227 $title->getNamespace() == NS_USER_TALK
) {
1229 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1231 wfProfileOut( __METHOD__
);
1236 * Get name of blocker
1237 * @return string name of blocker
1239 function blockedBy() {
1240 $this->getBlockedStatus();
1241 return $this->mBlockedby
;
1245 * Get blocking reason
1246 * @return string Blocking reason
1248 function blockedFor() {
1249 $this->getBlockedStatus();
1250 return $this->mBlockreason
;
1254 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1257 if( $this->mId
=== null and $this->mName
!== null
1258 and User
::isIP( $this->mName
) ) {
1259 // Special case, we know the user is anonymous
1261 } elseif( $this->mId
=== null ) {
1262 // Don't load if this was initialized from an ID
1269 * Set the user and reload all fields according to that ID
1271 function setId( $v ) {
1273 $this->clearInstanceCache( 'id' );
1277 * Get the user name, or the IP for anons
1279 function getName() {
1280 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1281 # Special case optimisation
1282 return $this->mName
;
1285 if ( $this->mName
=== false ) {
1287 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1289 return $this->mName
;
1294 * Set the user name.
1296 * This does not reload fields from the database according to the given
1297 * name. Rather, it is used to create a temporary "nonexistent user" for
1298 * later addition to the database. It can also be used to set the IP
1299 * address for an anonymous user to something other than the current
1302 * User::newFromName() has rougly the same function, when the named user
1305 function setName( $str ) {
1307 $this->mName
= $str;
1311 * Return the title dbkey form of the name, for eg user pages.
1315 function getTitleKey() {
1316 return str_replace( ' ', '_', $this->getName() );
1319 function getNewtalk() {
1322 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1323 if( $this->mNewtalk
=== -1 ) {
1324 $this->mNewtalk
= false; # reset talk page status
1326 # Check memcached separately for anons, who have no
1327 # entire User object stored in there.
1330 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1331 $newtalk = $wgMemc->get( $key );
1332 if( strval( $newtalk ) !== '' ) {
1333 $this->mNewtalk
= (bool)$newtalk;
1335 // Since we are caching this, make sure it is up to date by getting it
1337 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1338 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1341 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1345 return (bool)$this->mNewtalk
;
1349 * Return the talk page(s) this user has new messages on.
1351 function getNewMessageLinks() {
1353 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1356 if (!$this->getNewtalk())
1358 $up = $this->getUserPage();
1359 $utp = $up->getTalkPage();
1360 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1365 * Perform a user_newtalk check, uncached.
1366 * Use getNewtalk for a cached check.
1368 * @param string $field
1370 * @param bool $fromMaster True to fetch from the master, false for a slave
1374 function checkNewtalk( $field, $id, $fromMaster = false ) {
1375 if ( $fromMaster ) {
1376 $db = wfGetDB( DB_MASTER
);
1378 $db = wfGetDB( DB_SLAVE
);
1380 $ok = $db->selectField( 'user_newtalk', $field,
1381 array( $field => $id ), __METHOD__
);
1382 return $ok !== false;
1387 * @param string $field
1391 function updateNewtalk( $field, $id ) {
1392 $dbw = wfGetDB( DB_MASTER
);
1393 $dbw->insert( 'user_newtalk',
1394 array( $field => $id ),
1397 if ( $dbw->affectedRows() ) {
1398 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1401 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1407 * Clear the new messages flag for the given user
1408 * @param string $field
1412 function deleteNewtalk( $field, $id ) {
1413 $dbw = wfGetDB( DB_MASTER
);
1414 $dbw->delete( 'user_newtalk',
1415 array( $field => $id ),
1417 if ( $dbw->affectedRows() ) {
1418 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1421 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1427 * Update the 'You have new messages!' status.
1430 function setNewtalk( $val ) {
1431 if( wfReadOnly() ) {
1436 $this->mNewtalk
= $val;
1438 if( $this->isAnon() ) {
1440 $id = $this->getName();
1443 $id = $this->getId();
1448 $changed = $this->updateNewtalk( $field, $id );
1450 $changed = $this->deleteNewtalk( $field, $id );
1453 if( $this->isAnon() ) {
1454 // Anons have a separate memcached space, since
1455 // user records aren't kept for them.
1456 $key = wfMemcKey( 'newtalk', 'ip', $id );
1457 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1460 $this->invalidateCache();
1465 * Generate a current or new-future timestamp to be stored in the
1466 * user_touched field when we update things.
1468 private static function newTouchedTimestamp() {
1469 global $wgClockSkewFudge;
1470 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1474 * Clear user data from memcached.
1475 * Use after applying fun updates to the database; caller's
1476 * responsibility to update user_touched if appropriate.
1478 * Called implicitly from invalidateCache() and saveSettings().
1480 private function clearSharedCache() {
1483 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1488 * Immediately touch the user data cache for this account.
1489 * Updates user_touched field, and removes account data from memcached
1490 * for reload on the next hit.
1492 function invalidateCache() {
1495 $this->mTouched
= self
::newTouchedTimestamp();
1497 $dbw = wfGetDB( DB_MASTER
);
1498 $dbw->update( 'user',
1499 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1500 array( 'user_id' => $this->mId
),
1503 $this->clearSharedCache();
1507 function validateCache( $timestamp ) {
1509 return ($timestamp >= $this->mTouched
);
1513 * Encrypt a password.
1514 * It can eventually salt a password.
1515 * @see User::addSalt()
1516 * @param string $p clear Password.
1517 * @return string Encrypted password.
1519 function encryptPassword( $p ) {
1521 return wfEncryptPassword( $this->mId
, $p );
1525 * Set the password and reset the random token
1526 * Calls through to authentication plugin if necessary;
1527 * will have no effect if the auth plugin refuses to
1528 * pass the change through or if the legal password
1531 * As a special case, setting the password to null
1532 * wipes it, so the account cannot be logged in until
1533 * a new password is set, for instance via e-mail.
1535 * @param string $str
1536 * @throws PasswordError on failure
1538 function setPassword( $str ) {
1541 if( $str !== null ) {
1542 if( !$wgAuth->allowPasswordChange() ) {
1543 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1546 if( !$this->isValidPassword( $str ) ) {
1547 global $wgMinimalPasswordLength;
1548 throw new PasswordError( wfMsg( 'passwordtooshort',
1549 $wgMinimalPasswordLength ) );
1553 if( !$wgAuth->setPassword( $this, $str ) ) {
1554 throw new PasswordError( wfMsg( 'externaldberror' ) );
1557 $this->setInternalPassword( $str );
1563 * Set the password and reset the random token no matter
1566 * @param string $str
1568 function setInternalPassword( $str ) {
1572 if( $str === null ) {
1573 // Save an invalid hash...
1574 $this->mPassword
= '';
1576 $this->mPassword
= $this->encryptPassword( $str );
1578 $this->mNewpassword
= '';
1579 $this->mNewpassTime
= null;
1582 function getToken() {
1584 return $this->mToken
;
1588 * Set the random token (used for persistent authentication)
1589 * Called from loadDefaults() among other places.
1592 function setToken( $token = false ) {
1593 global $wgSecretKey, $wgProxyKey;
1596 if ( $wgSecretKey ) {
1597 $key = $wgSecretKey;
1598 } elseif ( $wgProxyKey ) {
1603 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1605 $this->mToken
= $token;
1609 function setCookiePassword( $str ) {
1611 $this->mCookiePassword
= md5( $str );
1615 * Set the password for a password reminder or new account email
1616 * Sets the user_newpass_time field if $throttle is true
1618 function setNewpassword( $str, $throttle = true ) {
1620 $this->mNewpassword
= $this->encryptPassword( $str );
1622 $this->mNewpassTime
= wfTimestampNow();
1627 * Returns true if a password reminder email has already been sent within
1628 * the last $wgPasswordReminderResendTime hours
1630 function isPasswordReminderThrottled() {
1631 global $wgPasswordReminderResendTime;
1633 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1636 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1637 return time() < $expiry;
1640 function getEmail() {
1642 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1643 return $this->mEmail
;
1646 function getEmailAuthenticationTimestamp() {
1648 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1649 return $this->mEmailAuthenticated
;
1652 function setEmail( $str ) {
1654 $this->mEmail
= $str;
1655 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1658 function getRealName() {
1660 return $this->mRealName
;
1663 function setRealName( $str ) {
1665 $this->mRealName
= $str;
1669 * @param string $oname The option to check
1670 * @param string $defaultOverride A default value returned if the option does not exist
1673 function getOption( $oname, $defaultOverride = '' ) {
1676 if ( is_null( $this->mOptions
) ) {
1677 if($defaultOverride != '') {
1678 return $defaultOverride;
1680 $this->mOptions
= User
::getDefaultOptions();
1683 if ( array_key_exists( $oname, $this->mOptions
) ) {
1684 return trim( $this->mOptions
[$oname] );
1686 return $defaultOverride;
1691 * Get the user's date preference, including some important migration for
1694 function getDatePreference() {
1695 if ( is_null( $this->mDatePreference
) ) {
1697 $value = $this->getOption( 'date' );
1698 $map = $wgLang->getDatePreferenceMigrationMap();
1699 if ( isset( $map[$value] ) ) {
1700 $value = $map[$value];
1702 $this->mDatePreference
= $value;
1704 return $this->mDatePreference
;
1708 * @param string $oname The option to check
1709 * @return bool False if the option is not selected, true if it is
1711 function getBoolOption( $oname ) {
1712 return (bool)$this->getOption( $oname );
1716 * Get an option as an integer value from the source string.
1717 * @param string $oname The option to check
1718 * @param int $default Optional value to return if option is unset/blank.
1721 function getIntOption( $oname, $default=0 ) {
1722 $val = $this->getOption( $oname );
1726 return intval( $val );
1729 function setOption( $oname, $val ) {
1731 if ( is_null( $this->mOptions
) ) {
1732 $this->mOptions
= User
::getDefaultOptions();
1734 if ( $oname == 'skin' ) {
1735 # Clear cached skin, so the new one displays immediately in Special:Preferences
1736 unset( $this->mSkin
);
1738 // Filter out any newlines that may have passed through input validation.
1739 // Newlines are used to separate items in the options blob.
1741 $val = str_replace( "\r\n", "\n", $val );
1742 $val = str_replace( "\r", "\n", $val );
1743 $val = str_replace( "\n", " ", $val );
1745 // Explicitly NULL values should refer to defaults
1746 global $wgDefaultUserOptions;
1747 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1748 $val = $wgDefaultUserOptions[$oname];
1750 $this->mOptions
[$oname] = $val;
1753 function getRights() {
1754 if ( is_null( $this->mRights
) ) {
1755 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1756 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1757 // Force reindexation of rights when a hook has unset one of them
1758 $this->mRights
= array_values( $this->mRights
);
1760 return $this->mRights
;
1764 * Get the list of explicit group memberships this user has.
1765 * The implicit * and user groups are not included.
1766 * @return array of strings
1768 function getGroups() {
1770 return $this->mGroups
;
1774 * Get the list of implicit group memberships this user has.
1775 * This includes all explicit groups, plus 'user' if logged in,
1776 * '*' for all accounts and autopromoted groups
1777 * @param boolean $recache Don't use the cache
1778 * @return array of strings
1780 function getEffectiveGroups( $recache = false ) {
1781 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1782 $this->mEffectiveGroups
= $this->getGroups();
1783 $this->mEffectiveGroups
[] = '*';
1784 if( $this->getId() ) {
1785 $this->mEffectiveGroups
[] = 'user';
1787 $this->mEffectiveGroups
= array_unique( array_merge(
1788 $this->mEffectiveGroups
,
1789 Autopromote
::getAutopromoteGroups( $this )
1792 # Hook for additional groups
1793 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1796 return $this->mEffectiveGroups
;
1799 /* Return the edit count for the user. This is where User::edits should have been */
1800 function getEditCount() {
1802 if ( !isset( $this->mEditCount
) ) {
1803 /* Populate the count, if it has not been populated yet */
1804 $this->mEditCount
= User
::edits($this->mId
);
1806 return $this->mEditCount
;
1814 * Add the user to the given group.
1815 * This takes immediate effect.
1816 * @param string $group
1818 function addGroup( $group ) {
1819 $dbw = wfGetDB( DB_MASTER
);
1820 if( $this->getId() ) {
1821 $dbw->insert( 'user_groups',
1823 'ug_user' => $this->getID(),
1824 'ug_group' => $group,
1827 array( 'IGNORE' ) );
1830 $this->loadGroups();
1831 $this->mGroups
[] = $group;
1832 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1834 $this->invalidateCache();
1838 * Remove the user from the given group.
1839 * This takes immediate effect.
1840 * @param string $group
1842 function removeGroup( $group ) {
1844 $dbw = wfGetDB( DB_MASTER
);
1845 $dbw->delete( 'user_groups',
1847 'ug_user' => $this->getID(),
1848 'ug_group' => $group,
1850 'User::removeGroup' );
1852 $this->loadGroups();
1853 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1854 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1856 $this->invalidateCache();
1861 * A more legible check for non-anonymousness.
1862 * Returns true if the user is not an anonymous visitor.
1866 function isLoggedIn() {
1867 return $this->getID() != 0;
1871 * A more legible check for anonymousness.
1872 * Returns true if the user is an anonymous visitor.
1877 return !$this->isLoggedIn();
1881 * Whether the user is a bot
1885 wfDeprecated( __METHOD__
);
1886 return $this->isAllowed( 'bot' );
1890 * Check if user is allowed to access a feature / make an action
1891 * @param string $action Action to be checked
1892 * @return boolean True: action is allowed, False: action should not be allowed
1894 function isAllowed($action='') {
1895 if ( $action === '' )
1896 // In the spirit of DWIM
1899 return in_array( $action, $this->getRights() );
1903 * Check whether to enable recent changes patrol features for this user
1906 public function useRCPatrol() {
1907 global $wgUseRCPatrol;
1908 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
1912 * Check whether to enable recent changes patrol features for this user
1915 public function useNPPatrol() {
1916 global $wgUseRCPatrol, $wgUseNPPatrol;
1917 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
1921 * Load a skin if it doesn't exist or return it
1922 * @todo FIXME : need to check the old failback system [AV]
1924 function &getSkin() {
1926 if ( ! isset( $this->mSkin
) ) {
1927 wfProfileIn( __METHOD__
);
1930 $userSkin = $this->getOption( 'skin' );
1931 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1933 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1934 wfProfileOut( __METHOD__
);
1936 return $this->mSkin
;
1940 * @param string $title Article title to look at
1944 * Check watched status of an article
1945 * @return bool True if article is watched
1947 function isWatched( $title ) {
1948 $wl = WatchedItem
::fromUserTitle( $this, $title );
1949 return $wl->isWatched();
1955 function addWatch( $title ) {
1956 $wl = WatchedItem
::fromUserTitle( $this, $title );
1958 $this->invalidateCache();
1962 * Stop watching an article
1964 function removeWatch( $title ) {
1965 $wl = WatchedItem
::fromUserTitle( $this, $title );
1967 $this->invalidateCache();
1971 * Clear the user's notification timestamp for the given title.
1972 * If e-notif e-mails are on, they will receive notification mails on
1973 * the next change of the page if it's watched etc.
1975 function clearNotification( &$title ) {
1976 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
1978 # Do nothing if the database is locked to writes
1979 if( wfReadOnly() ) {
1983 if ($title->getNamespace() == NS_USER_TALK
&&
1984 $title->getText() == $this->getName() ) {
1985 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1987 $this->setNewtalk( false );
1990 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
1994 if( $this->isAnon() ) {
1995 // Nothing else to do...
1999 // Only update the timestamp if the page is being watched.
2000 // The query to find out if it is watched is cached both in memcached and per-invocation,
2001 // and when it does have to be executed, it can be on a slave
2002 // If this is the user's newtalk page, we always update the timestamp
2003 if ($title->getNamespace() == NS_USER_TALK
&&
2004 $title->getText() == $wgUser->getName())
2007 } elseif ( $this->getId() == $wgUser->getId() ) {
2008 $watched = $title->userIsWatching();
2013 // If the page is watched by the user (or may be watched), update the timestamp on any
2014 // any matching rows
2016 $dbw = wfGetDB( DB_MASTER
);
2017 $dbw->update( 'watchlist',
2019 'wl_notificationtimestamp' => NULL
2020 ), array( /* WHERE */
2021 'wl_title' => $title->getDBkey(),
2022 'wl_namespace' => $title->getNamespace(),
2023 'wl_user' => $this->getID()
2024 ), 'User::clearLastVisited'
2032 * Resets all of the given user's page-change notification timestamps.
2033 * If e-notif e-mails are on, they will receive notification mails on
2034 * the next change of any watched page.
2036 * @param int $currentUser user ID number
2039 function clearAllNotifications( $currentUser ) {
2040 global $wgUseEnotif, $wgShowUpdatedMarker;
2041 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2042 $this->setNewtalk( false );
2045 if( $currentUser != 0 ) {
2046 $dbw = wfGetDB( DB_MASTER
);
2047 $dbw->update( 'watchlist',
2049 'wl_notificationtimestamp' => NULL
2050 ), array( /* WHERE */
2051 'wl_user' => $currentUser
2054 # We also need to clear here the "you have new message" notification for the own user_talk page
2055 # This is cleared one page view later in Article::viewUpdates();
2061 * @return string Encoding options
2063 function encodeOptions() {
2065 if ( is_null( $this->mOptions
) ) {
2066 $this->mOptions
= User
::getDefaultOptions();
2069 foreach ( $this->mOptions
as $oname => $oval ) {
2070 array_push( $a, $oname.'='.$oval );
2072 $s = implode( "\n", $a );
2079 function decodeOptions( $str ) {
2080 $this->mOptions
= array();
2081 $a = explode( "\n", $str );
2082 foreach ( $a as $s ) {
2084 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2085 $this->mOptions
[$m[1]] = $m[2];
2090 protected function setCookie( $name, $value, $exp=0 ) {
2091 global $wgCookiePrefix,$wgCookieDomain,$wgCookieSecure,$wgCookieExpiration, $wgCookieHttpOnly;
2093 $exp = time() +
$wgCookieExpiration;
2095 $httpOnlySafe = wfHttpOnlySafe();
2096 wfDebugLog( 'cookie',
2097 'setcookie: "' . implode( '", "',
2099 $wgCookiePrefix . $name,
2105 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2106 if( $httpOnlySafe && isset( $wgCookieHttpOnly ) ) {
2107 setcookie( $wgCookiePrefix . $name,
2113 $wgCookieHttpOnly );
2115 // setcookie() fails on PHP 5.1 if you give it future-compat paramters.
2117 setcookie( $wgCookiePrefix . $name,
2126 protected function clearCookie( $name ) {
2127 $this->setCookie( $name, '', time() - 86400 );
2130 function setCookies() {
2132 if ( 0 == $this->mId
) return;
2134 'wsUserID' => $this->mId
,
2135 'wsToken' => $this->mToken
,
2136 'wsUserName' => $this->getName()
2139 'UserID' => $this->mId
,
2140 'UserName' => $this->getName(),
2142 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2143 $cookies['Token'] = $this->mToken
;
2145 $cookies['Token'] = false;
2148 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2149 $_SESSION = $session +
$_SESSION;
2150 foreach ( $cookies as $name => $value ) {
2151 if ( $value === false ) {
2152 $this->clearCookie( $name );
2154 $this->setCookie( $name, $value );
2164 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2170 * Really logout user
2171 * Clears the cookies and session, resets the instance cache
2173 function doLogout() {
2174 $this->clearInstanceCache( 'defaults' );
2176 $_SESSION['wsUserID'] = 0;
2178 $this->clearCookie( 'UserID' );
2179 $this->clearCookie( 'Token' );
2181 # Remember when user logged out, to prevent seeing cached pages
2182 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2186 * Save object settings into database
2187 * @todo Only rarely do all these fields need to be set!
2189 function saveSettings() {
2191 if ( wfReadOnly() ) { return; }
2192 if ( 0 == $this->mId
) { return; }
2194 $this->mTouched
= self
::newTouchedTimestamp();
2196 $dbw = wfGetDB( DB_MASTER
);
2197 $dbw->update( 'user',
2199 'user_name' => $this->mName
,
2200 'user_password' => $this->mPassword
,
2201 'user_newpassword' => $this->mNewpassword
,
2202 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2203 'user_real_name' => $this->mRealName
,
2204 'user_email' => $this->mEmail
,
2205 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2206 'user_options' => $this->encodeOptions(),
2207 'user_touched' => $dbw->timestamp($this->mTouched
),
2208 'user_token' => $this->mToken
,
2209 'user_email_token' => $this->mEmailToken
,
2210 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2211 ), array( /* WHERE */
2212 'user_id' => $this->mId
2215 wfRunHooks( 'UserSaveSettings', array( $this ) );
2216 $this->clearSharedCache();
2220 * Checks if a user with the given name exists, returns the ID.
2222 function idForName() {
2223 $s = trim( $this->getName() );
2224 if ( $s === '' ) return 0;
2226 $dbr = wfGetDB( DB_SLAVE
);
2227 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2228 if ( $id === false ) {
2235 * Add a user to the database, return the user object
2237 * @param string $name The user's name
2238 * @param array $params Associative array of non-default parameters to save to the database:
2239 * password The user's password. Password logins will be disabled if this is omitted.
2240 * newpassword A temporary password mailed to the user
2241 * email The user's email address
2242 * email_authenticated The email authentication timestamp
2243 * real_name The user's real name
2244 * options An associative array of non-default options
2245 * token Random authentication token. Do not set.
2246 * registration Registration timestamp. Do not set.
2248 * @return User object, or null if the username already exists
2250 static function createNew( $name, $params = array() ) {
2253 if ( isset( $params['options'] ) ) {
2254 $user->mOptions
= $params['options'] +
$user->mOptions
;
2255 unset( $params['options'] );
2257 $dbw = wfGetDB( DB_MASTER
);
2258 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2260 'user_id' => $seqVal,
2261 'user_name' => $name,
2262 'user_password' => $user->mPassword
,
2263 'user_newpassword' => $user->mNewpassword
,
2264 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2265 'user_email' => $user->mEmail
,
2266 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2267 'user_real_name' => $user->mRealName
,
2268 'user_options' => $user->encodeOptions(),
2269 'user_token' => $user->mToken
,
2270 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2271 'user_editcount' => 0,
2273 foreach ( $params as $name => $value ) {
2274 $fields["user_$name"] = $value;
2276 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2277 if ( $dbw->affectedRows() ) {
2278 $newUser = User
::newFromId( $dbw->insertId() );
2286 * Add an existing user object to the database
2288 function addToDatabase() {
2290 $dbw = wfGetDB( DB_MASTER
);
2291 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2292 $dbw->insert( 'user',
2294 'user_id' => $seqVal,
2295 'user_name' => $this->mName
,
2296 'user_password' => $this->mPassword
,
2297 'user_newpassword' => $this->mNewpassword
,
2298 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2299 'user_email' => $this->mEmail
,
2300 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2301 'user_real_name' => $this->mRealName
,
2302 'user_options' => $this->encodeOptions(),
2303 'user_token' => $this->mToken
,
2304 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2305 'user_editcount' => 0,
2308 $this->mId
= $dbw->insertId();
2310 # Clear instance cache other than user table data, which is already accurate
2311 $this->clearInstanceCache();
2315 * If the (non-anonymous) user is blocked, this function will block any IP address
2316 * that they successfully log on from.
2318 function spreadBlock() {
2319 wfDebug( __METHOD__
."()\n" );
2321 if ( $this->mId
== 0 ) {
2325 $userblock = Block
::newFromDB( '', $this->mId
);
2326 if ( !$userblock ) {
2330 $userblock->doAutoblock( wfGetIp() );
2335 * Generate a string which will be different for any combination of
2336 * user options which would produce different parser output.
2337 * This will be used as part of the hash key for the parser cache,
2338 * so users will the same options can share the same cached data
2341 * Extensions which require it should install 'PageRenderingHash' hook,
2342 * which will give them a chance to modify this key based on their own
2347 function getPageRenderingHash() {
2348 global $wgContLang, $wgUseDynamicDates, $wgLang;
2350 return $this->mHash
;
2353 // stubthreshold is only included below for completeness,
2354 // it will always be 0 when this function is called by parsercache.
2356 $confstr = $this->getOption( 'math' );
2357 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2358 if ( $wgUseDynamicDates ) {
2359 $confstr .= '!' . $this->getDatePreference();
2361 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2362 $confstr .= '!' . $wgLang->getCode();
2363 $confstr .= '!' . $this->getOption( 'thumbsize' );
2364 // add in language specific options, if any
2365 $extra = $wgContLang->getExtraHashOptions();
2368 // Give a chance for extensions to modify the hash, if they have
2369 // extra options or other effects on the parser cache.
2370 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2372 // Make it a valid memcached key fragment
2373 $confstr = str_replace( ' ', '_', $confstr );
2374 $this->mHash
= $confstr;
2378 function isBlockedFromCreateAccount() {
2379 $this->getBlockedStatus();
2380 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2384 * Determine if the user is blocked from using Special:Emailuser.
2389 function isBlockedFromEmailuser() {
2390 $this->getBlockedStatus();
2391 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2394 function isAllowedToCreateAccount() {
2395 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2401 function setLoaded( $loaded ) {
2402 wfDeprecated( __METHOD__
);
2406 * Get this user's personal page title.
2411 function getUserPage() {
2412 return Title
::makeTitle( NS_USER
, $this->getName() );
2416 * Get this user's talk page title.
2421 function getTalkPage() {
2422 $title = $this->getUserPage();
2423 return $title->getTalkPage();
2429 function getMaxID() {
2430 static $res; // cache
2432 if ( isset( $res ) )
2435 $dbr = wfGetDB( DB_SLAVE
);
2436 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2441 * Determine whether the user is a newbie. Newbies are either
2442 * anonymous IPs, or the most recently created accounts.
2443 * @return bool True if it is a newbie.
2445 function isNewbie() {
2446 return !$this->isAllowed( 'autoconfirmed' );
2450 * Is the user active? We check to see if they've made at least
2451 * X number of edits in the last Y days.
2453 * @return bool true if the user is active, false if not
2455 public function isActiveEditor() {
2456 global $wgActiveUserEditCount, $wgActiveUserDays;
2457 $dbr = wfGetDB( DB_SLAVE
);
2459 // Stolen without shame from RC
2460 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2461 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
2462 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2464 $res = $dbr->select( 'revision', '1',
2465 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2467 array('LIMIT' => $wgActiveUserEditCount ) );
2469 $count = $dbr->numRows($res);
2470 $dbr->freeResult($res);
2472 return $count == $wgActiveUserEditCount;
2476 * Check to see if the given clear-text password is one of the accepted passwords
2477 * @param string $password User password.
2478 * @return bool True if the given password is correct otherwise False.
2480 function checkPassword( $password ) {
2484 // Even though we stop people from creating passwords that
2485 // are shorter than this, doesn't mean people wont be able
2486 // to. Certain authentication plugins do NOT want to save
2487 // domain passwords in a mysql database, so we should
2488 // check this (incase $wgAuth->strict() is false).
2489 if( !$this->isValidPassword( $password ) ) {
2493 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2495 } elseif( $wgAuth->strict() ) {
2496 /* Auth plugin doesn't allow local authentication */
2498 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2499 /* Auth plugin doesn't allow local authentication for this user name */
2502 $ep = $this->encryptPassword( $password );
2503 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
2505 } elseif ( function_exists( 'iconv' ) ) {
2506 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2507 # Check for this with iconv
2508 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2509 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
2517 * Check if the given clear-text password matches the temporary password
2518 * sent by e-mail for password reset operations.
2521 function checkTemporaryPassword( $plaintext ) {
2522 $hash = $this->encryptPassword( $plaintext );
2523 return $hash === $this->mNewpassword
;
2527 * Initialize (if necessary) and return a session token value
2528 * which can be used in edit forms to show that the user's
2529 * login credentials aren't being hijacked with a foreign form
2532 * @param mixed $salt - Optional function-specific data for hash.
2533 * Use a string or an array of strings.
2537 function editToken( $salt = '' ) {
2538 if ( $this->isAnon() ) {
2539 return EDIT_TOKEN_SUFFIX
;
2541 if( !isset( $_SESSION['wsEditToken'] ) ) {
2542 $token = $this->generateToken();
2543 $_SESSION['wsEditToken'] = $token;
2545 $token = $_SESSION['wsEditToken'];
2547 if( is_array( $salt ) ) {
2548 $salt = implode( '|', $salt );
2550 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2555 * Generate a hex-y looking random token for various uses.
2556 * Could be made more cryptographically sure if someone cares.
2559 function generateToken( $salt = '' ) {
2560 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2561 return md5( $token . $salt );
2565 * Check given value against the token value stored in the session.
2566 * A match should confirm that the form was submitted from the
2567 * user's own login session, not a form submission from a third-party
2570 * @param string $val - the input value to compare
2571 * @param string $salt - Optional function-specific data for hash
2575 function matchEditToken( $val, $salt = '' ) {
2576 $sessionToken = $this->editToken( $salt );
2577 if ( $val != $sessionToken ) {
2578 wfDebug( "User::matchEditToken: broken session data\n" );
2580 return $val == $sessionToken;
2584 * Check whether the edit token is fine except for the suffix
2586 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2587 $sessionToken = $this->editToken( $salt );
2588 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2592 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2593 * mail to the user's given address.
2595 * Calls saveSettings() internally; as it has side effects, not committing changes
2596 * would be pretty silly.
2598 * @return mixed True on success, a WikiError object on failure.
2600 function sendConfirmationMail() {
2602 $expiration = null; // gets passed-by-ref and defined in next line.
2603 $token = $this->confirmationToken( $expiration );
2604 $url = $this->confirmationTokenUrl( $token );
2605 $invalidateURL = $this->invalidationTokenUrl( $token );
2606 $this->saveSettings();
2608 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2609 wfMsg( 'confirmemail_body',
2613 $wgLang->timeanddate( $expiration, false ),
2618 * Send an e-mail to this user's account. Does not check for
2619 * confirmed status or validity.
2621 * @param string $subject
2622 * @param string $body
2623 * @param string $from Optional from address; default $wgPasswordSender will be used otherwise.
2624 * @return mixed True on success, a WikiError object on failure.
2626 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2627 if( is_null( $from ) ) {
2628 global $wgPasswordSender;
2629 $from = $wgPasswordSender;
2632 $to = new MailAddress( $this );
2633 $sender = new MailAddress( $from );
2634 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2638 * Generate, store, and return a new e-mail confirmation code.
2639 * A hash (unsalted since it's used as a key) is stored.
2641 * Call saveSettings() after calling this function to commit
2642 * this change to the database.
2644 * @param &$expiration mixed output: accepts the expiration time
2648 function confirmationToken( &$expiration ) {
2650 $expires = $now +
7 * 24 * 60 * 60;
2651 $expiration = wfTimestamp( TS_MW
, $expires );
2652 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2653 $hash = md5( $token );
2655 $this->mEmailToken
= $hash;
2656 $this->mEmailTokenExpires
= $expiration;
2661 * Return a URL the user can use to confirm their email address.
2662 * @param $token: accepts the email confirmation token
2666 function confirmationTokenUrl( $token ) {
2667 return $this->getTokenUrl( 'ConfirmEmail', $token );
2670 * Return a URL the user can use to invalidate their email address.
2671 * @param $token: accepts the email confirmation token
2675 function invalidationTokenUrl( $token ) {
2676 return $this->getTokenUrl( 'Invalidateemail', $token );
2680 * Internal function to format the e-mail validation/invalidation URLs.
2681 * This uses $wgArticlePath directly as a quickie hack to use the
2682 * hardcoded English names of the Special: pages, for ASCII safety.
2684 * Since these URLs get dropped directly into emails, using the
2685 * short English names avoids insanely long URL-encoded links, which
2686 * also sometimes can get corrupted in some browsers/mailers
2687 * (bug 6957 with Gmail and Internet Explorer).
2689 protected function getTokenUrl( $page, $token ) {
2690 global $wgArticlePath;
2694 "Special:$page/$token",
2699 * Mark the e-mail address confirmed.
2701 * Call saveSettings() after calling this function to commit the change.
2703 function confirmEmail() {
2704 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2709 * Invalidate the user's email confirmation, unauthenticate the email
2710 * if it was already confirmed.
2712 * Call saveSettings() after calling this function to commit the change.
2714 function invalidateEmail() {
2716 $this->mEmailToken
= null;
2717 $this->mEmailTokenExpires
= null;
2718 $this->setEmailAuthenticationTimestamp( null );
2722 function setEmailAuthenticationTimestamp( $timestamp ) {
2724 $this->mEmailAuthenticated
= $timestamp;
2725 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2729 * Is this user allowed to send e-mails within limits of current
2730 * site configuration?
2733 function canSendEmail() {
2734 $canSend = $this->isEmailConfirmed();
2735 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2740 * Is this user allowed to receive e-mails within limits of current
2741 * site configuration?
2744 function canReceiveEmail() {
2745 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2749 * Is this user's e-mail address valid-looking and confirmed within
2750 * limits of the current site configuration?
2752 * If $wgEmailAuthentication is on, this may require the user to have
2753 * confirmed their address by returning a code or using a password
2754 * sent to the address from the wiki.
2758 function isEmailConfirmed() {
2759 global $wgEmailAuthentication;
2762 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2763 if( $this->isAnon() )
2765 if( !self
::isValidEmailAddr( $this->mEmail
) )
2767 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2776 * Return true if there is an outstanding request for e-mail confirmation.
2779 function isEmailConfirmationPending() {
2780 global $wgEmailAuthentication;
2781 return $wgEmailAuthentication &&
2782 !$this->isEmailConfirmed() &&
2783 $this->mEmailToken
&&
2784 $this->mEmailTokenExpires
> wfTimestamp();
2788 * Get the timestamp of account creation, or false for
2789 * non-existent/anonymous user accounts
2793 public function getRegistration() {
2794 return $this->mId
> 0
2795 ?
$this->mRegistration
2800 * @param array $groups list of groups
2801 * @return array list of permission key names for given groups combined
2803 static function getGroupPermissions( $groups ) {
2804 global $wgGroupPermissions;
2806 foreach( $groups as $group ) {
2807 if( isset( $wgGroupPermissions[$group] ) ) {
2808 $rights = array_merge( $rights,
2809 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2816 * @param string $group key name
2817 * @return string localized descriptive name for group, if provided
2819 static function getGroupName( $group ) {
2820 global $wgMessageCache;
2821 $wgMessageCache->loadAllMessages();
2822 $key = "group-$group";
2823 $name = wfMsg( $key );
2824 return $name == '' ||
wfEmptyMsg( $key, $name )
2830 * @param string $group key name
2831 * @return string localized descriptive name for member of a group, if provided
2833 static function getGroupMember( $group ) {
2834 global $wgMessageCache;
2835 $wgMessageCache->loadAllMessages();
2836 $key = "group-$group-member";
2837 $name = wfMsg( $key );
2838 return $name == '' ||
wfEmptyMsg( $key, $name )
2844 * Return the set of defined explicit groups.
2845 * The implicit groups (by default *, 'user' and 'autoconfirmed')
2846 * are not included, as they are defined automatically,
2847 * not in the database.
2850 static function getAllGroups() {
2851 global $wgGroupPermissions;
2853 array_keys( $wgGroupPermissions ),
2854 self
::getImplicitGroups()
2859 * Get a list of all available permissions
2861 static function getAllRights() {
2862 if ( self
::$mAllRights === false ) {
2863 global $wgAvailableRights;
2864 if ( count( $wgAvailableRights ) ) {
2865 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
2867 self
::$mAllRights = self
::$mCoreRights;
2869 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
2871 return self
::$mAllRights;
2875 * Get a list of implicit groups
2879 public static function getImplicitGroups() {
2880 global $wgImplicitGroups;
2881 $groups = $wgImplicitGroups;
2882 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
2887 * Get the title of a page describing a particular group
2889 * @param $group Name of the group
2892 static function getGroupPage( $group ) {
2893 global $wgMessageCache;
2894 $wgMessageCache->loadAllMessages();
2895 $page = wfMsgForContent( 'grouppage-' . $group );
2896 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2897 $title = Title
::newFromText( $page );
2898 if( is_object( $title ) )
2905 * Create a link to the group in HTML, if available
2907 * @param $group Name of the group
2908 * @param $text The text of the link
2911 static function makeGroupLinkHTML( $group, $text = '' ) {
2913 $text = self
::getGroupName( $group );
2915 $title = self
::getGroupPage( $group );
2918 $sk = $wgUser->getSkin();
2919 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2926 * Create a link to the group in Wikitext, if available
2928 * @param $group Name of the group
2929 * @param $text The text of the link (by default, the name of the group)
2932 static function makeGroupLinkWiki( $group, $text = '' ) {
2934 $text = self
::getGroupName( $group );
2936 $title = self
::getGroupPage( $group );
2938 $page = $title->getPrefixedText();
2939 return "[[$page|$text]]";
2946 * Increment the user's edit-count field.
2947 * Will have no effect for anonymous users.
2949 function incEditCount() {
2950 if( !$this->isAnon() ) {
2951 $dbw = wfGetDB( DB_MASTER
);
2952 $dbw->update( 'user',
2953 array( 'user_editcount=user_editcount+1' ),
2954 array( 'user_id' => $this->getId() ),
2957 // Lazy initialization check...
2958 if( $dbw->affectedRows() == 0 ) {
2959 // Pull from a slave to be less cruel to servers
2960 // Accuracy isn't the point anyway here
2961 $dbr = wfGetDB( DB_SLAVE
);
2962 $count = $dbr->selectField( 'revision',
2964 array( 'rev_user' => $this->getId() ),
2967 // Now here's a goddamn hack...
2968 if( $dbr !== $dbw ) {
2969 // If we actually have a slave server, the count is
2970 // at least one behind because the current transaction
2971 // has not been committed and replicated.
2974 // But if DB_SLAVE is selecting the master, then the
2975 // count we just read includes the revision that was
2976 // just added in the working transaction.
2979 $dbw->update( 'user',
2980 array( 'user_editcount' => $count ),
2981 array( 'user_id' => $this->getId() ),
2985 // edit count in user cache too
2986 $this->invalidateCache();
2989 static function getRightDescription( $right ) {
2990 global $wgMessageCache;
2991 $wgMessageCache->loadAllMessages();
2992 $key = "right-$right";
2993 $name = wfMsg( $key );
2994 return $name == '' ||
wfEmptyMsg( $key, $name )