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