11 require_once( 'WatchedItem.php' );
13 # Number of characters in user_token field
14 define( 'USER_TOKEN_LENGTH', 32 );
16 # Serialized record version
17 define( 'MW_USER_VERSION', 2 );
27 var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
28 var $mEmailAuthenticated;
29 var $mRights, $mOptions;
30 var $mDataLoaded, $mNewpassword;
32 var $mBlockedby, $mBlockreason;
38 var $mVersion; // serialized version
40 /** Construct using User:loadDefaults() */
42 $this->loadDefaults();
43 $this->mVersion
= MW_USER_VERSION
;
47 * Static factory method
48 * @param string $name Username, validated by Title:newFromText()
52 function newFromName( $name ) {
55 # Force usernames to capital
57 $name = $wgContLang->ucfirst( $name );
59 # Clean up name according to title rules
60 $t = Title
::newFromText( $name );
65 # Reject various classes of invalid names
66 $canonicalName = $t->getText();
67 if( !User
::isValidUserName( $canonicalName ) ) {
71 $u->setName( $canonicalName );
72 $u->setId( $u->idFromName( $t->getText() ) );
77 * Factory method to fetch whichever use has a given email confirmation code.
78 * This code is generated when an account is created or its e-mail address
81 * If the code is invalid or has expired, returns NULL.
87 function newFromConfirmationCode( $code ) {
88 $dbr =& wfGetDB( DB_SLAVE
);
89 $name = $dbr->selectField( 'user', 'user_name', array(
90 'user_email_token' => md5( $code ),
91 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
93 if( is_string( $name ) ) {
94 return User
::newFromName( $name );
101 * Serialze sleep function, for better cache efficiency and avoidance of
102 * silly "incomplete type" errors when skins are cached
105 return array( 'mId', 'mName', 'mPassword', 'mEmail', 'mNewtalk',
106 'mEmailAuthenticated', 'mRights', 'mOptions', 'mDataLoaded',
107 'mNewpassword', 'mBlockedby', 'mBlockreason', 'mTouched',
108 'mToken', 'mRealName', 'mHash', 'mGroups' );
112 * Get username given an id.
113 * @param integer $id Database user id
114 * @return string Nickname of a user
117 function whoIs( $id ) {
118 $dbr =& wfGetDB( DB_SLAVE
);
119 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
123 * Get real username given an id.
124 * @param integer $id Database user id
125 * @return string Realname of a user
128 function whoIsReal( $id ) {
129 $dbr =& wfGetDB( DB_SLAVE
);
130 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
134 * Get database id given a user name
135 * @param string $name Nickname of a user
136 * @return integer|null Database user id (null: if non existent
139 function idFromName( $name ) {
140 $fname = "User::idFromName";
142 $nt = Title
::newFromText( $name );
143 if( is_null( $nt ) ) {
147 $dbr =& wfGetDB( DB_SLAVE
);
148 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
150 if ( $s === false ) {
158 * does the string match an anonymous IPv4 address?
161 * @param string $name Nickname of a user
164 function isIP( $name ) {
165 return preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/",$name);
166 /*return preg_match("/^
167 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
168 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
169 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
170 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
175 * Is the input a valid username?
177 * Checks if the input is a valid username, we don't want an empty string,
178 * an IP address, anything that containins slashes (would mess up subpages),
179 * is longer than the maximum allowed username size or doesn't begin with
182 * @param string $name
186 function isValidUserName( $name ) {
187 global $wgContLang, $wgMaxNameChars;
190 || User
::isIP( $name )
191 ||
strpos( $name, '/' ) !== false
192 ||
strlen( $name ) > $wgMaxNameChars
193 ||
$name != $wgContLang->ucfirst( $name ) )
200 * Is the input a valid password?
202 * @param string $password
206 function isValidPassword( $password ) {
207 global $wgMinimalPasswordLength;
208 return strlen( $password ) >= $wgMinimalPasswordLength;
212 * does the string match roughly an email address ?
214 * @todo Check for RFC 2822 compilance
217 * @param string $addr email address
221 function isValidEmailAddr ( $addr ) {
222 # There used to be a regular expression here, it got removed because it
223 # rejected valid addresses.
224 return ( trim( $addr ) != '' ) &&
225 (false !== strpos( $addr, '@' ) );
229 * probably return a random password
230 * @return string probably a random password
232 * @todo Check what is doing really [AV]
234 function randomPassword() {
235 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
236 $l = strlen( $pwchars ) - 1;
238 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
239 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
240 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
241 $pwchars{mt_rand( 0, $l )};
246 * Set properties to default
247 * Used at construction. It will load per language default settings only
248 * if we have an available language object.
250 function loadDefaults() {
253 $fname = 'User::loadDefaults' . $n;
254 wfProfileIn( $fname );
256 global $wgContLang, $wgIP, $wgDBname;
257 global $wgNamespacesToBeSearchedDefault;
260 $this->mNewtalk
= -1;
261 $this->mName
= $wgIP;
262 $this->mRealName
= $this->mEmail
= '';
263 $this->mEmailAuthenticated
= null;
264 $this->mPassword
= $this->mNewpassword
= '';
265 $this->mRights
= array();
266 $this->mGroups
= array();
267 $this->mOptions
= User
::getDefaultOptions();
269 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
270 $this->mOptions
['searchNs'.$nsnum] = $val;
272 unset( $this->mSkin
);
273 $this->mDataLoaded
= false;
274 $this->mBlockedby
= -1; # Unset
275 $this->setToken(); # Random
276 $this->mHash
= false;
278 if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
279 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgDBname.'LoggedOut'] );
282 $this->mTouched
= '0'; # Allow any pages to be cached
285 wfProfileOut( $fname );
289 * Combine the language default options with any site-specific options
290 * and add the default language variants.
296 function getDefaultOptions() {
298 * Site defaults will override the global/language defaults
300 global $wgContLang, $wgDefaultUserOptions;
301 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptions();
304 * default language setting
306 $variant = $wgContLang->getPreferredVariant();
307 $defOpt['variant'] = $variant;
308 $defOpt['language'] = $variant;
314 * Get a given default option value.
321 function getDefaultOption( $opt ) {
322 $defOpts = User
::getDefaultOptions();
323 if( isset( $defOpts[$opt] ) ) {
324 return $defOpts[$opt];
331 * Get blocking information
333 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
334 * non-critical checks are done against slaves. Check when actually saving should be done against
337 * Note that even if $bFromSlave is false, the check is done first against slave, then master.
338 * The logic is that if blocked on slave, we'll assume it's either blocked on master or
339 * just slightly outta sync and soon corrected - safer to block slightly more that less.
340 * And it's cheaper to check slave first, then master if needed, than master always.
342 function getBlockedStatus( $bFromSlave = true ) {
343 global $wgIP, $wgBlockCache, $wgProxyList, $wgEnableSorbs, $wgProxyWhitelist;
345 if ( -1 != $this->mBlockedby
) { return; }
347 $this->mBlockedby
= 0;
351 $block = new Block();
352 $block->forUpdate( $bFromSlave );
353 if ( $block->load( $wgIP , $this->mId
) ) {
354 $this->mBlockedby
= $block->mBy
;
355 $this->mBlockreason
= $block->mReason
;
356 $this->spreadBlock();
361 if ( !$this->mBlockedby
) {
362 # Check first against slave, and optionally from master.
363 $block = $wgBlockCache->get( $wgIP, true );
364 if ( !$block && !$bFromSlave )
366 # Not blocked: check against master, to make sure.
367 $wgBlockCache->clearLocal( );
368 $block = $wgBlockCache->get( $wgIP, false );
370 if ( $block !== false ) {
371 $this->mBlockedby
= $block->mBy
;
372 $this->mBlockreason
= $block->mReason
;
377 if ( !$this->isSysop() && !in_array( $wgIP, $wgProxyWhitelist ) ) {
380 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
381 $this->mBlockedby
= wfMsg( 'proxyblocker' );
382 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
386 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
387 if ( $this->inSorbsBlacklist( $wgIP ) ) {
388 $this->mBlockedby
= wfMsg( 'sorbs' );
389 $this->mBlockreason
= wfMsg( 'sorbsreason' );
395 function inSorbsBlacklist( $ip ) {
396 global $wgEnableSorbs;
397 return $wgEnableSorbs &&
398 $this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
401 function inOpmBlacklist( $ip ) {
403 return $wgEnableOpm &&
404 $this->inDnsBlacklist( $ip, 'opm.blitzed.org.' );
407 function inDnsBlacklist( $ip, $base ) {
408 $fname = 'User::inDnsBlacklist';
409 wfProfileIn( $fname );
414 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
416 for ( $i=4; $i>=1; $i-- ) {
417 $host .= $m[$i] . '.';
422 $ipList = gethostbynamel( $host );
425 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
428 wfDebug( "Requested $host, not found in $base.\n" );
432 wfProfileOut( $fname );
437 * Primitive rate limits: enforce maximum actions per time period
438 * to put a brake on flooding.
440 * Note: when using a shared cache like memcached, IP-address
441 * last-hit counters will be shared across wikis.
443 * @return bool true if a rate limiter was tripped
446 function pingLimiter( $action='edit' ) {
447 global $wgRateLimits;
448 if( !isset( $wgRateLimits[$action] ) ) {
451 if( $this->isAllowed( 'delete' ) ) {
456 global $wgMemc, $wgIP, $wgDBname, $wgRateLimitLog;
457 $fname = 'User::pingLimiter';
458 $limits = $wgRateLimits[$action];
460 $id = $this->getId();
462 if( isset( $limits['anon'] ) && $id == 0 ) {
463 $keys["$wgDBname:limiter:$action:anon"] = $limits['anon'];
466 if( isset( $limits['user'] ) && $id != 0 ) {
467 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['user'];
469 if( $this->isNewbie() ) {
470 if( isset( $limits['newbie'] ) && $id != 0 ) {
471 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['newbie'];
473 if( isset( $limits['ip'] ) ) {
474 $keys["mediawiki:limiter:$action:ip:$wgIP"] = $limits['ip'];
476 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $wgIP, $matches ) ) {
477 $subnet = $matches[1];
478 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
483 foreach( $keys as $key => $limit ) {
484 list( $max, $period ) = $limit;
485 $summary = "(limit $max in {$period}s)";
486 $count = $wgMemc->get( $key );
488 if( $count > $max ) {
489 wfDebug( "$fname: tripped! $key at $count $summary\n" );
490 if( $wgRateLimitLog ) {
491 @error_log
( wfTimestamp( TS_MW
) . ' ' . $wgDBname . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
495 wfDebug( "$fname: ok. $key at $count $summary\n" );
498 wfDebug( "$fname: adding record for $key $summary\n" );
499 $wgMemc->add( $key, 1, IntVal( $period ) );
501 $wgMemc->incr( $key );
508 * Check if user is blocked
509 * @return bool True if blocked, false otherwise
511 function isBlocked( $bFromSlave = false ) {
512 $this->getBlockedStatus( $bFromSlave );
513 return $this->mBlockedby
!== 0;
517 * Get name of blocker
518 * @return string name of blocker
520 function blockedBy() {
521 $this->getBlockedStatus();
522 return $this->mBlockedby
;
526 * Get blocking reason
527 * @return string Blocking reason
529 function blockedFor() {
530 $this->getBlockedStatus();
531 return $this->mBlockreason
;
535 * Initialise php session
537 function SetupSession() {
538 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
539 if( $wgSessionsInMemcached ) {
540 require_once( 'MemcachedSessions.php' );
541 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
542 # If it's left on 'user' or another setting from another
543 # application, it will end up failing. Try to recover.
544 ini_set ( 'session.save_handler', 'files' );
546 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
547 session_cache_limiter( 'private, must-revalidate' );
552 * Read datas from session
555 function loadFromSession() {
556 global $wgMemc, $wgDBname;
558 if ( isset( $_SESSION['wsUserID'] ) ) {
559 if ( 0 != $_SESSION['wsUserID'] ) {
560 $sId = $_SESSION['wsUserID'];
564 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
565 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
566 $_SESSION['wsUserID'] = $sId;
570 if ( isset( $_SESSION['wsUserName'] ) ) {
571 $sName = $_SESSION['wsUserName'];
572 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
573 $sName = $_COOKIE["{$wgDBname}UserName"];
574 $_SESSION['wsUserName'] = $sName;
579 $passwordCorrect = FALSE;
580 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
581 if( !is_object( $user ) ||
$user->mVersion
< MW_USER_VERSION
) {
582 # Expire old serialized objects; they may be corrupt.
585 if($makenew = !$user) {
586 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
589 $user->loadFromDatabase();
591 wfDebug( "User::loadFromSession() got from cache!\n" );
594 if ( isset( $_SESSION['wsToken'] ) ) {
595 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken
;
596 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
597 $passwordCorrect = $user->mToken
== $_COOKIE["{$wgDBname}Token"];
599 return new User(); # Can't log in from session
602 if ( ( $sName == $user->mName
) && $passwordCorrect ) {
604 if($wgMemc->set( $key, $user ))
605 wfDebug( "User::loadFromSession() successfully saved user\n" );
607 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
611 return new User(); # Can't log in from session
615 * Load a user from the database
617 function loadFromDatabase() {
618 global $wgCommandLineMode;
619 $fname = "User::loadFromDatabase";
621 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
622 # loading in a command line script, don't assume all command line scripts need it like this
623 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
624 if ( $this->mDataLoaded
) {
629 $this->mId
= IntVal( $this->mId
);
631 /** Anonymous user */
634 $this->mRights
= $this->getGroupPermissions( array( '*' ) );
635 $this->mDataLoaded
= true;
637 } # the following stuff is for non-anonymous users only
639 $dbr =& wfGetDB( DB_SLAVE
);
640 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
641 'user_email_authenticated',
642 'user_real_name','user_options','user_touched', 'user_token' ),
643 array( 'user_id' => $this->mId
), $fname );
645 if ( $s !== false ) {
646 $this->mName
= $s->user_name
;
647 $this->mEmail
= $s->user_email
;
648 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
649 $this->mRealName
= $s->user_real_name
;
650 $this->mPassword
= $s->user_password
;
651 $this->mNewpassword
= $s->user_newpassword
;
652 $this->decodeOptions( $s->user_options
);
653 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
654 $this->mToken
= $s->user_token
;
656 $res = $dbr->select( 'user_groups',
658 array( 'ug_user' => $this->mId
),
660 $this->mGroups
= array();
661 while( $row = $dbr->fetchObject( $res ) ) {
662 $this->mGroups
[] = $row->ug_group
;
664 $effectiveGroups = array_merge( array( '*', 'user' ), $this->mGroups
);
665 $this->mRights
= $this->getGroupPermissions( $effectiveGroups );
668 $this->mDataLoaded
= true;
671 function getID() { return $this->mId
; }
672 function setID( $v ) {
674 $this->mDataLoaded
= false;
678 $this->loadFromDatabase();
682 function setName( $str ) {
683 $this->loadFromDatabase();
689 * Return the title dbkey form of the name, for eg user pages.
693 function getTitleKey() {
694 return str_replace( ' ', '_', $this->getName() );
697 function getNewtalk() {
699 $fname = 'User::getNewtalk';
700 $this->loadFromDatabase();
702 # Load the newtalk status if it is unloaded (mNewtalk=-1)
703 if( $this->mNewtalk
== -1 ) {
704 $this->mNewtalk
= 0; # reset talk page status
706 # Check memcached separately for anons, who have no
707 # entire User object stored in there.
709 global $wgDBname, $wgMemc;
710 $key = "$wgDBname:newtalk:ip:{$this->mName}";
711 $newtalk = $wgMemc->get( $key );
712 if( is_integer( $newtalk ) ) {
713 $this->mNewtalk
= $newtalk ?
1 : 0;
714 return (bool)$this->mNewtalk
;
718 $dbr =& wfGetDB( DB_SLAVE
);
719 if ( $wgUseEnotif ) {
720 $res = $dbr->select( 'watchlist',
722 array( 'wl_title' => $this->getTitleKey(),
723 'wl_namespace' => NS_USER_TALK
,
724 'wl_user' => $this->mId
,
725 'wl_notificationtimestamp != 0' ),
726 'User::getNewtalk' );
727 if( $dbr->numRows($res) > 0 ) {
730 $dbr->freeResult( $res );
731 } elseif ( $this->mId
) {
732 $res = $dbr->select( 'user_newtalk', 1, array( 'user_id' => $this->mId
), $fname );
734 if ( $dbr->numRows($res)>0 ) {
737 $dbr->freeResult( $res );
739 $res = $dbr->select( 'user_newtalk', 1, array( 'user_ip' => $this->mName
), $fname );
740 $this->mNewtalk
= $dbr->numRows( $res ) > 0 ?
1 : 0;
741 $dbr->freeResult( $res );
745 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
749 return ( 0 != $this->mNewtalk
);
752 function setNewtalk( $val ) {
753 $this->loadFromDatabase();
754 $this->mNewtalk
= $val;
755 $this->invalidateCache();
758 function invalidateCache() {
759 global $wgClockSkewFudge;
760 $this->loadFromDatabase();
761 $this->mTouched
= wfTimestamp(TS_MW
, time() +
$wgClockSkewFudge );
762 # Don't forget to save the options after this or
763 # it won't take effect!
766 function validateCache( $timestamp ) {
767 $this->loadFromDatabase();
768 return ($timestamp >= $this->mTouched
);
773 * Will only be salted if $wgPasswordSalt is true
774 * @param string Password.
775 * @return string Salted password or clear password.
777 function addSalt( $p ) {
778 global $wgPasswordSalt;
780 return md5( "{$this->mId}-{$p}" );
786 * Encrypt a password.
787 * It can eventuall salt a password @see User::addSalt()
788 * @param string $p clear Password.
789 * @param string Encrypted password.
791 function encryptPassword( $p ) {
792 return $this->addSalt( md5( $p ) );
795 # Set the password and reset the random token
796 function setPassword( $str ) {
797 $this->loadFromDatabase();
799 $this->mPassword
= $this->encryptPassword( $str );
800 $this->mNewpassword
= '';
803 # Set the random token (used for persistent authentication)
804 function setToken( $token = false ) {
805 global $wgSecretKey, $wgProxyKey, $wgDBname;
807 if ( $wgSecretKey ) {
809 } elseif ( $wgProxyKey ) {
814 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId
);
816 $this->mToken
= $token;
821 function setCookiePassword( $str ) {
822 $this->loadFromDatabase();
823 $this->mCookiePassword
= md5( $str );
826 function setNewpassword( $str ) {
827 $this->loadFromDatabase();
828 $this->mNewpassword
= $this->encryptPassword( $str );
831 function getEmail() {
832 $this->loadFromDatabase();
833 return $this->mEmail
;
836 function getEmailAuthenticationTimestamp() {
837 $this->loadFromDatabase();
838 return $this->mEmailAuthenticated
;
841 function setEmail( $str ) {
842 $this->loadFromDatabase();
843 $this->mEmail
= $str;
846 function getRealName() {
847 $this->loadFromDatabase();
848 return $this->mRealName
;
851 function setRealName( $str ) {
852 $this->loadFromDatabase();
853 $this->mRealName
= $str;
856 function getOption( $oname ) {
857 $this->loadFromDatabase();
858 if ( array_key_exists( $oname, $this->mOptions
) ) {
859 return trim( $this->mOptions
[$oname] );
865 function setOption( $oname, $val ) {
866 $this->loadFromDatabase();
867 if ( $oname == 'skin' ) {
868 # Clear cached skin, so the new one displays immediately in Special:Preferences
869 unset( $this->mSkin
);
871 $this->mOptions
[$oname] = $val;
872 $this->invalidateCache();
875 function getRights() {
876 $this->loadFromDatabase();
877 return $this->mRights
;
881 * Get the list of explicit group memberships this user has.
882 * The implicit * and user groups are not included.
883 * @return array of strings
885 function getGroups() {
886 $this->loadFromDatabase();
887 return $this->mGroups
;
891 * Get the list of implicit group memberships this user has.
892 * This includes all explicit groups, plus 'user' if logged in
893 * and '*' for all accounts.
894 * @return array of strings
896 function getEffectiveGroups() {
897 $base = array( '*' );
898 if( $this->isLoggedIn() ) {
901 return array_merge( $base, $this->getGroups() );
905 * Remove the user from the given group.
906 * This takes immediate effect.
909 function addGroup( $group ) {
910 $dbw =& wfGetDB( DB_MASTER
);
911 $dbw->insert( 'user_groups',
913 'ug_user' => $this->getID(),
914 'ug_group' => $group,
919 $this->mGroups
= array_merge( $this->mGroups
, array( $group ) );
920 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups() );
922 $this->invalidateCache();
923 $this->saveSettings();
927 * Remove the user from the given group.
928 * This takes immediate effect.
931 function removeGroup( $group ) {
932 $dbw =& wfGetDB( DB_MASTER
);
933 $dbw->delete( 'user_groups',
935 'ug_user' => $this->getID(),
936 'ug_group' => $group,
938 'User::removeGroup' );
940 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
941 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups() );
943 $this->invalidateCache();
944 $this->saveSettings();
949 * A more legible check for non-anonymousness.
950 * Returns true if the user is not an anonymous visitor.
954 function isLoggedIn() {
955 return( $this->getID() != 0 );
959 * A more legible check for anonymousness.
960 * Returns true if the user is an anonymous visitor.
965 return !$this->isLoggedIn();
969 * Check if a user is sysop
970 * Die with backtrace. Use User:isAllowed() instead.
974 return $this->isAllowed( 'protect' );
978 function isDeveloper() {
979 return $this->isAllowed( 'siteadmin' );
983 function isBureaucrat() {
984 return $this->isAllowed( 'makesysop' );
988 * Whether the user is a bot
989 * @todo need to be migrated to the new user level management sytem
992 $this->loadFromDatabase();
993 return in_array( 'bot', $this->mRights
);
997 * Check if user is allowed to access a feature / make an action
998 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
999 * @return boolean True: action is allowed, False: action should not be allowed
1001 function isAllowed($action='') {
1002 $this->loadFromDatabase();
1003 return in_array( $action , $this->mRights
);
1007 * Load a skin if it doesn't exist or return it
1008 * @todo FIXME : need to check the old failback system [AV]
1010 function &getSkin() {
1012 if ( ! isset( $this->mSkin
) ) {
1013 $fname = 'User::getSkin';
1014 wfProfileIn( $fname );
1016 # get all skin names available
1017 $skinNames = Skin
::getSkinNames();
1020 $userSkin = $this->getOption( 'skin' );
1021 if ( $userSkin == '' ) { $userSkin = 'standard'; }
1023 if ( !isset( $skinNames[$userSkin] ) ) {
1024 # in case the user skin could not be found find a replacement
1028 2 => 'CologneBlue');
1029 # if phptal is enabled we should have monobook skin that
1030 # superseed the good old SkinStandard.
1031 if ( isset( $skinNames['monobook'] ) ) {
1032 $fallback[0] = 'MonoBook';
1035 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
1036 $sn = $fallback[$userSkin];
1041 # The user skin is available
1042 $sn = $skinNames[$userSkin];
1045 # Grab the skin class and initialise it. Each skin checks for PHPTal
1046 # and will not load if it's not enabled.
1047 require_once( $IP.'/skins/'.$sn.'.php' );
1049 # Check if we got if not failback to default skin
1050 $className = 'Skin'.$sn;
1051 if( !class_exists( $className ) ) {
1052 # DO NOT die if the class isn't found. This breaks maintenance
1053 # scripts and can cause a user account to be unrecoverable
1054 # except by SQL manipulation if a previously valid skin name
1055 # is no longer valid.
1056 $className = 'SkinStandard';
1057 require_once( $IP.'/skins/Standard.php' );
1059 $this->mSkin
=& new $className;
1060 wfProfileOut( $fname );
1062 return $this->mSkin
;
1066 * @param string $title Article title to look at
1070 * Check watched status of an article
1071 * @return bool True if article is watched
1073 function isWatched( $title ) {
1074 $wl = WatchedItem
::fromUserTitle( $this, $title );
1075 return $wl->isWatched();
1081 function addWatch( $title ) {
1082 $wl = WatchedItem
::fromUserTitle( $this, $title );
1084 $this->invalidateCache();
1088 * Stop watching an article
1090 function removeWatch( $title ) {
1091 $wl = WatchedItem
::fromUserTitle( $this, $title );
1093 $this->invalidateCache();
1097 * Clear the user's notification timestamp for the given title.
1098 * If e-notif e-mails are on, they will receive notification mails on
1099 * the next change of the page if it's watched etc.
1101 function clearNotification( &$title ) {
1102 global $wgUser, $wgUseEnotif;
1104 if ( !$wgUseEnotif ) {
1108 $userid = $this->getID();
1113 // Only update the timestamp if the page is being watched.
1114 // The query to find out if it is watched is cached both in memcached and per-invocation,
1115 // and when it does have to be executed, it can be on a slave
1116 // If this is the user's newtalk page, we always update the timestamp
1117 if ($title->getNamespace() == NS_USER_TALK
&&
1118 $title->getText() == $wgUser->getName())
1121 } elseif ( $this->getID() == $wgUser->getID() ) {
1122 $watched = $title->userIsWatching();
1127 // If the page is watched by the user (or may be watched), update the timestamp on any
1128 // any matching rows
1130 $dbw =& wfGetDB( DB_MASTER
);
1131 $success = $dbw->update( 'watchlist',
1133 'wl_notificationtimestamp' => 0
1134 ), array( /* WHERE */
1135 'wl_title' => $title->getDBkey(),
1136 'wl_namespace' => $title->getNamespace(),
1137 'wl_user' => $this->getID()
1138 ), 'User::clearLastVisited'
1146 * Resets all of the given user's page-change notification timestamps.
1147 * If e-notif e-mails are on, they will receive notification mails on
1148 * the next change of any watched page.
1150 * @param int $currentUser user ID number
1153 function clearAllNotifications( $currentUser ) {
1154 global $wgUseEnotif;
1155 if ( !$wgUseEnotif ) {
1158 if( $currentUser != 0 ) {
1160 $dbw =& wfGetDB( DB_MASTER
);
1161 $success = $dbw->update( 'watchlist',
1163 'wl_notificationtimestamp' => 0
1164 ), array( /* WHERE */
1165 'wl_user' => $currentUser
1166 ), 'UserMailer::clearAll'
1169 # we also need to clear here the "you have new message" notification for the own user_talk page
1170 # This is cleared one page view later in Article::viewUpdates();
1176 * @return string Encoding options
1178 function encodeOptions() {
1180 foreach ( $this->mOptions
as $oname => $oval ) {
1181 array_push( $a, $oname.'='.$oval );
1183 $s = implode( "\n", $a );
1190 function decodeOptions( $str ) {
1191 $a = explode( "\n", $str );
1192 foreach ( $a as $s ) {
1193 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1194 $this->mOptions
[$m[1]] = $m[2];
1199 function setCookies() {
1200 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
1201 if ( 0 == $this->mId
) return;
1202 $this->loadFromDatabase();
1203 $exp = time() +
$wgCookieExpiration;
1205 $_SESSION['wsUserID'] = $this->mId
;
1206 setcookie( $wgDBname.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain );
1208 $_SESSION['wsUserName'] = $this->mName
;
1209 setcookie( $wgDBname.'UserName', $this->mName
, $exp, $wgCookiePath, $wgCookieDomain );
1211 $_SESSION['wsToken'] = $this->mToken
;
1212 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1213 setcookie( $wgDBname.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain );
1215 setcookie( $wgDBname.'Token', '', time() - 3600 );
1221 * It will clean the session cookie
1224 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
1225 $this->loadDefaults();
1226 $this->setLoaded( true );
1228 $_SESSION['wsUserID'] = 0;
1230 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1231 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1233 # Remember when user logged out, to prevent seeing cached pages
1234 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain );
1238 * Save object settings into database
1240 function saveSettings() {
1241 global $wgMemc, $wgDBname, $wgUseEnotif;
1242 $fname = 'User::saveSettings';
1244 if ( wfReadOnly() ) { return; }
1245 $this->saveNewtalk();
1246 if ( 0 == $this->mId
) { return; }
1248 $dbw =& wfGetDB( DB_MASTER
);
1249 $dbw->update( 'user',
1251 'user_name' => $this->mName
,
1252 'user_password' => $this->mPassword
,
1253 'user_newpassword' => $this->mNewpassword
,
1254 'user_real_name' => $this->mRealName
,
1255 'user_email' => $this->mEmail
,
1256 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1257 'user_options' => $this->encodeOptions(),
1258 'user_touched' => $dbw->timestamp($this->mTouched
),
1259 'user_token' => $this->mToken
1260 ), array( /* WHERE */
1261 'user_id' => $this->mId
1264 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1268 * Save value of new talk flag.
1270 function saveNewtalk() {
1271 global $wgDBname, $wgMemc, $wgUseEnotif;
1273 $fname = 'User::saveNewtalk';
1277 if ( wfReadOnly() ) { return ; }
1278 $dbr =& wfGetDB( DB_SLAVE
);
1279 $dbw =& wfGetDB( DB_MASTER
);
1281 if ( $wgUseEnotif ) {
1282 if ( ! $this->getNewtalk() ) {
1283 # Delete the watchlist entry for user_talk page X watched by user X
1284 $dbw->delete( 'watchlist',
1285 array( 'wl_user' => $this->mId
,
1286 'wl_title' => $this->getTitleKey(),
1287 'wl_namespace' => NS_USER_TALK
),
1289 if ( $dbw->affectedRows() ) {
1293 # Anon users have a separate memcache space for newtalk
1294 # since they don't store their own info. Trim...
1295 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1299 if ($this->getID() != 0) {
1301 $value = $this->getID();
1305 $value = $this->mName
;
1306 $key = "$wgDBname:newtalk:ip:$this->mName";
1309 $dbr =& wfGetDB( DB_SLAVE
);
1310 $dbw =& wfGetDB( DB_MASTER
);
1312 $res = $dbr->selectField('user_newtalk', $field,
1313 array($field => $value), $fname);
1316 if ($res !== false && $this->mNewtalk
== 0) {
1317 $dbw->delete('user_newtalk', array($field => $value), $fname);
1319 $wgMemc->set( $key, 0 );
1321 } else if ($res === false && $this->mNewtalk
== 1) {
1322 $dbw->insert('user_newtalk', array($field => $value), $fname);
1324 $wgMemc->set( $key, 1 );
1331 # Update user_touched, so that newtalk notifications in the client cache are invalidated
1332 if ( $changed && $this->getID() ) {
1333 $dbw->update('user',
1334 /*SET*/ array( 'user_touched' => $this->mTouched
),
1335 /*WHERE*/ array( 'user_id' => $this->getID() ),
1337 $wgMemc->set( "$wgDBname:user:id:{$this->mId}", $this, 86400 );
1342 * Checks if a user with the given name exists, returns the ID
1344 function idForName() {
1345 $fname = 'User::idForName';
1348 $s = trim( $this->mName
);
1349 if ( 0 == strcmp( '', $s ) ) return 0;
1351 $dbr =& wfGetDB( DB_SLAVE
);
1352 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1353 if ( $id === false ) {
1360 * Add user object to the database
1362 function addToDatabase() {
1363 $fname = 'User::addToDatabase';
1364 $dbw =& wfGetDB( DB_MASTER
);
1365 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1366 $dbw->insert( 'user',
1368 'user_id' => $seqVal,
1369 'user_name' => $this->mName
,
1370 'user_password' => $this->mPassword
,
1371 'user_newpassword' => $this->mNewpassword
,
1372 'user_email' => $this->mEmail
,
1373 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1374 'user_real_name' => $this->mRealName
,
1375 'user_options' => $this->encodeOptions(),
1376 'user_token' => $this->mToken
1379 $this->mId
= $dbw->insertId();
1382 function spreadBlock() {
1384 # If the (non-anonymous) user is blocked, this function will block any IP address
1385 # that they successfully log on from.
1386 $fname = 'User::spreadBlock';
1388 wfDebug( "User:spreadBlock()\n" );
1389 if ( $this->mId
== 0 ) {
1393 $userblock = Block
::newFromDB( '', $this->mId
);
1394 if ( !$userblock->isValid() ) {
1398 # Check if this IP address is already blocked
1399 $ipblock = Block
::newFromDB( $wgIP );
1400 if ( $ipblock->isValid() ) {
1401 # Just update the timestamp
1402 $ipblock->updateTimestamp();
1406 # Make a new block object with the desired properties
1407 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1408 $ipblock->mAddress
= $wgIP;
1409 $ipblock->mUser
= 0;
1410 $ipblock->mBy
= $userblock->mBy
;
1411 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
1412 $ipblock->mTimestamp
= wfTimestampNow();
1413 $ipblock->mAuto
= 1;
1414 # If the user is already blocked with an expiry date, we don't
1415 # want to pile on top of that!
1416 if($userblock->mExpiry
) {
1417 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
1419 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
1427 function getPageRenderingHash() {
1430 return $this->mHash
;
1433 // stubthreshold is only included below for completeness,
1434 // it will always be 0 when this function is called by parsercache.
1436 $confstr = $this->getOption( 'math' );
1437 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1438 $confstr .= '!' . $this->getOption( 'editsection' );
1439 $confstr .= '!' . $this->getOption( 'date' );
1440 $confstr .= '!' . $this->getOption( 'numberheadings' );
1441 $confstr .= '!' . $this->getOption( 'language' );
1442 $confstr .= '!' . $this->getOption( 'thumbsize' );
1443 // add in language specific options, if any
1444 $extra = $wgContLang->getExtraHashOptions();
1447 $this->mHash
= $confstr;
1451 function isAllowedToCreateAccount() {
1452 return $this->isAllowed( 'createaccount' );
1456 * Set mDataLoaded, return previous value
1457 * Use this to prevent DB access in command-line scripts or similar situations
1459 function setLoaded( $loaded ) {
1460 return wfSetVar( $this->mDataLoaded
, $loaded );
1464 * Get this user's personal page title.
1469 function getUserPage() {
1470 return Title
::makeTitle( NS_USER
, $this->mName
);
1474 * Get this user's talk page title.
1479 function getTalkPage() {
1480 $title = $this->getUserPage();
1481 return $title->getTalkPage();
1487 function getMaxID() {
1488 $dbr =& wfGetDB( DB_SLAVE
);
1489 return $dbr->selectField( 'user', 'max(user_id)', false );
1493 * Determine whether the user is a newbie. Newbies are either
1494 * anonymous IPs, or the 1% most recently created accounts.
1495 * Bots and sysops are excluded.
1496 * @return bool True if it is a newbie.
1498 function isNewbie() {
1499 return $this->isAnon() ||
$this->mId
> User
::getMaxID() * 0.99 && !$this->isAllowed( 'delete' ) && !$this->isBot();
1503 * Check to see if the given clear-text password is one of the accepted passwords
1504 * @param string $password User password.
1505 * @return bool True if the given password is correct otherwise False.
1507 function checkPassword( $password ) {
1508 global $wgAuth, $wgMinimalPasswordLength;
1509 $this->loadFromDatabase();
1511 // Even though we stop people from creating passwords that
1512 // are shorter than this, doesn't mean people wont be able
1513 // to. Certain authentication plugins do NOT want to save
1514 // domain passwords in a mysql database, so we should
1515 // check this (incase $wgAuth->strict() is false).
1516 if( strlen( $password ) < $wgMinimalPasswordLength ) {
1520 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1522 } elseif( $wgAuth->strict() ) {
1523 /* Auth plugin doesn't allow local authentication */
1526 $ep = $this->encryptPassword( $password );
1527 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
1529 } elseif ( ($this->mNewpassword
!= '') && (0 == strcmp( $ep, $this->mNewpassword
)) ) {
1531 } elseif ( function_exists( 'iconv' ) ) {
1532 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1533 # Check for this with iconv
1534 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1535 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
1543 * Initialize (if necessary) and return a session token value
1544 * which can be used in edit forms to show that the user's
1545 * login credentials aren't being hijacked with a foreign form
1548 * @param mixed $salt - Optional function-specific data for hash.
1549 * Use a string or an array of strings.
1553 function editToken( $salt = '' ) {
1554 if( !isset( $_SESSION['wsEditToken'] ) ) {
1555 $token = $this->generateToken();
1556 $_SESSION['wsEditToken'] = $token;
1558 $token = $_SESSION['wsEditToken'];
1560 if( is_array( $salt ) ) {
1561 $salt = implode( '|', $salt );
1563 return md5( $token . $salt );
1567 * Generate a hex-y looking random token for various uses.
1568 * Could be made more cryptographically sure if someone cares.
1571 function generateToken( $salt = '' ) {
1572 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1573 return md5( $token . $salt );
1577 * Check given value against the token value stored in the session.
1578 * A match should confirm that the form was submitted from the
1579 * user's own login session, not a form submission from a third-party
1582 * @param string $val - the input value to compare
1583 * @param string $salt - Optional function-specific data for hash
1587 function matchEditToken( $val, $salt = '' ) {
1588 return ( $val == $this->editToken( $salt ) );
1592 * Generate a new e-mail confirmation token and send a confirmation
1593 * mail to the user's given address.
1595 * @return mixed True on success, a WikiError object on failure.
1597 function sendConfirmationMail() {
1598 global $wgIP, $wgContLang;
1599 $url = $this->confirmationTokenUrl( $expiration );
1600 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1601 wfMsg( 'confirmemail_body',
1605 $wgContLang->timeanddate( $expiration, false ) ) );
1609 * Send an e-mail to this user's account. Does not check for
1610 * confirmed status or validity.
1612 * @param string $subject
1613 * @param string $body
1614 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1615 * @return mixed True on success, a WikiError object on failure.
1617 function sendMail( $subject, $body, $from = null ) {
1618 if( is_null( $from ) ) {
1619 global $wgPasswordSender;
1620 $from = $wgPasswordSender;
1623 require_once( 'UserMailer.php' );
1624 $error = userMailer( $this->getEmail(), $from, $subject, $body );
1626 if( $error == '' ) {
1629 return new WikiError( $error );
1634 * Generate, store, and return a new e-mail confirmation code.
1635 * A hash (unsalted since it's used as a key) is stored.
1636 * @param &$expiration mixed output: accepts the expiration time
1640 function confirmationToken( &$expiration ) {
1641 $fname = 'User::confirmationToken';
1644 $expires = $now +
7 * 24 * 60 * 60;
1645 $expiration = wfTimestamp( TS_MW
, $expires );
1647 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
1648 $hash = md5( $token );
1650 $dbw =& wfGetDB( DB_MASTER
);
1651 $dbw->update( 'user',
1652 array( 'user_email_token' => $hash,
1653 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1654 array( 'user_id' => $this->mId
),
1661 * Generate and store a new e-mail confirmation token, and return
1662 * the URL the user can use to confirm.
1663 * @param &$expiration mixed output: accepts the expiration time
1667 function confirmationTokenUrl( &$expiration ) {
1668 $token = $this->confirmationToken( $expiration );
1669 $title = Title
::makeTitle( NS_SPECIAL
, 'Confirmemail/' . $token );
1670 return $title->getFullUrl();
1674 * Mark the e-mail address confirmed and save.
1676 function confirmEmail() {
1677 $this->loadFromDatabase();
1678 $this->mEmailAuthenticated
= wfTimestampNow();
1679 $this->saveSettings();
1684 * Is this user allowed to send e-mails within limits of current
1685 * site configuration?
1688 function canSendEmail() {
1689 return $this->isEmailConfirmed();
1693 * Is this user allowed to receive e-mails within limits of current
1694 * site configuration?
1697 function canReceiveEmail() {
1698 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1702 * Is this user's e-mail address valid-looking and confirmed within
1703 * limits of the current site configuration?
1705 * If $wgEmailAuthentication is on, this may require the user to have
1706 * confirmed their address by returning a code or using a password
1707 * sent to the address from the wiki.
1711 function isEmailConfirmed() {
1712 global $wgEmailAuthentication;
1713 $this->loadFromDatabase();
1714 if( $this->isAnon() )
1716 if( !$this->isValidEmailAddr( $this->mEmail
) )
1718 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
1724 * @param array $groups list of groups
1725 * @return array list of permission key names for given groups combined
1728 function getGroupPermissions( $groups ) {
1729 global $wgGroupPermissions;
1731 foreach( $groups as $group ) {
1732 if( isset( $wgGroupPermissions[$group] ) ) {
1733 $rights = array_merge( $rights,
1734 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
1741 * @param string $group key name
1742 * @return string localized descriptive name, if provided
1745 function getGroupName( $group ) {
1746 $key = "group-$group-name";
1747 $name = wfMsg( $key );
1748 if( $name == '' ||
$name == "<$key>" ) {
1756 * Return the set of defined explicit groups.
1757 * The * and 'user' groups are not included.
1761 function getAllGroups() {
1762 global $wgGroupPermissions;
1764 array_keys( $wgGroupPermissions ),
1765 array( '*', 'user' ) );