Move up devunt's name to Developers
[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 if ( wfReadOnly() ) {
2256 return;
2257 }
2258
2259 $this->load();
2260 $this->mNewtalk = $val;
2261
2262 if ( $this->isAnon() ) {
2263 $field = 'user_ip';
2264 $id = $this->getName();
2265 } else {
2266 $field = 'user_id';
2267 $id = $this->getId();
2268 }
2269
2270 if ( $val ) {
2271 $changed = $this->updateNewtalk( $field, $id, $curRev );
2272 } else {
2273 $changed = $this->deleteNewtalk( $field, $id );
2274 }
2275
2276 if ( $changed ) {
2277 $this->invalidateCache();
2278 }
2279 }
2280
2281 /**
2282 * Generate a current or new-future timestamp to be stored in the
2283 * user_touched field when we update things.
2284 * @return string Timestamp in TS_MW format
2285 */
2286 private function newTouchedTimestamp() {
2287 global $wgClockSkewFudge;
2288
2289 $time = wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2290 if ( $this->mTouched && $time <= $this->mTouched ) {
2291 $time = wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $this->mTouched ) + 1 );
2292 }
2293
2294 return $time;
2295 }
2296
2297 /**
2298 * Clear user data from memcached.
2299 * Use after applying fun updates to the database; caller's
2300 * responsibility to update user_touched if appropriate.
2301 *
2302 * Called implicitly from invalidateCache() and saveSettings().
2303 */
2304 public function clearSharedCache() {
2305 global $wgMemc;
2306
2307 $this->load();
2308 if ( $this->mId ) {
2309 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2310 }
2311 }
2312
2313 /**
2314 * Immediately touch the user data cache for this account
2315 *
2316 * Calls touch() and removes account data from memcached
2317 */
2318 public function invalidateCache() {
2319 $this->touch();
2320 $this->clearSharedCache();
2321 }
2322
2323 /**
2324 * Update the "touched" timestamp for the user
2325 *
2326 * This is useful on various login/logout events when making sure that
2327 * a browser or proxy that has multiple tenants does not suffer cache
2328 * pollution where the new user sees the old users content. The value
2329 * of getTouched() is checked when determining 304 vs 200 responses.
2330 * Unlike invalidateCache(), this preserves the User object cache and
2331 * avoids database writes.
2332 *
2333 * @since 1.25
2334 */
2335 public function touch() {
2336 $this->load();
2337
2338 if ( $this->mId ) {
2339 $this->mQuickTouched = $this->newTouchedTimestamp();
2340
2341 $cache = ObjectCache::getMainWANInstance();
2342 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId );
2343 $cache->touchCheckKey( $key );
2344 }
2345 }
2346
2347 /**
2348 * Validate the cache for this account.
2349 * @param string $timestamp A timestamp in TS_MW format
2350 * @return bool
2351 */
2352 public function validateCache( $timestamp ) {
2353 return ( $timestamp >= $this->getTouched() );
2354 }
2355
2356 /**
2357 * Get the user touched timestamp
2358 * @return string TS_MW Timestamp
2359 */
2360 public function getTouched() {
2361 $this->load();
2362
2363 if ( $this->mId ) {
2364 if ( $this->mQuickTouched === null ) {
2365 $cache = ObjectCache::getMainWANInstance();
2366 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId );
2367
2368 $timestamp = $cache->getCheckKeyTime( $key );
2369 if ( $timestamp ) {
2370 $this->mQuickTouched = wfTimestamp( TS_MW, $timestamp );
2371 } else {
2372 # Set the timestamp to get HTTP 304 cache hits
2373 $this->touch();
2374 }
2375 }
2376
2377 return max( $this->mTouched, $this->mQuickTouched );
2378 }
2379
2380 return $this->mTouched;
2381 }
2382
2383 /**
2384 * Get the user_touched timestamp field (time of last DB updates)
2385 * @return string TS_MW Timestamp
2386 * @since 1.26
2387 */
2388 protected function getDBTouched() {
2389 $this->load();
2390
2391 return $this->mTouched;
2392 }
2393
2394 /**
2395 * @return Password
2396 * @since 1.24
2397 */
2398 public function getPassword() {
2399 $this->loadPasswords();
2400
2401 return $this->mPassword;
2402 }
2403
2404 /**
2405 * @return Password
2406 * @since 1.24
2407 */
2408 public function getTemporaryPassword() {
2409 $this->loadPasswords();
2410
2411 return $this->mNewpassword;
2412 }
2413
2414 /**
2415 * Set the password and reset the random token.
2416 * Calls through to authentication plugin if necessary;
2417 * will have no effect if the auth plugin refuses to
2418 * pass the change through or if the legal password
2419 * checks fail.
2420 *
2421 * As a special case, setting the password to null
2422 * wipes it, so the account cannot be logged in until
2423 * a new password is set, for instance via e-mail.
2424 *
2425 * @param string $str New password to set
2426 * @throws PasswordError On failure
2427 *
2428 * @return bool
2429 */
2430 public function setPassword( $str ) {
2431 global $wgAuth;
2432
2433 $this->loadPasswords();
2434
2435 if ( $str !== null ) {
2436 if ( !$wgAuth->allowPasswordChange() ) {
2437 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2438 }
2439
2440 $status = $this->checkPasswordValidity( $str );
2441 if ( !$status->isGood() ) {
2442 throw new PasswordError( $status->getMessage()->text() );
2443 }
2444 }
2445
2446 if ( !$wgAuth->setPassword( $this, $str ) ) {
2447 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2448 }
2449
2450 $this->setInternalPassword( $str );
2451
2452 return true;
2453 }
2454
2455 /**
2456 * Set the password and reset the random token unconditionally.
2457 *
2458 * @param string|null $str New password to set or null to set an invalid
2459 * password hash meaning that the user will not be able to log in
2460 * through the web interface.
2461 */
2462 public function setInternalPassword( $str ) {
2463 $this->setToken();
2464
2465 $passwordFactory = self::getPasswordFactory();
2466 $this->mPassword = $passwordFactory->newFromPlaintext( $str );
2467
2468 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
2469 $this->mNewpassTime = null;
2470 }
2471
2472 /**
2473 * Get the user's current token.
2474 * @param bool $forceCreation Force the generation of a new token if the
2475 * user doesn't have one (default=true for backwards compatibility).
2476 * @return string Token
2477 */
2478 public function getToken( $forceCreation = true ) {
2479 $this->load();
2480 if ( !$this->mToken && $forceCreation ) {
2481 $this->setToken();
2482 }
2483 return $this->mToken;
2484 }
2485
2486 /**
2487 * Set the random token (used for persistent authentication)
2488 * Called from loadDefaults() among other places.
2489 *
2490 * @param string|bool $token If specified, set the token to this value
2491 */
2492 public function setToken( $token = false ) {
2493 $this->load();
2494 if ( !$token ) {
2495 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2496 } else {
2497 $this->mToken = $token;
2498 }
2499 }
2500
2501 /**
2502 * Set the password for a password reminder or new account email
2503 *
2504 * @param string $str New password to set or null to set an invalid
2505 * password hash meaning that the user will not be able to use it
2506 * @param bool $throttle If true, reset the throttle timestamp to the present
2507 */
2508 public function setNewpassword( $str, $throttle = true ) {
2509 $this->loadPasswords();
2510
2511 $this->mNewpassword = self::getPasswordFactory()->newFromPlaintext( $str );
2512 if ( $str === null ) {
2513 $this->mNewpassTime = null;
2514 } elseif ( $throttle ) {
2515 $this->mNewpassTime = wfTimestampNow();
2516 }
2517 }
2518
2519 /**
2520 * Has password reminder email been sent within the last
2521 * $wgPasswordReminderResendTime hours?
2522 * @return bool
2523 */
2524 public function isPasswordReminderThrottled() {
2525 global $wgPasswordReminderResendTime;
2526 $this->load();
2527 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2528 return false;
2529 }
2530 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2531 return time() < $expiry;
2532 }
2533
2534 /**
2535 * Get the user's e-mail address
2536 * @return string User's email address
2537 */
2538 public function getEmail() {
2539 $this->load();
2540 Hooks::run( 'UserGetEmail', array( $this, &$this->mEmail ) );
2541 return $this->mEmail;
2542 }
2543
2544 /**
2545 * Get the timestamp of the user's e-mail authentication
2546 * @return string TS_MW timestamp
2547 */
2548 public function getEmailAuthenticationTimestamp() {
2549 $this->load();
2550 Hooks::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2551 return $this->mEmailAuthenticated;
2552 }
2553
2554 /**
2555 * Set the user's e-mail address
2556 * @param string $str New e-mail address
2557 */
2558 public function setEmail( $str ) {
2559 $this->load();
2560 if ( $str == $this->mEmail ) {
2561 return;
2562 }
2563 $this->invalidateEmail();
2564 $this->mEmail = $str;
2565 Hooks::run( 'UserSetEmail', array( $this, &$this->mEmail ) );
2566 }
2567
2568 /**
2569 * Set the user's e-mail address and a confirmation mail if needed.
2570 *
2571 * @since 1.20
2572 * @param string $str New e-mail address
2573 * @return Status
2574 */
2575 public function setEmailWithConfirmation( $str ) {
2576 global $wgEnableEmail, $wgEmailAuthentication;
2577
2578 if ( !$wgEnableEmail ) {
2579 return Status::newFatal( 'emaildisabled' );
2580 }
2581
2582 $oldaddr = $this->getEmail();
2583 if ( $str === $oldaddr ) {
2584 return Status::newGood( true );
2585 }
2586
2587 $this->setEmail( $str );
2588
2589 if ( $str !== '' && $wgEmailAuthentication ) {
2590 // Send a confirmation request to the new address if needed
2591 $type = $oldaddr != '' ? 'changed' : 'set';
2592 $result = $this->sendConfirmationMail( $type );
2593 if ( $result->isGood() ) {
2594 // Say to the caller that a confirmation mail has been sent
2595 $result->value = 'eauth';
2596 }
2597 } else {
2598 $result = Status::newGood( true );
2599 }
2600
2601 return $result;
2602 }
2603
2604 /**
2605 * Get the user's real name
2606 * @return string User's real name
2607 */
2608 public function getRealName() {
2609 if ( !$this->isItemLoaded( 'realname' ) ) {
2610 $this->load();
2611 }
2612
2613 return $this->mRealName;
2614 }
2615
2616 /**
2617 * Set the user's real name
2618 * @param string $str New real name
2619 */
2620 public function setRealName( $str ) {
2621 $this->load();
2622 $this->mRealName = $str;
2623 }
2624
2625 /**
2626 * Get the user's current setting for a given option.
2627 *
2628 * @param string $oname The option to check
2629 * @param string $defaultOverride A default value returned if the option does not exist
2630 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2631 * @return string User's current value for the option
2632 * @see getBoolOption()
2633 * @see getIntOption()
2634 */
2635 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2636 global $wgHiddenPrefs;
2637 $this->loadOptions();
2638
2639 # We want 'disabled' preferences to always behave as the default value for
2640 # users, even if they have set the option explicitly in their settings (ie they
2641 # set it, and then it was disabled removing their ability to change it). But
2642 # we don't want to erase the preferences in the database in case the preference
2643 # is re-enabled again. So don't touch $mOptions, just override the returned value
2644 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2645 return self::getDefaultOption( $oname );
2646 }
2647
2648 if ( array_key_exists( $oname, $this->mOptions ) ) {
2649 return $this->mOptions[$oname];
2650 } else {
2651 return $defaultOverride;
2652 }
2653 }
2654
2655 /**
2656 * Get all user's options
2657 *
2658 * @param int $flags Bitwise combination of:
2659 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2660 * to the default value. (Since 1.25)
2661 * @return array
2662 */
2663 public function getOptions( $flags = 0 ) {
2664 global $wgHiddenPrefs;
2665 $this->loadOptions();
2666 $options = $this->mOptions;
2667
2668 # We want 'disabled' preferences to always behave as the default value for
2669 # users, even if they have set the option explicitly in their settings (ie they
2670 # set it, and then it was disabled removing their ability to change it). But
2671 # we don't want to erase the preferences in the database in case the preference
2672 # is re-enabled again. So don't touch $mOptions, just override the returned value
2673 foreach ( $wgHiddenPrefs as $pref ) {
2674 $default = self::getDefaultOption( $pref );
2675 if ( $default !== null ) {
2676 $options[$pref] = $default;
2677 }
2678 }
2679
2680 if ( $flags & self::GETOPTIONS_EXCLUDE_DEFAULTS ) {
2681 $options = array_diff_assoc( $options, self::getDefaultOptions() );
2682 }
2683
2684 return $options;
2685 }
2686
2687 /**
2688 * Get the user's current setting for a given option, as a boolean value.
2689 *
2690 * @param string $oname The option to check
2691 * @return bool User's current value for the option
2692 * @see getOption()
2693 */
2694 public function getBoolOption( $oname ) {
2695 return (bool)$this->getOption( $oname );
2696 }
2697
2698 /**
2699 * Get the user's current setting for a given option, as an integer value.
2700 *
2701 * @param string $oname The option to check
2702 * @param int $defaultOverride A default value returned if the option does not exist
2703 * @return int User's current value for the option
2704 * @see getOption()
2705 */
2706 public function getIntOption( $oname, $defaultOverride = 0 ) {
2707 $val = $this->getOption( $oname );
2708 if ( $val == '' ) {
2709 $val = $defaultOverride;
2710 }
2711 return intval( $val );
2712 }
2713
2714 /**
2715 * Set the given option for a user.
2716 *
2717 * You need to call saveSettings() to actually write to the database.
2718 *
2719 * @param string $oname The option to set
2720 * @param mixed $val New value to set
2721 */
2722 public function setOption( $oname, $val ) {
2723 $this->loadOptions();
2724
2725 // Explicitly NULL values should refer to defaults
2726 if ( is_null( $val ) ) {
2727 $val = self::getDefaultOption( $oname );
2728 }
2729
2730 $this->mOptions[$oname] = $val;
2731 }
2732
2733 /**
2734 * Get a token stored in the preferences (like the watchlist one),
2735 * resetting it if it's empty (and saving changes).
2736 *
2737 * @param string $oname The option name to retrieve the token from
2738 * @return string|bool User's current value for the option, or false if this option is disabled.
2739 * @see resetTokenFromOption()
2740 * @see getOption()
2741 */
2742 public function getTokenFromOption( $oname ) {
2743 global $wgHiddenPrefs;
2744 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2745 return false;
2746 }
2747
2748 $token = $this->getOption( $oname );
2749 if ( !$token ) {
2750 $token = $this->resetTokenFromOption( $oname );
2751 if ( !wfReadOnly() ) {
2752 $this->saveSettings();
2753 }
2754 }
2755 return $token;
2756 }
2757
2758 /**
2759 * Reset a token stored in the preferences (like the watchlist one).
2760 * *Does not* save user's preferences (similarly to setOption()).
2761 *
2762 * @param string $oname The option name to reset the token in
2763 * @return string|bool New token value, or false if this option is disabled.
2764 * @see getTokenFromOption()
2765 * @see setOption()
2766 */
2767 public function resetTokenFromOption( $oname ) {
2768 global $wgHiddenPrefs;
2769 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2770 return false;
2771 }
2772
2773 $token = MWCryptRand::generateHex( 40 );
2774 $this->setOption( $oname, $token );
2775 return $token;
2776 }
2777
2778 /**
2779 * Return a list of the types of user options currently returned by
2780 * User::getOptionKinds().
2781 *
2782 * Currently, the option kinds are:
2783 * - 'registered' - preferences which are registered in core MediaWiki or
2784 * by extensions using the UserGetDefaultOptions hook.
2785 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2786 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2787 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2788 * be used by user scripts.
2789 * - 'special' - "preferences" that are not accessible via User::getOptions
2790 * or User::setOptions.
2791 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2792 * These are usually legacy options, removed in newer versions.
2793 *
2794 * The API (and possibly others) use this function to determine the possible
2795 * option types for validation purposes, so make sure to update this when a
2796 * new option kind is added.
2797 *
2798 * @see User::getOptionKinds
2799 * @return array Option kinds
2800 */
2801 public static function listOptionKinds() {
2802 return array(
2803 'registered',
2804 'registered-multiselect',
2805 'registered-checkmatrix',
2806 'userjs',
2807 'special',
2808 'unused'
2809 );
2810 }
2811
2812 /**
2813 * Return an associative array mapping preferences keys to the kind of a preference they're
2814 * used for. Different kinds are handled differently when setting or reading preferences.
2815 *
2816 * See User::listOptionKinds for the list of valid option types that can be provided.
2817 *
2818 * @see User::listOptionKinds
2819 * @param IContextSource $context
2820 * @param array $options Assoc. array with options keys to check as keys.
2821 * Defaults to $this->mOptions.
2822 * @return array The key => kind mapping data
2823 */
2824 public function getOptionKinds( IContextSource $context, $options = null ) {
2825 $this->loadOptions();
2826 if ( $options === null ) {
2827 $options = $this->mOptions;
2828 }
2829
2830 $prefs = Preferences::getPreferences( $this, $context );
2831 $mapping = array();
2832
2833 // Pull out the "special" options, so they don't get converted as
2834 // multiselect or checkmatrix.
2835 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2836 foreach ( $specialOptions as $name => $value ) {
2837 unset( $prefs[$name] );
2838 }
2839
2840 // Multiselect and checkmatrix options are stored in the database with
2841 // one key per option, each having a boolean value. Extract those keys.
2842 $multiselectOptions = array();
2843 foreach ( $prefs as $name => $info ) {
2844 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2845 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2846 $opts = HTMLFormField::flattenOptions( $info['options'] );
2847 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2848
2849 foreach ( $opts as $value ) {
2850 $multiselectOptions["$prefix$value"] = true;
2851 }
2852
2853 unset( $prefs[$name] );
2854 }
2855 }
2856 $checkmatrixOptions = array();
2857 foreach ( $prefs as $name => $info ) {
2858 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2859 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2860 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2861 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2862 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2863
2864 foreach ( $columns as $column ) {
2865 foreach ( $rows as $row ) {
2866 $checkmatrixOptions["$prefix$column-$row"] = true;
2867 }
2868 }
2869
2870 unset( $prefs[$name] );
2871 }
2872 }
2873
2874 // $value is ignored
2875 foreach ( $options as $key => $value ) {
2876 if ( isset( $prefs[$key] ) ) {
2877 $mapping[$key] = 'registered';
2878 } elseif ( isset( $multiselectOptions[$key] ) ) {
2879 $mapping[$key] = 'registered-multiselect';
2880 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2881 $mapping[$key] = 'registered-checkmatrix';
2882 } elseif ( isset( $specialOptions[$key] ) ) {
2883 $mapping[$key] = 'special';
2884 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2885 $mapping[$key] = 'userjs';
2886 } else {
2887 $mapping[$key] = 'unused';
2888 }
2889 }
2890
2891 return $mapping;
2892 }
2893
2894 /**
2895 * Reset certain (or all) options to the site defaults
2896 *
2897 * The optional parameter determines which kinds of preferences will be reset.
2898 * Supported values are everything that can be reported by getOptionKinds()
2899 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2900 *
2901 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2902 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2903 * for backwards-compatibility.
2904 * @param IContextSource|null $context Context source used when $resetKinds
2905 * does not contain 'all', passed to getOptionKinds().
2906 * Defaults to RequestContext::getMain() when null.
2907 */
2908 public function resetOptions(
2909 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2910 IContextSource $context = null
2911 ) {
2912 $this->load();
2913 $defaultOptions = self::getDefaultOptions();
2914
2915 if ( !is_array( $resetKinds ) ) {
2916 $resetKinds = array( $resetKinds );
2917 }
2918
2919 if ( in_array( 'all', $resetKinds ) ) {
2920 $newOptions = $defaultOptions;
2921 } else {
2922 if ( $context === null ) {
2923 $context = RequestContext::getMain();
2924 }
2925
2926 $optionKinds = $this->getOptionKinds( $context );
2927 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2928 $newOptions = array();
2929
2930 // Use default values for the options that should be deleted, and
2931 // copy old values for the ones that shouldn't.
2932 foreach ( $this->mOptions as $key => $value ) {
2933 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2934 if ( array_key_exists( $key, $defaultOptions ) ) {
2935 $newOptions[$key] = $defaultOptions[$key];
2936 }
2937 } else {
2938 $newOptions[$key] = $value;
2939 }
2940 }
2941 }
2942
2943 Hooks::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions, $resetKinds ) );
2944
2945 $this->mOptions = $newOptions;
2946 $this->mOptionsLoaded = true;
2947 }
2948
2949 /**
2950 * Get the user's preferred date format.
2951 * @return string User's preferred date format
2952 */
2953 public function getDatePreference() {
2954 // Important migration for old data rows
2955 if ( is_null( $this->mDatePreference ) ) {
2956 global $wgLang;
2957 $value = $this->getOption( 'date' );
2958 $map = $wgLang->getDatePreferenceMigrationMap();
2959 if ( isset( $map[$value] ) ) {
2960 $value = $map[$value];
2961 }
2962 $this->mDatePreference = $value;
2963 }
2964 return $this->mDatePreference;
2965 }
2966
2967 /**
2968 * Determine based on the wiki configuration and the user's options,
2969 * whether this user must be over HTTPS no matter what.
2970 *
2971 * @return bool
2972 */
2973 public function requiresHTTPS() {
2974 global $wgSecureLogin;
2975 if ( !$wgSecureLogin ) {
2976 return false;
2977 } else {
2978 $https = $this->getBoolOption( 'prefershttps' );
2979 Hooks::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2980 if ( $https ) {
2981 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2982 }
2983 return $https;
2984 }
2985 }
2986
2987 /**
2988 * Get the user preferred stub threshold
2989 *
2990 * @return int
2991 */
2992 public function getStubThreshold() {
2993 global $wgMaxArticleSize; # Maximum article size, in Kb
2994 $threshold = $this->getIntOption( 'stubthreshold' );
2995 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2996 // If they have set an impossible value, disable the preference
2997 // so we can use the parser cache again.
2998 $threshold = 0;
2999 }
3000 return $threshold;
3001 }
3002
3003 /**
3004 * Get the permissions this user has.
3005 * @return array Array of String permission names
3006 */
3007 public function getRights() {
3008 if ( is_null( $this->mRights ) ) {
3009 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
3010 Hooks::run( 'UserGetRights', array( $this, &$this->mRights ) );
3011 // Force reindexation of rights when a hook has unset one of them
3012 $this->mRights = array_values( array_unique( $this->mRights ) );
3013 }
3014 return $this->mRights;
3015 }
3016
3017 /**
3018 * Get the list of explicit group memberships this user has.
3019 * The implicit * and user groups are not included.
3020 * @return array Array of String internal group names
3021 */
3022 public function getGroups() {
3023 $this->load();
3024 $this->loadGroups();
3025 return $this->mGroups;
3026 }
3027
3028 /**
3029 * Get the list of implicit group memberships this user has.
3030 * This includes all explicit groups, plus 'user' if logged in,
3031 * '*' for all accounts, and autopromoted groups
3032 * @param bool $recache Whether to avoid the cache
3033 * @return array Array of String internal group names
3034 */
3035 public function getEffectiveGroups( $recache = false ) {
3036 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
3037 $this->mEffectiveGroups = array_unique( array_merge(
3038 $this->getGroups(), // explicit groups
3039 $this->getAutomaticGroups( $recache ) // implicit groups
3040 ) );
3041 // Hook for additional groups
3042 Hooks::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
3043 // Force reindexation of groups when a hook has unset one of them
3044 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
3045 }
3046 return $this->mEffectiveGroups;
3047 }
3048
3049 /**
3050 * Get the list of implicit group memberships this user has.
3051 * This includes 'user' if logged in, '*' for all accounts,
3052 * and autopromoted groups
3053 * @param bool $recache Whether to avoid the cache
3054 * @return array Array of String internal group names
3055 */
3056 public function getAutomaticGroups( $recache = false ) {
3057 if ( $recache || is_null( $this->mImplicitGroups ) ) {
3058 $this->mImplicitGroups = array( '*' );
3059 if ( $this->getId() ) {
3060 $this->mImplicitGroups[] = 'user';
3061
3062 $this->mImplicitGroups = array_unique( array_merge(
3063 $this->mImplicitGroups,
3064 Autopromote::getAutopromoteGroups( $this )
3065 ) );
3066 }
3067 if ( $recache ) {
3068 // Assure data consistency with rights/groups,
3069 // as getEffectiveGroups() depends on this function
3070 $this->mEffectiveGroups = null;
3071 }
3072 }
3073 return $this->mImplicitGroups;
3074 }
3075
3076 /**
3077 * Returns the groups the user has belonged to.
3078 *
3079 * The user may still belong to the returned groups. Compare with getGroups().
3080 *
3081 * The function will not return groups the user had belonged to before MW 1.17
3082 *
3083 * @return array Names of the groups the user has belonged to.
3084 */
3085 public function getFormerGroups() {
3086 $this->load();
3087
3088 if ( is_null( $this->mFormerGroups ) ) {
3089 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
3090 ? wfGetDB( DB_MASTER )
3091 : wfGetDB( DB_SLAVE );
3092 $res = $db->select( 'user_former_groups',
3093 array( 'ufg_group' ),
3094 array( 'ufg_user' => $this->mId ),
3095 __METHOD__ );
3096 $this->mFormerGroups = array();
3097 foreach ( $res as $row ) {
3098 $this->mFormerGroups[] = $row->ufg_group;
3099 }
3100 }
3101
3102 return $this->mFormerGroups;
3103 }
3104
3105 /**
3106 * Get the user's edit count.
3107 * @return int|null Null for anonymous users
3108 */
3109 public function getEditCount() {
3110 if ( !$this->getId() ) {
3111 return null;
3112 }
3113
3114 if ( $this->mEditCount === null ) {
3115 /* Populate the count, if it has not been populated yet */
3116 $dbr = wfGetDB( DB_SLAVE );
3117 // check if the user_editcount field has been initialized
3118 $count = $dbr->selectField(
3119 'user', 'user_editcount',
3120 array( 'user_id' => $this->mId ),
3121 __METHOD__
3122 );
3123
3124 if ( $count === null ) {
3125 // it has not been initialized. do so.
3126 $count = $this->initEditCount();
3127 }
3128 $this->mEditCount = $count;
3129 }
3130 return (int)$this->mEditCount;
3131 }
3132
3133 /**
3134 * Add the user to the given group.
3135 * This takes immediate effect.
3136 * @param string $group Name of the group to add
3137 * @return bool
3138 */
3139 public function addGroup( $group ) {
3140 $this->load();
3141
3142 if ( !Hooks::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3143 return false;
3144 }
3145
3146 $dbw = wfGetDB( DB_MASTER );
3147 if ( $this->getId() ) {
3148 $dbw->insert( 'user_groups',
3149 array(
3150 'ug_user' => $this->getID(),
3151 'ug_group' => $group,
3152 ),
3153 __METHOD__,
3154 array( 'IGNORE' ) );
3155 }
3156
3157 $this->loadGroups();
3158 $this->mGroups[] = $group;
3159 // In case loadGroups was not called before, we now have the right twice.
3160 // Get rid of the duplicate.
3161 $this->mGroups = array_unique( $this->mGroups );
3162
3163 // Refresh the groups caches, and clear the rights cache so it will be
3164 // refreshed on the next call to $this->getRights().
3165 $this->getEffectiveGroups( true );
3166 $this->mRights = null;
3167
3168 $this->invalidateCache();
3169
3170 return true;
3171 }
3172
3173 /**
3174 * Remove the user from the given group.
3175 * This takes immediate effect.
3176 * @param string $group Name of the group to remove
3177 * @return bool
3178 */
3179 public function removeGroup( $group ) {
3180 $this->load();
3181 if ( !Hooks::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3182 return false;
3183 }
3184
3185 $dbw = wfGetDB( DB_MASTER );
3186 $dbw->delete( 'user_groups',
3187 array(
3188 'ug_user' => $this->getID(),
3189 'ug_group' => $group,
3190 ), __METHOD__
3191 );
3192 // Remember that the user was in this group
3193 $dbw->insert( 'user_former_groups',
3194 array(
3195 'ufg_user' => $this->getID(),
3196 'ufg_group' => $group,
3197 ),
3198 __METHOD__,
3199 array( 'IGNORE' )
3200 );
3201
3202 $this->loadGroups();
3203 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
3204
3205 // Refresh the groups caches, and clear the rights cache so it will be
3206 // refreshed on the next call to $this->getRights().
3207 $this->getEffectiveGroups( true );
3208 $this->mRights = null;
3209
3210 $this->invalidateCache();
3211
3212 return true;
3213 }
3214
3215 /**
3216 * Get whether the user is logged in
3217 * @return bool
3218 */
3219 public function isLoggedIn() {
3220 return $this->getID() != 0;
3221 }
3222
3223 /**
3224 * Get whether the user is anonymous
3225 * @return bool
3226 */
3227 public function isAnon() {
3228 return !$this->isLoggedIn();
3229 }
3230
3231 /**
3232 * Check if user is allowed to access a feature / make an action
3233 *
3234 * @param string $permissions,... Permissions to test
3235 * @return bool True if user is allowed to perform *any* of the given actions
3236 */
3237 public function isAllowedAny( /*...*/ ) {
3238 $permissions = func_get_args();
3239 foreach ( $permissions as $permission ) {
3240 if ( $this->isAllowed( $permission ) ) {
3241 return true;
3242 }
3243 }
3244 return false;
3245 }
3246
3247 /**
3248 *
3249 * @param string $permissions,... Permissions to test
3250 * @return bool True if the user is allowed to perform *all* of the given actions
3251 */
3252 public function isAllowedAll( /*...*/ ) {
3253 $permissions = func_get_args();
3254 foreach ( $permissions as $permission ) {
3255 if ( !$this->isAllowed( $permission ) ) {
3256 return false;
3257 }
3258 }
3259 return true;
3260 }
3261
3262 /**
3263 * Internal mechanics of testing a permission
3264 * @param string $action
3265 * @return bool
3266 */
3267 public function isAllowed( $action = '' ) {
3268 if ( $action === '' ) {
3269 return true; // In the spirit of DWIM
3270 }
3271 // Patrolling may not be enabled
3272 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3273 global $wgUseRCPatrol, $wgUseNPPatrol;
3274 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3275 return false;
3276 }
3277 }
3278 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3279 // by misconfiguration: 0 == 'foo'
3280 return in_array( $action, $this->getRights(), true );
3281 }
3282
3283 /**
3284 * Check whether to enable recent changes patrol features for this user
3285 * @return bool True or false
3286 */
3287 public function useRCPatrol() {
3288 global $wgUseRCPatrol;
3289 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3290 }
3291
3292 /**
3293 * Check whether to enable new pages patrol features for this user
3294 * @return bool True or false
3295 */
3296 public function useNPPatrol() {
3297 global $wgUseRCPatrol, $wgUseNPPatrol;
3298 return (
3299 ( $wgUseRCPatrol || $wgUseNPPatrol )
3300 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3301 );
3302 }
3303
3304 /**
3305 * Get the WebRequest object to use with this object
3306 *
3307 * @return WebRequest
3308 */
3309 public function getRequest() {
3310 if ( $this->mRequest ) {
3311 return $this->mRequest;
3312 } else {
3313 global $wgRequest;
3314 return $wgRequest;
3315 }
3316 }
3317
3318 /**
3319 * Get the current skin, loading it if required
3320 * @return Skin The current skin
3321 * @todo FIXME: Need to check the old failback system [AV]
3322 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3323 */
3324 public function getSkin() {
3325 wfDeprecated( __METHOD__, '1.18' );
3326 return RequestContext::getMain()->getSkin();
3327 }
3328
3329 /**
3330 * Get a WatchedItem for this user and $title.
3331 *
3332 * @since 1.22 $checkRights parameter added
3333 * @param Title $title
3334 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3335 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3336 * @return WatchedItem
3337 */
3338 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3339 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3340
3341 if ( isset( $this->mWatchedItems[$key] ) ) {
3342 return $this->mWatchedItems[$key];
3343 }
3344
3345 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3346 $this->mWatchedItems = array();
3347 }
3348
3349 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3350 return $this->mWatchedItems[$key];
3351 }
3352
3353 /**
3354 * Check the watched status of an article.
3355 * @since 1.22 $checkRights parameter added
3356 * @param Title $title Title of the article to look at
3357 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3358 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3359 * @return bool
3360 */
3361 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3362 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3363 }
3364
3365 /**
3366 * Watch an article.
3367 * @since 1.22 $checkRights parameter added
3368 * @param Title $title Title of the article to look at
3369 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3370 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3371 */
3372 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3373 $this->getWatchedItem( $title, $checkRights )->addWatch();
3374 $this->invalidateCache();
3375 }
3376
3377 /**
3378 * Stop watching an article.
3379 * @since 1.22 $checkRights parameter added
3380 * @param Title $title Title of the article to look at
3381 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3382 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3383 */
3384 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3385 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3386 $this->invalidateCache();
3387 }
3388
3389 /**
3390 * Clear the user's notification timestamp for the given title.
3391 * If e-notif e-mails are on, they will receive notification mails on
3392 * the next change of the page if it's watched etc.
3393 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3394 * @param Title $title Title of the article to look at
3395 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3396 */
3397 public function clearNotification( &$title, $oldid = 0 ) {
3398 global $wgUseEnotif, $wgShowUpdatedMarker;
3399
3400 // Do nothing if the database is locked to writes
3401 if ( wfReadOnly() ) {
3402 return;
3403 }
3404
3405 // Do nothing if not allowed to edit the watchlist
3406 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3407 return;
3408 }
3409
3410 // If we're working on user's talk page, we should update the talk page message indicator
3411 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3412 if ( !Hooks::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3413 return;
3414 }
3415
3416 $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null;
3417
3418 if ( !$oldid || !$nextid ) {
3419 // If we're looking at the latest revision, we should definitely clear it
3420 $this->setNewtalk( false );
3421 } else {
3422 // Otherwise we should update its revision, if it's present
3423 if ( $this->getNewtalk() ) {
3424 // Naturally the other one won't clear by itself
3425 $this->setNewtalk( false );
3426 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3427 }
3428 }
3429 }
3430
3431 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3432 return;
3433 }
3434
3435 if ( $this->isAnon() ) {
3436 // Nothing else to do...
3437 return;
3438 }
3439
3440 // Only update the timestamp if the page is being watched.
3441 // The query to find out if it is watched is cached both in memcached and per-invocation,
3442 // and when it does have to be executed, it can be on a slave
3443 // If this is the user's newtalk page, we always update the timestamp
3444 $force = '';
3445 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3446 $force = 'force';
3447 }
3448
3449 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3450 $force, $oldid, WatchedItem::DEFERRED
3451 );
3452 }
3453
3454 /**
3455 * Resets all of the given user's page-change notification timestamps.
3456 * If e-notif e-mails are on, they will receive notification mails on
3457 * the next change of any watched page.
3458 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3459 */
3460 public function clearAllNotifications() {
3461 if ( wfReadOnly() ) {
3462 return;
3463 }
3464
3465 // Do nothing if not allowed to edit the watchlist
3466 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3467 return;
3468 }
3469
3470 global $wgUseEnotif, $wgShowUpdatedMarker;
3471 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3472 $this->setNewtalk( false );
3473 return;
3474 }
3475 $id = $this->getId();
3476 if ( $id != 0 ) {
3477 $dbw = wfGetDB( DB_MASTER );
3478 $dbw->update( 'watchlist',
3479 array( /* SET */ 'wl_notificationtimestamp' => null ),
3480 array( /* WHERE */ 'wl_user' => $id ),
3481 __METHOD__
3482 );
3483 // We also need to clear here the "you have new message" notification for the own user_talk page;
3484 // it's cleared one page view later in WikiPage::doViewUpdates().
3485 }
3486 }
3487
3488 /**
3489 * Set a cookie on the user's client. Wrapper for
3490 * WebResponse::setCookie
3491 * @param string $name Name of the cookie to set
3492 * @param string $value Value to set
3493 * @param int $exp Expiration time, as a UNIX time value;
3494 * if 0 or not specified, use the default $wgCookieExpiration
3495 * @param bool $secure
3496 * true: Force setting the secure attribute when setting the cookie
3497 * false: Force NOT setting the secure attribute when setting the cookie
3498 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3499 * @param array $params Array of options sent passed to WebResponse::setcookie()
3500 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3501 * is passed.
3502 */
3503 protected function setCookie(
3504 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3505 ) {
3506 if ( $request === null ) {
3507 $request = $this->getRequest();
3508 }
3509 $params['secure'] = $secure;
3510 $request->response()->setcookie( $name, $value, $exp, $params );
3511 }
3512
3513 /**
3514 * Clear a cookie on the user's client
3515 * @param string $name Name of the cookie to clear
3516 * @param bool $secure
3517 * true: Force setting the secure attribute when setting the cookie
3518 * false: Force NOT setting the secure attribute when setting the cookie
3519 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3520 * @param array $params Array of options sent passed to WebResponse::setcookie()
3521 */
3522 protected function clearCookie( $name, $secure = null, $params = array() ) {
3523 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3524 }
3525
3526 /**
3527 * Set the default cookies for this session on the user's client.
3528 *
3529 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3530 * is passed.
3531 * @param bool $secure Whether to force secure/insecure cookies or use default
3532 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3533 */
3534 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3535 if ( $request === null ) {
3536 $request = $this->getRequest();
3537 }
3538
3539 $this->load();
3540 if ( 0 == $this->mId ) {
3541 return;
3542 }
3543 if ( !$this->mToken ) {
3544 // When token is empty or NULL generate a new one and then save it to the database
3545 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3546 // Simply by setting every cell in the user_token column to NULL and letting them be
3547 // regenerated as users log back into the wiki.
3548 $this->setToken();
3549 if ( !wfReadOnly() ) {
3550 $this->saveSettings();
3551 }
3552 }
3553 $session = array(
3554 'wsUserID' => $this->mId,
3555 'wsToken' => $this->mToken,
3556 'wsUserName' => $this->getName()
3557 );
3558 $cookies = array(
3559 'UserID' => $this->mId,
3560 'UserName' => $this->getName(),
3561 );
3562 if ( $rememberMe ) {
3563 $cookies['Token'] = $this->mToken;
3564 } else {
3565 $cookies['Token'] = false;
3566 }
3567
3568 Hooks::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3569
3570 foreach ( $session as $name => $value ) {
3571 $request->setSessionData( $name, $value );
3572 }
3573 foreach ( $cookies as $name => $value ) {
3574 if ( $value === false ) {
3575 $this->clearCookie( $name );
3576 } else {
3577 $this->setCookie( $name, $value, 0, $secure, array(), $request );
3578 }
3579 }
3580
3581 /**
3582 * If wpStickHTTPS was selected, also set an insecure cookie that
3583 * will cause the site to redirect the user to HTTPS, if they access
3584 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3585 * as the one set by centralauth (bug 53538). Also set it to session, or
3586 * standard time setting, based on if rememberme was set.
3587 */
3588 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3589 $this->setCookie(
3590 'forceHTTPS',
3591 'true',
3592 $rememberMe ? 0 : null,
3593 false,
3594 array( 'prefix' => '' ) // no prefix
3595 );
3596 }
3597 }
3598
3599 /**
3600 * Log this user out.
3601 */
3602 public function logout() {
3603 if ( Hooks::run( 'UserLogout', array( &$this ) ) ) {
3604 $this->doLogout();
3605 }
3606 }
3607
3608 /**
3609 * Clear the user's cookies and session, and reset the instance cache.
3610 * @see logout()
3611 */
3612 public function doLogout() {
3613 $this->clearInstanceCache( 'defaults' );
3614
3615 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3616
3617 $this->clearCookie( 'UserID' );
3618 $this->clearCookie( 'Token' );
3619 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3620
3621 // Remember when user logged out, to prevent seeing cached pages
3622 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3623 }
3624
3625 /**
3626 * Save this user's settings into the database.
3627 * @todo Only rarely do all these fields need to be set!
3628 */
3629 public function saveSettings() {
3630 global $wgAuth;
3631
3632 if ( wfReadOnly() ) {
3633 // @TODO: caller should deal with this instead!
3634 // This should really just be an exception.
3635 MWExceptionHandler::logException( new DBExpectedError(
3636 null,
3637 "Could not update user with ID '{$this->mId}'; DB is read-only."
3638 ) );
3639 return;
3640 }
3641
3642 $this->load();
3643 $this->loadPasswords();
3644 if ( 0 == $this->mId ) {
3645 return; // anon
3646 }
3647
3648 // This method is for updating existing users, so the user should
3649 // have been loaded from the master to begin with to avoid problems.
3650 if ( !( $this->queryFlagsUsed & self::READ_LATEST ) ) {
3651 wfWarn( "Attempting to save slave-loaded User object with ID '{$this->mId}'." );
3652 }
3653
3654 // Get a new user_touched that is higher than the old one.
3655 // This will be used for a CAS check as a last-resort safety
3656 // check against race conditions and slave lag.
3657 $oldTouched = $this->mTouched;
3658 $newTouched = $this->newTouchedTimestamp();
3659
3660 if ( !$wgAuth->allowSetLocalPassword() ) {
3661 $this->mPassword = self::getPasswordFactory()->newFromCiphertext( null );
3662 }
3663
3664 $dbw = wfGetDB( DB_MASTER );
3665 $dbw->update( 'user',
3666 array( /* SET */
3667 'user_name' => $this->mName,
3668 'user_password' => $this->mPassword->toString(),
3669 'user_newpassword' => $this->mNewpassword->toString(),
3670 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3671 'user_real_name' => $this->mRealName,
3672 'user_email' => $this->mEmail,
3673 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3674 'user_touched' => $dbw->timestamp( $newTouched ),
3675 'user_token' => strval( $this->mToken ),
3676 'user_email_token' => $this->mEmailToken,
3677 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3678 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3679 ), array( /* WHERE */
3680 'user_id' => $this->mId,
3681 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3682 ), __METHOD__
3683 );
3684
3685 if ( !$dbw->affectedRows() ) {
3686 // Maybe the problem was a missed cache update; clear it to be safe
3687 $this->clearSharedCache();
3688 // User was changed in the meantime or loaded with stale data
3689 MWExceptionHandler::logException( new MWException(
3690 "CAS update failed on user_touched for user ID '{$this->mId}';" .
3691 "the version of the user to be saved is older than the current version."
3692 ) );
3693
3694 return;
3695 }
3696
3697 $this->mTouched = $newTouched;
3698 $this->saveOptions();
3699
3700 Hooks::run( 'UserSaveSettings', array( $this ) );
3701 $this->clearSharedCache();
3702 $this->getUserPage()->invalidateCache();
3703
3704 // T95839: clear the cache again post-commit to reduce race conditions
3705 // where stale values are written back to the cache by other threads.
3706 // Note: this *still* doesn't deal with REPEATABLE-READ snapshot lag...
3707 $that = $this;
3708 $dbw->onTransactionIdle( function() use ( $that ) {
3709 $that->clearSharedCache();
3710 } );
3711 }
3712
3713 /**
3714 * If only this user's username is known, and it exists, return the user ID.
3715 * @return int
3716 */
3717 public function idForName() {
3718 $s = trim( $this->getName() );
3719 if ( $s === '' ) {
3720 return 0;
3721 }
3722
3723 $dbr = wfGetDB( DB_SLAVE );
3724 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3725 if ( $id === false ) {
3726 $id = 0;
3727 }
3728 return $id;
3729 }
3730
3731 /**
3732 * Add a user to the database, return the user object
3733 *
3734 * @param string $name Username to add
3735 * @param array $params Array of Strings Non-default parameters to save to
3736 * the database as user_* fields:
3737 * - password: The user's password hash. Password logins will be disabled
3738 * if this is omitted.
3739 * - newpassword: Hash for a temporary password that has been mailed to
3740 * the user.
3741 * - email: The user's email address.
3742 * - email_authenticated: The email authentication timestamp.
3743 * - real_name: The user's real name.
3744 * - options: An associative array of non-default options.
3745 * - token: Random authentication token. Do not set.
3746 * - registration: Registration timestamp. Do not set.
3747 *
3748 * @return User|null User object, or null if the username already exists.
3749 */
3750 public static function createNew( $name, $params = array() ) {
3751 $user = new User;
3752 $user->load();
3753 $user->loadPasswords();
3754 $user->setToken(); // init token
3755 if ( isset( $params['options'] ) ) {
3756 $user->mOptions = $params['options'] + (array)$user->mOptions;
3757 unset( $params['options'] );
3758 }
3759 $dbw = wfGetDB( DB_MASTER );
3760 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3761
3762 $fields = array(
3763 'user_id' => $seqVal,
3764 'user_name' => $name,
3765 'user_password' => $user->mPassword->toString(),
3766 'user_newpassword' => $user->mNewpassword->toString(),
3767 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3768 'user_email' => $user->mEmail,
3769 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3770 'user_real_name' => $user->mRealName,
3771 'user_token' => strval( $user->mToken ),
3772 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3773 'user_editcount' => 0,
3774 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3775 );
3776 foreach ( $params as $name => $value ) {
3777 $fields["user_$name"] = $value;
3778 }
3779 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3780 if ( $dbw->affectedRows() ) {
3781 $newUser = User::newFromId( $dbw->insertId() );
3782 } else {
3783 $newUser = null;
3784 }
3785 return $newUser;
3786 }
3787
3788 /**
3789 * Add this existing user object to the database. If the user already
3790 * exists, a fatal status object is returned, and the user object is
3791 * initialised with the data from the database.
3792 *
3793 * Previously, this function generated a DB error due to a key conflict
3794 * if the user already existed. Many extension callers use this function
3795 * in code along the lines of:
3796 *
3797 * $user = User::newFromName( $name );
3798 * if ( !$user->isLoggedIn() ) {
3799 * $user->addToDatabase();
3800 * }
3801 * // do something with $user...
3802 *
3803 * However, this was vulnerable to a race condition (bug 16020). By
3804 * initialising the user object if the user exists, we aim to support this
3805 * calling sequence as far as possible.
3806 *
3807 * Note that if the user exists, this function will acquire a write lock,
3808 * so it is still advisable to make the call conditional on isLoggedIn(),
3809 * and to commit the transaction after calling.
3810 *
3811 * @throws MWException
3812 * @return Status
3813 */
3814 public function addToDatabase() {
3815 $this->load();
3816 $this->loadPasswords();
3817 if ( !$this->mToken ) {
3818 $this->setToken(); // init token
3819 }
3820
3821 $this->mTouched = $this->newTouchedTimestamp();
3822
3823 $dbw = wfGetDB( DB_MASTER );
3824 $inWrite = $dbw->writesOrCallbacksPending();
3825 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3826 $dbw->insert( 'user',
3827 array(
3828 'user_id' => $seqVal,
3829 'user_name' => $this->mName,
3830 'user_password' => $this->mPassword->toString(),
3831 'user_newpassword' => $this->mNewpassword->toString(),
3832 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3833 'user_email' => $this->mEmail,
3834 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3835 'user_real_name' => $this->mRealName,
3836 'user_token' => strval( $this->mToken ),
3837 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3838 'user_editcount' => 0,
3839 'user_touched' => $dbw->timestamp( $this->mTouched ),
3840 ), __METHOD__,
3841 array( 'IGNORE' )
3842 );
3843 if ( !$dbw->affectedRows() ) {
3844 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3845 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3846 if ( $inWrite ) {
3847 // Can't commit due to pending writes that may need atomicity.
3848 // This may cause some lock contention unlike the case below.
3849 $options = array( 'LOCK IN SHARE MODE' );
3850 $flags = self::READ_LOCKING;
3851 } else {
3852 // Often, this case happens early in views before any writes when
3853 // using CentralAuth. It's should be OK to commit and break the snapshot.
3854 $dbw->commit( __METHOD__, 'flush' );
3855 $options = array();
3856 $flags = self::READ_LATEST;
3857 }
3858 $this->mId = $dbw->selectField( 'user', 'user_id',
3859 array( 'user_name' => $this->mName ), __METHOD__, $options );
3860 $loaded = false;
3861 if ( $this->mId ) {
3862 if ( $this->loadFromDatabase( $flags ) ) {
3863 $loaded = true;
3864 }
3865 }
3866 if ( !$loaded ) {
3867 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3868 "to insert user '{$this->mName}' row, but it was not present in select!" );
3869 }
3870 return Status::newFatal( 'userexists' );
3871 }
3872 $this->mId = $dbw->insertId();
3873
3874 // Clear instance cache other than user table data, which is already accurate
3875 $this->clearInstanceCache();
3876
3877 $this->saveOptions();
3878 return Status::newGood();
3879 }
3880
3881 /**
3882 * If this user is logged-in and blocked,
3883 * block any IP address they've successfully logged in from.
3884 * @return bool A block was spread
3885 */
3886 public function spreadAnyEditBlock() {
3887 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3888 return $this->spreadBlock();
3889 }
3890 return false;
3891 }
3892
3893 /**
3894 * If this (non-anonymous) user is blocked,
3895 * block the IP address they've successfully logged in from.
3896 * @return bool A block was spread
3897 */
3898 protected function spreadBlock() {
3899 wfDebug( __METHOD__ . "()\n" );
3900 $this->load();
3901 if ( $this->mId == 0 ) {
3902 return false;
3903 }
3904
3905 $userblock = Block::newFromTarget( $this->getName() );
3906 if ( !$userblock ) {
3907 return false;
3908 }
3909
3910 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3911 }
3912
3913 /**
3914 * Get whether the user is explicitly blocked from account creation.
3915 * @return bool|Block
3916 */
3917 public function isBlockedFromCreateAccount() {
3918 $this->getBlockedStatus();
3919 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3920 return $this->mBlock;
3921 }
3922
3923 # bug 13611: if the IP address the user is trying to create an account from is
3924 # blocked with createaccount disabled, prevent new account creation there even
3925 # when the user is logged in
3926 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3927 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3928 }
3929 return $this->mBlockedFromCreateAccount instanceof Block
3930 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3931 ? $this->mBlockedFromCreateAccount
3932 : false;
3933 }
3934
3935 /**
3936 * Get whether the user is blocked from using Special:Emailuser.
3937 * @return bool
3938 */
3939 public function isBlockedFromEmailuser() {
3940 $this->getBlockedStatus();
3941 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3942 }
3943
3944 /**
3945 * Get whether the user is allowed to create an account.
3946 * @return bool
3947 */
3948 public function isAllowedToCreateAccount() {
3949 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3950 }
3951
3952 /**
3953 * Get this user's personal page title.
3954 *
3955 * @return Title User's personal page title
3956 */
3957 public function getUserPage() {
3958 return Title::makeTitle( NS_USER, $this->getName() );
3959 }
3960
3961 /**
3962 * Get this user's talk page title.
3963 *
3964 * @return Title User's talk page title
3965 */
3966 public function getTalkPage() {
3967 $title = $this->getUserPage();
3968 return $title->getTalkPage();
3969 }
3970
3971 /**
3972 * Determine whether the user is a newbie. Newbies are either
3973 * anonymous IPs, or the most recently created accounts.
3974 * @return bool
3975 */
3976 public function isNewbie() {
3977 return !$this->isAllowed( 'autoconfirmed' );
3978 }
3979
3980 /**
3981 * Check to see if the given clear-text password is one of the accepted passwords
3982 * @param string $password User password
3983 * @return bool True if the given password is correct, otherwise False
3984 */
3985 public function checkPassword( $password ) {
3986 global $wgAuth, $wgLegacyEncoding;
3987
3988 $this->loadPasswords();
3989
3990 // Some passwords will give a fatal Status, which means there is
3991 // some sort of technical or security reason for this password to
3992 // be completely invalid and should never be checked (e.g., T64685)
3993 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
3994 return false;
3995 }
3996
3997 // Certain authentication plugins do NOT want to save
3998 // domain passwords in a mysql database, so we should
3999 // check this (in case $wgAuth->strict() is false).
4000 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4001 return true;
4002 } elseif ( $wgAuth->strict() ) {
4003 // Auth plugin doesn't allow local authentication
4004 return false;
4005 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4006 // Auth plugin doesn't allow local authentication for this user name
4007 return false;
4008 }
4009
4010 if ( !$this->mPassword->equals( $password ) ) {
4011 if ( $wgLegacyEncoding ) {
4012 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4013 // Check for this with iconv
4014 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4015 if ( $cp1252Password === $password || !$this->mPassword->equals( $cp1252Password ) ) {
4016 return false;
4017 }
4018 } else {
4019 return false;
4020 }
4021 }
4022
4023 $passwordFactory = self::getPasswordFactory();
4024 if ( $passwordFactory->needsUpdate( $this->mPassword ) && !wfReadOnly() ) {
4025 $this->mPassword = $passwordFactory->newFromPlaintext( $password );
4026 $this->saveSettings();
4027 }
4028
4029 return true;
4030 }
4031
4032 /**
4033 * Check if the given clear-text password matches the temporary password
4034 * sent by e-mail for password reset operations.
4035 *
4036 * @param string $plaintext
4037 *
4038 * @return bool True if matches, false otherwise
4039 */
4040 public function checkTemporaryPassword( $plaintext ) {
4041 global $wgNewPasswordExpiry;
4042
4043 $this->load();
4044 $this->loadPasswords();
4045 if ( $this->mNewpassword->equals( $plaintext ) ) {
4046 if ( is_null( $this->mNewpassTime ) ) {
4047 return true;
4048 }
4049 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
4050 return ( time() < $expiry );
4051 } else {
4052 return false;
4053 }
4054 }
4055
4056 /**
4057 * Alias for getEditToken.
4058 * @deprecated since 1.19, use getEditToken instead.
4059 *
4060 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4061 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4062 * @return string The new edit token
4063 */
4064 public function editToken( $salt = '', $request = null ) {
4065 wfDeprecated( __METHOD__, '1.19' );
4066 return $this->getEditToken( $salt, $request );
4067 }
4068
4069 /**
4070 * Internal implementation for self::getEditToken() and
4071 * self::matchEditToken().
4072 *
4073 * @param string|array $salt
4074 * @param WebRequest $request
4075 * @param string|int $timestamp
4076 * @return string
4077 */
4078 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4079 if ( $this->isAnon() ) {
4080 return self::EDIT_TOKEN_SUFFIX;
4081 } else {
4082 $token = $request->getSessionData( 'wsEditToken' );
4083 if ( $token === null ) {
4084 $token = MWCryptRand::generateHex( 32 );
4085 $request->setSessionData( 'wsEditToken', $token );
4086 }
4087 if ( is_array( $salt ) ) {
4088 $salt = implode( '|', $salt );
4089 }
4090 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4091 dechex( $timestamp ) .
4092 self::EDIT_TOKEN_SUFFIX;
4093 }
4094 }
4095
4096 /**
4097 * Initialize (if necessary) and return a session token value
4098 * which can be used in edit forms to show that the user's
4099 * login credentials aren't being hijacked with a foreign form
4100 * submission.
4101 *
4102 * @since 1.19
4103 *
4104 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4105 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4106 * @return string The new edit token
4107 */
4108 public function getEditToken( $salt = '', $request = null ) {
4109 return $this->getEditTokenAtTimestamp(
4110 $salt, $request ?: $this->getRequest(), wfTimestamp()
4111 );
4112 }
4113
4114 /**
4115 * Generate a looking random token for various uses.
4116 *
4117 * @return string The new random token
4118 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
4119 * wfRandomString for pseudo-randomness.
4120 */
4121 public static function generateToken() {
4122 return MWCryptRand::generateHex( 32 );
4123 }
4124
4125 /**
4126 * Get the embedded timestamp from a token.
4127 * @param string $val Input token
4128 * @return int|null
4129 */
4130 public static function getEditTokenTimestamp( $val ) {
4131 $suffixLen = strlen( self::EDIT_TOKEN_SUFFIX );
4132 if ( strlen( $val ) <= 32 + $suffixLen ) {
4133 return null;
4134 }
4135
4136 return hexdec( substr( $val, 32, -$suffixLen ) );
4137 }
4138
4139 /**
4140 * Check given value against the token value stored in the session.
4141 * A match should confirm that the form was submitted from the
4142 * user's own login session, not a form submission from a third-party
4143 * site.
4144 *
4145 * @param string $val Input value to compare
4146 * @param string $salt Optional function-specific data for hashing
4147 * @param WebRequest|null $request Object to use or null to use $wgRequest
4148 * @param int $maxage Fail tokens older than this, in seconds
4149 * @return bool Whether the token matches
4150 */
4151 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4152 if ( $this->isAnon() ) {
4153 return $val === self::EDIT_TOKEN_SUFFIX;
4154 }
4155
4156 $timestamp = self::getEditTokenTimestamp( $val );
4157 if ( $timestamp === null ) {
4158 return false;
4159 }
4160 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4161 // Expired token
4162 return false;
4163 }
4164
4165 $sessionToken = $this->getEditTokenAtTimestamp(
4166 $salt, $request ?: $this->getRequest(), $timestamp
4167 );
4168
4169 if ( $val != $sessionToken ) {
4170 wfDebug( "User::matchEditToken: broken session data\n" );
4171 }
4172
4173 return hash_equals( $sessionToken, $val );
4174 }
4175
4176 /**
4177 * Check given value against the token value stored in the session,
4178 * ignoring the suffix.
4179 *
4180 * @param string $val Input value to compare
4181 * @param string $salt Optional function-specific data for hashing
4182 * @param WebRequest|null $request Object to use or null to use $wgRequest
4183 * @param int $maxage Fail tokens older than this, in seconds
4184 * @return bool Whether the token matches
4185 */
4186 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4187 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self::EDIT_TOKEN_SUFFIX;
4188 return $this->matchEditToken( $val, $salt, $request, $maxage );
4189 }
4190
4191 /**
4192 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4193 * mail to the user's given address.
4194 *
4195 * @param string $type Message to send, either "created", "changed" or "set"
4196 * @return Status
4197 */
4198 public function sendConfirmationMail( $type = 'created' ) {
4199 global $wgLang;
4200 $expiration = null; // gets passed-by-ref and defined in next line.
4201 $token = $this->confirmationToken( $expiration );
4202 $url = $this->confirmationTokenUrl( $token );
4203 $invalidateURL = $this->invalidationTokenUrl( $token );
4204 $this->saveSettings();
4205
4206 if ( $type == 'created' || $type === false ) {
4207 $message = 'confirmemail_body';
4208 } elseif ( $type === true ) {
4209 $message = 'confirmemail_body_changed';
4210 } else {
4211 // Messages: confirmemail_body_changed, confirmemail_body_set
4212 $message = 'confirmemail_body_' . $type;
4213 }
4214
4215 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4216 wfMessage( $message,
4217 $this->getRequest()->getIP(),
4218 $this->getName(),
4219 $url,
4220 $wgLang->timeanddate( $expiration, false ),
4221 $invalidateURL,
4222 $wgLang->date( $expiration, false ),
4223 $wgLang->time( $expiration, false ) )->text() );
4224 }
4225
4226 /**
4227 * Send an e-mail to this user's account. Does not check for
4228 * confirmed status or validity.
4229 *
4230 * @param string $subject Message subject
4231 * @param string $body Message body
4232 * @param string $from Optional From address; if unspecified, default
4233 * $wgPasswordSender will be used.
4234 * @param string $replyto Reply-To address
4235 * @return Status
4236 */
4237 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4238 if ( is_null( $from ) ) {
4239 global $wgPasswordSender;
4240 $sender = new MailAddress( $wgPasswordSender,
4241 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4242 } else {
4243 $sender = MailAddress::newFromUser( $from );
4244 }
4245
4246 $to = MailAddress::newFromUser( $this );
4247 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
4248 }
4249
4250 /**
4251 * Generate, store, and return a new e-mail confirmation code.
4252 * A hash (unsalted, since it's used as a key) is stored.
4253 *
4254 * @note Call saveSettings() after calling this function to commit
4255 * this change to the database.
4256 *
4257 * @param string &$expiration Accepts the expiration time
4258 * @return string New token
4259 */
4260 protected function confirmationToken( &$expiration ) {
4261 global $wgUserEmailConfirmationTokenExpiry;
4262 $now = time();
4263 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4264 $expiration = wfTimestamp( TS_MW, $expires );
4265 $this->load();
4266 $token = MWCryptRand::generateHex( 32 );
4267 $hash = md5( $token );
4268 $this->mEmailToken = $hash;
4269 $this->mEmailTokenExpires = $expiration;
4270 return $token;
4271 }
4272
4273 /**
4274 * Return a URL the user can use to confirm their email address.
4275 * @param string $token Accepts the email confirmation token
4276 * @return string New token URL
4277 */
4278 protected function confirmationTokenUrl( $token ) {
4279 return $this->getTokenUrl( 'ConfirmEmail', $token );
4280 }
4281
4282 /**
4283 * Return a URL the user can use to invalidate their email address.
4284 * @param string $token Accepts the email confirmation token
4285 * @return string New token URL
4286 */
4287 protected function invalidationTokenUrl( $token ) {
4288 return $this->getTokenUrl( 'InvalidateEmail', $token );
4289 }
4290
4291 /**
4292 * Internal function to format the e-mail validation/invalidation URLs.
4293 * This uses a quickie hack to use the
4294 * hardcoded English names of the Special: pages, for ASCII safety.
4295 *
4296 * @note Since these URLs get dropped directly into emails, using the
4297 * short English names avoids insanely long URL-encoded links, which
4298 * also sometimes can get corrupted in some browsers/mailers
4299 * (bug 6957 with Gmail and Internet Explorer).
4300 *
4301 * @param string $page Special page
4302 * @param string $token Token
4303 * @return string Formatted URL
4304 */
4305 protected function getTokenUrl( $page, $token ) {
4306 // Hack to bypass localization of 'Special:'
4307 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4308 return $title->getCanonicalURL();
4309 }
4310
4311 /**
4312 * Mark the e-mail address confirmed.
4313 *
4314 * @note Call saveSettings() after calling this function to commit the change.
4315 *
4316 * @return bool
4317 */
4318 public function confirmEmail() {
4319 // Check if it's already confirmed, so we don't touch the database
4320 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4321 if ( !$this->isEmailConfirmed() ) {
4322 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4323 Hooks::run( 'ConfirmEmailComplete', array( $this ) );
4324 }
4325 return true;
4326 }
4327
4328 /**
4329 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4330 * address if it was already confirmed.
4331 *
4332 * @note Call saveSettings() after calling this function to commit the change.
4333 * @return bool Returns true
4334 */
4335 public function invalidateEmail() {
4336 $this->load();
4337 $this->mEmailToken = null;
4338 $this->mEmailTokenExpires = null;
4339 $this->setEmailAuthenticationTimestamp( null );
4340 $this->mEmail = '';
4341 Hooks::run( 'InvalidateEmailComplete', array( $this ) );
4342 return true;
4343 }
4344
4345 /**
4346 * Set the e-mail authentication timestamp.
4347 * @param string $timestamp TS_MW timestamp
4348 */
4349 public function setEmailAuthenticationTimestamp( $timestamp ) {
4350 $this->load();
4351 $this->mEmailAuthenticated = $timestamp;
4352 Hooks::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4353 }
4354
4355 /**
4356 * Is this user allowed to send e-mails within limits of current
4357 * site configuration?
4358 * @return bool
4359 */
4360 public function canSendEmail() {
4361 global $wgEnableEmail, $wgEnableUserEmail;
4362 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4363 return false;
4364 }
4365 $canSend = $this->isEmailConfirmed();
4366 Hooks::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4367 return $canSend;
4368 }
4369
4370 /**
4371 * Is this user allowed to receive e-mails within limits of current
4372 * site configuration?
4373 * @return bool
4374 */
4375 public function canReceiveEmail() {
4376 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4377 }
4378
4379 /**
4380 * Is this user's e-mail address valid-looking and confirmed within
4381 * limits of the current site configuration?
4382 *
4383 * @note If $wgEmailAuthentication is on, this may require the user to have
4384 * confirmed their address by returning a code or using a password
4385 * sent to the address from the wiki.
4386 *
4387 * @return bool
4388 */
4389 public function isEmailConfirmed() {
4390 global $wgEmailAuthentication;
4391 $this->load();
4392 $confirmed = true;
4393 if ( Hooks::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4394 if ( $this->isAnon() ) {
4395 return false;
4396 }
4397 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4398 return false;
4399 }
4400 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4401 return false;
4402 }
4403 return true;
4404 } else {
4405 return $confirmed;
4406 }
4407 }
4408
4409 /**
4410 * Check whether there is an outstanding request for e-mail confirmation.
4411 * @return bool
4412 */
4413 public function isEmailConfirmationPending() {
4414 global $wgEmailAuthentication;
4415 return $wgEmailAuthentication &&
4416 !$this->isEmailConfirmed() &&
4417 $this->mEmailToken &&
4418 $this->mEmailTokenExpires > wfTimestamp();
4419 }
4420
4421 /**
4422 * Get the timestamp of account creation.
4423 *
4424 * @return string|bool|null Timestamp of account creation, false for
4425 * non-existent/anonymous user accounts, or null if existing account
4426 * but information is not in database.
4427 */
4428 public function getRegistration() {
4429 if ( $this->isAnon() ) {
4430 return false;
4431 }
4432 $this->load();
4433 return $this->mRegistration;
4434 }
4435
4436 /**
4437 * Get the timestamp of the first edit
4438 *
4439 * @return string|bool Timestamp of first edit, or false for
4440 * non-existent/anonymous user accounts.
4441 */
4442 public function getFirstEditTimestamp() {
4443 if ( $this->getId() == 0 ) {
4444 return false; // anons
4445 }
4446 $dbr = wfGetDB( DB_SLAVE );
4447 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4448 array( 'rev_user' => $this->getId() ),
4449 __METHOD__,
4450 array( 'ORDER BY' => 'rev_timestamp ASC' )
4451 );
4452 if ( !$time ) {
4453 return false; // no edits
4454 }
4455 return wfTimestamp( TS_MW, $time );
4456 }
4457
4458 /**
4459 * Get the permissions associated with a given list of groups
4460 *
4461 * @param array $groups Array of Strings List of internal group names
4462 * @return array Array of Strings List of permission key names for given groups combined
4463 */
4464 public static function getGroupPermissions( $groups ) {
4465 global $wgGroupPermissions, $wgRevokePermissions;
4466 $rights = array();
4467 // grant every granted permission first
4468 foreach ( $groups as $group ) {
4469 if ( isset( $wgGroupPermissions[$group] ) ) {
4470 $rights = array_merge( $rights,
4471 // array_filter removes empty items
4472 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4473 }
4474 }
4475 // now revoke the revoked permissions
4476 foreach ( $groups as $group ) {
4477 if ( isset( $wgRevokePermissions[$group] ) ) {
4478 $rights = array_diff( $rights,
4479 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4480 }
4481 }
4482 return array_unique( $rights );
4483 }
4484
4485 /**
4486 * Get all the groups who have a given permission
4487 *
4488 * @param string $role Role to check
4489 * @return array Array of Strings List of internal group names with the given permission
4490 */
4491 public static function getGroupsWithPermission( $role ) {
4492 global $wgGroupPermissions;
4493 $allowedGroups = array();
4494 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4495 if ( self::groupHasPermission( $group, $role ) ) {
4496 $allowedGroups[] = $group;
4497 }
4498 }
4499 return $allowedGroups;
4500 }
4501
4502 /**
4503 * Check, if the given group has the given permission
4504 *
4505 * If you're wanting to check whether all users have a permission, use
4506 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4507 * from anyone.
4508 *
4509 * @since 1.21
4510 * @param string $group Group to check
4511 * @param string $role Role to check
4512 * @return bool
4513 */
4514 public static function groupHasPermission( $group, $role ) {
4515 global $wgGroupPermissions, $wgRevokePermissions;
4516 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4517 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4518 }
4519
4520 /**
4521 * Check if all users have the given permission
4522 *
4523 * @since 1.22
4524 * @param string $right Right to check
4525 * @return bool
4526 */
4527 public static function isEveryoneAllowed( $right ) {
4528 global $wgGroupPermissions, $wgRevokePermissions;
4529 static $cache = array();
4530
4531 // Use the cached results, except in unit tests which rely on
4532 // being able change the permission mid-request
4533 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4534 return $cache[$right];
4535 }
4536
4537 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4538 $cache[$right] = false;
4539 return false;
4540 }
4541
4542 // If it's revoked anywhere, then everyone doesn't have it
4543 foreach ( $wgRevokePermissions as $rights ) {
4544 if ( isset( $rights[$right] ) && $rights[$right] ) {
4545 $cache[$right] = false;
4546 return false;
4547 }
4548 }
4549
4550 // Allow extensions (e.g. OAuth) to say false
4551 if ( !Hooks::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4552 $cache[$right] = false;
4553 return false;
4554 }
4555
4556 $cache[$right] = true;
4557 return true;
4558 }
4559
4560 /**
4561 * Get the localized descriptive name for a group, if it exists
4562 *
4563 * @param string $group Internal group name
4564 * @return string Localized descriptive group name
4565 */
4566 public static function getGroupName( $group ) {
4567 $msg = wfMessage( "group-$group" );
4568 return $msg->isBlank() ? $group : $msg->text();
4569 }
4570
4571 /**
4572 * Get the localized descriptive name for a member of a group, if it exists
4573 *
4574 * @param string $group Internal group name
4575 * @param string $username Username for gender (since 1.19)
4576 * @return string Localized name for group member
4577 */
4578 public static function getGroupMember( $group, $username = '#' ) {
4579 $msg = wfMessage( "group-$group-member", $username );
4580 return $msg->isBlank() ? $group : $msg->text();
4581 }
4582
4583 /**
4584 * Return the set of defined explicit groups.
4585 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4586 * are not included, as they are defined automatically, not in the database.
4587 * @return array Array of internal group names
4588 */
4589 public static function getAllGroups() {
4590 global $wgGroupPermissions, $wgRevokePermissions;
4591 return array_diff(
4592 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4593 self::getImplicitGroups()
4594 );
4595 }
4596
4597 /**
4598 * Get a list of all available permissions.
4599 * @return string[] Array of permission names
4600 */
4601 public static function getAllRights() {
4602 if ( self::$mAllRights === false ) {
4603 global $wgAvailableRights;
4604 if ( count( $wgAvailableRights ) ) {
4605 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4606 } else {
4607 self::$mAllRights = self::$mCoreRights;
4608 }
4609 Hooks::run( 'UserGetAllRights', array( &self::$mAllRights ) );
4610 }
4611 return self::$mAllRights;
4612 }
4613
4614 /**
4615 * Get a list of implicit groups
4616 * @return array Array of Strings Array of internal group names
4617 */
4618 public static function getImplicitGroups() {
4619 global $wgImplicitGroups;
4620
4621 $groups = $wgImplicitGroups;
4622 # Deprecated, use $wgImplicitGroups instead
4623 Hooks::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4624
4625 return $groups;
4626 }
4627
4628 /**
4629 * Get the title of a page describing a particular group
4630 *
4631 * @param string $group Internal group name
4632 * @return Title|bool Title of the page if it exists, false otherwise
4633 */
4634 public static function getGroupPage( $group ) {
4635 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4636 if ( $msg->exists() ) {
4637 $title = Title::newFromText( $msg->text() );
4638 if ( is_object( $title ) ) {
4639 return $title;
4640 }
4641 }
4642 return false;
4643 }
4644
4645 /**
4646 * Create a link to the group in HTML, if available;
4647 * else return the group name.
4648 *
4649 * @param string $group Internal name of the group
4650 * @param string $text The text of the link
4651 * @return string HTML link to the group
4652 */
4653 public static function makeGroupLinkHTML( $group, $text = '' ) {
4654 if ( $text == '' ) {
4655 $text = self::getGroupName( $group );
4656 }
4657 $title = self::getGroupPage( $group );
4658 if ( $title ) {
4659 return Linker::link( $title, htmlspecialchars( $text ) );
4660 } else {
4661 return htmlspecialchars( $text );
4662 }
4663 }
4664
4665 /**
4666 * Create a link to the group in Wikitext, if available;
4667 * else return the group name.
4668 *
4669 * @param string $group Internal name of the group
4670 * @param string $text The text of the link
4671 * @return string Wikilink to the group
4672 */
4673 public static function makeGroupLinkWiki( $group, $text = '' ) {
4674 if ( $text == '' ) {
4675 $text = self::getGroupName( $group );
4676 }
4677 $title = self::getGroupPage( $group );
4678 if ( $title ) {
4679 $page = $title->getFullText();
4680 return "[[$page|$text]]";
4681 } else {
4682 return $text;
4683 }
4684 }
4685
4686 /**
4687 * Returns an array of the groups that a particular group can add/remove.
4688 *
4689 * @param string $group The group to check for whether it can add/remove
4690 * @return array Array( 'add' => array( addablegroups ),
4691 * 'remove' => array( removablegroups ),
4692 * 'add-self' => array( addablegroups to self),
4693 * 'remove-self' => array( removable groups from self) )
4694 */
4695 public static function changeableByGroup( $group ) {
4696 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4697
4698 $groups = array(
4699 'add' => array(),
4700 'remove' => array(),
4701 'add-self' => array(),
4702 'remove-self' => array()
4703 );
4704
4705 if ( empty( $wgAddGroups[$group] ) ) {
4706 // Don't add anything to $groups
4707 } elseif ( $wgAddGroups[$group] === true ) {
4708 // You get everything
4709 $groups['add'] = self::getAllGroups();
4710 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4711 $groups['add'] = $wgAddGroups[$group];
4712 }
4713
4714 // Same thing for remove
4715 if ( empty( $wgRemoveGroups[$group] ) ) {
4716 // Do nothing
4717 } elseif ( $wgRemoveGroups[$group] === true ) {
4718 $groups['remove'] = self::getAllGroups();
4719 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4720 $groups['remove'] = $wgRemoveGroups[$group];
4721 }
4722
4723 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4724 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4725 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4726 if ( is_int( $key ) ) {
4727 $wgGroupsAddToSelf['user'][] = $value;
4728 }
4729 }
4730 }
4731
4732 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4733 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4734 if ( is_int( $key ) ) {
4735 $wgGroupsRemoveFromSelf['user'][] = $value;
4736 }
4737 }
4738 }
4739
4740 // Now figure out what groups the user can add to him/herself
4741 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4742 // Do nothing
4743 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4744 // No idea WHY this would be used, but it's there
4745 $groups['add-self'] = User::getAllGroups();
4746 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4747 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4748 }
4749
4750 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4751 // Do nothing
4752 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4753 $groups['remove-self'] = User::getAllGroups();
4754 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4755 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4756 }
4757
4758 return $groups;
4759 }
4760
4761 /**
4762 * Returns an array of groups that this user can add and remove
4763 * @return array Array( 'add' => array( addablegroups ),
4764 * 'remove' => array( removablegroups ),
4765 * 'add-self' => array( addablegroups to self),
4766 * 'remove-self' => array( removable groups from self) )
4767 */
4768 public function changeableGroups() {
4769 if ( $this->isAllowed( 'userrights' ) ) {
4770 // This group gives the right to modify everything (reverse-
4771 // compatibility with old "userrights lets you change
4772 // everything")
4773 // Using array_merge to make the groups reindexed
4774 $all = array_merge( User::getAllGroups() );
4775 return array(
4776 'add' => $all,
4777 'remove' => $all,
4778 'add-self' => array(),
4779 'remove-self' => array()
4780 );
4781 }
4782
4783 // Okay, it's not so simple, we will have to go through the arrays
4784 $groups = array(
4785 'add' => array(),
4786 'remove' => array(),
4787 'add-self' => array(),
4788 'remove-self' => array()
4789 );
4790 $addergroups = $this->getEffectiveGroups();
4791
4792 foreach ( $addergroups as $addergroup ) {
4793 $groups = array_merge_recursive(
4794 $groups, $this->changeableByGroup( $addergroup )
4795 );
4796 $groups['add'] = array_unique( $groups['add'] );
4797 $groups['remove'] = array_unique( $groups['remove'] );
4798 $groups['add-self'] = array_unique( $groups['add-self'] );
4799 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4800 }
4801 return $groups;
4802 }
4803
4804 /**
4805 * Deferred version of incEditCountImmediate()
4806 */
4807 public function incEditCount() {
4808 $that = $this;
4809 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle( function() use ( $that ) {
4810 $that->incEditCountImmediate();
4811 } );
4812 }
4813
4814 /**
4815 * Increment the user's edit-count field.
4816 * Will have no effect for anonymous users.
4817 * @since 1.26
4818 */
4819 public function incEditCountImmediate() {
4820 if ( $this->isAnon() ) {
4821 return;
4822 }
4823
4824 $dbw = wfGetDB( DB_MASTER );
4825 // No rows will be "affected" if user_editcount is NULL
4826 $dbw->update(
4827 'user',
4828 array( 'user_editcount=user_editcount+1' ),
4829 array( 'user_id' => $this->getId() ),
4830 __METHOD__
4831 );
4832 // Lazy initialization check...
4833 if ( $dbw->affectedRows() == 0 ) {
4834 // Now here's a goddamn hack...
4835 $dbr = wfGetDB( DB_SLAVE );
4836 if ( $dbr !== $dbw ) {
4837 // If we actually have a slave server, the count is
4838 // at least one behind because the current transaction
4839 // has not been committed and replicated.
4840 $this->initEditCount( 1 );
4841 } else {
4842 // But if DB_SLAVE is selecting the master, then the
4843 // count we just read includes the revision that was
4844 // just added in the working transaction.
4845 $this->initEditCount();
4846 }
4847 }
4848 // Edit count in user cache too
4849 $this->invalidateCache();
4850 }
4851
4852 /**
4853 * Initialize user_editcount from data out of the revision table
4854 *
4855 * @param int $add Edits to add to the count from the revision table
4856 * @return int Number of edits
4857 */
4858 protected function initEditCount( $add = 0 ) {
4859 // Pull from a slave to be less cruel to servers
4860 // Accuracy isn't the point anyway here
4861 $dbr = wfGetDB( DB_SLAVE );
4862 $count = (int)$dbr->selectField(
4863 'revision',
4864 'COUNT(rev_user)',
4865 array( 'rev_user' => $this->getId() ),
4866 __METHOD__
4867 );
4868 $count = $count + $add;
4869
4870 $dbw = wfGetDB( DB_MASTER );
4871 $dbw->update(
4872 'user',
4873 array( 'user_editcount' => $count ),
4874 array( 'user_id' => $this->getId() ),
4875 __METHOD__
4876 );
4877
4878 return $count;
4879 }
4880
4881 /**
4882 * Get the description of a given right
4883 *
4884 * @param string $right Right to query
4885 * @return string Localized description of the right
4886 */
4887 public static function getRightDescription( $right ) {
4888 $key = "right-$right";
4889 $msg = wfMessage( $key );
4890 return $msg->isBlank() ? $right : $msg->text();
4891 }
4892
4893 /**
4894 * Make a new-style password hash
4895 *
4896 * @param string $password Plain-text password
4897 * @param bool|string $salt Optional salt, may be random or the user ID.
4898 * If unspecified or false, will generate one automatically
4899 * @return string Password hash
4900 * @deprecated since 1.24, use Password class
4901 */
4902 public static function crypt( $password, $salt = false ) {
4903 wfDeprecated( __METHOD__, '1.24' );
4904 $hash = self::getPasswordFactory()->newFromPlaintext( $password );
4905 return $hash->toString();
4906 }
4907
4908 /**
4909 * Compare a password hash with a plain-text password. Requires the user
4910 * ID if there's a chance that the hash is an old-style hash.
4911 *
4912 * @param string $hash Password hash
4913 * @param string $password Plain-text password to compare
4914 * @param string|bool $userId User ID for old-style password salt
4915 *
4916 * @return bool
4917 * @deprecated since 1.24, use Password class
4918 */
4919 public static function comparePasswords( $hash, $password, $userId = false ) {
4920 wfDeprecated( __METHOD__, '1.24' );
4921
4922 // Check for *really* old password hashes that don't even have a type
4923 // The old hash format was just an md5 hex hash, with no type information
4924 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4925 global $wgPasswordSalt;
4926 if ( $wgPasswordSalt ) {
4927 $password = ":B:{$userId}:{$hash}";
4928 } else {
4929 $password = ":A:{$hash}";
4930 }
4931 }
4932
4933 $hash = self::getPasswordFactory()->newFromCiphertext( $hash );
4934 return $hash->equals( $password );
4935 }
4936
4937 /**
4938 * Add a newuser log entry for this user.
4939 * Before 1.19 the return value was always true.
4940 *
4941 * @param string|bool $action Account creation type.
4942 * - String, one of the following values:
4943 * - 'create' for an anonymous user creating an account for himself.
4944 * This will force the action's performer to be the created user itself,
4945 * no matter the value of $wgUser
4946 * - 'create2' for a logged in user creating an account for someone else
4947 * - 'byemail' when the created user will receive its password by e-mail
4948 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4949 * - Boolean means whether the account was created by e-mail (deprecated):
4950 * - true will be converted to 'byemail'
4951 * - false will be converted to 'create' if this object is the same as
4952 * $wgUser and to 'create2' otherwise
4953 *
4954 * @param string $reason User supplied reason
4955 *
4956 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4957 */
4958 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4959 global $wgUser, $wgNewUserLog;
4960 if ( empty( $wgNewUserLog ) ) {
4961 return true; // disabled
4962 }
4963
4964 if ( $action === true ) {
4965 $action = 'byemail';
4966 } elseif ( $action === false ) {
4967 if ( $this->equals( $wgUser ) ) {
4968 $action = 'create';
4969 } else {
4970 $action = 'create2';
4971 }
4972 }
4973
4974 if ( $action === 'create' || $action === 'autocreate' ) {
4975 $performer = $this;
4976 } else {
4977 $performer = $wgUser;
4978 }
4979
4980 $logEntry = new ManualLogEntry( 'newusers', $action );
4981 $logEntry->setPerformer( $performer );
4982 $logEntry->setTarget( $this->getUserPage() );
4983 $logEntry->setComment( $reason );
4984 $logEntry->setParameters( array(
4985 '4::userid' => $this->getId(),
4986 ) );
4987 $logid = $logEntry->insert();
4988
4989 if ( $action !== 'autocreate' ) {
4990 $logEntry->publish( $logid );
4991 }
4992
4993 return (int)$logid;
4994 }
4995
4996 /**
4997 * Add an autocreate newuser log entry for this user
4998 * Used by things like CentralAuth and perhaps other authplugins.
4999 * Consider calling addNewUserLogEntry() directly instead.
5000 *
5001 * @return bool
5002 */
5003 public function addNewUserLogEntryAutoCreate() {
5004 $this->addNewUserLogEntry( 'autocreate' );
5005
5006 return true;
5007 }
5008
5009 /**
5010 * Load the user options either from cache, the database or an array
5011 *
5012 * @param array $data Rows for the current user out of the user_properties table
5013 */
5014 protected function loadOptions( $data = null ) {
5015 global $wgContLang;
5016
5017 $this->load();
5018
5019 if ( $this->mOptionsLoaded ) {
5020 return;
5021 }
5022
5023 $this->mOptions = self::getDefaultOptions();
5024
5025 if ( !$this->getId() ) {
5026 // For unlogged-in users, load language/variant options from request.
5027 // There's no need to do it for logged-in users: they can set preferences,
5028 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5029 // so don't override user's choice (especially when the user chooses site default).
5030 $variant = $wgContLang->getDefaultVariant();
5031 $this->mOptions['variant'] = $variant;
5032 $this->mOptions['language'] = $variant;
5033 $this->mOptionsLoaded = true;
5034 return;
5035 }
5036
5037 // Maybe load from the object
5038 if ( !is_null( $this->mOptionOverrides ) ) {
5039 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5040 foreach ( $this->mOptionOverrides as $key => $value ) {
5041 $this->mOptions[$key] = $value;
5042 }
5043 } else {
5044 if ( !is_array( $data ) ) {
5045 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5046 // Load from database
5047 $dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
5048 ? wfGetDB( DB_MASTER )
5049 : wfGetDB( DB_SLAVE );
5050
5051 $res = $dbr->select(
5052 'user_properties',
5053 array( 'up_property', 'up_value' ),
5054 array( 'up_user' => $this->getId() ),
5055 __METHOD__
5056 );
5057
5058 $this->mOptionOverrides = array();
5059 $data = array();
5060 foreach ( $res as $row ) {
5061 $data[$row->up_property] = $row->up_value;
5062 }
5063 }
5064 foreach ( $data as $property => $value ) {
5065 $this->mOptionOverrides[$property] = $value;
5066 $this->mOptions[$property] = $value;
5067 }
5068 }
5069
5070 $this->mOptionsLoaded = true;
5071
5072 Hooks::run( 'UserLoadOptions', array( $this, &$this->mOptions ) );
5073 }
5074
5075 /**
5076 * Saves the non-default options for this user, as previously set e.g. via
5077 * setOption(), in the database's "user_properties" (preferences) table.
5078 * Usually used via saveSettings().
5079 */
5080 protected function saveOptions() {
5081 $this->loadOptions();
5082
5083 // Not using getOptions(), to keep hidden preferences in database
5084 $saveOptions = $this->mOptions;
5085
5086 // Allow hooks to abort, for instance to save to a global profile.
5087 // Reset options to default state before saving.
5088 if ( !Hooks::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5089 return;
5090 }
5091
5092 $userId = $this->getId();
5093
5094 $insert_rows = array(); // all the new preference rows
5095 foreach ( $saveOptions as $key => $value ) {
5096 // Don't bother storing default values
5097 $defaultOption = self::getDefaultOption( $key );
5098 if ( ( $defaultOption === null && $value !== false && $value !== null )
5099 || $value != $defaultOption
5100 ) {
5101 $insert_rows[] = array(
5102 'up_user' => $userId,
5103 'up_property' => $key,
5104 'up_value' => $value,
5105 );
5106 }
5107 }
5108
5109 $dbw = wfGetDB( DB_MASTER );
5110
5111 $res = $dbw->select( 'user_properties',
5112 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__ );
5113
5114 // Find prior rows that need to be removed or updated. These rows will
5115 // all be deleted (the later so that INSERT IGNORE applies the new values).
5116 $keysDelete = array();
5117 foreach ( $res as $row ) {
5118 if ( !isset( $saveOptions[$row->up_property] )
5119 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
5120 ) {
5121 $keysDelete[] = $row->up_property;
5122 }
5123 }
5124
5125 if ( count( $keysDelete ) ) {
5126 // Do the DELETE by PRIMARY KEY for prior rows.
5127 // In the past a very large portion of calls to this function are for setting
5128 // 'rememberpassword' for new accounts (a preference that has since been removed).
5129 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5130 // caused gap locks on [max user ID,+infinity) which caused high contention since
5131 // updates would pile up on each other as they are for higher (newer) user IDs.
5132 // It might not be necessary these days, but it shouldn't hurt either.
5133 $dbw->delete( 'user_properties',
5134 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__ );
5135 }
5136 // Insert the new preference rows
5137 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
5138 }
5139
5140 /**
5141 * Lazily instantiate and return a factory object for making passwords
5142 *
5143 * @return PasswordFactory
5144 */
5145 public static function getPasswordFactory() {
5146 if ( self::$mPasswordFactory === null ) {
5147 self::$mPasswordFactory = new PasswordFactory();
5148 self::$mPasswordFactory->init( RequestContext::getMain()->getConfig() );
5149 }
5150
5151 return self::$mPasswordFactory;
5152 }
5153
5154 /**
5155 * Provide an array of HTML5 attributes to put on an input element
5156 * intended for the user to enter a new password. This may include
5157 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5158 *
5159 * Do *not* use this when asking the user to enter his current password!
5160 * Regardless of configuration, users may have invalid passwords for whatever
5161 * reason (e.g., they were set before requirements were tightened up).
5162 * Only use it when asking for a new password, like on account creation or
5163 * ResetPass.
5164 *
5165 * Obviously, you still need to do server-side checking.
5166 *
5167 * NOTE: A combination of bugs in various browsers means that this function
5168 * actually just returns array() unconditionally at the moment. May as
5169 * well keep it around for when the browser bugs get fixed, though.
5170 *
5171 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5172 *
5173 * @return array Array of HTML attributes suitable for feeding to
5174 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5175 * That will get confused by the boolean attribute syntax used.)
5176 */
5177 public static function passwordChangeInputAttribs() {
5178 global $wgMinimalPasswordLength;
5179
5180 if ( $wgMinimalPasswordLength == 0 ) {
5181 return array();
5182 }
5183
5184 # Note that the pattern requirement will always be satisfied if the
5185 # input is empty, so we need required in all cases.
5186 #
5187 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5188 # if e-mail confirmation is being used. Since HTML5 input validation
5189 # is b0rked anyway in some browsers, just return nothing. When it's
5190 # re-enabled, fix this code to not output required for e-mail
5191 # registration.
5192 #$ret = array( 'required' );
5193 $ret = array();
5194
5195 # We can't actually do this right now, because Opera 9.6 will print out
5196 # the entered password visibly in its error message! When other
5197 # browsers add support for this attribute, or Opera fixes its support,
5198 # we can add support with a version check to avoid doing this on Opera
5199 # versions where it will be a problem. Reported to Opera as
5200 # DSK-262266, but they don't have a public bug tracker for us to follow.
5201 /*
5202 if ( $wgMinimalPasswordLength > 1 ) {
5203 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5204 $ret['title'] = wfMessage( 'passwordtooshort' )
5205 ->numParams( $wgMinimalPasswordLength )->text();
5206 }
5207 */
5208
5209 return $ret;
5210 }
5211
5212 /**
5213 * Return the list of user fields that should be selected to create
5214 * a new user object.
5215 * @return array
5216 */
5217 public static function selectFields() {
5218 return array(
5219 'user_id',
5220 'user_name',
5221 'user_real_name',
5222 'user_email',
5223 'user_touched',
5224 'user_token',
5225 'user_email_authenticated',
5226 'user_email_token',
5227 'user_email_token_expires',
5228 'user_registration',
5229 'user_editcount',
5230 );
5231 }
5232
5233 /**
5234 * Factory function for fatal permission-denied errors
5235 *
5236 * @since 1.22
5237 * @param string $permission User right required
5238 * @return Status
5239 */
5240 static function newFatalPermissionDeniedStatus( $permission ) {
5241 global $wgLang;
5242
5243 $groups = array_map(
5244 array( 'User', 'makeGroupLinkWiki' ),
5245 User::getGroupsWithPermission( $permission )
5246 );
5247
5248 if ( $groups ) {
5249 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5250 } else {
5251 return Status::newFatal( 'badaccess-group0' );
5252 }
5253 }
5254
5255 /**
5256 * Checks if two user objects point to the same user.
5257 *
5258 * @since 1.25
5259 * @param User $user
5260 * @return bool
5261 */
5262 public function equals( User $user ) {
5263 return $this->getName() === $user->getName();
5264 }
5265 }