Fix.
[mediawiki.git] / includes / User.php
bloba4630b84e27b86c398b589235bd90e676f2f9049
1 <?php
2 /**
3 * See user.txt
5 */
7 # Number of characters in user_token field
8 define( 'USER_TOKEN_LENGTH', 32 );
10 # Serialized record version
11 define( 'MW_USER_VERSION', 5 );
13 # Some punctuation to prevent editing from broken text-mangling proxies.
14 # FIXME: this is embedded unescaped into HTML attributes in various
15 # places, so we can't safely include ' or " even though we really should.
16 define( 'EDIT_TOKEN_SUFFIX', '\\' );
18 /**
19 * Thrown by User::setPassword() on error
21 class PasswordError extends MWException {
22 // NOP
25 /**
28 class User {
30 /**
31 * A list of default user toggles, i.e. boolean user preferences that are
32 * displayed by Special:Preferences as checkboxes. This list can be
33 * extended via the UserToggles hook or $wgContLang->getExtraUserToggles().
35 static public $mToggles = array(
36 'highlightbroken',
37 'justify',
38 'hideminor',
39 'extendwatchlist',
40 'usenewrc',
41 'numberheadings',
42 'showtoolbar',
43 'editondblclick',
44 'editsection',
45 'editsectiononrightclick',
46 'showtoc',
47 'rememberpassword',
48 'editwidth',
49 'watchcreations',
50 'watchdefault',
51 'watchmoves',
52 'watchdeletion',
53 'minordefault',
54 'previewontop',
55 'previewonfirst',
56 'nocache',
57 'enotifwatchlistpages',
58 'enotifusertalkpages',
59 'enotifminoredits',
60 'enotifrevealaddr',
61 'shownumberswatching',
62 'fancysig',
63 'externaleditor',
64 'externaldiff',
65 'showjumplinks',
66 'uselivepreview',
67 'forceeditsummary',
68 'watchlisthideown',
69 'watchlisthidebots',
70 'watchlisthideminor',
71 'ccmeonemails',
72 'diffonly',
75 /**
76 * List of member variables which are saved to the shared cache (memcached).
77 * Any operation which changes the corresponding database fields must
78 * call a cache-clearing function.
80 static $mCacheVars = array(
81 # user table
82 'mId',
83 'mName',
84 'mRealName',
85 'mPassword',
86 'mNewpassword',
87 'mNewpassTime',
88 'mEmail',
89 'mOptions',
90 'mTouched',
91 'mToken',
92 'mEmailAuthenticated',
93 'mEmailToken',
94 'mEmailTokenExpires',
95 'mRegistration',
96 'mEditCount',
97 # user_group table
98 'mGroups',
102 * The cache variable declarations
104 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
105 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
106 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
109 * Whether the cache variables have been loaded
111 var $mDataLoaded;
114 * Initialisation data source if mDataLoaded==false. May be one of:
115 * defaults anonymous user initialised from class defaults
116 * name initialise from mName
117 * id initialise from mId
118 * session log in from cookies or session if possible
120 * Use the User::newFrom*() family of functions to set this.
122 var $mFrom;
125 * Lazy-initialised variables, invalidated with clearInstanceCache
127 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
128 $mBlockreason, $mBlock, $mEffectiveGroups;
130 /**
131 * Lightweight constructor for anonymous user
132 * Use the User::newFrom* factory functions for other kinds of users
134 function User() {
135 $this->clearInstanceCache( 'defaults' );
139 * Load the user table data for this object from the source given by mFrom
141 function load() {
142 if ( $this->mDataLoaded ) {
143 return;
145 wfProfileIn( __METHOD__ );
147 # Set it now to avoid infinite recursion in accessors
148 $this->mDataLoaded = true;
150 switch ( $this->mFrom ) {
151 case 'defaults':
152 $this->loadDefaults();
153 break;
154 case 'name':
155 $this->mId = self::idFromName( $this->mName );
156 if ( !$this->mId ) {
157 # Nonexistent user placeholder object
158 $this->loadDefaults( $this->mName );
159 } else {
160 $this->loadFromId();
162 break;
163 case 'id':
164 $this->loadFromId();
165 break;
166 case 'session':
167 $this->loadFromSession();
168 break;
169 default:
170 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
172 wfProfileOut( __METHOD__ );
176 * Load user table data given mId
177 * @return false if the ID does not exist, true otherwise
178 * @private
180 function loadFromId() {
181 global $wgMemc;
182 if ( $this->mId == 0 ) {
183 $this->loadDefaults();
184 return false;
187 # Try cache
188 $key = wfMemcKey( 'user', 'id', $this->mId );
189 $data = $wgMemc->get( $key );
190 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
191 # Object is expired, load from DB
192 $data = false;
195 if ( !$data ) {
196 wfDebug( "Cache miss for user {$this->mId}\n" );
197 # Load from DB
198 if ( !$this->loadFromDatabase() ) {
199 # Can't load from ID, user is anonymous
200 return false;
203 # Save to cache
204 $data = array();
205 foreach ( self::$mCacheVars as $name ) {
206 $data[$name] = $this->$name;
208 $data['mVersion'] = MW_USER_VERSION;
209 $wgMemc->set( $key, $data );
210 } else {
211 wfDebug( "Got user {$this->mId} from cache\n" );
212 # Restore from cache
213 foreach ( self::$mCacheVars as $name ) {
214 $this->$name = $data[$name];
217 return true;
221 * Static factory method for creation from username.
223 * This is slightly less efficient than newFromId(), so use newFromId() if
224 * you have both an ID and a name handy.
226 * @param string $name Username, validated by Title:newFromText()
227 * @param mixed $validate Validate username. Takes the same parameters as
228 * User::getCanonicalName(), except that true is accepted as an alias
229 * for 'valid', for BC.
231 * @return User object, or null if the username is invalid. If the username
232 * is not present in the database, the result will be a user object with
233 * a name, zero user ID and default settings.
234 * @static
236 static function newFromName( $name, $validate = 'valid' ) {
237 if ( $validate === true ) {
238 $validate = 'valid';
240 $name = self::getCanonicalName( $name, $validate );
241 if ( $name === false ) {
242 return null;
243 } else {
244 # Create unloaded user object
245 $u = new User;
246 $u->mName = $name;
247 $u->mFrom = 'name';
248 return $u;
252 static function newFromId( $id ) {
253 $u = new User;
254 $u->mId = $id;
255 $u->mFrom = 'id';
256 return $u;
260 * Factory method to fetch whichever user has a given email confirmation code.
261 * This code is generated when an account is created or its e-mail address
262 * has changed.
264 * If the code is invalid or has expired, returns NULL.
266 * @param string $code
267 * @return User
268 * @static
270 static function newFromConfirmationCode( $code ) {
271 $dbr = wfGetDB( DB_SLAVE );
272 $id = $dbr->selectField( 'user', 'user_id', array(
273 'user_email_token' => md5( $code ),
274 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
275 ) );
276 if( $id !== false ) {
277 return User::newFromId( $id );
278 } else {
279 return null;
284 * Create a new user object using data from session or cookies. If the
285 * login credentials are invalid, the result is an anonymous user.
287 * @return User
288 * @static
290 static function newFromSession() {
291 $user = new User;
292 $user->mFrom = 'session';
293 return $user;
297 * Get username given an id.
298 * @param integer $id Database user id
299 * @return string Nickname of a user
300 * @static
302 static function whoIs( $id ) {
303 $dbr = wfGetDB( DB_SLAVE );
304 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
308 * Get real username given an id.
309 * @param integer $id Database user id
310 * @return string Realname of a user
311 * @static
313 static function whoIsReal( $id ) {
314 $dbr = wfGetDB( DB_SLAVE );
315 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), 'User::whoIsReal' );
319 * Get database id given a user name
320 * @param string $name Nickname of a user
321 * @return integer|null Database user id (null: if non existent
322 * @static
324 static function idFromName( $name ) {
325 $nt = Title::newFromText( $name );
326 if( is_null( $nt ) ) {
327 # Illegal name
328 return null;
330 $dbr = wfGetDB( DB_SLAVE );
331 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
333 if ( $s === false ) {
334 return 0;
335 } else {
336 return $s->user_id;
341 * Does the string match an anonymous IPv4 address?
343 * This function exists for username validation, in order to reject
344 * usernames which are similar in form to IP addresses. Strings such
345 * as 300.300.300.300 will return true because it looks like an IP
346 * address, despite not being strictly valid.
348 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
349 * address because the usemod software would "cloak" anonymous IP
350 * addresses like this, if we allowed accounts like this to be created
351 * new users could get the old edits of these anonymous users.
353 * @bug 3631
355 * @static
356 * @param string $name Nickname of a user
357 * @return bool
359 static function isIP( $name ) {
360 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || User::isIPv6($name);
361 /*return preg_match("/^
362 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
363 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
364 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
365 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
366 $/x", $name);*/
370 * Check if $name is an IPv6 IP.
372 static function isIPv6($name) {
374 * if it has any non-valid characters, it can't be a valid IPv6
375 * address.
377 if (preg_match("/[^:a-fA-F0-9]/", $name))
378 return false;
380 $parts = explode(":", $name);
381 if (count($parts) < 3)
382 return false;
383 foreach ($parts as $part) {
384 if (!preg_match("/^[0-9a-fA-F]{0,4}$/", $part))
385 return false;
387 return true;
391 * Is the input a valid username?
393 * Checks if the input is a valid username, we don't want an empty string,
394 * an IP address, anything that containins slashes (would mess up subpages),
395 * is longer than the maximum allowed username size or doesn't begin with
396 * a capital letter.
398 * @param string $name
399 * @return bool
400 * @static
402 static function isValidUserName( $name ) {
403 global $wgContLang, $wgMaxNameChars;
405 if ( $name == ''
406 || User::isIP( $name )
407 || strpos( $name, '/' ) !== false
408 || strlen( $name ) > $wgMaxNameChars
409 || $name != $wgContLang->ucfirst( $name ) )
410 return false;
412 // Ensure that the name can't be misresolved as a different title,
413 // such as with extra namespace keys at the start.
414 $parsed = Title::newFromText( $name );
415 if( is_null( $parsed )
416 || $parsed->getNamespace()
417 || strcmp( $name, $parsed->getPrefixedText() ) )
418 return false;
420 // Check an additional blacklist of troublemaker characters.
421 // Should these be merged into the title char list?
422 $unicodeBlacklist = '/[' .
423 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
424 '\x{00a0}' . # non-breaking space
425 '\x{2000}-\x{200f}' . # various whitespace
426 '\x{2028}-\x{202f}' . # breaks and control chars
427 '\x{3000}' . # ideographic space
428 '\x{e000}-\x{f8ff}' . # private use
429 ']/u';
430 if( preg_match( $unicodeBlacklist, $name ) ) {
431 return false;
434 return true;
438 * Usernames which fail to pass this function will be blocked
439 * from user login and new account registrations, but may be used
440 * internally by batch processes.
442 * If an account already exists in this form, login will be blocked
443 * by a failure to pass this function.
445 * @param string $name
446 * @return bool
448 static function isUsableName( $name ) {
449 global $wgReservedUsernames;
450 return
451 // Must be a usable username, obviously ;)
452 self::isValidUserName( $name ) &&
454 // Certain names may be reserved for batch processes.
455 !in_array( $name, $wgReservedUsernames );
459 * Usernames which fail to pass this function will be blocked
460 * from new account registrations, but may be used internally
461 * either by batch processes or by user accounts which have
462 * already been created.
464 * Additional character blacklisting may be added here
465 * rather than in isValidUserName() to avoid disrupting
466 * existing accounts.
468 * @param string $name
469 * @return bool
471 static function isCreatableName( $name ) {
472 return
473 self::isUsableName( $name ) &&
475 // Registration-time character blacklisting...
476 strpos( $name, '@' ) === false;
480 * Is the input a valid password?
482 * @param string $password
483 * @return bool
484 * @static
486 static function isValidPassword( $password ) {
487 global $wgMinimalPasswordLength;
489 $result = null;
490 if( !wfRunHooks( 'isValidPassword', array( $password, &$result ) ) ) return $result;
491 if ($result === false) return false;
492 return (strlen( $password ) >= $wgMinimalPasswordLength);
496 * Does the string match roughly an email address ?
498 * There used to be a regular expression here, it got removed because it
499 * rejected valid addresses. Actually just check if there is '@' somewhere
500 * in the given address.
502 * @todo Check for RFC 2822 compilance
503 * @bug 959
505 * @param string $addr email address
506 * @static
507 * @return bool
509 static function isValidEmailAddr ( $addr ) {
510 return ( trim( $addr ) != '' ) &&
511 (false !== strpos( $addr, '@' ) );
515 * Given unvalidated user input, return a canonical username, or false if
516 * the username is invalid.
517 * @param string $name
518 * @param mixed $validate Type of validation to use:
519 * false No validation
520 * 'valid' Valid for batch processes
521 * 'usable' Valid for batch processes and login
522 * 'creatable' Valid for batch processes, login and account creation
524 static function getCanonicalName( $name, $validate = 'valid' ) {
525 # Force usernames to capital
526 global $wgContLang;
527 $name = $wgContLang->ucfirst( $name );
529 # Clean up name according to title rules
530 $t = Title::newFromText( $name );
531 if( is_null( $t ) ) {
532 return false;
535 # Reject various classes of invalid names
536 $name = $t->getText();
537 global $wgAuth;
538 $name = $wgAuth->getCanonicalName( $t->getText() );
540 switch ( $validate ) {
541 case false:
542 break;
543 case 'valid':
544 if ( !User::isValidUserName( $name ) ) {
545 $name = false;
547 break;
548 case 'usable':
549 if ( !User::isUsableName( $name ) ) {
550 $name = false;
552 break;
553 case 'creatable':
554 if ( !User::isCreatableName( $name ) ) {
555 $name = false;
557 break;
558 default:
559 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__ );
561 return $name;
565 * Count the number of edits of a user
567 * It should not be static and some day should be merged as proper member function / deprecated -- domas
569 * @param int $uid The user ID to check
570 * @return int
571 * @static
573 static function edits( $uid ) {
574 wfProfileIn( __METHOD__ );
575 $dbr = wfGetDB( DB_SLAVE );
576 // check if the user_editcount field has been initialized
577 $field = $dbr->selectField(
578 'user', 'user_editcount',
579 array( 'user_id' => $uid ),
580 __METHOD__
583 if( $field === null ) { // it has not been initialized. do so.
584 $dbw = wfGetDb( DB_MASTER );
585 $count = $dbr->selectField(
586 'revision', 'count(*)',
587 array( 'rev_user' => $uid ),
588 __METHOD__
590 $dbw->update(
591 'user',
592 array( 'user_editcount' => $count ),
593 array( 'user_id' => $uid ),
594 __METHOD__
596 } else {
597 $count = $field;
599 wfProfileOut( __METHOD__ );
600 return $count;
604 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
605 * @todo: hash random numbers to improve security, like generateToken()
607 * @return string
608 * @static
610 static function randomPassword() {
611 global $wgMinimalPasswordLength;
612 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
613 $l = strlen( $pwchars ) - 1;
615 $pwlength = max( 7, $wgMinimalPasswordLength );
616 $digit = mt_rand(0, $pwlength - 1);
617 $np = '';
618 for ( $i = 0; $i < $pwlength; $i++ ) {
619 $np .= $i == $digit ? chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
621 return $np;
625 * Set cached properties to default. Note: this no longer clears
626 * uncached lazy-initialised properties. The constructor does that instead.
628 * @private
630 function loadDefaults( $name = false ) {
631 wfProfileIn( __METHOD__ );
633 global $wgCookiePrefix;
635 $this->mId = 0;
636 $this->mName = $name;
637 $this->mRealName = '';
638 $this->mPassword = $this->mNewpassword = '';
639 $this->mNewpassTime = null;
640 $this->mEmail = '';
641 $this->mOptions = null; # Defer init
643 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
644 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
645 } else {
646 $this->mTouched = '0'; # Allow any pages to be cached
649 $this->setToken(); # Random
650 $this->mEmailAuthenticated = null;
651 $this->mEmailToken = '';
652 $this->mEmailTokenExpires = null;
653 $this->mRegistration = wfTimestamp( TS_MW );
654 $this->mGroups = array();
656 wfProfileOut( __METHOD__ );
660 * Initialise php session
661 * @deprecated use wfSetupSession()
663 function SetupSession() {
664 wfSetupSession();
668 * Load user data from the session or login cookie. If there are no valid
669 * credentials, initialises the user as an anon.
670 * @return true if the user is logged in, false otherwise
672 * @private
674 function loadFromSession() {
675 global $wgMemc, $wgCookiePrefix;
677 if ( isset( $_SESSION['wsUserID'] ) ) {
678 if ( 0 != $_SESSION['wsUserID'] ) {
679 $sId = $_SESSION['wsUserID'];
680 } else {
681 $this->loadDefaults();
682 return false;
684 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
685 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
686 $_SESSION['wsUserID'] = $sId;
687 } else {
688 $this->loadDefaults();
689 return false;
691 if ( isset( $_SESSION['wsUserName'] ) ) {
692 $sName = $_SESSION['wsUserName'];
693 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
694 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
695 $_SESSION['wsUserName'] = $sName;
696 } else {
697 $this->loadDefaults();
698 return false;
701 $passwordCorrect = FALSE;
702 $this->mId = $sId;
703 if ( !$this->loadFromId() ) {
704 # Not a valid ID, loadFromId has switched the object to anon for us
705 return false;
708 if ( isset( $_SESSION['wsToken'] ) ) {
709 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
710 $from = 'session';
711 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
712 $passwordCorrect = $this->mToken == $_COOKIE["{$wgCookiePrefix}Token"];
713 $from = 'cookie';
714 } else {
715 # No session or persistent login cookie
716 $this->loadDefaults();
717 return false;
720 if ( ( $sName == $this->mName ) && $passwordCorrect ) {
721 wfDebug( "Logged in from $from\n" );
722 return true;
723 } else {
724 # Invalid credentials
725 wfDebug( "Can't log in from $from, invalid credentials\n" );
726 $this->loadDefaults();
727 return false;
732 * Load user and user_group data from the database
733 * $this->mId must be set, this is how the user is identified.
735 * @return true if the user exists, false if the user is anonymous
736 * @private
738 function loadFromDatabase() {
739 # Paranoia
740 $this->mId = intval( $this->mId );
742 /** Anonymous user */
743 if( !$this->mId ) {
744 $this->loadDefaults();
745 return false;
748 $dbr = wfGetDB( DB_MASTER );
749 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
751 if ( $s !== false ) {
752 # Initialise user table data
753 $this->mName = $s->user_name;
754 $this->mRealName = $s->user_real_name;
755 $this->mPassword = $s->user_password;
756 $this->mNewpassword = $s->user_newpassword;
757 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $s->user_newpass_time );
758 $this->mEmail = $s->user_email;
759 $this->decodeOptions( $s->user_options );
760 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
761 $this->mToken = $s->user_token;
762 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $s->user_email_authenticated );
763 $this->mEmailToken = $s->user_email_token;
764 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $s->user_email_token_expires );
765 $this->mRegistration = wfTimestampOrNull( TS_MW, $s->user_registration );
766 $this->mEditCount = $s->user_editcount;
767 $this->getEditCount(); // revalidation for nulls
769 # Load group data
770 $res = $dbr->select( 'user_groups',
771 array( 'ug_group' ),
772 array( 'ug_user' => $this->mId ),
773 __METHOD__ );
774 $this->mGroups = array();
775 while( $row = $dbr->fetchObject( $res ) ) {
776 $this->mGroups[] = $row->ug_group;
778 return true;
779 } else {
780 # Invalid user_id
781 $this->mId = 0;
782 $this->loadDefaults();
783 return false;
788 * Clear various cached data stored in this object.
789 * @param string $reloadFrom Reload user and user_groups table data from a
790 * given source. May be "name", "id", "defaults", "session" or false for
791 * no reload.
793 function clearInstanceCache( $reloadFrom = false ) {
794 $this->mNewtalk = -1;
795 $this->mDatePreference = null;
796 $this->mBlockedby = -1; # Unset
797 $this->mHash = false;
798 $this->mSkin = null;
799 $this->mRights = null;
800 $this->mEffectiveGroups = null;
802 if ( $reloadFrom ) {
803 $this->mDataLoaded = false;
804 $this->mFrom = $reloadFrom;
809 * Combine the language default options with any site-specific options
810 * and add the default language variants.
811 * Not really private cause it's called by Language class
812 * @return array
813 * @static
814 * @private
816 static function getDefaultOptions() {
817 global $wgNamespacesToBeSearchedDefault;
819 * Site defaults will override the global/language defaults
821 global $wgDefaultUserOptions, $wgContLang;
822 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
825 * default language setting
827 $variant = $wgContLang->getPreferredVariant( false );
828 $defOpt['variant'] = $variant;
829 $defOpt['language'] = $variant;
831 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
832 $defOpt['searchNs'.$nsnum] = $val;
834 return $defOpt;
838 * Get a given default option value.
840 * @param string $opt
841 * @return string
842 * @static
843 * @public
845 function getDefaultOption( $opt ) {
846 $defOpts = User::getDefaultOptions();
847 if( isset( $defOpts[$opt] ) ) {
848 return $defOpts[$opt];
849 } else {
850 return '';
855 * Get a list of user toggle names
856 * @return array
858 static function getToggles() {
859 global $wgContLang;
860 $extraToggles = array();
861 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
862 return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
867 * Get blocking information
868 * @private
869 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
870 * non-critical checks are done against slaves. Check when actually saving should be done against
871 * master.
873 function getBlockedStatus( $bFromSlave = true ) {
874 global $wgEnableSorbs, $wgProxyWhitelist;
876 if ( -1 != $this->mBlockedby ) {
877 wfDebug( "User::getBlockedStatus: already loaded.\n" );
878 return;
881 wfProfileIn( __METHOD__ );
882 wfDebug( __METHOD__.": checking...\n" );
884 $this->mBlockedby = 0;
885 $this->mHideName = 0;
886 $ip = wfGetIP();
888 if ($this->isAllowed( 'ipblock-exempt' ) ) {
889 # Exempt from all types of IP-block
890 $ip = '';
893 # User/IP blocking
894 $this->mBlock = new Block();
895 $this->mBlock->fromMaster( !$bFromSlave );
896 if ( $this->mBlock->load( $ip , $this->mId ) ) {
897 wfDebug( __METHOD__.": Found block.\n" );
898 $this->mBlockedby = $this->mBlock->mBy;
899 $this->mBlockreason = $this->mBlock->mReason;
900 $this->mHideName = $this->mBlock->mHideName;
901 if ( $this->isLoggedIn() ) {
902 $this->spreadBlock();
904 } else {
905 $this->mBlock = null;
906 wfDebug( __METHOD__.": No block.\n" );
909 # Proxy blocking
910 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
912 # Local list
913 if ( wfIsLocallyBlockedProxy( $ip ) ) {
914 $this->mBlockedby = wfMsg( 'proxyblocker' );
915 $this->mBlockreason = wfMsg( 'proxyblockreason' );
918 # DNSBL
919 if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
920 if ( $this->inSorbsBlacklist( $ip ) ) {
921 $this->mBlockedby = wfMsg( 'sorbs' );
922 $this->mBlockreason = wfMsg( 'sorbsreason' );
927 # Extensions
928 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
930 wfProfileOut( __METHOD__ );
933 function inSorbsBlacklist( $ip ) {
934 global $wgEnableSorbs, $wgSorbsUrl;
936 return $wgEnableSorbs &&
937 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
940 function inDnsBlacklist( $ip, $base ) {
941 wfProfileIn( __METHOD__ );
943 $found = false;
944 $host = '';
946 $m = array();
947 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
948 # Make hostname
949 for ( $i=4; $i>=1; $i-- ) {
950 $host .= $m[$i] . '.';
952 $host .= $base;
954 # Send query
955 $ipList = gethostbynamel( $host );
957 if ( $ipList ) {
958 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
959 $found = true;
960 } else {
961 wfDebug( "Requested $host, not found in $base.\n" );
965 wfProfileOut( __METHOD__ );
966 return $found;
970 * Is this user subject to rate limiting?
972 * @return bool
974 public function isPingLimitable() {
975 global $wgRateLimitsExcludedGroups;
976 return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) != array();
980 * Primitive rate limits: enforce maximum actions per time period
981 * to put a brake on flooding.
983 * Note: when using a shared cache like memcached, IP-address
984 * last-hit counters will be shared across wikis.
986 * @return bool true if a rate limiter was tripped
987 * @public
989 function pingLimiter( $action='edit' ) {
991 # Call the 'PingLimiter' hook
992 $result = false;
993 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
994 return $result;
997 global $wgRateLimits, $wgRateLimitsExcludedGroups;
998 if( !isset( $wgRateLimits[$action] ) ) {
999 return false;
1002 # Some groups shouldn't trigger the ping limiter, ever
1003 if( !$this->isPingLimitable() )
1004 return false;
1006 global $wgMemc, $wgRateLimitLog;
1007 wfProfileIn( __METHOD__ );
1009 $limits = $wgRateLimits[$action];
1010 $keys = array();
1011 $id = $this->getId();
1012 $ip = wfGetIP();
1014 if( isset( $limits['anon'] ) && $id == 0 ) {
1015 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1018 if( isset( $limits['user'] ) && $id != 0 ) {
1019 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
1021 if( $this->isNewbie() ) {
1022 if( isset( $limits['newbie'] ) && $id != 0 ) {
1023 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1025 if( isset( $limits['ip'] ) ) {
1026 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1028 $matches = array();
1029 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1030 $subnet = $matches[1];
1031 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1035 $triggered = false;
1036 foreach( $keys as $key => $limit ) {
1037 list( $max, $period ) = $limit;
1038 $summary = "(limit $max in {$period}s)";
1039 $count = $wgMemc->get( $key );
1040 if( $count ) {
1041 if( $count > $max ) {
1042 wfDebug( __METHOD__.": tripped! $key at $count $summary\n" );
1043 if( $wgRateLimitLog ) {
1044 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1046 $triggered = true;
1047 } else {
1048 wfDebug( __METHOD__.": ok. $key at $count $summary\n" );
1050 } else {
1051 wfDebug( __METHOD__.": adding record for $key $summary\n" );
1052 $wgMemc->add( $key, 1, intval( $period ) );
1054 $wgMemc->incr( $key );
1057 wfProfileOut( __METHOD__ );
1058 return $triggered;
1062 * Check if user is blocked
1063 * @return bool True if blocked, false otherwise
1065 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1066 wfDebug( "User::isBlocked: enter\n" );
1067 $this->getBlockedStatus( $bFromSlave );
1068 return $this->mBlockedby !== 0;
1072 * Check if user is blocked from editing a particular article
1074 function isBlockedFrom( $title, $bFromSlave = false ) {
1075 global $wgBlockAllowsUTEdit;
1076 wfProfileIn( __METHOD__ );
1077 wfDebug( __METHOD__.": enter\n" );
1079 wfDebug( __METHOD__.": asking isBlocked()\n" );
1080 $blocked = $this->isBlocked( $bFromSlave );
1081 # If a user's name is suppressed, they cannot make edits anywhere
1082 if ( !$this->mHideName && $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1083 $title->getNamespace() == NS_USER_TALK ) {
1084 $blocked = false;
1085 wfDebug( __METHOD__.": self-talk page, ignoring any blocks\n" );
1087 wfProfileOut( __METHOD__ );
1088 return $blocked;
1092 * Get name of blocker
1093 * @return string name of blocker
1095 function blockedBy() {
1096 $this->getBlockedStatus();
1097 return $this->mBlockedby;
1101 * Get blocking reason
1102 * @return string Blocking reason
1104 function blockedFor() {
1105 $this->getBlockedStatus();
1106 return $this->mBlockreason;
1110 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1112 function getID() {
1113 $this->load();
1114 return $this->mId;
1118 * Set the user and reload all fields according to that ID
1119 * @deprecated use User::newFromId()
1121 function setID( $v ) {
1122 $this->mId = $v;
1123 $this->clearInstanceCache( 'id' );
1127 * Get the user name, or the IP for anons
1129 function getName() {
1130 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1131 # Special case optimisation
1132 return $this->mName;
1133 } else {
1134 $this->load();
1135 if ( $this->mName === false ) {
1136 $this->mName = wfGetIP();
1138 # Clean up IPs
1139 return IP::sanitizeIP($this->mName);
1144 * Set the user name.
1146 * This does not reload fields from the database according to the given
1147 * name. Rather, it is used to create a temporary "nonexistent user" for
1148 * later addition to the database. It can also be used to set the IP
1149 * address for an anonymous user to something other than the current
1150 * remote IP.
1152 * User::newFromName() has rougly the same function, when the named user
1153 * does not exist.
1155 function setName( $str ) {
1156 $this->load();
1157 $this->mName = $str;
1161 * Return the title dbkey form of the name, for eg user pages.
1162 * @return string
1163 * @public
1165 function getTitleKey() {
1166 return str_replace( ' ', '_', $this->getName() );
1169 function getNewtalk() {
1170 $this->load();
1172 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1173 if( $this->mNewtalk === -1 ) {
1174 $this->mNewtalk = false; # reset talk page status
1176 # Check memcached separately for anons, who have no
1177 # entire User object stored in there.
1178 if( !$this->mId ) {
1179 global $wgMemc;
1180 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1181 $newtalk = $wgMemc->get( $key );
1182 if( $newtalk != "" ) {
1183 $this->mNewtalk = (bool)$newtalk;
1184 } else {
1185 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
1186 $wgMemc->set( $key, (int)$this->mNewtalk, time() + 1800 );
1188 } else {
1189 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1193 return (bool)$this->mNewtalk;
1197 * Return the talk page(s) this user has new messages on.
1199 function getNewMessageLinks() {
1200 $talks = array();
1201 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1202 return $talks;
1204 if (!$this->getNewtalk())
1205 return array();
1206 $up = $this->getUserPage();
1207 $utp = $up->getTalkPage();
1208 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1213 * Perform a user_newtalk check on current slaves; if the memcached data
1214 * is funky we don't want newtalk state to get stuck on save, as that's
1215 * damn annoying.
1217 * @param string $field
1218 * @param mixed $id
1219 * @return bool
1220 * @private
1222 function checkNewtalk( $field, $id ) {
1223 $dbr = wfGetDB( DB_SLAVE );
1224 $ok = $dbr->selectField( 'user_newtalk', $field,
1225 array( $field => $id ), __METHOD__ );
1226 return $ok !== false;
1230 * Add or update the
1231 * @param string $field
1232 * @param mixed $id
1233 * @private
1235 function updateNewtalk( $field, $id ) {
1236 if( $this->checkNewtalk( $field, $id ) ) {
1237 wfDebug( __METHOD__." already set ($field, $id), ignoring\n" );
1238 return false;
1240 $dbw = wfGetDB( DB_MASTER );
1241 $dbw->insert( 'user_newtalk',
1242 array( $field => $id ),
1243 __METHOD__,
1244 'IGNORE' );
1245 wfDebug( __METHOD__.": set on ($field, $id)\n" );
1246 return true;
1250 * Clear the new messages flag for the given user
1251 * @param string $field
1252 * @param mixed $id
1253 * @private
1255 function deleteNewtalk( $field, $id ) {
1256 if( !$this->checkNewtalk( $field, $id ) ) {
1257 wfDebug( __METHOD__.": already gone ($field, $id), ignoring\n" );
1258 return false;
1260 $dbw = wfGetDB( DB_MASTER );
1261 $dbw->delete( 'user_newtalk',
1262 array( $field => $id ),
1263 __METHOD__ );
1264 wfDebug( __METHOD__.": killed on ($field, $id)\n" );
1265 return true;
1269 * Update the 'You have new messages!' status.
1270 * @param bool $val
1272 function setNewtalk( $val ) {
1273 if( wfReadOnly() ) {
1274 return;
1277 $this->load();
1278 $this->mNewtalk = $val;
1280 if( $this->isAnon() ) {
1281 $field = 'user_ip';
1282 $id = $this->getName();
1283 } else {
1284 $field = 'user_id';
1285 $id = $this->getId();
1288 if( $val ) {
1289 $changed = $this->updateNewtalk( $field, $id );
1290 } else {
1291 $changed = $this->deleteNewtalk( $field, $id );
1294 if( $changed ) {
1295 if( $this->isAnon() ) {
1296 // Anons have a separate memcached space, since
1297 // user records aren't kept for them.
1298 global $wgMemc;
1299 $key = wfMemcKey( 'newtalk', 'ip', $val );
1300 $wgMemc->set( $key, $val ? 1 : 0 );
1301 } else {
1302 if( $val ) {
1303 // Make sure the user page is watched, so a notification
1304 // will be sent out if enabled.
1305 $this->addWatch( $this->getTalkPage() );
1308 $this->invalidateCache();
1313 * Generate a current or new-future timestamp to be stored in the
1314 * user_touched field when we update things.
1316 private static function newTouchedTimestamp() {
1317 global $wgClockSkewFudge;
1318 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1322 * Clear user data from memcached.
1323 * Use after applying fun updates to the database; caller's
1324 * responsibility to update user_touched if appropriate.
1326 * Called implicitly from invalidateCache() and saveSettings().
1328 private function clearSharedCache() {
1329 if( $this->mId ) {
1330 global $wgMemc;
1331 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1336 * Immediately touch the user data cache for this account.
1337 * Updates user_touched field, and removes account data from memcached
1338 * for reload on the next hit.
1340 function invalidateCache() {
1341 $this->load();
1342 if( $this->mId ) {
1343 $this->mTouched = self::newTouchedTimestamp();
1345 $dbw = wfGetDB( DB_MASTER );
1346 $dbw->update( 'user',
1347 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1348 array( 'user_id' => $this->mId ),
1349 __METHOD__ );
1351 $this->clearSharedCache();
1355 function validateCache( $timestamp ) {
1356 $this->load();
1357 return ($timestamp >= $this->mTouched);
1361 * Encrypt a password.
1362 * It can eventuall salt a password @see User::addSalt()
1363 * @param string $p clear Password.
1364 * @return string Encrypted password.
1366 function encryptPassword( $p ) {
1367 $this->load();
1368 return wfEncryptPassword( $this->mId, $p );
1372 * Set the password and reset the random token
1373 * Calls through to authentication plugin if necessary;
1374 * will have no effect if the auth plugin refuses to
1375 * pass the change through or if the legal password
1376 * checks fail.
1378 * As a special case, setting the password to null
1379 * wipes it, so the account cannot be logged in until
1380 * a new password is set, for instance via e-mail.
1382 * @param string $str
1383 * @throws PasswordError on failure
1385 function setPassword( $str ) {
1386 global $wgAuth;
1388 if( $str !== null ) {
1389 if( !$wgAuth->allowPasswordChange() ) {
1390 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1393 if( !$this->isValidPassword( $str ) ) {
1394 global $wgMinimalPasswordLength;
1395 throw new PasswordError( wfMsg( 'passwordtooshort',
1396 $wgMinimalPasswordLength ) );
1400 if( !$wgAuth->setPassword( $this, $str ) ) {
1401 throw new PasswordError( wfMsg( 'externaldberror' ) );
1404 $this->setInternalPassword( $str );
1406 return true;
1410 * Set the password and reset the random token no matter
1411 * what.
1413 * @param string $str
1415 function setInternalPassword( $str ) {
1416 $this->load();
1417 $this->setToken();
1419 if( $str === null ) {
1420 // Save an invalid hash...
1421 $this->mPassword = '';
1422 } else {
1423 $this->mPassword = $this->encryptPassword( $str );
1425 $this->mNewpassword = '';
1426 $this->mNewpassTime = null;
1429 * Set the random token (used for persistent authentication)
1430 * Called from loadDefaults() among other places.
1431 * @private
1433 function setToken( $token = false ) {
1434 global $wgSecretKey, $wgProxyKey;
1435 $this->load();
1436 if ( !$token ) {
1437 if ( $wgSecretKey ) {
1438 $key = $wgSecretKey;
1439 } elseif ( $wgProxyKey ) {
1440 $key = $wgProxyKey;
1441 } else {
1442 $key = microtime();
1444 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1445 } else {
1446 $this->mToken = $token;
1450 function setCookiePassword( $str ) {
1451 $this->load();
1452 $this->mCookiePassword = md5( $str );
1456 * Set the password for a password reminder or new account email
1457 * Sets the user_newpass_time field if $throttle is true
1459 function setNewpassword( $str, $throttle = true ) {
1460 $this->load();
1461 $this->mNewpassword = $this->encryptPassword( $str );
1462 if ( $throttle ) {
1463 $this->mNewpassTime = wfTimestampNow();
1468 * Returns true if a password reminder email has already been sent within
1469 * the last $wgPasswordReminderResendTime hours
1471 function isPasswordReminderThrottled() {
1472 global $wgPasswordReminderResendTime;
1473 $this->load();
1474 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1475 return false;
1477 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1478 return time() < $expiry;
1481 function getEmail() {
1482 $this->load();
1483 return $this->mEmail;
1486 function getEmailAuthenticationTimestamp() {
1487 $this->load();
1488 return $this->mEmailAuthenticated;
1491 function setEmail( $str ) {
1492 $this->load();
1493 $this->mEmail = $str;
1496 function getRealName() {
1497 $this->load();
1498 return $this->mRealName;
1501 function setRealName( $str ) {
1502 $this->load();
1503 $this->mRealName = $str;
1507 * @param string $oname The option to check
1508 * @param string $defaultOverride A default value returned if the option does not exist
1509 * @return string
1511 function getOption( $oname, $defaultOverride = '' ) {
1512 $this->load();
1514 if ( is_null( $this->mOptions ) ) {
1515 if($defaultOverride != '') {
1516 return $defaultOverride;
1518 $this->mOptions = User::getDefaultOptions();
1521 if ( array_key_exists( $oname, $this->mOptions ) ) {
1522 return trim( $this->mOptions[$oname] );
1523 } else {
1524 return $defaultOverride;
1529 * Get the user's date preference, including some important migration for
1530 * old user rows.
1532 function getDatePreference() {
1533 if ( is_null( $this->mDatePreference ) ) {
1534 global $wgLang;
1535 $value = $this->getOption( 'date' );
1536 $map = $wgLang->getDatePreferenceMigrationMap();
1537 if ( isset( $map[$value] ) ) {
1538 $value = $map[$value];
1540 $this->mDatePreference = $value;
1542 return $this->mDatePreference;
1546 * @param string $oname The option to check
1547 * @return bool False if the option is not selected, true if it is
1549 function getBoolOption( $oname ) {
1550 return (bool)$this->getOption( $oname );
1554 * Get an option as an integer value from the source string.
1555 * @param string $oname The option to check
1556 * @param int $default Optional value to return if option is unset/blank.
1557 * @return int
1559 function getIntOption( $oname, $default=0 ) {
1560 $val = $this->getOption( $oname );
1561 if( $val == '' ) {
1562 $val = $default;
1564 return intval( $val );
1567 function setOption( $oname, $val ) {
1568 $this->load();
1569 if ( is_null( $this->mOptions ) ) {
1570 $this->mOptions = User::getDefaultOptions();
1572 if ( $oname == 'skin' ) {
1573 # Clear cached skin, so the new one displays immediately in Special:Preferences
1574 unset( $this->mSkin );
1576 // Filter out any newlines that may have passed through input validation.
1577 // Newlines are used to separate items in the options blob.
1578 $val = str_replace( "\r\n", "\n", $val );
1579 $val = str_replace( "\r", "\n", $val );
1580 $val = str_replace( "\n", " ", $val );
1581 $this->mOptions[$oname] = $val;
1584 function getRights() {
1585 if ( is_null( $this->mRights ) ) {
1586 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
1588 return $this->mRights;
1592 * Get the list of explicit group memberships this user has.
1593 * The implicit * and user groups are not included.
1594 * @return array of strings
1596 function getGroups() {
1597 $this->load();
1598 return $this->mGroups;
1602 * Get the list of implicit group memberships this user has.
1603 * This includes all explicit groups, plus 'user' if logged in
1604 * and '*' for all accounts.
1605 * @param boolean $recache Don't use the cache
1606 * @return array of strings
1608 function getEffectiveGroups( $recache = false ) {
1609 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
1610 $this->load();
1611 $this->mEffectiveGroups = $this->mGroups;
1612 $this->mEffectiveGroups[] = '*';
1613 if( $this->mId ) {
1614 $this->mEffectiveGroups[] = 'user';
1616 global $wgAutoConfirmAge, $wgAutoConfirmCount;
1618 $accountAge = time() - wfTimestampOrNull( TS_UNIX, $this->mRegistration );
1619 if( $accountAge >= $wgAutoConfirmAge && $this->getEditCount() >= $wgAutoConfirmCount ) {
1620 $this->mEffectiveGroups[] = 'autoconfirmed';
1622 # Implicit group for users whose email addresses are confirmed
1623 global $wgEmailAuthentication;
1624 if( self::isValidEmailAddr( $this->mEmail ) ) {
1625 if( $wgEmailAuthentication ) {
1626 if( $this->mEmailAuthenticated )
1627 $this->mEffectiveGroups[] = 'emailconfirmed';
1628 } else {
1629 $this->mEffectiveGroups[] = 'emailconfirmed';
1634 return $this->mEffectiveGroups;
1637 /* Return the edit count for the user. This is where User::edits should have been */
1638 function getEditCount() {
1639 if ($this->mId) {
1640 if ( !isset( $this->mEditCount ) ) {
1641 /* Populate the count, if it has not been populated yet */
1642 $this->mEditCount = User::edits($this->mId);
1644 return $this->mEditCount;
1645 } else {
1646 /* nil */
1647 return null;
1652 * Add the user to the given group.
1653 * This takes immediate effect.
1654 * @string $group
1656 function addGroup( $group ) {
1657 $this->load();
1658 $dbw = wfGetDB( DB_MASTER );
1659 if( $this->getId() ) {
1660 $dbw->insert( 'user_groups',
1661 array(
1662 'ug_user' => $this->getID(),
1663 'ug_group' => $group,
1665 'User::addGroup',
1666 array( 'IGNORE' ) );
1669 $this->mGroups[] = $group;
1670 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1672 $this->invalidateCache();
1676 * Remove the user from the given group.
1677 * This takes immediate effect.
1678 * @string $group
1680 function removeGroup( $group ) {
1681 $this->load();
1682 $dbw = wfGetDB( DB_MASTER );
1683 $dbw->delete( 'user_groups',
1684 array(
1685 'ug_user' => $this->getID(),
1686 'ug_group' => $group,
1688 'User::removeGroup' );
1690 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
1691 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1693 $this->invalidateCache();
1698 * A more legible check for non-anonymousness.
1699 * Returns true if the user is not an anonymous visitor.
1701 * @return bool
1703 function isLoggedIn() {
1704 return( $this->getID() != 0 );
1708 * A more legible check for anonymousness.
1709 * Returns true if the user is an anonymous visitor.
1711 * @return bool
1713 function isAnon() {
1714 return !$this->isLoggedIn();
1718 * Whether the user is a bot
1719 * @deprecated
1721 function isBot() {
1722 return $this->isAllowed( 'bot' );
1726 * Check if user is allowed to access a feature / make an action
1727 * @param string $action Action to be checked
1728 * @return boolean True: action is allowed, False: action should not be allowed
1730 function isAllowed($action='') {
1731 if ( $action === '' )
1732 // In the spirit of DWIM
1733 return true;
1735 return in_array( $action, $this->getRights() );
1739 * Load a skin if it doesn't exist or return it
1740 * @todo FIXME : need to check the old failback system [AV]
1742 function &getSkin() {
1743 global $wgRequest;
1744 if ( ! isset( $this->mSkin ) ) {
1745 wfProfileIn( __METHOD__ );
1747 # get the user skin
1748 $userSkin = $this->getOption( 'skin' );
1749 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1751 $this->mSkin =& Skin::newFromKey( $userSkin );
1752 wfProfileOut( __METHOD__ );
1754 return $this->mSkin;
1757 /**#@+
1758 * @param string $title Article title to look at
1762 * Check watched status of an article
1763 * @return bool True if article is watched
1765 function isWatched( $title ) {
1766 $wl = WatchedItem::fromUserTitle( $this, $title );
1767 return $wl->isWatched();
1771 * Watch an article
1773 function addWatch( $title ) {
1774 $wl = WatchedItem::fromUserTitle( $this, $title );
1775 $wl->addWatch();
1776 $this->invalidateCache();
1780 * Stop watching an article
1782 function removeWatch( $title ) {
1783 $wl = WatchedItem::fromUserTitle( $this, $title );
1784 $wl->removeWatch();
1785 $this->invalidateCache();
1789 * Clear the user's notification timestamp for the given title.
1790 * If e-notif e-mails are on, they will receive notification mails on
1791 * the next change of the page if it's watched etc.
1793 function clearNotification( &$title ) {
1794 global $wgUser, $wgUseEnotif;
1796 # Do nothing if the database is locked to writes
1797 if( wfReadOnly() ) {
1798 return;
1801 if ($title->getNamespace() == NS_USER_TALK &&
1802 $title->getText() == $this->getName() ) {
1803 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1804 return;
1805 $this->setNewtalk( false );
1808 if( !$wgUseEnotif ) {
1809 return;
1812 if( $this->isAnon() ) {
1813 // Nothing else to do...
1814 return;
1817 // Only update the timestamp if the page is being watched.
1818 // The query to find out if it is watched is cached both in memcached and per-invocation,
1819 // and when it does have to be executed, it can be on a slave
1820 // If this is the user's newtalk page, we always update the timestamp
1821 if ($title->getNamespace() == NS_USER_TALK &&
1822 $title->getText() == $wgUser->getName())
1824 $watched = true;
1825 } elseif ( $this->getID() == $wgUser->getID() ) {
1826 $watched = $title->userIsWatching();
1827 } else {
1828 $watched = true;
1831 // If the page is watched by the user (or may be watched), update the timestamp on any
1832 // any matching rows
1833 if ( $watched ) {
1834 $dbw = wfGetDB( DB_MASTER );
1835 $dbw->update( 'watchlist',
1836 array( /* SET */
1837 'wl_notificationtimestamp' => NULL
1838 ), array( /* WHERE */
1839 'wl_title' => $title->getDBkey(),
1840 'wl_namespace' => $title->getNamespace(),
1841 'wl_user' => $this->getID()
1842 ), 'User::clearLastVisited'
1847 /**#@-*/
1850 * Resets all of the given user's page-change notification timestamps.
1851 * If e-notif e-mails are on, they will receive notification mails on
1852 * the next change of any watched page.
1854 * @param int $currentUser user ID number
1855 * @public
1857 function clearAllNotifications( $currentUser ) {
1858 global $wgUseEnotif;
1859 if ( !$wgUseEnotif ) {
1860 $this->setNewtalk( false );
1861 return;
1863 if( $currentUser != 0 ) {
1865 $dbw = wfGetDB( DB_MASTER );
1866 $dbw->update( 'watchlist',
1867 array( /* SET */
1868 'wl_notificationtimestamp' => NULL
1869 ), array( /* WHERE */
1870 'wl_user' => $currentUser
1871 ), 'UserMailer::clearAll'
1874 # we also need to clear here the "you have new message" notification for the own user_talk page
1875 # This is cleared one page view later in Article::viewUpdates();
1880 * @private
1881 * @return string Encoding options
1883 function encodeOptions() {
1884 $this->load();
1885 if ( is_null( $this->mOptions ) ) {
1886 $this->mOptions = User::getDefaultOptions();
1888 $a = array();
1889 foreach ( $this->mOptions as $oname => $oval ) {
1890 array_push( $a, $oname.'='.$oval );
1892 $s = implode( "\n", $a );
1893 return $s;
1897 * @private
1899 function decodeOptions( $str ) {
1900 $this->mOptions = array();
1901 $a = explode( "\n", $str );
1902 foreach ( $a as $s ) {
1903 $m = array();
1904 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1905 $this->mOptions[$m[1]] = $m[2];
1910 function setCookies() {
1911 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1912 $this->load();
1913 if ( 0 == $this->mId ) return;
1914 $exp = time() + $wgCookieExpiration;
1916 $_SESSION['wsUserID'] = $this->mId;
1917 setcookie( $wgCookiePrefix.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1919 $_SESSION['wsUserName'] = $this->getName();
1920 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1922 $_SESSION['wsToken'] = $this->mToken;
1923 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1924 setcookie( $wgCookiePrefix.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1925 } else {
1926 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1931 * Logout user
1932 * Clears the cookies and session, resets the instance cache
1934 function logout() {
1935 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1936 $this->clearInstanceCache( 'defaults' );
1938 $_SESSION['wsUserID'] = 0;
1940 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1941 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1943 # Remember when user logged out, to prevent seeing cached pages
1944 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1948 * Save object settings into database
1949 * @fixme Only rarely do all these fields need to be set!
1951 function saveSettings() {
1952 $this->load();
1953 if ( wfReadOnly() ) { return; }
1954 if ( 0 == $this->mId ) { return; }
1956 $this->mTouched = self::newTouchedTimestamp();
1958 $dbw = wfGetDB( DB_MASTER );
1959 $dbw->update( 'user',
1960 array( /* SET */
1961 'user_name' => $this->mName,
1962 'user_password' => $this->mPassword,
1963 'user_newpassword' => $this->mNewpassword,
1964 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
1965 'user_real_name' => $this->mRealName,
1966 'user_email' => $this->mEmail,
1967 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1968 'user_options' => $this->encodeOptions(),
1969 'user_touched' => $dbw->timestamp($this->mTouched),
1970 'user_token' => $this->mToken
1971 ), array( /* WHERE */
1972 'user_id' => $this->mId
1973 ), __METHOD__
1975 $this->clearSharedCache();
1980 * Checks if a user with the given name exists, returns the ID
1982 function idForName() {
1983 $s = trim( $this->getName() );
1984 if ( 0 == strcmp( '', $s ) ) return 0;
1986 $dbr = wfGetDB( DB_SLAVE );
1987 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
1988 if ( $id === false ) {
1989 $id = 0;
1991 return $id;
1995 * Add a user to the database, return the user object
1997 * @param string $name The user's name
1998 * @param array $params Associative array of non-default parameters to save to the database:
1999 * password The user's password. Password logins will be disabled if this is omitted.
2000 * newpassword A temporary password mailed to the user
2001 * email The user's email address
2002 * email_authenticated The email authentication timestamp
2003 * real_name The user's real name
2004 * options An associative array of non-default options
2005 * token Random authentication token. Do not set.
2006 * registration Registration timestamp. Do not set.
2008 * @return User object, or null if the username already exists
2010 static function createNew( $name, $params = array() ) {
2011 $user = new User;
2012 $user->load();
2013 if ( isset( $params['options'] ) ) {
2014 $user->mOptions = $params['options'] + $user->mOptions;
2015 unset( $params['options'] );
2017 $dbw = wfGetDB( DB_MASTER );
2018 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2019 $fields = array(
2020 'user_id' => $seqVal,
2021 'user_name' => $name,
2022 'user_password' => $user->mPassword,
2023 'user_newpassword' => $user->mNewpassword,
2024 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ),
2025 'user_email' => $user->mEmail,
2026 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2027 'user_real_name' => $user->mRealName,
2028 'user_options' => $user->encodeOptions(),
2029 'user_token' => $user->mToken,
2030 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2031 'user_editcount' => 0,
2033 foreach ( $params as $name => $value ) {
2034 $fields["user_$name"] = $value;
2036 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2037 if ( $dbw->affectedRows() ) {
2038 $newUser = User::newFromId( $dbw->insertId() );
2039 } else {
2040 $newUser = null;
2042 return $newUser;
2046 * Add an existing user object to the database
2048 function addToDatabase() {
2049 $this->load();
2050 $dbw = wfGetDB( DB_MASTER );
2051 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2052 $dbw->insert( 'user',
2053 array(
2054 'user_id' => $seqVal,
2055 'user_name' => $this->mName,
2056 'user_password' => $this->mPassword,
2057 'user_newpassword' => $this->mNewpassword,
2058 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ),
2059 'user_email' => $this->mEmail,
2060 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2061 'user_real_name' => $this->mRealName,
2062 'user_options' => $this->encodeOptions(),
2063 'user_token' => $this->mToken,
2064 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2065 'user_editcount' => 0,
2066 ), __METHOD__
2068 $this->mId = $dbw->insertId();
2070 # Clear instance cache other than user table data, which is already accurate
2071 $this->clearInstanceCache();
2075 * If the (non-anonymous) user is blocked, this function will block any IP address
2076 * that they successfully log on from.
2078 function spreadBlock() {
2079 wfDebug( __METHOD__."()\n" );
2080 $this->load();
2081 if ( $this->mId == 0 ) {
2082 return;
2085 $userblock = Block::newFromDB( '', $this->mId );
2086 if ( !$userblock ) {
2087 return;
2090 $userblock->doAutoblock( wfGetIp() );
2095 * Generate a string which will be different for any combination of
2096 * user options which would produce different parser output.
2097 * This will be used as part of the hash key for the parser cache,
2098 * so users will the same options can share the same cached data
2099 * safely.
2101 * Extensions which require it should install 'PageRenderingHash' hook,
2102 * which will give them a chance to modify this key based on their own
2103 * settings.
2105 * @return string
2107 function getPageRenderingHash() {
2108 global $wgContLang, $wgUseDynamicDates, $wgLang;
2109 if( $this->mHash ){
2110 return $this->mHash;
2113 // stubthreshold is only included below for completeness,
2114 // it will always be 0 when this function is called by parsercache.
2116 $confstr = $this->getOption( 'math' );
2117 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2118 if ( $wgUseDynamicDates ) {
2119 $confstr .= '!' . $this->getDatePreference();
2121 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
2122 $confstr .= '!' . $wgLang->getCode();
2123 $confstr .= '!' . $this->getOption( 'thumbsize' );
2124 // add in language specific options, if any
2125 $extra = $wgContLang->getExtraHashOptions();
2126 $confstr .= $extra;
2128 // Give a chance for extensions to modify the hash, if they have
2129 // extra options or other effects on the parser cache.
2130 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2132 $this->mHash = $confstr;
2133 return $confstr;
2136 function isBlockedFromCreateAccount() {
2137 $this->getBlockedStatus();
2138 return $this->mBlock && $this->mBlock->mCreateAccount;
2141 function isAllowedToCreateAccount() {
2142 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2146 * @deprecated
2148 function setLoaded( $loaded ) {}
2151 * Get this user's personal page title.
2153 * @return Title
2154 * @public
2156 function getUserPage() {
2157 return Title::makeTitle( NS_USER, $this->getName() );
2161 * Get this user's talk page title.
2163 * @return Title
2164 * @public
2166 function getTalkPage() {
2167 $title = $this->getUserPage();
2168 return $title->getTalkPage();
2172 * @static
2174 function getMaxID() {
2175 static $res; // cache
2177 if ( isset( $res ) )
2178 return $res;
2179 else {
2180 $dbr = wfGetDB( DB_SLAVE );
2181 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2186 * Determine whether the user is a newbie. Newbies are either
2187 * anonymous IPs, or the most recently created accounts.
2188 * @return bool True if it is a newbie.
2190 function isNewbie() {
2191 return !$this->isAllowed( 'autoconfirmed' );
2195 * Check to see if the given clear-text password is one of the accepted passwords
2196 * @param string $password User password.
2197 * @return bool True if the given password is correct otherwise False.
2199 function checkPassword( $password ) {
2200 global $wgAuth;
2201 $this->load();
2203 // Even though we stop people from creating passwords that
2204 // are shorter than this, doesn't mean people wont be able
2205 // to. Certain authentication plugins do NOT want to save
2206 // domain passwords in a mysql database, so we should
2207 // check this (incase $wgAuth->strict() is false).
2208 if( !$this->isValidPassword( $password ) ) {
2209 return false;
2212 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2213 return true;
2214 } elseif( $wgAuth->strict() ) {
2215 /* Auth plugin doesn't allow local authentication */
2216 return false;
2218 $ep = $this->encryptPassword( $password );
2219 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
2220 return true;
2221 } elseif ( function_exists( 'iconv' ) ) {
2222 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2223 # Check for this with iconv
2224 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2225 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
2226 return true;
2229 return false;
2233 * Check if the given clear-text password matches the temporary password
2234 * sent by e-mail for password reset operations.
2235 * @return bool
2237 function checkTemporaryPassword( $plaintext ) {
2238 $hash = $this->encryptPassword( $plaintext );
2239 return $hash === $this->mNewpassword;
2243 * Initialize (if necessary) and return a session token value
2244 * which can be used in edit forms to show that the user's
2245 * login credentials aren't being hijacked with a foreign form
2246 * submission.
2248 * @param mixed $salt - Optional function-specific data for hash.
2249 * Use a string or an array of strings.
2250 * @return string
2251 * @public
2253 function editToken( $salt = '' ) {
2254 if( !isset( $_SESSION['wsEditToken'] ) ) {
2255 $token = $this->generateToken();
2256 $_SESSION['wsEditToken'] = $token;
2257 } else {
2258 $token = $_SESSION['wsEditToken'];
2260 if( is_array( $salt ) ) {
2261 $salt = implode( '|', $salt );
2263 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2267 * Generate a hex-y looking random token for various uses.
2268 * Could be made more cryptographically sure if someone cares.
2269 * @return string
2271 function generateToken( $salt = '' ) {
2272 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2273 return md5( $token . $salt );
2277 * Check given value against the token value stored in the session.
2278 * A match should confirm that the form was submitted from the
2279 * user's own login session, not a form submission from a third-party
2280 * site.
2282 * @param string $val - the input value to compare
2283 * @param string $salt - Optional function-specific data for hash
2284 * @return bool
2285 * @public
2287 function matchEditToken( $val, $salt = '' ) {
2288 global $wgMemc;
2289 $sessionToken = $this->editToken( $salt );
2290 if ( $val != $sessionToken ) {
2291 wfDebug( "User::matchEditToken: broken session data\n" );
2293 return $val == $sessionToken;
2297 * Generate a new e-mail confirmation token and send a confirmation
2298 * mail to the user's given address.
2300 * @return mixed True on success, a WikiError object on failure.
2302 function sendConfirmationMail() {
2303 global $wgContLang;
2304 $expiration = null; // gets passed-by-ref and defined in next line.
2305 $url = $this->confirmationTokenUrl( $expiration );
2306 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2307 wfMsg( 'confirmemail_body',
2308 wfGetIP(),
2309 $this->getName(),
2310 $url,
2311 $wgContLang->timeanddate( $expiration, false ) ) );
2315 * Send an e-mail to this user's account. Does not check for
2316 * confirmed status or validity.
2318 * @param string $subject
2319 * @param string $body
2320 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
2321 * @return mixed True on success, a WikiError object on failure.
2323 function sendMail( $subject, $body, $from = null ) {
2324 if( is_null( $from ) ) {
2325 global $wgPasswordSender;
2326 $from = $wgPasswordSender;
2329 require_once( 'UserMailer.php' );
2330 $to = new MailAddress( $this );
2331 $sender = new MailAddress( $from );
2332 $error = userMailer( $to, $sender, $subject, $body );
2334 if( $error == '' ) {
2335 return true;
2336 } else {
2337 return new WikiError( $error );
2342 * Generate, store, and return a new e-mail confirmation code.
2343 * A hash (unsalted since it's used as a key) is stored.
2344 * @param &$expiration mixed output: accepts the expiration time
2345 * @return string
2346 * @private
2348 function confirmationToken( &$expiration ) {
2349 $now = time();
2350 $expires = $now + 7 * 24 * 60 * 60;
2351 $expiration = wfTimestamp( TS_MW, $expires );
2353 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
2354 $hash = md5( $token );
2356 $dbw = wfGetDB( DB_MASTER );
2357 $dbw->update( 'user',
2358 array( 'user_email_token' => $hash,
2359 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2360 array( 'user_id' => $this->mId ),
2361 __METHOD__ );
2363 return $token;
2367 * Generate and store a new e-mail confirmation token, and return
2368 * the URL the user can use to confirm.
2369 * @param &$expiration mixed output: accepts the expiration time
2370 * @return string
2371 * @private
2373 function confirmationTokenUrl( &$expiration ) {
2374 $token = $this->confirmationToken( $expiration );
2375 $title = SpecialPage::getTitleFor( 'Confirmemail', $token );
2376 return $title->getFullUrl();
2380 * Mark the e-mail address confirmed and save.
2382 function confirmEmail() {
2383 $this->load();
2384 $this->mEmailAuthenticated = wfTimestampNow();
2385 $this->saveSettings();
2386 return true;
2390 * Is this user allowed to send e-mails within limits of current
2391 * site configuration?
2392 * @return bool
2394 function canSendEmail() {
2395 return $this->isEmailConfirmed();
2399 * Is this user allowed to receive e-mails within limits of current
2400 * site configuration?
2401 * @return bool
2403 function canReceiveEmail() {
2404 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2408 * Is this user's e-mail address valid-looking and confirmed within
2409 * limits of the current site configuration?
2411 * If $wgEmailAuthentication is on, this may require the user to have
2412 * confirmed their address by returning a code or using a password
2413 * sent to the address from the wiki.
2415 * @return bool
2417 function isEmailConfirmed() {
2418 global $wgEmailAuthentication;
2419 $this->load();
2420 $confirmed = true;
2421 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2422 if( $this->isAnon() )
2423 return false;
2424 if( !self::isValidEmailAddr( $this->mEmail ) )
2425 return false;
2426 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2427 return false;
2428 return true;
2429 } else {
2430 return $confirmed;
2435 * Return true if there is an outstanding request for e-mail confirmation.
2436 * @return bool
2438 function isEmailConfirmationPending() {
2439 global $wgEmailAuthentication;
2440 return $wgEmailAuthentication &&
2441 !$this->isEmailConfirmed() &&
2442 $this->mEmailToken &&
2443 $this->mEmailTokenExpires > wfTimestamp();
2447 * @param array $groups list of groups
2448 * @return array list of permission key names for given groups combined
2449 * @static
2451 static function getGroupPermissions( $groups ) {
2452 global $wgGroupPermissions;
2453 $rights = array();
2454 foreach( $groups as $group ) {
2455 if( isset( $wgGroupPermissions[$group] ) ) {
2456 $rights = array_merge( $rights,
2457 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2460 return $rights;
2464 * @param string $group key name
2465 * @return string localized descriptive name for group, if provided
2466 * @static
2468 static function getGroupName( $group ) {
2469 $key = "group-$group";
2470 $name = wfMsg( $key );
2471 if( $name == '' || wfEmptyMsg( $key, $name ) ) {
2472 return $group;
2473 } else {
2474 return $name;
2479 * @param string $group key name
2480 * @return string localized descriptive name for member of a group, if provided
2481 * @static
2483 static function getGroupMember( $group ) {
2484 $key = "group-$group-member";
2485 $name = wfMsg( $key );
2486 if( $name == '' || wfEmptyMsg( $key, $name ) ) {
2487 return $group;
2488 } else {
2489 return $name;
2494 * Return the set of defined explicit groups.
2495 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2496 * groups are not included, as they are defined
2497 * automatically, not in the database.
2498 * @return array
2499 * @static
2501 static function getAllGroups() {
2502 global $wgGroupPermissions;
2503 return array_diff(
2504 array_keys( $wgGroupPermissions ),
2505 array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
2509 * Get the title of a page describing a particular group
2511 * @param $group Name of the group
2512 * @return mixed
2514 static function getGroupPage( $group ) {
2515 $page = wfMsgForContent( 'grouppage-' . $group );
2516 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2517 $title = Title::newFromText( $page );
2518 if( is_object( $title ) )
2519 return $title;
2521 return false;
2525 * Create a link to the group in HTML, if available
2527 * @param $group Name of the group
2528 * @param $text The text of the link
2529 * @return mixed
2531 static function makeGroupLinkHTML( $group, $text = '' ) {
2532 if( $text == '' ) {
2533 $text = self::getGroupName( $group );
2535 $title = self::getGroupPage( $group );
2536 if( $title ) {
2537 global $wgUser;
2538 $sk = $wgUser->getSkin();
2539 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2540 } else {
2541 return $text;
2546 * Create a link to the group in Wikitext, if available
2548 * @param $group Name of the group
2549 * @param $text The text of the link (by default, the name of the group)
2550 * @return mixed
2552 static function makeGroupLinkWiki( $group, $text = '' ) {
2553 if( $text == '' ) {
2554 $text = self::getGroupName( $group );
2556 $title = self::getGroupPage( $group );
2557 if( $title ) {
2558 $page = $title->getPrefixedText();
2559 return "[[$page|$text]]";
2560 } else {
2561 return $text;
2566 * Increment the user's edit-count field.
2567 * Will have no effect for anonymous users.
2569 function incEditCount() {
2570 if( !$this->isAnon() ) {
2571 $dbw = wfGetDB( DB_MASTER );
2572 $dbw->update( 'user',
2573 array( 'user_editcount=user_editcount+1' ),
2574 array( 'user_id' => $this->getId() ),
2575 __METHOD__ );
2577 // Lazy initialization check...
2578 if( $dbw->affectedRows() == 0 ) {
2579 // Pull from a slave to be less cruel to servers
2580 // Accuracy isn't the point anyway here
2581 $dbr = wfGetDB( DB_SLAVE );
2582 $count = $dbr->selectField( 'revision',
2583 'COUNT(rev_user)',
2584 array( 'rev_user' => $this->getId() ),
2585 __METHOD__ );
2587 // Now here's a goddamn hack...
2588 if( $dbr !== $dbw ) {
2589 // If we actually have a slave server, the count is
2590 // at least one behind because the current transaction
2591 // has not been committed and replicated.
2592 $count++;
2593 } else {
2594 // But if DB_SLAVE is selecting the master, then the
2595 // count we just read includes the revision that was
2596 // just added in the working transaction.
2599 $dbw->update( 'user',
2600 array( 'user_editcount' => $count ),
2601 array( 'user_id' => $this->getId() ),
2602 __METHOD__ );
2605 // edit count in user cache too
2606 $this->invalidateCache();