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