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