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 if ( 0 === $this->mBlockedby
) { return false; }
386 * Get name of blocker
387 * @return string name of blocker
389 function blockedBy() {
390 $this->getBlockedStatus();
391 return $this->mBlockedby
;
395 * Get blocking reason
396 * @return string Blocking reason
398 function blockedFor() {
399 $this->getBlockedStatus();
400 return $this->mBlockreason
;
404 * Initialise php session
406 function SetupSession() {
407 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
408 if( $wgSessionsInMemcached ) {
409 require_once( 'MemcachedSessions.php' );
410 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
411 # If it's left on 'user' or another setting from another
412 # application, it will end up failing. Try to recover.
413 ini_set ( 'session.save_handler', 'files' );
415 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
416 session_cache_limiter( 'private, must-revalidate' );
421 * Read datas from session
424 function loadFromSession() {
425 global $wgMemc, $wgDBname;
427 if ( isset( $_SESSION['wsUserID'] ) ) {
428 if ( 0 != $_SESSION['wsUserID'] ) {
429 $sId = $_SESSION['wsUserID'];
433 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
434 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
435 $_SESSION['wsUserID'] = $sId;
439 if ( isset( $_SESSION['wsUserName'] ) ) {
440 $sName = $_SESSION['wsUserName'];
441 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
442 $sName = $_COOKIE["{$wgDBname}UserName"];
443 $_SESSION['wsUserName'] = $sName;
448 $passwordCorrect = FALSE;
449 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
450 if($makenew = !$user) {
451 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
454 $user->loadFromDatabase();
456 wfDebug( "User::loadFromSession() got from cache!\n" );
459 if ( isset( $_SESSION['wsToken'] ) ) {
460 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken
;
461 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
462 $passwordCorrect = $user->mToken
== $_COOKIE["{$wgDBname}Token"];
464 return new User(); # Can't log in from session
467 if ( ( $sName == $user->mName
) && $passwordCorrect ) {
469 if($wgMemc->set( $key, $user ))
470 wfDebug( "User::loadFromSession() successfully saved user\n" );
472 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
476 return new User(); # Can't log in from session
480 * Load a user from the database
482 function loadFromDatabase() {
483 global $wgCommandLineMode, $wgAnonGroupId, $wgLoggedInGroupId;
484 $fname = "User::loadFromDatabase";
486 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
487 # loading in a command line script, don't assume all command line scripts need it like this
488 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
489 if ( $this->mDataLoaded
) {
494 $this->mId
= IntVal( $this->mId
);
496 /** Anonymous user */
499 $anong = Group
::newFromId($wgAnonGroupId);
501 wfDebugDieBacktrace("Please update your database schema "
502 ."and populate initial group data from "
503 ."maintenance/archives patches");
504 $anong->loadFromDatabase();
505 $this->mRights
= explode(',', $anong->getRights());
506 $this->mDataLoaded
= true;
508 } # the following stuff is for non-anonymous users only
510 $dbr =& wfGetDB( DB_SLAVE
);
511 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
512 'user_email_authenticated',
513 'user_real_name','user_options','user_touched', 'user_token' ),
514 array( 'user_id' => $this->mId
), $fname );
516 if ( $s !== false ) {
517 $this->mName
= $s->user_name
;
518 $this->mEmail
= $s->user_email
;
519 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
520 $this->mRealName
= $s->user_real_name
;
521 $this->mPassword
= $s->user_password
;
522 $this->mNewpassword
= $s->user_newpassword
;
523 $this->decodeOptions( $s->user_options
);
524 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
525 $this->mToken
= $s->user_token
;
528 $res = $dbr->select( 'user_groups', array( 'ug_group' ), array( 'ug_user' => $this->mId
) );
530 while($group = $dbr->fetchRow($res)) {
531 $this->mGroups
[] = $group[0];
534 // add the default group for logged in user
535 $this->mGroups
[] = $wgLoggedInGroupId;
537 $this->mRights
= array();
538 // now we merge groups rights to get this user rights
539 foreach($this->mGroups
as $aGroupId) {
540 $g = Group
::newFromId($aGroupId);
541 $g->loadFromDatabase();
542 $this->mRights
= array_merge($this->mRights
, explode(',', $g->getRights()));
545 // array merge duplicate rights which are part of several groups
546 $this->mRights
= array_unique($this->mRights
);
548 $dbr->freeResult($res);
551 $this->mDataLoaded
= true;
554 function getID() { return $this->mId
; }
555 function setID( $v ) {
557 $this->mDataLoaded
= false;
561 $this->loadFromDatabase();
565 function setName( $str ) {
566 $this->loadFromDatabase();
572 * Return the title dbkey form of the name, for eg user pages.
576 function getTitleKey() {
577 return str_replace( ' ', '_', $this->getName() );
580 function getNewtalk() {
581 $fname = 'User::getNewtalk';
582 $this->loadFromDatabase();
584 # Load the newtalk status if it is unloaded (mNewtalk=-1)
585 if( $this->mNewtalk
== -1 ) {
586 $this->mNewtalk
= 0; # reset talk page status
588 # Check memcached separately for anons, who have no
589 # entire User object stored in there.
591 global $wgDBname, $wgMemc;
592 $key = "$wgDBname:newtalk:ip:{$this->mName}";
593 $newtalk = $wgMemc->get( $key );
594 if( is_integer( $newtalk ) ) {
595 $this->mNewtalk
= $newtalk ?
1 : 0;
596 return (bool)$this->mNewtalk
;
600 $dbr =& wfGetDB( DB_SLAVE
);
601 $res = $dbr->select( 'watchlist',
603 array( 'wl_title' => $this->getTitleKey(),
604 'wl_namespace' => NS_USER_TALK
,
605 'wl_user' => $this->mId
,
606 'wl_notificationtimestamp != 0' ),
607 'User::getNewtalk' );
608 if( $dbr->numRows($res) > 0 ) {
611 $dbr->freeResult( $res );
614 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
618 return ( 0 != $this->mNewtalk
);
621 function setNewtalk( $val ) {
622 $this->loadFromDatabase();
623 $this->mNewtalk
= $val;
624 $this->invalidateCache();
627 function invalidateCache() {
628 $this->loadFromDatabase();
629 $this->mTouched
= wfTimestampNow();
630 # Don't forget to save the options after this or
631 # it won't take effect!
634 function validateCache( $timestamp ) {
635 $this->loadFromDatabase();
636 return ($timestamp >= $this->mTouched
);
641 * Will only be salted if $wgPasswordSalt is true
642 * @param string Password.
643 * @return string Salted password or clear password.
645 function addSalt( $p ) {
646 global $wgPasswordSalt;
648 return md5( "{$this->mId}-{$p}" );
654 * Encrypt a password.
655 * It can eventuall salt a password @see User::addSalt()
656 * @param string $p clear Password.
657 * @param string Encrypted password.
659 function encryptPassword( $p ) {
660 return $this->addSalt( md5( $p ) );
663 # Set the password and reset the random token
664 function setPassword( $str ) {
665 $this->loadFromDatabase();
667 $this->mPassword
= $this->encryptPassword( $str );
668 $this->mNewpassword
= '';
671 # Set the random token (used for persistent authentication)
672 function setToken( $token = false ) {
673 global $wgSecretKey, $wgProxyKey, $wgDBname;
675 if ( $wgSecretKey ) {
677 } elseif ( $wgProxyKey ) {
682 $this->mToken
= md5( $wgSecretKey . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId
);
684 $this->mToken
= $token;
689 function setCookiePassword( $str ) {
690 $this->loadFromDatabase();
691 $this->mCookiePassword
= md5( $str );
694 function setNewpassword( $str ) {
695 $this->loadFromDatabase();
696 $this->mNewpassword
= $this->encryptPassword( $str );
699 function getEmail() {
700 $this->loadFromDatabase();
701 return $this->mEmail
;
704 function getEmailAuthenticationTimestamp() {
705 $this->loadFromDatabase();
706 return $this->mEmailAuthenticated
;
709 function setEmail( $str ) {
710 $this->loadFromDatabase();
711 $this->mEmail
= $str;
714 function getRealName() {
715 $this->loadFromDatabase();
716 return $this->mRealName
;
719 function setRealName( $str ) {
720 $this->loadFromDatabase();
721 $this->mRealName
= $str;
724 function getOption( $oname ) {
725 $this->loadFromDatabase();
726 if ( array_key_exists( $oname, $this->mOptions
) ) {
727 return $this->mOptions
[$oname];
733 function setOption( $oname, $val ) {
734 $this->loadFromDatabase();
735 if ( $oname == 'skin' ) {
736 # Clear cached skin, so the new one displays immediately in Special:Preferences
737 unset( $this->mSkin
);
739 $this->mOptions
[$oname] = $val;
740 $this->invalidateCache();
743 function getRights() {
744 $this->loadFromDatabase();
745 return $this->mRights
;
748 function addRight( $rname ) {
749 $this->loadFromDatabase();
750 array_push( $this->mRights
, $rname );
751 $this->invalidateCache();
754 function getGroups() {
755 $this->loadFromDatabase();
756 return $this->mGroups
;
759 function setGroups($groups) {
760 $this->loadFromDatabase();
761 $this->mGroups
= $groups;
762 $this->invalidateCache();
766 * A more legible check for non-anonymousness.
767 * Returns true if the user is not an anonymous visitor.
771 function isLoggedIn() {
772 return( $this->getID() != 0 );
776 * A more legible check for anonymousness.
777 * Returns true if the user is an anonymous visitor.
782 return !$this->isLoggedIn();
786 * Check if a user is sysop
787 * Die with backtrace. Use User:isAllowed() instead.
791 wfDebugDieBacktrace("User::isSysop() is deprecated. Use User::isAllowed() instead");
795 function isDeveloper() {
796 wfDebugDieBacktrace("User::isDeveloper() is deprecated. Use User::isAllowed() instead");
800 function isBureaucrat() {
801 wfDebugDieBacktrace("User::isBureaucrat() is deprecated. Use User::isAllowed() instead");
805 * Whether the user is a bot
806 * @todo need to be migrated to the new user level management sytem
809 $this->loadFromDatabase();
811 # Why was this here? I need a UID=0 conversion script [TS]
812 # if ( 0 == $this->mId ) { return false; }
814 return in_array( 'bot', $this->mRights
);
818 * Check if user is allowed to access a feature / make an action
819 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
820 * @return boolean True: action is allowed, False: action should not be allowed
822 function isAllowed($action='') {
823 $this->loadFromDatabase();
824 return in_array( $action , $this->mRights
);
828 * Load a skin if it doesn't exist or return it
829 * @todo FIXME : need to check the old failback system [AV]
831 function &getSkin() {
833 if ( ! isset( $this->mSkin
) ) {
834 $fname = 'User::getSkin';
835 wfProfileIn( $fname );
837 # get all skin names available
838 $skinNames = Skin
::getSkinNames();
841 $userSkin = $this->getOption( 'skin' );
842 if ( $userSkin == '' ) { $userSkin = 'standard'; }
844 if ( !isset( $skinNames[$userSkin] ) ) {
845 # in case the user skin could not be found find a replacement
850 # if phptal is enabled we should have monobook skin that
851 # superseed the good old SkinStandard.
852 if ( isset( $skinNames['monobook'] ) ) {
853 $fallback[0] = 'MonoBook';
856 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
857 $sn = $fallback[$userSkin];
862 # The user skin is available
863 $sn = $skinNames[$userSkin];
866 # Grab the skin class and initialise it. Each skin checks for PHPTal
867 # and will not load if it's not enabled.
868 require_once( $IP.'/skins/'.$sn.'.php' );
870 # Check if we got if not failback to default skin
871 $className = 'Skin'.$sn;
872 if( !class_exists( $className ) ) {
873 # DO NOT die if the class isn't found. This breaks maintenance
874 # scripts and can cause a user account to be unrecoverable
875 # except by SQL manipulation if a previously valid skin name
876 # is no longer valid.
877 $className = 'SkinStandard';
878 require_once( $IP.'/skins/Standard.php' );
880 $this->mSkin
=& new $className;
881 wfProfileOut( $fname );
887 * @param string $title Article title to look at
891 * Check watched status of an article
892 * @return bool True if article is watched
894 function isWatched( $title ) {
895 $wl = WatchedItem
::fromUserTitle( $this, $title );
896 return $wl->isWatched();
902 function addWatch( $title ) {
903 $wl = WatchedItem
::fromUserTitle( $this, $title );
905 $this->invalidateCache();
909 * Stop watching an article
911 function removeWatch( $title ) {
912 $wl = WatchedItem
::fromUserTitle( $this, $title );
914 $this->invalidateCache();
918 * Clear the user's notification timestamp for the given title.
919 * If e-notif e-mails are on, they will receive notification mails on
920 * the next change of the page if it's watched etc.
922 function clearNotification( $title ) {
923 $userid = $this->getId();
926 $dbw =& wfGetDB( DB_MASTER
);
927 $success = $dbw->update( 'watchlist',
929 'wl_notificationtimestamp' => 0
930 ), array( /* WHERE */
931 'wl_title' => $title->getDBkey(),
932 'wl_namespace' => $title->getNamespace(),
933 'wl_user' => $this->getId()
934 ), 'User::clearLastVisited'
941 * Resets all of the given user's page-change notification timestamps.
942 * If e-notif e-mails are on, they will receive notification mails on
943 * the next change of any watched page.
945 * @param int $currentUser user ID number
948 function clearAllNotifications( $currentUser ) {
949 if( $currentUser != 0 ) {
951 $dbw =& wfGetDB( DB_MASTER
);
952 $success = $dbw->update( 'watchlist',
954 'wl_notificationtimestamp' => 0
955 ), array( /* WHERE */
956 'wl_user' => $currentUser
957 ), 'UserMailer::clearAll'
960 # we also need to clear here the "you have new message" notification for the own user_talk page
961 # This is cleared one page view later in Article::viewUpdates();
967 * @return string Encoding options
969 function encodeOptions() {
971 foreach ( $this->mOptions
as $oname => $oval ) {
972 array_push( $a, $oname.'='.$oval );
974 $s = implode( "\n", $a );
981 function decodeOptions( $str ) {
982 $a = explode( "\n", $str );
983 foreach ( $a as $s ) {
984 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
985 $this->mOptions
[$m[1]] = $m[2];
990 function setCookies() {
991 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
992 if ( 0 == $this->mId
) return;
993 $this->loadFromDatabase();
994 $exp = time() +
$wgCookieExpiration;
996 $_SESSION['wsUserID'] = $this->mId
;
997 setcookie( $wgDBname.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain );
999 $_SESSION['wsUserName'] = $this->mName
;
1000 setcookie( $wgDBname.'UserName', $this->mName
, $exp, $wgCookiePath, $wgCookieDomain );
1002 $_SESSION['wsToken'] = $this->mToken
;
1003 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1004 setcookie( $wgDBname.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain );
1006 setcookie( $wgDBname.'Token', '', time() - 3600 );
1012 * It will clean the session cookie
1015 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
1016 $this->loadDefaults();
1017 $this->setLoaded( true );
1019 $_SESSION['wsUserID'] = 0;
1021 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1022 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1024 # Remember when user logged out, to prevent seeing cached pages
1025 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain );
1029 * Save object settings into database
1031 function saveSettings() {
1032 global $wgMemc, $wgDBname;
1033 $fname = 'User::saveSettings';
1035 $dbw =& wfGetDB( DB_MASTER
);
1036 if ( ! $this->getNewtalk() ) {
1037 # Delete the watchlist entry for user_talk page X watched by user X
1038 $dbw->delete( 'watchlist',
1039 array( 'wl_user' => $this->mId
,
1040 'wl_title' => $this->getTitleKey(),
1041 'wl_namespace' => NS_USER_TALK
),
1044 # Anon users have a separate memcache space for newtalk
1045 # since they don't store their own info. Trim...
1046 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1050 if ( 0 == $this->mId
) { return; }
1052 $dbw->update( 'user',
1054 'user_name' => $this->mName
,
1055 'user_password' => $this->mPassword
,
1056 'user_newpassword' => $this->mNewpassword
,
1057 'user_real_name' => $this->mRealName
,
1058 'user_email' => $this->mEmail
,
1059 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1060 'user_options' => $this->encodeOptions(),
1061 'user_touched' => $dbw->timestamp($this->mTouched
),
1062 'user_token' => $this->mToken
1063 ), array( /* WHERE */
1064 'user_id' => $this->mId
1067 $dbw->set( 'user_rights', 'ur_rights', implode( ',', $this->mRights
),
1068 'ur_user='. $this->mId
, $fname );
1069 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1071 // delete old groups
1072 $dbw->delete( 'user_groups', array( 'ug_user' => $this->mId
), $fname);
1075 foreach ($this->mGroups
as $group) {
1076 $dbw->replace( 'user_groups',
1077 array(array('ug_user','ug_group')),
1079 'ug_user' => $this->mId
,
1080 'ug_group' => $group
1088 * Checks if a user with the given name exists, returns the ID
1090 function idForName() {
1091 $fname = 'User::idForName';
1094 $s = trim( $this->mName
);
1095 if ( 0 == strcmp( '', $s ) ) return 0;
1097 $dbr =& wfGetDB( DB_SLAVE
);
1098 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1099 if ( $id === false ) {
1106 * Add user object to the database
1108 function addToDatabase() {
1109 $fname = 'User::addToDatabase';
1110 $dbw =& wfGetDB( DB_MASTER
);
1111 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1112 $dbw->insert( 'user',
1114 'user_id' => $seqVal,
1115 'user_name' => $this->mName
,
1116 'user_password' => $this->mPassword
,
1117 'user_newpassword' => $this->mNewpassword
,
1118 'user_email' => $this->mEmail
,
1119 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1120 'user_real_name' => $this->mRealName
,
1121 'user_options' => $this->encodeOptions(),
1122 'user_token' => $this->mToken
1125 $this->mId
= $dbw->insertId();
1126 $dbw->insert( 'user_rights',
1128 'ur_user' => $this->mId
,
1129 'ur_rights' => implode( ',', $this->mRights
)
1133 foreach ($this->mGroups
as $group) {
1134 $dbw->insert( 'user_groups',
1136 'ug_user' => $this->mId
,
1137 'ug_group' => $group
1143 function spreadBlock() {
1145 # If the (non-anonymous) user is blocked, this function will block any IP address
1146 # that they successfully log on from.
1147 $fname = 'User::spreadBlock';
1149 wfDebug( "User:spreadBlock()\n" );
1150 if ( $this->mId
== 0 ) {
1154 $userblock = Block
::newFromDB( '', $this->mId
);
1155 if ( !$userblock->isValid() ) {
1159 # Check if this IP address is already blocked
1160 $ipblock = Block
::newFromDB( $wgIP );
1161 if ( $ipblock->isValid() ) {
1162 # Just update the timestamp
1163 $ipblock->updateTimestamp();
1167 # Make a new block object with the desired properties
1168 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1169 $ipblock->mAddress
= $wgIP;
1170 $ipblock->mUser
= 0;
1171 $ipblock->mBy
= $userblock->mBy
;
1172 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
1173 $ipblock->mTimestamp
= wfTimestampNow();
1174 $ipblock->mAuto
= 1;
1175 # If the user is already blocked with an expiry date, we don't
1176 # want to pile on top of that!
1177 if($userblock->mExpiry
) {
1178 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
1180 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
1188 function getPageRenderingHash() {
1191 return $this->mHash
;
1194 // stubthreshold is only included below for completeness,
1195 // it will always be 0 when this function is called by parsercache.
1197 $confstr = $this->getOption( 'math' );
1198 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1199 $confstr .= '!' . $this->getOption( 'editsection' );
1200 $confstr .= '!' . $this->getOption( 'date' );
1201 $confstr .= '!' . $this->getOption( 'numberheadings' );
1202 $confstr .= '!' . $this->getOption( 'language' );
1203 $confstr .= '!' . $this->getOption( 'thumbsize' );
1204 // add in language specific options, if any
1205 $extra = $wgContLang->getExtraHashOptions();
1208 $this->mHash
= $confstr;
1212 function isAllowedToCreateAccount() {
1213 global $wgWhitelistAccount;
1216 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1217 foreach ($wgWhitelistAccount as $right => $ok) {
1218 $userHasRight = (!strcmp($right, 'user') ||
in_array($right, $this->getRights()));
1219 $allowed |
= ($ok && $userHasRight);
1225 * Set mDataLoaded, return previous value
1226 * Use this to prevent DB access in command-line scripts or similar situations
1228 function setLoaded( $loaded ) {
1229 return wfSetVar( $this->mDataLoaded
, $loaded );
1233 * Get this user's personal page title.
1238 function getUserPage() {
1239 return Title
::makeTitle( NS_USER
, $this->mName
);
1243 * Get this user's talk page title.
1248 function getTalkPage() {
1249 $title = $this->getUserPage();
1250 return $title->getTalkPage();
1256 function getMaxID() {
1257 $dbr =& wfGetDB( DB_SLAVE
);
1258 return $dbr->selectField( 'user', 'max(user_id)', false );
1262 * Determine whether the user is a newbie. Newbies are either
1263 * anonymous IPs, or the 1% most recently created accounts.
1264 * Bots and sysops are excluded.
1265 * @return bool True if it is a newbie.
1267 function isNewbie() {
1268 return $this->mId
> User
::getMaxID() * 0.99 && !$this->isSysop() && !$this->isBot() ||
$this->getID() == 0;
1272 * Check to see if the given clear-text password is one of the accepted passwords
1273 * @param string $password User password.
1274 * @return bool True if the given password is correct otherwise False.
1276 function checkPassword( $password ) {
1278 $this->loadFromDatabase();
1280 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1282 } elseif( $wgAuth->strict() ) {
1283 /* Auth plugin doesn't allow local authentication */
1286 $ep = $this->encryptPassword( $password );
1287 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
1289 } elseif ( ($this->mNewpassword
!= '') && (0 == strcmp( $ep, $this->mNewpassword
)) ) {
1290 # If e-mail confirmation hasn't been done already,
1291 # we may as well confirm it here -- the user can only
1292 # get this password via e-mail.
1293 $this->mEmailAuthenticated
= wfTimestampNow();
1295 # use the temporary one-time password only once: clear it now !
1296 $this->mNewpassword
= '';
1297 $this->saveSettings();
1299 } elseif ( function_exists( 'iconv' ) ) {
1300 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1301 # Check for this with iconv
1302 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1303 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
1311 * Initialize (if necessary) and return a session token value
1312 * which can be used in edit forms to show that the user's
1313 * login credentials aren't being hijacked with a foreign form
1316 * @param mixed $salt - Optional function-specific data for hash.
1317 * Use a string or an array of strings.
1321 function editToken( $salt = '' ) {
1322 if( !isset( $_SESSION['wsEditToken'] ) ) {
1323 $token = $this->generateToken();
1324 $_SESSION['wsEditToken'] = $token;
1326 $token = $_SESSION['wsEditToken'];
1328 if( is_array( $salt ) ) {
1329 $salt = implode( '|', $salt );
1331 return md5( $token . $salt );
1335 * Generate a hex-y looking random token for various uses.
1336 * Could be made more cryptographically sure if someone cares.
1339 function generateToken( $salt = '' ) {
1340 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1341 return md5( $token . $salt );
1345 * Check given value against the token value stored in the session.
1346 * A match should confirm that the form was submitted from the
1347 * user's own login session, not a form submission from a third-party
1350 * @param string $val - the input value to compare
1351 * @param string $salt - Optional function-specific data for hash
1355 function matchEditToken( $val, $salt = '' ) {
1356 return ( $val == $this->editToken( $salt ) );
1360 * Generate a new e-mail confirmation token and send a confirmation
1361 * mail to the user's given address.
1363 * @return mixed True on success, a WikiError object on failure.
1365 function sendConfirmationMail() {
1366 global $wgIP, $wgContLang;
1367 $url = $this->confirmationTokenUrl( $expiration );
1368 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1369 wfMsg( 'confirmemail_body',
1373 $wgContLang->timeanddate( $expiration, false ) ) );
1377 * Send an e-mail to this user's account. Does not check for
1378 * confirmed status or validity.
1380 * @param string $subject
1381 * @param string $body
1382 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1383 * @return mixed True on success, a WikiError object on failure.
1385 function sendMail( $subject, $body, $from = null ) {
1386 if( is_null( $from ) ) {
1387 global $wgPasswordSender;
1388 $from = $wgPasswordSender;
1391 require_once( 'UserMailer.php' );
1392 $error = userMailer( $this->getEmail(), $from, $subject, $body );
1394 if( $error == '' ) {
1397 return new WikiError( $error );
1402 * Generate, store, and return a new e-mail confirmation code.
1403 * A hash (unsalted since it's used as a key) is stored.
1404 * @param &$expiration mixed output: accepts the expiration time
1408 function confirmationToken( &$expiration ) {
1409 $fname = 'User::confirmationToken';
1412 $expires = $now +
7 * 24 * 60 * 60;
1413 $expiration = wfTimestamp( TS_MW
, $expires );
1415 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
1416 $hash = md5( $token );
1418 $dbw =& wfGetDB( DB_MASTER
);
1419 $dbw->update( 'user',
1420 array( 'user_email_token' => $hash,
1421 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1422 array( 'user_id' => $this->mId
),
1429 * Generate and store a new e-mail confirmation token, and return
1430 * the URL the user can use to confirm.
1431 * @param &$expiration mixed output: accepts the expiration time
1435 function confirmationTokenUrl( &$expiration ) {
1436 $token = $this->confirmationToken( $expiration );
1437 $title = Title
::makeTitle( NS_SPECIAL
, 'Confirmemail/' . $token );
1438 return $title->getFullUrl();
1442 * Mark the e-mail address confirmed and save.
1444 function confirmEmail() {
1445 $this->loadFromDatabase();
1446 $this->mEmailAuthenticated
= wfTimestampNow();
1447 $this->saveSettings();
1452 * Is this user allowed to send e-mails within limits of current
1453 * site configuration?
1456 function canSendEmail() {
1457 return $this->isEmailConfirmed();
1461 * Is this user allowed to receive e-mails within limits of current
1462 * site configuration?
1465 function canReceiveEmail() {
1466 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1470 * Is this user's e-mail address valid-looking and confirmed within
1471 * limits of the current site configuration?
1473 * If $wgEmailAuthentication is on, this may require the user to have
1474 * confirmed their address by returning a code or using a password
1475 * sent to the address from the wiki.
1479 function isEmailConfirmed() {
1480 global $wgEmailAuthentication;
1481 $this->loadFromDatabase();
1482 if( $this->isAnon() )
1484 if( !$this->isValidEmailAddr( $this->mEmail
) )
1486 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )