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