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