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