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