Update messages.inc and rebuild MessagesEn.php
[mediawiki.git] / includes / User.php
blob4211917d5c77aab84760b41a589e7c88587bbd08
1 <?php
2 /**
3 * See user.txt
4 * @file
5 */
7 # Number of characters in user_token field
8 define( 'USER_TOKEN_LENGTH', 32 );
10 # Serialized record version
11 define( 'MW_USER_VERSION', 6 );
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 * @ingroup 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 * Core rights
110 * Each of these should have a corresponding message of the form "right-$right"
112 static $mCoreRights = array(
113 'apihighlimits',
114 'autoconfirmed',
115 'autopatrol',
116 'bigdelete',
117 'block',
118 'blockemail',
119 'bot',
120 'browsearchive',
121 'createaccount',
122 'createpage',
123 'createtalk',
124 'delete',
125 'deletedhistory',
126 'edit',
127 'editinterface',
128 'editusercssjs',
129 'import',
130 'importupload',
131 'ipblock-exempt',
132 'markbotedits',
133 'minoredit',
134 'move',
135 'nominornewtalk',
136 'patrol',
137 'protect',
138 'proxyunbannable',
139 'purge',
140 'read',
141 'reupload',
142 'reupload-shared',
143 'rollback',
144 'suppressredirect',
145 'trackback',
146 'undelete',
147 'unwatchedpages',
148 'upload',
149 'upload_by_url',
150 'userrights',
152 static $mAllRights = false;
155 * The cache variable declarations
157 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
158 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
159 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
162 * Whether the cache variables have been loaded
164 var $mDataLoaded;
167 * Initialisation data source if mDataLoaded==false. May be one of:
168 * defaults anonymous user initialised from class defaults
169 * name initialise from mName
170 * id initialise from mId
171 * session log in from cookies or session if possible
173 * Use the User::newFrom*() family of functions to set this.
175 var $mFrom;
178 * Lazy-initialised variables, invalidated with clearInstanceCache
180 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
181 $mBlockreason, $mBlock, $mEffectiveGroups;
184 * Lightweight constructor for anonymous user
185 * Use the User::newFrom* factory functions for other kinds of users
187 function User() {
188 $this->clearInstanceCache( 'defaults' );
192 * Load the user table data for this object from the source given by mFrom
194 function load() {
195 if ( $this->mDataLoaded ) {
196 return;
198 wfProfileIn( __METHOD__ );
200 # Set it now to avoid infinite recursion in accessors
201 $this->mDataLoaded = true;
203 switch ( $this->mFrom ) {
204 case 'defaults':
205 $this->loadDefaults();
206 break;
207 case 'name':
208 $this->mId = self::idFromName( $this->mName );
209 if ( !$this->mId ) {
210 # Nonexistent user placeholder object
211 $this->loadDefaults( $this->mName );
212 } else {
213 $this->loadFromId();
215 break;
216 case 'id':
217 $this->loadFromId();
218 break;
219 case 'session':
220 $this->loadFromSession();
221 break;
222 default:
223 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
225 wfProfileOut( __METHOD__ );
229 * Load user table data given mId
230 * @return false if the ID does not exist, true otherwise
231 * @private
233 function loadFromId() {
234 global $wgMemc;
235 if ( $this->mId == 0 ) {
236 $this->loadDefaults();
237 return false;
240 # Try cache
241 $key = wfMemcKey( 'user', 'id', $this->mId );
242 $data = $wgMemc->get( $key );
243 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
244 # Object is expired, load from DB
245 $data = false;
248 if ( !$data ) {
249 wfDebug( "Cache miss for user {$this->mId}\n" );
250 # Load from DB
251 if ( !$this->loadFromDatabase() ) {
252 # Can't load from ID, user is anonymous
253 return false;
255 $this->saveToCache();
256 } else {
257 wfDebug( "Got user {$this->mId} from cache\n" );
258 # Restore from cache
259 foreach ( self::$mCacheVars as $name ) {
260 $this->$name = $data[$name];
263 return true;
267 * Save user data to the shared cache
269 function saveToCache() {
270 $this->load();
271 $this->loadGroups();
272 if ( $this->isAnon() ) {
273 // Anonymous users are uncached
274 return;
276 $data = array();
277 foreach ( self::$mCacheVars as $name ) {
278 $data[$name] = $this->$name;
280 $data['mVersion'] = MW_USER_VERSION;
281 $key = wfMemcKey( 'user', 'id', $this->mId );
282 global $wgMemc;
283 $wgMemc->set( $key, $data );
287 * Static factory method for creation from username.
289 * This is slightly less efficient than newFromId(), so use newFromId() if
290 * you have both an ID and a name handy.
292 * @param string $name Username, validated by Title:newFromText()
293 * @param mixed $validate Validate username. Takes the same parameters as
294 * User::getCanonicalName(), except that true is accepted as an alias
295 * for 'valid', for BC.
297 * @return User object, or null if the username is invalid. If the username
298 * is not present in the database, the result will be a user object with
299 * a name, zero user ID and default settings.
300 * @static
302 static function newFromName( $name, $validate = 'valid' ) {
303 if ( $validate === true ) {
304 $validate = 'valid';
306 $name = self::getCanonicalName( $name, $validate );
307 if ( $name === false ) {
308 return null;
309 } else {
310 # Create unloaded user object
311 $u = new User;
312 $u->mName = $name;
313 $u->mFrom = 'name';
314 return $u;
318 static function newFromId( $id ) {
319 $u = new User;
320 $u->mId = $id;
321 $u->mFrom = 'id';
322 return $u;
326 * Factory method to fetch whichever user has a given email confirmation code.
327 * This code is generated when an account is created or its e-mail address
328 * has changed.
330 * If the code is invalid or has expired, returns NULL.
332 * @param string $code
333 * @return User
334 * @static
336 static function newFromConfirmationCode( $code ) {
337 $dbr = wfGetDB( DB_SLAVE );
338 $id = $dbr->selectField( 'user', 'user_id', array(
339 'user_email_token' => md5( $code ),
340 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
341 ) );
342 if( $id !== false ) {
343 return User::newFromId( $id );
344 } else {
345 return null;
350 * Create a new user object using data from session or cookies. If the
351 * login credentials are invalid, the result is an anonymous user.
353 * @return User
354 * @static
356 static function newFromSession() {
357 $user = new User;
358 $user->mFrom = 'session';
359 return $user;
363 * Create a new user object from a user row.
364 * The row should have all fields from the user table in it.
366 static function newFromRow( $row ) {
367 $user = new User;
368 $user->loadFromRow( $row );
369 return $user;
373 * Get username given an id.
374 * @param integer $id Database user id
375 * @return string Nickname of a user
376 * @static
378 static function whoIs( $id ) {
379 $dbr = wfGetDB( DB_SLAVE );
380 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
384 * Get the real name of a user given their identifier
386 * @param int $id Database user id
387 * @return string Real name of a user
389 static function whoIsReal( $id ) {
390 $dbr = wfGetDB( DB_SLAVE );
391 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ );
395 * Get database id given a user name
396 * @param string $name Nickname of a user
397 * @return integer|null Database user id (null: if non existent
398 * @static
400 static function idFromName( $name ) {
401 $nt = Title::newFromText( $name );
402 if( is_null( $nt ) ) {
403 # Illegal name
404 return null;
406 $dbr = wfGetDB( DB_SLAVE );
407 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
409 if ( $s === false ) {
410 return 0;
411 } else {
412 return $s->user_id;
417 * Does the string match an anonymous IPv4 address?
419 * This function exists for username validation, in order to reject
420 * usernames which are similar in form to IP addresses. Strings such
421 * as 300.300.300.300 will return true because it looks like an IP
422 * address, despite not being strictly valid.
424 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
425 * address because the usemod software would "cloak" anonymous IP
426 * addresses like this, if we allowed accounts like this to be created
427 * new users could get the old edits of these anonymous users.
429 * @static
430 * @param string $name Nickname of a user
431 * @return bool
433 static function isIP( $name ) {
434 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || User::isIPv6($name);
435 /*return preg_match("/^
436 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
437 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
438 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
439 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
440 $/x", $name);*/
444 * Check if $name is an IPv6 IP.
446 static function isIPv6($name) {
448 * if it has any non-valid characters, it can't be a valid IPv6
449 * address.
451 if (preg_match("/[^:a-fA-F0-9]/", $name))
452 return false;
454 $parts = explode(":", $name);
455 if (count($parts) < 3)
456 return false;
457 foreach ($parts as $part) {
458 if (!preg_match("/^[0-9a-fA-F]{0,4}$/", $part))
459 return false;
461 return true;
465 * Is the input a valid username?
467 * Checks if the input is a valid username, we don't want an empty string,
468 * an IP address, anything that containins slashes (would mess up subpages),
469 * is longer than the maximum allowed username size or doesn't begin with
470 * a capital letter.
472 * @param string $name
473 * @return bool
474 * @static
476 static function isValidUserName( $name ) {
477 global $wgContLang, $wgMaxNameChars;
479 if ( $name == ''
480 || User::isIP( $name )
481 || strpos( $name, '/' ) !== false
482 || strlen( $name ) > $wgMaxNameChars
483 || $name != $wgContLang->ucfirst( $name ) ) {
484 wfDebugLog( 'username', __METHOD__ .
485 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
486 return false;
489 // Ensure that the name can't be misresolved as a different title,
490 // such as with extra namespace keys at the start.
491 $parsed = Title::newFromText( $name );
492 if( is_null( $parsed )
493 || $parsed->getNamespace()
494 || strcmp( $name, $parsed->getPrefixedText() ) ) {
495 wfDebugLog( 'username', __METHOD__ .
496 ": '$name' invalid due to ambiguous prefixes" );
497 return false;
500 // Check an additional blacklist of troublemaker characters.
501 // Should these be merged into the title char list?
502 $unicodeBlacklist = '/[' .
503 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
504 '\x{00a0}' . # non-breaking space
505 '\x{2000}-\x{200f}' . # various whitespace
506 '\x{2028}-\x{202f}' . # breaks and control chars
507 '\x{3000}' . # ideographic space
508 '\x{e000}-\x{f8ff}' . # private use
509 ']/u';
510 if( preg_match( $unicodeBlacklist, $name ) ) {
511 wfDebugLog( 'username', __METHOD__ .
512 ": '$name' invalid due to blacklisted characters" );
513 return false;
516 return true;
520 * Usernames which fail to pass this function will be blocked
521 * from user login and new account registrations, but may be used
522 * internally by batch processes.
524 * If an account already exists in this form, login will be blocked
525 * by a failure to pass this function.
527 * @param string $name
528 * @return bool
530 static function isUsableName( $name ) {
531 global $wgReservedUsernames;
532 return
533 // Must be a valid username, obviously ;)
534 self::isValidUserName( $name ) &&
536 // Certain names may be reserved for batch processes.
537 !in_array( $name, $wgReservedUsernames );
541 * Usernames which fail to pass this function will be blocked
542 * from new account registrations, but may be used internally
543 * either by batch processes or by user accounts which have
544 * already been created.
546 * Additional character blacklisting may be added here
547 * rather than in isValidUserName() to avoid disrupting
548 * existing accounts.
550 * @param string $name
551 * @return bool
553 static function isCreatableName( $name ) {
554 return
555 self::isUsableName( $name ) &&
557 // Registration-time character blacklisting...
558 strpos( $name, '@' ) === false;
562 * Is the input a valid password for this user?
564 * @param string $password Desired password
565 * @return bool
567 function isValidPassword( $password ) {
568 global $wgMinimalPasswordLength, $wgContLang;
570 $result = null;
571 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
572 return $result;
573 if( $result === false )
574 return false;
576 // Password needs to be long enough, and can't be the same as the username
577 return strlen( $password ) >= $wgMinimalPasswordLength
578 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName );
582 * Does a string look like an email address?
584 * There used to be a regular expression here, it got removed because it
585 * rejected valid addresses. Actually just check if there is '@' somewhere
586 * in the given address.
588 * @todo Check for RFC 2822 compilance (bug 959)
590 * @param string $addr email address
591 * @return bool
593 public static function isValidEmailAddr( $addr ) {
594 $result = null;
595 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
596 return $result;
599 return strpos( $addr, '@' ) !== false;
603 * Given unvalidated user input, return a canonical username, or false if
604 * the username is invalid.
605 * @param string $name
606 * @param mixed $validate Type of validation to use:
607 * false No validation
608 * 'valid' Valid for batch processes
609 * 'usable' Valid for batch processes and login
610 * 'creatable' Valid for batch processes, login and account creation
612 static function getCanonicalName( $name, $validate = 'valid' ) {
613 # Force usernames to capital
614 global $wgContLang;
615 $name = $wgContLang->ucfirst( $name );
617 # Reject names containing '#'; these will be cleaned up
618 # with title normalisation, but then it's too late to
619 # check elsewhere
620 if( strpos( $name, '#' ) !== false )
621 return false;
623 # Clean up name according to title rules
624 $t = Title::newFromText( $name );
625 if( is_null( $t ) ) {
626 return false;
629 # Reject various classes of invalid names
630 $name = $t->getText();
631 global $wgAuth;
632 $name = $wgAuth->getCanonicalName( $t->getText() );
634 switch ( $validate ) {
635 case false:
636 break;
637 case 'valid':
638 if ( !User::isValidUserName( $name ) ) {
639 $name = false;
641 break;
642 case 'usable':
643 if ( !User::isUsableName( $name ) ) {
644 $name = false;
646 break;
647 case 'creatable':
648 if ( !User::isCreatableName( $name ) ) {
649 $name = false;
651 break;
652 default:
653 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__ );
655 return $name;
659 * Count the number of edits of a user
661 * It should not be static and some day should be merged as proper member function / deprecated -- domas
663 * @param int $uid The user ID to check
664 * @return int
665 * @static
667 static function edits( $uid ) {
668 wfProfileIn( __METHOD__ );
669 $dbr = wfGetDB( DB_SLAVE );
670 // check if the user_editcount field has been initialized
671 $field = $dbr->selectField(
672 'user', 'user_editcount',
673 array( 'user_id' => $uid ),
674 __METHOD__
677 if( $field === null ) { // it has not been initialized. do so.
678 $dbw = wfGetDB( DB_MASTER );
679 $count = $dbr->selectField(
680 'revision', 'count(*)',
681 array( 'rev_user' => $uid ),
682 __METHOD__
684 $dbw->update(
685 'user',
686 array( 'user_editcount' => $count ),
687 array( 'user_id' => $uid ),
688 __METHOD__
690 } else {
691 $count = $field;
693 wfProfileOut( __METHOD__ );
694 return $count;
698 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
699 * @todo hash random numbers to improve security, like generateToken()
701 * @return string
702 * @static
704 static function randomPassword() {
705 global $wgMinimalPasswordLength;
706 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
707 $l = strlen( $pwchars ) - 1;
709 $pwlength = max( 7, $wgMinimalPasswordLength );
710 $digit = mt_rand(0, $pwlength - 1);
711 $np = '';
712 for ( $i = 0; $i < $pwlength; $i++ ) {
713 $np .= $i == $digit ? chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
715 return $np;
719 * Set cached properties to default. Note: this no longer clears
720 * uncached lazy-initialised properties. The constructor does that instead.
722 * @private
724 function loadDefaults( $name = false ) {
725 wfProfileIn( __METHOD__ );
727 global $wgCookiePrefix;
729 $this->mId = 0;
730 $this->mName = $name;
731 $this->mRealName = '';
732 $this->mPassword = $this->mNewpassword = '';
733 $this->mNewpassTime = null;
734 $this->mEmail = '';
735 $this->mOptions = null; # Defer init
737 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
738 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
739 } else {
740 $this->mTouched = '0'; # Allow any pages to be cached
743 $this->setToken(); # Random
744 $this->mEmailAuthenticated = null;
745 $this->mEmailToken = '';
746 $this->mEmailTokenExpires = null;
747 $this->mRegistration = wfTimestamp( TS_MW );
748 $this->mGroups = array();
750 wfProfileOut( __METHOD__ );
754 * Initialise php session
755 * @deprecated use wfSetupSession()
757 function SetupSession() {
758 wfDeprecated( __METHOD__ );
759 wfSetupSession();
763 * Load user data from the session or login cookie. If there are no valid
764 * credentials, initialises the user as an anon.
765 * @return true if the user is logged in, false otherwise
767 private function loadFromSession() {
768 global $wgMemc, $wgCookiePrefix;
770 $result = null;
771 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
772 if ( $result !== null ) {
773 return $result;
776 if ( isset( $_SESSION['wsUserID'] ) ) {
777 if ( 0 != $_SESSION['wsUserID'] ) {
778 $sId = $_SESSION['wsUserID'];
779 } else {
780 $this->loadDefaults();
781 return false;
783 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
784 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
785 $_SESSION['wsUserID'] = $sId;
786 } else {
787 $this->loadDefaults();
788 return false;
790 if ( isset( $_SESSION['wsUserName'] ) ) {
791 $sName = $_SESSION['wsUserName'];
792 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
793 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
794 $_SESSION['wsUserName'] = $sName;
795 } else {
796 $this->loadDefaults();
797 return false;
800 $passwordCorrect = FALSE;
801 $this->mId = $sId;
802 if ( !$this->loadFromId() ) {
803 # Not a valid ID, loadFromId has switched the object to anon for us
804 return false;
807 if ( isset( $_SESSION['wsToken'] ) ) {
808 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
809 $from = 'session';
810 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
811 $passwordCorrect = $this->mToken == $_COOKIE["{$wgCookiePrefix}Token"];
812 $from = 'cookie';
813 } else {
814 # No session or persistent login cookie
815 $this->loadDefaults();
816 return false;
819 if ( ( $sName == $this->mName ) && $passwordCorrect ) {
820 $_SESSION['wsToken'] = $this->mToken;
821 wfDebug( "Logged in from $from\n" );
822 return true;
823 } else {
824 # Invalid credentials
825 wfDebug( "Can't log in from $from, invalid credentials\n" );
826 $this->loadDefaults();
827 return false;
832 * Load user and user_group data from the database
833 * $this->mId must be set, this is how the user is identified.
835 * @return true if the user exists, false if the user is anonymous
836 * @private
838 function loadFromDatabase() {
839 # Paranoia
840 $this->mId = intval( $this->mId );
842 /** Anonymous user */
843 if( !$this->mId ) {
844 $this->loadDefaults();
845 return false;
848 $dbr = wfGetDB( DB_MASTER );
849 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
851 if ( $s !== false ) {
852 # Initialise user table data
853 $this->loadFromRow( $s );
854 $this->mGroups = null; // deferred
855 $this->getEditCount(); // revalidation for nulls
856 return true;
857 } else {
858 # Invalid user_id
859 $this->mId = 0;
860 $this->loadDefaults();
861 return false;
866 * Initialise the user object from a row from the user table
868 function loadFromRow( $row ) {
869 $this->mDataLoaded = true;
871 if ( isset( $row->user_id ) ) {
872 $this->mId = $row->user_id;
874 $this->mName = $row->user_name;
875 $this->mRealName = $row->user_real_name;
876 $this->mPassword = $row->user_password;
877 $this->mNewpassword = $row->user_newpassword;
878 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
879 $this->mEmail = $row->user_email;
880 $this->decodeOptions( $row->user_options );
881 $this->mTouched = wfTimestamp(TS_MW,$row->user_touched);
882 $this->mToken = $row->user_token;
883 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
884 $this->mEmailToken = $row->user_email_token;
885 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
886 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
887 $this->mEditCount = $row->user_editcount;
891 * Load the groups from the database if they aren't already loaded
892 * @private
894 function loadGroups() {
895 if ( is_null( $this->mGroups ) ) {
896 $dbr = wfGetDB( DB_MASTER );
897 $res = $dbr->select( 'user_groups',
898 array( 'ug_group' ),
899 array( 'ug_user' => $this->mId ),
900 __METHOD__ );
901 $this->mGroups = array();
902 while( $row = $dbr->fetchObject( $res ) ) {
903 $this->mGroups[] = $row->ug_group;
909 * Clear various cached data stored in this object.
910 * @param string $reloadFrom Reload user and user_groups table data from a
911 * given source. May be "name", "id", "defaults", "session" or false for
912 * no reload.
914 function clearInstanceCache( $reloadFrom = false ) {
915 $this->mNewtalk = -1;
916 $this->mDatePreference = null;
917 $this->mBlockedby = -1; # Unset
918 $this->mHash = false;
919 $this->mSkin = null;
920 $this->mRights = null;
921 $this->mEffectiveGroups = null;
923 if ( $reloadFrom ) {
924 $this->mDataLoaded = false;
925 $this->mFrom = $reloadFrom;
930 * Combine the language default options with any site-specific options
931 * and add the default language variants.
932 * Not really private cause it's called by Language class
933 * @return array
934 * @static
935 * @private
937 static function getDefaultOptions() {
938 global $wgNamespacesToBeSearchedDefault;
940 * Site defaults will override the global/language defaults
942 global $wgDefaultUserOptions, $wgContLang;
943 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
946 * default language setting
948 $variant = $wgContLang->getPreferredVariant( false );
949 $defOpt['variant'] = $variant;
950 $defOpt['language'] = $variant;
952 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
953 $defOpt['searchNs'.$nsnum] = $val;
955 return $defOpt;
959 * Get a given default option value.
961 * @param string $opt
962 * @return string
963 * @static
964 * @public
966 function getDefaultOption( $opt ) {
967 $defOpts = User::getDefaultOptions();
968 if( isset( $defOpts[$opt] ) ) {
969 return $defOpts[$opt];
970 } else {
971 return '';
976 * Get a list of user toggle names
977 * @return array
979 static function getToggles() {
980 global $wgContLang;
981 $extraToggles = array();
982 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
983 return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
988 * Get blocking information
989 * @private
990 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
991 * non-critical checks are done against slaves. Check when actually saving should be done against
992 * master.
994 function getBlockedStatus( $bFromSlave = true ) {
995 global $wgEnableSorbs, $wgProxyWhitelist;
997 if ( -1 != $this->mBlockedby ) {
998 wfDebug( "User::getBlockedStatus: already loaded.\n" );
999 return;
1002 wfProfileIn( __METHOD__ );
1003 wfDebug( __METHOD__.": checking...\n" );
1005 // Initialize data...
1006 // Otherwise something ends up stomping on $this->mBlockedby when
1007 // things get lazy-loaded later, causing false positive block hits
1008 // due to -1 !== 0. Probably session-related... Nothing should be
1009 // overwriting mBlockedby, surely?
1010 $this->load();
1012 $this->mBlockedby = 0;
1013 $this->mHideName = 0;
1014 $ip = wfGetIP();
1016 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1017 # Exempt from all types of IP-block
1018 $ip = '';
1021 # User/IP blocking
1022 $this->mBlock = new Block();
1023 $this->mBlock->fromMaster( !$bFromSlave );
1024 if ( $this->mBlock->load( $ip , $this->mId ) ) {
1025 wfDebug( __METHOD__.": Found block.\n" );
1026 $this->mBlockedby = $this->mBlock->mBy;
1027 $this->mBlockreason = $this->mBlock->mReason;
1028 $this->mHideName = $this->mBlock->mHideName;
1029 if ( $this->isLoggedIn() ) {
1030 $this->spreadBlock();
1032 } else {
1033 $this->mBlock = null;
1034 wfDebug( __METHOD__.": No block.\n" );
1037 # Proxy blocking
1038 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1039 # Local list
1040 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1041 $this->mBlockedby = wfMsg( 'proxyblocker' );
1042 $this->mBlockreason = wfMsg( 'proxyblockreason' );
1045 # DNSBL
1046 if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
1047 if ( $this->inSorbsBlacklist( $ip ) ) {
1048 $this->mBlockedby = wfMsg( 'sorbs' );
1049 $this->mBlockreason = wfMsg( 'sorbsreason' );
1054 # Extensions
1055 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1057 wfProfileOut( __METHOD__ );
1060 function inSorbsBlacklist( $ip ) {
1061 global $wgEnableSorbs, $wgSorbsUrl;
1063 return $wgEnableSorbs &&
1064 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1067 function inDnsBlacklist( $ip, $base ) {
1068 wfProfileIn( __METHOD__ );
1070 $found = false;
1071 $host = '';
1072 // FIXME: IPv6 ???
1073 $m = array();
1074 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
1075 # Make hostname
1076 for ( $i=4; $i>=1; $i-- ) {
1077 $host .= $m[$i] . '.';
1079 $host .= $base;
1081 # Send query
1082 $ipList = gethostbynamel( $host );
1084 if ( $ipList ) {
1085 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1086 $found = true;
1087 } else {
1088 wfDebug( "Requested $host, not found in $base.\n" );
1092 wfProfileOut( __METHOD__ );
1093 return $found;
1097 * Is this user subject to rate limiting?
1099 * @return bool
1101 public function isPingLimitable() {
1102 global $wgRateLimitsExcludedGroups;
1103 return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) == array();
1107 * Primitive rate limits: enforce maximum actions per time period
1108 * to put a brake on flooding.
1110 * Note: when using a shared cache like memcached, IP-address
1111 * last-hit counters will be shared across wikis.
1113 * @return bool true if a rate limiter was tripped
1114 * @public
1116 function pingLimiter( $action='edit' ) {
1118 # Call the 'PingLimiter' hook
1119 $result = false;
1120 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1121 return $result;
1124 global $wgRateLimits;
1125 if( !isset( $wgRateLimits[$action] ) ) {
1126 return false;
1129 # Some groups shouldn't trigger the ping limiter, ever
1130 if( !$this->isPingLimitable() )
1131 return false;
1133 global $wgMemc, $wgRateLimitLog;
1134 wfProfileIn( __METHOD__ );
1136 $limits = $wgRateLimits[$action];
1137 $keys = array();
1138 $id = $this->getId();
1139 $ip = wfGetIP();
1140 $userLimit = false;
1142 if( isset( $limits['anon'] ) && $id == 0 ) {
1143 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1146 if( isset( $limits['user'] ) && $id != 0 ) {
1147 $userLimit = $limits['user'];
1149 if( $this->isNewbie() ) {
1150 if( isset( $limits['newbie'] ) && $id != 0 ) {
1151 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1153 if( isset( $limits['ip'] ) ) {
1154 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1156 $matches = array();
1157 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1158 $subnet = $matches[1];
1159 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1162 // Check for group-specific permissions
1163 // If more than one group applies, use the group with the highest limit
1164 foreach ( $this->getGroups() as $group ) {
1165 if ( isset( $limits[$group] ) ) {
1166 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1167 $userLimit = $limits[$group];
1171 // Set the user limit key
1172 if ( $userLimit !== false ) {
1173 wfDebug( __METHOD__.": effective user limit: $userLimit\n" );
1174 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1177 $triggered = false;
1178 foreach( $keys as $key => $limit ) {
1179 list( $max, $period ) = $limit;
1180 $summary = "(limit $max in {$period}s)";
1181 $count = $wgMemc->get( $key );
1182 if( $count ) {
1183 if( $count > $max ) {
1184 wfDebug( __METHOD__.": tripped! $key at $count $summary\n" );
1185 if( $wgRateLimitLog ) {
1186 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1188 $triggered = true;
1189 } else {
1190 wfDebug( __METHOD__.": ok. $key at $count $summary\n" );
1192 } else {
1193 wfDebug( __METHOD__.": adding record for $key $summary\n" );
1194 $wgMemc->add( $key, 1, intval( $period ) );
1196 $wgMemc->incr( $key );
1199 wfProfileOut( __METHOD__ );
1200 return $triggered;
1204 * Check if user is blocked
1205 * @return bool True if blocked, false otherwise
1207 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1208 wfDebug( "User::isBlocked: enter\n" );
1209 $this->getBlockedStatus( $bFromSlave );
1210 return $this->mBlockedby !== 0;
1214 * Check if user is blocked from editing a particular article
1216 function isBlockedFrom( $title, $bFromSlave = false ) {
1217 global $wgBlockAllowsUTEdit;
1218 wfProfileIn( __METHOD__ );
1219 wfDebug( __METHOD__.": enter\n" );
1221 wfDebug( __METHOD__.": asking isBlocked()\n" );
1222 $blocked = $this->isBlocked( $bFromSlave );
1223 # If a user's name is suppressed, they cannot make edits anywhere
1224 if ( !$this->mHideName && $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1225 $title->getNamespace() == NS_USER_TALK ) {
1226 $blocked = false;
1227 wfDebug( __METHOD__.": self-talk page, ignoring any blocks\n" );
1229 wfProfileOut( __METHOD__ );
1230 return $blocked;
1234 * Get name of blocker
1235 * @return string name of blocker
1237 function blockedBy() {
1238 $this->getBlockedStatus();
1239 return $this->mBlockedby;
1243 * Get blocking reason
1244 * @return string Blocking reason
1246 function blockedFor() {
1247 $this->getBlockedStatus();
1248 return $this->mBlockreason;
1252 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1254 function getId() {
1255 if( $this->mId === null and $this->mName !== null
1256 and User::isIP( $this->mName ) ) {
1257 // Special case, we know the user is anonymous
1258 return 0;
1259 } elseif( $this->mId === null ) {
1260 // Don't load if this was initialized from an ID
1261 $this->load();
1263 return $this->mId;
1267 * Set the user and reload all fields according to that ID
1269 function setId( $v ) {
1270 $this->mId = $v;
1271 $this->clearInstanceCache( 'id' );
1275 * Get the user name, or the IP for anons
1277 function getName() {
1278 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1279 # Special case optimisation
1280 return $this->mName;
1281 } else {
1282 $this->load();
1283 if ( $this->mName === false ) {
1284 # Clean up IPs
1285 $this->mName = IP::sanitizeIP( wfGetIP() );
1287 return $this->mName;
1292 * Set the user name.
1294 * This does not reload fields from the database according to the given
1295 * name. Rather, it is used to create a temporary "nonexistent user" for
1296 * later addition to the database. It can also be used to set the IP
1297 * address for an anonymous user to something other than the current
1298 * remote IP.
1300 * User::newFromName() has rougly the same function, when the named user
1301 * does not exist.
1303 function setName( $str ) {
1304 $this->load();
1305 $this->mName = $str;
1309 * Return the title dbkey form of the name, for eg user pages.
1310 * @return string
1311 * @public
1313 function getTitleKey() {
1314 return str_replace( ' ', '_', $this->getName() );
1317 function getNewtalk() {
1318 $this->load();
1320 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1321 if( $this->mNewtalk === -1 ) {
1322 $this->mNewtalk = false; # reset talk page status
1324 # Check memcached separately for anons, who have no
1325 # entire User object stored in there.
1326 if( !$this->mId ) {
1327 global $wgMemc;
1328 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1329 $newtalk = $wgMemc->get( $key );
1330 if( strval( $newtalk ) !== '' ) {
1331 $this->mNewtalk = (bool)$newtalk;
1332 } else {
1333 // Since we are caching this, make sure it is up to date by getting it
1334 // from the master
1335 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1336 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1338 } else {
1339 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1343 return (bool)$this->mNewtalk;
1347 * Return the talk page(s) this user has new messages on.
1349 function getNewMessageLinks() {
1350 $talks = array();
1351 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1352 return $talks;
1354 if (!$this->getNewtalk())
1355 return array();
1356 $up = $this->getUserPage();
1357 $utp = $up->getTalkPage();
1358 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1363 * Perform a user_newtalk check, uncached.
1364 * Use getNewtalk for a cached check.
1366 * @param string $field
1367 * @param mixed $id
1368 * @param bool $fromMaster True to fetch from the master, false for a slave
1369 * @return bool
1370 * @private
1372 function checkNewtalk( $field, $id, $fromMaster = false ) {
1373 if ( $fromMaster ) {
1374 $db = wfGetDB( DB_MASTER );
1375 } else {
1376 $db = wfGetDB( DB_SLAVE );
1378 $ok = $db->selectField( 'user_newtalk', $field,
1379 array( $field => $id ), __METHOD__ );
1380 return $ok !== false;
1384 * Add or update the
1385 * @param string $field
1386 * @param mixed $id
1387 * @private
1389 function updateNewtalk( $field, $id ) {
1390 $dbw = wfGetDB( DB_MASTER );
1391 $dbw->insert( 'user_newtalk',
1392 array( $field => $id ),
1393 __METHOD__,
1394 'IGNORE' );
1395 if ( $dbw->affectedRows() ) {
1396 wfDebug( __METHOD__.": set on ($field, $id)\n" );
1397 return true;
1398 } else {
1399 wfDebug( __METHOD__." already set ($field, $id)\n" );
1400 return false;
1405 * Clear the new messages flag for the given user
1406 * @param string $field
1407 * @param mixed $id
1408 * @private
1410 function deleteNewtalk( $field, $id ) {
1411 $dbw = wfGetDB( DB_MASTER );
1412 $dbw->delete( 'user_newtalk',
1413 array( $field => $id ),
1414 __METHOD__ );
1415 if ( $dbw->affectedRows() ) {
1416 wfDebug( __METHOD__.": killed on ($field, $id)\n" );
1417 return true;
1418 } else {
1419 wfDebug( __METHOD__.": already gone ($field, $id)\n" );
1420 return false;
1425 * Update the 'You have new messages!' status.
1426 * @param bool $val
1428 function setNewtalk( $val ) {
1429 if( wfReadOnly() ) {
1430 return;
1433 $this->load();
1434 $this->mNewtalk = $val;
1436 if( $this->isAnon() ) {
1437 $field = 'user_ip';
1438 $id = $this->getName();
1439 } else {
1440 $field = 'user_id';
1441 $id = $this->getId();
1443 global $wgMemc;
1445 if( $val ) {
1446 $changed = $this->updateNewtalk( $field, $id );
1447 } else {
1448 $changed = $this->deleteNewtalk( $field, $id );
1451 if( $this->isAnon() ) {
1452 // Anons have a separate memcached space, since
1453 // user records aren't kept for them.
1454 $key = wfMemcKey( 'newtalk', 'ip', $id );
1455 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1457 if ( $changed ) {
1458 $this->invalidateCache();
1463 * Generate a current or new-future timestamp to be stored in the
1464 * user_touched field when we update things.
1466 private static function newTouchedTimestamp() {
1467 global $wgClockSkewFudge;
1468 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1472 * Clear user data from memcached.
1473 * Use after applying fun updates to the database; caller's
1474 * responsibility to update user_touched if appropriate.
1476 * Called implicitly from invalidateCache() and saveSettings().
1478 private function clearSharedCache() {
1479 if( $this->mId ) {
1480 global $wgMemc;
1481 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1486 * Immediately touch the user data cache for this account.
1487 * Updates user_touched field, and removes account data from memcached
1488 * for reload on the next hit.
1490 function invalidateCache() {
1491 $this->load();
1492 if( $this->mId ) {
1493 $this->mTouched = self::newTouchedTimestamp();
1495 $dbw = wfGetDB( DB_MASTER );
1496 $dbw->update( 'user',
1497 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1498 array( 'user_id' => $this->mId ),
1499 __METHOD__ );
1501 $this->clearSharedCache();
1505 function validateCache( $timestamp ) {
1506 $this->load();
1507 return ($timestamp >= $this->mTouched);
1511 * Encrypt a password.
1512 * It can eventually salt a password.
1513 * @see User::addSalt()
1514 * @param string $p clear Password.
1515 * @return string Encrypted password.
1517 function encryptPassword( $p ) {
1518 $this->load();
1519 return wfEncryptPassword( $this->mId, $p );
1523 * Set the password and reset the random token
1524 * Calls through to authentication plugin if necessary;
1525 * will have no effect if the auth plugin refuses to
1526 * pass the change through or if the legal password
1527 * checks fail.
1529 * As a special case, setting the password to null
1530 * wipes it, so the account cannot be logged in until
1531 * a new password is set, for instance via e-mail.
1533 * @param string $str
1534 * @throws PasswordError on failure
1536 function setPassword( $str ) {
1537 global $wgAuth;
1539 if( $str !== null ) {
1540 if( !$wgAuth->allowPasswordChange() ) {
1541 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1544 if( !$this->isValidPassword( $str ) ) {
1545 global $wgMinimalPasswordLength;
1546 throw new PasswordError( wfMsg( 'passwordtooshort',
1547 $wgMinimalPasswordLength ) );
1551 if( !$wgAuth->setPassword( $this, $str ) ) {
1552 throw new PasswordError( wfMsg( 'externaldberror' ) );
1555 $this->setInternalPassword( $str );
1557 return true;
1561 * Set the password and reset the random token no matter
1562 * what.
1564 * @param string $str
1566 function setInternalPassword( $str ) {
1567 $this->load();
1568 $this->setToken();
1570 if( $str === null ) {
1571 // Save an invalid hash...
1572 $this->mPassword = '';
1573 } else {
1574 $this->mPassword = $this->encryptPassword( $str );
1576 $this->mNewpassword = '';
1577 $this->mNewpassTime = null;
1580 * Set the random token (used for persistent authentication)
1581 * Called from loadDefaults() among other places.
1582 * @private
1584 function setToken( $token = false ) {
1585 global $wgSecretKey, $wgProxyKey;
1586 $this->load();
1587 if ( !$token ) {
1588 if ( $wgSecretKey ) {
1589 $key = $wgSecretKey;
1590 } elseif ( $wgProxyKey ) {
1591 $key = $wgProxyKey;
1592 } else {
1593 $key = microtime();
1595 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1596 } else {
1597 $this->mToken = $token;
1601 function setCookiePassword( $str ) {
1602 $this->load();
1603 $this->mCookiePassword = md5( $str );
1607 * Set the password for a password reminder or new account email
1608 * Sets the user_newpass_time field if $throttle is true
1610 function setNewpassword( $str, $throttle = true ) {
1611 $this->load();
1612 $this->mNewpassword = $this->encryptPassword( $str );
1613 if ( $throttle ) {
1614 $this->mNewpassTime = wfTimestampNow();
1619 * Returns true if a password reminder email has already been sent within
1620 * the last $wgPasswordReminderResendTime hours
1622 function isPasswordReminderThrottled() {
1623 global $wgPasswordReminderResendTime;
1624 $this->load();
1625 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1626 return false;
1628 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1629 return time() < $expiry;
1632 function getEmail() {
1633 $this->load();
1634 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1635 return $this->mEmail;
1638 function getEmailAuthenticationTimestamp() {
1639 $this->load();
1640 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1641 return $this->mEmailAuthenticated;
1644 function setEmail( $str ) {
1645 $this->load();
1646 $this->mEmail = $str;
1647 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1650 function getRealName() {
1651 $this->load();
1652 return $this->mRealName;
1655 function setRealName( $str ) {
1656 $this->load();
1657 $this->mRealName = $str;
1661 * @param string $oname The option to check
1662 * @param string $defaultOverride A default value returned if the option does not exist
1663 * @return string
1665 function getOption( $oname, $defaultOverride = '' ) {
1666 $this->load();
1668 if ( is_null( $this->mOptions ) ) {
1669 if($defaultOverride != '') {
1670 return $defaultOverride;
1672 $this->mOptions = User::getDefaultOptions();
1675 if ( array_key_exists( $oname, $this->mOptions ) ) {
1676 return trim( $this->mOptions[$oname] );
1677 } else {
1678 return $defaultOverride;
1683 * Get the user's date preference, including some important migration for
1684 * old user rows.
1686 function getDatePreference() {
1687 if ( is_null( $this->mDatePreference ) ) {
1688 global $wgLang;
1689 $value = $this->getOption( 'date' );
1690 $map = $wgLang->getDatePreferenceMigrationMap();
1691 if ( isset( $map[$value] ) ) {
1692 $value = $map[$value];
1694 $this->mDatePreference = $value;
1696 return $this->mDatePreference;
1700 * @param string $oname The option to check
1701 * @return bool False if the option is not selected, true if it is
1703 function getBoolOption( $oname ) {
1704 return (bool)$this->getOption( $oname );
1708 * Get an option as an integer value from the source string.
1709 * @param string $oname The option to check
1710 * @param int $default Optional value to return if option is unset/blank.
1711 * @return int
1713 function getIntOption( $oname, $default=0 ) {
1714 $val = $this->getOption( $oname );
1715 if( $val == '' ) {
1716 $val = $default;
1718 return intval( $val );
1721 function setOption( $oname, $val ) {
1722 $this->load();
1723 if ( is_null( $this->mOptions ) ) {
1724 $this->mOptions = User::getDefaultOptions();
1726 if ( $oname == 'skin' ) {
1727 # Clear cached skin, so the new one displays immediately in Special:Preferences
1728 unset( $this->mSkin );
1730 // Filter out any newlines that may have passed through input validation.
1731 // Newlines are used to separate items in the options blob.
1732 if( $val ) {
1733 $val = str_replace( "\r\n", "\n", $val );
1734 $val = str_replace( "\r", "\n", $val );
1735 $val = str_replace( "\n", " ", $val );
1737 // Explicitly NULL values should refer to defaults
1738 global $wgDefaultUserOptions;
1739 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1740 $val = $wgDefaultUserOptions[$oname];
1742 $this->mOptions[$oname] = $val;
1745 function getRights() {
1746 if ( is_null( $this->mRights ) ) {
1747 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
1748 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
1749 // Force reindexation of rights when a hook has unset one of them
1750 $this->mRights = array_values( $this->mRights );
1752 return $this->mRights;
1756 * Get the list of explicit group memberships this user has.
1757 * The implicit * and user groups are not included.
1758 * @return array of strings
1760 function getGroups() {
1761 $this->load();
1762 return $this->mGroups;
1766 * Get the list of implicit group memberships this user has.
1767 * This includes all explicit groups, plus 'user' if logged in,
1768 * '*' for all accounts and autopromoted groups
1769 * @param boolean $recache Don't use the cache
1770 * @return array of strings
1772 function getEffectiveGroups( $recache = false ) {
1773 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
1774 $this->mEffectiveGroups = $this->getGroups();
1775 $this->mEffectiveGroups[] = '*';
1776 if( $this->getId() ) {
1777 $this->mEffectiveGroups[] = 'user';
1779 $this->mEffectiveGroups = array_unique( array_merge(
1780 $this->mEffectiveGroups,
1781 Autopromote::getAutopromoteGroups( $this )
1782 ) );
1784 # Hook for additional groups
1785 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
1788 return $this->mEffectiveGroups;
1791 /* Return the edit count for the user. This is where User::edits should have been */
1792 function getEditCount() {
1793 if ($this->mId) {
1794 if ( !isset( $this->mEditCount ) ) {
1795 /* Populate the count, if it has not been populated yet */
1796 $this->mEditCount = User::edits($this->mId);
1798 return $this->mEditCount;
1799 } else {
1800 /* nil */
1801 return null;
1806 * Add the user to the given group.
1807 * This takes immediate effect.
1808 * @param string $group
1810 function addGroup( $group ) {
1811 $dbw = wfGetDB( DB_MASTER );
1812 if( $this->getId() ) {
1813 $dbw->insert( 'user_groups',
1814 array(
1815 'ug_user' => $this->getID(),
1816 'ug_group' => $group,
1818 'User::addGroup',
1819 array( 'IGNORE' ) );
1822 $this->loadGroups();
1823 $this->mGroups[] = $group;
1824 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1826 $this->invalidateCache();
1830 * Remove the user from the given group.
1831 * This takes immediate effect.
1832 * @param string $group
1834 function removeGroup( $group ) {
1835 $this->load();
1836 $dbw = wfGetDB( DB_MASTER );
1837 $dbw->delete( 'user_groups',
1838 array(
1839 'ug_user' => $this->getID(),
1840 'ug_group' => $group,
1842 'User::removeGroup' );
1844 $this->loadGroups();
1845 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
1846 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1848 $this->invalidateCache();
1853 * A more legible check for non-anonymousness.
1854 * Returns true if the user is not an anonymous visitor.
1856 * @return bool
1858 function isLoggedIn() {
1859 return $this->getID() != 0;
1863 * A more legible check for anonymousness.
1864 * Returns true if the user is an anonymous visitor.
1866 * @return bool
1868 function isAnon() {
1869 return !$this->isLoggedIn();
1873 * Whether the user is a bot
1874 * @deprecated
1876 function isBot() {
1877 wfDeprecated( __METHOD__ );
1878 return $this->isAllowed( 'bot' );
1882 * Check if user is allowed to access a feature / make an action
1883 * @param string $action Action to be checked
1884 * @return boolean True: action is allowed, False: action should not be allowed
1886 function isAllowed($action='') {
1887 if ( $action === '' )
1888 // In the spirit of DWIM
1889 return true;
1891 return in_array( $action, $this->getRights() );
1895 * Check whether to enable recent changes patrol features for this user
1896 * @return bool
1898 public function useRCPatrol() {
1899 global $wgUseRCPatrol;
1900 return( $wgUseRCPatrol && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
1904 * Check whether to enable recent changes patrol features for this user
1905 * @return bool
1907 public function useNPPatrol() {
1908 global $wgUseRCPatrol, $wgUseNPPatrol;
1909 return( ($wgUseRCPatrol || $wgUseNPPatrol) && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
1913 * Load a skin if it doesn't exist or return it
1914 * @todo FIXME : need to check the old failback system [AV]
1916 function &getSkin() {
1917 global $wgRequest;
1918 if ( ! isset( $this->mSkin ) ) {
1919 wfProfileIn( __METHOD__ );
1921 # get the user skin
1922 $userSkin = $this->getOption( 'skin' );
1923 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1925 $this->mSkin =& Skin::newFromKey( $userSkin );
1926 wfProfileOut( __METHOD__ );
1928 return $this->mSkin;
1931 /**#@+
1932 * @param string $title Article title to look at
1936 * Check watched status of an article
1937 * @return bool True if article is watched
1939 function isWatched( $title ) {
1940 $wl = WatchedItem::fromUserTitle( $this, $title );
1941 return $wl->isWatched();
1945 * Watch an article
1947 function addWatch( $title ) {
1948 $wl = WatchedItem::fromUserTitle( $this, $title );
1949 $wl->addWatch();
1950 $this->invalidateCache();
1954 * Stop watching an article
1956 function removeWatch( $title ) {
1957 $wl = WatchedItem::fromUserTitle( $this, $title );
1958 $wl->removeWatch();
1959 $this->invalidateCache();
1963 * Clear the user's notification timestamp for the given title.
1964 * If e-notif e-mails are on, they will receive notification mails on
1965 * the next change of the page if it's watched etc.
1967 function clearNotification( &$title ) {
1968 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
1970 # Do nothing if the database is locked to writes
1971 if( wfReadOnly() ) {
1972 return;
1975 if ($title->getNamespace() == NS_USER_TALK &&
1976 $title->getText() == $this->getName() ) {
1977 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1978 return;
1979 $this->setNewtalk( false );
1982 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
1983 return;
1986 if( $this->isAnon() ) {
1987 // Nothing else to do...
1988 return;
1991 // Only update the timestamp if the page is being watched.
1992 // The query to find out if it is watched is cached both in memcached and per-invocation,
1993 // and when it does have to be executed, it can be on a slave
1994 // If this is the user's newtalk page, we always update the timestamp
1995 if ($title->getNamespace() == NS_USER_TALK &&
1996 $title->getText() == $wgUser->getName())
1998 $watched = true;
1999 } elseif ( $this->getId() == $wgUser->getId() ) {
2000 $watched = $title->userIsWatching();
2001 } else {
2002 $watched = true;
2005 // If the page is watched by the user (or may be watched), update the timestamp on any
2006 // any matching rows
2007 if ( $watched ) {
2008 $dbw = wfGetDB( DB_MASTER );
2009 $dbw->update( 'watchlist',
2010 array( /* SET */
2011 'wl_notificationtimestamp' => NULL
2012 ), array( /* WHERE */
2013 'wl_title' => $title->getDBkey(),
2014 'wl_namespace' => $title->getNamespace(),
2015 'wl_user' => $this->getID()
2016 ), 'User::clearLastVisited'
2021 /**#@-*/
2024 * Resets all of the given user's page-change notification timestamps.
2025 * If e-notif e-mails are on, they will receive notification mails on
2026 * the next change of any watched page.
2028 * @param int $currentUser user ID number
2029 * @public
2031 function clearAllNotifications( $currentUser ) {
2032 global $wgUseEnotif, $wgShowUpdatedMarker;
2033 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2034 $this->setNewtalk( false );
2035 return;
2037 if( $currentUser != 0 ) {
2038 $dbw = wfGetDB( DB_MASTER );
2039 $dbw->update( 'watchlist',
2040 array( /* SET */
2041 'wl_notificationtimestamp' => NULL
2042 ), array( /* WHERE */
2043 'wl_user' => $currentUser
2044 ), __METHOD__
2046 # We also need to clear here the "you have new message" notification for the own user_talk page
2047 # This is cleared one page view later in Article::viewUpdates();
2052 * @private
2053 * @return string Encoding options
2055 function encodeOptions() {
2056 $this->load();
2057 if ( is_null( $this->mOptions ) ) {
2058 $this->mOptions = User::getDefaultOptions();
2060 $a = array();
2061 foreach ( $this->mOptions as $oname => $oval ) {
2062 array_push( $a, $oname.'='.$oval );
2064 $s = implode( "\n", $a );
2065 return $s;
2069 * @private
2071 function decodeOptions( $str ) {
2072 $this->mOptions = array();
2073 $a = explode( "\n", $str );
2074 foreach ( $a as $s ) {
2075 $m = array();
2076 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2077 $this->mOptions[$m[1]] = $m[2];
2082 protected function setCookie( $name, $value, $exp=0 ) {
2083 global $wgCookiePrefix,$wgCookieDomain,$wgCookieSecure,$wgCookieExpiration, $wgCookieHttpOnly;
2084 if( $exp == 0 ) {
2085 $exp = time() + $wgCookieExpiration;
2087 $httpOnlySafe = wfHttpOnlySafe();
2088 wfDebugLog( 'cookie',
2089 'setcookie: "' . implode( '", "',
2090 array(
2091 $wgCookiePrefix . $name,
2092 $value,
2093 $exp,
2094 '/',
2095 $wgCookieDomain,
2096 $wgCookieSecure,
2097 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2098 if( $httpOnlySafe && isset( $wgCookieHttpOnly ) ) {
2099 setcookie( $wgCookiePrefix . $name,
2100 $value,
2101 $exp,
2102 '/',
2103 $wgCookieDomain,
2104 $wgCookieSecure,
2105 $wgCookieHttpOnly );
2106 } else {
2107 // setcookie() fails on PHP 5.1 if you give it future-compat paramters.
2108 // stab stab!
2109 setcookie( $wgCookiePrefix . $name,
2110 $value,
2111 $exp,
2112 '/',
2113 $wgCookieDomain,
2114 $wgCookieSecure );
2118 protected function clearCookie( $name ) {
2119 $this->setCookie( $name, '', time() - 86400 );
2122 function setCookies() {
2123 $this->load();
2124 if ( 0 == $this->mId ) return;
2126 $_SESSION['wsUserID'] = $this->mId;
2128 $this->setCookie( 'UserID', $this->mId );
2129 $this->setCookie( 'UserName', $this->getName() );
2131 $_SESSION['wsUserName'] = $this->getName();
2133 $_SESSION['wsToken'] = $this->mToken;
2134 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2135 $this->setCookie( 'Token', $this->mToken );
2136 } else {
2137 $this->clearCookie( 'Token' );
2142 * Logout user.
2144 function logout() {
2145 global $wgUser;
2146 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2147 $this->doLogout();
2152 * Really logout user
2153 * Clears the cookies and session, resets the instance cache
2155 function doLogout() {
2156 $this->clearInstanceCache( 'defaults' );
2158 $_SESSION['wsUserID'] = 0;
2160 $this->clearCookie( 'UserID' );
2161 $this->clearCookie( 'Token' );
2163 # Remember when user logged out, to prevent seeing cached pages
2164 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2168 * Save object settings into database
2169 * @todo Only rarely do all these fields need to be set!
2171 function saveSettings() {
2172 $this->load();
2173 if ( wfReadOnly() ) { return; }
2174 if ( 0 == $this->mId ) { return; }
2176 $this->mTouched = self::newTouchedTimestamp();
2178 $dbw = wfGetDB( DB_MASTER );
2179 $dbw->update( 'user',
2180 array( /* SET */
2181 'user_name' => $this->mName,
2182 'user_password' => $this->mPassword,
2183 'user_newpassword' => $this->mNewpassword,
2184 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2185 'user_real_name' => $this->mRealName,
2186 'user_email' => $this->mEmail,
2187 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2188 'user_options' => $this->encodeOptions(),
2189 'user_touched' => $dbw->timestamp($this->mTouched),
2190 'user_token' => $this->mToken,
2191 'user_email_token' => $this->mEmailToken,
2192 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2193 ), array( /* WHERE */
2194 'user_id' => $this->mId
2195 ), __METHOD__
2197 wfRunHooks( 'UserSaveSettings', array( $this ) );
2198 $this->clearSharedCache();
2202 * Checks if a user with the given name exists, returns the ID.
2204 function idForName() {
2205 $s = trim( $this->getName() );
2206 if ( $s === '' ) return 0;
2208 $dbr = wfGetDB( DB_SLAVE );
2209 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2210 if ( $id === false ) {
2211 $id = 0;
2213 return $id;
2217 * Add a user to the database, return the user object
2219 * @param string $name The user's name
2220 * @param array $params Associative array of non-default parameters to save to the database:
2221 * password The user's password. Password logins will be disabled if this is omitted.
2222 * newpassword A temporary password mailed to the user
2223 * email The user's email address
2224 * email_authenticated The email authentication timestamp
2225 * real_name The user's real name
2226 * options An associative array of non-default options
2227 * token Random authentication token. Do not set.
2228 * registration Registration timestamp. Do not set.
2230 * @return User object, or null if the username already exists
2232 static function createNew( $name, $params = array() ) {
2233 $user = new User;
2234 $user->load();
2235 if ( isset( $params['options'] ) ) {
2236 $user->mOptions = $params['options'] + $user->mOptions;
2237 unset( $params['options'] );
2239 $dbw = wfGetDB( DB_MASTER );
2240 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2241 $fields = array(
2242 'user_id' => $seqVal,
2243 'user_name' => $name,
2244 'user_password' => $user->mPassword,
2245 'user_newpassword' => $user->mNewpassword,
2246 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ),
2247 'user_email' => $user->mEmail,
2248 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2249 'user_real_name' => $user->mRealName,
2250 'user_options' => $user->encodeOptions(),
2251 'user_token' => $user->mToken,
2252 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2253 'user_editcount' => 0,
2255 foreach ( $params as $name => $value ) {
2256 $fields["user_$name"] = $value;
2258 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2259 if ( $dbw->affectedRows() ) {
2260 $newUser = User::newFromId( $dbw->insertId() );
2261 } else {
2262 $newUser = null;
2264 return $newUser;
2268 * Add an existing user object to the database
2270 function addToDatabase() {
2271 $this->load();
2272 $dbw = wfGetDB( DB_MASTER );
2273 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2274 $dbw->insert( 'user',
2275 array(
2276 'user_id' => $seqVal,
2277 'user_name' => $this->mName,
2278 'user_password' => $this->mPassword,
2279 'user_newpassword' => $this->mNewpassword,
2280 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ),
2281 'user_email' => $this->mEmail,
2282 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2283 'user_real_name' => $this->mRealName,
2284 'user_options' => $this->encodeOptions(),
2285 'user_token' => $this->mToken,
2286 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2287 'user_editcount' => 0,
2288 ), __METHOD__
2290 $this->mId = $dbw->insertId();
2292 # Clear instance cache other than user table data, which is already accurate
2293 $this->clearInstanceCache();
2297 * If the (non-anonymous) user is blocked, this function will block any IP address
2298 * that they successfully log on from.
2300 function spreadBlock() {
2301 wfDebug( __METHOD__."()\n" );
2302 $this->load();
2303 if ( $this->mId == 0 ) {
2304 return;
2307 $userblock = Block::newFromDB( '', $this->mId );
2308 if ( !$userblock ) {
2309 return;
2312 $userblock->doAutoblock( wfGetIp() );
2317 * Generate a string which will be different for any combination of
2318 * user options which would produce different parser output.
2319 * This will be used as part of the hash key for the parser cache,
2320 * so users will the same options can share the same cached data
2321 * safely.
2323 * Extensions which require it should install 'PageRenderingHash' hook,
2324 * which will give them a chance to modify this key based on their own
2325 * settings.
2327 * @return string
2329 function getPageRenderingHash() {
2330 global $wgContLang, $wgUseDynamicDates, $wgLang;
2331 if( $this->mHash ){
2332 return $this->mHash;
2335 // stubthreshold is only included below for completeness,
2336 // it will always be 0 when this function is called by parsercache.
2338 $confstr = $this->getOption( 'math' );
2339 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2340 if ( $wgUseDynamicDates ) {
2341 $confstr .= '!' . $this->getDatePreference();
2343 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
2344 $confstr .= '!' . $wgLang->getCode();
2345 $confstr .= '!' . $this->getOption( 'thumbsize' );
2346 // add in language specific options, if any
2347 $extra = $wgContLang->getExtraHashOptions();
2348 $confstr .= $extra;
2350 // Give a chance for extensions to modify the hash, if they have
2351 // extra options or other effects on the parser cache.
2352 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2354 // Make it a valid memcached key fragment
2355 $confstr = str_replace( ' ', '_', $confstr );
2356 $this->mHash = $confstr;
2357 return $confstr;
2360 function isBlockedFromCreateAccount() {
2361 $this->getBlockedStatus();
2362 return $this->mBlock && $this->mBlock->mCreateAccount;
2366 * Determine if the user is blocked from using Special:Emailuser.
2368 * @public
2369 * @return boolean
2371 function isBlockedFromEmailuser() {
2372 $this->getBlockedStatus();
2373 return $this->mBlock && $this->mBlock->mBlockEmail;
2376 function isAllowedToCreateAccount() {
2377 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2381 * @deprecated
2383 function setLoaded( $loaded ) {
2384 wfDeprecated( __METHOD__ );
2388 * Get this user's personal page title.
2390 * @return Title
2391 * @public
2393 function getUserPage() {
2394 return Title::makeTitle( NS_USER, $this->getName() );
2398 * Get this user's talk page title.
2400 * @return Title
2401 * @public
2403 function getTalkPage() {
2404 $title = $this->getUserPage();
2405 return $title->getTalkPage();
2409 * @static
2411 function getMaxID() {
2412 static $res; // cache
2414 if ( isset( $res ) )
2415 return $res;
2416 else {
2417 $dbr = wfGetDB( DB_SLAVE );
2418 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2423 * Determine whether the user is a newbie. Newbies are either
2424 * anonymous IPs, or the most recently created accounts.
2425 * @return bool True if it is a newbie.
2427 function isNewbie() {
2428 return !$this->isAllowed( 'autoconfirmed' );
2432 * Check to see if the given clear-text password is one of the accepted passwords
2433 * @param string $password User password.
2434 * @return bool True if the given password is correct otherwise False.
2436 function checkPassword( $password ) {
2437 global $wgAuth;
2438 $this->load();
2440 // Even though we stop people from creating passwords that
2441 // are shorter than this, doesn't mean people wont be able
2442 // to. Certain authentication plugins do NOT want to save
2443 // domain passwords in a mysql database, so we should
2444 // check this (incase $wgAuth->strict() is false).
2445 if( !$this->isValidPassword( $password ) ) {
2446 return false;
2449 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2450 return true;
2451 } elseif( $wgAuth->strict() ) {
2452 /* Auth plugin doesn't allow local authentication */
2453 return false;
2454 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2455 /* Auth plugin doesn't allow local authentication for this user name */
2456 return false;
2458 $ep = $this->encryptPassword( $password );
2459 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
2460 return true;
2461 } elseif ( function_exists( 'iconv' ) ) {
2462 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2463 # Check for this with iconv
2464 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2465 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
2466 return true;
2469 return false;
2473 * Check if the given clear-text password matches the temporary password
2474 * sent by e-mail for password reset operations.
2475 * @return bool
2477 function checkTemporaryPassword( $plaintext ) {
2478 $hash = $this->encryptPassword( $plaintext );
2479 return $hash === $this->mNewpassword;
2483 * Initialize (if necessary) and return a session token value
2484 * which can be used in edit forms to show that the user's
2485 * login credentials aren't being hijacked with a foreign form
2486 * submission.
2488 * @param mixed $salt - Optional function-specific data for hash.
2489 * Use a string or an array of strings.
2490 * @return string
2491 * @public
2493 function editToken( $salt = '' ) {
2494 if ( $this->isAnon() ) {
2495 return EDIT_TOKEN_SUFFIX;
2496 } else {
2497 if( !isset( $_SESSION['wsEditToken'] ) ) {
2498 $token = $this->generateToken();
2499 $_SESSION['wsEditToken'] = $token;
2500 } else {
2501 $token = $_SESSION['wsEditToken'];
2503 if( is_array( $salt ) ) {
2504 $salt = implode( '|', $salt );
2506 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2511 * Generate a hex-y looking random token for various uses.
2512 * Could be made more cryptographically sure if someone cares.
2513 * @return string
2515 function generateToken( $salt = '' ) {
2516 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2517 return md5( $token . $salt );
2521 * Check given value against the token value stored in the session.
2522 * A match should confirm that the form was submitted from the
2523 * user's own login session, not a form submission from a third-party
2524 * site.
2526 * @param string $val - the input value to compare
2527 * @param string $salt - Optional function-specific data for hash
2528 * @return bool
2529 * @public
2531 function matchEditToken( $val, $salt = '' ) {
2532 $sessionToken = $this->editToken( $salt );
2533 if ( $val != $sessionToken ) {
2534 wfDebug( "User::matchEditToken: broken session data\n" );
2536 return $val == $sessionToken;
2540 * Check whether the edit token is fine except for the suffix
2542 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2543 $sessionToken = $this->editToken( $salt );
2544 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2548 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2549 * mail to the user's given address.
2551 * Calls saveSettings() internally; as it has side effects, not committing changes
2552 * would be pretty silly.
2554 * @return mixed True on success, a WikiError object on failure.
2556 function sendConfirmationMail() {
2557 global $wgLang;
2558 $expiration = null; // gets passed-by-ref and defined in next line.
2559 $token = $this->confirmationToken( $expiration );
2560 $url = $this->confirmationTokenUrl( $token );
2561 $invalidateURL = $this->invalidationTokenUrl( $token );
2562 $this->saveSettings();
2564 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2565 wfMsg( 'confirmemail_body',
2566 wfGetIP(),
2567 $this->getName(),
2568 $url,
2569 $wgLang->timeanddate( $expiration, false ),
2570 $invalidateURL ) );
2574 * Send an e-mail to this user's account. Does not check for
2575 * confirmed status or validity.
2577 * @param string $subject
2578 * @param string $body
2579 * @param string $from Optional from address; default $wgPasswordSender will be used otherwise.
2580 * @return mixed True on success, a WikiError object on failure.
2582 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2583 if( is_null( $from ) ) {
2584 global $wgPasswordSender;
2585 $from = $wgPasswordSender;
2588 $to = new MailAddress( $this );
2589 $sender = new MailAddress( $from );
2590 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2594 * Generate, store, and return a new e-mail confirmation code.
2595 * A hash (unsalted since it's used as a key) is stored.
2597 * Call saveSettings() after calling this function to commit
2598 * this change to the database.
2600 * @param &$expiration mixed output: accepts the expiration time
2601 * @return string
2602 * @private
2604 function confirmationToken( &$expiration ) {
2605 $now = time();
2606 $expires = $now + 7 * 24 * 60 * 60;
2607 $expiration = wfTimestamp( TS_MW, $expires );
2608 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
2609 $hash = md5( $token );
2610 $this->load();
2611 $this->mEmailToken = $hash;
2612 $this->mEmailTokenExpires = $expiration;
2613 return $token;
2617 * Return a URL the user can use to confirm their email address.
2618 * @param $token: accepts the email confirmation token
2619 * @return string
2620 * @private
2622 function confirmationTokenUrl( $token ) {
2623 $title = SpecialPage::getTitleFor( 'Confirmemail', $token );
2624 return $title->getFullUrl();
2627 * Return a URL the user can use to invalidate their email address.
2628 * @param $token: accepts the email confirmation token
2629 * @return string
2630 * @private
2632 function invalidationTokenUrl( $token ) {
2633 $title = SpecialPage::getTitleFor( 'Invalidateemail', $token );
2634 return $title->getFullUrl();
2638 * Mark the e-mail address confirmed.
2640 * Call saveSettings() after calling this function to commit the change.
2642 function confirmEmail() {
2643 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2644 return true;
2648 * Invalidate the user's email confirmation, unauthenticate the email
2649 * if it was already confirmed.
2651 * Call saveSettings() after calling this function to commit the change.
2653 function invalidateEmail() {
2654 $this->load();
2655 $this->mEmailToken = null;
2656 $this->mEmailTokenExpires = null;
2657 $this->setEmailAuthenticationTimestamp( null );
2658 return true;
2661 function setEmailAuthenticationTimestamp( $timestamp ) {
2662 $this->load();
2663 $this->mEmailAuthenticated = $timestamp;
2664 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2668 * Is this user allowed to send e-mails within limits of current
2669 * site configuration?
2670 * @return bool
2672 function canSendEmail() {
2673 $canSend = $this->isEmailConfirmed();
2674 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2675 return $canSend;
2679 * Is this user allowed to receive e-mails within limits of current
2680 * site configuration?
2681 * @return bool
2683 function canReceiveEmail() {
2684 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2688 * Is this user's e-mail address valid-looking and confirmed within
2689 * limits of the current site configuration?
2691 * If $wgEmailAuthentication is on, this may require the user to have
2692 * confirmed their address by returning a code or using a password
2693 * sent to the address from the wiki.
2695 * @return bool
2697 function isEmailConfirmed() {
2698 global $wgEmailAuthentication;
2699 $this->load();
2700 $confirmed = true;
2701 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2702 if( $this->isAnon() )
2703 return false;
2704 if( !self::isValidEmailAddr( $this->mEmail ) )
2705 return false;
2706 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2707 return false;
2708 return true;
2709 } else {
2710 return $confirmed;
2715 * Return true if there is an outstanding request for e-mail confirmation.
2716 * @return bool
2718 function isEmailConfirmationPending() {
2719 global $wgEmailAuthentication;
2720 return $wgEmailAuthentication &&
2721 !$this->isEmailConfirmed() &&
2722 $this->mEmailToken &&
2723 $this->mEmailTokenExpires > wfTimestamp();
2727 * Get the timestamp of account creation, or false for
2728 * non-existent/anonymous user accounts
2730 * @return mixed
2732 public function getRegistration() {
2733 return $this->mId > 0
2734 ? $this->mRegistration
2735 : false;
2739 * @param array $groups list of groups
2740 * @return array list of permission key names for given groups combined
2742 static function getGroupPermissions( $groups ) {
2743 global $wgGroupPermissions;
2744 $rights = array();
2745 foreach( $groups as $group ) {
2746 if( isset( $wgGroupPermissions[$group] ) ) {
2747 $rights = array_merge( $rights,
2748 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2751 return $rights;
2755 * @param string $group key name
2756 * @return string localized descriptive name for group, if provided
2758 static function getGroupName( $group ) {
2759 global $wgMessageCache;
2760 $wgMessageCache->loadAllMessages();
2761 $key = "group-$group";
2762 $name = wfMsg( $key );
2763 return $name == '' || wfEmptyMsg( $key, $name )
2764 ? $group
2765 : $name;
2769 * @param string $group key name
2770 * @return string localized descriptive name for member of a group, if provided
2772 static function getGroupMember( $group ) {
2773 global $wgMessageCache;
2774 $wgMessageCache->loadAllMessages();
2775 $key = "group-$group-member";
2776 $name = wfMsg( $key );
2777 return $name == '' || wfEmptyMsg( $key, $name )
2778 ? $group
2779 : $name;
2783 * Return the set of defined explicit groups.
2784 * The implicit groups (by default *, 'user' and 'autoconfirmed')
2785 * are not included, as they are defined automatically,
2786 * not in the database.
2787 * @return array
2789 static function getAllGroups() {
2790 global $wgGroupPermissions;
2791 return array_diff(
2792 array_keys( $wgGroupPermissions ),
2793 self::getImplicitGroups()
2798 * Get a list of all available permissions
2800 static function getAllRights() {
2801 if ( self::$mAllRights === false ) {
2802 global $wgAvailableRights;
2803 if ( count( $wgAvailableRights ) ) {
2804 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
2805 } else {
2806 self::$mAllRights = self::$mCoreRights;
2808 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
2810 return self::$mAllRights;
2814 * Get a list of implicit groups
2816 * @return array
2818 public static function getImplicitGroups() {
2819 global $wgImplicitGroups;
2820 $groups = $wgImplicitGroups;
2821 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
2822 return $groups;
2826 * Get the title of a page describing a particular group
2828 * @param $group Name of the group
2829 * @return mixed
2831 static function getGroupPage( $group ) {
2832 global $wgMessageCache;
2833 $wgMessageCache->loadAllMessages();
2834 $page = wfMsgForContent( 'grouppage-' . $group );
2835 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2836 $title = Title::newFromText( $page );
2837 if( is_object( $title ) )
2838 return $title;
2840 return false;
2844 * Create a link to the group in HTML, if available
2846 * @param $group Name of the group
2847 * @param $text The text of the link
2848 * @return mixed
2850 static function makeGroupLinkHTML( $group, $text = '' ) {
2851 if( $text == '' ) {
2852 $text = self::getGroupName( $group );
2854 $title = self::getGroupPage( $group );
2855 if( $title ) {
2856 global $wgUser;
2857 $sk = $wgUser->getSkin();
2858 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2859 } else {
2860 return $text;
2865 * Create a link to the group in Wikitext, if available
2867 * @param $group Name of the group
2868 * @param $text The text of the link (by default, the name of the group)
2869 * @return mixed
2871 static function makeGroupLinkWiki( $group, $text = '' ) {
2872 if( $text == '' ) {
2873 $text = self::getGroupName( $group );
2875 $title = self::getGroupPage( $group );
2876 if( $title ) {
2877 $page = $title->getPrefixedText();
2878 return "[[$page|$text]]";
2879 } else {
2880 return $text;
2885 * Increment the user's edit-count field.
2886 * Will have no effect for anonymous users.
2888 function incEditCount() {
2889 if( !$this->isAnon() ) {
2890 $dbw = wfGetDB( DB_MASTER );
2891 $dbw->update( 'user',
2892 array( 'user_editcount=user_editcount+1' ),
2893 array( 'user_id' => $this->getId() ),
2894 __METHOD__ );
2896 // Lazy initialization check...
2897 if( $dbw->affectedRows() == 0 ) {
2898 // Pull from a slave to be less cruel to servers
2899 // Accuracy isn't the point anyway here
2900 $dbr = wfGetDB( DB_SLAVE );
2901 $count = $dbr->selectField( 'revision',
2902 'COUNT(rev_user)',
2903 array( 'rev_user' => $this->getId() ),
2904 __METHOD__ );
2906 // Now here's a goddamn hack...
2907 if( $dbr !== $dbw ) {
2908 // If we actually have a slave server, the count is
2909 // at least one behind because the current transaction
2910 // has not been committed and replicated.
2911 $count++;
2912 } else {
2913 // But if DB_SLAVE is selecting the master, then the
2914 // count we just read includes the revision that was
2915 // just added in the working transaction.
2918 $dbw->update( 'user',
2919 array( 'user_editcount' => $count ),
2920 array( 'user_id' => $this->getId() ),
2921 __METHOD__ );
2924 // edit count in user cache too
2925 $this->invalidateCache();
2928 static function getRightDescription( $right ) {
2929 global $wgMessageCache;
2930 $wgMessageCache->loadAllMessages();
2931 $key = "right-$right";
2932 $name = wfMsg( $key );
2933 return $name == '' || wfEmptyMsg( $key, $name )
2934 ? $right
2935 : $name;