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