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