8 # Number of characters in user_token field
9 define( 'USER_TOKEN_LENGTH', 32 );
11 # Serialized record version
12 define( 'MW_USER_VERSION', 3 );
20 * When adding a new private variable, dont forget to add it to __sleep()
26 var $mBlockreason; //!<
28 var $mDataLoaded; //!<
30 var $mEmailAuthenticated; //!<
35 var $mNewpassword; //!<
40 var $mRegistration; //!<
45 var $mDatePreference; // !<
46 var $mVersion; //!< serialized version
50 * Default user options
51 * To change this array at runtime, use a UserDefaultOptions hook
53 static public $mDefaultOptions = array(
66 'highlightbroken' => 1,
70 'editsectiononrightclick'=> 0,
76 'rememberpassword' => 0,
77 'enotifwatchlistpages' => 0,
78 'enotifusertalkpages' => 1,
79 'enotifminoredits' => 0,
80 'enotifrevealaddr' => 0,
81 'shownumberswatching' => 1,
83 'externaleditor' => 0,
86 'numberheadings' => 0,
87 'uselivepreview' => 0,
88 'watchlistdays' => 3.0,
91 static public $mToggles = array(
101 'editsectiononrightclick',
111 'enotifwatchlistpages',
112 'enotifusertalkpages',
115 'shownumberswatching',
127 /** Constructor using User:loadDefaults() */
129 $this->loadDefaults();
130 $this->mVersion
= MW_USER_VERSION
;
134 * Static factory method
135 * @param string $name Username, validated by Title:newFromText()
136 * @param bool $validate Validate username
140 function newFromName( $name, $validate = true ) {
141 # Force usernames to capital
143 $name = $wgContLang->ucfirst( $name );
145 # Clean up name according to title rules
146 $t = Title
::newFromText( $name );
147 if( is_null( $t ) ) {
151 # Reject various classes of invalid names
152 $canonicalName = $t->getText();
154 $canonicalName = $wgAuth->getCanonicalName( $t->getText() );
156 if( $validate && !User
::isValidUserName( $canonicalName ) ) {
161 $u->setName( $canonicalName );
162 $u->setId( $u->idFromName( $canonicalName ) );
167 * Factory method to fetch whichever use has a given email confirmation code.
168 * This code is generated when an account is created or its e-mail address
171 * If the code is invalid or has expired, returns NULL.
173 * @param string $code
177 function newFromConfirmationCode( $code ) {
178 $dbr =& wfGetDB( DB_SLAVE
);
179 $name = $dbr->selectField( 'user', 'user_name', array(
180 'user_email_token' => md5( $code ),
181 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
183 if( is_string( $name ) ) {
184 return User
::newFromName( $name );
191 * Serialze sleep function, for better cache efficiency and avoidance of
192 * silly "incomplete type" errors when skins are cached. The array should
193 * contain names of private variables (see at top of User.php).
199 'mEmailAuthenticated',
218 * Get username given an id.
219 * @param integer $id Database user id
220 * @return string Nickname of a user
223 function whoIs( $id ) {
224 $dbr =& wfGetDB( DB_SLAVE
);
225 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
229 * Get real username given an id.
230 * @param integer $id Database user id
231 * @return string Realname of a user
234 function whoIsReal( $id ) {
235 $dbr =& wfGetDB( DB_SLAVE
);
236 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), 'User::whoIsReal' );
240 * Get database id given a user name
241 * @param string $name Nickname of a user
242 * @return integer|null Database user id (null: if non existent
245 function idFromName( $name ) {
246 $fname = "User::idFromName";
248 $nt = Title
::newFromText( $name );
249 if( is_null( $nt ) ) {
253 $dbr =& wfGetDB( DB_SLAVE
);
254 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), $fname );
256 if ( $s === false ) {
264 * Does the string match an anonymous IPv4 address?
266 * This function exists for username validation, in order to reject
267 * usernames which are similar in form to IP addresses. Strings such
268 * as 300.300.300.300 will return true because it looks like an IP
269 * address, despite not being strictly valid.
271 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
272 * address because the usemod software would "cloak" anonymous IP
273 * addresses like this, if we allowed accounts like this to be created
274 * new users could get the old edits of these anonymous users.
279 * @param string $name Nickname of a user
282 function isIP( $name ) {
283 return preg_match("/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/",$name);
284 /*return preg_match("/^
285 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
286 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
287 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
288 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
293 * Is the input a valid username?
295 * Checks if the input is a valid username, we don't want an empty string,
296 * an IP address, anything that containins slashes (would mess up subpages),
297 * is longer than the maximum allowed username size or doesn't begin with
300 * @param string $name
304 function isValidUserName( $name ) {
305 global $wgContLang, $wgMaxNameChars;
308 || User
::isIP( $name )
309 ||
strpos( $name, '/' ) !== false
310 ||
strlen( $name ) > $wgMaxNameChars
311 ||
$name != $wgContLang->ucfirst( $name ) )
314 // Ensure that the name can't be misresolved as a different title,
315 // such as with extra namespace keys at the start.
316 $parsed = Title
::newFromText( $name );
317 if( is_null( $parsed )
318 ||
$parsed->getNamespace()
319 ||
strcmp( $name, $parsed->getPrefixedText() ) )
322 // Check an additional blacklist of troublemaker characters.
323 // Should these be merged into the title char list?
324 $unicodeBlacklist = '/[' .
325 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
326 '\x{00a0}' . # non-breaking space
327 '\x{2000}-\x{200f}' . # various whitespace
328 '\x{2028}-\x{202f}' . # breaks and control chars
329 '\x{3000}' . # ideographic space
330 '\x{e000}-\x{f8ff}' . # private use
332 if( preg_match( $unicodeBlacklist, $name ) ) {
340 * Usernames which fail to pass this function will be blocked
341 * from user login and new account registrations, but may be used
342 * internally by batch processes.
344 * If an account already exists in this form, login will be blocked
345 * by a failure to pass this function.
347 * @param string $name
350 static function isUsableName( $name ) {
351 global $wgReservedUsernames;
353 // Must be a usable username, obviously ;)
354 self
::isValidUserName( $name ) &&
356 // Certain names may be reserved for batch processes.
357 !in_array( $name, $wgReservedUsernames );
361 * Usernames which fail to pass this function will be blocked
362 * from new account registrations, but may be used internally
363 * either by batch processes or by user accounts which have
364 * already been created.
366 * Additional character blacklisting may be added here
367 * rather than in isValidUserName() to avoid disrupting
370 * @param string $name
373 static function isCreatableName( $name ) {
375 self
::isUsableName( $name ) &&
377 // Registration-time character blacklisting...
378 strpos( $name, '@' ) === false;
382 * Is the input a valid password?
384 * @param string $password
388 function isValidPassword( $password ) {
389 global $wgMinimalPasswordLength;
390 return strlen( $password ) >= $wgMinimalPasswordLength;
394 * Does the string match roughly an email address ?
396 * There used to be a regular expression here, it got removed because it
397 * rejected valid addresses. Actually just check if there is '@' somewhere
398 * in the given address.
400 * @todo Check for RFC 2822 compilance
403 * @param string $addr email address
407 function isValidEmailAddr ( $addr ) {
408 return ( trim( $addr ) != '' ) &&
409 (false !== strpos( $addr, '@' ) );
413 * Count the number of edits of a user
415 * @param int $uid The user ID to check
418 function edits( $uid ) {
419 $fname = 'User::edits';
421 $dbr =& wfGetDB( DB_SLAVE
);
422 return $dbr->selectField(
423 'revision', 'count(*)',
424 array( 'rev_user' => $uid ),
430 * probably return a random password
431 * @return string probably a random password
433 * @todo Check what is doing really [AV]
435 function randomPassword() {
436 global $wgMinimalPasswordLength;
437 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
438 $l = strlen( $pwchars ) - 1;
440 $pwlength = max( 7, $wgMinimalPasswordLength );
441 $digit = mt_rand(0, $pwlength - 1);
443 for ( $i = 0; $i < $pwlength; $i++
) {
444 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
450 * Set properties to default
451 * Used at construction. It will load per language default settings only
452 * if we have an available language object.
454 function loadDefaults() {
457 $fname = 'User::loadDefaults' . $n;
458 wfProfileIn( $fname );
460 global $wgCookiePrefix;
461 global $wgNamespacesToBeSearchedDefault;
464 $this->mNewtalk
= -1;
465 $this->mName
= false;
466 $this->mRealName
= $this->mEmail
= '';
467 $this->mEmailAuthenticated
= null;
468 $this->mPassword
= $this->mNewpassword
= '';
469 $this->mRights
= array();
470 $this->mGroups
= array();
471 $this->mOptions
= null;
472 $this->mDatePreference
= null;
474 unset( $this->mSkin
);
475 $this->mDataLoaded
= false;
476 $this->mBlockedby
= -1; # Unset
477 $this->setToken(); # Random
478 $this->mHash
= false;
480 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
481 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
484 $this->mTouched
= '0'; # Allow any pages to be cached
487 $this->mRegistration
= wfTimestamp( TS_MW
);
489 wfProfileOut( $fname );
493 * Combine the language default options with any site-specific options
494 * and add the default language variants.
500 function getDefaultOptions() {
501 global $wgNamespacesToBeSearchedDefault;
503 * Site defaults will override the global/language defaults
506 $defOpt = self
::$mDefaultOptions +
$wgContLang->getDefaultUserOptionOverrides();
509 * default language setting
511 $variant = $wgContLang->getPreferredVariant( false );
512 $defOpt['variant'] = $variant;
513 $defOpt['language'] = $variant;
515 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
516 $defOpt['searchNs'.$nsnum] = $val;
522 * Get a given default option value.
529 function getDefaultOption( $opt ) {
530 $defOpts = User
::getDefaultOptions();
531 if( isset( $defOpts[$opt] ) ) {
532 return $defOpts[$opt];
539 * Get a list of user toggle names
542 static function getToggles() {
544 $extraToggles = array();
545 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
546 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
551 * Get blocking information
553 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
554 * non-critical checks are done against slaves. Check when actually saving should be done against
557 function getBlockedStatus( $bFromSlave = true ) {
558 global $wgEnableSorbs, $wgProxyWhitelist;
560 if ( -1 != $this->mBlockedby
) {
561 wfDebug( "User::getBlockedStatus: already loaded.\n" );
565 $fname = 'User::getBlockedStatus';
566 wfProfileIn( $fname );
567 wfDebug( "$fname: checking...\n" );
569 $this->mBlockedby
= 0;
573 $this->mBlock
= new Block();
574 $this->mBlock
->fromMaster( !$bFromSlave );
575 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
576 wfDebug( "$fname: Found block.\n" );
577 $this->mBlockedby
= $this->mBlock
->mBy
;
578 $this->mBlockreason
= $this->mBlock
->mReason
;
579 if ( $this->isLoggedIn() ) {
580 $this->spreadBlock();
583 $this->mBlock
= null;
584 wfDebug( "$fname: No block.\n" );
588 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
591 if ( wfIsLocallyBlockedProxy( $ip ) ) {
592 $this->mBlockedby
= wfMsg( 'proxyblocker' );
593 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
597 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
598 if ( $this->inSorbsBlacklist( $ip ) ) {
599 $this->mBlockedby
= wfMsg( 'sorbs' );
600 $this->mBlockreason
= wfMsg( 'sorbsreason' );
606 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
608 wfProfileOut( $fname );
611 function inSorbsBlacklist( $ip ) {
612 global $wgEnableSorbs;
613 return $wgEnableSorbs &&
614 $this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
617 function inDnsBlacklist( $ip, $base ) {
618 $fname = 'User::inDnsBlacklist';
619 wfProfileIn( $fname );
624 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
626 for ( $i=4; $i>=1; $i-- ) {
627 $host .= $m[$i] . '.';
632 $ipList = gethostbynamel( $host );
635 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
638 wfDebug( "Requested $host, not found in $base.\n" );
642 wfProfileOut( $fname );
647 * Primitive rate limits: enforce maximum actions per time period
648 * to put a brake on flooding.
650 * Note: when using a shared cache like memcached, IP-address
651 * last-hit counters will be shared across wikis.
653 * @return bool true if a rate limiter was tripped
656 function pingLimiter( $action='edit' ) {
657 global $wgRateLimits, $wgRateLimitsExcludedGroups;
658 if( !isset( $wgRateLimits[$action] ) ) {
662 # Some groups shouldn't trigger the ping limiter, ever
663 foreach( $this->getGroups() as $group ) {
664 if( array_search( $group, $wgRateLimitsExcludedGroups ) !== false )
668 global $wgMemc, $wgRateLimitLog;
669 $fname = 'User::pingLimiter';
670 wfProfileIn( $fname );
672 $limits = $wgRateLimits[$action];
674 $id = $this->getId();
677 if( isset( $limits['anon'] ) && $id == 0 ) {
678 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
681 if( isset( $limits['user'] ) && $id != 0 ) {
682 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
684 if( $this->isNewbie() ) {
685 if( isset( $limits['newbie'] ) && $id != 0 ) {
686 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
688 if( isset( $limits['ip'] ) ) {
689 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
691 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
692 $subnet = $matches[1];
693 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
698 foreach( $keys as $key => $limit ) {
699 list( $max, $period ) = $limit;
700 $summary = "(limit $max in {$period}s)";
701 $count = $wgMemc->get( $key );
703 if( $count > $max ) {
704 wfDebug( "$fname: tripped! $key at $count $summary\n" );
705 if( $wgRateLimitLog ) {
706 @error_log
( wfTimestamp( TS_MW
) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
710 wfDebug( "$fname: ok. $key at $count $summary\n" );
713 wfDebug( "$fname: adding record for $key $summary\n" );
714 $wgMemc->add( $key, 1, intval( $period ) );
716 $wgMemc->incr( $key );
719 wfProfileOut( $fname );
724 * Check if user is blocked
725 * @return bool True if blocked, false otherwise
727 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
728 wfDebug( "User::isBlocked: enter\n" );
729 $this->getBlockedStatus( $bFromSlave );
730 return $this->mBlockedby
!== 0;
734 * Check if user is blocked from editing a particular article
736 function isBlockedFrom( $title, $bFromSlave = false ) {
737 global $wgBlockAllowsUTEdit;
738 $fname = 'User::isBlockedFrom';
739 wfProfileIn( $fname );
740 wfDebug( "$fname: enter\n" );
742 if ( $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
743 $title->getNamespace() == NS_USER_TALK
)
746 wfDebug( "$fname: self-talk page, ignoring any blocks\n" );
748 wfDebug( "$fname: asking isBlocked()\n" );
749 $blocked = $this->isBlocked( $bFromSlave );
751 wfProfileOut( $fname );
756 * Get name of blocker
757 * @return string name of blocker
759 function blockedBy() {
760 $this->getBlockedStatus();
761 return $this->mBlockedby
;
765 * Get blocking reason
766 * @return string Blocking reason
768 function blockedFor() {
769 $this->getBlockedStatus();
770 return $this->mBlockreason
;
774 * Initialise php session
775 * @deprecated use wfSetupSession()
777 function SetupSession() {
782 * Create a new user object using data from session
785 function loadFromSession() {
786 global $wgMemc, $wgCookiePrefix;
788 if ( isset( $_SESSION['wsUserID'] ) ) {
789 if ( 0 != $_SESSION['wsUserID'] ) {
790 $sId = $_SESSION['wsUserID'];
794 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
795 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
796 $_SESSION['wsUserID'] = $sId;
800 if ( isset( $_SESSION['wsUserName'] ) ) {
801 $sName = $_SESSION['wsUserName'];
802 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
803 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
804 $_SESSION['wsUserName'] = $sName;
809 $passwordCorrect = FALSE;
810 $user = $wgMemc->get( $key = wfMemcKey( 'user', 'id', $sId ) );
811 if( !is_object( $user ) ||
$user->mVersion
< MW_USER_VERSION
) {
812 # Expire old serialized objects; they may be corrupt.
815 if($makenew = !$user) {
816 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
819 $user->loadFromDatabase();
821 wfDebug( "User::loadFromSession() got from cache!\n" );
822 # Set block status to unloaded, that should be loaded every time
823 $user->mBlockedby
= -1;
826 if ( isset( $_SESSION['wsToken'] ) ) {
827 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken
;
828 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
829 $passwordCorrect = $user->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
831 return new User(); # Can't log in from session
834 if ( ( $sName == $user->mName
) && $passwordCorrect ) {
836 if($wgMemc->set( $key, $user ))
837 wfDebug( "User::loadFromSession() successfully saved user\n" );
839 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
843 return new User(); # Can't log in from session
847 * Load a user from the database
849 function loadFromDatabase() {
850 $fname = "User::loadFromDatabase";
852 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
853 # loading in a command line script, don't assume all command line scripts need it like this
854 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
855 if ( $this->mDataLoaded
) {
860 $this->mId
= intval( $this->mId
);
862 /** Anonymous user */
865 $this->mRights
= $this->getGroupPermissions( array( '*' ) );
866 $this->mDataLoaded
= true;
868 } # the following stuff is for non-anonymous users only
870 $dbr =& wfGetDB( DB_SLAVE
);
871 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
872 'user_email_authenticated',
873 'user_real_name','user_options','user_touched', 'user_token', 'user_registration' ),
874 array( 'user_id' => $this->mId
), $fname );
876 if ( $s !== false ) {
877 $this->mName
= $s->user_name
;
878 $this->mEmail
= $s->user_email
;
879 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
880 $this->mRealName
= $s->user_real_name
;
881 $this->mPassword
= $s->user_password
;
882 $this->mNewpassword
= $s->user_newpassword
;
883 $this->decodeOptions( $s->user_options
);
884 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
885 $this->mToken
= $s->user_token
;
886 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $s->user_registration
);
888 $res = $dbr->select( 'user_groups',
890 array( 'ug_user' => $this->mId
),
892 $this->mGroups
= array();
893 while( $row = $dbr->fetchObject( $res ) ) {
894 $this->mGroups
[] = $row->ug_group
;
896 $implicitGroups = array( '*', 'user' );
898 global $wgAutoConfirmAge;
899 $accountAge = time() - wfTimestampOrNull( TS_UNIX
, $this->mRegistration
);
900 if( $accountAge >= $wgAutoConfirmAge ) {
901 $implicitGroups[] = 'autoconfirmed';
904 # Implicit group for users whose email addresses are confirmed
905 global $wgEmailAuthentication;
906 if( $this->isValidEmailAddr( $this->mEmail
) ) {
907 if( $wgEmailAuthentication ) {
908 if( $this->mEmailAuthenticated
)
909 $implicitGroups[] = 'emailconfirmed';
911 $implicitGroups[] = 'emailconfirmed';
915 $effectiveGroups = array_merge( $implicitGroups, $this->mGroups
);
916 $this->mRights
= $this->getGroupPermissions( $effectiveGroups );
919 $this->mDataLoaded
= true;
922 function getID() { return $this->mId
; }
923 function setID( $v ) {
925 $this->mDataLoaded
= false;
929 $this->loadFromDatabase();
930 if ( $this->mName
=== false ) {
931 $this->mName
= wfGetIP();
936 function setName( $str ) {
937 $this->loadFromDatabase();
943 * Return the title dbkey form of the name, for eg user pages.
947 function getTitleKey() {
948 return str_replace( ' ', '_', $this->getName() );
951 function getNewtalk() {
952 $this->loadFromDatabase();
954 # Load the newtalk status if it is unloaded (mNewtalk=-1)
955 if( $this->mNewtalk
=== -1 ) {
956 $this->mNewtalk
= false; # reset talk page status
958 # Check memcached separately for anons, who have no
959 # entire User object stored in there.
962 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
963 $newtalk = $wgMemc->get( $key );
964 if( is_integer( $newtalk ) ) {
965 $this->mNewtalk
= (bool)$newtalk;
967 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
968 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
971 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
975 return (bool)$this->mNewtalk
;
979 * Return the talk page(s) this user has new messages on.
981 function getNewMessageLinks() {
983 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
986 if (!$this->getNewtalk())
988 $up = $this->getUserPage();
989 $utp = $up->getTalkPage();
990 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
995 * Perform a user_newtalk check on current slaves; if the memcached data
996 * is funky we don't want newtalk state to get stuck on save, as that's
999 * @param string $field
1004 function checkNewtalk( $field, $id ) {
1005 $fname = 'User::checkNewtalk';
1006 $dbr =& wfGetDB( DB_SLAVE
);
1007 $ok = $dbr->selectField( 'user_newtalk', $field,
1008 array( $field => $id ), $fname );
1009 return $ok !== false;
1014 * @param string $field
1018 function updateNewtalk( $field, $id ) {
1019 $fname = 'User::updateNewtalk';
1020 if( $this->checkNewtalk( $field, $id ) ) {
1021 wfDebug( "$fname already set ($field, $id), ignoring\n" );
1024 $dbw =& wfGetDB( DB_MASTER
);
1025 $dbw->insert( 'user_newtalk',
1026 array( $field => $id ),
1029 wfDebug( "$fname: set on ($field, $id)\n" );
1034 * Clear the new messages flag for the given user
1035 * @param string $field
1039 function deleteNewtalk( $field, $id ) {
1040 $fname = 'User::deleteNewtalk';
1041 if( !$this->checkNewtalk( $field, $id ) ) {
1042 wfDebug( "$fname: already gone ($field, $id), ignoring\n" );
1045 $dbw =& wfGetDB( DB_MASTER
);
1046 $dbw->delete( 'user_newtalk',
1047 array( $field => $id ),
1049 wfDebug( "$fname: killed on ($field, $id)\n" );
1054 * Update the 'You have new messages!' status.
1057 function setNewtalk( $val ) {
1058 if( wfReadOnly() ) {
1062 $this->loadFromDatabase();
1063 $this->mNewtalk
= $val;
1065 $fname = 'User::setNewtalk';
1067 if( $this->isAnon() ) {
1069 $id = $this->getName();
1072 $id = $this->getId();
1076 $changed = $this->updateNewtalk( $field, $id );
1078 $changed = $this->deleteNewtalk( $field, $id );
1082 if( $this->isAnon() ) {
1083 // Anons have a separate memcached space, since
1084 // user records aren't kept for them.
1086 $key = wfMemcKey( 'newtalk', 'ip', $val );
1087 $wgMemc->set( $key, $val ?
1 : 0 );
1090 // Make sure the user page is watched, so a notification
1091 // will be sent out if enabled.
1092 $this->addWatch( $this->getTalkPage() );
1095 $this->invalidateCache();
1100 * Generate a current or new-future timestamp to be stored in the
1101 * user_touched field when we update things.
1103 private static function newTouchedTimestamp() {
1104 global $wgClockSkewFudge;
1105 return wfTimestamp( TS_MW
, time() +
$wgClockSkewFudge );
1109 * Clear user data from memcached.
1110 * Use after applying fun updates to the database; caller's
1111 * responsibility to update user_touched if appropriate.
1113 * Called implicitly from invalidateCache() and saveSettings().
1115 private function clearUserCache() {
1118 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId
) );
1123 * Immediately touch the user data cache for this account.
1124 * Updates user_touched field, and removes account data from memcached
1125 * for reload on the next hit.
1127 function invalidateCache() {
1129 $this->mTouched
= self
::newTouchedTimestamp();
1131 $dbw =& wfGetDB( DB_MASTER
);
1132 $dbw->update( 'user',
1133 array( 'user_touched' => $dbw->timestamp( $this->mTouched
) ),
1134 array( 'user_id' => $this->mId
),
1137 $this->clearUserCache();
1141 function validateCache( $timestamp ) {
1142 $this->loadFromDatabase();
1143 return ($timestamp >= $this->mTouched
);
1147 * Encrypt a password.
1148 * It can eventuall salt a password @see User::addSalt()
1149 * @param string $p clear Password.
1150 * @return string Encrypted password.
1152 function encryptPassword( $p ) {
1153 return wfEncryptPassword( $this->mId
, $p );
1156 # Set the password and reset the random token
1157 function setPassword( $str ) {
1158 $this->loadFromDatabase();
1160 $this->mPassword
= $this->encryptPassword( $str );
1161 $this->mNewpassword
= '';
1164 # Set the random token (used for persistent authentication)
1165 function setToken( $token = false ) {
1166 global $wgSecretKey, $wgProxyKey;
1168 if ( $wgSecretKey ) {
1169 $key = $wgSecretKey;
1170 } elseif ( $wgProxyKey ) {
1175 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId
);
1177 $this->mToken
= $token;
1182 function setCookiePassword( $str ) {
1183 $this->loadFromDatabase();
1184 $this->mCookiePassword
= md5( $str );
1187 function setNewpassword( $str ) {
1188 $this->loadFromDatabase();
1189 $this->mNewpassword
= $this->encryptPassword( $str );
1192 function getEmail() {
1193 $this->loadFromDatabase();
1194 return $this->mEmail
;
1197 function getEmailAuthenticationTimestamp() {
1198 $this->loadFromDatabase();
1199 return $this->mEmailAuthenticated
;
1202 function setEmail( $str ) {
1203 $this->loadFromDatabase();
1204 $this->mEmail
= $str;
1207 function getRealName() {
1208 $this->loadFromDatabase();
1209 return $this->mRealName
;
1212 function setRealName( $str ) {
1213 $this->loadFromDatabase();
1214 $this->mRealName
= $str;
1218 * @param string $oname The option to check
1221 function getOption( $oname ) {
1222 $this->loadFromDatabase();
1223 if ( is_null( $this->mOptions
) ) {
1224 $this->mOptions
= User
::getDefaultOptions();
1226 if ( array_key_exists( $oname, $this->mOptions
) ) {
1227 return trim( $this->mOptions
[$oname] );
1234 * Get the user's date preference, including some important migration for
1237 function getDatePreference() {
1238 if ( is_null( $this->mDatePreference
) ) {
1240 $value = $this->getOption( 'date' );
1241 $map = $wgLang->getDatePreferenceMigrationMap();
1242 if ( isset( $map[$value] ) ) {
1243 $value = $map[$value];
1245 $this->mDatePreference
= $value;
1247 return $this->mDatePreference
;
1251 * @param string $oname The option to check
1252 * @return bool False if the option is not selected, true if it is
1254 function getBoolOption( $oname ) {
1255 return (bool)$this->getOption( $oname );
1259 * Get an option as an integer value from the source string.
1260 * @param string $oname The option to check
1261 * @param int $default Optional value to return if option is unset/blank.
1264 function getIntOption( $oname, $default=0 ) {
1265 $val = $this->getOption( $oname );
1269 return intval( $val );
1272 function setOption( $oname, $val ) {
1273 $this->loadFromDatabase();
1274 if ( is_null( $this->mOptions
) ) {
1275 $this->mOptions
= User
::getDefaultOptions();
1277 if ( $oname == 'skin' ) {
1278 # Clear cached skin, so the new one displays immediately in Special:Preferences
1279 unset( $this->mSkin
);
1281 // Filter out any newlines that may have passed through input validation.
1282 // Newlines are used to separate items in the options blob.
1283 $val = str_replace( "\r\n", "\n", $val );
1284 $val = str_replace( "\r", "\n", $val );
1285 $val = str_replace( "\n", " ", $val );
1286 $this->mOptions
[$oname] = $val;
1289 function getRights() {
1290 $this->loadFromDatabase();
1291 return $this->mRights
;
1295 * Get the list of explicit group memberships this user has.
1296 * The implicit * and user groups are not included.
1297 * @return array of strings
1299 function getGroups() {
1300 $this->loadFromDatabase();
1301 return $this->mGroups
;
1305 * Get the list of implicit group memberships this user has.
1306 * This includes all explicit groups, plus 'user' if logged in
1307 * and '*' for all accounts.
1308 * @return array of strings
1310 function getEffectiveGroups() {
1311 $base = array( '*' );
1312 if( $this->isLoggedIn() ) {
1315 return array_merge( $base, $this->getGroups() );
1319 * Add the user to the given group.
1320 * This takes immediate effect.
1323 function addGroup( $group ) {
1324 $dbw =& wfGetDB( DB_MASTER
);
1325 $dbw->insert( 'user_groups',
1327 'ug_user' => $this->getID(),
1328 'ug_group' => $group,
1331 array( 'IGNORE' ) );
1333 $this->mGroups
= array_merge( $this->mGroups
, array( $group ) );
1334 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups() );
1336 $this->invalidateCache();
1340 * Remove the user from the given group.
1341 * This takes immediate effect.
1344 function removeGroup( $group ) {
1345 $dbw =& wfGetDB( DB_MASTER
);
1346 $dbw->delete( 'user_groups',
1348 'ug_user' => $this->getID(),
1349 'ug_group' => $group,
1351 'User::removeGroup' );
1353 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1354 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups() );
1356 $this->invalidateCache();
1361 * A more legible check for non-anonymousness.
1362 * Returns true if the user is not an anonymous visitor.
1366 function isLoggedIn() {
1367 return( $this->getID() != 0 );
1371 * A more legible check for anonymousness.
1372 * Returns true if the user is an anonymous visitor.
1377 return !$this->isLoggedIn();
1381 * Whether the user is a bot
1385 return $this->isAllowed( 'bot' );
1389 * Check if user is allowed to access a feature / make an action
1390 * @param string $action Action to be checked
1391 * @return boolean True: action is allowed, False: action should not be allowed
1393 function isAllowed($action='') {
1394 if ( $action === '' )
1395 // In the spirit of DWIM
1398 $this->loadFromDatabase();
1399 return in_array( $action , $this->mRights
);
1403 * Load a skin if it doesn't exist or return it
1404 * @todo FIXME : need to check the old failback system [AV]
1406 function &getSkin() {
1407 global $IP, $wgRequest;
1408 if ( ! isset( $this->mSkin
) ) {
1409 $fname = 'User::getSkin';
1410 wfProfileIn( $fname );
1413 $userSkin = $this->getOption( 'skin' );
1414 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1416 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1417 wfProfileOut( $fname );
1419 return $this->mSkin
;
1423 * @param string $title Article title to look at
1427 * Check watched status of an article
1428 * @return bool True if article is watched
1430 function isWatched( $title ) {
1431 $wl = WatchedItem
::fromUserTitle( $this, $title );
1432 return $wl->isWatched();
1438 function addWatch( $title ) {
1439 $wl = WatchedItem
::fromUserTitle( $this, $title );
1441 $this->invalidateCache();
1445 * Stop watching an article
1447 function removeWatch( $title ) {
1448 $wl = WatchedItem
::fromUserTitle( $this, $title );
1450 $this->invalidateCache();
1454 * Clear the user's notification timestamp for the given title.
1455 * If e-notif e-mails are on, they will receive notification mails on
1456 * the next change of the page if it's watched etc.
1458 function clearNotification( &$title ) {
1459 global $wgUser, $wgUseEnotif;
1462 if ($title->getNamespace() == NS_USER_TALK
&&
1463 $title->getText() == $this->getName() ) {
1464 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1466 $this->setNewtalk( false );
1469 if( !$wgUseEnotif ) {
1473 if( $this->isAnon() ) {
1474 // Nothing else to do...
1478 // Only update the timestamp if the page is being watched.
1479 // The query to find out if it is watched is cached both in memcached and per-invocation,
1480 // and when it does have to be executed, it can be on a slave
1481 // If this is the user's newtalk page, we always update the timestamp
1482 if ($title->getNamespace() == NS_USER_TALK
&&
1483 $title->getText() == $wgUser->getName())
1486 } elseif ( $this->getID() == $wgUser->getID() ) {
1487 $watched = $title->userIsWatching();
1492 // If the page is watched by the user (or may be watched), update the timestamp on any
1493 // any matching rows
1495 $dbw =& wfGetDB( DB_MASTER
);
1496 $success = $dbw->update( 'watchlist',
1498 'wl_notificationtimestamp' => NULL
1499 ), array( /* WHERE */
1500 'wl_title' => $title->getDBkey(),
1501 'wl_namespace' => $title->getNamespace(),
1502 'wl_user' => $this->getID()
1503 ), 'User::clearLastVisited'
1511 * Resets all of the given user's page-change notification timestamps.
1512 * If e-notif e-mails are on, they will receive notification mails on
1513 * the next change of any watched page.
1515 * @param int $currentUser user ID number
1518 function clearAllNotifications( $currentUser ) {
1519 global $wgUseEnotif;
1520 if ( !$wgUseEnotif ) {
1521 $this->setNewtalk( false );
1524 if( $currentUser != 0 ) {
1526 $dbw =& wfGetDB( DB_MASTER
);
1527 $success = $dbw->update( 'watchlist',
1529 'wl_notificationtimestamp' => NULL
1530 ), array( /* WHERE */
1531 'wl_user' => $currentUser
1532 ), 'UserMailer::clearAll'
1535 # we also need to clear here the "you have new message" notification for the own user_talk page
1536 # This is cleared one page view later in Article::viewUpdates();
1542 * @return string Encoding options
1544 function encodeOptions() {
1545 if ( is_null( $this->mOptions
) ) {
1546 $this->mOptions
= User
::getDefaultOptions();
1549 foreach ( $this->mOptions
as $oname => $oval ) {
1550 array_push( $a, $oname.'='.$oval );
1552 $s = implode( "\n", $a );
1559 function decodeOptions( $str ) {
1562 $this->mOptions
= array();
1563 $a = explode( "\n", $str );
1564 foreach ( $a as $s ) {
1565 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1566 $this->mOptions
[$m[1]] = $m[2];
1571 function setCookies() {
1572 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1573 if ( 0 == $this->mId
) return;
1574 $this->loadFromDatabase();
1575 $exp = time() +
$wgCookieExpiration;
1577 $_SESSION['wsUserID'] = $this->mId
;
1578 setcookie( $wgCookiePrefix.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1580 $_SESSION['wsUserName'] = $this->getName();
1581 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1583 $_SESSION['wsToken'] = $this->mToken
;
1584 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1585 setcookie( $wgCookiePrefix.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1587 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1593 * It will clean the session cookie
1596 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1597 $this->loadDefaults();
1598 $this->setLoaded( true );
1600 $_SESSION['wsUserID'] = 0;
1602 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1603 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1605 # Remember when user logged out, to prevent seeing cached pages
1606 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1610 * Save object settings into database
1611 * @fixme Only rarely do all these fields need to be set!
1613 function saveSettings() {
1614 $fname = 'User::saveSettings';
1616 if ( wfReadOnly() ) { return; }
1617 if ( 0 == $this->mId
) { return; }
1619 $this->mTouched
= self
::newTouchedTimestamp();
1621 $dbw =& wfGetDB( DB_MASTER
);
1622 $dbw->update( 'user',
1624 'user_name' => $this->mName
,
1625 'user_password' => $this->mPassword
,
1626 'user_newpassword' => $this->mNewpassword
,
1627 'user_real_name' => $this->mRealName
,
1628 'user_email' => $this->mEmail
,
1629 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1630 'user_options' => $this->encodeOptions(),
1631 'user_touched' => $dbw->timestamp($this->mTouched
),
1632 'user_token' => $this->mToken
1633 ), array( /* WHERE */
1634 'user_id' => $this->mId
1637 $this->clearUserCache();
1642 * Checks if a user with the given name exists, returns the ID
1644 function idForName() {
1645 $fname = 'User::idForName';
1648 $s = trim( $this->getName() );
1649 if ( 0 == strcmp( '', $s ) ) return 0;
1651 $dbr =& wfGetDB( DB_SLAVE
);
1652 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1653 if ( $id === false ) {
1660 * Add user object to the database
1662 function addToDatabase() {
1663 $fname = 'User::addToDatabase';
1664 $dbw =& wfGetDB( DB_MASTER
);
1665 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1666 $dbw->insert( 'user',
1668 'user_id' => $seqVal,
1669 'user_name' => $this->mName
,
1670 'user_password' => $this->mPassword
,
1671 'user_newpassword' => $this->mNewpassword
,
1672 'user_email' => $this->mEmail
,
1673 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1674 'user_real_name' => $this->mRealName
,
1675 'user_options' => $this->encodeOptions(),
1676 'user_token' => $this->mToken
,
1677 'user_registration' => $dbw->timestamp( $this->mRegistration
),
1680 $this->mId
= $dbw->insertId();
1683 function spreadBlock() {
1684 # If the (non-anonymous) user is blocked, this function will block any IP address
1685 # that they successfully log on from.
1686 $fname = 'User::spreadBlock';
1688 wfDebug( "User:spreadBlock()\n" );
1689 if ( $this->mId
== 0 ) {
1693 $userblock = Block
::newFromDB( '', $this->mId
);
1694 if ( !$userblock ) {
1698 # Check if this IP address is already blocked
1699 $ipblock = Block
::newFromDB( wfGetIP() );
1701 # If the user is already blocked. Then check if the autoblock would
1702 # excede the user block. If it would excede, then do nothing, else
1703 # prolong block time
1704 if ($userblock->mExpiry
&&
1705 ($userblock->mExpiry
< Block
::getAutoblockExpiry($ipblock->mTimestamp
))) {
1708 # Just update the timestamp
1709 $ipblock->updateTimestamp();
1712 $ipblock = new Block
;
1715 # Make a new block object with the desired properties
1716 wfDebug( "Autoblocking {$this->mName}@" . wfGetIP() . "\n" );
1717 $ipblock->mAddress
= wfGetIP();
1718 $ipblock->mUser
= 0;
1719 $ipblock->mBy
= $userblock->mBy
;
1720 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
1721 $ipblock->mTimestamp
= wfTimestampNow();
1722 $ipblock->mAuto
= 1;
1723 # If the user is already blocked with an expiry date, we don't
1724 # want to pile on top of that!
1725 if($userblock->mExpiry
) {
1726 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
1728 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
1737 * Generate a string which will be different for any combination of
1738 * user options which would produce different parser output.
1739 * This will be used as part of the hash key for the parser cache,
1740 * so users will the same options can share the same cached data
1743 * Extensions which require it should install 'PageRenderingHash' hook,
1744 * which will give them a chance to modify this key based on their own
1749 function getPageRenderingHash() {
1750 global $wgContLang, $wgUseDynamicDates;
1752 return $this->mHash
;
1755 // stubthreshold is only included below for completeness,
1756 // it will always be 0 when this function is called by parsercache.
1758 $confstr = $this->getOption( 'math' );
1759 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1760 if ( $wgUseDynamicDates ) {
1761 $confstr .= '!' . $this->getDatePreference();
1763 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
1764 $confstr .= '!' . $this->getOption( 'language' );
1765 $confstr .= '!' . $this->getOption( 'thumbsize' );
1766 // add in language specific options, if any
1767 $extra = $wgContLang->getExtraHashOptions();
1770 // Give a chance for extensions to modify the hash, if they have
1771 // extra options or other effects on the parser cache.
1772 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
1774 $this->mHash
= $confstr;
1778 function isBlockedFromCreateAccount() {
1779 $this->getBlockedStatus();
1780 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
1783 function isAllowedToCreateAccount() {
1784 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
1788 * Set mDataLoaded, return previous value
1789 * Use this to prevent DB access in command-line scripts or similar situations
1791 function setLoaded( $loaded ) {
1792 return wfSetVar( $this->mDataLoaded
, $loaded );
1796 * Get this user's personal page title.
1801 function getUserPage() {
1802 return Title
::makeTitle( NS_USER
, $this->getName() );
1806 * Get this user's talk page title.
1811 function getTalkPage() {
1812 $title = $this->getUserPage();
1813 return $title->getTalkPage();
1819 function getMaxID() {
1820 static $res; // cache
1822 if ( isset( $res ) )
1825 $dbr =& wfGetDB( DB_SLAVE
);
1826 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
1831 * Determine whether the user is a newbie. Newbies are either
1832 * anonymous IPs, or the most recently created accounts.
1833 * @return bool True if it is a newbie.
1835 function isNewbie() {
1836 return !$this->isAllowed( 'autoconfirmed' );
1840 * Check to see if the given clear-text password is one of the accepted passwords
1841 * @param string $password User password.
1842 * @return bool True if the given password is correct otherwise False.
1844 function checkPassword( $password ) {
1845 global $wgAuth, $wgMinimalPasswordLength;
1846 $this->loadFromDatabase();
1848 // Even though we stop people from creating passwords that
1849 // are shorter than this, doesn't mean people wont be able
1850 // to. Certain authentication plugins do NOT want to save
1851 // domain passwords in a mysql database, so we should
1852 // check this (incase $wgAuth->strict() is false).
1853 if( strlen( $password ) < $wgMinimalPasswordLength ) {
1857 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1859 } elseif( $wgAuth->strict() ) {
1860 /* Auth plugin doesn't allow local authentication */
1863 $ep = $this->encryptPassword( $password );
1864 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
1866 } elseif ( ($this->mNewpassword
!= '') && (0 == strcmp( $ep, $this->mNewpassword
)) ) {
1868 } elseif ( function_exists( 'iconv' ) ) {
1869 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1870 # Check for this with iconv
1871 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
1872 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
1880 * Initialize (if necessary) and return a session token value
1881 * which can be used in edit forms to show that the user's
1882 * login credentials aren't being hijacked with a foreign form
1885 * @param mixed $salt - Optional function-specific data for hash.
1886 * Use a string or an array of strings.
1890 function editToken( $salt = '' ) {
1891 if( !isset( $_SESSION['wsEditToken'] ) ) {
1892 $token = $this->generateToken();
1893 $_SESSION['wsEditToken'] = $token;
1895 $token = $_SESSION['wsEditToken'];
1897 if( is_array( $salt ) ) {
1898 $salt = implode( '|', $salt );
1900 return md5( $token . $salt );
1904 * Generate a hex-y looking random token for various uses.
1905 * Could be made more cryptographically sure if someone cares.
1908 function generateToken( $salt = '' ) {
1909 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1910 return md5( $token . $salt );
1914 * Check given value against the token value stored in the session.
1915 * A match should confirm that the form was submitted from the
1916 * user's own login session, not a form submission from a third-party
1919 * @param string $val - the input value to compare
1920 * @param string $salt - Optional function-specific data for hash
1924 function matchEditToken( $val, $salt = '' ) {
1926 $sessionToken = $this->editToken( $salt );
1927 if ( $val != $sessionToken ) {
1928 wfDebug( "User::matchEditToken: broken session data\n" );
1930 return $val == $sessionToken;
1934 * Generate a new e-mail confirmation token and send a confirmation
1935 * mail to the user's given address.
1937 * @return mixed True on success, a WikiError object on failure.
1939 function sendConfirmationMail() {
1941 $url = $this->confirmationTokenUrl( $expiration );
1942 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1943 wfMsg( 'confirmemail_body',
1947 $wgContLang->timeanddate( $expiration, false ) ) );
1951 * Send an e-mail to this user's account. Does not check for
1952 * confirmed status or validity.
1954 * @param string $subject
1955 * @param string $body
1956 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1957 * @return mixed True on success, a WikiError object on failure.
1959 function sendMail( $subject, $body, $from = null ) {
1960 if( is_null( $from ) ) {
1961 global $wgPasswordSender;
1962 $from = $wgPasswordSender;
1965 require_once( 'UserMailer.php' );
1966 $to = new MailAddress( $this );
1967 $sender = new MailAddress( $from );
1968 $error = userMailer( $to, $sender, $subject, $body );
1970 if( $error == '' ) {
1973 return new WikiError( $error );
1978 * Generate, store, and return a new e-mail confirmation code.
1979 * A hash (unsalted since it's used as a key) is stored.
1980 * @param &$expiration mixed output: accepts the expiration time
1984 function confirmationToken( &$expiration ) {
1985 $fname = 'User::confirmationToken';
1988 $expires = $now +
7 * 24 * 60 * 60;
1989 $expiration = wfTimestamp( TS_MW
, $expires );
1991 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
1992 $hash = md5( $token );
1994 $dbw =& wfGetDB( DB_MASTER
);
1995 $dbw->update( 'user',
1996 array( 'user_email_token' => $hash,
1997 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1998 array( 'user_id' => $this->mId
),
2005 * Generate and store a new e-mail confirmation token, and return
2006 * the URL the user can use to confirm.
2007 * @param &$expiration mixed output: accepts the expiration time
2011 function confirmationTokenUrl( &$expiration ) {
2012 $token = $this->confirmationToken( $expiration );
2013 $title = Title
::makeTitle( NS_SPECIAL
, 'Confirmemail/' . $token );
2014 return $title->getFullUrl();
2018 * Mark the e-mail address confirmed and save.
2020 function confirmEmail() {
2021 $this->loadFromDatabase();
2022 $this->mEmailAuthenticated
= wfTimestampNow();
2023 $this->saveSettings();
2028 * Is this user allowed to send e-mails within limits of current
2029 * site configuration?
2032 function canSendEmail() {
2033 return $this->isEmailConfirmed();
2037 * Is this user allowed to receive e-mails within limits of current
2038 * site configuration?
2041 function canReceiveEmail() {
2042 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2046 * Is this user's e-mail address valid-looking and confirmed within
2047 * limits of the current site configuration?
2049 * If $wgEmailAuthentication is on, this may require the user to have
2050 * confirmed their address by returning a code or using a password
2051 * sent to the address from the wiki.
2055 function isEmailConfirmed() {
2056 global $wgEmailAuthentication;
2057 $this->loadFromDatabase();
2059 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2060 if( $this->isAnon() )
2062 if( !$this->isValidEmailAddr( $this->mEmail
) )
2064 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2073 * @param array $groups list of groups
2074 * @return array list of permission key names for given groups combined
2077 static function getGroupPermissions( $groups ) {
2078 global $wgGroupPermissions;
2080 foreach( $groups as $group ) {
2081 if( isset( $wgGroupPermissions[$group] ) ) {
2082 $rights = array_merge( $rights,
2083 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2090 * @param string $group key name
2091 * @return string localized descriptive name for group, if provided
2094 static function getGroupName( $group ) {
2095 $key = "group-$group";
2096 $name = wfMsg( $key );
2097 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2105 * @param string $group key name
2106 * @return string localized descriptive name for member of a group, if provided
2109 static function getGroupMember( $group ) {
2110 $key = "group-$group-member";
2111 $name = wfMsg( $key );
2112 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2120 * Return the set of defined explicit groups.
2121 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2122 * groups are not included, as they are defined
2123 * automatically, not in the database.
2127 static function getAllGroups() {
2128 global $wgGroupPermissions;
2130 array_keys( $wgGroupPermissions ),
2131 array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
2135 * Get the title of a page describing a particular group
2137 * @param $group Name of the group
2140 static function getGroupPage( $group ) {
2141 $page = wfMsgForContent( 'grouppage-' . $group );
2142 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2143 $title = Title
::newFromText( $page );
2144 if( is_object( $title ) )
2151 * Create a link to the group in HTML, if available
2153 * @param $group Name of the group
2154 * @param $text The text of the link
2157 static function makeGroupLinkHTML( $group, $text = '' ) {
2159 $text = self
::getGroupName( $group );
2161 $title = self
::getGroupPage( $group );
2164 $sk = $wgUser->getSkin();
2165 return $sk->makeLinkObj( $title, $text );
2172 * Create a link to the group in Wikitext, if available
2174 * @param $group Name of the group
2175 * @param $text The text of the link (by default, the name of the group)
2178 static function makeGroupLinkWiki( $group, $text = '' ) {
2180 $text = self
::getGroupName( $group );
2182 $title = self
::getGroupPage( $group );
2184 $page = $title->getPrefixedText();
2185 return "[[$page|$text]]";