Merge "jquery.suggestions: Handle CSS ellipsis better for IE"
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 */
22
23 /**
24 * Int Number of characters in user_token field.
25 * @ingroup Constants
26 */
27 define( 'USER_TOKEN_LENGTH', 32 );
28
29 /**
30 * Int Serialized record version.
31 * @ingroup Constants
32 */
33 define( 'MW_USER_VERSION', 9 );
34
35 /**
36 * String Some punctuation to prevent editing from broken text-mangling proxies.
37 * @ingroup Constants
38 */
39 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
40
41 /**
42 * Thrown by User::setPassword() on error.
43 * @ingroup Exception
44 */
45 class PasswordError extends MWException {
46 // NOP
47 }
48
49 /**
50 * The User object encapsulates all of the user-specific settings (user_id,
51 * name, rights, password, email address, options, last login time). Client
52 * classes use the getXXX() functions to access these fields. These functions
53 * do all the work of determining whether the user is logged in,
54 * whether the requested option can be satisfied from cookies or
55 * whether a database query is needed. Most of the settings needed
56 * for rendering normal pages are set in the cookie to minimize use
57 * of the database.
58 */
59 class User {
60 /**
61 * Global constants made accessible as class constants so that autoloader
62 * magic can be used.
63 */
64 const USER_TOKEN_LENGTH = USER_TOKEN_LENGTH;
65 const MW_USER_VERSION = MW_USER_VERSION;
66 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
67
68 /**
69 * Maximum items in $mWatchedItems
70 */
71 const MAX_WATCHED_ITEMS_CACHE = 100;
72
73 /**
74 * Array of Strings List of member variables which are saved to the
75 * shared cache (memcached). Any operation which changes the
76 * corresponding database fields must call a cache-clearing function.
77 * @showinitializer
78 */
79 protected static $mCacheVars = array(
80 // user table
81 'mId',
82 'mName',
83 'mRealName',
84 'mPassword',
85 'mNewpassword',
86 'mNewpassTime',
87 'mEmail',
88 'mTouched',
89 'mToken',
90 'mEmailAuthenticated',
91 'mEmailToken',
92 'mEmailTokenExpires',
93 'mPasswordExpires',
94 'mRegistration',
95 'mEditCount',
96 // user_groups table
97 'mGroups',
98 // user_properties table
99 'mOptionOverrides',
100 );
101
102 /**
103 * Array of Strings Core rights.
104 * Each of these should have a corresponding message of the form
105 * "right-$right".
106 * @showinitializer
107 */
108 protected static $mCoreRights = array(
109 'apihighlimits',
110 'autoconfirmed',
111 'autopatrol',
112 'bigdelete',
113 'block',
114 'blockemail',
115 'bot',
116 'browsearchive',
117 'createaccount',
118 'createpage',
119 'createtalk',
120 'delete',
121 'deletedhistory',
122 'deletedtext',
123 'deletelogentry',
124 'deleterevision',
125 'edit',
126 'editinterface',
127 'editprotected',
128 'editmyoptions',
129 'editmyprivateinfo',
130 'editmyusercss',
131 'editmyuserjs',
132 'editmywatchlist',
133 'editsemiprotected',
134 'editusercssjs', #deprecated
135 'editusercss',
136 'edituserjs',
137 'hideuser',
138 'import',
139 'importupload',
140 'ipblock-exempt',
141 'markbotedits',
142 'mergehistory',
143 'minoredit',
144 'move',
145 'movefile',
146 'move-categorypages',
147 'move-rootuserpages',
148 'move-subpages',
149 'nominornewtalk',
150 'noratelimit',
151 'override-export-depth',
152 'passwordreset',
153 'patrol',
154 'patrolmarks',
155 'protect',
156 'proxyunbannable',
157 'purge',
158 'read',
159 'reupload',
160 'reupload-own',
161 'reupload-shared',
162 'rollback',
163 'sendemail',
164 'siteadmin',
165 'suppressionlog',
166 'suppressredirect',
167 'suppressrevision',
168 'unblockself',
169 'undelete',
170 'unwatchedpages',
171 'upload',
172 'upload_by_url',
173 'userrights',
174 'userrights-interwiki',
175 'viewmyprivateinfo',
176 'viewmywatchlist',
177 'writeapi',
178 );
179
180 /**
181 * String Cached results of getAllRights()
182 */
183 protected static $mAllRights = false;
184
185 /** @name Cache variables */
186 //@{
187 public $mId;
188
189 public $mName;
190
191 public $mRealName;
192
193 public $mPassword;
194
195 public $mNewpassword;
196
197 public $mNewpassTime;
198
199 public $mEmail;
200
201 public $mTouched;
202
203 protected $mToken;
204
205 public $mEmailAuthenticated;
206
207 protected $mEmailToken;
208
209 protected $mEmailTokenExpires;
210
211 protected $mRegistration;
212
213 protected $mEditCount;
214
215 public $mGroups;
216
217 protected $mOptionOverrides;
218
219 protected $mPasswordExpires;
220 //@}
221
222 /**
223 * Bool Whether the cache variables have been loaded.
224 */
225 //@{
226 public $mOptionsLoaded;
227
228 /**
229 * Array with already loaded items or true if all items have been loaded.
230 */
231 protected $mLoadedItems = array();
232 //@}
233
234 /**
235 * String Initialization data source if mLoadedItems!==true. May be one of:
236 * - 'defaults' anonymous user initialised from class defaults
237 * - 'name' initialise from mName
238 * - 'id' initialise from mId
239 * - 'session' log in from cookies or session if possible
240 *
241 * Use the User::newFrom*() family of functions to set this.
242 */
243 public $mFrom;
244
245 /**
246 * Lazy-initialized variables, invalidated with clearInstanceCache
247 */
248 protected $mNewtalk;
249
250 protected $mDatePreference;
251
252 public $mBlockedby;
253
254 protected $mHash;
255
256 public $mRights;
257
258 protected $mBlockreason;
259
260 protected $mEffectiveGroups;
261
262 protected $mImplicitGroups;
263
264 protected $mFormerGroups;
265
266 protected $mBlockedGlobally;
267
268 protected $mLocked;
269
270 public $mHideName;
271
272 public $mOptions;
273
274 /**
275 * @var WebRequest
276 */
277 private $mRequest;
278
279 /** @var Block */
280 public $mBlock;
281
282 /** @var bool */
283 protected $mAllowUsertalk;
284
285 /** @var Block */
286 private $mBlockedFromCreateAccount = false;
287
288 /** @var array */
289 private $mWatchedItems = array();
290
291 public static $idCacheByName = array();
292
293 /**
294 * Lightweight constructor for an anonymous user.
295 * Use the User::newFrom* factory functions for other kinds of users.
296 *
297 * @see newFromName()
298 * @see newFromId()
299 * @see newFromConfirmationCode()
300 * @see newFromSession()
301 * @see newFromRow()
302 */
303 public function __construct() {
304 $this->clearInstanceCache( 'defaults' );
305 }
306
307 /**
308 * @return string
309 */
310 public function __toString() {
311 return $this->getName();
312 }
313
314 /**
315 * Load the user table data for this object from the source given by mFrom.
316 */
317 public function load() {
318 if ( $this->mLoadedItems === true ) {
319 return;
320 }
321 wfProfileIn( __METHOD__ );
322
323 // Set it now to avoid infinite recursion in accessors
324 $this->mLoadedItems = true;
325
326 switch ( $this->mFrom ) {
327 case 'defaults':
328 $this->loadDefaults();
329 break;
330 case 'name':
331 $this->mId = self::idFromName( $this->mName );
332 if ( !$this->mId ) {
333 // Nonexistent user placeholder object
334 $this->loadDefaults( $this->mName );
335 } else {
336 $this->loadFromId();
337 }
338 break;
339 case 'id':
340 $this->loadFromId();
341 break;
342 case 'session':
343 if ( !$this->loadFromSession() ) {
344 // Loading from session failed. Load defaults.
345 $this->loadDefaults();
346 }
347 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
348 break;
349 default:
350 wfProfileOut( __METHOD__ );
351 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
352 }
353 wfProfileOut( __METHOD__ );
354 }
355
356 /**
357 * Load user table data, given mId has already been set.
358 * @return bool false if the ID does not exist, true otherwise
359 */
360 public function loadFromId() {
361 global $wgMemc;
362 if ( $this->mId == 0 ) {
363 $this->loadDefaults();
364 return false;
365 }
366
367 // Try cache
368 $key = wfMemcKey( 'user', 'id', $this->mId );
369 $data = $wgMemc->get( $key );
370 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
371 // Object is expired, load from DB
372 $data = false;
373 }
374
375 if ( !$data ) {
376 wfDebug( "User: cache miss for user {$this->mId}\n" );
377 // Load from DB
378 if ( !$this->loadFromDatabase() ) {
379 // Can't load from ID, user is anonymous
380 return false;
381 }
382 $this->saveToCache();
383 } else {
384 wfDebug( "User: got user {$this->mId} from cache\n" );
385 // Restore from cache
386 foreach ( self::$mCacheVars as $name ) {
387 $this->$name = $data[$name];
388 }
389 }
390
391 $this->mLoadedItems = true;
392
393 return true;
394 }
395
396 /**
397 * Save user data to the shared cache
398 */
399 public function saveToCache() {
400 $this->load();
401 $this->loadGroups();
402 $this->loadOptions();
403 if ( $this->isAnon() ) {
404 // Anonymous users are uncached
405 return;
406 }
407 $data = array();
408 foreach ( self::$mCacheVars as $name ) {
409 $data[$name] = $this->$name;
410 }
411 $data['mVersion'] = MW_USER_VERSION;
412 $key = wfMemcKey( 'user', 'id', $this->mId );
413 global $wgMemc;
414 $wgMemc->set( $key, $data );
415 }
416
417 /** @name newFrom*() static factory methods */
418 //@{
419
420 /**
421 * Static factory method for creation from username.
422 *
423 * This is slightly less efficient than newFromId(), so use newFromId() if
424 * you have both an ID and a name handy.
425 *
426 * @param string $name Username, validated by Title::newFromText()
427 * @param string|bool $validate Validate username. Takes the same parameters as
428 * User::getCanonicalName(), except that true is accepted as an alias
429 * for 'valid', for BC.
430 *
431 * @return User|bool User object, or false if the username is invalid
432 * (e.g. if it contains illegal characters or is an IP address). If the
433 * username is not present in the database, the result will be a user object
434 * with a name, zero user ID and default settings.
435 */
436 public static function newFromName( $name, $validate = 'valid' ) {
437 if ( $validate === true ) {
438 $validate = 'valid';
439 }
440 $name = self::getCanonicalName( $name, $validate );
441 if ( $name === false ) {
442 return false;
443 } else {
444 // Create unloaded user object
445 $u = new User;
446 $u->mName = $name;
447 $u->mFrom = 'name';
448 $u->setItemLoaded( 'name' );
449 return $u;
450 }
451 }
452
453 /**
454 * Static factory method for creation from a given user ID.
455 *
456 * @param int $id Valid user ID
457 * @return User The corresponding User object
458 */
459 public static function newFromId( $id ) {
460 $u = new User;
461 $u->mId = $id;
462 $u->mFrom = 'id';
463 $u->setItemLoaded( 'id' );
464 return $u;
465 }
466
467 /**
468 * Factory method to fetch whichever user has a given email confirmation code.
469 * This code is generated when an account is created or its e-mail address
470 * has changed.
471 *
472 * If the code is invalid or has expired, returns NULL.
473 *
474 * @param string $code Confirmation code
475 * @return User|null
476 */
477 public static function newFromConfirmationCode( $code ) {
478 $dbr = wfGetDB( DB_SLAVE );
479 $id = $dbr->selectField( 'user', 'user_id', array(
480 'user_email_token' => md5( $code ),
481 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
482 ) );
483 if ( $id !== false ) {
484 return User::newFromId( $id );
485 } else {
486 return null;
487 }
488 }
489
490 /**
491 * Create a new user object using data from session or cookies. If the
492 * login credentials are invalid, the result is an anonymous user.
493 *
494 * @param WebRequest|null $request Object to use; $wgRequest will be used if omitted.
495 * @return User
496 */
497 public static function newFromSession( WebRequest $request = null ) {
498 $user = new User;
499 $user->mFrom = 'session';
500 $user->mRequest = $request;
501 return $user;
502 }
503
504 /**
505 * Create a new user object from a user row.
506 * The row should have the following fields from the user table in it:
507 * - either user_name or user_id to load further data if needed (or both)
508 * - user_real_name
509 * - all other fields (email, password, etc.)
510 * It is useless to provide the remaining fields if either user_id,
511 * user_name and user_real_name are not provided because the whole row
512 * will be loaded once more from the database when accessing them.
513 *
514 * @param stdClass $row A row from the user table
515 * @param array $data Further data to load into the object (see User::loadFromRow for valid keys)
516 * @return User
517 */
518 public static function newFromRow( $row, $data = null ) {
519 $user = new User;
520 $user->loadFromRow( $row, $data );
521 return $user;
522 }
523
524 //@}
525
526 /**
527 * Get the username corresponding to a given user ID
528 * @param int $id User ID
529 * @return string|bool The corresponding username
530 */
531 public static function whoIs( $id ) {
532 return UserCache::singleton()->getProp( $id, 'name' );
533 }
534
535 /**
536 * Get the real name of a user given their user ID
537 *
538 * @param int $id User ID
539 * @return string|bool The corresponding user's real name
540 */
541 public static function whoIsReal( $id ) {
542 return UserCache::singleton()->getProp( $id, 'real_name' );
543 }
544
545 /**
546 * Get database id given a user name
547 * @param string $name Username
548 * @return int|null The corresponding user's ID, or null if user is nonexistent
549 */
550 public static function idFromName( $name ) {
551 $nt = Title::makeTitleSafe( NS_USER, $name );
552 if ( is_null( $nt ) ) {
553 // Illegal name
554 return null;
555 }
556
557 if ( isset( self::$idCacheByName[$name] ) ) {
558 return self::$idCacheByName[$name];
559 }
560
561 $dbr = wfGetDB( DB_SLAVE );
562 $s = $dbr->selectRow(
563 'user',
564 array( 'user_id' ),
565 array( 'user_name' => $nt->getText() ),
566 __METHOD__
567 );
568
569 if ( $s === false ) {
570 $result = null;
571 } else {
572 $result = $s->user_id;
573 }
574
575 self::$idCacheByName[$name] = $result;
576
577 if ( count( self::$idCacheByName ) > 1000 ) {
578 self::$idCacheByName = array();
579 }
580
581 return $result;
582 }
583
584 /**
585 * Reset the cache used in idFromName(). For use in tests.
586 */
587 public static function resetIdByNameCache() {
588 self::$idCacheByName = array();
589 }
590
591 /**
592 * Does the string match an anonymous IPv4 address?
593 *
594 * This function exists for username validation, in order to reject
595 * usernames which are similar in form to IP addresses. Strings such
596 * as 300.300.300.300 will return true because it looks like an IP
597 * address, despite not being strictly valid.
598 *
599 * We match "\d{1,3}\.\d{1,3}\.\d{1,3}\.xxx" as an anonymous IP
600 * address because the usemod software would "cloak" anonymous IP
601 * addresses like this, if we allowed accounts like this to be created
602 * new users could get the old edits of these anonymous users.
603 *
604 * @param string $name Name to match
605 * @return bool
606 */
607 public static function isIP( $name ) {
608 return preg_match( '/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/', $name )
609 || IP::isIPv6( $name );
610 }
611
612 /**
613 * Is the input a valid username?
614 *
615 * Checks if the input is a valid username, we don't want an empty string,
616 * an IP address, anything that contains slashes (would mess up subpages),
617 * is longer than the maximum allowed username size or doesn't begin with
618 * a capital letter.
619 *
620 * @param string $name Name to match
621 * @return bool
622 */
623 public static function isValidUserName( $name ) {
624 global $wgContLang, $wgMaxNameChars;
625
626 if ( $name == ''
627 || User::isIP( $name )
628 || strpos( $name, '/' ) !== false
629 || strlen( $name ) > $wgMaxNameChars
630 || $name != $wgContLang->ucfirst( $name ) ) {
631 wfDebugLog( 'username', __METHOD__ .
632 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
633 return false;
634 }
635
636 // Ensure that the name can't be misresolved as a different title,
637 // such as with extra namespace keys at the start.
638 $parsed = Title::newFromText( $name );
639 if ( is_null( $parsed )
640 || $parsed->getNamespace()
641 || strcmp( $name, $parsed->getPrefixedText() ) ) {
642 wfDebugLog( 'username', __METHOD__ .
643 ": '$name' invalid due to ambiguous prefixes" );
644 return false;
645 }
646
647 // Check an additional blacklist of troublemaker characters.
648 // Should these be merged into the title char list?
649 $unicodeBlacklist = '/[' .
650 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
651 '\x{00a0}' . # non-breaking space
652 '\x{2000}-\x{200f}' . # various whitespace
653 '\x{2028}-\x{202f}' . # breaks and control chars
654 '\x{3000}' . # ideographic space
655 '\x{e000}-\x{f8ff}' . # private use
656 ']/u';
657 if ( preg_match( $unicodeBlacklist, $name ) ) {
658 wfDebugLog( 'username', __METHOD__ .
659 ": '$name' invalid due to blacklisted characters" );
660 return false;
661 }
662
663 return true;
664 }
665
666 /**
667 * Usernames which fail to pass this function will be blocked
668 * from user login and new account registrations, but may be used
669 * internally by batch processes.
670 *
671 * If an account already exists in this form, login will be blocked
672 * by a failure to pass this function.
673 *
674 * @param string $name Name to match
675 * @return bool
676 */
677 public static function isUsableName( $name ) {
678 global $wgReservedUsernames;
679 // Must be a valid username, obviously ;)
680 if ( !self::isValidUserName( $name ) ) {
681 return false;
682 }
683
684 static $reservedUsernames = false;
685 if ( !$reservedUsernames ) {
686 $reservedUsernames = $wgReservedUsernames;
687 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
688 }
689
690 // Certain names may be reserved for batch processes.
691 foreach ( $reservedUsernames as $reserved ) {
692 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
693 $reserved = wfMessage( substr( $reserved, 4 ) )->inContentLanguage()->text();
694 }
695 if ( $reserved == $name ) {
696 return false;
697 }
698 }
699 return true;
700 }
701
702 /**
703 * Usernames which fail to pass this function will be blocked
704 * from new account registrations, but may be used internally
705 * either by batch processes or by user accounts which have
706 * already been created.
707 *
708 * Additional blacklisting may be added here rather than in
709 * isValidUserName() to avoid disrupting existing accounts.
710 *
711 * @param string $name String to match
712 * @return bool
713 */
714 public static function isCreatableName( $name ) {
715 global $wgInvalidUsernameCharacters;
716
717 // Ensure that the username isn't longer than 235 bytes, so that
718 // (at least for the builtin skins) user javascript and css files
719 // will work. (bug 23080)
720 if ( strlen( $name ) > 235 ) {
721 wfDebugLog( 'username', __METHOD__ .
722 ": '$name' invalid due to length" );
723 return false;
724 }
725
726 // Preg yells if you try to give it an empty string
727 if ( $wgInvalidUsernameCharacters !== '' ) {
728 if ( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
729 wfDebugLog( 'username', __METHOD__ .
730 ": '$name' invalid due to wgInvalidUsernameCharacters" );
731 return false;
732 }
733 }
734
735 return self::isUsableName( $name );
736 }
737
738 /**
739 * Is the input a valid password for this user?
740 *
741 * @param string $password Desired password
742 * @return bool
743 */
744 public function isValidPassword( $password ) {
745 //simple boolean wrapper for getPasswordValidity
746 return $this->getPasswordValidity( $password ) === true;
747 }
748
749
750 /**
751 * Given unvalidated password input, return error message on failure.
752 *
753 * @param string $password Desired password
754 * @return bool|string|array true on success, string or array of error message on failure
755 */
756 public function getPasswordValidity( $password ) {
757 $result = $this->checkPasswordValidity( $password );
758 if ( $result->isGood() ) {
759 return true;
760 } else {
761 $messages = array();
762 foreach ( $result->getErrorsByType( 'error' ) as $error ) {
763 $messages[] = $error['message'];
764 }
765 foreach ( $result->getErrorsByType( 'warning' ) as $warning ) {
766 $messages[] = $warning['message'];
767 }
768 if ( count( $messages ) === 1 ) {
769 return $messages[0];
770 }
771 return $messages;
772 }
773 }
774
775 /**
776 * Check if this is a valid password for this user. Status will be good if
777 * the password is valid, or have an array of error messages if not.
778 *
779 * @param string $password Desired password
780 * @return Status
781 * @since 1.23
782 */
783 public function checkPasswordValidity( $password ) {
784 global $wgMinimalPasswordLength, $wgContLang;
785
786 static $blockedLogins = array(
787 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
788 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
789 );
790
791 $status = Status::newGood();
792
793 $result = false; //init $result to false for the internal checks
794
795 if ( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) ) {
796 $status->error( $result );
797 return $status;
798 }
799
800 if ( $result === false ) {
801 if ( strlen( $password ) < $wgMinimalPasswordLength ) {
802 $status->error( 'passwordtooshort', $wgMinimalPasswordLength );
803 return $status;
804 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
805 $status->error( 'password-name-match' );
806 return $status;
807 } elseif ( isset( $blockedLogins[$this->getName()] )
808 && $password == $blockedLogins[$this->getName()]
809 ) {
810 $status->error( 'password-login-forbidden' );
811 return $status;
812 } else {
813 //it seems weird returning a Good status here, but this is because of the
814 //initialization of $result to false above. If the hook is never run or it
815 //doesn't modify $result, then we will likely get down into this if with
816 //a valid password.
817 return $status;
818 }
819 } elseif ( $result === true ) {
820 return $status;
821 } else {
822 $status->error( $result );
823 return $status; //the isValidPassword hook set a string $result and returned true
824 }
825 }
826
827 /**
828 * Expire a user's password
829 * @since 1.23
830 * @param int $ts Optional timestamp to convert, default 0 for the current time
831 */
832 public function expirePassword( $ts = 0 ) {
833 $this->load();
834 $timestamp = wfTimestamp( TS_MW, $ts );
835 $this->mPasswordExpires = $timestamp;
836 $this->saveSettings();
837 }
838
839 /**
840 * Clear the password expiration for a user
841 * @since 1.23
842 * @param bool $load Ensure user object is loaded first
843 */
844 public function resetPasswordExpiration( $load = true ) {
845 global $wgPasswordExpirationDays;
846 if ( $load ) {
847 $this->load();
848 }
849 $newExpire = null;
850 if ( $wgPasswordExpirationDays ) {
851 $newExpire = wfTimestamp(
852 TS_MW,
853 time() + ( $wgPasswordExpirationDays * 24 * 3600 )
854 );
855 }
856 // Give extensions a chance to force an expiration
857 wfRunHooks( 'ResetPasswordExpiration', array( $this, &$newExpire ) );
858 $this->mPasswordExpires = $newExpire;
859 }
860
861 /**
862 * Check if the user's password is expired.
863 * TODO: Put this and password length into a PasswordPolicy object
864 * @since 1.23
865 * @return string|bool The expiration type, or false if not expired
866 * hard: A password change is required to login
867 * soft: Allow login, but encourage password change
868 * false: Password is not expired
869 */
870 public function getPasswordExpired() {
871 global $wgPasswordExpireGrace;
872 $expired = false;
873 $now = wfTimestamp();
874 $expiration = $this->getPasswordExpireDate();
875 $expUnix = wfTimestamp( TS_UNIX, $expiration );
876 if ( $expiration !== null && $expUnix < $now ) {
877 $expired = ( $expUnix + $wgPasswordExpireGrace < $now ) ? 'hard' : 'soft';
878 }
879 return $expired;
880 }
881
882 /**
883 * Get this user's password expiration date. Since this may be using
884 * the cached User object, we assume that whatever mechanism is setting
885 * the expiration date is also expiring the User cache.
886 * @since 1.23
887 * @return string|bool The datestamp of the expiration, or null if not set
888 */
889 public function getPasswordExpireDate() {
890 $this->load();
891 return $this->mPasswordExpires;
892 }
893
894 /**
895 * Does a string look like an e-mail address?
896 *
897 * This validates an email address using an HTML5 specification found at:
898 * http://www.whatwg.org/html/states-of-the-type-attribute.html#valid-e-mail-address
899 * Which as of 2011-01-24 says:
900 *
901 * A valid e-mail address is a string that matches the ABNF production
902 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
903 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
904 * 3.5.
905 *
906 * This function is an implementation of the specification as requested in
907 * bug 22449.
908 *
909 * Client-side forms will use the same standard validation rules via JS or
910 * HTML 5 validation; additional restrictions can be enforced server-side
911 * by extensions via the 'isValidEmailAddr' hook.
912 *
913 * Note that this validation doesn't 100% match RFC 2822, but is believed
914 * to be liberal enough for wide use. Some invalid addresses will still
915 * pass validation here.
916 *
917 * @param string $addr E-mail address
918 * @return bool
919 * @deprecated since 1.18 call Sanitizer::isValidEmail() directly
920 */
921 public static function isValidEmailAddr( $addr ) {
922 wfDeprecated( __METHOD__, '1.18' );
923 return Sanitizer::validateEmail( $addr );
924 }
925
926 /**
927 * Given unvalidated user input, return a canonical username, or false if
928 * the username is invalid.
929 * @param string $name User input
930 * @param string|bool $validate Type of validation to use:
931 * - false No validation
932 * - 'valid' Valid for batch processes
933 * - 'usable' Valid for batch processes and login
934 * - 'creatable' Valid for batch processes, login and account creation
935 *
936 * @throws MWException
937 * @return bool|string
938 */
939 public static function getCanonicalName( $name, $validate = 'valid' ) {
940 // Force usernames to capital
941 global $wgContLang;
942 $name = $wgContLang->ucfirst( $name );
943
944 # Reject names containing '#'; these will be cleaned up
945 # with title normalisation, but then it's too late to
946 # check elsewhere
947 if ( strpos( $name, '#' ) !== false ) {
948 return false;
949 }
950
951 // Clean up name according to title rules
952 $t = ( $validate === 'valid' ) ?
953 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
954 // Check for invalid titles
955 if ( is_null( $t ) ) {
956 return false;
957 }
958
959 // Reject various classes of invalid names
960 global $wgAuth;
961 $name = $wgAuth->getCanonicalName( $t->getText() );
962
963 switch ( $validate ) {
964 case false:
965 break;
966 case 'valid':
967 if ( !User::isValidUserName( $name ) ) {
968 $name = false;
969 }
970 break;
971 case 'usable':
972 if ( !User::isUsableName( $name ) ) {
973 $name = false;
974 }
975 break;
976 case 'creatable':
977 if ( !User::isCreatableName( $name ) ) {
978 $name = false;
979 }
980 break;
981 default:
982 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
983 }
984 return $name;
985 }
986
987 /**
988 * Count the number of edits of a user
989 *
990 * @param int $uid User ID to check
991 * @return int The user's edit count
992 *
993 * @deprecated since 1.21 in favour of User::getEditCount
994 */
995 public static function edits( $uid ) {
996 wfDeprecated( __METHOD__, '1.21' );
997 $user = self::newFromId( $uid );
998 return $user->getEditCount();
999 }
1000
1001 /**
1002 * Return a random password.
1003 *
1004 * @return string New random password
1005 */
1006 public static function randomPassword() {
1007 global $wgMinimalPasswordLength;
1008 // Decide the final password length based on our min password length,
1009 // stopping at a minimum of 10 chars.
1010 $length = max( 10, $wgMinimalPasswordLength );
1011 // Multiply by 1.25 to get the number of hex characters we need
1012 $length = $length * 1.25;
1013 // Generate random hex chars
1014 $hex = MWCryptRand::generateHex( $length );
1015 // Convert from base 16 to base 32 to get a proper password like string
1016 return wfBaseConvert( $hex, 16, 32 );
1017 }
1018
1019 /**
1020 * Set cached properties to default.
1021 *
1022 * @note This no longer clears uncached lazy-initialised properties;
1023 * the constructor does that instead.
1024 *
1025 * @param string|bool $name
1026 */
1027 public function loadDefaults( $name = false ) {
1028 wfProfileIn( __METHOD__ );
1029
1030 $this->mId = 0;
1031 $this->mName = $name;
1032 $this->mRealName = '';
1033 $this->mPassword = $this->mNewpassword = '';
1034 $this->mNewpassTime = null;
1035 $this->mEmail = '';
1036 $this->mOptionOverrides = null;
1037 $this->mOptionsLoaded = false;
1038
1039 $loggedOut = $this->getRequest()->getCookie( 'LoggedOut' );
1040 if ( $loggedOut !== null ) {
1041 $this->mTouched = wfTimestamp( TS_MW, $loggedOut );
1042 } else {
1043 $this->mTouched = '1'; # Allow any pages to be cached
1044 }
1045
1046 $this->mToken = null; // Don't run cryptographic functions till we need a token
1047 $this->mEmailAuthenticated = null;
1048 $this->mEmailToken = '';
1049 $this->mEmailTokenExpires = null;
1050 $this->mPasswordExpires = null;
1051 $this->resetPasswordExpiration( false );
1052 $this->mRegistration = wfTimestamp( TS_MW );
1053 $this->mGroups = array();
1054
1055 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
1056
1057 wfProfileOut( __METHOD__ );
1058 }
1059
1060 /**
1061 * Return whether an item has been loaded.
1062 *
1063 * @param string $item Item to check. Current possibilities:
1064 * - id
1065 * - name
1066 * - realname
1067 * @param string $all 'all' to check if the whole object has been loaded
1068 * or any other string to check if only the item is available (e.g.
1069 * for optimisation)
1070 * @return bool
1071 */
1072 public function isItemLoaded( $item, $all = 'all' ) {
1073 return ( $this->mLoadedItems === true && $all === 'all' ) ||
1074 ( isset( $this->mLoadedItems[$item] ) && $this->mLoadedItems[$item] === true );
1075 }
1076
1077 /**
1078 * Set that an item has been loaded
1079 *
1080 * @param string $item
1081 */
1082 protected function setItemLoaded( $item ) {
1083 if ( is_array( $this->mLoadedItems ) ) {
1084 $this->mLoadedItems[$item] = true;
1085 }
1086 }
1087
1088 /**
1089 * Load user data from the session or login cookie.
1090 * @return bool True if the user is logged in, false otherwise.
1091 */
1092 private function loadFromSession() {
1093 $result = null;
1094 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
1095 if ( $result !== null ) {
1096 return $result;
1097 }
1098
1099 $request = $this->getRequest();
1100
1101 $cookieId = $request->getCookie( 'UserID' );
1102 $sessId = $request->getSessionData( 'wsUserID' );
1103
1104 if ( $cookieId !== null ) {
1105 $sId = intval( $cookieId );
1106 if ( $sessId !== null && $cookieId != $sessId ) {
1107 wfDebugLog( 'loginSessions', "Session user ID ($sessId) and
1108 cookie user ID ($sId) don't match!" );
1109 return false;
1110 }
1111 $request->setSessionData( 'wsUserID', $sId );
1112 } elseif ( $sessId !== null && $sessId != 0 ) {
1113 $sId = $sessId;
1114 } else {
1115 return false;
1116 }
1117
1118 if ( $request->getSessionData( 'wsUserName' ) !== null ) {
1119 $sName = $request->getSessionData( 'wsUserName' );
1120 } elseif ( $request->getCookie( 'UserName' ) !== null ) {
1121 $sName = $request->getCookie( 'UserName' );
1122 $request->setSessionData( 'wsUserName', $sName );
1123 } else {
1124 return false;
1125 }
1126
1127 $proposedUser = User::newFromId( $sId );
1128 if ( !$proposedUser->isLoggedIn() ) {
1129 // Not a valid ID
1130 return false;
1131 }
1132
1133 global $wgBlockDisablesLogin;
1134 if ( $wgBlockDisablesLogin && $proposedUser->isBlocked() ) {
1135 // User blocked and we've disabled blocked user logins
1136 return false;
1137 }
1138
1139 if ( $request->getSessionData( 'wsToken' ) ) {
1140 $passwordCorrect =
1141 ( $proposedUser->getToken( false ) === $request->getSessionData( 'wsToken' ) );
1142 $from = 'session';
1143 } elseif ( $request->getCookie( 'Token' ) ) {
1144 # Get the token from DB/cache and clean it up to remove garbage padding.
1145 # This deals with historical problems with bugs and the default column value.
1146 $token = rtrim( $proposedUser->getToken( false ) ); // correct token
1147 // Make comparison in constant time (bug 61346)
1148 $passwordCorrect = strlen( $token )
1149 && hash_equals( $token, $request->getCookie( 'Token' ) );
1150 $from = 'cookie';
1151 } else {
1152 // No session or persistent login cookie
1153 return false;
1154 }
1155
1156 if ( ( $sName === $proposedUser->getName() ) && $passwordCorrect ) {
1157 $this->loadFromUserObject( $proposedUser );
1158 $request->setSessionData( 'wsToken', $this->mToken );
1159 wfDebug( "User: logged in from $from\n" );
1160 return true;
1161 } else {
1162 // Invalid credentials
1163 wfDebug( "User: can't log in from $from, invalid credentials\n" );
1164 return false;
1165 }
1166 }
1167
1168 /**
1169 * Load user and user_group data from the database.
1170 * $this->mId must be set, this is how the user is identified.
1171 *
1172 * @return bool True if the user exists, false if the user is anonymous
1173 */
1174 public function loadFromDatabase() {
1175 // Paranoia
1176 $this->mId = intval( $this->mId );
1177
1178 // Anonymous user
1179 if ( !$this->mId ) {
1180 $this->loadDefaults();
1181 return false;
1182 }
1183
1184 $dbr = wfGetDB( DB_MASTER );
1185 $s = $dbr->selectRow(
1186 'user',
1187 self::selectFields(),
1188 array( 'user_id' => $this->mId ),
1189 __METHOD__
1190 );
1191
1192 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1193
1194 if ( $s !== false ) {
1195 // Initialise user table data
1196 $this->loadFromRow( $s );
1197 $this->mGroups = null; // deferred
1198 $this->getEditCount(); // revalidation for nulls
1199 return true;
1200 } else {
1201 // Invalid user_id
1202 $this->mId = 0;
1203 $this->loadDefaults();
1204 return false;
1205 }
1206 }
1207
1208 /**
1209 * Initialize this object from a row from the user table.
1210 *
1211 * @param stdClass $row Row from the user table to load.
1212 * @param array $data Further user data to load into the object
1213 *
1214 * user_groups Array with groups out of the user_groups table
1215 * user_properties Array with properties out of the user_properties table
1216 */
1217 public function loadFromRow( $row, $data = null ) {
1218 $all = true;
1219
1220 $this->mGroups = null; // deferred
1221
1222 if ( isset( $row->user_name ) ) {
1223 $this->mName = $row->user_name;
1224 $this->mFrom = 'name';
1225 $this->setItemLoaded( 'name' );
1226 } else {
1227 $all = false;
1228 }
1229
1230 if ( isset( $row->user_real_name ) ) {
1231 $this->mRealName = $row->user_real_name;
1232 $this->setItemLoaded( 'realname' );
1233 } else {
1234 $all = false;
1235 }
1236
1237 if ( isset( $row->user_id ) ) {
1238 $this->mId = intval( $row->user_id );
1239 $this->mFrom = 'id';
1240 $this->setItemLoaded( 'id' );
1241 } else {
1242 $all = false;
1243 }
1244
1245 if ( isset( $row->user_editcount ) ) {
1246 $this->mEditCount = $row->user_editcount;
1247 } else {
1248 $all = false;
1249 }
1250
1251 if ( isset( $row->user_password ) ) {
1252 $this->mPassword = $row->user_password;
1253 $this->mNewpassword = $row->user_newpassword;
1254 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1255 $this->mEmail = $row->user_email;
1256 if ( isset( $row->user_options ) ) {
1257 $this->decodeOptions( $row->user_options );
1258 }
1259 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1260 $this->mToken = $row->user_token;
1261 if ( $this->mToken == '' ) {
1262 $this->mToken = null;
1263 }
1264 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1265 $this->mEmailToken = $row->user_email_token;
1266 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1267 $this->mPasswordExpires = wfTimestampOrNull( TS_MW, $row->user_password_expires );
1268 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1269 } else {
1270 $all = false;
1271 }
1272
1273 if ( $all ) {
1274 $this->mLoadedItems = true;
1275 }
1276
1277 if ( is_array( $data ) ) {
1278 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1279 $this->mGroups = $data['user_groups'];
1280 }
1281 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1282 $this->loadOptions( $data['user_properties'] );
1283 }
1284 }
1285 }
1286
1287 /**
1288 * Load the data for this user object from another user object.
1289 *
1290 * @param User $user
1291 */
1292 protected function loadFromUserObject( $user ) {
1293 $user->load();
1294 $user->loadGroups();
1295 $user->loadOptions();
1296 foreach ( self::$mCacheVars as $var ) {
1297 $this->$var = $user->$var;
1298 }
1299 }
1300
1301 /**
1302 * Load the groups from the database if they aren't already loaded.
1303 */
1304 private function loadGroups() {
1305 if ( is_null( $this->mGroups ) ) {
1306 $dbr = wfGetDB( DB_MASTER );
1307 $res = $dbr->select( 'user_groups',
1308 array( 'ug_group' ),
1309 array( 'ug_user' => $this->mId ),
1310 __METHOD__ );
1311 $this->mGroups = array();
1312 foreach ( $res as $row ) {
1313 $this->mGroups[] = $row->ug_group;
1314 }
1315 }
1316 }
1317
1318 /**
1319 * Add the user to the group if he/she meets given criteria.
1320 *
1321 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1322 * possible to remove manually via Special:UserRights. In such case it
1323 * will not be re-added automatically. The user will also not lose the
1324 * group if they no longer meet the criteria.
1325 *
1326 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1327 *
1328 * @return array Array of groups the user has been promoted to.
1329 *
1330 * @see $wgAutopromoteOnce
1331 */
1332 public function addAutopromoteOnceGroups( $event ) {
1333 global $wgAutopromoteOnceLogInRC, $wgAuth;
1334
1335 $toPromote = array();
1336 if ( $this->getId() ) {
1337 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1338 if ( count( $toPromote ) ) {
1339 $oldGroups = $this->getGroups(); // previous groups
1340
1341 foreach ( $toPromote as $group ) {
1342 $this->addGroup( $group );
1343 }
1344 // update groups in external authentication database
1345 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1346
1347 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1348
1349 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1350 $logEntry->setPerformer( $this );
1351 $logEntry->setTarget( $this->getUserPage() );
1352 $logEntry->setParameters( array(
1353 '4::oldgroups' => $oldGroups,
1354 '5::newgroups' => $newGroups,
1355 ) );
1356 $logid = $logEntry->insert();
1357 if ( $wgAutopromoteOnceLogInRC ) {
1358 $logEntry->publish( $logid );
1359 }
1360 }
1361 }
1362 return $toPromote;
1363 }
1364
1365 /**
1366 * Clear various cached data stored in this object. The cache of the user table
1367 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1368 *
1369 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1370 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1371 */
1372 public function clearInstanceCache( $reloadFrom = false ) {
1373 $this->mNewtalk = -1;
1374 $this->mDatePreference = null;
1375 $this->mBlockedby = -1; # Unset
1376 $this->mHash = false;
1377 $this->mRights = null;
1378 $this->mEffectiveGroups = null;
1379 $this->mImplicitGroups = null;
1380 $this->mGroups = null;
1381 $this->mOptions = null;
1382 $this->mOptionsLoaded = false;
1383 $this->mEditCount = null;
1384
1385 if ( $reloadFrom ) {
1386 $this->mLoadedItems = array();
1387 $this->mFrom = $reloadFrom;
1388 }
1389 }
1390
1391 /**
1392 * Combine the language default options with any site-specific options
1393 * and add the default language variants.
1394 *
1395 * @return array Array of String options
1396 */
1397 public static function getDefaultOptions() {
1398 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1399
1400 static $defOpt = null;
1401 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1402 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1403 // mid-request and see that change reflected in the return value of this function.
1404 // Which is insane and would never happen during normal MW operation
1405 return $defOpt;
1406 }
1407
1408 $defOpt = $wgDefaultUserOptions;
1409 // Default language setting
1410 $defOpt['language'] = $wgContLang->getCode();
1411 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1412 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1413 }
1414 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1415 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1416 }
1417 $defOpt['skin'] = $wgDefaultSkin;
1418
1419 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1420
1421 return $defOpt;
1422 }
1423
1424 /**
1425 * Get a given default option value.
1426 *
1427 * @param string $opt Name of option to retrieve
1428 * @return string Default option value
1429 */
1430 public static function getDefaultOption( $opt ) {
1431 $defOpts = self::getDefaultOptions();
1432 if ( isset( $defOpts[$opt] ) ) {
1433 return $defOpts[$opt];
1434 } else {
1435 return null;
1436 }
1437 }
1438
1439 /**
1440 * Get blocking information
1441 * @param bool $bFromSlave Whether to check the slave database first.
1442 * To improve performance, non-critical checks are done against slaves.
1443 * Check when actually saving should be done against master.
1444 */
1445 private function getBlockedStatus( $bFromSlave = true ) {
1446 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1447
1448 if ( -1 != $this->mBlockedby ) {
1449 return;
1450 }
1451
1452 wfProfileIn( __METHOD__ );
1453 wfDebug( __METHOD__ . ": checking...\n" );
1454
1455 // Initialize data...
1456 // Otherwise something ends up stomping on $this->mBlockedby when
1457 // things get lazy-loaded later, causing false positive block hits
1458 // due to -1 !== 0. Probably session-related... Nothing should be
1459 // overwriting mBlockedby, surely?
1460 $this->load();
1461
1462 # We only need to worry about passing the IP address to the Block generator if the
1463 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1464 # know which IP address they're actually coming from
1465 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1466 $ip = $this->getRequest()->getIP();
1467 } else {
1468 $ip = null;
1469 }
1470
1471 // User/IP blocking
1472 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1473
1474 // Proxy blocking
1475 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1476 && !in_array( $ip, $wgProxyWhitelist )
1477 ) {
1478 // Local list
1479 if ( self::isLocallyBlockedProxy( $ip ) ) {
1480 $block = new Block;
1481 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1482 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1483 $block->setTarget( $ip );
1484 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1485 $block = new Block;
1486 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1487 $block->mReason = wfMessage( 'sorbsreason' )->text();
1488 $block->setTarget( $ip );
1489 }
1490 }
1491
1492 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1493 if ( !$block instanceof Block
1494 && $wgApplyIpBlocksToXff
1495 && $ip !== null
1496 && !$this->isAllowed( 'proxyunbannable' )
1497 && !in_array( $ip, $wgProxyWhitelist )
1498 ) {
1499 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1500 $xff = array_map( 'trim', explode( ',', $xff ) );
1501 $xff = array_diff( $xff, array( $ip ) );
1502 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1503 $block = Block::chooseBlock( $xffblocks, $xff );
1504 if ( $block instanceof Block ) {
1505 # Mangle the reason to alert the user that the block
1506 # originated from matching the X-Forwarded-For header.
1507 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1508 }
1509 }
1510
1511 if ( $block instanceof Block ) {
1512 wfDebug( __METHOD__ . ": Found block.\n" );
1513 $this->mBlock = $block;
1514 $this->mBlockedby = $block->getByName();
1515 $this->mBlockreason = $block->mReason;
1516 $this->mHideName = $block->mHideName;
1517 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1518 } else {
1519 $this->mBlockedby = '';
1520 $this->mHideName = 0;
1521 $this->mAllowUsertalk = false;
1522 }
1523
1524 // Extensions
1525 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1526
1527 wfProfileOut( __METHOD__ );
1528 }
1529
1530 /**
1531 * Whether the given IP is in a DNS blacklist.
1532 *
1533 * @param string $ip IP to check
1534 * @param bool $checkWhitelist Whether to check the whitelist first
1535 * @return bool True if blacklisted.
1536 */
1537 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1538 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1539 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1540
1541 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1542 return false;
1543 }
1544
1545 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1546 return false;
1547 }
1548
1549 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1550 return $this->inDnsBlacklist( $ip, $urls );
1551 }
1552
1553 /**
1554 * Whether the given IP is in a given DNS blacklist.
1555 *
1556 * @param string $ip IP to check
1557 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1558 * @return bool True if blacklisted.
1559 */
1560 public function inDnsBlacklist( $ip, $bases ) {
1561 wfProfileIn( __METHOD__ );
1562
1563 $found = false;
1564 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1565 if ( IP::isIPv4( $ip ) ) {
1566 // Reverse IP, bug 21255
1567 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1568
1569 foreach ( (array)$bases as $base ) {
1570 // Make hostname
1571 // If we have an access key, use that too (ProjectHoneypot, etc.)
1572 if ( is_array( $base ) ) {
1573 if ( count( $base ) >= 2 ) {
1574 // Access key is 1, base URL is 0
1575 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1576 } else {
1577 $host = "$ipReversed.{$base[0]}";
1578 }
1579 } else {
1580 $host = "$ipReversed.$base";
1581 }
1582
1583 // Send query
1584 $ipList = gethostbynamel( $host );
1585
1586 if ( $ipList ) {
1587 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1588 $found = true;
1589 break;
1590 } else {
1591 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1592 }
1593 }
1594 }
1595
1596 wfProfileOut( __METHOD__ );
1597 return $found;
1598 }
1599
1600 /**
1601 * Check if an IP address is in the local proxy list
1602 *
1603 * @param string $ip
1604 *
1605 * @return bool
1606 */
1607 public static function isLocallyBlockedProxy( $ip ) {
1608 global $wgProxyList;
1609
1610 if ( !$wgProxyList ) {
1611 return false;
1612 }
1613 wfProfileIn( __METHOD__ );
1614
1615 if ( !is_array( $wgProxyList ) ) {
1616 // Load from the specified file
1617 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1618 }
1619
1620 if ( !is_array( $wgProxyList ) ) {
1621 $ret = false;
1622 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1623 $ret = true;
1624 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1625 // Old-style flipped proxy list
1626 $ret = true;
1627 } else {
1628 $ret = false;
1629 }
1630 wfProfileOut( __METHOD__ );
1631 return $ret;
1632 }
1633
1634 /**
1635 * Is this user subject to rate limiting?
1636 *
1637 * @return bool True if rate limited
1638 */
1639 public function isPingLimitable() {
1640 global $wgRateLimitsExcludedIPs;
1641 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1642 // No other good way currently to disable rate limits
1643 // for specific IPs. :P
1644 // But this is a crappy hack and should die.
1645 return false;
1646 }
1647 return !$this->isAllowed( 'noratelimit' );
1648 }
1649
1650 /**
1651 * Primitive rate limits: enforce maximum actions per time period
1652 * to put a brake on flooding.
1653 *
1654 * The method generates both a generic profiling point and a per action one
1655 * (suffix being "-$action".
1656 *
1657 * @note When using a shared cache like memcached, IP-address
1658 * last-hit counters will be shared across wikis.
1659 *
1660 * @param string $action Action to enforce; 'edit' if unspecified
1661 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1662 * @return bool True if a rate limiter was tripped
1663 */
1664 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1665 // Call the 'PingLimiter' hook
1666 $result = false;
1667 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1668 return $result;
1669 }
1670
1671 global $wgRateLimits;
1672 if ( !isset( $wgRateLimits[$action] ) ) {
1673 return false;
1674 }
1675
1676 // Some groups shouldn't trigger the ping limiter, ever
1677 if ( !$this->isPingLimitable() ) {
1678 return false;
1679 }
1680
1681 global $wgMemc;
1682 wfProfileIn( __METHOD__ );
1683 wfProfileIn( __METHOD__ . '-' . $action );
1684
1685 $limits = $wgRateLimits[$action];
1686 $keys = array();
1687 $id = $this->getId();
1688 $userLimit = false;
1689
1690 if ( isset( $limits['anon'] ) && $id == 0 ) {
1691 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1692 }
1693
1694 if ( isset( $limits['user'] ) && $id != 0 ) {
1695 $userLimit = $limits['user'];
1696 }
1697 if ( $this->isNewbie() ) {
1698 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1699 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1700 }
1701 if ( isset( $limits['ip'] ) ) {
1702 $ip = $this->getRequest()->getIP();
1703 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1704 }
1705 if ( isset( $limits['subnet'] ) ) {
1706 $ip = $this->getRequest()->getIP();
1707 $matches = array();
1708 $subnet = false;
1709 if ( IP::isIPv6( $ip ) ) {
1710 $parts = IP::parseRange( "$ip/64" );
1711 $subnet = $parts[0];
1712 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1713 // IPv4
1714 $subnet = $matches[1];
1715 }
1716 if ( $subnet !== false ) {
1717 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1718 }
1719 }
1720 }
1721 // Check for group-specific permissions
1722 // If more than one group applies, use the group with the highest limit
1723 foreach ( $this->getGroups() as $group ) {
1724 if ( isset( $limits[$group] ) ) {
1725 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1726 $userLimit = $limits[$group];
1727 }
1728 }
1729 }
1730 // Set the user limit key
1731 if ( $userLimit !== false ) {
1732 list( $max, $period ) = $userLimit;
1733 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1734 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1735 }
1736
1737 $triggered = false;
1738 foreach ( $keys as $key => $limit ) {
1739 list( $max, $period ) = $limit;
1740 $summary = "(limit $max in {$period}s)";
1741 $count = $wgMemc->get( $key );
1742 // Already pinged?
1743 if ( $count ) {
1744 if ( $count >= $max ) {
1745 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1746 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1747 $triggered = true;
1748 } else {
1749 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1750 }
1751 } else {
1752 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1753 if ( $incrBy > 0 ) {
1754 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1755 }
1756 }
1757 if ( $incrBy > 0 ) {
1758 $wgMemc->incr( $key, $incrBy );
1759 }
1760 }
1761
1762 wfProfileOut( __METHOD__ . '-' . $action );
1763 wfProfileOut( __METHOD__ );
1764 return $triggered;
1765 }
1766
1767 /**
1768 * Check if user is blocked
1769 *
1770 * @param bool $bFromSlave Whether to check the slave database instead of
1771 * the master. Hacked from false due to horrible probs on site.
1772 * @return bool True if blocked, false otherwise
1773 */
1774 public function isBlocked( $bFromSlave = true ) {
1775 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1776 }
1777
1778 /**
1779 * Get the block affecting the user, or null if the user is not blocked
1780 *
1781 * @param bool $bFromSlave Whether to check the slave database instead of the master
1782 * @return Block|null
1783 */
1784 public function getBlock( $bFromSlave = true ) {
1785 $this->getBlockedStatus( $bFromSlave );
1786 return $this->mBlock instanceof Block ? $this->mBlock : null;
1787 }
1788
1789 /**
1790 * Check if user is blocked from editing a particular article
1791 *
1792 * @param Title $title Title to check
1793 * @param bool $bFromSlave Whether to check the slave database instead of the master
1794 * @return bool
1795 */
1796 public function isBlockedFrom( $title, $bFromSlave = false ) {
1797 global $wgBlockAllowsUTEdit;
1798 wfProfileIn( __METHOD__ );
1799
1800 $blocked = $this->isBlocked( $bFromSlave );
1801 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1802 // If a user's name is suppressed, they cannot make edits anywhere
1803 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1804 && $title->getNamespace() == NS_USER_TALK ) {
1805 $blocked = false;
1806 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1807 }
1808
1809 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1810
1811 wfProfileOut( __METHOD__ );
1812 return $blocked;
1813 }
1814
1815 /**
1816 * If user is blocked, return the name of the user who placed the block
1817 * @return string Name of blocker
1818 */
1819 public function blockedBy() {
1820 $this->getBlockedStatus();
1821 return $this->mBlockedby;
1822 }
1823
1824 /**
1825 * If user is blocked, return the specified reason for the block
1826 * @return string Blocking reason
1827 */
1828 public function blockedFor() {
1829 $this->getBlockedStatus();
1830 return $this->mBlockreason;
1831 }
1832
1833 /**
1834 * If user is blocked, return the ID for the block
1835 * @return int Block ID
1836 */
1837 public function getBlockId() {
1838 $this->getBlockedStatus();
1839 return ( $this->mBlock ? $this->mBlock->getId() : false );
1840 }
1841
1842 /**
1843 * Check if user is blocked on all wikis.
1844 * Do not use for actual edit permission checks!
1845 * This is intended for quick UI checks.
1846 *
1847 * @param string $ip IP address, uses current client if none given
1848 * @return bool True if blocked, false otherwise
1849 */
1850 public function isBlockedGlobally( $ip = '' ) {
1851 if ( $this->mBlockedGlobally !== null ) {
1852 return $this->mBlockedGlobally;
1853 }
1854 // User is already an IP?
1855 if ( IP::isIPAddress( $this->getName() ) ) {
1856 $ip = $this->getName();
1857 } elseif ( !$ip ) {
1858 $ip = $this->getRequest()->getIP();
1859 }
1860 $blocked = false;
1861 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1862 $this->mBlockedGlobally = (bool)$blocked;
1863 return $this->mBlockedGlobally;
1864 }
1865
1866 /**
1867 * Check if user account is locked
1868 *
1869 * @return bool True if locked, false otherwise
1870 */
1871 public function isLocked() {
1872 if ( $this->mLocked !== null ) {
1873 return $this->mLocked;
1874 }
1875 global $wgAuth;
1876 StubObject::unstub( $wgAuth );
1877 $authUser = $wgAuth->getUserInstance( $this );
1878 $this->mLocked = (bool)$authUser->isLocked();
1879 return $this->mLocked;
1880 }
1881
1882 /**
1883 * Check if user account is hidden
1884 *
1885 * @return bool True if hidden, false otherwise
1886 */
1887 public function isHidden() {
1888 if ( $this->mHideName !== null ) {
1889 return $this->mHideName;
1890 }
1891 $this->getBlockedStatus();
1892 if ( !$this->mHideName ) {
1893 global $wgAuth;
1894 StubObject::unstub( $wgAuth );
1895 $authUser = $wgAuth->getUserInstance( $this );
1896 $this->mHideName = (bool)$authUser->isHidden();
1897 }
1898 return $this->mHideName;
1899 }
1900
1901 /**
1902 * Get the user's ID.
1903 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1904 */
1905 public function getId() {
1906 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1907 // Special case, we know the user is anonymous
1908 return 0;
1909 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1910 // Don't load if this was initialized from an ID
1911 $this->load();
1912 }
1913 return $this->mId;
1914 }
1915
1916 /**
1917 * Set the user and reload all fields according to a given ID
1918 * @param int $v User ID to reload
1919 */
1920 public function setId( $v ) {
1921 $this->mId = $v;
1922 $this->clearInstanceCache( 'id' );
1923 }
1924
1925 /**
1926 * Get the user name, or the IP of an anonymous user
1927 * @return string User's name or IP address
1928 */
1929 public function getName() {
1930 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1931 // Special case optimisation
1932 return $this->mName;
1933 } else {
1934 $this->load();
1935 if ( $this->mName === false ) {
1936 // Clean up IPs
1937 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1938 }
1939 return $this->mName;
1940 }
1941 }
1942
1943 /**
1944 * Set the user name.
1945 *
1946 * This does not reload fields from the database according to the given
1947 * name. Rather, it is used to create a temporary "nonexistent user" for
1948 * later addition to the database. It can also be used to set the IP
1949 * address for an anonymous user to something other than the current
1950 * remote IP.
1951 *
1952 * @note User::newFromName() has roughly the same function, when the named user
1953 * does not exist.
1954 * @param string $str New user name to set
1955 */
1956 public function setName( $str ) {
1957 $this->load();
1958 $this->mName = $str;
1959 }
1960
1961 /**
1962 * Get the user's name escaped by underscores.
1963 * @return string Username escaped by underscores.
1964 */
1965 public function getTitleKey() {
1966 return str_replace( ' ', '_', $this->getName() );
1967 }
1968
1969 /**
1970 * Check if the user has new messages.
1971 * @return bool True if the user has new messages
1972 */
1973 public function getNewtalk() {
1974 $this->load();
1975
1976 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1977 if ( $this->mNewtalk === -1 ) {
1978 $this->mNewtalk = false; # reset talk page status
1979
1980 // Check memcached separately for anons, who have no
1981 // entire User object stored in there.
1982 if ( !$this->mId ) {
1983 global $wgDisableAnonTalk;
1984 if ( $wgDisableAnonTalk ) {
1985 // Anon newtalk disabled by configuration.
1986 $this->mNewtalk = false;
1987 } else {
1988 global $wgMemc;
1989 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1990 $newtalk = $wgMemc->get( $key );
1991 if ( strval( $newtalk ) !== '' ) {
1992 $this->mNewtalk = (bool)$newtalk;
1993 } else {
1994 // Since we are caching this, make sure it is up to date by getting it
1995 // from the master
1996 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1997 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1998 }
1999 }
2000 } else {
2001 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2002 }
2003 }
2004
2005 return (bool)$this->mNewtalk;
2006 }
2007
2008 /**
2009 * Return the data needed to construct links for new talk page message
2010 * alerts. If there are new messages, this will return an associative array
2011 * with the following data:
2012 * wiki: The database name of the wiki
2013 * link: Root-relative link to the user's talk page
2014 * rev: The last talk page revision that the user has seen or null. This
2015 * is useful for building diff links.
2016 * If there are no new messages, it returns an empty array.
2017 * @note This function was designed to accomodate multiple talk pages, but
2018 * currently only returns a single link and revision.
2019 * @return array
2020 */
2021 public function getNewMessageLinks() {
2022 $talks = array();
2023 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2024 return $talks;
2025 } elseif ( !$this->getNewtalk() ) {
2026 return array();
2027 }
2028 $utp = $this->getTalkPage();
2029 $dbr = wfGetDB( DB_SLAVE );
2030 // Get the "last viewed rev" timestamp from the oldest message notification
2031 $timestamp = $dbr->selectField( 'user_newtalk',
2032 'MIN(user_last_timestamp)',
2033 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2034 __METHOD__ );
2035 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2036 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2037 }
2038
2039 /**
2040 * Get the revision ID for the last talk page revision viewed by the talk
2041 * page owner.
2042 * @return int|null Revision ID or null
2043 */
2044 public function getNewMessageRevisionId() {
2045 $newMessageRevisionId = null;
2046 $newMessageLinks = $this->getNewMessageLinks();
2047 if ( $newMessageLinks ) {
2048 // Note: getNewMessageLinks() never returns more than a single link
2049 // and it is always for the same wiki, but we double-check here in
2050 // case that changes some time in the future.
2051 if ( count( $newMessageLinks ) === 1
2052 && $newMessageLinks[0]['wiki'] === wfWikiID()
2053 && $newMessageLinks[0]['rev']
2054 ) {
2055 $newMessageRevision = $newMessageLinks[0]['rev'];
2056 $newMessageRevisionId = $newMessageRevision->getId();
2057 }
2058 }
2059 return $newMessageRevisionId;
2060 }
2061
2062 /**
2063 * Internal uncached check for new messages
2064 *
2065 * @see getNewtalk()
2066 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2067 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2068 * @param bool $fromMaster true to fetch from the master, false for a slave
2069 * @return bool True if the user has new messages
2070 */
2071 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2072 if ( $fromMaster ) {
2073 $db = wfGetDB( DB_MASTER );
2074 } else {
2075 $db = wfGetDB( DB_SLAVE );
2076 }
2077 $ok = $db->selectField( 'user_newtalk', $field,
2078 array( $field => $id ), __METHOD__ );
2079 return $ok !== false;
2080 }
2081
2082 /**
2083 * Add or update the new messages flag
2084 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2085 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2086 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2087 * @return bool True if successful, false otherwise
2088 */
2089 protected function updateNewtalk( $field, $id, $curRev = null ) {
2090 // Get timestamp of the talk page revision prior to the current one
2091 $prevRev = $curRev ? $curRev->getPrevious() : false;
2092 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2093 // Mark the user as having new messages since this revision
2094 $dbw = wfGetDB( DB_MASTER );
2095 $dbw->insert( 'user_newtalk',
2096 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2097 __METHOD__,
2098 'IGNORE' );
2099 if ( $dbw->affectedRows() ) {
2100 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2101 return true;
2102 } else {
2103 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2104 return false;
2105 }
2106 }
2107
2108 /**
2109 * Clear the new messages flag for the given user
2110 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2111 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2112 * @return bool True if successful, false otherwise
2113 */
2114 protected function deleteNewtalk( $field, $id ) {
2115 $dbw = wfGetDB( DB_MASTER );
2116 $dbw->delete( 'user_newtalk',
2117 array( $field => $id ),
2118 __METHOD__ );
2119 if ( $dbw->affectedRows() ) {
2120 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2121 return true;
2122 } else {
2123 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2124 return false;
2125 }
2126 }
2127
2128 /**
2129 * Update the 'You have new messages!' status.
2130 * @param bool $val Whether the user has new messages
2131 * @param Revision $curRev New, as yet unseen revision of the user talk
2132 * page. Ignored if null or !$val.
2133 */
2134 public function setNewtalk( $val, $curRev = null ) {
2135 if ( wfReadOnly() ) {
2136 return;
2137 }
2138
2139 $this->load();
2140 $this->mNewtalk = $val;
2141
2142 if ( $this->isAnon() ) {
2143 $field = 'user_ip';
2144 $id = $this->getName();
2145 } else {
2146 $field = 'user_id';
2147 $id = $this->getId();
2148 }
2149 global $wgMemc;
2150
2151 if ( $val ) {
2152 $changed = $this->updateNewtalk( $field, $id, $curRev );
2153 } else {
2154 $changed = $this->deleteNewtalk( $field, $id );
2155 }
2156
2157 if ( $this->isAnon() ) {
2158 // Anons have a separate memcached space, since
2159 // user records aren't kept for them.
2160 $key = wfMemcKey( 'newtalk', 'ip', $id );
2161 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
2162 }
2163 if ( $changed ) {
2164 $this->invalidateCache();
2165 }
2166 }
2167
2168 /**
2169 * Generate a current or new-future timestamp to be stored in the
2170 * user_touched field when we update things.
2171 * @return string Timestamp in TS_MW format
2172 */
2173 private static function newTouchedTimestamp() {
2174 global $wgClockSkewFudge;
2175 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2176 }
2177
2178 /**
2179 * Clear user data from memcached.
2180 * Use after applying fun updates to the database; caller's
2181 * responsibility to update user_touched if appropriate.
2182 *
2183 * Called implicitly from invalidateCache() and saveSettings().
2184 */
2185 private function clearSharedCache() {
2186 $this->load();
2187 if ( $this->mId ) {
2188 global $wgMemc;
2189 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2190 }
2191 }
2192
2193 /**
2194 * Immediately touch the user data cache for this account.
2195 * Updates user_touched field, and removes account data from memcached
2196 * for reload on the next hit.
2197 */
2198 public function invalidateCache() {
2199 if ( wfReadOnly() ) {
2200 return;
2201 }
2202 $this->load();
2203 if ( $this->mId ) {
2204 $this->mTouched = self::newTouchedTimestamp();
2205
2206 $dbw = wfGetDB( DB_MASTER );
2207 $userid = $this->mId;
2208 $touched = $this->mTouched;
2209 $method = __METHOD__;
2210 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2211 // Prevent contention slams by checking user_touched first
2212 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2213 $needsPurge = $dbw->selectField( 'user', '1',
2214 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2215 if ( $needsPurge ) {
2216 $dbw->update( 'user',
2217 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2218 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2219 $method
2220 );
2221 }
2222 } );
2223 $this->clearSharedCache();
2224 }
2225 }
2226
2227 /**
2228 * Validate the cache for this account.
2229 * @param string $timestamp A timestamp in TS_MW format
2230 * @return bool
2231 */
2232 public function validateCache( $timestamp ) {
2233 $this->load();
2234 return ( $timestamp >= $this->mTouched );
2235 }
2236
2237 /**
2238 * Get the user touched timestamp
2239 * @return string Timestamp
2240 */
2241 public function getTouched() {
2242 $this->load();
2243 return $this->mTouched;
2244 }
2245
2246 /**
2247 * Set the password and reset the random token.
2248 * Calls through to authentication plugin if necessary;
2249 * will have no effect if the auth plugin refuses to
2250 * pass the change through or if the legal password
2251 * checks fail.
2252 *
2253 * As a special case, setting the password to null
2254 * wipes it, so the account cannot be logged in until
2255 * a new password is set, for instance via e-mail.
2256 *
2257 * @param string $str New password to set
2258 * @throws PasswordError on failure
2259 *
2260 * @return bool
2261 */
2262 public function setPassword( $str ) {
2263 global $wgAuth;
2264
2265 if ( $str !== null ) {
2266 if ( !$wgAuth->allowPasswordChange() ) {
2267 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2268 }
2269
2270 if ( !$this->isValidPassword( $str ) ) {
2271 global $wgMinimalPasswordLength;
2272 $valid = $this->getPasswordValidity( $str );
2273 if ( is_array( $valid ) ) {
2274 $message = array_shift( $valid );
2275 $params = $valid;
2276 } else {
2277 $message = $valid;
2278 $params = array( $wgMinimalPasswordLength );
2279 }
2280 throw new PasswordError( wfMessage( $message, $params )->text() );
2281 }
2282 }
2283
2284 if ( !$wgAuth->setPassword( $this, $str ) ) {
2285 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2286 }
2287
2288 $this->setInternalPassword( $str );
2289
2290 return true;
2291 }
2292
2293 /**
2294 * Set the password and reset the random token unconditionally.
2295 *
2296 * @param string|null $str New password to set or null to set an invalid
2297 * password hash meaning that the user will not be able to log in
2298 * through the web interface.
2299 */
2300 public function setInternalPassword( $str ) {
2301 $this->load();
2302 $this->setToken();
2303
2304 if ( $str === null ) {
2305 // Save an invalid hash...
2306 $this->mPassword = '';
2307 } else {
2308 $this->mPassword = self::crypt( $str );
2309 }
2310 $this->mNewpassword = '';
2311 $this->mNewpassTime = null;
2312 }
2313
2314 /**
2315 * Get the user's current token.
2316 * @param bool $forceCreation Force the generation of a new token if the
2317 * user doesn't have one (default=true for backwards compatibility).
2318 * @return string Token
2319 */
2320 public function getToken( $forceCreation = true ) {
2321 $this->load();
2322 if ( !$this->mToken && $forceCreation ) {
2323 $this->setToken();
2324 }
2325 return $this->mToken;
2326 }
2327
2328 /**
2329 * Set the random token (used for persistent authentication)
2330 * Called from loadDefaults() among other places.
2331 *
2332 * @param string|bool $token If specified, set the token to this value
2333 */
2334 public function setToken( $token = false ) {
2335 $this->load();
2336 if ( !$token ) {
2337 $this->mToken = MWCryptRand::generateHex( USER_TOKEN_LENGTH );
2338 } else {
2339 $this->mToken = $token;
2340 }
2341 }
2342
2343 /**
2344 * Set the password for a password reminder or new account email
2345 *
2346 * @param string $str New password to set or null to set an invalid
2347 * password hash meaning that the user will not be able to use it
2348 * @param bool $throttle If true, reset the throttle timestamp to the present
2349 */
2350 public function setNewpassword( $str, $throttle = true ) {
2351 $this->load();
2352
2353 if ( $str === null ) {
2354 $this->mNewpassword = '';
2355 $this->mNewpassTime = null;
2356 } else {
2357 $this->mNewpassword = self::crypt( $str );
2358 if ( $throttle ) {
2359 $this->mNewpassTime = wfTimestampNow();
2360 }
2361 }
2362 }
2363
2364 /**
2365 * Has password reminder email been sent within the last
2366 * $wgPasswordReminderResendTime hours?
2367 * @return bool
2368 */
2369 public function isPasswordReminderThrottled() {
2370 global $wgPasswordReminderResendTime;
2371 $this->load();
2372 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2373 return false;
2374 }
2375 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2376 return time() < $expiry;
2377 }
2378
2379 /**
2380 * Get the user's e-mail address
2381 * @return string User's email address
2382 */
2383 public function getEmail() {
2384 $this->load();
2385 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2386 return $this->mEmail;
2387 }
2388
2389 /**
2390 * Get the timestamp of the user's e-mail authentication
2391 * @return string TS_MW timestamp
2392 */
2393 public function getEmailAuthenticationTimestamp() {
2394 $this->load();
2395 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2396 return $this->mEmailAuthenticated;
2397 }
2398
2399 /**
2400 * Set the user's e-mail address
2401 * @param string $str New e-mail address
2402 */
2403 public function setEmail( $str ) {
2404 $this->load();
2405 if ( $str == $this->mEmail ) {
2406 return;
2407 }
2408 $this->mEmail = $str;
2409 $this->invalidateEmail();
2410 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2411 }
2412
2413 /**
2414 * Set the user's e-mail address and a confirmation mail if needed.
2415 *
2416 * @since 1.20
2417 * @param string $str New e-mail address
2418 * @return Status
2419 */
2420 public function setEmailWithConfirmation( $str ) {
2421 global $wgEnableEmail, $wgEmailAuthentication;
2422
2423 if ( !$wgEnableEmail ) {
2424 return Status::newFatal( 'emaildisabled' );
2425 }
2426
2427 $oldaddr = $this->getEmail();
2428 if ( $str === $oldaddr ) {
2429 return Status::newGood( true );
2430 }
2431
2432 $this->setEmail( $str );
2433
2434 if ( $str !== '' && $wgEmailAuthentication ) {
2435 // Send a confirmation request to the new address if needed
2436 $type = $oldaddr != '' ? 'changed' : 'set';
2437 $result = $this->sendConfirmationMail( $type );
2438 if ( $result->isGood() ) {
2439 // Say the the caller that a confirmation mail has been sent
2440 $result->value = 'eauth';
2441 }
2442 } else {
2443 $result = Status::newGood( true );
2444 }
2445
2446 return $result;
2447 }
2448
2449 /**
2450 * Get the user's real name
2451 * @return string User's real name
2452 */
2453 public function getRealName() {
2454 if ( !$this->isItemLoaded( 'realname' ) ) {
2455 $this->load();
2456 }
2457
2458 return $this->mRealName;
2459 }
2460
2461 /**
2462 * Set the user's real name
2463 * @param string $str New real name
2464 */
2465 public function setRealName( $str ) {
2466 $this->load();
2467 $this->mRealName = $str;
2468 }
2469
2470 /**
2471 * Get the user's current setting for a given option.
2472 *
2473 * @param string $oname The option to check
2474 * @param string $defaultOverride A default value returned if the option does not exist
2475 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2476 * @return string User's current value for the option
2477 * @see getBoolOption()
2478 * @see getIntOption()
2479 */
2480 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2481 global $wgHiddenPrefs;
2482 $this->loadOptions();
2483
2484 # We want 'disabled' preferences to always behave as the default value for
2485 # users, even if they have set the option explicitly in their settings (ie they
2486 # set it, and then it was disabled removing their ability to change it). But
2487 # we don't want to erase the preferences in the database in case the preference
2488 # is re-enabled again. So don't touch $mOptions, just override the returned value
2489 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2490 return self::getDefaultOption( $oname );
2491 }
2492
2493 if ( array_key_exists( $oname, $this->mOptions ) ) {
2494 return $this->mOptions[$oname];
2495 } else {
2496 return $defaultOverride;
2497 }
2498 }
2499
2500 /**
2501 * Get all user's options
2502 *
2503 * @return array
2504 */
2505 public function getOptions() {
2506 global $wgHiddenPrefs;
2507 $this->loadOptions();
2508 $options = $this->mOptions;
2509
2510 # We want 'disabled' preferences to always behave as the default value for
2511 # users, even if they have set the option explicitly in their settings (ie they
2512 # set it, and then it was disabled removing their ability to change it). But
2513 # we don't want to erase the preferences in the database in case the preference
2514 # is re-enabled again. So don't touch $mOptions, just override the returned value
2515 foreach ( $wgHiddenPrefs as $pref ) {
2516 $default = self::getDefaultOption( $pref );
2517 if ( $default !== null ) {
2518 $options[$pref] = $default;
2519 }
2520 }
2521
2522 return $options;
2523 }
2524
2525 /**
2526 * Get the user's current setting for a given option, as a boolean value.
2527 *
2528 * @param string $oname The option to check
2529 * @return bool User's current value for the option
2530 * @see getOption()
2531 */
2532 public function getBoolOption( $oname ) {
2533 return (bool)$this->getOption( $oname );
2534 }
2535
2536 /**
2537 * Get the user's current setting for a given option, as an integer value.
2538 *
2539 * @param string $oname The option to check
2540 * @param int $defaultOverride A default value returned if the option does not exist
2541 * @return int User's current value for the option
2542 * @see getOption()
2543 */
2544 public function getIntOption( $oname, $defaultOverride = 0 ) {
2545 $val = $this->getOption( $oname );
2546 if ( $val == '' ) {
2547 $val = $defaultOverride;
2548 }
2549 return intval( $val );
2550 }
2551
2552 /**
2553 * Set the given option for a user.
2554 *
2555 * @param string $oname The option to set
2556 * @param mixed $val New value to set
2557 */
2558 public function setOption( $oname, $val ) {
2559 $this->loadOptions();
2560
2561 // Explicitly NULL values should refer to defaults
2562 if ( is_null( $val ) ) {
2563 $val = self::getDefaultOption( $oname );
2564 }
2565
2566 $this->mOptions[$oname] = $val;
2567 }
2568
2569 /**
2570 * Get a token stored in the preferences (like the watchlist one),
2571 * resetting it if it's empty (and saving changes).
2572 *
2573 * @param string $oname The option name to retrieve the token from
2574 * @return string|bool User's current value for the option, or false if this option is disabled.
2575 * @see resetTokenFromOption()
2576 * @see getOption()
2577 */
2578 public function getTokenFromOption( $oname ) {
2579 global $wgHiddenPrefs;
2580 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2581 return false;
2582 }
2583
2584 $token = $this->getOption( $oname );
2585 if ( !$token ) {
2586 $token = $this->resetTokenFromOption( $oname );
2587 $this->saveSettings();
2588 }
2589 return $token;
2590 }
2591
2592 /**
2593 * Reset a token stored in the preferences (like the watchlist one).
2594 * *Does not* save user's preferences (similarly to setOption()).
2595 *
2596 * @param string $oname The option name to reset the token in
2597 * @return string|bool New token value, or false if this option is disabled.
2598 * @see getTokenFromOption()
2599 * @see setOption()
2600 */
2601 public function resetTokenFromOption( $oname ) {
2602 global $wgHiddenPrefs;
2603 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2604 return false;
2605 }
2606
2607 $token = MWCryptRand::generateHex( 40 );
2608 $this->setOption( $oname, $token );
2609 return $token;
2610 }
2611
2612 /**
2613 * Return a list of the types of user options currently returned by
2614 * User::getOptionKinds().
2615 *
2616 * Currently, the option kinds are:
2617 * - 'registered' - preferences which are registered in core MediaWiki or
2618 * by extensions using the UserGetDefaultOptions hook.
2619 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2620 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2621 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2622 * be used by user scripts.
2623 * - 'special' - "preferences" that are not accessible via User::getOptions
2624 * or User::setOptions.
2625 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2626 * These are usually legacy options, removed in newer versions.
2627 *
2628 * The API (and possibly others) use this function to determine the possible
2629 * option types for validation purposes, so make sure to update this when a
2630 * new option kind is added.
2631 *
2632 * @see User::getOptionKinds
2633 * @return array Option kinds
2634 */
2635 public static function listOptionKinds() {
2636 return array(
2637 'registered',
2638 'registered-multiselect',
2639 'registered-checkmatrix',
2640 'userjs',
2641 'special',
2642 'unused'
2643 );
2644 }
2645
2646 /**
2647 * Return an associative array mapping preferences keys to the kind of a preference they're
2648 * used for. Different kinds are handled differently when setting or reading preferences.
2649 *
2650 * See User::listOptionKinds for the list of valid option types that can be provided.
2651 *
2652 * @see User::listOptionKinds
2653 * @param IContextSource $context
2654 * @param array $options Assoc. array with options keys to check as keys.
2655 * Defaults to $this->mOptions.
2656 * @return array the key => kind mapping data
2657 */
2658 public function getOptionKinds( IContextSource $context, $options = null ) {
2659 $this->loadOptions();
2660 if ( $options === null ) {
2661 $options = $this->mOptions;
2662 }
2663
2664 $prefs = Preferences::getPreferences( $this, $context );
2665 $mapping = array();
2666
2667 // Pull out the "special" options, so they don't get converted as
2668 // multiselect or checkmatrix.
2669 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2670 foreach ( $specialOptions as $name => $value ) {
2671 unset( $prefs[$name] );
2672 }
2673
2674 // Multiselect and checkmatrix options are stored in the database with
2675 // one key per option, each having a boolean value. Extract those keys.
2676 $multiselectOptions = array();
2677 foreach ( $prefs as $name => $info ) {
2678 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2679 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2680 $opts = HTMLFormField::flattenOptions( $info['options'] );
2681 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2682
2683 foreach ( $opts as $value ) {
2684 $multiselectOptions["$prefix$value"] = true;
2685 }
2686
2687 unset( $prefs[$name] );
2688 }
2689 }
2690 $checkmatrixOptions = array();
2691 foreach ( $prefs as $name => $info ) {
2692 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2693 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2694 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2695 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2696 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2697
2698 foreach ( $columns as $column ) {
2699 foreach ( $rows as $row ) {
2700 $checkmatrixOptions["$prefix-$column-$row"] = true;
2701 }
2702 }
2703
2704 unset( $prefs[$name] );
2705 }
2706 }
2707
2708 // $value is ignored
2709 foreach ( $options as $key => $value ) {
2710 if ( isset( $prefs[$key] ) ) {
2711 $mapping[$key] = 'registered';
2712 } elseif ( isset( $multiselectOptions[$key] ) ) {
2713 $mapping[$key] = 'registered-multiselect';
2714 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2715 $mapping[$key] = 'registered-checkmatrix';
2716 } elseif ( isset( $specialOptions[$key] ) ) {
2717 $mapping[$key] = 'special';
2718 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2719 $mapping[$key] = 'userjs';
2720 } else {
2721 $mapping[$key] = 'unused';
2722 }
2723 }
2724
2725 return $mapping;
2726 }
2727
2728 /**
2729 * Reset certain (or all) options to the site defaults
2730 *
2731 * The optional parameter determines which kinds of preferences will be reset.
2732 * Supported values are everything that can be reported by getOptionKinds()
2733 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2734 *
2735 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2736 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2737 * for backwards-compatibility.
2738 * @param IContextSource|null $context Context source used when $resetKinds
2739 * does not contain 'all', passed to getOptionKinds().
2740 * Defaults to RequestContext::getMain() when null.
2741 */
2742 public function resetOptions(
2743 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2744 IContextSource $context = null
2745 ) {
2746 $this->load();
2747 $defaultOptions = self::getDefaultOptions();
2748
2749 if ( !is_array( $resetKinds ) ) {
2750 $resetKinds = array( $resetKinds );
2751 }
2752
2753 if ( in_array( 'all', $resetKinds ) ) {
2754 $newOptions = $defaultOptions;
2755 } else {
2756 if ( $context === null ) {
2757 $context = RequestContext::getMain();
2758 }
2759
2760 $optionKinds = $this->getOptionKinds( $context );
2761 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2762 $newOptions = array();
2763
2764 // Use default values for the options that should be deleted, and
2765 // copy old values for the ones that shouldn't.
2766 foreach ( $this->mOptions as $key => $value ) {
2767 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2768 if ( array_key_exists( $key, $defaultOptions ) ) {
2769 $newOptions[$key] = $defaultOptions[$key];
2770 }
2771 } else {
2772 $newOptions[$key] = $value;
2773 }
2774 }
2775 }
2776
2777 $this->mOptions = $newOptions;
2778 $this->mOptionsLoaded = true;
2779 }
2780
2781 /**
2782 * Get the user's preferred date format.
2783 * @return string User's preferred date format
2784 */
2785 public function getDatePreference() {
2786 // Important migration for old data rows
2787 if ( is_null( $this->mDatePreference ) ) {
2788 global $wgLang;
2789 $value = $this->getOption( 'date' );
2790 $map = $wgLang->getDatePreferenceMigrationMap();
2791 if ( isset( $map[$value] ) ) {
2792 $value = $map[$value];
2793 }
2794 $this->mDatePreference = $value;
2795 }
2796 return $this->mDatePreference;
2797 }
2798
2799 /**
2800 * Determine based on the wiki configuration and the user's options,
2801 * whether this user must be over HTTPS no matter what.
2802 *
2803 * @return bool
2804 */
2805 public function requiresHTTPS() {
2806 global $wgSecureLogin;
2807 if ( !$wgSecureLogin ) {
2808 return false;
2809 } else {
2810 $https = $this->getBoolOption( 'prefershttps' );
2811 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2812 if ( $https ) {
2813 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2814 }
2815 return $https;
2816 }
2817 }
2818
2819 /**
2820 * Get the user preferred stub threshold
2821 *
2822 * @return int
2823 */
2824 public function getStubThreshold() {
2825 global $wgMaxArticleSize; # Maximum article size, in Kb
2826 $threshold = $this->getIntOption( 'stubthreshold' );
2827 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2828 // If they have set an impossible value, disable the preference
2829 // so we can use the parser cache again.
2830 $threshold = 0;
2831 }
2832 return $threshold;
2833 }
2834
2835 /**
2836 * Get the permissions this user has.
2837 * @return array Array of String permission names
2838 */
2839 public function getRights() {
2840 if ( is_null( $this->mRights ) ) {
2841 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2842 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2843 // Force reindexation of rights when a hook has unset one of them
2844 $this->mRights = array_values( array_unique( $this->mRights ) );
2845 }
2846 return $this->mRights;
2847 }
2848
2849 /**
2850 * Get the list of explicit group memberships this user has.
2851 * The implicit * and user groups are not included.
2852 * @return array Array of String internal group names
2853 */
2854 public function getGroups() {
2855 $this->load();
2856 $this->loadGroups();
2857 return $this->mGroups;
2858 }
2859
2860 /**
2861 * Get the list of implicit group memberships this user has.
2862 * This includes all explicit groups, plus 'user' if logged in,
2863 * '*' for all accounts, and autopromoted groups
2864 * @param bool $recache Whether to avoid the cache
2865 * @return array Array of String internal group names
2866 */
2867 public function getEffectiveGroups( $recache = false ) {
2868 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2869 wfProfileIn( __METHOD__ );
2870 $this->mEffectiveGroups = array_unique( array_merge(
2871 $this->getGroups(), // explicit groups
2872 $this->getAutomaticGroups( $recache ) // implicit groups
2873 ) );
2874 // Hook for additional groups
2875 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2876 // Force reindexation of groups when a hook has unset one of them
2877 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2878 wfProfileOut( __METHOD__ );
2879 }
2880 return $this->mEffectiveGroups;
2881 }
2882
2883 /**
2884 * Get the list of implicit group memberships this user has.
2885 * This includes 'user' if logged in, '*' for all accounts,
2886 * and autopromoted groups
2887 * @param bool $recache Whether to avoid the cache
2888 * @return array Array of String internal group names
2889 */
2890 public function getAutomaticGroups( $recache = false ) {
2891 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2892 wfProfileIn( __METHOD__ );
2893 $this->mImplicitGroups = array( '*' );
2894 if ( $this->getId() ) {
2895 $this->mImplicitGroups[] = 'user';
2896
2897 $this->mImplicitGroups = array_unique( array_merge(
2898 $this->mImplicitGroups,
2899 Autopromote::getAutopromoteGroups( $this )
2900 ) );
2901 }
2902 if ( $recache ) {
2903 // Assure data consistency with rights/groups,
2904 // as getEffectiveGroups() depends on this function
2905 $this->mEffectiveGroups = null;
2906 }
2907 wfProfileOut( __METHOD__ );
2908 }
2909 return $this->mImplicitGroups;
2910 }
2911
2912 /**
2913 * Returns the groups the user has belonged to.
2914 *
2915 * The user may still belong to the returned groups. Compare with getGroups().
2916 *
2917 * The function will not return groups the user had belonged to before MW 1.17
2918 *
2919 * @return array Names of the groups the user has belonged to.
2920 */
2921 public function getFormerGroups() {
2922 if ( is_null( $this->mFormerGroups ) ) {
2923 $dbr = wfGetDB( DB_MASTER );
2924 $res = $dbr->select( 'user_former_groups',
2925 array( 'ufg_group' ),
2926 array( 'ufg_user' => $this->mId ),
2927 __METHOD__ );
2928 $this->mFormerGroups = array();
2929 foreach ( $res as $row ) {
2930 $this->mFormerGroups[] = $row->ufg_group;
2931 }
2932 }
2933 return $this->mFormerGroups;
2934 }
2935
2936 /**
2937 * Get the user's edit count.
2938 * @return int|null null for anonymous users
2939 */
2940 public function getEditCount() {
2941 if ( !$this->getId() ) {
2942 return null;
2943 }
2944
2945 if ( !isset( $this->mEditCount ) ) {
2946 /* Populate the count, if it has not been populated yet */
2947 wfProfileIn( __METHOD__ );
2948 $dbr = wfGetDB( DB_SLAVE );
2949 // check if the user_editcount field has been initialized
2950 $count = $dbr->selectField(
2951 'user', 'user_editcount',
2952 array( 'user_id' => $this->mId ),
2953 __METHOD__
2954 );
2955
2956 if ( $count === null ) {
2957 // it has not been initialized. do so.
2958 $count = $this->initEditCount();
2959 }
2960 $this->mEditCount = $count;
2961 wfProfileOut( __METHOD__ );
2962 }
2963 return (int)$this->mEditCount;
2964 }
2965
2966 /**
2967 * Add the user to the given group.
2968 * This takes immediate effect.
2969 * @param string $group Name of the group to add
2970 */
2971 public function addGroup( $group ) {
2972 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2973 $dbw = wfGetDB( DB_MASTER );
2974 if ( $this->getId() ) {
2975 $dbw->insert( 'user_groups',
2976 array(
2977 'ug_user' => $this->getID(),
2978 'ug_group' => $group,
2979 ),
2980 __METHOD__,
2981 array( 'IGNORE' ) );
2982 }
2983 }
2984 $this->loadGroups();
2985 $this->mGroups[] = $group;
2986 // In case loadGroups was not called before, we now have the right twice.
2987 // Get rid of the duplicate.
2988 $this->mGroups = array_unique( $this->mGroups );
2989
2990 // Refresh the groups caches, and clear the rights cache so it will be
2991 // refreshed on the next call to $this->getRights().
2992 $this->getEffectiveGroups( true );
2993 $this->mRights = null;
2994
2995 $this->invalidateCache();
2996 }
2997
2998 /**
2999 * Remove the user from the given group.
3000 * This takes immediate effect.
3001 * @param string $group Name of the group to remove
3002 */
3003 public function removeGroup( $group ) {
3004 $this->load();
3005 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3006 $dbw = wfGetDB( DB_MASTER );
3007 $dbw->delete( 'user_groups',
3008 array(
3009 'ug_user' => $this->getID(),
3010 'ug_group' => $group,
3011 ), __METHOD__ );
3012 // Remember that the user was in this group
3013 $dbw->insert( 'user_former_groups',
3014 array(
3015 'ufg_user' => $this->getID(),
3016 'ufg_group' => $group,
3017 ),
3018 __METHOD__,
3019 array( 'IGNORE' ) );
3020 }
3021 $this->loadGroups();
3022 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
3023
3024 // Refresh the groups caches, and clear the rights cache so it will be
3025 // refreshed on the next call to $this->getRights().
3026 $this->getEffectiveGroups( true );
3027 $this->mRights = null;
3028
3029 $this->invalidateCache();
3030 }
3031
3032 /**
3033 * Get whether the user is logged in
3034 * @return bool
3035 */
3036 public function isLoggedIn() {
3037 return $this->getID() != 0;
3038 }
3039
3040 /**
3041 * Get whether the user is anonymous
3042 * @return bool
3043 */
3044 public function isAnon() {
3045 return !$this->isLoggedIn();
3046 }
3047
3048 /**
3049 * Check if user is allowed to access a feature / make an action
3050 *
3051 * @internal param \String $varargs permissions to test
3052 * @return bool True if user is allowed to perform *any* of the given actions
3053 *
3054 * @return bool
3055 */
3056 public function isAllowedAny( /*...*/ ) {
3057 $permissions = func_get_args();
3058 foreach ( $permissions as $permission ) {
3059 if ( $this->isAllowed( $permission ) ) {
3060 return true;
3061 }
3062 }
3063 return false;
3064 }
3065
3066 /**
3067 *
3068 * @internal param $varargs string
3069 * @return bool True if the user is allowed to perform *all* of the given actions
3070 */
3071 public function isAllowedAll( /*...*/ ) {
3072 $permissions = func_get_args();
3073 foreach ( $permissions as $permission ) {
3074 if ( !$this->isAllowed( $permission ) ) {
3075 return false;
3076 }
3077 }
3078 return true;
3079 }
3080
3081 /**
3082 * Internal mechanics of testing a permission
3083 * @param string $action
3084 * @return bool
3085 */
3086 public function isAllowed( $action = '' ) {
3087 if ( $action === '' ) {
3088 return true; // In the spirit of DWIM
3089 }
3090 // Patrolling may not be enabled
3091 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3092 global $wgUseRCPatrol, $wgUseNPPatrol;
3093 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3094 return false;
3095 }
3096 }
3097 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3098 // by misconfiguration: 0 == 'foo'
3099 return in_array( $action, $this->getRights(), true );
3100 }
3101
3102 /**
3103 * Check whether to enable recent changes patrol features for this user
3104 * @return bool True or false
3105 */
3106 public function useRCPatrol() {
3107 global $wgUseRCPatrol;
3108 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3109 }
3110
3111 /**
3112 * Check whether to enable new pages patrol features for this user
3113 * @return bool True or false
3114 */
3115 public function useNPPatrol() {
3116 global $wgUseRCPatrol, $wgUseNPPatrol;
3117 return (
3118 ( $wgUseRCPatrol || $wgUseNPPatrol )
3119 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3120 );
3121 }
3122
3123 /**
3124 * Get the WebRequest object to use with this object
3125 *
3126 * @return WebRequest
3127 */
3128 public function getRequest() {
3129 if ( $this->mRequest ) {
3130 return $this->mRequest;
3131 } else {
3132 global $wgRequest;
3133 return $wgRequest;
3134 }
3135 }
3136
3137 /**
3138 * Get the current skin, loading it if required
3139 * @return Skin The current skin
3140 * @todo FIXME: Need to check the old failback system [AV]
3141 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3142 */
3143 public function getSkin() {
3144 wfDeprecated( __METHOD__, '1.18' );
3145 return RequestContext::getMain()->getSkin();
3146 }
3147
3148 /**
3149 * Get a WatchedItem for this user and $title.
3150 *
3151 * @since 1.22 $checkRights parameter added
3152 * @param Title $title
3153 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3154 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3155 * @return WatchedItem
3156 */
3157 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3158 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3159
3160 if ( isset( $this->mWatchedItems[$key] ) ) {
3161 return $this->mWatchedItems[$key];
3162 }
3163
3164 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3165 $this->mWatchedItems = array();
3166 }
3167
3168 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3169 return $this->mWatchedItems[$key];
3170 }
3171
3172 /**
3173 * Check the watched status of an article.
3174 * @since 1.22 $checkRights parameter added
3175 * @param Title $title Title of the article to look at
3176 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3177 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3178 * @return bool
3179 */
3180 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3181 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3182 }
3183
3184 /**
3185 * Watch an article.
3186 * @since 1.22 $checkRights parameter added
3187 * @param Title $title Title of the article to look at
3188 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3189 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3190 */
3191 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3192 $this->getWatchedItem( $title, $checkRights )->addWatch();
3193 $this->invalidateCache();
3194 }
3195
3196 /**
3197 * Stop watching an article.
3198 * @since 1.22 $checkRights parameter added
3199 * @param Title $title Title of the article to look at
3200 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3201 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3202 */
3203 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3204 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3205 $this->invalidateCache();
3206 }
3207
3208 /**
3209 * Clear the user's notification timestamp for the given title.
3210 * If e-notif e-mails are on, they will receive notification mails on
3211 * the next change of the page if it's watched etc.
3212 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3213 * @param Title $title Title of the article to look at
3214 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3215 */
3216 public function clearNotification( &$title, $oldid = 0 ) {
3217 global $wgUseEnotif, $wgShowUpdatedMarker;
3218
3219 // Do nothing if the database is locked to writes
3220 if ( wfReadOnly() ) {
3221 return;
3222 }
3223
3224 // Do nothing if not allowed to edit the watchlist
3225 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3226 return;
3227 }
3228
3229 // If we're working on user's talk page, we should update the talk page message indicator
3230 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3231 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3232 return;
3233 }
3234
3235 $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null;
3236
3237 if ( !$oldid || !$nextid ) {
3238 // If we're looking at the latest revision, we should definitely clear it
3239 $this->setNewtalk( false );
3240 } else {
3241 // Otherwise we should update its revision, if it's present
3242 if ( $this->getNewtalk() ) {
3243 // Naturally the other one won't clear by itself
3244 $this->setNewtalk( false );
3245 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3246 }
3247 }
3248 }
3249
3250 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3251 return;
3252 }
3253
3254 if ( $this->isAnon() ) {
3255 // Nothing else to do...
3256 return;
3257 }
3258
3259 // Only update the timestamp if the page is being watched.
3260 // The query to find out if it is watched is cached both in memcached and per-invocation,
3261 // and when it does have to be executed, it can be on a slave
3262 // If this is the user's newtalk page, we always update the timestamp
3263 $force = '';
3264 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3265 $force = 'force';
3266 }
3267
3268 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3269 }
3270
3271 /**
3272 * Resets all of the given user's page-change notification timestamps.
3273 * If e-notif e-mails are on, they will receive notification mails on
3274 * the next change of any watched page.
3275 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3276 */
3277 public function clearAllNotifications() {
3278 if ( wfReadOnly() ) {
3279 return;
3280 }
3281
3282 // Do nothing if not allowed to edit the watchlist
3283 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3284 return;
3285 }
3286
3287 global $wgUseEnotif, $wgShowUpdatedMarker;
3288 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3289 $this->setNewtalk( false );
3290 return;
3291 }
3292 $id = $this->getId();
3293 if ( $id != 0 ) {
3294 $dbw = wfGetDB( DB_MASTER );
3295 $dbw->update( 'watchlist',
3296 array( /* SET */ 'wl_notificationtimestamp' => null ),
3297 array( /* WHERE */ 'wl_user' => $id ),
3298 __METHOD__
3299 );
3300 // We also need to clear here the "you have new message" notification for the own user_talk page;
3301 // it's cleared one page view later in WikiPage::doViewUpdates().
3302 }
3303 }
3304
3305 /**
3306 * Set this user's options from an encoded string
3307 * @param string $str Encoded options to import
3308 *
3309 * @deprecated since 1.19 due to removal of user_options from the user table
3310 */
3311 private function decodeOptions( $str ) {
3312 wfDeprecated( __METHOD__, '1.19' );
3313 if ( !$str ) {
3314 return;
3315 }
3316
3317 $this->mOptionsLoaded = true;
3318 $this->mOptionOverrides = array();
3319
3320 // If an option is not set in $str, use the default value
3321 $this->mOptions = self::getDefaultOptions();
3322
3323 $a = explode( "\n", $str );
3324 foreach ( $a as $s ) {
3325 $m = array();
3326 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
3327 $this->mOptions[$m[1]] = $m[2];
3328 $this->mOptionOverrides[$m[1]] = $m[2];
3329 }
3330 }
3331 }
3332
3333 /**
3334 * Set a cookie on the user's client. Wrapper for
3335 * WebResponse::setCookie
3336 * @param string $name Name of the cookie to set
3337 * @param string $value Value to set
3338 * @param int $exp Expiration time, as a UNIX time value;
3339 * if 0 or not specified, use the default $wgCookieExpiration
3340 * @param bool $secure
3341 * true: Force setting the secure attribute when setting the cookie
3342 * false: Force NOT setting the secure attribute when setting the cookie
3343 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3344 * @param array $params Array of options sent passed to WebResponse::setcookie()
3345 */
3346 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3347 $params['secure'] = $secure;
3348 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3349 }
3350
3351 /**
3352 * Clear a cookie on the user's client
3353 * @param string $name Name of the cookie to clear
3354 * @param bool $secure
3355 * true: Force setting the secure attribute when setting the cookie
3356 * false: Force NOT setting the secure attribute when setting the cookie
3357 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3358 * @param array $params Array of options sent passed to WebResponse::setcookie()
3359 */
3360 protected function clearCookie( $name, $secure = null, $params = array() ) {
3361 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3362 }
3363
3364 /**
3365 * Set the default cookies for this session on the user's client.
3366 *
3367 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3368 * is passed.
3369 * @param bool $secure Whether to force secure/insecure cookies or use default
3370 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3371 */
3372 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3373 if ( $request === null ) {
3374 $request = $this->getRequest();
3375 }
3376
3377 $this->load();
3378 if ( 0 == $this->mId ) {
3379 return;
3380 }
3381 if ( !$this->mToken ) {
3382 // When token is empty or NULL generate a new one and then save it to the database
3383 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3384 // Simply by setting every cell in the user_token column to NULL and letting them be
3385 // regenerated as users log back into the wiki.
3386 $this->setToken();
3387 $this->saveSettings();
3388 }
3389 $session = array(
3390 'wsUserID' => $this->mId,
3391 'wsToken' => $this->mToken,
3392 'wsUserName' => $this->getName()
3393 );
3394 $cookies = array(
3395 'UserID' => $this->mId,
3396 'UserName' => $this->getName(),
3397 );
3398 if ( $rememberMe ) {
3399 $cookies['Token'] = $this->mToken;
3400 } else {
3401 $cookies['Token'] = false;
3402 }
3403
3404 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3405
3406 foreach ( $session as $name => $value ) {
3407 $request->setSessionData( $name, $value );
3408 }
3409 foreach ( $cookies as $name => $value ) {
3410 if ( $value === false ) {
3411 $this->clearCookie( $name );
3412 } else {
3413 $this->setCookie( $name, $value, 0, $secure );
3414 }
3415 }
3416
3417 /**
3418 * If wpStickHTTPS was selected, also set an insecure cookie that
3419 * will cause the site to redirect the user to HTTPS, if they access
3420 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3421 * as the one set by centralauth (bug 53538). Also set it to session, or
3422 * standard time setting, based on if rememberme was set.
3423 */
3424 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3425 $this->setCookie(
3426 'forceHTTPS',
3427 'true',
3428 $rememberMe ? 0 : null,
3429 false,
3430 array( 'prefix' => '' ) // no prefix
3431 );
3432 }
3433 }
3434
3435 /**
3436 * Log this user out.
3437 */
3438 public function logout() {
3439 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3440 $this->doLogout();
3441 }
3442 }
3443
3444 /**
3445 * Clear the user's cookies and session, and reset the instance cache.
3446 * @see logout()
3447 */
3448 public function doLogout() {
3449 $this->clearInstanceCache( 'defaults' );
3450
3451 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3452
3453 $this->clearCookie( 'UserID' );
3454 $this->clearCookie( 'Token' );
3455 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3456
3457 // Remember when user logged out, to prevent seeing cached pages
3458 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3459 }
3460
3461 /**
3462 * Save this user's settings into the database.
3463 * @todo Only rarely do all these fields need to be set!
3464 */
3465 public function saveSettings() {
3466 global $wgAuth;
3467
3468 $this->load();
3469 if ( wfReadOnly() ) {
3470 return;
3471 }
3472 if ( 0 == $this->mId ) {
3473 return;
3474 }
3475
3476 $this->mTouched = self::newTouchedTimestamp();
3477 if ( !$wgAuth->allowSetLocalPassword() ) {
3478 $this->mPassword = '';
3479 }
3480
3481 $dbw = wfGetDB( DB_MASTER );
3482 $dbw->update( 'user',
3483 array( /* SET */
3484 'user_name' => $this->mName,
3485 'user_password' => $this->mPassword,
3486 'user_newpassword' => $this->mNewpassword,
3487 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3488 'user_real_name' => $this->mRealName,
3489 'user_email' => $this->mEmail,
3490 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3491 'user_touched' => $dbw->timestamp( $this->mTouched ),
3492 'user_token' => strval( $this->mToken ),
3493 'user_email_token' => $this->mEmailToken,
3494 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3495 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3496 ), array( /* WHERE */
3497 'user_id' => $this->mId
3498 ), __METHOD__
3499 );
3500
3501 $this->saveOptions();
3502
3503 wfRunHooks( 'UserSaveSettings', array( $this ) );
3504 $this->clearSharedCache();
3505 $this->getUserPage()->invalidateCache();
3506 }
3507
3508 /**
3509 * If only this user's username is known, and it exists, return the user ID.
3510 * @return int
3511 */
3512 public function idForName() {
3513 $s = trim( $this->getName() );
3514 if ( $s === '' ) {
3515 return 0;
3516 }
3517
3518 $dbr = wfGetDB( DB_SLAVE );
3519 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3520 if ( $id === false ) {
3521 $id = 0;
3522 }
3523 return $id;
3524 }
3525
3526 /**
3527 * Add a user to the database, return the user object
3528 *
3529 * @param string $name Username to add
3530 * @param array $params Array of Strings Non-default parameters to save to
3531 * the database as user_* fields:
3532 * - password: The user's password hash. Password logins will be disabled
3533 * if this is omitted.
3534 * - newpassword: Hash for a temporary password that has been mailed to
3535 * the user.
3536 * - email: The user's email address.
3537 * - email_authenticated: The email authentication timestamp.
3538 * - real_name: The user's real name.
3539 * - options: An associative array of non-default options.
3540 * - token: Random authentication token. Do not set.
3541 * - registration: Registration timestamp. Do not set.
3542 *
3543 * @return User|null User object, or null if the username already exists.
3544 */
3545 public static function createNew( $name, $params = array() ) {
3546 $user = new User;
3547 $user->load();
3548 $user->setToken(); // init token
3549 if ( isset( $params['options'] ) ) {
3550 $user->mOptions = $params['options'] + (array)$user->mOptions;
3551 unset( $params['options'] );
3552 }
3553 $dbw = wfGetDB( DB_MASTER );
3554 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3555
3556 $fields = array(
3557 'user_id' => $seqVal,
3558 'user_name' => $name,
3559 'user_password' => $user->mPassword,
3560 'user_newpassword' => $user->mNewpassword,
3561 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3562 'user_email' => $user->mEmail,
3563 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3564 'user_real_name' => $user->mRealName,
3565 'user_token' => strval( $user->mToken ),
3566 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3567 'user_editcount' => 0,
3568 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3569 );
3570 foreach ( $params as $name => $value ) {
3571 $fields["user_$name"] = $value;
3572 }
3573 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3574 if ( $dbw->affectedRows() ) {
3575 $newUser = User::newFromId( $dbw->insertId() );
3576 } else {
3577 $newUser = null;
3578 }
3579 return $newUser;
3580 }
3581
3582 /**
3583 * Add this existing user object to the database. If the user already
3584 * exists, a fatal status object is returned, and the user object is
3585 * initialised with the data from the database.
3586 *
3587 * Previously, this function generated a DB error due to a key conflict
3588 * if the user already existed. Many extension callers use this function
3589 * in code along the lines of:
3590 *
3591 * $user = User::newFromName( $name );
3592 * if ( !$user->isLoggedIn() ) {
3593 * $user->addToDatabase();
3594 * }
3595 * // do something with $user...
3596 *
3597 * However, this was vulnerable to a race condition (bug 16020). By
3598 * initialising the user object if the user exists, we aim to support this
3599 * calling sequence as far as possible.
3600 *
3601 * Note that if the user exists, this function will acquire a write lock,
3602 * so it is still advisable to make the call conditional on isLoggedIn(),
3603 * and to commit the transaction after calling.
3604 *
3605 * @throws MWException
3606 * @return Status
3607 */
3608 public function addToDatabase() {
3609 $this->load();
3610 if ( !$this->mToken ) {
3611 $this->setToken(); // init token
3612 }
3613
3614 $this->mTouched = self::newTouchedTimestamp();
3615
3616 $dbw = wfGetDB( DB_MASTER );
3617 $inWrite = $dbw->writesOrCallbacksPending();
3618 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3619 $dbw->insert( 'user',
3620 array(
3621 'user_id' => $seqVal,
3622 'user_name' => $this->mName,
3623 'user_password' => $this->mPassword,
3624 'user_newpassword' => $this->mNewpassword,
3625 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3626 'user_email' => $this->mEmail,
3627 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3628 'user_real_name' => $this->mRealName,
3629 'user_token' => strval( $this->mToken ),
3630 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3631 'user_editcount' => 0,
3632 'user_touched' => $dbw->timestamp( $this->mTouched ),
3633 ), __METHOD__,
3634 array( 'IGNORE' )
3635 );
3636 if ( !$dbw->affectedRows() ) {
3637 if ( !$inWrite ) {
3638 // XXX: Get out of REPEATABLE-READ so the SELECT below works.
3639 // Often this case happens early in views before any writes.
3640 // This shows up at least with CentralAuth.
3641 $dbw->commit( __METHOD__, 'flush' );
3642 }
3643 $this->mId = $dbw->selectField( 'user', 'user_id',
3644 array( 'user_name' => $this->mName ), __METHOD__ );
3645 $loaded = false;
3646 if ( $this->mId ) {
3647 if ( $this->loadFromDatabase() ) {
3648 $loaded = true;
3649 }
3650 }
3651 if ( !$loaded ) {
3652 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3653 "to insert user '{$this->mName}' row, but it was not present in select!" );
3654 }
3655 return Status::newFatal( 'userexists' );
3656 }
3657 $this->mId = $dbw->insertId();
3658
3659 // Clear instance cache other than user table data, which is already accurate
3660 $this->clearInstanceCache();
3661
3662 $this->saveOptions();
3663 return Status::newGood();
3664 }
3665
3666 /**
3667 * If this user is logged-in and blocked,
3668 * block any IP address they've successfully logged in from.
3669 * @return bool A block was spread
3670 */
3671 public function spreadAnyEditBlock() {
3672 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3673 return $this->spreadBlock();
3674 }
3675 return false;
3676 }
3677
3678 /**
3679 * If this (non-anonymous) user is blocked,
3680 * block the IP address they've successfully logged in from.
3681 * @return bool A block was spread
3682 */
3683 protected function spreadBlock() {
3684 wfDebug( __METHOD__ . "()\n" );
3685 $this->load();
3686 if ( $this->mId == 0 ) {
3687 return false;
3688 }
3689
3690 $userblock = Block::newFromTarget( $this->getName() );
3691 if ( !$userblock ) {
3692 return false;
3693 }
3694
3695 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3696 }
3697
3698 /**
3699 * Get whether the user is explicitly blocked from account creation.
3700 * @return bool|Block
3701 */
3702 public function isBlockedFromCreateAccount() {
3703 $this->getBlockedStatus();
3704 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3705 return $this->mBlock;
3706 }
3707
3708 # bug 13611: if the IP address the user is trying to create an account from is
3709 # blocked with createaccount disabled, prevent new account creation there even
3710 # when the user is logged in
3711 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3712 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3713 }
3714 return $this->mBlockedFromCreateAccount instanceof Block
3715 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3716 ? $this->mBlockedFromCreateAccount
3717 : false;
3718 }
3719
3720 /**
3721 * Get whether the user is blocked from using Special:Emailuser.
3722 * @return bool
3723 */
3724 public function isBlockedFromEmailuser() {
3725 $this->getBlockedStatus();
3726 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3727 }
3728
3729 /**
3730 * Get whether the user is allowed to create an account.
3731 * @return bool
3732 */
3733 public function isAllowedToCreateAccount() {
3734 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3735 }
3736
3737 /**
3738 * Get this user's personal page title.
3739 *
3740 * @return Title User's personal page title
3741 */
3742 public function getUserPage() {
3743 return Title::makeTitle( NS_USER, $this->getName() );
3744 }
3745
3746 /**
3747 * Get this user's talk page title.
3748 *
3749 * @return Title User's talk page title
3750 */
3751 public function getTalkPage() {
3752 $title = $this->getUserPage();
3753 return $title->getTalkPage();
3754 }
3755
3756 /**
3757 * Determine whether the user is a newbie. Newbies are either
3758 * anonymous IPs, or the most recently created accounts.
3759 * @return bool
3760 */
3761 public function isNewbie() {
3762 return !$this->isAllowed( 'autoconfirmed' );
3763 }
3764
3765 /**
3766 * Check to see if the given clear-text password is one of the accepted passwords
3767 * @param string $password user password.
3768 * @return bool True if the given password is correct, otherwise False.
3769 */
3770 public function checkPassword( $password ) {
3771 global $wgAuth, $wgLegacyEncoding;
3772 $this->load();
3773
3774 // Certain authentication plugins do NOT want to save
3775 // domain passwords in a mysql database, so we should
3776 // check this (in case $wgAuth->strict() is false).
3777
3778 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3779 return true;
3780 } elseif ( $wgAuth->strict() ) {
3781 // Auth plugin doesn't allow local authentication
3782 return false;
3783 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3784 // Auth plugin doesn't allow local authentication for this user name
3785 return false;
3786 }
3787 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
3788 return true;
3789 } elseif ( $wgLegacyEncoding ) {
3790 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3791 // Check for this with iconv
3792 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3793 if ( $cp1252Password != $password
3794 && self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId )
3795 ) {
3796 return true;
3797 }
3798 }
3799 return false;
3800 }
3801
3802 /**
3803 * Check if the given clear-text password matches the temporary password
3804 * sent by e-mail for password reset operations.
3805 *
3806 * @param string $plaintext
3807 *
3808 * @return bool True if matches, false otherwise
3809 */
3810 public function checkTemporaryPassword( $plaintext ) {
3811 global $wgNewPasswordExpiry;
3812
3813 $this->load();
3814 if ( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
3815 if ( is_null( $this->mNewpassTime ) ) {
3816 return true;
3817 }
3818 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3819 return ( time() < $expiry );
3820 } else {
3821 return false;
3822 }
3823 }
3824
3825 /**
3826 * Alias for getEditToken.
3827 * @deprecated since 1.19, use getEditToken instead.
3828 *
3829 * @param string|array $salt of Strings Optional function-specific data for hashing
3830 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3831 * @return string The new edit token
3832 */
3833 public function editToken( $salt = '', $request = null ) {
3834 wfDeprecated( __METHOD__, '1.19' );
3835 return $this->getEditToken( $salt, $request );
3836 }
3837
3838 /**
3839 * Initialize (if necessary) and return a session token value
3840 * which can be used in edit forms to show that the user's
3841 * login credentials aren't being hijacked with a foreign form
3842 * submission.
3843 *
3844 * @since 1.19
3845 *
3846 * @param string|array $salt of Strings Optional function-specific data for hashing
3847 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3848 * @return string The new edit token
3849 */
3850 public function getEditToken( $salt = '', $request = null ) {
3851 if ( $request == null ) {
3852 $request = $this->getRequest();
3853 }
3854
3855 if ( $this->isAnon() ) {
3856 return EDIT_TOKEN_SUFFIX;
3857 } else {
3858 $token = $request->getSessionData( 'wsEditToken' );
3859 if ( $token === null ) {
3860 $token = MWCryptRand::generateHex( 32 );
3861 $request->setSessionData( 'wsEditToken', $token );
3862 }
3863 if ( is_array( $salt ) ) {
3864 $salt = implode( '|', $salt );
3865 }
3866 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
3867 }
3868 }
3869
3870 /**
3871 * Generate a looking random token for various uses.
3872 *
3873 * @return string The new random token
3874 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3875 * wfRandomString for pseudo-randomness.
3876 */
3877 public static function generateToken() {
3878 return MWCryptRand::generateHex( 32 );
3879 }
3880
3881 /**
3882 * Check given value against the token value stored in the session.
3883 * A match should confirm that the form was submitted from the
3884 * user's own login session, not a form submission from a third-party
3885 * site.
3886 *
3887 * @param string $val Input value to compare
3888 * @param string $salt Optional function-specific data for hashing
3889 * @param WebRequest|null $request Object to use or null to use $wgRequest
3890 * @return bool Whether the token matches
3891 */
3892 public function matchEditToken( $val, $salt = '', $request = null ) {
3893 $sessionToken = $this->getEditToken( $salt, $request );
3894 if ( $val != $sessionToken ) {
3895 wfDebug( "User::matchEditToken: broken session data\n" );
3896 }
3897
3898 return $val == $sessionToken;
3899 }
3900
3901 /**
3902 * Check given value against the token value stored in the session,
3903 * ignoring the suffix.
3904 *
3905 * @param string $val Input value to compare
3906 * @param string $salt Optional function-specific data for hashing
3907 * @param WebRequest|null $request object to use or null to use $wgRequest
3908 * @return bool Whether the token matches
3909 */
3910 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3911 $sessionToken = $this->getEditToken( $salt, $request );
3912 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3913 }
3914
3915 /**
3916 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3917 * mail to the user's given address.
3918 *
3919 * @param string $type Message to send, either "created", "changed" or "set"
3920 * @return Status
3921 */
3922 public function sendConfirmationMail( $type = 'created' ) {
3923 global $wgLang;
3924 $expiration = null; // gets passed-by-ref and defined in next line.
3925 $token = $this->confirmationToken( $expiration );
3926 $url = $this->confirmationTokenUrl( $token );
3927 $invalidateURL = $this->invalidationTokenUrl( $token );
3928 $this->saveSettings();
3929
3930 if ( $type == 'created' || $type === false ) {
3931 $message = 'confirmemail_body';
3932 } elseif ( $type === true ) {
3933 $message = 'confirmemail_body_changed';
3934 } else {
3935 // Messages: confirmemail_body_changed, confirmemail_body_set
3936 $message = 'confirmemail_body_' . $type;
3937 }
3938
3939 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3940 wfMessage( $message,
3941 $this->getRequest()->getIP(),
3942 $this->getName(),
3943 $url,
3944 $wgLang->timeanddate( $expiration, false ),
3945 $invalidateURL,
3946 $wgLang->date( $expiration, false ),
3947 $wgLang->time( $expiration, false ) )->text() );
3948 }
3949
3950 /**
3951 * Send an e-mail to this user's account. Does not check for
3952 * confirmed status or validity.
3953 *
3954 * @param string $subject Message subject
3955 * @param string $body Message body
3956 * @param string $from Optional From address; if unspecified, default
3957 * $wgPasswordSender will be used.
3958 * @param string $replyto Reply-To address
3959 * @return Status
3960 */
3961 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3962 if ( is_null( $from ) ) {
3963 global $wgPasswordSender;
3964 $sender = new MailAddress( $wgPasswordSender,
3965 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3966 } else {
3967 $sender = new MailAddress( $from );
3968 }
3969
3970 $to = new MailAddress( $this );
3971 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
3972 }
3973
3974 /**
3975 * Generate, store, and return a new e-mail confirmation code.
3976 * A hash (unsalted, since it's used as a key) is stored.
3977 *
3978 * @note Call saveSettings() after calling this function to commit
3979 * this change to the database.
3980 *
3981 * @param string &$expiration Accepts the expiration time
3982 * @return string New token
3983 */
3984 protected function confirmationToken( &$expiration ) {
3985 global $wgUserEmailConfirmationTokenExpiry;
3986 $now = time();
3987 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
3988 $expiration = wfTimestamp( TS_MW, $expires );
3989 $this->load();
3990 $token = MWCryptRand::generateHex( 32 );
3991 $hash = md5( $token );
3992 $this->mEmailToken = $hash;
3993 $this->mEmailTokenExpires = $expiration;
3994 return $token;
3995 }
3996
3997 /**
3998 * Return a URL the user can use to confirm their email address.
3999 * @param string $token Accepts the email confirmation token
4000 * @return string New token URL
4001 */
4002 protected function confirmationTokenUrl( $token ) {
4003 return $this->getTokenUrl( 'ConfirmEmail', $token );
4004 }
4005
4006 /**
4007 * Return a URL the user can use to invalidate their email address.
4008 * @param string $token Accepts the email confirmation token
4009 * @return string New token URL
4010 */
4011 protected function invalidationTokenUrl( $token ) {
4012 return $this->getTokenUrl( 'InvalidateEmail', $token );
4013 }
4014
4015 /**
4016 * Internal function to format the e-mail validation/invalidation URLs.
4017 * This uses a quickie hack to use the
4018 * hardcoded English names of the Special: pages, for ASCII safety.
4019 *
4020 * @note Since these URLs get dropped directly into emails, using the
4021 * short English names avoids insanely long URL-encoded links, which
4022 * also sometimes can get corrupted in some browsers/mailers
4023 * (bug 6957 with Gmail and Internet Explorer).
4024 *
4025 * @param string $page Special page
4026 * @param string $token Token
4027 * @return string Formatted URL
4028 */
4029 protected function getTokenUrl( $page, $token ) {
4030 // Hack to bypass localization of 'Special:'
4031 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4032 return $title->getCanonicalURL();
4033 }
4034
4035 /**
4036 * Mark the e-mail address confirmed.
4037 *
4038 * @note Call saveSettings() after calling this function to commit the change.
4039 *
4040 * @return bool
4041 */
4042 public function confirmEmail() {
4043 // Check if it's already confirmed, so we don't touch the database
4044 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4045 if ( !$this->isEmailConfirmed() ) {
4046 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4047 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
4048 }
4049 return true;
4050 }
4051
4052 /**
4053 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4054 * address if it was already confirmed.
4055 *
4056 * @note Call saveSettings() after calling this function to commit the change.
4057 * @return bool Returns true
4058 */
4059 public function invalidateEmail() {
4060 $this->load();
4061 $this->mEmailToken = null;
4062 $this->mEmailTokenExpires = null;
4063 $this->setEmailAuthenticationTimestamp( null );
4064 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4065 return true;
4066 }
4067
4068 /**
4069 * Set the e-mail authentication timestamp.
4070 * @param string $timestamp TS_MW timestamp
4071 */
4072 public function setEmailAuthenticationTimestamp( $timestamp ) {
4073 $this->load();
4074 $this->mEmailAuthenticated = $timestamp;
4075 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4076 }
4077
4078 /**
4079 * Is this user allowed to send e-mails within limits of current
4080 * site configuration?
4081 * @return bool
4082 */
4083 public function canSendEmail() {
4084 global $wgEnableEmail, $wgEnableUserEmail;
4085 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4086 return false;
4087 }
4088 $canSend = $this->isEmailConfirmed();
4089 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4090 return $canSend;
4091 }
4092
4093 /**
4094 * Is this user allowed to receive e-mails within limits of current
4095 * site configuration?
4096 * @return bool
4097 */
4098 public function canReceiveEmail() {
4099 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4100 }
4101
4102 /**
4103 * Is this user's e-mail address valid-looking and confirmed within
4104 * limits of the current site configuration?
4105 *
4106 * @note If $wgEmailAuthentication is on, this may require the user to have
4107 * confirmed their address by returning a code or using a password
4108 * sent to the address from the wiki.
4109 *
4110 * @return bool
4111 */
4112 public function isEmailConfirmed() {
4113 global $wgEmailAuthentication;
4114 $this->load();
4115 $confirmed = true;
4116 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4117 if ( $this->isAnon() ) {
4118 return false;
4119 }
4120 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4121 return false;
4122 }
4123 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4124 return false;
4125 }
4126 return true;
4127 } else {
4128 return $confirmed;
4129 }
4130 }
4131
4132 /**
4133 * Check whether there is an outstanding request for e-mail confirmation.
4134 * @return bool
4135 */
4136 public function isEmailConfirmationPending() {
4137 global $wgEmailAuthentication;
4138 return $wgEmailAuthentication &&
4139 !$this->isEmailConfirmed() &&
4140 $this->mEmailToken &&
4141 $this->mEmailTokenExpires > wfTimestamp();
4142 }
4143
4144 /**
4145 * Get the timestamp of account creation.
4146 *
4147 * @return string|bool|null Timestamp of account creation, false for
4148 * non-existent/anonymous user accounts, or null if existing account
4149 * but information is not in database.
4150 */
4151 public function getRegistration() {
4152 if ( $this->isAnon() ) {
4153 return false;
4154 }
4155 $this->load();
4156 return $this->mRegistration;
4157 }
4158
4159 /**
4160 * Get the timestamp of the first edit
4161 *
4162 * @return string|bool Timestamp of first edit, or false for
4163 * non-existent/anonymous user accounts.
4164 */
4165 public function getFirstEditTimestamp() {
4166 if ( $this->getId() == 0 ) {
4167 return false; // anons
4168 }
4169 $dbr = wfGetDB( DB_SLAVE );
4170 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4171 array( 'rev_user' => $this->getId() ),
4172 __METHOD__,
4173 array( 'ORDER BY' => 'rev_timestamp ASC' )
4174 );
4175 if ( !$time ) {
4176 return false; // no edits
4177 }
4178 return wfTimestamp( TS_MW, $time );
4179 }
4180
4181 /**
4182 * Get the permissions associated with a given list of groups
4183 *
4184 * @param array $groups Array of Strings List of internal group names
4185 * @return array Array of Strings List of permission key names for given groups combined
4186 */
4187 public static function getGroupPermissions( $groups ) {
4188 global $wgGroupPermissions, $wgRevokePermissions;
4189 $rights = array();
4190 // grant every granted permission first
4191 foreach ( $groups as $group ) {
4192 if ( isset( $wgGroupPermissions[$group] ) ) {
4193 $rights = array_merge( $rights,
4194 // array_filter removes empty items
4195 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4196 }
4197 }
4198 // now revoke the revoked permissions
4199 foreach ( $groups as $group ) {
4200 if ( isset( $wgRevokePermissions[$group] ) ) {
4201 $rights = array_diff( $rights,
4202 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4203 }
4204 }
4205 return array_unique( $rights );
4206 }
4207
4208 /**
4209 * Get all the groups who have a given permission
4210 *
4211 * @param string $role Role to check
4212 * @return array Array of Strings List of internal group names with the given permission
4213 */
4214 public static function getGroupsWithPermission( $role ) {
4215 global $wgGroupPermissions;
4216 $allowedGroups = array();
4217 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4218 if ( self::groupHasPermission( $group, $role ) ) {
4219 $allowedGroups[] = $group;
4220 }
4221 }
4222 return $allowedGroups;
4223 }
4224
4225 /**
4226 * Check, if the given group has the given permission
4227 *
4228 * If you're wanting to check whether all users have a permission, use
4229 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4230 * from anyone.
4231 *
4232 * @since 1.21
4233 * @param string $group Group to check
4234 * @param string $role Role to check
4235 * @return bool
4236 */
4237 public static function groupHasPermission( $group, $role ) {
4238 global $wgGroupPermissions, $wgRevokePermissions;
4239 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4240 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4241 }
4242
4243 /**
4244 * Check if all users have the given permission
4245 *
4246 * @since 1.22
4247 * @param string $right Right to check
4248 * @return bool
4249 */
4250 public static function isEveryoneAllowed( $right ) {
4251 global $wgGroupPermissions, $wgRevokePermissions;
4252 static $cache = array();
4253
4254 // Use the cached results, except in unit tests which rely on
4255 // being able change the permission mid-request
4256 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4257 return $cache[$right];
4258 }
4259
4260 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4261 $cache[$right] = false;
4262 return false;
4263 }
4264
4265 // If it's revoked anywhere, then everyone doesn't have it
4266 foreach ( $wgRevokePermissions as $rights ) {
4267 if ( isset( $rights[$right] ) && $rights[$right] ) {
4268 $cache[$right] = false;
4269 return false;
4270 }
4271 }
4272
4273 // Allow extensions (e.g. OAuth) to say false
4274 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4275 $cache[$right] = false;
4276 return false;
4277 }
4278
4279 $cache[$right] = true;
4280 return true;
4281 }
4282
4283 /**
4284 * Get the localized descriptive name for a group, if it exists
4285 *
4286 * @param string $group Internal group name
4287 * @return string Localized descriptive group name
4288 */
4289 public static function getGroupName( $group ) {
4290 $msg = wfMessage( "group-$group" );
4291 return $msg->isBlank() ? $group : $msg->text();
4292 }
4293
4294 /**
4295 * Get the localized descriptive name for a member of a group, if it exists
4296 *
4297 * @param string $group Internal group name
4298 * @param string $username Username for gender (since 1.19)
4299 * @return string Localized name for group member
4300 */
4301 public static function getGroupMember( $group, $username = '#' ) {
4302 $msg = wfMessage( "group-$group-member", $username );
4303 return $msg->isBlank() ? $group : $msg->text();
4304 }
4305
4306 /**
4307 * Return the set of defined explicit groups.
4308 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4309 * are not included, as they are defined automatically, not in the database.
4310 * @return array Array of internal group names
4311 */
4312 public static function getAllGroups() {
4313 global $wgGroupPermissions, $wgRevokePermissions;
4314 return array_diff(
4315 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4316 self::getImplicitGroups()
4317 );
4318 }
4319
4320 /**
4321 * Get a list of all available permissions.
4322 * @return array Array of permission names
4323 */
4324 public static function getAllRights() {
4325 if ( self::$mAllRights === false ) {
4326 global $wgAvailableRights;
4327 if ( count( $wgAvailableRights ) ) {
4328 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4329 } else {
4330 self::$mAllRights = self::$mCoreRights;
4331 }
4332 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
4333 }
4334 return self::$mAllRights;
4335 }
4336
4337 /**
4338 * Get a list of implicit groups
4339 * @return array Array of Strings Array of internal group names
4340 */
4341 public static function getImplicitGroups() {
4342 global $wgImplicitGroups;
4343
4344 $groups = $wgImplicitGroups;
4345 # Deprecated, use $wgImplictGroups instead
4346 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );
4347
4348 return $groups;
4349 }
4350
4351 /**
4352 * Get the title of a page describing a particular group
4353 *
4354 * @param string $group Internal group name
4355 * @return Title|bool Title of the page if it exists, false otherwise
4356 */
4357 public static function getGroupPage( $group ) {
4358 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4359 if ( $msg->exists() ) {
4360 $title = Title::newFromText( $msg->text() );
4361 if ( is_object( $title ) ) {
4362 return $title;
4363 }
4364 }
4365 return false;
4366 }
4367
4368 /**
4369 * Create a link to the group in HTML, if available;
4370 * else return the group name.
4371 *
4372 * @param string $group Internal name of the group
4373 * @param string $text The text of the link
4374 * @return string HTML link to the group
4375 */
4376 public static function makeGroupLinkHTML( $group, $text = '' ) {
4377 if ( $text == '' ) {
4378 $text = self::getGroupName( $group );
4379 }
4380 $title = self::getGroupPage( $group );
4381 if ( $title ) {
4382 return Linker::link( $title, htmlspecialchars( $text ) );
4383 } else {
4384 return $text;
4385 }
4386 }
4387
4388 /**
4389 * Create a link to the group in Wikitext, if available;
4390 * else return the group name.
4391 *
4392 * @param string $group Internal name of the group
4393 * @param string $text The text of the link
4394 * @return string Wikilink to the group
4395 */
4396 public static function makeGroupLinkWiki( $group, $text = '' ) {
4397 if ( $text == '' ) {
4398 $text = self::getGroupName( $group );
4399 }
4400 $title = self::getGroupPage( $group );
4401 if ( $title ) {
4402 $page = $title->getPrefixedText();
4403 return "[[$page|$text]]";
4404 } else {
4405 return $text;
4406 }
4407 }
4408
4409 /**
4410 * Returns an array of the groups that a particular group can add/remove.
4411 *
4412 * @param string $group The group to check for whether it can add/remove
4413 * @return array array( 'add' => array( addablegroups ),
4414 * 'remove' => array( removablegroups ),
4415 * 'add-self' => array( addablegroups to self),
4416 * 'remove-self' => array( removable groups from self) )
4417 */
4418 public static function changeableByGroup( $group ) {
4419 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4420
4421 $groups = array(
4422 'add' => array(),
4423 'remove' => array(),
4424 'add-self' => array(),
4425 'remove-self' => array()
4426 );
4427
4428 if ( empty( $wgAddGroups[$group] ) ) {
4429 // Don't add anything to $groups
4430 } elseif ( $wgAddGroups[$group] === true ) {
4431 // You get everything
4432 $groups['add'] = self::getAllGroups();
4433 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4434 $groups['add'] = $wgAddGroups[$group];
4435 }
4436
4437 // Same thing for remove
4438 if ( empty( $wgRemoveGroups[$group] ) ) {
4439 } elseif ( $wgRemoveGroups[$group] === true ) {
4440 $groups['remove'] = self::getAllGroups();
4441 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4442 $groups['remove'] = $wgRemoveGroups[$group];
4443 }
4444
4445 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4446 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4447 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4448 if ( is_int( $key ) ) {
4449 $wgGroupsAddToSelf['user'][] = $value;
4450 }
4451 }
4452 }
4453
4454 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4455 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4456 if ( is_int( $key ) ) {
4457 $wgGroupsRemoveFromSelf['user'][] = $value;
4458 }
4459 }
4460 }
4461
4462 // Now figure out what groups the user can add to him/herself
4463 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4464 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4465 // No idea WHY this would be used, but it's there
4466 $groups['add-self'] = User::getAllGroups();
4467 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4468 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4469 }
4470
4471 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4472 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4473 $groups['remove-self'] = User::getAllGroups();
4474 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4475 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4476 }
4477
4478 return $groups;
4479 }
4480
4481 /**
4482 * Returns an array of groups that this user can add and remove
4483 * @return array array( 'add' => array( addablegroups ),
4484 * 'remove' => array( removablegroups ),
4485 * 'add-self' => array( addablegroups to self),
4486 * 'remove-self' => array( removable groups from self) )
4487 */
4488 public function changeableGroups() {
4489 if ( $this->isAllowed( 'userrights' ) ) {
4490 // This group gives the right to modify everything (reverse-
4491 // compatibility with old "userrights lets you change
4492 // everything")
4493 // Using array_merge to make the groups reindexed
4494 $all = array_merge( User::getAllGroups() );
4495 return array(
4496 'add' => $all,
4497 'remove' => $all,
4498 'add-self' => array(),
4499 'remove-self' => array()
4500 );
4501 }
4502
4503 // Okay, it's not so simple, we will have to go through the arrays
4504 $groups = array(
4505 'add' => array(),
4506 'remove' => array(),
4507 'add-self' => array(),
4508 'remove-self' => array()
4509 );
4510 $addergroups = $this->getEffectiveGroups();
4511
4512 foreach ( $addergroups as $addergroup ) {
4513 $groups = array_merge_recursive(
4514 $groups, $this->changeableByGroup( $addergroup )
4515 );
4516 $groups['add'] = array_unique( $groups['add'] );
4517 $groups['remove'] = array_unique( $groups['remove'] );
4518 $groups['add-self'] = array_unique( $groups['add-self'] );
4519 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4520 }
4521 return $groups;
4522 }
4523
4524 /**
4525 * Increment the user's edit-count field.
4526 * Will have no effect for anonymous users.
4527 */
4528 public function incEditCount() {
4529 if ( !$this->isAnon() ) {
4530 $dbw = wfGetDB( DB_MASTER );
4531 $dbw->update(
4532 'user',
4533 array( 'user_editcount=user_editcount+1' ),
4534 array( 'user_id' => $this->getId() ),
4535 __METHOD__
4536 );
4537
4538 // Lazy initialization check...
4539 if ( $dbw->affectedRows() == 0 ) {
4540 // Now here's a goddamn hack...
4541 $dbr = wfGetDB( DB_SLAVE );
4542 if ( $dbr !== $dbw ) {
4543 // If we actually have a slave server, the count is
4544 // at least one behind because the current transaction
4545 // has not been committed and replicated.
4546 $this->initEditCount( 1 );
4547 } else {
4548 // But if DB_SLAVE is selecting the master, then the
4549 // count we just read includes the revision that was
4550 // just added in the working transaction.
4551 $this->initEditCount();
4552 }
4553 }
4554 }
4555 // edit count in user cache too
4556 $this->invalidateCache();
4557 }
4558
4559 /**
4560 * Initialize user_editcount from data out of the revision table
4561 *
4562 * @param int $add Edits to add to the count from the revision table
4563 * @return int Number of edits
4564 */
4565 protected function initEditCount( $add = 0 ) {
4566 // Pull from a slave to be less cruel to servers
4567 // Accuracy isn't the point anyway here
4568 $dbr = wfGetDB( DB_SLAVE );
4569 $count = (int)$dbr->selectField(
4570 'revision',
4571 'COUNT(rev_user)',
4572 array( 'rev_user' => $this->getId() ),
4573 __METHOD__
4574 );
4575 $count = $count + $add;
4576
4577 $dbw = wfGetDB( DB_MASTER );
4578 $dbw->update(
4579 'user',
4580 array( 'user_editcount' => $count ),
4581 array( 'user_id' => $this->getId() ),
4582 __METHOD__
4583 );
4584
4585 return $count;
4586 }
4587
4588 /**
4589 * Get the description of a given right
4590 *
4591 * @param string $right Right to query
4592 * @return string Localized description of the right
4593 */
4594 public static function getRightDescription( $right ) {
4595 $key = "right-$right";
4596 $msg = wfMessage( $key );
4597 return $msg->isBlank() ? $right : $msg->text();
4598 }
4599
4600 /**
4601 * Make an old-style password hash
4602 *
4603 * @param string $password Plain-text password
4604 * @param string $userId User ID
4605 * @return string Password hash
4606 */
4607 public static function oldCrypt( $password, $userId ) {
4608 global $wgPasswordSalt;
4609 if ( $wgPasswordSalt ) {
4610 return md5( $userId . '-' . md5( $password ) );
4611 } else {
4612 return md5( $password );
4613 }
4614 }
4615
4616 /**
4617 * Make a new-style password hash
4618 *
4619 * @param string $password Plain-text password
4620 * @param bool|string $salt Optional salt, may be random or the user ID.
4621 * If unspecified or false, will generate one automatically
4622 * @return string Password hash
4623 */
4624 public static function crypt( $password, $salt = false ) {
4625 global $wgPasswordSalt;
4626
4627 $hash = '';
4628 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4629 return $hash;
4630 }
4631
4632 if ( $wgPasswordSalt ) {
4633 if ( $salt === false ) {
4634 $salt = MWCryptRand::generateHex( 8 );
4635 }
4636 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4637 } else {
4638 return ':A:' . md5( $password );
4639 }
4640 }
4641
4642 /**
4643 * Compare a password hash with a plain-text password. Requires the user
4644 * ID if there's a chance that the hash is an old-style hash.
4645 *
4646 * @param string $hash Password hash
4647 * @param string $password Plain-text password to compare
4648 * @param string|bool $userId User ID for old-style password salt
4649 *
4650 * @return bool
4651 */
4652 public static function comparePasswords( $hash, $password, $userId = false ) {
4653 $type = substr( $hash, 0, 3 );
4654
4655 $result = false;
4656 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4657 return $result;
4658 }
4659
4660 if ( $type == ':A:' ) {
4661 // Unsalted
4662 return md5( $password ) === substr( $hash, 3 );
4663 } elseif ( $type == ':B:' ) {
4664 // Salted
4665 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4666 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4667 } else {
4668 // Old-style
4669 return self::oldCrypt( $password, $userId ) === $hash;
4670 }
4671 }
4672
4673 /**
4674 * Add a newuser log entry for this user.
4675 * Before 1.19 the return value was always true.
4676 *
4677 * @param string|bool $action Account creation type.
4678 * - String, one of the following values:
4679 * - 'create' for an anonymous user creating an account for himself.
4680 * This will force the action's performer to be the created user itself,
4681 * no matter the value of $wgUser
4682 * - 'create2' for a logged in user creating an account for someone else
4683 * - 'byemail' when the created user will receive its password by e-mail
4684 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4685 * - Boolean means whether the account was created by e-mail (deprecated):
4686 * - true will be converted to 'byemail'
4687 * - false will be converted to 'create' if this object is the same as
4688 * $wgUser and to 'create2' otherwise
4689 *
4690 * @param string $reason User supplied reason
4691 *
4692 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4693 */
4694 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4695 global $wgUser, $wgNewUserLog;
4696 if ( empty( $wgNewUserLog ) ) {
4697 return true; // disabled
4698 }
4699
4700 if ( $action === true ) {
4701 $action = 'byemail';
4702 } elseif ( $action === false ) {
4703 if ( $this->getName() == $wgUser->getName() ) {
4704 $action = 'create';
4705 } else {
4706 $action = 'create2';
4707 }
4708 }
4709
4710 if ( $action === 'create' || $action === 'autocreate' ) {
4711 $performer = $this;
4712 } else {
4713 $performer = $wgUser;
4714 }
4715
4716 $logEntry = new ManualLogEntry( 'newusers', $action );
4717 $logEntry->setPerformer( $performer );
4718 $logEntry->setTarget( $this->getUserPage() );
4719 $logEntry->setComment( $reason );
4720 $logEntry->setParameters( array(
4721 '4::userid' => $this->getId(),
4722 ) );
4723 $logid = $logEntry->insert();
4724
4725 if ( $action !== 'autocreate' ) {
4726 $logEntry->publish( $logid );
4727 }
4728
4729 return (int)$logid;
4730 }
4731
4732 /**
4733 * Add an autocreate newuser log entry for this user
4734 * Used by things like CentralAuth and perhaps other authplugins.
4735 * Consider calling addNewUserLogEntry() directly instead.
4736 *
4737 * @return bool
4738 */
4739 public function addNewUserLogEntryAutoCreate() {
4740 $this->addNewUserLogEntry( 'autocreate' );
4741
4742 return true;
4743 }
4744
4745 /**
4746 * Load the user options either from cache, the database or an array
4747 *
4748 * @param array $data Rows for the current user out of the user_properties table
4749 */
4750 protected function loadOptions( $data = null ) {
4751 global $wgContLang;
4752
4753 $this->load();
4754
4755 if ( $this->mOptionsLoaded ) {
4756 return;
4757 }
4758
4759 $this->mOptions = self::getDefaultOptions();
4760
4761 if ( !$this->getId() ) {
4762 // For unlogged-in users, load language/variant options from request.
4763 // There's no need to do it for logged-in users: they can set preferences,
4764 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4765 // so don't override user's choice (especially when the user chooses site default).
4766 $variant = $wgContLang->getDefaultVariant();
4767 $this->mOptions['variant'] = $variant;
4768 $this->mOptions['language'] = $variant;
4769 $this->mOptionsLoaded = true;
4770 return;
4771 }
4772
4773 // Maybe load from the object
4774 if ( !is_null( $this->mOptionOverrides ) ) {
4775 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4776 foreach ( $this->mOptionOverrides as $key => $value ) {
4777 $this->mOptions[$key] = $value;
4778 }
4779 } else {
4780 if ( !is_array( $data ) ) {
4781 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4782 // Load from database
4783 $dbr = wfGetDB( DB_SLAVE );
4784
4785 $res = $dbr->select(
4786 'user_properties',
4787 array( 'up_property', 'up_value' ),
4788 array( 'up_user' => $this->getId() ),
4789 __METHOD__
4790 );
4791
4792 $this->mOptionOverrides = array();
4793 $data = array();
4794 foreach ( $res as $row ) {
4795 $data[$row->up_property] = $row->up_value;
4796 }
4797 }
4798 foreach ( $data as $property => $value ) {
4799 $this->mOptionOverrides[$property] = $value;
4800 $this->mOptions[$property] = $value;
4801 }
4802 }
4803
4804 $this->mOptionsLoaded = true;
4805
4806 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4807 }
4808
4809 /**
4810 * @todo document
4811 */
4812 protected function saveOptions() {
4813 $this->loadOptions();
4814
4815 // Not using getOptions(), to keep hidden preferences in database
4816 $saveOptions = $this->mOptions;
4817
4818 // Allow hooks to abort, for instance to save to a global profile.
4819 // Reset options to default state before saving.
4820 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4821 return;
4822 }
4823
4824 $userId = $this->getId();
4825 $insert_rows = array();
4826 foreach ( $saveOptions as $key => $value ) {
4827 // Don't bother storing default values
4828 $defaultOption = self::getDefaultOption( $key );
4829 if ( ( is_null( $defaultOption ) &&
4830 !( $value === false || is_null( $value ) ) ) ||
4831 $value != $defaultOption
4832 ) {
4833 $insert_rows[] = array(
4834 'up_user' => $userId,
4835 'up_property' => $key,
4836 'up_value' => $value,
4837 );
4838 }
4839 }
4840
4841 $dbw = wfGetDB( DB_MASTER );
4842 // Find and delete any prior preference rows...
4843 $res = $dbw->select( 'user_properties',
4844 array( 'up_property' ), array( 'up_user' => $userId ), __METHOD__ );
4845 $priorKeys = array();
4846 foreach ( $res as $row ) {
4847 $priorKeys[] = $row->up_property;
4848 }
4849 if ( count( $priorKeys ) ) {
4850 // Do the DELETE by PRIMARY KEY for prior rows.
4851 // In the past a very large portion of calls to this function are for setting
4852 // 'rememberpassword' for new accounts (a preference that has since been removed).
4853 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4854 // caused gap locks on [max user ID,+infinity) which caused high contention since
4855 // updates would pile up on each other as they are for higher (newer) user IDs.
4856 // It might not be necessary these days, but it shouldn't hurt either.
4857 $dbw->delete( 'user_properties',
4858 array( 'up_user' => $userId, 'up_property' => $priorKeys ), __METHOD__ );
4859 }
4860 // Insert the new preference rows
4861 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4862 }
4863
4864 /**
4865 * Provide an array of HTML5 attributes to put on an input element
4866 * intended for the user to enter a new password. This may include
4867 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4868 *
4869 * Do *not* use this when asking the user to enter his current password!
4870 * Regardless of configuration, users may have invalid passwords for whatever
4871 * reason (e.g., they were set before requirements were tightened up).
4872 * Only use it when asking for a new password, like on account creation or
4873 * ResetPass.
4874 *
4875 * Obviously, you still need to do server-side checking.
4876 *
4877 * NOTE: A combination of bugs in various browsers means that this function
4878 * actually just returns array() unconditionally at the moment. May as
4879 * well keep it around for when the browser bugs get fixed, though.
4880 *
4881 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4882 *
4883 * @return array Array of HTML attributes suitable for feeding to
4884 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4885 * That will get confused by the boolean attribute syntax used.)
4886 */
4887 public static function passwordChangeInputAttribs() {
4888 global $wgMinimalPasswordLength;
4889
4890 if ( $wgMinimalPasswordLength == 0 ) {
4891 return array();
4892 }
4893
4894 # Note that the pattern requirement will always be satisfied if the
4895 # input is empty, so we need required in all cases.
4896 #
4897 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4898 # if e-mail confirmation is being used. Since HTML5 input validation
4899 # is b0rked anyway in some browsers, just return nothing. When it's
4900 # re-enabled, fix this code to not output required for e-mail
4901 # registration.
4902 #$ret = array( 'required' );
4903 $ret = array();
4904
4905 # We can't actually do this right now, because Opera 9.6 will print out
4906 # the entered password visibly in its error message! When other
4907 # browsers add support for this attribute, or Opera fixes its support,
4908 # we can add support with a version check to avoid doing this on Opera
4909 # versions where it will be a problem. Reported to Opera as
4910 # DSK-262266, but they don't have a public bug tracker for us to follow.
4911 /*
4912 if ( $wgMinimalPasswordLength > 1 ) {
4913 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4914 $ret['title'] = wfMessage( 'passwordtooshort' )
4915 ->numParams( $wgMinimalPasswordLength )->text();
4916 }
4917 */
4918
4919 return $ret;
4920 }
4921
4922 /**
4923 * Return the list of user fields that should be selected to create
4924 * a new user object.
4925 * @return array
4926 */
4927 public static function selectFields() {
4928 return array(
4929 'user_id',
4930 'user_name',
4931 'user_real_name',
4932 'user_password',
4933 'user_newpassword',
4934 'user_newpass_time',
4935 'user_email',
4936 'user_touched',
4937 'user_token',
4938 'user_email_authenticated',
4939 'user_email_token',
4940 'user_email_token_expires',
4941 'user_password_expires',
4942 'user_registration',
4943 'user_editcount',
4944 );
4945 }
4946
4947 /**
4948 * Factory function for fatal permission-denied errors
4949 *
4950 * @since 1.22
4951 * @param string $permission User right required
4952 * @return Status
4953 */
4954 static function newFatalPermissionDeniedStatus( $permission ) {
4955 global $wgLang;
4956
4957 $groups = array_map(
4958 array( 'User', 'makeGroupLinkWiki' ),
4959 User::getGroupsWithPermission( $permission )
4960 );
4961
4962 if ( $groups ) {
4963 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4964 } else {
4965 return Status::newFatal( 'badaccess-group0' );
4966 }
4967 }
4968 }