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