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