r32045 committed from wrong working branch. Revert and commit the one I wanted.
[mediawiki.git] / includes / User.php
bloba8bfbe65d3ac74572bc7c6e040fe22f68e60fd47
1 <?php
2 /**
3 * See user.txt
5 */
7 # Number of characters in user_token field
8 define( 'USER_TOKEN_LENGTH', 32 );
10 # Serialized record version
11 define( 'MW_USER_VERSION', 5 );
13 # Some punctuation to prevent editing from broken text-mangling proxies.
14 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
16 /**
17 * Thrown by User::setPassword() on error
18 * @addtogroup Exception
20 class PasswordError extends MWException {
21 // NOP
24 /**
25 * The User object encapsulates all of the user-specific settings (user_id,
26 * name, rights, password, email address, options, last login time). Client
27 * classes use the getXXX() functions to access these fields. These functions
28 * do all the work of determining whether the user is logged in,
29 * whether the requested option can be satisfied from cookies or
30 * whether a database query is needed. Most of the settings needed
31 * for rendering normal pages are set in the cookie to minimize use
32 * of the database.
34 class User {
36 /**
37 * A list of default user toggles, i.e. boolean user preferences that are
38 * displayed by Special:Preferences as checkboxes. This list can be
39 * extended via the UserToggles hook or $wgContLang->getExtraUserToggles().
41 static public $mToggles = array(
42 'highlightbroken',
43 'justify',
44 'hideminor',
45 'extendwatchlist',
46 'usenewrc',
47 'numberheadings',
48 'showtoolbar',
49 'editondblclick',
50 'editsection',
51 'editsectiononrightclick',
52 'showtoc',
53 'rememberpassword',
54 'editwidth',
55 'watchcreations',
56 'watchdefault',
57 'watchmoves',
58 'watchdeletion',
59 'minordefault',
60 'previewontop',
61 'previewonfirst',
62 'nocache',
63 'enotifwatchlistpages',
64 'enotifusertalkpages',
65 'enotifminoredits',
66 'enotifrevealaddr',
67 'shownumberswatching',
68 'fancysig',
69 'externaleditor',
70 'externaldiff',
71 'showjumplinks',
72 'uselivepreview',
73 'forceeditsummary',
74 'watchlisthideown',
75 'watchlisthidebots',
76 'watchlisthideminor',
77 'ccmeonemails',
78 'diffonly',
79 'showhiddencats',
82 /**
83 * List of member variables which are saved to the shared cache (memcached).
84 * Any operation which changes the corresponding database fields must
85 * call a cache-clearing function.
87 static $mCacheVars = array(
88 # user table
89 'mId',
90 'mName',
91 'mRealName',
92 'mPassword',
93 'mNewpassword',
94 'mNewpassTime',
95 'mEmail',
96 'mOptions',
97 'mTouched',
98 'mToken',
99 'mEmailAuthenticated',
100 'mEmailToken',
101 'mEmailTokenExpires',
102 'mRegistration',
103 'mEditCount',
104 # user_group table
105 'mGroups',
109 * The cache variable declarations
111 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
112 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
113 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
116 * Whether the cache variables have been loaded
118 var $mDataLoaded;
121 * Initialisation data source if mDataLoaded==false. May be one of:
122 * defaults anonymous user initialised from class defaults
123 * name initialise from mName
124 * id initialise from mId
125 * session log in from cookies or session if possible
127 * Use the User::newFrom*() family of functions to set this.
129 var $mFrom;
132 * Lazy-initialised variables, invalidated with clearInstanceCache
134 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
135 $mBlockreason, $mBlock, $mEffectiveGroups;
137 /**
138 * Lightweight constructor for anonymous user
139 * Use the User::newFrom* factory functions for other kinds of users
141 function User() {
142 $this->clearInstanceCache( 'defaults' );
146 * Load the user table data for this object from the source given by mFrom
148 function load() {
149 if ( $this->mDataLoaded ) {
150 return;
152 wfProfileIn( __METHOD__ );
154 # Set it now to avoid infinite recursion in accessors
155 $this->mDataLoaded = true;
157 switch ( $this->mFrom ) {
158 case 'defaults':
159 $this->loadDefaults();
160 break;
161 case 'name':
162 $this->mId = self::idFromName( $this->mName );
163 if ( !$this->mId ) {
164 # Nonexistent user placeholder object
165 $this->loadDefaults( $this->mName );
166 } else {
167 $this->loadFromId();
169 break;
170 case 'id':
171 $this->loadFromId();
172 break;
173 case 'session':
174 $this->loadFromSession();
175 break;
176 default:
177 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
179 wfProfileOut( __METHOD__ );
183 * Load user table data given mId
184 * @return false if the ID does not exist, true otherwise
185 * @private
187 function loadFromId() {
188 global $wgMemc;
189 if ( $this->mId == 0 ) {
190 $this->loadDefaults();
191 return false;
194 # Try cache
195 $key = wfMemcKey( 'user', 'id', $this->mId );
196 $data = $wgMemc->get( $key );
197 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
198 # Object is expired, load from DB
199 $data = false;
202 if ( !$data ) {
203 wfDebug( "Cache miss for user {$this->mId}\n" );
204 # Load from DB
205 if ( !$this->loadFromDatabase() ) {
206 # Can't load from ID, user is anonymous
207 return false;
210 $this->saveToCache();
211 } else {
212 wfDebug( "Got user {$this->mId} from cache\n" );
213 # Restore from cache
214 foreach ( self::$mCacheVars as $name ) {
215 $this->$name = $data[$name];
218 return true;
222 * Save user data to the shared cache
224 function saveToCache() {
225 $this->load();
226 if ( $this->isAnon() ) {
227 // Anonymous users are uncached
228 return;
230 $data = array();
231 foreach ( self::$mCacheVars as $name ) {
232 $data[$name] = $this->$name;
234 $data['mVersion'] = MW_USER_VERSION;
235 $key = wfMemcKey( 'user', 'id', $this->mId );
236 global $wgMemc;
237 $wgMemc->set( $key, $data );
241 * Static factory method for creation from username.
243 * This is slightly less efficient than newFromId(), so use newFromId() if
244 * you have both an ID and a name handy.
246 * @param string $name Username, validated by Title:newFromText()
247 * @param mixed $validate Validate username. Takes the same parameters as
248 * User::getCanonicalName(), except that true is accepted as an alias
249 * for 'valid', for BC.
251 * @return User object, or null if the username is invalid. If the username
252 * is not present in the database, the result will be a user object with
253 * a name, zero user ID and default settings.
254 * @static
256 static function newFromName( $name, $validate = 'valid' ) {
257 if ( $validate === true ) {
258 $validate = 'valid';
260 $name = self::getCanonicalName( $name, $validate );
261 if ( $name === false ) {
262 return null;
263 } else {
264 # Create unloaded user object
265 $u = new User;
266 $u->mName = $name;
267 $u->mFrom = 'name';
268 return $u;
272 static function newFromId( $id ) {
273 $u = new User;
274 $u->mId = $id;
275 $u->mFrom = 'id';
276 return $u;
280 * Factory method to fetch whichever user has a given email confirmation code.
281 * This code is generated when an account is created or its e-mail address
282 * has changed.
284 * If the code is invalid or has expired, returns NULL.
286 * @param string $code
287 * @return User
288 * @static
290 static function newFromConfirmationCode( $code ) {
291 $dbr = wfGetDB( DB_SLAVE );
292 $id = $dbr->selectField( 'user', 'user_id', array(
293 'user_email_token' => md5( $code ),
294 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
295 ) );
296 if( $id !== false ) {
297 return User::newFromId( $id );
298 } else {
299 return null;
304 * Create a new user object using data from session or cookies. If the
305 * login credentials are invalid, the result is an anonymous user.
307 * @return User
308 * @static
310 static function newFromSession() {
311 $user = new User;
312 $user->mFrom = 'session';
313 return $user;
317 * Get username given an id.
318 * @param integer $id Database user id
319 * @return string Nickname of a user
320 * @static
322 static function whoIs( $id ) {
323 $dbr = wfGetDB( DB_SLAVE );
324 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
328 * Get the real name of a user given their identifier
330 * @param int $id Database user id
331 * @return string Real name of a user
333 static function whoIsReal( $id ) {
334 $dbr = wfGetDB( DB_SLAVE );
335 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ );
339 * Get database id given a user name
340 * @param string $name Nickname of a user
341 * @return integer|null Database user id (null: if non existent
342 * @static
344 static function idFromName( $name ) {
345 $nt = Title::newFromText( $name );
346 if( is_null( $nt ) ) {
347 # Illegal name
348 return null;
350 $dbr = wfGetDB( DB_SLAVE );
351 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
353 if ( $s === false ) {
354 return 0;
355 } else {
356 return $s->user_id;
361 * Does the string match an anonymous IPv4 address?
363 * This function exists for username validation, in order to reject
364 * usernames which are similar in form to IP addresses. Strings such
365 * as 300.300.300.300 will return true because it looks like an IP
366 * address, despite not being strictly valid.
368 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
369 * address because the usemod software would "cloak" anonymous IP
370 * addresses like this, if we allowed accounts like this to be created
371 * new users could get the old edits of these anonymous users.
373 * @static
374 * @param string $name Nickname of a user
375 * @return bool
377 static function isIP( $name ) {
378 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || User::isIPv6($name);
379 /*return preg_match("/^
380 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
381 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
382 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
383 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
384 $/x", $name);*/
388 * Check if $name is an IPv6 IP.
390 static function isIPv6($name) {
392 * if it has any non-valid characters, it can't be a valid IPv6
393 * address.
395 if (preg_match("/[^:a-fA-F0-9]/", $name))
396 return false;
398 $parts = explode(":", $name);
399 if (count($parts) < 3)
400 return false;
401 foreach ($parts as $part) {
402 if (!preg_match("/^[0-9a-fA-F]{0,4}$/", $part))
403 return false;
405 return true;
409 * Is the input a valid username?
411 * Checks if the input is a valid username, we don't want an empty string,
412 * an IP address, anything that containins slashes (would mess up subpages),
413 * is longer than the maximum allowed username size or doesn't begin with
414 * a capital letter.
416 * @param string $name
417 * @return bool
418 * @static
420 static function isValidUserName( $name ) {
421 global $wgContLang, $wgMaxNameChars;
423 if ( $name == ''
424 || User::isIP( $name )
425 || strpos( $name, '/' ) !== false
426 || strlen( $name ) > $wgMaxNameChars
427 || $name != $wgContLang->ucfirst( $name ) ) {
428 wfDebugLog( 'username', __METHOD__ .
429 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
430 return false;
433 // Ensure that the name can't be misresolved as a different title,
434 // such as with extra namespace keys at the start.
435 $parsed = Title::newFromText( $name );
436 if( is_null( $parsed )
437 || $parsed->getNamespace()
438 || strcmp( $name, $parsed->getPrefixedText() ) ) {
439 wfDebugLog( 'username', __METHOD__ .
440 ": '$name' invalid due to ambiguous prefixes" );
441 return false;
444 // Check an additional blacklist of troublemaker characters.
445 // Should these be merged into the title char list?
446 $unicodeBlacklist = '/[' .
447 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
448 '\x{00a0}' . # non-breaking space
449 '\x{2000}-\x{200f}' . # various whitespace
450 '\x{2028}-\x{202f}' . # breaks and control chars
451 '\x{3000}' . # ideographic space
452 '\x{e000}-\x{f8ff}' . # private use
453 ']/u';
454 if( preg_match( $unicodeBlacklist, $name ) ) {
455 wfDebugLog( 'username', __METHOD__ .
456 ": '$name' invalid due to blacklisted characters" );
457 return false;
460 return true;
464 * Usernames which fail to pass this function will be blocked
465 * from user login and new account registrations, but may be used
466 * internally by batch processes.
468 * If an account already exists in this form, login will be blocked
469 * by a failure to pass this function.
471 * @param string $name
472 * @return bool
474 static function isUsableName( $name ) {
475 global $wgReservedUsernames;
476 return
477 // Must be a valid username, obviously ;)
478 self::isValidUserName( $name ) &&
480 // Certain names may be reserved for batch processes.
481 !in_array( $name, $wgReservedUsernames );
485 * Usernames which fail to pass this function will be blocked
486 * from new account registrations, but may be used internally
487 * either by batch processes or by user accounts which have
488 * already been created.
490 * Additional character blacklisting may be added here
491 * rather than in isValidUserName() to avoid disrupting
492 * existing accounts.
494 * @param string $name
495 * @return bool
497 static function isCreatableName( $name ) {
498 return
499 self::isUsableName( $name ) &&
501 // Registration-time character blacklisting...
502 strpos( $name, '@' ) === false;
506 * Is the input a valid password for this user?
508 * @param string $password Desired password
509 * @return bool
511 function isValidPassword( $password ) {
512 global $wgMinimalPasswordLength, $wgContLang;
514 $result = null;
515 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
516 return $result;
517 if( $result === false )
518 return false;
520 // Password needs to be long enough, and can't be the same as the username
521 return strlen( $password ) >= $wgMinimalPasswordLength
522 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName );
526 * Does a string look like an email address?
528 * There used to be a regular expression here, it got removed because it
529 * rejected valid addresses. Actually just check if there is '@' somewhere
530 * in the given address.
532 * @todo Check for RFC 2822 compilance (bug 959)
534 * @param string $addr email address
535 * @return bool
537 public static function isValidEmailAddr( $addr ) {
538 $result = null;
539 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
540 return $result;
543 return strpos( $addr, '@' ) !== false;
547 * Given unvalidated user input, return a canonical username, or false if
548 * the username is invalid.
549 * @param string $name
550 * @param mixed $validate Type of validation to use:
551 * false No validation
552 * 'valid' Valid for batch processes
553 * 'usable' Valid for batch processes and login
554 * 'creatable' Valid for batch processes, login and account creation
556 static function getCanonicalName( $name, $validate = 'valid' ) {
557 # Force usernames to capital
558 global $wgContLang;
559 $name = $wgContLang->ucfirst( $name );
561 # Reject names containing '#'; these will be cleaned up
562 # with title normalisation, but then it's too late to
563 # check elsewhere
564 if( strpos( $name, '#' ) !== false )
565 return false;
567 # Clean up name according to title rules
568 $t = Title::newFromText( $name );
569 if( is_null( $t ) ) {
570 return false;
573 # Reject various classes of invalid names
574 $name = $t->getText();
575 global $wgAuth;
576 $name = $wgAuth->getCanonicalName( $t->getText() );
578 switch ( $validate ) {
579 case false:
580 break;
581 case 'valid':
582 if ( !User::isValidUserName( $name ) ) {
583 $name = false;
585 break;
586 case 'usable':
587 if ( !User::isUsableName( $name ) ) {
588 $name = false;
590 break;
591 case 'creatable':
592 if ( !User::isCreatableName( $name ) ) {
593 $name = false;
595 break;
596 default:
597 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__ );
599 return $name;
603 * Count the number of edits of a user
605 * It should not be static and some day should be merged as proper member function / deprecated -- domas
607 * @param int $uid The user ID to check
608 * @return int
609 * @static
611 static function edits( $uid ) {
612 wfProfileIn( __METHOD__ );
613 $dbr = wfGetDB( DB_SLAVE );
614 // check if the user_editcount field has been initialized
615 $field = $dbr->selectField(
616 'user', 'user_editcount',
617 array( 'user_id' => $uid ),
618 __METHOD__
621 if( $field === null ) { // it has not been initialized. do so.
622 $dbw = wfGetDB( DB_MASTER );
623 $count = $dbr->selectField(
624 'revision', 'count(*)',
625 array( 'rev_user' => $uid ),
626 __METHOD__
628 $dbw->update(
629 'user',
630 array( 'user_editcount' => $count ),
631 array( 'user_id' => $uid ),
632 __METHOD__
634 } else {
635 $count = $field;
637 wfProfileOut( __METHOD__ );
638 return $count;
642 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
643 * @todo hash random numbers to improve security, like generateToken()
645 * @return string
646 * @static
648 static function randomPassword() {
649 global $wgMinimalPasswordLength;
650 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
651 $l = strlen( $pwchars ) - 1;
653 $pwlength = max( 7, $wgMinimalPasswordLength );
654 $digit = mt_rand(0, $pwlength - 1);
655 $np = '';
656 for ( $i = 0; $i < $pwlength; $i++ ) {
657 $np .= $i == $digit ? chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
659 return $np;
663 * Set cached properties to default. Note: this no longer clears
664 * uncached lazy-initialised properties. The constructor does that instead.
666 * @private
668 function loadDefaults( $name = false ) {
669 wfProfileIn( __METHOD__ );
671 global $wgCookiePrefix;
673 $this->mId = 0;
674 $this->mName = $name;
675 $this->mRealName = '';
676 $this->mPassword = $this->mNewpassword = '';
677 $this->mNewpassTime = null;
678 $this->mEmail = '';
679 $this->mOptions = null; # Defer init
681 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
682 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
683 } else {
684 $this->mTouched = '0'; # Allow any pages to be cached
687 $this->setToken(); # Random
688 $this->mEmailAuthenticated = null;
689 $this->mEmailToken = '';
690 $this->mEmailTokenExpires = null;
691 $this->mRegistration = wfTimestamp( TS_MW );
692 $this->mGroups = array();
694 wfProfileOut( __METHOD__ );
698 * Initialise php session
699 * @deprecated use wfSetupSession()
701 function SetupSession() {
702 wfDeprecated( __METHOD__ );
703 wfSetupSession();
707 * Load user data from the session or login cookie. If there are no valid
708 * credentials, initialises the user as an anon.
709 * @return true if the user is logged in, false otherwise
711 private function loadFromSession() {
712 global $wgMemc, $wgCookiePrefix;
714 if ( isset( $_SESSION['wsUserID'] ) ) {
715 if ( 0 != $_SESSION['wsUserID'] ) {
716 $sId = $_SESSION['wsUserID'];
717 } else {
718 $this->loadDefaults();
719 return false;
721 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
722 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
723 $_SESSION['wsUserID'] = $sId;
724 } else {
725 $this->loadDefaults();
726 return false;
728 if ( isset( $_SESSION['wsUserName'] ) ) {
729 $sName = $_SESSION['wsUserName'];
730 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
731 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
732 $_SESSION['wsUserName'] = $sName;
733 } else {
734 $this->loadDefaults();
735 return false;
738 $passwordCorrect = FALSE;
739 $this->mId = $sId;
740 if ( !$this->loadFromId() ) {
741 # Not a valid ID, loadFromId has switched the object to anon for us
742 return false;
745 if ( isset( $_SESSION['wsToken'] ) ) {
746 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
747 $from = 'session';
748 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
749 $passwordCorrect = $this->mToken == $_COOKIE["{$wgCookiePrefix}Token"];
750 $from = 'cookie';
751 } else {
752 # No session or persistent login cookie
753 $this->loadDefaults();
754 return false;
757 if ( ( $sName == $this->mName ) && $passwordCorrect ) {
758 $_SESSION['wsToken'] = $this->mToken;
759 wfDebug( "Logged in from $from\n" );
760 return true;
761 } else {
762 # Invalid credentials
763 wfDebug( "Can't log in from $from, invalid credentials\n" );
764 $this->loadDefaults();
765 return false;
770 * Load user and user_group data from the database
771 * $this->mId must be set, this is how the user is identified.
773 * @return true if the user exists, false if the user is anonymous
774 * @private
776 function loadFromDatabase() {
777 # Paranoia
778 $this->mId = intval( $this->mId );
780 /** Anonymous user */
781 if( !$this->mId ) {
782 $this->loadDefaults();
783 return false;
786 $dbr = wfGetDB( DB_MASTER );
787 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
789 if ( $s !== false ) {
790 # Initialise user table data
791 $this->mName = $s->user_name;
792 $this->mRealName = $s->user_real_name;
793 $this->mPassword = $s->user_password;
794 $this->mNewpassword = $s->user_newpassword;
795 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $s->user_newpass_time );
796 $this->mEmail = $s->user_email;
797 $this->decodeOptions( $s->user_options );
798 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
799 $this->mToken = $s->user_token;
800 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $s->user_email_authenticated );
801 $this->mEmailToken = $s->user_email_token;
802 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $s->user_email_token_expires );
803 $this->mRegistration = wfTimestampOrNull( TS_MW, $s->user_registration );
804 $this->mEditCount = $s->user_editcount;
805 $this->getEditCount(); // revalidation for nulls
807 # Load group data
808 $res = $dbr->select( 'user_groups',
809 array( 'ug_group' ),
810 array( 'ug_user' => $this->mId ),
811 __METHOD__ );
812 $this->mGroups = array();
813 while( $row = $dbr->fetchObject( $res ) ) {
814 $this->mGroups[] = $row->ug_group;
816 return true;
817 } else {
818 # Invalid user_id
819 $this->mId = 0;
820 $this->loadDefaults();
821 return false;
826 * Clear various cached data stored in this object.
827 * @param string $reloadFrom Reload user and user_groups table data from a
828 * given source. May be "name", "id", "defaults", "session" or false for
829 * no reload.
831 function clearInstanceCache( $reloadFrom = false ) {
832 $this->mNewtalk = -1;
833 $this->mDatePreference = null;
834 $this->mBlockedby = -1; # Unset
835 $this->mHash = false;
836 $this->mSkin = null;
837 $this->mRights = null;
838 $this->mEffectiveGroups = null;
840 if ( $reloadFrom ) {
841 $this->mDataLoaded = false;
842 $this->mFrom = $reloadFrom;
847 * Combine the language default options with any site-specific options
848 * and add the default language variants.
849 * Not really private cause it's called by Language class
850 * @return array
851 * @static
852 * @private
854 static function getDefaultOptions() {
855 global $wgNamespacesToBeSearchedDefault;
857 * Site defaults will override the global/language defaults
859 global $wgDefaultUserOptions, $wgContLang;
860 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
863 * default language setting
865 $variant = $wgContLang->getPreferredVariant( false );
866 $defOpt['variant'] = $variant;
867 $defOpt['language'] = $variant;
869 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
870 $defOpt['searchNs'.$nsnum] = $val;
872 return $defOpt;
876 * Get a given default option value.
878 * @param string $opt
879 * @return string
880 * @static
881 * @public
883 function getDefaultOption( $opt ) {
884 $defOpts = User::getDefaultOptions();
885 if( isset( $defOpts[$opt] ) ) {
886 return $defOpts[$opt];
887 } else {
888 return '';
893 * Get a list of user toggle names
894 * @return array
896 static function getToggles() {
897 global $wgContLang;
898 $extraToggles = array();
899 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
900 return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
905 * Get blocking information
906 * @private
907 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
908 * non-critical checks are done against slaves. Check when actually saving should be done against
909 * master.
911 function getBlockedStatus( $bFromSlave = true ) {
912 global $wgEnableSorbs, $wgProxyWhitelist;
914 if ( -1 != $this->mBlockedby ) {
915 wfDebug( "User::getBlockedStatus: already loaded.\n" );
916 return;
919 wfProfileIn( __METHOD__ );
920 wfDebug( __METHOD__.": checking...\n" );
922 $this->mBlockedby = 0;
923 $this->mHideName = 0;
924 $ip = wfGetIP();
926 if ($this->isAllowed( 'ipblock-exempt' ) ) {
927 # Exempt from all types of IP-block
928 $ip = '';
931 # User/IP blocking
932 $this->mBlock = new Block();
933 $this->mBlock->fromMaster( !$bFromSlave );
934 if ( $this->mBlock->load( $ip , $this->mId ) ) {
935 wfDebug( __METHOD__.": Found block.\n" );
936 $this->mBlockedby = $this->mBlock->mBy;
937 $this->mBlockreason = $this->mBlock->mReason;
938 $this->mHideName = $this->mBlock->mHideName;
939 if ( $this->isLoggedIn() ) {
940 $this->spreadBlock();
942 } else {
943 $this->mBlock = null;
944 wfDebug( __METHOD__.": No block.\n" );
947 # Proxy blocking
948 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
950 # Local list
951 if ( wfIsLocallyBlockedProxy( $ip ) ) {
952 $this->mBlockedby = wfMsg( 'proxyblocker' );
953 $this->mBlockreason = wfMsg( 'proxyblockreason' );
956 # DNSBL
957 if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
958 if ( $this->inSorbsBlacklist( $ip ) ) {
959 $this->mBlockedby = wfMsg( 'sorbs' );
960 $this->mBlockreason = wfMsg( 'sorbsreason' );
965 # Extensions
966 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
968 wfProfileOut( __METHOD__ );
971 function inSorbsBlacklist( $ip ) {
972 global $wgEnableSorbs, $wgSorbsUrl;
974 return $wgEnableSorbs &&
975 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
978 function inDnsBlacklist( $ip, $base ) {
979 wfProfileIn( __METHOD__ );
981 $found = false;
982 $host = '';
984 $m = array();
985 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
986 # Make hostname
987 for ( $i=4; $i>=1; $i-- ) {
988 $host .= $m[$i] . '.';
990 $host .= $base;
992 # Send query
993 $ipList = gethostbynamel( $host );
995 if ( $ipList ) {
996 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
997 $found = true;
998 } else {
999 wfDebug( "Requested $host, not found in $base.\n" );
1003 wfProfileOut( __METHOD__ );
1004 return $found;
1008 * Is this user subject to rate limiting?
1010 * @return bool
1012 public function isPingLimitable() {
1013 global $wgRateLimitsExcludedGroups;
1014 return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) == array();
1018 * Primitive rate limits: enforce maximum actions per time period
1019 * to put a brake on flooding.
1021 * Note: when using a shared cache like memcached, IP-address
1022 * last-hit counters will be shared across wikis.
1024 * @return bool true if a rate limiter was tripped
1025 * @public
1027 function pingLimiter( $action='edit' ) {
1029 # Call the 'PingLimiter' hook
1030 $result = false;
1031 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1032 return $result;
1035 global $wgRateLimits;
1036 if( !isset( $wgRateLimits[$action] ) ) {
1037 return false;
1040 # Some groups shouldn't trigger the ping limiter, ever
1041 if( !$this->isPingLimitable() )
1042 return false;
1044 global $wgMemc, $wgRateLimitLog;
1045 wfProfileIn( __METHOD__ );
1047 $limits = $wgRateLimits[$action];
1048 $keys = array();
1049 $id = $this->getId();
1050 $ip = wfGetIP();
1052 if( isset( $limits['anon'] ) && $id == 0 ) {
1053 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1056 if( isset( $limits['user'] ) && $id != 0 ) {
1057 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
1059 if( $this->isNewbie() ) {
1060 if( isset( $limits['newbie'] ) && $id != 0 ) {
1061 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1063 if( isset( $limits['ip'] ) ) {
1064 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1066 $matches = array();
1067 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1068 $subnet = $matches[1];
1069 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1073 $triggered = false;
1074 foreach( $keys as $key => $limit ) {
1075 list( $max, $period ) = $limit;
1076 $summary = "(limit $max in {$period}s)";
1077 $count = $wgMemc->get( $key );
1078 if( $count ) {
1079 if( $count > $max ) {
1080 wfDebug( __METHOD__.": tripped! $key at $count $summary\n" );
1081 if( $wgRateLimitLog ) {
1082 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1084 $triggered = true;
1085 } else {
1086 wfDebug( __METHOD__.": ok. $key at $count $summary\n" );
1088 } else {
1089 wfDebug( __METHOD__.": adding record for $key $summary\n" );
1090 $wgMemc->add( $key, 1, intval( $period ) );
1092 $wgMemc->incr( $key );
1095 wfProfileOut( __METHOD__ );
1096 return $triggered;
1100 * Check if user is blocked
1101 * @return bool True if blocked, false otherwise
1103 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1104 wfDebug( "User::isBlocked: enter\n" );
1105 $this->getBlockedStatus( $bFromSlave );
1106 return $this->mBlockedby !== 0;
1110 * Check if user is blocked from editing a particular article
1112 function isBlockedFrom( $title, $bFromSlave = false ) {
1113 global $wgBlockAllowsUTEdit;
1114 wfProfileIn( __METHOD__ );
1115 wfDebug( __METHOD__.": enter\n" );
1117 wfDebug( __METHOD__.": asking isBlocked()\n" );
1118 $blocked = $this->isBlocked( $bFromSlave );
1119 # If a user's name is suppressed, they cannot make edits anywhere
1120 if ( !$this->mHideName && $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1121 $title->getNamespace() == NS_USER_TALK ) {
1122 $blocked = false;
1123 wfDebug( __METHOD__.": self-talk page, ignoring any blocks\n" );
1125 wfProfileOut( __METHOD__ );
1126 return $blocked;
1130 * Get name of blocker
1131 * @return string name of blocker
1133 function blockedBy() {
1134 $this->getBlockedStatus();
1135 return $this->mBlockedby;
1139 * Get blocking reason
1140 * @return string Blocking reason
1142 function blockedFor() {
1143 $this->getBlockedStatus();
1144 return $this->mBlockreason;
1148 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1150 function getID() {
1151 if( $this->mId === null and $this->mName !== null
1152 and User::isIP( $this->mName ) ) {
1153 // Special case, we know the user is anonymous
1154 return 0;
1155 } elseif( $this->mId === null ) {
1156 // Don't load if this was initialized from an ID
1157 $this->load();
1159 return $this->mId;
1163 * Set the user and reload all fields according to that ID
1164 * @deprecated use User::newFromId()
1166 function setID( $v ) {
1167 wfDeprecated( __METHOD__ );
1168 $this->mId = $v;
1169 $this->clearInstanceCache( 'id' );
1173 * Get the user name, or the IP for anons
1175 function getName() {
1176 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1177 # Special case optimisation
1178 return $this->mName;
1179 } else {
1180 $this->load();
1181 if ( $this->mName === false ) {
1182 # Clean up IPs
1183 $this->mName = IP::sanitizeIP( wfGetIP() );
1185 return $this->mName;
1190 * Set the user name.
1192 * This does not reload fields from the database according to the given
1193 * name. Rather, it is used to create a temporary "nonexistent user" for
1194 * later addition to the database. It can also be used to set the IP
1195 * address for an anonymous user to something other than the current
1196 * remote IP.
1198 * User::newFromName() has rougly the same function, when the named user
1199 * does not exist.
1201 function setName( $str ) {
1202 $this->load();
1203 $this->mName = $str;
1207 * Return the title dbkey form of the name, for eg user pages.
1208 * @return string
1209 * @public
1211 function getTitleKey() {
1212 return str_replace( ' ', '_', $this->getName() );
1215 function getNewtalk() {
1216 $this->load();
1218 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1219 if( $this->mNewtalk === -1 ) {
1220 $this->mNewtalk = false; # reset talk page status
1222 # Check memcached separately for anons, who have no
1223 # entire User object stored in there.
1224 if( !$this->mId ) {
1225 global $wgMemc;
1226 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1227 $newtalk = $wgMemc->get( $key );
1228 if( strval( $newtalk ) !== '' ) {
1229 $this->mNewtalk = (bool)$newtalk;
1230 } else {
1231 // Since we are caching this, make sure it is up to date by getting it
1232 // from the master
1233 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1234 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1236 } else {
1237 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1241 return (bool)$this->mNewtalk;
1245 * Return the talk page(s) this user has new messages on.
1247 function getNewMessageLinks() {
1248 $talks = array();
1249 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1250 return $talks;
1252 if (!$this->getNewtalk())
1253 return array();
1254 $up = $this->getUserPage();
1255 $utp = $up->getTalkPage();
1256 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1261 * Perform a user_newtalk check, uncached.
1262 * Use getNewtalk for a cached check.
1264 * @param string $field
1265 * @param mixed $id
1266 * @param bool $fromMaster True to fetch from the master, false for a slave
1267 * @return bool
1268 * @private
1270 function checkNewtalk( $field, $id, $fromMaster = false ) {
1271 if ( $fromMaster ) {
1272 $db = wfGetDB( DB_MASTER );
1273 } else {
1274 $db = wfGetDB( DB_SLAVE );
1276 $ok = $db->selectField( 'user_newtalk', $field,
1277 array( $field => $id ), __METHOD__ );
1278 return $ok !== false;
1282 * Add or update the
1283 * @param string $field
1284 * @param mixed $id
1285 * @private
1287 function updateNewtalk( $field, $id ) {
1288 $dbw = wfGetDB( DB_MASTER );
1289 $dbw->insert( 'user_newtalk',
1290 array( $field => $id ),
1291 __METHOD__,
1292 'IGNORE' );
1293 if ( $dbw->affectedRows() ) {
1294 wfDebug( __METHOD__.": set on ($field, $id)\n" );
1295 return true;
1296 } else {
1297 wfDebug( __METHOD__." already set ($field, $id)\n" );
1298 return false;
1303 * Clear the new messages flag for the given user
1304 * @param string $field
1305 * @param mixed $id
1306 * @private
1308 function deleteNewtalk( $field, $id ) {
1309 $dbw = wfGetDB( DB_MASTER );
1310 $dbw->delete( 'user_newtalk',
1311 array( $field => $id ),
1312 __METHOD__ );
1313 if ( $dbw->affectedRows() ) {
1314 wfDebug( __METHOD__.": killed on ($field, $id)\n" );
1315 return true;
1316 } else {
1317 wfDebug( __METHOD__.": already gone ($field, $id)\n" );
1318 return false;
1323 * Update the 'You have new messages!' status.
1324 * @param bool $val
1326 function setNewtalk( $val ) {
1327 if( wfReadOnly() ) {
1328 return;
1331 $this->load();
1332 $this->mNewtalk = $val;
1334 if( $this->isAnon() ) {
1335 $field = 'user_ip';
1336 $id = $this->getName();
1337 } else {
1338 $field = 'user_id';
1339 $id = $this->getId();
1341 global $wgMemc;
1343 if( $val ) {
1344 $changed = $this->updateNewtalk( $field, $id );
1345 } else {
1346 $changed = $this->deleteNewtalk( $field, $id );
1349 if( $this->isAnon() ) {
1350 // Anons have a separate memcached space, since
1351 // user records aren't kept for them.
1352 $key = wfMemcKey( 'newtalk', 'ip', $id );
1353 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1355 if ( $changed ) {
1356 $this->invalidateCache();
1361 * Generate a current or new-future timestamp to be stored in the
1362 * user_touched field when we update things.
1364 private static function newTouchedTimestamp() {
1365 global $wgClockSkewFudge;
1366 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1370 * Clear user data from memcached.
1371 * Use after applying fun updates to the database; caller's
1372 * responsibility to update user_touched if appropriate.
1374 * Called implicitly from invalidateCache() and saveSettings().
1376 private function clearSharedCache() {
1377 if( $this->mId ) {
1378 global $wgMemc;
1379 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1384 * Immediately touch the user data cache for this account.
1385 * Updates user_touched field, and removes account data from memcached
1386 * for reload on the next hit.
1388 function invalidateCache() {
1389 $this->load();
1390 if( $this->mId ) {
1391 $this->mTouched = self::newTouchedTimestamp();
1393 $dbw = wfGetDB( DB_MASTER );
1394 $dbw->update( 'user',
1395 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1396 array( 'user_id' => $this->mId ),
1397 __METHOD__ );
1399 $this->clearSharedCache();
1403 function validateCache( $timestamp ) {
1404 $this->load();
1405 return ($timestamp >= $this->mTouched);
1409 * Encrypt a password.
1410 * It can eventually salt a password.
1411 * @see User::addSalt()
1412 * @param string $p clear Password.
1413 * @return string Encrypted password.
1415 function encryptPassword( $p ) {
1416 $this->load();
1417 return wfEncryptPassword( $this->mId, $p );
1421 * Set the password and reset the random token
1422 * Calls through to authentication plugin if necessary;
1423 * will have no effect if the auth plugin refuses to
1424 * pass the change through or if the legal password
1425 * checks fail.
1427 * As a special case, setting the password to null
1428 * wipes it, so the account cannot be logged in until
1429 * a new password is set, for instance via e-mail.
1431 * @param string $str
1432 * @throws PasswordError on failure
1434 function setPassword( $str ) {
1435 global $wgAuth;
1437 if( $str !== null ) {
1438 if( !$wgAuth->allowPasswordChange() ) {
1439 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1442 if( !$this->isValidPassword( $str ) ) {
1443 global $wgMinimalPasswordLength;
1444 throw new PasswordError( wfMsg( 'passwordtooshort',
1445 $wgMinimalPasswordLength ) );
1449 if( !$wgAuth->setPassword( $this, $str ) ) {
1450 throw new PasswordError( wfMsg( 'externaldberror' ) );
1453 $this->setInternalPassword( $str );
1455 return true;
1459 * Set the password and reset the random token no matter
1460 * what.
1462 * @param string $str
1464 function setInternalPassword( $str ) {
1465 $this->load();
1466 $this->setToken();
1468 if( $str === null ) {
1469 // Save an invalid hash...
1470 $this->mPassword = '';
1471 } else {
1472 $this->mPassword = $this->encryptPassword( $str );
1474 $this->mNewpassword = '';
1475 $this->mNewpassTime = null;
1478 * Set the random token (used for persistent authentication)
1479 * Called from loadDefaults() among other places.
1480 * @private
1482 function setToken( $token = false ) {
1483 global $wgSecretKey, $wgProxyKey;
1484 $this->load();
1485 if ( !$token ) {
1486 if ( $wgSecretKey ) {
1487 $key = $wgSecretKey;
1488 } elseif ( $wgProxyKey ) {
1489 $key = $wgProxyKey;
1490 } else {
1491 $key = microtime();
1493 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1494 } else {
1495 $this->mToken = $token;
1499 function setCookiePassword( $str ) {
1500 $this->load();
1501 $this->mCookiePassword = md5( $str );
1505 * Set the password for a password reminder or new account email
1506 * Sets the user_newpass_time field if $throttle is true
1508 function setNewpassword( $str, $throttle = true ) {
1509 $this->load();
1510 $this->mNewpassword = $this->encryptPassword( $str );
1511 if ( $throttle ) {
1512 $this->mNewpassTime = wfTimestampNow();
1517 * Returns true if a password reminder email has already been sent within
1518 * the last $wgPasswordReminderResendTime hours
1520 function isPasswordReminderThrottled() {
1521 global $wgPasswordReminderResendTime;
1522 $this->load();
1523 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1524 return false;
1526 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1527 return time() < $expiry;
1530 function getEmail() {
1531 $this->load();
1532 return $this->mEmail;
1535 function getEmailAuthenticationTimestamp() {
1536 $this->load();
1537 return $this->mEmailAuthenticated;
1540 function setEmail( $str ) {
1541 $this->load();
1542 $this->mEmail = $str;
1545 function getRealName() {
1546 $this->load();
1547 return $this->mRealName;
1550 function setRealName( $str ) {
1551 $this->load();
1552 $this->mRealName = $str;
1556 * @param string $oname The option to check
1557 * @param string $defaultOverride A default value returned if the option does not exist
1558 * @return string
1560 function getOption( $oname, $defaultOverride = '' ) {
1561 $this->load();
1563 if ( is_null( $this->mOptions ) ) {
1564 if($defaultOverride != '') {
1565 return $defaultOverride;
1567 $this->mOptions = User::getDefaultOptions();
1570 if ( array_key_exists( $oname, $this->mOptions ) ) {
1571 return trim( $this->mOptions[$oname] );
1572 } else {
1573 return $defaultOverride;
1578 * Get the user's date preference, including some important migration for
1579 * old user rows.
1581 function getDatePreference() {
1582 if ( is_null( $this->mDatePreference ) ) {
1583 global $wgLang;
1584 $value = $this->getOption( 'date' );
1585 $map = $wgLang->getDatePreferenceMigrationMap();
1586 if ( isset( $map[$value] ) ) {
1587 $value = $map[$value];
1589 $this->mDatePreference = $value;
1591 return $this->mDatePreference;
1595 * @param string $oname The option to check
1596 * @return bool False if the option is not selected, true if it is
1598 function getBoolOption( $oname ) {
1599 return (bool)$this->getOption( $oname );
1603 * Get an option as an integer value from the source string.
1604 * @param string $oname The option to check
1605 * @param int $default Optional value to return if option is unset/blank.
1606 * @return int
1608 function getIntOption( $oname, $default=0 ) {
1609 $val = $this->getOption( $oname );
1610 if( $val == '' ) {
1611 $val = $default;
1613 return intval( $val );
1616 function setOption( $oname, $val ) {
1617 $this->load();
1618 if ( is_null( $this->mOptions ) ) {
1619 $this->mOptions = User::getDefaultOptions();
1621 if ( $oname == 'skin' ) {
1622 # Clear cached skin, so the new one displays immediately in Special:Preferences
1623 unset( $this->mSkin );
1625 // Filter out any newlines that may have passed through input validation.
1626 // Newlines are used to separate items in the options blob.
1627 $val = str_replace( "\r\n", "\n", $val );
1628 $val = str_replace( "\r", "\n", $val );
1629 $val = str_replace( "\n", " ", $val );
1630 $this->mOptions[$oname] = $val;
1633 function getRights() {
1634 if ( is_null( $this->mRights ) ) {
1635 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
1636 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
1638 return $this->mRights;
1642 * Get the list of explicit group memberships this user has.
1643 * The implicit * and user groups are not included.
1644 * @return array of strings
1646 function getGroups() {
1647 $this->load();
1648 return $this->mGroups;
1652 * Get the list of implicit group memberships this user has.
1653 * This includes all explicit groups, plus 'user' if logged in,
1654 * '*' for all accounts and autopromoted groups
1655 * @param boolean $recache Don't use the cache
1656 * @return array of strings
1658 function getEffectiveGroups( $recache = false ) {
1659 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
1660 $this->load();
1661 $this->mEffectiveGroups = $this->mGroups;
1662 $this->mEffectiveGroups[] = '*';
1663 if( $this->mId ) {
1664 $this->mEffectiveGroups[] = 'user';
1666 $this->mEffectiveGroups = array_unique( array_merge(
1667 $this->mEffectiveGroups,
1668 Autopromote::getAutopromoteGroups( $this )
1669 ) );
1671 # Hook for additional groups
1672 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
1675 return $this->mEffectiveGroups;
1678 /* Return the edit count for the user. This is where User::edits should have been */
1679 function getEditCount() {
1680 if ($this->mId) {
1681 if ( !isset( $this->mEditCount ) ) {
1682 /* Populate the count, if it has not been populated yet */
1683 $this->mEditCount = User::edits($this->mId);
1685 return $this->mEditCount;
1686 } else {
1687 /* nil */
1688 return null;
1693 * Add the user to the given group.
1694 * This takes immediate effect.
1695 * @param string $group
1697 function addGroup( $group ) {
1698 $this->load();
1699 $dbw = wfGetDB( DB_MASTER );
1700 if( $this->getId() ) {
1701 $dbw->insert( 'user_groups',
1702 array(
1703 'ug_user' => $this->getID(),
1704 'ug_group' => $group,
1706 'User::addGroup',
1707 array( 'IGNORE' ) );
1710 $this->mGroups[] = $group;
1711 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1713 $this->invalidateCache();
1717 * Remove the user from the given group.
1718 * This takes immediate effect.
1719 * @param string $group
1721 function removeGroup( $group ) {
1722 $this->load();
1723 $dbw = wfGetDB( DB_MASTER );
1724 $dbw->delete( 'user_groups',
1725 array(
1726 'ug_user' => $this->getID(),
1727 'ug_group' => $group,
1729 'User::removeGroup' );
1731 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
1732 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1734 $this->invalidateCache();
1739 * A more legible check for non-anonymousness.
1740 * Returns true if the user is not an anonymous visitor.
1742 * @return bool
1744 function isLoggedIn() {
1745 return $this->getID() != 0;
1749 * A more legible check for anonymousness.
1750 * Returns true if the user is an anonymous visitor.
1752 * @return bool
1754 function isAnon() {
1755 return !$this->isLoggedIn();
1759 * Whether the user is a bot
1760 * @deprecated
1762 function isBot() {
1763 wfDeprecated( __METHOD__ );
1764 return $this->isAllowed( 'bot' );
1768 * Check if user is allowed to access a feature / make an action
1769 * @param string $action Action to be checked
1770 * @return boolean True: action is allowed, False: action should not be allowed
1772 function isAllowed($action='') {
1773 if ( $action === '' )
1774 // In the spirit of DWIM
1775 return true;
1777 return in_array( $action, $this->getRights() );
1781 * Load a skin if it doesn't exist or return it
1782 * @todo FIXME : need to check the old failback system [AV]
1784 function &getSkin() {
1785 global $wgRequest;
1786 if ( ! isset( $this->mSkin ) ) {
1787 wfProfileIn( __METHOD__ );
1789 # get the user skin
1790 $userSkin = $this->getOption( 'skin' );
1791 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1793 $this->mSkin =& Skin::newFromKey( $userSkin );
1794 wfProfileOut( __METHOD__ );
1796 return $this->mSkin;
1799 /**#@+
1800 * @param string $title Article title to look at
1804 * Check watched status of an article
1805 * @return bool True if article is watched
1807 function isWatched( $title ) {
1808 $wl = WatchedItem::fromUserTitle( $this, $title );
1809 return $wl->isWatched();
1813 * Watch an article
1815 function addWatch( $title ) {
1816 $wl = WatchedItem::fromUserTitle( $this, $title );
1817 $wl->addWatch();
1818 $this->invalidateCache();
1822 * Stop watching an article
1824 function removeWatch( $title ) {
1825 $wl = WatchedItem::fromUserTitle( $this, $title );
1826 $wl->removeWatch();
1827 $this->invalidateCache();
1831 * Clear the user's notification timestamp for the given title.
1832 * If e-notif e-mails are on, they will receive notification mails on
1833 * the next change of the page if it's watched etc.
1835 function clearNotification( &$title ) {
1836 global $wgUser, $wgUseEnotif;
1838 # Do nothing if the database is locked to writes
1839 if( wfReadOnly() ) {
1840 return;
1843 if ($title->getNamespace() == NS_USER_TALK &&
1844 $title->getText() == $this->getName() ) {
1845 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1846 return;
1847 $this->setNewtalk( false );
1850 if( !$wgUseEnotif ) {
1851 return;
1854 if( $this->isAnon() ) {
1855 // Nothing else to do...
1856 return;
1859 // Only update the timestamp if the page is being watched.
1860 // The query to find out if it is watched is cached both in memcached and per-invocation,
1861 // and when it does have to be executed, it can be on a slave
1862 // If this is the user's newtalk page, we always update the timestamp
1863 if ($title->getNamespace() == NS_USER_TALK &&
1864 $title->getText() == $wgUser->getName())
1866 $watched = true;
1867 } elseif ( $this->getID() == $wgUser->getID() ) {
1868 $watched = $title->userIsWatching();
1869 } else {
1870 $watched = true;
1873 // If the page is watched by the user (or may be watched), update the timestamp on any
1874 // any matching rows
1875 if ( $watched ) {
1876 $dbw = wfGetDB( DB_MASTER );
1877 $dbw->update( 'watchlist',
1878 array( /* SET */
1879 'wl_notificationtimestamp' => NULL
1880 ), array( /* WHERE */
1881 'wl_title' => $title->getDBkey(),
1882 'wl_namespace' => $title->getNamespace(),
1883 'wl_user' => $this->getID()
1884 ), 'User::clearLastVisited'
1889 /**#@-*/
1892 * Resets all of the given user's page-change notification timestamps.
1893 * If e-notif e-mails are on, they will receive notification mails on
1894 * the next change of any watched page.
1896 * @param int $currentUser user ID number
1897 * @public
1899 function clearAllNotifications( $currentUser ) {
1900 global $wgUseEnotif;
1901 if ( !$wgUseEnotif ) {
1902 $this->setNewtalk( false );
1903 return;
1905 if( $currentUser != 0 ) {
1907 $dbw = wfGetDB( DB_MASTER );
1908 $dbw->update( 'watchlist',
1909 array( /* SET */
1910 'wl_notificationtimestamp' => NULL
1911 ), array( /* WHERE */
1912 'wl_user' => $currentUser
1913 ), __METHOD__
1916 # we also need to clear here the "you have new message" notification for the own user_talk page
1917 # This is cleared one page view later in Article::viewUpdates();
1922 * @private
1923 * @return string Encoding options
1925 function encodeOptions() {
1926 $this->load();
1927 if ( is_null( $this->mOptions ) ) {
1928 $this->mOptions = User::getDefaultOptions();
1930 $a = array();
1931 foreach ( $this->mOptions as $oname => $oval ) {
1932 array_push( $a, $oname.'='.$oval );
1934 $s = implode( "\n", $a );
1935 return $s;
1939 * @private
1941 function decodeOptions( $str ) {
1942 $this->mOptions = array();
1943 $a = explode( "\n", $str );
1944 foreach ( $a as $s ) {
1945 $m = array();
1946 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1947 $this->mOptions[$m[1]] = $m[2];
1952 function setCookies() {
1953 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1954 $this->load();
1955 if ( 0 == $this->mId ) return;
1956 $exp = time() + $wgCookieExpiration;
1958 $_SESSION['wsUserID'] = $this->mId;
1959 setcookie( $wgCookiePrefix.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1961 $_SESSION['wsUserName'] = $this->getName();
1962 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1964 $_SESSION['wsToken'] = $this->mToken;
1965 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1966 setcookie( $wgCookiePrefix.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1967 } else {
1968 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1973 * Logout user.
1975 function logout() {
1976 global $wgUser;
1977 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
1978 $this->doLogout();
1979 wfRunHooks( 'UserLogoutComplete', array(&$wgUser) );
1984 * Really logout user
1985 * Clears the cookies and session, resets the instance cache
1987 function doLogout() {
1988 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1989 $this->clearInstanceCache( 'defaults' );
1991 $_SESSION['wsUserID'] = 0;
1993 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1994 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1996 # Remember when user logged out, to prevent seeing cached pages
1997 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2001 * Save object settings into database
2002 * @todo Only rarely do all these fields need to be set!
2004 function saveSettings() {
2005 $this->load();
2006 if ( wfReadOnly() ) { return; }
2007 if ( 0 == $this->mId ) { return; }
2009 $this->mTouched = self::newTouchedTimestamp();
2011 $dbw = wfGetDB( DB_MASTER );
2012 $dbw->update( 'user',
2013 array( /* SET */
2014 'user_name' => $this->mName,
2015 'user_password' => $this->mPassword,
2016 'user_newpassword' => $this->mNewpassword,
2017 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2018 'user_real_name' => $this->mRealName,
2019 'user_email' => $this->mEmail,
2020 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2021 'user_options' => $this->encodeOptions(),
2022 'user_touched' => $dbw->timestamp($this->mTouched),
2023 'user_token' => $this->mToken
2024 ), array( /* WHERE */
2025 'user_id' => $this->mId
2026 ), __METHOD__
2028 $this->clearSharedCache();
2033 * Checks if a user with the given name exists, returns the ID.
2035 function idForName() {
2036 $s = trim( $this->getName() );
2037 if ( $s === '' ) return 0;
2039 $dbr = wfGetDB( DB_SLAVE );
2040 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2041 if ( $id === false ) {
2042 $id = 0;
2044 return $id;
2048 * Add a user to the database, return the user object
2050 * @param string $name The user's name
2051 * @param array $params Associative array of non-default parameters to save to the database:
2052 * password The user's password. Password logins will be disabled if this is omitted.
2053 * newpassword A temporary password mailed to the user
2054 * email The user's email address
2055 * email_authenticated The email authentication timestamp
2056 * real_name The user's real name
2057 * options An associative array of non-default options
2058 * token Random authentication token. Do not set.
2059 * registration Registration timestamp. Do not set.
2061 * @return User object, or null if the username already exists
2063 static function createNew( $name, $params = array() ) {
2064 $user = new User;
2065 $user->load();
2066 if ( isset( $params['options'] ) ) {
2067 $user->mOptions = $params['options'] + $user->mOptions;
2068 unset( $params['options'] );
2070 $dbw = wfGetDB( DB_MASTER );
2071 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2072 $fields = array(
2073 'user_id' => $seqVal,
2074 'user_name' => $name,
2075 'user_password' => $user->mPassword,
2076 'user_newpassword' => $user->mNewpassword,
2077 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ),
2078 'user_email' => $user->mEmail,
2079 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2080 'user_real_name' => $user->mRealName,
2081 'user_options' => $user->encodeOptions(),
2082 'user_token' => $user->mToken,
2083 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2084 'user_editcount' => 0,
2086 foreach ( $params as $name => $value ) {
2087 $fields["user_$name"] = $value;
2089 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2090 if ( $dbw->affectedRows() ) {
2091 $newUser = User::newFromId( $dbw->insertId() );
2092 } else {
2093 $newUser = null;
2095 return $newUser;
2099 * Add an existing user object to the database
2101 function addToDatabase() {
2102 $this->load();
2103 $dbw = wfGetDB( DB_MASTER );
2104 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2105 $dbw->insert( 'user',
2106 array(
2107 'user_id' => $seqVal,
2108 'user_name' => $this->mName,
2109 'user_password' => $this->mPassword,
2110 'user_newpassword' => $this->mNewpassword,
2111 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ),
2112 'user_email' => $this->mEmail,
2113 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2114 'user_real_name' => $this->mRealName,
2115 'user_options' => $this->encodeOptions(),
2116 'user_token' => $this->mToken,
2117 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2118 'user_editcount' => 0,
2119 ), __METHOD__
2121 $this->mId = $dbw->insertId();
2123 # Clear instance cache other than user table data, which is already accurate
2124 $this->clearInstanceCache();
2128 * If the (non-anonymous) user is blocked, this function will block any IP address
2129 * that they successfully log on from.
2131 function spreadBlock() {
2132 wfDebug( __METHOD__."()\n" );
2133 $this->load();
2134 if ( $this->mId == 0 ) {
2135 return;
2138 $userblock = Block::newFromDB( '', $this->mId );
2139 if ( !$userblock ) {
2140 return;
2143 $userblock->doAutoblock( wfGetIp() );
2148 * Generate a string which will be different for any combination of
2149 * user options which would produce different parser output.
2150 * This will be used as part of the hash key for the parser cache,
2151 * so users will the same options can share the same cached data
2152 * safely.
2154 * Extensions which require it should install 'PageRenderingHash' hook,
2155 * which will give them a chance to modify this key based on their own
2156 * settings.
2158 * @return string
2160 function getPageRenderingHash() {
2161 global $wgContLang, $wgUseDynamicDates, $wgLang;
2162 if( $this->mHash ){
2163 return $this->mHash;
2166 // stubthreshold is only included below for completeness,
2167 // it will always be 0 when this function is called by parsercache.
2169 $confstr = $this->getOption( 'math' );
2170 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2171 if ( $wgUseDynamicDates ) {
2172 $confstr .= '!' . $this->getDatePreference();
2174 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
2175 $confstr .= '!' . $wgLang->getCode();
2176 $confstr .= '!' . $this->getOption( 'thumbsize' );
2177 // add in language specific options, if any
2178 $extra = $wgContLang->getExtraHashOptions();
2179 $confstr .= $extra;
2181 // Give a chance for extensions to modify the hash, if they have
2182 // extra options or other effects on the parser cache.
2183 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2185 // Make it a valid memcached key fragment
2186 $confstr = str_replace( ' ', '_', $confstr );
2187 $this->mHash = $confstr;
2188 return $confstr;
2191 function isBlockedFromCreateAccount() {
2192 $this->getBlockedStatus();
2193 return $this->mBlock && $this->mBlock->mCreateAccount;
2197 * Determine if the user is blocked from using Special:Emailuser.
2199 * @public
2200 * @return boolean
2202 function isBlockedFromEmailuser() {
2203 $this->getBlockedStatus();
2204 return $this->mBlock && $this->mBlock->mBlockEmail;
2207 function isAllowedToCreateAccount() {
2208 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2212 * @deprecated
2214 function setLoaded( $loaded ) {
2215 wfDeprecated( __METHOD__ );
2219 * Get this user's personal page title.
2221 * @return Title
2222 * @public
2224 function getUserPage() {
2225 return Title::makeTitle( NS_USER, $this->getName() );
2229 * Get this user's talk page title.
2231 * @return Title
2232 * @public
2234 function getTalkPage() {
2235 $title = $this->getUserPage();
2236 return $title->getTalkPage();
2240 * @static
2242 function getMaxID() {
2243 static $res; // cache
2245 if ( isset( $res ) )
2246 return $res;
2247 else {
2248 $dbr = wfGetDB( DB_SLAVE );
2249 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2254 * Determine whether the user is a newbie. Newbies are either
2255 * anonymous IPs, or the most recently created accounts.
2256 * @return bool True if it is a newbie.
2258 function isNewbie() {
2259 return !$this->isAllowed( 'autoconfirmed' );
2263 * Check to see if the given clear-text password is one of the accepted passwords
2264 * @param string $password User password.
2265 * @return bool True if the given password is correct otherwise False.
2267 function checkPassword( $password ) {
2268 global $wgAuth;
2269 $this->load();
2271 // Even though we stop people from creating passwords that
2272 // are shorter than this, doesn't mean people wont be able
2273 // to. Certain authentication plugins do NOT want to save
2274 // domain passwords in a mysql database, so we should
2275 // check this (incase $wgAuth->strict() is false).
2276 if( !$this->isValidPassword( $password ) ) {
2277 return false;
2280 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2281 return true;
2282 } elseif( $wgAuth->strict() ) {
2283 /* Auth plugin doesn't allow local authentication */
2284 return false;
2285 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2286 /* Auth plugin doesn't allow local authentication for this user name */
2287 return false;
2289 $ep = $this->encryptPassword( $password );
2290 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
2291 return true;
2292 } elseif ( function_exists( 'iconv' ) ) {
2293 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2294 # Check for this with iconv
2295 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2296 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
2297 return true;
2300 return false;
2304 * Check if the given clear-text password matches the temporary password
2305 * sent by e-mail for password reset operations.
2306 * @return bool
2308 function checkTemporaryPassword( $plaintext ) {
2309 $hash = $this->encryptPassword( $plaintext );
2310 return $hash === $this->mNewpassword;
2314 * Initialize (if necessary) and return a session token value
2315 * which can be used in edit forms to show that the user's
2316 * login credentials aren't being hijacked with a foreign form
2317 * submission.
2319 * @param mixed $salt - Optional function-specific data for hash.
2320 * Use a string or an array of strings.
2321 * @return string
2322 * @public
2324 function editToken( $salt = '' ) {
2325 if ( $this->isAnon() ) {
2326 return EDIT_TOKEN_SUFFIX;
2327 } else {
2328 if( !isset( $_SESSION['wsEditToken'] ) ) {
2329 $token = $this->generateToken();
2330 $_SESSION['wsEditToken'] = $token;
2331 } else {
2332 $token = $_SESSION['wsEditToken'];
2334 if( is_array( $salt ) ) {
2335 $salt = implode( '|', $salt );
2337 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2342 * Generate a hex-y looking random token for various uses.
2343 * Could be made more cryptographically sure if someone cares.
2344 * @return string
2346 function generateToken( $salt = '' ) {
2347 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2348 return md5( $token . $salt );
2352 * Check given value against the token value stored in the session.
2353 * A match should confirm that the form was submitted from the
2354 * user's own login session, not a form submission from a third-party
2355 * site.
2357 * @param string $val - the input value to compare
2358 * @param string $salt - Optional function-specific data for hash
2359 * @return bool
2360 * @public
2362 function matchEditToken( $val, $salt = '' ) {
2363 $sessionToken = $this->editToken( $salt );
2364 if ( $val != $sessionToken ) {
2365 wfDebug( "User::matchEditToken: broken session data\n" );
2367 return $val == $sessionToken;
2371 * Check whether the edit token is fine except for the suffix
2373 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2374 $sessionToken = $this->editToken( $salt );
2375 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2379 * Generate a new e-mail confirmation token and send a confirmation
2380 * mail to the user's given address.
2382 * @return mixed True on success, a WikiError object on failure.
2384 function sendConfirmationMail() {
2385 global $wgContLang;
2386 $expiration = null; // gets passed-by-ref and defined in next line.
2387 $url = $this->confirmationTokenUrl( $expiration );
2388 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2389 wfMsg( 'confirmemail_body',
2390 wfGetIP(),
2391 $this->getName(),
2392 $url,
2393 $wgContLang->timeanddate( $expiration, false ) ) );
2397 * Send an e-mail to this user's account. Does not check for
2398 * confirmed status or validity.
2400 * @param string $subject
2401 * @param string $body
2402 * @param string $from Optional from address; default $wgPasswordSender will be used otherwise.
2403 * @return mixed True on success, a WikiError object on failure.
2405 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2406 if( is_null( $from ) ) {
2407 global $wgPasswordSender;
2408 $from = $wgPasswordSender;
2411 $to = new MailAddress( $this );
2412 $sender = new MailAddress( $from );
2413 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2417 * Generate, store, and return a new e-mail confirmation code.
2418 * A hash (unsalted since it's used as a key) is stored.
2419 * @param &$expiration mixed output: accepts the expiration time
2420 * @return string
2421 * @private
2423 function confirmationToken( &$expiration ) {
2424 $now = time();
2425 $expires = $now + 7 * 24 * 60 * 60;
2426 $expiration = wfTimestamp( TS_MW, $expires );
2428 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
2429 $hash = md5( $token );
2431 $dbw = wfGetDB( DB_MASTER );
2432 $dbw->update( 'user',
2433 array( 'user_email_token' => $hash,
2434 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2435 array( 'user_id' => $this->mId ),
2436 __METHOD__ );
2438 return $token;
2442 * Generate and store a new e-mail confirmation token, and return
2443 * the URL the user can use to confirm.
2444 * @param &$expiration mixed output: accepts the expiration time
2445 * @return string
2446 * @private
2448 function confirmationTokenUrl( &$expiration ) {
2449 $token = $this->confirmationToken( $expiration );
2450 $title = SpecialPage::getTitleFor( 'Confirmemail', $token );
2451 return $title->getFullUrl();
2455 * Mark the e-mail address confirmed and save.
2457 function confirmEmail() {
2458 $this->load();
2459 $this->mEmailAuthenticated = wfTimestampNow();
2460 $this->saveSettings();
2461 return true;
2465 * Is this user allowed to send e-mails within limits of current
2466 * site configuration?
2467 * @return bool
2469 function canSendEmail() {
2470 $canSend = $this->isEmailConfirmed();
2471 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2472 return $canSend;
2476 * Is this user allowed to receive e-mails within limits of current
2477 * site configuration?
2478 * @return bool
2480 function canReceiveEmail() {
2481 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2485 * Is this user's e-mail address valid-looking and confirmed within
2486 * limits of the current site configuration?
2488 * If $wgEmailAuthentication is on, this may require the user to have
2489 * confirmed their address by returning a code or using a password
2490 * sent to the address from the wiki.
2492 * @return bool
2494 function isEmailConfirmed() {
2495 global $wgEmailAuthentication;
2496 $this->load();
2497 $confirmed = true;
2498 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2499 if( $this->isAnon() )
2500 return false;
2501 if( !self::isValidEmailAddr( $this->mEmail ) )
2502 return false;
2503 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2504 return false;
2505 return true;
2506 } else {
2507 return $confirmed;
2512 * Return true if there is an outstanding request for e-mail confirmation.
2513 * @return bool
2515 function isEmailConfirmationPending() {
2516 global $wgEmailAuthentication;
2517 return $wgEmailAuthentication &&
2518 !$this->isEmailConfirmed() &&
2519 $this->mEmailToken &&
2520 $this->mEmailTokenExpires > wfTimestamp();
2524 * Get the timestamp of account creation, or false for
2525 * non-existent/anonymous user accounts
2527 * @return mixed
2529 public function getRegistration() {
2530 return $this->mId > 0
2531 ? $this->mRegistration
2532 : false;
2536 * @param array $groups list of groups
2537 * @return array list of permission key names for given groups combined
2538 * @static
2540 static function getGroupPermissions( $groups ) {
2541 global $wgGroupPermissions;
2542 $rights = array();
2543 foreach( $groups as $group ) {
2544 if( isset( $wgGroupPermissions[$group] ) ) {
2545 $rights = array_merge( $rights,
2546 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2549 return $rights;
2553 * @param string $group key name
2554 * @return string localized descriptive name for group, if provided
2555 * @static
2557 static function getGroupName( $group ) {
2558 global $wgMessageCache;
2559 $wgMessageCache->loadAllMessages();
2560 $key = "group-$group";
2561 $name = wfMsg( $key );
2562 return $name == '' || wfEmptyMsg( $key, $name )
2563 ? $group
2564 : $name;
2568 * @param string $group key name
2569 * @return string localized descriptive name for member of a group, if provided
2570 * @static
2572 static function getGroupMember( $group ) {
2573 global $wgMessageCache;
2574 $wgMessageCache->loadAllMessages();
2575 $key = "group-$group-member";
2576 $name = wfMsg( $key );
2577 return $name == '' || wfEmptyMsg( $key, $name )
2578 ? $group
2579 : $name;
2583 * Return the set of defined explicit groups.
2584 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2585 * groups are not included, as they are defined
2586 * automatically, not in the database.
2587 * @return array
2588 * @static
2590 static function getAllGroups() {
2591 global $wgGroupPermissions;
2592 return array_diff(
2593 array_keys( $wgGroupPermissions ),
2594 self::getImplicitGroups()
2599 * Get a list of implicit groups
2601 * @return array
2603 public static function getImplicitGroups() {
2604 global $wgImplicitGroups;
2605 $groups = $wgImplicitGroups;
2606 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
2607 return $groups;
2611 * Get the title of a page describing a particular group
2613 * @param $group Name of the group
2614 * @return mixed
2616 static function getGroupPage( $group ) {
2617 global $wgMessageCache;
2618 $wgMessageCache->loadAllMessages();
2619 $page = wfMsgForContent( 'grouppage-' . $group );
2620 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2621 $title = Title::newFromText( $page );
2622 if( is_object( $title ) )
2623 return $title;
2625 return false;
2629 * Create a link to the group in HTML, if available
2631 * @param $group Name of the group
2632 * @param $text The text of the link
2633 * @return mixed
2635 static function makeGroupLinkHTML( $group, $text = '' ) {
2636 if( $text == '' ) {
2637 $text = self::getGroupName( $group );
2639 $title = self::getGroupPage( $group );
2640 if( $title ) {
2641 global $wgUser;
2642 $sk = $wgUser->getSkin();
2643 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2644 } else {
2645 return $text;
2650 * Create a link to the group in Wikitext, if available
2652 * @param $group Name of the group
2653 * @param $text The text of the link (by default, the name of the group)
2654 * @return mixed
2656 static function makeGroupLinkWiki( $group, $text = '' ) {
2657 if( $text == '' ) {
2658 $text = self::getGroupName( $group );
2660 $title = self::getGroupPage( $group );
2661 if( $title ) {
2662 $page = $title->getPrefixedText();
2663 return "[[$page|$text]]";
2664 } else {
2665 return $text;
2670 * Increment the user's edit-count field.
2671 * Will have no effect for anonymous users.
2673 function incEditCount() {
2674 if( !$this->isAnon() ) {
2675 $dbw = wfGetDB( DB_MASTER );
2676 $dbw->update( 'user',
2677 array( 'user_editcount=user_editcount+1' ),
2678 array( 'user_id' => $this->getId() ),
2679 __METHOD__ );
2681 // Lazy initialization check...
2682 if( $dbw->affectedRows() == 0 ) {
2683 // Pull from a slave to be less cruel to servers
2684 // Accuracy isn't the point anyway here
2685 $dbr = wfGetDB( DB_SLAVE );
2686 $count = $dbr->selectField( 'revision',
2687 'COUNT(rev_user)',
2688 array( 'rev_user' => $this->getId() ),
2689 __METHOD__ );
2691 // Now here's a goddamn hack...
2692 if( $dbr !== $dbw ) {
2693 // If we actually have a slave server, the count is
2694 // at least one behind because the current transaction
2695 // has not been committed and replicated.
2696 $count++;
2697 } else {
2698 // But if DB_SLAVE is selecting the master, then the
2699 // count we just read includes the revision that was
2700 // just added in the working transaction.
2703 $dbw->update( 'user',
2704 array( 'user_editcount' => $count ),
2705 array( 'user_id' => $this->getId() ),
2706 __METHOD__ );
2709 // edit count in user cache too
2710 $this->invalidateCache();