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 * Is the input a valid password?
342 * @param string $password
346 function isValidPassword( $password ) {
347 global $wgMinimalPasswordLength;
348 return strlen( $password ) >= $wgMinimalPasswordLength;
352 * Does the string match roughly an email address ?
354 * There used to be a regular expression here, it got removed because it
355 * rejected valid addresses. Actually just check if there is '@' somewhere
356 * in the given address.
358 * @todo Check for RFC 2822 compilance
361 * @param string $addr email address
365 function isValidEmailAddr ( $addr ) {
366 return ( trim( $addr ) != '' ) &&
367 (false !== strpos( $addr, '@' ) );
371 * Count the number of edits of a user
373 * @param int $uid The user ID to check
376 function edits( $uid ) {
377 $fname = 'User::edits';
379 $dbr =& wfGetDB( DB_SLAVE
);
380 return $dbr->selectField(
381 'revision', 'count(*)',
382 array( 'rev_user' => $uid ),
388 * probably return a random password
389 * @return string probably a random password
391 * @todo Check what is doing really [AV]
393 function randomPassword() {
394 global $wgMinimalPasswordLength;
395 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
396 $l = strlen( $pwchars ) - 1;
398 $pwlength = max( 7, $wgMinimalPasswordLength );
399 $digit = mt_rand(0, $pwlength - 1);
401 for ( $i = 0; $i < $pwlength; $i++
) {
402 $np .= $i == $digit ?
chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
408 * Set properties to default
409 * Used at construction. It will load per language default settings only
410 * if we have an available language object.
412 function loadDefaults() {
415 $fname = 'User::loadDefaults' . $n;
416 wfProfileIn( $fname );
418 global $wgCookiePrefix;
419 global $wgNamespacesToBeSearchedDefault;
422 $this->mNewtalk
= -1;
423 $this->mName
= false;
424 $this->mRealName
= $this->mEmail
= '';
425 $this->mEmailAuthenticated
= null;
426 $this->mPassword
= $this->mNewpassword
= '';
427 $this->mRights
= array();
428 $this->mGroups
= array();
429 $this->mOptions
= null;
430 $this->mDatePreference
= null;
432 unset( $this->mSkin
);
433 $this->mDataLoaded
= false;
434 $this->mBlockedby
= -1; # Unset
435 $this->setToken(); # Random
436 $this->mHash
= false;
438 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
439 $this->mTouched
= wfTimestamp( TS_MW
, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
442 $this->mTouched
= '0'; # Allow any pages to be cached
445 $this->mRegistration
= wfTimestamp( TS_MW
);
447 wfProfileOut( $fname );
451 * Combine the language default options with any site-specific options
452 * and add the default language variants.
458 function getDefaultOptions() {
459 global $wgNamespacesToBeSearchedDefault;
461 * Site defaults will override the global/language defaults
464 $defOpt = self
::$mDefaultOptions +
$wgContLang->getDefaultUserOptionOverrides();
467 * default language setting
469 $variant = $wgContLang->getPreferredVariant( false );
470 $defOpt['variant'] = $variant;
471 $defOpt['language'] = $variant;
473 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
474 $defOpt['searchNs'.$nsnum] = $val;
480 * Get a given default option value.
487 function getDefaultOption( $opt ) {
488 $defOpts = User
::getDefaultOptions();
489 if( isset( $defOpts[$opt] ) ) {
490 return $defOpts[$opt];
497 * Get a list of user toggle names
500 static function getToggles() {
502 $extraToggles = array();
503 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
504 return array_merge( self
::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
509 * Get blocking information
511 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
512 * non-critical checks are done against slaves. Check when actually saving should be done against
515 function getBlockedStatus( $bFromSlave = true ) {
516 global $wgEnableSorbs, $wgProxyWhitelist;
518 if ( -1 != $this->mBlockedby
) {
519 wfDebug( "User::getBlockedStatus: already loaded.\n" );
523 $fname = 'User::getBlockedStatus';
524 wfProfileIn( $fname );
525 wfDebug( "$fname: checking...\n" );
527 $this->mBlockedby
= 0;
531 $this->mBlock
= new Block();
532 $this->mBlock
->fromMaster( !$bFromSlave );
533 if ( $this->mBlock
->load( $ip , $this->mId
) ) {
534 wfDebug( "$fname: Found block.\n" );
535 $this->mBlockedby
= $this->mBlock
->mBy
;
536 $this->mBlockreason
= $this->mBlock
->mReason
;
537 if ( $this->isLoggedIn() ) {
538 $this->spreadBlock();
541 $this->mBlock
= null;
542 wfDebug( "$fname: No block.\n" );
546 # FIXME ? proxyunbannable is to deprecate the old isSysop()
547 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
550 if ( wfIsLocallyBlockedProxy( $ip ) ) {
551 $this->mBlockedby
= wfMsg( 'proxyblocker' );
552 $this->mBlockreason
= wfMsg( 'proxyblockreason' );
556 if ( !$this->mBlockedby
&& $wgEnableSorbs && !$this->getID() ) {
557 if ( $this->inSorbsBlacklist( $ip ) ) {
558 $this->mBlockedby
= wfMsg( 'sorbs' );
559 $this->mBlockreason
= wfMsg( 'sorbsreason' );
565 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
567 wfProfileOut( $fname );
570 function inSorbsBlacklist( $ip ) {
571 global $wgEnableSorbs;
572 return $wgEnableSorbs &&
573 $this->inDnsBlacklist( $ip, 'http.dnsbl.sorbs.net.' );
576 function inDnsBlacklist( $ip, $base ) {
577 $fname = 'User::inDnsBlacklist';
578 wfProfileIn( $fname );
583 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
585 for ( $i=4; $i>=1; $i-- ) {
586 $host .= $m[$i] . '.';
591 $ipList = gethostbynamel( $host );
594 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
597 wfDebug( "Requested $host, not found in $base.\n" );
601 wfProfileOut( $fname );
606 * Primitive rate limits: enforce maximum actions per time period
607 * to put a brake on flooding.
609 * Note: when using a shared cache like memcached, IP-address
610 * last-hit counters will be shared across wikis.
612 * @return bool true if a rate limiter was tripped
615 function pingLimiter( $action='edit' ) {
616 global $wgRateLimits, $wgRateLimitsExcludedGroups;
617 if( !isset( $wgRateLimits[$action] ) ) {
621 # Some groups shouldn't trigger the ping limiter, ever
622 foreach( $this->getGroups() as $group ) {
623 if( array_search( $group, $wgRateLimitsExcludedGroups ) !== false )
627 global $wgMemc, $wgDBname, $wgRateLimitLog;
628 $fname = 'User::pingLimiter';
629 wfProfileIn( $fname );
631 $limits = $wgRateLimits[$action];
633 $id = $this->getId();
636 if( isset( $limits['anon'] ) && $id == 0 ) {
637 $keys["$wgDBname:limiter:$action:anon"] = $limits['anon'];
640 if( isset( $limits['user'] ) && $id != 0 ) {
641 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['user'];
643 if( $this->isNewbie() ) {
644 if( isset( $limits['newbie'] ) && $id != 0 ) {
645 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['newbie'];
647 if( isset( $limits['ip'] ) ) {
648 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
650 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
651 $subnet = $matches[1];
652 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
657 foreach( $keys as $key => $limit ) {
658 list( $max, $period ) = $limit;
659 $summary = "(limit $max in {$period}s)";
660 $count = $wgMemc->get( $key );
662 if( $count > $max ) {
663 wfDebug( "$fname: tripped! $key at $count $summary\n" );
664 if( $wgRateLimitLog ) {
665 @error_log
( wfTimestamp( TS_MW
) . ' ' . $wgDBname . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
669 wfDebug( "$fname: ok. $key at $count $summary\n" );
672 wfDebug( "$fname: adding record for $key $summary\n" );
673 $wgMemc->add( $key, 1, intval( $period ) );
675 $wgMemc->incr( $key );
678 wfProfileOut( $fname );
683 * Check if user is blocked
684 * @return bool True if blocked, false otherwise
686 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
687 wfDebug( "User::isBlocked: enter\n" );
688 $this->getBlockedStatus( $bFromSlave );
689 return $this->mBlockedby
!== 0;
693 * Check if user is blocked from editing a particular article
695 function isBlockedFrom( $title, $bFromSlave = false ) {
696 global $wgBlockAllowsUTEdit;
697 $fname = 'User::isBlockedFrom';
698 wfProfileIn( $fname );
699 wfDebug( "$fname: enter\n" );
701 if ( $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
702 $title->getNamespace() == NS_USER_TALK
)
705 wfDebug( "$fname: self-talk page, ignoring any blocks\n" );
707 wfDebug( "$fname: asking isBlocked()\n" );
708 $blocked = $this->isBlocked( $bFromSlave );
710 wfProfileOut( $fname );
715 * Get name of blocker
716 * @return string name of blocker
718 function blockedBy() {
719 $this->getBlockedStatus();
720 return $this->mBlockedby
;
724 * Get blocking reason
725 * @return string Blocking reason
727 function blockedFor() {
728 $this->getBlockedStatus();
729 return $this->mBlockreason
;
733 * Initialise php session
734 * @deprecated use wfSetupSession()
736 function SetupSession() {
741 * Create a new user object using data from session
744 function loadFromSession() {
745 global $wgMemc, $wgDBname, $wgCookiePrefix;
747 if ( isset( $_SESSION['wsUserID'] ) ) {
748 if ( 0 != $_SESSION['wsUserID'] ) {
749 $sId = $_SESSION['wsUserID'];
753 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
754 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
755 $_SESSION['wsUserID'] = $sId;
759 if ( isset( $_SESSION['wsUserName'] ) ) {
760 $sName = $_SESSION['wsUserName'];
761 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
762 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
763 $_SESSION['wsUserName'] = $sName;
768 $passwordCorrect = FALSE;
769 $user = $wgMemc->get( $key = "$wgDBname:user:id:$sId" );
770 if( !is_object( $user ) ||
$user->mVersion
< MW_USER_VERSION
) {
771 # Expire old serialized objects; they may be corrupt.
774 if($makenew = !$user) {
775 wfDebug( "User::loadFromSession() unable to load from memcached\n" );
778 $user->loadFromDatabase();
780 wfDebug( "User::loadFromSession() got from cache!\n" );
781 # Set block status to unloaded, that should be loaded every time
782 $user->mBlockedby
= -1;
785 if ( isset( $_SESSION['wsToken'] ) ) {
786 $passwordCorrect = $_SESSION['wsToken'] == $user->mToken
;
787 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
788 $passwordCorrect = $user->mToken
== $_COOKIE["{$wgCookiePrefix}Token"];
790 return new User(); # Can't log in from session
793 if ( ( $sName == $user->mName
) && $passwordCorrect ) {
795 if($wgMemc->set( $key, $user ))
796 wfDebug( "User::loadFromSession() successfully saved user\n" );
798 wfDebug( "User::loadFromSession() unable to save to memcached\n" );
802 return new User(); # Can't log in from session
806 * Load a user from the database
808 function loadFromDatabase() {
809 $fname = "User::loadFromDatabase";
811 # Counter-intuitive, breaks various things, use User::setLoaded() if you want to suppress
812 # loading in a command line script, don't assume all command line scripts need it like this
813 #if ( $this->mDataLoaded || $wgCommandLineMode ) {
814 if ( $this->mDataLoaded
) {
819 $this->mId
= intval( $this->mId
);
821 /** Anonymous user */
824 $this->mRights
= $this->getGroupPermissions( array( '*' ) );
825 $this->mDataLoaded
= true;
827 } # the following stuff is for non-anonymous users only
829 $dbr =& wfGetDB( DB_SLAVE
);
830 $s = $dbr->selectRow( 'user', array( 'user_name','user_password','user_newpassword','user_email',
831 'user_email_authenticated',
832 'user_real_name','user_options','user_touched', 'user_token', 'user_registration' ),
833 array( 'user_id' => $this->mId
), $fname );
835 if ( $s !== false ) {
836 $this->mName
= $s->user_name
;
837 $this->mEmail
= $s->user_email
;
838 $this->mEmailAuthenticated
= wfTimestampOrNull( TS_MW
, $s->user_email_authenticated
);
839 $this->mRealName
= $s->user_real_name
;
840 $this->mPassword
= $s->user_password
;
841 $this->mNewpassword
= $s->user_newpassword
;
842 $this->decodeOptions( $s->user_options
);
843 $this->mTouched
= wfTimestamp(TS_MW
,$s->user_touched
);
844 $this->mToken
= $s->user_token
;
845 $this->mRegistration
= wfTimestampOrNull( TS_MW
, $s->user_registration
);
847 $res = $dbr->select( 'user_groups',
849 array( 'ug_user' => $this->mId
),
851 $this->mGroups
= array();
852 while( $row = $dbr->fetchObject( $res ) ) {
853 $this->mGroups
[] = $row->ug_group
;
855 $implicitGroups = array( '*', 'user' );
857 global $wgAutoConfirmAge;
858 $accountAge = time() - wfTimestampOrNull( TS_UNIX
, $this->mRegistration
);
859 if( $accountAge >= $wgAutoConfirmAge ) {
860 $implicitGroups[] = 'autoconfirmed';
863 # Implicit group for users whose email addresses are confirmed
864 global $wgEmailAuthentication;
865 if( $this->isValidEmailAddr( $this->mEmail
) ) {
866 if( $wgEmailAuthentication ) {
867 if( $this->mEmailAuthenticated
)
868 $implicitGroups[] = 'emailconfirmed';
870 $implicitGroups[] = 'emailconfirmed';
874 $effectiveGroups = array_merge( $implicitGroups, $this->mGroups
);
875 $this->mRights
= $this->getGroupPermissions( $effectiveGroups );
878 $this->mDataLoaded
= true;
881 function getID() { return $this->mId
; }
882 function setID( $v ) {
884 $this->mDataLoaded
= false;
888 $this->loadFromDatabase();
889 if ( $this->mName
=== false ) {
890 $this->mName
= wfGetIP();
895 function setName( $str ) {
896 $this->loadFromDatabase();
902 * Return the title dbkey form of the name, for eg user pages.
906 function getTitleKey() {
907 return str_replace( ' ', '_', $this->getName() );
910 function getNewtalk() {
911 $this->loadFromDatabase();
913 # Load the newtalk status if it is unloaded (mNewtalk=-1)
914 if( $this->mNewtalk
=== -1 ) {
915 $this->mNewtalk
= false; # reset talk page status
917 # Check memcached separately for anons, who have no
918 # entire User object stored in there.
920 global $wgDBname, $wgMemc;
921 $key = "$wgDBname:newtalk:ip:" . $this->getName();
922 $newtalk = $wgMemc->get( $key );
923 if( is_integer( $newtalk ) ) {
924 $this->mNewtalk
= (bool)$newtalk;
926 $this->mNewtalk
= $this->checkNewtalk( 'user_ip', $this->getName() );
927 $wgMemc->set( $key, $this->mNewtalk
, time() ); // + 1800 );
930 $this->mNewtalk
= $this->checkNewtalk( 'user_id', $this->mId
);
934 return (bool)$this->mNewtalk
;
938 * Return the talk page(s) this user has new messages on.
940 function getNewMessageLinks() {
943 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
946 if (!$this->getNewtalk())
948 $up = $this->getUserPage();
949 $utp = $up->getTalkPage();
950 return array(array("wiki" => $wgDBname, "link" => $utp->getLocalURL()));
955 * Perform a user_newtalk check on current slaves; if the memcached data
956 * is funky we don't want newtalk state to get stuck on save, as that's
959 * @param string $field
964 function checkNewtalk( $field, $id ) {
965 $fname = 'User::checkNewtalk';
966 $dbr =& wfGetDB( DB_SLAVE
);
967 $ok = $dbr->selectField( 'user_newtalk', $field,
968 array( $field => $id ), $fname );
969 return $ok !== false;
974 * @param string $field
978 function updateNewtalk( $field, $id ) {
979 $fname = 'User::updateNewtalk';
980 if( $this->checkNewtalk( $field, $id ) ) {
981 wfDebug( "$fname already set ($field, $id), ignoring\n" );
984 $dbw =& wfGetDB( DB_MASTER
);
985 $dbw->insert( 'user_newtalk',
986 array( $field => $id ),
989 wfDebug( "$fname: set on ($field, $id)\n" );
994 * Clear the new messages flag for the given user
995 * @param string $field
999 function deleteNewtalk( $field, $id ) {
1000 $fname = 'User::deleteNewtalk';
1001 if( !$this->checkNewtalk( $field, $id ) ) {
1002 wfDebug( "$fname: already gone ($field, $id), ignoring\n" );
1005 $dbw =& wfGetDB( DB_MASTER
);
1006 $dbw->delete( 'user_newtalk',
1007 array( $field => $id ),
1009 wfDebug( "$fname: killed on ($field, $id)\n" );
1014 * Update the 'You have new messages!' status.
1017 function setNewtalk( $val ) {
1018 if( wfReadOnly() ) {
1022 $this->loadFromDatabase();
1023 $this->mNewtalk
= $val;
1025 $fname = 'User::setNewtalk';
1027 if( $this->isAnon() ) {
1029 $id = $this->getName();
1032 $id = $this->getId();
1036 $changed = $this->updateNewtalk( $field, $id );
1038 $changed = $this->deleteNewtalk( $field, $id );
1042 if( $this->isAnon() ) {
1043 // Anons have a separate memcached space, since
1044 // user records aren't kept for them.
1045 global $wgDBname, $wgMemc;
1046 $key = "$wgDBname:newtalk:ip:$val";
1047 $wgMemc->set( $key, $val ?
1 : 0 );
1050 // Make sure the user page is watched, so a notification
1051 // will be sent out if enabled.
1052 $this->addWatch( $this->getTalkPage() );
1055 $this->invalidateCache();
1056 $this->saveSettings();
1060 function invalidateCache() {
1061 global $wgClockSkewFudge;
1062 $this->loadFromDatabase();
1063 $this->mTouched
= wfTimestamp(TS_MW
, time() +
$wgClockSkewFudge );
1064 # Don't forget to save the options after this or
1065 # it won't take effect!
1068 function validateCache( $timestamp ) {
1069 $this->loadFromDatabase();
1070 return ($timestamp >= $this->mTouched
);
1074 * Encrypt a password.
1075 * It can eventuall salt a password @see User::addSalt()
1076 * @param string $p clear Password.
1077 * @return string Encrypted password.
1079 function encryptPassword( $p ) {
1080 return wfEncryptPassword( $this->mId
, $p );
1083 # Set the password and reset the random token
1084 function setPassword( $str ) {
1085 $this->loadFromDatabase();
1087 $this->mPassword
= $this->encryptPassword( $str );
1088 $this->mNewpassword
= '';
1091 # Set the random token (used for persistent authentication)
1092 function setToken( $token = false ) {
1093 global $wgSecretKey, $wgProxyKey, $wgDBname;
1095 if ( $wgSecretKey ) {
1096 $key = $wgSecretKey;
1097 } elseif ( $wgProxyKey ) {
1102 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId
);
1104 $this->mToken
= $token;
1109 function setCookiePassword( $str ) {
1110 $this->loadFromDatabase();
1111 $this->mCookiePassword
= md5( $str );
1114 function setNewpassword( $str ) {
1115 $this->loadFromDatabase();
1116 $this->mNewpassword
= $this->encryptPassword( $str );
1119 function getEmail() {
1120 $this->loadFromDatabase();
1121 return $this->mEmail
;
1124 function getEmailAuthenticationTimestamp() {
1125 $this->loadFromDatabase();
1126 return $this->mEmailAuthenticated
;
1129 function setEmail( $str ) {
1130 $this->loadFromDatabase();
1131 $this->mEmail
= $str;
1134 function getRealName() {
1135 $this->loadFromDatabase();
1136 return $this->mRealName
;
1139 function setRealName( $str ) {
1140 $this->loadFromDatabase();
1141 $this->mRealName
= $str;
1145 * @param string $oname The option to check
1148 function getOption( $oname ) {
1149 $this->loadFromDatabase();
1150 if ( is_null( $this->mOptions
) ) {
1151 $this->mOptions
= User
::getDefaultOptions();
1153 if ( array_key_exists( $oname, $this->mOptions
) ) {
1154 return trim( $this->mOptions
[$oname] );
1161 * Get the user's date preference, including some important migration for
1164 function getDatePreference() {
1165 if ( is_null( $this->mDatePreference
) ) {
1167 $value = $this->getOption( 'date' );
1168 $map = $wgLang->getDatePreferenceMigrationMap();
1169 if ( isset( $map[$value] ) ) {
1170 $value = $map[$value];
1172 $this->mDatePreference
= $value;
1174 return $this->mDatePreference
;
1178 * @param string $oname The option to check
1179 * @return bool False if the option is not selected, true if it is
1181 function getBoolOption( $oname ) {
1182 return (bool)$this->getOption( $oname );
1186 * Get an option as an integer value from the source string.
1187 * @param string $oname The option to check
1188 * @param int $default Optional value to return if option is unset/blank.
1191 function getIntOption( $oname, $default=0 ) {
1192 $val = $this->getOption( $oname );
1196 return intval( $val );
1199 function setOption( $oname, $val ) {
1200 $this->loadFromDatabase();
1201 if ( is_null( $this->mOptions
) ) {
1202 $this->mOptions
= User
::getDefaultOptions();
1204 if ( $oname == 'skin' ) {
1205 # Clear cached skin, so the new one displays immediately in Special:Preferences
1206 unset( $this->mSkin
);
1208 // Filter out any newlines that may have passed through input validation.
1209 // Newlines are used to separate items in the options blob.
1210 $val = str_replace( "\r\n", "\n", $val );
1211 $val = str_replace( "\r", "\n", $val );
1212 $val = str_replace( "\n", " ", $val );
1213 $this->mOptions
[$oname] = $val;
1214 $this->invalidateCache();
1217 function getRights() {
1218 $this->loadFromDatabase();
1219 return $this->mRights
;
1223 * Get the list of explicit group memberships this user has.
1224 * The implicit * and user groups are not included.
1225 * @return array of strings
1227 function getGroups() {
1228 $this->loadFromDatabase();
1229 return $this->mGroups
;
1233 * Get the list of implicit group memberships this user has.
1234 * This includes all explicit groups, plus 'user' if logged in
1235 * and '*' for all accounts.
1236 * @return array of strings
1238 function getEffectiveGroups() {
1239 $base = array( '*' );
1240 if( $this->isLoggedIn() ) {
1243 return array_merge( $base, $this->getGroups() );
1247 * Add the user to the given group.
1248 * This takes immediate effect.
1251 function addGroup( $group ) {
1252 $dbw =& wfGetDB( DB_MASTER
);
1253 $dbw->insert( 'user_groups',
1255 'ug_user' => $this->getID(),
1256 'ug_group' => $group,
1259 array( 'IGNORE' ) );
1261 $this->mGroups
= array_merge( $this->mGroups
, array( $group ) );
1262 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups() );
1264 $this->invalidateCache();
1265 $this->saveSettings();
1269 * Remove the user from the given group.
1270 * This takes immediate effect.
1273 function removeGroup( $group ) {
1274 $dbw =& wfGetDB( DB_MASTER
);
1275 $dbw->delete( 'user_groups',
1277 'ug_user' => $this->getID(),
1278 'ug_group' => $group,
1280 'User::removeGroup' );
1282 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1283 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups() );
1285 $this->invalidateCache();
1286 $this->saveSettings();
1291 * A more legible check for non-anonymousness.
1292 * Returns true if the user is not an anonymous visitor.
1296 function isLoggedIn() {
1297 return( $this->getID() != 0 );
1301 * A more legible check for anonymousness.
1302 * Returns true if the user is an anonymous visitor.
1307 return !$this->isLoggedIn();
1311 * Deprecated in 1.6, die in 1.7, to be removed in 1.8
1314 function isSysop() {
1315 throw new MWException( "Call to deprecated (v1.7) User::isSysop() method\n" );
1319 * Deprecated in 1.6, die in 1.7, to be removed in 1.8
1322 function isDeveloper() {
1323 throw new MWException( "Call to deprecated (v1.7) User::isDeveloper() method\n" );
1327 * Deprecated in 1.6, die in 1.7, to be removed in 1.8
1330 function isBureaucrat() {
1331 throw new MWException( "Call to deprecated (v1.7) User::isBureaucrat() method\n" );
1335 * Whether the user is a bot
1339 return $this->isAllowed( 'bot' );
1343 * Check if user is allowed to access a feature / make an action
1344 * @param string $action Action to be checked
1345 * @return boolean True: action is allowed, False: action should not be allowed
1347 function isAllowed($action='') {
1348 if ( $action === '' )
1349 // In the spirit of DWIM
1352 $this->loadFromDatabase();
1353 return in_array( $action , $this->mRights
);
1357 * Load a skin if it doesn't exist or return it
1358 * @todo FIXME : need to check the old failback system [AV]
1360 function &getSkin() {
1361 global $IP, $wgRequest;
1362 if ( ! isset( $this->mSkin
) ) {
1363 $fname = 'User::getSkin';
1364 wfProfileIn( $fname );
1367 $userSkin = $this->getOption( 'skin' );
1368 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1370 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1371 wfProfileOut( $fname );
1373 return $this->mSkin
;
1377 * @param string $title Article title to look at
1381 * Check watched status of an article
1382 * @return bool True if article is watched
1384 function isWatched( $title ) {
1385 $wl = WatchedItem
::fromUserTitle( $this, $title );
1386 return $wl->isWatched();
1392 function addWatch( $title ) {
1393 $wl = WatchedItem
::fromUserTitle( $this, $title );
1395 $this->invalidateCache();
1399 * Stop watching an article
1401 function removeWatch( $title ) {
1402 $wl = WatchedItem
::fromUserTitle( $this, $title );
1404 $this->invalidateCache();
1408 * Clear the user's notification timestamp for the given title.
1409 * If e-notif e-mails are on, they will receive notification mails on
1410 * the next change of the page if it's watched etc.
1412 function clearNotification( &$title ) {
1413 global $wgUser, $wgUseEnotif;
1416 if ($title->getNamespace() == NS_USER_TALK
&&
1417 $title->getText() == $this->getName() ) {
1418 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1420 $this->setNewtalk( false );
1423 if( !$wgUseEnotif ) {
1427 if( $this->isAnon() ) {
1428 // Nothing else to do...
1432 // Only update the timestamp if the page is being watched.
1433 // The query to find out if it is watched is cached both in memcached and per-invocation,
1434 // and when it does have to be executed, it can be on a slave
1435 // If this is the user's newtalk page, we always update the timestamp
1436 if ($title->getNamespace() == NS_USER_TALK
&&
1437 $title->getText() == $wgUser->getName())
1440 } elseif ( $this->getID() == $wgUser->getID() ) {
1441 $watched = $title->userIsWatching();
1446 // If the page is watched by the user (or may be watched), update the timestamp on any
1447 // any matching rows
1449 $dbw =& wfGetDB( DB_MASTER
);
1450 $success = $dbw->update( 'watchlist',
1452 'wl_notificationtimestamp' => NULL
1453 ), array( /* WHERE */
1454 'wl_title' => $title->getDBkey(),
1455 'wl_namespace' => $title->getNamespace(),
1456 'wl_user' => $this->getID()
1457 ), 'User::clearLastVisited'
1465 * Resets all of the given user's page-change notification timestamps.
1466 * If e-notif e-mails are on, they will receive notification mails on
1467 * the next change of any watched page.
1469 * @param int $currentUser user ID number
1472 function clearAllNotifications( $currentUser ) {
1473 global $wgUseEnotif;
1474 if ( !$wgUseEnotif ) {
1475 $this->setNewtalk( false );
1478 if( $currentUser != 0 ) {
1480 $dbw =& wfGetDB( DB_MASTER
);
1481 $success = $dbw->update( 'watchlist',
1483 'wl_notificationtimestamp' => 0
1484 ), array( /* WHERE */
1485 'wl_user' => $currentUser
1486 ), 'UserMailer::clearAll'
1489 # we also need to clear here the "you have new message" notification for the own user_talk page
1490 # This is cleared one page view later in Article::viewUpdates();
1496 * @return string Encoding options
1498 function encodeOptions() {
1499 if ( is_null( $this->mOptions
) ) {
1500 $this->mOptions
= User
::getDefaultOptions();
1503 foreach ( $this->mOptions
as $oname => $oval ) {
1504 array_push( $a, $oname.'='.$oval );
1506 $s = implode( "\n", $a );
1513 function decodeOptions( $str ) {
1516 $this->mOptions
= array();
1517 $a = explode( "\n", $str );
1518 foreach ( $a as $s ) {
1519 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1520 $this->mOptions
[$m[1]] = $m[2];
1525 function setCookies() {
1526 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1527 if ( 0 == $this->mId
) return;
1528 $this->loadFromDatabase();
1529 $exp = time() +
$wgCookieExpiration;
1531 $_SESSION['wsUserID'] = $this->mId
;
1532 setcookie( $wgCookiePrefix.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1534 $_SESSION['wsUserName'] = $this->getName();
1535 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1537 $_SESSION['wsToken'] = $this->mToken
;
1538 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1539 setcookie( $wgCookiePrefix.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1541 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1547 * It will clean the session cookie
1550 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1551 $this->loadDefaults();
1552 $this->setLoaded( true );
1554 $_SESSION['wsUserID'] = 0;
1556 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1557 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1559 # Remember when user logged out, to prevent seeing cached pages
1560 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1564 * Save object settings into database
1566 function saveSettings() {
1567 global $wgMemc, $wgDBname;
1568 $fname = 'User::saveSettings';
1570 if ( wfReadOnly() ) { return; }
1571 if ( 0 == $this->mId
) { return; }
1573 $dbw =& wfGetDB( DB_MASTER
);
1574 $dbw->update( 'user',
1576 'user_name' => $this->mName
,
1577 'user_password' => $this->mPassword
,
1578 'user_newpassword' => $this->mNewpassword
,
1579 'user_real_name' => $this->mRealName
,
1580 'user_email' => $this->mEmail
,
1581 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1582 'user_options' => $this->encodeOptions(),
1583 'user_touched' => $dbw->timestamp($this->mTouched
),
1584 'user_token' => $this->mToken
1585 ), array( /* WHERE */
1586 'user_id' => $this->mId
1589 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1594 * Checks if a user with the given name exists, returns the ID
1596 function idForName() {
1597 $fname = 'User::idForName';
1600 $s = trim( $this->getName() );
1601 if ( 0 == strcmp( '', $s ) ) return 0;
1603 $dbr =& wfGetDB( DB_SLAVE
);
1604 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1605 if ( $id === false ) {
1612 * Add user object to the database
1614 function addToDatabase() {
1615 $fname = 'User::addToDatabase';
1616 $dbw =& wfGetDB( DB_MASTER
);
1617 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1618 $dbw->insert( 'user',
1620 'user_id' => $seqVal,
1621 'user_name' => $this->mName
,
1622 'user_password' => $this->mPassword
,
1623 'user_newpassword' => $this->mNewpassword
,
1624 'user_email' => $this->mEmail
,
1625 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1626 'user_real_name' => $this->mRealName
,
1627 'user_options' => $this->encodeOptions(),
1628 'user_token' => $this->mToken
,
1629 'user_registration' => $dbw->timestamp( $this->mRegistration
),
1632 $this->mId
= $dbw->insertId();
1635 function spreadBlock() {
1636 # If the (non-anonymous) user is blocked, this function will block any IP address
1637 # that they successfully log on from.
1638 $fname = 'User::spreadBlock';
1640 wfDebug( "User:spreadBlock()\n" );
1641 if ( $this->mId
== 0 ) {
1645 $userblock = Block
::newFromDB( '', $this->mId
);
1646 if ( !$userblock ) {
1650 # Check if this IP address is already blocked
1651 $ipblock = Block
::newFromDB( wfGetIP() );
1653 # If the user is already blocked. Then check if the autoblock would
1654 # excede the user block. If it would excede, then do nothing, else
1655 # prolong block time
1656 if ($userblock->mExpiry
&&
1657 ($userblock->mExpiry
< Block
::getAutoblockExpiry($ipblock->mTimestamp
))) {
1660 # Just update the timestamp
1661 $ipblock->updateTimestamp();
1664 $ipblock = new Block
;
1667 # Make a new block object with the desired properties
1668 wfDebug( "Autoblocking {$this->mName}@" . wfGetIP() . "\n" );
1669 $ipblock->mAddress
= wfGetIP();
1670 $ipblock->mUser
= 0;
1671 $ipblock->mBy
= $userblock->mBy
;
1672 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
1673 $ipblock->mTimestamp
= wfTimestampNow();
1674 $ipblock->mAuto
= 1;
1675 # If the user is already blocked with an expiry date, we don't
1676 # want to pile on top of that!
1677 if($userblock->mExpiry
) {
1678 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
1680 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
1689 * Generate a string which will be different for any combination of
1690 * user options which would produce different parser output.
1691 * This will be used as part of the hash key for the parser cache,
1692 * so users will the same options can share the same cached data
1695 * Extensions which require it should install 'PageRenderingHash' hook,
1696 * which will give them a chance to modify this key based on their own
1701 function getPageRenderingHash() {
1702 global $wgContLang, $wgUseDynamicDates;
1704 return $this->mHash
;
1707 // stubthreshold is only included below for completeness,
1708 // it will always be 0 when this function is called by parsercache.
1710 $confstr = $this->getOption( 'math' );
1711 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1712 if ( $wgUseDynamicDates ) {
1713 $confstr .= '!' . $this->getDatePreference();
1715 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
1716 $confstr .= '!' . $this->getOption( 'language' );
1717 $confstr .= '!' . $this->getOption( 'thumbsize' );
1718 // add in language specific options, if any
1719 $extra = $wgContLang->getExtraHashOptions();
1722 // Give a chance for extensions to modify the hash, if they have
1723 // extra options or other effects on the parser cache.
1724 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
1726 $this->mHash
= $confstr;
1730 function isBlockedFromCreateAccount() {
1731 $this->getBlockedStatus();
1732 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
1735 function isAllowedToCreateAccount() {
1736 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
1740 * Set mDataLoaded, return previous value
1741 * Use this to prevent DB access in command-line scripts or similar situations
1743 function setLoaded( $loaded ) {
1744 return wfSetVar( $this->mDataLoaded
, $loaded );
1748 * Get this user's personal page title.
1753 function getUserPage() {
1754 return Title
::makeTitle( NS_USER
, $this->getName() );
1758 * Get this user's talk page title.
1763 function getTalkPage() {
1764 $title = $this->getUserPage();
1765 return $title->getTalkPage();
1771 function getMaxID() {
1772 static $res; // cache
1774 if ( isset( $res ) )
1777 $dbr =& wfGetDB( DB_SLAVE
);
1778 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
1783 * Determine whether the user is a newbie. Newbies are either
1784 * anonymous IPs, or the most recently created accounts.
1785 * @return bool True if it is a newbie.
1787 function isNewbie() {
1788 return !$this->isAllowed( 'autoconfirmed' );
1792 * Check to see if the given clear-text password is one of the accepted passwords
1793 * @param string $password User password.
1794 * @return bool True if the given password is correct otherwise False.
1796 function checkPassword( $password ) {
1797 global $wgAuth, $wgMinimalPasswordLength;
1798 $this->loadFromDatabase();
1800 // Even though we stop people from creating passwords that
1801 // are shorter than this, doesn't mean people wont be able
1802 // to. Certain authentication plugins do NOT want to save
1803 // domain passwords in a mysql database, so we should
1804 // check this (incase $wgAuth->strict() is false).
1805 if( strlen( $password ) < $wgMinimalPasswordLength ) {
1809 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1811 } elseif( $wgAuth->strict() ) {
1812 /* Auth plugin doesn't allow local authentication */
1815 $ep = $this->encryptPassword( $password );
1816 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
1818 } elseif ( ($this->mNewpassword
!= '') && (0 == strcmp( $ep, $this->mNewpassword
)) ) {
1820 } elseif ( function_exists( 'iconv' ) ) {
1821 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1822 # Check for this with iconv
1823 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1824 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
1832 * Initialize (if necessary) and return a session token value
1833 * which can be used in edit forms to show that the user's
1834 * login credentials aren't being hijacked with a foreign form
1837 * @param mixed $salt - Optional function-specific data for hash.
1838 * Use a string or an array of strings.
1842 function editToken( $salt = '' ) {
1843 if( !isset( $_SESSION['wsEditToken'] ) ) {
1844 $token = $this->generateToken();
1845 $_SESSION['wsEditToken'] = $token;
1847 $token = $_SESSION['wsEditToken'];
1849 if( is_array( $salt ) ) {
1850 $salt = implode( '|', $salt );
1852 return md5( $token . $salt );
1856 * Generate a hex-y looking random token for various uses.
1857 * Could be made more cryptographically sure if someone cares.
1860 function generateToken( $salt = '' ) {
1861 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1862 return md5( $token . $salt );
1866 * Check given value against the token value stored in the session.
1867 * A match should confirm that the form was submitted from the
1868 * user's own login session, not a form submission from a third-party
1871 * @param string $val - the input value to compare
1872 * @param string $salt - Optional function-specific data for hash
1876 function matchEditToken( $val, $salt = '' ) {
1878 $sessionToken = $this->editToken( $salt );
1879 if ( $val != $sessionToken ) {
1880 wfDebug( "User::matchEditToken: broken session data\n" );
1882 return $val == $sessionToken;
1886 * Generate a new e-mail confirmation token and send a confirmation
1887 * mail to the user's given address.
1889 * @return mixed True on success, a WikiError object on failure.
1891 function sendConfirmationMail() {
1893 $url = $this->confirmationTokenUrl( $expiration );
1894 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1895 wfMsg( 'confirmemail_body',
1899 $wgContLang->timeanddate( $expiration, false ) ) );
1903 * Send an e-mail to this user's account. Does not check for
1904 * confirmed status or validity.
1906 * @param string $subject
1907 * @param string $body
1908 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1909 * @return mixed True on success, a WikiError object on failure.
1911 function sendMail( $subject, $body, $from = null ) {
1912 if( is_null( $from ) ) {
1913 global $wgPasswordSender;
1914 $from = $wgPasswordSender;
1917 require_once( 'UserMailer.php' );
1918 $to = new MailAddress( $this );
1919 $sender = new MailAddress( $from );
1920 $error = userMailer( $to, $sender, $subject, $body );
1922 if( $error == '' ) {
1925 return new WikiError( $error );
1930 * Generate, store, and return a new e-mail confirmation code.
1931 * A hash (unsalted since it's used as a key) is stored.
1932 * @param &$expiration mixed output: accepts the expiration time
1936 function confirmationToken( &$expiration ) {
1937 $fname = 'User::confirmationToken';
1940 $expires = $now +
7 * 24 * 60 * 60;
1941 $expiration = wfTimestamp( TS_MW
, $expires );
1943 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
1944 $hash = md5( $token );
1946 $dbw =& wfGetDB( DB_MASTER
);
1947 $dbw->update( 'user',
1948 array( 'user_email_token' => $hash,
1949 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1950 array( 'user_id' => $this->mId
),
1957 * Generate and store a new e-mail confirmation token, and return
1958 * the URL the user can use to confirm.
1959 * @param &$expiration mixed output: accepts the expiration time
1963 function confirmationTokenUrl( &$expiration ) {
1964 $token = $this->confirmationToken( $expiration );
1965 $title = Title
::makeTitle( NS_SPECIAL
, 'Confirmemail/' . $token );
1966 return $title->getFullUrl();
1970 * Mark the e-mail address confirmed and save.
1972 function confirmEmail() {
1973 $this->loadFromDatabase();
1974 $this->mEmailAuthenticated
= wfTimestampNow();
1975 $this->saveSettings();
1980 * Is this user allowed to send e-mails within limits of current
1981 * site configuration?
1984 function canSendEmail() {
1985 return $this->isEmailConfirmed();
1989 * Is this user allowed to receive e-mails within limits of current
1990 * site configuration?
1993 function canReceiveEmail() {
1994 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
1998 * Is this user's e-mail address valid-looking and confirmed within
1999 * limits of the current site configuration?
2001 * If $wgEmailAuthentication is on, this may require the user to have
2002 * confirmed their address by returning a code or using a password
2003 * sent to the address from the wiki.
2007 function isEmailConfirmed() {
2008 global $wgEmailAuthentication;
2009 $this->loadFromDatabase();
2011 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2012 if( $this->isAnon() )
2014 if( !$this->isValidEmailAddr( $this->mEmail
) )
2016 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2025 * @param array $groups list of groups
2026 * @return array list of permission key names for given groups combined
2029 function getGroupPermissions( $groups ) {
2030 global $wgGroupPermissions;
2032 foreach( $groups as $group ) {
2033 if( isset( $wgGroupPermissions[$group] ) ) {
2034 $rights = array_merge( $rights,
2035 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2042 * @param string $group key name
2043 * @return string localized descriptive name for group, if provided
2046 function getGroupName( $group ) {
2047 $key = "group-$group";
2048 $name = wfMsg( $key );
2049 if( $name == '' ||
$name == "<$key>" ) {
2057 * @param string $group key name
2058 * @return string localized descriptive name for member of a group, if provided
2061 function getGroupMember( $group ) {
2062 $key = "group-$group-member";
2063 $name = wfMsg( $key );
2064 if( $name == '' ||
$name == "<$key>" ) {
2073 * Return the set of defined explicit groups.
2074 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2075 * groups are not included, as they are defined
2076 * automatically, not in the database.
2080 function getAllGroups() {
2081 global $wgGroupPermissions;
2083 array_keys( $wgGroupPermissions ),
2084 array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
2088 * Get the title of a page describing a particular group
2090 * @param $group Name of the group
2093 function getGroupPage( $group ) {
2094 $page = wfMsgForContent( 'grouppage-' . $group );
2095 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2096 $title = Title
::newFromText( $page );
2097 if( is_object( $title ) )