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