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 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1106 // Deprecated, but kept for backwards-compatibility config
1109 return !$this->isAllowed('noratelimit');
1113 * Primitive rate limits: enforce maximum actions per time period
1114 * to put a brake on flooding.
1116 * Note: when using a shared cache like memcached, IP-address
1117 * last-hit counters will be shared across wikis.
1119 * @return bool true if a rate limiter was tripped
1122 function pingLimiter( $action='edit' ) {
1124 # Call the 'PingLimiter' hook
1126 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1130 global $wgRateLimits;
1131 if( !isset( $wgRateLimits[$action] ) ) {
1135 # Some groups shouldn't trigger the ping limiter, ever
1136 if( !$this->isPingLimitable() )
1139 global $wgMemc, $wgRateLimitLog;
1140 wfProfileIn( __METHOD__
);
1142 $limits = $wgRateLimits[$action];
1144 $id = $this->getId();
1148 if( isset( $limits['anon'] ) && $id == 0 ) {
1149 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1152 if( isset( $limits['user'] ) && $id != 0 ) {
1153 $userLimit = $limits['user'];
1155 if( $this->isNewbie() ) {
1156 if( isset( $limits['newbie'] ) && $id != 0 ) {
1157 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1159 if( isset( $limits['ip'] ) ) {
1160 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1163 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1164 $subnet = $matches[1];
1165 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1168 // Check for group-specific permissions
1169 // If more than one group applies, use the group with the highest limit
1170 foreach ( $this->getGroups() as $group ) {
1171 if ( isset( $limits[$group] ) ) {
1172 if ( $userLimit === false ||
$limits[$group] > $userLimit ) {
1173 $userLimit = $limits[$group];
1177 // Set the user limit key
1178 if ( $userLimit !== false ) {
1179 wfDebug( __METHOD__
.": effective user limit: $userLimit\n" );
1180 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1184 foreach( $keys as $key => $limit ) {
1185 list( $max, $period ) = $limit;
1186 $summary = "(limit $max in {$period}s)";
1187 $count = $wgMemc->get( $key );
1189 if( $count > $max ) {
1190 wfDebug( __METHOD__
.": tripped! $key at $count $summary\n" );
1191 if( $wgRateLimitLog ) {
1192 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1196 wfDebug( __METHOD__
.": ok. $key at $count $summary\n" );
1199 wfDebug( __METHOD__
.": adding record for $key $summary\n" );
1200 $wgMemc->add( $key, 1, intval( $period ) );
1202 $wgMemc->incr( $key );
1205 wfProfileOut( __METHOD__
);
1210 * Check if user is blocked
1211 * @return bool True if blocked, false otherwise
1213 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1214 wfDebug( "User::isBlocked: enter\n" );
1215 $this->getBlockedStatus( $bFromSlave );
1216 return $this->mBlockedby
!== 0;
1220 * Check if user is blocked from editing a particular article
1222 function isBlockedFrom( $title, $bFromSlave = false ) {
1223 global $wgBlockAllowsUTEdit;
1224 wfProfileIn( __METHOD__
);
1225 wfDebug( __METHOD__
.": enter\n" );
1227 wfDebug( __METHOD__
.": asking isBlocked()\n" );
1228 $blocked = $this->isBlocked( $bFromSlave );
1229 # If a user's name is suppressed, they cannot make edits anywhere
1230 if ( !$this->mHideName
&& $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1231 $title->getNamespace() == NS_USER_TALK
) {
1233 wfDebug( __METHOD__
.": self-talk page, ignoring any blocks\n" );
1235 wfProfileOut( __METHOD__
);
1240 * Get name of blocker
1241 * @return string name of blocker
1243 function blockedBy() {
1244 $this->getBlockedStatus();
1245 return $this->mBlockedby
;
1249 * Get blocking reason
1250 * @return string Blocking reason
1252 function blockedFor() {
1253 $this->getBlockedStatus();
1254 return $this->mBlockreason
;
1258 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1261 if( $this->mId
=== null and $this->mName
!== null
1262 and User
::isIP( $this->mName
) ) {
1263 // Special case, we know the user is anonymous
1265 } elseif( $this->mId
=== null ) {
1266 // Don't load if this was initialized from an ID
1273 * Set the user and reload all fields according to that ID
1275 function setId( $v ) {
1277 $this->clearInstanceCache( 'id' );
1281 * Get the user name, or the IP for anons
1283 function getName() {
1284 if ( !$this->mDataLoaded
&& $this->mFrom
== 'name' ) {
1285 # Special case optimisation
1286 return $this->mName
;
1289 if ( $this->mName
=== false ) {
1291 $this->mName
= IP
::sanitizeIP( wfGetIP() );
1293 return $this->mName
;
1298 * Set the user name.
1300 * This does not reload fields from the database according to the given
1301 * name. Rather, it is used to create a temporary "nonexistent user" for
1302 * later addition to the database. It can also be used to set the IP
1303 * address for an anonymous user to something other than the current
1306 * User::newFromName() has rougly the same function, when the named user
1309 function setName( $str ) {
1311 $this->mName
= $str;
1315 * Return the title dbkey form of the name, for eg user pages.
1319 function getTitleKey() {
1320 return str_replace( ' ', '_', $this->getName() );
1323 function getNewtalk() {
1326 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1327 if( $this->mNewtalk
=== -1 ) {
1328 $this->mNewtalk
= false; # reset talk page status
1330 # Check memcached separately for anons, who have no
1331 # entire User object stored in there.
1334 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1335 $newtalk = $wgMemc->get( $key );
1336 if( strval( $newtalk ) !== '' ) {
1337 $this->mNewtalk
= (bool)$newtalk;
1339 // Since we are caching this, make sure it is up to date by getting it
1341 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName(), true );
1342 $wgMemc->set( $key, (int)$this->mNewtalk
, 1800 );
1345 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
1349 return (bool)$this->mNewtalk
;
1353 * Return the talk page(s) this user has new messages on.
1355 function getNewMessageLinks() {
1357 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1360 if (!$this->getNewtalk())
1362 $up = $this->getUserPage();
1363 $utp = $up->getTalkPage();
1364 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1369 * Perform a user_newtalk check, uncached.
1370 * Use getNewtalk for a cached check.
1372 * @param string $field
1374 * @param bool $fromMaster True to fetch from the master, false for a slave
1378 function checkNewtalk( $field, $id, $fromMaster = false ) {
1379 if ( $fromMaster ) {
1380 $db = wfGetDB( DB_MASTER
);
1382 $db = wfGetDB( DB_SLAVE
);
1384 $ok = $db->selectField( 'user_newtalk', $field,
1385 array( $field => $id ), __METHOD__
);
1386 return $ok !== false;
1391 * @param string $field
1395 function updateNewtalk( $field, $id ) {
1396 $dbw = wfGetDB( DB_MASTER
);
1397 $dbw->insert( 'user_newtalk',
1398 array( $field => $id ),
1401 if ( $dbw->affectedRows() ) {
1402 wfDebug( __METHOD__
.": set on ($field, $id)\n" );
1405 wfDebug( __METHOD__
." already set ($field, $id)\n" );
1411 * Clear the new messages flag for the given user
1412 * @param string $field
1416 function deleteNewtalk( $field, $id ) {
1417 $dbw = wfGetDB( DB_MASTER
);
1418 $dbw->delete( 'user_newtalk',
1419 array( $field => $id ),
1421 if ( $dbw->affectedRows() ) {
1422 wfDebug( __METHOD__
.": killed on ($field, $id)\n" );
1425 wfDebug( __METHOD__
.": already gone ($field, $id)\n" );
1431 * Update the 'You have new messages!' status.
1434 function setNewtalk( $val ) {
1435 if( wfReadOnly() ) {
1440 $this->mNewtalk
= $val;
1442 if( $this->isAnon() ) {
1444 $id = $this->getName();
1447 $id = $this->getId();
1452 $changed = $this->updateNewtalk( $field, $id );
1454 $changed = $this->deleteNewtalk( $field, $id );
1457 if( $this->isAnon() ) {
1458 // Anons have a separate memcached space, since
1459 // user records aren't kept for them.
1460 $key = wfMemcKey( 'newtalk', 'ip', $id );
1461 $wgMemc->set( $key, $val ?
1 : 0, 1800 );
1464 $this->invalidateCache();
1469 * Generate a current or new-future timestamp to be stored in the
1470 * user_touched field when we update things.
1472 private static function newTouchedTimestamp() {
1473 global $wgClockSkewFudge;
1474 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1478 * Clear user data from memcached.
1479 * Use after applying fun updates to the database; caller's
1480 * responsibility to update user_touched if appropriate.
1482 * Called implicitly from invalidateCache() and saveSettings().
1484 private function clearSharedCache() {
1487 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1492 * Immediately touch the user data cache for this account.
1493 * Updates user_touched field, and removes account data from memcached
1494 * for reload on the next hit.
1496 function invalidateCache() {
1499 $this->mTouched
= self
::newTouchedTimestamp();
1501 $dbw = wfGetDB( DB_MASTER
);
1502 $dbw->update( 'user',
1503 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1504 array( 'user_id' => $this->mId
),
1507 $this->clearSharedCache();
1511 function validateCache( $timestamp ) {
1513 return ($timestamp >= $this->mTouched
);
1517 * Set the password and reset the random token
1518 * Calls through to authentication plugin if necessary;
1519 * will have no effect if the auth plugin refuses to
1520 * pass the change through or if the legal password
1523 * As a special case, setting the password to null
1524 * wipes it, so the account cannot be logged in until
1525 * a new password is set, for instance via e-mail.
1527 * @param string $str
1528 * @throws PasswordError on failure
1530 function setPassword( $str ) {
1533 if( $str !== null ) {
1534 if( !$wgAuth->allowPasswordChange() ) {
1535 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1538 if( !$this->isValidPassword( $str ) ) {
1539 global $wgMinimalPasswordLength;
1540 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1541 $wgMinimalPasswordLength ) );
1545 if( !$wgAuth->setPassword( $this, $str ) ) {
1546 throw new PasswordError( wfMsg( 'externaldberror' ) );
1549 $this->setInternalPassword( $str );
1555 * Set the password and reset the random token no matter
1558 * @param string $str
1560 function setInternalPassword( $str ) {
1564 if( $str === null ) {
1565 // Save an invalid hash...
1566 $this->mPassword
= '';
1568 $this->mPassword
= self
::crypt( $str );
1570 $this->mNewpassword
= '';
1571 $this->mNewpassTime
= null;
1574 function getToken() {
1576 return $this->mToken
;
1580 * Set the random token (used for persistent authentication)
1581 * Called from loadDefaults() among other places.
1584 function setToken( $token = false ) {
1585 global $wgSecretKey, $wgProxyKey;
1588 if ( $wgSecretKey ) {
1589 $key = $wgSecretKey;
1590 } elseif ( $wgProxyKey ) {
1595 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1597 $this->mToken
= $token;
1601 function setCookiePassword( $str ) {
1603 $this->mCookiePassword
= md5( $str );
1607 * Set the password for a password reminder or new account email
1608 * Sets the user_newpass_time field if $throttle is true
1610 function setNewpassword( $str, $throttle = true ) {
1612 $this->mNewpassword
= self
::crypt( $str );
1614 $this->mNewpassTime
= wfTimestampNow();
1619 * Returns true if a password reminder email has already been sent within
1620 * the last $wgPasswordReminderResendTime hours
1622 function isPasswordReminderThrottled() {
1623 global $wgPasswordReminderResendTime;
1625 if ( !$this->mNewpassTime ||
!$wgPasswordReminderResendTime ) {
1628 $expiry = wfTimestamp( TS_UNIX
, $this->mNewpassTime
) +
$wgPasswordReminderResendTime * 3600;
1629 return time() < $expiry;
1632 function getEmail() {
1634 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail
) );
1635 return $this->mEmail
;
1638 function getEmailAuthenticationTimestamp() {
1640 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
1641 return $this->mEmailAuthenticated
;
1644 function setEmail( $str ) {
1646 $this->mEmail
= $str;
1647 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail
) );
1650 function getRealName() {
1652 return $this->mRealName
;
1655 function setRealName( $str ) {
1657 $this->mRealName
= $str;
1661 * @param string $oname The option to check
1662 * @param string $defaultOverride A default value returned if the option does not exist
1665 function getOption( $oname, $defaultOverride = '' ) {
1668 if ( is_null( $this->mOptions
) ) {
1669 if($defaultOverride != '') {
1670 return $defaultOverride;
1672 $this->mOptions
= User
::getDefaultOptions();
1675 if ( array_key_exists( $oname, $this->mOptions
) ) {
1676 return trim( $this->mOptions
[$oname] );
1678 return $defaultOverride;
1683 * Get the user's date preference, including some important migration for
1686 function getDatePreference() {
1687 if ( is_null( $this->mDatePreference
) ) {
1689 $value = $this->getOption( 'date' );
1690 $map = $wgLang->getDatePreferenceMigrationMap();
1691 if ( isset( $map[$value] ) ) {
1692 $value = $map[$value];
1694 $this->mDatePreference
= $value;
1696 return $this->mDatePreference
;
1700 * @param string $oname The option to check
1701 * @return bool False if the option is not selected, true if it is
1703 function getBoolOption( $oname ) {
1704 return (bool)$this->getOption( $oname );
1708 * Get an option as an integer value from the source string.
1709 * @param string $oname The option to check
1710 * @param int $default Optional value to return if option is unset/blank.
1713 function getIntOption( $oname, $default=0 ) {
1714 $val = $this->getOption( $oname );
1718 return intval( $val );
1721 function setOption( $oname, $val ) {
1723 if ( is_null( $this->mOptions
) ) {
1724 $this->mOptions
= User
::getDefaultOptions();
1726 if ( $oname == 'skin' ) {
1727 # Clear cached skin, so the new one displays immediately in Special:Preferences
1728 unset( $this->mSkin
);
1730 // Filter out any newlines that may have passed through input validation.
1731 // Newlines are used to separate items in the options blob.
1733 $val = str_replace( "\r\n", "\n", $val );
1734 $val = str_replace( "\r", "\n", $val );
1735 $val = str_replace( "\n", " ", $val );
1737 // Explicitly NULL values should refer to defaults
1738 global $wgDefaultUserOptions;
1739 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1740 $val = $wgDefaultUserOptions[$oname];
1742 $this->mOptions
[$oname] = $val;
1745 function getRights() {
1746 if ( is_null( $this->mRights
) ) {
1747 $this->mRights
= self
::getGroupPermissions( $this->getEffectiveGroups() );
1748 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights
) );
1749 // Force reindexation of rights when a hook has unset one of them
1750 $this->mRights
= array_values( $this->mRights
);
1752 return $this->mRights
;
1756 * Get the list of explicit group memberships this user has.
1757 * The implicit * and user groups are not included.
1758 * @return array of strings
1760 function getGroups() {
1762 return $this->mGroups
;
1766 * Get the list of implicit group memberships this user has.
1767 * This includes all explicit groups, plus 'user' if logged in,
1768 * '*' for all accounts and autopromoted groups
1769 * @param boolean $recache Don't use the cache
1770 * @return array of strings
1772 function getEffectiveGroups( $recache = false ) {
1773 if ( $recache ||
is_null( $this->mEffectiveGroups
) ) {
1774 $this->mEffectiveGroups
= $this->getGroups();
1775 $this->mEffectiveGroups
[] = '*';
1776 if( $this->getId() ) {
1777 $this->mEffectiveGroups
[] = 'user';
1779 $this->mEffectiveGroups
= array_unique( array_merge(
1780 $this->mEffectiveGroups
,
1781 Autopromote
::getAutopromoteGroups( $this )
1784 # Hook for additional groups
1785 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups
) );
1788 return $this->mEffectiveGroups
;
1791 /* Return the edit count for the user. This is where User::edits should have been */
1792 function getEditCount() {
1794 if ( !isset( $this->mEditCount
) ) {
1795 /* Populate the count, if it has not been populated yet */
1796 $this->mEditCount
= User
::edits($this->mId
);
1798 return $this->mEditCount
;
1806 * Add the user to the given group.
1807 * This takes immediate effect.
1808 * @param string $group
1810 function addGroup( $group ) {
1811 $dbw = wfGetDB( DB_MASTER
);
1812 if( $this->getId() ) {
1813 $dbw->insert( 'user_groups',
1815 'ug_user' => $this->getID(),
1816 'ug_group' => $group,
1819 array( 'IGNORE' ) );
1822 $this->loadGroups();
1823 $this->mGroups
[] = $group;
1824 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1826 $this->invalidateCache();
1830 * Remove the user from the given group.
1831 * This takes immediate effect.
1832 * @param string $group
1834 function removeGroup( $group ) {
1836 $dbw = wfGetDB( DB_MASTER
);
1837 $dbw->delete( 'user_groups',
1839 'ug_user' => $this->getID(),
1840 'ug_group' => $group,
1842 'User::removeGroup' );
1844 $this->loadGroups();
1845 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1846 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups( true ) );
1848 $this->invalidateCache();
1853 * A more legible check for non-anonymousness.
1854 * Returns true if the user is not an anonymous visitor.
1858 function isLoggedIn() {
1859 return $this->getID() != 0;
1863 * A more legible check for anonymousness.
1864 * Returns true if the user is an anonymous visitor.
1869 return !$this->isLoggedIn();
1873 * Whether the user is a bot
1877 wfDeprecated( __METHOD__
);
1878 return $this->isAllowed( 'bot' );
1882 * Check if user is allowed to access a feature / make an action
1883 * @param string $action Action to be checked
1884 * @return boolean True: action is allowed, False: action should not be allowed
1886 function isAllowed($action='') {
1887 if ( $action === '' )
1888 // In the spirit of DWIM
1891 return in_array( $action, $this->getRights() );
1895 * Check whether to enable recent changes patrol features for this user
1898 public function useRCPatrol() {
1899 global $wgUseRCPatrol;
1900 return( $wgUseRCPatrol && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
1904 * Check whether to enable recent changes patrol features for this user
1907 public function useNPPatrol() {
1908 global $wgUseRCPatrol, $wgUseNPPatrol;
1909 return( ($wgUseRCPatrol ||
$wgUseNPPatrol) && ($this->isAllowed('patrol') ||
$this->isAllowed('patrolmarks')) );
1913 * Load a skin if it doesn't exist or return it
1914 * @todo FIXME : need to check the old failback system [AV]
1916 function &getSkin() {
1918 if ( ! isset( $this->mSkin
) ) {
1919 wfProfileIn( __METHOD__
);
1922 $userSkin = $this->getOption( 'skin' );
1923 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1925 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1926 wfProfileOut( __METHOD__
);
1928 return $this->mSkin
;
1932 * @param string $title Article title to look at
1936 * Check watched status of an article
1937 * @return bool True if article is watched
1939 function isWatched( $title ) {
1940 $wl = WatchedItem
::fromUserTitle( $this, $title );
1941 return $wl->isWatched();
1947 function addWatch( $title ) {
1948 $wl = WatchedItem
::fromUserTitle( $this, $title );
1950 $this->invalidateCache();
1954 * Stop watching an article
1956 function removeWatch( $title ) {
1957 $wl = WatchedItem
::fromUserTitle( $this, $title );
1959 $this->invalidateCache();
1963 * Clear the user's notification timestamp for the given title.
1964 * If e-notif e-mails are on, they will receive notification mails on
1965 * the next change of the page if it's watched etc.
1967 function clearNotification( &$title ) {
1968 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
1970 # Do nothing if the database is locked to writes
1971 if( wfReadOnly() ) {
1975 if ($title->getNamespace() == NS_USER_TALK
&&
1976 $title->getText() == $this->getName() ) {
1977 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1979 $this->setNewtalk( false );
1982 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
1986 if( $this->isAnon() ) {
1987 // Nothing else to do...
1991 // Only update the timestamp if the page is being watched.
1992 // The query to find out if it is watched is cached both in memcached and per-invocation,
1993 // and when it does have to be executed, it can be on a slave
1994 // If this is the user's newtalk page, we always update the timestamp
1995 if ($title->getNamespace() == NS_USER_TALK
&&
1996 $title->getText() == $wgUser->getName())
1999 } elseif ( $this->getId() == $wgUser->getId() ) {
2000 $watched = $title->userIsWatching();
2005 // If the page is watched by the user (or may be watched), update the timestamp on any
2006 // any matching rows
2008 $dbw = wfGetDB( DB_MASTER
);
2009 $dbw->update( 'watchlist',
2011 'wl_notificationtimestamp' => NULL
2012 ), array( /* WHERE */
2013 'wl_title' => $title->getDBkey(),
2014 'wl_namespace' => $title->getNamespace(),
2015 'wl_user' => $this->getID()
2016 ), 'User::clearLastVisited'
2024 * Resets all of the given user's page-change notification timestamps.
2025 * If e-notif e-mails are on, they will receive notification mails on
2026 * the next change of any watched page.
2028 * @param int $currentUser user ID number
2031 function clearAllNotifications( $currentUser ) {
2032 global $wgUseEnotif, $wgShowUpdatedMarker;
2033 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2034 $this->setNewtalk( false );
2037 if( $currentUser != 0 ) {
2038 $dbw = wfGetDB( DB_MASTER
);
2039 $dbw->update( 'watchlist',
2041 'wl_notificationtimestamp' => NULL
2042 ), array( /* WHERE */
2043 'wl_user' => $currentUser
2046 # We also need to clear here the "you have new message" notification for the own user_talk page
2047 # This is cleared one page view later in Article::viewUpdates();
2053 * @return string Encoding options
2055 function encodeOptions() {
2057 if ( is_null( $this->mOptions
) ) {
2058 $this->mOptions
= User
::getDefaultOptions();
2061 foreach ( $this->mOptions
as $oname => $oval ) {
2062 array_push( $a, $oname.'='.$oval );
2064 $s = implode( "\n", $a );
2071 function decodeOptions( $str ) {
2072 $this->mOptions
= array();
2073 $a = explode( "\n", $str );
2074 foreach ( $a as $s ) {
2076 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2077 $this->mOptions
[$m[1]] = $m[2];
2082 protected function setCookie( $name, $value, $exp=0 ) {
2083 global $wgCookiePrefix,$wgCookieDomain,$wgCookieSecure,$wgCookieExpiration, $wgCookieHttpOnly;
2085 $exp = time() +
$wgCookieExpiration;
2087 $httpOnlySafe = wfHttpOnlySafe();
2088 wfDebugLog( 'cookie',
2089 'setcookie: "' . implode( '", "',
2091 $wgCookiePrefix . $name,
2097 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2098 if( $httpOnlySafe && isset( $wgCookieHttpOnly ) ) {
2099 setcookie( $wgCookiePrefix . $name,
2105 $wgCookieHttpOnly );
2107 // setcookie() fails on PHP 5.1 if you give it future-compat paramters.
2109 setcookie( $wgCookiePrefix . $name,
2118 protected function clearCookie( $name ) {
2119 $this->setCookie( $name, '', time() - 86400 );
2122 function setCookies() {
2124 if ( 0 == $this->mId
) return;
2126 'wsUserID' => $this->mId
,
2127 'wsToken' => $this->mToken
,
2128 'wsUserName' => $this->getName()
2131 'UserID' => $this->mId
,
2132 'UserName' => $this->getName(),
2134 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2135 $cookies['Token'] = $this->mToken
;
2137 $cookies['Token'] = false;
2140 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2141 $_SESSION = $session +
$_SESSION;
2142 foreach ( $cookies as $name => $value ) {
2143 if ( $value === false ) {
2144 $this->clearCookie( $name );
2146 $this->setCookie( $name, $value );
2156 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2162 * Really logout user
2163 * Clears the cookies and session, resets the instance cache
2165 function doLogout() {
2166 $this->clearInstanceCache( 'defaults' );
2168 $_SESSION['wsUserID'] = 0;
2170 $this->clearCookie( 'UserID' );
2171 $this->clearCookie( 'Token' );
2173 # Remember when user logged out, to prevent seeing cached pages
2174 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() +
86400 );
2178 * Save object settings into database
2179 * @todo Only rarely do all these fields need to be set!
2181 function saveSettings() {
2183 if ( wfReadOnly() ) { return; }
2184 if ( 0 == $this->mId
) { return; }
2186 $this->mTouched
= self
::newTouchedTimestamp();
2188 $dbw = wfGetDB( DB_MASTER
);
2189 $dbw->update( 'user',
2191 'user_name' => $this->mName
,
2192 'user_password' => $this->mPassword
,
2193 'user_newpassword' => $this->mNewpassword
,
2194 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime
),
2195 'user_real_name' => $this->mRealName
,
2196 'user_email' => $this->mEmail
,
2197 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2198 'user_options' => $this->encodeOptions(),
2199 'user_touched' => $dbw->timestamp($this->mTouched
),
2200 'user_token' => $this->mToken
,
2201 'user_email_token' => $this->mEmailToken
,
2202 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires
),
2203 ), array( /* WHERE */
2204 'user_id' => $this->mId
2207 wfRunHooks( 'UserSaveSettings', array( $this ) );
2208 $this->clearSharedCache();
2212 * Checks if a user with the given name exists, returns the ID.
2214 function idForName() {
2215 $s = trim( $this->getName() );
2216 if ( $s === '' ) return 0;
2218 $dbr = wfGetDB( DB_SLAVE
);
2219 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__
);
2220 if ( $id === false ) {
2227 * Add a user to the database, return the user object
2229 * @param string $name The user's name
2230 * @param array $params Associative array of non-default parameters to save to the database:
2231 * password The user's password. Password logins will be disabled if this is omitted.
2232 * newpassword A temporary password mailed to the user
2233 * email The user's email address
2234 * email_authenticated The email authentication timestamp
2235 * real_name The user's real name
2236 * options An associative array of non-default options
2237 * token Random authentication token. Do not set.
2238 * registration Registration timestamp. Do not set.
2240 * @return User object, or null if the username already exists
2242 static function createNew( $name, $params = array() ) {
2245 if ( isset( $params['options'] ) ) {
2246 $user->mOptions
= $params['options'] +
$user->mOptions
;
2247 unset( $params['options'] );
2249 $dbw = wfGetDB( DB_MASTER
);
2250 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2252 'user_id' => $seqVal,
2253 'user_name' => $name,
2254 'user_password' => $user->mPassword
,
2255 'user_newpassword' => $user->mNewpassword
,
2256 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime
),
2257 'user_email' => $user->mEmail
,
2258 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated
),
2259 'user_real_name' => $user->mRealName
,
2260 'user_options' => $user->encodeOptions(),
2261 'user_token' => $user->mToken
,
2262 'user_registration' => $dbw->timestamp( $user->mRegistration
),
2263 'user_editcount' => 0,
2265 foreach ( $params as $name => $value ) {
2266 $fields["user_$name"] = $value;
2268 $dbw->insert( 'user', $fields, __METHOD__
, array( 'IGNORE' ) );
2269 if ( $dbw->affectedRows() ) {
2270 $newUser = User
::newFromId( $dbw->insertId() );
2278 * Add an existing user object to the database
2280 function addToDatabase() {
2282 $dbw = wfGetDB( DB_MASTER
);
2283 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2284 $dbw->insert( 'user',
2286 'user_id' => $seqVal,
2287 'user_name' => $this->mName
,
2288 'user_password' => $this->mPassword
,
2289 'user_newpassword' => $this->mNewpassword
,
2290 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime
),
2291 'user_email' => $this->mEmail
,
2292 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
2293 'user_real_name' => $this->mRealName
,
2294 'user_options' => $this->encodeOptions(),
2295 'user_token' => $this->mToken
,
2296 'user_registration' => $dbw->timestamp( $this->mRegistration
),
2297 'user_editcount' => 0,
2300 $this->mId
= $dbw->insertId();
2302 # Clear instance cache other than user table data, which is already accurate
2303 $this->clearInstanceCache();
2307 * If the (non-anonymous) user is blocked, this function will block any IP address
2308 * that they successfully log on from.
2310 function spreadBlock() {
2311 wfDebug( __METHOD__
."()\n" );
2313 if ( $this->mId
== 0 ) {
2317 $userblock = Block
::newFromDB( '', $this->mId
);
2318 if ( !$userblock ) {
2322 $userblock->doAutoblock( wfGetIp() );
2327 * Generate a string which will be different for any combination of
2328 * user options which would produce different parser output.
2329 * This will be used as part of the hash key for the parser cache,
2330 * so users will the same options can share the same cached data
2333 * Extensions which require it should install 'PageRenderingHash' hook,
2334 * which will give them a chance to modify this key based on their own
2337 * @param $content Bool: wheter use the content language to generate the
2341 function getPageRenderingHash( $content = false ) {
2342 global $wgContLang, $wgUseDynamicDates, $wgLang;
2343 if( $this->mHash
&& !$content ){
2344 return $this->mHash
;
2347 // stubthreshold is only included below for completeness,
2348 // it will always be 0 when this function is called by parsercache.
2350 $confstr = $this->getOption( 'math' );
2351 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2352 if ( $wgUseDynamicDates ) {
2353 $confstr .= '!' . $this->getDatePreference();
2355 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
2357 $confstr .= '!' . $wgContLang->getCode();
2359 $confstr .= '!' . $wgLang->getCode();
2361 $confstr .= '!' . $this->getOption( 'thumbsize' );
2362 // add in language specific options, if any
2363 $extra = $wgContLang->getExtraHashOptions();
2366 // Give a chance for extensions to modify the hash, if they have
2367 // extra options or other effects on the parser cache.
2368 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2370 // Make it a valid memcached key fragment
2371 $confstr = str_replace( ' ', '_', $confstr );
2372 $this->mHash
= $confstr;
2376 function isBlockedFromCreateAccount() {
2377 $this->getBlockedStatus();
2378 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
2382 * Determine if the user is blocked from using Special:Emailuser.
2387 function isBlockedFromEmailuser() {
2388 $this->getBlockedStatus();
2389 return $this->mBlock
&& $this->mBlock
->mBlockEmail
;
2392 function isAllowedToCreateAccount() {
2393 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2399 function setLoaded( $loaded ) {
2400 wfDeprecated( __METHOD__
);
2404 * Get this user's personal page title.
2409 function getUserPage() {
2410 return Title
::makeTitle( NS_USER
, $this->getName() );
2414 * Get this user's talk page title.
2419 function getTalkPage() {
2420 $title = $this->getUserPage();
2421 return $title->getTalkPage();
2427 function getMaxID() {
2428 static $res; // cache
2430 if ( isset( $res ) )
2433 $dbr = wfGetDB( DB_SLAVE
);
2434 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2439 * Determine whether the user is a newbie. Newbies are either
2440 * anonymous IPs, or the most recently created accounts.
2441 * @return bool True if it is a newbie.
2443 function isNewbie() {
2444 return !$this->isAllowed( 'autoconfirmed' );
2448 * Is the user active? We check to see if they've made at least
2449 * X number of edits in the last Y days.
2451 * @return bool true if the user is active, false if not
2453 public function isActiveEditor() {
2454 global $wgActiveUserEditCount, $wgActiveUserDays;
2455 $dbr = wfGetDB( DB_SLAVE
);
2457 // Stolen without shame from RC
2458 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2459 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime %
86400 );
2460 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2462 $res = $dbr->select( 'revision', '1',
2463 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2465 array('LIMIT' => $wgActiveUserEditCount ) );
2467 $count = $dbr->numRows($res);
2468 $dbr->freeResult($res);
2470 return $count == $wgActiveUserEditCount;
2474 * Check to see if the given clear-text password is one of the accepted passwords
2475 * @param string $password User password.
2476 * @return bool True if the given password is correct otherwise False.
2478 function checkPassword( $password ) {
2482 // Even though we stop people from creating passwords that
2483 // are shorter than this, doesn't mean people wont be able
2484 // to. Certain authentication plugins do NOT want to save
2485 // domain passwords in a mysql database, so we should
2486 // check this (incase $wgAuth->strict() is false).
2487 if( !$this->isValidPassword( $password ) ) {
2491 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2493 } elseif( $wgAuth->strict() ) {
2494 /* Auth plugin doesn't allow local authentication */
2496 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2497 /* Auth plugin doesn't allow local authentication for this user name */
2500 if ( self
::comparePasswords( $this->mPassword
, $password, $this->mId
) ) {
2502 } elseif ( function_exists( 'iconv' ) ) {
2503 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2504 # Check for this with iconv
2505 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2506 if ( self
::comparePasswords( $this->mPassword
, $cp1252Password, $this->mId
) ) {
2514 * Check if the given clear-text password matches the temporary password
2515 * sent by e-mail for password reset operations.
2518 function checkTemporaryPassword( $plaintext ) {
2519 return self
::comparePasswords( $this->mNewpassword
, $plaintext, $this->getId() );
2523 * Initialize (if necessary) and return a session token value
2524 * which can be used in edit forms to show that the user's
2525 * login credentials aren't being hijacked with a foreign form
2528 * @param mixed $salt - Optional function-specific data for hash.
2529 * Use a string or an array of strings.
2533 function editToken( $salt = '' ) {
2534 if ( $this->isAnon() ) {
2535 return EDIT_TOKEN_SUFFIX
;
2537 if( !isset( $_SESSION['wsEditToken'] ) ) {
2538 $token = $this->generateToken();
2539 $_SESSION['wsEditToken'] = $token;
2541 $token = $_SESSION['wsEditToken'];
2543 if( is_array( $salt ) ) {
2544 $salt = implode( '|', $salt );
2546 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX
;
2551 * Generate a hex-y looking random token for various uses.
2552 * Could be made more cryptographically sure if someone cares.
2555 function generateToken( $salt = '' ) {
2556 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2557 return md5( $token . $salt );
2561 * Check given value against the token value stored in the session.
2562 * A match should confirm that the form was submitted from the
2563 * user's own login session, not a form submission from a third-party
2566 * @param string $val - the input value to compare
2567 * @param string $salt - Optional function-specific data for hash
2571 function matchEditToken( $val, $salt = '' ) {
2572 $sessionToken = $this->editToken( $salt );
2573 if ( $val != $sessionToken ) {
2574 wfDebug( "User::matchEditToken: broken session data\n" );
2576 return $val == $sessionToken;
2580 * Check whether the edit token is fine except for the suffix
2582 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2583 $sessionToken = $this->editToken( $salt );
2584 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2588 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2589 * mail to the user's given address.
2591 * Calls saveSettings() internally; as it has side effects, not committing changes
2592 * would be pretty silly.
2594 * @return mixed True on success, a WikiError object on failure.
2596 function sendConfirmationMail() {
2598 $expiration = null; // gets passed-by-ref and defined in next line.
2599 $token = $this->confirmationToken( $expiration );
2600 $url = $this->confirmationTokenUrl( $token );
2601 $invalidateURL = $this->invalidationTokenUrl( $token );
2602 $this->saveSettings();
2604 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2605 wfMsg( 'confirmemail_body',
2609 $wgLang->timeanddate( $expiration, false ),
2614 * Send an e-mail to this user's account. Does not check for
2615 * confirmed status or validity.
2617 * @param string $subject
2618 * @param string $body
2619 * @param string $from Optional from address; default $wgPasswordSender will be used otherwise.
2620 * @return mixed True on success, a WikiError object on failure.
2622 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2623 if( is_null( $from ) ) {
2624 global $wgPasswordSender;
2625 $from = $wgPasswordSender;
2628 $to = new MailAddress( $this );
2629 $sender = new MailAddress( $from );
2630 return UserMailer
::send( $to, $sender, $subject, $body, $replyto );
2634 * Generate, store, and return a new e-mail confirmation code.
2635 * A hash (unsalted since it's used as a key) is stored.
2637 * Call saveSettings() after calling this function to commit
2638 * this change to the database.
2640 * @param &$expiration mixed output: accepts the expiration time
2644 function confirmationToken( &$expiration ) {
2646 $expires = $now +
7 * 24 * 60 * 60;
2647 $expiration = wfTimestamp( TS_MW
, $expires );
2648 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
2649 $hash = md5( $token );
2651 $this->mEmailToken
= $hash;
2652 $this->mEmailTokenExpires
= $expiration;
2657 * Return a URL the user can use to confirm their email address.
2658 * @param $token: accepts the email confirmation token
2662 function confirmationTokenUrl( $token ) {
2663 return $this->getTokenUrl( 'ConfirmEmail', $token );
2666 * Return a URL the user can use to invalidate their email address.
2667 * @param $token: accepts the email confirmation token
2671 function invalidationTokenUrl( $token ) {
2672 return $this->getTokenUrl( 'Invalidateemail', $token );
2676 * Internal function to format the e-mail validation/invalidation URLs.
2677 * This uses $wgArticlePath directly as a quickie hack to use the
2678 * hardcoded English names of the Special: pages, for ASCII safety.
2680 * Since these URLs get dropped directly into emails, using the
2681 * short English names avoids insanely long URL-encoded links, which
2682 * also sometimes can get corrupted in some browsers/mailers
2683 * (bug 6957 with Gmail and Internet Explorer).
2685 protected function getTokenUrl( $page, $token ) {
2686 global $wgArticlePath;
2690 "Special:$page/$token",
2695 * Mark the e-mail address confirmed.
2697 * Call saveSettings() after calling this function to commit the change.
2699 function confirmEmail() {
2700 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2705 * Invalidate the user's email confirmation, unauthenticate the email
2706 * if it was already confirmed.
2708 * Call saveSettings() after calling this function to commit the change.
2710 function invalidateEmail() {
2712 $this->mEmailToken
= null;
2713 $this->mEmailTokenExpires
= null;
2714 $this->setEmailAuthenticationTimestamp( null );
2718 function setEmailAuthenticationTimestamp( $timestamp ) {
2720 $this->mEmailAuthenticated
= $timestamp;
2721 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated
) );
2725 * Is this user allowed to send e-mails within limits of current
2726 * site configuration?
2729 function canSendEmail() {
2730 $canSend = $this->isEmailConfirmed();
2731 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2736 * Is this user allowed to receive e-mails within limits of current
2737 * site configuration?
2740 function canReceiveEmail() {
2741 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2745 * Is this user's e-mail address valid-looking and confirmed within
2746 * limits of the current site configuration?
2748 * If $wgEmailAuthentication is on, this may require the user to have
2749 * confirmed their address by returning a code or using a password
2750 * sent to the address from the wiki.
2754 function isEmailConfirmed() {
2755 global $wgEmailAuthentication;
2758 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2759 if( $this->isAnon() )
2761 if( !self
::isValidEmailAddr( $this->mEmail
) )
2763 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2772 * Return true if there is an outstanding request for e-mail confirmation.
2775 function isEmailConfirmationPending() {
2776 global $wgEmailAuthentication;
2777 return $wgEmailAuthentication &&
2778 !$this->isEmailConfirmed() &&
2779 $this->mEmailToken
&&
2780 $this->mEmailTokenExpires
> wfTimestamp();
2784 * Get the timestamp of account creation, or false for
2785 * non-existent/anonymous user accounts
2789 public function getRegistration() {
2790 return $this->mId
> 0
2791 ?
$this->mRegistration
2796 * @param array $groups list of groups
2797 * @return array list of permission key names for given groups combined
2799 static function getGroupPermissions( $groups ) {
2800 global $wgGroupPermissions;
2802 foreach( $groups as $group ) {
2803 if( isset( $wgGroupPermissions[$group] ) ) {
2804 $rights = array_merge( $rights,
2805 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2812 * @param string $group key name
2813 * @return string localized descriptive name for group, if provided
2815 static function getGroupName( $group ) {
2816 global $wgMessageCache;
2817 $wgMessageCache->loadAllMessages();
2818 $key = "group-$group";
2819 $name = wfMsg( $key );
2820 return $name == '' ||
wfEmptyMsg( $key, $name )
2826 * @param string $group key name
2827 * @return string localized descriptive name for member of a group, if provided
2829 static function getGroupMember( $group ) {
2830 global $wgMessageCache;
2831 $wgMessageCache->loadAllMessages();
2832 $key = "group-$group-member";
2833 $name = wfMsg( $key );
2834 return $name == '' ||
wfEmptyMsg( $key, $name )
2840 * Return the set of defined explicit groups.
2841 * The implicit groups (by default *, 'user' and 'autoconfirmed')
2842 * are not included, as they are defined automatically,
2843 * not in the database.
2846 static function getAllGroups() {
2847 global $wgGroupPermissions;
2849 array_keys( $wgGroupPermissions ),
2850 self
::getImplicitGroups()
2855 * Get a list of all available permissions
2857 static function getAllRights() {
2858 if ( self
::$mAllRights === false ) {
2859 global $wgAvailableRights;
2860 if ( count( $wgAvailableRights ) ) {
2861 self
::$mAllRights = array_unique( array_merge( self
::$mCoreRights, $wgAvailableRights ) );
2863 self
::$mAllRights = self
::$mCoreRights;
2865 wfRunHooks( 'UserGetAllRights', array( &self
::$mAllRights ) );
2867 return self
::$mAllRights;
2871 * Get a list of implicit groups
2875 public static function getImplicitGroups() {
2876 global $wgImplicitGroups;
2877 $groups = $wgImplicitGroups;
2878 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
2883 * Get the title of a page describing a particular group
2885 * @param $group Name of the group
2888 static function getGroupPage( $group ) {
2889 global $wgMessageCache;
2890 $wgMessageCache->loadAllMessages();
2891 $page = wfMsgForContent( 'grouppage-' . $group );
2892 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2893 $title = Title
::newFromText( $page );
2894 if( is_object( $title ) )
2901 * Create a link to the group in HTML, if available
2903 * @param $group Name of the group
2904 * @param $text The text of the link
2907 static function makeGroupLinkHTML( $group, $text = '' ) {
2909 $text = self
::getGroupName( $group );
2911 $title = self
::getGroupPage( $group );
2914 $sk = $wgUser->getSkin();
2915 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2922 * Create a link to the group in Wikitext, if available
2924 * @param $group Name of the group
2925 * @param $text The text of the link (by default, the name of the group)
2928 static function makeGroupLinkWiki( $group, $text = '' ) {
2930 $text = self
::getGroupName( $group );
2932 $title = self
::getGroupPage( $group );
2934 $page = $title->getPrefixedText();
2935 return "[[$page|$text]]";
2942 * Increment the user's edit-count field.
2943 * Will have no effect for anonymous users.
2945 function incEditCount() {
2946 if( !$this->isAnon() ) {
2947 $dbw = wfGetDB( DB_MASTER
);
2948 $dbw->update( 'user',
2949 array( 'user_editcount=user_editcount+1' ),
2950 array( 'user_id' => $this->getId() ),
2953 // Lazy initialization check...
2954 if( $dbw->affectedRows() == 0 ) {
2955 // Pull from a slave to be less cruel to servers
2956 // Accuracy isn't the point anyway here
2957 $dbr = wfGetDB( DB_SLAVE
);
2958 $count = $dbr->selectField( 'revision',
2960 array( 'rev_user' => $this->getId() ),
2963 // Now here's a goddamn hack...
2964 if( $dbr !== $dbw ) {
2965 // If we actually have a slave server, the count is
2966 // at least one behind because the current transaction
2967 // has not been committed and replicated.
2970 // But if DB_SLAVE is selecting the master, then the
2971 // count we just read includes the revision that was
2972 // just added in the working transaction.
2975 $dbw->update( 'user',
2976 array( 'user_editcount' => $count ),
2977 array( 'user_id' => $this->getId() ),
2981 // edit count in user cache too
2982 $this->invalidateCache();
2985 static function getRightDescription( $right ) {
2986 global $wgMessageCache;
2987 $wgMessageCache->loadAllMessages();
2988 $key = "right-$right";
2989 $name = wfMsg( $key );
2990 return $name == '' ||
wfEmptyMsg( $key, $name )
2996 * Make an old-style password hash
2998 * @param string $password Plain-text password
2999 * @param string $userId User ID
3001 static function oldCrypt( $password, $userId ) {
3002 global $wgPasswordSalt;
3003 if ( $wgPasswordSalt ) {
3004 return md5( $userId . '-' . md5( $password ) );
3006 return md5( $password );
3011 * Make a new-style password hash
3013 * @param string $password Plain-text password
3014 * @param string $salt Salt, may be random or the user ID. False to generate a salt.
3016 static function crypt( $password, $salt = false ) {
3017 global $wgPasswordSalt;
3019 if($wgPasswordSalt) {
3020 if ( $salt === false ) {
3021 $salt = substr( wfGenerateToken(), 0, 8 );
3023 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3025 return ':A:' . md5( $password);
3030 * Compare a password hash with a plain-text password. Requires the user
3031 * ID if there's a chance that the hash is an old-style hash.
3033 * @param string $hash Password hash
3034 * @param string $password Plain-text password to compare
3035 * @param string $userId User ID for old-style password salt
3037 static function comparePasswords( $hash, $password, $userId = false ) {
3039 $type = substr( $hash, 0, 3 );
3040 if ( $type == ':A:' ) {
3042 return md5( $password ) === substr( $hash, 3 );
3043 } elseif ( $type == ':B:' ) {
3045 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3046 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3049 return self
::oldCrypt( $password, $userId ) === $hash;