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