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