Merge "PPAccum_Hash -> PPDAccum_Hash"
[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 && $this->compareSecrets( $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 * A comparison of two strings, not vulnerable to timing attacks
1170 * @param string $answer The secret string that you are comparing against.
1171 * @param string $test Compare this string to the $answer.
1172 * @return bool True if the strings are the same, false otherwise
1173 */
1174 protected function compareSecrets( $answer, $test ) {
1175 if ( strlen( $answer ) !== strlen( $test ) ) {
1176 $passwordCorrect = false;
1177 } else {
1178 $result = 0;
1179 $answerLength = strlen( $answer );
1180 for ( $i = 0; $i < $answerLength; $i++ ) {
1181 $result |= ord( $answer[$i] ) ^ ord( $test[$i] );
1182 }
1183 $passwordCorrect = ( $result == 0 );
1184 }
1185
1186 return $passwordCorrect;
1187 }
1188
1189 /**
1190 * Load user and user_group data from the database.
1191 * $this->mId must be set, this is how the user is identified.
1192 *
1193 * @return bool True if the user exists, false if the user is anonymous
1194 */
1195 public function loadFromDatabase() {
1196 // Paranoia
1197 $this->mId = intval( $this->mId );
1198
1199 // Anonymous user
1200 if ( !$this->mId ) {
1201 $this->loadDefaults();
1202 return false;
1203 }
1204
1205 $dbr = wfGetDB( DB_MASTER );
1206 $s = $dbr->selectRow(
1207 'user',
1208 self::selectFields(),
1209 array( 'user_id' => $this->mId ),
1210 __METHOD__
1211 );
1212
1213 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
1214
1215 if ( $s !== false ) {
1216 // Initialise user table data
1217 $this->loadFromRow( $s );
1218 $this->mGroups = null; // deferred
1219 $this->getEditCount(); // revalidation for nulls
1220 return true;
1221 } else {
1222 // Invalid user_id
1223 $this->mId = 0;
1224 $this->loadDefaults();
1225 return false;
1226 }
1227 }
1228
1229 /**
1230 * Initialize this object from a row from the user table.
1231 *
1232 * @param stdClass $row Row from the user table to load.
1233 * @param array $data Further user data to load into the object
1234 *
1235 * user_groups Array with groups out of the user_groups table
1236 * user_properties Array with properties out of the user_properties table
1237 */
1238 public function loadFromRow( $row, $data = null ) {
1239 $all = true;
1240
1241 $this->mGroups = null; // deferred
1242
1243 if ( isset( $row->user_name ) ) {
1244 $this->mName = $row->user_name;
1245 $this->mFrom = 'name';
1246 $this->setItemLoaded( 'name' );
1247 } else {
1248 $all = false;
1249 }
1250
1251 if ( isset( $row->user_real_name ) ) {
1252 $this->mRealName = $row->user_real_name;
1253 $this->setItemLoaded( 'realname' );
1254 } else {
1255 $all = false;
1256 }
1257
1258 if ( isset( $row->user_id ) ) {
1259 $this->mId = intval( $row->user_id );
1260 $this->mFrom = 'id';
1261 $this->setItemLoaded( 'id' );
1262 } else {
1263 $all = false;
1264 }
1265
1266 if ( isset( $row->user_editcount ) ) {
1267 $this->mEditCount = $row->user_editcount;
1268 } else {
1269 $all = false;
1270 }
1271
1272 if ( isset( $row->user_password ) ) {
1273 $this->mPassword = $row->user_password;
1274 $this->mNewpassword = $row->user_newpassword;
1275 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
1276 $this->mEmail = $row->user_email;
1277 if ( isset( $row->user_options ) ) {
1278 $this->decodeOptions( $row->user_options );
1279 }
1280 $this->mTouched = wfTimestamp( TS_MW, $row->user_touched );
1281 $this->mToken = $row->user_token;
1282 if ( $this->mToken == '' ) {
1283 $this->mToken = null;
1284 }
1285 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
1286 $this->mEmailToken = $row->user_email_token;
1287 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1288 $this->mPasswordExpires = wfTimestampOrNull( TS_MW, $row->user_password_expires );
1289 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1290 } else {
1291 $all = false;
1292 }
1293
1294 if ( $all ) {
1295 $this->mLoadedItems = true;
1296 }
1297
1298 if ( is_array( $data ) ) {
1299 if ( isset( $data['user_groups'] ) && is_array( $data['user_groups'] ) ) {
1300 $this->mGroups = $data['user_groups'];
1301 }
1302 if ( isset( $data['user_properties'] ) && is_array( $data['user_properties'] ) ) {
1303 $this->loadOptions( $data['user_properties'] );
1304 }
1305 }
1306 }
1307
1308 /**
1309 * Load the data for this user object from another user object.
1310 *
1311 * @param User $user
1312 */
1313 protected function loadFromUserObject( $user ) {
1314 $user->load();
1315 $user->loadGroups();
1316 $user->loadOptions();
1317 foreach ( self::$mCacheVars as $var ) {
1318 $this->$var = $user->$var;
1319 }
1320 }
1321
1322 /**
1323 * Load the groups from the database if they aren't already loaded.
1324 */
1325 private function loadGroups() {
1326 if ( is_null( $this->mGroups ) ) {
1327 $dbr = wfGetDB( DB_MASTER );
1328 $res = $dbr->select( 'user_groups',
1329 array( 'ug_group' ),
1330 array( 'ug_user' => $this->mId ),
1331 __METHOD__ );
1332 $this->mGroups = array();
1333 foreach ( $res as $row ) {
1334 $this->mGroups[] = $row->ug_group;
1335 }
1336 }
1337 }
1338
1339 /**
1340 * Add the user to the group if he/she meets given criteria.
1341 *
1342 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1343 * possible to remove manually via Special:UserRights. In such case it
1344 * will not be re-added automatically. The user will also not lose the
1345 * group if they no longer meet the criteria.
1346 *
1347 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1348 *
1349 * @return array Array of groups the user has been promoted to.
1350 *
1351 * @see $wgAutopromoteOnce
1352 */
1353 public function addAutopromoteOnceGroups( $event ) {
1354 global $wgAutopromoteOnceLogInRC, $wgAuth;
1355
1356 $toPromote = array();
1357 if ( $this->getId() ) {
1358 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1359 if ( count( $toPromote ) ) {
1360 $oldGroups = $this->getGroups(); // previous groups
1361
1362 foreach ( $toPromote as $group ) {
1363 $this->addGroup( $group );
1364 }
1365 // update groups in external authentication database
1366 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1367
1368 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1369
1370 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1371 $logEntry->setPerformer( $this );
1372 $logEntry->setTarget( $this->getUserPage() );
1373 $logEntry->setParameters( array(
1374 '4::oldgroups' => $oldGroups,
1375 '5::newgroups' => $newGroups,
1376 ) );
1377 $logid = $logEntry->insert();
1378 if ( $wgAutopromoteOnceLogInRC ) {
1379 $logEntry->publish( $logid );
1380 }
1381 }
1382 }
1383 return $toPromote;
1384 }
1385
1386 /**
1387 * Clear various cached data stored in this object. The cache of the user table
1388 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1389 *
1390 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1391 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1392 */
1393 public function clearInstanceCache( $reloadFrom = false ) {
1394 $this->mNewtalk = -1;
1395 $this->mDatePreference = null;
1396 $this->mBlockedby = -1; # Unset
1397 $this->mHash = false;
1398 $this->mRights = null;
1399 $this->mEffectiveGroups = null;
1400 $this->mImplicitGroups = null;
1401 $this->mGroups = null;
1402 $this->mOptions = null;
1403 $this->mOptionsLoaded = false;
1404 $this->mEditCount = null;
1405
1406 if ( $reloadFrom ) {
1407 $this->mLoadedItems = array();
1408 $this->mFrom = $reloadFrom;
1409 }
1410 }
1411
1412 /**
1413 * Combine the language default options with any site-specific options
1414 * and add the default language variants.
1415 *
1416 * @return array Array of String options
1417 */
1418 public static function getDefaultOptions() {
1419 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1420
1421 static $defOpt = null;
1422 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1423 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1424 // mid-request and see that change reflected in the return value of this function.
1425 // Which is insane and would never happen during normal MW operation
1426 return $defOpt;
1427 }
1428
1429 $defOpt = $wgDefaultUserOptions;
1430 // Default language setting
1431 $defOpt['language'] = $wgContLang->getCode();
1432 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1433 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1434 }
1435 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1436 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1437 }
1438 $defOpt['skin'] = $wgDefaultSkin;
1439
1440 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1441
1442 return $defOpt;
1443 }
1444
1445 /**
1446 * Get a given default option value.
1447 *
1448 * @param string $opt Name of option to retrieve
1449 * @return string Default option value
1450 */
1451 public static function getDefaultOption( $opt ) {
1452 $defOpts = self::getDefaultOptions();
1453 if ( isset( $defOpts[$opt] ) ) {
1454 return $defOpts[$opt];
1455 } else {
1456 return null;
1457 }
1458 }
1459
1460 /**
1461 * Get blocking information
1462 * @param bool $bFromSlave Whether to check the slave database first.
1463 * To improve performance, non-critical checks are done against slaves.
1464 * Check when actually saving should be done against master.
1465 */
1466 private function getBlockedStatus( $bFromSlave = true ) {
1467 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1468
1469 if ( -1 != $this->mBlockedby ) {
1470 return;
1471 }
1472
1473 wfProfileIn( __METHOD__ );
1474 wfDebug( __METHOD__ . ": checking...\n" );
1475
1476 // Initialize data...
1477 // Otherwise something ends up stomping on $this->mBlockedby when
1478 // things get lazy-loaded later, causing false positive block hits
1479 // due to -1 !== 0. Probably session-related... Nothing should be
1480 // overwriting mBlockedby, surely?
1481 $this->load();
1482
1483 # We only need to worry about passing the IP address to the Block generator if the
1484 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1485 # know which IP address they're actually coming from
1486 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1487 $ip = $this->getRequest()->getIP();
1488 } else {
1489 $ip = null;
1490 }
1491
1492 // User/IP blocking
1493 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1494
1495 // Proxy blocking
1496 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1497 && !in_array( $ip, $wgProxyWhitelist )
1498 ) {
1499 // Local list
1500 if ( self::isLocallyBlockedProxy( $ip ) ) {
1501 $block = new Block;
1502 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1503 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1504 $block->setTarget( $ip );
1505 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1506 $block = new Block;
1507 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1508 $block->mReason = wfMessage( 'sorbsreason' )->text();
1509 $block->setTarget( $ip );
1510 }
1511 }
1512
1513 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1514 if ( !$block instanceof Block
1515 && $wgApplyIpBlocksToXff
1516 && $ip !== null
1517 && !$this->isAllowed( 'proxyunbannable' )
1518 && !in_array( $ip, $wgProxyWhitelist )
1519 ) {
1520 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1521 $xff = array_map( 'trim', explode( ',', $xff ) );
1522 $xff = array_diff( $xff, array( $ip ) );
1523 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1524 $block = Block::chooseBlock( $xffblocks, $xff );
1525 if ( $block instanceof Block ) {
1526 # Mangle the reason to alert the user that the block
1527 # originated from matching the X-Forwarded-For header.
1528 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1529 }
1530 }
1531
1532 if ( $block instanceof Block ) {
1533 wfDebug( __METHOD__ . ": Found block.\n" );
1534 $this->mBlock = $block;
1535 $this->mBlockedby = $block->getByName();
1536 $this->mBlockreason = $block->mReason;
1537 $this->mHideName = $block->mHideName;
1538 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1539 } else {
1540 $this->mBlockedby = '';
1541 $this->mHideName = 0;
1542 $this->mAllowUsertalk = false;
1543 }
1544
1545 // Extensions
1546 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1547
1548 wfProfileOut( __METHOD__ );
1549 }
1550
1551 /**
1552 * Whether the given IP is in a DNS blacklist.
1553 *
1554 * @param string $ip IP to check
1555 * @param bool $checkWhitelist Whether to check the whitelist first
1556 * @return bool True if blacklisted.
1557 */
1558 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1559 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1560 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1561
1562 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1563 return false;
1564 }
1565
1566 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1567 return false;
1568 }
1569
1570 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1571 return $this->inDnsBlacklist( $ip, $urls );
1572 }
1573
1574 /**
1575 * Whether the given IP is in a given DNS blacklist.
1576 *
1577 * @param string $ip IP to check
1578 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1579 * @return bool True if blacklisted.
1580 */
1581 public function inDnsBlacklist( $ip, $bases ) {
1582 wfProfileIn( __METHOD__ );
1583
1584 $found = false;
1585 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1586 if ( IP::isIPv4( $ip ) ) {
1587 // Reverse IP, bug 21255
1588 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1589
1590 foreach ( (array)$bases as $base ) {
1591 // Make hostname
1592 // If we have an access key, use that too (ProjectHoneypot, etc.)
1593 if ( is_array( $base ) ) {
1594 if ( count( $base ) >= 2 ) {
1595 // Access key is 1, base URL is 0
1596 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1597 } else {
1598 $host = "$ipReversed.{$base[0]}";
1599 }
1600 } else {
1601 $host = "$ipReversed.$base";
1602 }
1603
1604 // Send query
1605 $ipList = gethostbynamel( $host );
1606
1607 if ( $ipList ) {
1608 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1609 $found = true;
1610 break;
1611 } else {
1612 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1613 }
1614 }
1615 }
1616
1617 wfProfileOut( __METHOD__ );
1618 return $found;
1619 }
1620
1621 /**
1622 * Check if an IP address is in the local proxy list
1623 *
1624 * @param string $ip
1625 *
1626 * @return bool
1627 */
1628 public static function isLocallyBlockedProxy( $ip ) {
1629 global $wgProxyList;
1630
1631 if ( !$wgProxyList ) {
1632 return false;
1633 }
1634 wfProfileIn( __METHOD__ );
1635
1636 if ( !is_array( $wgProxyList ) ) {
1637 // Load from the specified file
1638 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1639 }
1640
1641 if ( !is_array( $wgProxyList ) ) {
1642 $ret = false;
1643 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1644 $ret = true;
1645 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1646 // Old-style flipped proxy list
1647 $ret = true;
1648 } else {
1649 $ret = false;
1650 }
1651 wfProfileOut( __METHOD__ );
1652 return $ret;
1653 }
1654
1655 /**
1656 * Is this user subject to rate limiting?
1657 *
1658 * @return bool True if rate limited
1659 */
1660 public function isPingLimitable() {
1661 global $wgRateLimitsExcludedIPs;
1662 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1663 // No other good way currently to disable rate limits
1664 // for specific IPs. :P
1665 // But this is a crappy hack and should die.
1666 return false;
1667 }
1668 return !$this->isAllowed( 'noratelimit' );
1669 }
1670
1671 /**
1672 * Primitive rate limits: enforce maximum actions per time period
1673 * to put a brake on flooding.
1674 *
1675 * @note When using a shared cache like memcached, IP-address
1676 * last-hit counters will be shared across wikis.
1677 *
1678 * @param string $action Action to enforce; 'edit' if unspecified
1679 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1680 * @return bool True if a rate limiter was tripped
1681 */
1682 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1683 // Call the 'PingLimiter' hook
1684 $result = false;
1685 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1686 return $result;
1687 }
1688
1689 global $wgRateLimits;
1690 if ( !isset( $wgRateLimits[$action] ) ) {
1691 return false;
1692 }
1693
1694 // Some groups shouldn't trigger the ping limiter, ever
1695 if ( !$this->isPingLimitable() ) {
1696 return false;
1697 }
1698
1699 global $wgMemc;
1700 wfProfileIn( __METHOD__ );
1701
1702 $limits = $wgRateLimits[$action];
1703 $keys = array();
1704 $id = $this->getId();
1705 $userLimit = false;
1706
1707 if ( isset( $limits['anon'] ) && $id == 0 ) {
1708 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1709 }
1710
1711 if ( isset( $limits['user'] ) && $id != 0 ) {
1712 $userLimit = $limits['user'];
1713 }
1714 if ( $this->isNewbie() ) {
1715 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1716 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1717 }
1718 if ( isset( $limits['ip'] ) ) {
1719 $ip = $this->getRequest()->getIP();
1720 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1721 }
1722 if ( isset( $limits['subnet'] ) ) {
1723 $ip = $this->getRequest()->getIP();
1724 $matches = array();
1725 $subnet = false;
1726 if ( IP::isIPv6( $ip ) ) {
1727 $parts = IP::parseRange( "$ip/64" );
1728 $subnet = $parts[0];
1729 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1730 // IPv4
1731 $subnet = $matches[1];
1732 }
1733 if ( $subnet !== false ) {
1734 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1735 }
1736 }
1737 }
1738 // Check for group-specific permissions
1739 // If more than one group applies, use the group with the highest limit
1740 foreach ( $this->getGroups() as $group ) {
1741 if ( isset( $limits[$group] ) ) {
1742 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1743 $userLimit = $limits[$group];
1744 }
1745 }
1746 }
1747 // Set the user limit key
1748 if ( $userLimit !== false ) {
1749 list( $max, $period ) = $userLimit;
1750 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1751 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1752 }
1753
1754 $triggered = false;
1755 foreach ( $keys as $key => $limit ) {
1756 list( $max, $period ) = $limit;
1757 $summary = "(limit $max in {$period}s)";
1758 $count = $wgMemc->get( $key );
1759 // Already pinged?
1760 if ( $count ) {
1761 if ( $count >= $max ) {
1762 wfDebugLog( 'ratelimit', $this->getName() . " tripped! $key at $count $summary" );
1763 $triggered = true;
1764 } else {
1765 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1766 }
1767 } else {
1768 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1769 if ( $incrBy > 0 ) {
1770 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1771 }
1772 }
1773 if ( $incrBy > 0 ) {
1774 $wgMemc->incr( $key, $incrBy );
1775 }
1776 }
1777
1778 wfProfileOut( __METHOD__ );
1779 return $triggered;
1780 }
1781
1782 /**
1783 * Check if user is blocked
1784 *
1785 * @param bool $bFromSlave Whether to check the slave database instead of
1786 * the master. Hacked from false due to horrible probs on site.
1787 * @return bool True if blocked, false otherwise
1788 */
1789 public function isBlocked( $bFromSlave = true ) {
1790 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1791 }
1792
1793 /**
1794 * Get the block affecting the user, or null if the user is not blocked
1795 *
1796 * @param bool $bFromSlave Whether to check the slave database instead of the master
1797 * @return Block|null
1798 */
1799 public function getBlock( $bFromSlave = true ) {
1800 $this->getBlockedStatus( $bFromSlave );
1801 return $this->mBlock instanceof Block ? $this->mBlock : null;
1802 }
1803
1804 /**
1805 * Check if user is blocked from editing a particular article
1806 *
1807 * @param Title $title Title to check
1808 * @param bool $bFromSlave Whether to check the slave database instead of the master
1809 * @return bool
1810 */
1811 public function isBlockedFrom( $title, $bFromSlave = false ) {
1812 global $wgBlockAllowsUTEdit;
1813 wfProfileIn( __METHOD__ );
1814
1815 $blocked = $this->isBlocked( $bFromSlave );
1816 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1817 // If a user's name is suppressed, they cannot make edits anywhere
1818 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1819 && $title->getNamespace() == NS_USER_TALK ) {
1820 $blocked = false;
1821 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1822 }
1823
1824 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1825
1826 wfProfileOut( __METHOD__ );
1827 return $blocked;
1828 }
1829
1830 /**
1831 * If user is blocked, return the name of the user who placed the block
1832 * @return string Name of blocker
1833 */
1834 public function blockedBy() {
1835 $this->getBlockedStatus();
1836 return $this->mBlockedby;
1837 }
1838
1839 /**
1840 * If user is blocked, return the specified reason for the block
1841 * @return string Blocking reason
1842 */
1843 public function blockedFor() {
1844 $this->getBlockedStatus();
1845 return $this->mBlockreason;
1846 }
1847
1848 /**
1849 * If user is blocked, return the ID for the block
1850 * @return int Block ID
1851 */
1852 public function getBlockId() {
1853 $this->getBlockedStatus();
1854 return ( $this->mBlock ? $this->mBlock->getId() : false );
1855 }
1856
1857 /**
1858 * Check if user is blocked on all wikis.
1859 * Do not use for actual edit permission checks!
1860 * This is intended for quick UI checks.
1861 *
1862 * @param string $ip IP address, uses current client if none given
1863 * @return bool True if blocked, false otherwise
1864 */
1865 public function isBlockedGlobally( $ip = '' ) {
1866 if ( $this->mBlockedGlobally !== null ) {
1867 return $this->mBlockedGlobally;
1868 }
1869 // User is already an IP?
1870 if ( IP::isIPAddress( $this->getName() ) ) {
1871 $ip = $this->getName();
1872 } elseif ( !$ip ) {
1873 $ip = $this->getRequest()->getIP();
1874 }
1875 $blocked = false;
1876 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1877 $this->mBlockedGlobally = (bool)$blocked;
1878 return $this->mBlockedGlobally;
1879 }
1880
1881 /**
1882 * Check if user account is locked
1883 *
1884 * @return bool True if locked, false otherwise
1885 */
1886 public function isLocked() {
1887 if ( $this->mLocked !== null ) {
1888 return $this->mLocked;
1889 }
1890 global $wgAuth;
1891 StubObject::unstub( $wgAuth );
1892 $authUser = $wgAuth->getUserInstance( $this );
1893 $this->mLocked = (bool)$authUser->isLocked();
1894 return $this->mLocked;
1895 }
1896
1897 /**
1898 * Check if user account is hidden
1899 *
1900 * @return bool True if hidden, false otherwise
1901 */
1902 public function isHidden() {
1903 if ( $this->mHideName !== null ) {
1904 return $this->mHideName;
1905 }
1906 $this->getBlockedStatus();
1907 if ( !$this->mHideName ) {
1908 global $wgAuth;
1909 StubObject::unstub( $wgAuth );
1910 $authUser = $wgAuth->getUserInstance( $this );
1911 $this->mHideName = (bool)$authUser->isHidden();
1912 }
1913 return $this->mHideName;
1914 }
1915
1916 /**
1917 * Get the user's ID.
1918 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1919 */
1920 public function getId() {
1921 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1922 // Special case, we know the user is anonymous
1923 return 0;
1924 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1925 // Don't load if this was initialized from an ID
1926 $this->load();
1927 }
1928 return $this->mId;
1929 }
1930
1931 /**
1932 * Set the user and reload all fields according to a given ID
1933 * @param int $v User ID to reload
1934 */
1935 public function setId( $v ) {
1936 $this->mId = $v;
1937 $this->clearInstanceCache( 'id' );
1938 }
1939
1940 /**
1941 * Get the user name, or the IP of an anonymous user
1942 * @return string User's name or IP address
1943 */
1944 public function getName() {
1945 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1946 // Special case optimisation
1947 return $this->mName;
1948 } else {
1949 $this->load();
1950 if ( $this->mName === false ) {
1951 // Clean up IPs
1952 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1953 }
1954 return $this->mName;
1955 }
1956 }
1957
1958 /**
1959 * Set the user name.
1960 *
1961 * This does not reload fields from the database according to the given
1962 * name. Rather, it is used to create a temporary "nonexistent user" for
1963 * later addition to the database. It can also be used to set the IP
1964 * address for an anonymous user to something other than the current
1965 * remote IP.
1966 *
1967 * @note User::newFromName() has roughly the same function, when the named user
1968 * does not exist.
1969 * @param string $str New user name to set
1970 */
1971 public function setName( $str ) {
1972 $this->load();
1973 $this->mName = $str;
1974 }
1975
1976 /**
1977 * Get the user's name escaped by underscores.
1978 * @return string Username escaped by underscores.
1979 */
1980 public function getTitleKey() {
1981 return str_replace( ' ', '_', $this->getName() );
1982 }
1983
1984 /**
1985 * Check if the user has new messages.
1986 * @return bool True if the user has new messages
1987 */
1988 public function getNewtalk() {
1989 $this->load();
1990
1991 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1992 if ( $this->mNewtalk === -1 ) {
1993 $this->mNewtalk = false; # reset talk page status
1994
1995 // Check memcached separately for anons, who have no
1996 // entire User object stored in there.
1997 if ( !$this->mId ) {
1998 global $wgDisableAnonTalk;
1999 if ( $wgDisableAnonTalk ) {
2000 // Anon newtalk disabled by configuration.
2001 $this->mNewtalk = false;
2002 } else {
2003 global $wgMemc;
2004 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
2005 $newtalk = $wgMemc->get( $key );
2006 if ( strval( $newtalk ) !== '' ) {
2007 $this->mNewtalk = (bool)$newtalk;
2008 } else {
2009 // Since we are caching this, make sure it is up to date by getting it
2010 // from the master
2011 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
2012 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
2013 }
2014 }
2015 } else {
2016 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2017 }
2018 }
2019
2020 return (bool)$this->mNewtalk;
2021 }
2022
2023 /**
2024 * Return the data needed to construct links for new talk page message
2025 * alerts. If there are new messages, this will return an associative array
2026 * with the following data:
2027 * wiki: The database name of the wiki
2028 * link: Root-relative link to the user's talk page
2029 * rev: The last talk page revision that the user has seen or null. This
2030 * is useful for building diff links.
2031 * If there are no new messages, it returns an empty array.
2032 * @note This function was designed to accomodate multiple talk pages, but
2033 * currently only returns a single link and revision.
2034 * @return array
2035 */
2036 public function getNewMessageLinks() {
2037 $talks = array();
2038 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2039 return $talks;
2040 } elseif ( !$this->getNewtalk() ) {
2041 return array();
2042 }
2043 $utp = $this->getTalkPage();
2044 $dbr = wfGetDB( DB_SLAVE );
2045 // Get the "last viewed rev" timestamp from the oldest message notification
2046 $timestamp = $dbr->selectField( 'user_newtalk',
2047 'MIN(user_last_timestamp)',
2048 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2049 __METHOD__ );
2050 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2051 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2052 }
2053
2054 /**
2055 * Get the revision ID for the last talk page revision viewed by the talk
2056 * page owner.
2057 * @return int|null Revision ID or null
2058 */
2059 public function getNewMessageRevisionId() {
2060 $newMessageRevisionId = null;
2061 $newMessageLinks = $this->getNewMessageLinks();
2062 if ( $newMessageLinks ) {
2063 // Note: getNewMessageLinks() never returns more than a single link
2064 // and it is always for the same wiki, but we double-check here in
2065 // case that changes some time in the future.
2066 if ( count( $newMessageLinks ) === 1
2067 && $newMessageLinks[0]['wiki'] === wfWikiID()
2068 && $newMessageLinks[0]['rev']
2069 ) {
2070 $newMessageRevision = $newMessageLinks[0]['rev'];
2071 $newMessageRevisionId = $newMessageRevision->getId();
2072 }
2073 }
2074 return $newMessageRevisionId;
2075 }
2076
2077 /**
2078 * Internal uncached check for new messages
2079 *
2080 * @see getNewtalk()
2081 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2082 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2083 * @param bool $fromMaster true to fetch from the master, false for a slave
2084 * @return bool True if the user has new messages
2085 */
2086 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
2087 if ( $fromMaster ) {
2088 $db = wfGetDB( DB_MASTER );
2089 } else {
2090 $db = wfGetDB( DB_SLAVE );
2091 }
2092 $ok = $db->selectField( 'user_newtalk', $field,
2093 array( $field => $id ), __METHOD__ );
2094 return $ok !== false;
2095 }
2096
2097 /**
2098 * Add or update the new messages flag
2099 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2100 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2101 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2102 * @return bool True if successful, false otherwise
2103 */
2104 protected function updateNewtalk( $field, $id, $curRev = null ) {
2105 // Get timestamp of the talk page revision prior to the current one
2106 $prevRev = $curRev ? $curRev->getPrevious() : false;
2107 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2108 // Mark the user as having new messages since this revision
2109 $dbw = wfGetDB( DB_MASTER );
2110 $dbw->insert( 'user_newtalk',
2111 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2112 __METHOD__,
2113 'IGNORE' );
2114 if ( $dbw->affectedRows() ) {
2115 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2116 return true;
2117 } else {
2118 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2119 return false;
2120 }
2121 }
2122
2123 /**
2124 * Clear the new messages flag for the given user
2125 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2126 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2127 * @return bool True if successful, false otherwise
2128 */
2129 protected function deleteNewtalk( $field, $id ) {
2130 $dbw = wfGetDB( DB_MASTER );
2131 $dbw->delete( 'user_newtalk',
2132 array( $field => $id ),
2133 __METHOD__ );
2134 if ( $dbw->affectedRows() ) {
2135 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2136 return true;
2137 } else {
2138 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2139 return false;
2140 }
2141 }
2142
2143 /**
2144 * Update the 'You have new messages!' status.
2145 * @param bool $val Whether the user has new messages
2146 * @param Revision $curRev New, as yet unseen revision of the user talk
2147 * page. Ignored if null or !$val.
2148 */
2149 public function setNewtalk( $val, $curRev = null ) {
2150 if ( wfReadOnly() ) {
2151 return;
2152 }
2153
2154 $this->load();
2155 $this->mNewtalk = $val;
2156
2157 if ( $this->isAnon() ) {
2158 $field = 'user_ip';
2159 $id = $this->getName();
2160 } else {
2161 $field = 'user_id';
2162 $id = $this->getId();
2163 }
2164 global $wgMemc;
2165
2166 if ( $val ) {
2167 $changed = $this->updateNewtalk( $field, $id, $curRev );
2168 } else {
2169 $changed = $this->deleteNewtalk( $field, $id );
2170 }
2171
2172 if ( $this->isAnon() ) {
2173 // Anons have a separate memcached space, since
2174 // user records aren't kept for them.
2175 $key = wfMemcKey( 'newtalk', 'ip', $id );
2176 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
2177 }
2178 if ( $changed ) {
2179 $this->invalidateCache();
2180 }
2181 }
2182
2183 /**
2184 * Generate a current or new-future timestamp to be stored in the
2185 * user_touched field when we update things.
2186 * @return string Timestamp in TS_MW format
2187 */
2188 private static function newTouchedTimestamp() {
2189 global $wgClockSkewFudge;
2190 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2191 }
2192
2193 /**
2194 * Clear user data from memcached.
2195 * Use after applying fun updates to the database; caller's
2196 * responsibility to update user_touched if appropriate.
2197 *
2198 * Called implicitly from invalidateCache() and saveSettings().
2199 */
2200 private function clearSharedCache() {
2201 $this->load();
2202 if ( $this->mId ) {
2203 global $wgMemc;
2204 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2205 }
2206 }
2207
2208 /**
2209 * Immediately touch the user data cache for this account.
2210 * Updates user_touched field, and removes account data from memcached
2211 * for reload on the next hit.
2212 */
2213 public function invalidateCache() {
2214 if ( wfReadOnly() ) {
2215 return;
2216 }
2217 $this->load();
2218 if ( $this->mId ) {
2219 $this->mTouched = self::newTouchedTimestamp();
2220
2221 $dbw = wfGetDB( DB_MASTER );
2222 $userid = $this->mId;
2223 $touched = $this->mTouched;
2224 $method = __METHOD__;
2225 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2226 // Prevent contention slams by checking user_touched first
2227 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2228 $needsPurge = $dbw->selectField( 'user', '1',
2229 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2230 if ( $needsPurge ) {
2231 $dbw->update( 'user',
2232 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2233 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2234 $method
2235 );
2236 }
2237 } );
2238 $this->clearSharedCache();
2239 }
2240 }
2241
2242 /**
2243 * Validate the cache for this account.
2244 * @param string $timestamp A timestamp in TS_MW format
2245 * @return bool
2246 */
2247 public function validateCache( $timestamp ) {
2248 $this->load();
2249 return ( $timestamp >= $this->mTouched );
2250 }
2251
2252 /**
2253 * Get the user touched timestamp
2254 * @return string Timestamp
2255 */
2256 public function getTouched() {
2257 $this->load();
2258 return $this->mTouched;
2259 }
2260
2261 /**
2262 * Set the password and reset the random token.
2263 * Calls through to authentication plugin if necessary;
2264 * will have no effect if the auth plugin refuses to
2265 * pass the change through or if the legal password
2266 * checks fail.
2267 *
2268 * As a special case, setting the password to null
2269 * wipes it, so the account cannot be logged in until
2270 * a new password is set, for instance via e-mail.
2271 *
2272 * @param string $str New password to set
2273 * @throws PasswordError on failure
2274 *
2275 * @return bool
2276 */
2277 public function setPassword( $str ) {
2278 global $wgAuth;
2279
2280 if ( $str !== null ) {
2281 if ( !$wgAuth->allowPasswordChange() ) {
2282 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2283 }
2284
2285 if ( !$this->isValidPassword( $str ) ) {
2286 global $wgMinimalPasswordLength;
2287 $valid = $this->getPasswordValidity( $str );
2288 if ( is_array( $valid ) ) {
2289 $message = array_shift( $valid );
2290 $params = $valid;
2291 } else {
2292 $message = $valid;
2293 $params = array( $wgMinimalPasswordLength );
2294 }
2295 throw new PasswordError( wfMessage( $message, $params )->text() );
2296 }
2297 }
2298
2299 if ( !$wgAuth->setPassword( $this, $str ) ) {
2300 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2301 }
2302
2303 $this->setInternalPassword( $str );
2304
2305 return true;
2306 }
2307
2308 /**
2309 * Set the password and reset the random token unconditionally.
2310 *
2311 * @param string|null $str New password to set or null to set an invalid
2312 * password hash meaning that the user will not be able to log in
2313 * through the web interface.
2314 */
2315 public function setInternalPassword( $str ) {
2316 $this->load();
2317 $this->setToken();
2318
2319 if ( $str === null ) {
2320 // Save an invalid hash...
2321 $this->mPassword = '';
2322 } else {
2323 $this->mPassword = self::crypt( $str );
2324 }
2325 $this->mNewpassword = '';
2326 $this->mNewpassTime = null;
2327 }
2328
2329 /**
2330 * Get the user's current token.
2331 * @param bool $forceCreation Force the generation of a new token if the
2332 * user doesn't have one (default=true for backwards compatibility).
2333 * @return string Token
2334 */
2335 public function getToken( $forceCreation = true ) {
2336 $this->load();
2337 if ( !$this->mToken && $forceCreation ) {
2338 $this->setToken();
2339 }
2340 return $this->mToken;
2341 }
2342
2343 /**
2344 * Set the random token (used for persistent authentication)
2345 * Called from loadDefaults() among other places.
2346 *
2347 * @param string|bool $token If specified, set the token to this value
2348 */
2349 public function setToken( $token = false ) {
2350 $this->load();
2351 if ( !$token ) {
2352 $this->mToken = MWCryptRand::generateHex( USER_TOKEN_LENGTH );
2353 } else {
2354 $this->mToken = $token;
2355 }
2356 }
2357
2358 /**
2359 * Set the password for a password reminder or new account email
2360 *
2361 * @param string $str New password to set or null to set an invalid
2362 * password hash meaning that the user will not be able to use it
2363 * @param bool $throttle If true, reset the throttle timestamp to the present
2364 */
2365 public function setNewpassword( $str, $throttle = true ) {
2366 $this->load();
2367
2368 if ( $str === null ) {
2369 $this->mNewpassword = '';
2370 $this->mNewpassTime = null;
2371 } else {
2372 $this->mNewpassword = self::crypt( $str );
2373 if ( $throttle ) {
2374 $this->mNewpassTime = wfTimestampNow();
2375 }
2376 }
2377 }
2378
2379 /**
2380 * Has password reminder email been sent within the last
2381 * $wgPasswordReminderResendTime hours?
2382 * @return bool
2383 */
2384 public function isPasswordReminderThrottled() {
2385 global $wgPasswordReminderResendTime;
2386 $this->load();
2387 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2388 return false;
2389 }
2390 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2391 return time() < $expiry;
2392 }
2393
2394 /**
2395 * Get the user's e-mail address
2396 * @return string User's email address
2397 */
2398 public function getEmail() {
2399 $this->load();
2400 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2401 return $this->mEmail;
2402 }
2403
2404 /**
2405 * Get the timestamp of the user's e-mail authentication
2406 * @return string TS_MW timestamp
2407 */
2408 public function getEmailAuthenticationTimestamp() {
2409 $this->load();
2410 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2411 return $this->mEmailAuthenticated;
2412 }
2413
2414 /**
2415 * Set the user's e-mail address
2416 * @param string $str New e-mail address
2417 */
2418 public function setEmail( $str ) {
2419 $this->load();
2420 if ( $str == $this->mEmail ) {
2421 return;
2422 }
2423 $this->mEmail = $str;
2424 $this->invalidateEmail();
2425 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2426 }
2427
2428 /**
2429 * Set the user's e-mail address and a confirmation mail if needed.
2430 *
2431 * @since 1.20
2432 * @param string $str New e-mail address
2433 * @return Status
2434 */
2435 public function setEmailWithConfirmation( $str ) {
2436 global $wgEnableEmail, $wgEmailAuthentication;
2437
2438 if ( !$wgEnableEmail ) {
2439 return Status::newFatal( 'emaildisabled' );
2440 }
2441
2442 $oldaddr = $this->getEmail();
2443 if ( $str === $oldaddr ) {
2444 return Status::newGood( true );
2445 }
2446
2447 $this->setEmail( $str );
2448
2449 if ( $str !== '' && $wgEmailAuthentication ) {
2450 // Send a confirmation request to the new address if needed
2451 $type = $oldaddr != '' ? 'changed' : 'set';
2452 $result = $this->sendConfirmationMail( $type );
2453 if ( $result->isGood() ) {
2454 // Say the the caller that a confirmation mail has been sent
2455 $result->value = 'eauth';
2456 }
2457 } else {
2458 $result = Status::newGood( true );
2459 }
2460
2461 return $result;
2462 }
2463
2464 /**
2465 * Get the user's real name
2466 * @return string User's real name
2467 */
2468 public function getRealName() {
2469 if ( !$this->isItemLoaded( 'realname' ) ) {
2470 $this->load();
2471 }
2472
2473 return $this->mRealName;
2474 }
2475
2476 /**
2477 * Set the user's real name
2478 * @param string $str New real name
2479 */
2480 public function setRealName( $str ) {
2481 $this->load();
2482 $this->mRealName = $str;
2483 }
2484
2485 /**
2486 * Get the user's current setting for a given option.
2487 *
2488 * @param string $oname The option to check
2489 * @param string $defaultOverride A default value returned if the option does not exist
2490 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2491 * @return string User's current value for the option
2492 * @see getBoolOption()
2493 * @see getIntOption()
2494 */
2495 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2496 global $wgHiddenPrefs;
2497 $this->loadOptions();
2498
2499 # We want 'disabled' preferences to always behave as the default value for
2500 # users, even if they have set the option explicitly in their settings (ie they
2501 # set it, and then it was disabled removing their ability to change it). But
2502 # we don't want to erase the preferences in the database in case the preference
2503 # is re-enabled again. So don't touch $mOptions, just override the returned value
2504 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2505 return self::getDefaultOption( $oname );
2506 }
2507
2508 if ( array_key_exists( $oname, $this->mOptions ) ) {
2509 return $this->mOptions[$oname];
2510 } else {
2511 return $defaultOverride;
2512 }
2513 }
2514
2515 /**
2516 * Get all user's options
2517 *
2518 * @return array
2519 */
2520 public function getOptions() {
2521 global $wgHiddenPrefs;
2522 $this->loadOptions();
2523 $options = $this->mOptions;
2524
2525 # We want 'disabled' preferences to always behave as the default value for
2526 # users, even if they have set the option explicitly in their settings (ie they
2527 # set it, and then it was disabled removing their ability to change it). But
2528 # we don't want to erase the preferences in the database in case the preference
2529 # is re-enabled again. So don't touch $mOptions, just override the returned value
2530 foreach ( $wgHiddenPrefs as $pref ) {
2531 $default = self::getDefaultOption( $pref );
2532 if ( $default !== null ) {
2533 $options[$pref] = $default;
2534 }
2535 }
2536
2537 return $options;
2538 }
2539
2540 /**
2541 * Get the user's current setting for a given option, as a boolean value.
2542 *
2543 * @param string $oname The option to check
2544 * @return bool User's current value for the option
2545 * @see getOption()
2546 */
2547 public function getBoolOption( $oname ) {
2548 return (bool)$this->getOption( $oname );
2549 }
2550
2551 /**
2552 * Get the user's current setting for a given option, as an integer value.
2553 *
2554 * @param string $oname The option to check
2555 * @param int $defaultOverride A default value returned if the option does not exist
2556 * @return int User's current value for the option
2557 * @see getOption()
2558 */
2559 public function getIntOption( $oname, $defaultOverride = 0 ) {
2560 $val = $this->getOption( $oname );
2561 if ( $val == '' ) {
2562 $val = $defaultOverride;
2563 }
2564 return intval( $val );
2565 }
2566
2567 /**
2568 * Set the given option for a user.
2569 *
2570 * @param string $oname The option to set
2571 * @param mixed $val New value to set
2572 */
2573 public function setOption( $oname, $val ) {
2574 $this->loadOptions();
2575
2576 // Explicitly NULL values should refer to defaults
2577 if ( is_null( $val ) ) {
2578 $val = self::getDefaultOption( $oname );
2579 }
2580
2581 $this->mOptions[$oname] = $val;
2582 }
2583
2584 /**
2585 * Get a token stored in the preferences (like the watchlist one),
2586 * resetting it if it's empty (and saving changes).
2587 *
2588 * @param string $oname The option name to retrieve the token from
2589 * @return string|bool User's current value for the option, or false if this option is disabled.
2590 * @see resetTokenFromOption()
2591 * @see getOption()
2592 */
2593 public function getTokenFromOption( $oname ) {
2594 global $wgHiddenPrefs;
2595 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2596 return false;
2597 }
2598
2599 $token = $this->getOption( $oname );
2600 if ( !$token ) {
2601 $token = $this->resetTokenFromOption( $oname );
2602 $this->saveSettings();
2603 }
2604 return $token;
2605 }
2606
2607 /**
2608 * Reset a token stored in the preferences (like the watchlist one).
2609 * *Does not* save user's preferences (similarly to setOption()).
2610 *
2611 * @param string $oname The option name to reset the token in
2612 * @return string|bool New token value, or false if this option is disabled.
2613 * @see getTokenFromOption()
2614 * @see setOption()
2615 */
2616 public function resetTokenFromOption( $oname ) {
2617 global $wgHiddenPrefs;
2618 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2619 return false;
2620 }
2621
2622 $token = MWCryptRand::generateHex( 40 );
2623 $this->setOption( $oname, $token );
2624 return $token;
2625 }
2626
2627 /**
2628 * Return a list of the types of user options currently returned by
2629 * User::getOptionKinds().
2630 *
2631 * Currently, the option kinds are:
2632 * - 'registered' - preferences which are registered in core MediaWiki or
2633 * by extensions using the UserGetDefaultOptions hook.
2634 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2635 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2636 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2637 * be used by user scripts.
2638 * - 'special' - "preferences" that are not accessible via User::getOptions
2639 * or User::setOptions.
2640 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2641 * These are usually legacy options, removed in newer versions.
2642 *
2643 * The API (and possibly others) use this function to determine the possible
2644 * option types for validation purposes, so make sure to update this when a
2645 * new option kind is added.
2646 *
2647 * @see User::getOptionKinds
2648 * @return array Option kinds
2649 */
2650 public static function listOptionKinds() {
2651 return array(
2652 'registered',
2653 'registered-multiselect',
2654 'registered-checkmatrix',
2655 'userjs',
2656 'special',
2657 'unused'
2658 );
2659 }
2660
2661 /**
2662 * Return an associative array mapping preferences keys to the kind of a preference they're
2663 * used for. Different kinds are handled differently when setting or reading preferences.
2664 *
2665 * See User::listOptionKinds for the list of valid option types that can be provided.
2666 *
2667 * @see User::listOptionKinds
2668 * @param IContextSource $context
2669 * @param array $options Assoc. array with options keys to check as keys.
2670 * Defaults to $this->mOptions.
2671 * @return array the key => kind mapping data
2672 */
2673 public function getOptionKinds( IContextSource $context, $options = null ) {
2674 $this->loadOptions();
2675 if ( $options === null ) {
2676 $options = $this->mOptions;
2677 }
2678
2679 $prefs = Preferences::getPreferences( $this, $context );
2680 $mapping = array();
2681
2682 // Pull out the "special" options, so they don't get converted as
2683 // multiselect or checkmatrix.
2684 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2685 foreach ( $specialOptions as $name => $value ) {
2686 unset( $prefs[$name] );
2687 }
2688
2689 // Multiselect and checkmatrix options are stored in the database with
2690 // one key per option, each having a boolean value. Extract those keys.
2691 $multiselectOptions = array();
2692 foreach ( $prefs as $name => $info ) {
2693 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2694 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2695 $opts = HTMLFormField::flattenOptions( $info['options'] );
2696 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2697
2698 foreach ( $opts as $value ) {
2699 $multiselectOptions["$prefix$value"] = true;
2700 }
2701
2702 unset( $prefs[$name] );
2703 }
2704 }
2705 $checkmatrixOptions = array();
2706 foreach ( $prefs as $name => $info ) {
2707 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2708 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2709 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2710 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2711 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2712
2713 foreach ( $columns as $column ) {
2714 foreach ( $rows as $row ) {
2715 $checkmatrixOptions["$prefix-$column-$row"] = true;
2716 }
2717 }
2718
2719 unset( $prefs[$name] );
2720 }
2721 }
2722
2723 // $value is ignored
2724 foreach ( $options as $key => $value ) {
2725 if ( isset( $prefs[$key] ) ) {
2726 $mapping[$key] = 'registered';
2727 } elseif ( isset( $multiselectOptions[$key] ) ) {
2728 $mapping[$key] = 'registered-multiselect';
2729 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2730 $mapping[$key] = 'registered-checkmatrix';
2731 } elseif ( isset( $specialOptions[$key] ) ) {
2732 $mapping[$key] = 'special';
2733 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2734 $mapping[$key] = 'userjs';
2735 } else {
2736 $mapping[$key] = 'unused';
2737 }
2738 }
2739
2740 return $mapping;
2741 }
2742
2743 /**
2744 * Reset certain (or all) options to the site defaults
2745 *
2746 * The optional parameter determines which kinds of preferences will be reset.
2747 * Supported values are everything that can be reported by getOptionKinds()
2748 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2749 *
2750 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2751 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2752 * for backwards-compatibility.
2753 * @param IContextSource|null $context Context source used when $resetKinds
2754 * does not contain 'all', passed to getOptionKinds().
2755 * Defaults to RequestContext::getMain() when null.
2756 */
2757 public function resetOptions(
2758 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2759 IContextSource $context = null
2760 ) {
2761 $this->load();
2762 $defaultOptions = self::getDefaultOptions();
2763
2764 if ( !is_array( $resetKinds ) ) {
2765 $resetKinds = array( $resetKinds );
2766 }
2767
2768 if ( in_array( 'all', $resetKinds ) ) {
2769 $newOptions = $defaultOptions;
2770 } else {
2771 if ( $context === null ) {
2772 $context = RequestContext::getMain();
2773 }
2774
2775 $optionKinds = $this->getOptionKinds( $context );
2776 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2777 $newOptions = array();
2778
2779 // Use default values for the options that should be deleted, and
2780 // copy old values for the ones that shouldn't.
2781 foreach ( $this->mOptions as $key => $value ) {
2782 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2783 if ( array_key_exists( $key, $defaultOptions ) ) {
2784 $newOptions[$key] = $defaultOptions[$key];
2785 }
2786 } else {
2787 $newOptions[$key] = $value;
2788 }
2789 }
2790 }
2791
2792 $this->mOptions = $newOptions;
2793 $this->mOptionsLoaded = true;
2794 }
2795
2796 /**
2797 * Get the user's preferred date format.
2798 * @return string User's preferred date format
2799 */
2800 public function getDatePreference() {
2801 // Important migration for old data rows
2802 if ( is_null( $this->mDatePreference ) ) {
2803 global $wgLang;
2804 $value = $this->getOption( 'date' );
2805 $map = $wgLang->getDatePreferenceMigrationMap();
2806 if ( isset( $map[$value] ) ) {
2807 $value = $map[$value];
2808 }
2809 $this->mDatePreference = $value;
2810 }
2811 return $this->mDatePreference;
2812 }
2813
2814 /**
2815 * Determine based on the wiki configuration and the user's options,
2816 * whether this user must be over HTTPS no matter what.
2817 *
2818 * @return bool
2819 */
2820 public function requiresHTTPS() {
2821 global $wgSecureLogin;
2822 if ( !$wgSecureLogin ) {
2823 return false;
2824 } else {
2825 $https = $this->getBoolOption( 'prefershttps' );
2826 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2827 if ( $https ) {
2828 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2829 }
2830 return $https;
2831 }
2832 }
2833
2834 /**
2835 * Get the user preferred stub threshold
2836 *
2837 * @return int
2838 */
2839 public function getStubThreshold() {
2840 global $wgMaxArticleSize; # Maximum article size, in Kb
2841 $threshold = $this->getIntOption( 'stubthreshold' );
2842 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2843 // If they have set an impossible value, disable the preference
2844 // so we can use the parser cache again.
2845 $threshold = 0;
2846 }
2847 return $threshold;
2848 }
2849
2850 /**
2851 * Get the permissions this user has.
2852 * @return array Array of String permission names
2853 */
2854 public function getRights() {
2855 if ( is_null( $this->mRights ) ) {
2856 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2857 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2858 // Force reindexation of rights when a hook has unset one of them
2859 $this->mRights = array_values( array_unique( $this->mRights ) );
2860 }
2861 return $this->mRights;
2862 }
2863
2864 /**
2865 * Get the list of explicit group memberships this user has.
2866 * The implicit * and user groups are not included.
2867 * @return array Array of String internal group names
2868 */
2869 public function getGroups() {
2870 $this->load();
2871 $this->loadGroups();
2872 return $this->mGroups;
2873 }
2874
2875 /**
2876 * Get the list of implicit group memberships this user has.
2877 * This includes all explicit groups, plus 'user' if logged in,
2878 * '*' for all accounts, and autopromoted groups
2879 * @param bool $recache Whether to avoid the cache
2880 * @return array Array of String internal group names
2881 */
2882 public function getEffectiveGroups( $recache = false ) {
2883 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2884 wfProfileIn( __METHOD__ );
2885 $this->mEffectiveGroups = array_unique( array_merge(
2886 $this->getGroups(), // explicit groups
2887 $this->getAutomaticGroups( $recache ) // implicit groups
2888 ) );
2889 // Hook for additional groups
2890 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2891 // Force reindexation of groups when a hook has unset one of them
2892 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2893 wfProfileOut( __METHOD__ );
2894 }
2895 return $this->mEffectiveGroups;
2896 }
2897
2898 /**
2899 * Get the list of implicit group memberships this user has.
2900 * This includes 'user' if logged in, '*' for all accounts,
2901 * and autopromoted groups
2902 * @param bool $recache Whether to avoid the cache
2903 * @return array Array of String internal group names
2904 */
2905 public function getAutomaticGroups( $recache = false ) {
2906 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2907 wfProfileIn( __METHOD__ );
2908 $this->mImplicitGroups = array( '*' );
2909 if ( $this->getId() ) {
2910 $this->mImplicitGroups[] = 'user';
2911
2912 $this->mImplicitGroups = array_unique( array_merge(
2913 $this->mImplicitGroups,
2914 Autopromote::getAutopromoteGroups( $this )
2915 ) );
2916 }
2917 if ( $recache ) {
2918 // Assure data consistency with rights/groups,
2919 // as getEffectiveGroups() depends on this function
2920 $this->mEffectiveGroups = null;
2921 }
2922 wfProfileOut( __METHOD__ );
2923 }
2924 return $this->mImplicitGroups;
2925 }
2926
2927 /**
2928 * Returns the groups the user has belonged to.
2929 *
2930 * The user may still belong to the returned groups. Compare with getGroups().
2931 *
2932 * The function will not return groups the user had belonged to before MW 1.17
2933 *
2934 * @return array Names of the groups the user has belonged to.
2935 */
2936 public function getFormerGroups() {
2937 if ( is_null( $this->mFormerGroups ) ) {
2938 $dbr = wfGetDB( DB_MASTER );
2939 $res = $dbr->select( 'user_former_groups',
2940 array( 'ufg_group' ),
2941 array( 'ufg_user' => $this->mId ),
2942 __METHOD__ );
2943 $this->mFormerGroups = array();
2944 foreach ( $res as $row ) {
2945 $this->mFormerGroups[] = $row->ufg_group;
2946 }
2947 }
2948 return $this->mFormerGroups;
2949 }
2950
2951 /**
2952 * Get the user's edit count.
2953 * @return int|null null for anonymous users
2954 */
2955 public function getEditCount() {
2956 if ( !$this->getId() ) {
2957 return null;
2958 }
2959
2960 if ( !isset( $this->mEditCount ) ) {
2961 /* Populate the count, if it has not been populated yet */
2962 wfProfileIn( __METHOD__ );
2963 $dbr = wfGetDB( DB_SLAVE );
2964 // check if the user_editcount field has been initialized
2965 $count = $dbr->selectField(
2966 'user', 'user_editcount',
2967 array( 'user_id' => $this->mId ),
2968 __METHOD__
2969 );
2970
2971 if ( $count === null ) {
2972 // it has not been initialized. do so.
2973 $count = $this->initEditCount();
2974 }
2975 $this->mEditCount = $count;
2976 wfProfileOut( __METHOD__ );
2977 }
2978 return (int)$this->mEditCount;
2979 }
2980
2981 /**
2982 * Add the user to the given group.
2983 * This takes immediate effect.
2984 * @param string $group Name of the group to add
2985 */
2986 public function addGroup( $group ) {
2987 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2988 $dbw = wfGetDB( DB_MASTER );
2989 if ( $this->getId() ) {
2990 $dbw->insert( 'user_groups',
2991 array(
2992 'ug_user' => $this->getID(),
2993 'ug_group' => $group,
2994 ),
2995 __METHOD__,
2996 array( 'IGNORE' ) );
2997 }
2998 }
2999 $this->loadGroups();
3000 $this->mGroups[] = $group;
3001 // In case loadGroups was not called before, we now have the right twice.
3002 // Get rid of the duplicate.
3003 $this->mGroups = array_unique( $this->mGroups );
3004
3005 // Refresh the groups caches, and clear the rights cache so it will be
3006 // refreshed on the next call to $this->getRights().
3007 $this->getEffectiveGroups( true );
3008 $this->mRights = null;
3009
3010 $this->invalidateCache();
3011 }
3012
3013 /**
3014 * Remove the user from the given group.
3015 * This takes immediate effect.
3016 * @param string $group Name of the group to remove
3017 */
3018 public function removeGroup( $group ) {
3019 $this->load();
3020 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3021 $dbw = wfGetDB( DB_MASTER );
3022 $dbw->delete( 'user_groups',
3023 array(
3024 'ug_user' => $this->getID(),
3025 'ug_group' => $group,
3026 ), __METHOD__ );
3027 // Remember that the user was in this group
3028 $dbw->insert( 'user_former_groups',
3029 array(
3030 'ufg_user' => $this->getID(),
3031 'ufg_group' => $group,
3032 ),
3033 __METHOD__,
3034 array( 'IGNORE' ) );
3035 }
3036 $this->loadGroups();
3037 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
3038
3039 // Refresh the groups caches, and clear the rights cache so it will be
3040 // refreshed on the next call to $this->getRights().
3041 $this->getEffectiveGroups( true );
3042 $this->mRights = null;
3043
3044 $this->invalidateCache();
3045 }
3046
3047 /**
3048 * Get whether the user is logged in
3049 * @return bool
3050 */
3051 public function isLoggedIn() {
3052 return $this->getID() != 0;
3053 }
3054
3055 /**
3056 * Get whether the user is anonymous
3057 * @return bool
3058 */
3059 public function isAnon() {
3060 return !$this->isLoggedIn();
3061 }
3062
3063 /**
3064 * Check if user is allowed to access a feature / make an action
3065 *
3066 * @internal param \String $varargs permissions to test
3067 * @return bool True if user is allowed to perform *any* of the given actions
3068 *
3069 * @return bool
3070 */
3071 public function isAllowedAny( /*...*/ ) {
3072 $permissions = func_get_args();
3073 foreach ( $permissions as $permission ) {
3074 if ( $this->isAllowed( $permission ) ) {
3075 return true;
3076 }
3077 }
3078 return false;
3079 }
3080
3081 /**
3082 *
3083 * @internal param $varargs string
3084 * @return bool True if the user is allowed to perform *all* of the given actions
3085 */
3086 public function isAllowedAll( /*...*/ ) {
3087 $permissions = func_get_args();
3088 foreach ( $permissions as $permission ) {
3089 if ( !$this->isAllowed( $permission ) ) {
3090 return false;
3091 }
3092 }
3093 return true;
3094 }
3095
3096 /**
3097 * Internal mechanics of testing a permission
3098 * @param string $action
3099 * @return bool
3100 */
3101 public function isAllowed( $action = '' ) {
3102 if ( $action === '' ) {
3103 return true; // In the spirit of DWIM
3104 }
3105 // Patrolling may not be enabled
3106 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3107 global $wgUseRCPatrol, $wgUseNPPatrol;
3108 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3109 return false;
3110 }
3111 }
3112 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3113 // by misconfiguration: 0 == 'foo'
3114 return in_array( $action, $this->getRights(), true );
3115 }
3116
3117 /**
3118 * Check whether to enable recent changes patrol features for this user
3119 * @return bool True or false
3120 */
3121 public function useRCPatrol() {
3122 global $wgUseRCPatrol;
3123 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3124 }
3125
3126 /**
3127 * Check whether to enable new pages patrol features for this user
3128 * @return bool True or false
3129 */
3130 public function useNPPatrol() {
3131 global $wgUseRCPatrol, $wgUseNPPatrol;
3132 return (
3133 ( $wgUseRCPatrol || $wgUseNPPatrol )
3134 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3135 );
3136 }
3137
3138 /**
3139 * Get the WebRequest object to use with this object
3140 *
3141 * @return WebRequest
3142 */
3143 public function getRequest() {
3144 if ( $this->mRequest ) {
3145 return $this->mRequest;
3146 } else {
3147 global $wgRequest;
3148 return $wgRequest;
3149 }
3150 }
3151
3152 /**
3153 * Get the current skin, loading it if required
3154 * @return Skin The current skin
3155 * @todo FIXME: Need to check the old failback system [AV]
3156 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3157 */
3158 public function getSkin() {
3159 wfDeprecated( __METHOD__, '1.18' );
3160 return RequestContext::getMain()->getSkin();
3161 }
3162
3163 /**
3164 * Get a WatchedItem for this user and $title.
3165 *
3166 * @since 1.22 $checkRights parameter added
3167 * @param Title $title
3168 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3169 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3170 * @return WatchedItem
3171 */
3172 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3173 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3174
3175 if ( isset( $this->mWatchedItems[$key] ) ) {
3176 return $this->mWatchedItems[$key];
3177 }
3178
3179 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3180 $this->mWatchedItems = array();
3181 }
3182
3183 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3184 return $this->mWatchedItems[$key];
3185 }
3186
3187 /**
3188 * Check the watched status of an article.
3189 * @since 1.22 $checkRights parameter added
3190 * @param Title $title Title of the article to look at
3191 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3192 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3193 * @return bool
3194 */
3195 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3196 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3197 }
3198
3199 /**
3200 * Watch an article.
3201 * @since 1.22 $checkRights parameter added
3202 * @param Title $title Title of the article to look at
3203 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3204 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3205 */
3206 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3207 $this->getWatchedItem( $title, $checkRights )->addWatch();
3208 $this->invalidateCache();
3209 }
3210
3211 /**
3212 * Stop watching an article.
3213 * @since 1.22 $checkRights parameter added
3214 * @param Title $title Title of the article to look at
3215 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3216 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3217 */
3218 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3219 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3220 $this->invalidateCache();
3221 }
3222
3223 /**
3224 * Clear the user's notification timestamp for the given title.
3225 * If e-notif e-mails are on, they will receive notification mails on
3226 * the next change of the page if it's watched etc.
3227 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3228 * @param Title $title Title of the article to look at
3229 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3230 */
3231 public function clearNotification( &$title, $oldid = 0 ) {
3232 global $wgUseEnotif, $wgShowUpdatedMarker;
3233
3234 // Do nothing if the database is locked to writes
3235 if ( wfReadOnly() ) {
3236 return;
3237 }
3238
3239 // Do nothing if not allowed to edit the watchlist
3240 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3241 return;
3242 }
3243
3244 // If we're working on user's talk page, we should update the talk page message indicator
3245 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3246 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3247 return;
3248 }
3249
3250 $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null;
3251
3252 if ( !$oldid || !$nextid ) {
3253 // If we're looking at the latest revision, we should definitely clear it
3254 $this->setNewtalk( false );
3255 } else {
3256 // Otherwise we should update its revision, if it's present
3257 if ( $this->getNewtalk() ) {
3258 // Naturally the other one won't clear by itself
3259 $this->setNewtalk( false );
3260 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3261 }
3262 }
3263 }
3264
3265 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3266 return;
3267 }
3268
3269 if ( $this->isAnon() ) {
3270 // Nothing else to do...
3271 return;
3272 }
3273
3274 // Only update the timestamp if the page is being watched.
3275 // The query to find out if it is watched is cached both in memcached and per-invocation,
3276 // and when it does have to be executed, it can be on a slave
3277 // If this is the user's newtalk page, we always update the timestamp
3278 $force = '';
3279 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3280 $force = 'force';
3281 }
3282
3283 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3284 }
3285
3286 /**
3287 * Resets all of the given user's page-change notification timestamps.
3288 * If e-notif e-mails are on, they will receive notification mails on
3289 * the next change of any watched page.
3290 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3291 */
3292 public function clearAllNotifications() {
3293 if ( wfReadOnly() ) {
3294 return;
3295 }
3296
3297 // Do nothing if not allowed to edit the watchlist
3298 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3299 return;
3300 }
3301
3302 global $wgUseEnotif, $wgShowUpdatedMarker;
3303 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3304 $this->setNewtalk( false );
3305 return;
3306 }
3307 $id = $this->getId();
3308 if ( $id != 0 ) {
3309 $dbw = wfGetDB( DB_MASTER );
3310 $dbw->update( 'watchlist',
3311 array( /* SET */ 'wl_notificationtimestamp' => null ),
3312 array( /* WHERE */ 'wl_user' => $id ),
3313 __METHOD__
3314 );
3315 // We also need to clear here the "you have new message" notification for the own user_talk page;
3316 // it's cleared one page view later in WikiPage::doViewUpdates().
3317 }
3318 }
3319
3320 /**
3321 * Set this user's options from an encoded string
3322 * @param string $str Encoded options to import
3323 *
3324 * @deprecated since 1.19 due to removal of user_options from the user table
3325 */
3326 private function decodeOptions( $str ) {
3327 wfDeprecated( __METHOD__, '1.19' );
3328 if ( !$str ) {
3329 return;
3330 }
3331
3332 $this->mOptionsLoaded = true;
3333 $this->mOptionOverrides = array();
3334
3335 // If an option is not set in $str, use the default value
3336 $this->mOptions = self::getDefaultOptions();
3337
3338 $a = explode( "\n", $str );
3339 foreach ( $a as $s ) {
3340 $m = array();
3341 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
3342 $this->mOptions[$m[1]] = $m[2];
3343 $this->mOptionOverrides[$m[1]] = $m[2];
3344 }
3345 }
3346 }
3347
3348 /**
3349 * Set a cookie on the user's client. Wrapper for
3350 * WebResponse::setCookie
3351 * @param string $name Name of the cookie to set
3352 * @param string $value Value to set
3353 * @param int $exp Expiration time, as a UNIX time value;
3354 * if 0 or not specified, use the default $wgCookieExpiration
3355 * @param bool $secure
3356 * true: Force setting the secure attribute when setting the cookie
3357 * false: Force NOT setting the secure attribute when setting the cookie
3358 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3359 * @param array $params Array of options sent passed to WebResponse::setcookie()
3360 */
3361 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3362 $params['secure'] = $secure;
3363 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3364 }
3365
3366 /**
3367 * Clear a cookie on the user's client
3368 * @param string $name Name of the cookie to clear
3369 * @param bool $secure
3370 * true: Force setting the secure attribute when setting the cookie
3371 * false: Force NOT setting the secure attribute when setting the cookie
3372 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3373 * @param array $params Array of options sent passed to WebResponse::setcookie()
3374 */
3375 protected function clearCookie( $name, $secure = null, $params = array() ) {
3376 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3377 }
3378
3379 /**
3380 * Set the default cookies for this session on the user's client.
3381 *
3382 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3383 * is passed.
3384 * @param bool $secure Whether to force secure/insecure cookies or use default
3385 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3386 */
3387 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3388 if ( $request === null ) {
3389 $request = $this->getRequest();
3390 }
3391
3392 $this->load();
3393 if ( 0 == $this->mId ) {
3394 return;
3395 }
3396 if ( !$this->mToken ) {
3397 // When token is empty or NULL generate a new one and then save it to the database
3398 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3399 // Simply by setting every cell in the user_token column to NULL and letting them be
3400 // regenerated as users log back into the wiki.
3401 $this->setToken();
3402 $this->saveSettings();
3403 }
3404 $session = array(
3405 'wsUserID' => $this->mId,
3406 'wsToken' => $this->mToken,
3407 'wsUserName' => $this->getName()
3408 );
3409 $cookies = array(
3410 'UserID' => $this->mId,
3411 'UserName' => $this->getName(),
3412 );
3413 if ( $rememberMe ) {
3414 $cookies['Token'] = $this->mToken;
3415 } else {
3416 $cookies['Token'] = false;
3417 }
3418
3419 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3420
3421 foreach ( $session as $name => $value ) {
3422 $request->setSessionData( $name, $value );
3423 }
3424 foreach ( $cookies as $name => $value ) {
3425 if ( $value === false ) {
3426 $this->clearCookie( $name );
3427 } else {
3428 $this->setCookie( $name, $value, 0, $secure );
3429 }
3430 }
3431
3432 /**
3433 * If wpStickHTTPS was selected, also set an insecure cookie that
3434 * will cause the site to redirect the user to HTTPS, if they access
3435 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3436 * as the one set by centralauth (bug 53538). Also set it to session, or
3437 * standard time setting, based on if rememberme was set.
3438 */
3439 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3440 $this->setCookie(
3441 'forceHTTPS',
3442 'true',
3443 $rememberMe ? 0 : null,
3444 false,
3445 array( 'prefix' => '' ) // no prefix
3446 );
3447 }
3448 }
3449
3450 /**
3451 * Log this user out.
3452 */
3453 public function logout() {
3454 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3455 $this->doLogout();
3456 }
3457 }
3458
3459 /**
3460 * Clear the user's cookies and session, and reset the instance cache.
3461 * @see logout()
3462 */
3463 public function doLogout() {
3464 $this->clearInstanceCache( 'defaults' );
3465
3466 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3467
3468 $this->clearCookie( 'UserID' );
3469 $this->clearCookie( 'Token' );
3470 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3471
3472 // Remember when user logged out, to prevent seeing cached pages
3473 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3474 }
3475
3476 /**
3477 * Save this user's settings into the database.
3478 * @todo Only rarely do all these fields need to be set!
3479 */
3480 public function saveSettings() {
3481 global $wgAuth;
3482
3483 $this->load();
3484 if ( wfReadOnly() ) {
3485 return;
3486 }
3487 if ( 0 == $this->mId ) {
3488 return;
3489 }
3490
3491 $this->mTouched = self::newTouchedTimestamp();
3492 if ( !$wgAuth->allowSetLocalPassword() ) {
3493 $this->mPassword = '';
3494 }
3495
3496 $dbw = wfGetDB( DB_MASTER );
3497 $dbw->update( 'user',
3498 array( /* SET */
3499 'user_name' => $this->mName,
3500 'user_password' => $this->mPassword,
3501 'user_newpassword' => $this->mNewpassword,
3502 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3503 'user_real_name' => $this->mRealName,
3504 'user_email' => $this->mEmail,
3505 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3506 'user_touched' => $dbw->timestamp( $this->mTouched ),
3507 'user_token' => strval( $this->mToken ),
3508 'user_email_token' => $this->mEmailToken,
3509 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3510 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3511 ), array( /* WHERE */
3512 'user_id' => $this->mId
3513 ), __METHOD__
3514 );
3515
3516 $this->saveOptions();
3517
3518 wfRunHooks( 'UserSaveSettings', array( $this ) );
3519 $this->clearSharedCache();
3520 $this->getUserPage()->invalidateCache();
3521 }
3522
3523 /**
3524 * If only this user's username is known, and it exists, return the user ID.
3525 * @return int
3526 */
3527 public function idForName() {
3528 $s = trim( $this->getName() );
3529 if ( $s === '' ) {
3530 return 0;
3531 }
3532
3533 $dbr = wfGetDB( DB_SLAVE );
3534 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3535 if ( $id === false ) {
3536 $id = 0;
3537 }
3538 return $id;
3539 }
3540
3541 /**
3542 * Add a user to the database, return the user object
3543 *
3544 * @param string $name Username to add
3545 * @param array $params Array of Strings Non-default parameters to save to
3546 * the database as user_* fields:
3547 * - password: The user's password hash. Password logins will be disabled
3548 * if this is omitted.
3549 * - newpassword: Hash for a temporary password that has been mailed to
3550 * the user.
3551 * - email: The user's email address.
3552 * - email_authenticated: The email authentication timestamp.
3553 * - real_name: The user's real name.
3554 * - options: An associative array of non-default options.
3555 * - token: Random authentication token. Do not set.
3556 * - registration: Registration timestamp. Do not set.
3557 *
3558 * @return User|null User object, or null if the username already exists.
3559 */
3560 public static function createNew( $name, $params = array() ) {
3561 $user = new User;
3562 $user->load();
3563 $user->setToken(); // init token
3564 if ( isset( $params['options'] ) ) {
3565 $user->mOptions = $params['options'] + (array)$user->mOptions;
3566 unset( $params['options'] );
3567 }
3568 $dbw = wfGetDB( DB_MASTER );
3569 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3570
3571 $fields = array(
3572 'user_id' => $seqVal,
3573 'user_name' => $name,
3574 'user_password' => $user->mPassword,
3575 'user_newpassword' => $user->mNewpassword,
3576 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3577 'user_email' => $user->mEmail,
3578 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3579 'user_real_name' => $user->mRealName,
3580 'user_token' => strval( $user->mToken ),
3581 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3582 'user_editcount' => 0,
3583 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3584 );
3585 foreach ( $params as $name => $value ) {
3586 $fields["user_$name"] = $value;
3587 }
3588 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3589 if ( $dbw->affectedRows() ) {
3590 $newUser = User::newFromId( $dbw->insertId() );
3591 } else {
3592 $newUser = null;
3593 }
3594 return $newUser;
3595 }
3596
3597 /**
3598 * Add this existing user object to the database. If the user already
3599 * exists, a fatal status object is returned, and the user object is
3600 * initialised with the data from the database.
3601 *
3602 * Previously, this function generated a DB error due to a key conflict
3603 * if the user already existed. Many extension callers use this function
3604 * in code along the lines of:
3605 *
3606 * $user = User::newFromName( $name );
3607 * if ( !$user->isLoggedIn() ) {
3608 * $user->addToDatabase();
3609 * }
3610 * // do something with $user...
3611 *
3612 * However, this was vulnerable to a race condition (bug 16020). By
3613 * initialising the user object if the user exists, we aim to support this
3614 * calling sequence as far as possible.
3615 *
3616 * Note that if the user exists, this function will acquire a write lock,
3617 * so it is still advisable to make the call conditional on isLoggedIn(),
3618 * and to commit the transaction after calling.
3619 *
3620 * @throws MWException
3621 * @return Status
3622 */
3623 public function addToDatabase() {
3624 $this->load();
3625 if ( !$this->mToken ) {
3626 $this->setToken(); // init token
3627 }
3628
3629 $this->mTouched = self::newTouchedTimestamp();
3630
3631 $dbw = wfGetDB( DB_MASTER );
3632 $inWrite = $dbw->writesOrCallbacksPending();
3633 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3634 $dbw->insert( 'user',
3635 array(
3636 'user_id' => $seqVal,
3637 'user_name' => $this->mName,
3638 'user_password' => $this->mPassword,
3639 'user_newpassword' => $this->mNewpassword,
3640 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3641 'user_email' => $this->mEmail,
3642 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3643 'user_real_name' => $this->mRealName,
3644 'user_token' => strval( $this->mToken ),
3645 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3646 'user_editcount' => 0,
3647 'user_touched' => $dbw->timestamp( $this->mTouched ),
3648 ), __METHOD__,
3649 array( 'IGNORE' )
3650 );
3651 if ( !$dbw->affectedRows() ) {
3652 if ( !$inWrite ) {
3653 // XXX: Get out of REPEATABLE-READ so the SELECT below works.
3654 // Often this case happens early in views before any writes.
3655 // This shows up at least with CentralAuth.
3656 $dbw->commit( __METHOD__, 'flush' );
3657 }
3658 $this->mId = $dbw->selectField( 'user', 'user_id',
3659 array( 'user_name' => $this->mName ), __METHOD__ );
3660 $loaded = false;
3661 if ( $this->mId ) {
3662 if ( $this->loadFromDatabase() ) {
3663 $loaded = true;
3664 }
3665 }
3666 if ( !$loaded ) {
3667 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3668 "to insert user '{$this->mName}' row, but it was not present in select!" );
3669 }
3670 return Status::newFatal( 'userexists' );
3671 }
3672 $this->mId = $dbw->insertId();
3673
3674 // Clear instance cache other than user table data, which is already accurate
3675 $this->clearInstanceCache();
3676
3677 $this->saveOptions();
3678 return Status::newGood();
3679 }
3680
3681 /**
3682 * If this user is logged-in and blocked,
3683 * block any IP address they've successfully logged in from.
3684 * @return bool A block was spread
3685 */
3686 public function spreadAnyEditBlock() {
3687 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3688 return $this->spreadBlock();
3689 }
3690 return false;
3691 }
3692
3693 /**
3694 * If this (non-anonymous) user is blocked,
3695 * block the IP address they've successfully logged in from.
3696 * @return bool A block was spread
3697 */
3698 protected function spreadBlock() {
3699 wfDebug( __METHOD__ . "()\n" );
3700 $this->load();
3701 if ( $this->mId == 0 ) {
3702 return false;
3703 }
3704
3705 $userblock = Block::newFromTarget( $this->getName() );
3706 if ( !$userblock ) {
3707 return false;
3708 }
3709
3710 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3711 }
3712
3713 /**
3714 * Get whether the user is explicitly blocked from account creation.
3715 * @return bool|Block
3716 */
3717 public function isBlockedFromCreateAccount() {
3718 $this->getBlockedStatus();
3719 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3720 return $this->mBlock;
3721 }
3722
3723 # bug 13611: if the IP address the user is trying to create an account from is
3724 # blocked with createaccount disabled, prevent new account creation there even
3725 # when the user is logged in
3726 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3727 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3728 }
3729 return $this->mBlockedFromCreateAccount instanceof Block
3730 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3731 ? $this->mBlockedFromCreateAccount
3732 : false;
3733 }
3734
3735 /**
3736 * Get whether the user is blocked from using Special:Emailuser.
3737 * @return bool
3738 */
3739 public function isBlockedFromEmailuser() {
3740 $this->getBlockedStatus();
3741 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3742 }
3743
3744 /**
3745 * Get whether the user is allowed to create an account.
3746 * @return bool
3747 */
3748 public function isAllowedToCreateAccount() {
3749 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3750 }
3751
3752 /**
3753 * Get this user's personal page title.
3754 *
3755 * @return Title User's personal page title
3756 */
3757 public function getUserPage() {
3758 return Title::makeTitle( NS_USER, $this->getName() );
3759 }
3760
3761 /**
3762 * Get this user's talk page title.
3763 *
3764 * @return Title User's talk page title
3765 */
3766 public function getTalkPage() {
3767 $title = $this->getUserPage();
3768 return $title->getTalkPage();
3769 }
3770
3771 /**
3772 * Determine whether the user is a newbie. Newbies are either
3773 * anonymous IPs, or the most recently created accounts.
3774 * @return bool
3775 */
3776 public function isNewbie() {
3777 return !$this->isAllowed( 'autoconfirmed' );
3778 }
3779
3780 /**
3781 * Check to see if the given clear-text password is one of the accepted passwords
3782 * @param string $password user password.
3783 * @return bool True if the given password is correct, otherwise False.
3784 */
3785 public function checkPassword( $password ) {
3786 global $wgAuth, $wgLegacyEncoding;
3787 $this->load();
3788
3789 // Certain authentication plugins do NOT want to save
3790 // domain passwords in a mysql database, so we should
3791 // check this (in case $wgAuth->strict() is false).
3792
3793 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3794 return true;
3795 } elseif ( $wgAuth->strict() ) {
3796 // Auth plugin doesn't allow local authentication
3797 return false;
3798 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3799 // Auth plugin doesn't allow local authentication for this user name
3800 return false;
3801 }
3802 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
3803 return true;
3804 } elseif ( $wgLegacyEncoding ) {
3805 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3806 // Check for this with iconv
3807 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3808 if ( $cp1252Password != $password
3809 && self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId )
3810 ) {
3811 return true;
3812 }
3813 }
3814 return false;
3815 }
3816
3817 /**
3818 * Check if the given clear-text password matches the temporary password
3819 * sent by e-mail for password reset operations.
3820 *
3821 * @param string $plaintext
3822 *
3823 * @return bool True if matches, false otherwise
3824 */
3825 public function checkTemporaryPassword( $plaintext ) {
3826 global $wgNewPasswordExpiry;
3827
3828 $this->load();
3829 if ( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
3830 if ( is_null( $this->mNewpassTime ) ) {
3831 return true;
3832 }
3833 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3834 return ( time() < $expiry );
3835 } else {
3836 return false;
3837 }
3838 }
3839
3840 /**
3841 * Alias for getEditToken.
3842 * @deprecated since 1.19, use getEditToken instead.
3843 *
3844 * @param string|array $salt of Strings Optional function-specific data for hashing
3845 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3846 * @return string The new edit token
3847 */
3848 public function editToken( $salt = '', $request = null ) {
3849 wfDeprecated( __METHOD__, '1.19' );
3850 return $this->getEditToken( $salt, $request );
3851 }
3852
3853 /**
3854 * Initialize (if necessary) and return a session token value
3855 * which can be used in edit forms to show that the user's
3856 * login credentials aren't being hijacked with a foreign form
3857 * submission.
3858 *
3859 * @since 1.19
3860 *
3861 * @param string|array $salt of Strings Optional function-specific data for hashing
3862 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3863 * @return string The new edit token
3864 */
3865 public function getEditToken( $salt = '', $request = null ) {
3866 if ( $request == null ) {
3867 $request = $this->getRequest();
3868 }
3869
3870 if ( $this->isAnon() ) {
3871 return EDIT_TOKEN_SUFFIX;
3872 } else {
3873 $token = $request->getSessionData( 'wsEditToken' );
3874 if ( $token === null ) {
3875 $token = MWCryptRand::generateHex( 32 );
3876 $request->setSessionData( 'wsEditToken', $token );
3877 }
3878 if ( is_array( $salt ) ) {
3879 $salt = implode( '|', $salt );
3880 }
3881 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
3882 }
3883 }
3884
3885 /**
3886 * Generate a looking random token for various uses.
3887 *
3888 * @return string The new random token
3889 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3890 * wfRandomString for pseudo-randomness.
3891 */
3892 public static function generateToken() {
3893 return MWCryptRand::generateHex( 32 );
3894 }
3895
3896 /**
3897 * Check given value against the token value stored in the session.
3898 * A match should confirm that the form was submitted from the
3899 * user's own login session, not a form submission from a third-party
3900 * site.
3901 *
3902 * @param string $val Input value to compare
3903 * @param string $salt Optional function-specific data for hashing
3904 * @param WebRequest|null $request Object to use or null to use $wgRequest
3905 * @return bool Whether the token matches
3906 */
3907 public function matchEditToken( $val, $salt = '', $request = null ) {
3908 $sessionToken = $this->getEditToken( $salt, $request );
3909 if ( $val != $sessionToken ) {
3910 wfDebug( "User::matchEditToken: broken session data\n" );
3911 }
3912
3913 return $val == $sessionToken;
3914 }
3915
3916 /**
3917 * Check given value against the token value stored in the session,
3918 * ignoring the suffix.
3919 *
3920 * @param string $val Input value to compare
3921 * @param string $salt Optional function-specific data for hashing
3922 * @param WebRequest|null $request object to use or null to use $wgRequest
3923 * @return bool Whether the token matches
3924 */
3925 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3926 $sessionToken = $this->getEditToken( $salt, $request );
3927 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3928 }
3929
3930 /**
3931 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3932 * mail to the user's given address.
3933 *
3934 * @param string $type Message to send, either "created", "changed" or "set"
3935 * @return Status
3936 */
3937 public function sendConfirmationMail( $type = 'created' ) {
3938 global $wgLang;
3939 $expiration = null; // gets passed-by-ref and defined in next line.
3940 $token = $this->confirmationToken( $expiration );
3941 $url = $this->confirmationTokenUrl( $token );
3942 $invalidateURL = $this->invalidationTokenUrl( $token );
3943 $this->saveSettings();
3944
3945 if ( $type == 'created' || $type === false ) {
3946 $message = 'confirmemail_body';
3947 } elseif ( $type === true ) {
3948 $message = 'confirmemail_body_changed';
3949 } else {
3950 // Messages: confirmemail_body_changed, confirmemail_body_set
3951 $message = 'confirmemail_body_' . $type;
3952 }
3953
3954 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3955 wfMessage( $message,
3956 $this->getRequest()->getIP(),
3957 $this->getName(),
3958 $url,
3959 $wgLang->timeanddate( $expiration, false ),
3960 $invalidateURL,
3961 $wgLang->date( $expiration, false ),
3962 $wgLang->time( $expiration, false ) )->text() );
3963 }
3964
3965 /**
3966 * Send an e-mail to this user's account. Does not check for
3967 * confirmed status or validity.
3968 *
3969 * @param string $subject Message subject
3970 * @param string $body Message body
3971 * @param string $from Optional From address; if unspecified, default
3972 * $wgPasswordSender will be used.
3973 * @param string $replyto Reply-To address
3974 * @return Status
3975 */
3976 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3977 if ( is_null( $from ) ) {
3978 global $wgPasswordSender;
3979 $sender = new MailAddress( $wgPasswordSender,
3980 wfMessage( 'emailsender' )->inContentLanguage()->text() );
3981 } else {
3982 $sender = new MailAddress( $from );
3983 }
3984
3985 $to = new MailAddress( $this );
3986 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
3987 }
3988
3989 /**
3990 * Generate, store, and return a new e-mail confirmation code.
3991 * A hash (unsalted, since it's used as a key) is stored.
3992 *
3993 * @note Call saveSettings() after calling this function to commit
3994 * this change to the database.
3995 *
3996 * @param string &$expiration Accepts the expiration time
3997 * @return string New token
3998 */
3999 protected function confirmationToken( &$expiration ) {
4000 global $wgUserEmailConfirmationTokenExpiry;
4001 $now = time();
4002 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4003 $expiration = wfTimestamp( TS_MW, $expires );
4004 $this->load();
4005 $token = MWCryptRand::generateHex( 32 );
4006 $hash = md5( $token );
4007 $this->mEmailToken = $hash;
4008 $this->mEmailTokenExpires = $expiration;
4009 return $token;
4010 }
4011
4012 /**
4013 * Return a URL the user can use to confirm their email address.
4014 * @param string $token Accepts the email confirmation token
4015 * @return string New token URL
4016 */
4017 protected function confirmationTokenUrl( $token ) {
4018 return $this->getTokenUrl( 'ConfirmEmail', $token );
4019 }
4020
4021 /**
4022 * Return a URL the user can use to invalidate their email address.
4023 * @param string $token Accepts the email confirmation token
4024 * @return string New token URL
4025 */
4026 protected function invalidationTokenUrl( $token ) {
4027 return $this->getTokenUrl( 'InvalidateEmail', $token );
4028 }
4029
4030 /**
4031 * Internal function to format the e-mail validation/invalidation URLs.
4032 * This uses a quickie hack to use the
4033 * hardcoded English names of the Special: pages, for ASCII safety.
4034 *
4035 * @note Since these URLs get dropped directly into emails, using the
4036 * short English names avoids insanely long URL-encoded links, which
4037 * also sometimes can get corrupted in some browsers/mailers
4038 * (bug 6957 with Gmail and Internet Explorer).
4039 *
4040 * @param string $page Special page
4041 * @param string $token Token
4042 * @return string Formatted URL
4043 */
4044 protected function getTokenUrl( $page, $token ) {
4045 // Hack to bypass localization of 'Special:'
4046 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4047 return $title->getCanonicalURL();
4048 }
4049
4050 /**
4051 * Mark the e-mail address confirmed.
4052 *
4053 * @note Call saveSettings() after calling this function to commit the change.
4054 *
4055 * @return bool
4056 */
4057 public function confirmEmail() {
4058 // Check if it's already confirmed, so we don't touch the database
4059 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4060 if ( !$this->isEmailConfirmed() ) {
4061 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4062 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
4063 }
4064 return true;
4065 }
4066
4067 /**
4068 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4069 * address if it was already confirmed.
4070 *
4071 * @note Call saveSettings() after calling this function to commit the change.
4072 * @return bool Returns true
4073 */
4074 public function invalidateEmail() {
4075 $this->load();
4076 $this->mEmailToken = null;
4077 $this->mEmailTokenExpires = null;
4078 $this->setEmailAuthenticationTimestamp( null );
4079 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
4080 return true;
4081 }
4082
4083 /**
4084 * Set the e-mail authentication timestamp.
4085 * @param string $timestamp TS_MW timestamp
4086 */
4087 public function setEmailAuthenticationTimestamp( $timestamp ) {
4088 $this->load();
4089 $this->mEmailAuthenticated = $timestamp;
4090 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4091 }
4092
4093 /**
4094 * Is this user allowed to send e-mails within limits of current
4095 * site configuration?
4096 * @return bool
4097 */
4098 public function canSendEmail() {
4099 global $wgEnableEmail, $wgEnableUserEmail;
4100 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4101 return false;
4102 }
4103 $canSend = $this->isEmailConfirmed();
4104 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
4105 return $canSend;
4106 }
4107
4108 /**
4109 * Is this user allowed to receive e-mails within limits of current
4110 * site configuration?
4111 * @return bool
4112 */
4113 public function canReceiveEmail() {
4114 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4115 }
4116
4117 /**
4118 * Is this user's e-mail address valid-looking and confirmed within
4119 * limits of the current site configuration?
4120 *
4121 * @note If $wgEmailAuthentication is on, this may require the user to have
4122 * confirmed their address by returning a code or using a password
4123 * sent to the address from the wiki.
4124 *
4125 * @return bool
4126 */
4127 public function isEmailConfirmed() {
4128 global $wgEmailAuthentication;
4129 $this->load();
4130 $confirmed = true;
4131 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4132 if ( $this->isAnon() ) {
4133 return false;
4134 }
4135 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4136 return false;
4137 }
4138 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4139 return false;
4140 }
4141 return true;
4142 } else {
4143 return $confirmed;
4144 }
4145 }
4146
4147 /**
4148 * Check whether there is an outstanding request for e-mail confirmation.
4149 * @return bool
4150 */
4151 public function isEmailConfirmationPending() {
4152 global $wgEmailAuthentication;
4153 return $wgEmailAuthentication &&
4154 !$this->isEmailConfirmed() &&
4155 $this->mEmailToken &&
4156 $this->mEmailTokenExpires > wfTimestamp();
4157 }
4158
4159 /**
4160 * Get the timestamp of account creation.
4161 *
4162 * @return string|bool|null Timestamp of account creation, false for
4163 * non-existent/anonymous user accounts, or null if existing account
4164 * but information is not in database.
4165 */
4166 public function getRegistration() {
4167 if ( $this->isAnon() ) {
4168 return false;
4169 }
4170 $this->load();
4171 return $this->mRegistration;
4172 }
4173
4174 /**
4175 * Get the timestamp of the first edit
4176 *
4177 * @return string|bool Timestamp of first edit, or false for
4178 * non-existent/anonymous user accounts.
4179 */
4180 public function getFirstEditTimestamp() {
4181 if ( $this->getId() == 0 ) {
4182 return false; // anons
4183 }
4184 $dbr = wfGetDB( DB_SLAVE );
4185 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4186 array( 'rev_user' => $this->getId() ),
4187 __METHOD__,
4188 array( 'ORDER BY' => 'rev_timestamp ASC' )
4189 );
4190 if ( !$time ) {
4191 return false; // no edits
4192 }
4193 return wfTimestamp( TS_MW, $time );
4194 }
4195
4196 /**
4197 * Get the permissions associated with a given list of groups
4198 *
4199 * @param array $groups Array of Strings List of internal group names
4200 * @return array Array of Strings List of permission key names for given groups combined
4201 */
4202 public static function getGroupPermissions( $groups ) {
4203 global $wgGroupPermissions, $wgRevokePermissions;
4204 $rights = array();
4205 // grant every granted permission first
4206 foreach ( $groups as $group ) {
4207 if ( isset( $wgGroupPermissions[$group] ) ) {
4208 $rights = array_merge( $rights,
4209 // array_filter removes empty items
4210 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4211 }
4212 }
4213 // now revoke the revoked permissions
4214 foreach ( $groups as $group ) {
4215 if ( isset( $wgRevokePermissions[$group] ) ) {
4216 $rights = array_diff( $rights,
4217 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4218 }
4219 }
4220 return array_unique( $rights );
4221 }
4222
4223 /**
4224 * Get all the groups who have a given permission
4225 *
4226 * @param string $role Role to check
4227 * @return array Array of Strings List of internal group names with the given permission
4228 */
4229 public static function getGroupsWithPermission( $role ) {
4230 global $wgGroupPermissions;
4231 $allowedGroups = array();
4232 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4233 if ( self::groupHasPermission( $group, $role ) ) {
4234 $allowedGroups[] = $group;
4235 }
4236 }
4237 return $allowedGroups;
4238 }
4239
4240 /**
4241 * Check, if the given group has the given permission
4242 *
4243 * If you're wanting to check whether all users have a permission, use
4244 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4245 * from anyone.
4246 *
4247 * @since 1.21
4248 * @param string $group Group to check
4249 * @param string $role Role to check
4250 * @return bool
4251 */
4252 public static function groupHasPermission( $group, $role ) {
4253 global $wgGroupPermissions, $wgRevokePermissions;
4254 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4255 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4256 }
4257
4258 /**
4259 * Check if all users have the given permission
4260 *
4261 * @since 1.22
4262 * @param string $right Right to check
4263 * @return bool
4264 */
4265 public static function isEveryoneAllowed( $right ) {
4266 global $wgGroupPermissions, $wgRevokePermissions;
4267 static $cache = array();
4268
4269 // Use the cached results, except in unit tests which rely on
4270 // being able change the permission mid-request
4271 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4272 return $cache[$right];
4273 }
4274
4275 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4276 $cache[$right] = false;
4277 return false;
4278 }
4279
4280 // If it's revoked anywhere, then everyone doesn't have it
4281 foreach ( $wgRevokePermissions as $rights ) {
4282 if ( isset( $rights[$right] ) && $rights[$right] ) {
4283 $cache[$right] = false;
4284 return false;
4285 }
4286 }
4287
4288 // Allow extensions (e.g. OAuth) to say false
4289 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4290 $cache[$right] = false;
4291 return false;
4292 }
4293
4294 $cache[$right] = true;
4295 return true;
4296 }
4297
4298 /**
4299 * Get the localized descriptive name for a group, if it exists
4300 *
4301 * @param string $group Internal group name
4302 * @return string Localized descriptive group name
4303 */
4304 public static function getGroupName( $group ) {
4305 $msg = wfMessage( "group-$group" );
4306 return $msg->isBlank() ? $group : $msg->text();
4307 }
4308
4309 /**
4310 * Get the localized descriptive name for a member of a group, if it exists
4311 *
4312 * @param string $group Internal group name
4313 * @param string $username Username for gender (since 1.19)
4314 * @return string Localized name for group member
4315 */
4316 public static function getGroupMember( $group, $username = '#' ) {
4317 $msg = wfMessage( "group-$group-member", $username );
4318 return $msg->isBlank() ? $group : $msg->text();
4319 }
4320
4321 /**
4322 * Return the set of defined explicit groups.
4323 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4324 * are not included, as they are defined automatically, not in the database.
4325 * @return array Array of internal group names
4326 */
4327 public static function getAllGroups() {
4328 global $wgGroupPermissions, $wgRevokePermissions;
4329 return array_diff(
4330 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4331 self::getImplicitGroups()
4332 );
4333 }
4334
4335 /**
4336 * Get a list of all available permissions.
4337 * @return array Array of permission names
4338 */
4339 public static function getAllRights() {
4340 if ( self::$mAllRights === false ) {
4341 global $wgAvailableRights;
4342 if ( count( $wgAvailableRights ) ) {
4343 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4344 } else {
4345 self::$mAllRights = self::$mCoreRights;
4346 }
4347 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
4348 }
4349 return self::$mAllRights;
4350 }
4351
4352 /**
4353 * Get a list of implicit groups
4354 * @return array Array of Strings Array of internal group names
4355 */
4356 public static function getImplicitGroups() {
4357 global $wgImplicitGroups;
4358
4359 $groups = $wgImplicitGroups;
4360 # Deprecated, use $wgImplictGroups instead
4361 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) );
4362
4363 return $groups;
4364 }
4365
4366 /**
4367 * Get the title of a page describing a particular group
4368 *
4369 * @param string $group Internal group name
4370 * @return Title|bool Title of the page if it exists, false otherwise
4371 */
4372 public static function getGroupPage( $group ) {
4373 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4374 if ( $msg->exists() ) {
4375 $title = Title::newFromText( $msg->text() );
4376 if ( is_object( $title ) ) {
4377 return $title;
4378 }
4379 }
4380 return false;
4381 }
4382
4383 /**
4384 * Create a link to the group in HTML, if available;
4385 * else return the group name.
4386 *
4387 * @param string $group Internal name of the group
4388 * @param string $text The text of the link
4389 * @return string HTML link to the group
4390 */
4391 public static function makeGroupLinkHTML( $group, $text = '' ) {
4392 if ( $text == '' ) {
4393 $text = self::getGroupName( $group );
4394 }
4395 $title = self::getGroupPage( $group );
4396 if ( $title ) {
4397 return Linker::link( $title, htmlspecialchars( $text ) );
4398 } else {
4399 return $text;
4400 }
4401 }
4402
4403 /**
4404 * Create a link to the group in Wikitext, if available;
4405 * else return the group name.
4406 *
4407 * @param string $group Internal name of the group
4408 * @param string $text The text of the link
4409 * @return string Wikilink to the group
4410 */
4411 public static function makeGroupLinkWiki( $group, $text = '' ) {
4412 if ( $text == '' ) {
4413 $text = self::getGroupName( $group );
4414 }
4415 $title = self::getGroupPage( $group );
4416 if ( $title ) {
4417 $page = $title->getPrefixedText();
4418 return "[[$page|$text]]";
4419 } else {
4420 return $text;
4421 }
4422 }
4423
4424 /**
4425 * Returns an array of the groups that a particular group can add/remove.
4426 *
4427 * @param string $group The group to check for whether it can add/remove
4428 * @return array array( 'add' => array( addablegroups ),
4429 * 'remove' => array( removablegroups ),
4430 * 'add-self' => array( addablegroups to self),
4431 * 'remove-self' => array( removable groups from self) )
4432 */
4433 public static function changeableByGroup( $group ) {
4434 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4435
4436 $groups = array(
4437 'add' => array(),
4438 'remove' => array(),
4439 'add-self' => array(),
4440 'remove-self' => array()
4441 );
4442
4443 if ( empty( $wgAddGroups[$group] ) ) {
4444 // Don't add anything to $groups
4445 } elseif ( $wgAddGroups[$group] === true ) {
4446 // You get everything
4447 $groups['add'] = self::getAllGroups();
4448 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4449 $groups['add'] = $wgAddGroups[$group];
4450 }
4451
4452 // Same thing for remove
4453 if ( empty( $wgRemoveGroups[$group] ) ) {
4454 } elseif ( $wgRemoveGroups[$group] === true ) {
4455 $groups['remove'] = self::getAllGroups();
4456 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4457 $groups['remove'] = $wgRemoveGroups[$group];
4458 }
4459
4460 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4461 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4462 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4463 if ( is_int( $key ) ) {
4464 $wgGroupsAddToSelf['user'][] = $value;
4465 }
4466 }
4467 }
4468
4469 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4470 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4471 if ( is_int( $key ) ) {
4472 $wgGroupsRemoveFromSelf['user'][] = $value;
4473 }
4474 }
4475 }
4476
4477 // Now figure out what groups the user can add to him/herself
4478 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4479 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4480 // No idea WHY this would be used, but it's there
4481 $groups['add-self'] = User::getAllGroups();
4482 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4483 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4484 }
4485
4486 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4487 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4488 $groups['remove-self'] = User::getAllGroups();
4489 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4490 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4491 }
4492
4493 return $groups;
4494 }
4495
4496 /**
4497 * Returns an array of groups that this user can add and remove
4498 * @return array array( 'add' => array( addablegroups ),
4499 * 'remove' => array( removablegroups ),
4500 * 'add-self' => array( addablegroups to self),
4501 * 'remove-self' => array( removable groups from self) )
4502 */
4503 public function changeableGroups() {
4504 if ( $this->isAllowed( 'userrights' ) ) {
4505 // This group gives the right to modify everything (reverse-
4506 // compatibility with old "userrights lets you change
4507 // everything")
4508 // Using array_merge to make the groups reindexed
4509 $all = array_merge( User::getAllGroups() );
4510 return array(
4511 'add' => $all,
4512 'remove' => $all,
4513 'add-self' => array(),
4514 'remove-self' => array()
4515 );
4516 }
4517
4518 // Okay, it's not so simple, we will have to go through the arrays
4519 $groups = array(
4520 'add' => array(),
4521 'remove' => array(),
4522 'add-self' => array(),
4523 'remove-self' => array()
4524 );
4525 $addergroups = $this->getEffectiveGroups();
4526
4527 foreach ( $addergroups as $addergroup ) {
4528 $groups = array_merge_recursive(
4529 $groups, $this->changeableByGroup( $addergroup )
4530 );
4531 $groups['add'] = array_unique( $groups['add'] );
4532 $groups['remove'] = array_unique( $groups['remove'] );
4533 $groups['add-self'] = array_unique( $groups['add-self'] );
4534 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4535 }
4536 return $groups;
4537 }
4538
4539 /**
4540 * Increment the user's edit-count field.
4541 * Will have no effect for anonymous users.
4542 */
4543 public function incEditCount() {
4544 if ( !$this->isAnon() ) {
4545 $dbw = wfGetDB( DB_MASTER );
4546 $dbw->update(
4547 'user',
4548 array( 'user_editcount=user_editcount+1' ),
4549 array( 'user_id' => $this->getId() ),
4550 __METHOD__
4551 );
4552
4553 // Lazy initialization check...
4554 if ( $dbw->affectedRows() == 0 ) {
4555 // Now here's a goddamn hack...
4556 $dbr = wfGetDB( DB_SLAVE );
4557 if ( $dbr !== $dbw ) {
4558 // If we actually have a slave server, the count is
4559 // at least one behind because the current transaction
4560 // has not been committed and replicated.
4561 $this->initEditCount( 1 );
4562 } else {
4563 // But if DB_SLAVE is selecting the master, then the
4564 // count we just read includes the revision that was
4565 // just added in the working transaction.
4566 $this->initEditCount();
4567 }
4568 }
4569 }
4570 // edit count in user cache too
4571 $this->invalidateCache();
4572 }
4573
4574 /**
4575 * Initialize user_editcount from data out of the revision table
4576 *
4577 * @param int $add Edits to add to the count from the revision table
4578 * @return int Number of edits
4579 */
4580 protected function initEditCount( $add = 0 ) {
4581 // Pull from a slave to be less cruel to servers
4582 // Accuracy isn't the point anyway here
4583 $dbr = wfGetDB( DB_SLAVE );
4584 $count = (int)$dbr->selectField(
4585 'revision',
4586 'COUNT(rev_user)',
4587 array( 'rev_user' => $this->getId() ),
4588 __METHOD__
4589 );
4590 $count = $count + $add;
4591
4592 $dbw = wfGetDB( DB_MASTER );
4593 $dbw->update(
4594 'user',
4595 array( 'user_editcount' => $count ),
4596 array( 'user_id' => $this->getId() ),
4597 __METHOD__
4598 );
4599
4600 return $count;
4601 }
4602
4603 /**
4604 * Get the description of a given right
4605 *
4606 * @param string $right Right to query
4607 * @return string Localized description of the right
4608 */
4609 public static function getRightDescription( $right ) {
4610 $key = "right-$right";
4611 $msg = wfMessage( $key );
4612 return $msg->isBlank() ? $right : $msg->text();
4613 }
4614
4615 /**
4616 * Make an old-style password hash
4617 *
4618 * @param string $password Plain-text password
4619 * @param string $userId User ID
4620 * @return string Password hash
4621 */
4622 public static function oldCrypt( $password, $userId ) {
4623 global $wgPasswordSalt;
4624 if ( $wgPasswordSalt ) {
4625 return md5( $userId . '-' . md5( $password ) );
4626 } else {
4627 return md5( $password );
4628 }
4629 }
4630
4631 /**
4632 * Make a new-style password hash
4633 *
4634 * @param string $password Plain-text password
4635 * @param bool|string $salt Optional salt, may be random or the user ID.
4636 * If unspecified or false, will generate one automatically
4637 * @return string Password hash
4638 */
4639 public static function crypt( $password, $salt = false ) {
4640 global $wgPasswordSalt;
4641
4642 $hash = '';
4643 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4644 return $hash;
4645 }
4646
4647 if ( $wgPasswordSalt ) {
4648 if ( $salt === false ) {
4649 $salt = MWCryptRand::generateHex( 8 );
4650 }
4651 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4652 } else {
4653 return ':A:' . md5( $password );
4654 }
4655 }
4656
4657 /**
4658 * Compare a password hash with a plain-text password. Requires the user
4659 * ID if there's a chance that the hash is an old-style hash.
4660 *
4661 * @param string $hash Password hash
4662 * @param string $password Plain-text password to compare
4663 * @param string|bool $userId User ID for old-style password salt
4664 *
4665 * @return bool
4666 */
4667 public static function comparePasswords( $hash, $password, $userId = false ) {
4668 $type = substr( $hash, 0, 3 );
4669
4670 $result = false;
4671 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4672 return $result;
4673 }
4674
4675 if ( $type == ':A:' ) {
4676 // Unsalted
4677 return md5( $password ) === substr( $hash, 3 );
4678 } elseif ( $type == ':B:' ) {
4679 // Salted
4680 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4681 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4682 } else {
4683 // Old-style
4684 return self::oldCrypt( $password, $userId ) === $hash;
4685 }
4686 }
4687
4688 /**
4689 * Add a newuser log entry for this user.
4690 * Before 1.19 the return value was always true.
4691 *
4692 * @param string|bool $action Account creation type.
4693 * - String, one of the following values:
4694 * - 'create' for an anonymous user creating an account for himself.
4695 * This will force the action's performer to be the created user itself,
4696 * no matter the value of $wgUser
4697 * - 'create2' for a logged in user creating an account for someone else
4698 * - 'byemail' when the created user will receive its password by e-mail
4699 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4700 * - Boolean means whether the account was created by e-mail (deprecated):
4701 * - true will be converted to 'byemail'
4702 * - false will be converted to 'create' if this object is the same as
4703 * $wgUser and to 'create2' otherwise
4704 *
4705 * @param string $reason User supplied reason
4706 *
4707 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4708 */
4709 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4710 global $wgUser, $wgNewUserLog;
4711 if ( empty( $wgNewUserLog ) ) {
4712 return true; // disabled
4713 }
4714
4715 if ( $action === true ) {
4716 $action = 'byemail';
4717 } elseif ( $action === false ) {
4718 if ( $this->getName() == $wgUser->getName() ) {
4719 $action = 'create';
4720 } else {
4721 $action = 'create2';
4722 }
4723 }
4724
4725 if ( $action === 'create' || $action === 'autocreate' ) {
4726 $performer = $this;
4727 } else {
4728 $performer = $wgUser;
4729 }
4730
4731 $logEntry = new ManualLogEntry( 'newusers', $action );
4732 $logEntry->setPerformer( $performer );
4733 $logEntry->setTarget( $this->getUserPage() );
4734 $logEntry->setComment( $reason );
4735 $logEntry->setParameters( array(
4736 '4::userid' => $this->getId(),
4737 ) );
4738 $logid = $logEntry->insert();
4739
4740 if ( $action !== 'autocreate' ) {
4741 $logEntry->publish( $logid );
4742 }
4743
4744 return (int)$logid;
4745 }
4746
4747 /**
4748 * Add an autocreate newuser log entry for this user
4749 * Used by things like CentralAuth and perhaps other authplugins.
4750 * Consider calling addNewUserLogEntry() directly instead.
4751 *
4752 * @return bool
4753 */
4754 public function addNewUserLogEntryAutoCreate() {
4755 $this->addNewUserLogEntry( 'autocreate' );
4756
4757 return true;
4758 }
4759
4760 /**
4761 * Load the user options either from cache, the database or an array
4762 *
4763 * @param array $data Rows for the current user out of the user_properties table
4764 */
4765 protected function loadOptions( $data = null ) {
4766 global $wgContLang;
4767
4768 $this->load();
4769
4770 if ( $this->mOptionsLoaded ) {
4771 return;
4772 }
4773
4774 $this->mOptions = self::getDefaultOptions();
4775
4776 if ( !$this->getId() ) {
4777 // For unlogged-in users, load language/variant options from request.
4778 // There's no need to do it for logged-in users: they can set preferences,
4779 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4780 // so don't override user's choice (especially when the user chooses site default).
4781 $variant = $wgContLang->getDefaultVariant();
4782 $this->mOptions['variant'] = $variant;
4783 $this->mOptions['language'] = $variant;
4784 $this->mOptionsLoaded = true;
4785 return;
4786 }
4787
4788 // Maybe load from the object
4789 if ( !is_null( $this->mOptionOverrides ) ) {
4790 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4791 foreach ( $this->mOptionOverrides as $key => $value ) {
4792 $this->mOptions[$key] = $value;
4793 }
4794 } else {
4795 if ( !is_array( $data ) ) {
4796 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4797 // Load from database
4798 $dbr = wfGetDB( DB_SLAVE );
4799
4800 $res = $dbr->select(
4801 'user_properties',
4802 array( 'up_property', 'up_value' ),
4803 array( 'up_user' => $this->getId() ),
4804 __METHOD__
4805 );
4806
4807 $this->mOptionOverrides = array();
4808 $data = array();
4809 foreach ( $res as $row ) {
4810 $data[$row->up_property] = $row->up_value;
4811 }
4812 }
4813 foreach ( $data as $property => $value ) {
4814 $this->mOptionOverrides[$property] = $value;
4815 $this->mOptions[$property] = $value;
4816 }
4817 }
4818
4819 $this->mOptionsLoaded = true;
4820
4821 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4822 }
4823
4824 /**
4825 * @todo document
4826 */
4827 protected function saveOptions() {
4828 $this->loadOptions();
4829
4830 // Not using getOptions(), to keep hidden preferences in database
4831 $saveOptions = $this->mOptions;
4832
4833 // Allow hooks to abort, for instance to save to a global profile.
4834 // Reset options to default state before saving.
4835 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4836 return;
4837 }
4838
4839 $userId = $this->getId();
4840 $insert_rows = array();
4841 foreach ( $saveOptions as $key => $value ) {
4842 // Don't bother storing default values
4843 $defaultOption = self::getDefaultOption( $key );
4844 if ( ( is_null( $defaultOption ) &&
4845 !( $value === false || is_null( $value ) ) ) ||
4846 $value != $defaultOption
4847 ) {
4848 $insert_rows[] = array(
4849 'up_user' => $userId,
4850 'up_property' => $key,
4851 'up_value' => $value,
4852 );
4853 }
4854 }
4855
4856 $dbw = wfGetDB( DB_MASTER );
4857 // Find and delete any prior preference rows...
4858 $res = $dbw->select( 'user_properties',
4859 array( 'up_property' ), array( 'up_user' => $userId ), __METHOD__ );
4860 $priorKeys = array();
4861 foreach ( $res as $row ) {
4862 $priorKeys[] = $row->up_property;
4863 }
4864 if ( count( $priorKeys ) ) {
4865 // Do the DELETE by PRIMARY KEY for prior rows.
4866 // In the past a very large portion of calls to this function are for setting
4867 // 'rememberpassword' for new accounts (a preference that has since been removed).
4868 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4869 // caused gap locks on [max user ID,+infinity) which caused high contention since
4870 // updates would pile up on each other as they are for higher (newer) user IDs.
4871 // It might not be necessary these days, but it shouldn't hurt either.
4872 $dbw->delete( 'user_properties',
4873 array( 'up_user' => $userId, 'up_property' => $priorKeys ), __METHOD__ );
4874 }
4875 // Insert the new preference rows
4876 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4877 }
4878
4879 /**
4880 * Provide an array of HTML5 attributes to put on an input element
4881 * intended for the user to enter a new password. This may include
4882 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4883 *
4884 * Do *not* use this when asking the user to enter his current password!
4885 * Regardless of configuration, users may have invalid passwords for whatever
4886 * reason (e.g., they were set before requirements were tightened up).
4887 * Only use it when asking for a new password, like on account creation or
4888 * ResetPass.
4889 *
4890 * Obviously, you still need to do server-side checking.
4891 *
4892 * NOTE: A combination of bugs in various browsers means that this function
4893 * actually just returns array() unconditionally at the moment. May as
4894 * well keep it around for when the browser bugs get fixed, though.
4895 *
4896 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4897 *
4898 * @return array Array of HTML attributes suitable for feeding to
4899 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4900 * That will get confused by the boolean attribute syntax used.)
4901 */
4902 public static function passwordChangeInputAttribs() {
4903 global $wgMinimalPasswordLength;
4904
4905 if ( $wgMinimalPasswordLength == 0 ) {
4906 return array();
4907 }
4908
4909 # Note that the pattern requirement will always be satisfied if the
4910 # input is empty, so we need required in all cases.
4911 #
4912 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4913 # if e-mail confirmation is being used. Since HTML5 input validation
4914 # is b0rked anyway in some browsers, just return nothing. When it's
4915 # re-enabled, fix this code to not output required for e-mail
4916 # registration.
4917 #$ret = array( 'required' );
4918 $ret = array();
4919
4920 # We can't actually do this right now, because Opera 9.6 will print out
4921 # the entered password visibly in its error message! When other
4922 # browsers add support for this attribute, or Opera fixes its support,
4923 # we can add support with a version check to avoid doing this on Opera
4924 # versions where it will be a problem. Reported to Opera as
4925 # DSK-262266, but they don't have a public bug tracker for us to follow.
4926 /*
4927 if ( $wgMinimalPasswordLength > 1 ) {
4928 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4929 $ret['title'] = wfMessage( 'passwordtooshort' )
4930 ->numParams( $wgMinimalPasswordLength )->text();
4931 }
4932 */
4933
4934 return $ret;
4935 }
4936
4937 /**
4938 * Return the list of user fields that should be selected to create
4939 * a new user object.
4940 * @return array
4941 */
4942 public static function selectFields() {
4943 return array(
4944 'user_id',
4945 'user_name',
4946 'user_real_name',
4947 'user_password',
4948 'user_newpassword',
4949 'user_newpass_time',
4950 'user_email',
4951 'user_touched',
4952 'user_token',
4953 'user_email_authenticated',
4954 'user_email_token',
4955 'user_email_token_expires',
4956 'user_password_expires',
4957 'user_registration',
4958 'user_editcount',
4959 );
4960 }
4961
4962 /**
4963 * Factory function for fatal permission-denied errors
4964 *
4965 * @since 1.22
4966 * @param string $permission User right required
4967 * @return Status
4968 */
4969 static function newFatalPermissionDeniedStatus( $permission ) {
4970 global $wgLang;
4971
4972 $groups = array_map(
4973 array( 'User', 'makeGroupLinkWiki' ),
4974 User::getGroupsWithPermission( $permission )
4975 );
4976
4977 if ( $groups ) {
4978 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4979 } else {
4980 return Status::newFatal( 'badaccess-group0' );
4981 }
4982 }
4983 }