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