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