d71e5e1f110eb966660abcf15c572c1f321cf9fa
[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->mToken );
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 Token
2461 */
2462 public function getToken( $forceCreation = true ) {
2463 $this->load();
2464 if ( !$this->mToken && $forceCreation ) {
2465 $this->setToken();
2466 }
2467 return $this->mToken;
2468 }
2469
2470 /**
2471 * Set the random token (used for persistent authentication)
2472 * Called from loadDefaults() among other places.
2473 *
2474 * @param string|bool $token If specified, set the token to this value
2475 */
2476 public function setToken( $token = false ) {
2477 $this->load();
2478 if ( !$token ) {
2479 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2480 } else {
2481 $this->mToken = $token;
2482 }
2483 }
2484
2485 /**
2486 * Set the password for a password reminder or new account email
2487 *
2488 * @deprecated since 1.27, AuthManager is coming
2489 * @param string $str New password to set or null to set an invalid
2490 * password hash meaning that the user will not be able to use it
2491 * @param bool $throttle If true, reset the throttle timestamp to the present
2492 */
2493 public function setNewpassword( $str, $throttle = true ) {
2494 $id = $this->getId();
2495 if ( $id == 0 ) {
2496 throw new LogicException( 'Cannot set new password for a user that is not in the database.' );
2497 }
2498
2499 $dbw = wfGetDB( DB_MASTER );
2500
2501 $passwordFactory = new PasswordFactory();
2502 $passwordFactory->init( RequestContext::getMain()->getConfig() );
2503 $update = array(
2504 'user_newpassword' => $passwordFactory->newFromPlaintext( $str )->toString(),
2505 );
2506
2507 if ( $str === null ) {
2508 $update['user_newpass_time'] = null;
2509 } elseif ( $throttle ) {
2510 $update['user_newpass_time'] = $dbw->timestamp();
2511 }
2512
2513 $dbw->update( 'user', $update, array( 'user_id' => $id ), __METHOD__ );
2514 }
2515
2516 /**
2517 * Has password reminder email been sent within the last
2518 * $wgPasswordReminderResendTime hours?
2519 * @return bool
2520 */
2521 public function isPasswordReminderThrottled() {
2522 global $wgPasswordReminderResendTime;
2523
2524 if ( !$wgPasswordReminderResendTime ) {
2525 return false;
2526 }
2527
2528 $this->load();
2529
2530 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
2531 ? wfGetDB( DB_MASTER )
2532 : wfGetDB( DB_SLAVE );
2533 $newpassTime = $db->selectField(
2534 'user',
2535 'user_newpass_time',
2536 array( 'user_id' => $this->getId() ),
2537 __METHOD__
2538 );
2539
2540 if ( $newpassTime === null ) {
2541 return false;
2542 }
2543 $expiry = wfTimestamp( TS_UNIX, $newpassTime ) + $wgPasswordReminderResendTime * 3600;
2544 return time() < $expiry;
2545 }
2546
2547 /**
2548 * Get the user's e-mail address
2549 * @return string User's email address
2550 */
2551 public function getEmail() {
2552 $this->load();
2553 Hooks::run( 'UserGetEmail', array( $this, &$this->mEmail ) );
2554 return $this->mEmail;
2555 }
2556
2557 /**
2558 * Get the timestamp of the user's e-mail authentication
2559 * @return string TS_MW timestamp
2560 */
2561 public function getEmailAuthenticationTimestamp() {
2562 $this->load();
2563 Hooks::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2564 return $this->mEmailAuthenticated;
2565 }
2566
2567 /**
2568 * Set the user's e-mail address
2569 * @param string $str New e-mail address
2570 */
2571 public function setEmail( $str ) {
2572 $this->load();
2573 if ( $str == $this->mEmail ) {
2574 return;
2575 }
2576 $this->invalidateEmail();
2577 $this->mEmail = $str;
2578 Hooks::run( 'UserSetEmail', array( $this, &$this->mEmail ) );
2579 }
2580
2581 /**
2582 * Set the user's e-mail address and a confirmation mail if needed.
2583 *
2584 * @since 1.20
2585 * @param string $str New e-mail address
2586 * @return Status
2587 */
2588 public function setEmailWithConfirmation( $str ) {
2589 global $wgEnableEmail, $wgEmailAuthentication;
2590
2591 if ( !$wgEnableEmail ) {
2592 return Status::newFatal( 'emaildisabled' );
2593 }
2594
2595 $oldaddr = $this->getEmail();
2596 if ( $str === $oldaddr ) {
2597 return Status::newGood( true );
2598 }
2599
2600 $this->setEmail( $str );
2601
2602 if ( $str !== '' && $wgEmailAuthentication ) {
2603 // Send a confirmation request to the new address if needed
2604 $type = $oldaddr != '' ? 'changed' : 'set';
2605 $result = $this->sendConfirmationMail( $type );
2606 if ( $result->isGood() ) {
2607 // Say to the caller that a confirmation mail has been sent
2608 $result->value = 'eauth';
2609 }
2610 } else {
2611 $result = Status::newGood( true );
2612 }
2613
2614 return $result;
2615 }
2616
2617 /**
2618 * Get the user's real name
2619 * @return string User's real name
2620 */
2621 public function getRealName() {
2622 if ( !$this->isItemLoaded( 'realname' ) ) {
2623 $this->load();
2624 }
2625
2626 return $this->mRealName;
2627 }
2628
2629 /**
2630 * Set the user's real name
2631 * @param string $str New real name
2632 */
2633 public function setRealName( $str ) {
2634 $this->load();
2635 $this->mRealName = $str;
2636 }
2637
2638 /**
2639 * Get the user's current setting for a given option.
2640 *
2641 * @param string $oname The option to check
2642 * @param string $defaultOverride A default value returned if the option does not exist
2643 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2644 * @return string User's current value for the option
2645 * @see getBoolOption()
2646 * @see getIntOption()
2647 */
2648 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2649 global $wgHiddenPrefs;
2650 $this->loadOptions();
2651
2652 # We want 'disabled' preferences to always behave as the default value for
2653 # users, even if they have set the option explicitly in their settings (ie they
2654 # set it, and then it was disabled removing their ability to change it). But
2655 # we don't want to erase the preferences in the database in case the preference
2656 # is re-enabled again. So don't touch $mOptions, just override the returned value
2657 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2658 return self::getDefaultOption( $oname );
2659 }
2660
2661 if ( array_key_exists( $oname, $this->mOptions ) ) {
2662 return $this->mOptions[$oname];
2663 } else {
2664 return $defaultOverride;
2665 }
2666 }
2667
2668 /**
2669 * Get all user's options
2670 *
2671 * @param int $flags Bitwise combination of:
2672 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2673 * to the default value. (Since 1.25)
2674 * @return array
2675 */
2676 public function getOptions( $flags = 0 ) {
2677 global $wgHiddenPrefs;
2678 $this->loadOptions();
2679 $options = $this->mOptions;
2680
2681 # We want 'disabled' preferences to always behave as the default value for
2682 # users, even if they have set the option explicitly in their settings (ie they
2683 # set it, and then it was disabled removing their ability to change it). But
2684 # we don't want to erase the preferences in the database in case the preference
2685 # is re-enabled again. So don't touch $mOptions, just override the returned value
2686 foreach ( $wgHiddenPrefs as $pref ) {
2687 $default = self::getDefaultOption( $pref );
2688 if ( $default !== null ) {
2689 $options[$pref] = $default;
2690 }
2691 }
2692
2693 if ( $flags & self::GETOPTIONS_EXCLUDE_DEFAULTS ) {
2694 $options = array_diff_assoc( $options, self::getDefaultOptions() );
2695 }
2696
2697 return $options;
2698 }
2699
2700 /**
2701 * Get the user's current setting for a given option, as a boolean value.
2702 *
2703 * @param string $oname The option to check
2704 * @return bool User's current value for the option
2705 * @see getOption()
2706 */
2707 public function getBoolOption( $oname ) {
2708 return (bool)$this->getOption( $oname );
2709 }
2710
2711 /**
2712 * Get the user's current setting for a given option, as an integer value.
2713 *
2714 * @param string $oname The option to check
2715 * @param int $defaultOverride A default value returned if the option does not exist
2716 * @return int User's current value for the option
2717 * @see getOption()
2718 */
2719 public function getIntOption( $oname, $defaultOverride = 0 ) {
2720 $val = $this->getOption( $oname );
2721 if ( $val == '' ) {
2722 $val = $defaultOverride;
2723 }
2724 return intval( $val );
2725 }
2726
2727 /**
2728 * Set the given option for a user.
2729 *
2730 * You need to call saveSettings() to actually write to the database.
2731 *
2732 * @param string $oname The option to set
2733 * @param mixed $val New value to set
2734 */
2735 public function setOption( $oname, $val ) {
2736 $this->loadOptions();
2737
2738 // Explicitly NULL values should refer to defaults
2739 if ( is_null( $val ) ) {
2740 $val = self::getDefaultOption( $oname );
2741 }
2742
2743 $this->mOptions[$oname] = $val;
2744 }
2745
2746 /**
2747 * Get a token stored in the preferences (like the watchlist one),
2748 * resetting it if it's empty (and saving changes).
2749 *
2750 * @param string $oname The option name to retrieve the token from
2751 * @return string|bool User's current value for the option, or false if this option is disabled.
2752 * @see resetTokenFromOption()
2753 * @see getOption()
2754 * @deprecated 1.26 Applications should use the OAuth extension
2755 */
2756 public function getTokenFromOption( $oname ) {
2757 global $wgHiddenPrefs;
2758
2759 $id = $this->getId();
2760 if ( !$id || in_array( $oname, $wgHiddenPrefs ) ) {
2761 return false;
2762 }
2763
2764 $token = $this->getOption( $oname );
2765 if ( !$token ) {
2766 // Default to a value based on the user token to avoid space
2767 // wasted on storing tokens for all users. When this option
2768 // is set manually by the user, only then is it stored.
2769 $token = hash_hmac( 'sha1', "$oname:$id", $this->getToken() );
2770 }
2771
2772 return $token;
2773 }
2774
2775 /**
2776 * Reset a token stored in the preferences (like the watchlist one).
2777 * *Does not* save user's preferences (similarly to setOption()).
2778 *
2779 * @param string $oname The option name to reset the token in
2780 * @return string|bool New token value, or false if this option is disabled.
2781 * @see getTokenFromOption()
2782 * @see setOption()
2783 */
2784 public function resetTokenFromOption( $oname ) {
2785 global $wgHiddenPrefs;
2786 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2787 return false;
2788 }
2789
2790 $token = MWCryptRand::generateHex( 40 );
2791 $this->setOption( $oname, $token );
2792 return $token;
2793 }
2794
2795 /**
2796 * Return a list of the types of user options currently returned by
2797 * User::getOptionKinds().
2798 *
2799 * Currently, the option kinds are:
2800 * - 'registered' - preferences which are registered in core MediaWiki or
2801 * by extensions using the UserGetDefaultOptions hook.
2802 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2803 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2804 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2805 * be used by user scripts.
2806 * - 'special' - "preferences" that are not accessible via User::getOptions
2807 * or User::setOptions.
2808 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2809 * These are usually legacy options, removed in newer versions.
2810 *
2811 * The API (and possibly others) use this function to determine the possible
2812 * option types for validation purposes, so make sure to update this when a
2813 * new option kind is added.
2814 *
2815 * @see User::getOptionKinds
2816 * @return array Option kinds
2817 */
2818 public static function listOptionKinds() {
2819 return array(
2820 'registered',
2821 'registered-multiselect',
2822 'registered-checkmatrix',
2823 'userjs',
2824 'special',
2825 'unused'
2826 );
2827 }
2828
2829 /**
2830 * Return an associative array mapping preferences keys to the kind of a preference they're
2831 * used for. Different kinds are handled differently when setting or reading preferences.
2832 *
2833 * See User::listOptionKinds for the list of valid option types that can be provided.
2834 *
2835 * @see User::listOptionKinds
2836 * @param IContextSource $context
2837 * @param array $options Assoc. array with options keys to check as keys.
2838 * Defaults to $this->mOptions.
2839 * @return array The key => kind mapping data
2840 */
2841 public function getOptionKinds( IContextSource $context, $options = null ) {
2842 $this->loadOptions();
2843 if ( $options === null ) {
2844 $options = $this->mOptions;
2845 }
2846
2847 $prefs = Preferences::getPreferences( $this, $context );
2848 $mapping = array();
2849
2850 // Pull out the "special" options, so they don't get converted as
2851 // multiselect or checkmatrix.
2852 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2853 foreach ( $specialOptions as $name => $value ) {
2854 unset( $prefs[$name] );
2855 }
2856
2857 // Multiselect and checkmatrix options are stored in the database with
2858 // one key per option, each having a boolean value. Extract those keys.
2859 $multiselectOptions = array();
2860 foreach ( $prefs as $name => $info ) {
2861 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2862 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2863 $opts = HTMLFormField::flattenOptions( $info['options'] );
2864 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2865
2866 foreach ( $opts as $value ) {
2867 $multiselectOptions["$prefix$value"] = true;
2868 }
2869
2870 unset( $prefs[$name] );
2871 }
2872 }
2873 $checkmatrixOptions = array();
2874 foreach ( $prefs as $name => $info ) {
2875 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2876 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2877 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2878 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2879 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2880
2881 foreach ( $columns as $column ) {
2882 foreach ( $rows as $row ) {
2883 $checkmatrixOptions["$prefix$column-$row"] = true;
2884 }
2885 }
2886
2887 unset( $prefs[$name] );
2888 }
2889 }
2890
2891 // $value is ignored
2892 foreach ( $options as $key => $value ) {
2893 if ( isset( $prefs[$key] ) ) {
2894 $mapping[$key] = 'registered';
2895 } elseif ( isset( $multiselectOptions[$key] ) ) {
2896 $mapping[$key] = 'registered-multiselect';
2897 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2898 $mapping[$key] = 'registered-checkmatrix';
2899 } elseif ( isset( $specialOptions[$key] ) ) {
2900 $mapping[$key] = 'special';
2901 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2902 $mapping[$key] = 'userjs';
2903 } else {
2904 $mapping[$key] = 'unused';
2905 }
2906 }
2907
2908 return $mapping;
2909 }
2910
2911 /**
2912 * Reset certain (or all) options to the site defaults
2913 *
2914 * The optional parameter determines which kinds of preferences will be reset.
2915 * Supported values are everything that can be reported by getOptionKinds()
2916 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2917 *
2918 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2919 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2920 * for backwards-compatibility.
2921 * @param IContextSource|null $context Context source used when $resetKinds
2922 * does not contain 'all', passed to getOptionKinds().
2923 * Defaults to RequestContext::getMain() when null.
2924 */
2925 public function resetOptions(
2926 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2927 IContextSource $context = null
2928 ) {
2929 $this->load();
2930 $defaultOptions = self::getDefaultOptions();
2931
2932 if ( !is_array( $resetKinds ) ) {
2933 $resetKinds = array( $resetKinds );
2934 }
2935
2936 if ( in_array( 'all', $resetKinds ) ) {
2937 $newOptions = $defaultOptions;
2938 } else {
2939 if ( $context === null ) {
2940 $context = RequestContext::getMain();
2941 }
2942
2943 $optionKinds = $this->getOptionKinds( $context );
2944 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2945 $newOptions = array();
2946
2947 // Use default values for the options that should be deleted, and
2948 // copy old values for the ones that shouldn't.
2949 foreach ( $this->mOptions as $key => $value ) {
2950 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2951 if ( array_key_exists( $key, $defaultOptions ) ) {
2952 $newOptions[$key] = $defaultOptions[$key];
2953 }
2954 } else {
2955 $newOptions[$key] = $value;
2956 }
2957 }
2958 }
2959
2960 Hooks::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions, $resetKinds ) );
2961
2962 $this->mOptions = $newOptions;
2963 $this->mOptionsLoaded = true;
2964 }
2965
2966 /**
2967 * Get the user's preferred date format.
2968 * @return string User's preferred date format
2969 */
2970 public function getDatePreference() {
2971 // Important migration for old data rows
2972 if ( is_null( $this->mDatePreference ) ) {
2973 global $wgLang;
2974 $value = $this->getOption( 'date' );
2975 $map = $wgLang->getDatePreferenceMigrationMap();
2976 if ( isset( $map[$value] ) ) {
2977 $value = $map[$value];
2978 }
2979 $this->mDatePreference = $value;
2980 }
2981 return $this->mDatePreference;
2982 }
2983
2984 /**
2985 * Determine based on the wiki configuration and the user's options,
2986 * whether this user must be over HTTPS no matter what.
2987 *
2988 * @return bool
2989 */
2990 public function requiresHTTPS() {
2991 global $wgSecureLogin;
2992 if ( !$wgSecureLogin ) {
2993 return false;
2994 } else {
2995 $https = $this->getBoolOption( 'prefershttps' );
2996 Hooks::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2997 if ( $https ) {
2998 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2999 }
3000 return $https;
3001 }
3002 }
3003
3004 /**
3005 * Get the user preferred stub threshold
3006 *
3007 * @return int
3008 */
3009 public function getStubThreshold() {
3010 global $wgMaxArticleSize; # Maximum article size, in Kb
3011 $threshold = $this->getIntOption( 'stubthreshold' );
3012 if ( $threshold > $wgMaxArticleSize * 1024 ) {
3013 // If they have set an impossible value, disable the preference
3014 // so we can use the parser cache again.
3015 $threshold = 0;
3016 }
3017 return $threshold;
3018 }
3019
3020 /**
3021 * Get the permissions this user has.
3022 * @return array Array of String permission names
3023 */
3024 public function getRights() {
3025 if ( is_null( $this->mRights ) ) {
3026 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
3027 Hooks::run( 'UserGetRights', array( $this, &$this->mRights ) );
3028 // Force reindexation of rights when a hook has unset one of them
3029 $this->mRights = array_values( array_unique( $this->mRights ) );
3030 }
3031 return $this->mRights;
3032 }
3033
3034 /**
3035 * Get the list of explicit group memberships this user has.
3036 * The implicit * and user groups are not included.
3037 * @return array Array of String internal group names
3038 */
3039 public function getGroups() {
3040 $this->load();
3041 $this->loadGroups();
3042 return $this->mGroups;
3043 }
3044
3045 /**
3046 * Get the list of implicit group memberships this user has.
3047 * This includes all explicit groups, plus 'user' if logged in,
3048 * '*' for all accounts, and autopromoted groups
3049 * @param bool $recache Whether to avoid the cache
3050 * @return array Array of String internal group names
3051 */
3052 public function getEffectiveGroups( $recache = false ) {
3053 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
3054 $this->mEffectiveGroups = array_unique( array_merge(
3055 $this->getGroups(), // explicit groups
3056 $this->getAutomaticGroups( $recache ) // implicit groups
3057 ) );
3058 // Hook for additional groups
3059 Hooks::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
3060 // Force reindexation of groups when a hook has unset one of them
3061 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
3062 }
3063 return $this->mEffectiveGroups;
3064 }
3065
3066 /**
3067 * Get the list of implicit group memberships this user has.
3068 * This includes 'user' if logged in, '*' for all accounts,
3069 * and autopromoted groups
3070 * @param bool $recache Whether to avoid the cache
3071 * @return array Array of String internal group names
3072 */
3073 public function getAutomaticGroups( $recache = false ) {
3074 if ( $recache || is_null( $this->mImplicitGroups ) ) {
3075 $this->mImplicitGroups = array( '*' );
3076 if ( $this->getId() ) {
3077 $this->mImplicitGroups[] = 'user';
3078
3079 $this->mImplicitGroups = array_unique( array_merge(
3080 $this->mImplicitGroups,
3081 Autopromote::getAutopromoteGroups( $this )
3082 ) );
3083 }
3084 if ( $recache ) {
3085 // Assure data consistency with rights/groups,
3086 // as getEffectiveGroups() depends on this function
3087 $this->mEffectiveGroups = null;
3088 }
3089 }
3090 return $this->mImplicitGroups;
3091 }
3092
3093 /**
3094 * Returns the groups the user has belonged to.
3095 *
3096 * The user may still belong to the returned groups. Compare with getGroups().
3097 *
3098 * The function will not return groups the user had belonged to before MW 1.17
3099 *
3100 * @return array Names of the groups the user has belonged to.
3101 */
3102 public function getFormerGroups() {
3103 $this->load();
3104
3105 if ( is_null( $this->mFormerGroups ) ) {
3106 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
3107 ? wfGetDB( DB_MASTER )
3108 : wfGetDB( DB_SLAVE );
3109 $res = $db->select( 'user_former_groups',
3110 array( 'ufg_group' ),
3111 array( 'ufg_user' => $this->mId ),
3112 __METHOD__ );
3113 $this->mFormerGroups = array();
3114 foreach ( $res as $row ) {
3115 $this->mFormerGroups[] = $row->ufg_group;
3116 }
3117 }
3118
3119 return $this->mFormerGroups;
3120 }
3121
3122 /**
3123 * Get the user's edit count.
3124 * @return int|null Null for anonymous users
3125 */
3126 public function getEditCount() {
3127 if ( !$this->getId() ) {
3128 return null;
3129 }
3130
3131 if ( $this->mEditCount === null ) {
3132 /* Populate the count, if it has not been populated yet */
3133 $dbr = wfGetDB( DB_SLAVE );
3134 // check if the user_editcount field has been initialized
3135 $count = $dbr->selectField(
3136 'user', 'user_editcount',
3137 array( 'user_id' => $this->mId ),
3138 __METHOD__
3139 );
3140
3141 if ( $count === null ) {
3142 // it has not been initialized. do so.
3143 $count = $this->initEditCount();
3144 }
3145 $this->mEditCount = $count;
3146 }
3147 return (int)$this->mEditCount;
3148 }
3149
3150 /**
3151 * Add the user to the given group.
3152 * This takes immediate effect.
3153 * @param string $group Name of the group to add
3154 * @return bool
3155 */
3156 public function addGroup( $group ) {
3157 $this->load();
3158
3159 if ( !Hooks::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3160 return false;
3161 }
3162
3163 $dbw = wfGetDB( DB_MASTER );
3164 if ( $this->getId() ) {
3165 $dbw->insert( 'user_groups',
3166 array(
3167 'ug_user' => $this->getID(),
3168 'ug_group' => $group,
3169 ),
3170 __METHOD__,
3171 array( 'IGNORE' ) );
3172 }
3173
3174 $this->loadGroups();
3175 $this->mGroups[] = $group;
3176 // In case loadGroups was not called before, we now have the right twice.
3177 // Get rid of the duplicate.
3178 $this->mGroups = array_unique( $this->mGroups );
3179
3180 // Refresh the groups caches, and clear the rights cache so it will be
3181 // refreshed on the next call to $this->getRights().
3182 $this->getEffectiveGroups( true );
3183 $this->mRights = null;
3184
3185 $this->invalidateCache();
3186
3187 return true;
3188 }
3189
3190 /**
3191 * Remove the user from the given group.
3192 * This takes immediate effect.
3193 * @param string $group Name of the group to remove
3194 * @return bool
3195 */
3196 public function removeGroup( $group ) {
3197 $this->load();
3198 if ( !Hooks::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3199 return false;
3200 }
3201
3202 $dbw = wfGetDB( DB_MASTER );
3203 $dbw->delete( 'user_groups',
3204 array(
3205 'ug_user' => $this->getID(),
3206 'ug_group' => $group,
3207 ), __METHOD__
3208 );
3209 // Remember that the user was in this group
3210 $dbw->insert( 'user_former_groups',
3211 array(
3212 'ufg_user' => $this->getID(),
3213 'ufg_group' => $group,
3214 ),
3215 __METHOD__,
3216 array( 'IGNORE' )
3217 );
3218
3219 $this->loadGroups();
3220 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
3221
3222 // Refresh the groups caches, and clear the rights cache so it will be
3223 // refreshed on the next call to $this->getRights().
3224 $this->getEffectiveGroups( true );
3225 $this->mRights = null;
3226
3227 $this->invalidateCache();
3228
3229 return true;
3230 }
3231
3232 /**
3233 * Get whether the user is logged in
3234 * @return bool
3235 */
3236 public function isLoggedIn() {
3237 return $this->getID() != 0;
3238 }
3239
3240 /**
3241 * Get whether the user is anonymous
3242 * @return bool
3243 */
3244 public function isAnon() {
3245 return !$this->isLoggedIn();
3246 }
3247
3248 /**
3249 * Check if user is allowed to access a feature / make an action
3250 *
3251 * @param string ... Permissions to test
3252 * @return bool True if user is allowed to perform *any* of the given actions
3253 */
3254 public function isAllowedAny() {
3255 $permissions = func_get_args();
3256 foreach ( $permissions as $permission ) {
3257 if ( $this->isAllowed( $permission ) ) {
3258 return true;
3259 }
3260 }
3261 return false;
3262 }
3263
3264 /**
3265 *
3266 * @param string ... Permissions to test
3267 * @return bool True if the user is allowed to perform *all* of the given actions
3268 */
3269 public function isAllowedAll() {
3270 $permissions = func_get_args();
3271 foreach ( $permissions as $permission ) {
3272 if ( !$this->isAllowed( $permission ) ) {
3273 return false;
3274 }
3275 }
3276 return true;
3277 }
3278
3279 /**
3280 * Internal mechanics of testing a permission
3281 * @param string $action
3282 * @return bool
3283 */
3284 public function isAllowed( $action = '' ) {
3285 if ( $action === '' ) {
3286 return true; // In the spirit of DWIM
3287 }
3288 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3289 // by misconfiguration: 0 == 'foo'
3290 return in_array( $action, $this->getRights(), true );
3291 }
3292
3293 /**
3294 * Check whether to enable recent changes patrol features for this user
3295 * @return bool True or false
3296 */
3297 public function useRCPatrol() {
3298 global $wgUseRCPatrol;
3299 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3300 }
3301
3302 /**
3303 * Check whether to enable new pages patrol features for this user
3304 * @return bool True or false
3305 */
3306 public function useNPPatrol() {
3307 global $wgUseRCPatrol, $wgUseNPPatrol;
3308 return (
3309 ( $wgUseRCPatrol || $wgUseNPPatrol )
3310 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3311 );
3312 }
3313
3314 /**
3315 * Check whether to enable new files patrol features for this user
3316 * @return bool True or false
3317 */
3318 public function useFilePatrol() {
3319 global $wgUseRCPatrol, $wgUseFilePatrol;
3320 return (
3321 ( $wgUseRCPatrol || $wgUseFilePatrol )
3322 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3323 );
3324 }
3325
3326 /**
3327 * Get the WebRequest object to use with this object
3328 *
3329 * @return WebRequest
3330 */
3331 public function getRequest() {
3332 if ( $this->mRequest ) {
3333 return $this->mRequest;
3334 } else {
3335 global $wgRequest;
3336 return $wgRequest;
3337 }
3338 }
3339
3340 /**
3341 * Get a WatchedItem for this user and $title.
3342 *
3343 * @since 1.22 $checkRights parameter added
3344 * @param Title $title
3345 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3346 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3347 * @return WatchedItem
3348 */
3349 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3350 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3351
3352 if ( isset( $this->mWatchedItems[$key] ) ) {
3353 return $this->mWatchedItems[$key];
3354 }
3355
3356 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3357 $this->mWatchedItems = array();
3358 }
3359
3360 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3361 return $this->mWatchedItems[$key];
3362 }
3363
3364 /**
3365 * Check the watched status of an article.
3366 * @since 1.22 $checkRights parameter added
3367 * @param Title $title Title of the article to look at
3368 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3369 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3370 * @return bool
3371 */
3372 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3373 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3374 }
3375
3376 /**
3377 * Watch an article.
3378 * @since 1.22 $checkRights parameter added
3379 * @param Title $title Title of the article to look at
3380 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3381 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3382 */
3383 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3384 $this->getWatchedItem( $title, $checkRights )->addWatch();
3385 $this->invalidateCache();
3386 }
3387
3388 /**
3389 * Stop watching an article.
3390 * @since 1.22 $checkRights parameter added
3391 * @param Title $title Title of the article to look at
3392 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3393 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3394 */
3395 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3396 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3397 $this->invalidateCache();
3398 }
3399
3400 /**
3401 * Clear the user's notification timestamp for the given title.
3402 * If e-notif e-mails are on, they will receive notification mails on
3403 * the next change of the page if it's watched etc.
3404 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3405 * @param Title $title Title of the article to look at
3406 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3407 */
3408 public function clearNotification( &$title, $oldid = 0 ) {
3409 global $wgUseEnotif, $wgShowUpdatedMarker;
3410
3411 // Do nothing if the database is locked to writes
3412 if ( wfReadOnly() ) {
3413 return;
3414 }
3415
3416 // Do nothing if not allowed to edit the watchlist
3417 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3418 return;
3419 }
3420
3421 // If we're working on user's talk page, we should update the talk page message indicator
3422 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3423 if ( !Hooks::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3424 return;
3425 }
3426
3427 $that = $this;
3428 // Try to update the DB post-send and only if needed...
3429 DeferredUpdates::addCallableUpdate( function() use ( $that, $title, $oldid ) {
3430 if ( !$that->getNewtalk() ) {
3431 return; // no notifications to clear
3432 }
3433
3434 // Delete the last notifications (they stack up)
3435 $that->setNewtalk( false );
3436
3437 // If there is a new, unseen, revision, use its timestamp
3438 $nextid = $oldid
3439 ? $title->getNextRevisionID( $oldid, Title::GAID_FOR_UPDATE )
3440 : null;
3441 if ( $nextid ) {
3442 $that->setNewtalk( true, Revision::newFromId( $nextid ) );
3443 }
3444 } );
3445 }
3446
3447 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3448 return;
3449 }
3450
3451 if ( $this->isAnon() ) {
3452 // Nothing else to do...
3453 return;
3454 }
3455
3456 // Only update the timestamp if the page is being watched.
3457 // The query to find out if it is watched is cached both in memcached and per-invocation,
3458 // and when it does have to be executed, it can be on a slave
3459 // If this is the user's newtalk page, we always update the timestamp
3460 $force = '';
3461 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3462 $force = 'force';
3463 }
3464
3465 $this->getWatchedItem( $title )->resetNotificationTimestamp(
3466 $force, $oldid
3467 );
3468 }
3469
3470 /**
3471 * Resets all of the given user's page-change notification timestamps.
3472 * If e-notif e-mails are on, they will receive notification mails on
3473 * the next change of any watched page.
3474 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3475 */
3476 public function clearAllNotifications() {
3477 if ( wfReadOnly() ) {
3478 return;
3479 }
3480
3481 // Do nothing if not allowed to edit the watchlist
3482 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3483 return;
3484 }
3485
3486 global $wgUseEnotif, $wgShowUpdatedMarker;
3487 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3488 $this->setNewtalk( false );
3489 return;
3490 }
3491 $id = $this->getId();
3492 if ( $id != 0 ) {
3493 $dbw = wfGetDB( DB_MASTER );
3494 $dbw->update( 'watchlist',
3495 array( /* SET */ 'wl_notificationtimestamp' => null ),
3496 array( /* WHERE */ 'wl_user' => $id, 'wl_notificationtimestamp IS NOT NULL' ),
3497 __METHOD__
3498 );
3499 // We also need to clear here the "you have new message" notification for the own user_talk page;
3500 // it's cleared one page view later in WikiPage::doViewUpdates().
3501 }
3502 }
3503
3504 /**
3505 * Set a cookie on the user's client. Wrapper for
3506 * WebResponse::setCookie
3507 * @param string $name Name of the cookie to set
3508 * @param string $value Value to set
3509 * @param int $exp Expiration time, as a UNIX time value;
3510 * if 0 or not specified, use the default $wgCookieExpiration
3511 * @param bool $secure
3512 * true: Force setting the secure attribute when setting the cookie
3513 * false: Force NOT setting the secure attribute when setting the cookie
3514 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3515 * @param array $params Array of options sent passed to WebResponse::setcookie()
3516 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3517 * is passed.
3518 */
3519 protected function setCookie(
3520 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3521 ) {
3522 if ( $request === null ) {
3523 $request = $this->getRequest();
3524 }
3525 $params['secure'] = $secure;
3526 $request->response()->setCookie( $name, $value, $exp, $params );
3527 }
3528
3529 /**
3530 * Clear a cookie on the user's client
3531 * @param string $name Name of the cookie to clear
3532 * @param bool $secure
3533 * true: Force setting the secure attribute when setting the cookie
3534 * false: Force NOT setting the secure attribute when setting the cookie
3535 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3536 * @param array $params Array of options sent passed to WebResponse::setcookie()
3537 */
3538 protected function clearCookie( $name, $secure = null, $params = array() ) {
3539 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3540 }
3541
3542 /**
3543 * Set an extended login cookie on the user's client. The expiry of the cookie
3544 * is controlled by the $wgExtendedLoginCookieExpiration configuration
3545 * variable.
3546 *
3547 * @see User::setCookie
3548 *
3549 * @param string $name Name of the cookie to set
3550 * @param string $value Value to set
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 */
3556 protected function setExtendedLoginCookie( $name, $value, $secure ) {
3557 global $wgExtendedLoginCookieExpiration, $wgCookieExpiration;
3558
3559 $exp = time();
3560 $exp += $wgExtendedLoginCookieExpiration !== null
3561 ? $wgExtendedLoginCookieExpiration
3562 : $wgCookieExpiration;
3563
3564 $this->setCookie( $name, $value, $exp, $secure );
3565 }
3566
3567 /**
3568 * Set the default cookies for this session on the user's client.
3569 *
3570 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3571 * is passed.
3572 * @param bool $secure Whether to force secure/insecure cookies or use default
3573 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3574 */
3575 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3576 global $wgExtendedLoginCookies;
3577
3578 if ( $request === null ) {
3579 $request = $this->getRequest();
3580 }
3581
3582 $this->load();
3583 if ( 0 == $this->mId ) {
3584 return;
3585 }
3586 if ( !$this->mToken ) {
3587 // When token is empty or NULL generate a new one and then save it to the database
3588 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3589 // Simply by setting every cell in the user_token column to NULL and letting them be
3590 // regenerated as users log back into the wiki.
3591 $this->setToken();
3592 if ( !wfReadOnly() ) {
3593 $this->saveSettings();
3594 }
3595 }
3596 $session = array(
3597 'wsUserID' => $this->mId,
3598 'wsToken' => $this->mToken,
3599 'wsUserName' => $this->getName()
3600 );
3601 $cookies = array(
3602 'UserID' => $this->mId,
3603 'UserName' => $this->getName(),
3604 );
3605 if ( $rememberMe ) {
3606 $cookies['Token'] = $this->mToken;
3607 } else {
3608 $cookies['Token'] = false;
3609 }
3610
3611 Hooks::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3612
3613 foreach ( $session as $name => $value ) {
3614 $request->setSessionData( $name, $value );
3615 }
3616 foreach ( $cookies as $name => $value ) {
3617 if ( $value === false ) {
3618 $this->clearCookie( $name );
3619 } elseif ( $rememberMe && in_array( $name, $wgExtendedLoginCookies ) ) {
3620 $this->setExtendedLoginCookie( $name, $value, $secure );
3621 } else {
3622 $this->setCookie( $name, $value, 0, $secure, array(), $request );
3623 }
3624 }
3625
3626 /**
3627 * If wpStickHTTPS was selected, also set an insecure cookie that
3628 * will cause the site to redirect the user to HTTPS, if they access
3629 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3630 * as the one set by centralauth (bug 53538). Also set it to session, or
3631 * standard time setting, based on if rememberme was set.
3632 */
3633 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3634 $this->setCookie(
3635 'forceHTTPS',
3636 'true',
3637 $rememberMe ? 0 : null,
3638 false,
3639 array( 'prefix' => '' ) // no prefix
3640 );
3641 }
3642 }
3643
3644 /**
3645 * Log this user out.
3646 */
3647 public function logout() {
3648 if ( Hooks::run( 'UserLogout', array( &$this ) ) ) {
3649 $this->doLogout();
3650 }
3651 }
3652
3653 /**
3654 * Clear the user's cookies and session, and reset the instance cache.
3655 * @see logout()
3656 */
3657 public function doLogout() {
3658 $this->clearInstanceCache( 'defaults' );
3659
3660 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3661
3662 $this->clearCookie( 'UserID' );
3663 $this->clearCookie( 'Token' );
3664 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3665
3666 // Remember when user logged out, to prevent seeing cached pages
3667 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3668 }
3669
3670 /**
3671 * Save this user's settings into the database.
3672 * @todo Only rarely do all these fields need to be set!
3673 */
3674 public function saveSettings() {
3675 if ( wfReadOnly() ) {
3676 // @TODO: caller should deal with this instead!
3677 // This should really just be an exception.
3678 MWExceptionHandler::logException( new DBExpectedError(
3679 null,
3680 "Could not update user with ID '{$this->mId}'; DB is read-only."
3681 ) );
3682 return;
3683 }
3684
3685 $this->load();
3686 if ( 0 == $this->mId ) {
3687 return; // anon
3688 }
3689
3690 // Get a new user_touched that is higher than the old one.
3691 // This will be used for a CAS check as a last-resort safety
3692 // check against race conditions and slave lag.
3693 $oldTouched = $this->mTouched;
3694 $newTouched = $this->newTouchedTimestamp();
3695
3696 $dbw = wfGetDB( DB_MASTER );
3697 $dbw->update( 'user',
3698 array( /* SET */
3699 'user_name' => $this->mName,
3700 'user_real_name' => $this->mRealName,
3701 'user_email' => $this->mEmail,
3702 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3703 'user_touched' => $dbw->timestamp( $newTouched ),
3704 'user_token' => strval( $this->mToken ),
3705 'user_email_token' => $this->mEmailToken,
3706 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3707 ), array( /* WHERE */
3708 'user_id' => $this->mId,
3709 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3710 ), __METHOD__
3711 );
3712
3713 if ( !$dbw->affectedRows() ) {
3714 // Maybe the problem was a missed cache update; clear it to be safe
3715 $this->clearSharedCache( 'refresh' );
3716 // User was changed in the meantime or loaded with stale data
3717 $from = ( $this->queryFlagsUsed & self::READ_LATEST ) ? 'master' : 'slave';
3718 throw new MWException(
3719 "CAS update failed on user_touched for user ID '{$this->mId}' (read from $from);" .
3720 " the version of the user to be saved is older than the current version."
3721 );
3722 }
3723
3724 $this->mTouched = $newTouched;
3725 $this->saveOptions();
3726
3727 Hooks::run( 'UserSaveSettings', array( $this ) );
3728 $this->clearSharedCache();
3729 $this->getUserPage()->invalidateCache();
3730 }
3731
3732 /**
3733 * If only this user's username is known, and it exists, return the user ID.
3734 *
3735 * @param int $flags Bitfield of User:READ_* constants; useful for existence checks
3736 * @return int
3737 */
3738 public function idForName( $flags = 0 ) {
3739 $s = trim( $this->getName() );
3740 if ( $s === '' ) {
3741 return 0;
3742 }
3743
3744 $db = ( ( $flags & self::READ_LATEST ) == self::READ_LATEST )
3745 ? wfGetDB( DB_MASTER )
3746 : wfGetDB( DB_SLAVE );
3747
3748 $options = ( ( $flags & self::READ_LOCKING ) == self::READ_LOCKING )
3749 ? array( 'LOCK IN SHARE MODE' )
3750 : array();
3751
3752 $id = $db->selectField( 'user',
3753 'user_id', array( 'user_name' => $s ), __METHOD__, $options );
3754
3755 return (int)$id;
3756 }
3757
3758 /**
3759 * Add a user to the database, return the user object
3760 *
3761 * @param string $name Username to add
3762 * @param array $params Array of Strings Non-default parameters to save to
3763 * the database as user_* fields:
3764 * - email: The user's email address.
3765 * - email_authenticated: The email authentication timestamp.
3766 * - real_name: The user's real name.
3767 * - options: An associative array of non-default options.
3768 * - token: Random authentication token. Do not set.
3769 * - registration: Registration timestamp. Do not set.
3770 *
3771 * @return User|null User object, or null if the username already exists.
3772 */
3773 public static function createNew( $name, $params = array() ) {
3774 foreach ( array( 'password', 'newpassword', 'newpass_time', 'password_expires' ) as $field ) {
3775 if ( isset( $params[$field] ) ) {
3776 wfDeprecated( __METHOD__ . " with param '$field'", '1.27' );
3777 unset( $params[$field] );
3778 }
3779 }
3780
3781 $user = new User;
3782 $user->load();
3783 $user->setToken(); // init token
3784 if ( isset( $params['options'] ) ) {
3785 $user->mOptions = $params['options'] + (array)$user->mOptions;
3786 unset( $params['options'] );
3787 }
3788 $dbw = wfGetDB( DB_MASTER );
3789 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3790
3791 $noPass = PasswordFactory::newInvalidPassword()->toString();
3792
3793 $fields = array(
3794 'user_id' => $seqVal,
3795 'user_name' => $name,
3796 'user_password' => $noPass,
3797 'user_newpassword' => $noPass,
3798 'user_email' => $user->mEmail,
3799 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3800 'user_real_name' => $user->mRealName,
3801 'user_token' => strval( $user->mToken ),
3802 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3803 'user_editcount' => 0,
3804 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3805 );
3806 foreach ( $params as $name => $value ) {
3807 $fields["user_$name"] = $value;
3808 }
3809 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3810 if ( $dbw->affectedRows() ) {
3811 $newUser = User::newFromId( $dbw->insertId() );
3812 } else {
3813 $newUser = null;
3814 }
3815 return $newUser;
3816 }
3817
3818 /**
3819 * Add this existing user object to the database. If the user already
3820 * exists, a fatal status object is returned, and the user object is
3821 * initialised with the data from the database.
3822 *
3823 * Previously, this function generated a DB error due to a key conflict
3824 * if the user already existed. Many extension callers use this function
3825 * in code along the lines of:
3826 *
3827 * $user = User::newFromName( $name );
3828 * if ( !$user->isLoggedIn() ) {
3829 * $user->addToDatabase();
3830 * }
3831 * // do something with $user...
3832 *
3833 * However, this was vulnerable to a race condition (bug 16020). By
3834 * initialising the user object if the user exists, we aim to support this
3835 * calling sequence as far as possible.
3836 *
3837 * Note that if the user exists, this function will acquire a write lock,
3838 * so it is still advisable to make the call conditional on isLoggedIn(),
3839 * and to commit the transaction after calling.
3840 *
3841 * @throws MWException
3842 * @return Status
3843 */
3844 public function addToDatabase() {
3845 $this->load();
3846 if ( !$this->mToken ) {
3847 $this->setToken(); // init token
3848 }
3849
3850 $this->mTouched = $this->newTouchedTimestamp();
3851
3852 $noPass = PasswordFactory::newInvalidPassword()->toString();
3853
3854 $dbw = wfGetDB( DB_MASTER );
3855 $inWrite = $dbw->writesOrCallbacksPending();
3856 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3857 $dbw->insert( 'user',
3858 array(
3859 'user_id' => $seqVal,
3860 'user_name' => $this->mName,
3861 'user_password' => $noPass,
3862 'user_newpassword' => $noPass,
3863 'user_email' => $this->mEmail,
3864 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3865 'user_real_name' => $this->mRealName,
3866 'user_token' => strval( $this->mToken ),
3867 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3868 'user_editcount' => 0,
3869 'user_touched' => $dbw->timestamp( $this->mTouched ),
3870 ), __METHOD__,
3871 array( 'IGNORE' )
3872 );
3873 if ( !$dbw->affectedRows() ) {
3874 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3875 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3876 if ( $inWrite ) {
3877 // Can't commit due to pending writes that may need atomicity.
3878 // This may cause some lock contention unlike the case below.
3879 $options = array( 'LOCK IN SHARE MODE' );
3880 $flags = self::READ_LOCKING;
3881 } else {
3882 // Often, this case happens early in views before any writes when
3883 // using CentralAuth. It's should be OK to commit and break the snapshot.
3884 $dbw->commit( __METHOD__, 'flush' );
3885 $options = array();
3886 $flags = self::READ_LATEST;
3887 }
3888 $this->mId = $dbw->selectField( 'user', 'user_id',
3889 array( 'user_name' => $this->mName ), __METHOD__, $options );
3890 $loaded = false;
3891 if ( $this->mId ) {
3892 if ( $this->loadFromDatabase( $flags ) ) {
3893 $loaded = true;
3894 }
3895 }
3896 if ( !$loaded ) {
3897 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3898 "to insert user '{$this->mName}' row, but it was not present in select!" );
3899 }
3900 return Status::newFatal( 'userexists' );
3901 }
3902 $this->mId = $dbw->insertId();
3903 self::$idCacheByName[$this->mName] = $this->mId;
3904
3905 // Clear instance cache other than user table data, which is already accurate
3906 $this->clearInstanceCache();
3907
3908 $this->saveOptions();
3909 return Status::newGood();
3910 }
3911
3912 /**
3913 * If this user is logged-in and blocked,
3914 * block any IP address they've successfully logged in from.
3915 * @return bool A block was spread
3916 */
3917 public function spreadAnyEditBlock() {
3918 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3919 return $this->spreadBlock();
3920 }
3921 return false;
3922 }
3923
3924 /**
3925 * If this (non-anonymous) user is blocked,
3926 * block the IP address they've successfully logged in from.
3927 * @return bool A block was spread
3928 */
3929 protected function spreadBlock() {
3930 wfDebug( __METHOD__ . "()\n" );
3931 $this->load();
3932 if ( $this->mId == 0 ) {
3933 return false;
3934 }
3935
3936 $userblock = Block::newFromTarget( $this->getName() );
3937 if ( !$userblock ) {
3938 return false;
3939 }
3940
3941 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3942 }
3943
3944 /**
3945 * Get whether the user is explicitly blocked from account creation.
3946 * @return bool|Block
3947 */
3948 public function isBlockedFromCreateAccount() {
3949 $this->getBlockedStatus();
3950 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3951 return $this->mBlock;
3952 }
3953
3954 # bug 13611: if the IP address the user is trying to create an account from is
3955 # blocked with createaccount disabled, prevent new account creation there even
3956 # when the user is logged in
3957 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3958 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3959 }
3960 return $this->mBlockedFromCreateAccount instanceof Block
3961 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3962 ? $this->mBlockedFromCreateAccount
3963 : false;
3964 }
3965
3966 /**
3967 * Get whether the user is blocked from using Special:Emailuser.
3968 * @return bool
3969 */
3970 public function isBlockedFromEmailuser() {
3971 $this->getBlockedStatus();
3972 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3973 }
3974
3975 /**
3976 * Get whether the user is allowed to create an account.
3977 * @return bool
3978 */
3979 public function isAllowedToCreateAccount() {
3980 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3981 }
3982
3983 /**
3984 * Get this user's personal page title.
3985 *
3986 * @return Title User's personal page title
3987 */
3988 public function getUserPage() {
3989 return Title::makeTitle( NS_USER, $this->getName() );
3990 }
3991
3992 /**
3993 * Get this user's talk page title.
3994 *
3995 * @return Title User's talk page title
3996 */
3997 public function getTalkPage() {
3998 $title = $this->getUserPage();
3999 return $title->getTalkPage();
4000 }
4001
4002 /**
4003 * Determine whether the user is a newbie. Newbies are either
4004 * anonymous IPs, or the most recently created accounts.
4005 * @return bool
4006 */
4007 public function isNewbie() {
4008 return !$this->isAllowed( 'autoconfirmed' );
4009 }
4010
4011 /**
4012 * Check to see if the given clear-text password is one of the accepted passwords
4013 * @deprecated since 1.27. AuthManager is coming.
4014 * @param string $password User password
4015 * @return bool True if the given password is correct, otherwise False
4016 */
4017 public function checkPassword( $password ) {
4018 global $wgAuth, $wgLegacyEncoding;
4019
4020 $this->load();
4021
4022 // Some passwords will give a fatal Status, which means there is
4023 // some sort of technical or security reason for this password to
4024 // be completely invalid and should never be checked (e.g., T64685)
4025 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
4026 return false;
4027 }
4028
4029 // Certain authentication plugins do NOT want to save
4030 // domain passwords in a mysql database, so we should
4031 // check this (in case $wgAuth->strict() is false).
4032 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
4033 return true;
4034 } elseif ( $wgAuth->strict() ) {
4035 // Auth plugin doesn't allow local authentication
4036 return false;
4037 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
4038 // Auth plugin doesn't allow local authentication for this user name
4039 return false;
4040 }
4041
4042 $passwordFactory = new PasswordFactory();
4043 $passwordFactory->init( RequestContext::getMain()->getConfig() );
4044 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
4045 ? wfGetDB( DB_MASTER )
4046 : wfGetDB( DB_SLAVE );
4047
4048 try {
4049 $mPassword = $passwordFactory->newFromCiphertext( $db->selectField(
4050 'user', 'user_password', array( 'user_id' => $this->getId() ), __METHOD__
4051 ) );
4052 } catch ( PasswordError $e ) {
4053 wfDebug( 'Invalid password hash found in database.' );
4054 $mPassword = PasswordFactory::newInvalidPassword();
4055 }
4056
4057 if ( !$mPassword->equals( $password ) ) {
4058 if ( $wgLegacyEncoding ) {
4059 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
4060 // Check for this with iconv
4061 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
4062 if ( $cp1252Password === $password || !$mPassword->equals( $cp1252Password ) ) {
4063 return false;
4064 }
4065 } else {
4066 return false;
4067 }
4068 }
4069
4070 if ( $passwordFactory->needsUpdate( $mPassword ) && !wfReadOnly() ) {
4071 $this->setPasswordInternal( $password );
4072 }
4073
4074 return true;
4075 }
4076
4077 /**
4078 * Check if the given clear-text password matches the temporary password
4079 * sent by e-mail for password reset operations.
4080 *
4081 * @deprecated since 1.27. AuthManager is coming.
4082 * @param string $plaintext
4083 * @return bool True if matches, false otherwise
4084 */
4085 public function checkTemporaryPassword( $plaintext ) {
4086 global $wgNewPasswordExpiry;
4087
4088 $this->load();
4089
4090 $passwordFactory = new PasswordFactory();
4091 $passwordFactory->init( RequestContext::getMain()->getConfig() );
4092 $db = ( $this->queryFlagsUsed & self::READ_LATEST )
4093 ? wfGetDB( DB_MASTER )
4094 : wfGetDB( DB_SLAVE );
4095
4096 $row = $db->selectRow(
4097 'user',
4098 array( 'user_newpassword', 'user_newpass_time' ),
4099 array( 'user_id' => $this->getId() ),
4100 __METHOD__
4101 );
4102 try {
4103 $newPassword = $passwordFactory->newFromCiphertext( $row->user_newpassword );
4104 } catch ( PasswordError $e ) {
4105 wfDebug( 'Invalid password hash found in database.' );
4106 $newPassword = PasswordFactory::newInvalidPassword();
4107 }
4108
4109 if ( $newPassword->equals( $plaintext ) ) {
4110 if ( is_null( $row->user_newpass_time ) ) {
4111 return true;
4112 }
4113 $expiry = wfTimestamp( TS_UNIX, $row->user_newpass_time ) + $wgNewPasswordExpiry;
4114 return ( time() < $expiry );
4115 } else {
4116 return false;
4117 }
4118 }
4119
4120 /**
4121 * Internal implementation for self::getEditToken() and
4122 * self::matchEditToken().
4123 *
4124 * @param string|array $salt
4125 * @param WebRequest $request
4126 * @param string|int $timestamp
4127 * @return string
4128 */
4129 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4130 if ( $this->isAnon() ) {
4131 return self::EDIT_TOKEN_SUFFIX;
4132 } else {
4133 $token = $request->getSessionData( 'wsEditToken' );
4134 if ( $token === null ) {
4135 $token = MWCryptRand::generateHex( 32 );
4136 $request->setSessionData( 'wsEditToken', $token );
4137 }
4138 if ( is_array( $salt ) ) {
4139 $salt = implode( '|', $salt );
4140 }
4141 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4142 dechex( $timestamp ) .
4143 self::EDIT_TOKEN_SUFFIX;
4144 }
4145 }
4146
4147 /**
4148 * Initialize (if necessary) and return a session token value
4149 * which can be used in edit forms to show that the user's
4150 * login credentials aren't being hijacked with a foreign form
4151 * submission.
4152 *
4153 * @since 1.19
4154 *
4155 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4156 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4157 * @return string The new edit token
4158 */
4159 public function getEditToken( $salt = '', $request = null ) {
4160 return $this->getEditTokenAtTimestamp(
4161 $salt, $request ?: $this->getRequest(), wfTimestamp()
4162 );
4163 }
4164
4165 /**
4166 * Get the embedded timestamp from a token.
4167 * @param string $val Input token
4168 * @return int|null
4169 */
4170 public static function getEditTokenTimestamp( $val ) {
4171 $suffixLen = strlen( self::EDIT_TOKEN_SUFFIX );
4172 if ( strlen( $val ) <= 32 + $suffixLen ) {
4173 return null;
4174 }
4175
4176 return hexdec( substr( $val, 32, -$suffixLen ) );
4177 }
4178
4179 /**
4180 * Check given value against the token value stored in the session.
4181 * A match should confirm that the form was submitted from the
4182 * user's own login session, not a form submission from a third-party
4183 * site.
4184 *
4185 * @param string $val Input value to compare
4186 * @param string $salt Optional function-specific data for hashing
4187 * @param WebRequest|null $request Object to use or null to use $wgRequest
4188 * @param int $maxage Fail tokens older than this, in seconds
4189 * @return bool Whether the token matches
4190 */
4191 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4192 if ( $this->isAnon() ) {
4193 return $val === self::EDIT_TOKEN_SUFFIX;
4194 }
4195
4196 $timestamp = self::getEditTokenTimestamp( $val );
4197 if ( $timestamp === null ) {
4198 return false;
4199 }
4200 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4201 // Expired token
4202 return false;
4203 }
4204
4205 $sessionToken = $this->getEditTokenAtTimestamp(
4206 $salt, $request ?: $this->getRequest(), $timestamp
4207 );
4208
4209 if ( !hash_equals( $sessionToken, $val ) ) {
4210 wfDebug( "User::matchEditToken: broken session data\n" );
4211 }
4212
4213 return hash_equals( $sessionToken, $val );
4214 }
4215
4216 /**
4217 * Check given value against the token value stored in the session,
4218 * ignoring the suffix.
4219 *
4220 * @param string $val Input value to compare
4221 * @param string $salt Optional function-specific data for hashing
4222 * @param WebRequest|null $request Object to use or null to use $wgRequest
4223 * @param int $maxage Fail tokens older than this, in seconds
4224 * @return bool Whether the token matches
4225 */
4226 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4227 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self::EDIT_TOKEN_SUFFIX;
4228 return $this->matchEditToken( $val, $salt, $request, $maxage );
4229 }
4230
4231 /**
4232 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4233 * mail to the user's given address.
4234 *
4235 * @param string $type Message to send, either "created", "changed" or "set"
4236 * @return Status
4237 */
4238 public function sendConfirmationMail( $type = 'created' ) {
4239 global $wgLang;
4240 $expiration = null; // gets passed-by-ref and defined in next line.
4241 $token = $this->confirmationToken( $expiration );
4242 $url = $this->confirmationTokenUrl( $token );
4243 $invalidateURL = $this->invalidationTokenUrl( $token );
4244 $this->saveSettings();
4245
4246 if ( $type == 'created' || $type === false ) {
4247 $message = 'confirmemail_body';
4248 } elseif ( $type === true ) {
4249 $message = 'confirmemail_body_changed';
4250 } else {
4251 // Messages: confirmemail_body_changed, confirmemail_body_set
4252 $message = 'confirmemail_body_' . $type;
4253 }
4254
4255 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4256 wfMessage( $message,
4257 $this->getRequest()->getIP(),
4258 $this->getName(),
4259 $url,
4260 $wgLang->userTimeAndDate( $expiration, $this ),
4261 $invalidateURL,
4262 $wgLang->userDate( $expiration, $this ),
4263 $wgLang->userTime( $expiration, $this ) )->text() );
4264 }
4265
4266 /**
4267 * Send an e-mail to this user's account. Does not check for
4268 * confirmed status or validity.
4269 *
4270 * @param string $subject Message subject
4271 * @param string $body Message body
4272 * @param User|null $from Optional sending user; if unspecified, default
4273 * $wgPasswordSender will be used.
4274 * @param string $replyto Reply-To address
4275 * @return Status
4276 */
4277 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4278 global $wgPasswordSender;
4279
4280 if ( $from instanceof User ) {
4281 $sender = MailAddress::newFromUser( $from );
4282 } else {
4283 $sender = new MailAddress( $wgPasswordSender,
4284 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4285 }
4286 $to = MailAddress::newFromUser( $this );
4287
4288 return UserMailer::send( $to, $sender, $subject, $body, array(
4289 'replyTo' => $replyto,
4290 ) );
4291 }
4292
4293 /**
4294 * Generate, store, and return a new e-mail confirmation code.
4295 * A hash (unsalted, since it's used as a key) is stored.
4296 *
4297 * @note Call saveSettings() after calling this function to commit
4298 * this change to the database.
4299 *
4300 * @param string &$expiration Accepts the expiration time
4301 * @return string New token
4302 */
4303 protected function confirmationToken( &$expiration ) {
4304 global $wgUserEmailConfirmationTokenExpiry;
4305 $now = time();
4306 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4307 $expiration = wfTimestamp( TS_MW, $expires );
4308 $this->load();
4309 $token = MWCryptRand::generateHex( 32 );
4310 $hash = md5( $token );
4311 $this->mEmailToken = $hash;
4312 $this->mEmailTokenExpires = $expiration;
4313 return $token;
4314 }
4315
4316 /**
4317 * Return a URL the user can use to confirm their email address.
4318 * @param string $token Accepts the email confirmation token
4319 * @return string New token URL
4320 */
4321 protected function confirmationTokenUrl( $token ) {
4322 return $this->getTokenUrl( 'ConfirmEmail', $token );
4323 }
4324
4325 /**
4326 * Return a URL the user can use to invalidate their email address.
4327 * @param string $token Accepts the email confirmation token
4328 * @return string New token URL
4329 */
4330 protected function invalidationTokenUrl( $token ) {
4331 return $this->getTokenUrl( 'InvalidateEmail', $token );
4332 }
4333
4334 /**
4335 * Internal function to format the e-mail validation/invalidation URLs.
4336 * This uses a quickie hack to use the
4337 * hardcoded English names of the Special: pages, for ASCII safety.
4338 *
4339 * @note Since these URLs get dropped directly into emails, using the
4340 * short English names avoids insanely long URL-encoded links, which
4341 * also sometimes can get corrupted in some browsers/mailers
4342 * (bug 6957 with Gmail and Internet Explorer).
4343 *
4344 * @param string $page Special page
4345 * @param string $token Token
4346 * @return string Formatted URL
4347 */
4348 protected function getTokenUrl( $page, $token ) {
4349 // Hack to bypass localization of 'Special:'
4350 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4351 return $title->getCanonicalURL();
4352 }
4353
4354 /**
4355 * Mark the e-mail address confirmed.
4356 *
4357 * @note Call saveSettings() after calling this function to commit the change.
4358 *
4359 * @return bool
4360 */
4361 public function confirmEmail() {
4362 // Check if it's already confirmed, so we don't touch the database
4363 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4364 if ( !$this->isEmailConfirmed() ) {
4365 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4366 Hooks::run( 'ConfirmEmailComplete', array( $this ) );
4367 }
4368 return true;
4369 }
4370
4371 /**
4372 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4373 * address if it was already confirmed.
4374 *
4375 * @note Call saveSettings() after calling this function to commit the change.
4376 * @return bool Returns true
4377 */
4378 public function invalidateEmail() {
4379 $this->load();
4380 $this->mEmailToken = null;
4381 $this->mEmailTokenExpires = null;
4382 $this->setEmailAuthenticationTimestamp( null );
4383 $this->mEmail = '';
4384 Hooks::run( 'InvalidateEmailComplete', array( $this ) );
4385 return true;
4386 }
4387
4388 /**
4389 * Set the e-mail authentication timestamp.
4390 * @param string $timestamp TS_MW timestamp
4391 */
4392 public function setEmailAuthenticationTimestamp( $timestamp ) {
4393 $this->load();
4394 $this->mEmailAuthenticated = $timestamp;
4395 Hooks::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4396 }
4397
4398 /**
4399 * Is this user allowed to send e-mails within limits of current
4400 * site configuration?
4401 * @return bool
4402 */
4403 public function canSendEmail() {
4404 global $wgEnableEmail, $wgEnableUserEmail;
4405 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4406 return false;
4407 }
4408 $canSend = $this->isEmailConfirmed();
4409 Hooks::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4410 return $canSend;
4411 }
4412
4413 /**
4414 * Is this user allowed to receive e-mails within limits of current
4415 * site configuration?
4416 * @return bool
4417 */
4418 public function canReceiveEmail() {
4419 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4420 }
4421
4422 /**
4423 * Is this user's e-mail address valid-looking and confirmed within
4424 * limits of the current site configuration?
4425 *
4426 * @note If $wgEmailAuthentication is on, this may require the user to have
4427 * confirmed their address by returning a code or using a password
4428 * sent to the address from the wiki.
4429 *
4430 * @return bool
4431 */
4432 public function isEmailConfirmed() {
4433 global $wgEmailAuthentication;
4434 $this->load();
4435 $confirmed = true;
4436 if ( Hooks::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4437 if ( $this->isAnon() ) {
4438 return false;
4439 }
4440 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4441 return false;
4442 }
4443 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4444 return false;
4445 }
4446 return true;
4447 } else {
4448 return $confirmed;
4449 }
4450 }
4451
4452 /**
4453 * Check whether there is an outstanding request for e-mail confirmation.
4454 * @return bool
4455 */
4456 public function isEmailConfirmationPending() {
4457 global $wgEmailAuthentication;
4458 return $wgEmailAuthentication &&
4459 !$this->isEmailConfirmed() &&
4460 $this->mEmailToken &&
4461 $this->mEmailTokenExpires > wfTimestamp();
4462 }
4463
4464 /**
4465 * Get the timestamp of account creation.
4466 *
4467 * @return string|bool|null Timestamp of account creation, false for
4468 * non-existent/anonymous user accounts, or null if existing account
4469 * but information is not in database.
4470 */
4471 public function getRegistration() {
4472 if ( $this->isAnon() ) {
4473 return false;
4474 }
4475 $this->load();
4476 return $this->mRegistration;
4477 }
4478
4479 /**
4480 * Get the timestamp of the first edit
4481 *
4482 * @return string|bool Timestamp of first edit, or false for
4483 * non-existent/anonymous user accounts.
4484 */
4485 public function getFirstEditTimestamp() {
4486 if ( $this->getId() == 0 ) {
4487 return false; // anons
4488 }
4489 $dbr = wfGetDB( DB_SLAVE );
4490 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4491 array( 'rev_user' => $this->getId() ),
4492 __METHOD__,
4493 array( 'ORDER BY' => 'rev_timestamp ASC' )
4494 );
4495 if ( !$time ) {
4496 return false; // no edits
4497 }
4498 return wfTimestamp( TS_MW, $time );
4499 }
4500
4501 /**
4502 * Get the permissions associated with a given list of groups
4503 *
4504 * @param array $groups Array of Strings List of internal group names
4505 * @return array Array of Strings List of permission key names for given groups combined
4506 */
4507 public static function getGroupPermissions( $groups ) {
4508 global $wgGroupPermissions, $wgRevokePermissions;
4509 $rights = array();
4510 // grant every granted permission first
4511 foreach ( $groups as $group ) {
4512 if ( isset( $wgGroupPermissions[$group] ) ) {
4513 $rights = array_merge( $rights,
4514 // array_filter removes empty items
4515 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4516 }
4517 }
4518 // now revoke the revoked permissions
4519 foreach ( $groups as $group ) {
4520 if ( isset( $wgRevokePermissions[$group] ) ) {
4521 $rights = array_diff( $rights,
4522 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4523 }
4524 }
4525 return array_unique( $rights );
4526 }
4527
4528 /**
4529 * Get all the groups who have a given permission
4530 *
4531 * @param string $role Role to check
4532 * @return array Array of Strings List of internal group names with the given permission
4533 */
4534 public static function getGroupsWithPermission( $role ) {
4535 global $wgGroupPermissions;
4536 $allowedGroups = array();
4537 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4538 if ( self::groupHasPermission( $group, $role ) ) {
4539 $allowedGroups[] = $group;
4540 }
4541 }
4542 return $allowedGroups;
4543 }
4544
4545 /**
4546 * Check, if the given group has the given permission
4547 *
4548 * If you're wanting to check whether all users have a permission, use
4549 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4550 * from anyone.
4551 *
4552 * @since 1.21
4553 * @param string $group Group to check
4554 * @param string $role Role to check
4555 * @return bool
4556 */
4557 public static function groupHasPermission( $group, $role ) {
4558 global $wgGroupPermissions, $wgRevokePermissions;
4559 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4560 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4561 }
4562
4563 /**
4564 * Check if all users may be assumed to have the given permission
4565 *
4566 * We generally assume so if the right is granted to '*' and isn't revoked
4567 * on any group. It doesn't attempt to take grants or other extension
4568 * limitations on rights into account in the general case, though, as that
4569 * would require it to always return false and defeat the purpose.
4570 * Specifically, session-based rights restrictions (such as OAuth or bot
4571 * passwords) are applied based on the current session.
4572 *
4573 * @since 1.22
4574 * @param string $right Right to check
4575 * @return bool
4576 */
4577 public static function isEveryoneAllowed( $right ) {
4578 global $wgGroupPermissions, $wgRevokePermissions;
4579 static $cache = array();
4580
4581 // Use the cached results, except in unit tests which rely on
4582 // being able change the permission mid-request
4583 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4584 return $cache[$right];
4585 }
4586
4587 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4588 $cache[$right] = false;
4589 return false;
4590 }
4591
4592 // If it's revoked anywhere, then everyone doesn't have it
4593 foreach ( $wgRevokePermissions as $rights ) {
4594 if ( isset( $rights[$right] ) && $rights[$right] ) {
4595 $cache[$right] = false;
4596 return false;
4597 }
4598 }
4599
4600 // Allow extensions to say false
4601 if ( !Hooks::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4602 $cache[$right] = false;
4603 return false;
4604 }
4605
4606 $cache[$right] = true;
4607 return true;
4608 }
4609
4610 /**
4611 * Get the localized descriptive name for a group, if it exists
4612 *
4613 * @param string $group Internal group name
4614 * @return string Localized descriptive group name
4615 */
4616 public static function getGroupName( $group ) {
4617 $msg = wfMessage( "group-$group" );
4618 return $msg->isBlank() ? $group : $msg->text();
4619 }
4620
4621 /**
4622 * Get the localized descriptive name for a member of a group, if it exists
4623 *
4624 * @param string $group Internal group name
4625 * @param string $username Username for gender (since 1.19)
4626 * @return string Localized name for group member
4627 */
4628 public static function getGroupMember( $group, $username = '#' ) {
4629 $msg = wfMessage( "group-$group-member", $username );
4630 return $msg->isBlank() ? $group : $msg->text();
4631 }
4632
4633 /**
4634 * Return the set of defined explicit groups.
4635 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4636 * are not included, as they are defined automatically, not in the database.
4637 * @return array Array of internal group names
4638 */
4639 public static function getAllGroups() {
4640 global $wgGroupPermissions, $wgRevokePermissions;
4641 return array_diff(
4642 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4643 self::getImplicitGroups()
4644 );
4645 }
4646
4647 /**
4648 * Get a list of all available permissions.
4649 * @return string[] Array of permission names
4650 */
4651 public static function getAllRights() {
4652 if ( self::$mAllRights === false ) {
4653 global $wgAvailableRights;
4654 if ( count( $wgAvailableRights ) ) {
4655 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4656 } else {
4657 self::$mAllRights = self::$mCoreRights;
4658 }
4659 Hooks::run( 'UserGetAllRights', array( &self::$mAllRights ) );
4660 }
4661 return self::$mAllRights;
4662 }
4663
4664 /**
4665 * Get a list of implicit groups
4666 * @return array Array of Strings Array of internal group names
4667 */
4668 public static function getImplicitGroups() {
4669 global $wgImplicitGroups;
4670
4671 $groups = $wgImplicitGroups;
4672 # Deprecated, use $wgImplicitGroups instead
4673 Hooks::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4674
4675 return $groups;
4676 }
4677
4678 /**
4679 * Get the title of a page describing a particular group
4680 *
4681 * @param string $group Internal group name
4682 * @return Title|bool Title of the page if it exists, false otherwise
4683 */
4684 public static function getGroupPage( $group ) {
4685 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4686 if ( $msg->exists() ) {
4687 $title = Title::newFromText( $msg->text() );
4688 if ( is_object( $title ) ) {
4689 return $title;
4690 }
4691 }
4692 return false;
4693 }
4694
4695 /**
4696 * Create a link to the group in HTML, if available;
4697 * else return the group name.
4698 *
4699 * @param string $group Internal name of the group
4700 * @param string $text The text of the link
4701 * @return string HTML link to the group
4702 */
4703 public static function makeGroupLinkHTML( $group, $text = '' ) {
4704 if ( $text == '' ) {
4705 $text = self::getGroupName( $group );
4706 }
4707 $title = self::getGroupPage( $group );
4708 if ( $title ) {
4709 return Linker::link( $title, htmlspecialchars( $text ) );
4710 } else {
4711 return htmlspecialchars( $text );
4712 }
4713 }
4714
4715 /**
4716 * Create a link to the group in Wikitext, if available;
4717 * else return the group name.
4718 *
4719 * @param string $group Internal name of the group
4720 * @param string $text The text of the link
4721 * @return string Wikilink to the group
4722 */
4723 public static function makeGroupLinkWiki( $group, $text = '' ) {
4724 if ( $text == '' ) {
4725 $text = self::getGroupName( $group );
4726 }
4727 $title = self::getGroupPage( $group );
4728 if ( $title ) {
4729 $page = $title->getFullText();
4730 return "[[$page|$text]]";
4731 } else {
4732 return $text;
4733 }
4734 }
4735
4736 /**
4737 * Returns an array of the groups that a particular group can add/remove.
4738 *
4739 * @param string $group The group to check for whether it can add/remove
4740 * @return array Array( 'add' => array( addablegroups ),
4741 * 'remove' => array( removablegroups ),
4742 * 'add-self' => array( addablegroups to self),
4743 * 'remove-self' => array( removable groups from self) )
4744 */
4745 public static function changeableByGroup( $group ) {
4746 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4747
4748 $groups = array(
4749 'add' => array(),
4750 'remove' => array(),
4751 'add-self' => array(),
4752 'remove-self' => array()
4753 );
4754
4755 if ( empty( $wgAddGroups[$group] ) ) {
4756 // Don't add anything to $groups
4757 } elseif ( $wgAddGroups[$group] === true ) {
4758 // You get everything
4759 $groups['add'] = self::getAllGroups();
4760 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4761 $groups['add'] = $wgAddGroups[$group];
4762 }
4763
4764 // Same thing for remove
4765 if ( empty( $wgRemoveGroups[$group] ) ) {
4766 // Do nothing
4767 } elseif ( $wgRemoveGroups[$group] === true ) {
4768 $groups['remove'] = self::getAllGroups();
4769 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4770 $groups['remove'] = $wgRemoveGroups[$group];
4771 }
4772
4773 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4774 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4775 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4776 if ( is_int( $key ) ) {
4777 $wgGroupsAddToSelf['user'][] = $value;
4778 }
4779 }
4780 }
4781
4782 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4783 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4784 if ( is_int( $key ) ) {
4785 $wgGroupsRemoveFromSelf['user'][] = $value;
4786 }
4787 }
4788 }
4789
4790 // Now figure out what groups the user can add to him/herself
4791 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4792 // Do nothing
4793 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4794 // No idea WHY this would be used, but it's there
4795 $groups['add-self'] = User::getAllGroups();
4796 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4797 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4798 }
4799
4800 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4801 // Do nothing
4802 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4803 $groups['remove-self'] = User::getAllGroups();
4804 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4805 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4806 }
4807
4808 return $groups;
4809 }
4810
4811 /**
4812 * Returns an array of groups that this user can add and remove
4813 * @return array Array( 'add' => array( addablegroups ),
4814 * 'remove' => array( removablegroups ),
4815 * 'add-self' => array( addablegroups to self),
4816 * 'remove-self' => array( removable groups from self) )
4817 */
4818 public function changeableGroups() {
4819 if ( $this->isAllowed( 'userrights' ) ) {
4820 // This group gives the right to modify everything (reverse-
4821 // compatibility with old "userrights lets you change
4822 // everything")
4823 // Using array_merge to make the groups reindexed
4824 $all = array_merge( User::getAllGroups() );
4825 return array(
4826 'add' => $all,
4827 'remove' => $all,
4828 'add-self' => array(),
4829 'remove-self' => array()
4830 );
4831 }
4832
4833 // Okay, it's not so simple, we will have to go through the arrays
4834 $groups = array(
4835 'add' => array(),
4836 'remove' => array(),
4837 'add-self' => array(),
4838 'remove-self' => array()
4839 );
4840 $addergroups = $this->getEffectiveGroups();
4841
4842 foreach ( $addergroups as $addergroup ) {
4843 $groups = array_merge_recursive(
4844 $groups, $this->changeableByGroup( $addergroup )
4845 );
4846 $groups['add'] = array_unique( $groups['add'] );
4847 $groups['remove'] = array_unique( $groups['remove'] );
4848 $groups['add-self'] = array_unique( $groups['add-self'] );
4849 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4850 }
4851 return $groups;
4852 }
4853
4854 /**
4855 * Deferred version of incEditCountImmediate()
4856 */
4857 public function incEditCount() {
4858 $that = $this;
4859 wfGetDB( DB_MASTER )->onTransactionPreCommitOrIdle( function() use ( $that ) {
4860 $that->incEditCountImmediate();
4861 } );
4862 }
4863
4864 /**
4865 * Increment the user's edit-count field.
4866 * Will have no effect for anonymous users.
4867 * @since 1.26
4868 */
4869 public function incEditCountImmediate() {
4870 if ( $this->isAnon() ) {
4871 return;
4872 }
4873
4874 $dbw = wfGetDB( DB_MASTER );
4875 // No rows will be "affected" if user_editcount is NULL
4876 $dbw->update(
4877 'user',
4878 array( 'user_editcount=user_editcount+1' ),
4879 array( 'user_id' => $this->getId(), 'user_editcount IS NOT NULL' ),
4880 __METHOD__
4881 );
4882 // Lazy initialization check...
4883 if ( $dbw->affectedRows() == 0 ) {
4884 // Now here's a goddamn hack...
4885 $dbr = wfGetDB( DB_SLAVE );
4886 if ( $dbr !== $dbw ) {
4887 // If we actually have a slave server, the count is
4888 // at least one behind because the current transaction
4889 // has not been committed and replicated.
4890 $this->initEditCount( 1 );
4891 } else {
4892 // But if DB_SLAVE is selecting the master, then the
4893 // count we just read includes the revision that was
4894 // just added in the working transaction.
4895 $this->initEditCount();
4896 }
4897 }
4898 // Edit count in user cache too
4899 $this->invalidateCache();
4900 }
4901
4902 /**
4903 * Initialize user_editcount from data out of the revision table
4904 *
4905 * @param int $add Edits to add to the count from the revision table
4906 * @return int Number of edits
4907 */
4908 protected function initEditCount( $add = 0 ) {
4909 // Pull from a slave to be less cruel to servers
4910 // Accuracy isn't the point anyway here
4911 $dbr = wfGetDB( DB_SLAVE );
4912 $count = (int)$dbr->selectField(
4913 'revision',
4914 'COUNT(rev_user)',
4915 array( 'rev_user' => $this->getId() ),
4916 __METHOD__
4917 );
4918 $count = $count + $add;
4919
4920 $dbw = wfGetDB( DB_MASTER );
4921 $dbw->update(
4922 'user',
4923 array( 'user_editcount' => $count ),
4924 array( 'user_id' => $this->getId() ),
4925 __METHOD__
4926 );
4927
4928 return $count;
4929 }
4930
4931 /**
4932 * Get the description of a given right
4933 *
4934 * @param string $right Right to query
4935 * @return string Localized description of the right
4936 */
4937 public static function getRightDescription( $right ) {
4938 $key = "right-$right";
4939 $msg = wfMessage( $key );
4940 return $msg->isBlank() ? $right : $msg->text();
4941 }
4942
4943 /**
4944 * Make a new-style password hash
4945 *
4946 * @param string $password Plain-text password
4947 * @param bool|string $salt Optional salt, may be random or the user ID.
4948 * If unspecified or false, will generate one automatically
4949 * @return string Password hash
4950 * @deprecated since 1.24, use Password class
4951 */
4952 public static function crypt( $password, $salt = false ) {
4953 wfDeprecated( __METHOD__, '1.24' );
4954 $passwordFactory = new PasswordFactory();
4955 $passwordFactory->init( RequestContext::getMain()->getConfig() );
4956 $hash = $passwordFactory->newFromPlaintext( $password );
4957 return $hash->toString();
4958 }
4959
4960 /**
4961 * Compare a password hash with a plain-text password. Requires the user
4962 * ID if there's a chance that the hash is an old-style hash.
4963 *
4964 * @param string $hash Password hash
4965 * @param string $password Plain-text password to compare
4966 * @param string|bool $userId User ID for old-style password salt
4967 *
4968 * @return bool
4969 * @deprecated since 1.24, use Password class
4970 */
4971 public static function comparePasswords( $hash, $password, $userId = false ) {
4972 wfDeprecated( __METHOD__, '1.24' );
4973
4974 // Check for *really* old password hashes that don't even have a type
4975 // The old hash format was just an md5 hex hash, with no type information
4976 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4977 global $wgPasswordSalt;
4978 if ( $wgPasswordSalt ) {
4979 $password = ":B:{$userId}:{$hash}";
4980 } else {
4981 $password = ":A:{$hash}";
4982 }
4983 }
4984
4985 $passwordFactory = new PasswordFactory();
4986 $passwordFactory->init( RequestContext::getMain()->getConfig() );
4987 $hash = $passwordFactory->newFromCiphertext( $hash );
4988 return $hash->equals( $password );
4989 }
4990
4991 /**
4992 * Add a newuser log entry for this user.
4993 * Before 1.19 the return value was always true.
4994 *
4995 * @param string|bool $action Account creation type.
4996 * - String, one of the following values:
4997 * - 'create' for an anonymous user creating an account for himself.
4998 * This will force the action's performer to be the created user itself,
4999 * no matter the value of $wgUser
5000 * - 'create2' for a logged in user creating an account for someone else
5001 * - 'byemail' when the created user will receive its password by e-mail
5002 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
5003 * - Boolean means whether the account was created by e-mail (deprecated):
5004 * - true will be converted to 'byemail'
5005 * - false will be converted to 'create' if this object is the same as
5006 * $wgUser and to 'create2' otherwise
5007 *
5008 * @param string $reason User supplied reason
5009 *
5010 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
5011 */
5012 public function addNewUserLogEntry( $action = false, $reason = '' ) {
5013 global $wgUser, $wgNewUserLog;
5014 if ( empty( $wgNewUserLog ) ) {
5015 return true; // disabled
5016 }
5017
5018 if ( $action === true ) {
5019 $action = 'byemail';
5020 } elseif ( $action === false ) {
5021 if ( $this->equals( $wgUser ) ) {
5022 $action = 'create';
5023 } else {
5024 $action = 'create2';
5025 }
5026 }
5027
5028 if ( $action === 'create' || $action === 'autocreate' ) {
5029 $performer = $this;
5030 } else {
5031 $performer = $wgUser;
5032 }
5033
5034 $logEntry = new ManualLogEntry( 'newusers', $action );
5035 $logEntry->setPerformer( $performer );
5036 $logEntry->setTarget( $this->getUserPage() );
5037 $logEntry->setComment( $reason );
5038 $logEntry->setParameters( array(
5039 '4::userid' => $this->getId(),
5040 ) );
5041 $logid = $logEntry->insert();
5042
5043 if ( $action !== 'autocreate' ) {
5044 $logEntry->publish( $logid );
5045 }
5046
5047 return (int)$logid;
5048 }
5049
5050 /**
5051 * Add an autocreate newuser log entry for this user
5052 * Used by things like CentralAuth and perhaps other authplugins.
5053 * Consider calling addNewUserLogEntry() directly instead.
5054 *
5055 * @return bool
5056 */
5057 public function addNewUserLogEntryAutoCreate() {
5058 $this->addNewUserLogEntry( 'autocreate' );
5059
5060 return true;
5061 }
5062
5063 /**
5064 * Load the user options either from cache, the database or an array
5065 *
5066 * @param array $data Rows for the current user out of the user_properties table
5067 */
5068 protected function loadOptions( $data = null ) {
5069 global $wgContLang;
5070
5071 $this->load();
5072
5073 if ( $this->mOptionsLoaded ) {
5074 return;
5075 }
5076
5077 $this->mOptions = self::getDefaultOptions();
5078
5079 if ( !$this->getId() ) {
5080 // For unlogged-in users, load language/variant options from request.
5081 // There's no need to do it for logged-in users: they can set preferences,
5082 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
5083 // so don't override user's choice (especially when the user chooses site default).
5084 $variant = $wgContLang->getDefaultVariant();
5085 $this->mOptions['variant'] = $variant;
5086 $this->mOptions['language'] = $variant;
5087 $this->mOptionsLoaded = true;
5088 return;
5089 }
5090
5091 // Maybe load from the object
5092 if ( !is_null( $this->mOptionOverrides ) ) {
5093 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
5094 foreach ( $this->mOptionOverrides as $key => $value ) {
5095 $this->mOptions[$key] = $value;
5096 }
5097 } else {
5098 if ( !is_array( $data ) ) {
5099 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
5100 // Load from database
5101 $dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
5102 ? wfGetDB( DB_MASTER )
5103 : wfGetDB( DB_SLAVE );
5104
5105 $res = $dbr->select(
5106 'user_properties',
5107 array( 'up_property', 'up_value' ),
5108 array( 'up_user' => $this->getId() ),
5109 __METHOD__
5110 );
5111
5112 $this->mOptionOverrides = array();
5113 $data = array();
5114 foreach ( $res as $row ) {
5115 $data[$row->up_property] = $row->up_value;
5116 }
5117 }
5118 foreach ( $data as $property => $value ) {
5119 $this->mOptionOverrides[$property] = $value;
5120 $this->mOptions[$property] = $value;
5121 }
5122 }
5123
5124 $this->mOptionsLoaded = true;
5125
5126 Hooks::run( 'UserLoadOptions', array( $this, &$this->mOptions ) );
5127 }
5128
5129 /**
5130 * Saves the non-default options for this user, as previously set e.g. via
5131 * setOption(), in the database's "user_properties" (preferences) table.
5132 * Usually used via saveSettings().
5133 */
5134 protected function saveOptions() {
5135 $this->loadOptions();
5136
5137 // Not using getOptions(), to keep hidden preferences in database
5138 $saveOptions = $this->mOptions;
5139
5140 // Allow hooks to abort, for instance to save to a global profile.
5141 // Reset options to default state before saving.
5142 if ( !Hooks::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5143 return;
5144 }
5145
5146 $userId = $this->getId();
5147
5148 $insert_rows = array(); // all the new preference rows
5149 foreach ( $saveOptions as $key => $value ) {
5150 // Don't bother storing default values
5151 $defaultOption = self::getDefaultOption( $key );
5152 if ( ( $defaultOption === null && $value !== false && $value !== null )
5153 || $value != $defaultOption
5154 ) {
5155 $insert_rows[] = array(
5156 'up_user' => $userId,
5157 'up_property' => $key,
5158 'up_value' => $value,
5159 );
5160 }
5161 }
5162
5163 $dbw = wfGetDB( DB_MASTER );
5164
5165 $res = $dbw->select( 'user_properties',
5166 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__ );
5167
5168 // Find prior rows that need to be removed or updated. These rows will
5169 // all be deleted (the later so that INSERT IGNORE applies the new values).
5170 $keysDelete = array();
5171 foreach ( $res as $row ) {
5172 if ( !isset( $saveOptions[$row->up_property] )
5173 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
5174 ) {
5175 $keysDelete[] = $row->up_property;
5176 }
5177 }
5178
5179 if ( count( $keysDelete ) ) {
5180 // Do the DELETE by PRIMARY KEY for prior rows.
5181 // In the past a very large portion of calls to this function are for setting
5182 // 'rememberpassword' for new accounts (a preference that has since been removed).
5183 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5184 // caused gap locks on [max user ID,+infinity) which caused high contention since
5185 // updates would pile up on each other as they are for higher (newer) user IDs.
5186 // It might not be necessary these days, but it shouldn't hurt either.
5187 $dbw->delete( 'user_properties',
5188 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__ );
5189 }
5190 // Insert the new preference rows
5191 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
5192 }
5193
5194 /**
5195 * Lazily instantiate and return a factory object for making passwords
5196 *
5197 * @deprecated since 1.27, create a PasswordFactory directly instead
5198 * @return PasswordFactory
5199 */
5200 public static function getPasswordFactory() {
5201 wfDeprecated( __METHOD__, '1.27' );
5202 $ret = new PasswordFactory();
5203 $ret->init( RequestContext::getMain()->getConfig() );
5204 return $ret;
5205 }
5206
5207 /**
5208 * Provide an array of HTML5 attributes to put on an input element
5209 * intended for the user to enter a new password. This may include
5210 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5211 *
5212 * Do *not* use this when asking the user to enter his current password!
5213 * Regardless of configuration, users may have invalid passwords for whatever
5214 * reason (e.g., they were set before requirements were tightened up).
5215 * Only use it when asking for a new password, like on account creation or
5216 * ResetPass.
5217 *
5218 * Obviously, you still need to do server-side checking.
5219 *
5220 * NOTE: A combination of bugs in various browsers means that this function
5221 * actually just returns array() unconditionally at the moment. May as
5222 * well keep it around for when the browser bugs get fixed, though.
5223 *
5224 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5225 *
5226 * @deprecated since 1.27
5227 * @return array Array of HTML attributes suitable for feeding to
5228 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5229 * That will get confused by the boolean attribute syntax used.)
5230 */
5231 public static function passwordChangeInputAttribs() {
5232 global $wgMinimalPasswordLength;
5233
5234 if ( $wgMinimalPasswordLength == 0 ) {
5235 return array();
5236 }
5237
5238 # Note that the pattern requirement will always be satisfied if the
5239 # input is empty, so we need required in all cases.
5240
5241 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5242 # if e-mail confirmation is being used. Since HTML5 input validation
5243 # is b0rked anyway in some browsers, just return nothing. When it's
5244 # re-enabled, fix this code to not output required for e-mail
5245 # registration.
5246 # $ret = array( 'required' );
5247 $ret = array();
5248
5249 # We can't actually do this right now, because Opera 9.6 will print out
5250 # the entered password visibly in its error message! When other
5251 # browsers add support for this attribute, or Opera fixes its support,
5252 # we can add support with a version check to avoid doing this on Opera
5253 # versions where it will be a problem. Reported to Opera as
5254 # DSK-262266, but they don't have a public bug tracker for us to follow.
5255 /*
5256 if ( $wgMinimalPasswordLength > 1 ) {
5257 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5258 $ret['title'] = wfMessage( 'passwordtooshort' )
5259 ->numParams( $wgMinimalPasswordLength )->text();
5260 }
5261 */
5262
5263 return $ret;
5264 }
5265
5266 /**
5267 * Return the list of user fields that should be selected to create
5268 * a new user object.
5269 * @return array
5270 */
5271 public static function selectFields() {
5272 return array(
5273 'user_id',
5274 'user_name',
5275 'user_real_name',
5276 'user_email',
5277 'user_touched',
5278 'user_token',
5279 'user_email_authenticated',
5280 'user_email_token',
5281 'user_email_token_expires',
5282 'user_registration',
5283 'user_editcount',
5284 );
5285 }
5286
5287 /**
5288 * Factory function for fatal permission-denied errors
5289 *
5290 * @since 1.22
5291 * @param string $permission User right required
5292 * @return Status
5293 */
5294 static function newFatalPermissionDeniedStatus( $permission ) {
5295 global $wgLang;
5296
5297 $groups = array_map(
5298 array( 'User', 'makeGroupLinkWiki' ),
5299 User::getGroupsWithPermission( $permission )
5300 );
5301
5302 if ( $groups ) {
5303 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5304 } else {
5305 return Status::newFatal( 'badaccess-group0' );
5306 }
5307 }
5308
5309 /**
5310 * Get a new instance of this user that was loaded from the master via a locking read
5311 *
5312 * Use this instead of the main context User when updating that user. This avoids races
5313 * where that user was loaded from a slave or even the master but without proper locks.
5314 *
5315 * @return User|null Returns null if the user was not found in the DB
5316 * @since 1.27
5317 */
5318 public function getInstanceForUpdate() {
5319 if ( !$this->getId() ) {
5320 return null; // anon
5321 }
5322
5323 $user = self::newFromId( $this->getId() );
5324 if ( !$user->loadFromId( self::READ_EXCLUSIVE ) ) {
5325 return null;
5326 }
5327
5328 return $user;
5329 }
5330
5331 /**
5332 * Checks if two user objects point to the same user.
5333 *
5334 * @since 1.25
5335 * @param User $user
5336 * @return bool
5337 */
5338 public function equals( User $user ) {
5339 return $this->getName() === $user->getName();
5340 }
5341 }