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