Helps to actually _put_ the info into $wgMemc...
[mediawiki.git] / includes / User.php
blob5661c015f042f5a4d075673710042a54279ab6bd
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
4 * @file
5 */
7 /**
8 * \type{\int} Number of characters in user_token field.
9 * @ingroup Constants
11 define( 'USER_TOKEN_LENGTH', 32 );
13 /**
14 * \type{\int} Serialized record version.
15 * @ingroup Constants
17 define( 'MW_USER_VERSION', 6 );
19 /**
20 * \type{\string} Some punctuation to prevent editing from broken text-mangling proxies.
21 * @ingroup Constants
23 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
25 /**
26 * Thrown by User::setPassword() on error.
27 * @ingroup Exception
29 class PasswordError extends MWException {
30 // NOP
33 /**
34 * The User object encapsulates all of the user-specific settings (user_id,
35 * name, rights, password, email address, options, last login time). Client
36 * classes use the getXXX() functions to access these fields. These functions
37 * do all the work of determining whether the user is logged in,
38 * whether the requested option can be satisfied from cookies or
39 * whether a database query is needed. Most of the settings needed
40 * for rendering normal pages are set in the cookie to minimize use
41 * of the database.
43 class User {
45 /**
46 * \type{\arrayof{\string}} A list of default user toggles, i.e., boolean user
47 * preferences that are displayed by Special:Preferences as checkboxes.
48 * This list can be extended via the UserToggles hook or by
49 * $wgContLang::getExtraUserToggles().
50 * @showinitializer
52 public static $mToggles = array(
53 'highlightbroken',
54 'justify',
55 'hideminor',
56 'extendwatchlist',
57 'usenewrc',
58 'numberheadings',
59 'showtoolbar',
60 'editondblclick',
61 'editsection',
62 'editsectiononrightclick',
63 'showtoc',
64 'rememberpassword',
65 'editwidth',
66 'watchcreations',
67 'watchdefault',
68 'watchmoves',
69 'watchdeletion',
70 'minordefault',
71 'previewontop',
72 'previewonfirst',
73 'nocache',
74 'enotifwatchlistpages',
75 'enotifusertalkpages',
76 'enotifminoredits',
77 'enotifrevealaddr',
78 'shownumberswatching',
79 'fancysig',
80 'externaleditor',
81 'externaldiff',
82 'showjumplinks',
83 'uselivepreview',
84 'forceeditsummary',
85 'watchlisthideminor',
86 'watchlisthidebots',
87 'watchlisthideown',
88 'watchlisthideanons',
89 'watchlisthideliu',
90 'ccmeonemails',
91 'diffonly',
92 'showhiddencats',
93 'noconvertlink',
96 /**
97 * \type{\arrayof{\string}} List of member variables which are saved to the
98 * shared cache (memcached). Any operation which changes the
99 * corresponding database fields must call a cache-clearing function.
100 * @showinitializer
102 static $mCacheVars = array(
103 // user table
104 'mId',
105 'mName',
106 'mRealName',
107 'mPassword',
108 'mNewpassword',
109 'mNewpassTime',
110 'mEmail',
111 'mOptions',
112 'mTouched',
113 'mToken',
114 'mEmailAuthenticated',
115 'mEmailToken',
116 'mEmailTokenExpires',
117 'mRegistration',
118 'mEditCount',
119 // user_group table
120 'mGroups',
124 * \type{\arrayof{\string}} Core rights.
125 * Each of these should have a corresponding message of the form
126 * "right-$right".
127 * @showinitializer
129 static $mCoreRights = array(
130 'apihighlimits',
131 'autoconfirmed',
132 'autopatrol',
133 'bigdelete',
134 'block',
135 'blockemail',
136 'bot',
137 'browsearchive',
138 'createaccount',
139 'createpage',
140 'createtalk',
141 'delete',
142 'deletedhistory',
143 'edit',
144 'editinterface',
145 'editusercssjs',
146 'import',
147 'importupload',
148 'ipblock-exempt',
149 'markbotedits',
150 'minoredit',
151 'move',
152 'nominornewtalk',
153 'noratelimit',
154 'patrol',
155 'protect',
156 'proxyunbannable',
157 'purge',
158 'read',
159 'reupload',
160 'reupload-shared',
161 'rollback',
162 'siteadmin',
163 'suppressredirect',
164 'trackback',
165 'undelete',
166 'unwatchedpages',
167 'upload',
168 'upload_by_url',
169 'userrights',
172 * \type{\string} Cached results of getAllRights()
174 static $mAllRights = false;
176 /** @name Cache variables */
177 //@{
178 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
179 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
180 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
181 //@}
184 * \type{\bool} Whether the cache variables have been loaded.
186 var $mDataLoaded;
189 * \type{\string} Initialization data source if mDataLoaded==false. May be one of:
190 * - 'defaults' anonymous user initialised from class defaults
191 * - 'name' initialise from mName
192 * - 'id' initialise from mId
193 * - 'session' log in from cookies or session if possible
195 * Use the User::newFrom*() family of functions to set this.
197 var $mFrom;
199 /** @name Lazy-initialized variables, invalidated with clearInstanceCache */
200 //@{
201 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
202 $mBlockreason, $mBlock, $mEffectiveGroups;
203 //@}
206 * Lightweight constructor for an anonymous user.
207 * Use the User::newFrom* factory functions for other kinds of users.
209 * @see newFromName()
210 * @see newFromId()
211 * @see newFromConfirmationCode()
212 * @see newFromSession()
213 * @see newFromRow()
215 function User() {
216 $this->clearInstanceCache( 'defaults' );
220 * Load the user table data for this object from the source given by mFrom.
222 function load() {
223 if ( $this->mDataLoaded ) {
224 return;
226 wfProfileIn( __METHOD__ );
228 # Set it now to avoid infinite recursion in accessors
229 $this->mDataLoaded = true;
231 switch ( $this->mFrom ) {
232 case 'defaults':
233 $this->loadDefaults();
234 break;
235 case 'name':
236 $this->mId = self::idFromName( $this->mName );
237 if ( !$this->mId ) {
238 # Nonexistent user placeholder object
239 $this->loadDefaults( $this->mName );
240 } else {
241 $this->loadFromId();
243 break;
244 case 'id':
245 $this->loadFromId();
246 break;
247 case 'session':
248 $this->loadFromSession();
249 break;
250 default:
251 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
253 wfProfileOut( __METHOD__ );
257 * Load user table data, given mId has already been set.
258 * @return \type{\bool} false if the ID does not exist, true otherwise
259 * @private
261 function loadFromId() {
262 global $wgMemc;
263 if ( $this->mId == 0 ) {
264 $this->loadDefaults();
265 return false;
268 # Try cache
269 $key = wfMemcKey( 'user', 'id', $this->mId );
270 $data = $wgMemc->get( $key );
271 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
272 # Object is expired, load from DB
273 $data = false;
276 if ( !$data ) {
277 wfDebug( "Cache miss for user {$this->mId}\n" );
278 # Load from DB
279 if ( !$this->loadFromDatabase() ) {
280 # Can't load from ID, user is anonymous
281 return false;
283 $this->saveToCache();
284 } else {
285 wfDebug( "Got user {$this->mId} from cache\n" );
286 # Restore from cache
287 foreach ( self::$mCacheVars as $name ) {
288 $this->$name = $data[$name];
291 return true;
295 * Save user data to the shared cache
297 function saveToCache() {
298 $this->load();
299 $this->loadGroups();
300 if ( $this->isAnon() ) {
301 // Anonymous users are uncached
302 return;
304 $data = array();
305 foreach ( self::$mCacheVars as $name ) {
306 $data[$name] = $this->$name;
308 $data['mVersion'] = MW_USER_VERSION;
309 $key = wfMemcKey( 'user', 'id', $this->mId );
310 global $wgMemc;
311 $wgMemc->set( $key, $data );
315 /** @name newFrom*() static factory methods */
316 //@{
319 * Static factory method for creation from username.
321 * This is slightly less efficient than newFromId(), so use newFromId() if
322 * you have both an ID and a name handy.
324 * @param $name \type{\string} Username, validated by Title::newFromText()
325 * @param $validate \type{\mixed} Validate username. Takes the same parameters as
326 * User::getCanonicalName(), except that true is accepted as an alias
327 * for 'valid', for BC.
329 * @return \type{User} The User object, or null if the username is invalid. If the
330 * username is not present in the database, the result will be a user object
331 * with a name, zero user ID and default settings.
333 static function newFromName( $name, $validate = 'valid' ) {
334 if ( $validate === true ) {
335 $validate = 'valid';
337 $name = self::getCanonicalName( $name, $validate );
338 if ( $name === false ) {
339 return null;
340 } else {
341 # Create unloaded user object
342 $u = new User;
343 $u->mName = $name;
344 $u->mFrom = 'name';
345 return $u;
350 * Static factory method for creation from a given user ID.
352 * @param $id \type{\int} Valid user ID
353 * @return \type{User} The corresponding User object
355 static function newFromId( $id ) {
356 $u = new User;
357 $u->mId = $id;
358 $u->mFrom = 'id';
359 return $u;
363 * Factory method to fetch whichever user has a given email confirmation code.
364 * This code is generated when an account is created or its e-mail address
365 * has changed.
367 * If the code is invalid or has expired, returns NULL.
369 * @param $code \type{\string} Confirmation code
370 * @return \type{User}
372 static function newFromConfirmationCode( $code ) {
373 $dbr = wfGetDB( DB_SLAVE );
374 $id = $dbr->selectField( 'user', 'user_id', array(
375 'user_email_token' => md5( $code ),
376 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
377 ) );
378 if( $id !== false ) {
379 return User::newFromId( $id );
380 } else {
381 return null;
386 * Create a new user object using data from session or cookies. If the
387 * login credentials are invalid, the result is an anonymous user.
389 * @return \type{User}
391 static function newFromSession() {
392 $user = new User;
393 $user->mFrom = 'session';
394 return $user;
398 * Create a new user object from a user row.
399 * The row should have all fields from the user table in it.
400 * @param $row array A row from the user table
401 * @return \type{User}
403 static function newFromRow( $row ) {
404 $user = new User;
405 $user->loadFromRow( $row );
406 return $user;
409 //@}
413 * Get the username corresponding to a given user ID
414 * @param $id \type{\int} %User ID
415 * @return \type{\string} The corresponding username
417 static function whoIs( $id ) {
418 $dbr = wfGetDB( DB_SLAVE );
419 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
423 * Get the real name of a user given their user ID
425 * @param $id \type{\int} %User ID
426 * @return \type{\string} The corresponding user's real name
428 static function whoIsReal( $id ) {
429 $dbr = wfGetDB( DB_SLAVE );
430 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ );
434 * Get database id given a user name
435 * @param $name \type{\string} Username
436 * @return \twotypes{\int,\null} The corresponding user's ID, or null if user is nonexistent
437 * @static
439 static function idFromName( $name ) {
440 $nt = Title::newFromText( $name );
441 if( is_null( $nt ) ) {
442 # Illegal name
443 return null;
445 $dbr = wfGetDB( DB_SLAVE );
446 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
448 if ( $s === false ) {
449 return 0;
450 } else {
451 return $s->user_id;
456 * Does the string match an anonymous IPv4 address?
458 * This function exists for username validation, in order to reject
459 * usernames which are similar in form to IP addresses. Strings such
460 * as 300.300.300.300 will return true because it looks like an IP
461 * address, despite not being strictly valid.
463 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
464 * address because the usemod software would "cloak" anonymous IP
465 * addresses like this, if we allowed accounts like this to be created
466 * new users could get the old edits of these anonymous users.
468 * @param $name \type{\string} String to match
469 * @return \type{\bool} True or false
471 static function isIP( $name ) {
472 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP::isIPv6($name);
476 * Is the input a valid username?
478 * Checks if the input is a valid username, we don't want an empty string,
479 * an IP address, anything that containins slashes (would mess up subpages),
480 * is longer than the maximum allowed username size or doesn't begin with
481 * a capital letter.
483 * @param $name \type{\string} String to match
484 * @return \type{\bool} True or false
486 static function isValidUserName( $name ) {
487 global $wgContLang, $wgMaxNameChars;
489 if ( $name == ''
490 || User::isIP( $name )
491 || strpos( $name, '/' ) !== false
492 || strlen( $name ) > $wgMaxNameChars
493 || $name != $wgContLang->ucfirst( $name ) ) {
494 wfDebugLog( 'username', __METHOD__ .
495 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
496 return false;
499 // Ensure that the name can't be misresolved as a different title,
500 // such as with extra namespace keys at the start.
501 $parsed = Title::newFromText( $name );
502 if( is_null( $parsed )
503 || $parsed->getNamespace()
504 || strcmp( $name, $parsed->getPrefixedText() ) ) {
505 wfDebugLog( 'username', __METHOD__ .
506 ": '$name' invalid due to ambiguous prefixes" );
507 return false;
510 // Check an additional blacklist of troublemaker characters.
511 // Should these be merged into the title char list?
512 $unicodeBlacklist = '/[' .
513 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
514 '\x{00a0}' . # non-breaking space
515 '\x{2000}-\x{200f}' . # various whitespace
516 '\x{2028}-\x{202f}' . # breaks and control chars
517 '\x{3000}' . # ideographic space
518 '\x{e000}-\x{f8ff}' . # private use
519 ']/u';
520 if( preg_match( $unicodeBlacklist, $name ) ) {
521 wfDebugLog( 'username', __METHOD__ .
522 ": '$name' invalid due to blacklisted characters" );
523 return false;
526 return true;
530 * Usernames which fail to pass this function will be blocked
531 * from user login and new account registrations, but may be used
532 * internally by batch processes.
534 * If an account already exists in this form, login will be blocked
535 * by a failure to pass this function.
537 * @param $name \type{\string} String to match
538 * @return \type{\bool} True or false
540 static function isUsableName( $name ) {
541 global $wgReservedUsernames;
542 // Must be a valid username, obviously ;)
543 if ( !self::isValidUserName( $name ) ) {
544 return false;
547 static $reservedUsernames = false;
548 if ( !$reservedUsernames ) {
549 $reservedUsernames = $wgReservedUsernames;
550 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
553 // Certain names may be reserved for batch processes.
554 foreach ( $reservedUsernames as $reserved ) {
555 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
556 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
558 if ( $reserved == $name ) {
559 return false;
562 return true;
566 * Usernames which fail to pass this function will be blocked
567 * from new account registrations, but may be used internally
568 * either by batch processes or by user accounts which have
569 * already been created.
571 * Additional character blacklisting may be added here
572 * rather than in isValidUserName() to avoid disrupting
573 * existing accounts.
575 * @param $name \type{\string} String to match
576 * @return \type{\bool} True or false
578 static function isCreatableName( $name ) {
579 return
580 self::isUsableName( $name ) &&
582 // Registration-time character blacklisting...
583 strpos( $name, '@' ) === false;
587 * Is the input a valid password for this user?
589 * @param $password \type{\string} Desired password
590 * @return \type{\bool} True or false
592 function isValidPassword( $password ) {
593 global $wgMinimalPasswordLength, $wgContLang;
595 $result = null;
596 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
597 return $result;
598 if( $result === false )
599 return false;
601 // Password needs to be long enough, and can't be the same as the username
602 return strlen( $password ) >= $wgMinimalPasswordLength
603 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName );
607 * Does a string look like an e-mail address?
609 * There used to be a regular expression here, it got removed because it
610 * rejected valid addresses. Actually just check if there is '@' somewhere
611 * in the given address.
613 * @todo Check for RFC 2822 compilance (bug 959)
615 * @param $addr \type{\string} E-mail address
616 * @return \type{\bool} True or false
618 public static function isValidEmailAddr( $addr ) {
619 $result = null;
620 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
621 return $result;
624 return strpos( $addr, '@' ) !== false;
628 * Given unvalidated user input, return a canonical username, or false if
629 * the username is invalid.
630 * @param $name \type{\string} User input
631 * @param $validate \twotypes{\string,\bool} Type of validation to use:
632 * - false No validation
633 * - 'valid' Valid for batch processes
634 * - 'usable' Valid for batch processes and login
635 * - 'creatable' Valid for batch processes, login and account creation
637 static function getCanonicalName( $name, $validate = 'valid' ) {
638 # Force usernames to capital
639 global $wgContLang;
640 $name = $wgContLang->ucfirst( $name );
642 # Reject names containing '#'; these will be cleaned up
643 # with title normalisation, but then it's too late to
644 # check elsewhere
645 if( strpos( $name, '#' ) !== false )
646 return false;
648 # Clean up name according to title rules
649 $t = Title::newFromText( $name );
650 if( is_null( $t ) ) {
651 return false;
654 # Reject various classes of invalid names
655 $name = $t->getText();
656 global $wgAuth;
657 $name = $wgAuth->getCanonicalName( $t->getText() );
659 switch ( $validate ) {
660 case false:
661 break;
662 case 'valid':
663 if ( !User::isValidUserName( $name ) ) {
664 $name = false;
666 break;
667 case 'usable':
668 if ( !User::isUsableName( $name ) ) {
669 $name = false;
671 break;
672 case 'creatable':
673 if ( !User::isCreatableName( $name ) ) {
674 $name = false;
676 break;
677 default:
678 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__ );
680 return $name;
684 * Count the number of edits of a user
685 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
687 * @param $uid \type{\int} %User ID to check
688 * @return \type{\int} The user's edit count
690 static function edits( $uid ) {
691 wfProfileIn( __METHOD__ );
692 $dbr = wfGetDB( DB_SLAVE );
693 // check if the user_editcount field has been initialized
694 $field = $dbr->selectField(
695 'user', 'user_editcount',
696 array( 'user_id' => $uid ),
697 __METHOD__
700 if( $field === null ) { // it has not been initialized. do so.
701 $dbw = wfGetDB( DB_MASTER );
702 $count = $dbr->selectField(
703 'revision', 'count(*)',
704 array( 'rev_user' => $uid ),
705 __METHOD__
707 $dbw->update(
708 'user',
709 array( 'user_editcount' => $count ),
710 array( 'user_id' => $uid ),
711 __METHOD__
713 } else {
714 $count = $field;
716 wfProfileOut( __METHOD__ );
717 return $count;
721 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
722 * @todo hash random numbers to improve security, like generateToken()
724 * @return \type{\string} New random password
726 static function randomPassword() {
727 global $wgMinimalPasswordLength;
728 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
729 $l = strlen( $pwchars ) - 1;
731 $pwlength = max( 7, $wgMinimalPasswordLength );
732 $digit = mt_rand(0, $pwlength - 1);
733 $np = '';
734 for ( $i = 0; $i < $pwlength; $i++ ) {
735 $np .= $i == $digit ? chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
737 return $np;
741 * Set cached properties to default.
743 * @note This no longer clears uncached lazy-initialised properties;
744 * the constructor does that instead.
745 * @private
747 function loadDefaults( $name = false ) {
748 wfProfileIn( __METHOD__ );
750 global $wgCookiePrefix;
752 $this->mId = 0;
753 $this->mName = $name;
754 $this->mRealName = '';
755 $this->mPassword = $this->mNewpassword = '';
756 $this->mNewpassTime = null;
757 $this->mEmail = '';
758 $this->mOptions = null; # Defer init
760 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
761 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
762 } else {
763 $this->mTouched = '0'; # Allow any pages to be cached
766 $this->setToken(); # Random
767 $this->mEmailAuthenticated = null;
768 $this->mEmailToken = '';
769 $this->mEmailTokenExpires = null;
770 $this->mRegistration = wfTimestamp( TS_MW );
771 $this->mGroups = array();
773 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
775 wfProfileOut( __METHOD__ );
779 * @deprecated Use wfSetupSession().
781 function SetupSession() {
782 wfDeprecated( __METHOD__ );
783 wfSetupSession();
787 * Load user data from the session or login cookie. If there are no valid
788 * credentials, initialises the user as an anonymous user.
789 * @return \type{\bool} True if the user is logged in, false otherwise.
791 private function loadFromSession() {
792 global $wgMemc, $wgCookiePrefix;
794 $result = null;
795 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
796 if ( $result !== null ) {
797 return $result;
800 if ( isset( $_SESSION['wsUserID'] ) ) {
801 if ( 0 != $_SESSION['wsUserID'] ) {
802 $sId = $_SESSION['wsUserID'];
803 } else {
804 $this->loadDefaults();
805 return false;
807 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
808 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
809 $_SESSION['wsUserID'] = $sId;
810 } else {
811 $this->loadDefaults();
812 return false;
814 if ( isset( $_SESSION['wsUserName'] ) ) {
815 $sName = $_SESSION['wsUserName'];
816 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
817 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
818 $_SESSION['wsUserName'] = $sName;
819 } else {
820 $this->loadDefaults();
821 return false;
824 $passwordCorrect = FALSE;
825 $this->mId = $sId;
826 if ( !$this->loadFromId() ) {
827 # Not a valid ID, loadFromId has switched the object to anon for us
828 return false;
831 if ( isset( $_SESSION['wsToken'] ) ) {
832 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
833 $from = 'session';
834 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
835 $passwordCorrect = $this->mToken == $_COOKIE["{$wgCookiePrefix}Token"];
836 $from = 'cookie';
837 } else {
838 # No session or persistent login cookie
839 $this->loadDefaults();
840 return false;
843 if ( ( $sName == $this->mName ) && $passwordCorrect ) {
844 $_SESSION['wsToken'] = $this->mToken;
845 wfDebug( "Logged in from $from\n" );
846 return true;
847 } else {
848 # Invalid credentials
849 wfDebug( "Can't log in from $from, invalid credentials\n" );
850 $this->loadDefaults();
851 return false;
856 * Load user and user_group data from the database.
857 * $this::mId must be set, this is how the user is identified.
859 * @return \type{\bool} True if the user exists, false if the user is anonymous
860 * @private
862 function loadFromDatabase() {
863 # Paranoia
864 $this->mId = intval( $this->mId );
866 /** Anonymous user */
867 if( !$this->mId ) {
868 $this->loadDefaults();
869 return false;
872 $dbr = wfGetDB( DB_MASTER );
873 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
875 if ( $s !== false ) {
876 # Initialise user table data
877 $this->loadFromRow( $s );
878 $this->mGroups = null; // deferred
879 $this->getEditCount(); // revalidation for nulls
880 return true;
881 } else {
882 # Invalid user_id
883 $this->mId = 0;
884 $this->loadDefaults();
885 return false;
890 * Initialize this object from a row from the user table.
892 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
894 function loadFromRow( $row ) {
895 $this->mDataLoaded = true;
897 if ( isset( $row->user_id ) ) {
898 $this->mId = $row->user_id;
900 $this->mName = $row->user_name;
901 $this->mRealName = $row->user_real_name;
902 $this->mPassword = $row->user_password;
903 $this->mNewpassword = $row->user_newpassword;
904 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
905 $this->mEmail = $row->user_email;
906 $this->decodeOptions( $row->user_options );
907 $this->mTouched = wfTimestamp(TS_MW,$row->user_touched);
908 $this->mToken = $row->user_token;
909 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
910 $this->mEmailToken = $row->user_email_token;
911 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
912 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
913 $this->mEditCount = $row->user_editcount;
917 * Load the groups from the database if they aren't already loaded.
918 * @private
920 function loadGroups() {
921 if ( is_null( $this->mGroups ) ) {
922 $dbr = wfGetDB( DB_MASTER );
923 $res = $dbr->select( 'user_groups',
924 array( 'ug_group' ),
925 array( 'ug_user' => $this->mId ),
926 __METHOD__ );
927 $this->mGroups = array();
928 while( $row = $dbr->fetchObject( $res ) ) {
929 $this->mGroups[] = $row->ug_group;
935 * Clear various cached data stored in this object.
936 * @param $reloadFrom \type{\string} Reload user and user_groups table data from a
937 * given source. May be "name", "id", "defaults", "session", or false for
938 * no reload.
940 function clearInstanceCache( $reloadFrom = false ) {
941 $this->mNewtalk = -1;
942 $this->mDatePreference = null;
943 $this->mBlockedby = -1; # Unset
944 $this->mHash = false;
945 $this->mSkin = null;
946 $this->mRights = null;
947 $this->mEffectiveGroups = null;
949 if ( $reloadFrom ) {
950 $this->mDataLoaded = false;
951 $this->mFrom = $reloadFrom;
956 * Combine the language default options with any site-specific options
957 * and add the default language variants.
959 * @return \type{\arrayof{\string}} Array of options
961 static function getDefaultOptions() {
962 global $wgNamespacesToBeSearchedDefault;
964 * Site defaults will override the global/language defaults
966 global $wgDefaultUserOptions, $wgContLang;
967 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
970 * default language setting
972 $variant = $wgContLang->getPreferredVariant( false );
973 $defOpt['variant'] = $variant;
974 $defOpt['language'] = $variant;
976 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
977 $defOpt['searchNs'.$nsnum] = $val;
979 return $defOpt;
983 * Get a given default option value.
985 * @param $opt \type{\string} Name of option to retrieve
986 * @return \type{\string} Default option value
988 public static function getDefaultOption( $opt ) {
989 $defOpts = self::getDefaultOptions();
990 if( isset( $defOpts[$opt] ) ) {
991 return $defOpts[$opt];
992 } else {
993 return '';
998 * Get a list of user toggle names
999 * @return \type{\arrayof{\string}} Array of user toggle names
1001 static function getToggles() {
1002 global $wgContLang;
1003 $extraToggles = array();
1004 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1005 return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1010 * Get blocking information
1011 * @private
1012 * @param $bFromSlave \type{\bool} Whether to check the slave database first. To
1013 * improve performance, non-critical checks are done
1014 * against slaves. Check when actually saving should be
1015 * done against master.
1017 function getBlockedStatus( $bFromSlave = true ) {
1018 global $wgEnableSorbs, $wgProxyWhitelist;
1020 if ( -1 != $this->mBlockedby ) {
1021 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1022 return;
1025 wfProfileIn( __METHOD__ );
1026 wfDebug( __METHOD__.": checking...\n" );
1028 // Initialize data...
1029 // Otherwise something ends up stomping on $this->mBlockedby when
1030 // things get lazy-loaded later, causing false positive block hits
1031 // due to -1 !== 0. Probably session-related... Nothing should be
1032 // overwriting mBlockedby, surely?
1033 $this->load();
1035 $this->mBlockedby = 0;
1036 $this->mHideName = 0;
1037 $ip = wfGetIP();
1039 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1040 # Exempt from all types of IP-block
1041 $ip = '';
1044 # User/IP blocking
1045 $this->mBlock = new Block();
1046 $this->mBlock->fromMaster( !$bFromSlave );
1047 if ( $this->mBlock->load( $ip , $this->mId ) ) {
1048 wfDebug( __METHOD__.": Found block.\n" );
1049 $this->mBlockedby = $this->mBlock->mBy;
1050 $this->mBlockreason = $this->mBlock->mReason;
1051 $this->mHideName = $this->mBlock->mHideName;
1052 if ( $this->isLoggedIn() ) {
1053 $this->spreadBlock();
1055 } else {
1056 $this->mBlock = null;
1057 wfDebug( __METHOD__.": No block.\n" );
1060 # Proxy blocking
1061 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1062 # Local list
1063 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1064 $this->mBlockedby = wfMsg( 'proxyblocker' );
1065 $this->mBlockreason = wfMsg( 'proxyblockreason' );
1068 # DNSBL
1069 if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
1070 if ( $this->inSorbsBlacklist( $ip ) ) {
1071 $this->mBlockedby = wfMsg( 'sorbs' );
1072 $this->mBlockreason = wfMsg( 'sorbsreason' );
1077 # Extensions
1078 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1080 wfProfileOut( __METHOD__ );
1084 * Whether the given IP is in the SORBS blacklist.
1086 * @param $ip \type{\string} IP to check
1087 * @return \type{\bool} True if blacklisted
1089 function inSorbsBlacklist( $ip ) {
1090 global $wgEnableSorbs, $wgSorbsUrl;
1092 return $wgEnableSorbs &&
1093 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1097 * Whether the given IP is in a given DNS blacklist.
1099 * @param $ip \type{\string} IP to check
1100 * @param $base \type{\string} URL of the DNS blacklist
1101 * @return \type{\bool} True if blacklisted
1103 function inDnsBlacklist( $ip, $base ) {
1104 wfProfileIn( __METHOD__ );
1106 $found = false;
1107 $host = '';
1108 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1109 if( IP::isIPv4($ip) ) {
1110 # Make hostname
1111 $host = "$ip.$base";
1113 # Send query
1114 $ipList = gethostbynamel( $host );
1116 if( $ipList ) {
1117 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1118 $found = true;
1119 } else {
1120 wfDebug( "Requested $host, not found in $base.\n" );
1124 wfProfileOut( __METHOD__ );
1125 return $found;
1129 * Is this user subject to rate limiting?
1131 * @return \type{\bool} True if rate limited
1133 public function isPingLimitable() {
1134 global $wgRateLimitsExcludedGroups;
1135 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1136 // Deprecated, but kept for backwards-compatibility config
1137 return false;
1139 return !$this->isAllowed('noratelimit');
1143 * Primitive rate limits: enforce maximum actions per time period
1144 * to put a brake on flooding.
1146 * @note When using a shared cache like memcached, IP-address
1147 * last-hit counters will be shared across wikis.
1149 * @param $action \type{\string} Action to enforce; 'edit' if unspecified
1150 * @return \type{\bool} True if a rate limiter was tripped
1152 function pingLimiter( $action='edit' ) {
1154 # Call the 'PingLimiter' hook
1155 $result = false;
1156 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1157 return $result;
1160 global $wgRateLimits;
1161 if( !isset( $wgRateLimits[$action] ) ) {
1162 return false;
1165 # Some groups shouldn't trigger the ping limiter, ever
1166 if( !$this->isPingLimitable() )
1167 return false;
1169 global $wgMemc, $wgRateLimitLog;
1170 wfProfileIn( __METHOD__ );
1172 $limits = $wgRateLimits[$action];
1173 $keys = array();
1174 $id = $this->getId();
1175 $ip = wfGetIP();
1176 $userLimit = false;
1178 if( isset( $limits['anon'] ) && $id == 0 ) {
1179 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1182 if( isset( $limits['user'] ) && $id != 0 ) {
1183 $userLimit = $limits['user'];
1185 if( $this->isNewbie() ) {
1186 if( isset( $limits['newbie'] ) && $id != 0 ) {
1187 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1189 if( isset( $limits['ip'] ) ) {
1190 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1192 $matches = array();
1193 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1194 $subnet = $matches[1];
1195 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1198 // Check for group-specific permissions
1199 // If more than one group applies, use the group with the highest limit
1200 foreach ( $this->getGroups() as $group ) {
1201 if ( isset( $limits[$group] ) ) {
1202 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1203 $userLimit = $limits[$group];
1207 // Set the user limit key
1208 if ( $userLimit !== false ) {
1209 wfDebug( __METHOD__.": effective user limit: $userLimit\n" );
1210 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1213 $triggered = false;
1214 foreach( $keys as $key => $limit ) {
1215 list( $max, $period ) = $limit;
1216 $summary = "(limit $max in {$period}s)";
1217 $count = $wgMemc->get( $key );
1218 if( $count ) {
1219 if( $count > $max ) {
1220 wfDebug( __METHOD__.": tripped! $key at $count $summary\n" );
1221 if( $wgRateLimitLog ) {
1222 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1224 $triggered = true;
1225 } else {
1226 wfDebug( __METHOD__.": ok. $key at $count $summary\n" );
1228 } else {
1229 wfDebug( __METHOD__.": adding record for $key $summary\n" );
1230 $wgMemc->add( $key, 1, intval( $period ) );
1232 $wgMemc->incr( $key );
1235 wfProfileOut( __METHOD__ );
1236 return $triggered;
1240 * Check if user is blocked
1242 * @param $bFromSlave \type{\bool} Whether to check the slave database instead of the master
1243 * @return \type{\bool} True if blocked, false otherwise
1245 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1246 wfDebug( "User::isBlocked: enter\n" );
1247 $this->getBlockedStatus( $bFromSlave );
1248 return $this->mBlockedby !== 0;
1252 * Check if user is blocked from editing a particular article
1254 * @param $title \type{\string} Title to check
1255 * @param $bFromSlave \type{\bool} Whether to check the slave database instead of the master
1256 * @return \type{\bool} True if blocked, false otherwise
1258 function isBlockedFrom( $title, $bFromSlave = false ) {
1259 global $wgBlockAllowsUTEdit;
1260 wfProfileIn( __METHOD__ );
1261 wfDebug( __METHOD__.": enter\n" );
1263 wfDebug( __METHOD__.": asking isBlocked()\n" );
1264 $blocked = $this->isBlocked( $bFromSlave );
1265 # If a user's name is suppressed, they cannot make edits anywhere
1266 if ( !$this->mHideName && $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1267 $title->getNamespace() == NS_USER_TALK ) {
1268 $blocked = false;
1269 wfDebug( __METHOD__.": self-talk page, ignoring any blocks\n" );
1271 wfProfileOut( __METHOD__ );
1272 return $blocked;
1276 * If user is blocked, return the name of the user who placed the block
1277 * @return \type{\string} name of blocker
1279 function blockedBy() {
1280 $this->getBlockedStatus();
1281 return $this->mBlockedby;
1285 * If user is blocked, return the specified reason for the block
1286 * @return \type{\string} Blocking reason
1288 function blockedFor() {
1289 $this->getBlockedStatus();
1290 return $this->mBlockreason;
1294 * Get the user's ID.
1295 * @return \type{\int} The user's ID; 0 if the user is anonymous or nonexistent
1297 function getId() {
1298 if( $this->mId === null and $this->mName !== null
1299 and User::isIP( $this->mName ) ) {
1300 // Special case, we know the user is anonymous
1301 return 0;
1302 } elseif( $this->mId === null ) {
1303 // Don't load if this was initialized from an ID
1304 $this->load();
1306 return $this->mId;
1310 * Set the user and reload all fields according to a given ID
1311 * @param $v \type{\int} %User ID to reload
1313 function setId( $v ) {
1314 $this->mId = $v;
1315 $this->clearInstanceCache( 'id' );
1319 * Get the user name, or the IP of an anonymous user
1320 * @return \type{\string} User's name or IP address
1322 function getName() {
1323 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1324 # Special case optimisation
1325 return $this->mName;
1326 } else {
1327 $this->load();
1328 if ( $this->mName === false ) {
1329 # Clean up IPs
1330 $this->mName = IP::sanitizeIP( wfGetIP() );
1332 return $this->mName;
1337 * Set the user name.
1339 * This does not reload fields from the database according to the given
1340 * name. Rather, it is used to create a temporary "nonexistent user" for
1341 * later addition to the database. It can also be used to set the IP
1342 * address for an anonymous user to something other than the current
1343 * remote IP.
1345 * @note User::newFromName() has rougly the same function, when the named user
1346 * does not exist.
1347 * @param $str \type{\string} New user name to set
1349 function setName( $str ) {
1350 $this->load();
1351 $this->mName = $str;
1355 * Get the user's name escaped by underscores.
1356 * @return \type{\string} Username escaped by underscores
1358 function getTitleKey() {
1359 return str_replace( ' ', '_', $this->getName() );
1363 * Check if the user has new messages.
1364 * @return \type{\bool} True if the user has new messages
1366 function getNewtalk() {
1367 $this->load();
1369 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1370 if( $this->mNewtalk === -1 ) {
1371 $this->mNewtalk = false; # reset talk page status
1373 # Check memcached separately for anons, who have no
1374 # entire User object stored in there.
1375 if( !$this->mId ) {
1376 global $wgMemc;
1377 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1378 $newtalk = $wgMemc->get( $key );
1379 if( strval( $newtalk ) !== '' ) {
1380 $this->mNewtalk = (bool)$newtalk;
1381 } else {
1382 // Since we are caching this, make sure it is up to date by getting it
1383 // from the master
1384 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1385 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1387 } else {
1388 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1392 return (bool)$this->mNewtalk;
1396 * Return the talk page(s) this user has new messages on.
1397 * @return \type{\arrayof{\string}} Array of page URLs
1399 function getNewMessageLinks() {
1400 $talks = array();
1401 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1402 return $talks;
1404 if (!$this->getNewtalk())
1405 return array();
1406 $up = $this->getUserPage();
1407 $utp = $up->getTalkPage();
1408 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1413 * Internal uncached check for new messages
1415 * @see getNewtalk()
1416 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1417 * @param $id \twotypes{\string,\int} User's IP address for anonymous users, %User ID otherwise
1418 * @param $fromMaster \type{\bool} true to fetch from the master, false for a slave
1419 * @return \type{\bool} True if the user has new messages
1420 * @private
1422 function checkNewtalk( $field, $id, $fromMaster = false ) {
1423 if ( $fromMaster ) {
1424 $db = wfGetDB( DB_MASTER );
1425 } else {
1426 $db = wfGetDB( DB_SLAVE );
1428 $ok = $db->selectField( 'user_newtalk', $field,
1429 array( $field => $id ), __METHOD__ );
1430 return $ok !== false;
1434 * Add or update the new messages flag
1435 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1436 * @param $id \twotypes{string,\int} User's IP address for anonymous users, %User ID otherwise
1437 * @return \type{\bool} True if successful, false otherwise
1438 * @private
1440 function updateNewtalk( $field, $id ) {
1441 $dbw = wfGetDB( DB_MASTER );
1442 $dbw->insert( 'user_newtalk',
1443 array( $field => $id ),
1444 __METHOD__,
1445 'IGNORE' );
1446 if ( $dbw->affectedRows() ) {
1447 wfDebug( __METHOD__.": set on ($field, $id)\n" );
1448 return true;
1449 } else {
1450 wfDebug( __METHOD__." already set ($field, $id)\n" );
1451 return false;
1456 * Clear the new messages flag for the given user
1457 * @param $field \type{\string} 'user_ip' for anonymous users, 'user_id' otherwise
1458 * @param $id \twotypes{\string,\int} User's IP address for anonymous users, %User ID otherwise
1459 * @return \type{\bool} True if successful, false otherwise
1460 * @private
1462 function deleteNewtalk( $field, $id ) {
1463 $dbw = wfGetDB( DB_MASTER );
1464 $dbw->delete( 'user_newtalk',
1465 array( $field => $id ),
1466 __METHOD__ );
1467 if ( $dbw->affectedRows() ) {
1468 wfDebug( __METHOD__.": killed on ($field, $id)\n" );
1469 return true;
1470 } else {
1471 wfDebug( __METHOD__.": already gone ($field, $id)\n" );
1472 return false;
1477 * Update the 'You have new messages!' status.
1478 * @param $val \type{\bool} Whether the user has new messages
1480 function setNewtalk( $val ) {
1481 if( wfReadOnly() ) {
1482 return;
1485 $this->load();
1486 $this->mNewtalk = $val;
1488 if( $this->isAnon() ) {
1489 $field = 'user_ip';
1490 $id = $this->getName();
1491 } else {
1492 $field = 'user_id';
1493 $id = $this->getId();
1495 global $wgMemc;
1497 if( $val ) {
1498 $changed = $this->updateNewtalk( $field, $id );
1499 } else {
1500 $changed = $this->deleteNewtalk( $field, $id );
1503 if( $this->isAnon() ) {
1504 // Anons have a separate memcached space, since
1505 // user records aren't kept for them.
1506 $key = wfMemcKey( 'newtalk', 'ip', $id );
1507 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1509 if ( $changed ) {
1510 $this->invalidateCache();
1515 * Generate a current or new-future timestamp to be stored in the
1516 * user_touched field when we update things.
1517 * @return \type{\string} Timestamp in TS_MW format
1519 private static function newTouchedTimestamp() {
1520 global $wgClockSkewFudge;
1521 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1525 * Clear user data from memcached.
1526 * Use after applying fun updates to the database; caller's
1527 * responsibility to update user_touched if appropriate.
1529 * Called implicitly from invalidateCache() and saveSettings().
1531 private function clearSharedCache() {
1532 if( $this->mId ) {
1533 global $wgMemc;
1534 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1539 * Immediately touch the user data cache for this account.
1540 * Updates user_touched field, and removes account data from memcached
1541 * for reload on the next hit.
1543 function invalidateCache() {
1544 $this->load();
1545 if( $this->mId ) {
1546 $this->mTouched = self::newTouchedTimestamp();
1548 $dbw = wfGetDB( DB_MASTER );
1549 $dbw->update( 'user',
1550 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1551 array( 'user_id' => $this->mId ),
1552 __METHOD__ );
1554 $this->clearSharedCache();
1559 * Validate the cache for this account.
1560 * @param $timestamp \type{\string} A timestamp in TS_MW format
1562 function validateCache( $timestamp ) {
1563 $this->load();
1564 return ($timestamp >= $this->mTouched);
1568 * Get the user touched timestamp
1570 function getTouched() {
1571 $this->load();
1572 return $this->mTouched;
1576 * Set the password and reset the random token.
1577 * Calls through to authentication plugin if necessary;
1578 * will have no effect if the auth plugin refuses to
1579 * pass the change through or if the legal password
1580 * checks fail.
1582 * As a special case, setting the password to null
1583 * wipes it, so the account cannot be logged in until
1584 * a new password is set, for instance via e-mail.
1586 * @param $str \type{\string} New password to set
1587 * @throws PasswordError on failure
1589 function setPassword( $str ) {
1590 global $wgAuth;
1592 if( $str !== null ) {
1593 if( !$wgAuth->allowPasswordChange() ) {
1594 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1597 if( !$this->isValidPassword( $str ) ) {
1598 global $wgMinimalPasswordLength;
1599 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1600 $wgMinimalPasswordLength ) );
1604 if( !$wgAuth->setPassword( $this, $str ) ) {
1605 throw new PasswordError( wfMsg( 'externaldberror' ) );
1608 $this->setInternalPassword( $str );
1610 return true;
1614 * Set the password and reset the random token unconditionally.
1616 * @param $str \type{\string} New password to set
1618 function setInternalPassword( $str ) {
1619 $this->load();
1620 $this->setToken();
1622 if( $str === null ) {
1623 // Save an invalid hash...
1624 $this->mPassword = '';
1625 } else {
1626 $this->mPassword = self::crypt( $str );
1628 $this->mNewpassword = '';
1629 $this->mNewpassTime = null;
1633 * Get the user's current token.
1634 * @return \type{\string} Token
1636 function getToken() {
1637 $this->load();
1638 return $this->mToken;
1642 * Set the random token (used for persistent authentication)
1643 * Called from loadDefaults() among other places.
1645 * @param $token \type{\string} If specified, set the token to this value
1646 * @private
1648 function setToken( $token = false ) {
1649 global $wgSecretKey, $wgProxyKey;
1650 $this->load();
1651 if ( !$token ) {
1652 if ( $wgSecretKey ) {
1653 $key = $wgSecretKey;
1654 } elseif ( $wgProxyKey ) {
1655 $key = $wgProxyKey;
1656 } else {
1657 $key = microtime();
1659 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1660 } else {
1661 $this->mToken = $token;
1666 * Set the cookie password
1668 * @param $str \type{\string} New cookie password
1669 * @private
1671 function setCookiePassword( $str ) {
1672 $this->load();
1673 $this->mCookiePassword = md5( $str );
1677 * Set the password for a password reminder or new account email
1679 * @param $str \type{\string} New password to set
1680 * @param $throttle \type{\bool} If true, reset the throttle timestamp to the present
1682 function setNewpassword( $str, $throttle = true ) {
1683 $this->load();
1684 $this->mNewpassword = self::crypt( $str );
1685 if ( $throttle ) {
1686 $this->mNewpassTime = wfTimestampNow();
1691 * Has password reminder email been sent within the last
1692 * $wgPasswordReminderResendTime hours?
1693 * @return \type{\bool} True or false
1695 function isPasswordReminderThrottled() {
1696 global $wgPasswordReminderResendTime;
1697 $this->load();
1698 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1699 return false;
1701 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1702 return time() < $expiry;
1706 * Get the user's e-mail address
1707 * @return \type{\string} User's e-mail address
1709 function getEmail() {
1710 $this->load();
1711 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1712 return $this->mEmail;
1716 * Get the timestamp of the user's e-mail authentication
1717 * @return \type{\string} TS_MW timestamp
1719 function getEmailAuthenticationTimestamp() {
1720 $this->load();
1721 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1722 return $this->mEmailAuthenticated;
1726 * Set the user's e-mail address
1727 * @param $str \type{\string} New e-mail address
1729 function setEmail( $str ) {
1730 $this->load();
1731 $this->mEmail = $str;
1732 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1736 * Get the user's real name
1737 * @return \type{\string} User's real name
1739 function getRealName() {
1740 $this->load();
1741 return $this->mRealName;
1745 * Set the user's real name
1746 * @param $str \type{\string} New real name
1748 function setRealName( $str ) {
1749 $this->load();
1750 $this->mRealName = $str;
1754 * Get the user's current setting for a given option.
1756 * @param $oname \type{\string} The option to check
1757 * @param $defaultOverride \type{\string} A default value returned if the option does not exist
1758 * @return \type{\string} User's current value for the option
1759 * @see getBoolOption()
1760 * @see getIntOption()
1762 function getOption( $oname, $defaultOverride = '' ) {
1763 $this->load();
1765 if ( is_null( $this->mOptions ) ) {
1766 if($defaultOverride != '') {
1767 return $defaultOverride;
1769 $this->mOptions = User::getDefaultOptions();
1772 if ( array_key_exists( $oname, $this->mOptions ) ) {
1773 return trim( $this->mOptions[$oname] );
1774 } else {
1775 return $defaultOverride;
1780 * Get the user's current setting for a given option, as a boolean value.
1782 * @param $oname \type{\string} The option to check
1783 * @return \type{\bool} User's current value for the option
1784 * @see getOption()
1786 function getBoolOption( $oname ) {
1787 return (bool)$this->getOption( $oname );
1792 * Get the user's current setting for a given option, as a boolean value.
1794 * @param $oname \type{\string} The option to check
1795 * @param $defaultOverride \type{\int} A default value returned if the option does not exist
1796 * @return \type{\int} User's current value for the option
1797 * @see getOption()
1799 function getIntOption( $oname, $defaultOverride=0 ) {
1800 $val = $this->getOption( $oname );
1801 if( $val == '' ) {
1802 $val = $defaultOverride;
1804 return intval( $val );
1808 * Set the given option for a user.
1810 * @param $oname \type{\string} The option to set
1811 * @param $val \type{\mixed} New value to set
1813 function setOption( $oname, $val ) {
1814 $this->load();
1815 if ( is_null( $this->mOptions ) ) {
1816 $this->mOptions = User::getDefaultOptions();
1818 if ( $oname == 'skin' ) {
1819 # Clear cached skin, so the new one displays immediately in Special:Preferences
1820 unset( $this->mSkin );
1822 // Filter out any newlines that may have passed through input validation.
1823 // Newlines are used to separate items in the options blob.
1824 if( $val ) {
1825 $val = str_replace( "\r\n", "\n", $val );
1826 $val = str_replace( "\r", "\n", $val );
1827 $val = str_replace( "\n", " ", $val );
1829 // Explicitly NULL values should refer to defaults
1830 global $wgDefaultUserOptions;
1831 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1832 $val = $wgDefaultUserOptions[$oname];
1834 $this->mOptions[$oname] = $val;
1838 * Get the user's preferred date format.
1839 * @return \type{\string} User's preferred date format
1841 function getDatePreference() {
1842 // Important migration for old data rows
1843 if ( is_null( $this->mDatePreference ) ) {
1844 global $wgLang;
1845 $value = $this->getOption( 'date' );
1846 $map = $wgLang->getDatePreferenceMigrationMap();
1847 if ( isset( $map[$value] ) ) {
1848 $value = $map[$value];
1850 $this->mDatePreference = $value;
1852 return $this->mDatePreference;
1856 * Get the permissions this user has.
1857 * @return \type{\arrayof{\string}} Array of permission names
1859 function getRights() {
1860 if ( is_null( $this->mRights ) ) {
1861 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
1862 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
1863 // Force reindexation of rights when a hook has unset one of them
1864 $this->mRights = array_values( $this->mRights );
1866 return $this->mRights;
1870 * Get the list of explicit group memberships this user has.
1871 * The implicit * and user groups are not included.
1872 * @return \type{\arrayof{\string}} Array of internal group names
1874 function getGroups() {
1875 $this->load();
1876 return $this->mGroups;
1880 * Get the list of implicit group memberships this user has.
1881 * This includes all explicit groups, plus 'user' if logged in,
1882 * '*' for all accounts and autopromoted groups
1884 * @param $recache \type{\bool} Whether to avoid the cache
1885 * @return \type{\arrayof{\string}} Array of internal group names
1887 function getEffectiveGroups( $recache = false ) {
1888 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
1889 $this->mEffectiveGroups = $this->getGroups();
1890 $this->mEffectiveGroups[] = '*';
1891 if( $this->getId() ) {
1892 $this->mEffectiveGroups[] = 'user';
1894 $this->mEffectiveGroups = array_unique( array_merge(
1895 $this->mEffectiveGroups,
1896 Autopromote::getAutopromoteGroups( $this )
1897 ) );
1899 # Hook for additional groups
1900 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
1903 return $this->mEffectiveGroups;
1907 * Get the user's edit count.
1908 * @return \type{\int} User's edit count
1910 function getEditCount() {
1911 if ($this->mId) {
1912 if ( !isset( $this->mEditCount ) ) {
1913 /* Populate the count, if it has not been populated yet */
1914 $this->mEditCount = User::edits($this->mId);
1916 return $this->mEditCount;
1917 } else {
1918 /* nil */
1919 return null;
1924 * Add the user to the given group.
1925 * This takes immediate effect.
1926 * @param $group \type{\string} Name of the group to add
1928 function addGroup( $group ) {
1929 $dbw = wfGetDB( DB_MASTER );
1930 if( $this->getId() ) {
1931 $dbw->insert( 'user_groups',
1932 array(
1933 'ug_user' => $this->getID(),
1934 'ug_group' => $group,
1936 'User::addGroup',
1937 array( 'IGNORE' ) );
1940 $this->loadGroups();
1941 $this->mGroups[] = $group;
1942 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1944 $this->invalidateCache();
1948 * Remove the user from the given group.
1949 * This takes immediate effect.
1950 * @param $group \type{\string} Name of the group to remove
1952 function removeGroup( $group ) {
1953 $this->load();
1954 $dbw = wfGetDB( DB_MASTER );
1955 $dbw->delete( 'user_groups',
1956 array(
1957 'ug_user' => $this->getID(),
1958 'ug_group' => $group,
1960 'User::removeGroup' );
1962 $this->loadGroups();
1963 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
1964 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1966 $this->invalidateCache();
1971 * Get whether the user is logged in
1972 * @return \type{\bool} True or false
1974 function isLoggedIn() {
1975 return $this->getID() != 0;
1979 * Get whether the user is anonymous
1980 * @return \type{\bool} True or false
1982 function isAnon() {
1983 return !$this->isLoggedIn();
1987 * Get whether the user is a bot
1988 * @return \type{\bool} True or false
1989 * @deprecated
1991 function isBot() {
1992 wfDeprecated( __METHOD__ );
1993 return $this->isAllowed( 'bot' );
1997 * Check if user is allowed to access a feature / make an action
1998 * @param $action \type{\string} action to be checked
1999 * @return \type{\bool} True if action is allowed, else false
2001 function isAllowed($action='') {
2002 if ( $action === '' )
2003 // In the spirit of DWIM
2004 return true;
2006 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2007 # by misconfiguration: 0 == 'foo'
2008 return in_array( $action, $this->getRights(), true );
2012 * Check whether to enable recent changes patrol features for this user
2013 * @return \type{\bool} True or false
2015 public function useRCPatrol() {
2016 global $wgUseRCPatrol;
2017 return( $wgUseRCPatrol && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
2021 * Check whether to enable new pages patrol features for this user
2022 * @return \type{\bool} True or false
2024 public function useNPPatrol() {
2025 global $wgUseRCPatrol, $wgUseNPPatrol;
2026 return( ($wgUseRCPatrol || $wgUseNPPatrol) && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
2030 * Get the current skin, loading it if required
2031 * @return \type{Skin} Current skin
2032 * @todo FIXME : need to check the old failback system [AV]
2034 function &getSkin() {
2035 global $wgRequest;
2036 if ( ! isset( $this->mSkin ) ) {
2037 wfProfileIn( __METHOD__ );
2039 # get the user skin
2040 $userSkin = $this->getOption( 'skin' );
2041 $userSkin = $wgRequest->getVal('useskin', $userSkin);
2043 $this->mSkin =& Skin::newFromKey( $userSkin );
2044 wfProfileOut( __METHOD__ );
2046 return $this->mSkin;
2050 * Check the watched status of an article.
2051 * @param $title \type{Title} Title of the article to look at
2052 * @return \type{\bool} True if article is watched
2054 function isWatched( $title ) {
2055 $wl = WatchedItem::fromUserTitle( $this, $title );
2056 return $wl->isWatched();
2060 * Watch an article.
2061 * @param $title \type{Title} Title of the article to look at
2063 function addWatch( $title ) {
2064 $wl = WatchedItem::fromUserTitle( $this, $title );
2065 $wl->addWatch();
2066 $this->invalidateCache();
2070 * Stop watching an article.
2071 * @param $title \type{Title} Title of the article to look at
2073 function removeWatch( $title ) {
2074 $wl = WatchedItem::fromUserTitle( $this, $title );
2075 $wl->removeWatch();
2076 $this->invalidateCache();
2080 * Clear the user's notification timestamp for the given title.
2081 * If e-notif e-mails are on, they will receive notification mails on
2082 * the next change of the page if it's watched etc.
2083 * @param $title \type{Title} Title of the article to look at
2085 function clearNotification( &$title ) {
2086 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2088 # Do nothing if the database is locked to writes
2089 if( wfReadOnly() ) {
2090 return;
2093 if ($title->getNamespace() == NS_USER_TALK &&
2094 $title->getText() == $this->getName() ) {
2095 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
2096 return;
2097 $this->setNewtalk( false );
2100 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2101 return;
2104 if( $this->isAnon() ) {
2105 // Nothing else to do...
2106 return;
2109 // Only update the timestamp if the page is being watched.
2110 // The query to find out if it is watched is cached both in memcached and per-invocation,
2111 // and when it does have to be executed, it can be on a slave
2112 // If this is the user's newtalk page, we always update the timestamp
2113 if ($title->getNamespace() == NS_USER_TALK &&
2114 $title->getText() == $wgUser->getName())
2116 $watched = true;
2117 } elseif ( $this->getId() == $wgUser->getId() ) {
2118 $watched = $title->userIsWatching();
2119 } else {
2120 $watched = true;
2123 // If the page is watched by the user (or may be watched), update the timestamp on any
2124 // any matching rows
2125 if ( $watched ) {
2126 $dbw = wfGetDB( DB_MASTER );
2127 $dbw->update( 'watchlist',
2128 array( /* SET */
2129 'wl_notificationtimestamp' => NULL
2130 ), array( /* WHERE */
2131 'wl_title' => $title->getDBkey(),
2132 'wl_namespace' => $title->getNamespace(),
2133 'wl_user' => $this->getID()
2134 ), __METHOD__
2140 * Resets all of the given user's page-change notification timestamps.
2141 * If e-notif e-mails are on, they will receive notification mails on
2142 * the next change of any watched page.
2144 * @param $currentUser \type{\int} %User ID
2146 function clearAllNotifications( $currentUser ) {
2147 global $wgUseEnotif, $wgShowUpdatedMarker;
2148 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2149 $this->setNewtalk( false );
2150 return;
2152 if( $currentUser != 0 ) {
2153 $dbw = wfGetDB( DB_MASTER );
2154 $dbw->update( 'watchlist',
2155 array( /* SET */
2156 'wl_notificationtimestamp' => NULL
2157 ), array( /* WHERE */
2158 'wl_user' => $currentUser
2159 ), __METHOD__
2161 # We also need to clear here the "you have new message" notification for the own user_talk page
2162 # This is cleared one page view later in Article::viewUpdates();
2167 * Encode this user's options as a string
2168 * @return \type{\string} Encoded options
2169 * @private
2171 function encodeOptions() {
2172 $this->load();
2173 if ( is_null( $this->mOptions ) ) {
2174 $this->mOptions = User::getDefaultOptions();
2176 $a = array();
2177 foreach ( $this->mOptions as $oname => $oval ) {
2178 array_push( $a, $oname.'='.$oval );
2180 $s = implode( "\n", $a );
2181 return $s;
2185 * Set this user's options from an encoded string
2186 * @param $str \type{\string} Encoded options to import
2187 * @private
2189 function decodeOptions( $str ) {
2190 $this->mOptions = array();
2191 $a = explode( "\n", $str );
2192 foreach ( $a as $s ) {
2193 $m = array();
2194 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2195 $this->mOptions[$m[1]] = $m[2];
2201 * Set a cookie on the user's client. Wrapper for
2202 * WebResponse::setCookie
2204 protected function setCookie( $name, $value, $exp=0 ) {
2205 global $wgRequest;
2206 $wgRequest->response()->setcookie( $name, $value, $exp );
2210 * Clear a cookie on the user's client
2211 * @param $name \type{\string} Name of the cookie to clear
2213 protected function clearCookie( $name ) {
2214 $this->setCookie( $name, '', time() - 86400 );
2218 * Set the default cookies for this session on the user's client.
2220 function setCookies() {
2221 $this->load();
2222 if ( 0 == $this->mId ) return;
2223 $session = array(
2224 'wsUserID' => $this->mId,
2225 'wsToken' => $this->mToken,
2226 'wsUserName' => $this->getName()
2228 $cookies = array(
2229 'UserID' => $this->mId,
2230 'UserName' => $this->getName(),
2232 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2233 $cookies['Token'] = $this->mToken;
2234 } else {
2235 $cookies['Token'] = false;
2238 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2239 $_SESSION = $session + $_SESSION;
2240 foreach ( $cookies as $name => $value ) {
2241 if ( $value === false ) {
2242 $this->clearCookie( $name );
2243 } else {
2244 $this->setCookie( $name, $value );
2250 * Log this user out.
2252 function logout() {
2253 global $wgUser;
2254 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2255 $this->doLogout();
2260 * Clear the user's cookies and session, and reset the instance cache.
2261 * @private
2262 * @see logout()
2264 function doLogout() {
2265 $this->clearInstanceCache( 'defaults' );
2267 $_SESSION['wsUserID'] = 0;
2269 $this->clearCookie( 'UserID' );
2270 $this->clearCookie( 'Token' );
2272 # Remember when user logged out, to prevent seeing cached pages
2273 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2277 * Save this user's settings into the database.
2278 * @todo Only rarely do all these fields need to be set!
2280 function saveSettings() {
2281 $this->load();
2282 if ( wfReadOnly() ) { return; }
2283 if ( 0 == $this->mId ) { return; }
2285 $this->mTouched = self::newTouchedTimestamp();
2287 $dbw = wfGetDB( DB_MASTER );
2288 $dbw->update( 'user',
2289 array( /* SET */
2290 'user_name' => $this->mName,
2291 'user_password' => $this->mPassword,
2292 'user_newpassword' => $this->mNewpassword,
2293 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2294 'user_real_name' => $this->mRealName,
2295 'user_email' => $this->mEmail,
2296 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2297 'user_options' => $this->encodeOptions(),
2298 'user_touched' => $dbw->timestamp($this->mTouched),
2299 'user_token' => $this->mToken,
2300 'user_email_token' => $this->mEmailToken,
2301 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2302 ), array( /* WHERE */
2303 'user_id' => $this->mId
2304 ), __METHOD__
2306 wfRunHooks( 'UserSaveSettings', array( $this ) );
2307 $this->clearSharedCache();
2311 * If only this user's username is known, and it exists, return the user ID.
2313 function idForName() {
2314 $s = trim( $this->getName() );
2315 if ( $s === '' ) return 0;
2317 $dbr = wfGetDB( DB_SLAVE );
2318 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2319 if ( $id === false ) {
2320 $id = 0;
2322 return $id;
2326 * Add a user to the database, return the user object
2328 * @param $name \type{\string} Username to add
2329 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2330 * - password The user's password. Password logins will be disabled if this is omitted.
2331 * - newpassword A temporary password mailed to the user
2332 * - email The user's email address
2333 * - email_authenticated The email authentication timestamp
2334 * - real_name The user's real name
2335 * - options An associative array of non-default options
2336 * - token Random authentication token. Do not set.
2337 * - registration Registration timestamp. Do not set.
2339 * @return \type{User} A new User object, or null if the username already exists
2341 static function createNew( $name, $params = array() ) {
2342 $user = new User;
2343 $user->load();
2344 if ( isset( $params['options'] ) ) {
2345 $user->mOptions = $params['options'] + $user->mOptions;
2346 unset( $params['options'] );
2348 $dbw = wfGetDB( DB_MASTER );
2349 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2350 $fields = array(
2351 'user_id' => $seqVal,
2352 'user_name' => $name,
2353 'user_password' => $user->mPassword,
2354 'user_newpassword' => $user->mNewpassword,
2355 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ),
2356 'user_email' => $user->mEmail,
2357 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2358 'user_real_name' => $user->mRealName,
2359 'user_options' => $user->encodeOptions(),
2360 'user_token' => $user->mToken,
2361 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2362 'user_editcount' => 0,
2364 foreach ( $params as $name => $value ) {
2365 $fields["user_$name"] = $value;
2367 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2368 if ( $dbw->affectedRows() ) {
2369 $newUser = User::newFromId( $dbw->insertId() );
2370 } else {
2371 $newUser = null;
2373 return $newUser;
2377 * Add this existing user object to the database
2379 function addToDatabase() {
2380 $this->load();
2381 $dbw = wfGetDB( DB_MASTER );
2382 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2383 $dbw->insert( 'user',
2384 array(
2385 'user_id' => $seqVal,
2386 'user_name' => $this->mName,
2387 'user_password' => $this->mPassword,
2388 'user_newpassword' => $this->mNewpassword,
2389 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ),
2390 'user_email' => $this->mEmail,
2391 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2392 'user_real_name' => $this->mRealName,
2393 'user_options' => $this->encodeOptions(),
2394 'user_token' => $this->mToken,
2395 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2396 'user_editcount' => 0,
2397 ), __METHOD__
2399 $this->mId = $dbw->insertId();
2401 // Clear instance cache other than user table data, which is already accurate
2402 $this->clearInstanceCache();
2406 * If this (non-anonymous) user is blocked, block any IP address
2407 * they've successfully logged in from.
2409 function spreadBlock() {
2410 wfDebug( __METHOD__."()\n" );
2411 $this->load();
2412 if ( $this->mId == 0 ) {
2413 return;
2416 $userblock = Block::newFromDB( '', $this->mId );
2417 if ( !$userblock ) {
2418 return;
2421 $userblock->doAutoblock( wfGetIp() );
2426 * Generate a string which will be different for any combination of
2427 * user options which would produce different parser output.
2428 * This will be used as part of the hash key for the parser cache,
2429 * so users will the same options can share the same cached data
2430 * safely.
2432 * Extensions which require it should install 'PageRenderingHash' hook,
2433 * which will give them a chance to modify this key based on their own
2434 * settings.
2436 * @return \type{\string} Page rendering hash
2438 function getPageRenderingHash() {
2439 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2440 if( $this->mHash ){
2441 return $this->mHash;
2444 // stubthreshold is only included below for completeness,
2445 // it will always be 0 when this function is called by parsercache.
2447 $confstr = $this->getOption( 'math' );
2448 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2449 if ( $wgUseDynamicDates ) {
2450 $confstr .= '!' . $this->getDatePreference();
2452 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
2453 $confstr .= '!' . $wgLang->getCode();
2454 $confstr .= '!' . $this->getOption( 'thumbsize' );
2455 // add in language specific options, if any
2456 $extra = $wgContLang->getExtraHashOptions();
2457 $confstr .= $extra;
2459 $confstr .= $wgRenderHashAppend;
2461 // Give a chance for extensions to modify the hash, if they have
2462 // extra options or other effects on the parser cache.
2463 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2465 // Make it a valid memcached key fragment
2466 $confstr = str_replace( ' ', '_', $confstr );
2467 $this->mHash = $confstr;
2468 return $confstr;
2472 * Get whether the user is explicitly blocked from account creation.
2473 * @return \type{\bool} True if blocked
2475 function isBlockedFromCreateAccount() {
2476 $this->getBlockedStatus();
2477 return $this->mBlock && $this->mBlock->mCreateAccount;
2481 * Get whether the user is blocked from using Special:Emailuser.
2482 * @return \type{\bool} True if blocked
2484 function isBlockedFromEmailuser() {
2485 $this->getBlockedStatus();
2486 return $this->mBlock && $this->mBlock->mBlockEmail;
2490 * Get whether the user is allowed to create an account.
2491 * @return \type{\bool} True if allowed
2493 function isAllowedToCreateAccount() {
2494 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2498 * @deprecated
2500 function setLoaded( $loaded ) {
2501 wfDeprecated( __METHOD__ );
2505 * Get this user's personal page title.
2507 * @return \type{Title} User's personal page title
2509 function getUserPage() {
2510 return Title::makeTitle( NS_USER, $this->getName() );
2514 * Get this user's talk page title.
2516 * @return \type{Title} User's talk page title
2518 function getTalkPage() {
2519 $title = $this->getUserPage();
2520 return $title->getTalkPage();
2524 * Get the maximum valid user ID.
2525 * @return \type{\int} %User ID
2526 * @static
2528 function getMaxID() {
2529 static $res; // cache
2531 if ( isset( $res ) )
2532 return $res;
2533 else {
2534 $dbr = wfGetDB( DB_SLAVE );
2535 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2540 * Determine whether the user is a newbie. Newbies are either
2541 * anonymous IPs, or the most recently created accounts.
2542 * @return \type{\bool} True if the user is a newbie
2544 function isNewbie() {
2545 return !$this->isAllowed( 'autoconfirmed' );
2549 * Is the user active? We check to see if they've made at least
2550 * X number of edits in the last Y days.
2552 * @return \type{\bool} True if the user is active, false if not.
2554 public function isActiveEditor() {
2555 global $wgActiveUserEditCount, $wgActiveUserDays;
2556 $dbr = wfGetDB( DB_SLAVE );
2558 // Stolen without shame from RC
2559 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2560 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime % 86400 );
2561 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2563 $res = $dbr->select( 'revision', '1',
2564 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2565 __METHOD__,
2566 array('LIMIT' => $wgActiveUserEditCount ) );
2568 $count = $dbr->numRows($res);
2569 $dbr->freeResult($res);
2571 return $count == $wgActiveUserEditCount;
2575 * Check to see if the given clear-text password is one of the accepted passwords
2576 * @param $password \type{\string} user password.
2577 * @return \type{\bool} True if the given password is correct, otherwise False.
2579 function checkPassword( $password ) {
2580 global $wgAuth;
2581 $this->load();
2583 // Even though we stop people from creating passwords that
2584 // are shorter than this, doesn't mean people wont be able
2585 // to. Certain authentication plugins do NOT want to save
2586 // domain passwords in a mysql database, so we should
2587 // check this (incase $wgAuth->strict() is false).
2588 if( !$this->isValidPassword( $password ) ) {
2589 return false;
2592 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2593 return true;
2594 } elseif( $wgAuth->strict() ) {
2595 /* Auth plugin doesn't allow local authentication */
2596 return false;
2597 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2598 /* Auth plugin doesn't allow local authentication for this user name */
2599 return false;
2601 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
2602 return true;
2603 } elseif ( function_exists( 'iconv' ) ) {
2604 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2605 # Check for this with iconv
2606 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2607 if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) {
2608 return true;
2611 return false;
2615 * Check if the given clear-text password matches the temporary password
2616 * sent by e-mail for password reset operations.
2617 * @return \type{\bool} True if matches, false otherwise
2619 function checkTemporaryPassword( $plaintext ) {
2620 return self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() );
2624 * Initialize (if necessary) and return a session token value
2625 * which can be used in edit forms to show that the user's
2626 * login credentials aren't being hijacked with a foreign form
2627 * submission.
2629 * @param $salt \twotypes{\string,\arrayof{\string}} Optional function-specific data for hashing
2630 * @return \type{\string} The new edit token
2632 function editToken( $salt = '' ) {
2633 if ( $this->isAnon() ) {
2634 return EDIT_TOKEN_SUFFIX;
2635 } else {
2636 if( !isset( $_SESSION['wsEditToken'] ) ) {
2637 $token = $this->generateToken();
2638 $_SESSION['wsEditToken'] = $token;
2639 } else {
2640 $token = $_SESSION['wsEditToken'];
2642 if( is_array( $salt ) ) {
2643 $salt = implode( '|', $salt );
2645 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2650 * Generate a looking random token for various uses.
2652 * @param $salt \type{\string} Optional salt value
2653 * @return \type{\string} The new random token
2655 function generateToken( $salt = '' ) {
2656 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2657 return md5( $token . $salt );
2661 * Check given value against the token value stored in the session.
2662 * A match should confirm that the form was submitted from the
2663 * user's own login session, not a form submission from a third-party
2664 * site.
2666 * @param $val \type{\string} Input value to compare
2667 * @param $salt \type{\string} Optional function-specific data for hashing
2668 * @return \type{\bool} Whether the token matches
2670 function matchEditToken( $val, $salt = '' ) {
2671 $sessionToken = $this->editToken( $salt );
2672 if ( $val != $sessionToken ) {
2673 wfDebug( "User::matchEditToken: broken session data\n" );
2675 return $val == $sessionToken;
2679 * Check given value against the token value stored in the session,
2680 * ignoring the suffix.
2682 * @param $val \type{\string} Input value to compare
2683 * @param $salt \type{\string} Optional function-specific data for hashing
2684 * @return \type{\bool} Whether the token matches
2686 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2687 $sessionToken = $this->editToken( $salt );
2688 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2692 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2693 * mail to the user's given address.
2695 * @return \twotypes{\bool,WikiError} True on success, a WikiError object on failure.
2697 function sendConfirmationMail() {
2698 global $wgLang;
2699 $expiration = null; // gets passed-by-ref and defined in next line.
2700 $token = $this->confirmationToken( $expiration );
2701 $url = $this->confirmationTokenUrl( $token );
2702 $invalidateURL = $this->invalidationTokenUrl( $token );
2703 $this->saveSettings();
2705 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2706 wfMsg( 'confirmemail_body',
2707 wfGetIP(),
2708 $this->getName(),
2709 $url,
2710 $wgLang->timeanddate( $expiration, false ),
2711 $invalidateURL ) );
2715 * Send an e-mail to this user's account. Does not check for
2716 * confirmed status or validity.
2718 * @param $subject \type{\string} Message subject
2719 * @param $body \type{\string} Message body
2720 * @param $from \type{\string} Optional From address; if unspecified, default $wgPasswordSender will be used
2721 * @param $replyto \type{\string} Reply-to address
2722 * @return \twotypes{\bool,WikiError} True on success, a WikiError object on failure
2724 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2725 if( is_null( $from ) ) {
2726 global $wgPasswordSender;
2727 $from = $wgPasswordSender;
2730 $to = new MailAddress( $this );
2731 $sender = new MailAddress( $from );
2732 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2736 * Generate, store, and return a new e-mail confirmation code.
2737 * A hash (unsalted, since it's used as a key) is stored.
2739 * @note Call saveSettings() after calling this function to commit
2740 * this change to the database.
2742 * @param[out] &$expiration \type{\mixed} Accepts the expiration time
2743 * @return \type{\string} New token
2744 * @private
2746 function confirmationToken( &$expiration ) {
2747 $now = time();
2748 $expires = $now + 7 * 24 * 60 * 60;
2749 $expiration = wfTimestamp( TS_MW, $expires );
2750 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
2751 $hash = md5( $token );
2752 $this->load();
2753 $this->mEmailToken = $hash;
2754 $this->mEmailTokenExpires = $expiration;
2755 return $token;
2759 * Return a URL the user can use to confirm their email address.
2760 * @param $token \type{\string} Accepts the email confirmation token
2761 * @return \type{\string} New token URL
2762 * @private
2764 function confirmationTokenUrl( $token ) {
2765 return $this->getTokenUrl( 'ConfirmEmail', $token );
2768 * Return a URL the user can use to invalidate their email address.
2770 * @param $token \type{\string} Accepts the email confirmation token
2771 * @return \type{\string} New token URL
2772 * @private
2774 function invalidationTokenUrl( $token ) {
2775 return $this->getTokenUrl( 'Invalidateemail', $token );
2779 * Internal function to format the e-mail validation/invalidation URLs.
2780 * This uses $wgArticlePath directly as a quickie hack to use the
2781 * hardcoded English names of the Special: pages, for ASCII safety.
2783 * @note Since these URLs get dropped directly into emails, using the
2784 * short English names avoids insanely long URL-encoded links, which
2785 * also sometimes can get corrupted in some browsers/mailers
2786 * (bug 6957 with Gmail and Internet Explorer).
2788 * @param $page \type{\string} Special page
2789 * @param $token \type{\string} Token
2790 * @return \type{\string} Formatted URL
2792 protected function getTokenUrl( $page, $token ) {
2793 global $wgArticlePath;
2794 return wfExpandUrl(
2795 str_replace(
2796 '$1',
2797 "Special:$page/$token",
2798 $wgArticlePath ) );
2802 * Mark the e-mail address confirmed.
2804 * @note Call saveSettings() after calling this function to commit the change.
2806 function confirmEmail() {
2807 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2808 return true;
2812 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2813 * address if it was already confirmed.
2815 * @note Call saveSettings() after calling this function to commit the change.
2817 function invalidateEmail() {
2818 $this->load();
2819 $this->mEmailToken = null;
2820 $this->mEmailTokenExpires = null;
2821 $this->setEmailAuthenticationTimestamp( null );
2822 return true;
2826 * Set the e-mail authentication timestamp.
2827 * @param $timestamp \type{\string} TS_MW timestamp
2829 function setEmailAuthenticationTimestamp( $timestamp ) {
2830 $this->load();
2831 $this->mEmailAuthenticated = $timestamp;
2832 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2836 * Is this user allowed to send e-mails within limits of current
2837 * site configuration?
2838 * @return \type{\bool} True if allowed
2840 function canSendEmail() {
2841 $canSend = $this->isEmailConfirmed();
2842 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2843 return $canSend;
2847 * Is this user allowed to receive e-mails within limits of current
2848 * site configuration?
2849 * @return \type{\bool} True if allowed
2851 function canReceiveEmail() {
2852 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2856 * Is this user's e-mail address valid-looking and confirmed within
2857 * limits of the current site configuration?
2859 * @note If $wgEmailAuthentication is on, this may require the user to have
2860 * confirmed their address by returning a code or using a password
2861 * sent to the address from the wiki.
2863 * @return \type{\bool} True if confirmed
2865 function isEmailConfirmed() {
2866 global $wgEmailAuthentication;
2867 $this->load();
2868 $confirmed = true;
2869 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2870 if( $this->isAnon() )
2871 return false;
2872 if( !self::isValidEmailAddr( $this->mEmail ) )
2873 return false;
2874 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2875 return false;
2876 return true;
2877 } else {
2878 return $confirmed;
2883 * Check whether there is an outstanding request for e-mail confirmation.
2884 * @return \type{\bool} True if pending
2886 function isEmailConfirmationPending() {
2887 global $wgEmailAuthentication;
2888 return $wgEmailAuthentication &&
2889 !$this->isEmailConfirmed() &&
2890 $this->mEmailToken &&
2891 $this->mEmailTokenExpires > wfTimestamp();
2895 * Get the timestamp of account creation.
2897 * @return \twotypes{\string,\bool} string Timestamp of account creation, or false for
2898 * non-existent/anonymous user accounts.
2900 public function getRegistration() {
2901 return $this->mId > 0
2902 ? $this->mRegistration
2903 : false;
2907 * Get the permissions associated with a given list of groups
2909 * @param $groups \type{\arrayof{\string}} List of internal group names
2910 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
2912 static function getGroupPermissions( $groups ) {
2913 global $wgGroupPermissions;
2914 $rights = array();
2915 foreach( $groups as $group ) {
2916 if( isset( $wgGroupPermissions[$group] ) ) {
2917 $rights = array_merge( $rights,
2918 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2921 return $rights;
2925 * Get all the groups who have a given permission
2927 * @param $role \type{\string} Role to check
2928 * @return \type{\arrayof{\string}} List of internal group names with the given permission
2930 static function getGroupsWithPermission( $role ) {
2931 global $wgGroupPermissions;
2932 $allowedGroups = array();
2933 foreach ( $wgGroupPermissions as $group => $rights ) {
2934 if ( isset( $rights[$role] ) && $rights[$role] ) {
2935 $allowedGroups[] = $group;
2938 return $allowedGroups;
2942 * Get the localized descriptive name for a group, if it exists
2944 * @param $group \type{\string} Internal group name
2945 * @return \type{\string} Localized descriptive group name
2947 static function getGroupName( $group ) {
2948 global $wgMessageCache;
2949 $wgMessageCache->loadAllMessages();
2950 $key = "group-$group";
2951 $name = wfMsg( $key );
2952 return $name == '' || wfEmptyMsg( $key, $name )
2953 ? $group
2954 : $name;
2958 * Get the localized descriptive name for a member of a group, if it exists
2960 * @param $group \type{\string} Internal group name
2961 * @return \type{\string} Localized name for group member
2963 static function getGroupMember( $group ) {
2964 global $wgMessageCache;
2965 $wgMessageCache->loadAllMessages();
2966 $key = "group-$group-member";
2967 $name = wfMsg( $key );
2968 return $name == '' || wfEmptyMsg( $key, $name )
2969 ? $group
2970 : $name;
2974 * Return the set of defined explicit groups.
2975 * The implicit groups (by default *, 'user' and 'autoconfirmed')
2976 * are not included, as they are defined automatically, not in the database.
2977 * @return \type{\arrayof{\string}} Array of internal group names
2979 static function getAllGroups() {
2980 global $wgGroupPermissions;
2981 return array_diff(
2982 array_keys( $wgGroupPermissions ),
2983 self::getImplicitGroups()
2988 * Get a list of all available permissions.
2989 * @return \type{\arrayof{\string}} Array of permission names
2991 static function getAllRights() {
2992 if ( self::$mAllRights === false ) {
2993 global $wgAvailableRights;
2994 if ( count( $wgAvailableRights ) ) {
2995 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
2996 } else {
2997 self::$mAllRights = self::$mCoreRights;
2999 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
3001 return self::$mAllRights;
3005 * Get a list of implicit groups
3006 * @return \type{\arrayof{\string}} Array of internal group names
3008 public static function getImplicitGroups() {
3009 global $wgImplicitGroups;
3010 $groups = $wgImplicitGroups;
3011 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3012 return $groups;
3016 * Get the title of a page describing a particular group
3018 * @param $group \type{\string} Internal group name
3019 * @return \twotypes{Title,\bool} Title of the page if it exists, false otherwise
3021 static function getGroupPage( $group ) {
3022 global $wgMessageCache;
3023 $wgMessageCache->loadAllMessages();
3024 $page = wfMsgForContent( 'grouppage-' . $group );
3025 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3026 $title = Title::newFromText( $page );
3027 if( is_object( $title ) )
3028 return $title;
3030 return false;
3034 * Create a link to the group in HTML, if available;
3035 * else return the group name.
3037 * @param $group \type{\string} Internal name of the group
3038 * @param $text \type{\string} The text of the link
3039 * @return \type{\string} HTML link to the group
3041 static function makeGroupLinkHTML( $group, $text = '' ) {
3042 if( $text == '' ) {
3043 $text = self::getGroupName( $group );
3045 $title = self::getGroupPage( $group );
3046 if( $title ) {
3047 global $wgUser;
3048 $sk = $wgUser->getSkin();
3049 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
3050 } else {
3051 return $text;
3056 * Create a link to the group in Wikitext, if available;
3057 * else return the group name.
3059 * @param $group \type{\string} Internal name of the group
3060 * @param $text \type{\string} The text of the link
3061 * @return \type{\string} Wikilink to the group
3063 static function makeGroupLinkWiki( $group, $text = '' ) {
3064 if( $text == '' ) {
3065 $text = self::getGroupName( $group );
3067 $title = self::getGroupPage( $group );
3068 if( $title ) {
3069 $page = $title->getPrefixedText();
3070 return "[[$page|$text]]";
3071 } else {
3072 return $text;
3077 * Increment the user's edit-count field.
3078 * Will have no effect for anonymous users.
3080 function incEditCount() {
3081 if( !$this->isAnon() ) {
3082 $dbw = wfGetDB( DB_MASTER );
3083 $dbw->update( 'user',
3084 array( 'user_editcount=user_editcount+1' ),
3085 array( 'user_id' => $this->getId() ),
3086 __METHOD__ );
3088 // Lazy initialization check...
3089 if( $dbw->affectedRows() == 0 ) {
3090 // Pull from a slave to be less cruel to servers
3091 // Accuracy isn't the point anyway here
3092 $dbr = wfGetDB( DB_SLAVE );
3093 $count = $dbr->selectField( 'revision',
3094 'COUNT(rev_user)',
3095 array( 'rev_user' => $this->getId() ),
3096 __METHOD__ );
3098 // Now here's a goddamn hack...
3099 if( $dbr !== $dbw ) {
3100 // If we actually have a slave server, the count is
3101 // at least one behind because the current transaction
3102 // has not been committed and replicated.
3103 $count++;
3104 } else {
3105 // But if DB_SLAVE is selecting the master, then the
3106 // count we just read includes the revision that was
3107 // just added in the working transaction.
3110 $dbw->update( 'user',
3111 array( 'user_editcount' => $count ),
3112 array( 'user_id' => $this->getId() ),
3113 __METHOD__ );
3116 // edit count in user cache too
3117 $this->invalidateCache();
3121 * Get the description of a given right
3123 * @param $right \type{\string} Right to query
3124 * @return \type{\string} Localized description of the right
3126 static function getRightDescription( $right ) {
3127 global $wgMessageCache;
3128 $wgMessageCache->loadAllMessages();
3129 $key = "right-$right";
3130 $name = wfMsg( $key );
3131 return $name == '' || wfEmptyMsg( $key, $name )
3132 ? $right
3133 : $name;
3137 * Make an old-style password hash
3139 * @param $password \type{\string} Plain-text password
3140 * @param $userId \type{\string} %User ID
3141 * @return \type{\string} Password hash
3143 static function oldCrypt( $password, $userId ) {
3144 global $wgPasswordSalt;
3145 if ( $wgPasswordSalt ) {
3146 return md5( $userId . '-' . md5( $password ) );
3147 } else {
3148 return md5( $password );
3153 * Make a new-style password hash
3155 * @param $password \type{\string} Plain-text password
3156 * @param $salt \type{\string} Optional salt, may be random or the user ID.
3157 * If unspecified or false, will generate one automatically
3158 * @return \type{\string} Password hash
3160 static function crypt( $password, $salt = false ) {
3161 global $wgPasswordSalt;
3163 if($wgPasswordSalt) {
3164 if ( $salt === false ) {
3165 $salt = substr( wfGenerateToken(), 0, 8 );
3167 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3168 } else {
3169 return ':A:' . md5( $password);
3174 * Compare a password hash with a plain-text password. Requires the user
3175 * ID if there's a chance that the hash is an old-style hash.
3177 * @param $hash \type{\string} Password hash
3178 * @param $password \type{\string} Plain-text password to compare
3179 * @param $userId \type{\string} %User ID for old-style password salt
3180 * @return \type{\bool} True if matches, false otherwise
3182 static function comparePasswords( $hash, $password, $userId = false ) {
3183 $m = false;
3184 $type = substr( $hash, 0, 3 );
3185 if ( $type == ':A:' ) {
3186 # Unsalted
3187 return md5( $password ) === substr( $hash, 3 );
3188 } elseif ( $type == ':B:' ) {
3189 # Salted
3190 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3191 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3192 } else {
3193 # Old-style
3194 return self::oldCrypt( $password, $userId ) === $hash;
3199 * Add a newuser log entry for this user
3200 * @param bool $byEmail, account made by email?
3202 public function addNewUserLogEntry( $byEmail = false ) {
3203 global $wgUser, $wgContLang, $wgNewUserLog;
3204 if( empty($wgNewUserLog) ) {
3205 return true; // disabled
3207 $talk = $wgContLang->getFormattedNsText( NS_TALK );
3208 if( $this->getName() == $wgUser->getName() ) {
3209 $action = 'create';
3210 $message = '';
3211 } else {
3212 $action = 'create2';
3213 $message = $byEmail ? wfMsgForContent( 'newuserlog-byemail' ) : '';
3215 $log = new LogPage( 'newusers' );
3216 $log->addEntry( $action, $this->getUserPage(), $message, array( $this->getId() ) );
3217 return true;
3221 * Add an autocreate newuser log entry for this user
3222 * Used by things like CentralAuth and perhaps other authplugins.
3224 public function addNewUserLogEntryAutoCreate() {
3225 global $wgNewUserLog;
3226 if( empty($wgNewUserLog) ) {
3227 return true; // disabled
3229 $log = new LogPage( 'newusers', false );
3230 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3231 return true;