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