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