]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/User.php
MediaWiki 1.17.4
[autoinstalls/mediawiki.git] / includes / User.php
1 <?php
2 /**
3  * Implements the User class for the %MediaWiki software.
4  * @file
5  */
6
7 /**
8  * \int Number of characters in user_token field.
9  * @ingroup Constants
10  */
11 define( 'USER_TOKEN_LENGTH', 32 );
12
13 /**
14  * \int Serialized record version.
15  * @ingroup Constants
16  */
17 define( 'MW_USER_VERSION', 8 );
18
19 /**
20  * \string Some punctuation to prevent editing from broken text-mangling proxies.
21  * @ingroup Constants
22  */
23 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
24
25 /**
26  * Thrown by User::setPassword() on error.
27  * @ingroup Exception
28  */
29 class PasswordError extends MWException {
30         // NOP
31 }
32
33 /**
34  * The User object encapsulates all of the user-specific settings (user_id,
35  * name, rights, password, email address, options, last login time). Client
36  * classes use the getXXX() functions to access these fields. These functions
37  * do all the work of determining whether the user is logged in,
38  * whether the requested option can be satisfied from cookies or
39  * whether a database query is needed. Most of the settings needed
40  * for rendering normal pages are set in the cookie to minimize use
41  * of the database.
42  */
43 class User {
44         /**
45          * Global constants made accessible as class constants so that autoloader
46          * magic can be used.
47          */
48         const USER_TOKEN_LENGTH = USER_TOKEN_LENGTH;
49         const MW_USER_VERSION = MW_USER_VERSION;
50         const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
51
52         /**
53          * \type{\arrayof{\string}} List of member variables which are saved to the
54          * shared cache (memcached). Any operation which changes the
55          * corresponding database fields must call a cache-clearing function.
56          * @showinitializer
57          */
58         static $mCacheVars = array(
59                 // user table
60                 'mId',
61                 'mName',
62                 'mRealName',
63                 'mPassword',
64                 'mNewpassword',
65                 'mNewpassTime',
66                 'mEmail',
67                 'mTouched',
68                 'mToken',
69                 'mEmailAuthenticated',
70                 'mEmailToken',
71                 'mEmailTokenExpires',
72                 'mRegistration',
73                 'mEditCount',
74                 // user_group table
75                 'mGroups',
76                 // user_properties table
77                 'mOptionOverrides',
78         );
79
80         /**
81          * \type{\arrayof{\string}} Core rights.
82          * Each of these should have a corresponding message of the form
83          * "right-$right".
84          * @showinitializer
85          */
86         static $mCoreRights = array(
87                 'apihighlimits',
88                 'autoconfirmed',
89                 'autopatrol',
90                 'bigdelete',
91                 'block',
92                 'blockemail',
93                 'bot',
94                 'browsearchive',
95                 'createaccount',
96                 'createpage',
97                 'createtalk',
98                 'delete',
99                 'deletedhistory',
100                 'deletedtext',
101                 'deleterevision',
102                 'edit',
103                 'editinterface',
104                 'editusercssjs', #deprecated
105                 'editusercss',
106                 'edituserjs',
107                 'hideuser',
108                 'import',
109                 'importupload',
110                 'ipblock-exempt',
111                 'markbotedits',
112                 'mergehistory',
113                 'minoredit',
114                 'move',
115                 'movefile',
116                 'move-rootuserpages',
117                 'move-subpages',
118                 'nominornewtalk',
119                 'noratelimit',
120                 'override-export-depth',
121                 'patrol',
122                 'protect',
123                 'proxyunbannable',
124                 'purge',
125                 'read',
126                 'reupload',
127                 'reupload-shared',
128                 'rollback',
129                 'selenium',
130                 'sendemail',
131                 'siteadmin',
132                 'suppressionlog',
133                 'suppressredirect',
134                 'suppressrevision',
135                 'trackback',
136                 'unblockself',
137                 'undelete',
138                 'unwatchedpages',
139                 'upload',
140                 'upload_by_url',
141                 'userrights',
142                 'userrights-interwiki',
143                 'writeapi',
144         );
145         /**
146          * \string Cached results of getAllRights()
147          */
148         static $mAllRights = false;
149
150         /** @name Cache variables */
151         //@{
152         var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
153                 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
154                 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups, $mOptionOverrides;
155         //@}
156
157         /**
158          * \bool Whether the cache variables have been loaded.
159          */
160         var $mDataLoaded, $mAuthLoaded, $mOptionsLoaded;
161
162         /**
163          * \string Initialization data source if mDataLoaded==false. May be one of:
164          *  - 'defaults'   anonymous user initialised from class defaults
165          *  - 'name'       initialise from mName
166          *  - 'id'         initialise from mId
167          *  - 'session'    log in from cookies or session if possible
168          *
169          * Use the User::newFrom*() family of functions to set this.
170          */
171         var $mFrom;
172
173         /** @name Lazy-initialized variables, invalidated with clearInstanceCache */
174         //@{
175         var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
176                 $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
177                 $mLocked, $mHideName, $mOptions;
178         //@}
179
180         static $idCacheByName = array();
181
182         /**
183          * Lightweight constructor for an anonymous user.
184          * Use the User::newFrom* factory functions for other kinds of users.
185          *
186          * @see newFromName()
187          * @see newFromId()
188          * @see newFromConfirmationCode()
189          * @see newFromSession()
190          * @see newFromRow()
191          */
192         function __construct() {
193                 $this->clearInstanceCache( 'defaults' );
194         }
195
196         /**
197          * Load the user table data for this object from the source given by mFrom.
198          */
199         function load() {
200                 if ( $this->mDataLoaded ) {
201                         return;
202                 }
203                 wfProfileIn( __METHOD__ );
204
205                 # Set it now to avoid infinite recursion in accessors
206                 $this->mDataLoaded = true;
207
208                 switch ( $this->mFrom ) {
209                         case 'defaults':
210                                 $this->loadDefaults();
211                                 break;
212                         case 'name':
213                                 $this->mId = self::idFromName( $this->mName );
214                                 if ( !$this->mId ) {
215                                         # Nonexistent user placeholder object
216                                         $this->loadDefaults( $this->mName );
217                                 } else {
218                                         $this->loadFromId();
219                                 }
220                                 break;
221                         case 'id':
222                                 $this->loadFromId();
223                                 break;
224                         case 'session':
225                                 $this->loadFromSession();
226                                 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
227                                 break;
228                         default:
229                                 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
230                 }
231                 wfProfileOut( __METHOD__ );
232         }
233
234         /**
235          * Load user table data, given mId has already been set.
236          * @return \bool false if the ID does not exist, true otherwise
237          * @private
238          */
239         function loadFromId() {
240                 global $wgMemc;
241                 if ( $this->mId == 0 ) {
242                         $this->loadDefaults();
243                         return false;
244                 }
245
246                 # Try cache
247                 $key = wfMemcKey( 'user', 'id', $this->mId );
248                 $data = $wgMemc->get( $key );
249                 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
250                         # Object is expired, load from DB
251                         $data = false;
252                 }
253
254                 if ( !$data ) {
255                         wfDebug( "User: cache miss for user {$this->mId}\n" );
256                         # Load from DB
257                         if ( !$this->loadFromDatabase() ) {
258                                 # Can't load from ID, user is anonymous
259                                 return false;
260                         }
261                         $this->saveToCache();
262                 } else {
263                         wfDebug( "User: got user {$this->mId} from cache\n" );
264                         # Restore from cache
265                         foreach ( self::$mCacheVars as $name ) {
266                                 $this->$name = $data[$name];
267                         }
268                 }
269                 return true;
270         }
271
272         /**
273          * Save user data to the shared cache
274          */
275         function saveToCache() {
276                 $this->load();
277                 $this->loadGroups();
278                 $this->loadOptions();
279                 if ( $this->isAnon() ) {
280                         // Anonymous users are uncached
281                         return;
282                 }
283                 $data = array();
284                 foreach ( self::$mCacheVars as $name ) {
285                         $data[$name] = $this->$name;
286                 }
287                 $data['mVersion'] = MW_USER_VERSION;
288                 $key = wfMemcKey( 'user', 'id', $this->mId );
289                 global $wgMemc;
290                 $wgMemc->set( $key, $data );
291         }
292
293
294         /** @name newFrom*() static factory methods */
295         //@{
296
297         /**
298          * Static factory method for creation from username.
299          *
300          * This is slightly less efficient than newFromId(), so use newFromId() if
301          * you have both an ID and a name handy.
302          *
303          * @param $name \string Username, validated by Title::newFromText()
304          * @param $validate \mixed Validate username. Takes the same parameters as
305          *    User::getCanonicalName(), except that true is accepted as an alias
306          *    for 'valid', for BC.
307          *
308          * @return User The User object, or false if the username is invalid
309          *    (e.g. if it contains illegal characters or is an IP address). If the
310          *    username is not present in the database, the result will be a user object
311          *    with a name, zero user ID and default settings.
312          */
313         static function newFromName( $name, $validate = 'valid' ) {
314                 if ( $validate === true ) {
315                         $validate = 'valid';
316                 }
317                 $name = self::getCanonicalName( $name, $validate );
318                 if ( $name === false ) {
319                         return false;
320                 } else {
321                         # Create unloaded user object
322                         $u = new User;
323                         $u->mName = $name;
324                         $u->mFrom = 'name';
325                         return $u;
326                 }
327         }
328
329         /**
330          * Static factory method for creation from a given user ID.
331          *
332          * @param $id \int Valid user ID
333          * @return \type{User} The corresponding User object
334          */
335         static function newFromId( $id ) {
336                 $u = new User;
337                 $u->mId = $id;
338                 $u->mFrom = 'id';
339                 return $u;
340         }
341
342         /**
343          * Factory method to fetch whichever user has a given email confirmation code.
344          * This code is generated when an account is created or its e-mail address
345          * has changed.
346          *
347          * If the code is invalid or has expired, returns NULL.
348          *
349          * @param $code \string Confirmation code
350          * @return \type{User}
351          */
352         static function newFromConfirmationCode( $code ) {
353                 $dbr = wfGetDB( DB_SLAVE );
354                 $id = $dbr->selectField( 'user', 'user_id', array(
355                         'user_email_token' => md5( $code ),
356                         'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
357                         ) );
358                 if( $id !== false ) {
359                         return User::newFromId( $id );
360                 } else {
361                         return null;
362                 }
363         }
364
365         /**
366          * Create a new user object using data from session or cookies. If the
367          * login credentials are invalid, the result is an anonymous user.
368          *
369          * @return \type{User}
370          */
371         static function newFromSession() {
372                 $user = new User;
373                 $user->mFrom = 'session';
374                 return $user;
375         }
376
377         /**
378          * Create a new user object from a user row.
379          * The row should have all fields from the user table in it.
380          * @param $row array A row from the user table
381          * @return \type{User}
382          */
383         static function newFromRow( $row ) {
384                 $user = new User;
385                 $user->loadFromRow( $row );
386                 return $user;
387         }
388
389         //@}
390
391
392         /**
393          * Get the username corresponding to a given user ID
394          * @param $id \int User ID
395          * @return \string The corresponding username
396          */
397         static function whoIs( $id ) {
398                 $dbr = wfGetDB( DB_SLAVE );
399                 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), __METHOD__ );
400         }
401
402         /**
403          * Get the real name of a user given their user ID
404          *
405          * @param $id \int User ID
406          * @return \string The corresponding user's real name
407          */
408         static function whoIsReal( $id ) {
409                 $dbr = wfGetDB( DB_SLAVE );
410                 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ );
411         }
412
413         /**
414          * Get database id given a user name
415          * @param $name \string Username
416          * @return \types{\int,\null} The corresponding user's ID, or null if user is nonexistent
417          */
418         static function idFromName( $name ) {
419                 $nt = Title::makeTitleSafe( NS_USER, $name );
420                 if( is_null( $nt ) ) {
421                         # Illegal name
422                         return null;
423                 }
424
425                 if ( isset( self::$idCacheByName[$name] ) ) {
426                         return self::$idCacheByName[$name];
427                 }
428
429                 $dbr = wfGetDB( DB_SLAVE );
430                 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
431
432                 if ( $s === false ) {
433                         $result = null;
434                 } else {
435                         $result = $s->user_id;
436                 }
437
438                 self::$idCacheByName[$name] = $result;
439
440                 if ( count( self::$idCacheByName ) > 1000 ) {
441                         self::$idCacheByName = array();
442                 }
443
444                 return $result;
445         }
446
447         /**
448          * Does the string match an anonymous IPv4 address?
449          *
450          * This function exists for username validation, in order to reject
451          * usernames which are similar in form to IP addresses. Strings such
452          * as 300.300.300.300 will return true because it looks like an IP
453          * address, despite not being strictly valid.
454          *
455          * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
456          * address because the usemod software would "cloak" anonymous IP
457          * addresses like this, if we allowed accounts like this to be created
458          * new users could get the old edits of these anonymous users.
459          *
460          * @param $name \string String to match
461          * @return \bool True or false
462          */
463         static function isIP( $name ) {
464                 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP::isIPv6($name);
465         }
466
467         /**
468          * Is the input a valid username?
469          *
470          * Checks if the input is a valid username, we don't want an empty string,
471          * an IP address, anything that containins slashes (would mess up subpages),
472          * is longer than the maximum allowed username size or doesn't begin with
473          * a capital letter.
474          *
475          * @param $name \string String to match
476          * @return \bool True or false
477          */
478         static function isValidUserName( $name ) {
479                 global $wgContLang, $wgMaxNameChars;
480
481                 if ( $name == ''
482                 || User::isIP( $name )
483                 || strpos( $name, '/' ) !== false
484                 || strlen( $name ) > $wgMaxNameChars
485                 || $name != $wgContLang->ucfirst( $name ) ) {
486                         wfDebugLog( 'username', __METHOD__ .
487                                 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
488                         return false;
489                 }
490
491                 // Ensure that the name can't be misresolved as a different title,
492                 // such as with extra namespace keys at the start.
493                 $parsed = Title::newFromText( $name );
494                 if( is_null( $parsed )
495                         || $parsed->getNamespace()
496                         || strcmp( $name, $parsed->getPrefixedText() ) ) {
497                         wfDebugLog( 'username', __METHOD__ .
498                                 ": '$name' invalid due to ambiguous prefixes" );
499                         return false;
500                 }
501
502                 // Check an additional blacklist of troublemaker characters.
503                 // Should these be merged into the title char list?
504                 $unicodeBlacklist = '/[' .
505                         '\x{0080}-\x{009f}' . # iso-8859-1 control chars
506                         '\x{00a0}' .          # non-breaking space
507                         '\x{2000}-\x{200f}' . # various whitespace
508                         '\x{2028}-\x{202f}' . # breaks and control chars
509                         '\x{3000}' .          # ideographic space
510                         '\x{e000}-\x{f8ff}' . # private use
511                         ']/u';
512                 if( preg_match( $unicodeBlacklist, $name ) ) {
513                         wfDebugLog( 'username', __METHOD__ .
514                                 ": '$name' invalid due to blacklisted characters" );
515                         return false;
516                 }
517
518                 return true;
519         }
520
521         /**
522          * Usernames which fail to pass this function will be blocked
523          * from user login and new account registrations, but may be used
524          * internally by batch processes.
525          *
526          * If an account already exists in this form, login will be blocked
527          * by a failure to pass this function.
528          *
529          * @param $name \string String to match
530          * @return \bool True or false
531          */
532         static function isUsableName( $name ) {
533                 global $wgReservedUsernames;
534                 // Must be a valid username, obviously ;)
535                 if ( !self::isValidUserName( $name ) ) {
536                         return false;
537                 }
538
539                 static $reservedUsernames = false;
540                 if ( !$reservedUsernames ) {
541                         $reservedUsernames = $wgReservedUsernames;
542                         wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
543                 }
544
545                 // Certain names may be reserved for batch processes.
546                 foreach ( $reservedUsernames as $reserved ) {
547                         if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
548                                 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
549                         }
550                         if ( $reserved == $name ) {
551                                 return false;
552                         }
553                 }
554                 return true;
555         }
556
557         /**
558          * Usernames which fail to pass this function will be blocked
559          * from new account registrations, but may be used internally
560          * either by batch processes or by user accounts which have
561          * already been created.
562          *
563          * Additional blacklisting may be added here rather than in
564          * isValidUserName() to avoid disrupting existing accounts.
565          *
566          * @param $name \string String to match
567          * @return \bool True or false
568          */
569         static function isCreatableName( $name ) {
570                 global $wgInvalidUsernameCharacters;
571
572                 // Ensure that the username isn't longer than 235 bytes, so that
573                 // (at least for the builtin skins) user javascript and css files
574                 // will work. (bug 23080)
575                 if( strlen( $name ) > 235 ) {
576                         wfDebugLog( 'username', __METHOD__ .
577                                 ": '$name' invalid due to length" );
578                         return false;
579                 }
580
581                 // Preg yells if you try to give it an empty string
582                 if( $wgInvalidUsernameCharacters ) {
583                         if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
584                                 wfDebugLog( 'username', __METHOD__ .
585                                         ": '$name' invalid due to wgInvalidUsernameCharacters" );
586                                 return false;
587                         }
588                 }
589
590                 return self::isUsableName( $name );
591         }
592
593         /**
594          * Is the input a valid password for this user?
595          *
596          * @param $password String Desired password
597          * @return bool True or false
598          */
599         function isValidPassword( $password ) {
600                 //simple boolean wrapper for getPasswordValidity
601                 return $this->getPasswordValidity( $password ) === true;
602         }
603
604         /**
605          * Given unvalidated password input, return error message on failure.
606          *
607          * @param $password String Desired password
608          * @return mixed: true on success, string of error message on failure
609          */
610         function getPasswordValidity( $password ) {
611                 global $wgMinimalPasswordLength, $wgContLang;
612                 
613                 static $blockedLogins = array(
614                         'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
615                         'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
616                 );
617
618                 $result = false; //init $result to false for the internal checks
619
620                 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
621                         return $result;
622
623                 if ( $result === false ) {
624                         if( strlen( $password ) < $wgMinimalPasswordLength ) {
625                                 return 'passwordtooshort';
626                         } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
627                                 return 'password-name-match';
628                         } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
629                                 return 'password-login-forbidden';
630                         } else {
631                                 //it seems weird returning true here, but this is because of the
632                                 //initialization of $result to false above. If the hook is never run or it
633                                 //doesn't modify $result, then we will likely get down into this if with
634                                 //a valid password.
635                                 return true;
636                         }
637                 } elseif( $result === true ) {
638                         return true;
639                 } else {
640                         return $result; //the isValidPassword hook set a string $result and returned true
641                 }
642         }
643
644         /**
645          * Does a string look like an e-mail address?
646          *
647          * This validates an email address using an HTML5 specification found at:
648          * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
649          * Which as of 2011-01-24 says:
650          *
651          *     A valid e-mail address is a string that matches the ABNF production
652          *   1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
653          *   in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
654          *   3.5.
655          *
656          * This function is an implementation of the specification as requested in
657          * bug 22449.
658          *
659          * Client-side forms will use the same standard validation rules via JS or
660          * HTML 5 validation; additional restrictions can be enforced server-side
661          * by extensions via the 'isValidEmailAddr' hook.
662          *
663          * Note that this validation doesn't 100% match RFC 2822, but is believed
664          * to be liberal enough for wide use. Some invalid addresses will still
665          * pass validation here.
666          *
667          * @param $addr String E-mail address
668          * @return Bool
669          */
670         public static function isValidEmailAddr( $addr ) {
671                 $result = null;
672                 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
673                         return $result;
674                 }
675
676                 // Please note strings below are enclosed in brackets [], this make the
677                 // hyphen "-" a range indicator. Hence it is double backslashed below.
678                 // See bug 26948
679                 $rfc5322_atext   = "a-z0-9!#$%&'*+\\-\/=?^_`{|}~" ;
680                 $rfc1034_ldh_str = "a-z0-9\\-" ;
681
682                 $HTML5_email_regexp = "/
683                 ^                      # start of string
684                 [$rfc5322_atext\\.]+    # user part which is liberal :p
685                 @                      # 'apostrophe'
686                 [$rfc1034_ldh_str]+       # First domain part
687                 (\\.[$rfc1034_ldh_str]+)*  # Following part prefixed with a dot
688                 $                      # End of string
689                 /ix" ; // case Insensitive, eXtended
690
691                 return (bool) preg_match( $HTML5_email_regexp, $addr );
692         }
693
694         /**
695          * Given unvalidated user input, return a canonical username, or false if
696          * the username is invalid.
697          * @param $name \string User input
698          * @param $validate \types{\string,\bool} Type of validation to use:
699          *                - false        No validation
700          *                - 'valid'      Valid for batch processes
701          *                - 'usable'     Valid for batch processes and login
702          *                - 'creatable'  Valid for batch processes, login and account creation
703          */
704         static function getCanonicalName( $name, $validate = 'valid' ) {
705                 # Force usernames to capital
706                 global $wgContLang;
707                 $name = $wgContLang->ucfirst( $name );
708
709                 # Reject names containing '#'; these will be cleaned up
710                 # with title normalisation, but then it's too late to
711                 # check elsewhere
712                 if( strpos( $name, '#' ) !== false )
713                         return false;
714
715                 # Clean up name according to title rules
716                 $t = ( $validate === 'valid' ) ?
717                         Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
718                 # Check for invalid titles
719                 if( is_null( $t ) ) {
720                         return false;
721                 }
722
723                 # Reject various classes of invalid names
724                 global $wgAuth;
725                 $name = $wgAuth->getCanonicalName( $t->getText() );
726
727                 switch ( $validate ) {
728                         case false:
729                                 break;
730                         case 'valid':
731                                 if ( !User::isValidUserName( $name ) ) {
732                                         $name = false;
733                                 }
734                                 break;
735                         case 'usable':
736                                 if ( !User::isUsableName( $name ) ) {
737                                         $name = false;
738                                 }
739                                 break;
740                         case 'creatable':
741                                 if ( !User::isCreatableName( $name ) ) {
742                                         $name = false;
743                                 }
744                                 break;
745                         default:
746                                 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
747                 }
748                 return $name;
749         }
750
751         /**
752          * Count the number of edits of a user
753          * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
754          *
755          * @param $uid \int User ID to check
756          * @return \int The user's edit count
757          */
758         static function edits( $uid ) {
759                 wfProfileIn( __METHOD__ );
760                 $dbr = wfGetDB( DB_SLAVE );
761                 // check if the user_editcount field has been initialized
762                 $field = $dbr->selectField(
763                         'user', 'user_editcount',
764                         array( 'user_id' => $uid ),
765                         __METHOD__
766                 );
767
768                 if( $field === null ) { // it has not been initialized. do so.
769                         $dbw = wfGetDB( DB_MASTER );
770                         $count = $dbr->selectField(
771                                 'revision', 'count(*)',
772                                 array( 'rev_user' => $uid ),
773                                 __METHOD__
774                         );
775                         $dbw->update(
776                                 'user',
777                                 array( 'user_editcount' => $count ),
778                                 array( 'user_id' => $uid ),
779                                 __METHOD__
780                         );
781                 } else {
782                         $count = $field;
783                 }
784                 wfProfileOut( __METHOD__ );
785                 return $count;
786         }
787
788         /**
789          * Return a random password.
790          *
791          * @return \string New random password
792          */
793         static function randomPassword() {
794                 global $wgMinimalPasswordLength;
795                 // Decide the final password length based on our min password length, stopping at a minimum of 10 chars
796                 $length = max( 10, $wgMinimalPasswordLength );
797                 // Multiply by 1.25 to get the number of hex characters we need
798                 $length = $length * 1.25;
799                 // Generate random hex chars
800                 $hex = MWCryptRand::generateHex( $length );
801                 // Convert from base 16 to base 32 to get a proper password like string
802                 return wfBaseConvert( $hex, 16, 32 );
803         }
804
805         /**
806          * Set cached properties to default.
807          *
808          * @note This no longer clears uncached lazy-initialised properties;
809          *       the constructor does that instead.
810          * @private
811          */
812         function loadDefaults( $name = false ) {
813                 wfProfileIn( __METHOD__ );
814
815                 global $wgRequest;
816
817                 $this->mId = 0;
818                 $this->mName = $name;
819                 $this->mRealName = '';
820                 $this->mPassword = $this->mNewpassword = '';
821                 $this->mNewpassTime = null;
822                 $this->mEmail = '';
823                 $this->mOptionOverrides = null;
824                 $this->mOptionsLoaded = false;
825
826                 if( $wgRequest->getCookie( 'LoggedOut' ) !== null ) {
827                         $this->mTouched = wfTimestamp( TS_MW, $wgRequest->getCookie( 'LoggedOut' ) );
828                 } else {
829                         $this->mTouched = '0'; # Allow any pages to be cached
830                 }
831
832                 $this->mToken = null; // Don't run cryptographic functions till we need a token
833                 $this->mEmailAuthenticated = null;
834                 $this->mEmailToken = '';
835                 $this->mEmailTokenExpires = null;
836                 $this->mRegistration = wfTimestamp( TS_MW );
837                 $this->mGroups = array();
838
839                 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
840
841                 wfProfileOut( __METHOD__ );
842         }
843
844         /**
845          * @deprecated Use wfSetupSession().
846          */
847         function SetupSession() {
848                 wfDeprecated( __METHOD__ );
849                 wfSetupSession();
850         }
851
852         /**
853          * Load user data from the session or login cookie. If there are no valid
854          * credentials, initialises the user as an anonymous user.
855          * @return \bool True if the user is logged in, false otherwise.
856          */
857         private function loadFromSession() {
858                 global $wgRequest, $wgExternalAuthType, $wgAutocreatePolicy;
859
860                 $result = null;
861                 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
862                 if ( $result !== null ) {
863                         return $result;
864                 }
865
866                 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
867                         $extUser = ExternalUser::newFromCookie();
868                         if ( $extUser ) {
869                                 # TODO: Automatically create the user here (or probably a bit
870                                 # lower down, in fact)
871                         }
872                 }
873
874                 if ( $wgRequest->getCookie( 'UserID' ) !== null ) {
875                         $sId = intval( $wgRequest->getCookie( 'UserID' ) );
876                         if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
877                                 $this->loadDefaults(); // Possible collision!
878                                 wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
879                                         cookie user ID ($sId) don't match!" );
880                                 return false;
881                         }
882                         $_SESSION['wsUserID'] = $sId;
883                 } else if ( isset( $_SESSION['wsUserID'] ) ) {
884                         if ( $_SESSION['wsUserID'] != 0 ) {
885                                 $sId = $_SESSION['wsUserID'];
886                         } else {
887                                 $this->loadDefaults();
888                                 return false;
889                         }
890                 } else {
891                         $this->loadDefaults();
892                         return false;
893                 }
894
895                 if ( isset( $_SESSION['wsUserName'] ) ) {
896                         $sName = $_SESSION['wsUserName'];
897                 } else if ( $wgRequest->getCookie('UserName') !== null ) {
898                         $sName = $wgRequest->getCookie('UserName');
899                         $_SESSION['wsUserName'] = $sName;
900                 } else {
901                         $this->loadDefaults();
902                         return false;
903                 }
904
905                 $proposedUser = User::newFromId( $sId );
906                 if ( !$proposedUser->isLoggedIn() ) {
907                         # Not a valid ID
908                         $this->loadDefaults();
909                         return false;
910                 }
911
912                 global $wgBlockDisablesLogin;
913                 if( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
914                         # User blocked and we've disabled blocked user logins
915                         $this->loadDefaults();
916                         return false;
917                 }
918
919                 if ( isset( $_SESSION['wsToken'] ) && $_SESSION['wsToken'] ) {
920                         $passwordCorrect = $proposedUser->getToken( false ) === $_SESSION['wsToken'];
921                         $from = 'session';
922                 } elseif ( $wgRequest->getCookie( 'Token' ) ) {
923                         $passwordCorrect = $proposedUser->getToken( false ) === $wgRequest->getCookie( 'Token' );
924                         $from = 'cookie';
925                 } else {
926                         # No session or persistent login cookie
927                         $this->loadDefaults();
928                         return false;
929                 }
930
931                 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
932                         $this->loadFromUserObject( $proposedUser );
933                         $_SESSION['wsToken'] = $this->mToken;
934                         wfDebug( "User: logged in from $from\n" );
935                         return true;
936                 } else {
937                         # Invalid credentials
938                         wfDebug( "User: can't log in from $from, invalid credentials\n" );
939                         $this->loadDefaults();
940                         return false;
941                 }
942         }
943
944         /**
945          * Load the data for this user object from another user object. 
946          */
947         protected function loadFromUserObject( $user ) {
948                 $user->load();
949                 $user->loadGroups();
950                 $user->loadOptions();
951                 foreach ( self::$mCacheVars as $var ) {
952                         $this->$var = $user->$var;
953                 }
954         }
955
956         /**
957          * Load user and user_group data from the database.
958          * $this::mId must be set, this is how the user is identified.
959          *
960          * @return \bool True if the user exists, false if the user is anonymous
961          * @private
962          */
963         function loadFromDatabase() {
964                 # Paranoia
965                 $this->mId = intval( $this->mId );
966
967                 /** Anonymous user */
968                 if( !$this->mId ) {
969                         $this->loadDefaults();
970                         return false;
971                 }
972
973                 $dbr = wfGetDB( DB_MASTER );
974                 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
975
976                 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
977
978                 if ( $s !== false ) {
979                         # Initialise user table data
980                         $this->loadFromRow( $s );
981                         $this->mGroups = null; // deferred
982                         $this->getEditCount(); // revalidation for nulls
983                         return true;
984                 } else {
985                         # Invalid user_id
986                         $this->mId = 0;
987                         $this->loadDefaults();
988                         return false;
989                 }
990         }
991
992         /**
993          * Initialize this object from a row from the user table.
994          *
995          * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
996          */
997         function loadFromRow( $row ) {
998                 $this->mDataLoaded = true;
999
1000                 if ( isset( $row->user_id ) ) {
1001                         $this->mId = intval( $row->user_id );
1002                 }
1003                 $this->mName = $row->user_name;
1004                 $this->mRealName = $row->user_real_name;
1005                 $this->mPassword = $row->user_password;
1006                 $this->mNewpassword = $row->user_newpassword;
1007                 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1008                 $this->mEmail = $row->user_email;
1009                 $this->decodeOptions( $row->user_options );
1010                 $this->mTouched = wfTimestamp(TS_MW,$row->user_touched);
1011                 $this->mToken = $row->user_token;
1012                 if ( $this->mToken == '' ) {
1013                         $this->mToken = null;
1014                 }
1015                 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1016                 $this->mEmailToken = $row->user_email_token;
1017                 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1018                 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1019                 $this->mEditCount = $row->user_editcount;
1020         }
1021
1022         /**
1023          * Load the groups from the database if they aren't already loaded.
1024          * @private
1025          */
1026         function loadGroups() {
1027                 if ( is_null( $this->mGroups ) ) {
1028                         $dbr = wfGetDB( DB_MASTER );
1029                         $res = $dbr->select( 'user_groups',
1030                                 array( 'ug_group' ),
1031                                 array( 'ug_user' => $this->mId ),
1032                                 __METHOD__ );
1033                         $this->mGroups = array();
1034                         foreach ( $res as $row ) {
1035                                 $this->mGroups[] = $row->ug_group;
1036                         }
1037                 }
1038         }
1039
1040         /**
1041          * Clear various cached data stored in this object.
1042          * @param $reloadFrom \string Reload user and user_groups table data from a
1043          *   given source. May be "name", "id", "defaults", "session", or false for
1044          *   no reload.
1045          */
1046         function clearInstanceCache( $reloadFrom = false ) {
1047                 $this->mNewtalk = -1;
1048                 $this->mDatePreference = null;
1049                 $this->mBlockedby = -1; # Unset
1050                 $this->mHash = false;
1051                 $this->mSkin = null;
1052                 $this->mRights = null;
1053                 $this->mEffectiveGroups = null;
1054                 $this->mOptions = null;
1055
1056                 if ( $reloadFrom ) {
1057                         $this->mDataLoaded = false;
1058                         $this->mFrom = $reloadFrom;
1059                 }
1060         }
1061
1062         /**
1063          * Combine the language default options with any site-specific options
1064          * and add the default language variants.
1065          *
1066          * @return \type{\arrayof{\string}} Array of options
1067          */
1068         static function getDefaultOptions() {
1069                 global $wgNamespacesToBeSearchedDefault;
1070                 /**
1071                  * Site defaults will override the global/language defaults
1072                  */
1073                 global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1074                 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
1075
1076                 /**
1077                  * default language setting
1078                  */
1079                 $variant = $wgContLang->getDefaultVariant();
1080                 $defOpt['variant'] = $variant;
1081                 $defOpt['language'] = $variant;
1082                 foreach( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1083                         $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1084                 }
1085                 $defOpt['skin'] = $wgDefaultSkin;
1086
1087                 return $defOpt;
1088         }
1089
1090         /**
1091          * Get a given default option value.
1092          *
1093          * @param $opt \string Name of option to retrieve
1094          * @return \string Default option value
1095          */
1096         public static function getDefaultOption( $opt ) {
1097                 $defOpts = self::getDefaultOptions();
1098                 if( isset( $defOpts[$opt] ) ) {
1099                         return $defOpts[$opt];
1100                 } else {
1101                         return null;
1102                 }
1103         }
1104
1105
1106         /**
1107          * Get blocking information
1108          * @private
1109          * @param $bFromSlave \bool Whether to check the slave database first. To
1110          *                    improve performance, non-critical checks are done
1111          *                    against slaves. Check when actually saving should be
1112          *                    done against master.
1113          */
1114         function getBlockedStatus( $bFromSlave = true ) {
1115                 global $wgProxyWhitelist, $wgUser;
1116
1117                 if ( -1 != $this->mBlockedby ) {
1118                         wfDebug( "User::getBlockedStatus: already loaded.\n" );
1119                         return;
1120                 }
1121
1122                 wfProfileIn( __METHOD__ );
1123                 wfDebug( __METHOD__.": checking...\n" );
1124
1125                 // Initialize data...
1126                 // Otherwise something ends up stomping on $this->mBlockedby when
1127                 // things get lazy-loaded later, causing false positive block hits
1128                 // due to -1 !== 0. Probably session-related... Nothing should be
1129                 // overwriting mBlockedby, surely?
1130                 $this->load();
1131
1132                 $this->mBlockedby = 0;
1133                 $this->mHideName = 0;
1134                 $this->mAllowUsertalk = 0;
1135
1136                 # Check if we are looking at an IP or a logged-in user
1137                 if ( $this->isIP( $this->getName() ) ) {
1138                         $ip = $this->getName();
1139                 } else {
1140                         # Check if we are looking at the current user
1141                         # If we don't, and the user is logged in, we don't know about
1142                         # his IP / autoblock status, so ignore autoblock of current user's IP
1143                         if ( $this->getID() != $wgUser->getID() ) {
1144                                 $ip = '';
1145                         } else {
1146                                 # Get IP of current user
1147                                 $ip = wfGetIP();
1148                         }
1149                 }
1150
1151                 if ( $this->isAllowed( 'ipblock-exempt' ) ) {
1152                         # Exempt from all types of IP-block
1153                         $ip = '';
1154                 }
1155
1156                 # User/IP blocking
1157                 $this->mBlock = new Block();
1158                 $this->mBlock->fromMaster( !$bFromSlave );
1159                 if ( $this->mBlock->load( $ip , $this->mId ) ) {
1160                         wfDebug( __METHOD__ . ": Found block.\n" );
1161                         $this->mBlockedby = $this->mBlock->mBy;
1162                         if( $this->mBlockedby == 0 )
1163                                 $this->mBlockedby = $this->mBlock->mByName;
1164                         $this->mBlockreason = $this->mBlock->mReason;
1165                         $this->mHideName = $this->mBlock->mHideName;
1166                         $this->mAllowUsertalk = $this->mBlock->mAllowUsertalk;
1167                         if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1168                                 $this->spreadBlock();
1169                         }
1170                 } else {
1171                         // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1172                         // apply to users. Note that the existence of $this->mBlock is not used to
1173                         // check for edit blocks, $this->mBlockedby is instead.
1174                 }
1175
1176                 # Proxy blocking
1177                 if ( !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1178                         # Local list
1179                         if ( wfIsLocallyBlockedProxy( $ip ) ) {
1180                                 $this->mBlockedby = wfMsg( 'proxyblocker' );
1181                                 $this->mBlockreason = wfMsg( 'proxyblockreason' );
1182                         }
1183
1184                         # DNSBL
1185                         if ( !$this->mBlockedby && !$this->getID() ) {
1186                                 if ( $this->isDnsBlacklisted( $ip ) ) {
1187                                         $this->mBlockedby = wfMsg( 'sorbs' );
1188                                         $this->mBlockreason = wfMsg( 'sorbsreason' );
1189                                 }
1190                         }
1191                 }
1192
1193                 # Extensions
1194                 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1195
1196                 wfProfileOut( __METHOD__ );
1197         }
1198
1199         /**
1200          * Whether the given IP is in a DNS blacklist.
1201          *
1202          * @param $ip \string IP to check
1203          * @param $checkWhitelist Boolean: whether to check the whitelist first
1204          * @return \bool True if blacklisted.
1205          */
1206         function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1207                 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1208                         $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1209
1210                 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1211                         return false;
1212
1213                 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1214                         return false;
1215
1216                 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1217                 return $this->inDnsBlacklist( $ip, $urls );
1218         }
1219
1220         /**
1221          * Whether the given IP is in a given DNS blacklist.
1222          *
1223          * @param $ip \string IP to check
1224          * @param $bases \string or Array of Strings: URL of the DNS blacklist
1225          * @return \bool True if blacklisted.
1226          */
1227         function inDnsBlacklist( $ip, $bases ) {
1228                 wfProfileIn( __METHOD__ );
1229
1230                 $found = false;
1231                 // FIXME: IPv6 ???  (http://bugs.php.net/bug.php?id=33170)
1232                 if( IP::isIPv4( $ip ) ) {
1233                         # Reverse IP, bug 21255
1234                         $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1235
1236                         foreach( (array)$bases as $base ) {
1237                                 # Make hostname
1238                                 $host = "$ipReversed.$base";
1239
1240                                 # Send query
1241                                 $ipList = gethostbynamel( $host );
1242
1243                                 if( $ipList ) {
1244                                         wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1245                                         $found = true;
1246                                         break;
1247                                 } else {
1248                                         wfDebug( "Requested $host, not found in $base.\n" );
1249                                 }
1250                         }
1251                 }
1252
1253                 wfProfileOut( __METHOD__ );
1254                 return $found;
1255         }
1256
1257         /**
1258          * Is this user subject to rate limiting?
1259          *
1260          * @return \bool True if rate limited
1261          */
1262         public function isPingLimitable() {
1263                 global $wgRateLimitsExcludedGroups;
1264                 global $wgRateLimitsExcludedIPs;
1265                 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1266                         // Deprecated, but kept for backwards-compatibility config
1267                         return false;
1268                 }
1269                 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1270                         // No other good way currently to disable rate limits
1271                         // for specific IPs. :P
1272                         // But this is a crappy hack and should die.
1273                         return false;
1274                 }
1275                 return !$this->isAllowed('noratelimit');
1276         }
1277
1278         /**
1279          * Primitive rate limits: enforce maximum actions per time period
1280          * to put a brake on flooding.
1281          *
1282          * @note When using a shared cache like memcached, IP-address
1283          * last-hit counters will be shared across wikis.
1284          *
1285          * @param $action \string Action to enforce; 'edit' if unspecified
1286          * @return \bool True if a rate limiter was tripped
1287          */
1288         function pingLimiter( $action = 'edit' ) {
1289                 # Call the 'PingLimiter' hook
1290                 $result = false;
1291                 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1292                         return $result;
1293                 }
1294
1295                 global $wgRateLimits;
1296                 if( !isset( $wgRateLimits[$action] ) ) {
1297                         return false;
1298                 }
1299
1300                 # Some groups shouldn't trigger the ping limiter, ever
1301                 if( !$this->isPingLimitable() )
1302                         return false;
1303
1304                 global $wgMemc, $wgRateLimitLog;
1305                 wfProfileIn( __METHOD__ );
1306
1307                 $limits = $wgRateLimits[$action];
1308                 $keys = array();
1309                 $id = $this->getId();
1310                 $ip = wfGetIP();
1311                 $userLimit = false;
1312
1313                 if( isset( $limits['anon'] ) && $id == 0 ) {
1314                         $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1315                 }
1316
1317                 if( isset( $limits['user'] ) && $id != 0 ) {
1318                         $userLimit = $limits['user'];
1319                 }
1320                 if( $this->isNewbie() ) {
1321                         if( isset( $limits['newbie'] ) && $id != 0 ) {
1322                                 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1323                         }
1324                         if( isset( $limits['ip'] ) ) {
1325                                 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1326                         }
1327                         $matches = array();
1328                         if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1329                                 $subnet = $matches[1];
1330                                 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1331                         }
1332                 }
1333                 // Check for group-specific permissions
1334                 // If more than one group applies, use the group with the highest limit
1335                 foreach ( $this->getGroups() as $group ) {
1336                         if ( isset( $limits[$group] ) ) {
1337                                 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1338                                         $userLimit = $limits[$group];
1339                                 }
1340                         }
1341                 }
1342                 // Set the user limit key
1343                 if ( $userLimit !== false ) {
1344                         wfDebug( __METHOD__ . ": effective user limit: $userLimit\n" );
1345                         $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1346                 }
1347
1348                 $triggered = false;
1349                 foreach( $keys as $key => $limit ) {
1350                         list( $max, $period ) = $limit;
1351                         $summary = "(limit $max in {$period}s)";
1352                         $count = $wgMemc->get( $key );
1353                         // Already pinged?
1354                         if( $count ) {
1355                                 if( $count > $max ) {
1356                                         wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" );
1357                                         if( $wgRateLimitLog ) {
1358                                                 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1359                                         }
1360                                         $triggered = true;
1361                                 } else {
1362                                         wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1363                                 }
1364                         } else {
1365                                 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1366                                 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1367                         }
1368                         $wgMemc->incr( $key );
1369                 }
1370
1371                 wfProfileOut( __METHOD__ );
1372                 return $triggered;
1373         }
1374
1375         /**
1376          * Check if user is blocked
1377          *
1378          * @param $bFromSlave \bool Whether to check the slave database instead of the master
1379          * @return \bool True if blocked, false otherwise
1380          */
1381         function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1382                 wfDebug( "User::isBlocked: enter\n" );
1383                 $this->getBlockedStatus( $bFromSlave );
1384                 return $this->mBlockedby !== 0;
1385         }
1386
1387         /**
1388          * Check if user is blocked from editing a particular article
1389          *
1390          * @param $title      \string Title to check
1391          * @param $bFromSlave \bool   Whether to check the slave database instead of the master
1392          * @return \bool True if blocked, false otherwise
1393          */
1394         function isBlockedFrom( $title, $bFromSlave = false ) {
1395                 global $wgBlockAllowsUTEdit;
1396                 wfProfileIn( __METHOD__ );
1397                 wfDebug( __METHOD__ . ": enter\n" );
1398
1399                 wfDebug( __METHOD__ . ": asking isBlocked()\n" );
1400                 $blocked = $this->isBlocked( $bFromSlave );
1401                 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1402                 # If a user's name is suppressed, they cannot make edits anywhere
1403                 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
1404                   $title->getNamespace() == NS_USER_TALK ) {
1405                         $blocked = false;
1406                         wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1407                 }
1408
1409                 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1410
1411                 wfProfileOut( __METHOD__ );
1412                 return $blocked;
1413         }
1414
1415         /**
1416          * If user is blocked, return the name of the user who placed the block
1417          * @return \string name of blocker
1418          */
1419         function blockedBy() {
1420                 $this->getBlockedStatus();
1421                 return $this->mBlockedby;
1422         }
1423
1424         /**
1425          * If user is blocked, return the specified reason for the block
1426          * @return \string Blocking reason
1427          */
1428         function blockedFor() {
1429                 $this->getBlockedStatus();
1430                 return $this->mBlockreason;
1431         }
1432
1433         /**
1434          * If user is blocked, return the ID for the block
1435          * @return \int Block ID
1436          */
1437         function getBlockId() {
1438                 $this->getBlockedStatus();
1439                 return ( $this->mBlock ? $this->mBlock->mId : false );
1440         }
1441
1442         /**
1443          * Check if user is blocked on all wikis.
1444          * Do not use for actual edit permission checks!
1445          * This is intented for quick UI checks.
1446          *
1447          * @param $ip \type{\string} IP address, uses current client if none given
1448          * @return \type{\bool} True if blocked, false otherwise
1449          */
1450         function isBlockedGlobally( $ip = '' ) {
1451                 if( $this->mBlockedGlobally !== null ) {
1452                         return $this->mBlockedGlobally;
1453                 }
1454                 // User is already an IP?
1455                 if( IP::isIPAddress( $this->getName() ) ) {
1456                         $ip = $this->getName();
1457                 } else if( !$ip ) {
1458                         $ip = wfGetIP();
1459                 }
1460                 $blocked = false;
1461                 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1462                 $this->mBlockedGlobally = (bool)$blocked;
1463                 return $this->mBlockedGlobally;
1464         }
1465
1466         /**
1467          * Check if user account is locked
1468          *
1469          * @return \type{\bool} True if locked, false otherwise
1470          */
1471         function isLocked() {
1472                 if( $this->mLocked !== null ) {
1473                         return $this->mLocked;
1474                 }
1475                 global $wgAuth;
1476                 $authUser = $wgAuth->getUserInstance( $this );
1477                 $this->mLocked = (bool)$authUser->isLocked();
1478                 return $this->mLocked;
1479         }
1480
1481         /**
1482          * Check if user account is hidden
1483          *
1484          * @return \type{\bool} True if hidden, false otherwise
1485          */
1486         function isHidden() {
1487                 if( $this->mHideName !== null ) {
1488                         return $this->mHideName;
1489                 }
1490                 $this->getBlockedStatus();
1491                 if( !$this->mHideName ) {
1492                         global $wgAuth;
1493                         $authUser = $wgAuth->getUserInstance( $this );
1494                         $this->mHideName = (bool)$authUser->isHidden();
1495                 }
1496                 return $this->mHideName;
1497         }
1498
1499         /**
1500          * Get the user's ID.
1501          * @return Integer The user's ID; 0 if the user is anonymous or nonexistent
1502          */
1503         function getId() {
1504                 if( $this->mId === null and $this->mName !== null
1505                 and User::isIP( $this->mName ) ) {
1506                         // Special case, we know the user is anonymous
1507                         return 0;
1508                 } elseif( $this->mId === null ) {
1509                         // Don't load if this was initialized from an ID
1510                         $this->load();
1511                 }
1512                 return $this->mId;
1513         }
1514
1515         /**
1516          * Set the user and reload all fields according to a given ID
1517          * @param $v \int User ID to reload
1518          */
1519         function setId( $v ) {
1520                 $this->mId = $v;
1521                 $this->clearInstanceCache( 'id' );
1522         }
1523
1524         /**
1525          * Get the user name, or the IP of an anonymous user
1526          * @return \string User's name or IP address
1527          */
1528         function getName() {
1529                 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1530                         # Special case optimisation
1531                         return $this->mName;
1532                 } else {
1533                         $this->load();
1534                         if ( $this->mName === false ) {
1535                                 # Clean up IPs
1536                                 $this->mName = IP::sanitizeIP( wfGetIP() );
1537                         }
1538                         return $this->mName;
1539                 }
1540         }
1541
1542         /**
1543          * Set the user name.
1544          *
1545          * This does not reload fields from the database according to the given
1546          * name. Rather, it is used to create a temporary "nonexistent user" for
1547          * later addition to the database. It can also be used to set the IP
1548          * address for an anonymous user to something other than the current
1549          * remote IP.
1550          *
1551          * @note User::newFromName() has rougly the same function, when the named user
1552          * does not exist.
1553          * @param $str \string New user name to set
1554          */
1555         function setName( $str ) {
1556                 $this->load();
1557                 $this->mName = $str;
1558         }
1559
1560         /**
1561          * Get the user's name escaped by underscores.
1562          * @return \string Username escaped by underscores.
1563          */
1564         function getTitleKey() {
1565                 return str_replace( ' ', '_', $this->getName() );
1566         }
1567
1568         /**
1569          * Check if the user has new messages.
1570          * @return \bool True if the user has new messages
1571          */
1572         function getNewtalk() {
1573                 $this->load();
1574
1575                 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1576                 if( $this->mNewtalk === -1 ) {
1577                         $this->mNewtalk = false; # reset talk page status
1578
1579                         # Check memcached separately for anons, who have no
1580                         # entire User object stored in there.
1581                         if( !$this->mId ) {
1582                                 global $wgMemc;
1583                                 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1584                                 $newtalk = $wgMemc->get( $key );
1585                                 if( strval( $newtalk ) !== '' ) {
1586                                         $this->mNewtalk = (bool)$newtalk;
1587                                 } else {
1588                                         // Since we are caching this, make sure it is up to date by getting it
1589                                         // from the master
1590                                         $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1591                                         $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1592                                 }
1593                         } else {
1594                                 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1595                         }
1596                 }
1597
1598                 return (bool)$this->mNewtalk;
1599         }
1600
1601         /**
1602          * Return the talk page(s) this user has new messages on.
1603          * @return \type{\arrayof{\string}} Array of page URLs
1604          */
1605         function getNewMessageLinks() {
1606                 $talks = array();
1607                 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1608                         return $talks;
1609
1610                 if( !$this->getNewtalk() )
1611                         return array();
1612                 $up = $this->getUserPage();
1613                 $utp = $up->getTalkPage();
1614                 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1615         }
1616
1617         /**
1618          * Internal uncached check for new messages
1619          *
1620          * @see getNewtalk()
1621          * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1622          * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1623          * @param $fromMaster \bool true to fetch from the master, false for a slave
1624          * @return \bool True if the user has new messages
1625          * @private
1626          */
1627         function checkNewtalk( $field, $id, $fromMaster = false ) {
1628                 if ( $fromMaster ) {
1629                         $db = wfGetDB( DB_MASTER );
1630                 } else {
1631                         $db = wfGetDB( DB_SLAVE );
1632                 }
1633                 $ok = $db->selectField( 'user_newtalk', $field,
1634                         array( $field => $id ), __METHOD__ );
1635                 return $ok !== false;
1636         }
1637
1638         /**
1639          * Add or update the new messages flag
1640          * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1641          * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1642          * @return \bool True if successful, false otherwise
1643          * @private
1644          */
1645         function updateNewtalk( $field, $id ) {
1646                 $dbw = wfGetDB( DB_MASTER );
1647                 $dbw->insert( 'user_newtalk',
1648                         array( $field => $id ),
1649                         __METHOD__,
1650                         'IGNORE' );
1651                 if ( $dbw->affectedRows() ) {
1652                         wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
1653                         return true;
1654                 } else {
1655                         wfDebug( __METHOD__ . " already set ($field, $id)\n" );
1656                         return false;
1657                 }
1658         }
1659
1660         /**
1661          * Clear the new messages flag for the given user
1662          * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1663          * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1664          * @return \bool True if successful, false otherwise
1665          * @private
1666          */
1667         function deleteNewtalk( $field, $id ) {
1668                 $dbw = wfGetDB( DB_MASTER );
1669                 $dbw->delete( 'user_newtalk',
1670                         array( $field => $id ),
1671                         __METHOD__ );
1672                 if ( $dbw->affectedRows() ) {
1673                         wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
1674                         return true;
1675                 } else {
1676                         wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
1677                         return false;
1678                 }
1679         }
1680
1681         /**
1682          * Update the 'You have new messages!' status.
1683          * @param $val \bool Whether the user has new messages
1684          */
1685         function setNewtalk( $val ) {
1686                 if( wfReadOnly() ) {
1687                         return;
1688                 }
1689
1690                 $this->load();
1691                 $this->mNewtalk = $val;
1692
1693                 if( $this->isAnon() ) {
1694                         $field = 'user_ip';
1695                         $id = $this->getName();
1696                 } else {
1697                         $field = 'user_id';
1698                         $id = $this->getId();
1699                 }
1700                 global $wgMemc;
1701
1702                 if( $val ) {
1703                         $changed = $this->updateNewtalk( $field, $id );
1704                 } else {
1705                         $changed = $this->deleteNewtalk( $field, $id );
1706                 }
1707
1708                 if( $this->isAnon() ) {
1709                         // Anons have a separate memcached space, since
1710                         // user records aren't kept for them.
1711                         $key = wfMemcKey( 'newtalk', 'ip', $id );
1712                         $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1713                 }
1714                 if ( $changed ) {
1715                         $this->invalidateCache();
1716                 }
1717         }
1718
1719         /**
1720          * Generate a current or new-future timestamp to be stored in the
1721          * user_touched field when we update things.
1722          * @return \string Timestamp in TS_MW format
1723          */
1724         private static function newTouchedTimestamp() {
1725                 global $wgClockSkewFudge;
1726                 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1727         }
1728
1729         /**
1730          * Clear user data from memcached.
1731          * Use after applying fun updates to the database; caller's
1732          * responsibility to update user_touched if appropriate.
1733          *
1734          * Called implicitly from invalidateCache() and saveSettings().
1735          */
1736         private function clearSharedCache() {
1737                 $this->load();
1738                 if( $this->mId ) {
1739                         global $wgMemc;
1740                         $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1741                 }
1742         }
1743
1744         /**
1745          * Immediately touch the user data cache for this account.
1746          * Updates user_touched field, and removes account data from memcached
1747          * for reload on the next hit.
1748          */
1749         function invalidateCache() {
1750                 if( wfReadOnly() ) {
1751                         return;
1752                 }
1753                 $this->load();
1754                 if( $this->mId ) {
1755                         $this->mTouched = self::newTouchedTimestamp();
1756
1757                         $dbw = wfGetDB( DB_MASTER );
1758                         $dbw->update( 'user',
1759                                 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1760                                 array( 'user_id' => $this->mId ),
1761                                 __METHOD__ );
1762
1763                         $this->clearSharedCache();
1764                 }
1765         }
1766
1767         /**
1768          * Validate the cache for this account.
1769          * @param $timestamp \string A timestamp in TS_MW format
1770          */
1771         function validateCache( $timestamp ) {
1772                 $this->load();
1773                 return ( $timestamp >= $this->mTouched );
1774         }
1775
1776         /**
1777          * Get the user touched timestamp
1778          */
1779         function getTouched() {
1780                 $this->load();
1781                 return $this->mTouched;
1782         }
1783
1784         /**
1785          * Set the password and reset the random token.
1786          * Calls through to authentication plugin if necessary;
1787          * will have no effect if the auth plugin refuses to
1788          * pass the change through or if the legal password
1789          * checks fail.
1790          *
1791          * As a special case, setting the password to null
1792          * wipes it, so the account cannot be logged in until
1793          * a new password is set, for instance via e-mail.
1794          *
1795          * @param $str \string New password to set
1796          * @throws PasswordError on failure
1797          */
1798         function setPassword( $str ) {
1799                 global $wgAuth;
1800
1801                 if( $str !== null ) {
1802                         if( !$wgAuth->allowPasswordChange() ) {
1803                                 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1804                         }
1805
1806                         if( !$this->isValidPassword( $str ) ) {
1807                                 global $wgMinimalPasswordLength;
1808                                 $valid = $this->getPasswordValidity( $str );
1809                                 throw new PasswordError( wfMsgExt( $valid, array( 'parsemag' ),
1810                                         $wgMinimalPasswordLength ) );
1811                         }
1812                 }
1813
1814                 if( !$wgAuth->setPassword( $this, $str ) ) {
1815                         throw new PasswordError( wfMsg( 'externaldberror' ) );
1816                 }
1817
1818                 $this->setInternalPassword( $str );
1819
1820                 return true;
1821         }
1822
1823         /**
1824          * Set the password and reset the random token unconditionally.
1825          *
1826          * @param $str \string New password to set
1827          */
1828         function setInternalPassword( $str ) {
1829                 $this->load();
1830                 $this->setToken();
1831
1832                 if( $str === null ) {
1833                         // Save an invalid hash...
1834                         $this->mPassword = '';
1835                 } else {
1836                         $this->mPassword = self::crypt( $str );
1837                 }
1838                 $this->mNewpassword = '';
1839                 $this->mNewpassTime = null;
1840         }
1841
1842         /**
1843          * Get the user's current token.
1844          * @param $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
1845          * @return \string Token
1846          */
1847         function getToken( $forceCreation = true ) {
1848                 $this->load();
1849                 if ( !$this->mToken && $forceCreation ) {
1850                         $this->setToken();
1851                 }
1852                 return $this->mToken;
1853         }
1854
1855         /**
1856          * Set the random token (used for persistent authentication)
1857          * Called from loadDefaults() among other places.
1858          *
1859          * @param $token \string If specified, set the token to this value
1860          * @private
1861          */
1862         function setToken( $token = false ) {
1863                 global $wgSecretKey, $wgProxyKey;
1864                 $this->load();
1865                 if ( !$token ) {
1866                         $this->mToken = MWCryptRand::generateHex( USER_TOKEN_LENGTH );
1867                 } else {
1868                         $this->mToken = $token;
1869                 }
1870         }
1871
1872         /**
1873          * Set the cookie password
1874          *
1875          * @param $str \string New cookie password
1876          * @private
1877          */
1878         function setCookiePassword( $str ) {
1879                 $this->load();
1880                 $this->mCookiePassword = md5( $str );
1881         }
1882
1883         /**
1884          * Set the password for a password reminder or new account email
1885          *
1886          * @param $str \string New password to set
1887          * @param $throttle \bool If true, reset the throttle timestamp to the present
1888          */
1889         function setNewpassword( $str, $throttle = true ) {
1890                 $this->load();
1891                 $this->mNewpassword = self::crypt( $str );
1892                 if ( $throttle ) {
1893                         $this->mNewpassTime = wfTimestampNow();
1894                 }
1895         }
1896
1897         /**
1898          * Has password reminder email been sent within the last
1899          * $wgPasswordReminderResendTime hours?
1900          * @return \bool True or false
1901          */
1902         function isPasswordReminderThrottled() {
1903                 global $wgPasswordReminderResendTime;
1904                 $this->load();
1905                 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1906                         return false;
1907                 }
1908                 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1909                 return time() < $expiry;
1910         }
1911
1912         /**
1913          * Get the user's e-mail address
1914          * @return \string User's email address
1915          */
1916         function getEmail() {
1917                 $this->load();
1918                 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1919                 return $this->mEmail;
1920         }
1921
1922         /**
1923          * Get the timestamp of the user's e-mail authentication
1924          * @return \string TS_MW timestamp
1925          */
1926         function getEmailAuthenticationTimestamp() {
1927                 $this->load();
1928                 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1929                 return $this->mEmailAuthenticated;
1930         }
1931
1932         /**
1933          * Set the user's e-mail address
1934          * @param $str \string New e-mail address
1935          */
1936         function setEmail( $str ) {
1937                 $this->load();
1938                 $this->mEmail = $str;
1939                 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1940         }
1941
1942         /**
1943          * Get the user's real name
1944          * @return \string User's real name
1945          */
1946         function getRealName() {
1947                 $this->load();
1948                 return $this->mRealName;
1949         }
1950
1951         /**
1952          * Set the user's real name
1953          * @param $str \string New real name
1954          */
1955         function setRealName( $str ) {
1956                 $this->load();
1957                 $this->mRealName = $str;
1958         }
1959
1960         /**
1961          * Get the user's current setting for a given option.
1962          *
1963          * @param $oname \string The option to check
1964          * @param $defaultOverride \string A default value returned if the option does not exist
1965          * @return \string User's current value for the option
1966          * @see getBoolOption()
1967          * @see getIntOption()
1968          */
1969         function getOption( $oname, $defaultOverride = null ) {
1970                 $this->loadOptions();
1971
1972                 if ( is_null( $this->mOptions ) ) {
1973                         if($defaultOverride != '') {
1974                                 return $defaultOverride;
1975                         }
1976                         $this->mOptions = User::getDefaultOptions();
1977                 }
1978
1979                 if ( array_key_exists( $oname, $this->mOptions ) ) {
1980                         return $this->mOptions[$oname];
1981                 } else {
1982                         return $defaultOverride;
1983                 }
1984         }
1985
1986         /**
1987          * Get all user's options
1988          *
1989          * @return array
1990          */
1991         public function getOptions() {
1992                 $this->loadOptions();
1993                 return $this->mOptions;
1994         }
1995
1996         /**
1997          * Get the user's current setting for a given option, as a boolean value.
1998          *
1999          * @param $oname \string The option to check
2000          * @return \bool User's current value for the option
2001          * @see getOption()
2002          */
2003         function getBoolOption( $oname ) {
2004                 return (bool)$this->getOption( $oname );
2005         }
2006
2007
2008         /**
2009          * Get the user's current setting for a given option, as a boolean value.
2010          *
2011          * @param $oname \string The option to check
2012          * @param $defaultOverride \int A default value returned if the option does not exist
2013          * @return \int User's current value for the option
2014          * @see getOption()
2015          */
2016         function getIntOption( $oname, $defaultOverride=0 ) {
2017                 $val = $this->getOption( $oname );
2018                 if( $val == '' ) {
2019                         $val = $defaultOverride;
2020                 }
2021                 return intval( $val );
2022         }
2023
2024         /**
2025          * Set the given option for a user.
2026          *
2027          * @param $oname \string The option to set
2028          * @param $val \mixed New value to set
2029          */
2030         function setOption( $oname, $val ) {
2031                 $this->load();
2032                 $this->loadOptions();
2033
2034                 if ( $oname == 'skin' ) {
2035                         # Clear cached skin, so the new one displays immediately in Special:Preferences
2036                         $this->mSkin = null;
2037                 }
2038
2039                 // Explicitly NULL values should refer to defaults
2040                 global $wgDefaultUserOptions;
2041                 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
2042                         $val = $wgDefaultUserOptions[$oname];
2043                 }
2044
2045                 $this->mOptions[$oname] = $val;
2046         }
2047
2048         /**
2049          * Reset all options to the site defaults
2050          */
2051         function resetOptions() {
2052                 $this->mOptions = User::getDefaultOptions();
2053         }
2054
2055         /**
2056          * Get the user's preferred date format.
2057          * @return \string User's preferred date format
2058          */
2059         function getDatePreference() {
2060                 // Important migration for old data rows
2061                 if ( is_null( $this->mDatePreference ) ) {
2062                         global $wgLang;
2063                         $value = $this->getOption( 'date' );
2064                         $map = $wgLang->getDatePreferenceMigrationMap();
2065                         if ( isset( $map[$value] ) ) {
2066                                 $value = $map[$value];
2067                         }
2068                         $this->mDatePreference = $value;
2069                 }
2070                 return $this->mDatePreference;
2071         }
2072
2073         /**
2074          * Get the user preferred stub threshold
2075          */
2076         function getStubThreshold() {
2077                 global $wgMaxArticleSize; # Maximum article size, in Kb
2078                 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2079                 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2080                         # If they have set an impossible value, disable the preference
2081                         # so we can use the parser cache again.
2082                         $threshold = 0;
2083                 }
2084                 return $threshold;
2085         }
2086
2087         /**
2088          * Get the permissions this user has.
2089          * @return \type{\arrayof{\string}} Array of permission names
2090          */
2091         function getRights() {
2092                 if ( is_null( $this->mRights ) ) {
2093                         $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2094                         wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2095                         // Force reindexation of rights when a hook has unset one of them
2096                         $this->mRights = array_values( $this->mRights );
2097                 }
2098                 return $this->mRights;
2099         }
2100
2101         /**
2102          * Get the list of explicit group memberships this user has.
2103          * The implicit * and user groups are not included.
2104          * @return \type{\arrayof{\string}} Array of internal group names
2105          */
2106         function getGroups() {
2107                 $this->load();
2108                 return $this->mGroups;
2109         }
2110
2111         /**
2112          * Get the list of implicit group memberships this user has.
2113          * This includes all explicit groups, plus 'user' if logged in,
2114          * '*' for all accounts and autopromoted groups
2115          * @param $recache \bool Whether to avoid the cache
2116          * @return \type{\arrayof{\string}} Array of internal group names
2117          */
2118         function getEffectiveGroups( $recache = false ) {
2119                 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2120                         wfProfileIn( __METHOD__ );
2121                         $this->mEffectiveGroups = $this->getGroups();
2122                         $this->mEffectiveGroups[] = '*';
2123                         if( $this->getId() ) {
2124                                 $this->mEffectiveGroups[] = 'user';
2125
2126                                 $this->mEffectiveGroups = array_unique( array_merge(
2127                                         $this->mEffectiveGroups,
2128                                         Autopromote::getAutopromoteGroups( $this )
2129                                 ) );
2130
2131                                 # Hook for additional groups
2132                                 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2133                         }
2134                         wfProfileOut( __METHOD__ );
2135                 }
2136                 return $this->mEffectiveGroups;
2137         }
2138
2139         /**
2140          * Get the user's edit count.
2141          * @return \int User'e edit count
2142          */
2143         function getEditCount() {
2144                 if( $this->getId() ) {
2145                         if ( !isset( $this->mEditCount ) ) {
2146                                 /* Populate the count, if it has not been populated yet */
2147                                 $this->mEditCount = User::edits( $this->mId );
2148                         }
2149                         return $this->mEditCount;
2150                 } else {
2151                         /* nil */
2152                         return null;
2153                 }
2154         }
2155
2156         /**
2157          * Add the user to the given group.
2158          * This takes immediate effect.
2159          * @param $group \string Name of the group to add
2160          */
2161         function addGroup( $group ) {
2162                 $dbw = wfGetDB( DB_MASTER );
2163                 if( $this->getId() ) {
2164                         $dbw->insert( 'user_groups',
2165                                 array(
2166                                         'ug_user'  => $this->getID(),
2167                                         'ug_group' => $group,
2168                                 ),
2169                                 __METHOD__,
2170                                 array( 'IGNORE' ) );
2171                 }
2172
2173                 $this->loadGroups();
2174                 $this->mGroups[] = $group;
2175                 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2176
2177                 $this->invalidateCache();
2178         }
2179
2180         /**
2181          * Remove the user from the given group.
2182          * This takes immediate effect.
2183          * @param $group \string Name of the group to remove
2184          */
2185         function removeGroup( $group ) {
2186                 $this->load();
2187                 $dbw = wfGetDB( DB_MASTER );
2188                 $dbw->delete( 'user_groups',
2189                         array(
2190                                 'ug_user'  => $this->getID(),
2191                                 'ug_group' => $group,
2192                         ), __METHOD__ );
2193
2194                 $this->loadGroups();
2195                 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2196                 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2197
2198                 $this->invalidateCache();
2199         }
2200
2201         /**
2202          * Get whether the user is logged in
2203          * @return \bool True or false
2204          */
2205         function isLoggedIn() {
2206                 return $this->getID() != 0;
2207         }
2208
2209         /**
2210          * Get whether the user is anonymous
2211          * @return \bool True or false
2212          */
2213         function isAnon() {
2214                 return !$this->isLoggedIn();
2215         }
2216
2217         /**
2218          * Get whether the user is a bot
2219          * @return \bool True or false
2220          * @deprecated
2221          */
2222         function isBot() {
2223                 wfDeprecated( __METHOD__ );
2224                 return $this->isAllowed( 'bot' );
2225         }
2226
2227         /**
2228          * Check if user is allowed to access a feature / make an action
2229          * @param $action \string action to be checked
2230          * @return Boolean: True if action is allowed, else false
2231          */
2232         function isAllowed( $action = '' ) {
2233                 if ( $action === '' ) {
2234                         return true; // In the spirit of DWIM
2235                 }
2236                 # Patrolling may not be enabled
2237                 if( $action === 'patrol' || $action === 'autopatrol' ) {
2238                         global $wgUseRCPatrol, $wgUseNPPatrol;
2239                         if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2240                                 return false;
2241                 }
2242                 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2243                 # by misconfiguration: 0 == 'foo'
2244                 return in_array( $action, $this->getRights(), true );
2245         }
2246
2247         /**
2248          * Check whether to enable recent changes patrol features for this user
2249          * @return Boolean: True or false
2250          */
2251         public function useRCPatrol() {
2252                 global $wgUseRCPatrol;
2253                 return( $wgUseRCPatrol && ( $this->isAllowed( 'patrol' ) || $this->isAllowed( 'patrolmarks' ) ) );
2254         }
2255
2256         /**
2257          * Check whether to enable new pages patrol features for this user
2258          * @return \bool True or false
2259          */
2260         public function useNPPatrol() {
2261                 global $wgUseRCPatrol, $wgUseNPPatrol;
2262                 return( ( $wgUseRCPatrol || $wgUseNPPatrol ) && ( $this->isAllowed( 'patrol' ) || $this->isAllowed( 'patrolmarks' ) ) );
2263         }
2264
2265         /**
2266          * Get the current skin, loading it if required, and setting a title
2267          * @param $t Title: the title to use in the skin
2268          * @return Skin The current skin
2269          * @todo FIXME : need to check the old failback system [AV]
2270          */
2271         function getSkin( $t = null ) {
2272                 if( !$this->mSkin ) {
2273                         global $wgOut;
2274                         $this->mSkin = $this->createSkinObject();
2275                         $this->mSkin->setTitle( $wgOut->getTitle() );
2276                 }
2277                 if ( $t && ( !$this->mSkin->getTitle() || !$t->equals( $this->mSkin->getTitle() ) ) ) {
2278                         $skin = $this->createSkinObject();
2279                         $skin->setTitle( $t );
2280                         return $skin;
2281                 } else {
2282                         return $this->mSkin;
2283                 }
2284         }
2285
2286         // Creates a Skin object, for getSkin()
2287         private function createSkinObject() {
2288                 wfProfileIn( __METHOD__ );
2289
2290                 global $wgHiddenPrefs;
2291                 if( !in_array( 'skin', $wgHiddenPrefs ) ) {
2292                         global $wgRequest;
2293                         # get the user skin
2294                         $userSkin = $this->getOption( 'skin' );
2295                         $userSkin = $wgRequest->getVal( 'useskin', $userSkin );
2296                 } else {
2297                         # if we're not allowing users to override, then use the default
2298                         global $wgDefaultSkin;
2299                         $userSkin = $wgDefaultSkin;
2300                 }
2301
2302                 $skin = Skin::newFromKey( $userSkin );
2303                 wfProfileOut( __METHOD__ );
2304
2305                 return $skin;
2306         }
2307
2308         /**
2309          * Check the watched status of an article.
2310          * @param $title \type{Title} Title of the article to look at
2311          * @return \bool True if article is watched
2312          */
2313         function isWatched( $title ) {
2314                 $wl = WatchedItem::fromUserTitle( $this, $title );
2315                 return $wl->isWatched();
2316         }
2317
2318         /**
2319          * Watch an article.
2320          * @param $title \type{Title} Title of the article to look at
2321          */
2322         function addWatch( $title ) {
2323                 $wl = WatchedItem::fromUserTitle( $this, $title );
2324                 $wl->addWatch();
2325                 $this->invalidateCache();
2326         }
2327
2328         /**
2329          * Stop watching an article.
2330          * @param $title \type{Title} Title of the article to look at
2331          */
2332         function removeWatch( $title ) {
2333                 $wl = WatchedItem::fromUserTitle( $this, $title );
2334                 $wl->removeWatch();
2335                 $this->invalidateCache();
2336         }
2337
2338         /**
2339          * Clear the user's notification timestamp for the given title.
2340          * If e-notif e-mails are on, they will receive notification mails on
2341          * the next change of the page if it's watched etc.
2342          * @param $title \type{Title} Title of the article to look at
2343          */
2344         function clearNotification( &$title ) {
2345                 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2346
2347                 # Do nothing if the database is locked to writes
2348                 if( wfReadOnly() ) {
2349                         return;
2350                 }
2351
2352                 if( $title->getNamespace() == NS_USER_TALK &&
2353                         $title->getText() == $this->getName() ) {
2354                         if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2355                                 return;
2356                         $this->setNewtalk( false );
2357                 }
2358
2359                 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2360                         return;
2361                 }
2362
2363                 if( $this->isAnon() ) {
2364                         // Nothing else to do...
2365                         return;
2366                 }
2367
2368                 // Only update the timestamp if the page is being watched.
2369                 // The query to find out if it is watched is cached both in memcached and per-invocation,
2370                 // and when it does have to be executed, it can be on a slave
2371                 // If this is the user's newtalk page, we always update the timestamp
2372                 if( $title->getNamespace() == NS_USER_TALK &&
2373                         $title->getText() == $wgUser->getName() )
2374                 {
2375                         $watched = true;
2376                 } elseif ( $this->getId() == $wgUser->getId() ) {
2377                         $watched = $title->userIsWatching();
2378                 } else {
2379                         $watched = true;
2380                 }
2381
2382                 // If the page is watched by the user (or may be watched), update the timestamp on any
2383                 // any matching rows
2384                 if ( $watched ) {
2385                         $dbw = wfGetDB( DB_MASTER );
2386                         $dbw->update( 'watchlist',
2387                                         array( /* SET */
2388                                                 'wl_notificationtimestamp' => null
2389                                         ), array( /* WHERE */
2390                                                 'wl_title' => $title->getDBkey(),
2391                                                 'wl_namespace' => $title->getNamespace(),
2392                                                 'wl_user' => $this->getID()
2393                                         ), __METHOD__
2394                         );
2395                 }
2396         }
2397
2398         /**
2399          * Resets all of the given user's page-change notification timestamps.
2400          * If e-notif e-mails are on, they will receive notification mails on
2401          * the next change of any watched page.
2402          *
2403          * @param $currentUser \int User ID
2404          */
2405         function clearAllNotifications( $currentUser ) {
2406                 global $wgUseEnotif, $wgShowUpdatedMarker;
2407                 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2408                         $this->setNewtalk( false );
2409                         return;
2410                 }
2411                 if( $currentUser != 0 )  {
2412                         $dbw = wfGetDB( DB_MASTER );
2413                         $dbw->update( 'watchlist',
2414                                 array( /* SET */
2415                                         'wl_notificationtimestamp' => null
2416                                 ), array( /* WHERE */
2417                                         'wl_user' => $currentUser
2418                                 ), __METHOD__
2419                         );
2420                 #       We also need to clear here the "you have new message" notification for the own user_talk page
2421                 #       This is cleared one page view later in Article::viewUpdates();
2422                 }
2423         }
2424
2425         /**
2426          * Set this user's options from an encoded string
2427          * @param $str \string Encoded options to import
2428          * @private
2429          */
2430         function decodeOptions( $str ) {
2431                 if( !$str )
2432                         return;
2433
2434                 $this->mOptionsLoaded = true;
2435                 $this->mOptionOverrides = array();
2436
2437                 // If an option is not set in $str, use the default value
2438                 $this->mOptions = self::getDefaultOptions();
2439
2440                 $a = explode( "\n", $str );
2441                 foreach ( $a as $s ) {
2442                         $m = array();
2443                         if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2444                                 $this->mOptions[$m[1]] = $m[2];
2445                                 $this->mOptionOverrides[$m[1]] = $m[2];
2446                         }
2447                 }
2448         }
2449
2450         /**
2451          * Set a cookie on the user's client. Wrapper for
2452          * WebResponse::setCookie
2453          * @param $name \string Name of the cookie to set
2454          * @param $value \string Value to set
2455          * @param $exp \int Expiration time, as a UNIX time value;
2456          *                   if 0 or not specified, use the default $wgCookieExpiration
2457          */
2458         protected function setCookie( $name, $value, $exp = 0 ) {
2459                 global $wgRequest;
2460                 $wgRequest->response()->setcookie( $name, $value, $exp );
2461         }
2462
2463         /**
2464          * Clear a cookie on the user's client
2465          * @param $name \string Name of the cookie to clear
2466          */
2467         protected function clearCookie( $name ) {
2468                 $this->setCookie( $name, '', time() - 86400 );
2469         }
2470
2471         /**
2472          * Set the default cookies for this session on the user's client.
2473          */
2474         function setCookies() {
2475                 $this->load();
2476                 if ( 0 == $this->mId ) return;
2477                 if ( !$this->mToken ) {
2478                         // When token is empty or NULL generate a new one and then save it to the database
2479                         // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
2480                         // Simply by setting every cell in the user_token column to NULL and letting them be
2481                         // regenerated as users log back into the wiki.
2482                         $this->setToken();
2483                         $this->saveSettings();
2484                 }
2485                 $session = array(
2486                         'wsUserID' => $this->mId,
2487                         'wsToken' => $this->mToken,
2488                         'wsUserName' => $this->getName()
2489                 );
2490                 $cookies = array(
2491                         'UserID' => $this->mId,
2492                         'UserName' => $this->getName(),
2493                 );
2494                 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2495                         $cookies['Token'] = $this->mToken;
2496                 } else {
2497                         $cookies['Token'] = false;
2498                 }
2499
2500                 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2501                 #check for null, since the hook could cause a null value
2502                 if ( !is_null( $session ) && isset( $_SESSION ) ){
2503                         $_SESSION = $session + $_SESSION;
2504                 }
2505                 foreach ( $cookies as $name => $value ) {
2506                         if ( $value === false ) {
2507                                 $this->clearCookie( $name );
2508                         } else {
2509                                 $this->setCookie( $name, $value );
2510                         }
2511                 }
2512         }
2513
2514         /**
2515          * Log this user out.
2516          */
2517         function logout() {
2518                 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2519                         $this->doLogout();
2520                 }
2521         }
2522
2523         /**
2524          * Clear the user's cookies and session, and reset the instance cache.
2525          * @private
2526          * @see logout()
2527          */
2528         function doLogout() {
2529                 $this->clearInstanceCache( 'defaults' );
2530
2531                 $_SESSION['wsUserID'] = 0;
2532
2533                 $this->clearCookie( 'UserID' );
2534                 $this->clearCookie( 'Token' );
2535
2536                 # Remember when user logged out, to prevent seeing cached pages
2537                 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2538         }
2539
2540         /**
2541          * Save this user's settings into the database.
2542          * @todo Only rarely do all these fields need to be set!
2543          */
2544         function saveSettings() {
2545                 $this->load();
2546                 if ( wfReadOnly() ) { return; }
2547                 if ( 0 == $this->mId ) { return; }
2548
2549                 $this->mTouched = self::newTouchedTimestamp();
2550
2551                 $dbw = wfGetDB( DB_MASTER );
2552                 $dbw->update( 'user',
2553                         array( /* SET */
2554                                 'user_name' => $this->mName,
2555                                 'user_password' => $this->mPassword,
2556                                 'user_newpassword' => $this->mNewpassword,
2557                                 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2558                                 'user_real_name' => $this->mRealName,
2559                                 'user_email' => $this->mEmail,
2560                                 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2561                                 'user_options' => '',
2562                                 'user_touched' => $dbw->timestamp( $this->mTouched ),
2563                                 'user_token' => strval( $this->mToken ),
2564                                 'user_email_token' => $this->mEmailToken,
2565                                 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2566                         ), array( /* WHERE */
2567                                 'user_id' => $this->mId
2568                         ), __METHOD__
2569                 );
2570
2571                 $this->saveOptions();
2572
2573                 wfRunHooks( 'UserSaveSettings', array( $this ) );
2574                 $this->clearSharedCache();
2575                 $this->getUserPage()->invalidateCache();
2576         }
2577
2578         /**
2579          * If only this user's username is known, and it exists, return the user ID.
2580          */
2581         function idForName() {
2582                 $s = trim( $this->getName() );
2583                 if ( $s === '' ) return 0;
2584
2585                 $dbr = wfGetDB( DB_SLAVE );
2586                 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2587                 if ( $id === false ) {
2588                         $id = 0;
2589                 }
2590                 return $id;
2591         }
2592
2593         /**
2594          * Add a user to the database, return the user object
2595          *
2596          * @param $name \string Username to add
2597          * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2598          *   - password             The user's password. Password logins will be disabled if this is omitted.
2599          *   - newpassword          A temporary password mailed to the user
2600          *   - email                The user's email address
2601          *   - email_authenticated  The email authentication timestamp
2602          *   - real_name            The user's real name
2603          *   - options              An associative array of non-default options
2604          *   - token                Random authentication token. Do not set.
2605          *   - registration         Registration timestamp. Do not set.
2606          *
2607          * @return \type{User} A new User object, or null if the username already exists
2608          */
2609         static function createNew( $name, $params = array() ) {
2610                 $user = new User;
2611                 $user->load();
2612                 if ( isset( $params['options'] ) ) {
2613                         $user->mOptions = $params['options'] + (array)$user->mOptions;
2614                         unset( $params['options'] );
2615                 }
2616                 $dbw = wfGetDB( DB_MASTER );
2617                 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2618
2619                 $fields = array(
2620                         'user_id' => $seqVal,
2621                         'user_name' => $name,
2622                         'user_password' => $user->mPassword,
2623                         'user_newpassword' => $user->mNewpassword,
2624                         'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
2625                         'user_email' => $user->mEmail,
2626                         'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2627                         'user_real_name' => $user->mRealName,
2628                         'user_options' => '',
2629                         'user_token' => strval( $user->mToken ),
2630                         'user_registration' => $dbw->timestamp( $user->mRegistration ),
2631                         'user_editcount' => 0,
2632                 );
2633                 foreach ( $params as $name => $value ) {
2634                         $fields["user_$name"] = $value;
2635                 }
2636                 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2637                 if ( $dbw->affectedRows() ) {
2638                         $newUser = User::newFromId( $dbw->insertId() );
2639                 } else {
2640                         $newUser = null;
2641                 }
2642                 return $newUser;
2643         }
2644
2645         /**
2646          * Add this existing user object to the database
2647          */
2648         function addToDatabase() {
2649                 $this->load();
2650                 $dbw = wfGetDB( DB_MASTER );
2651                 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2652                 $dbw->insert( 'user',
2653                         array(
2654                                 'user_id' => $seqVal,
2655                                 'user_name' => $this->mName,
2656                                 'user_password' => $this->mPassword,
2657                                 'user_newpassword' => $this->mNewpassword,
2658                                 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2659                                 'user_email' => $this->mEmail,
2660                                 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2661                                 'user_real_name' => $this->mRealName,
2662                                 'user_options' => '',
2663                                 'user_token' => strval( $this->mToken ),
2664                                 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2665                                 'user_editcount' => 0,
2666                         ), __METHOD__
2667                 );
2668                 $this->mId = $dbw->insertId();
2669
2670                 // Clear instance cache other than user table data, which is already accurate
2671                 $this->clearInstanceCache();
2672
2673                 $this->saveOptions();
2674         }
2675
2676         /**
2677          * If this (non-anonymous) user is blocked, block any IP address
2678          * they've successfully logged in from.
2679          */
2680         function spreadBlock() {
2681                 wfDebug( __METHOD__ . "()\n" );
2682                 $this->load();
2683                 if ( $this->mId == 0 ) {
2684                         return;
2685                 }
2686
2687                 $userblock = Block::newFromDB( '', $this->mId );
2688                 if ( !$userblock ) {
2689                         return;
2690                 }
2691
2692                 $userblock->doAutoblock( wfGetIP() );
2693         }
2694
2695         /**
2696          * Generate a string which will be different for any combination of
2697          * user options which would produce different parser output.
2698          * This will be used as part of the hash key for the parser cache,
2699          * so users with the same options can share the same cached data
2700          * safely.
2701          *
2702          * Extensions which require it should install 'PageRenderingHash' hook,
2703          * which will give them a chance to modify this key based on their own
2704          * settings.
2705          *
2706          * @deprecated use the ParserOptions object to get the relevant options
2707          * @return \string Page rendering hash
2708          */
2709         function getPageRenderingHash() {
2710                 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2711                 if( $this->mHash ){
2712                         return $this->mHash;
2713                 }
2714                 wfDeprecated( __METHOD__ );
2715
2716                 // stubthreshold is only included below for completeness,
2717                 // since it disables the parser cache, its value will always
2718                 // be 0 when this function is called by parsercache.
2719
2720                 $confstr =        $this->getOption( 'math' );
2721                 $confstr .= '!' . $this->getStubThreshold();
2722                 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
2723                         $confstr .= '!' . $this->getDatePreference();
2724                 }
2725                 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ? '1' : '' );
2726                 $confstr .= '!' . $wgLang->getCode();
2727                 $confstr .= '!' . $this->getOption( 'thumbsize' );
2728                 // add in language specific options, if any
2729                 $extra = $wgContLang->getExtraHashOptions();
2730                 $confstr .= $extra;
2731
2732                 // Since the skin could be overloading link(), it should be
2733                 // included here but in practice, none of our skins do that.
2734
2735                 $confstr .= $wgRenderHashAppend;
2736
2737                 // Give a chance for extensions to modify the hash, if they have
2738                 // extra options or other effects on the parser cache.
2739                 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2740
2741                 // Make it a valid memcached key fragment
2742                 $confstr = str_replace( ' ', '_', $confstr );
2743                 $this->mHash = $confstr;
2744                 return $confstr;
2745         }
2746
2747         /**
2748          * Get whether the user is explicitly blocked from account creation.
2749          * @return \bool True if blocked
2750          */
2751         function isBlockedFromCreateAccount() {
2752                 $this->getBlockedStatus();
2753                 return $this->mBlock && $this->mBlock->mCreateAccount;
2754         }
2755
2756         /**
2757          * Get whether the user is blocked from using Special:Emailuser.
2758          * @return Boolean: True if blocked
2759          */
2760         function isBlockedFromEmailuser() {
2761                 $this->getBlockedStatus();
2762                 return $this->mBlock && $this->mBlock->mBlockEmail;
2763         }
2764
2765         /**
2766          * Get whether the user is allowed to create an account.
2767          * @return Boolean: True if allowed
2768          */
2769         function isAllowedToCreateAccount() {
2770                 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2771         }
2772
2773         /**
2774          * Get this user's personal page title.
2775          *
2776          * @return Title: User's personal page title
2777          */
2778         function getUserPage() {
2779                 return Title::makeTitle( NS_USER, $this->getName() );
2780         }
2781
2782         /**
2783          * Get this user's talk page title.
2784          *
2785          * @return Title: User's talk page title
2786          */
2787         function getTalkPage() {
2788                 $title = $this->getUserPage();
2789                 return $title->getTalkPage();
2790         }
2791
2792         /**
2793          * Get the maximum valid user ID.
2794          * @return Integer: User ID
2795          * @static
2796          */
2797         function getMaxID() {
2798                 static $res; // cache
2799
2800                 if ( isset( $res ) ) {
2801                         return $res;
2802                 } else {
2803                         $dbr = wfGetDB( DB_SLAVE );
2804                         return $res = $dbr->selectField( 'user', 'max(user_id)', false, __METHOD__ );
2805                 }
2806         }
2807
2808         /**
2809          * Determine whether the user is a newbie. Newbies are either
2810          * anonymous IPs, or the most recently created accounts.
2811          * @return Boolean: True if the user is a newbie
2812          */
2813         function isNewbie() {
2814                 return !$this->isAllowed( 'autoconfirmed' );
2815         }
2816
2817         /**
2818          * Check to see if the given clear-text password is one of the accepted passwords
2819          * @param $password String: user password.
2820          * @return Boolean: True if the given password is correct, otherwise False.
2821          */
2822         function checkPassword( $password ) {
2823                 global $wgAuth;
2824                 $this->load();
2825
2826                 // Even though we stop people from creating passwords that
2827                 // are shorter than this, doesn't mean people wont be able
2828                 // to. Certain authentication plugins do NOT want to save
2829                 // domain passwords in a mysql database, so we should
2830                 // check this (in case $wgAuth->strict() is false).
2831                 if( !$this->isValidPassword( $password ) ) {
2832                         return false;
2833                 }
2834
2835                 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2836                         return true;
2837                 } elseif( $wgAuth->strict() ) {
2838                         /* Auth plugin doesn't allow local authentication */
2839                         return false;
2840                 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2841                         /* Auth plugin doesn't allow local authentication for this user name */
2842                         return false;
2843                 }
2844                 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
2845                         return true;
2846                 } elseif ( function_exists( 'iconv' ) ) {
2847                         # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2848                         # Check for this with iconv
2849                         $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2850                         if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) {
2851                                 return true;
2852                         }
2853                 }
2854                 return false;
2855         }
2856
2857         /**
2858          * Check if the given clear-text password matches the temporary password
2859          * sent by e-mail for password reset operations.
2860          * @return Boolean: True if matches, false otherwise
2861          */
2862         function checkTemporaryPassword( $plaintext ) {
2863                 global $wgNewPasswordExpiry;
2864                 if( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
2865                         if ( is_null( $this->mNewpassTime ) ) {
2866                                 return true;
2867                         }
2868                         $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
2869                         return ( time() < $expiry );
2870                 } else {
2871                         return false;
2872                 }
2873         }
2874
2875         /**
2876          * Initialize (if necessary) and return a session token value
2877          * which can be used in edit forms to show that the user's
2878          * login credentials aren't being hijacked with a foreign form
2879          * submission.
2880          *
2881          * @param $salt \types{\string,\arrayof{\string}} Optional function-specific data for hashing
2882          * @return \string The new edit token
2883          */
2884         function editToken( $salt = '' ) {
2885                 if ( $this->isAnon() ) {
2886                         return EDIT_TOKEN_SUFFIX;
2887                 } else {
2888                         if( !isset( $_SESSION['wsEditToken'] ) ) {
2889                                 $token = MWCryptRand::generateHex( 32 );
2890                                 $_SESSION['wsEditToken'] = $token;
2891                         } else {
2892                                 $token = $_SESSION['wsEditToken'];
2893                         }
2894                         if( is_array( $salt ) ) {
2895                                 $salt = implode( '|', $salt );
2896                         }
2897                         return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2898                 }
2899         }
2900
2901         /**
2902          * Generate a looking random token for various uses.
2903          *
2904          * @param $salt \string Optional salt value
2905          * @return \string The new random token
2906          */
2907         public static function generateToken( $salt = '' ) {
2908                 return MWCryptRand::generateHex( 32 );
2909         }
2910
2911         /**
2912          * Check given value against the token value stored in the session.
2913          * A match should confirm that the form was submitted from the
2914          * user's own login session, not a form submission from a third-party
2915          * site.
2916          *
2917          * @param $val \string Input value to compare
2918          * @param $salt \string Optional function-specific data for hashing
2919          * @return Boolean: Whether the token matches
2920          */
2921         function matchEditToken( $val, $salt = '' ) {
2922                 $sessionToken = $this->editToken( $salt );
2923                 if ( $val != $sessionToken ) {
2924                         wfDebug( "User::matchEditToken: broken session data\n" );
2925                 }
2926                 return $val == $sessionToken;
2927         }
2928
2929         /**
2930          * Check given value against the token value stored in the session,
2931          * ignoring the suffix.
2932          *
2933          * @param $val \string Input value to compare
2934          * @param $salt \string Optional function-specific data for hashing
2935          * @return Boolean: Whether the token matches
2936          */
2937         function matchEditTokenNoSuffix( $val, $salt = '' ) {
2938                 $sessionToken = $this->editToken( $salt );
2939                 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2940         }
2941
2942         /**
2943          * Generate a new e-mail confirmation token and send a confirmation/invalidation
2944          * mail to the user's given address.
2945          *
2946          * @param $type String: message to send, either "created", "changed" or "set"
2947          * @return Status object
2948          */
2949         function sendConfirmationMail( $type = 'created' ) {
2950                 global $wgLang;
2951                 $expiration = null; // gets passed-by-ref and defined in next line.
2952                 $token = $this->confirmationToken( $expiration );
2953                 $url = $this->confirmationTokenUrl( $token );
2954                 $invalidateURL = $this->invalidationTokenUrl( $token );
2955                 $this->saveSettings();
2956
2957                 if ( $type == 'created' || $type === false ) {
2958                         $message = 'confirmemail_body';
2959                 } elseif ( $type === true ) {
2960                         $message = 'confirmemail_body_changed';
2961                 } else {
2962                         $message = 'confirmemail_body_' . $type;
2963                 }
2964
2965                 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2966                         wfMsg( $message,
2967                                 wfGetIP(),
2968                                 $this->getName(),
2969                                 $url,
2970                                 $wgLang->timeanddate( $expiration, false ),
2971                                 $invalidateURL,
2972                                 $wgLang->date( $expiration, false ),
2973                                 $wgLang->time( $expiration, false ) ) );
2974         }
2975
2976         /**
2977          * Send an e-mail to this user's account. Does not check for
2978          * confirmed status or validity.
2979          *
2980          * @param $subject \string Message subject
2981          * @param $body \string Message body
2982          * @param $from \string Optional From address; if unspecified, default $wgPasswordSender will be used
2983          * @param $replyto \string Reply-To address
2984          * @return Status object
2985          */
2986         function sendMail( $subject, $body, $from = null, $replyto = null ) {
2987                 if( is_null( $from ) ) {
2988                         global $wgPasswordSender, $wgPasswordSenderName;
2989                         $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
2990                 } else {
2991                         $sender = new MailAddress( $from );
2992                 }
2993
2994                 $to = new MailAddress( $this );
2995                 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2996         }
2997
2998         /**
2999          * Generate, store, and return a new e-mail confirmation code.
3000          * A hash (unsalted, since it's used as a key) is stored.
3001          *
3002          * @note Call saveSettings() after calling this function to commit
3003          * this change to the database.
3004          *
3005          * @param[out] &$expiration \mixed Accepts the expiration time
3006          * @return \string New token
3007          * @private
3008          */
3009         function confirmationToken( &$expiration ) {
3010                 $now = time();
3011                 $expires = $now + 7 * 24 * 60 * 60;
3012                 $expiration = wfTimestamp( TS_MW, $expires );
3013                 $token = MWCryptRand::generateHex( 32 );
3014                 $hash = md5( $token );
3015                 $this->load();
3016                 $this->mEmailToken = $hash;
3017                 $this->mEmailTokenExpires = $expiration;
3018                 return $token;
3019         }
3020
3021         /**
3022         * Return a URL the user can use to confirm their email address.
3023          * @param $token \string Accepts the email confirmation token
3024          * @return \string New token URL
3025          * @private
3026          */
3027         function confirmationTokenUrl( $token ) {
3028                 return $this->getTokenUrl( 'ConfirmEmail', $token );
3029         }
3030
3031         /**
3032          * Return a URL the user can use to invalidate their email address.
3033          * @param $token \string Accepts the email confirmation token
3034          * @return \string New token URL
3035          * @private
3036          */
3037         function invalidationTokenUrl( $token ) {
3038                 return $this->getTokenUrl( 'Invalidateemail', $token );
3039         }
3040
3041         /**
3042          * Internal function to format the e-mail validation/invalidation URLs.
3043          * This uses $wgArticlePath directly as a quickie hack to use the
3044          * hardcoded English names of the Special: pages, for ASCII safety.
3045          *
3046          * @note Since these URLs get dropped directly into emails, using the
3047          * short English names avoids insanely long URL-encoded links, which
3048          * also sometimes can get corrupted in some browsers/mailers
3049          * (bug 6957 with Gmail and Internet Explorer).
3050          *
3051          * @param $page \string Special page
3052          * @param $token \string Token
3053          * @return \string Formatted URL
3054          */
3055         protected function getTokenUrl( $page, $token ) {
3056                 global $wgArticlePath;
3057                 return wfExpandUrl(
3058                         str_replace(
3059                                 '$1',
3060                                 "Special:$page/$token",
3061                                 $wgArticlePath ) );
3062         }
3063
3064         /**
3065          * Mark the e-mail address confirmed.
3066          *
3067          * @note Call saveSettings() after calling this function to commit the change.
3068          */
3069         function confirmEmail() {
3070                 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3071                 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3072                 return true;
3073         }
3074
3075         /**
3076          * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3077          * address if it was already confirmed.
3078          *
3079          * @note Call saveSettings() after calling this function to commit the change.
3080          */
3081         function invalidateEmail() {
3082                 $this->load();
3083                 $this->mEmailToken = null;
3084                 $this->mEmailTokenExpires = null;
3085                 $this->setEmailAuthenticationTimestamp( null );
3086                 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3087                 return true;
3088         }
3089
3090         /**
3091          * Set the e-mail authentication timestamp.
3092          * @param $timestamp \string TS_MW timestamp
3093          */
3094         function setEmailAuthenticationTimestamp( $timestamp ) {
3095                 $this->load();
3096                 $this->mEmailAuthenticated = $timestamp;
3097                 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
3098         }
3099
3100         /**
3101          * Is this user allowed to send e-mails within limits of current
3102          * site configuration?
3103          * @return Boolean: True if allowed
3104          */
3105         function canSendEmail() {
3106                 global $wgEnableEmail, $wgEnableUserEmail;
3107                 if( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
3108                         return false;
3109                 }
3110                 $canSend = $this->isEmailConfirmed();
3111                 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3112                 return $canSend;
3113         }
3114
3115         /**
3116          * Is this user allowed to receive e-mails within limits of current
3117          * site configuration?
3118          * @return Boolean: True if allowed
3119          */
3120         function canReceiveEmail() {
3121                 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3122         }
3123
3124         /**
3125          * Is this user's e-mail address valid-looking and confirmed within
3126          * limits of the current site configuration?
3127          *
3128          * @note If $wgEmailAuthentication is on, this may require the user to have
3129          * confirmed their address by returning a code or using a password
3130          * sent to the address from the wiki.
3131          *
3132          * @return Boolean: True if confirmed
3133          */
3134         function isEmailConfirmed() {
3135                 global $wgEmailAuthentication;
3136                 $this->load();
3137                 $confirmed = true;
3138                 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3139                         if( $this->isAnon() )
3140                                 return false;
3141                         if( !self::isValidEmailAddr( $this->mEmail ) )
3142                                 return false;
3143                         if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3144                                 return false;
3145                         return true;
3146                 } else {
3147                         return $confirmed;
3148                 }
3149         }
3150
3151         /**
3152          * Check whether there is an outstanding request for e-mail confirmation.
3153          * @return Boolean: True if pending
3154          */
3155         function isEmailConfirmationPending() {
3156                 global $wgEmailAuthentication;
3157                 return $wgEmailAuthentication &&
3158                         !$this->isEmailConfirmed() &&
3159                         $this->mEmailToken &&
3160                         $this->mEmailTokenExpires > wfTimestamp();
3161         }
3162
3163         /**
3164          * Get the timestamp of account creation.
3165          *
3166          * @return \types{\string,\bool} string Timestamp of account creation, or false for
3167          *                                non-existent/anonymous user accounts.
3168          */
3169         public function getRegistration() {
3170                 return $this->getId() > 0
3171                         ? $this->mRegistration
3172                         : false;
3173         }
3174
3175         /**
3176          * Get the timestamp of the first edit
3177          *
3178          * @return \types{\string,\bool} string Timestamp of first edit, or false for
3179          *                                non-existent/anonymous user accounts.
3180          */
3181         public function getFirstEditTimestamp() {
3182                 if( $this->getId() == 0 ) return false; // anons
3183                 $dbr = wfGetDB( DB_SLAVE );
3184                 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3185                         array( 'rev_user' => $this->getId() ),
3186                         __METHOD__,
3187                         array( 'ORDER BY' => 'rev_timestamp ASC' )
3188                 );
3189                 if( !$time ) return false; // no edits
3190                 return wfTimestamp( TS_MW, $time );
3191         }
3192
3193         /**
3194          * Get the permissions associated with a given list of groups
3195          *
3196          * @param $groups \type{\arrayof{\string}} List of internal group names
3197          * @return \type{\arrayof{\string}} List of permission key names for given groups combined
3198          */
3199         static function getGroupPermissions( $groups ) {
3200                 global $wgGroupPermissions, $wgRevokePermissions;
3201                 $rights = array();
3202                 // grant every granted permission first
3203                 foreach( $groups as $group ) {
3204                         if( isset( $wgGroupPermissions[$group] ) ) {
3205                                 $rights = array_merge( $rights,
3206                                         // array_filter removes empty items
3207                                         array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3208                         }
3209                 }
3210                 // now revoke the revoked permissions
3211                 foreach( $groups as $group ) {
3212                         if( isset( $wgRevokePermissions[$group] ) ) {
3213                                 $rights = array_diff( $rights,
3214                                         array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3215                         }
3216                 }
3217                 return array_unique( $rights );
3218         }
3219
3220         /**
3221          * Get all the groups who have a given permission
3222          *
3223          * @param $role \string Role to check
3224          * @return \type{\arrayof{\string}} List of internal group names with the given permission
3225          */
3226         static function getGroupsWithPermission( $role ) {
3227                 global $wgGroupPermissions;
3228                 $allowedGroups = array();
3229                 foreach ( $wgGroupPermissions as $group => $rights ) {
3230                         if ( isset( $rights[$role] ) && $rights[$role] ) {
3231                                 $allowedGroups[] = $group;
3232                         }
3233                 }
3234                 return $allowedGroups;
3235         }
3236
3237         /**
3238          * Get the localized descriptive name for a group, if it exists
3239          *
3240          * @param $group \string Internal group name
3241          * @return \string Localized descriptive group name
3242          */
3243         static function getGroupName( $group ) {
3244                 $key = "group-$group";
3245                 $name = wfMsg( $key );
3246                 return $name == '' || wfEmptyMsg( $key, $name )
3247                         ? $group
3248                         : $name;
3249         }
3250
3251         /**
3252          * Get the localized descriptive name for a member of a group, if it exists
3253          *
3254          * @param $group \string Internal group name
3255          * @return \string Localized name for group member
3256          */
3257         static function getGroupMember( $group ) {
3258                 $key = "group-$group-member";
3259                 $name = wfMsg( $key );
3260                 return $name == '' || wfEmptyMsg( $key, $name )
3261                         ? $group
3262                         : $name;
3263         }
3264
3265         /**
3266          * Return the set of defined explicit groups.
3267          * The implicit groups (by default *, 'user' and 'autoconfirmed')
3268          * are not included, as they are defined automatically, not in the database.
3269          * @return Array of internal group names
3270          */
3271         static function getAllGroups() {
3272                 global $wgGroupPermissions, $wgRevokePermissions;
3273                 return array_diff(
3274                         array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3275                         self::getImplicitGroups()
3276                 );
3277         }
3278
3279         /**
3280          * Get a list of all available permissions.
3281          * @return Array of permission names
3282          */
3283         static function getAllRights() {
3284                 if ( self::$mAllRights === false ) {
3285                         global $wgAvailableRights;
3286                         if ( count( $wgAvailableRights ) ) {
3287                                 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
3288                         } else {
3289                                 self::$mAllRights = self::$mCoreRights;
3290                         }
3291                         wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
3292                 }
3293                 return self::$mAllRights;
3294         }
3295
3296         /**
3297          * Get a list of implicit groups
3298          * @return \type{\arrayof{\string}} Array of internal group names
3299          */
3300         public static function getImplicitGroups() {
3301                 global $wgImplicitGroups;
3302                 $groups = $wgImplicitGroups;
3303                 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );       #deprecated, use $wgImplictGroups instead
3304                 return $groups;
3305         }
3306
3307         /**
3308          * Get the title of a page describing a particular group
3309          *
3310          * @param $group \string Internal group name
3311          * @return \types{\type{Title},\bool} Title of the page if it exists, false otherwise
3312          */
3313         static function getGroupPage( $group ) {
3314                 $page = wfMsgForContent( 'grouppage-' . $group );
3315                 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3316                         $title = Title::newFromText( $page );
3317                         if( is_object( $title ) )
3318                                 return $title;
3319                 }
3320                 return false;
3321         }
3322
3323         /**
3324          * Create a link to the group in HTML, if available;
3325          * else return the group name.
3326          *
3327          * @param $group \string Internal name of the group
3328          * @param $text \string The text of the link
3329          * @return \string HTML link to the group
3330          */
3331         static function makeGroupLinkHTML( $group, $text = '' ) {
3332                 if( $text == '' ) {
3333                         $text = self::getGroupName( $group );
3334                 }
3335                 $title = self::getGroupPage( $group );
3336                 if( $title ) {
3337                         global $wgUser;
3338                         $sk = $wgUser->getSkin();
3339                         return $sk->link( $title, htmlspecialchars( $text ) );
3340                 } else {
3341                         return $text;
3342                 }
3343         }
3344
3345         /**
3346          * Create a link to the group in Wikitext, if available;
3347          * else return the group name.
3348          *
3349          * @param $group \string Internal name of the group
3350          * @param $text \string The text of the link
3351          * @return \string Wikilink to the group
3352          */
3353         static function makeGroupLinkWiki( $group, $text = '' ) {
3354                 if( $text == '' ) {
3355                         $text = self::getGroupName( $group );
3356                 }
3357                 $title = self::getGroupPage( $group );
3358                 if( $title ) {
3359                         $page = $title->getPrefixedText();
3360                         return "[[$page|$text]]";
3361                 } else {
3362                         return $text;
3363                 }
3364         }
3365
3366         /**
3367          * Returns an array of the groups that a particular group can add/remove.
3368          *
3369          * @param $group String: the group to check for whether it can add/remove
3370          * @return Array array( 'add' => array( addablegroups ),
3371          *  'remove' => array( removablegroups ),
3372          *  'add-self' => array( addablegroups to self),
3373          *  'remove-self' => array( removable groups from self) )
3374          */
3375         static function changeableByGroup( $group ) {
3376                 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3377
3378                 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3379                 if( empty( $wgAddGroups[$group] ) ) {
3380                         // Don't add anything to $groups
3381                 } elseif( $wgAddGroups[$group] === true ) {
3382                         // You get everything
3383                         $groups['add'] = self::getAllGroups();
3384                 } elseif( is_array( $wgAddGroups[$group] ) ) {
3385                         $groups['add'] = $wgAddGroups[$group];
3386                 }
3387
3388                 // Same thing for remove
3389                 if( empty( $wgRemoveGroups[$group] ) ) {
3390                 } elseif( $wgRemoveGroups[$group] === true ) {
3391                         $groups['remove'] = self::getAllGroups();
3392                 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3393                         $groups['remove'] = $wgRemoveGroups[$group];
3394                 }
3395
3396                 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3397                 if( empty( $wgGroupsAddToSelf['user']) || $wgGroupsAddToSelf['user'] !== true ) {
3398                         foreach( $wgGroupsAddToSelf as $key => $value ) {
3399                                 if( is_int( $key ) ) {
3400                                         $wgGroupsAddToSelf['user'][] = $value;
3401                                 }
3402                         }
3403                 }
3404
3405                 if( empty( $wgGroupsRemoveFromSelf['user']) || $wgGroupsRemoveFromSelf['user'] !== true ) {
3406                         foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3407                                 if( is_int( $key ) ) {
3408                                         $wgGroupsRemoveFromSelf['user'][] = $value;
3409                                 }
3410                         }
3411                 }
3412
3413                 // Now figure out what groups the user can add to him/herself
3414                 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3415                 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3416                         // No idea WHY this would be used, but it's there
3417                         $groups['add-self'] = User::getAllGroups();
3418                 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3419                         $groups['add-self'] = $wgGroupsAddToSelf[$group];
3420                 }
3421
3422                 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3423                 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3424                         $groups['remove-self'] = User::getAllGroups();
3425                 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3426                         $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3427                 }
3428
3429                 return $groups;
3430         }
3431
3432         /**
3433          * Returns an array of groups that this user can add and remove
3434          * @return Array array( 'add' => array( addablegroups ),
3435          *  'remove' => array( removablegroups ),
3436          *  'add-self' => array( addablegroups to self),
3437          *  'remove-self' => array( removable groups from self) )
3438          */
3439         function changeableGroups() {
3440                 if( $this->isAllowed( 'userrights' ) ) {
3441                         // This group gives the right to modify everything (reverse-
3442                         // compatibility with old "userrights lets you change
3443                         // everything")
3444                         // Using array_merge to make the groups reindexed
3445                         $all = array_merge( User::getAllGroups() );
3446                         return array(
3447                                 'add' => $all,
3448                                 'remove' => $all,
3449                                 'add-self' => array(),
3450                                 'remove-self' => array()
3451                         );
3452                 }
3453
3454                 // Okay, it's not so simple, we will have to go through the arrays
3455                 $groups = array(
3456                         'add' => array(),
3457                         'remove' => array(),
3458                         'add-self' => array(),
3459                         'remove-self' => array()
3460                 );
3461                 $addergroups = $this->getEffectiveGroups();
3462
3463                 foreach( $addergroups as $addergroup ) {
3464                         $groups = array_merge_recursive(
3465                                 $groups, $this->changeableByGroup( $addergroup )
3466                         );
3467                         $groups['add']    = array_unique( $groups['add'] );
3468                         $groups['remove'] = array_unique( $groups['remove'] );
3469                         $groups['add-self'] = array_unique( $groups['add-self'] );
3470                         $groups['remove-self'] = array_unique( $groups['remove-self'] );
3471                 }
3472                 return $groups;
3473         }
3474
3475         /**
3476          * Increment the user's edit-count field.
3477          * Will have no effect for anonymous users.
3478          */
3479         function incEditCount() {
3480                 if( !$this->isAnon() ) {
3481                         $dbw = wfGetDB( DB_MASTER );
3482                         $dbw->update( 'user',
3483                                 array( 'user_editcount=user_editcount+1' ),
3484                                 array( 'user_id' => $this->getId() ),
3485                                 __METHOD__ );
3486
3487                         // Lazy initialization check...
3488                         if( $dbw->affectedRows() == 0 ) {
3489                                 // Pull from a slave to be less cruel to servers
3490                                 // Accuracy isn't the point anyway here
3491                                 $dbr = wfGetDB( DB_SLAVE );
3492                                 $count = $dbr->selectField( 'revision',
3493                                         'COUNT(rev_user)',
3494                                         array( 'rev_user' => $this->getId() ),
3495                                         __METHOD__ );
3496
3497                                 // Now here's a goddamn hack...
3498                                 if( $dbr !== $dbw ) {
3499                                         // If we actually have a slave server, the count is
3500                                         // at least one behind because the current transaction
3501                                         // has not been committed and replicated.
3502                                         $count++;
3503                                 } else {
3504                                         // But if DB_SLAVE is selecting the master, then the
3505                                         // count we just read includes the revision that was
3506                                         // just added in the working transaction.
3507                                 }
3508
3509                                 $dbw->update( 'user',
3510                                         array( 'user_editcount' => $count ),
3511                                         array( 'user_id' => $this->getId() ),
3512                                         __METHOD__ );
3513                         }
3514                 }
3515                 // edit count in user cache too
3516                 $this->invalidateCache();
3517         }
3518
3519         /**
3520          * Get the description of a given right
3521          *
3522          * @param $right \string Right to query
3523          * @return \string Localized description of the right
3524          */
3525         static function getRightDescription( $right ) {
3526                 $key = "right-$right";
3527                 $name = wfMsg( $key );
3528                 return $name == '' || wfEmptyMsg( $key, $name )
3529                         ? $right
3530                         : $name;
3531         }
3532
3533         /**
3534          * Make an old-style password hash
3535          *
3536          * @param $password \string Plain-text password
3537          * @param $userId \string User ID
3538          * @return \string Password hash
3539          */
3540         static function oldCrypt( $password, $userId ) {
3541                 global $wgPasswordSalt;
3542                 if ( $wgPasswordSalt ) {
3543                         return md5( $userId . '-' . md5( $password ) );
3544                 } else {
3545                         return md5( $password );
3546                 }
3547         }
3548
3549         /**
3550          * Make a new-style password hash
3551          *
3552          * @param $password \string Plain-text password
3553          * @param $salt \string Optional salt, may be random or the user ID.
3554          *                     If unspecified or false, will generate one automatically
3555          * @return \string Password hash
3556          */
3557         static function crypt( $password, $salt = false ) {
3558                 global $wgPasswordSalt;
3559
3560                 $hash = '';
3561                 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3562                         return $hash;
3563                 }
3564
3565                 if( $wgPasswordSalt ) {
3566                         if ( $salt === false ) {
3567                                 $salt = MWCryptRand::generateHex( 8 );
3568                         }
3569                         return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3570                 } else {
3571                         return ':A:' . md5( $password );
3572                 }
3573         }
3574
3575         /**
3576          * Compare a password hash with a plain-text password. Requires the user
3577          * ID if there's a chance that the hash is an old-style hash.
3578          *
3579          * @param $hash \string Password hash
3580          * @param $password \string Plain-text password to compare
3581          * @param $userId \string User ID for old-style password salt
3582          * @return Boolean:
3583          */
3584         static function comparePasswords( $hash, $password, $userId = false ) {
3585                 $type = substr( $hash, 0, 3 );
3586
3587                 $result = false;
3588                 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3589                         return $result;
3590                 }
3591
3592                 if ( $type == ':A:' ) {
3593                         # Unsalted
3594                         return md5( $password ) === substr( $hash, 3 );
3595                 } elseif ( $type == ':B:' ) {
3596                         # Salted
3597                         list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3598                         return md5( $salt.'-'.md5( $password ) ) === $realHash;
3599                 } else {
3600                         # Old-style
3601                         return self::oldCrypt( $password, $userId ) === $hash;
3602                 }
3603         }
3604
3605         /**
3606          * Add a newuser log entry for this user
3607          *
3608          * @param $byEmail Boolean: account made by email?
3609          * @param $reason String: user supplied reason
3610          */
3611         public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
3612                 global $wgUser, $wgContLang, $wgNewUserLog;
3613                 if( empty( $wgNewUserLog ) ) {
3614                         return true; // disabled
3615                 }
3616
3617                 if( $this->getName() == $wgUser->getName() ) {
3618                         $action = 'create';
3619                 } else {
3620                         $action = 'create2';
3621                         if ( $byEmail ) {
3622                                 if ( $reason === '' ) {
3623                                         $reason = wfMsgForContent( 'newuserlog-byemail' );
3624                                 } else {
3625                                         $reason = $wgContLang->commaList( array(
3626                                                 $reason, wfMsgForContent( 'newuserlog-byemail' ) ) );
3627                                 }
3628                         }
3629                 }
3630                 $log = new LogPage( 'newusers' );
3631                 $log->addEntry(
3632                         $action,
3633                         $this->getUserPage(),
3634                         $reason,
3635                         array( $this->getId() )
3636                 );
3637                 return true;
3638         }
3639
3640         /**
3641          * Add an autocreate newuser log entry for this user
3642          * Used by things like CentralAuth and perhaps other authplugins.
3643          */
3644         public function addNewUserLogEntryAutoCreate() {
3645                 global $wgNewUserLog, $wgLogAutocreatedAccounts;
3646                 if( !$wgNewUserLog || !$wgLogAutocreatedAccounts ) {
3647                         return true; // disabled
3648                 }
3649                 $log = new LogPage( 'newusers', false );
3650                 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3651                 return true;
3652         }
3653
3654         protected function loadOptions() {
3655                 $this->load();
3656                 if ( $this->mOptionsLoaded || !$this->getId() )
3657                         return;
3658
3659                 $this->mOptions = self::getDefaultOptions();
3660
3661                 // Maybe load from the object
3662                 if ( !is_null( $this->mOptionOverrides ) ) {
3663                         wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
3664                         foreach( $this->mOptionOverrides as $key => $value ) {
3665                                 $this->mOptions[$key] = $value;
3666                         }
3667                 } else {
3668                         wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
3669                         // Load from database
3670                         $dbr = wfGetDB( DB_SLAVE );
3671
3672                         $res = $dbr->select(
3673                                 'user_properties',
3674                                 '*',
3675                                 array( 'up_user' => $this->getId() ),
3676                                 __METHOD__
3677                         );
3678
3679                         foreach ( $res as $row ) {
3680                                 $this->mOptionOverrides[$row->up_property] = $row->up_value;
3681                                 $this->mOptions[$row->up_property] = $row->up_value;
3682                         }
3683                 }
3684
3685                 $this->mOptionsLoaded = true;
3686
3687                 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
3688         }
3689
3690         protected function saveOptions() {
3691                 global $wgAllowPrefChange;
3692
3693                 $extuser = ExternalUser::newFromUser( $this );
3694
3695                 $this->loadOptions();
3696                 $dbw = wfGetDB( DB_MASTER );
3697
3698                 $insert_rows = array();
3699
3700                 $saveOptions = $this->mOptions;
3701
3702                 // Allow hooks to abort, for instance to save to a global profile.
3703                 // Reset options to default state before saving.
3704                 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3705                         return;
3706
3707                 foreach( $saveOptions as $key => $value ) {
3708                         # Don't bother storing default values
3709                         if ( ( is_null( self::getDefaultOption( $key ) ) &&
3710                                         !( $value === false || is_null($value) ) ) ||
3711                                         $value != self::getDefaultOption( $key ) ) {
3712                                 $insert_rows[] = array(
3713                                                 'up_user' => $this->getId(),
3714                                                 'up_property' => $key,
3715                                                 'up_value' => $value,
3716                                         );
3717                         }
3718                         if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3719                                 switch ( $wgAllowPrefChange[$key] ) {
3720                                         case 'local':
3721                                         case 'message':
3722                                                 break;
3723                                         case 'semiglobal':
3724                                         case 'global':
3725                                                 $extuser->setPref( $key, $value );
3726                                 }
3727                         }
3728                 }
3729
3730                 $dbw->begin();
3731                 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__ );
3732                 $dbw->insert( 'user_properties', $insert_rows, __METHOD__ );
3733                 $dbw->commit();
3734         }
3735
3736         /**
3737          * Provide an array of HTML5 attributes to put on an input element
3738          * intended for the user to enter a new password.  This may include
3739          * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3740          *
3741          * Do *not* use this when asking the user to enter his current password!
3742          * Regardless of configuration, users may have invalid passwords for whatever
3743          * reason (e.g., they were set before requirements were tightened up).
3744          * Only use it when asking for a new password, like on account creation or
3745          * ResetPass.
3746          *
3747          * Obviously, you still need to do server-side checking.
3748          *
3749          * NOTE: A combination of bugs in various browsers means that this function
3750          * actually just returns array() unconditionally at the moment.  May as
3751          * well keep it around for when the browser bugs get fixed, though.
3752          *
3753          * @return array Array of HTML attributes suitable for feeding to
3754          *   Html::element(), directly or indirectly.  (Don't feed to Xml::*()!
3755          *   That will potentially output invalid XHTML 1.0 Transitional, and will
3756          *   get confused by the boolean attribute syntax used.)
3757          */
3758         public static function passwordChangeInputAttribs() {
3759                 global $wgMinimalPasswordLength;
3760
3761                 if ( $wgMinimalPasswordLength == 0 ) {
3762                         return array();
3763                 }
3764
3765                 # Note that the pattern requirement will always be satisfied if the
3766                 # input is empty, so we need required in all cases.
3767                 #
3768                 # FIXME (bug 23769): This needs to not claim the password is required
3769                 # if e-mail confirmation is being used.  Since HTML5 input validation
3770                 # is b0rked anyway in some browsers, just return nothing.  When it's
3771                 # re-enabled, fix this code to not output required for e-mail
3772                 # registration.
3773                 #$ret = array( 'required' );
3774                 $ret = array();
3775
3776                 # We can't actually do this right now, because Opera 9.6 will print out
3777                 # the entered password visibly in its error message!  When other
3778                 # browsers add support for this attribute, or Opera fixes its support,
3779                 # we can add support with a version check to avoid doing this on Opera
3780                 # versions where it will be a problem.  Reported to Opera as
3781                 # DSK-262266, but they don't have a public bug tracker for us to follow.
3782                 /*
3783                 if ( $wgMinimalPasswordLength > 1 ) {
3784                         $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
3785                         $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
3786                                 $wgMinimalPasswordLength );
3787                 }
3788                 */
3789
3790                 return $ret;
3791         }
3792
3793         /**
3794          * Format the user message using a hook, a template, or, failing these, a static format.
3795          * @param $subject   String the subject of the message
3796          * @param $text      String the content of the message
3797          * @param $signature String the signature, if provided.
3798          */
3799         static protected function formatUserMessage( $subject, $text, $signature ) {
3800                 if ( wfRunHooks( 'FormatUserMessage',
3801                                 array( $subject, &$text, $signature ) ) ) {
3802
3803                         $signature = empty($signature) ? "~~~~~" : "{$signature} ~~~~~";
3804
3805                         $template = Title::newFromText( wfMsgForContent( 'usermessage-template' ) );
3806                         if ( !$template
3807                                         || $template->getNamespace() !== NS_TEMPLATE
3808                                         || !$template->exists() ) {
3809                                 $text = "\n== $subject ==\n\n$text\n\n-- $signature";
3810                         } else {
3811                                 $text = '{{'. $template->getText()
3812                                         . " | subject=$subject | body=$text | signature=$signature }}";
3813                         }
3814                 }
3815
3816                 return $text;
3817         }
3818
3819         /**
3820          * Leave a user a message
3821          * @param $subject String the subject of the message
3822          * @param $text String the message to leave
3823          * @param $signature String Text to leave in the signature
3824          * @param $summary String the summary for this change, defaults to
3825          *                        "Leave system message."
3826          * @param $editor User The user leaving the message, defaults to
3827          *                        "{{MediaWiki:usermessage-editor}}"
3828          * @param $flags Int default edit flags
3829          *
3830          * @return boolean true if it was successful
3831          */
3832         public function leaveUserMessage( $subject, $text, $signature = "",
3833                         $summary = null, $editor = null, $flags = 0 ) {
3834                 if ( !isset( $summary ) ) {
3835                         $summary = wfMsgForContent( 'usermessage-summary' );
3836                 }
3837
3838                 if ( !isset( $editor ) ) {
3839                         $editor = User::newFromName( wfMsgForContent( 'usermessage-editor' ) );
3840                         if ( !$editor->isLoggedIn() ) {
3841                                 $editor->addToDatabase();
3842                         }
3843                 }
3844
3845                 $article = new Article( $this->getTalkPage() );
3846                 wfRunHooks( 'SetupUserMessageArticle',
3847                         array( $this, &$article, $subject, $text, $signature, $summary, $editor ) );
3848
3849
3850                 $text = self::formatUserMessage( $subject, $text, $signature );
3851                 $flags = $article->checkFlags( $flags );
3852
3853                 if ( $flags & EDIT_UPDATE ) {
3854                         $text = $article->getContent() . $text;
3855                 }
3856
3857                 $dbw = wfGetDB( DB_MASTER );
3858                 $dbw->begin();
3859
3860                 try {
3861                         $status = $article->doEdit( $text, $summary, $flags, false, $editor );
3862                 } catch ( DBQueryError $e ) {
3863                         $status = Status::newFatal("DB Error");
3864                 }
3865
3866                 if ( $status->isGood() ) {
3867                         // Set newtalk with the right user ID
3868                         $this->setNewtalk( true );
3869                         wfRunHooks( 'AfterUserMessage',
3870                                 array( $this, $article, $summary, $text, $signature, $summary, $editor ) );
3871                         $dbw->commit();
3872                 } else {
3873                         // The article was concurrently created
3874                         wfDebug( __METHOD__ . ": Error ".$status->getWikiText() );
3875                         $dbw->rollback();
3876                 }
3877
3878                 return $status->isGood();
3879         }
3880 }