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