4913de89d29ba4e4cb9d70fad6f9b92a813193fc
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, $wgDBname, $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["$wgDBname:limiter:$action:anon"] = $limits['anon'];
681 if( isset( $limits['user'] ) && $id != 0 ) {
682 $keys["$wgDBname:limiter:$action:user:$id"] = $limits['user'];
684 if( $this->isNewbie() ) {
685 if( isset( $limits['newbie'] ) && $id != 0 ) {
686 $keys["$wgDBname: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
) . ' ' . $wgDBname . ': ' . $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, $wgDBname, $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 = "$wgDBname: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.
961 global $wgDBname, $wgMemc;
962 $key = "$wgDBname: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() {
984 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
987 if (!$this->getNewtalk())
989 $up = $this->getUserPage();
990 $utp = $up->getTalkPage();
991 return array(array("wiki" => $wgDBname, "link" => $utp->getLocalURL()));
996 * Perform a user_newtalk check on current slaves; if the memcached data
997 * is funky we don't want newtalk state to get stuck on save, as that's
1000 * @param string $field
1005 function checkNewtalk( $field, $id ) {
1006 $fname = 'User::checkNewtalk';
1007 $dbr =& wfGetDB( DB_SLAVE
);
1008 $ok = $dbr->selectField( 'user_newtalk', $field,
1009 array( $field => $id ), $fname );
1010 return $ok !== false;
1015 * @param string $field
1019 function updateNewtalk( $field, $id ) {
1020 $fname = 'User::updateNewtalk';
1021 if( $this->checkNewtalk( $field, $id ) ) {
1022 wfDebug( "$fname already set ($field, $id), ignoring\n" );
1025 $dbw =& wfGetDB( DB_MASTER
);
1026 $dbw->insert( 'user_newtalk',
1027 array( $field => $id ),
1030 wfDebug( "$fname: set on ($field, $id)\n" );
1035 * Clear the new messages flag for the given user
1036 * @param string $field
1040 function deleteNewtalk( $field, $id ) {
1041 $fname = 'User::deleteNewtalk';
1042 if( !$this->checkNewtalk( $field, $id ) ) {
1043 wfDebug( "$fname: already gone ($field, $id), ignoring\n" );
1046 $dbw =& wfGetDB( DB_MASTER
);
1047 $dbw->delete( 'user_newtalk',
1048 array( $field => $id ),
1050 wfDebug( "$fname: killed on ($field, $id)\n" );
1055 * Update the 'You have new messages!' status.
1058 function setNewtalk( $val ) {
1059 if( wfReadOnly() ) {
1063 $this->loadFromDatabase();
1064 $this->mNewtalk
= $val;
1066 $fname = 'User::setNewtalk';
1068 if( $this->isAnon() ) {
1070 $id = $this->getName();
1073 $id = $this->getId();
1077 $changed = $this->updateNewtalk( $field, $id );
1079 $changed = $this->deleteNewtalk( $field, $id );
1083 if( $this->isAnon() ) {
1084 // Anons have a separate memcached space, since
1085 // user records aren't kept for them.
1086 global $wgDBname, $wgMemc;
1087 $key = "$wgDBname:newtalk:ip:$val";
1088 $wgMemc->set( $key, $val ?
1 : 0 );
1091 // Make sure the user page is watched, so a notification
1092 // will be sent out if enabled.
1093 $this->addWatch( $this->getTalkPage() );
1096 $this->invalidateCache();
1097 $this->saveSettings();
1101 function invalidateCache() {
1102 global $wgClockSkewFudge;
1103 $this->loadFromDatabase();
1104 $this->mTouched
= wfTimestamp(TS_MW
, time() +
$wgClockSkewFudge );
1105 # Don't forget to save the options after this or
1106 # it won't take effect!
1109 function validateCache( $timestamp ) {
1110 $this->loadFromDatabase();
1111 return ($timestamp >= $this->mTouched
);
1115 * Encrypt a password.
1116 * It can eventuall salt a password @see User::addSalt()
1117 * @param string $p clear Password.
1118 * @return string Encrypted password.
1120 function encryptPassword( $p ) {
1121 return wfEncryptPassword( $this->mId
, $p );
1124 # Set the password and reset the random token
1125 function setPassword( $str ) {
1126 $this->loadFromDatabase();
1128 $this->mPassword
= $this->encryptPassword( $str );
1129 $this->mNewpassword
= '';
1132 # Set the random token (used for persistent authentication)
1133 function setToken( $token = false ) {
1134 global $wgSecretKey, $wgProxyKey, $wgDBname;
1136 if ( $wgSecretKey ) {
1137 $key = $wgSecretKey;
1138 } elseif ( $wgProxyKey ) {
1143 $this->mToken
= md5( $key . mt_rand( 0, 0x7fffffff ) . $wgDBname . $this->mId
);
1145 $this->mToken
= $token;
1150 function setCookiePassword( $str ) {
1151 $this->loadFromDatabase();
1152 $this->mCookiePassword
= md5( $str );
1155 function setNewpassword( $str ) {
1156 $this->loadFromDatabase();
1157 $this->mNewpassword
= $this->encryptPassword( $str );
1160 function getEmail() {
1161 $this->loadFromDatabase();
1162 return $this->mEmail
;
1165 function getEmailAuthenticationTimestamp() {
1166 $this->loadFromDatabase();
1167 return $this->mEmailAuthenticated
;
1170 function setEmail( $str ) {
1171 $this->loadFromDatabase();
1172 $this->mEmail
= $str;
1175 function getRealName() {
1176 $this->loadFromDatabase();
1177 return $this->mRealName
;
1180 function setRealName( $str ) {
1181 $this->loadFromDatabase();
1182 $this->mRealName
= $str;
1186 * @param string $oname The option to check
1189 function getOption( $oname ) {
1190 $this->loadFromDatabase();
1191 if ( is_null( $this->mOptions
) ) {
1192 $this->mOptions
= User
::getDefaultOptions();
1194 if ( array_key_exists( $oname, $this->mOptions
) ) {
1195 return trim( $this->mOptions
[$oname] );
1202 * Get the user's date preference, including some important migration for
1205 function getDatePreference() {
1206 if ( is_null( $this->mDatePreference
) ) {
1208 $value = $this->getOption( 'date' );
1209 $map = $wgLang->getDatePreferenceMigrationMap();
1210 if ( isset( $map[$value] ) ) {
1211 $value = $map[$value];
1213 $this->mDatePreference
= $value;
1215 return $this->mDatePreference
;
1219 * @param string $oname The option to check
1220 * @return bool False if the option is not selected, true if it is
1222 function getBoolOption( $oname ) {
1223 return (bool)$this->getOption( $oname );
1227 * Get an option as an integer value from the source string.
1228 * @param string $oname The option to check
1229 * @param int $default Optional value to return if option is unset/blank.
1232 function getIntOption( $oname, $default=0 ) {
1233 $val = $this->getOption( $oname );
1237 return intval( $val );
1240 function setOption( $oname, $val ) {
1241 $this->loadFromDatabase();
1242 if ( is_null( $this->mOptions
) ) {
1243 $this->mOptions
= User
::getDefaultOptions();
1245 if ( $oname == 'skin' ) {
1246 # Clear cached skin, so the new one displays immediately in Special:Preferences
1247 unset( $this->mSkin
);
1249 // Filter out any newlines that may have passed through input validation.
1250 // Newlines are used to separate items in the options blob.
1251 $val = str_replace( "\r\n", "\n", $val );
1252 $val = str_replace( "\r", "\n", $val );
1253 $val = str_replace( "\n", " ", $val );
1254 $this->mOptions
[$oname] = $val;
1255 $this->invalidateCache();
1258 function getRights() {
1259 $this->loadFromDatabase();
1260 return $this->mRights
;
1264 * Get the list of explicit group memberships this user has.
1265 * The implicit * and user groups are not included.
1266 * @return array of strings
1268 function getGroups() {
1269 $this->loadFromDatabase();
1270 return $this->mGroups
;
1274 * Get the list of implicit group memberships this user has.
1275 * This includes all explicit groups, plus 'user' if logged in
1276 * and '*' for all accounts.
1277 * @return array of strings
1279 function getEffectiveGroups() {
1280 $base = array( '*' );
1281 if( $this->isLoggedIn() ) {
1284 return array_merge( $base, $this->getGroups() );
1288 * Add the user to the given group.
1289 * This takes immediate effect.
1292 function addGroup( $group ) {
1293 $dbw =& wfGetDB( DB_MASTER
);
1294 $dbw->insert( 'user_groups',
1296 'ug_user' => $this->getID(),
1297 'ug_group' => $group,
1300 array( 'IGNORE' ) );
1302 $this->mGroups
= array_merge( $this->mGroups
, array( $group ) );
1303 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups() );
1305 $this->invalidateCache();
1306 $this->saveSettings();
1310 * Remove the user from the given group.
1311 * This takes immediate effect.
1314 function removeGroup( $group ) {
1315 $dbw =& wfGetDB( DB_MASTER
);
1316 $dbw->delete( 'user_groups',
1318 'ug_user' => $this->getID(),
1319 'ug_group' => $group,
1321 'User::removeGroup' );
1323 $this->mGroups
= array_diff( $this->mGroups
, array( $group ) );
1324 $this->mRights
= User
::getGroupPermissions( $this->getEffectiveGroups() );
1326 $this->invalidateCache();
1327 $this->saveSettings();
1332 * A more legible check for non-anonymousness.
1333 * Returns true if the user is not an anonymous visitor.
1337 function isLoggedIn() {
1338 return( $this->getID() != 0 );
1342 * A more legible check for anonymousness.
1343 * Returns true if the user is an anonymous visitor.
1348 return !$this->isLoggedIn();
1352 * Whether the user is a bot
1356 return $this->isAllowed( 'bot' );
1360 * Check if user is allowed to access a feature / make an action
1361 * @param string $action Action to be checked
1362 * @return boolean True: action is allowed, False: action should not be allowed
1364 function isAllowed($action='') {
1365 if ( $action === '' )
1366 // In the spirit of DWIM
1369 $this->loadFromDatabase();
1370 return in_array( $action , $this->mRights
);
1374 * Load a skin if it doesn't exist or return it
1375 * @todo FIXME : need to check the old failback system [AV]
1377 function &getSkin() {
1378 global $IP, $wgRequest;
1379 if ( ! isset( $this->mSkin
) ) {
1380 $fname = 'User::getSkin';
1381 wfProfileIn( $fname );
1384 $userSkin = $this->getOption( 'skin' );
1385 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1387 $this->mSkin
=& Skin
::newFromKey( $userSkin );
1388 wfProfileOut( $fname );
1390 return $this->mSkin
;
1394 * @param string $title Article title to look at
1398 * Check watched status of an article
1399 * @return bool True if article is watched
1401 function isWatched( $title ) {
1402 $wl = WatchedItem
::fromUserTitle( $this, $title );
1403 return $wl->isWatched();
1409 function addWatch( $title ) {
1410 $wl = WatchedItem
::fromUserTitle( $this, $title );
1412 $this->invalidateCache();
1416 * Stop watching an article
1418 function removeWatch( $title ) {
1419 $wl = WatchedItem
::fromUserTitle( $this, $title );
1421 $this->invalidateCache();
1425 * Clear the user's notification timestamp for the given title.
1426 * If e-notif e-mails are on, they will receive notification mails on
1427 * the next change of the page if it's watched etc.
1429 function clearNotification( &$title ) {
1430 global $wgUser, $wgUseEnotif;
1433 if ($title->getNamespace() == NS_USER_TALK
&&
1434 $title->getText() == $this->getName() ) {
1435 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1437 $this->setNewtalk( false );
1440 if( !$wgUseEnotif ) {
1444 if( $this->isAnon() ) {
1445 // Nothing else to do...
1449 // Only update the timestamp if the page is being watched.
1450 // The query to find out if it is watched is cached both in memcached and per-invocation,
1451 // and when it does have to be executed, it can be on a slave
1452 // If this is the user's newtalk page, we always update the timestamp
1453 if ($title->getNamespace() == NS_USER_TALK
&&
1454 $title->getText() == $wgUser->getName())
1457 } elseif ( $this->getID() == $wgUser->getID() ) {
1458 $watched = $title->userIsWatching();
1463 // If the page is watched by the user (or may be watched), update the timestamp on any
1464 // any matching rows
1466 $dbw =& wfGetDB( DB_MASTER
);
1467 $success = $dbw->update( 'watchlist',
1469 'wl_notificationtimestamp' => NULL
1470 ), array( /* WHERE */
1471 'wl_title' => $title->getDBkey(),
1472 'wl_namespace' => $title->getNamespace(),
1473 'wl_user' => $this->getID()
1474 ), 'User::clearLastVisited'
1482 * Resets all of the given user's page-change notification timestamps.
1483 * If e-notif e-mails are on, they will receive notification mails on
1484 * the next change of any watched page.
1486 * @param int $currentUser user ID number
1489 function clearAllNotifications( $currentUser ) {
1490 global $wgUseEnotif;
1491 if ( !$wgUseEnotif ) {
1492 $this->setNewtalk( false );
1495 if( $currentUser != 0 ) {
1497 $dbw =& wfGetDB( DB_MASTER
);
1498 $success = $dbw->update( 'watchlist',
1500 'wl_notificationtimestamp' => NULL
1501 ), array( /* WHERE */
1502 'wl_user' => $currentUser
1503 ), 'UserMailer::clearAll'
1506 # we also need to clear here the "you have new message" notification for the own user_talk page
1507 # This is cleared one page view later in Article::viewUpdates();
1513 * @return string Encoding options
1515 function encodeOptions() {
1516 if ( is_null( $this->mOptions
) ) {
1517 $this->mOptions
= User
::getDefaultOptions();
1520 foreach ( $this->mOptions
as $oname => $oval ) {
1521 array_push( $a, $oname.'='.$oval );
1523 $s = implode( "\n", $a );
1530 function decodeOptions( $str ) {
1533 $this->mOptions
= array();
1534 $a = explode( "\n", $str );
1535 foreach ( $a as $s ) {
1536 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1537 $this->mOptions
[$m[1]] = $m[2];
1542 function setCookies() {
1543 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1544 if ( 0 == $this->mId
) return;
1545 $this->loadFromDatabase();
1546 $exp = time() +
$wgCookieExpiration;
1548 $_SESSION['wsUserID'] = $this->mId
;
1549 setcookie( $wgCookiePrefix.'UserID', $this->mId
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1551 $_SESSION['wsUserName'] = $this->getName();
1552 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1554 $_SESSION['wsToken'] = $this->mToken
;
1555 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1556 setcookie( $wgCookiePrefix.'Token', $this->mToken
, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1558 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1564 * It will clean the session cookie
1567 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1568 $this->loadDefaults();
1569 $this->setLoaded( true );
1571 $_SESSION['wsUserID'] = 0;
1573 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1574 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1576 # Remember when user logged out, to prevent seeing cached pages
1577 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() +
86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1581 * Save object settings into database
1583 function saveSettings() {
1584 global $wgMemc, $wgDBname;
1585 $fname = 'User::saveSettings';
1587 if ( wfReadOnly() ) { return; }
1588 if ( 0 == $this->mId
) { return; }
1590 $dbw =& wfGetDB( DB_MASTER
);
1591 $dbw->update( 'user',
1593 'user_name' => $this->mName
,
1594 'user_password' => $this->mPassword
,
1595 'user_newpassword' => $this->mNewpassword
,
1596 'user_real_name' => $this->mRealName
,
1597 'user_email' => $this->mEmail
,
1598 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1599 'user_options' => $this->encodeOptions(),
1600 'user_touched' => $dbw->timestamp($this->mTouched
),
1601 'user_token' => $this->mToken
1602 ), array( /* WHERE */
1603 'user_id' => $this->mId
1606 $wgMemc->delete( "$wgDBname:user:id:$this->mId" );
1611 * Checks if a user with the given name exists, returns the ID
1613 function idForName() {
1614 $fname = 'User::idForName';
1617 $s = trim( $this->getName() );
1618 if ( 0 == strcmp( '', $s ) ) return 0;
1620 $dbr =& wfGetDB( DB_SLAVE
);
1621 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), $fname );
1622 if ( $id === false ) {
1629 * Add user object to the database
1631 function addToDatabase() {
1632 $fname = 'User::addToDatabase';
1633 $dbw =& wfGetDB( DB_MASTER
);
1634 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1635 $dbw->insert( 'user',
1637 'user_id' => $seqVal,
1638 'user_name' => $this->mName
,
1639 'user_password' => $this->mPassword
,
1640 'user_newpassword' => $this->mNewpassword
,
1641 'user_email' => $this->mEmail
,
1642 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated
),
1643 'user_real_name' => $this->mRealName
,
1644 'user_options' => $this->encodeOptions(),
1645 'user_token' => $this->mToken
,
1646 'user_registration' => $dbw->timestamp( $this->mRegistration
),
1649 $this->mId
= $dbw->insertId();
1652 function spreadBlock() {
1653 # If the (non-anonymous) user is blocked, this function will block any IP address
1654 # that they successfully log on from.
1655 $fname = 'User::spreadBlock';
1657 wfDebug( "User:spreadBlock()\n" );
1658 if ( $this->mId
== 0 ) {
1662 $userblock = Block
::newFromDB( '', $this->mId
);
1663 if ( !$userblock ) {
1667 # Check if this IP address is already blocked
1668 $ipblock = Block
::newFromDB( wfGetIP() );
1670 # If the user is already blocked. Then check if the autoblock would
1671 # excede the user block. If it would excede, then do nothing, else
1672 # prolong block time
1673 if ($userblock->mExpiry
&&
1674 ($userblock->mExpiry
< Block
::getAutoblockExpiry($ipblock->mTimestamp
))) {
1677 # Just update the timestamp
1678 $ipblock->updateTimestamp();
1681 $ipblock = new Block
;
1684 # Make a new block object with the desired properties
1685 wfDebug( "Autoblocking {$this->mName}@" . wfGetIP() . "\n" );
1686 $ipblock->mAddress
= wfGetIP();
1687 $ipblock->mUser
= 0;
1688 $ipblock->mBy
= $userblock->mBy
;
1689 $ipblock->mReason
= wfMsg( 'autoblocker', $this->getName(), $userblock->mReason
);
1690 $ipblock->mTimestamp
= wfTimestampNow();
1691 $ipblock->mAuto
= 1;
1692 # If the user is already blocked with an expiry date, we don't
1693 # want to pile on top of that!
1694 if($userblock->mExpiry
) {
1695 $ipblock->mExpiry
= min ( $userblock->mExpiry
, Block
::getAutoblockExpiry( $ipblock->mTimestamp
));
1697 $ipblock->mExpiry
= Block
::getAutoblockExpiry( $ipblock->mTimestamp
);
1706 * Generate a string which will be different for any combination of
1707 * user options which would produce different parser output.
1708 * This will be used as part of the hash key for the parser cache,
1709 * so users will the same options can share the same cached data
1712 * Extensions which require it should install 'PageRenderingHash' hook,
1713 * which will give them a chance to modify this key based on their own
1718 function getPageRenderingHash() {
1719 global $wgContLang, $wgUseDynamicDates;
1721 return $this->mHash
;
1724 // stubthreshold is only included below for completeness,
1725 // it will always be 0 when this function is called by parsercache.
1727 $confstr = $this->getOption( 'math' );
1728 $confstr .= '!' . $this->getOption( 'stubthreshold' );
1729 if ( $wgUseDynamicDates ) {
1730 $confstr .= '!' . $this->getDatePreference();
1732 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ?
'1' : '');
1733 $confstr .= '!' . $this->getOption( 'language' );
1734 $confstr .= '!' . $this->getOption( 'thumbsize' );
1735 // add in language specific options, if any
1736 $extra = $wgContLang->getExtraHashOptions();
1739 // Give a chance for extensions to modify the hash, if they have
1740 // extra options or other effects on the parser cache.
1741 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
1743 $this->mHash
= $confstr;
1747 function isBlockedFromCreateAccount() {
1748 $this->getBlockedStatus();
1749 return $this->mBlock
&& $this->mBlock
->mCreateAccount
;
1752 function isAllowedToCreateAccount() {
1753 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
1757 * Set mDataLoaded, return previous value
1758 * Use this to prevent DB access in command-line scripts or similar situations
1760 function setLoaded( $loaded ) {
1761 return wfSetVar( $this->mDataLoaded
, $loaded );
1765 * Get this user's personal page title.
1770 function getUserPage() {
1771 return Title
::makeTitle( NS_USER
, $this->getName() );
1775 * Get this user's talk page title.
1780 function getTalkPage() {
1781 $title = $this->getUserPage();
1782 return $title->getTalkPage();
1788 function getMaxID() {
1789 static $res; // cache
1791 if ( isset( $res ) )
1794 $dbr =& wfGetDB( DB_SLAVE
);
1795 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
1800 * Determine whether the user is a newbie. Newbies are either
1801 * anonymous IPs, or the most recently created accounts.
1802 * @return bool True if it is a newbie.
1804 function isNewbie() {
1805 return !$this->isAllowed( 'autoconfirmed' );
1809 * Check to see if the given clear-text password is one of the accepted passwords
1810 * @param string $password User password.
1811 * @return bool True if the given password is correct otherwise False.
1813 function checkPassword( $password ) {
1814 global $wgAuth, $wgMinimalPasswordLength;
1815 $this->loadFromDatabase();
1817 // Even though we stop people from creating passwords that
1818 // are shorter than this, doesn't mean people wont be able
1819 // to. Certain authentication plugins do NOT want to save
1820 // domain passwords in a mysql database, so we should
1821 // check this (incase $wgAuth->strict() is false).
1822 if( strlen( $password ) < $wgMinimalPasswordLength ) {
1826 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
1828 } elseif( $wgAuth->strict() ) {
1829 /* Auth plugin doesn't allow local authentication */
1832 $ep = $this->encryptPassword( $password );
1833 if ( 0 == strcmp( $ep, $this->mPassword
) ) {
1835 } elseif ( ($this->mNewpassword
!= '') && (0 == strcmp( $ep, $this->mNewpassword
)) ) {
1837 } elseif ( function_exists( 'iconv' ) ) {
1838 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
1839 # Check for this with iconv
1840 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252', $password ) );
1841 if ( 0 == strcmp( $cp1252hash, $this->mPassword
) ) {
1849 * Initialize (if necessary) and return a session token value
1850 * which can be used in edit forms to show that the user's
1851 * login credentials aren't being hijacked with a foreign form
1854 * @param mixed $salt - Optional function-specific data for hash.
1855 * Use a string or an array of strings.
1859 function editToken( $salt = '' ) {
1860 if( !isset( $_SESSION['wsEditToken'] ) ) {
1861 $token = $this->generateToken();
1862 $_SESSION['wsEditToken'] = $token;
1864 $token = $_SESSION['wsEditToken'];
1866 if( is_array( $salt ) ) {
1867 $salt = implode( '|', $salt );
1869 return md5( $token . $salt );
1873 * Generate a hex-y looking random token for various uses.
1874 * Could be made more cryptographically sure if someone cares.
1877 function generateToken( $salt = '' ) {
1878 $token = dechex( mt_rand() ) . dechex( mt_rand() );
1879 return md5( $token . $salt );
1883 * Check given value against the token value stored in the session.
1884 * A match should confirm that the form was submitted from the
1885 * user's own login session, not a form submission from a third-party
1888 * @param string $val - the input value to compare
1889 * @param string $salt - Optional function-specific data for hash
1893 function matchEditToken( $val, $salt = '' ) {
1895 $sessionToken = $this->editToken( $salt );
1896 if ( $val != $sessionToken ) {
1897 wfDebug( "User::matchEditToken: broken session data\n" );
1899 return $val == $sessionToken;
1903 * Generate a new e-mail confirmation token and send a confirmation
1904 * mail to the user's given address.
1906 * @return mixed True on success, a WikiError object on failure.
1908 function sendConfirmationMail() {
1910 $url = $this->confirmationTokenUrl( $expiration );
1911 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
1912 wfMsg( 'confirmemail_body',
1916 $wgContLang->timeanddate( $expiration, false ) ) );
1920 * Send an e-mail to this user's account. Does not check for
1921 * confirmed status or validity.
1923 * @param string $subject
1924 * @param string $body
1925 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
1926 * @return mixed True on success, a WikiError object on failure.
1928 function sendMail( $subject, $body, $from = null ) {
1929 if( is_null( $from ) ) {
1930 global $wgPasswordSender;
1931 $from = $wgPasswordSender;
1934 require_once( 'UserMailer.php' );
1935 $to = new MailAddress( $this );
1936 $sender = new MailAddress( $from );
1937 $error = userMailer( $to, $sender, $subject, $body );
1939 if( $error == '' ) {
1942 return new WikiError( $error );
1947 * Generate, store, and return a new e-mail confirmation code.
1948 * A hash (unsalted since it's used as a key) is stored.
1949 * @param &$expiration mixed output: accepts the expiration time
1953 function confirmationToken( &$expiration ) {
1954 $fname = 'User::confirmationToken';
1957 $expires = $now +
7 * 24 * 60 * 60;
1958 $expiration = wfTimestamp( TS_MW
, $expires );
1960 $token = $this->generateToken( $this->mId
. $this->mEmail
. $expires );
1961 $hash = md5( $token );
1963 $dbw =& wfGetDB( DB_MASTER
);
1964 $dbw->update( 'user',
1965 array( 'user_email_token' => $hash,
1966 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
1967 array( 'user_id' => $this->mId
),
1974 * Generate and store a new e-mail confirmation token, and return
1975 * the URL the user can use to confirm.
1976 * @param &$expiration mixed output: accepts the expiration time
1980 function confirmationTokenUrl( &$expiration ) {
1981 $token = $this->confirmationToken( $expiration );
1982 $title = Title
::makeTitle( NS_SPECIAL
, 'Confirmemail/' . $token );
1983 return $title->getFullUrl();
1987 * Mark the e-mail address confirmed and save.
1989 function confirmEmail() {
1990 $this->loadFromDatabase();
1991 $this->mEmailAuthenticated
= wfTimestampNow();
1992 $this->saveSettings();
1997 * Is this user allowed to send e-mails within limits of current
1998 * site configuration?
2001 function canSendEmail() {
2002 return $this->isEmailConfirmed();
2006 * Is this user allowed to receive e-mails within limits of current
2007 * site configuration?
2010 function canReceiveEmail() {
2011 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2015 * Is this user's e-mail address valid-looking and confirmed within
2016 * limits of the current site configuration?
2018 * If $wgEmailAuthentication is on, this may require the user to have
2019 * confirmed their address by returning a code or using a password
2020 * sent to the address from the wiki.
2024 function isEmailConfirmed() {
2025 global $wgEmailAuthentication;
2026 $this->loadFromDatabase();
2028 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2029 if( $this->isAnon() )
2031 if( !$this->isValidEmailAddr( $this->mEmail
) )
2033 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2042 * @param array $groups list of groups
2043 * @return array list of permission key names for given groups combined
2046 static function getGroupPermissions( $groups ) {
2047 global $wgGroupPermissions;
2049 foreach( $groups as $group ) {
2050 if( isset( $wgGroupPermissions[$group] ) ) {
2051 $rights = array_merge( $rights,
2052 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2059 * @param string $group key name
2060 * @return string localized descriptive name for group, if provided
2063 static function getGroupName( $group ) {
2064 $key = "group-$group";
2065 $name = wfMsg( $key );
2066 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2074 * @param string $group key name
2075 * @return string localized descriptive name for member of a group, if provided
2078 static function getGroupMember( $group ) {
2079 $key = "group-$group-member";
2080 $name = wfMsg( $key );
2081 if( $name == '' ||
wfEmptyMsg( $key, $name ) ) {
2089 * Return the set of defined explicit groups.
2090 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2091 * groups are not included, as they are defined
2092 * automatically, not in the database.
2096 static function getAllGroups() {
2097 global $wgGroupPermissions;
2099 array_keys( $wgGroupPermissions ),
2100 array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
2104 * Get the title of a page describing a particular group
2106 * @param $group Name of the group
2109 static function getGroupPage( $group ) {
2110 $page = wfMsgForContent( 'grouppage-' . $group );
2111 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2112 $title = Title
::newFromText( $page );
2113 if( is_object( $title ) )
2120 * Create a link to the group in HTML, if available
2122 * @param $group Name of the group
2123 * @param $text The text of the link
2126 static function makeGroupLinkHTML( $group, $text = '' ) {
2128 $text = self
::getGroupName( $group );
2130 $title = self
::getGroupPage( $group );
2133 $sk = $wgUser->getSkin();
2134 return $sk->makeLinkObj( $title, $text );
2141 * Create a link to the group in Wikitext, if available
2143 * @param $group Name of the group
2144 * @param $text The text of the link (by default, the name of the group)
2147 static function makeGroupLinkWiki( $group, $text = '' ) {
2149 $text = self
::getGroupName( $group );
2151 $title = self
::getGroupPage( $group );
2153 $page = $title->getPrefixedText();
2154 return "[[$page|$text]]";