11 require_once( 'WatchedItem.php' );
13 # Number of characters in user_token field
14 define( 'USER_TOKEN_LENGTH', 32 );
24 var $mId, $mName, $mPassword, $mEmail, $mNewtalk;
25 var $mEmailAuthenticated;
26 var $mRights, $mOptions;
27 var $mDataLoaded, $mNewpassword;
29 var $mBlockedby, $mBlockreason;
36 /** Construct using User:loadDefaults() */
38 $this->loadDefaults();
42 * Static factory method
43 * @param string $name Username, validated by Title:newFromText()
47 function newFromName( $name ) {
50 # Clean up name according to title rules
52 $t = Title
::newFromText( $name );
56 $u->setName( $t->getText() );
57 $u->setId( $u->idFromName( $t->getText() ) );
63 * Factory method to fetch whichever use has a given email confirmation code.
64 * This code is generated when an account is created or its e-mail address
67 * If the code is invalid or has expired, returns NULL.
73 function newFromConfirmationCode( $code ) {
74 $dbr =& wfGetDB( DB_SLAVE
);
75 $name = $dbr->selectField( 'user', 'user_name', array(
76 'user_email_token' => md5( $code ),
77 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
79 if( is_string( $name ) ) {
80 return User
::newFromName( $name );
87 * Get username given an id.
88 * @param integer $id Database user id
89 * @return string Nickname of a user
92 function whoIs( $id ) {
93 $dbr =& wfGetDB( DB_SLAVE
);
94 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ) );
98 * Get real username given an id.
99 * @param integer $id Database user id
100 * @return string Realname of a user
103 function whoIsReal( $id ) {
104 $dbr =& wfGetDB( DB_SLAVE
);
105 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ) );
109 * Get database id given a user name
110 * @param string $name Nickname of a user
111 * @return integer|null Database user id (null: if non existent
114 function idFromName( $name ) {
115 $fname = "User::idFromName";
117 $nt = Title
::newFromText( $name );
118 if( is_null( $nt ) ) {
122 $dbr =& wfGetDB( DB_SLAVE
);
123 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
125 if ( $s === false ) {
133 * does the string match an anonymous IPv4 address?
136 * @param string $name Nickname of a user
139 function isIP( $name ) {
140 return preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}$/",$name);
141 /*return preg_match("/^
142 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
143 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
144 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
145 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
150 * does the string match roughly an email address ?
154 * @param string $addr email address
158 function isValidEmailAddr ( $addr ) {
159 # There used to be a regular expression here, it got removed because it
160 # rejected valid addresses.
161 return ( trim( $addr ) != '' ) &&
162 (false !== strpos( $addr, '@' ) );
166 * probably return a random password
167 * @return string probably a random password
169 * @todo Check what is doing really [AV]
171 function randomPassword() {
172 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
173 $l = strlen( $pwchars ) - 1;
175 $np = $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
176 $pwchars{mt_rand( 0, $l )} . chr( mt_rand(48, 57) ) .
177 $pwchars{mt_rand( 0, $l )} . $pwchars{mt_rand( 0, $l )} .
178 $pwchars{mt_rand( 0, $l )};
183 * Set properties to default
184 * Used at construction. It will load per language default settings only
185 * if we have an available language object.
187 function loadDefaults() {
190 $fname = 'User::loadDefaults' . $n;
191 wfProfileIn( $fname );
193 global $wgContLang, $wgIP, $wgDBname;
194 global $wgNamespacesToBeSearchedDefault;
197 $this->mNewtalk
= -1;
198 $this->mName
= $wgIP;
199 $this->mRealName
= $this->mEmail
= '';
200 $this->mEmailAuthenticated
= null;
201 $this->mPassword
= $this->mNewpassword
= '';
202 $this->mRights
= array();
203 $this->mGroups
= array();
204 // Getting user defaults only if we have an available language
205 if( isset( $wgContLang ) ) {
206 $this->loadDefaultFromLanguage();
209 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
210 $this->mOptions
['searchNs'.$nsnum] = $val;
212 unset( $this->mSkin
);
213 $this->mDataLoaded
= false;
214 $this->mBlockedby
= -1; # Unset
215 $this->setToken(); # Random
216 $this->mHash
= false;
218 if ( isset( $_COOKIE[$wgDBname.'LoggedOut'] ) ) {
219 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgDBname.'LoggedOut'] );
222 $this->mTouched
= '0'; # Allow any pages to be cached
225 wfProfileOut( $fname );
229 * Used to load user options from a language.
230 * This is not in loadDefault() cause we sometime create user before having
233 function loadDefaultFromLanguage(){
234 $this->mOptions
= User
::getDefaultOptions();
238 * Combine the language default options with any site-specific options
239 * and add the default language variants.
245 function getDefaultOptions() {
247 * Site defaults will override the global/language defaults
249 global $wgContLang, $wgDefaultUserOptions;
250 $defOpt = $wgDefaultUserOptions +
$wgContLang->getDefaultUserOptions();
253 * default language setting
255 $variant = $wgContLang->getPreferredVariant();
256 $defOpt['variant'] = $variant;
257 $defOpt['language'] = $variant;
263 * Get a given default option value.
270 function getDefaultOption( $opt ) {
271 $defOpts = User
::getDefaultOptions();
272 if( isset( $defOpts[$opt] ) ) {
273 return $defOpts[$opt];
280 * Get blocking information
282 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
283 * non-critical checks are done against slaves. Check when actually saving should be done against
286 * Note that even if $bFromSlave is false, the check is done first against slave, then master.
287 * The logic is that if blocked on slave, we'll assume it's either blocked on master or
288 * just slightly outta sync and soon corrected - safer to block slightly more that less.
289 * And it's cheaper to check slave first, then master if needed, than master always.
291 function getBlockedStatus( $bFromSlave = true ) {
292 global $wgIP, $wgBlockCache, $wgProxyList, $wgEnableSorbs, $wgProxyWhitelist;
294 if ( -1 != $this->mBlockedby
) { return; }
296 $this->mBlockedby
= 0;
300 $block = new Block();
301 $block->forUpdate( $bFromSlave );
302 if ( $block->load( $wgIP , $this->mId
) ) {
303 $this->mBlockedby
= $block->mBy
;
304 $this->mBlockreason
= $block->mReason
;
305 $this->spreadBlock();
310 if ( !$this->mBlockedby
) {
311 # Check first against slave, and optionally from master.
312 $block = $wgBlockCache->get( $wgIP, true );
313 if ( !$block && !$bFromSlave )
315 # Not blocked: check against master, to make sure.
316 $wgBlockCache->clearLocal( );
317 $block = $wgBlockCache->get( $wgIP, false );
319 if ( $block !== false ) {
320 $this->mBlockedby
= $block->mBy
;
321 $this->mBlockreason
= $block->mReason
;
326 if ( !$this->isSysop() && !in_array( $wgIP, $wgProxyWhitelist ) ) {
329 if ( array_key_exists( $wgIP, $wgProxyList ) ) {
330 $this->mBlockedby
= wfMsg( 'proxyblocker' );
331 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
335 if ( !$this->mBlockedby
&& $wgEnableSorbs ) {
336 if ( $this->inSorbsBlacklist( $wgIP ) ) {
337 $this->mBlockedby
= wfMsg( 'sorbs' );
338 $this->mBlockreason
= wfMsg( 'sorbsreason' );
344 function inSorbsBlacklist( $ip ) {
345 global $wgEnableSorbs;
346 return $wgEnableSorbs &&
347 $this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
350 function inOpmBlacklist( $ip ) {
352 return $wgEnableOpm &&
353 $this->inDnsBlacklist( $ip, 'opm.blitzed.org.' );
356 function inDnsBlacklist( $ip, $base ) {
357 $fname = 'User::inDnsBlacklist';
358 wfProfileIn( $fname );
363 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
365 for ( $i=4; $i>=1; $i-- ) {
366 $host .= $m[$i] . '.';
371 $ipList = gethostbynamel( $host );
374 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
377 wfDebug( "Requested $host, not found in $base.\n" );
381 wfProfileOut( $fname );
386 * Primitive rate limits: enforce maximum actions per time period
387 * to put a brake on flooding.
389 * Note: when using a shared cache like memcached, IP-address
390 * last-hit counters will be shared across wikis.
392 * @return bool true if a rate limiter was tripped
395 function pingLimiter( $action='edit' ) {
396 global $wgRateLimits;
397 if( !isset( $wgRateLimits[$action] ) ) {
400 if( $this->isAllowed( 'delete' ) ) {
405 global $wgMemc, $wgIP, $wgDBname, $wgRateLimitLog;
406 $fname = 'User::pingLimiter';
407 $limits = $wgRateLimits[$action];
409 $id = $this->getId();
411 if( isset( $limits['anon'] ) && $id == 0 ) {
412 $keys["$wgDBname:limiter:$action:anon"] = $limits['anon'];
415 if( isset( $limits['user'] ) && $id != 0 ) {
416 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['user'];
418 if( $this->isNewbie() ) {
419 if( isset( $limits['newbie'] ) && $id != 0 ) {
420 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['newbie'];
422 if( isset( $limits['ip'] ) ) {
423 $keys["mediawiki:limiter:$action:ip:$wgIP"] = $limits['ip'];
425 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $wgIP, $matches ) ) {
426 $subnet = $matches[1];
427 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
432 foreach( $keys as $key => $limit ) {
433 list( $max, $period ) = $limit;
434 $summary = "(limit $max in {$period}s)";
435 $count = $wgMemc->get( $key );
437 if( $count > $max ) {
438 wfDebug( "$fname: tripped! $key at $count $summary\n" );
439 if( $wgRateLimitLog ) {
440 @error_log
( wfTimestamp( TS_MW
) . ' ' . $wgDBname . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
444 wfDebug( "$fname: ok. $key at $count $summary\n" );
447 wfDebug( "$fname: adding record for $key $summary\n" );
448 $wgMemc->add( $key, 1, IntVal( $period ) );
450 $wgMemc->incr( $key );
457 * Check if user is blocked
458 * @return bool True if blocked, false otherwise
460 function isBlocked( $bFromSlave = false ) {
461 $this->getBlockedStatus( $bFromSlave );
462 return $this->mBlockedby
!== 0;
466 * Get name of blocker
467 * @return string name of blocker
469 function blockedBy() {
470 $this->getBlockedStatus();
471 return $this->mBlockedby
;
475 * Get blocking reason
476 * @return string Blocking reason
478 function blockedFor() {
479 $this->getBlockedStatus();
480 return $this->mBlockreason
;
484 * Initialise php session
486 function SetupSession() {
487 global $wgSessionsInMemcached, $wgCookiePath, $wgCookieDomain;
488 if( $wgSessionsInMemcached ) {
489 require_once( 'MemcachedSessions.php' );
490 } elseif( 'files' != ini_get( 'session.save_handler' ) ) {
491 # If it's left on 'user' or another setting from another
492 # application, it will end up failing. Try to recover.
493 ini_set ( 'session.save_handler', 'files' );
495 session_set_cookie_params( 0, $wgCookiePath, $wgCookieDomain );
496 session_cache_limiter( 'private, must-revalidate' );
501 * Read datas from session
504 function loadFromSession() {
505 global $wgMemc, $wgDBname;
507 if ( isset( $_SESSION['wsUserID'] ) ) {
508 if ( 0 != $_SESSION['wsUserID'] ) {
509 $sId = $_SESSION['wsUserID'];
513 } else if ( isset( $_COOKIE["{$wgDBname}UserID"] ) ) {
514 $sId = IntVal( $_COOKIE["{$wgDBname}UserID"] );
515 $_SESSION['wsUserID'] = $sId;
519 if ( isset( $_SESSION['wsUserName'] ) ) {
520 $sName = $_SESSION['wsUserName'];
521 } else if ( isset( $_COOKIE["{$wgDBname}UserName"] ) ) {
522 $sName = $_COOKIE["{$wgDBname}UserName"];
523 $_SESSION['wsUserName'] = $sName;
528 $passwordCorrect = FALSE;
529 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
530 if($makenew = !$user) {
531 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
534 $user->loadFromDatabase();
536 wfDebug( "User::loadFromSession() got from cache!\n" );
539 if ( isset( $_SESSION['wsToken'] ) ) {
540 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken
;
541 } else if ( isset( $_COOKIE["{$wgDBname}Token"] ) ) {
542 $passwordCorrect = $user->mToken
== $_COOKIE["{$wgDBname}Token"];
544 return new User(); # Can't log in from session
547 if ( ( $sName == $user->mName
) && $passwordCorrect ) {
549 if($wgMemc->set( $key, $user ))
550 wfDebug( "User::loadFromSession() successfully saved user\n" );
552 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
556 return new User(); # Can't log in from session
560 * Load a user from the database
562 function loadFromDatabase() {
563 global $wgCommandLineMode;
564 $fname = "User::loadFromDatabase";
566 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
567 # loading in a command line script, don't assume all command line scripts need it like this
568 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
569 if ( $this->mDataLoaded
) {
574 $this->mId
= IntVal( $this->mId
);
576 /** Anonymous user */
579 $this->mRights
= $this->getGroupPermissions( array( '*' ) );
580 $this->mDataLoaded
= true;
582 } # the following stuff is for non-anonymous users only
584 $dbr =& wfGetDB( DB_SLAVE
);
585 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
586 'user_email_authenticated',
587 'user_real_name','user_options','user_touched', 'user_token' ),
588 array( 'user_id' => $this->mId
), $fname );
590 if ( $s !== false ) {
591 $this->mName
= $s->user_name
;
592 $this->mEmail
= $s->user_email
;
593 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
594 $this->mRealName
= $s->user_real_name
;
595 $this->mPassword
= $s->user_password
;
596 $this->mNewpassword
= $s->user_newpassword
;
597 $this->decodeOptions( $s->user_options
);
598 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
599 $this->mToken
= $s->user_token
;
601 $res = $dbr->select( 'user_groups',
603 array( 'ug_user' => $this->mId
),
605 $this->mGroups
= array();
606 while( $row = $dbr->fetchObject( $res ) ) {
607 $this->mGroups
[] = $row->ug_group
;
609 $effectiveGroups = array_merge( array( '*', 'user' ), $this->mGroups
);
610 $this->mRights
= $this->getGroupPermissions( $effectiveGroups );
613 $this->mDataLoaded
= true;
616 function getID() { return $this->mId
; }
617 function setID( $v ) {
619 $this->mDataLoaded
= false;
623 $this->loadFromDatabase();
627 function setName( $str ) {
628 $this->loadFromDatabase();
634 * Return the title dbkey form of the name, for eg user pages.
638 function getTitleKey() {
639 return str_replace( ' ', '_', $this->getName() );
642 function getNewtalk() {
643 $fname = 'User::getNewtalk';
644 $this->loadFromDatabase();
646 # Load the newtalk status if it is unloaded (mNewtalk=-1)
647 if( $this->mNewtalk
== -1 ) {
648 $this->mNewtalk
= 0; # reset talk page status
650 # Check memcached separately for anons, who have no
651 # entire User object stored in there.
653 global $wgDBname, $wgMemc;
654 $key = "$wgDBname:newtalk:ip:{$this->mName}";
655 $newtalk = $wgMemc->get( $key );
656 if( is_integer( $newtalk ) ) {
657 $this->mNewtalk
= $newtalk ?
1 : 0;
658 return (bool)$this->mNewtalk
;
662 $dbr =& wfGetDB( DB_SLAVE
);
663 $res = $dbr->select( 'watchlist',
665 array( 'wl_title' => $this->getTitleKey(),
666 'wl_namespace' => NS_USER_TALK
,
667 'wl_user' => $this->mId
,
668 'wl_notificationtimestamp != 0' ),
669 'User::getNewtalk' );
670 if( $dbr->numRows($res) > 0 ) {
673 $dbr->freeResult( $res );
676 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
680 return ( 0 != $this->mNewtalk
);
683 function setNewtalk( $val ) {
684 $this->loadFromDatabase();
685 $this->mNewtalk
= $val;
686 $this->invalidateCache();
689 function invalidateCache() {
690 global $wgClockSkewFudge;
691 $this->loadFromDatabase();
692 $this->mTouched
= wfTimestamp(TS_MW
, time() +
$wgClockSkewFudge );
693 # Don't forget to save the options after this or
694 # it won't take effect!
697 function validateCache( $timestamp ) {
698 $this->loadFromDatabase();
699 return ($timestamp >= $this->mTouched
);
704 * Will only be salted if $wgPasswordSalt is true
705 * @param string Password.
706 * @return string Salted password or clear password.
708 function addSalt( $p ) {
709 global $wgPasswordSalt;
711 return md5( "{$this->mId}-{$p}" );
717 * Encrypt a password.
718 * It can eventuall salt a password @see User::addSalt()
719 * @param string $p clear Password.
720 * @param string Encrypted password.
722 function encryptPassword( $p ) {
723 return $this->addSalt( md5( $p ) );
726 # Set the password and reset the random token
727 function setPassword( $str ) {
728 $this->loadFromDatabase();
730 $this->mPassword
= $this->encryptPassword( $str );
731 $this->mNewpassword
= '';
734 # Set the random token (used for persistent authentication)
735 function setToken( $token = false ) {
736 global $wgSecretKey, $wgProxyKey, $wgDBname;
738 if ( $wgSecretKey ) {
740 } elseif ( $wgProxyKey ) {
745 $this->mToken
= md5( $wgSecretKey . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId
);
747 $this->mToken
= $token;
752 function setCookiePassword( $str ) {
753 $this->loadFromDatabase();
754 $this->mCookiePassword
= md5( $str );
757 function setNewpassword( $str ) {
758 $this->loadFromDatabase();
759 $this->mNewpassword
= $this->encryptPassword( $str );
762 function getEmail() {
763 $this->loadFromDatabase();
764 return $this->mEmail
;
767 function getEmailAuthenticationTimestamp() {
768 $this->loadFromDatabase();
769 return $this->mEmailAuthenticated
;
772 function setEmail( $str ) {
773 $this->loadFromDatabase();
774 $this->mEmail
= $str;
777 function getRealName() {
778 $this->loadFromDatabase();
779 return $this->mRealName
;
782 function setRealName( $str ) {
783 $this->loadFromDatabase();
784 $this->mRealName
= $str;
787 function getOption( $oname ) {
788 $this->loadFromDatabase();
789 if ( array_key_exists( $oname, $this->mOptions
) ) {
790 return $this->mOptions
[$oname];
796 function setOption( $oname, $val ) {
797 $this->loadFromDatabase();
798 if ( $oname == 'skin' ) {
799 # Clear cached skin, so the new one displays immediately in Special:Preferences
800 unset( $this->mSkin
);
802 $this->mOptions
[$oname] = $val;
803 $this->invalidateCache();
806 function getRights() {
807 $this->loadFromDatabase();
808 return $this->mRights
;
812 * Get the list of explicit group memberships this user has.
813 * The implicit * and user groups are not included.
814 * @return array of strings
816 function getGroups() {
817 $this->loadFromDatabase();
818 return $this->mGroups
;
822 * Get the list of implicit group memberships this user has.
823 * This includes all explicit groups, plus 'user' if logged in
824 * and '*' for all accounts.
825 * @return array of strings
827 function getEffectiveGroups() {
828 $base = array( '*' );
829 if( $this->isLoggedIn() ) {
832 return array_merge( $base, $this->getGroups() );
836 * Remove the user from the given group.
837 * This takes immediate effect.
840 function addGroup( $group ) {
841 $dbw =& wfGetDB( DB_MASTER
);
842 $dbw->insert( 'user_groups',
844 'ug_user' => $this->getID(),
845 'ug_group' => $group,
850 $this->mGroups
= array_merge( $this->mGroups
, array( $group ) );
851 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups() );
853 $this->invalidateCache();
854 $this->saveSettings();
858 * Remove the user from the given group.
859 * This takes immediate effect.
862 function removeGroup( $group ) {
863 $dbw =& wfGetDB( DB_MASTER
);
864 $dbw->delete( 'user_groups',
866 'ug_user' => $this->getID(),
867 'ug_group' => $group,
869 'User::removeGroup' );
871 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
872 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups() );
874 $this->invalidateCache();
875 $this->saveSettings();
880 * A more legible check for non-anonymousness.
881 * Returns true if the user is not an anonymous visitor.
885 function isLoggedIn() {
886 return( $this->getID() != 0 );
890 * A more legible check for anonymousness.
891 * Returns true if the user is an anonymous visitor.
896 return !$this->isLoggedIn();
900 * Check if a user is sysop
901 * Die with backtrace. Use User:isAllowed() instead.
905 return $this->isAllowed( 'protect' );
909 function isDeveloper() {
910 return $this->isAllowed( 'siteadmin' );
914 function isBureaucrat() {
915 return $this->isAllowed( 'makesysop' );
919 * Whether the user is a bot
920 * @todo need to be migrated to the new user level management sytem
923 $this->loadFromDatabase();
924 return in_array( 'bot', $this->mRights
);
928 * Check if user is allowed to access a feature / make an action
929 * @param string $action Action to be checked (see $wgAvailableRights in Defines.php for possible actions).
930 * @return boolean True: action is allowed, False: action should not be allowed
932 function isAllowed($action='') {
933 $this->loadFromDatabase();
934 return in_array( $action , $this->mRights
);
938 * Load a skin if it doesn't exist or return it
939 * @todo FIXME : need to check the old failback system [AV]
941 function &getSkin() {
943 if ( ! isset( $this->mSkin
) ) {
944 $fname = 'User::getSkin';
945 wfProfileIn( $fname );
947 # get all skin names available
948 $skinNames = Skin
::getSkinNames();
951 $userSkin = $this->getOption( 'skin' );
952 if ( $userSkin == '' ) { $userSkin = 'standard'; }
954 if ( !isset( $skinNames[$userSkin] ) ) {
955 # in case the user skin could not be found find a replacement
960 # if phptal is enabled we should have monobook skin that
961 # superseed the good old SkinStandard.
962 if ( isset( $skinNames['monobook'] ) ) {
963 $fallback[0] = 'MonoBook';
966 if(is_numeric($userSkin) && isset( $fallback[$userSkin]) ){
967 $sn = $fallback[$userSkin];
972 # The user skin is available
973 $sn = $skinNames[$userSkin];
976 # Grab the skin class and initialise it. Each skin checks for PHPTal
977 # and will not load if it's not enabled.
978 require_once( $IP.'/skins/'.$sn.'.php' );
980 # Check if we got if not failback to default skin
981 $className = 'Skin'.$sn;
982 if( !class_exists( $className ) ) {
983 # DO NOT die if the class isn't found. This breaks maintenance
984 # scripts and can cause a user account to be unrecoverable
985 # except by SQL manipulation if a previously valid skin name
986 # is no longer valid.
987 $className = 'SkinStandard';
988 require_once( $IP.'/skins/Standard.php' );
990 $this->mSkin
=& new $className;
991 wfProfileOut( $fname );
997 * @param string $title Article title to look at
1001 * Check watched status of an article
1002 * @return bool True if article is watched
1004 function isWatched( $title ) {
1005 $wl = WatchedItem
::fromUserTitle( $this, $title );
1006 return $wl->isWatched();
1012 function addWatch( $title ) {
1013 $wl = WatchedItem
::fromUserTitle( $this, $title );
1015 $this->invalidateCache();
1019 * Stop watching an article
1021 function removeWatch( $title ) {
1022 $wl = WatchedItem
::fromUserTitle( $this, $title );
1024 $this->invalidateCache();
1028 * Clear the user's notification timestamp for the given title.
1029 * If e-notif e-mails are on, they will receive notification mails on
1030 * the next change of the page if it's watched etc.
1032 function clearNotification( &$title ) {
1035 $userid = $this->getID();
1039 // Only update the timestamp if the page is being watched.
1040 // The query to find out if it is watched is cached both in memcached and per-invocation,
1041 // and when it does have to be executed, it can be on a slave
1042 // If this is the user's newtalk page, we always update the timestamp
1043 if ($title->getNamespace() == NS_USER_TALK
&&
1044 $title->getText() == $wgUser->getName())
1047 } elseif ( $this->getID() == $wgUser->getID() ) {
1048 $watched = $title->userIsWatching();
1053 // If the page is watched by the user (or may be watched), update the timestamp on any
1054 // any matching rows
1056 $dbw =& wfGetDB( DB_MASTER
);
1057 $success = $dbw->update( 'watchlist',
1059 'wl_notificationtimestamp' => 0
1060 ), array( /* WHERE */
1061 'wl_title' => $title->getDBkey(),
1062 'wl_namespace' => $title->getNamespace(),
1063 'wl_user' => $this->getID()
1064 ), 'User::clearLastVisited'
1072 * Resets all of the given user's page-change notification timestamps.
1073 * If e-notif e-mails are on, they will receive notification mails on
1074 * the next change of any watched page.
1076 * @param int $currentUser user ID number
1079 function clearAllNotifications( $currentUser ) {
1080 if( $currentUser != 0 ) {
1082 $dbw =& wfGetDB( DB_MASTER
);
1083 $success = $dbw->update( 'watchlist',
1085 'wl_notificationtimestamp' => 0
1086 ), array( /* WHERE */
1087 'wl_user' => $currentUser
1088 ), 'UserMailer::clearAll'
1091 # we also need to clear here the "you have new message" notification for the own user_talk page
1092 # This is cleared one page view later in Article::viewUpdates();
1098 * @return string Encoding options
1100 function encodeOptions() {
1102 foreach ( $this->mOptions
as $oname => $oval ) {
1103 array_push( $a, $oname.'='.$oval );
1105 $s = implode( "\n", $a );
1112 function decodeOptions( $str ) {
1113 $a = explode( "\n", $str );
1114 foreach ( $a as $s ) {
1115 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1116 $this->mOptions
[$m[1]] = $m[2];
1121 function setCookies() {
1122 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgDBname;
1123 if ( 0 == $this->mId
) return;
1124 $this->loadFromDatabase();
1125 $exp = time() +
$wgCookieExpiration;
1127 $_SESSION['wsUserID'] = $this->mId
;
1128 setcookie( $wgDBname.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain );
1130 $_SESSION['wsUserName'] = $this->mName
;
1131 setcookie( $wgDBname.'UserName', $this->mName
, $exp, $wgCookiePath, $wgCookieDomain );
1133 $_SESSION['wsToken'] = $this->mToken
;
1134 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1135 setcookie( $wgDBname.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain );
1137 setcookie( $wgDBname.'Token', '', time() - 3600 );
1143 * It will clean the session cookie
1146 global $wgCookiePath, $wgCookieDomain, $wgDBname, $wgIP;
1147 $this->loadDefaults();
1148 $this->setLoaded( true );
1150 $_SESSION['wsUserID'] = 0;
1152 setcookie( $wgDBname.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1153 setcookie( $wgDBname.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain );
1155 # Remember when user logged out, to prevent seeing cached pages
1156 setcookie( $wgDBname.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain );
1160 * Save object settings into database
1162 function saveSettings() {
1163 global $wgMemc, $wgDBname;
1164 $fname = 'User::saveSettings';
1166 $dbw =& wfGetDB( DB_MASTER
);
1167 if ( ! $this->getNewtalk() ) {
1168 # Delete the watchlist entry for user_talk page X watched by user X
1169 $dbw->delete( 'watchlist',
1170 array( 'wl_user' => $this->mId
,
1171 'wl_title' => $this->getTitleKey(),
1172 'wl_namespace' => NS_USER_TALK
),
1175 # Anon users have a separate memcache space for newtalk
1176 # since they don't store their own info. Trim...
1177 $wgMemc->delete( "$wgDBname:newtalk:ip:{$this->mName}" );
1181 if ( 0 == $this->mId
) { return; }
1183 $dbw->update( 'user',
1185 'user_name' => $this->mName
,
1186 'user_password' => $this->mPassword
,
1187 'user_newpassword' => $this->mNewpassword
,
1188 'user_real_name' => $this->mRealName
,
1189 'user_email' => $this->mEmail
,
1190 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1191 'user_options' => $this->encodeOptions(),
1192 'user_touched' => $dbw->timestamp($this->mTouched
),
1193 'user_token' => $this->mToken
1194 ), array( /* WHERE */
1195 'user_id' => $this->mId
1198 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1202 * Checks if a user with the given name exists, returns the ID
1204 function idForName() {
1205 $fname = 'User::idForName';
1208 $s = trim( $this->mName
);
1209 if ( 0 == strcmp( '', $s ) ) return 0;
1211 $dbr =& wfGetDB( DB_SLAVE
);
1212 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1213 if ( $id === false ) {
1220 * Add user object to the database
1222 function addToDatabase() {
1223 $fname = 'User::addToDatabase';
1224 $dbw =& wfGetDB( DB_MASTER
);
1225 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1226 $dbw->insert( 'user',
1228 'user_id' => $seqVal,
1229 'user_name' => $this->mName
,
1230 'user_password' => $this->mPassword
,
1231 'user_newpassword' => $this->mNewpassword
,
1232 'user_email' => $this->mEmail
,
1233 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1234 'user_real_name' => $this->mRealName
,
1235 'user_options' => $this->encodeOptions(),
1236 'user_token' => $this->mToken
1239 $this->mId
= $dbw->insertId();
1242 function spreadBlock() {
1244 # If the (non-anonymous) user is blocked, this function will block any IP address
1245 # that they successfully log on from.
1246 $fname = 'User::spreadBlock';
1248 wfDebug( "User:spreadBlock()\n" );
1249 if ( $this->mId
== 0 ) {
1253 $userblock = Block
::newFromDB( '', $this->mId
);
1254 if ( !$userblock->isValid() ) {
1258 # Check if this IP address is already blocked
1259 $ipblock = Block
::newFromDB( $wgIP );
1260 if ( $ipblock->isValid() ) {
1261 # Just update the timestamp
1262 $ipblock->updateTimestamp();
1266 # Make a new block object with the desired properties
1267 wfDebug( "Autoblocking {$this->mName}@{$wgIP}\n" );
1268 $ipblock->mAddress
= $wgIP;
1269 $ipblock->mUser
= 0;
1270 $ipblock->mBy
= $userblock->mBy
;
1271 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
1272 $ipblock->mTimestamp
= wfTimestampNow();
1273 $ipblock->mAuto
= 1;
1274 # If the user is already blocked with an expiry date, we don't
1275 # want to pile on top of that!
1276 if($userblock->mExpiry
) {
1277 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
1279 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
1287 function getPageRenderingHash() {
1290 return $this->mHash
;
1293 // stubthreshold is only included below for completeness,
1294 // it will always be 0 when this function is called by parsercache.
1296 $confstr = $this->getOption( 'math' );
1297 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1298 $confstr .= '!' . $this->getOption( 'editsection' );
1299 $confstr .= '!' . $this->getOption( 'date' );
1300 $confstr .= '!' . $this->getOption( 'numberheadings' );
1301 $confstr .= '!' . $this->getOption( 'language' );
1302 $confstr .= '!' . $this->getOption( 'thumbsize' );
1303 // add in language specific options, if any
1304 $extra = $wgContLang->getExtraHashOptions();
1307 $this->mHash
= $confstr;
1311 function isAllowedToCreateAccount() {
1312 global $wgWhitelistAccount;
1315 if (!$wgWhitelistAccount) { return 1; }; // default behaviour
1316 foreach ($wgWhitelistAccount as $right => $ok) {
1317 $userHasRight = (!strcmp($right, 'user') ||
in_array($right, $this->getRights()));
1318 $allowed |
= ($ok && $userHasRight);
1324 * Set mDataLoaded, return previous value
1325 * Use this to prevent DB access in command-line scripts or similar situations
1327 function setLoaded( $loaded ) {
1328 return wfSetVar( $this->mDataLoaded
, $loaded );
1332 * Get this user's personal page title.
1337 function getUserPage() {
1338 return Title
::makeTitle( NS_USER
, $this->mName
);
1342 * Get this user's talk page title.
1347 function getTalkPage() {
1348 $title = $this->getUserPage();
1349 return $title->getTalkPage();
1355 function getMaxID() {
1356 $dbr =& wfGetDB( DB_SLAVE
);
1357 return $dbr->selectField( 'user', 'max(user_id)', false );
1361 * Determine whether the user is a newbie. Newbies are either
1362 * anonymous IPs, or the 1% most recently created accounts.
1363 * Bots and sysops are excluded.
1364 * @return bool True if it is a newbie.
1366 function isNewbie() {
1367 return $this->isAnon() ||
$this->mId
> User
::getMaxID() * 0.99 && !$this->isAllowed( 'delete' ) && !$this->isBot();
1371 * Check to see if the given clear-text password is one of the accepted passwords
1372 * @param string $password User password.
1373 * @return bool True if the given password is correct otherwise False.
1375 function checkPassword( $password ) {
1376 global $wgAuth, $wgMinimalPasswordLength;
1377 $this->loadFromDatabase();
1379 // Even though we stop people from creating passwords that
1380 // are shorter than this, doesn't mean people wont be able
1381 // to. Certain authentication plugins do NOT want to save
1382 // domain passwords in a mysql database, so we should
1383 // check this (incase $wgAuth->strict() is false).
1384 if( strlen( $password ) < $wgMinimalPasswordLength ) {
1388 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1390 } elseif( $wgAuth->strict() ) {
1391 /* Auth plugin doesn't allow local authentication */
1394 $ep = $this->encryptPassword( $password );
1395 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
1397 } elseif ( ($this->mNewpassword
!= '') && (0 == strcmp( $ep, $this->mNewpassword
)) ) {
1399 } elseif ( function_exists( 'iconv' ) ) {
1400 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1401 # Check for this with iconv
1402 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1403 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
1411 * Initialize (if necessary) and return a session token value
1412 * which can be used in edit forms to show that the user's
1413 * login credentials aren't being hijacked with a foreign form
1416 * @param mixed $salt - Optional function-specific data for hash.
1417 * Use a string or an array of strings.
1421 function editToken( $salt = '' ) {
1422 if( !isset( $_SESSION['wsEditToken'] ) ) {
1423 $token = $this->generateToken();
1424 $_SESSION['wsEditToken'] = $token;
1426 $token = $_SESSION['wsEditToken'];
1428 if( is_array( $salt ) ) {
1429 $salt = implode( '|', $salt );
1431 return md5( $token . $salt );
1435 * Generate a hex-y looking random token for various uses.
1436 * Could be made more cryptographically sure if someone cares.
1439 function generateToken( $salt = '' ) {
1440 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1441 return md5( $token . $salt );
1445 * Check given value against the token value stored in the session.
1446 * A match should confirm that the form was submitted from the
1447 * user's own login session, not a form submission from a third-party
1450 * @param string $val - the input value to compare
1451 * @param string $salt - Optional function-specific data for hash
1455 function matchEditToken( $val, $salt = '' ) {
1456 return ( $val == $this->editToken( $salt ) );
1460 * Generate a new e-mail confirmation token and send a confirmation
1461 * mail to the user's given address.
1463 * @return mixed True on success, a WikiError object on failure.
1465 function sendConfirmationMail() {
1466 global $wgIP, $wgContLang;
1467 $url = $this->confirmationTokenUrl( $expiration );
1468 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1469 wfMsg( 'confirmemail_body',
1473 $wgContLang->timeanddate( $expiration, false ) ) );
1477 * Send an e-mail to this user's account. Does not check for
1478 * confirmed status or validity.
1480 * @param string $subject
1481 * @param string $body
1482 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1483 * @return mixed True on success, a WikiError object on failure.
1485 function sendMail( $subject, $body, $from = null ) {
1486 if( is_null( $from ) ) {
1487 global $wgPasswordSender;
1488 $from = $wgPasswordSender;
1491 require_once( 'UserMailer.php' );
1492 $error = userMailer( $this->getEmail(), $from, $subject, $body );
1494 if( $error == '' ) {
1497 return new WikiError( $error );
1502 * Generate, store, and return a new e-mail confirmation code.
1503 * A hash (unsalted since it's used as a key) is stored.
1504 * @param &$expiration mixed output: accepts the expiration time
1508 function confirmationToken( &$expiration ) {
1509 $fname = 'User::confirmationToken';
1512 $expires = $now +
7 * 24 * 60 * 60;
1513 $expiration = wfTimestamp( TS_MW
, $expires );
1515 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
1516 $hash = md5( $token );
1518 $dbw =& wfGetDB( DB_MASTER
);
1519 $dbw->update( 'user',
1520 array( 'user_email_token' => $hash,
1521 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1522 array( 'user_id' => $this->mId
),
1529 * Generate and store a new e-mail confirmation token, and return
1530 * the URL the user can use to confirm.
1531 * @param &$expiration mixed output: accepts the expiration time
1535 function confirmationTokenUrl( &$expiration ) {
1536 $token = $this->confirmationToken( $expiration );
1537 $title = Title
::makeTitle( NS_SPECIAL
, 'Confirmemail/' . $token );
1538 return $title->getFullUrl();
1542 * Mark the e-mail address confirmed and save.
1544 function confirmEmail() {
1545 $this->loadFromDatabase();
1546 $this->mEmailAuthenticated
= wfTimestampNow();
1547 $this->saveSettings();
1552 * Is this user allowed to send e-mails within limits of current
1553 * site configuration?
1556 function canSendEmail() {
1557 return $this->isEmailConfirmed();
1561 * Is this user allowed to receive e-mails within limits of current
1562 * site configuration?
1565 function canReceiveEmail() {
1566 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1570 * Is this user's e-mail address valid-looking and confirmed within
1571 * limits of the current site configuration?
1573 * If $wgEmailAuthentication is on, this may require the user to have
1574 * confirmed their address by returning a code or using a password
1575 * sent to the address from the wiki.
1579 function isEmailConfirmed() {
1580 global $wgEmailAuthentication;
1581 $this->loadFromDatabase();
1582 if( $this->isAnon() )
1584 if( !$this->isValidEmailAddr( $this->mEmail
) )
1586 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
1592 * @param array $groups list of groups
1593 * @return array list of permission key names for given groups combined
1596 function getGroupPermissions( $groups ) {
1597 global $wgGroupPermissions;
1599 foreach( $groups as $group ) {
1600 if( isset( $wgGroupPermissions[$group] ) ) {
1601 $rights = array_merge( $rights, $wgGroupPermissions[$group] );
1608 * @param string $group key name
1609 * @return string localized descriptive name, if provided
1612 function getGroupName( $group ) {
1613 $key = "group-$group-name";
1614 $name = wfMsg( $key );
1615 if( $name == '' ||
$name == "<$key>" ) {
1623 * Return the set of defined explicit groups.
1624 * The * and 'user' groups are not included.
1628 function getAllGroups() {
1629 global $wgGroupPermissions;
1631 array_keys( $wgGroupPermissions ),
1632 array( '*', 'user' ) );