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