11 require_once( 'WatchedItem.php' );
12 require_once( 'Group.php' );
14 # Number of characters in user_token field
15 define( 'USER_TOKEN_LENGTH', 32 );
25 var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
26 var $mEmailAuthenticated;
27 var $mRights, $mOptions;
28 var $mDataLoaded, $mNewpassword;
30 var $mBlockedby, $mBlockreason;
35 /** Array of group id the user belong to */
39 /** Construct using User:loadDefaults() */
41 $this->loadDefaults();
45 * Static factory method
46 * @param string $name Username, validated by Title:newFromText()
50 function newFromName( $name ) {
53 # Clean up name according to title rules
55 $t = Title
::newFromText( $name );
59 $u->setName( $t->getText() );
60 $u->setId( $u->idFromName( $t->getText() ) );
66 * Factory method to fetch whichever use has a given email confirmation code.
67 * This code is generated when an account is created or its e-mail address
70 * If the code is invalid or has expired, returns NULL.
76 function newFromConfirmationCode( $code ) {
77 $dbr =& wfGetDB( DB_SLAVE
);
78 $name = $dbr->selectField( 'user', 'user_name', array(
79 'user_email_token' => md5( $code ),
80 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
82 if( is_string( $name ) ) {
83 return User
::newFromName( $name );
90 * Get username given an id.
91 * @param integer $id Database user id
92 * @return string Nickname of a user
95 function whoIs( $id ) {
96 $dbr =& wfGetDB( DB_SLAVE
);
97 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
101 * Get real username given an id.
102 * @param integer $id Database user id
103 * @return string Realname of a user
106 function whoIsReal( $id ) {
107 $dbr =& wfGetDB( DB_SLAVE
);
108 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
112 * Get database id given a user name
113 * @param string $name Nickname of a user
114 * @return integer|null Database user id (null: if non existent
117 function idFromName( $name ) {
118 $fname = "User::idFromName";
120 $nt = Title
::newFromText( $name );
121 if( is_null( $nt ) ) {
125 $dbr =& wfGetDB( DB_SLAVE
);
126 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
128 if ( $s === false ) {
136 * does the string match an anonymous IPv4 address?
139 * @param string $name Nickname of a user
142 function isIP( $name ) {
143 return preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$name);
144 /*return preg_match("/^
145 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
146 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
147 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
148 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
153 * does the string match roughly an email address ?
157 * @param string $addr email address
161 function isValidEmailAddr ( $addr ) {
162 # There used to be a regular expression here, it got removed because it
163 # rejected valid addresses.
164 return ( trim( $addr ) != '' ) &&
165 (false !== strpos( $addr, '@' ) );
169 * probably return a random password
170 * @return string probably a random password
172 * @todo Check what is doing really [AV]
174 function randomPassword() {
175 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
176 $l = strlen( $pwchars ) - 1;
178 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
179 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
180 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
181 $pwchars{mt_rand( 0, $l )};
186 * Set properties to default
187 * Used at construction. It will load per language default settings only
188 * if we have an available language object.
190 function loadDefaults() {
193 $fname = 'User::loadDefaults' . $n;
194 wfProfileIn( $fname );
196 global $wgContLang, $wgIP, $wgDBname;
197 global $wgNamespacesToBeSearchedDefault;
200 $this->mNewtalk
= -1;
201 $this->mName
= $wgIP;
202 $this->mRealName
= $this->mEmail
= '';
203 $this->mEmailAuthenticated
= null;
204 $this->mPassword
= $this->mNewpassword
= '';
205 $this->mRights
= array();
206 $this->mGroups
= array();
207 // Getting user defaults only if we have an available language
208 if( isset( $wgContLang ) ) {
209 $this->loadDefaultFromLanguage();
212 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
213 $this->mOptions
['searchNs'.$nsnum] = $val;
215 unset( $this->mSkin
);
216 $this->mDataLoaded
= false;
217 $this->mBlockedby
= -1; # Unset
218 $this->setToken(); # Random
219 $this->mHash
= false;
221 if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
222 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgDBname.'LoggedOut'] );
225 $this->mTouched
= '0'; # Allow any pages to be cached
228 wfProfileOut( $fname );
232 * Used to load user options from a language.
233 * This is not in loadDefault() cause we sometime create user before having
236 function loadDefaultFromLanguage(){
237 $this->mOptions
= User
::getDefaultOptions();
241 * Combine the language default options with any site-specific options
242 * and add the default language variants.
248 function getDefaultOptions() {
250 * Site defaults will override the global/language defaults
252 global $wgContLang, $wgDefaultUserOptions;
253 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptions();
256 * default language setting
258 $variant = $wgContLang->getPreferredVariant();
259 $defOpt['variant'] = $variant;
260 $defOpt['language'] = $variant;
266 * Get a given default option value.
273 function getDefaultOption( $opt ) {
274 $defOpts = User
::getDefaultOptions();
275 if( isset( $defOpts[$opt] ) ) {
276 return $defOpts[$opt];
283 * Get blocking information
285 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
286 * non-critical checks are done against slaves. Check when actually saving should be done against
289 * Note that even if $bFromSlave is false, the check is done first against slave, then master.
290 * The logic is that if blocked on slave, we'll assume it's either blocked on master or
291 * just slightly outta sync and soon corrected - safer to block slightly more that less.
292 * And it's cheaper to check slave first, then master if needed, than master always.
294 function getBlockedStatus() {
295 global $wgIP, $wgBlockCache, $wgProxyList, $wgEnableSorbs, $bFromSlave;
297 if ( -1 != $this->mBlockedby
) { return; }
299 $this->mBlockedby
= 0;
303 $block = new Block();
304 $block->forUpdate( $bFromSlave );
305 if ( $block->load( $wgIP , $this->mId
) ) {
306 $this->mBlockedby
= $block->mBy
;
307 $this->mBlockreason
= $block->mReason
;
308 $this->spreadBlock();
313 if ( !$this->mBlockedby
) {
314 # Check first against slave, and optionally from master.
315 $block = $wgBlockCache->get( $wgIP, true );
316 if ( !$block && !$bFromSlave )
318 # Not blocked: check against master, to make sure.
319 $wgBlockCache->clearLocal( );
320 $block = $wgBlockCache->get( $wgIP, false );
322 if ( $block !== false ) {
323 $this->mBlockedby
= $block->mBy
;
324 $this->mBlockreason
= $block->mReason
;
329 if ( !$this->mBlockedby
) {
330 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
331 $this->mBlockedby
= wfMsg( 'proxyblocker' );
332 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
337 if ( !$this->mBlockedby
&& $wgEnableSorbs ) {
338 if ( $this->inSorbsBlacklist( $wgIP ) ) {
339 $this->mBlockedby
= wfMsg( 'sorbs' );
340 $this->mBlockreason
= wfMsg( 'sorbsreason' );
346 function inSorbsBlacklist( $ip ) {
347 $fname = 'User::inSorbsBlacklist';
348 wfProfileIn( $fname );
353 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
355 for ( $i=4; $i>=1; $i-- ) {
356 $host .= $m[$i] . '.';
358 $host .= 'http.dnsbl.sorbs.net.';
361 $ipList = gethostbynamel( $host );
364 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy!\n" );
367 wfDebug( "Requested $host, not found.\n" );
371 wfProfileOut( $fname );
376 * Check if user is blocked
377 * @return bool True if blocked, false otherwise
379 function isBlocked( $bFromSlave = false ) {
380 $this->getBlockedStatus( $bFromSlave );
381 return $this->mBlockedby
!== 0;
385 * Get name of blocker
386 * @return string name of blocker
388 function blockedBy() {
389 $this->getBlockedStatus();
390 return $this->mBlockedby
;
394 * Get blocking reason
395 * @return string Blocking reason
397 function blockedFor() {
398 $this->getBlockedStatus();
399 return $this->mBlockreason
;
403 * Initialise php session
405 function SetupSession() {
406 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
407 if( $wgSessionsInMemcached ) {
408 require_once( 'MemcachedSessions.php' );
409 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
410 # If it's left on 'user' or another setting from another
411 # application, it will end up failing. Try to recover.
412 ini_set ( 'session.save_handler', 'files' );
414 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
415 session_cache_limiter( 'private, must-revalidate' );
420 * Read datas from session
423 function loadFromSession() {
424 global $wgMemc, $wgDBname;
426 if ( isset( $_SESSION['wsUserID'] ) ) {
427 if ( 0 != $_SESSION['wsUserID'] ) {
428 $sId = $_SESSION['wsUserID'];
432 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
433 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
434 $_SESSION['wsUserID'] = $sId;
438 if ( isset( $_SESSION['wsUserName'] ) ) {
439 $sName = $_SESSION['wsUserName'];
440 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
441 $sName = $_COOKIE["{$wgDBname}UserName"];
442 $_SESSION['wsUserName'] = $sName;
447 $passwordCorrect = FALSE;
448 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
449 if($makenew = !$user) {
450 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
453 $user->loadFromDatabase();
455 wfDebug( "User::loadFromSession() got from cache!\n" );
458 if ( isset( $_SESSION['wsToken'] ) ) {
459 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken
;
460 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
461 $passwordCorrect = $user->mToken
== $_COOKIE["{$wgDBname}Token"];
463 return new User(); # Can't log in from session
466 if ( ( $sName == $user->mName
) && $passwordCorrect ) {
468 if($wgMemc->set( $key, $user ))
469 wfDebug( "User::loadFromSession() successfully saved user\n" );
471 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
475 return new User(); # Can't log in from session
479 * Load a user from the database
481 function loadFromDatabase() {
482 global $wgCommandLineMode, $wgAnonGroupId, $wgLoggedInGroupId;
483 $fname = "User::loadFromDatabase";
485 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
486 # loading in a command line script, don't assume all command line scripts need it like this
487 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
488 if ( $this->mDataLoaded
) {
493 $this->mId
= IntVal( $this->mId
);
495 /** Anonymous user */
498 $anong = Group
::newFromId($wgAnonGroupId);
500 wfDebugDieBacktrace("Please update your database schema "
501 ."and populate initial group data from "
502 ."maintenance/archives patches");
503 $anong->loadFromDatabase();
504 $this->mRights
= explode(',', $anong->getRights());
505 $this->mDataLoaded
= true;
507 } # the following stuff is for non-anonymous users only
509 $dbr =& wfGetDB( DB_SLAVE
);
510 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
511 'user_email_authenticated',
512 'user_real_name','user_options','user_touched', 'user_token' ),
513 array( 'user_id' => $this->mId
), $fname );
515 if ( $s !== false ) {
516 $this->mName
= $s->user_name
;
517 $this->mEmail
= $s->user_email
;
518 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
519 $this->mRealName
= $s->user_real_name
;
520 $this->mPassword
= $s->user_password
;
521 $this->mNewpassword
= $s->user_newpassword
;
522 $this->decodeOptions( $s->user_options
);
523 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
524 $this->mToken
= $s->user_token
;
527 $res = $dbr->select( 'user_groups', array( 'ug_group' ), array( 'ug_user' => $this->mId
) );
529 // add the default group for logged in user
530 $this->mGroups
= array( $wgLoggedInGroupId );
532 while($group = $dbr->fetchRow($res)) {
533 if ( $group[0] != $wgLoggedInGroupId ) {
534 $this->mGroups
[] = $group[0];
539 $this->mRights
= array();
540 // now we merge groups rights to get this user rights
541 foreach($this->mGroups
as $aGroupId) {
542 $g = Group
::newFromId($aGroupId);
543 $g->loadFromDatabase();
544 $this->mRights
= array_merge($this->mRights
, explode(',', $g->getRights()));
547 // array merge duplicate rights which are part of several groups
548 $this->mRights
= array_unique($this->mRights
);
550 $dbr->freeResult($res);
553 $this->mDataLoaded
= true;
556 function getID() { return $this->mId
; }
557 function setID( $v ) {
559 $this->mDataLoaded
= false;
563 $this->loadFromDatabase();
567 function setName( $str ) {
568 $this->loadFromDatabase();
574 * Return the title dbkey form of the name, for eg user pages.
578 function getTitleKey() {
579 return str_replace( ' ', '_', $this->getName() );
582 function getNewtalk() {
583 $fname = 'User::getNewtalk';
584 $this->loadFromDatabase();
586 # Load the newtalk status if it is unloaded (mNewtalk=-1)
587 if( $this->mNewtalk
== -1 ) {
588 $this->mNewtalk
= 0; # reset talk page status
590 # Check memcached separately for anons, who have no
591 # entire User object stored in there.
593 global $wgDBname, $wgMemc;
594 $key = "$wgDBname:newtalk:ip:{$this->mName}";
595 $newtalk = $wgMemc->get( $key );
596 if( is_integer( $newtalk ) ) {
597 $this->mNewtalk
= $newtalk ?
1 : 0;
598 return (bool)$this->mNewtalk
;
602 $dbr =& wfGetDB( DB_SLAVE
);
603 $res = $dbr->select( 'watchlist',
605 array( 'wl_title' => $this->getTitleKey(),
606 'wl_namespace' => NS_USER_TALK
,
607 'wl_user' => $this->mId
,
608 'wl_notificationtimestamp != 0' ),
609 'User::getNewtalk' );
610 if( $dbr->numRows($res) > 0 ) {
613 $dbr->freeResult( $res );
616 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
620 return ( 0 != $this->mNewtalk
);
623 function setNewtalk( $val ) {
624 $this->loadFromDatabase();
625 $this->mNewtalk
= $val;
626 $this->invalidateCache();
629 function invalidateCache() {
630 $this->loadFromDatabase();
631 $this->mTouched
= wfTimestampNow();
632 # Don't forget to save the options after this or
633 # it won't take effect!
636 function validateCache( $timestamp ) {
637 $this->loadFromDatabase();
638 return ($timestamp >= $this->mTouched
);
643 * Will only be salted if $wgPasswordSalt is true
644 * @param string Password.
645 * @return string Salted password or clear password.
647 function addSalt( $p ) {
648 global $wgPasswordSalt;
650 return md5( "{$this->mId}-{$p}" );
656 * Encrypt a password.
657 * It can eventuall salt a password @see User::addSalt()
658 * @param string $p clear Password.
659 * @param string Encrypted password.
661 function encryptPassword( $p ) {
662 return $this->addSalt( md5( $p ) );
665 # Set the password and reset the random token
666 function setPassword( $str ) {
667 $this->loadFromDatabase();
669 $this->mPassword
= $this->encryptPassword( $str );
670 $this->mNewpassword
= '';
673 # Set the random token (used for persistent authentication)
674 function setToken( $token = false ) {
675 global $wgSecretKey, $wgProxyKey, $wgDBname;
677 if ( $wgSecretKey ) {
679 } elseif ( $wgProxyKey ) {
684 $this->mToken
= md5( $wgSecretKey . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId
);
686 $this->mToken
= $token;
691 function setCookiePassword( $str ) {
692 $this->loadFromDatabase();
693 $this->mCookiePassword
= md5( $str );
696 function setNewpassword( $str ) {
697 $this->loadFromDatabase();
698 $this->mNewpassword
= $this->encryptPassword( $str );
701 function getEmail() {
702 $this->loadFromDatabase();
703 return $this->mEmail
;
706 function getEmailAuthenticationTimestamp() {
707 $this->loadFromDatabase();
708 return $this->mEmailAuthenticated
;
711 function setEmail( $str ) {
712 $this->loadFromDatabase();
713 $this->mEmail
= $str;
716 function getRealName() {
717 $this->loadFromDatabase();
718 return $this->mRealName
;
721 function setRealName( $str ) {
722 $this->loadFromDatabase();
723 $this->mRealName
= $str;
726 function getOption( $oname ) {
727 $this->loadFromDatabase();
728 if ( array_key_exists( $oname, $this->mOptions
) ) {
729 return $this->mOptions
[$oname];
735 function setOption( $oname, $val ) {
736 $this->loadFromDatabase();
737 if ( $oname == 'skin' ) {
738 # Clear cached skin, so the new one displays immediately in Special:Preferences
739 unset( $this->mSkin
);
741 $this->mOptions
[$oname] = $val;
742 $this->invalidateCache();
745 function getRights() {
746 $this->loadFromDatabase();
747 return $this->mRights
;
750 function addRight( $rname ) {
751 $this->loadFromDatabase();
752 array_push( $this->mRights
, $rname );
753 $this->invalidateCache();
756 function getGroups() {
757 $this->loadFromDatabase();
758 return $this->mGroups
;
761 function setGroups($groups) {
762 $this->loadFromDatabase();
763 $this->mGroups
= $groups;
764 $this->invalidateCache();
768 * A more legible check for non-anonymousness.
769 * Returns true if the user is not an anonymous visitor.
773 function isLoggedIn() {
774 return( $this->getID() != 0 );
778 * A more legible check for anonymousness.
779 * Returns true if the user is an anonymous visitor.
784 return !$this->isLoggedIn();
788 * Check if a user is sysop
789 * Die with backtrace. Use User:isAllowed() instead.
793 wfDebugDieBacktrace("User::isSysop() is deprecated. Use User::isAllowed() instead");
797 function isDeveloper() {
798 wfDebugDieBacktrace("User::isDeveloper() is deprecated. Use User::isAllowed() instead");
802 function isBureaucrat() {
803 wfDebugDieBacktrace("User::isBureaucrat() is deprecated. Use User::isAllowed() instead");
807 * Whether the user is a bot
808 * @todo need to be migrated to the new user level management sytem
811 $this->loadFromDatabase();
812 return in_array( 'bot', $this->mRights
);
816 * Check if user is allowed to access a feature / make an action
817 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
818 * @return boolean True: action is allowed, False: action should not be allowed
820 function isAllowed($action='') {
821 $this->loadFromDatabase();
822 return in_array( $action , $this->mRights
);
826 * Load a skin if it doesn't exist or return it
827 * @todo FIXME : need to check the old failback system [AV]
829 function &getSkin() {
831 if ( ! isset( $this->mSkin
) ) {
832 $fname = 'User::getSkin';
833 wfProfileIn( $fname );
835 # get all skin names available
836 $skinNames = Skin
::getSkinNames();
839 $userSkin = $this->getOption( 'skin' );
840 if ( $userSkin == '' ) { $userSkin = 'standard'; }
842 if ( !isset( $skinNames[$userSkin] ) ) {
843 # in case the user skin could not be found find a replacement
848 # if phptal is enabled we should have monobook skin that
849 # superseed the good old SkinStandard.
850 if ( isset( $skinNames['monobook'] ) ) {
851 $fallback[0] = 'MonoBook';
854 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
855 $sn = $fallback[$userSkin];
860 # The user skin is available
861 $sn = $skinNames[$userSkin];
864 # Grab the skin class and initialise it. Each skin checks for PHPTal
865 # and will not load if it's not enabled.
866 require_once( $IP.'/skins/'.$sn.'.php' );
868 # Check if we got if not failback to default skin
869 $className = 'Skin'.$sn;
870 if( !class_exists( $className ) ) {
871 # DO NOT die if the class isn't found. This breaks maintenance
872 # scripts and can cause a user account to be unrecoverable
873 # except by SQL manipulation if a previously valid skin name
874 # is no longer valid.
875 $className = 'SkinStandard';
876 require_once( $IP.'/skins/Standard.php' );
878 $this->mSkin
=& new $className;
879 wfProfileOut( $fname );
885 * @param string $title Article title to look at
889 * Check watched status of an article
890 * @return bool True if article is watched
892 function isWatched( $title ) {
893 $wl = WatchedItem
::fromUserTitle( $this, $title );
894 return $wl->isWatched();
900 function addWatch( $title ) {
901 $wl = WatchedItem
::fromUserTitle( $this, $title );
903 $this->invalidateCache();
907 * Stop watching an article
909 function removeWatch( $title ) {
910 $wl = WatchedItem
::fromUserTitle( $this, $title );
912 $this->invalidateCache();
916 * Clear the user's notification timestamp for the given title.
917 * If e-notif e-mails are on, they will receive notification mails on
918 * the next change of the page if it's watched etc.
920 function clearNotification( &$title ) {
923 $userid = $this->getID();
927 // Only update the timestamp if the page is being watched.
928 // The query to find out if it is watched is cached both in memcached and per-invocation,
929 // and when it does have to be executed, it can be on a slave
930 // If this is the user's newtalk page, we always update the timestamp
931 if ($title->getNamespace() == NS_USER_TALK
&&
932 $title->getText() == $wgUser->getName())
935 } elseif ( $this->getID() == $wgUser->getID() ) {
936 $watched = $title->userIsWatching();
941 // If the page is watched by the user (or may be watched), update the timestamp on any
944 $dbw =& wfGetDB( DB_MASTER
);
945 $success = $dbw->update( 'watchlist',
947 'wl_notificationtimestamp' => 0
948 ), array( /* WHERE */
949 'wl_title' => $title->getDBkey(),
950 'wl_namespace' => $title->getNamespace(),
951 'wl_user' => $this->getID()
952 ), 'User::clearLastVisited'
960 * Resets all of the given user's page-change notification timestamps.
961 * If e-notif e-mails are on, they will receive notification mails on
962 * the next change of any watched page.
964 * @param int $currentUser user ID number
967 function clearAllNotifications( $currentUser ) {
968 if( $currentUser != 0 ) {
970 $dbw =& wfGetDB( DB_MASTER
);
971 $success = $dbw->update( 'watchlist',
973 'wl_notificationtimestamp' => 0
974 ), array( /* WHERE */
975 'wl_user' => $currentUser
976 ), 'UserMailer::clearAll'
979 # we also need to clear here the "you have new message" notification for the own user_talk page
980 # This is cleared one page view later in Article::viewUpdates();
986 * @return string Encoding options
988 function encodeOptions() {
990 foreach ( $this->mOptions
as $oname => $oval ) {
991 array_push( $a, $oname.'='.$oval );
993 $s = implode( "\n", $a );
1000 function decodeOptions( $str ) {
1001 $a = explode( "\n", $str );
1002 foreach ( $a as $s ) {
1003 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1004 $this->mOptions
[$m[1]] = $m[2];
1009 function setCookies() {
1010 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
1011 if ( 0 == $this->mId
) return;
1012 $this->loadFromDatabase();
1013 $exp = time() +
$wgCookieExpiration;
1015 $_SESSION['wsUserID'] = $this->mId
;
1016 setcookie( $wgDBname.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain );
1018 $_SESSION['wsUserName'] = $this->mName
;
1019 setcookie( $wgDBname.'UserName', $this->mName
, $exp, $wgCookiePath, $wgCookieDomain );
1021 $_SESSION['wsToken'] = $this->mToken
;
1022 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1023 setcookie( $wgDBname.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain );
1025 setcookie( $wgDBname.'Token', '', time() - 3600 );
1031 * It will clean the session cookie
1034 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
1035 $this->loadDefaults();
1036 $this->setLoaded( true );
1038 $_SESSION['wsUserID'] = 0;
1040 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1041 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1043 # Remember when user logged out, to prevent seeing cached pages
1044 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain );
1048 * Save object settings into database
1050 function saveSettings() {
1051 global $wgMemc, $wgDBname;
1052 $fname = 'User::saveSettings';
1054 $dbw =& wfGetDB( DB_MASTER
);
1055 if ( ! $this->getNewtalk() ) {
1056 # Delete the watchlist entry for user_talk page X watched by user X
1057 $dbw->delete( 'watchlist',
1058 array( 'wl_user' => $this->mId
,
1059 'wl_title' => $this->getTitleKey(),
1060 'wl_namespace' => NS_USER_TALK
),
1063 # Anon users have a separate memcache space for newtalk
1064 # since they don't store their own info. Trim...
1065 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1069 if ( 0 == $this->mId
) { return; }
1071 $dbw->update( 'user',
1073 'user_name' => $this->mName
,
1074 'user_password' => $this->mPassword
,
1075 'user_newpassword' => $this->mNewpassword
,
1076 'user_real_name' => $this->mRealName
,
1077 'user_email' => $this->mEmail
,
1078 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1079 'user_options' => $this->encodeOptions(),
1080 'user_touched' => $dbw->timestamp($this->mTouched
),
1081 'user_token' => $this->mToken
1082 ), array( /* WHERE */
1083 'user_id' => $this->mId
1086 $dbw->set( 'user_rights', 'ur_rights', implode( ',', $this->mRights
),
1087 'ur_user='. $this->mId
, $fname );
1088 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1090 // delete old groups
1091 $dbw->delete( 'user_groups', array( 'ug_user' => $this->mId
), $fname);
1094 foreach ($this->mGroups
as $group) {
1095 $dbw->replace( 'user_groups',
1096 array(array('ug_user','ug_group')),
1098 'ug_user' => $this->mId
,
1099 'ug_group' => $group
1107 * Checks if a user with the given name exists, returns the ID
1109 function idForName() {
1110 $fname = 'User::idForName';
1113 $s = trim( $this->mName
);
1114 if ( 0 == strcmp( '', $s ) ) return 0;
1116 $dbr =& wfGetDB( DB_SLAVE
);
1117 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1118 if ( $id === false ) {
1125 * Add user object to the database
1127 function addToDatabase() {
1128 $fname = 'User::addToDatabase';
1129 $dbw =& wfGetDB( DB_MASTER
);
1130 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1131 $dbw->insert( 'user',
1133 'user_id' => $seqVal,
1134 'user_name' => $this->mName
,
1135 'user_password' => $this->mPassword
,
1136 'user_newpassword' => $this->mNewpassword
,
1137 'user_email' => $this->mEmail
,
1138 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1139 'user_real_name' => $this->mRealName
,
1140 'user_options' => $this->encodeOptions(),
1141 'user_token' => $this->mToken
1144 $this->mId
= $dbw->insertId();
1145 $dbw->insert( 'user_rights',
1147 'ur_user' => $this->mId
,
1148 'ur_rights' => implode( ',', $this->mRights
)
1152 foreach ($this->mGroups
as $group) {
1153 $dbw->insert( 'user_groups',
1155 'ug_user' => $this->mId
,
1156 'ug_group' => $group
1162 function spreadBlock() {
1164 # If the (non-anonymous) user is blocked, this function will block any IP address
1165 # that they successfully log on from.
1166 $fname = 'User::spreadBlock';
1168 wfDebug( "User:spreadBlock()\n" );
1169 if ( $this->mId
== 0 ) {
1173 $userblock = Block
::newFromDB( '', $this->mId
);
1174 if ( !$userblock->isValid() ) {
1178 # Check if this IP address is already blocked
1179 $ipblock = Block
::newFromDB( $wgIP );
1180 if ( $ipblock->isValid() ) {
1181 # Just update the timestamp
1182 $ipblock->updateTimestamp();
1186 # Make a new block object with the desired properties
1187 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1188 $ipblock->mAddress
= $wgIP;
1189 $ipblock->mUser
= 0;
1190 $ipblock->mBy
= $userblock->mBy
;
1191 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
1192 $ipblock->mTimestamp
= wfTimestampNow();
1193 $ipblock->mAuto
= 1;
1194 # If the user is already blocked with an expiry date, we don't
1195 # want to pile on top of that!
1196 if($userblock->mExpiry
) {
1197 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
1199 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
1207 function getPageRenderingHash() {
1210 return $this->mHash
;
1213 // stubthreshold is only included below for completeness,
1214 // it will always be 0 when this function is called by parsercache.
1216 $confstr = $this->getOption( 'math' );
1217 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1218 $confstr .= '!' . $this->getOption( 'editsection' );
1219 $confstr .= '!' . $this->getOption( 'date' );
1220 $confstr .= '!' . $this->getOption( 'numberheadings' );
1221 $confstr .= '!' . $this->getOption( 'language' );
1222 $confstr .= '!' . $this->getOption( 'thumbsize' );
1223 // add in language specific options, if any
1224 $extra = $wgContLang->getExtraHashOptions();
1227 $this->mHash
= $confstr;
1231 function isAllowedToCreateAccount() {
1232 global $wgWhitelistAccount;
1235 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1236 foreach ($wgWhitelistAccount as $right => $ok) {
1237 $userHasRight = (!strcmp($right, 'user') ||
in_array($right, $this->getRights()));
1238 $allowed |
= ($ok && $userHasRight);
1244 * Set mDataLoaded, return previous value
1245 * Use this to prevent DB access in command-line scripts or similar situations
1247 function setLoaded( $loaded ) {
1248 return wfSetVar( $this->mDataLoaded
, $loaded );
1252 * Get this user's personal page title.
1257 function getUserPage() {
1258 return Title
::makeTitle( NS_USER
, $this->mName
);
1262 * Get this user's talk page title.
1267 function getTalkPage() {
1268 $title = $this->getUserPage();
1269 return $title->getTalkPage();
1275 function getMaxID() {
1276 $dbr =& wfGetDB( DB_SLAVE
);
1277 return $dbr->selectField( 'user', 'max(user_id)', false );
1281 * Determine whether the user is a newbie. Newbies are either
1282 * anonymous IPs, or the 1% most recently created accounts.
1283 * Bots and sysops are excluded.
1284 * @return bool True if it is a newbie.
1286 function isNewbie() {
1287 return $this->mId
> User
::getMaxID() * 0.99 && !$this->isAllowed( 'delete' ) && !$this->isBot() ||
$this->getID() == 0;
1291 * Check to see if the given clear-text password is one of the accepted passwords
1292 * @param string $password User password.
1293 * @return bool True if the given password is correct otherwise False.
1295 function checkPassword( $password ) {
1297 $this->loadFromDatabase();
1299 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1301 } elseif( $wgAuth->strict() ) {
1302 /* Auth plugin doesn't allow local authentication */
1305 $ep = $this->encryptPassword( $password );
1306 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
1308 } elseif ( ($this->mNewpassword
!= '') && (0 == strcmp( $ep, $this->mNewpassword
)) ) {
1309 # If e-mail confirmation hasn't been done already,
1310 # we may as well confirm it here -- the user can only
1311 # get this password via e-mail.
1312 $this->mEmailAuthenticated
= wfTimestampNow();
1314 # use the temporary one-time password only once: clear it now !
1315 $this->mNewpassword
= '';
1316 $this->saveSettings();
1318 } elseif ( function_exists( 'iconv' ) ) {
1319 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1320 # Check for this with iconv
1321 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1322 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
1330 * Initialize (if necessary) and return a session token value
1331 * which can be used in edit forms to show that the user's
1332 * login credentials aren't being hijacked with a foreign form
1335 * @param mixed $salt - Optional function-specific data for hash.
1336 * Use a string or an array of strings.
1340 function editToken( $salt = '' ) {
1341 if( !isset( $_SESSION['wsEditToken'] ) ) {
1342 $token = $this->generateToken();
1343 $_SESSION['wsEditToken'] = $token;
1345 $token = $_SESSION['wsEditToken'];
1347 if( is_array( $salt ) ) {
1348 $salt = implode( '|', $salt );
1350 return md5( $token . $salt );
1354 * Generate a hex-y looking random token for various uses.
1355 * Could be made more cryptographically sure if someone cares.
1358 function generateToken( $salt = '' ) {
1359 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1360 return md5( $token . $salt );
1364 * Check given value against the token value stored in the session.
1365 * A match should confirm that the form was submitted from the
1366 * user's own login session, not a form submission from a third-party
1369 * @param string $val - the input value to compare
1370 * @param string $salt - Optional function-specific data for hash
1374 function matchEditToken( $val, $salt = '' ) {
1375 return ( $val == $this->editToken( $salt ) );
1379 * Generate a new e-mail confirmation token and send a confirmation
1380 * mail to the user's given address.
1382 * @return mixed True on success, a WikiError object on failure.
1384 function sendConfirmationMail() {
1385 global $wgIP, $wgContLang;
1386 $url = $this->confirmationTokenUrl( $expiration );
1387 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1388 wfMsg( 'confirmemail_body',
1392 $wgContLang->timeanddate( $expiration, false ) ) );
1396 * Send an e-mail to this user's account. Does not check for
1397 * confirmed status or validity.
1399 * @param string $subject
1400 * @param string $body
1401 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1402 * @return mixed True on success, a WikiError object on failure.
1404 function sendMail( $subject, $body, $from = null ) {
1405 if( is_null( $from ) ) {
1406 global $wgPasswordSender;
1407 $from = $wgPasswordSender;
1410 require_once( 'UserMailer.php' );
1411 $error = userMailer( $this->getEmail(), $from, $subject, $body );
1413 if( $error == '' ) {
1416 return new WikiError( $error );
1421 * Generate, store, and return a new e-mail confirmation code.
1422 * A hash (unsalted since it's used as a key) is stored.
1423 * @param &$expiration mixed output: accepts the expiration time
1427 function confirmationToken( &$expiration ) {
1428 $fname = 'User::confirmationToken';
1431 $expires = $now +
7 * 24 * 60 * 60;
1432 $expiration = wfTimestamp( TS_MW
, $expires );
1434 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
1435 $hash = md5( $token );
1437 $dbw =& wfGetDB( DB_MASTER
);
1438 $dbw->update( 'user',
1439 array( 'user_email_token' => $hash,
1440 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1441 array( 'user_id' => $this->mId
),
1448 * Generate and store a new e-mail confirmation token, and return
1449 * the URL the user can use to confirm.
1450 * @param &$expiration mixed output: accepts the expiration time
1454 function confirmationTokenUrl( &$expiration ) {
1455 $token = $this->confirmationToken( $expiration );
1456 $title = Title
::makeTitle( NS_SPECIAL
, 'Confirmemail/' . $token );
1457 return $title->getFullUrl();
1461 * Mark the e-mail address confirmed and save.
1463 function confirmEmail() {
1464 $this->loadFromDatabase();
1465 $this->mEmailAuthenticated
= wfTimestampNow();
1466 $this->saveSettings();
1471 * Is this user allowed to send e-mails within limits of current
1472 * site configuration?
1475 function canSendEmail() {
1476 return $this->isEmailConfirmed();
1480 * Is this user allowed to receive e-mails within limits of current
1481 * site configuration?
1484 function canReceiveEmail() {
1485 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1489 * Is this user's e-mail address valid-looking and confirmed within
1490 * limits of the current site configuration?
1492 * If $wgEmailAuthentication is on, this may require the user to have
1493 * confirmed their address by returning a code or using a password
1494 * sent to the address from the wiki.
1498 function isEmailConfirmed() {
1499 global $wgEmailAuthentication;
1500 $this->loadFromDatabase();
1501 if( $this->isAnon() )
1503 if( !$this->isValidEmailAddr( $this->mEmail
) )
1505 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )