]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/User.php
MediaWiki 1.11.0
[autoinstalls/mediawiki.git] / includes / User.php
1 <?php
2 /**
3  * See user.txt
4  *
5  */
6
7 # Number of characters in user_token field
8 define( 'USER_TOKEN_LENGTH', 32 );
9
10 # Serialized record version
11 define( 'MW_USER_VERSION', 5 );
12
13 # Some punctuation to prevent editing from broken text-mangling proxies.
14 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
15
16 /**
17  * Thrown by User::setPassword() on error
18  * @addtogroup Exception
19  */
20 class PasswordError extends MWException {
21         // NOP
22 }
23
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.
33  */
34 class User {
35
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().
40          */
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         );
80
81         /**
82          * List of member variables which are saved to the shared cache (memcached).
83          * Any operation which changes the corresponding database fields must 
84          * call a cache-clearing function.
85          */
86         static $mCacheVars = array(
87                 # user table
88                 'mId',
89                 'mName',
90                 'mRealName',
91                 'mPassword',
92                 'mNewpassword',
93                 'mNewpassTime',
94                 'mEmail',
95                 'mOptions',
96                 'mTouched',
97                 'mToken',
98                 'mEmailAuthenticated',
99                 'mEmailToken',
100                 'mEmailTokenExpires',
101                 'mRegistration',
102                 'mEditCount',
103                 # user_group table
104                 'mGroups',
105         );
106
107         /**
108          * The cache variable declarations
109          */
110         var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime, 
111                 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated, 
112                 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
113
114         /**
115          * Whether the cache variables have been loaded
116          */
117         var $mDataLoaded;
118
119         /**
120          * Initialisation data source if mDataLoaded==false. May be one of:
121          *    defaults      anonymous user initialised from class defaults
122          *    name          initialise from mName
123          *    id            initialise from mId
124          *    session       log in from cookies or session if possible
125          *
126          * Use the User::newFrom*() family of functions to set this.
127          */
128         var $mFrom;
129
130         /**
131          * Lazy-initialised variables, invalidated with clearInstanceCache
132          */
133         var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
134                 $mBlockreason, $mBlock, $mEffectiveGroups;
135
136         /** 
137          * Lightweight constructor for anonymous user
138          * Use the User::newFrom* factory functions for other kinds of users
139          */
140         function User() {
141                 $this->clearInstanceCache( 'defaults' );
142         }
143
144         /**
145          * Load the user table data for this object from the source given by mFrom
146          */
147         function load() {
148                 if ( $this->mDataLoaded ) {
149                         return;
150                 }
151                 wfProfileIn( __METHOD__ );
152
153                 # Set it now to avoid infinite recursion in accessors
154                 $this->mDataLoaded = true;
155
156                 switch ( $this->mFrom ) {
157                         case 'defaults':
158                                 $this->loadDefaults();
159                                 break;
160                         case 'name':
161                                 $this->mId = self::idFromName( $this->mName );
162                                 if ( !$this->mId ) {
163                                         # Nonexistent user placeholder object
164                                         $this->loadDefaults( $this->mName );
165                                 } else {
166                                         $this->loadFromId();
167                                 }
168                                 break;
169                         case 'id':
170                                 $this->loadFromId();
171                                 break;
172                         case 'session':
173                                 $this->loadFromSession();
174                                 break;
175                         default:
176                                 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
177                 }
178                 wfProfileOut( __METHOD__ );
179         }
180
181         /**
182          * Load user table data given mId
183          * @return false if the ID does not exist, true otherwise
184          * @private
185          */
186         function loadFromId() {
187                 global $wgMemc;
188                 if ( $this->mId == 0 ) {
189                         $this->loadDefaults();
190                         return false;
191                 } 
192
193                 # Try cache
194                 $key = wfMemcKey( 'user', 'id', $this->mId );
195                 $data = $wgMemc->get( $key );
196                 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
197                         # Object is expired, load from DB
198                         $data = false;
199                 }
200                 
201                 if ( !$data ) {
202                         wfDebug( "Cache miss for user {$this->mId}\n" );
203                         # Load from DB
204                         if ( !$this->loadFromDatabase() ) {
205                                 # Can't load from ID, user is anonymous
206                                 return false;
207                         }
208
209                         # Save to cache
210                         $data = array();
211                         foreach ( self::$mCacheVars as $name ) {
212                                 $data[$name] = $this->$name;
213                         }
214                         $data['mVersion'] = MW_USER_VERSION;
215                         $wgMemc->set( $key, $data );
216                 } else {
217                         wfDebug( "Got user {$this->mId} from cache\n" );
218                         # Restore from cache
219                         foreach ( self::$mCacheVars as $name ) {
220                                 $this->$name = $data[$name];
221                         }
222                 }
223                 return true;
224         }
225
226         /**
227          * Static factory method for creation from username.
228          *
229          * This is slightly less efficient than newFromId(), so use newFromId() if
230          * you have both an ID and a name handy. 
231          *
232          * @param string $name Username, validated by Title:newFromText()
233          * @param mixed $validate Validate username. Takes the same parameters as 
234          *    User::getCanonicalName(), except that true is accepted as an alias 
235          *    for 'valid', for BC.
236          * 
237          * @return User object, or null if the username is invalid. If the username 
238          *    is not present in the database, the result will be a user object with
239          *    a name, zero user ID and default settings. 
240          * @static
241          */
242         static function newFromName( $name, $validate = 'valid' ) {
243                 if ( $validate === true ) {
244                         $validate = 'valid';
245                 }
246                 $name = self::getCanonicalName( $name, $validate );
247                 if ( $name === false ) {
248                         return null;
249                 } else {
250                         # Create unloaded user object
251                         $u = new User;
252                         $u->mName = $name;
253                         $u->mFrom = 'name';
254                         return $u;
255                 }
256         }
257
258         static function newFromId( $id ) {
259                 $u = new User;
260                 $u->mId = $id;
261                 $u->mFrom = 'id';
262                 return $u;
263         }
264
265         /**
266          * Factory method to fetch whichever user has a given email confirmation code.
267          * This code is generated when an account is created or its e-mail address
268          * has changed.
269          *
270          * If the code is invalid or has expired, returns NULL.
271          *
272          * @param string $code
273          * @return User
274          * @static
275          */
276         static function newFromConfirmationCode( $code ) {
277                 $dbr = wfGetDB( DB_SLAVE );
278                 $id = $dbr->selectField( 'user', 'user_id', array(
279                         'user_email_token' => md5( $code ),
280                         'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
281                         ) );
282                 if( $id !== false ) {
283                         return User::newFromId( $id );
284                 } else {
285                         return null;
286                 }
287         }
288         
289         /**
290          * Create a new user object using data from session or cookies. If the
291          * login credentials are invalid, the result is an anonymous user.
292          *
293          * @return User
294          * @static
295          */
296         static function newFromSession() {
297                 $user = new User;
298                 $user->mFrom = 'session';
299                 return $user;
300         }
301
302         /**
303          * Get username given an id.
304          * @param integer $id Database user id
305          * @return string Nickname of a user
306          * @static
307          */
308         static function whoIs( $id ) {
309                 $dbr = wfGetDB( DB_SLAVE );
310                 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
311         }
312
313         /**
314          * Get the real name of a user given their identifier
315          *
316          * @param int $id Database user id
317          * @return string Real name of a user
318          */
319         static function whoIsReal( $id ) {
320                 $dbr = wfGetDB( DB_SLAVE );
321                 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ );
322         }
323
324         /**
325          * Get database id given a user name
326          * @param string $name Nickname of a user
327          * @return integer|null Database user id (null: if non existent
328          * @static
329          */
330         static function idFromName( $name ) {
331                 $nt = Title::newFromText( $name );
332                 if( is_null( $nt ) ) {
333                         # Illegal name
334                         return null;
335                 }
336                 $dbr = wfGetDB( DB_SLAVE );
337                 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
338
339                 if ( $s === false ) {
340                         return 0;
341                 } else {
342                         return $s->user_id;
343                 }
344         }
345
346         /**
347          * Does the string match an anonymous IPv4 address?
348          *
349          * This function exists for username validation, in order to reject
350          * usernames which are similar in form to IP addresses. Strings such
351          * as 300.300.300.300 will return true because it looks like an IP 
352          * address, despite not being strictly valid.
353          * 
354          * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
355          * address because the usemod software would "cloak" anonymous IP
356          * addresses like this, if we allowed accounts like this to be created
357          * new users could get the old edits of these anonymous users.
358          *
359          * @static
360          * @param string $name Nickname of a user
361          * @return bool
362          */
363         static function isIP( $name ) {
364                 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || User::isIPv6($name);
365                 /*return preg_match("/^
366                         (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
367                         (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
368                         (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
369                         (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
370                 $/x", $name);*/
371         }
372
373         /**
374          * Check if $name is an IPv6 IP.
375          */
376         static function isIPv6($name) {
377                 /* 
378                  * if it has any non-valid characters, it can't be a valid IPv6  
379                  * address.
380                  */
381                 if (preg_match("/[^:a-fA-F0-9]/", $name))
382                         return false;
383
384                 $parts = explode(":", $name);
385                 if (count($parts) < 3)
386                         return false;
387                 foreach ($parts as $part) {
388                         if (!preg_match("/^[0-9a-fA-F]{0,4}$/", $part))
389                                 return false;
390                 }
391                 return true;
392         }
393
394         /**
395          * Is the input a valid username?
396          *
397          * Checks if the input is a valid username, we don't want an empty string,
398          * an IP address, anything that containins slashes (would mess up subpages),
399          * is longer than the maximum allowed username size or doesn't begin with
400          * a capital letter.
401          *
402          * @param string $name
403          * @return bool
404          * @static
405          */
406         static function isValidUserName( $name ) {
407                 global $wgContLang, $wgMaxNameChars;
408
409                 if ( $name == ''
410                 || User::isIP( $name )
411                 || strpos( $name, '/' ) !== false
412                 || strlen( $name ) > $wgMaxNameChars
413                 || $name != $wgContLang->ucfirst( $name ) )
414                         return false;
415
416                 // Ensure that the name can't be misresolved as a different title,
417                 // such as with extra namespace keys at the start.
418                 $parsed = Title::newFromText( $name );
419                 if( is_null( $parsed )
420                         || $parsed->getNamespace()
421                         || strcmp( $name, $parsed->getPrefixedText() ) )
422                         return false;
423                 
424                 // Check an additional blacklist of troublemaker characters.
425                 // Should these be merged into the title char list?
426                 $unicodeBlacklist = '/[' .
427                         '\x{0080}-\x{009f}' . # iso-8859-1 control chars
428                         '\x{00a0}' .          # non-breaking space
429                         '\x{2000}-\x{200f}' . # various whitespace
430                         '\x{2028}-\x{202f}' . # breaks and control chars
431                         '\x{3000}' .          # ideographic space
432                         '\x{e000}-\x{f8ff}' . # private use
433                         ']/u';
434                 if( preg_match( $unicodeBlacklist, $name ) ) {
435                         return false;
436                 }
437                 
438                 return true;
439         }
440         
441         /**
442          * Usernames which fail to pass this function will be blocked
443          * from user login and new account registrations, but may be used
444          * internally by batch processes.
445          *
446          * If an account already exists in this form, login will be blocked
447          * by a failure to pass this function.
448          *
449          * @param string $name
450          * @return bool
451          */
452         static function isUsableName( $name ) {
453                 global $wgReservedUsernames;
454                 return
455                         // Must be a valid username, obviously ;)
456                         self::isValidUserName( $name ) &&
457                         
458                         // Certain names may be reserved for batch processes.
459                         !in_array( $name, $wgReservedUsernames );
460         }
461         
462         /**
463          * Usernames which fail to pass this function will be blocked
464          * from new account registrations, but may be used internally
465          * either by batch processes or by user accounts which have
466          * already been created.
467          *
468          * Additional character blacklisting may be added here
469          * rather than in isValidUserName() to avoid disrupting
470          * existing accounts.
471          *
472          * @param string $name
473          * @return bool
474          */
475         static function isCreatableName( $name ) {
476                 return
477                         self::isUsableName( $name ) &&
478                         
479                         // Registration-time character blacklisting...
480                         strpos( $name, '@' ) === false;
481         }
482
483         /**
484          * Is the input a valid password for this user?
485          *
486          * @param string $password Desired password
487          * @return bool
488          */
489         function isValidPassword( $password ) {
490                 global $wgMinimalPasswordLength, $wgContLang;
491
492                 $result = null;
493                 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
494                         return $result;
495                 if( $result === false )
496                         return false;
497                         
498                 // Password needs to be long enough, and can't be the same as the username
499                 return strlen( $password ) >= $wgMinimalPasswordLength
500                         && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName );
501         }
502
503         /**
504          * Does a string look like an email address?
505          *
506          * There used to be a regular expression here, it got removed because it
507          * rejected valid addresses. Actually just check if there is '@' somewhere
508          * in the given address.
509          *
510          * @todo Check for RFC 2822 compilance (bug 959)
511          *
512          * @param string $addr email address
513          * @return bool
514          */
515         public static function isValidEmailAddr( $addr ) {
516                 return strpos( $addr, '@' ) !== false;
517         }
518
519         /**
520          * Given unvalidated user input, return a canonical username, or false if 
521          * the username is invalid.
522          * @param string $name
523          * @param mixed $validate Type of validation to use:
524          *                         false        No validation
525          *                         'valid'      Valid for batch processes
526          *                         'usable'     Valid for batch processes and login
527          *                         'creatable'  Valid for batch processes, login and account creation
528          */
529         static function getCanonicalName( $name, $validate = 'valid' ) {
530                 # Force usernames to capital
531                 global $wgContLang;
532                 $name = $wgContLang->ucfirst( $name );
533
534                 # Reject names containing '#'; these will be cleaned up
535                 # with title normalisation, but then it's too late to
536                 # check elsewhere
537                 if( strpos( $name, '#' ) !== false )
538                         return false;
539
540                 # Clean up name according to title rules
541                 $t = Title::newFromText( $name );
542                 if( is_null( $t ) ) {
543                         return false;
544                 }
545
546                 # Reject various classes of invalid names
547                 $name = $t->getText();
548                 global $wgAuth;
549                 $name = $wgAuth->getCanonicalName( $t->getText() );
550
551                 switch ( $validate ) {
552                         case false:
553                                 break;
554                         case 'valid':
555                                 if ( !User::isValidUserName( $name ) ) {
556                                         $name = false;
557                                 }
558                                 break;
559                         case 'usable':
560                                 if ( !User::isUsableName( $name ) ) {
561                                         $name = false;
562                                 }
563                                 break;
564                         case 'creatable':
565                                 if ( !User::isCreatableName( $name ) ) {
566                                         $name = false;
567                                 }
568                                 break;
569                         default:
570                                 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__ );
571                 }
572                 return $name;
573         }
574
575         /**
576          * Count the number of edits of a user
577          *
578          * It should not be static and some day should be merged as proper member function / deprecated -- domas
579          * 
580          * @param int $uid The user ID to check
581          * @return int
582          * @static
583          */
584         static function edits( $uid ) {
585                 wfProfileIn( __METHOD__ );
586                 $dbr = wfGetDB( DB_SLAVE );
587                 // check if the user_editcount field has been initialized
588                 $field = $dbr->selectField(
589                         'user', 'user_editcount',
590                         array( 'user_id' => $uid ),
591                         __METHOD__
592                 );
593
594                 if( $field === null ) { // it has not been initialized. do so.
595                         $dbw = wfGetDb( DB_MASTER );
596                         $count = $dbr->selectField(
597                                 'revision', 'count(*)',
598                                 array( 'rev_user' => $uid ),
599                                 __METHOD__
600                         );
601                         $dbw->update(
602                                 'user',
603                                 array( 'user_editcount' => $count ),
604                                 array( 'user_id' => $uid ),
605                                 __METHOD__
606                         );
607                 } else {
608                         $count = $field;
609                 }
610                 wfProfileOut( __METHOD__ );
611                 return $count;
612         }
613
614         /**
615          * Return a random password. Sourced from mt_rand, so it's not particularly secure.
616          * @todo hash random numbers to improve security, like generateToken()
617          *
618          * @return string
619          * @static
620          */
621         static function randomPassword() {
622                 global $wgMinimalPasswordLength;
623                 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
624                 $l = strlen( $pwchars ) - 1;
625
626                 $pwlength = max( 7, $wgMinimalPasswordLength );
627                 $digit = mt_rand(0, $pwlength - 1);
628                 $np = '';
629                 for ( $i = 0; $i < $pwlength; $i++ ) {
630                         $np .= $i == $digit ? chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
631                 }
632                 return $np;
633         }
634
635         /**
636          * Set cached properties to default. Note: this no longer clears 
637          * uncached lazy-initialised properties. The constructor does that instead.
638          *
639          * @private
640          */
641         function loadDefaults( $name = false ) {
642                 wfProfileIn( __METHOD__ );
643
644                 global $wgCookiePrefix;
645
646                 $this->mId = 0;
647                 $this->mName = $name;
648                 $this->mRealName = '';
649                 $this->mPassword = $this->mNewpassword = '';
650                 $this->mNewpassTime = null;
651                 $this->mEmail = '';
652                 $this->mOptions = null; # Defer init
653
654                 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
655                         $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
656                 } else {
657                         $this->mTouched = '0'; # Allow any pages to be cached
658                 }
659
660                 $this->setToken(); # Random
661                 $this->mEmailAuthenticated = null;
662                 $this->mEmailToken = '';
663                 $this->mEmailTokenExpires = null;
664                 $this->mRegistration = wfTimestamp( TS_MW );
665                 $this->mGroups = array();
666
667                 wfProfileOut( __METHOD__ );
668         }
669         
670         /**
671          * Initialise php session
672          * @deprecated use wfSetupSession()
673          */
674         function SetupSession() {
675                 wfSetupSession();
676         }
677
678         /**
679          * Load user data from the session or login cookie. If there are no valid
680          * credentials, initialises the user as an anon.
681          * @return true if the user is logged in, false otherwise
682          */
683         private function loadFromSession() {
684                 global $wgMemc, $wgCookiePrefix;
685
686                 if ( isset( $_SESSION['wsUserID'] ) ) {
687                         if ( 0 != $_SESSION['wsUserID'] ) {
688                                 $sId = $_SESSION['wsUserID'];
689                         } else {
690                                 $this->loadDefaults();
691                                 return false;
692                         }
693                 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
694                         $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
695                         $_SESSION['wsUserID'] = $sId;
696                 } else {
697                         $this->loadDefaults();
698                         return false;
699                 }
700                 if ( isset( $_SESSION['wsUserName'] ) ) {
701                         $sName = $_SESSION['wsUserName'];
702                 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
703                         $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
704                         $_SESSION['wsUserName'] = $sName;
705                 } else {
706                         $this->loadDefaults();
707                         return false;
708                 }
709
710                 $passwordCorrect = FALSE;
711                 $this->mId = $sId;
712                 if ( !$this->loadFromId() ) {
713                         # Not a valid ID, loadFromId has switched the object to anon for us
714                         return false;
715                 }
716                 
717                 if ( isset( $_SESSION['wsToken'] ) ) {
718                         $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
719                         $from = 'session';
720                 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
721                         $passwordCorrect = $this->mToken == $_COOKIE["{$wgCookiePrefix}Token"];
722                         $from = 'cookie';
723                 } else {
724                         # No session or persistent login cookie
725                         $this->loadDefaults();
726                         return false;
727                 }
728
729                 if ( ( $sName == $this->mName ) && $passwordCorrect ) {
730                         $_SESSION['wsToken'] = $this->mToken;
731                         wfDebug( "Logged in from $from\n" );
732                         return true;
733                 } else {
734                         # Invalid credentials
735                         wfDebug( "Can't log in from $from, invalid credentials\n" );
736                         $this->loadDefaults();
737                         return false;
738                 }
739         }
740         
741         /**
742          * Load user and user_group data from the database
743          * $this->mId must be set, this is how the user is identified.
744          * 
745          * @return true if the user exists, false if the user is anonymous
746          * @private
747          */
748         function loadFromDatabase() {
749                 # Paranoia
750                 $this->mId = intval( $this->mId );
751
752                 /** Anonymous user */
753                 if( !$this->mId ) {
754                         $this->loadDefaults();
755                         return false;
756                 }
757
758                 $dbr = wfGetDB( DB_MASTER );
759                 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
760
761                 if ( $s !== false ) {
762                         # Initialise user table data
763                         $this->mName = $s->user_name;
764                         $this->mRealName = $s->user_real_name;
765                         $this->mPassword = $s->user_password;
766                         $this->mNewpassword = $s->user_newpassword;
767                         $this->mNewpassTime = wfTimestampOrNull( TS_MW, $s->user_newpass_time );
768                         $this->mEmail = $s->user_email;
769                         $this->decodeOptions( $s->user_options );
770                         $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
771                         $this->mToken = $s->user_token;
772                         $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $s->user_email_authenticated );
773                         $this->mEmailToken = $s->user_email_token;
774                         $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $s->user_email_token_expires );
775                         $this->mRegistration = wfTimestampOrNull( TS_MW, $s->user_registration );
776                         $this->mEditCount = $s->user_editcount; 
777                         $this->getEditCount(); // revalidation for nulls
778
779                         # Load group data
780                         $res = $dbr->select( 'user_groups',
781                                 array( 'ug_group' ),
782                                 array( 'ug_user' => $this->mId ),
783                                 __METHOD__ );
784                         $this->mGroups = array();
785                         while( $row = $dbr->fetchObject( $res ) ) {
786                                 $this->mGroups[] = $row->ug_group;
787                         }
788                         return true;
789                 } else {
790                         # Invalid user_id
791                         $this->mId = 0;
792                         $this->loadDefaults();
793                         return false;
794                 }
795         }
796
797         /**
798          * Clear various cached data stored in this object. 
799          * @param string $reloadFrom Reload user and user_groups table data from a 
800          *   given source. May be "name", "id", "defaults", "session" or false for 
801          *   no reload.
802          */
803         function clearInstanceCache( $reloadFrom = false ) {
804                 $this->mNewtalk = -1;
805                 $this->mDatePreference = null;
806                 $this->mBlockedby = -1; # Unset
807                 $this->mHash = false;
808                 $this->mSkin = null;
809                 $this->mRights = null;
810                 $this->mEffectiveGroups = null;
811
812                 if ( $reloadFrom ) {
813                         $this->mDataLoaded = false;
814                         $this->mFrom = $reloadFrom;
815                 }
816         }
817
818         /**
819          * Combine the language default options with any site-specific options
820          * and add the default language variants.
821          * Not really private cause it's called by Language class
822          * @return array
823          * @static
824          * @private
825          */
826         static function getDefaultOptions() {
827                 global $wgNamespacesToBeSearchedDefault;
828                 /**
829                  * Site defaults will override the global/language defaults
830                  */
831                 global $wgDefaultUserOptions, $wgContLang;
832                 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
833
834                 /**
835                  * default language setting
836                  */
837                 $variant = $wgContLang->getPreferredVariant( false );
838                 $defOpt['variant'] = $variant;
839                 $defOpt['language'] = $variant;
840
841                 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
842                         $defOpt['searchNs'.$nsnum] = $val;
843                 }
844                 return $defOpt;
845         }
846
847         /**
848          * Get a given default option value.
849          *
850          * @param string $opt
851          * @return string
852          * @static
853          * @public
854          */
855         function getDefaultOption( $opt ) {
856                 $defOpts = User::getDefaultOptions();
857                 if( isset( $defOpts[$opt] ) ) {
858                         return $defOpts[$opt];
859                 } else {
860                         return '';
861                 }
862         }
863
864         /**
865          * Get a list of user toggle names
866          * @return array
867          */
868         static function getToggles() {
869                 global $wgContLang;
870                 $extraToggles = array();
871                 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
872                 return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
873         }
874
875
876         /**
877          * Get blocking information
878          * @private
879          * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
880          *  non-critical checks are done against slaves. Check when actually saving should be done against
881          *  master.
882          */
883         function getBlockedStatus( $bFromSlave = true ) {
884                 global $wgEnableSorbs, $wgProxyWhitelist;
885
886                 if ( -1 != $this->mBlockedby ) {
887                         wfDebug( "User::getBlockedStatus: already loaded.\n" );
888                         return;
889                 }
890
891                 wfProfileIn( __METHOD__ );
892                 wfDebug( __METHOD__.": checking...\n" );
893
894                 $this->mBlockedby = 0; 
895                 $this->mHideName = 0;
896                 $ip = wfGetIP();
897
898                 if ($this->isAllowed( 'ipblock-exempt' ) ) {
899                         # Exempt from all types of IP-block
900                         $ip = '';
901                 }
902
903                 # User/IP blocking
904                 $this->mBlock = new Block();
905                 $this->mBlock->fromMaster( !$bFromSlave );
906                 if ( $this->mBlock->load( $ip , $this->mId ) ) {
907                         wfDebug( __METHOD__.": Found block.\n" );
908                         $this->mBlockedby = $this->mBlock->mBy;
909                         $this->mBlockreason = $this->mBlock->mReason;
910                         $this->mHideName = $this->mBlock->mHideName;
911                         if ( $this->isLoggedIn() ) {
912                                 $this->spreadBlock();
913                         }
914                 } else {
915                         $this->mBlock = null;
916                         wfDebug( __METHOD__.": No block.\n" );
917                 }
918
919                 # Proxy blocking
920                 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
921
922                         # Local list
923                         if ( wfIsLocallyBlockedProxy( $ip ) ) {
924                                 $this->mBlockedby = wfMsg( 'proxyblocker' );
925                                 $this->mBlockreason = wfMsg( 'proxyblockreason' );
926                         }
927
928                         # DNSBL
929                         if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
930                                 if ( $this->inSorbsBlacklist( $ip ) ) {
931                                         $this->mBlockedby = wfMsg( 'sorbs' );
932                                         $this->mBlockreason = wfMsg( 'sorbsreason' );
933                                 }
934                         }
935                 }
936
937                 # Extensions
938                 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
939
940                 wfProfileOut( __METHOD__ );
941         }
942
943         function inSorbsBlacklist( $ip ) {
944                 global $wgEnableSorbs, $wgSorbsUrl;
945
946                 return $wgEnableSorbs &&
947                         $this->inDnsBlacklist( $ip, $wgSorbsUrl );
948         }
949
950         function inDnsBlacklist( $ip, $base ) {
951                 wfProfileIn( __METHOD__ );
952
953                 $found = false;
954                 $host = '';
955
956                 $m = array();
957                 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
958                         # Make hostname
959                         for ( $i=4; $i>=1; $i-- ) {
960                                 $host .= $m[$i] . '.';
961                         }
962                         $host .= $base;
963
964                         # Send query
965                         $ipList = gethostbynamel( $host );
966
967                         if ( $ipList ) {
968                                 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
969                                 $found = true;
970                         } else {
971                                 wfDebug( "Requested $host, not found in $base.\n" );
972                         }
973                 }
974
975                 wfProfileOut( __METHOD__ );
976                 return $found;
977         }
978
979         /**
980          * Is this user subject to rate limiting?
981          *
982          * @return bool
983          */
984         public function isPingLimitable() {
985                 global $wgRateLimitsExcludedGroups;
986                 return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) == array();
987         }
988
989         /**
990          * Primitive rate limits: enforce maximum actions per time period
991          * to put a brake on flooding.
992          *
993          * Note: when using a shared cache like memcached, IP-address
994          * last-hit counters will be shared across wikis.
995          *
996          * @return bool true if a rate limiter was tripped
997          * @public
998          */
999         function pingLimiter( $action='edit' ) {
1000
1001                 # Call the 'PingLimiter' hook
1002                 $result = false;
1003                 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1004                         return $result;
1005                 }
1006
1007                 global $wgRateLimits, $wgRateLimitsExcludedGroups;
1008                 if( !isset( $wgRateLimits[$action] ) ) {
1009                         return false;
1010                 }
1011
1012                 # Some groups shouldn't trigger the ping limiter, ever
1013                 if( !$this->isPingLimitable() )
1014                         return false;
1015
1016                 global $wgMemc, $wgRateLimitLog;
1017                 wfProfileIn( __METHOD__ );
1018
1019                 $limits = $wgRateLimits[$action];
1020                 $keys = array();
1021                 $id = $this->getId();
1022                 $ip = wfGetIP();
1023
1024                 if( isset( $limits['anon'] ) && $id == 0 ) {
1025                         $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1026                 }
1027
1028                 if( isset( $limits['user'] ) && $id != 0 ) {
1029                         $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
1030                 }
1031                 if( $this->isNewbie() ) {
1032                         if( isset( $limits['newbie'] ) && $id != 0 ) {
1033                                 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1034                         }
1035                         if( isset( $limits['ip'] ) ) {
1036                                 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1037                         }
1038                         $matches = array();
1039                         if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1040                                 $subnet = $matches[1];
1041                                 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1042                         }
1043                 }
1044
1045                 $triggered = false;
1046                 foreach( $keys as $key => $limit ) {
1047                         list( $max, $period ) = $limit;
1048                         $summary = "(limit $max in {$period}s)";
1049                         $count = $wgMemc->get( $key );
1050                         if( $count ) {
1051                                 if( $count > $max ) {
1052                                         wfDebug( __METHOD__.": tripped! $key at $count $summary\n" );
1053                                         if( $wgRateLimitLog ) {
1054                                                 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1055                                         }
1056                                         $triggered = true;
1057                                 } else {
1058                                         wfDebug( __METHOD__.": ok. $key at $count $summary\n" );
1059                                 }
1060                         } else {
1061                                 wfDebug( __METHOD__.": adding record for $key $summary\n" );
1062                                 $wgMemc->add( $key, 1, intval( $period ) );
1063                         }
1064                         $wgMemc->incr( $key );
1065                 }
1066
1067                 wfProfileOut( __METHOD__ );
1068                 return $triggered;
1069         }
1070
1071         /**
1072          * Check if user is blocked
1073          * @return bool True if blocked, false otherwise
1074          */
1075         function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1076                 wfDebug( "User::isBlocked: enter\n" );
1077                 $this->getBlockedStatus( $bFromSlave );
1078                 return $this->mBlockedby !== 0;
1079         }
1080
1081         /**
1082          * Check if user is blocked from editing a particular article
1083          */
1084         function isBlockedFrom( $title, $bFromSlave = false ) {
1085                 global $wgBlockAllowsUTEdit;
1086                 wfProfileIn( __METHOD__ );
1087                 wfDebug( __METHOD__.": enter\n" );
1088
1089                 wfDebug( __METHOD__.": asking isBlocked()\n" );
1090                 $blocked = $this->isBlocked( $bFromSlave );
1091                 # If a user's name is suppressed, they cannot make edits anywhere
1092                 if ( !$this->mHideName && $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1093                   $title->getNamespace() == NS_USER_TALK ) {
1094                         $blocked = false;
1095                         wfDebug( __METHOD__.": self-talk page, ignoring any blocks\n" );
1096                 }
1097                 wfProfileOut( __METHOD__ );
1098                 return $blocked;
1099         }
1100
1101         /**
1102          * Get name of blocker
1103          * @return string name of blocker
1104          */
1105         function blockedBy() {
1106                 $this->getBlockedStatus();
1107                 return $this->mBlockedby;
1108         }
1109
1110         /**
1111          * Get blocking reason
1112          * @return string Blocking reason
1113          */
1114         function blockedFor() {
1115                 $this->getBlockedStatus();
1116                 return $this->mBlockreason;
1117         }
1118
1119         /**
1120          * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1121          */
1122         function getID() {
1123                 if( $this->mId === null and $this->mName !== null
1124                 and User::isIP( $this->mName ) ) {
1125                         // Special case, we know the user is anonymous
1126                         return 0;
1127                 } elseif( $this->mId === null ) {
1128                         // Don't load if this was initialized from an ID
1129                         $this->load();
1130                 }
1131                 return $this->mId;
1132         }
1133
1134         /**
1135          * Set the user and reload all fields according to that ID
1136          * @deprecated use User::newFromId()
1137          */
1138         function setID( $v ) {
1139                 $this->mId = $v;
1140                 $this->clearInstanceCache( 'id' );
1141         }
1142
1143         /**
1144          * Get the user name, or the IP for anons
1145          */
1146         function getName() {
1147                 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1148                         # Special case optimisation
1149                         return $this->mName;
1150                 } else {
1151                         $this->load();
1152                         if ( $this->mName === false ) {
1153                                 # Clean up IPs
1154                                 $this->mName = IP::sanitizeIP( wfGetIP() );
1155                         }
1156                         return $this->mName;
1157                 }
1158         }
1159
1160         /**
1161          * Set the user name. 
1162          *
1163          * This does not reload fields from the database according to the given 
1164          * name. Rather, it is used to create a temporary "nonexistent user" for
1165          * later addition to the database. It can also be used to set the IP 
1166          * address for an anonymous user to something other than the current 
1167          * remote IP.
1168          *
1169          * User::newFromName() has rougly the same function, when the named user
1170          * does not exist.
1171          */
1172         function setName( $str ) {
1173                 $this->load();
1174                 $this->mName = $str;
1175         }
1176
1177         /**
1178          * Return the title dbkey form of the name, for eg user pages.
1179          * @return string
1180          * @public
1181          */
1182         function getTitleKey() {
1183                 return str_replace( ' ', '_', $this->getName() );
1184         }
1185
1186         function getNewtalk() {
1187                 $this->load();
1188
1189                 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1190                 if( $this->mNewtalk === -1 ) {
1191                         $this->mNewtalk = false; # reset talk page status
1192
1193                         # Check memcached separately for anons, who have no
1194                         # entire User object stored in there.
1195                         if( !$this->mId ) {
1196                                 global $wgMemc;
1197                                 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1198                                 $newtalk = $wgMemc->get( $key );
1199                                 if( $newtalk != "" ) {
1200                                         $this->mNewtalk = (bool)$newtalk;
1201                                 } else {
1202                                         $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
1203                                         $wgMemc->set( $key, (int)$this->mNewtalk, time() + 1800 );
1204                                 }
1205                         } else {
1206                                 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1207                         }
1208                 }
1209
1210                 return (bool)$this->mNewtalk;
1211         }
1212
1213         /**
1214          * Return the talk page(s) this user has new messages on.
1215          */
1216         function getNewMessageLinks() {
1217                 $talks = array();
1218                 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1219                         return $talks;
1220
1221                 if (!$this->getNewtalk())
1222                         return array();
1223                 $up = $this->getUserPage();
1224                 $utp = $up->getTalkPage();
1225                 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1226         }
1227
1228                 
1229         /**
1230          * Perform a user_newtalk check on current slaves; if the memcached data
1231          * is funky we don't want newtalk state to get stuck on save, as that's
1232          * damn annoying.
1233          *
1234          * @param string $field
1235          * @param mixed $id
1236          * @return bool
1237          * @private
1238          */
1239         function checkNewtalk( $field, $id ) {
1240                 $dbr = wfGetDB( DB_SLAVE );
1241                 $ok = $dbr->selectField( 'user_newtalk', $field,
1242                         array( $field => $id ), __METHOD__ );
1243                 return $ok !== false;
1244         }
1245
1246         /**
1247          * Add or update the
1248          * @param string $field
1249          * @param mixed $id
1250          * @private
1251          */
1252         function updateNewtalk( $field, $id ) {
1253                 if( $this->checkNewtalk( $field, $id ) ) {
1254                         wfDebug( __METHOD__." already set ($field, $id), ignoring\n" );
1255                         return false;
1256                 }
1257                 $dbw = wfGetDB( DB_MASTER );
1258                 $dbw->insert( 'user_newtalk',
1259                         array( $field => $id ),
1260                         __METHOD__,
1261                         'IGNORE' );
1262                 wfDebug( __METHOD__.": set on ($field, $id)\n" );
1263                 return true;
1264         }
1265
1266         /**
1267          * Clear the new messages flag for the given user
1268          * @param string $field
1269          * @param mixed $id
1270          * @private
1271          */
1272         function deleteNewtalk( $field, $id ) {
1273                 if( !$this->checkNewtalk( $field, $id ) ) {
1274                         wfDebug( __METHOD__.": already gone ($field, $id), ignoring\n" );
1275                         return false;
1276                 }
1277                 $dbw = wfGetDB( DB_MASTER );
1278                 $dbw->delete( 'user_newtalk',
1279                         array( $field => $id ),
1280                         __METHOD__ );
1281                 wfDebug( __METHOD__.": killed on ($field, $id)\n" );
1282                 return true;
1283         }
1284
1285         /**
1286          * Update the 'You have new messages!' status.
1287          * @param bool $val
1288          */
1289         function setNewtalk( $val ) {
1290                 if( wfReadOnly() ) {
1291                         return;
1292                 }
1293
1294                 $this->load();
1295                 $this->mNewtalk = $val;
1296
1297                 if( $this->isAnon() ) {
1298                         $field = 'user_ip';
1299                         $id = $this->getName();
1300                 } else {
1301                         $field = 'user_id';
1302                         $id = $this->getId();
1303                 }
1304
1305                 if( $val ) {
1306                         $changed = $this->updateNewtalk( $field, $id );
1307                 } else {
1308                         $changed = $this->deleteNewtalk( $field, $id );
1309                 }
1310
1311                 if( $changed ) {
1312                         if( $this->isAnon() ) {
1313                                 // Anons have a separate memcached space, since
1314                                 // user records aren't kept for them.
1315                                 global $wgMemc;
1316                                 $key = wfMemcKey( 'newtalk', 'ip', $val );
1317                                 $wgMemc->set( $key, $val ? 1 : 0 );
1318                         } else {
1319                                 if( $val ) {
1320                                         // Make sure the user page is watched, so a notification
1321                                         // will be sent out if enabled.
1322                                         $this->addWatch( $this->getTalkPage() );
1323                                 }
1324                         }
1325                         $this->invalidateCache();
1326                 }
1327         }
1328         
1329         /**
1330          * Generate a current or new-future timestamp to be stored in the
1331          * user_touched field when we update things.
1332          */
1333         private static function newTouchedTimestamp() {
1334                 global $wgClockSkewFudge;
1335                 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1336         }
1337         
1338         /**
1339          * Clear user data from memcached.
1340          * Use after applying fun updates to the database; caller's
1341          * responsibility to update user_touched if appropriate.
1342          *
1343          * Called implicitly from invalidateCache() and saveSettings().
1344          */
1345         private function clearSharedCache() {
1346                 if( $this->mId ) {
1347                         global $wgMemc;
1348                         $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1349                 }
1350         }
1351
1352         /**
1353          * Immediately touch the user data cache for this account.
1354          * Updates user_touched field, and removes account data from memcached
1355          * for reload on the next hit.
1356          */
1357         function invalidateCache() {
1358                 $this->load();
1359                 if( $this->mId ) {
1360                         $this->mTouched = self::newTouchedTimestamp();
1361                         
1362                         $dbw = wfGetDB( DB_MASTER );
1363                         $dbw->update( 'user',
1364                                 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1365                                 array( 'user_id' => $this->mId ),
1366                                 __METHOD__ );
1367                         
1368                         $this->clearSharedCache();
1369                 }
1370         }
1371
1372         function validateCache( $timestamp ) {
1373                 $this->load();
1374                 return ($timestamp >= $this->mTouched);
1375         }
1376
1377         /**
1378          * Encrypt a password.
1379          * It can eventually salt a password.
1380          * @see User::addSalt()
1381          * @param string $p clear Password.
1382          * @return string Encrypted password.
1383          */
1384         function encryptPassword( $p ) {
1385                 $this->load();
1386                 return wfEncryptPassword( $this->mId, $p );
1387         }
1388
1389         /**
1390          * Set the password and reset the random token
1391          * Calls through to authentication plugin if necessary;
1392          * will have no effect if the auth plugin refuses to
1393          * pass the change through or if the legal password
1394          * checks fail.
1395          *
1396          * As a special case, setting the password to null
1397          * wipes it, so the account cannot be logged in until
1398          * a new password is set, for instance via e-mail.
1399          *
1400          * @param string $str
1401          * @throws PasswordError on failure
1402          */
1403         function setPassword( $str ) {
1404                 global $wgAuth;
1405                 
1406                 if( $str !== null ) {
1407                         if( !$wgAuth->allowPasswordChange() ) {
1408                                 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1409                         }
1410                 
1411                         if( !$this->isValidPassword( $str ) ) {
1412                                 global $wgMinimalPasswordLength;
1413                                 throw new PasswordError( wfMsg( 'passwordtooshort',
1414                                         $wgMinimalPasswordLength ) );
1415                         }
1416                 }
1417
1418                 if( !$wgAuth->setPassword( $this, $str ) ) {
1419                         throw new PasswordError( wfMsg( 'externaldberror' ) );
1420                 }
1421                 
1422                 $this->setInternalPassword( $str );
1423
1424                 return true;
1425         }
1426
1427         /**
1428          * Set the password and reset the random token no matter
1429          * what.
1430          *
1431          * @param string $str
1432          */
1433         function setInternalPassword( $str ) {
1434                 $this->load();
1435                 $this->setToken();
1436                 
1437                 if( $str === null ) {
1438                         // Save an invalid hash...
1439                         $this->mPassword = '';
1440                 } else {
1441                         $this->mPassword = $this->encryptPassword( $str );
1442                 }
1443                 $this->mNewpassword = '';
1444                 $this->mNewpassTime = null;
1445         }
1446         /**
1447          * Set the random token (used for persistent authentication)
1448          * Called from loadDefaults() among other places.
1449          * @private
1450          */
1451         function setToken( $token = false ) {
1452                 global $wgSecretKey, $wgProxyKey;
1453                 $this->load();
1454                 if ( !$token ) {
1455                         if ( $wgSecretKey ) {
1456                                 $key = $wgSecretKey;
1457                         } elseif ( $wgProxyKey ) {
1458                                 $key = $wgProxyKey;
1459                         } else {
1460                                 $key = microtime();
1461                         }
1462                         $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1463                 } else {
1464                         $this->mToken = $token;
1465                 }
1466         }
1467
1468         function setCookiePassword( $str ) {
1469                 $this->load();
1470                 $this->mCookiePassword = md5( $str );
1471         }
1472
1473         /**
1474          * Set the password for a password reminder or new account email
1475          * Sets the user_newpass_time field if $throttle is true
1476          */
1477         function setNewpassword( $str, $throttle = true ) {
1478                 $this->load();
1479                 $this->mNewpassword = $this->encryptPassword( $str );
1480                 if ( $throttle ) {
1481                         $this->mNewpassTime = wfTimestampNow();
1482                 }
1483         }
1484
1485         /**
1486          * Returns true if a password reminder email has already been sent within
1487          * the last $wgPasswordReminderResendTime hours
1488          */
1489         function isPasswordReminderThrottled() {
1490                 global $wgPasswordReminderResendTime;
1491                 $this->load();
1492                 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1493                         return false;
1494                 }
1495                 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1496                 return time() < $expiry;
1497         }
1498         
1499         function getEmail() {
1500                 $this->load();
1501                 return $this->mEmail;
1502         }
1503
1504         function getEmailAuthenticationTimestamp() {
1505                 $this->load();
1506                 return $this->mEmailAuthenticated;
1507         }
1508
1509         function setEmail( $str ) {
1510                 $this->load();
1511                 $this->mEmail = $str;
1512         }
1513
1514         function getRealName() {
1515                 $this->load();
1516                 return $this->mRealName;
1517         }
1518
1519         function setRealName( $str ) {
1520                 $this->load();
1521                 $this->mRealName = $str;
1522         }
1523
1524         /**
1525          * @param string $oname The option to check
1526          * @param string $defaultOverride A default value returned if the option does not exist
1527          * @return string
1528          */
1529         function getOption( $oname, $defaultOverride = '' ) {
1530                 $this->load();
1531
1532                 if ( is_null( $this->mOptions ) ) {
1533                         if($defaultOverride != '') {
1534                                 return $defaultOverride;
1535                         }
1536                         $this->mOptions = User::getDefaultOptions();
1537                 }
1538
1539                 if ( array_key_exists( $oname, $this->mOptions ) ) {
1540                         return trim( $this->mOptions[$oname] );
1541                 } else {
1542                         return $defaultOverride;
1543                 }
1544         }
1545
1546         /**
1547          * Get the user's date preference, including some important migration for 
1548          * old user rows.
1549          */
1550         function getDatePreference() {
1551                 if ( is_null( $this->mDatePreference ) ) {
1552                         global $wgLang;
1553                         $value = $this->getOption( 'date' );
1554                         $map = $wgLang->getDatePreferenceMigrationMap();
1555                         if ( isset( $map[$value] ) ) {
1556                                 $value = $map[$value];
1557                         }
1558                         $this->mDatePreference = $value;
1559                 }
1560                 return $this->mDatePreference;
1561         }
1562
1563         /**
1564          * @param string $oname The option to check
1565          * @return bool False if the option is not selected, true if it is
1566          */
1567         function getBoolOption( $oname ) {
1568                 return (bool)$this->getOption( $oname );
1569         }
1570         
1571         /**
1572          * Get an option as an integer value from the source string.
1573          * @param string $oname The option to check
1574          * @param int $default Optional value to return if option is unset/blank.
1575          * @return int
1576          */
1577         function getIntOption( $oname, $default=0 ) {
1578                 $val = $this->getOption( $oname );
1579                 if( $val == '' ) {
1580                         $val = $default;
1581                 }
1582                 return intval( $val );
1583         }
1584
1585         function setOption( $oname, $val ) {
1586                 $this->load();
1587                 if ( is_null( $this->mOptions ) ) {
1588                         $this->mOptions = User::getDefaultOptions();
1589                 }
1590                 if ( $oname == 'skin' ) {
1591                         # Clear cached skin, so the new one displays immediately in Special:Preferences
1592                         unset( $this->mSkin );
1593                 }
1594                 // Filter out any newlines that may have passed through input validation.
1595                 // Newlines are used to separate items in the options blob.
1596                 $val = str_replace( "\r\n", "\n", $val );
1597                 $val = str_replace( "\r", "\n", $val );
1598                 $val = str_replace( "\n", " ", $val );
1599                 $this->mOptions[$oname] = $val;
1600         }
1601
1602         function getRights() {
1603                 if ( is_null( $this->mRights ) ) {
1604                         $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
1605                         wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
1606                 }
1607                 return $this->mRights;
1608         }
1609
1610         /**
1611          * Get the list of explicit group memberships this user has.
1612          * The implicit * and user groups are not included.
1613          * @return array of strings
1614          */
1615         function getGroups() {
1616                 $this->load();
1617                 return $this->mGroups;
1618         }
1619
1620         /**
1621          * Get the list of implicit group memberships this user has.
1622          * This includes all explicit groups, plus 'user' if logged in
1623          * and '*' for all accounts.
1624          * @param boolean $recache Don't use the cache
1625          * @return array of strings
1626          */
1627         function getEffectiveGroups( $recache = false ) {
1628                 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
1629                         $this->load();
1630                         $this->mEffectiveGroups = $this->mGroups;
1631                         $this->mEffectiveGroups[] = '*';
1632                         if( $this->mId ) {
1633                                 $this->mEffectiveGroups[] = 'user';
1634                                 
1635                                 global $wgAutoConfirmAge, $wgAutoConfirmCount;
1636
1637                                 $accountAge = time() - wfTimestampOrNull( TS_UNIX, $this->mRegistration );
1638                                 if( $accountAge >= $wgAutoConfirmAge && $this->getEditCount() >= $wgAutoConfirmCount ) {
1639                                         $this->mEffectiveGroups[] = 'autoconfirmed';
1640                                 }
1641                                 # Implicit group for users whose email addresses are confirmed
1642                                 global $wgEmailAuthentication;
1643                                 if( self::isValidEmailAddr( $this->mEmail ) ) {
1644                                         if( $wgEmailAuthentication ) {
1645                                                 if( $this->mEmailAuthenticated )
1646                                                         $this->mEffectiveGroups[] = 'emailconfirmed';
1647                                         } else {
1648                                                 $this->mEffectiveGroups[] = 'emailconfirmed';
1649                                         }
1650                                 }
1651                                 # Hook for additional groups
1652                                 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
1653                         }
1654                 }
1655                 return $this->mEffectiveGroups;
1656         }
1657         
1658         /* Return the edit count for the user. This is where User::edits should have been */
1659         function getEditCount() {
1660                 if ($this->mId) {
1661                         if ( !isset( $this->mEditCount ) ) {
1662                                 /* Populate the count, if it has not been populated yet */
1663                                 $this->mEditCount = User::edits($this->mId);
1664                         } 
1665                         return $this->mEditCount;
1666                 } else {
1667                         /* nil */
1668                         return null;
1669                 }
1670         }
1671         
1672         /**
1673          * Add the user to the given group.
1674          * This takes immediate effect.
1675          * @param string $group
1676          */
1677         function addGroup( $group ) {
1678                 $this->load();
1679                 $dbw = wfGetDB( DB_MASTER );
1680                 if( $this->getId() ) {
1681                         $dbw->insert( 'user_groups',
1682                                 array(
1683                                         'ug_user'  => $this->getID(),
1684                                         'ug_group' => $group,
1685                                 ),
1686                                 'User::addGroup',
1687                                 array( 'IGNORE' ) );
1688                 }
1689
1690                 $this->mGroups[] = $group;
1691                 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1692
1693                 $this->invalidateCache();
1694         }
1695
1696         /**
1697          * Remove the user from the given group.
1698          * This takes immediate effect.
1699          * @param string $group
1700          */
1701         function removeGroup( $group ) {
1702                 $this->load();
1703                 $dbw = wfGetDB( DB_MASTER );
1704                 $dbw->delete( 'user_groups',
1705                         array(
1706                                 'ug_user'  => $this->getID(),
1707                                 'ug_group' => $group,
1708                         ),
1709                         'User::removeGroup' );
1710
1711                 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
1712                 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1713
1714                 $this->invalidateCache();
1715         }
1716
1717
1718         /**
1719          * A more legible check for non-anonymousness.
1720          * Returns true if the user is not an anonymous visitor.
1721          *
1722          * @return bool
1723          */
1724         function isLoggedIn() {
1725                 if( $this->mId === null and $this->mName !== null ) {
1726                         // Special-case optimization
1727                         return !self::isIP( $this->mName );
1728                 }
1729                 return $this->getID() != 0;
1730         }
1731
1732         /**
1733          * A more legible check for anonymousness.
1734          * Returns true if the user is an anonymous visitor.
1735          *
1736          * @return bool
1737          */
1738         function isAnon() {
1739                 return !$this->isLoggedIn();
1740         }
1741
1742         /**
1743          * Whether the user is a bot
1744          * @deprecated
1745          */
1746         function isBot() {
1747                 return $this->isAllowed( 'bot' );
1748         }
1749
1750         /**
1751          * Check if user is allowed to access a feature / make an action
1752          * @param string $action Action to be checked
1753          * @return boolean True: action is allowed, False: action should not be allowed
1754          */
1755         function isAllowed($action='') {
1756                 if ( $action === '' )
1757                         // In the spirit of DWIM
1758                         return true;
1759
1760                 return in_array( $action, $this->getRights() );
1761         }
1762
1763         /**
1764          * Load a skin if it doesn't exist or return it
1765          * @todo FIXME : need to check the old failback system [AV]
1766          */
1767         function &getSkin() {
1768                 global $wgRequest;
1769                 if ( ! isset( $this->mSkin ) ) {
1770                         wfProfileIn( __METHOD__ );
1771
1772                         # get the user skin
1773                         $userSkin = $this->getOption( 'skin' );
1774                         $userSkin = $wgRequest->getVal('useskin', $userSkin);
1775
1776                         $this->mSkin =& Skin::newFromKey( $userSkin );
1777                         wfProfileOut( __METHOD__ );
1778                 }
1779                 return $this->mSkin;
1780         }
1781
1782         /**#@+
1783          * @param string $title Article title to look at
1784          */
1785
1786         /**
1787          * Check watched status of an article
1788          * @return bool True if article is watched
1789          */
1790         function isWatched( $title ) {
1791                 $wl = WatchedItem::fromUserTitle( $this, $title );
1792                 return $wl->isWatched();
1793         }
1794
1795         /**
1796          * Watch an article
1797          */
1798         function addWatch( $title ) {
1799                 $wl = WatchedItem::fromUserTitle( $this, $title );
1800                 $wl->addWatch();
1801                 $this->invalidateCache();
1802         }
1803
1804         /**
1805          * Stop watching an article
1806          */
1807         function removeWatch( $title ) {
1808                 $wl = WatchedItem::fromUserTitle( $this, $title );
1809                 $wl->removeWatch();
1810                 $this->invalidateCache();
1811         }
1812
1813         /**
1814          * Clear the user's notification timestamp for the given title.
1815          * If e-notif e-mails are on, they will receive notification mails on
1816          * the next change of the page if it's watched etc.
1817          */
1818         function clearNotification( &$title ) {
1819                 global $wgUser, $wgUseEnotif;
1820
1821                 # Do nothing if the database is locked to writes
1822                 if( wfReadOnly() ) {
1823                         return;
1824                 }
1825
1826                 if ($title->getNamespace() == NS_USER_TALK &&
1827                         $title->getText() == $this->getName() ) {
1828                         if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1829                                 return;
1830                         $this->setNewtalk( false );
1831                 }
1832
1833                 if( !$wgUseEnotif ) {
1834                         return;
1835                 }
1836
1837                 if( $this->isAnon() ) {
1838                         // Nothing else to do...
1839                         return;
1840                 }
1841
1842                 // Only update the timestamp if the page is being watched.
1843                 // The query to find out if it is watched is cached both in memcached and per-invocation,
1844                 // and when it does have to be executed, it can be on a slave
1845                 // If this is the user's newtalk page, we always update the timestamp
1846                 if ($title->getNamespace() == NS_USER_TALK &&
1847                         $title->getText() == $wgUser->getName())
1848                 {
1849                         $watched = true;
1850                 } elseif ( $this->getID() == $wgUser->getID() ) {
1851                         $watched = $title->userIsWatching();
1852                 } else {
1853                         $watched = true;
1854                 }
1855
1856                 // If the page is watched by the user (or may be watched), update the timestamp on any
1857                 // any matching rows
1858                 if ( $watched ) {
1859                         $dbw = wfGetDB( DB_MASTER );
1860                         $dbw->update( 'watchlist',
1861                                         array( /* SET */
1862                                                 'wl_notificationtimestamp' => NULL
1863                                         ), array( /* WHERE */
1864                                                 'wl_title' => $title->getDBkey(),
1865                                                 'wl_namespace' => $title->getNamespace(),
1866                                                 'wl_user' => $this->getID()
1867                                         ), 'User::clearLastVisited'
1868                         );
1869                 }
1870         }
1871
1872         /**#@-*/
1873
1874         /**
1875          * Resets all of the given user's page-change notification timestamps.
1876          * If e-notif e-mails are on, they will receive notification mails on
1877          * the next change of any watched page.
1878          *
1879          * @param int $currentUser user ID number
1880          * @public
1881          */
1882         function clearAllNotifications( $currentUser ) {
1883                 global $wgUseEnotif;
1884                 if ( !$wgUseEnotif ) {
1885                         $this->setNewtalk( false );
1886                         return;
1887                 }
1888                 if( $currentUser != 0 )  {
1889
1890                         $dbw = wfGetDB( DB_MASTER );
1891                         $dbw->update( 'watchlist',
1892                                 array( /* SET */
1893                                         'wl_notificationtimestamp' => NULL
1894                                 ), array( /* WHERE */
1895                                         'wl_user' => $currentUser
1896                                 ), 'UserMailer::clearAll'
1897                         );
1898
1899                 #       we also need to clear here the "you have new message" notification for the own user_talk page
1900                 #       This is cleared one page view later in Article::viewUpdates();
1901                 }
1902         }
1903
1904         /**
1905          * @private
1906          * @return string Encoding options
1907          */
1908         function encodeOptions() {
1909                 $this->load();
1910                 if ( is_null( $this->mOptions ) ) {
1911                         $this->mOptions = User::getDefaultOptions();
1912                 }
1913                 $a = array();
1914                 foreach ( $this->mOptions as $oname => $oval ) {
1915                         array_push( $a, $oname.'='.$oval );
1916                 }
1917                 $s = implode( "\n", $a );
1918                 return $s;
1919         }
1920
1921         /**
1922          * @private
1923          */
1924         function decodeOptions( $str ) {
1925                 $this->mOptions = array();
1926                 $a = explode( "\n", $str );
1927                 foreach ( $a as $s ) {
1928                         $m = array();
1929                         if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1930                                 $this->mOptions[$m[1]] = $m[2];
1931                         }
1932                 }
1933         }
1934
1935         function setCookies() {
1936                 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1937                 $this->load();
1938                 if ( 0 == $this->mId ) return;
1939                 $exp = time() + $wgCookieExpiration;
1940
1941                 $_SESSION['wsUserID'] = $this->mId;
1942                 setcookie( $wgCookiePrefix.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1943
1944                 $_SESSION['wsUserName'] = $this->getName();
1945                 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1946
1947                 $_SESSION['wsToken'] = $this->mToken;
1948                 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1949                         setcookie( $wgCookiePrefix.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1950                 } else {
1951                         setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1952                 }
1953         }
1954
1955         /**
1956          * Logout user
1957          * Clears the cookies and session, resets the instance cache
1958          */
1959         function logout() {
1960                 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1961                 $this->clearInstanceCache( 'defaults' );
1962
1963                 $_SESSION['wsUserID'] = 0;
1964
1965                 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1966                 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1967
1968                 # Remember when user logged out, to prevent seeing cached pages
1969                 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1970         }
1971
1972         /**
1973          * Save object settings into database
1974          * @todo Only rarely do all these fields need to be set!
1975          */
1976         function saveSettings() {
1977                 $this->load();
1978                 if ( wfReadOnly() ) { return; }
1979                 if ( 0 == $this->mId ) { return; }
1980                 
1981                 $this->mTouched = self::newTouchedTimestamp();
1982
1983                 $dbw = wfGetDB( DB_MASTER );
1984                 $dbw->update( 'user',
1985                         array( /* SET */
1986                                 'user_name' => $this->mName,
1987                                 'user_password' => $this->mPassword,
1988                                 'user_newpassword' => $this->mNewpassword,
1989                                 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
1990                                 'user_real_name' => $this->mRealName,
1991                                 'user_email' => $this->mEmail,
1992                                 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1993                                 'user_options' => $this->encodeOptions(),
1994                                 'user_touched' => $dbw->timestamp($this->mTouched),
1995                                 'user_token' => $this->mToken
1996                         ), array( /* WHERE */
1997                                 'user_id' => $this->mId
1998                         ), __METHOD__
1999                 );
2000                 $this->clearSharedCache();
2001         }
2002
2003
2004         /**
2005          * Checks if a user with the given name exists, returns the ID
2006          */
2007         function idForName() {
2008                 $s = trim( $this->getName() );
2009                 if ( 0 == strcmp( '', $s ) ) return 0;
2010
2011                 $dbr = wfGetDB( DB_SLAVE );
2012                 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2013                 if ( $id === false ) {
2014                         $id = 0;
2015                 }
2016                 return $id;
2017         }
2018
2019         /**
2020          * Add a user to the database, return the user object
2021          *
2022          * @param string $name The user's name
2023          * @param array $params Associative array of non-default parameters to save to the database:
2024          *     password             The user's password. Password logins will be disabled if this is omitted.
2025          *     newpassword          A temporary password mailed to the user
2026          *     email                The user's email address
2027          *     email_authenticated  The email authentication timestamp
2028          *     real_name            The user's real name
2029          *     options              An associative array of non-default options
2030          *     token                Random authentication token. Do not set.
2031          *     registration         Registration timestamp. Do not set.
2032          *
2033          * @return User object, or null if the username already exists
2034          */
2035         static function createNew( $name, $params = array() ) {
2036                 $user = new User;
2037                 $user->load();
2038                 if ( isset( $params['options'] ) ) {
2039                         $user->mOptions = $params['options'] + $user->mOptions;
2040                         unset( $params['options'] );
2041                 }
2042                 $dbw = wfGetDB( DB_MASTER );
2043                 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2044                 $fields = array(
2045                         'user_id' => $seqVal,
2046                         'user_name' => $name,
2047                         'user_password' => $user->mPassword,
2048                         'user_newpassword' => $user->mNewpassword,
2049                         'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ),
2050                         'user_email' => $user->mEmail,
2051                         'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2052                         'user_real_name' => $user->mRealName,
2053                         'user_options' => $user->encodeOptions(),
2054                         'user_token' => $user->mToken,
2055                         'user_registration' => $dbw->timestamp( $user->mRegistration ),
2056                         'user_editcount' => 0,
2057                 );
2058                 foreach ( $params as $name => $value ) {
2059                         $fields["user_$name"] = $value;
2060                 }
2061                 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2062                 if ( $dbw->affectedRows() ) {
2063                         $newUser = User::newFromId( $dbw->insertId() );
2064                 } else {
2065                         $newUser = null;
2066                 }
2067                 return $newUser;
2068         }
2069         
2070         /**
2071          * Add an existing user object to the database
2072          */
2073         function addToDatabase() {
2074                 $this->load();
2075                 $dbw = wfGetDB( DB_MASTER );
2076                 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2077                 $dbw->insert( 'user',
2078                         array(
2079                                 'user_id' => $seqVal,
2080                                 'user_name' => $this->mName,
2081                                 'user_password' => $this->mPassword,
2082                                 'user_newpassword' => $this->mNewpassword,
2083                                 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ),
2084                                 'user_email' => $this->mEmail,
2085                                 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2086                                 'user_real_name' => $this->mRealName,
2087                                 'user_options' => $this->encodeOptions(),
2088                                 'user_token' => $this->mToken,
2089                                 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2090                                 'user_editcount' => 0,
2091                         ), __METHOD__
2092                 );
2093                 $this->mId = $dbw->insertId();
2094
2095                 # Clear instance cache other than user table data, which is already accurate
2096                 $this->clearInstanceCache();
2097         }
2098
2099         /**
2100          * If the (non-anonymous) user is blocked, this function will block any IP address
2101          * that they successfully log on from.
2102          */
2103         function spreadBlock() {
2104                 wfDebug( __METHOD__."()\n" );
2105                 $this->load();
2106                 if ( $this->mId == 0 ) {
2107                         return;
2108                 }
2109
2110                 $userblock = Block::newFromDB( '', $this->mId );
2111                 if ( !$userblock ) {
2112                         return;
2113                 }
2114
2115                 $userblock->doAutoblock( wfGetIp() );
2116
2117         }
2118
2119         /**
2120          * Generate a string which will be different for any combination of
2121          * user options which would produce different parser output.
2122          * This will be used as part of the hash key for the parser cache,
2123          * so users will the same options can share the same cached data
2124          * safely.
2125          *
2126          * Extensions which require it should install 'PageRenderingHash' hook,
2127          * which will give them a chance to modify this key based on their own
2128          * settings.
2129          *
2130          * @return string
2131          */
2132         function getPageRenderingHash() {
2133                 global $wgContLang, $wgUseDynamicDates, $wgLang;
2134                 if( $this->mHash ){
2135                         return $this->mHash;
2136                 }
2137
2138                 // stubthreshold is only included below for completeness,
2139                 // it will always be 0 when this function is called by parsercache.
2140
2141                 $confstr =        $this->getOption( 'math' );
2142                 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2143                 if ( $wgUseDynamicDates ) {
2144                         $confstr .= '!' . $this->getDatePreference();
2145                 }
2146                 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
2147                 $confstr .= '!' . $wgLang->getCode();
2148                 $confstr .= '!' . $this->getOption( 'thumbsize' );
2149                 // add in language specific options, if any
2150                 $extra = $wgContLang->getExtraHashOptions();
2151                 $confstr .= $extra;
2152
2153                 // Give a chance for extensions to modify the hash, if they have
2154                 // extra options or other effects on the parser cache.
2155                 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2156
2157                 // Make it a valid memcached key fragment
2158                 $confstr = str_replace( ' ', '_', $confstr );
2159                 $this->mHash = $confstr;
2160                 return $confstr;
2161         }
2162
2163         function isBlockedFromCreateAccount() {
2164                 $this->getBlockedStatus();
2165                 return $this->mBlock && $this->mBlock->mCreateAccount;
2166         }
2167
2168         /**
2169          * Determine if the user is blocked from using Special:Emailuser.
2170          *
2171          * @public
2172          * @return boolean
2173          */
2174         function isBlockedFromEmailuser() {
2175                 $this->getBlockedStatus();
2176                 return $this->mBlock && $this->mBlock->mBlockEmail;
2177         }
2178
2179         function isAllowedToCreateAccount() {
2180                 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2181         }
2182
2183         /**
2184          * @deprecated
2185          */
2186         function setLoaded( $loaded ) {}
2187
2188         /**
2189          * Get this user's personal page title.
2190          *
2191          * @return Title
2192          * @public
2193          */
2194         function getUserPage() {
2195                 return Title::makeTitle( NS_USER, $this->getName() );
2196         }
2197
2198         /**
2199          * Get this user's talk page title.
2200          *
2201          * @return Title
2202          * @public
2203          */
2204         function getTalkPage() {
2205                 $title = $this->getUserPage();
2206                 return $title->getTalkPage();
2207         }
2208
2209         /**
2210          * @static
2211          */
2212         function getMaxID() {
2213                 static $res; // cache
2214
2215                 if ( isset( $res ) )
2216                         return $res;
2217                 else {
2218                         $dbr = wfGetDB( DB_SLAVE );
2219                         return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2220                 }
2221         }
2222
2223         /**
2224          * Determine whether the user is a newbie. Newbies are either
2225          * anonymous IPs, or the most recently created accounts.
2226          * @return bool True if it is a newbie.
2227          */
2228         function isNewbie() {
2229                 return !$this->isAllowed( 'autoconfirmed' );
2230         }
2231
2232         /**
2233          * Check to see if the given clear-text password is one of the accepted passwords
2234          * @param string $password User password.
2235          * @return bool True if the given password is correct otherwise False.
2236          */
2237         function checkPassword( $password ) {
2238                 global $wgAuth;
2239                 $this->load();
2240
2241                 // Even though we stop people from creating passwords that
2242                 // are shorter than this, doesn't mean people wont be able
2243                 // to. Certain authentication plugins do NOT want to save
2244                 // domain passwords in a mysql database, so we should
2245                 // check this (incase $wgAuth->strict() is false).
2246                 if( !$this->isValidPassword( $password ) ) {
2247                         return false;
2248                 }
2249
2250                 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2251                         return true;
2252                 } elseif( $wgAuth->strict() ) {
2253                         /* Auth plugin doesn't allow local authentication */
2254                         return false;
2255                 }
2256                 $ep = $this->encryptPassword( $password );
2257                 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
2258                         return true;
2259                 } elseif ( function_exists( 'iconv' ) ) {
2260                         # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2261                         # Check for this with iconv
2262                         $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2263                         if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
2264                                 return true;
2265                         }
2266                 }
2267                 return false;
2268         }
2269         
2270         /**
2271          * Check if the given clear-text password matches the temporary password
2272          * sent by e-mail for password reset operations.
2273          * @return bool
2274          */
2275         function checkTemporaryPassword( $plaintext ) {
2276                 $hash = $this->encryptPassword( $plaintext );
2277                 return $hash === $this->mNewpassword;
2278         }
2279
2280         /**
2281          * Initialize (if necessary) and return a session token value
2282          * which can be used in edit forms to show that the user's
2283          * login credentials aren't being hijacked with a foreign form
2284          * submission.
2285          *
2286          * @param mixed $salt - Optional function-specific data for hash.
2287          *                      Use a string or an array of strings.
2288          * @return string
2289          * @public
2290          */
2291         function editToken( $salt = '' ) {
2292                 if ( $this->isAnon() ) {
2293                         return EDIT_TOKEN_SUFFIX;
2294                 } else {
2295                         if( !isset( $_SESSION['wsEditToken'] ) ) {
2296                                 $token = $this->generateToken();
2297                                 $_SESSION['wsEditToken'] = $token;
2298                         } else {
2299                                 $token = $_SESSION['wsEditToken'];
2300                         }
2301                         if( is_array( $salt ) ) {
2302                                 $salt = implode( '|', $salt );
2303                         }
2304                         return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2305                 }
2306         }
2307
2308         /**
2309          * Generate a hex-y looking random token for various uses.
2310          * Could be made more cryptographically sure if someone cares.
2311          * @return string
2312          */
2313         function generateToken( $salt = '' ) {
2314                 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2315                 return md5( $token . $salt );
2316         }
2317
2318         /**
2319          * Check given value against the token value stored in the session.
2320          * A match should confirm that the form was submitted from the
2321          * user's own login session, not a form submission from a third-party
2322          * site.
2323          *
2324          * @param string $val - the input value to compare
2325          * @param string $salt - Optional function-specific data for hash
2326          * @return bool
2327          * @public
2328          */
2329         function matchEditToken( $val, $salt = '' ) {
2330                 $sessionToken = $this->editToken( $salt );
2331                 if ( $val != $sessionToken ) {
2332                         wfDebug( "User::matchEditToken: broken session data\n" );
2333                 }
2334                 return $val == $sessionToken;
2335         }
2336
2337         /**
2338          * Check whether the edit token is fine except for the suffix
2339          */
2340         function matchEditTokenNoSuffix( $val, $salt = '' ) {
2341                 $sessionToken = $this->editToken( $salt );
2342                 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2343         }
2344
2345         /**
2346          * Generate a new e-mail confirmation token and send a confirmation
2347          * mail to the user's given address.
2348          *
2349          * @return mixed True on success, a WikiError object on failure.
2350          */
2351         function sendConfirmationMail() {
2352                 global $wgContLang;
2353                 $expiration = null; // gets passed-by-ref and defined in next line.
2354                 $url = $this->confirmationTokenUrl( $expiration );
2355                 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2356                         wfMsg( 'confirmemail_body',
2357                                 wfGetIP(),
2358                                 $this->getName(),
2359                                 $url,
2360                                 $wgContLang->timeanddate( $expiration, false ) ) );
2361         }
2362
2363         /**
2364          * Send an e-mail to this user's account. Does not check for
2365          * confirmed status or validity.
2366          *
2367          * @param string $subject
2368          * @param string $body
2369          * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
2370          * @return mixed True on success, a WikiError object on failure.
2371          */
2372         function sendMail( $subject, $body, $from = null ) {
2373                 if( is_null( $from ) ) {
2374                         global $wgPasswordSender;
2375                         $from = $wgPasswordSender;
2376                 }
2377
2378                 require_once( 'UserMailer.php' );
2379                 $to = new MailAddress( $this );
2380                 $sender = new MailAddress( $from );
2381                 $error = userMailer( $to, $sender, $subject, $body );
2382
2383                 if( $error == '' ) {
2384                         return true;
2385                 } else {
2386                         return new WikiError( $error );
2387                 }
2388         }
2389
2390         /**
2391          * Generate, store, and return a new e-mail confirmation code.
2392          * A hash (unsalted since it's used as a key) is stored.
2393          * @param &$expiration mixed output: accepts the expiration time
2394          * @return string
2395          * @private
2396          */
2397         function confirmationToken( &$expiration ) {
2398                 $now = time();
2399                 $expires = $now + 7 * 24 * 60 * 60;
2400                 $expiration = wfTimestamp( TS_MW, $expires );
2401
2402                 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
2403                 $hash = md5( $token );
2404
2405                 $dbw = wfGetDB( DB_MASTER );
2406                 $dbw->update( 'user',
2407                         array( 'user_email_token'         => $hash,
2408                                'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2409                         array( 'user_id'                  => $this->mId ),
2410                         __METHOD__ );
2411
2412                 return $token;
2413         }
2414
2415         /**
2416          * Generate and store a new e-mail confirmation token, and return
2417          * the URL the user can use to confirm.
2418          * @param &$expiration mixed output: accepts the expiration time
2419          * @return string
2420          * @private
2421          */
2422         function confirmationTokenUrl( &$expiration ) {
2423                 $token = $this->confirmationToken( $expiration );
2424                 $title = SpecialPage::getTitleFor( 'Confirmemail', $token );
2425                 return $title->getFullUrl();
2426         }
2427
2428         /**
2429          * Mark the e-mail address confirmed and save.
2430          */
2431         function confirmEmail() {
2432                 $this->load();
2433                 $this->mEmailAuthenticated = wfTimestampNow();
2434                 $this->saveSettings();
2435                 return true;
2436         }
2437
2438         /**
2439          * Is this user allowed to send e-mails within limits of current
2440          * site configuration?
2441          * @return bool
2442          */
2443         function canSendEmail() {
2444                 return $this->isEmailConfirmed();
2445         }
2446
2447         /**
2448          * Is this user allowed to receive e-mails within limits of current
2449          * site configuration?
2450          * @return bool
2451          */
2452         function canReceiveEmail() {
2453                 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2454         }
2455
2456         /**
2457          * Is this user's e-mail address valid-looking and confirmed within
2458          * limits of the current site configuration?
2459          *
2460          * If $wgEmailAuthentication is on, this may require the user to have
2461          * confirmed their address by returning a code or using a password
2462          * sent to the address from the wiki.
2463          *
2464          * @return bool
2465          */
2466         function isEmailConfirmed() {
2467                 global $wgEmailAuthentication;
2468                 $this->load();
2469                 $confirmed = true;
2470                 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2471                         if( $this->isAnon() )
2472                                 return false;
2473                         if( !self::isValidEmailAddr( $this->mEmail ) )
2474                                 return false;
2475                         if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2476                                 return false;
2477                         return true;
2478                 } else {
2479                         return $confirmed;
2480                 }
2481         }
2482         
2483         /**
2484          * Return true if there is an outstanding request for e-mail confirmation.
2485          * @return bool
2486          */
2487         function isEmailConfirmationPending() {
2488                 global $wgEmailAuthentication;
2489                 return $wgEmailAuthentication &&
2490                         !$this->isEmailConfirmed() &&
2491                         $this->mEmailToken &&
2492                         $this->mEmailTokenExpires > wfTimestamp();
2493         }
2494         
2495         /**
2496          * Get the timestamp of account creation, or false for
2497          * non-existent/anonymous user accounts
2498          *
2499          * @return mixed
2500          */
2501         public function getRegistration() {
2502                 return $this->mId > 0
2503                         ? $this->mRegistration
2504                         : false;
2505         }
2506
2507         /**
2508          * @param array $groups list of groups
2509          * @return array list of permission key names for given groups combined
2510          * @static
2511          */
2512         static function getGroupPermissions( $groups ) {
2513                 global $wgGroupPermissions;
2514                 $rights = array();
2515                 foreach( $groups as $group ) {
2516                         if( isset( $wgGroupPermissions[$group] ) ) {
2517                                 $rights = array_merge( $rights,
2518                                         array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2519                         }
2520                 }
2521                 return $rights;
2522         }
2523
2524         /**
2525          * @param string $group key name
2526          * @return string localized descriptive name for group, if provided
2527          * @static
2528          */
2529         static function getGroupName( $group ) {
2530                 global $wgMessageCache;
2531                 $wgMessageCache->loadAllMessages();
2532                 $key = "group-$group";
2533                 $name = wfMsg( $key );
2534                 return $name == '' || wfEmptyMsg( $key, $name )
2535                         ? $group
2536                         : $name;
2537         }
2538
2539         /**
2540          * @param string $group key name
2541          * @return string localized descriptive name for member of a group, if provided
2542          * @static
2543          */
2544         static function getGroupMember( $group ) {
2545                 global $wgMessageCache;
2546                 $wgMessageCache->loadAllMessages();
2547                 $key = "group-$group-member";
2548                 $name = wfMsg( $key );
2549                 return $name == '' || wfEmptyMsg( $key, $name )
2550                         ? $group
2551                         : $name;
2552         }
2553
2554         /**
2555          * Return the set of defined explicit groups.
2556          * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2557          * groups are not included, as they are defined
2558          * automatically, not in the database.
2559          * @return array
2560          * @static
2561          */
2562         static function getAllGroups() {
2563                 global $wgGroupPermissions;
2564                 return array_diff(
2565                         array_keys( $wgGroupPermissions ),
2566                         self::getImplicitGroups()
2567                 );
2568         }
2569
2570         /**
2571          * Get a list of implicit groups
2572          *
2573          * @return array
2574          */
2575         public static function getImplicitGroups() {
2576                 static $groups = null;
2577                 if( !is_array( $groups ) ) {
2578                         $groups = array( '*', 'user', 'autoconfirmed', 'emailconfirmed' );
2579                         wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );
2580                 }
2581                 return $groups;
2582         }
2583
2584         /**
2585          * Get the title of a page describing a particular group
2586          *
2587          * @param $group Name of the group
2588          * @return mixed
2589          */
2590         static function getGroupPage( $group ) {
2591                 global $wgMessageCache;
2592                 $wgMessageCache->loadAllMessages();
2593                 $page = wfMsgForContent( 'grouppage-' . $group );
2594                 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2595                         $title = Title::newFromText( $page );
2596                         if( is_object( $title ) )
2597                                 return $title;
2598                 }
2599                 return false;
2600         }
2601
2602         /**
2603          * Create a link to the group in HTML, if available
2604          *
2605          * @param $group Name of the group
2606          * @param $text The text of the link
2607          * @return mixed
2608          */
2609         static function makeGroupLinkHTML( $group, $text = '' ) {
2610                 if( $text == '' ) {
2611                         $text = self::getGroupName( $group );
2612                 }
2613                 $title = self::getGroupPage( $group );
2614                 if( $title ) {
2615                         global $wgUser;
2616                         $sk = $wgUser->getSkin();
2617                         return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2618                 } else {
2619                         return $text;
2620                 }
2621         }
2622
2623         /**
2624          * Create a link to the group in Wikitext, if available
2625          *
2626          * @param $group Name of the group
2627          * @param $text The text of the link (by default, the name of the group)
2628          * @return mixed
2629          */
2630         static function makeGroupLinkWiki( $group, $text = '' ) {
2631                 if( $text == '' ) {
2632                         $text = self::getGroupName( $group );
2633                 }
2634                 $title = self::getGroupPage( $group );
2635                 if( $title ) {
2636                         $page = $title->getPrefixedText();
2637                         return "[[$page|$text]]";
2638                 } else {
2639                         return $text;
2640                 }
2641         }
2642         
2643         /**
2644          * Increment the user's edit-count field.
2645          * Will have no effect for anonymous users.
2646          */
2647         function incEditCount() {
2648                 if( !$this->isAnon() ) {
2649                         $dbw = wfGetDB( DB_MASTER );
2650                         $dbw->update( 'user',
2651                                 array( 'user_editcount=user_editcount+1' ),
2652                                 array( 'user_id' => $this->getId() ),
2653                                 __METHOD__ );
2654                         
2655                         // Lazy initialization check...
2656                         if( $dbw->affectedRows() == 0 ) {
2657                                 // Pull from a slave to be less cruel to servers
2658                                 // Accuracy isn't the point anyway here
2659                                 $dbr = wfGetDB( DB_SLAVE );
2660                                 $count = $dbr->selectField( 'revision',
2661                                         'COUNT(rev_user)',
2662                                         array( 'rev_user' => $this->getId() ),
2663                                         __METHOD__ );
2664                                 
2665                                 // Now here's a goddamn hack...
2666                                 if( $dbr !== $dbw ) {
2667                                         // If we actually have a slave server, the count is
2668                                         // at least one behind because the current transaction
2669                                         // has not been committed and replicated.
2670                                         $count++;
2671                                 } else {
2672                                         // But if DB_SLAVE is selecting the master, then the
2673                                         // count we just read includes the revision that was
2674                                         // just added in the working transaction.
2675                                 }
2676                                 
2677                                 $dbw->update( 'user',
2678                                         array( 'user_editcount' => $count ),
2679                                         array( 'user_id' => $this->getId() ),
2680                                         __METHOD__ );
2681                         }
2682                 }
2683                 // edit count in user cache too
2684                 $this->invalidateCache();
2685         }
2686 }
2687
2688