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