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 $mEmailAuthenticationtimestamp;
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
47 * @param string $name Username, validated by Title:newFromText()
49 function newFromName( $name ) {
52 # Clean up name according to title rules
54 $t = Title
::newFromText( $name );
58 $u->setName( $t->getText() );
59 $u->setId( $u->idFromName( $t->getText() ) );
65 * Get username given an id.
66 * @param integer $id Database user id
67 * @return string Nickname of a user
70 function whoIs( $id ) {
71 $dbr =& wfGetDB( DB_SLAVE
);
72 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
76 * Get real username given an id.
77 * @param integer $id Database user id
78 * @return string Realname of a user
81 function whoIsReal( $id ) {
82 $dbr =& wfGetDB( DB_SLAVE
);
83 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
87 * Get database id given a user name
88 * @param string $name Nickname of a user
89 * @return integer|null Database user id (null: if non existent
92 function idFromName( $name ) {
93 $fname = "User::idFromName";
95 $nt = Title
::newFromText( $name );
96 if( is_null( $nt ) ) {
100 $dbr =& wfGetDB( DB_SLAVE
);
101 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
103 if ( $s === false ) {
111 * does the string match an anonymous user IP address?
112 * @param string $name Nickname of a user
115 function isIP( $name ) {
116 return preg_match("/^\d{1,3}\.\d{1,3}.\d{1,3}\.\d{1,3}$/",$name);
120 * does the string match roughly an email address ?
121 * @param string $addr email address
124 function isValidEmailAddr ( $addr ) {
125 return preg_match( '/^([a-z0-9_.-]+([a-z0-9_.-]+)*\@[a-z0-9_-]+([a-z0-9_.-]+)*([a-z.]{2,})+)$/', strtolower($addr));
129 * probably return a random password
130 * @return string probably a random password
132 * @todo Check what is doing really [AV]
134 function randomPassword() {
135 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
136 $l = strlen( $pwchars ) - 1;
138 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
139 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
140 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
141 $pwchars{mt_rand( 0, $l )};
146 * Set properties to default
147 * Used at construction. It will load per language default settings only
148 * if we have an available language object.
150 function loadDefaults() {
153 $fname = 'User::loadDefaults' . $n;
154 wfProfileIn( $fname );
156 global $wgContLang, $wgIP, $wgDBname;
157 global $wgNamespacesToBeSearchedDefault;
160 $this->mNewtalk
= -1;
161 $this->mName
= $wgIP;
162 $this->mRealName
= $this->mEmail
= '';
163 $this->mEmailAuthenticationtimestamp
= 0;
164 $this->mPassword
= $this->mNewpassword
= '';
165 $this->mRights
= array();
166 $this->mGroups
= array();
167 // Getting user defaults only if we have an available language
168 if( isset( $wgContLang ) ) {
169 $this->loadDefaultFromLanguage();
172 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
173 $this->mOptions
['searchNs'.$nsnum] = $val;
175 unset( $this->mSkin
);
176 $this->mDataLoaded
= false;
177 $this->mBlockedby
= -1; # Unset
178 $this->setToken(); # Random
179 $this->mHash
= false;
181 if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
182 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgDBname.'LoggedOut'] );
185 $this->mTouched
= '0'; # Allow any pages to be cached
188 wfProfileOut( $fname );
192 * Used to load user options from a language.
193 * This is not in loadDefault() cause we sometime create user before having
196 function loadDefaultFromLanguage(){
197 $this->mOptions
= User
::getDefaultOptions();
201 * Combine the language default options with any site-specific options
202 * and add the default language variants.
208 function getDefaultOptions() {
210 * Site defaults will override the global/language defaults
212 global $wgContLang, $wgDefaultUserOptions;
213 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptions();
216 * default language setting
218 $variant = $wgContLang->getPreferredVariant();
219 $defOpt['variant'] = $variant;
220 $defOpt['language'] = $variant;
226 * Get a given default option value.
233 function getDefaultOption( $opt ) {
234 $defOpts = User
::getDefaultOptions();
235 if( isset( $defOpts[$opt] ) ) {
236 return $defOpts[$opt];
243 * Get blocking information
245 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
246 * non-critical checks are done against slaves. Check when actually saving should be done against
249 * Note that even if $bFromSlave is false, the check is done first against slave, then master.
250 * The logic is that if blocked on slave, we'll assume it's either blocked on master or
251 * just slightly outta sync and soon corrected - safer to block slightly more that less.
252 * And it's cheaper to check slave first, then master if needed, than master always.
254 function getBlockedStatus() {
255 global $wgIP, $wgBlockCache, $wgProxyList, $wgEnableSorbs, $bFromSlave;
257 if ( -1 != $this->mBlockedby
) { return; }
259 $this->mBlockedby
= 0;
263 $block = new Block();
264 $block->forUpdate( $bFromSlave );
265 if ( $block->load( $wgIP , $this->mId
) ) {
266 $this->mBlockedby
= $block->mBy
;
267 $this->mBlockreason
= $block->mReason
;
268 $this->spreadBlock();
273 if ( !$this->mBlockedby
) {
274 # Check first against slave, and optionally from master.
275 $block = $wgBlockCache->get( $wgIP, true );
276 if ( !$block && !$bFromSlave )
278 # Not blocked: check against master, to make sure.
279 $wgBlockCache->clearLocal( );
280 $block = $wgBlockCache->get( $wgIP, false );
282 if ( $block !== false ) {
283 $this->mBlockedby
= $block->mBy
;
284 $this->mBlockreason
= $block->mReason
;
289 if ( !$this->mBlockedby
) {
290 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
291 $this->mBlockedby
= wfMsg( 'proxyblocker' );
292 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
297 if ( !$this->mBlockedby
&& $wgEnableSorbs ) {
298 if ( $this->inSorbsBlacklist( $wgIP ) ) {
299 $this->mBlockedby
= wfMsg( 'sorbs' );
300 $this->mBlockreason
= wfMsg( 'sorbsreason' );
306 function inSorbsBlacklist( $ip ) {
307 $fname = 'User::inSorbsBlacklist';
308 wfProfileIn( $fname );
313 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
315 for ( $i=4; $i>=1; $i-- ) {
316 $host .= $m[$i] . '.';
318 $host .= 'http.dnsbl.sorbs.net.';
321 $ipList = gethostbynamel( $host );
324 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy!\n" );
327 wfDebug( "Requested $host, not found.\n" );
331 wfProfileOut( $fname );
336 * Check if user is blocked
337 * @return bool True if blocked, false otherwise
339 function isBlocked( $bFromSlave = false ) {
340 $this->getBlockedStatus( $bFromSlave );
341 if ( 0 === $this->mBlockedby
) { return false; }
346 * Get name of blocker
347 * @return string name of blocker
349 function blockedBy() {
350 $this->getBlockedStatus();
351 return $this->mBlockedby
;
355 * Get blocking reason
356 * @return string Blocking reason
358 function blockedFor() {
359 $this->getBlockedStatus();
360 return $this->mBlockreason
;
364 * Initialise php session
366 function SetupSession() {
367 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
368 if( $wgSessionsInMemcached ) {
369 require_once( 'MemcachedSessions.php' );
370 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
371 # If it's left on 'user' or another setting from another
372 # application, it will end up failing. Try to recover.
373 ini_set ( 'session.save_handler', 'files' );
375 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
376 session_cache_limiter( 'private, must-revalidate' );
381 * Read datas from session
384 function loadFromSession() {
385 global $wgMemc, $wgDBname;
387 if ( isset( $_SESSION['wsUserID'] ) ) {
388 if ( 0 != $_SESSION['wsUserID'] ) {
389 $sId = $_SESSION['wsUserID'];
393 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
394 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
395 $_SESSION['wsUserID'] = $sId;
399 if ( isset( $_SESSION['wsUserName'] ) ) {
400 $sName = $_SESSION['wsUserName'];
401 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
402 $sName = $_COOKIE["{$wgDBname}UserName"];
403 $_SESSION['wsUserName'] = $sName;
408 $passwordCorrect = FALSE;
409 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
410 if($makenew = !$user) {
411 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
414 $user->loadFromDatabase();
416 wfDebug( "User::loadFromSession() got from cache!\n" );
419 if ( isset( $_SESSION['wsToken'] ) ) {
420 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken
;
421 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
422 $passwordCorrect = $user->mToken
== $_COOKIE["{$wgDBname}Token"];
424 return new User(); # Can't log in from session
427 if ( ( $sName == $user->mName
) && $passwordCorrect ) {
429 if($wgMemc->set( $key, $user ))
430 wfDebug( "User::loadFromSession() successfully saved user\n" );
432 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
436 return new User(); # Can't log in from session
440 * Load a user from the database
442 function loadFromDatabase() {
443 global $wgCommandLineMode, $wgAnonGroupId, $wgLoggedInGroupId;
444 $fname = "User::loadFromDatabase";
446 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
447 # loading in a command line script, don't assume all command line scripts need it like this
448 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
449 if ( $this->mDataLoaded
) {
454 $this->mId
= IntVal( $this->mId
);
456 /** Anonymous user */
459 $anong = Group
::newFromId($wgAnonGroupId);
461 wfDebugDieBacktrace("Please update your database schema "
462 ."and populate initial group data from "
463 ."maintenance/archives patches");
464 $anong->loadFromDatabase();
465 $this->mRights
= explode(',', $anong->getRights());
466 $this->mDataLoaded
= true;
468 } # the following stuff is for non-anonymous users only
470 $dbr =& wfGetDB( DB_SLAVE
);
471 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
472 'user_emailauthenticationtimestamp',
473 'user_real_name','user_options','user_touched', 'user_token' ),
474 array( 'user_id' => $this->mId
), $fname );
476 if ( $s !== false ) {
477 $this->mName
= $s->user_name
;
478 $this->mEmail
= $s->user_email
;
479 $this->mEmailAuthenticationtimestamp
= wfTimestamp(TS_MW
,$s->user_emailauthenticationtimestamp
);
480 $this->mRealName
= $s->user_real_name
;
481 $this->mPassword
= $s->user_password
;
482 $this->mNewpassword
= $s->user_newpassword
;
483 $this->decodeOptions( $s->user_options
);
484 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
485 $this->mToken
= $s->user_token
;
488 $res = $dbr->select( 'user_groups', array( 'ug_group' ), array( 'ug_user' => $this->mId
) );
490 while($group = $dbr->fetchRow($res)) {
491 $this->mGroups
[] = $group[0];
494 // add the default group for logged in user
495 $this->mGroups
[] = $wgLoggedInGroupId;
497 $this->mRights
= array();
498 // now we merge groups rights to get this user rights
499 foreach($this->mGroups
as $aGroupId) {
500 $g = Group
::newFromId($aGroupId);
501 $g->loadFromDatabase();
502 $this->mRights
= array_merge($this->mRights
, explode(',', $g->getRights()));
505 // array merge duplicate rights which are part of several groups
506 $this->mRights
= array_unique($this->mRights
);
508 $dbr->freeResult($res);
511 $this->mDataLoaded
= true;
514 function getID() { return $this->mId
; }
515 function setID( $v ) {
517 $this->mDataLoaded
= false;
521 $this->loadFromDatabase();
525 function setName( $str ) {
526 $this->loadFromDatabase();
532 * Return the title dbkey form of the name, for eg user pages.
536 function getTitleKey() {
537 return str_replace( ' ', '_', $this->getName() );
540 function getNewtalk() {
541 $fname = 'User::getNewtalk';
542 $this->loadFromDatabase();
544 # Load the newtalk status if it is unloaded (mNewtalk=-1)
545 if( $this->mNewtalk
== -1 ) {
546 $this->mNewtalk
= 0; # reset talk page status
548 # Check memcached separately for anons, who have no
549 # entire User object stored in there.
551 global $wgDBname, $wgMemc;
552 $key = "$wgDBname:newtalk:ip:{$this->mName}";
553 $newtalk = $wgMemc->get( $key );
554 if( is_integer( $newtalk ) ) {
555 $this->mNewtalk
= $newtalk ?
1 : 0;
556 return (bool)$this->mNewtalk
;
560 $dbr =& wfGetDB( DB_SLAVE
);
561 $res = $dbr->select( 'watchlist',
563 array( 'wl_title' => $this->getTitleKey(),
564 'wl_namespace' => NS_USER_TALK
,
565 'wl_user' => $this->mId
,
566 'wl_notificationtimestamp != 0' ),
567 'User::getNewtalk' );
568 if( $dbr->numRows($res) > 0 ) {
571 $dbr->freeResult( $res );
574 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
578 return ( 0 != $this->mNewtalk
);
581 function setNewtalk( $val ) {
582 $this->loadFromDatabase();
583 $this->mNewtalk
= $val;
584 $this->invalidateCache();
587 function invalidateCache() {
588 $this->loadFromDatabase();
589 $this->mTouched
= wfTimestampNow();
590 # Don't forget to save the options after this or
591 # it won't take effect!
594 function validateCache( $timestamp ) {
595 $this->loadFromDatabase();
596 return ($timestamp >= $this->mTouched
);
601 * Will only be salted if $wgPasswordSalt is true
602 * @param string Password.
603 * @return string Salted password or clear password.
605 function addSalt( $p ) {
606 global $wgPasswordSalt;
608 return md5( "{$this->mId}-{$p}" );
614 * Encrypt a password.
615 * It can eventuall salt a password @see User::addSalt()
616 * @param string $p clear Password.
617 * @param string Encrypted password.
619 function encryptPassword( $p ) {
620 return $this->addSalt( md5( $p ) );
623 # Set the password and reset the random token
624 function setPassword( $str ) {
625 $this->loadFromDatabase();
627 $this->mPassword
= $this->encryptPassword( $str );
628 $this->mNewpassword
= '';
631 # Set the random token (used for persistent authentication)
632 function setToken( $token = false ) {
633 global $wgSecretKey, $wgProxyKey, $wgDBname;
635 if ( $wgSecretKey ) {
637 } elseif ( $wgProxyKey ) {
642 $this->mToken
= md5( $wgSecretKey . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId
);
644 $this->mToken
= $token;
649 function setCookiePassword( $str ) {
650 $this->loadFromDatabase();
651 $this->mCookiePassword
= md5( $str );
654 function setNewpassword( $str ) {
655 $this->loadFromDatabase();
656 $this->mNewpassword
= $this->encryptPassword( $str );
659 function getEmail() {
660 $this->loadFromDatabase();
661 return $this->mEmail
;
664 function getEmailAuthenticationtimestamp() {
665 $this->loadFromDatabase();
666 return $this->mEmailAuthenticationtimestamp
;
669 function setEmail( $str ) {
670 $this->loadFromDatabase();
671 $this->mEmail
= $str;
674 function getRealName() {
675 $this->loadFromDatabase();
676 return $this->mRealName
;
679 function setRealName( $str ) {
680 $this->loadFromDatabase();
681 $this->mRealName
= $str;
684 function getOption( $oname ) {
685 $this->loadFromDatabase();
686 if ( array_key_exists( $oname, $this->mOptions
) ) {
687 return $this->mOptions
[$oname];
693 function setOption( $oname, $val ) {
694 $this->loadFromDatabase();
695 if ( $oname == 'skin' ) {
696 # Clear cached skin, so the new one displays immediately in Special:Preferences
697 unset( $this->mSkin
);
699 $this->mOptions
[$oname] = $val;
700 $this->invalidateCache();
703 function getRights() {
704 $this->loadFromDatabase();
705 return $this->mRights
;
708 function addRight( $rname ) {
709 $this->loadFromDatabase();
710 array_push( $this->mRights
, $rname );
711 $this->invalidateCache();
714 function getGroups() {
715 $this->loadFromDatabase();
716 return $this->mGroups
;
719 function setGroups($groups) {
720 $this->loadFromDatabase();
721 $this->mGroups
= $groups;
722 $this->invalidateCache();
726 * A more legible check for non-anonymousness.
727 * Returns true if the user is not an anonymous visitor.
731 function isLoggedIn() {
732 return( $this->getID() != 0 );
736 * A more legible check for anonymousness.
737 * Returns true if the user is an anonymous visitor.
742 return !$this->isLoggedIn();
746 * Check if a user is sysop
747 * Die with backtrace. Use User:isAllowed() instead.
751 wfDebugDieBacktrace("User::isSysop() is deprecated. Use User::isAllowed() instead");
755 function isDeveloper() {
756 wfDebugDieBacktrace("User::isDeveloper() is deprecated. Use User::isAllowed() instead");
760 function isBureaucrat() {
761 wfDebugDieBacktrace("User::isBureaucrat() is deprecated. Use User::isAllowed() instead");
765 * Whether the user is a bot
766 * @todo need to be migrated to the new user level management sytem
769 $this->loadFromDatabase();
771 # Why was this here? I need a UID=0 conversion script [TS]
772 # if ( 0 == $this->mId ) { return false; }
774 return in_array( 'bot', $this->mRights
);
778 * Check if user is allowed to access a feature / make an action
779 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
780 * @return boolean True: action is allowed, False: action should not be allowed
782 function isAllowed($action='') {
783 $this->loadFromDatabase();
784 return in_array( $action , $this->mRights
);
788 * Load a skin if it doesn't exist or return it
789 * @todo FIXME : need to check the old failback system [AV]
791 function &getSkin() {
793 if ( ! isset( $this->mSkin
) ) {
794 $fname = 'User::getSkin';
795 wfProfileIn( $fname );
797 # get all skin names available
798 $skinNames = Skin
::getSkinNames();
801 $userSkin = $this->getOption( 'skin' );
802 if ( $userSkin == '' ) { $userSkin = 'standard'; }
804 if ( !isset( $skinNames[$userSkin] ) ) {
805 # in case the user skin could not be found find a replacement
810 # if phptal is enabled we should have monobook skin that
811 # superseed the good old SkinStandard.
812 if ( isset( $skinNames['monobook'] ) ) {
813 $fallback[0] = 'MonoBook';
816 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
817 $sn = $fallback[$userSkin];
822 # The user skin is available
823 $sn = $skinNames[$userSkin];
826 # Grab the skin class and initialise it. Each skin checks for PHPTal
827 # and will not load if it's not enabled.
828 require_once( $IP.'/skins/'.$sn.'.php' );
830 # Check if we got if not failback to default skin
831 $className = 'Skin'.$sn;
832 if( !class_exists( $className ) ) {
833 # DO NOT die if the class isn't found. This breaks maintenance
834 # scripts and can cause a user account to be unrecoverable
835 # except by SQL manipulation if a previously valid skin name
836 # is no longer valid.
837 $className = 'SkinStandard';
838 require_once( $IP.'/skins/Standard.php' );
840 $this->mSkin
=& new $className;
841 wfProfileOut( $fname );
847 * @param string $title Article title to look at
851 * Check watched status of an article
852 * @return bool True if article is watched
854 function isWatched( $title ) {
855 $wl = WatchedItem
::fromUserTitle( $this, $title );
856 return $wl->isWatched();
862 function addWatch( $title ) {
863 $wl = WatchedItem
::fromUserTitle( $this, $title );
865 $this->invalidateCache();
869 * Stop watching an article
871 function removeWatch( $title ) {
872 $wl = WatchedItem
::fromUserTitle( $this, $title );
874 $this->invalidateCache();
878 * Clear the user's notification timestamp for the given title.
879 * If e-notif e-mails are on, they will receive notification mails on
880 * the next change of the page if it's watched etc.
882 function clearNotification( $title ) {
883 $userid = $this->getId();
886 $dbw =& wfGetDB( DB_MASTER
);
887 $success = $dbw->update( 'watchlist',
889 'wl_notificationtimestamp' => 0
890 ), array( /* WHERE */
891 'wl_title' => $title->getDBkey(),
892 'wl_namespace' => $title->getNamespace(),
893 'wl_user' => $this->getId()
894 ), 'User::clearLastVisited'
901 * Resets all of the given user's page-change notification timestamps.
902 * If e-notif e-mails are on, they will receive notification mails on
903 * the next change of any watched page.
905 * @param int $currentUser user ID number
908 function clearAllNotifications( $currentUser ) {
909 if( $currentUser != 0 ) {
911 $dbw =& wfGetDB( DB_MASTER
);
912 $success = $dbw->update( 'watchlist',
914 'wl_notificationtimestamp' => 0
915 ), array( /* WHERE */
916 'wl_user' => $currentUser
917 ), 'UserMailer::clearAll'
920 # we also need to clear here the "you have new message" notification for the own user_talk page
921 # This is cleared one page view later in Article::viewUpdates();
927 * @return string Encoding options
929 function encodeOptions() {
931 foreach ( $this->mOptions
as $oname => $oval ) {
932 array_push( $a, $oname.'='.$oval );
934 $s = implode( "\n", $a );
941 function decodeOptions( $str ) {
942 $a = explode( "\n", $str );
943 foreach ( $a as $s ) {
944 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
945 $this->mOptions
[$m[1]] = $m[2];
950 function setCookies() {
951 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
952 if ( 0 == $this->mId
) return;
953 $this->loadFromDatabase();
954 $exp = time() +
$wgCookieExpiration;
956 $_SESSION['wsUserID'] = $this->mId
;
957 setcookie( $wgDBname.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain );
959 $_SESSION['wsUserName'] = $this->mName
;
960 setcookie( $wgDBname.'UserName', $this->mName
, $exp, $wgCookiePath, $wgCookieDomain );
962 $_SESSION['wsToken'] = $this->mToken
;
963 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
964 setcookie( $wgDBname.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain );
966 setcookie( $wgDBname.'Token', '', time() - 3600 );
972 * It will clean the session cookie
975 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
976 $this->loadDefaults();
977 $this->setLoaded( true );
979 $_SESSION['wsUserID'] = 0;
981 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
982 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
984 # Remember when user logged out, to prevent seeing cached pages
985 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain );
989 * Save object settings into database
991 function saveSettings() {
992 global $wgMemc, $wgDBname;
993 $fname = 'User::saveSettings';
995 $dbw =& wfGetDB( DB_MASTER
);
996 if ( ! $this->getNewtalk() ) {
997 # Delete the watchlist entry for user_talk page X watched by user X
998 $dbw->delete( 'watchlist',
999 array( 'wl_user' => $this->mId
,
1000 'wl_title' => $this->getTitleKey(),
1001 'wl_namespace' => NS_USER_TALK
),
1004 # Anon users have a separate memcache space for newtalk
1005 # since they don't store their own info. Trim...
1006 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1010 if ( 0 == $this->mId
) { return; }
1012 $dbw->update( 'user',
1014 'user_name' => $this->mName
,
1015 'user_password' => $this->mPassword
,
1016 'user_newpassword' => $this->mNewpassword
,
1017 'user_real_name' => $this->mRealName
,
1018 'user_email' => $this->mEmail
,
1019 'user_emailauthenticationtimestamp' => $dbw->timestamp($this->mEmailAuthenticationtimestamp
),
1020 'user_options' => $this->encodeOptions(),
1021 'user_touched' => $dbw->timestamp($this->mTouched
),
1022 'user_token' => $this->mToken
1023 ), array( /* WHERE */
1024 'user_id' => $this->mId
1027 $dbw->set( 'user_rights', 'ur_rights', implode( ',', $this->mRights
),
1028 'ur_user='. $this->mId
, $fname );
1029 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1031 // delete old groups
1032 $dbw->delete( 'user_groups', array( 'ug_user' => $this->mId
), $fname);
1035 foreach ($this->mGroups
as $group) {
1036 $dbw->replace( 'user_groups',
1037 array(array('ug_user','ug_group')),
1039 'ug_user' => $this->mId
,
1040 'ug_group' => $group
1048 * Checks if a user with the given name exists, returns the ID
1050 function idForName() {
1051 $fname = 'User::idForName';
1054 $s = trim( $this->mName
);
1055 if ( 0 == strcmp( '', $s ) ) return 0;
1057 $dbr =& wfGetDB( DB_SLAVE
);
1058 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1059 if ( $id === false ) {
1066 * Add user object to the database
1068 function addToDatabase() {
1069 $fname = 'User::addToDatabase';
1070 $dbw =& wfGetDB( DB_MASTER
);
1071 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1072 $dbw->insert( 'user',
1074 'user_id' => $seqVal,
1075 'user_name' => $this->mName
,
1076 'user_password' => $this->mPassword
,
1077 'user_newpassword' => $this->mNewpassword
,
1078 'user_email' => $this->mEmail
,
1079 'user_emailauthenticationtimestamp' => $dbw->timestamp($this->mEmailAuthenticationtimestamp
),
1080 'user_real_name' => $this->mRealName
,
1081 'user_options' => $this->encodeOptions(),
1082 'user_token' => $this->mToken
1085 $this->mId
= $dbw->insertId();
1086 $dbw->insert( 'user_rights',
1088 'ur_user' => $this->mId
,
1089 'ur_rights' => implode( ',', $this->mRights
)
1093 foreach ($this->mGroups
as $group) {
1094 $dbw->insert( 'user_groups',
1096 'ug_user' => $this->mId
,
1097 'ug_group' => $group
1103 function spreadBlock() {
1105 # If the (non-anonymous) user is blocked, this function will block any IP address
1106 # that they successfully log on from.
1107 $fname = 'User::spreadBlock';
1109 wfDebug( "User:spreadBlock()\n" );
1110 if ( $this->mId
== 0 ) {
1114 $userblock = Block
::newFromDB( '', $this->mId
);
1115 if ( !$userblock->isValid() ) {
1119 # Check if this IP address is already blocked
1120 $ipblock = Block
::newFromDB( $wgIP );
1121 if ( $ipblock->isValid() ) {
1122 # Just update the timestamp
1123 $ipblock->updateTimestamp();
1127 # Make a new block object with the desired properties
1128 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1129 $ipblock->mAddress
= $wgIP;
1130 $ipblock->mUser
= 0;
1131 $ipblock->mBy
= $userblock->mBy
;
1132 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
1133 $ipblock->mTimestamp
= wfTimestampNow();
1134 $ipblock->mAuto
= 1;
1135 # If the user is already blocked with an expiry date, we don't
1136 # want to pile on top of that!
1137 if($userblock->mExpiry
) {
1138 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
1140 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
1148 function getPageRenderingHash() {
1151 return $this->mHash
;
1154 // stubthreshold is only included below for completeness,
1155 // it will always be 0 when this function is called by parsercache.
1157 $confstr = $this->getOption( 'math' );
1158 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1159 $confstr .= '!' . $this->getOption( 'editsection' );
1160 $confstr .= '!' . $this->getOption( 'date' );
1161 $confstr .= '!' . $this->getOption( 'numberheadings' );
1162 $confstr .= '!' . $this->getOption( 'language' );
1163 $confstr .= '!' . $this->getOption( 'thumbsize' );
1164 // add in language specific options, if any
1165 $extra = $wgContLang->getExtraHashOptions();
1168 $this->mHash
= $confstr;
1172 function isAllowedToCreateAccount() {
1173 global $wgWhitelistAccount;
1176 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1177 foreach ($wgWhitelistAccount as $right => $ok) {
1178 $userHasRight = (!strcmp($right, 'user') ||
in_array($right, $this->getRights()));
1179 $allowed |
= ($ok && $userHasRight);
1185 * Set mDataLoaded, return previous value
1186 * Use this to prevent DB access in command-line scripts or similar situations
1188 function setLoaded( $loaded ) {
1189 return wfSetVar( $this->mDataLoaded
, $loaded );
1193 * Get this user's personal page title.
1198 function getUserPage() {
1199 return Title
::makeTitle( NS_USER
, $this->mName
);
1203 * Get this user's talk page title.
1208 function getTalkPage() {
1209 $title = $this->getUserPage();
1210 return $title->getTalkPage();
1216 function getMaxID() {
1217 $dbr =& wfGetDB( DB_SLAVE
);
1218 return $dbr->selectField( 'user', 'max(user_id)', false );
1222 * Determine whether the user is a newbie. Newbies are either
1223 * anonymous IPs, or the 1% most recently created accounts.
1224 * Bots and sysops are excluded.
1225 * @return bool True if it is a newbie.
1227 function isNewbie() {
1228 return $this->mId
> User
::getMaxID() * 0.99 && !$this->isSysop() && !$this->isBot() ||
$this->getID() == 0;
1232 * Check to see if the given clear-text password is one of the accepted passwords
1233 * @param string $password User password.
1234 * @return bool True if the given password is correct otherwise False.
1236 function checkPassword( $password ) {
1238 $this->loadFromDatabase();
1240 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1242 } elseif( $wgAuth->strict() ) {
1243 /* Auth plugin doesn't allow local authentication */
1246 $ep = $this->encryptPassword( $password );
1247 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
1249 } elseif ( ($this->mNewpassword
!= '') && (0 == strcmp( $ep, $this->mNewpassword
)) ) {
1250 $this->mEmailAuthenticationtimestamp
= wfTimestampNow();
1251 $this->mNewpassword
= ''; # use the temporary one-time password only once: clear it now !
1252 $this->saveSettings();
1254 } elseif ( function_exists( 'iconv' ) ) {
1255 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1256 # Check for this with iconv
1257 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1258 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
1266 * Initialize (if necessary) and return a session token value
1267 * which can be used in edit forms to show that the user's
1268 * login credentials aren't being hijacked with a foreign form
1271 * @param mixed $salt - Optional function-specific data for hash.
1272 * Use a string or an array of strings.
1276 function editToken( $salt = '' ) {
1277 if( !isset( $_SESSION['wsEditToken'] ) ) {
1278 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1279 $_SESSION['wsEditToken'] = $token;
1281 $token = $_SESSION['wsEditToken'];
1283 if( is_array( $salt ) ) {
1284 $salt = implode( '|', $salt );
1286 return md5( $token . $salt );
1290 * Check given value against the token value stored in the session.
1291 * A match should confirm that the form was submitted from the
1292 * user's own login session, not a form submission from a third-party
1295 * @param string $val - the input value to compare
1296 * @param string $salt - Optional function-specific data for hash
1300 function matchEditToken( $val, $salt = '' ) {
1301 return ( $val == $this->editToken( $salt ) );