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