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