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();
68 $canonicalName = $wgAuth->getCanonicalName( $t->getText() );
70 if( !User
::isValidUserName( $canonicalName ) ) {
74 $u->setName( $canonicalName );
75 $u->setId( $u->idFromName( $canonicalName ) );
80 * Factory method to fetch whichever use has a given email confirmation code.
81 * This code is generated when an account is created or its e-mail address
84 * If the code is invalid or has expired, returns NULL.
90 function newFromConfirmationCode( $code ) {
91 $dbr =& wfGetDB( DB_SLAVE
);
92 $name = $dbr->selectField( 'user', 'user_name', array(
93 'user_email_token' => md5( $code ),
94 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
96 if( is_string( $name ) ) {
97 return User
::newFromName( $name );
104 * Serialze sleep function, for better cache efficiency and avoidance of
105 * silly "incomplete type" errors when skins are cached
108 return array( 'mId', 'mName', 'mPassword', 'mEmail', 'mNewtalk',
109 'mEmailAuthenticated', 'mRights', 'mOptions', 'mDataLoaded',
110 'mNewpassword', 'mBlockedby', 'mBlockreason', 'mTouched',
111 'mToken', 'mRealName', 'mHash', 'mGroups' );
115 * Get username given an id.
116 * @param integer $id Database user id
117 * @return string Nickname of a user
120 function whoIs( $id ) {
121 $dbr =& wfGetDB( DB_SLAVE
);
122 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
126 * Get real username given an id.
127 * @param integer $id Database user id
128 * @return string Realname of a user
131 function whoIsReal( $id ) {
132 $dbr =& wfGetDB( DB_SLAVE
);
133 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
137 * Get database id given a user name
138 * @param string $name Nickname of a user
139 * @return integer|null Database user id (null: if non existent
142 function idFromName( $name ) {
143 $fname = "User::idFromName";
145 $nt = Title
::newFromText( $name );
146 if( is_null( $nt ) ) {
150 $dbr =& wfGetDB( DB_SLAVE
);
151 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
153 if ( $s === false ) {
161 * does the string match an anonymous IPv4 address?
164 * @param string $name Nickname of a user
167 function isIP( $name ) {
168 return preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/",$name);
169 /*return preg_match("/^
170 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
171 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
172 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
173 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
178 * Is the input a valid username?
180 * Checks if the input is a valid username, we don't want an empty string,
181 * an IP address, anything that containins slashes (would mess up subpages),
182 * is longer than the maximum allowed username size or doesn't begin with
185 * @param string $name
189 function isValidUserName( $name ) {
190 global $wgContLang, $wgMaxNameChars;
193 || User
::isIP( $name )
194 ||
strpos( $name, '/' ) !== false
195 ||
strlen( $name ) > $wgMaxNameChars
196 ||
$name != $wgContLang->ucfirst( $name ) )
203 * Is the input a valid password?
205 * @param string $password
209 function isValidPassword( $password ) {
210 global $wgMinimalPasswordLength;
211 return strlen( $password ) >= $wgMinimalPasswordLength;
215 * does the string match roughly an email address ?
217 * @todo Check for RFC 2822 compilance
220 * @param string $addr email address
224 function isValidEmailAddr ( $addr ) {
225 # There used to be a regular expression here, it got removed because it
226 # rejected valid addresses.
227 return ( trim( $addr ) != '' ) &&
228 (false !== strpos( $addr, '@' ) );
232 * Count the number of edits of a user
234 * @param int $uid The user ID to check
237 function edits( $uid ) {
238 $fname = 'User::editCount';
240 $dbr =& wfGetDB( DB_SLAVE
);
241 return $dbr->selectField(
242 'revision', 'count(*)',
243 array( 'rev_user' => $uid ),
249 * probably return a random password
250 * @return string probably a random password
252 * @todo Check what is doing really [AV]
254 function randomPassword() {
255 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
256 $l = strlen( $pwchars ) - 1;
258 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
259 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
260 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
261 $pwchars{mt_rand( 0, $l )};
266 * Set properties to default
267 * Used at construction. It will load per language default settings only
268 * if we have an available language object.
270 function loadDefaults() {
273 $fname = 'User::loadDefaults' . $n;
274 wfProfileIn( $fname );
276 global $wgContLang, $wgIP, $wgDBname;
277 global $wgNamespacesToBeSearchedDefault;
280 $this->mNewtalk
= -1;
281 $this->mName
= $wgIP;
282 $this->mRealName
= $this->mEmail
= '';
283 $this->mEmailAuthenticated
= null;
284 $this->mPassword
= $this->mNewpassword
= '';
285 $this->mRights
= array();
286 $this->mGroups
= array();
287 $this->mOptions
= User
::getDefaultOptions();
289 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
290 $this->mOptions
['searchNs'.$nsnum] = $val;
292 unset( $this->mSkin
);
293 $this->mDataLoaded
= false;
294 $this->mBlockedby
= -1; # Unset
295 $this->setToken(); # Random
296 $this->mHash
= false;
298 if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
299 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgDBname.'LoggedOut'] );
302 $this->mTouched
= '0'; # Allow any pages to be cached
305 wfProfileOut( $fname );
309 * Combine the language default options with any site-specific options
310 * and add the default language variants.
316 function getDefaultOptions() {
318 * Site defaults will override the global/language defaults
320 global $wgContLang, $wgDefaultUserOptions;
321 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptions();
324 * default language setting
326 $variant = $wgContLang->getPreferredVariant();
327 $defOpt['variant'] = $variant;
328 $defOpt['language'] = $variant;
334 * Get a given default option value.
341 function getDefaultOption( $opt ) {
342 $defOpts = User
::getDefaultOptions();
343 if( isset( $defOpts[$opt] ) ) {
344 return $defOpts[$opt];
351 * Get blocking information
353 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
354 * non-critical checks are done against slaves. Check when actually saving should be done against
357 * Note that even if $bFromSlave is false, the check is done first against slave, then master.
358 * The logic is that if blocked on slave, we'll assume it's either blocked on master or
359 * just slightly outta sync and soon corrected - safer to block slightly more that less.
360 * And it's cheaper to check slave first, then master if needed, than master always.
362 function getBlockedStatus( $bFromSlave = true ) {
363 global $wgIP, $wgBlockCache, $wgProxyList, $wgEnableSorbs, $wgProxyWhitelist;
365 if ( -1 != $this->mBlockedby
) { return; }
367 $this->mBlockedby
= 0;
371 $block = new Block();
372 $block->forUpdate( $bFromSlave );
373 if ( $block->load( $wgIP , $this->mId
) ) {
374 $this->mBlockedby
= $block->mBy
;
375 $this->mBlockreason
= $block->mReason
;
376 $this->spreadBlock();
381 if ( !$this->mBlockedby
) {
382 # Check first against slave, and optionally from master.
383 $block = $wgBlockCache->get( $wgIP, true );
384 if ( !$block && !$bFromSlave )
386 # Not blocked: check against master, to make sure.
387 $wgBlockCache->clearLocal( );
388 $block = $wgBlockCache->get( $wgIP, false );
390 if ( $block !== false ) {
391 $this->mBlockedby
= $block->mBy
;
392 $this->mBlockreason
= $block->mReason
;
397 if ( !$this->isSysop() && !in_array( $wgIP, $wgProxyWhitelist ) ) {
400 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
401 $this->mBlockedby
= wfMsg( 'proxyblocker' );
402 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
406 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
407 if ( $this->inSorbsBlacklist( $wgIP ) ) {
408 $this->mBlockedby
= wfMsg( 'sorbs' );
409 $this->mBlockreason
= wfMsg( 'sorbsreason' );
415 function inSorbsBlacklist( $ip ) {
416 global $wgEnableSorbs;
417 return $wgEnableSorbs &&
418 $this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
421 function inOpmBlacklist( $ip ) {
423 return $wgEnableOpm &&
424 $this->inDnsBlacklist( $ip, 'opm.blitzed.org.' );
427 function inDnsBlacklist( $ip, $base ) {
428 $fname = 'User::inDnsBlacklist';
429 wfProfileIn( $fname );
434 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
436 for ( $i=4; $i>=1; $i-- ) {
437 $host .= $m[$i] . '.';
442 $ipList = gethostbynamel( $host );
445 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
448 wfDebug( "Requested $host, not found in $base.\n" );
452 wfProfileOut( $fname );
457 * Primitive rate limits: enforce maximum actions per time period
458 * to put a brake on flooding.
460 * Note: when using a shared cache like memcached, IP-address
461 * last-hit counters will be shared across wikis.
463 * @return bool true if a rate limiter was tripped
466 function pingLimiter( $action='edit' ) {
467 global $wgRateLimits;
468 if( !isset( $wgRateLimits[$action] ) ) {
471 if( $this->isAllowed( 'delete' ) ) {
476 global $wgMemc, $wgIP, $wgDBname, $wgRateLimitLog;
477 $fname = 'User::pingLimiter';
478 $limits = $wgRateLimits[$action];
480 $id = $this->getId();
482 if( isset( $limits['anon'] ) && $id == 0 ) {
483 $keys["$wgDBname:limiter:$action:anon"] = $limits['anon'];
486 if( isset( $limits['user'] ) && $id != 0 ) {
487 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['user'];
489 if( $this->isNewbie() ) {
490 if( isset( $limits['newbie'] ) && $id != 0 ) {
491 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['newbie'];
493 if( isset( $limits['ip'] ) ) {
494 $keys["mediawiki:limiter:$action:ip:$wgIP"] = $limits['ip'];
496 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $wgIP, $matches ) ) {
497 $subnet = $matches[1];
498 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
503 foreach( $keys as $key => $limit ) {
504 list( $max, $period ) = $limit;
505 $summary = "(limit $max in {$period}s)";
506 $count = $wgMemc->get( $key );
508 if( $count > $max ) {
509 wfDebug( "$fname: tripped! $key at $count $summary\n" );
510 if( $wgRateLimitLog ) {
511 @error_log
( wfTimestamp( TS_MW
) . ' ' . $wgDBname . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
515 wfDebug( "$fname: ok. $key at $count $summary\n" );
518 wfDebug( "$fname: adding record for $key $summary\n" );
519 $wgMemc->add( $key, 1, IntVal( $period ) );
521 $wgMemc->incr( $key );
528 * Check if user is blocked
529 * @return bool True if blocked, false otherwise
531 function isBlocked( $bFromSlave = false ) {
532 $this->getBlockedStatus( $bFromSlave );
533 return $this->mBlockedby
!== 0;
537 * Check if user is blocked from editing a particular article
539 function isBlockedFrom( $title, $bFromSlave = false ) {
540 global $wgBlockAllowsUTEdit;
541 if ( $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
542 $title->getNamespace() == NS_USER_TALK
)
546 return $this->isBlocked( $bFromSlave );
551 * Get name of blocker
552 * @return string name of blocker
554 function blockedBy() {
555 $this->getBlockedStatus();
556 return $this->mBlockedby
;
560 * Get blocking reason
561 * @return string Blocking reason
563 function blockedFor() {
564 $this->getBlockedStatus();
565 return $this->mBlockreason
;
569 * Initialise php session
571 function SetupSession() {
572 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
573 if( $wgSessionsInMemcached ) {
574 require_once( 'MemcachedSessions.php' );
575 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
576 # If it's left on 'user' or another setting from another
577 # application, it will end up failing. Try to recover.
578 ini_set ( 'session.save_handler', 'files' );
580 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
581 session_cache_limiter( 'private, must-revalidate' );
586 * Read datas from session
589 function loadFromSession() {
590 global $wgMemc, $wgDBname;
592 if ( isset( $_SESSION['wsUserID'] ) ) {
593 if ( 0 != $_SESSION['wsUserID'] ) {
594 $sId = $_SESSION['wsUserID'];
598 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
599 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
600 $_SESSION['wsUserID'] = $sId;
604 if ( isset( $_SESSION['wsUserName'] ) ) {
605 $sName = $_SESSION['wsUserName'];
606 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
607 $sName = $_COOKIE["{$wgDBname}UserName"];
608 $_SESSION['wsUserName'] = $sName;
613 $passwordCorrect = FALSE;
614 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
615 if( !is_object( $user ) ||
$user->mVersion
< MW_USER_VERSION
) {
616 # Expire old serialized objects; they may be corrupt.
619 if($makenew = !$user) {
620 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
623 $user->loadFromDatabase();
625 wfDebug( "User::loadFromSession() got from cache!\n" );
628 if ( isset( $_SESSION['wsToken'] ) ) {
629 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken
;
630 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
631 $passwordCorrect = $user->mToken
== $_COOKIE["{$wgDBname}Token"];
633 return new User(); # Can't log in from session
636 if ( ( $sName == $user->mName
) && $passwordCorrect ) {
638 if($wgMemc->set( $key, $user ))
639 wfDebug( "User::loadFromSession() successfully saved user\n" );
641 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
645 return new User(); # Can't log in from session
649 * Load a user from the database
651 function loadFromDatabase() {
652 global $wgCommandLineMode;
653 $fname = "User::loadFromDatabase";
655 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
656 # loading in a command line script, don't assume all command line scripts need it like this
657 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
658 if ( $this->mDataLoaded
) {
663 $this->mId
= IntVal( $this->mId
);
665 /** Anonymous user */
668 $this->mRights
= $this->getGroupPermissions( array( '*' ) );
669 $this->mDataLoaded
= true;
671 } # the following stuff is for non-anonymous users only
673 $dbr =& wfGetDB( DB_SLAVE
);
674 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
675 'user_email_authenticated',
676 'user_real_name','user_options','user_touched', 'user_token' ),
677 array( 'user_id' => $this->mId
), $fname );
679 if ( $s !== false ) {
680 $this->mName
= $s->user_name
;
681 $this->mEmail
= $s->user_email
;
682 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
683 $this->mRealName
= $s->user_real_name
;
684 $this->mPassword
= $s->user_password
;
685 $this->mNewpassword
= $s->user_newpassword
;
686 $this->decodeOptions( $s->user_options
);
687 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
688 $this->mToken
= $s->user_token
;
690 $res = $dbr->select( 'user_groups',
692 array( 'ug_user' => $this->mId
),
694 $this->mGroups
= array();
695 while( $row = $dbr->fetchObject( $res ) ) {
696 $this->mGroups
[] = $row->ug_group
;
698 $effectiveGroups = array_merge( array( '*', 'user' ), $this->mGroups
);
699 $this->mRights
= $this->getGroupPermissions( $effectiveGroups );
702 $this->mDataLoaded
= true;
705 function getID() { return $this->mId
; }
706 function setID( $v ) {
708 $this->mDataLoaded
= false;
712 $this->loadFromDatabase();
716 function setName( $str ) {
717 $this->loadFromDatabase();
723 * Return the title dbkey form of the name, for eg user pages.
727 function getTitleKey() {
728 return str_replace( ' ', '_', $this->getName() );
731 function getNewtalk() {
733 $fname = 'User::getNewtalk';
734 $this->loadFromDatabase();
736 # Load the newtalk status if it is unloaded (mNewtalk=-1)
737 if( $this->mNewtalk
== -1 ) {
738 $this->mNewtalk
= 0; # reset talk page status
740 # Check memcached separately for anons, who have no
741 # entire User object stored in there.
743 global $wgDBname, $wgMemc;
744 $key = "$wgDBname:newtalk:ip:{$this->mName}";
745 $newtalk = $wgMemc->get( $key );
746 if( is_integer( $newtalk ) ) {
747 $this->mNewtalk
= $newtalk ?
1 : 0;
748 return (bool)$this->mNewtalk
;
752 $dbr =& wfGetDB( DB_SLAVE
);
753 if ( $wgUseEnotif ) {
754 $res = $dbr->select( 'watchlist',
756 array( 'wl_title' => $this->getTitleKey(),
757 'wl_namespace' => NS_USER_TALK
,
758 'wl_user' => $this->mId
,
759 'wl_notificationtimestamp != 0' ),
760 'User::getNewtalk' );
761 if( $dbr->numRows($res) > 0 ) {
764 $dbr->freeResult( $res );
765 } elseif ( $this->mId
) {
766 $res = $dbr->select( 'user_newtalk', 1, array( 'user_id' => $this->mId
), $fname );
768 if ( $dbr->numRows($res)>0 ) {
771 $dbr->freeResult( $res );
773 $res = $dbr->select( 'user_newtalk', 1, array( 'user_ip' => $this->mName
), $fname );
774 $this->mNewtalk
= $dbr->numRows( $res ) > 0 ?
1 : 0;
775 $dbr->freeResult( $res );
779 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
783 return ( 0 != $this->mNewtalk
);
786 function setNewtalk( $val ) {
787 $this->loadFromDatabase();
788 $this->mNewtalk
= $val;
789 $this->invalidateCache();
792 function invalidateCache() {
793 global $wgClockSkewFudge;
794 $this->loadFromDatabase();
795 $this->mTouched
= wfTimestamp(TS_MW
, time() +
$wgClockSkewFudge );
796 # Don't forget to save the options after this or
797 # it won't take effect!
800 function validateCache( $timestamp ) {
801 $this->loadFromDatabase();
802 return ($timestamp >= $this->mTouched
);
807 * Will only be salted if $wgPasswordSalt is true
808 * @param string Password.
809 * @return string Salted password or clear password.
811 function addSalt( $p ) {
812 global $wgPasswordSalt;
814 return md5( "{$this->mId}-{$p}" );
820 * Encrypt a password.
821 * It can eventuall salt a password @see User::addSalt()
822 * @param string $p clear Password.
823 * @param string Encrypted password.
825 function encryptPassword( $p ) {
826 return $this->addSalt( md5( $p ) );
829 # Set the password and reset the random token
830 function setPassword( $str ) {
831 $this->loadFromDatabase();
833 $this->mPassword
= $this->encryptPassword( $str );
834 $this->mNewpassword
= '';
837 # Set the random token (used for persistent authentication)
838 function setToken( $token = false ) {
839 global $wgSecretKey, $wgProxyKey, $wgDBname;
841 if ( $wgSecretKey ) {
843 } elseif ( $wgProxyKey ) {
848 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId
);
850 $this->mToken
= $token;
855 function setCookiePassword( $str ) {
856 $this->loadFromDatabase();
857 $this->mCookiePassword
= md5( $str );
860 function setNewpassword( $str ) {
861 $this->loadFromDatabase();
862 $this->mNewpassword
= $this->encryptPassword( $str );
865 function getEmail() {
866 $this->loadFromDatabase();
867 return $this->mEmail
;
870 function getEmailAuthenticationTimestamp() {
871 $this->loadFromDatabase();
872 return $this->mEmailAuthenticated
;
875 function setEmail( $str ) {
876 $this->loadFromDatabase();
877 $this->mEmail
= $str;
880 function getRealName() {
881 $this->loadFromDatabase();
882 return $this->mRealName
;
885 function setRealName( $str ) {
886 $this->loadFromDatabase();
887 $this->mRealName
= $str;
890 function getOption( $oname ) {
891 $this->loadFromDatabase();
892 if ( array_key_exists( $oname, $this->mOptions
) ) {
893 return trim( $this->mOptions
[$oname] );
899 function setOption( $oname, $val ) {
900 $this->loadFromDatabase();
901 if ( $oname == 'skin' ) {
902 # Clear cached skin, so the new one displays immediately in Special:Preferences
903 unset( $this->mSkin
);
905 $this->mOptions
[$oname] = $val;
906 $this->invalidateCache();
909 function getRights() {
910 $this->loadFromDatabase();
911 return $this->mRights
;
915 * Get the list of explicit group memberships this user has.
916 * The implicit * and user groups are not included.
917 * @return array of strings
919 function getGroups() {
920 $this->loadFromDatabase();
921 return $this->mGroups
;
925 * Get the list of implicit group memberships this user has.
926 * This includes all explicit groups, plus 'user' if logged in
927 * and '*' for all accounts.
928 * @return array of strings
930 function getEffectiveGroups() {
931 $base = array( '*' );
932 if( $this->isLoggedIn() ) {
935 return array_merge( $base, $this->getGroups() );
939 * Remove the user from the given group.
940 * This takes immediate effect.
943 function addGroup( $group ) {
944 $dbw =& wfGetDB( DB_MASTER
);
945 $dbw->insert( 'user_groups',
947 'ug_user' => $this->getID(),
948 'ug_group' => $group,
953 $this->mGroups
= array_merge( $this->mGroups
, array( $group ) );
954 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups() );
956 $this->invalidateCache();
957 $this->saveSettings();
961 * Remove the user from the given group.
962 * This takes immediate effect.
965 function removeGroup( $group ) {
966 $dbw =& wfGetDB( DB_MASTER
);
967 $dbw->delete( 'user_groups',
969 'ug_user' => $this->getID(),
970 'ug_group' => $group,
972 'User::removeGroup' );
974 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
975 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups() );
977 $this->invalidateCache();
978 $this->saveSettings();
983 * A more legible check for non-anonymousness.
984 * Returns true if the user is not an anonymous visitor.
988 function isLoggedIn() {
989 return( $this->getID() != 0 );
993 * A more legible check for anonymousness.
994 * Returns true if the user is an anonymous visitor.
999 return !$this->isLoggedIn();
1003 * Check if a user is sysop
1004 * Die with backtrace. Use User:isAllowed() instead.
1007 function isSysop() {
1008 return $this->isAllowed( 'protect' );
1012 function isDeveloper() {
1013 return $this->isAllowed( 'siteadmin' );
1017 function isBureaucrat() {
1018 return $this->isAllowed( 'makesysop' );
1022 * Whether the user is a bot
1023 * @todo need to be migrated to the new user level management sytem
1026 $this->loadFromDatabase();
1027 return in_array( 'bot', $this->mRights
);
1031 * Check if user is allowed to access a feature / make an action
1032 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
1033 * @return boolean True: action is allowed, False: action should not be allowed
1035 function isAllowed($action='') {
1036 $this->loadFromDatabase();
1037 return in_array( $action , $this->mRights
);
1041 * Load a skin if it doesn't exist or return it
1042 * @todo FIXME : need to check the old failback system [AV]
1044 function &getSkin() {
1045 global $IP, $wgRequest;
1046 if ( ! isset( $this->mSkin
) ) {
1047 $fname = 'User::getSkin';
1048 wfProfileIn( $fname );
1050 # get all skin names available
1051 $skinNames = Skin
::getSkinNames();
1054 $userSkin = $this->getOption( 'skin' );
1055 $userSkin = $wgRequest->getText('useskin', $userSkin);
1056 if ( $userSkin == '' ) { $userSkin = 'standard'; }
1058 if ( !isset( $skinNames[$userSkin] ) ) {
1059 # in case the user skin could not be found find a replacement
1063 2 => 'CologneBlue');
1064 # if phptal is enabled we should have monobook skin that
1065 # superseed the good old SkinStandard.
1066 if ( isset( $skinNames['monobook'] ) ) {
1067 $fallback[0] = 'MonoBook';
1070 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
1071 $sn = $fallback[$userSkin];
1076 # The user skin is available
1077 $sn = $skinNames[$userSkin];
1080 # Grab the skin class and initialise it. Each skin checks for PHPTal
1081 # and will not load if it's not enabled.
1082 require_once( $IP.'/skins/'.$sn.'.php' );
1084 # Check if we got if not failback to default skin
1085 $className = 'Skin'.$sn;
1086 if( !class_exists( $className ) ) {
1087 # DO NOT die if the class isn't found. This breaks maintenance
1088 # scripts and can cause a user account to be unrecoverable
1089 # except by SQL manipulation if a previously valid skin name
1090 # is no longer valid.
1091 $className = 'SkinStandard';
1092 require_once( $IP.'/skins/Standard.php' );
1094 $this->mSkin
=& new $className;
1095 wfProfileOut( $fname );
1097 return $this->mSkin
;
1101 * @param string $title Article title to look at
1105 * Check watched status of an article
1106 * @return bool True if article is watched
1108 function isWatched( $title ) {
1109 $wl = WatchedItem
::fromUserTitle( $this, $title );
1110 return $wl->isWatched();
1116 function addWatch( $title ) {
1117 $wl = WatchedItem
::fromUserTitle( $this, $title );
1119 $this->invalidateCache();
1123 * Stop watching an article
1125 function removeWatch( $title ) {
1126 $wl = WatchedItem
::fromUserTitle( $this, $title );
1128 $this->invalidateCache();
1132 * Clear the user's notification timestamp for the given title.
1133 * If e-notif e-mails are on, they will receive notification mails on
1134 * the next change of the page if it's watched etc.
1136 function clearNotification( &$title ) {
1137 global $wgUser, $wgUseEnotif;
1139 if ( !$wgUseEnotif ) {
1143 $userid = $this->getID();
1148 // Only update the timestamp if the page is being watched.
1149 // The query to find out if it is watched is cached both in memcached and per-invocation,
1150 // and when it does have to be executed, it can be on a slave
1151 // If this is the user's newtalk page, we always update the timestamp
1152 if ($title->getNamespace() == NS_USER_TALK
&&
1153 $title->getText() == $wgUser->getName())
1156 } elseif ( $this->getID() == $wgUser->getID() ) {
1157 $watched = $title->userIsWatching();
1162 // If the page is watched by the user (or may be watched), update the timestamp on any
1163 // any matching rows
1165 $dbw =& wfGetDB( DB_MASTER
);
1166 $success = $dbw->update( 'watchlist',
1168 'wl_notificationtimestamp' => 0
1169 ), array( /* WHERE */
1170 'wl_title' => $title->getDBkey(),
1171 'wl_namespace' => $title->getNamespace(),
1172 'wl_user' => $this->getID()
1173 ), 'User::clearLastVisited'
1181 * Resets all of the given user's page-change notification timestamps.
1182 * If e-notif e-mails are on, they will receive notification mails on
1183 * the next change of any watched page.
1185 * @param int $currentUser user ID number
1188 function clearAllNotifications( $currentUser ) {
1189 global $wgUseEnotif;
1190 if ( !$wgUseEnotif ) {
1193 if( $currentUser != 0 ) {
1195 $dbw =& wfGetDB( DB_MASTER
);
1196 $success = $dbw->update( 'watchlist',
1198 'wl_notificationtimestamp' => 0
1199 ), array( /* WHERE */
1200 'wl_user' => $currentUser
1201 ), 'UserMailer::clearAll'
1204 # we also need to clear here the "you have new message" notification for the own user_talk page
1205 # This is cleared one page view later in Article::viewUpdates();
1211 * @return string Encoding options
1213 function encodeOptions() {
1215 foreach ( $this->mOptions
as $oname => $oval ) {
1216 array_push( $a, $oname.'='.$oval );
1218 $s = implode( "\n", $a );
1225 function decodeOptions( $str ) {
1226 $a = explode( "\n", $str );
1227 foreach ( $a as $s ) {
1228 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1229 $this->mOptions
[$m[1]] = $m[2];
1234 function setCookies() {
1235 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
1236 if ( 0 == $this->mId
) return;
1237 $this->loadFromDatabase();
1238 $exp = time() +
$wgCookieExpiration;
1240 $_SESSION['wsUserID'] = $this->mId
;
1241 setcookie( $wgDBname.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain );
1243 $_SESSION['wsUserName'] = $this->mName
;
1244 setcookie( $wgDBname.'UserName', $this->mName
, $exp, $wgCookiePath, $wgCookieDomain );
1246 $_SESSION['wsToken'] = $this->mToken
;
1247 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1248 setcookie( $wgDBname.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain );
1250 setcookie( $wgDBname.'Token', '', time() - 3600 );
1256 * It will clean the session cookie
1259 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
1260 $this->loadDefaults();
1261 $this->setLoaded( true );
1263 $_SESSION['wsUserID'] = 0;
1265 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1266 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1268 # Remember when user logged out, to prevent seeing cached pages
1269 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain );
1273 * Save object settings into database
1275 function saveSettings() {
1276 global $wgMemc, $wgDBname, $wgUseEnotif;
1277 $fname = 'User::saveSettings';
1279 if ( wfReadOnly() ) { return; }
1280 $this->saveNewtalk();
1281 if ( 0 == $this->mId
) { return; }
1283 $dbw =& wfGetDB( DB_MASTER
);
1284 $dbw->update( 'user',
1286 'user_name' => $this->mName
,
1287 'user_password' => $this->mPassword
,
1288 'user_newpassword' => $this->mNewpassword
,
1289 'user_real_name' => $this->mRealName
,
1290 'user_email' => $this->mEmail
,
1291 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1292 'user_options' => $this->encodeOptions(),
1293 'user_touched' => $dbw->timestamp($this->mTouched
),
1294 'user_token' => $this->mToken
1295 ), array( /* WHERE */
1296 'user_id' => $this->mId
1299 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1303 * Save value of new talk flag.
1305 function saveNewtalk() {
1306 global $wgDBname, $wgMemc, $wgUseEnotif;
1308 $fname = 'User::saveNewtalk';
1312 if ( wfReadOnly() ) { return ; }
1313 $dbr =& wfGetDB( DB_SLAVE
);
1314 $dbw =& wfGetDB( DB_MASTER
);
1316 if ( $wgUseEnotif ) {
1317 if ( ! $this->getNewtalk() ) {
1318 # Delete the watchlist entry for user_talk page X watched by user X
1319 $dbw->delete( 'watchlist',
1320 array( 'wl_user' => $this->mId
,
1321 'wl_title' => $this->getTitleKey(),
1322 'wl_namespace' => NS_USER_TALK
),
1324 if ( $dbw->affectedRows() ) {
1328 # Anon users have a separate memcache space for newtalk
1329 # since they don't store their own info. Trim...
1330 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1334 if ($this->getID() != 0) {
1336 $value = $this->getID();
1340 $value = $this->mName
;
1341 $key = "$wgDBname:newtalk:ip:$this->mName";
1344 $dbr =& wfGetDB( DB_SLAVE
);
1345 $dbw =& wfGetDB( DB_MASTER
);
1347 $res = $dbr->selectField('user_newtalk', $field,
1348 array($field => $value), $fname);
1351 if ($res !== false && $this->mNewtalk
== 0) {
1352 $dbw->delete('user_newtalk', array($field => $value), $fname);
1354 $wgMemc->set( $key, 0 );
1356 } else if ($res === false && $this->mNewtalk
== 1) {
1357 $dbw->insert('user_newtalk', array($field => $value), $fname);
1359 $wgMemc->set( $key, 1 );
1366 # Update user_touched, so that newtalk notifications in the client cache are invalidated
1367 if ( $changed && $this->getID() ) {
1368 $dbw->update('user',
1369 /*SET*/ array( 'user_touched' => $this->mTouched
),
1370 /*WHERE*/ array( 'user_id' => $this->getID() ),
1372 $wgMemc->set( "$wgDBname:user:id:{$this->mId}", $this, 86400 );
1377 * Checks if a user with the given name exists, returns the ID
1379 function idForName() {
1380 $fname = 'User::idForName';
1383 $s = trim( $this->mName
);
1384 if ( 0 == strcmp( '', $s ) ) return 0;
1386 $dbr =& wfGetDB( DB_SLAVE
);
1387 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1388 if ( $id === false ) {
1395 * Add user object to the database
1397 function addToDatabase() {
1398 $fname = 'User::addToDatabase';
1399 $dbw =& wfGetDB( DB_MASTER
);
1400 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1401 $dbw->insert( 'user',
1403 'user_id' => $seqVal,
1404 'user_name' => $this->mName
,
1405 'user_password' => $this->mPassword
,
1406 'user_newpassword' => $this->mNewpassword
,
1407 'user_email' => $this->mEmail
,
1408 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1409 'user_real_name' => $this->mRealName
,
1410 'user_options' => $this->encodeOptions(),
1411 'user_token' => $this->mToken
1414 $this->mId
= $dbw->insertId();
1417 function spreadBlock() {
1419 # If the (non-anonymous) user is blocked, this function will block any IP address
1420 # that they successfully log on from.
1421 $fname = 'User::spreadBlock';
1423 wfDebug( "User:spreadBlock()\n" );
1424 if ( $this->mId
== 0 ) {
1428 $userblock = Block
::newFromDB( '', $this->mId
);
1429 if ( !$userblock->isValid() ) {
1433 # Check if this IP address is already blocked
1434 $ipblock = Block
::newFromDB( $wgIP );
1435 if ( $ipblock->isValid() ) {
1436 # Just update the timestamp
1437 $ipblock->updateTimestamp();
1441 # Make a new block object with the desired properties
1442 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1443 $ipblock->mAddress
= $wgIP;
1444 $ipblock->mUser
= 0;
1445 $ipblock->mBy
= $userblock->mBy
;
1446 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
1447 $ipblock->mTimestamp
= wfTimestampNow();
1448 $ipblock->mAuto
= 1;
1449 # If the user is already blocked with an expiry date, we don't
1450 # want to pile on top of that!
1451 if($userblock->mExpiry
) {
1452 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
1454 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
1462 function getPageRenderingHash() {
1465 return $this->mHash
;
1468 // stubthreshold is only included below for completeness,
1469 // it will always be 0 when this function is called by parsercache.
1471 $confstr = $this->getOption( 'math' );
1472 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1473 $confstr .= '!' . $this->getOption( 'date' );
1474 $confstr .= '!' . $this->getOption( 'numberheadings' );
1475 $confstr .= '!' . $this->getOption( 'language' );
1476 $confstr .= '!' . $this->getOption( 'thumbsize' );
1477 // add in language specific options, if any
1478 $extra = $wgContLang->getExtraHashOptions();
1481 $this->mHash
= $confstr;
1485 function isAllowedToCreateAccount() {
1486 return $this->isAllowed( 'createaccount' );
1490 * Set mDataLoaded, return previous value
1491 * Use this to prevent DB access in command-line scripts or similar situations
1493 function setLoaded( $loaded ) {
1494 return wfSetVar( $this->mDataLoaded
, $loaded );
1498 * Get this user's personal page title.
1503 function getUserPage() {
1504 return Title
::makeTitle( NS_USER
, $this->mName
);
1508 * Get this user's talk page title.
1513 function getTalkPage() {
1514 $title = $this->getUserPage();
1515 return $title->getTalkPage();
1521 function getMaxID() {
1522 $dbr =& wfGetDB( DB_SLAVE
);
1523 return $dbr->selectField( 'user', 'max(user_id)', false );
1527 * Determine whether the user is a newbie. Newbies are either
1528 * anonymous IPs, or the 1% most recently created accounts.
1529 * Bots and sysops are excluded.
1530 * @return bool True if it is a newbie.
1532 function isNewbie() {
1533 return $this->isAnon() ||
$this->mId
> User
::getMaxID() * 0.99 && !$this->isAllowed( 'delete' ) && !$this->isBot();
1537 * Check to see if the given clear-text password is one of the accepted passwords
1538 * @param string $password User password.
1539 * @return bool True if the given password is correct otherwise False.
1541 function checkPassword( $password ) {
1542 global $wgAuth, $wgMinimalPasswordLength;
1543 $this->loadFromDatabase();
1545 // Even though we stop people from creating passwords that
1546 // are shorter than this, doesn't mean people wont be able
1547 // to. Certain authentication plugins do NOT want to save
1548 // domain passwords in a mysql database, so we should
1549 // check this (incase $wgAuth->strict() is false).
1550 if( strlen( $password ) < $wgMinimalPasswordLength ) {
1554 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1556 } elseif( $wgAuth->strict() ) {
1557 /* Auth plugin doesn't allow local authentication */
1560 $ep = $this->encryptPassword( $password );
1561 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
1563 } elseif ( ($this->mNewpassword
!= '') && (0 == strcmp( $ep, $this->mNewpassword
)) ) {
1565 } elseif ( function_exists( 'iconv' ) ) {
1566 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1567 # Check for this with iconv
1568 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1569 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
1577 * Initialize (if necessary) and return a session token value
1578 * which can be used in edit forms to show that the user's
1579 * login credentials aren't being hijacked with a foreign form
1582 * @param mixed $salt - Optional function-specific data for hash.
1583 * Use a string or an array of strings.
1587 function editToken( $salt = '' ) {
1588 if( !isset( $_SESSION['wsEditToken'] ) ) {
1589 $token = $this->generateToken();
1590 $_SESSION['wsEditToken'] = $token;
1592 $token = $_SESSION['wsEditToken'];
1594 if( is_array( $salt ) ) {
1595 $salt = implode( '|', $salt );
1597 return md5( $token . $salt );
1601 * Generate a hex-y looking random token for various uses.
1602 * Could be made more cryptographically sure if someone cares.
1605 function generateToken( $salt = '' ) {
1606 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1607 return md5( $token . $salt );
1611 * Check given value against the token value stored in the session.
1612 * A match should confirm that the form was submitted from the
1613 * user's own login session, not a form submission from a third-party
1616 * @param string $val - the input value to compare
1617 * @param string $salt - Optional function-specific data for hash
1621 function matchEditToken( $val, $salt = '' ) {
1622 return ( $val == $this->editToken( $salt ) );
1626 * Generate a new e-mail confirmation token and send a confirmation
1627 * mail to the user's given address.
1629 * @return mixed True on success, a WikiError object on failure.
1631 function sendConfirmationMail() {
1632 global $wgIP, $wgContLang;
1633 $url = $this->confirmationTokenUrl( $expiration );
1634 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1635 wfMsg( 'confirmemail_body',
1639 $wgContLang->timeanddate( $expiration, false ) ) );
1643 * Send an e-mail to this user's account. Does not check for
1644 * confirmed status or validity.
1646 * @param string $subject
1647 * @param string $body
1648 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1649 * @return mixed True on success, a WikiError object on failure.
1651 function sendMail( $subject, $body, $from = null ) {
1652 if( is_null( $from ) ) {
1653 global $wgPasswordSender;
1654 $from = $wgPasswordSender;
1657 require_once( 'UserMailer.php' );
1658 $error = userMailer( $this->getEmail(), $from, $subject, $body );
1660 if( $error == '' ) {
1663 return new WikiError( $error );
1668 * Generate, store, and return a new e-mail confirmation code.
1669 * A hash (unsalted since it's used as a key) is stored.
1670 * @param &$expiration mixed output: accepts the expiration time
1674 function confirmationToken( &$expiration ) {
1675 $fname = 'User::confirmationToken';
1678 $expires = $now +
7 * 24 * 60 * 60;
1679 $expiration = wfTimestamp( TS_MW
, $expires );
1681 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
1682 $hash = md5( $token );
1684 $dbw =& wfGetDB( DB_MASTER
);
1685 $dbw->update( 'user',
1686 array( 'user_email_token' => $hash,
1687 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1688 array( 'user_id' => $this->mId
),
1695 * Generate and store a new e-mail confirmation token, and return
1696 * the URL the user can use to confirm.
1697 * @param &$expiration mixed output: accepts the expiration time
1701 function confirmationTokenUrl( &$expiration ) {
1702 $token = $this->confirmationToken( $expiration );
1703 $title = Title
::makeTitle( NS_SPECIAL
, 'Confirmemail/' . $token );
1704 return $title->getFullUrl();
1708 * Mark the e-mail address confirmed and save.
1710 function confirmEmail() {
1711 $this->loadFromDatabase();
1712 $this->mEmailAuthenticated
= wfTimestampNow();
1713 $this->saveSettings();
1718 * Is this user allowed to send e-mails within limits of current
1719 * site configuration?
1722 function canSendEmail() {
1723 return $this->isEmailConfirmed();
1727 * Is this user allowed to receive e-mails within limits of current
1728 * site configuration?
1731 function canReceiveEmail() {
1732 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1736 * Is this user's e-mail address valid-looking and confirmed within
1737 * limits of the current site configuration?
1739 * If $wgEmailAuthentication is on, this may require the user to have
1740 * confirmed their address by returning a code or using a password
1741 * sent to the address from the wiki.
1745 function isEmailConfirmed() {
1746 global $wgEmailAuthentication;
1747 $this->loadFromDatabase();
1748 if( $this->isAnon() )
1750 if( !$this->isValidEmailAddr( $this->mEmail
) )
1752 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
1758 * @param array $groups list of groups
1759 * @return array list of permission key names for given groups combined
1762 function getGroupPermissions( $groups ) {
1763 global $wgGroupPermissions;
1765 foreach( $groups as $group ) {
1766 if( isset( $wgGroupPermissions[$group] ) ) {
1767 $rights = array_merge( $rights,
1768 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
1775 * @param string $group key name
1776 * @return string localized descriptive name, if provided
1779 function getGroupName( $group ) {
1780 $key = "group-$group-name";
1781 $name = wfMsg( $key );
1782 if( $name == '' ||
$name == "<$key>" ) {
1790 * Return the set of defined explicit groups.
1791 * The * and 'user' groups are not included.
1795 function getAllGroups() {
1796 global $wgGroupPermissions;
1798 array_keys( $wgGroupPermissions ),
1799 array( '*', 'user' ) );