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