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 while($group = $dbr->fetchRow($res)) {
530 $this->mGroups
[] = $group[0];
533 // add the default group for logged in user
534 $this->mGroups
[] = $wgLoggedInGroupId;
536 $this->mRights
= array();
537 // now we merge groups rights to get this user rights
538 foreach($this->mGroups
as $aGroupId) {
539 $g = Group
::newFromId($aGroupId);
540 $g->loadFromDatabase();
541 $this->mRights
= array_merge($this->mRights
, explode(',', $g->getRights()));
544 // array merge duplicate rights which are part of several groups
545 $this->mRights
= array_unique($this->mRights
);
547 $dbr->freeResult($res);
550 $this->mDataLoaded
= true;
553 function getID() { return $this->mId
; }
554 function setID( $v ) {
556 $this->mDataLoaded
= false;
560 $this->loadFromDatabase();
564 function setName( $str ) {
565 $this->loadFromDatabase();
571 * Return the title dbkey form of the name, for eg user pages.
575 function getTitleKey() {
576 return str_replace( ' ', '_', $this->getName() );
579 function getNewtalk() {
580 $fname = 'User::getNewtalk';
581 $this->loadFromDatabase();
583 # Load the newtalk status if it is unloaded (mNewtalk=-1)
584 if( $this->mNewtalk
== -1 ) {
585 $this->mNewtalk
= 0; # reset talk page status
587 # Check memcached separately for anons, who have no
588 # entire User object stored in there.
590 global $wgDBname, $wgMemc;
591 $key = "$wgDBname:newtalk:ip:{$this->mName}";
592 $newtalk = $wgMemc->get( $key );
593 if( is_integer( $newtalk ) ) {
594 $this->mNewtalk
= $newtalk ?
1 : 0;
595 return (bool)$this->mNewtalk
;
599 $dbr =& wfGetDB( DB_SLAVE
);
600 $res = $dbr->select( 'watchlist',
602 array( 'wl_title' => $this->getTitleKey(),
603 'wl_namespace' => NS_USER_TALK
,
604 'wl_user' => $this->mId
,
605 'wl_notificationtimestamp != 0' ),
606 'User::getNewtalk' );
607 if( $dbr->numRows($res) > 0 ) {
610 $dbr->freeResult( $res );
613 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
617 return ( 0 != $this->mNewtalk
);
620 function setNewtalk( $val ) {
621 $this->loadFromDatabase();
622 $this->mNewtalk
= $val;
623 $this->invalidateCache();
626 function invalidateCache() {
627 $this->loadFromDatabase();
628 $this->mTouched
= wfTimestampNow();
629 # Don't forget to save the options after this or
630 # it won't take effect!
633 function validateCache( $timestamp ) {
634 $this->loadFromDatabase();
635 return ($timestamp >= $this->mTouched
);
640 * Will only be salted if $wgPasswordSalt is true
641 * @param string Password.
642 * @return string Salted password or clear password.
644 function addSalt( $p ) {
645 global $wgPasswordSalt;
647 return md5( "{$this->mId}-{$p}" );
653 * Encrypt a password.
654 * It can eventuall salt a password @see User::addSalt()
655 * @param string $p clear Password.
656 * @param string Encrypted password.
658 function encryptPassword( $p ) {
659 return $this->addSalt( md5( $p ) );
662 # Set the password and reset the random token
663 function setPassword( $str ) {
664 $this->loadFromDatabase();
666 $this->mPassword
= $this->encryptPassword( $str );
667 $this->mNewpassword
= '';
670 # Set the random token (used for persistent authentication)
671 function setToken( $token = false ) {
672 global $wgSecretKey, $wgProxyKey, $wgDBname;
674 if ( $wgSecretKey ) {
676 } elseif ( $wgProxyKey ) {
681 $this->mToken
= md5( $wgSecretKey . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId
);
683 $this->mToken
= $token;
688 function setCookiePassword( $str ) {
689 $this->loadFromDatabase();
690 $this->mCookiePassword
= md5( $str );
693 function setNewpassword( $str ) {
694 $this->loadFromDatabase();
695 $this->mNewpassword
= $this->encryptPassword( $str );
698 function getEmail() {
699 $this->loadFromDatabase();
700 return $this->mEmail
;
703 function getEmailAuthenticationTimestamp() {
704 $this->loadFromDatabase();
705 return $this->mEmailAuthenticated
;
708 function setEmail( $str ) {
709 $this->loadFromDatabase();
710 $this->mEmail
= $str;
713 function getRealName() {
714 $this->loadFromDatabase();
715 return $this->mRealName
;
718 function setRealName( $str ) {
719 $this->loadFromDatabase();
720 $this->mRealName
= $str;
723 function getOption( $oname ) {
724 $this->loadFromDatabase();
725 if ( array_key_exists( $oname, $this->mOptions
) ) {
726 return $this->mOptions
[$oname];
732 function setOption( $oname, $val ) {
733 $this->loadFromDatabase();
734 if ( $oname == 'skin' ) {
735 # Clear cached skin, so the new one displays immediately in Special:Preferences
736 unset( $this->mSkin
);
738 $this->mOptions
[$oname] = $val;
739 $this->invalidateCache();
742 function getRights() {
743 $this->loadFromDatabase();
744 return $this->mRights
;
747 function addRight( $rname ) {
748 $this->loadFromDatabase();
749 array_push( $this->mRights
, $rname );
750 $this->invalidateCache();
753 function getGroups() {
754 $this->loadFromDatabase();
755 return $this->mGroups
;
758 function setGroups($groups) {
759 $this->loadFromDatabase();
760 $this->mGroups
= $groups;
761 $this->invalidateCache();
765 * A more legible check for non-anonymousness.
766 * Returns true if the user is not an anonymous visitor.
770 function isLoggedIn() {
771 return( $this->getID() != 0 );
775 * A more legible check for anonymousness.
776 * Returns true if the user is an anonymous visitor.
781 return !$this->isLoggedIn();
785 * Check if a user is sysop
786 * Die with backtrace. Use User:isAllowed() instead.
790 wfDebugDieBacktrace("User::isSysop() is deprecated. Use User::isAllowed() instead");
794 function isDeveloper() {
795 wfDebugDieBacktrace("User::isDeveloper() is deprecated. Use User::isAllowed() instead");
799 function isBureaucrat() {
800 wfDebugDieBacktrace("User::isBureaucrat() is deprecated. Use User::isAllowed() instead");
804 * Whether the user is a bot
805 * @todo need to be migrated to the new user level management sytem
808 $this->loadFromDatabase();
809 return in_array( 'bot', $this->mRights
);
813 * Check if user is allowed to access a feature / make an action
814 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
815 * @return boolean True: action is allowed, False: action should not be allowed
817 function isAllowed($action='') {
818 $this->loadFromDatabase();
819 return in_array( $action , $this->mRights
);
823 * Load a skin if it doesn't exist or return it
824 * @todo FIXME : need to check the old failback system [AV]
826 function &getSkin() {
828 if ( ! isset( $this->mSkin
) ) {
829 $fname = 'User::getSkin';
830 wfProfileIn( $fname );
832 # get all skin names available
833 $skinNames = Skin
::getSkinNames();
836 $userSkin = $this->getOption( 'skin' );
837 if ( $userSkin == '' ) { $userSkin = 'standard'; }
839 if ( !isset( $skinNames[$userSkin] ) ) {
840 # in case the user skin could not be found find a replacement
845 # if phptal is enabled we should have monobook skin that
846 # superseed the good old SkinStandard.
847 if ( isset( $skinNames['monobook'] ) ) {
848 $fallback[0] = 'MonoBook';
851 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
852 $sn = $fallback[$userSkin];
857 # The user skin is available
858 $sn = $skinNames[$userSkin];
861 # Grab the skin class and initialise it. Each skin checks for PHPTal
862 # and will not load if it's not enabled.
863 require_once( $IP.'/skins/'.$sn.'.php' );
865 # Check if we got if not failback to default skin
866 $className = 'Skin'.$sn;
867 if( !class_exists( $className ) ) {
868 # DO NOT die if the class isn't found. This breaks maintenance
869 # scripts and can cause a user account to be unrecoverable
870 # except by SQL manipulation if a previously valid skin name
871 # is no longer valid.
872 $className = 'SkinStandard';
873 require_once( $IP.'/skins/Standard.php' );
875 $this->mSkin
=& new $className;
876 wfProfileOut( $fname );
882 * @param string $title Article title to look at
886 * Check watched status of an article
887 * @return bool True if article is watched
889 function isWatched( $title ) {
890 $wl = WatchedItem
::fromUserTitle( $this, $title );
891 return $wl->isWatched();
897 function addWatch( $title ) {
898 $wl = WatchedItem
::fromUserTitle( $this, $title );
900 $this->invalidateCache();
904 * Stop watching an article
906 function removeWatch( $title ) {
907 $wl = WatchedItem
::fromUserTitle( $this, $title );
909 $this->invalidateCache();
913 * Clear the user's notification timestamp for the given title.
914 * If e-notif e-mails are on, they will receive notification mails on
915 * the next change of the page if it's watched etc.
917 function clearNotification( $title ) {
918 $userid = $this->getId();
921 $dbw =& wfGetDB( DB_MASTER
);
922 $success = $dbw->update( 'watchlist',
924 'wl_notificationtimestamp' => 0
925 ), array( /* WHERE */
926 'wl_title' => $title->getDBkey(),
927 'wl_namespace' => $title->getNamespace(),
928 'wl_user' => $this->getId()
929 ), 'User::clearLastVisited'
936 * Resets all of the given user's page-change notification timestamps.
937 * If e-notif e-mails are on, they will receive notification mails on
938 * the next change of any watched page.
940 * @param int $currentUser user ID number
943 function clearAllNotifications( $currentUser ) {
944 if( $currentUser != 0 ) {
946 $dbw =& wfGetDB( DB_MASTER
);
947 $success = $dbw->update( 'watchlist',
949 'wl_notificationtimestamp' => 0
950 ), array( /* WHERE */
951 'wl_user' => $currentUser
952 ), 'UserMailer::clearAll'
955 # we also need to clear here the "you have new message" notification for the own user_talk page
956 # This is cleared one page view later in Article::viewUpdates();
962 * @return string Encoding options
964 function encodeOptions() {
966 foreach ( $this->mOptions
as $oname => $oval ) {
967 array_push( $a, $oname.'='.$oval );
969 $s = implode( "\n", $a );
976 function decodeOptions( $str ) {
977 $a = explode( "\n", $str );
978 foreach ( $a as $s ) {
979 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
980 $this->mOptions
[$m[1]] = $m[2];
985 function setCookies() {
986 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
987 if ( 0 == $this->mId
) return;
988 $this->loadFromDatabase();
989 $exp = time() +
$wgCookieExpiration;
991 $_SESSION['wsUserID'] = $this->mId
;
992 setcookie( $wgDBname.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain );
994 $_SESSION['wsUserName'] = $this->mName
;
995 setcookie( $wgDBname.'UserName', $this->mName
, $exp, $wgCookiePath, $wgCookieDomain );
997 $_SESSION['wsToken'] = $this->mToken
;
998 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
999 setcookie( $wgDBname.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain );
1001 setcookie( $wgDBname.'Token', '', time() - 3600 );
1007 * It will clean the session cookie
1010 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
1011 $this->loadDefaults();
1012 $this->setLoaded( true );
1014 $_SESSION['wsUserID'] = 0;
1016 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1017 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1019 # Remember when user logged out, to prevent seeing cached pages
1020 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain );
1024 * Save object settings into database
1026 function saveSettings() {
1027 global $wgMemc, $wgDBname;
1028 $fname = 'User::saveSettings';
1030 $dbw =& wfGetDB( DB_MASTER
);
1031 if ( ! $this->getNewtalk() ) {
1032 # Delete the watchlist entry for user_talk page X watched by user X
1033 $dbw->delete( 'watchlist',
1034 array( 'wl_user' => $this->mId
,
1035 'wl_title' => $this->getTitleKey(),
1036 'wl_namespace' => NS_USER_TALK
),
1039 # Anon users have a separate memcache space for newtalk
1040 # since they don't store their own info. Trim...
1041 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1045 if ( 0 == $this->mId
) { return; }
1047 $dbw->update( 'user',
1049 'user_name' => $this->mName
,
1050 'user_password' => $this->mPassword
,
1051 'user_newpassword' => $this->mNewpassword
,
1052 'user_real_name' => $this->mRealName
,
1053 'user_email' => $this->mEmail
,
1054 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1055 'user_options' => $this->encodeOptions(),
1056 'user_touched' => $dbw->timestamp($this->mTouched
),
1057 'user_token' => $this->mToken
1058 ), array( /* WHERE */
1059 'user_id' => $this->mId
1062 $dbw->set( 'user_rights', 'ur_rights', implode( ',', $this->mRights
),
1063 'ur_user='. $this->mId
, $fname );
1064 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1066 // delete old groups
1067 $dbw->delete( 'user_groups', array( 'ug_user' => $this->mId
), $fname);
1070 foreach ($this->mGroups
as $group) {
1071 $dbw->replace( 'user_groups',
1072 array(array('ug_user','ug_group')),
1074 'ug_user' => $this->mId
,
1075 'ug_group' => $group
1083 * Checks if a user with the given name exists, returns the ID
1085 function idForName() {
1086 $fname = 'User::idForName';
1089 $s = trim( $this->mName
);
1090 if ( 0 == strcmp( '', $s ) ) return 0;
1092 $dbr =& wfGetDB( DB_SLAVE
);
1093 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1094 if ( $id === false ) {
1101 * Add user object to the database
1103 function addToDatabase() {
1104 $fname = 'User::addToDatabase';
1105 $dbw =& wfGetDB( DB_MASTER
);
1106 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1107 $dbw->insert( 'user',
1109 'user_id' => $seqVal,
1110 'user_name' => $this->mName
,
1111 'user_password' => $this->mPassword
,
1112 'user_newpassword' => $this->mNewpassword
,
1113 'user_email' => $this->mEmail
,
1114 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1115 'user_real_name' => $this->mRealName
,
1116 'user_options' => $this->encodeOptions(),
1117 'user_token' => $this->mToken
1120 $this->mId
= $dbw->insertId();
1121 $dbw->insert( 'user_rights',
1123 'ur_user' => $this->mId
,
1124 'ur_rights' => implode( ',', $this->mRights
)
1128 foreach ($this->mGroups
as $group) {
1129 $dbw->insert( 'user_groups',
1131 'ug_user' => $this->mId
,
1132 'ug_group' => $group
1138 function spreadBlock() {
1140 # If the (non-anonymous) user is blocked, this function will block any IP address
1141 # that they successfully log on from.
1142 $fname = 'User::spreadBlock';
1144 wfDebug( "User:spreadBlock()\n" );
1145 if ( $this->mId
== 0 ) {
1149 $userblock = Block
::newFromDB( '', $this->mId
);
1150 if ( !$userblock->isValid() ) {
1154 # Check if this IP address is already blocked
1155 $ipblock = Block
::newFromDB( $wgIP );
1156 if ( $ipblock->isValid() ) {
1157 # Just update the timestamp
1158 $ipblock->updateTimestamp();
1162 # Make a new block object with the desired properties
1163 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1164 $ipblock->mAddress
= $wgIP;
1165 $ipblock->mUser
= 0;
1166 $ipblock->mBy
= $userblock->mBy
;
1167 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
1168 $ipblock->mTimestamp
= wfTimestampNow();
1169 $ipblock->mAuto
= 1;
1170 # If the user is already blocked with an expiry date, we don't
1171 # want to pile on top of that!
1172 if($userblock->mExpiry
) {
1173 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
1175 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
1183 function getPageRenderingHash() {
1186 return $this->mHash
;
1189 // stubthreshold is only included below for completeness,
1190 // it will always be 0 when this function is called by parsercache.
1192 $confstr = $this->getOption( 'math' );
1193 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1194 $confstr .= '!' . $this->getOption( 'editsection' );
1195 $confstr .= '!' . $this->getOption( 'date' );
1196 $confstr .= '!' . $this->getOption( 'numberheadings' );
1197 $confstr .= '!' . $this->getOption( 'language' );
1198 $confstr .= '!' . $this->getOption( 'thumbsize' );
1199 // add in language specific options, if any
1200 $extra = $wgContLang->getExtraHashOptions();
1203 $this->mHash
= $confstr;
1207 function isAllowedToCreateAccount() {
1208 global $wgWhitelistAccount;
1211 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1212 foreach ($wgWhitelistAccount as $right => $ok) {
1213 $userHasRight = (!strcmp($right, 'user') ||
in_array($right, $this->getRights()));
1214 $allowed |
= ($ok && $userHasRight);
1220 * Set mDataLoaded, return previous value
1221 * Use this to prevent DB access in command-line scripts or similar situations
1223 function setLoaded( $loaded ) {
1224 return wfSetVar( $this->mDataLoaded
, $loaded );
1228 * Get this user's personal page title.
1233 function getUserPage() {
1234 return Title
::makeTitle( NS_USER
, $this->mName
);
1238 * Get this user's talk page title.
1243 function getTalkPage() {
1244 $title = $this->getUserPage();
1245 return $title->getTalkPage();
1251 function getMaxID() {
1252 $dbr =& wfGetDB( DB_SLAVE
);
1253 return $dbr->selectField( 'user', 'max(user_id)', false );
1257 * Determine whether the user is a newbie. Newbies are either
1258 * anonymous IPs, or the 1% most recently created accounts.
1259 * Bots and sysops are excluded.
1260 * @return bool True if it is a newbie.
1262 function isNewbie() {
1263 return $this->mId
> User
::getMaxID() * 0.99 && !$this->isSysop() && !$this->isBot() ||
$this->getID() == 0;
1267 * Check to see if the given clear-text password is one of the accepted passwords
1268 * @param string $password User password.
1269 * @return bool True if the given password is correct otherwise False.
1271 function checkPassword( $password ) {
1273 $this->loadFromDatabase();
1275 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1277 } elseif( $wgAuth->strict() ) {
1278 /* Auth plugin doesn't allow local authentication */
1281 $ep = $this->encryptPassword( $password );
1282 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
1284 } elseif ( ($this->mNewpassword
!= '') && (0 == strcmp( $ep, $this->mNewpassword
)) ) {
1285 # If e-mail confirmation hasn't been done already,
1286 # we may as well confirm it here -- the user can only
1287 # get this password via e-mail.
1288 $this->mEmailAuthenticated
= wfTimestampNow();
1290 # use the temporary one-time password only once: clear it now !
1291 $this->mNewpassword
= '';
1292 $this->saveSettings();
1294 } elseif ( function_exists( 'iconv' ) ) {
1295 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1296 # Check for this with iconv
1297 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1298 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
1306 * Initialize (if necessary) and return a session token value
1307 * which can be used in edit forms to show that the user's
1308 * login credentials aren't being hijacked with a foreign form
1311 * @param mixed $salt - Optional function-specific data for hash.
1312 * Use a string or an array of strings.
1316 function editToken( $salt = '' ) {
1317 if( !isset( $_SESSION['wsEditToken'] ) ) {
1318 $token = $this->generateToken();
1319 $_SESSION['wsEditToken'] = $token;
1321 $token = $_SESSION['wsEditToken'];
1323 if( is_array( $salt ) ) {
1324 $salt = implode( '|', $salt );
1326 return md5( $token . $salt );
1330 * Generate a hex-y looking random token for various uses.
1331 * Could be made more cryptographically sure if someone cares.
1334 function generateToken( $salt = '' ) {
1335 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1336 return md5( $token . $salt );
1340 * Check given value against the token value stored in the session.
1341 * A match should confirm that the form was submitted from the
1342 * user's own login session, not a form submission from a third-party
1345 * @param string $val - the input value to compare
1346 * @param string $salt - Optional function-specific data for hash
1350 function matchEditToken( $val, $salt = '' ) {
1351 return ( $val == $this->editToken( $salt ) );
1355 * Generate a new e-mail confirmation token and send a confirmation
1356 * mail to the user's given address.
1358 * @return mixed True on success, a WikiError object on failure.
1360 function sendConfirmationMail() {
1361 global $wgIP, $wgContLang;
1362 $url = $this->confirmationTokenUrl( $expiration );
1363 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1364 wfMsg( 'confirmemail_body',
1368 $wgContLang->timeanddate( $expiration, false ) ) );
1372 * Send an e-mail to this user's account. Does not check for
1373 * confirmed status or validity.
1375 * @param string $subject
1376 * @param string $body
1377 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1378 * @return mixed True on success, a WikiError object on failure.
1380 function sendMail( $subject, $body, $from = null ) {
1381 if( is_null( $from ) ) {
1382 global $wgPasswordSender;
1383 $from = $wgPasswordSender;
1386 require_once( 'UserMailer.php' );
1387 $error = userMailer( $this->getEmail(), $from, $subject, $body );
1389 if( $error == '' ) {
1392 return new WikiError( $error );
1397 * Generate, store, and return a new e-mail confirmation code.
1398 * A hash (unsalted since it's used as a key) is stored.
1399 * @param &$expiration mixed output: accepts the expiration time
1403 function confirmationToken( &$expiration ) {
1404 $fname = 'User::confirmationToken';
1407 $expires = $now +
7 * 24 * 60 * 60;
1408 $expiration = wfTimestamp( TS_MW
, $expires );
1410 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
1411 $hash = md5( $token );
1413 $dbw =& wfGetDB( DB_MASTER
);
1414 $dbw->update( 'user',
1415 array( 'user_email_token' => $hash,
1416 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1417 array( 'user_id' => $this->mId
),
1424 * Generate and store a new e-mail confirmation token, and return
1425 * the URL the user can use to confirm.
1426 * @param &$expiration mixed output: accepts the expiration time
1430 function confirmationTokenUrl( &$expiration ) {
1431 $token = $this->confirmationToken( $expiration );
1432 $title = Title
::makeTitle( NS_SPECIAL
, 'Confirmemail/' . $token );
1433 return $title->getFullUrl();
1437 * Mark the e-mail address confirmed and save.
1439 function confirmEmail() {
1440 $this->loadFromDatabase();
1441 $this->mEmailAuthenticated
= wfTimestampNow();
1442 $this->saveSettings();
1447 * Is this user allowed to send e-mails within limits of current
1448 * site configuration?
1451 function canSendEmail() {
1452 return $this->isEmailConfirmed();
1456 * Is this user allowed to receive e-mails within limits of current
1457 * site configuration?
1460 function canReceiveEmail() {
1461 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1465 * Is this user's e-mail address valid-looking and confirmed within
1466 * limits of the current site configuration?
1468 * If $wgEmailAuthentication is on, this may require the user to have
1469 * confirmed their address by returning a code or using a password
1470 * sent to the address from the wiki.
1474 function isEmailConfirmed() {
1475 global $wgEmailAuthentication;
1476 $this->loadFromDatabase();
1477 if( $this->isAnon() )
1479 if( !$this->isValidEmailAddr( $this->mEmail
) )
1481 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )