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