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