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