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