]> scripts.mit.edu Git - autoinstalls/mediawiki.git/blob - includes/User.php
MediaWiki 1.17.2
[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. Sourced from mt_rand, so it's not particularly secure.
790          * @todo hash random numbers to improve security, like generateToken()
791          *
792          * @return \string New random password
793          */
794         static function randomPassword() {
795                 global $wgMinimalPasswordLength;
796                 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
797                 $l = strlen( $pwchars ) - 1;
798
799                 $pwlength = max( 7, $wgMinimalPasswordLength );
800                 $digit = mt_rand( 0, $pwlength - 1 );
801                 $np = '';
802                 for ( $i = 0; $i < $pwlength; $i++ ) {
803                         $np .= $i == $digit ? chr( mt_rand( 48, 57 ) ) : $pwchars{ mt_rand( 0, $l ) };
804                 }
805                 return $np;
806         }
807
808         /**
809          * Set cached properties to default.
810          *
811          * @note This no longer clears uncached lazy-initialised properties;
812          *       the constructor does that instead.
813          * @private
814          */
815         function loadDefaults( $name = false ) {
816                 wfProfileIn( __METHOD__ );
817
818                 global $wgRequest;
819
820                 $this->mId = 0;
821                 $this->mName = $name;
822                 $this->mRealName = '';
823                 $this->mPassword = $this->mNewpassword = '';
824                 $this->mNewpassTime = null;
825                 $this->mEmail = '';
826                 $this->mOptionOverrides = null;
827                 $this->mOptionsLoaded = false;
828
829                 if( $wgRequest->getCookie( 'LoggedOut' ) !== null ) {
830                         $this->mTouched = wfTimestamp( TS_MW, $wgRequest->getCookie( 'LoggedOut' ) );
831                 } else {
832                         $this->mTouched = '0'; # Allow any pages to be cached
833                 }
834
835                 $this->setToken(); # Random
836                 $this->mEmailAuthenticated = null;
837                 $this->mEmailToken = '';
838                 $this->mEmailTokenExpires = null;
839                 $this->mRegistration = wfTimestamp( TS_MW );
840                 $this->mGroups = array();
841
842                 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
843
844                 wfProfileOut( __METHOD__ );
845         }
846
847         /**
848          * @deprecated Use wfSetupSession().
849          */
850         function SetupSession() {
851                 wfDeprecated( __METHOD__ );
852                 wfSetupSession();
853         }
854
855         /**
856          * Load user data from the session or login cookie. If there are no valid
857          * credentials, initialises the user as an anonymous user.
858          * @return \bool True if the user is logged in, false otherwise.
859          */
860         private function loadFromSession() {
861                 global $wgRequest, $wgExternalAuthType, $wgAutocreatePolicy;
862
863                 $result = null;
864                 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
865                 if ( $result !== null ) {
866                         return $result;
867                 }
868
869                 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
870                         $extUser = ExternalUser::newFromCookie();
871                         if ( $extUser ) {
872                                 # TODO: Automatically create the user here (or probably a bit
873                                 # lower down, in fact)
874                         }
875                 }
876
877                 if ( $wgRequest->getCookie( 'UserID' ) !== null ) {
878                         $sId = intval( $wgRequest->getCookie( 'UserID' ) );
879                         if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
880                                 $this->loadDefaults(); // Possible collision!
881                                 wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
882                                         cookie user ID ($sId) don't match!" );
883                                 return false;
884                         }
885                         $_SESSION['wsUserID'] = $sId;
886                 } else if ( isset( $_SESSION['wsUserID'] ) ) {
887                         if ( $_SESSION['wsUserID'] != 0 ) {
888                                 $sId = $_SESSION['wsUserID'];
889                         } else {
890                                 $this->loadDefaults();
891                                 return false;
892                         }
893                 } else {
894                         $this->loadDefaults();
895                         return false;
896                 }
897
898                 if ( isset( $_SESSION['wsUserName'] ) ) {
899                         $sName = $_SESSION['wsUserName'];
900                 } else if ( $wgRequest->getCookie('UserName') !== null ) {
901                         $sName = $wgRequest->getCookie('UserName');
902                         $_SESSION['wsUserName'] = $sName;
903                 } else {
904                         $this->loadDefaults();
905                         return false;
906                 }
907
908                 $proposedUser = User::newFromId( $sId );
909                 if ( !$proposedUser->isLoggedIn() ) {
910                         # Not a valid ID
911                         $this->loadDefaults();
912                         return false;
913                 }
914
915                 global $wgBlockDisablesLogin;
916                 if( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
917                         # User blocked and we've disabled blocked user logins
918                         $this->loadDefaults();
919                         return false;
920                 }
921
922                 if ( isset( $_SESSION['wsToken'] ) ) {
923                         $passwordCorrect = $proposedUser->getToken() === $_SESSION['wsToken'];
924                         $from = 'session';
925                 } else if ( $wgRequest->getCookie( 'Token' ) !== null ) {
926                         $passwordCorrect = $proposedUser->getToken() === $wgRequest->getCookie( 'Token' );
927                         $from = 'cookie';
928                 } else {
929                         # No session or persistent login cookie
930                         $this->loadDefaults();
931                         return false;
932                 }
933
934                 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
935                         $this->loadFromUserObject( $proposedUser );
936                         $_SESSION['wsToken'] = $this->mToken;
937                         wfDebug( "User: logged in from $from\n" );
938                         return true;
939                 } else {
940                         # Invalid credentials
941                         wfDebug( "User: can't log in from $from, invalid credentials\n" );
942                         $this->loadDefaults();
943                         return false;
944                 }
945         }
946
947         /**
948          * Load the data for this user object from another user object. 
949          */
950         protected function loadFromUserObject( $user ) {
951                 $user->load();
952                 $user->loadGroups();
953                 $user->loadOptions();
954                 foreach ( self::$mCacheVars as $var ) {
955                         $this->$var = $user->$var;
956                 }
957         }
958
959         /**
960          * Load user and user_group data from the database.
961          * $this::mId must be set, this is how the user is identified.
962          *
963          * @return \bool True if the user exists, false if the user is anonymous
964          * @private
965          */
966         function loadFromDatabase() {
967                 # Paranoia
968                 $this->mId = intval( $this->mId );
969
970                 /** Anonymous user */
971                 if( !$this->mId ) {
972                         $this->loadDefaults();
973                         return false;
974                 }
975
976                 $dbr = wfGetDB( DB_MASTER );
977                 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
978
979                 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
980
981                 if ( $s !== false ) {
982                         # Initialise user table data
983                         $this->loadFromRow( $s );
984                         $this->mGroups = null; // deferred
985                         $this->getEditCount(); // revalidation for nulls
986                         return true;
987                 } else {
988                         # Invalid user_id
989                         $this->mId = 0;
990                         $this->loadDefaults();
991                         return false;
992                 }
993         }
994
995         /**
996          * Initialize this object from a row from the user table.
997          *
998          * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
999          */
1000         function loadFromRow( $row ) {
1001                 $this->mDataLoaded = true;
1002
1003                 if ( isset( $row->user_id ) ) {
1004                         $this->mId = intval( $row->user_id );
1005                 }
1006                 $this->mName = $row->user_name;
1007                 $this->mRealName = $row->user_real_name;
1008                 $this->mPassword = $row->user_password;
1009                 $this->mNewpassword = $row->user_newpassword;
1010                 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1011                 $this->mEmail = $row->user_email;
1012                 $this->decodeOptions( $row->user_options );
1013                 $this->mTouched = wfTimestamp(TS_MW,$row->user_touched);
1014                 $this->mToken = $row->user_token;
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          * @return \string Token
1845          */
1846         function getToken() {
1847                 $this->load();
1848                 return $this->mToken;
1849         }
1850
1851         /**
1852          * Set the random token (used for persistent authentication)
1853          * Called from loadDefaults() among other places.
1854          *
1855          * @param $token \string If specified, set the token to this value
1856          * @private
1857          */
1858         function setToken( $token = false ) {
1859                 global $wgSecretKey, $wgProxyKey;
1860                 $this->load();
1861                 if ( !$token ) {
1862                         if ( $wgSecretKey ) {
1863                                 $key = $wgSecretKey;
1864                         } elseif ( $wgProxyKey ) {
1865                                 $key = $wgProxyKey;
1866                         } else {
1867                                 $key = microtime();
1868                         }
1869                         $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1870                 } else {
1871                         $this->mToken = $token;
1872                 }
1873         }
1874
1875         /**
1876          * Set the cookie password
1877          *
1878          * @param $str \string New cookie password
1879          * @private
1880          */
1881         function setCookiePassword( $str ) {
1882                 $this->load();
1883                 $this->mCookiePassword = md5( $str );
1884         }
1885
1886         /**
1887          * Set the password for a password reminder or new account email
1888          *
1889          * @param $str \string New password to set
1890          * @param $throttle \bool If true, reset the throttle timestamp to the present
1891          */
1892         function setNewpassword( $str, $throttle = true ) {
1893                 $this->load();
1894                 $this->mNewpassword = self::crypt( $str );
1895                 if ( $throttle ) {
1896                         $this->mNewpassTime = wfTimestampNow();
1897                 }
1898         }
1899
1900         /**
1901          * Has password reminder email been sent within the last
1902          * $wgPasswordReminderResendTime hours?
1903          * @return \bool True or false
1904          */
1905         function isPasswordReminderThrottled() {
1906                 global $wgPasswordReminderResendTime;
1907                 $this->load();
1908                 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1909                         return false;
1910                 }
1911                 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1912                 return time() < $expiry;
1913         }
1914
1915         /**
1916          * Get the user's e-mail address
1917          * @return \string User's email address
1918          */
1919         function getEmail() {
1920                 $this->load();
1921                 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1922                 return $this->mEmail;
1923         }
1924
1925         /**
1926          * Get the timestamp of the user's e-mail authentication
1927          * @return \string TS_MW timestamp
1928          */
1929         function getEmailAuthenticationTimestamp() {
1930                 $this->load();
1931                 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1932                 return $this->mEmailAuthenticated;
1933         }
1934
1935         /**
1936          * Set the user's e-mail address
1937          * @param $str \string New e-mail address
1938          */
1939         function setEmail( $str ) {
1940                 $this->load();
1941                 $this->mEmail = $str;
1942                 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1943         }
1944
1945         /**
1946          * Get the user's real name
1947          * @return \string User's real name
1948          */
1949         function getRealName() {
1950                 $this->load();
1951                 return $this->mRealName;
1952         }
1953
1954         /**
1955          * Set the user's real name
1956          * @param $str \string New real name
1957          */
1958         function setRealName( $str ) {
1959                 $this->load();
1960                 $this->mRealName = $str;
1961         }
1962
1963         /**
1964          * Get the user's current setting for a given option.
1965          *
1966          * @param $oname \string The option to check
1967          * @param $defaultOverride \string A default value returned if the option does not exist
1968          * @return \string User's current value for the option
1969          * @see getBoolOption()
1970          * @see getIntOption()
1971          */
1972         function getOption( $oname, $defaultOverride = null ) {
1973                 $this->loadOptions();
1974
1975                 if ( is_null( $this->mOptions ) ) {
1976                         if($defaultOverride != '') {
1977                                 return $defaultOverride;
1978                         }
1979                         $this->mOptions = User::getDefaultOptions();
1980                 }
1981
1982                 if ( array_key_exists( $oname, $this->mOptions ) ) {
1983                         return $this->mOptions[$oname];
1984                 } else {
1985                         return $defaultOverride;
1986                 }
1987         }
1988
1989         /**
1990          * Get all user's options
1991          *
1992          * @return array
1993          */
1994         public function getOptions() {
1995                 $this->loadOptions();
1996                 return $this->mOptions;
1997         }
1998
1999         /**
2000          * Get the user's current setting for a given option, as a boolean value.
2001          *
2002          * @param $oname \string The option to check
2003          * @return \bool User's current value for the option
2004          * @see getOption()
2005          */
2006         function getBoolOption( $oname ) {
2007                 return (bool)$this->getOption( $oname );
2008         }
2009
2010
2011         /**
2012          * Get the user's current setting for a given option, as a boolean value.
2013          *
2014          * @param $oname \string The option to check
2015          * @param $defaultOverride \int A default value returned if the option does not exist
2016          * @return \int User's current value for the option
2017          * @see getOption()
2018          */
2019         function getIntOption( $oname, $defaultOverride=0 ) {
2020                 $val = $this->getOption( $oname );
2021                 if( $val == '' ) {
2022                         $val = $defaultOverride;
2023                 }
2024                 return intval( $val );
2025         }
2026
2027         /**
2028          * Set the given option for a user.
2029          *
2030          * @param $oname \string The option to set
2031          * @param $val \mixed New value to set
2032          */
2033         function setOption( $oname, $val ) {
2034                 $this->load();
2035                 $this->loadOptions();
2036
2037                 if ( $oname == 'skin' ) {
2038                         # Clear cached skin, so the new one displays immediately in Special:Preferences
2039                         $this->mSkin = null;
2040                 }
2041
2042                 // Explicitly NULL values should refer to defaults
2043                 global $wgDefaultUserOptions;
2044                 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
2045                         $val = $wgDefaultUserOptions[$oname];
2046                 }
2047
2048                 $this->mOptions[$oname] = $val;
2049         }
2050
2051         /**
2052          * Reset all options to the site defaults
2053          */
2054         function resetOptions() {
2055                 $this->mOptions = User::getDefaultOptions();
2056         }
2057
2058         /**
2059          * Get the user's preferred date format.
2060          * @return \string User's preferred date format
2061          */
2062         function getDatePreference() {
2063                 // Important migration for old data rows
2064                 if ( is_null( $this->mDatePreference ) ) {
2065                         global $wgLang;
2066                         $value = $this->getOption( 'date' );
2067                         $map = $wgLang->getDatePreferenceMigrationMap();
2068                         if ( isset( $map[$value] ) ) {
2069                                 $value = $map[$value];
2070                         }
2071                         $this->mDatePreference = $value;
2072                 }
2073                 return $this->mDatePreference;
2074         }
2075
2076         /**
2077          * Get the user preferred stub threshold
2078          */
2079         function getStubThreshold() {
2080                 global $wgMaxArticleSize; # Maximum article size, in Kb
2081                 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2082                 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2083                         # If they have set an impossible value, disable the preference
2084                         # so we can use the parser cache again.
2085                         $threshold = 0;
2086                 }
2087                 return $threshold;
2088         }
2089
2090         /**
2091          * Get the permissions this user has.
2092          * @return \type{\arrayof{\string}} Array of permission names
2093          */
2094         function getRights() {
2095                 if ( is_null( $this->mRights ) ) {
2096                         $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2097                         wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2098                         // Force reindexation of rights when a hook has unset one of them
2099                         $this->mRights = array_values( $this->mRights );
2100                 }
2101                 return $this->mRights;
2102         }
2103
2104         /**
2105          * Get the list of explicit group memberships this user has.
2106          * The implicit * and user groups are not included.
2107          * @return \type{\arrayof{\string}} Array of internal group names
2108          */
2109         function getGroups() {
2110                 $this->load();
2111                 return $this->mGroups;
2112         }
2113
2114         /**
2115          * Get the list of implicit group memberships this user has.
2116          * This includes all explicit groups, plus 'user' if logged in,
2117          * '*' for all accounts and autopromoted groups
2118          * @param $recache \bool Whether to avoid the cache
2119          * @return \type{\arrayof{\string}} Array of internal group names
2120          */
2121         function getEffectiveGroups( $recache = false ) {
2122                 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2123                         wfProfileIn( __METHOD__ );
2124                         $this->mEffectiveGroups = $this->getGroups();
2125                         $this->mEffectiveGroups[] = '*';
2126                         if( $this->getId() ) {
2127                                 $this->mEffectiveGroups[] = 'user';
2128
2129                                 $this->mEffectiveGroups = array_unique( array_merge(
2130                                         $this->mEffectiveGroups,
2131                                         Autopromote::getAutopromoteGroups( $this )
2132                                 ) );
2133
2134                                 # Hook for additional groups
2135                                 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2136                         }
2137                         wfProfileOut( __METHOD__ );
2138                 }
2139                 return $this->mEffectiveGroups;
2140         }
2141
2142         /**
2143          * Get the user's edit count.
2144          * @return \int User'e edit count
2145          */
2146         function getEditCount() {
2147                 if( $this->getId() ) {
2148                         if ( !isset( $this->mEditCount ) ) {
2149                                 /* Populate the count, if it has not been populated yet */
2150                                 $this->mEditCount = User::edits( $this->mId );
2151                         }
2152                         return $this->mEditCount;
2153                 } else {
2154                         /* nil */
2155                         return null;
2156                 }
2157         }
2158
2159         /**
2160          * Add the user to the given group.
2161          * This takes immediate effect.
2162          * @param $group \string Name of the group to add
2163          */
2164         function addGroup( $group ) {
2165                 $dbw = wfGetDB( DB_MASTER );
2166                 if( $this->getId() ) {
2167                         $dbw->insert( 'user_groups',
2168                                 array(
2169                                         'ug_user'  => $this->getID(),
2170                                         'ug_group' => $group,
2171                                 ),
2172                                 __METHOD__,
2173                                 array( 'IGNORE' ) );
2174                 }
2175
2176                 $this->loadGroups();
2177                 $this->mGroups[] = $group;
2178                 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2179
2180                 $this->invalidateCache();
2181         }
2182
2183         /**
2184          * Remove the user from the given group.
2185          * This takes immediate effect.
2186          * @param $group \string Name of the group to remove
2187          */
2188         function removeGroup( $group ) {
2189                 $this->load();
2190                 $dbw = wfGetDB( DB_MASTER );
2191                 $dbw->delete( 'user_groups',
2192                         array(
2193                                 'ug_user'  => $this->getID(),
2194                                 'ug_group' => $group,
2195                         ), __METHOD__ );
2196
2197                 $this->loadGroups();
2198                 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2199                 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2200
2201                 $this->invalidateCache();
2202         }
2203
2204         /**
2205          * Get whether the user is logged in
2206          * @return \bool True or false
2207          */
2208         function isLoggedIn() {
2209                 return $this->getID() != 0;
2210         }
2211
2212         /**
2213          * Get whether the user is anonymous
2214          * @return \bool True or false
2215          */
2216         function isAnon() {
2217                 return !$this->isLoggedIn();
2218         }
2219
2220         /**
2221          * Get whether the user is a bot
2222          * @return \bool True or false
2223          * @deprecated
2224          */
2225         function isBot() {
2226                 wfDeprecated( __METHOD__ );
2227                 return $this->isAllowed( 'bot' );
2228         }
2229
2230         /**
2231          * Check if user is allowed to access a feature / make an action
2232          * @param $action \string action to be checked
2233          * @return Boolean: True if action is allowed, else false
2234          */
2235         function isAllowed( $action = '' ) {
2236                 if ( $action === '' ) {
2237                         return true; // In the spirit of DWIM
2238                 }
2239                 # Patrolling may not be enabled
2240                 if( $action === 'patrol' || $action === 'autopatrol' ) {
2241                         global $wgUseRCPatrol, $wgUseNPPatrol;
2242                         if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2243                                 return false;
2244                 }
2245                 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2246                 # by misconfiguration: 0 == 'foo'
2247                 return in_array( $action, $this->getRights(), true );
2248         }
2249
2250         /**
2251          * Check whether to enable recent changes patrol features for this user
2252          * @return Boolean: True or false
2253          */
2254         public function useRCPatrol() {
2255                 global $wgUseRCPatrol;
2256                 return( $wgUseRCPatrol && ( $this->isAllowed( 'patrol' ) || $this->isAllowed( 'patrolmarks' ) ) );
2257         }
2258
2259         /**
2260          * Check whether to enable new pages patrol features for this user
2261          * @return \bool True or false
2262          */
2263         public function useNPPatrol() {
2264                 global $wgUseRCPatrol, $wgUseNPPatrol;
2265                 return( ( $wgUseRCPatrol || $wgUseNPPatrol ) && ( $this->isAllowed( 'patrol' ) || $this->isAllowed( 'patrolmarks' ) ) );
2266         }
2267
2268         /**
2269          * Get the current skin, loading it if required, and setting a title
2270          * @param $t Title: the title to use in the skin
2271          * @return Skin The current skin
2272          * @todo FIXME : need to check the old failback system [AV]
2273          */
2274         function getSkin( $t = null ) {
2275                 if( !$this->mSkin ) {
2276                         global $wgOut;
2277                         $this->mSkin = $this->createSkinObject();
2278                         $this->mSkin->setTitle( $wgOut->getTitle() );
2279                 }
2280                 if ( $t && ( !$this->mSkin->getTitle() || !$t->equals( $this->mSkin->getTitle() ) ) ) {
2281                         $skin = $this->createSkinObject();
2282                         $skin->setTitle( $t );
2283                         return $skin;
2284                 } else {
2285                         return $this->mSkin;
2286                 }
2287         }
2288
2289         // Creates a Skin object, for getSkin()
2290         private function createSkinObject() {
2291                 wfProfileIn( __METHOD__ );
2292
2293                 global $wgHiddenPrefs;
2294                 if( !in_array( 'skin', $wgHiddenPrefs ) ) {
2295                         global $wgRequest;
2296                         # get the user skin
2297                         $userSkin = $this->getOption( 'skin' );
2298                         $userSkin = $wgRequest->getVal( 'useskin', $userSkin );
2299                 } else {
2300                         # if we're not allowing users to override, then use the default
2301                         global $wgDefaultSkin;
2302                         $userSkin = $wgDefaultSkin;
2303                 }
2304
2305                 $skin = Skin::newFromKey( $userSkin );
2306                 wfProfileOut( __METHOD__ );
2307
2308                 return $skin;
2309         }
2310
2311         /**
2312          * Check the watched status of an article.
2313          * @param $title \type{Title} Title of the article to look at
2314          * @return \bool True if article is watched
2315          */
2316         function isWatched( $title ) {
2317                 $wl = WatchedItem::fromUserTitle( $this, $title );
2318                 return $wl->isWatched();
2319         }
2320
2321         /**
2322          * Watch an article.
2323          * @param $title \type{Title} Title of the article to look at
2324          */
2325         function addWatch( $title ) {
2326                 $wl = WatchedItem::fromUserTitle( $this, $title );
2327                 $wl->addWatch();
2328                 $this->invalidateCache();
2329         }
2330
2331         /**
2332          * Stop watching an article.
2333          * @param $title \type{Title} Title of the article to look at
2334          */
2335         function removeWatch( $title ) {
2336                 $wl = WatchedItem::fromUserTitle( $this, $title );
2337                 $wl->removeWatch();
2338                 $this->invalidateCache();
2339         }
2340
2341         /**
2342          * Clear the user's notification timestamp for the given title.
2343          * If e-notif e-mails are on, they will receive notification mails on
2344          * the next change of the page if it's watched etc.
2345          * @param $title \type{Title} Title of the article to look at
2346          */
2347         function clearNotification( &$title ) {
2348                 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2349
2350                 # Do nothing if the database is locked to writes
2351                 if( wfReadOnly() ) {
2352                         return;
2353                 }
2354
2355                 if( $title->getNamespace() == NS_USER_TALK &&
2356                         $title->getText() == $this->getName() ) {
2357                         if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2358                                 return;
2359                         $this->setNewtalk( false );
2360                 }
2361
2362                 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2363                         return;
2364                 }
2365
2366                 if( $this->isAnon() ) {
2367                         // Nothing else to do...
2368                         return;
2369                 }
2370
2371                 // Only update the timestamp if the page is being watched.
2372                 // The query to find out if it is watched is cached both in memcached and per-invocation,
2373                 // and when it does have to be executed, it can be on a slave
2374                 // If this is the user's newtalk page, we always update the timestamp
2375                 if( $title->getNamespace() == NS_USER_TALK &&
2376                         $title->getText() == $wgUser->getName() )
2377                 {
2378                         $watched = true;
2379                 } elseif ( $this->getId() == $wgUser->getId() ) {
2380                         $watched = $title->userIsWatching();
2381                 } else {
2382                         $watched = true;
2383                 }
2384
2385                 // If the page is watched by the user (or may be watched), update the timestamp on any
2386                 // any matching rows
2387                 if ( $watched ) {
2388                         $dbw = wfGetDB( DB_MASTER );
2389                         $dbw->update( 'watchlist',
2390                                         array( /* SET */
2391                                                 'wl_notificationtimestamp' => null
2392                                         ), array( /* WHERE */
2393                                                 'wl_title' => $title->getDBkey(),
2394                                                 'wl_namespace' => $title->getNamespace(),
2395                                                 'wl_user' => $this->getID()
2396                                         ), __METHOD__
2397                         );
2398                 }
2399         }
2400
2401         /**
2402          * Resets all of the given user's page-change notification timestamps.
2403          * If e-notif e-mails are on, they will receive notification mails on
2404          * the next change of any watched page.
2405          *
2406          * @param $currentUser \int User ID
2407          */
2408         function clearAllNotifications( $currentUser ) {
2409                 global $wgUseEnotif, $wgShowUpdatedMarker;
2410                 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2411                         $this->setNewtalk( false );
2412                         return;
2413                 }
2414                 if( $currentUser != 0 )  {
2415                         $dbw = wfGetDB( DB_MASTER );
2416                         $dbw->update( 'watchlist',
2417                                 array( /* SET */
2418                                         'wl_notificationtimestamp' => null
2419                                 ), array( /* WHERE */
2420                                         'wl_user' => $currentUser
2421                                 ), __METHOD__
2422                         );
2423                 #       We also need to clear here the "you have new message" notification for the own user_talk page
2424                 #       This is cleared one page view later in Article::viewUpdates();
2425                 }
2426         }
2427
2428         /**
2429          * Set this user's options from an encoded string
2430          * @param $str \string Encoded options to import
2431          * @private
2432          */
2433         function decodeOptions( $str ) {
2434                 if( !$str )
2435                         return;
2436
2437                 $this->mOptionsLoaded = true;
2438                 $this->mOptionOverrides = array();
2439
2440                 // If an option is not set in $str, use the default value
2441                 $this->mOptions = self::getDefaultOptions();
2442
2443                 $a = explode( "\n", $str );
2444                 foreach ( $a as $s ) {
2445                         $m = array();
2446                         if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2447                                 $this->mOptions[$m[1]] = $m[2];
2448                                 $this->mOptionOverrides[$m[1]] = $m[2];
2449                         }
2450                 }
2451         }
2452
2453         /**
2454          * Set a cookie on the user's client. Wrapper for
2455          * WebResponse::setCookie
2456          * @param $name \string Name of the cookie to set
2457          * @param $value \string Value to set
2458          * @param $exp \int Expiration time, as a UNIX time value;
2459          *                   if 0 or not specified, use the default $wgCookieExpiration
2460          */
2461         protected function setCookie( $name, $value, $exp = 0 ) {
2462                 global $wgRequest;
2463                 $wgRequest->response()->setcookie( $name, $value, $exp );
2464         }
2465
2466         /**
2467          * Clear a cookie on the user's client
2468          * @param $name \string Name of the cookie to clear
2469          */
2470         protected function clearCookie( $name ) {
2471                 $this->setCookie( $name, '', time() - 86400 );
2472         }
2473
2474         /**
2475          * Set the default cookies for this session on the user's client.
2476          */
2477         function setCookies() {
2478                 $this->load();
2479                 if ( 0 == $this->mId ) return;
2480                 $session = array(
2481                         'wsUserID' => $this->mId,
2482                         'wsToken' => $this->mToken,
2483                         'wsUserName' => $this->getName()
2484                 );
2485                 $cookies = array(
2486                         'UserID' => $this->mId,
2487                         'UserName' => $this->getName(),
2488                 );
2489                 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2490                         $cookies['Token'] = $this->mToken;
2491                 } else {
2492                         $cookies['Token'] = false;
2493                 }
2494
2495                 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2496                 #check for null, since the hook could cause a null value
2497                 if ( !is_null( $session ) && isset( $_SESSION ) ){
2498                         $_SESSION = $session + $_SESSION;
2499                 }
2500                 foreach ( $cookies as $name => $value ) {
2501                         if ( $value === false ) {
2502                                 $this->clearCookie( $name );
2503                         } else {
2504                                 $this->setCookie( $name, $value );
2505                         }
2506                 }
2507         }
2508
2509         /**
2510          * Log this user out.
2511          */
2512         function logout() {
2513                 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2514                         $this->doLogout();
2515                 }
2516         }
2517
2518         /**
2519          * Clear the user's cookies and session, and reset the instance cache.
2520          * @private
2521          * @see logout()
2522          */
2523         function doLogout() {
2524                 $this->clearInstanceCache( 'defaults' );
2525
2526                 $_SESSION['wsUserID'] = 0;
2527
2528                 $this->clearCookie( 'UserID' );
2529                 $this->clearCookie( 'Token' );
2530
2531                 # Remember when user logged out, to prevent seeing cached pages
2532                 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2533         }
2534
2535         /**
2536          * Save this user's settings into the database.
2537          * @todo Only rarely do all these fields need to be set!
2538          */
2539         function saveSettings() {
2540                 $this->load();
2541                 if ( wfReadOnly() ) { return; }
2542                 if ( 0 == $this->mId ) { return; }
2543
2544                 $this->mTouched = self::newTouchedTimestamp();
2545
2546                 $dbw = wfGetDB( DB_MASTER );
2547                 $dbw->update( 'user',
2548                         array( /* SET */
2549                                 'user_name' => $this->mName,
2550                                 'user_password' => $this->mPassword,
2551                                 'user_newpassword' => $this->mNewpassword,
2552                                 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2553                                 'user_real_name' => $this->mRealName,
2554                                 'user_email' => $this->mEmail,
2555                                 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2556                                 'user_options' => '',
2557                                 'user_touched' => $dbw->timestamp( $this->mTouched ),
2558                                 'user_token' => $this->mToken,
2559                                 'user_email_token' => $this->mEmailToken,
2560                                 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2561                         ), array( /* WHERE */
2562                                 'user_id' => $this->mId
2563                         ), __METHOD__
2564                 );
2565
2566                 $this->saveOptions();
2567
2568                 wfRunHooks( 'UserSaveSettings', array( $this ) );
2569                 $this->clearSharedCache();
2570                 $this->getUserPage()->invalidateCache();
2571         }
2572
2573         /**
2574          * If only this user's username is known, and it exists, return the user ID.
2575          */
2576         function idForName() {
2577                 $s = trim( $this->getName() );
2578                 if ( $s === '' ) return 0;
2579
2580                 $dbr = wfGetDB( DB_SLAVE );
2581                 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2582                 if ( $id === false ) {
2583                         $id = 0;
2584                 }
2585                 return $id;
2586         }
2587
2588         /**
2589          * Add a user to the database, return the user object
2590          *
2591          * @param $name \string Username to add
2592          * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2593          *   - password             The user's password. Password logins will be disabled if this is omitted.
2594          *   - newpassword          A temporary password mailed to the user
2595          *   - email                The user's email address
2596          *   - email_authenticated  The email authentication timestamp
2597          *   - real_name            The user's real name
2598          *   - options              An associative array of non-default options
2599          *   - token                Random authentication token. Do not set.
2600          *   - registration         Registration timestamp. Do not set.
2601          *
2602          * @return \type{User} A new User object, or null if the username already exists
2603          */
2604         static function createNew( $name, $params = array() ) {
2605                 $user = new User;
2606                 $user->load();
2607                 if ( isset( $params['options'] ) ) {
2608                         $user->mOptions = $params['options'] + (array)$user->mOptions;
2609                         unset( $params['options'] );
2610                 }
2611                 $dbw = wfGetDB( DB_MASTER );
2612                 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2613
2614                 $fields = array(
2615                         'user_id' => $seqVal,
2616                         'user_name' => $name,
2617                         'user_password' => $user->mPassword,
2618                         'user_newpassword' => $user->mNewpassword,
2619                         'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
2620                         'user_email' => $user->mEmail,
2621                         'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2622                         'user_real_name' => $user->mRealName,
2623                         'user_options' => '',
2624                         'user_token' => $user->mToken,
2625                         'user_registration' => $dbw->timestamp( $user->mRegistration ),
2626                         'user_editcount' => 0,
2627                 );
2628                 foreach ( $params as $name => $value ) {
2629                         $fields["user_$name"] = $value;
2630                 }
2631                 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2632                 if ( $dbw->affectedRows() ) {
2633                         $newUser = User::newFromId( $dbw->insertId() );
2634                 } else {
2635                         $newUser = null;
2636                 }
2637                 return $newUser;
2638         }
2639
2640         /**
2641          * Add this existing user object to the database
2642          */
2643         function addToDatabase() {
2644                 $this->load();
2645                 $dbw = wfGetDB( DB_MASTER );
2646                 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2647                 $dbw->insert( 'user',
2648                         array(
2649                                 'user_id' => $seqVal,
2650                                 'user_name' => $this->mName,
2651                                 'user_password' => $this->mPassword,
2652                                 'user_newpassword' => $this->mNewpassword,
2653                                 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2654                                 'user_email' => $this->mEmail,
2655                                 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2656                                 'user_real_name' => $this->mRealName,
2657                                 'user_options' => '',
2658                                 'user_token' => $this->mToken,
2659                                 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2660                                 'user_editcount' => 0,
2661                         ), __METHOD__
2662                 );
2663                 $this->mId = $dbw->insertId();
2664
2665                 // Clear instance cache other than user table data, which is already accurate
2666                 $this->clearInstanceCache();
2667
2668                 $this->saveOptions();
2669         }
2670
2671         /**
2672          * If this (non-anonymous) user is blocked, block any IP address
2673          * they've successfully logged in from.
2674          */
2675         function spreadBlock() {
2676                 wfDebug( __METHOD__ . "()\n" );
2677                 $this->load();
2678                 if ( $this->mId == 0 ) {
2679                         return;
2680                 }
2681
2682                 $userblock = Block::newFromDB( '', $this->mId );
2683                 if ( !$userblock ) {
2684                         return;
2685                 }
2686
2687                 $userblock->doAutoblock( wfGetIP() );
2688         }
2689
2690         /**
2691          * Generate a string which will be different for any combination of
2692          * user options which would produce different parser output.
2693          * This will be used as part of the hash key for the parser cache,
2694          * so users with the same options can share the same cached data
2695          * safely.
2696          *
2697          * Extensions which require it should install 'PageRenderingHash' hook,
2698          * which will give them a chance to modify this key based on their own
2699          * settings.
2700          *
2701          * @deprecated use the ParserOptions object to get the relevant options
2702          * @return \string Page rendering hash
2703          */
2704         function getPageRenderingHash() {
2705                 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2706                 if( $this->mHash ){
2707                         return $this->mHash;
2708                 }
2709                 wfDeprecated( __METHOD__ );
2710
2711                 // stubthreshold is only included below for completeness,
2712                 // since it disables the parser cache, its value will always
2713                 // be 0 when this function is called by parsercache.
2714
2715                 $confstr =        $this->getOption( 'math' );
2716                 $confstr .= '!' . $this->getStubThreshold();
2717                 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
2718                         $confstr .= '!' . $this->getDatePreference();
2719                 }
2720                 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ? '1' : '' );
2721                 $confstr .= '!' . $wgLang->getCode();
2722                 $confstr .= '!' . $this->getOption( 'thumbsize' );
2723                 // add in language specific options, if any
2724                 $extra = $wgContLang->getExtraHashOptions();
2725                 $confstr .= $extra;
2726
2727                 // Since the skin could be overloading link(), it should be
2728                 // included here but in practice, none of our skins do that.
2729
2730                 $confstr .= $wgRenderHashAppend;
2731
2732                 // Give a chance for extensions to modify the hash, if they have
2733                 // extra options or other effects on the parser cache.
2734                 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2735
2736                 // Make it a valid memcached key fragment
2737                 $confstr = str_replace( ' ', '_', $confstr );
2738                 $this->mHash = $confstr;
2739                 return $confstr;
2740         }
2741
2742         /**
2743          * Get whether the user is explicitly blocked from account creation.
2744          * @return \bool True if blocked
2745          */
2746         function isBlockedFromCreateAccount() {
2747                 $this->getBlockedStatus();
2748                 return $this->mBlock && $this->mBlock->mCreateAccount;
2749         }
2750
2751         /**
2752          * Get whether the user is blocked from using Special:Emailuser.
2753          * @return Boolean: True if blocked
2754          */
2755         function isBlockedFromEmailuser() {
2756                 $this->getBlockedStatus();
2757                 return $this->mBlock && $this->mBlock->mBlockEmail;
2758         }
2759
2760         /**
2761          * Get whether the user is allowed to create an account.
2762          * @return Boolean: True if allowed
2763          */
2764         function isAllowedToCreateAccount() {
2765                 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2766         }
2767
2768         /**
2769          * Get this user's personal page title.
2770          *
2771          * @return Title: User's personal page title
2772          */
2773         function getUserPage() {
2774                 return Title::makeTitle( NS_USER, $this->getName() );
2775         }
2776
2777         /**
2778          * Get this user's talk page title.
2779          *
2780          * @return Title: User's talk page title
2781          */
2782         function getTalkPage() {
2783                 $title = $this->getUserPage();
2784                 return $title->getTalkPage();
2785         }
2786
2787         /**
2788          * Get the maximum valid user ID.
2789          * @return Integer: User ID
2790          * @static
2791          */
2792         function getMaxID() {
2793                 static $res; // cache
2794
2795                 if ( isset( $res ) ) {
2796                         return $res;
2797                 } else {
2798                         $dbr = wfGetDB( DB_SLAVE );
2799                         return $res = $dbr->selectField( 'user', 'max(user_id)', false, __METHOD__ );
2800                 }
2801         }
2802
2803         /**
2804          * Determine whether the user is a newbie. Newbies are either
2805          * anonymous IPs, or the most recently created accounts.
2806          * @return Boolean: True if the user is a newbie
2807          */
2808         function isNewbie() {
2809                 return !$this->isAllowed( 'autoconfirmed' );
2810         }
2811
2812         /**
2813          * Check to see if the given clear-text password is one of the accepted passwords
2814          * @param $password String: user password.
2815          * @return Boolean: True if the given password is correct, otherwise False.
2816          */
2817         function checkPassword( $password ) {
2818                 global $wgAuth;
2819                 $this->load();
2820
2821                 // Even though we stop people from creating passwords that
2822                 // are shorter than this, doesn't mean people wont be able
2823                 // to. Certain authentication plugins do NOT want to save
2824                 // domain passwords in a mysql database, so we should
2825                 // check this (in case $wgAuth->strict() is false).
2826                 if( !$this->isValidPassword( $password ) ) {
2827                         return false;
2828                 }
2829
2830                 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2831                         return true;
2832                 } elseif( $wgAuth->strict() ) {
2833                         /* Auth plugin doesn't allow local authentication */
2834                         return false;
2835                 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2836                         /* Auth plugin doesn't allow local authentication for this user name */
2837                         return false;
2838                 }
2839                 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
2840                         return true;
2841                 } elseif ( function_exists( 'iconv' ) ) {
2842                         # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2843                         # Check for this with iconv
2844                         $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2845                         if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) {
2846                                 return true;
2847                         }
2848                 }
2849                 return false;
2850         }
2851
2852         /**
2853          * Check if the given clear-text password matches the temporary password
2854          * sent by e-mail for password reset operations.
2855          * @return Boolean: True if matches, false otherwise
2856          */
2857         function checkTemporaryPassword( $plaintext ) {
2858                 global $wgNewPasswordExpiry;
2859                 if( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
2860                         if ( is_null( $this->mNewpassTime ) ) {
2861                                 return true;
2862                         }
2863                         $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
2864                         return ( time() < $expiry );
2865                 } else {
2866                         return false;
2867                 }
2868         }
2869
2870         /**
2871          * Initialize (if necessary) and return a session token value
2872          * which can be used in edit forms to show that the user's
2873          * login credentials aren't being hijacked with a foreign form
2874          * submission.
2875          *
2876          * @param $salt \types{\string,\arrayof{\string}} Optional function-specific data for hashing
2877          * @return \string The new edit token
2878          */
2879         function editToken( $salt = '' ) {
2880                 if ( $this->isAnon() ) {
2881                         return EDIT_TOKEN_SUFFIX;
2882                 } else {
2883                         if( !isset( $_SESSION['wsEditToken'] ) ) {
2884                                 $token = self::generateToken();
2885                                 $_SESSION['wsEditToken'] = $token;
2886                         } else {
2887                                 $token = $_SESSION['wsEditToken'];
2888                         }
2889                         if( is_array( $salt ) ) {
2890                                 $salt = implode( '|', $salt );
2891                         }
2892                         return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2893                 }
2894         }
2895
2896         /**
2897          * Generate a looking random token for various uses.
2898          *
2899          * @param $salt \string Optional salt value
2900          * @return \string The new random token
2901          */
2902         public static function generateToken( $salt = '' ) {
2903                 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2904                 return md5( $token . $salt );
2905         }
2906
2907         /**
2908          * Check given value against the token value stored in the session.
2909          * A match should confirm that the form was submitted from the
2910          * user's own login session, not a form submission from a third-party
2911          * site.
2912          *
2913          * @param $val \string Input value to compare
2914          * @param $salt \string Optional function-specific data for hashing
2915          * @return Boolean: Whether the token matches
2916          */
2917         function matchEditToken( $val, $salt = '' ) {
2918                 $sessionToken = $this->editToken( $salt );
2919                 if ( $val != $sessionToken ) {
2920                         wfDebug( "User::matchEditToken: broken session data\n" );
2921                 }
2922                 return $val == $sessionToken;
2923         }
2924
2925         /**
2926          * Check given value against the token value stored in the session,
2927          * ignoring the suffix.
2928          *
2929          * @param $val \string Input value to compare
2930          * @param $salt \string Optional function-specific data for hashing
2931          * @return Boolean: Whether the token matches
2932          */
2933         function matchEditTokenNoSuffix( $val, $salt = '' ) {
2934                 $sessionToken = $this->editToken( $salt );
2935                 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2936         }
2937
2938         /**
2939          * Generate a new e-mail confirmation token and send a confirmation/invalidation
2940          * mail to the user's given address.
2941          *
2942          * @param $type String: message to send, either "created", "changed" or "set"
2943          * @return Status object
2944          */
2945         function sendConfirmationMail( $type = 'created' ) {
2946                 global $wgLang;
2947                 $expiration = null; // gets passed-by-ref and defined in next line.
2948                 $token = $this->confirmationToken( $expiration );
2949                 $url = $this->confirmationTokenUrl( $token );
2950                 $invalidateURL = $this->invalidationTokenUrl( $token );
2951                 $this->saveSettings();
2952
2953                 if ( $type == 'created' || $type === false ) {
2954                         $message = 'confirmemail_body';
2955                 } elseif ( $type === true ) {
2956                         $message = 'confirmemail_body_changed';
2957                 } else {
2958                         $message = 'confirmemail_body_' . $type;
2959                 }
2960
2961                 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2962                         wfMsg( $message,
2963                                 wfGetIP(),
2964                                 $this->getName(),
2965                                 $url,
2966                                 $wgLang->timeanddate( $expiration, false ),
2967                                 $invalidateURL,
2968                                 $wgLang->date( $expiration, false ),
2969                                 $wgLang->time( $expiration, false ) ) );
2970         }
2971
2972         /**
2973          * Send an e-mail to this user's account. Does not check for
2974          * confirmed status or validity.
2975          *
2976          * @param $subject \string Message subject
2977          * @param $body \string Message body
2978          * @param $from \string Optional From address; if unspecified, default $wgPasswordSender will be used
2979          * @param $replyto \string Reply-To address
2980          * @return Status object
2981          */
2982         function sendMail( $subject, $body, $from = null, $replyto = null ) {
2983                 if( is_null( $from ) ) {
2984                         global $wgPasswordSender, $wgPasswordSenderName;
2985                         $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
2986                 } else {
2987                         $sender = new MailAddress( $from );
2988                 }
2989
2990                 $to = new MailAddress( $this );
2991                 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2992         }
2993
2994         /**
2995          * Generate, store, and return a new e-mail confirmation code.
2996          * A hash (unsalted, since it's used as a key) is stored.
2997          *
2998          * @note Call saveSettings() after calling this function to commit
2999          * this change to the database.
3000          *
3001          * @param[out] &$expiration \mixed Accepts the expiration time
3002          * @return \string New token
3003          * @private
3004          */
3005         function confirmationToken( &$expiration ) {
3006                 $now = time();
3007                 $expires = $now + 7 * 24 * 60 * 60;
3008                 $expiration = wfTimestamp( TS_MW, $expires );
3009                 $token = self::generateToken( $this->mId . $this->mEmail . $expires );
3010                 $hash = md5( $token );
3011                 $this->load();
3012                 $this->mEmailToken = $hash;
3013                 $this->mEmailTokenExpires = $expiration;
3014                 return $token;
3015         }
3016
3017         /**
3018         * Return a URL the user can use to confirm their email address.
3019          * @param $token \string Accepts the email confirmation token
3020          * @return \string New token URL
3021          * @private
3022          */
3023         function confirmationTokenUrl( $token ) {
3024                 return $this->getTokenUrl( 'ConfirmEmail', $token );
3025         }
3026
3027         /**
3028          * Return a URL the user can use to invalidate their email address.
3029          * @param $token \string Accepts the email confirmation token
3030          * @return \string New token URL
3031          * @private
3032          */
3033         function invalidationTokenUrl( $token ) {
3034                 return $this->getTokenUrl( 'Invalidateemail', $token );
3035         }
3036
3037         /**
3038          * Internal function to format the e-mail validation/invalidation URLs.
3039          * This uses $wgArticlePath directly as a quickie hack to use the
3040          * hardcoded English names of the Special: pages, for ASCII safety.
3041          *
3042          * @note Since these URLs get dropped directly into emails, using the
3043          * short English names avoids insanely long URL-encoded links, which
3044          * also sometimes can get corrupted in some browsers/mailers
3045          * (bug 6957 with Gmail and Internet Explorer).
3046          *
3047          * @param $page \string Special page
3048          * @param $token \string Token
3049          * @return \string Formatted URL
3050          */
3051         protected function getTokenUrl( $page, $token ) {
3052                 global $wgArticlePath;
3053                 return wfExpandUrl(
3054                         str_replace(
3055                                 '$1',
3056                                 "Special:$page/$token",
3057                                 $wgArticlePath ) );
3058         }
3059
3060         /**
3061          * Mark the e-mail address confirmed.
3062          *
3063          * @note Call saveSettings() after calling this function to commit the change.
3064          */
3065         function confirmEmail() {
3066                 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3067                 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3068                 return true;
3069         }
3070
3071         /**
3072          * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3073          * address if it was already confirmed.
3074          *
3075          * @note Call saveSettings() after calling this function to commit the change.
3076          */
3077         function invalidateEmail() {
3078                 $this->load();
3079                 $this->mEmailToken = null;
3080                 $this->mEmailTokenExpires = null;
3081                 $this->setEmailAuthenticationTimestamp( null );
3082                 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3083                 return true;
3084         }
3085
3086         /**
3087          * Set the e-mail authentication timestamp.
3088          * @param $timestamp \string TS_MW timestamp
3089          */
3090         function setEmailAuthenticationTimestamp( $timestamp ) {
3091                 $this->load();
3092                 $this->mEmailAuthenticated = $timestamp;
3093                 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
3094         }
3095
3096         /**
3097          * Is this user allowed to send e-mails within limits of current
3098          * site configuration?
3099          * @return Boolean: True if allowed
3100          */
3101         function canSendEmail() {
3102                 global $wgEnableEmail, $wgEnableUserEmail;
3103                 if( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
3104                         return false;
3105                 }
3106                 $canSend = $this->isEmailConfirmed();
3107                 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3108                 return $canSend;
3109         }
3110
3111         /**
3112          * Is this user allowed to receive e-mails within limits of current
3113          * site configuration?
3114          * @return Boolean: True if allowed
3115          */
3116         function canReceiveEmail() {
3117                 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3118         }
3119
3120         /**
3121          * Is this user's e-mail address valid-looking and confirmed within
3122          * limits of the current site configuration?
3123          *
3124          * @note If $wgEmailAuthentication is on, this may require the user to have
3125          * confirmed their address by returning a code or using a password
3126          * sent to the address from the wiki.
3127          *
3128          * @return Boolean: True if confirmed
3129          */
3130         function isEmailConfirmed() {
3131                 global $wgEmailAuthentication;
3132                 $this->load();
3133                 $confirmed = true;
3134                 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3135                         if( $this->isAnon() )
3136                                 return false;
3137                         if( !self::isValidEmailAddr( $this->mEmail ) )
3138                                 return false;
3139                         if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3140                                 return false;
3141                         return true;
3142                 } else {
3143                         return $confirmed;
3144                 }
3145         }
3146
3147         /**
3148          * Check whether there is an outstanding request for e-mail confirmation.
3149          * @return Boolean: True if pending
3150          */
3151         function isEmailConfirmationPending() {
3152                 global $wgEmailAuthentication;
3153                 return $wgEmailAuthentication &&
3154                         !$this->isEmailConfirmed() &&
3155                         $this->mEmailToken &&
3156                         $this->mEmailTokenExpires > wfTimestamp();
3157         }
3158
3159         /**
3160          * Get the timestamp of account creation.
3161          *
3162          * @return \types{\string,\bool} string Timestamp of account creation, or false for
3163          *                                non-existent/anonymous user accounts.
3164          */
3165         public function getRegistration() {
3166                 return $this->getId() > 0
3167                         ? $this->mRegistration
3168                         : false;
3169         }
3170
3171         /**
3172          * Get the timestamp of the first edit
3173          *
3174          * @return \types{\string,\bool} string Timestamp of first edit, or false for
3175          *                                non-existent/anonymous user accounts.
3176          */
3177         public function getFirstEditTimestamp() {
3178                 if( $this->getId() == 0 ) return false; // anons
3179                 $dbr = wfGetDB( DB_SLAVE );
3180                 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3181                         array( 'rev_user' => $this->getId() ),
3182                         __METHOD__,
3183                         array( 'ORDER BY' => 'rev_timestamp ASC' )
3184                 );
3185                 if( !$time ) return false; // no edits
3186                 return wfTimestamp( TS_MW, $time );
3187         }
3188
3189         /**
3190          * Get the permissions associated with a given list of groups
3191          *
3192          * @param $groups \type{\arrayof{\string}} List of internal group names
3193          * @return \type{\arrayof{\string}} List of permission key names for given groups combined
3194          */
3195         static function getGroupPermissions( $groups ) {
3196                 global $wgGroupPermissions, $wgRevokePermissions;
3197                 $rights = array();
3198                 // grant every granted permission first
3199                 foreach( $groups as $group ) {
3200                         if( isset( $wgGroupPermissions[$group] ) ) {
3201                                 $rights = array_merge( $rights,
3202                                         // array_filter removes empty items
3203                                         array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3204                         }
3205                 }
3206                 // now revoke the revoked permissions
3207                 foreach( $groups as $group ) {
3208                         if( isset( $wgRevokePermissions[$group] ) ) {
3209                                 $rights = array_diff( $rights,
3210                                         array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3211                         }
3212                 }
3213                 return array_unique( $rights );
3214         }
3215
3216         /**
3217          * Get all the groups who have a given permission
3218          *
3219          * @param $role \string Role to check
3220          * @return \type{\arrayof{\string}} List of internal group names with the given permission
3221          */
3222         static function getGroupsWithPermission( $role ) {
3223                 global $wgGroupPermissions;
3224                 $allowedGroups = array();
3225                 foreach ( $wgGroupPermissions as $group => $rights ) {
3226                         if ( isset( $rights[$role] ) && $rights[$role] ) {
3227                                 $allowedGroups[] = $group;
3228                         }
3229                 }
3230                 return $allowedGroups;
3231         }
3232
3233         /**
3234          * Get the localized descriptive name for a group, if it exists
3235          *
3236          * @param $group \string Internal group name
3237          * @return \string Localized descriptive group name
3238          */
3239         static function getGroupName( $group ) {
3240                 $key = "group-$group";
3241                 $name = wfMsg( $key );
3242                 return $name == '' || wfEmptyMsg( $key, $name )
3243                         ? $group
3244                         : $name;
3245         }
3246
3247         /**
3248          * Get the localized descriptive name for a member of a group, if it exists
3249          *
3250          * @param $group \string Internal group name
3251          * @return \string Localized name for group member
3252          */
3253         static function getGroupMember( $group ) {
3254                 $key = "group-$group-member";
3255                 $name = wfMsg( $key );
3256                 return $name == '' || wfEmptyMsg( $key, $name )
3257                         ? $group
3258                         : $name;
3259         }
3260
3261         /**
3262          * Return the set of defined explicit groups.
3263          * The implicit groups (by default *, 'user' and 'autoconfirmed')
3264          * are not included, as they are defined automatically, not in the database.
3265          * @return Array of internal group names
3266          */
3267         static function getAllGroups() {
3268                 global $wgGroupPermissions, $wgRevokePermissions;
3269                 return array_diff(
3270                         array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3271                         self::getImplicitGroups()
3272                 );
3273         }
3274
3275         /**
3276          * Get a list of all available permissions.
3277          * @return Array of permission names
3278          */
3279         static function getAllRights() {
3280                 if ( self::$mAllRights === false ) {
3281                         global $wgAvailableRights;
3282                         if ( count( $wgAvailableRights ) ) {
3283                                 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
3284                         } else {
3285                                 self::$mAllRights = self::$mCoreRights;
3286                         }
3287                         wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
3288                 }
3289                 return self::$mAllRights;
3290         }
3291
3292         /**
3293          * Get a list of implicit groups
3294          * @return \type{\arrayof{\string}} Array of internal group names
3295          */
3296         public static function getImplicitGroups() {
3297                 global $wgImplicitGroups;
3298                 $groups = $wgImplicitGroups;
3299                 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );       #deprecated, use $wgImplictGroups instead
3300                 return $groups;
3301         }
3302
3303         /**
3304          * Get the title of a page describing a particular group
3305          *
3306          * @param $group \string Internal group name
3307          * @return \types{\type{Title},\bool} Title of the page if it exists, false otherwise
3308          */
3309         static function getGroupPage( $group ) {
3310                 $page = wfMsgForContent( 'grouppage-' . $group );
3311                 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3312                         $title = Title::newFromText( $page );
3313                         if( is_object( $title ) )
3314                                 return $title;
3315                 }
3316                 return false;
3317         }
3318
3319         /**
3320          * Create a link to the group in HTML, if available;
3321          * else return the group name.
3322          *
3323          * @param $group \string Internal name of the group
3324          * @param $text \string The text of the link
3325          * @return \string HTML link to the group
3326          */
3327         static function makeGroupLinkHTML( $group, $text = '' ) {
3328                 if( $text == '' ) {
3329                         $text = self::getGroupName( $group );
3330                 }
3331                 $title = self::getGroupPage( $group );
3332                 if( $title ) {
3333                         global $wgUser;
3334                         $sk = $wgUser->getSkin();
3335                         return $sk->link( $title, htmlspecialchars( $text ) );
3336                 } else {
3337                         return $text;
3338                 }
3339         }
3340
3341         /**
3342          * Create a link to the group in Wikitext, if available;
3343          * else return the group name.
3344          *
3345          * @param $group \string Internal name of the group
3346          * @param $text \string The text of the link
3347          * @return \string Wikilink to the group
3348          */
3349         static function makeGroupLinkWiki( $group, $text = '' ) {
3350                 if( $text == '' ) {
3351                         $text = self::getGroupName( $group );
3352                 }
3353                 $title = self::getGroupPage( $group );
3354                 if( $title ) {
3355                         $page = $title->getPrefixedText();
3356                         return "[[$page|$text]]";
3357                 } else {
3358                         return $text;
3359                 }
3360         }
3361
3362         /**
3363          * Returns an array of the groups that a particular group can add/remove.
3364          *
3365          * @param $group String: the group to check for whether it can add/remove
3366          * @return Array array( 'add' => array( addablegroups ),
3367          *  'remove' => array( removablegroups ),
3368          *  'add-self' => array( addablegroups to self),
3369          *  'remove-self' => array( removable groups from self) )
3370          */
3371         static function changeableByGroup( $group ) {
3372                 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3373
3374                 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3375                 if( empty( $wgAddGroups[$group] ) ) {
3376                         // Don't add anything to $groups
3377                 } elseif( $wgAddGroups[$group] === true ) {
3378                         // You get everything
3379                         $groups['add'] = self::getAllGroups();
3380                 } elseif( is_array( $wgAddGroups[$group] ) ) {
3381                         $groups['add'] = $wgAddGroups[$group];
3382                 }
3383
3384                 // Same thing for remove
3385                 if( empty( $wgRemoveGroups[$group] ) ) {
3386                 } elseif( $wgRemoveGroups[$group] === true ) {
3387                         $groups['remove'] = self::getAllGroups();
3388                 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3389                         $groups['remove'] = $wgRemoveGroups[$group];
3390                 }
3391
3392                 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3393                 if( empty( $wgGroupsAddToSelf['user']) || $wgGroupsAddToSelf['user'] !== true ) {
3394                         foreach( $wgGroupsAddToSelf as $key => $value ) {
3395                                 if( is_int( $key ) ) {
3396                                         $wgGroupsAddToSelf['user'][] = $value;
3397                                 }
3398                         }
3399                 }
3400
3401                 if( empty( $wgGroupsRemoveFromSelf['user']) || $wgGroupsRemoveFromSelf['user'] !== true ) {
3402                         foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3403                                 if( is_int( $key ) ) {
3404                                         $wgGroupsRemoveFromSelf['user'][] = $value;
3405                                 }
3406                         }
3407                 }
3408
3409                 // Now figure out what groups the user can add to him/herself
3410                 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3411                 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3412                         // No idea WHY this would be used, but it's there
3413                         $groups['add-self'] = User::getAllGroups();
3414                 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3415                         $groups['add-self'] = $wgGroupsAddToSelf[$group];
3416                 }
3417
3418                 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3419                 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3420                         $groups['remove-self'] = User::getAllGroups();
3421                 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3422                         $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3423                 }
3424
3425                 return $groups;
3426         }
3427
3428         /**
3429          * Returns an array of groups that this user can add and remove
3430          * @return Array array( 'add' => array( addablegroups ),
3431          *  'remove' => array( removablegroups ),
3432          *  'add-self' => array( addablegroups to self),
3433          *  'remove-self' => array( removable groups from self) )
3434          */
3435         function changeableGroups() {
3436                 if( $this->isAllowed( 'userrights' ) ) {
3437                         // This group gives the right to modify everything (reverse-
3438                         // compatibility with old "userrights lets you change
3439                         // everything")
3440                         // Using array_merge to make the groups reindexed
3441                         $all = array_merge( User::getAllGroups() );
3442                         return array(
3443                                 'add' => $all,
3444                                 'remove' => $all,
3445                                 'add-self' => array(),
3446                                 'remove-self' => array()
3447                         );
3448                 }
3449
3450                 // Okay, it's not so simple, we will have to go through the arrays
3451                 $groups = array(
3452                         'add' => array(),
3453                         'remove' => array(),
3454                         'add-self' => array(),
3455                         'remove-self' => array()
3456                 );
3457                 $addergroups = $this->getEffectiveGroups();
3458
3459                 foreach( $addergroups as $addergroup ) {
3460                         $groups = array_merge_recursive(
3461                                 $groups, $this->changeableByGroup( $addergroup )
3462                         );
3463                         $groups['add']    = array_unique( $groups['add'] );
3464                         $groups['remove'] = array_unique( $groups['remove'] );
3465                         $groups['add-self'] = array_unique( $groups['add-self'] );
3466                         $groups['remove-self'] = array_unique( $groups['remove-self'] );
3467                 }
3468                 return $groups;
3469         }
3470
3471         /**
3472          * Increment the user's edit-count field.
3473          * Will have no effect for anonymous users.
3474          */
3475         function incEditCount() {
3476                 if( !$this->isAnon() ) {
3477                         $dbw = wfGetDB( DB_MASTER );
3478                         $dbw->update( 'user',
3479                                 array( 'user_editcount=user_editcount+1' ),
3480                                 array( 'user_id' => $this->getId() ),
3481                                 __METHOD__ );
3482
3483                         // Lazy initialization check...
3484                         if( $dbw->affectedRows() == 0 ) {
3485                                 // Pull from a slave to be less cruel to servers
3486                                 // Accuracy isn't the point anyway here
3487                                 $dbr = wfGetDB( DB_SLAVE );
3488                                 $count = $dbr->selectField( 'revision',
3489                                         'COUNT(rev_user)',
3490                                         array( 'rev_user' => $this->getId() ),
3491                                         __METHOD__ );
3492
3493                                 // Now here's a goddamn hack...
3494                                 if( $dbr !== $dbw ) {
3495                                         // If we actually have a slave server, the count is
3496                                         // at least one behind because the current transaction
3497                                         // has not been committed and replicated.
3498                                         $count++;
3499                                 } else {
3500                                         // But if DB_SLAVE is selecting the master, then the
3501                                         // count we just read includes the revision that was
3502                                         // just added in the working transaction.
3503                                 }
3504
3505                                 $dbw->update( 'user',
3506                                         array( 'user_editcount' => $count ),
3507                                         array( 'user_id' => $this->getId() ),
3508                                         __METHOD__ );
3509                         }
3510                 }
3511                 // edit count in user cache too
3512                 $this->invalidateCache();
3513         }
3514
3515         /**
3516          * Get the description of a given right
3517          *
3518          * @param $right \string Right to query
3519          * @return \string Localized description of the right
3520          */
3521         static function getRightDescription( $right ) {
3522                 $key = "right-$right";
3523                 $name = wfMsg( $key );
3524                 return $name == '' || wfEmptyMsg( $key, $name )
3525                         ? $right
3526                         : $name;
3527         }
3528
3529         /**
3530          * Make an old-style password hash
3531          *
3532          * @param $password \string Plain-text password
3533          * @param $userId \string User ID
3534          * @return \string Password hash
3535          */
3536         static function oldCrypt( $password, $userId ) {
3537                 global $wgPasswordSalt;
3538                 if ( $wgPasswordSalt ) {
3539                         return md5( $userId . '-' . md5( $password ) );
3540                 } else {
3541                         return md5( $password );
3542                 }
3543         }
3544
3545         /**
3546          * Make a new-style password hash
3547          *
3548          * @param $password \string Plain-text password
3549          * @param $salt \string Optional salt, may be random or the user ID.
3550          *                     If unspecified or false, will generate one automatically
3551          * @return \string Password hash
3552          */
3553         static function crypt( $password, $salt = false ) {
3554                 global $wgPasswordSalt;
3555
3556                 $hash = '';
3557                 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3558                         return $hash;
3559                 }
3560
3561                 if( $wgPasswordSalt ) {
3562                         if ( $salt === false ) {
3563                                 $salt = substr( wfGenerateToken(), 0, 8 );
3564                         }
3565                         return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3566                 } else {
3567                         return ':A:' . md5( $password );
3568                 }
3569         }
3570
3571         /**
3572          * Compare a password hash with a plain-text password. Requires the user
3573          * ID if there's a chance that the hash is an old-style hash.
3574          *
3575          * @param $hash \string Password hash
3576          * @param $password \string Plain-text password to compare
3577          * @param $userId \string User ID for old-style password salt
3578          * @return Boolean:
3579          */
3580         static function comparePasswords( $hash, $password, $userId = false ) {
3581                 $type = substr( $hash, 0, 3 );
3582
3583                 $result = false;
3584                 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3585                         return $result;
3586                 }
3587
3588                 if ( $type == ':A:' ) {
3589                         # Unsalted
3590                         return md5( $password ) === substr( $hash, 3 );
3591                 } elseif ( $type == ':B:' ) {
3592                         # Salted
3593                         list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3594                         return md5( $salt.'-'.md5( $password ) ) == $realHash;
3595                 } else {
3596                         # Old-style
3597                         return self::oldCrypt( $password, $userId ) === $hash;
3598                 }
3599         }
3600
3601         /**
3602          * Add a newuser log entry for this user
3603          *
3604          * @param $byEmail Boolean: account made by email?
3605          * @param $reason String: user supplied reason
3606          */
3607         public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
3608                 global $wgUser, $wgContLang, $wgNewUserLog;
3609                 if( empty( $wgNewUserLog ) ) {
3610                         return true; // disabled
3611                 }
3612
3613                 if( $this->getName() == $wgUser->getName() ) {
3614                         $action = 'create';
3615                 } else {
3616                         $action = 'create2';
3617                         if ( $byEmail ) {
3618                                 if ( $reason === '' ) {
3619                                         $reason = wfMsgForContent( 'newuserlog-byemail' );
3620                                 } else {
3621                                         $reason = $wgContLang->commaList( array(
3622                                                 $reason, wfMsgForContent( 'newuserlog-byemail' ) ) );
3623                                 }
3624                         }
3625                 }
3626                 $log = new LogPage( 'newusers' );
3627                 $log->addEntry(
3628                         $action,
3629                         $this->getUserPage(),
3630                         $reason,
3631                         array( $this->getId() )
3632                 );
3633                 return true;
3634         }
3635
3636         /**
3637          * Add an autocreate newuser log entry for this user
3638          * Used by things like CentralAuth and perhaps other authplugins.
3639          */
3640         public function addNewUserLogEntryAutoCreate() {
3641                 global $wgNewUserLog, $wgLogAutocreatedAccounts;
3642                 if( !$wgNewUserLog || !$wgLogAutocreatedAccounts ) {
3643                         return true; // disabled
3644                 }
3645                 $log = new LogPage( 'newusers', false );
3646                 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3647                 return true;
3648         }
3649
3650         protected function loadOptions() {
3651                 $this->load();
3652                 if ( $this->mOptionsLoaded || !$this->getId() )
3653                         return;
3654
3655                 $this->mOptions = self::getDefaultOptions();
3656
3657                 // Maybe load from the object
3658                 if ( !is_null( $this->mOptionOverrides ) ) {
3659                         wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
3660                         foreach( $this->mOptionOverrides as $key => $value ) {
3661                                 $this->mOptions[$key] = $value;
3662                         }
3663                 } else {
3664                         wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
3665                         // Load from database
3666                         $dbr = wfGetDB( DB_SLAVE );
3667
3668                         $res = $dbr->select(
3669                                 'user_properties',
3670                                 '*',
3671                                 array( 'up_user' => $this->getId() ),
3672                                 __METHOD__
3673                         );
3674
3675                         foreach ( $res as $row ) {
3676                                 $this->mOptionOverrides[$row->up_property] = $row->up_value;
3677                                 $this->mOptions[$row->up_property] = $row->up_value;
3678                         }
3679                 }
3680
3681                 $this->mOptionsLoaded = true;
3682
3683                 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
3684         }
3685
3686         protected function saveOptions() {
3687                 global $wgAllowPrefChange;
3688
3689                 $extuser = ExternalUser::newFromUser( $this );
3690
3691                 $this->loadOptions();
3692                 $dbw = wfGetDB( DB_MASTER );
3693
3694                 $insert_rows = array();
3695
3696                 $saveOptions = $this->mOptions;
3697
3698                 // Allow hooks to abort, for instance to save to a global profile.
3699                 // Reset options to default state before saving.
3700                 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3701                         return;
3702
3703                 foreach( $saveOptions as $key => $value ) {
3704                         # Don't bother storing default values
3705                         if ( ( is_null( self::getDefaultOption( $key ) ) &&
3706                                         !( $value === false || is_null($value) ) ) ||
3707                                         $value != self::getDefaultOption( $key ) ) {
3708                                 $insert_rows[] = array(
3709                                                 'up_user' => $this->getId(),
3710                                                 'up_property' => $key,
3711                                                 'up_value' => $value,
3712                                         );
3713                         }
3714                         if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3715                                 switch ( $wgAllowPrefChange[$key] ) {
3716                                         case 'local':
3717                                         case 'message':
3718                                                 break;
3719                                         case 'semiglobal':
3720                                         case 'global':
3721                                                 $extuser->setPref( $key, $value );
3722                                 }
3723                         }
3724                 }
3725
3726                 $dbw->begin();
3727                 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__ );
3728                 $dbw->insert( 'user_properties', $insert_rows, __METHOD__ );
3729                 $dbw->commit();
3730         }
3731
3732         /**
3733          * Provide an array of HTML5 attributes to put on an input element
3734          * intended for the user to enter a new password.  This may include
3735          * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3736          *
3737          * Do *not* use this when asking the user to enter his current password!
3738          * Regardless of configuration, users may have invalid passwords for whatever
3739          * reason (e.g., they were set before requirements were tightened up).
3740          * Only use it when asking for a new password, like on account creation or
3741          * ResetPass.
3742          *
3743          * Obviously, you still need to do server-side checking.
3744          *
3745          * NOTE: A combination of bugs in various browsers means that this function
3746          * actually just returns array() unconditionally at the moment.  May as
3747          * well keep it around for when the browser bugs get fixed, though.
3748          *
3749          * @return array Array of HTML attributes suitable for feeding to
3750          *   Html::element(), directly or indirectly.  (Don't feed to Xml::*()!
3751          *   That will potentially output invalid XHTML 1.0 Transitional, and will
3752          *   get confused by the boolean attribute syntax used.)
3753          */
3754         public static function passwordChangeInputAttribs() {
3755                 global $wgMinimalPasswordLength;
3756
3757                 if ( $wgMinimalPasswordLength == 0 ) {
3758                         return array();
3759                 }
3760
3761                 # Note that the pattern requirement will always be satisfied if the
3762                 # input is empty, so we need required in all cases.
3763                 #
3764                 # FIXME (bug 23769): This needs to not claim the password is required
3765                 # if e-mail confirmation is being used.  Since HTML5 input validation
3766                 # is b0rked anyway in some browsers, just return nothing.  When it's
3767                 # re-enabled, fix this code to not output required for e-mail
3768                 # registration.
3769                 #$ret = array( 'required' );
3770                 $ret = array();
3771
3772                 # We can't actually do this right now, because Opera 9.6 will print out
3773                 # the entered password visibly in its error message!  When other
3774                 # browsers add support for this attribute, or Opera fixes its support,
3775                 # we can add support with a version check to avoid doing this on Opera
3776                 # versions where it will be a problem.  Reported to Opera as
3777                 # DSK-262266, but they don't have a public bug tracker for us to follow.
3778                 /*
3779                 if ( $wgMinimalPasswordLength > 1 ) {
3780                         $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
3781                         $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
3782                                 $wgMinimalPasswordLength );
3783                 }
3784                 */
3785
3786                 return $ret;
3787         }
3788
3789         /**
3790          * Format the user message using a hook, a template, or, failing these, a static format.
3791          * @param $subject   String the subject of the message
3792          * @param $text      String the content of the message
3793          * @param $signature String the signature, if provided.
3794          */
3795         static protected function formatUserMessage( $subject, $text, $signature ) {
3796                 if ( wfRunHooks( 'FormatUserMessage',
3797                                 array( $subject, &$text, $signature ) ) ) {
3798
3799                         $signature = empty($signature) ? "~~~~~" : "{$signature} ~~~~~";
3800
3801                         $template = Title::newFromText( wfMsgForContent( 'usermessage-template' ) );
3802                         if ( !$template
3803                                         || $template->getNamespace() !== NS_TEMPLATE
3804                                         || !$template->exists() ) {
3805                                 $text = "\n== $subject ==\n\n$text\n\n-- $signature";
3806                         } else {
3807                                 $text = '{{'. $template->getText()
3808                                         . " | subject=$subject | body=$text | signature=$signature }}";
3809                         }
3810                 }
3811
3812                 return $text;
3813         }
3814
3815         /**
3816          * Leave a user a message
3817          * @param $subject String the subject of the message
3818          * @param $text String the message to leave
3819          * @param $signature String Text to leave in the signature
3820          * @param $summary String the summary for this change, defaults to
3821          *                        "Leave system message."
3822          * @param $editor User The user leaving the message, defaults to
3823          *                        "{{MediaWiki:usermessage-editor}}"
3824          * @param $flags Int default edit flags
3825          *
3826          * @return boolean true if it was successful
3827          */
3828         public function leaveUserMessage( $subject, $text, $signature = "",
3829                         $summary = null, $editor = null, $flags = 0 ) {
3830                 if ( !isset( $summary ) ) {
3831                         $summary = wfMsgForContent( 'usermessage-summary' );
3832                 }
3833
3834                 if ( !isset( $editor ) ) {
3835                         $editor = User::newFromName( wfMsgForContent( 'usermessage-editor' ) );
3836                         if ( !$editor->isLoggedIn() ) {
3837                                 $editor->addToDatabase();
3838                         }
3839                 }
3840
3841                 $article = new Article( $this->getTalkPage() );
3842                 wfRunHooks( 'SetupUserMessageArticle',
3843                         array( $this, &$article, $subject, $text, $signature, $summary, $editor ) );
3844
3845
3846                 $text = self::formatUserMessage( $subject, $text, $signature );
3847                 $flags = $article->checkFlags( $flags );
3848
3849                 if ( $flags & EDIT_UPDATE ) {
3850                         $text = $article->getContent() . $text;
3851                 }
3852
3853                 $dbw = wfGetDB( DB_MASTER );
3854                 $dbw->begin();
3855
3856                 try {
3857                         $status = $article->doEdit( $text, $summary, $flags, false, $editor );
3858                 } catch ( DBQueryError $e ) {
3859                         $status = Status::newFatal("DB Error");
3860                 }
3861
3862                 if ( $status->isGood() ) {
3863                         // Set newtalk with the right user ID
3864                         $this->setNewtalk( true );
3865                         wfRunHooks( 'AfterUserMessage',
3866                                 array( $this, $article, $summary, $text, $signature, $summary, $editor ) );
3867                         $dbw->commit();
3868                 } else {
3869                         // The article was concurrently created
3870                         wfDebug( __METHOD__ . ": Error ".$status->getWikiText() );
3871                         $dbw->rollback();
3872                 }
3873
3874                 return $status->isGood();
3875         }
3876 }