Merge "Added CAS-style logic to User::saveSettings as a final sanity check"
[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 $dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
1375 ? wfGetDB( DB_MASTER )
1376 : wfGetDB( DB_SLAVE );
1377 $res = $dbr->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 && ( $this->mPassword === null || $this->mNewpassword === null ) ) {
1399 $this->loadFromRow( wfGetDB( DB_MASTER )->selectRow(
1400 'user',
1401 array( 'user_password', 'user_newpassword', 'user_newpass_time', 'user_password_expires' ),
1402 array( 'user_id' => $this->getId() ),
1403 __METHOD__
1404 ) );
1405 }
1406 }
1407
1408 /**
1409 * Add the user to the group if he/she meets given criteria.
1410 *
1411 * Contrary to autopromotion by \ref $wgAutopromote, the group will be
1412 * possible to remove manually via Special:UserRights. In such case it
1413 * will not be re-added automatically. The user will also not lose the
1414 * group if they no longer meet the criteria.
1415 *
1416 * @param string $event Key in $wgAutopromoteOnce (each one has groups/criteria)
1417 *
1418 * @return array Array of groups the user has been promoted to.
1419 *
1420 * @see $wgAutopromoteOnce
1421 */
1422 public function addAutopromoteOnceGroups( $event ) {
1423 global $wgAutopromoteOnceLogInRC, $wgAuth;
1424
1425 $toPromote = array();
1426 if ( !wfReadOnly() && $this->getId() ) {
1427 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1428 if ( count( $toPromote ) ) {
1429 $oldGroups = $this->getGroups(); // previous groups
1430
1431 foreach ( $toPromote as $group ) {
1432 $this->addGroup( $group );
1433 }
1434 // update groups in external authentication database
1435 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1436
1437 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1438
1439 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1440 $logEntry->setPerformer( $this );
1441 $logEntry->setTarget( $this->getUserPage() );
1442 $logEntry->setParameters( array(
1443 '4::oldgroups' => $oldGroups,
1444 '5::newgroups' => $newGroups,
1445 ) );
1446 $logid = $logEntry->insert();
1447 if ( $wgAutopromoteOnceLogInRC ) {
1448 $logEntry->publish( $logid );
1449 }
1450 }
1451 }
1452
1453 return $toPromote;
1454 }
1455
1456 /**
1457 * Clear various cached data stored in this object. The cache of the user table
1458 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1459 *
1460 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1461 * given source. May be "name", "id", "defaults", "session", or false for no reload.
1462 */
1463 public function clearInstanceCache( $reloadFrom = false ) {
1464 $this->mNewtalk = -1;
1465 $this->mDatePreference = null;
1466 $this->mBlockedby = -1; # Unset
1467 $this->mHash = false;
1468 $this->mRights = null;
1469 $this->mEffectiveGroups = null;
1470 $this->mImplicitGroups = null;
1471 $this->mGroups = null;
1472 $this->mOptions = null;
1473 $this->mOptionsLoaded = false;
1474 $this->mEditCount = null;
1475
1476 if ( $reloadFrom ) {
1477 $this->mLoadedItems = array();
1478 $this->mFrom = $reloadFrom;
1479 }
1480 }
1481
1482 /**
1483 * Combine the language default options with any site-specific options
1484 * and add the default language variants.
1485 *
1486 * @return array Array of String options
1487 */
1488 public static function getDefaultOptions() {
1489 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1490
1491 static $defOpt = null;
1492 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1493 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1494 // mid-request and see that change reflected in the return value of this function.
1495 // Which is insane and would never happen during normal MW operation
1496 return $defOpt;
1497 }
1498
1499 $defOpt = $wgDefaultUserOptions;
1500 // Default language setting
1501 $defOpt['language'] = $wgContLang->getCode();
1502 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1503 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1504 }
1505 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1506 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1507 }
1508 $defOpt['skin'] = Skin::normalizeKey( $wgDefaultSkin );
1509
1510 Hooks::run( 'UserGetDefaultOptions', array( &$defOpt ) );
1511
1512 return $defOpt;
1513 }
1514
1515 /**
1516 * Get a given default option value.
1517 *
1518 * @param string $opt Name of option to retrieve
1519 * @return string Default option value
1520 */
1521 public static function getDefaultOption( $opt ) {
1522 $defOpts = self::getDefaultOptions();
1523 if ( isset( $defOpts[$opt] ) ) {
1524 return $defOpts[$opt];
1525 } else {
1526 return null;
1527 }
1528 }
1529
1530 /**
1531 * Get blocking information
1532 * @param bool $bFromSlave Whether to check the slave database first.
1533 * To improve performance, non-critical checks are done against slaves.
1534 * Check when actually saving should be done against master.
1535 */
1536 private function getBlockedStatus( $bFromSlave = true ) {
1537 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1538
1539 if ( -1 != $this->mBlockedby ) {
1540 return;
1541 }
1542
1543 wfDebug( __METHOD__ . ": checking...\n" );
1544
1545 // Initialize data...
1546 // Otherwise something ends up stomping on $this->mBlockedby when
1547 // things get lazy-loaded later, causing false positive block hits
1548 // due to -1 !== 0. Probably session-related... Nothing should be
1549 // overwriting mBlockedby, surely?
1550 $this->load();
1551
1552 # We only need to worry about passing the IP address to the Block generator if the
1553 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1554 # know which IP address they're actually coming from
1555 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1556 $ip = $this->getRequest()->getIP();
1557 } else {
1558 $ip = null;
1559 }
1560
1561 // User/IP blocking
1562 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1563
1564 // Proxy blocking
1565 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1566 && !in_array( $ip, $wgProxyWhitelist )
1567 ) {
1568 // Local list
1569 if ( self::isLocallyBlockedProxy( $ip ) ) {
1570 $block = new Block;
1571 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1572 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1573 $block->setTarget( $ip );
1574 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1575 $block = new Block;
1576 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1577 $block->mReason = wfMessage( 'sorbsreason' )->text();
1578 $block->setTarget( $ip );
1579 }
1580 }
1581
1582 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1583 if ( !$block instanceof Block
1584 && $wgApplyIpBlocksToXff
1585 && $ip !== null
1586 && !$this->isAllowed( 'proxyunbannable' )
1587 && !in_array( $ip, $wgProxyWhitelist )
1588 ) {
1589 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1590 $xff = array_map( 'trim', explode( ',', $xff ) );
1591 $xff = array_diff( $xff, array( $ip ) );
1592 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1593 $block = Block::chooseBlock( $xffblocks, $xff );
1594 if ( $block instanceof Block ) {
1595 # Mangle the reason to alert the user that the block
1596 # originated from matching the X-Forwarded-For header.
1597 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1598 }
1599 }
1600
1601 if ( $block instanceof Block ) {
1602 wfDebug( __METHOD__ . ": Found block.\n" );
1603 $this->mBlock = $block;
1604 $this->mBlockedby = $block->getByName();
1605 $this->mBlockreason = $block->mReason;
1606 $this->mHideName = $block->mHideName;
1607 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1608 } else {
1609 $this->mBlockedby = '';
1610 $this->mHideName = 0;
1611 $this->mAllowUsertalk = false;
1612 }
1613
1614 // Extensions
1615 Hooks::run( 'GetBlockedStatus', array( &$this ) );
1616
1617 }
1618
1619 /**
1620 * Whether the given IP is in a DNS blacklist.
1621 *
1622 * @param string $ip IP to check
1623 * @param bool $checkWhitelist Whether to check the whitelist first
1624 * @return bool True if blacklisted.
1625 */
1626 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1627 global $wgEnableDnsBlacklist, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1628
1629 if ( !$wgEnableDnsBlacklist ) {
1630 return false;
1631 }
1632
1633 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1634 return false;
1635 }
1636
1637 return $this->inDnsBlacklist( $ip, $wgDnsBlacklistUrls );
1638 }
1639
1640 /**
1641 * Whether the given IP is in a given DNS blacklist.
1642 *
1643 * @param string $ip IP to check
1644 * @param string|array $bases Array of Strings: URL of the DNS blacklist
1645 * @return bool True if blacklisted.
1646 */
1647 public function inDnsBlacklist( $ip, $bases ) {
1648
1649 $found = false;
1650 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1651 if ( IP::isIPv4( $ip ) ) {
1652 // Reverse IP, bug 21255
1653 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1654
1655 foreach ( (array)$bases as $base ) {
1656 // Make hostname
1657 // If we have an access key, use that too (ProjectHoneypot, etc.)
1658 if ( is_array( $base ) ) {
1659 if ( count( $base ) >= 2 ) {
1660 // Access key is 1, base URL is 0
1661 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1662 } else {
1663 $host = "$ipReversed.{$base[0]}";
1664 }
1665 } else {
1666 $host = "$ipReversed.$base";
1667 }
1668
1669 // Send query
1670 $ipList = gethostbynamel( $host );
1671
1672 if ( $ipList ) {
1673 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!" );
1674 $found = true;
1675 break;
1676 } else {
1677 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base." );
1678 }
1679 }
1680 }
1681
1682 return $found;
1683 }
1684
1685 /**
1686 * Check if an IP address is in the local proxy list
1687 *
1688 * @param string $ip
1689 *
1690 * @return bool
1691 */
1692 public static function isLocallyBlockedProxy( $ip ) {
1693 global $wgProxyList;
1694
1695 if ( !$wgProxyList ) {
1696 return false;
1697 }
1698
1699 if ( !is_array( $wgProxyList ) ) {
1700 // Load from the specified file
1701 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1702 }
1703
1704 if ( !is_array( $wgProxyList ) ) {
1705 $ret = false;
1706 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1707 $ret = true;
1708 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1709 // Old-style flipped proxy list
1710 $ret = true;
1711 } else {
1712 $ret = false;
1713 }
1714 return $ret;
1715 }
1716
1717 /**
1718 * Is this user subject to rate limiting?
1719 *
1720 * @return bool True if rate limited
1721 */
1722 public function isPingLimitable() {
1723 global $wgRateLimitsExcludedIPs;
1724 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1725 // No other good way currently to disable rate limits
1726 // for specific IPs. :P
1727 // But this is a crappy hack and should die.
1728 return false;
1729 }
1730 return !$this->isAllowed( 'noratelimit' );
1731 }
1732
1733 /**
1734 * Primitive rate limits: enforce maximum actions per time period
1735 * to put a brake on flooding.
1736 *
1737 * The method generates both a generic profiling point and a per action one
1738 * (suffix being "-$action".
1739 *
1740 * @note When using a shared cache like memcached, IP-address
1741 * last-hit counters will be shared across wikis.
1742 *
1743 * @param string $action Action to enforce; 'edit' if unspecified
1744 * @param int $incrBy Positive amount to increment counter by [defaults to 1]
1745 * @return bool True if a rate limiter was tripped
1746 */
1747 public function pingLimiter( $action = 'edit', $incrBy = 1 ) {
1748 // Call the 'PingLimiter' hook
1749 $result = false;
1750 if ( !Hooks::run( 'PingLimiter', array( &$this, $action, &$result, $incrBy ) ) ) {
1751 return $result;
1752 }
1753
1754 global $wgRateLimits;
1755 if ( !isset( $wgRateLimits[$action] ) ) {
1756 return false;
1757 }
1758
1759 // Some groups shouldn't trigger the ping limiter, ever
1760 if ( !$this->isPingLimitable() ) {
1761 return false;
1762 }
1763
1764 global $wgMemc;
1765
1766 $limits = $wgRateLimits[$action];
1767 $keys = array();
1768 $id = $this->getId();
1769 $userLimit = false;
1770
1771 if ( isset( $limits['anon'] ) && $id == 0 ) {
1772 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1773 }
1774
1775 if ( isset( $limits['user'] ) && $id != 0 ) {
1776 $userLimit = $limits['user'];
1777 }
1778 if ( $this->isNewbie() ) {
1779 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1780 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1781 }
1782 if ( isset( $limits['ip'] ) ) {
1783 $ip = $this->getRequest()->getIP();
1784 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1785 }
1786 if ( isset( $limits['subnet'] ) ) {
1787 $ip = $this->getRequest()->getIP();
1788 $matches = array();
1789 $subnet = false;
1790 if ( IP::isIPv6( $ip ) ) {
1791 $parts = IP::parseRange( "$ip/64" );
1792 $subnet = $parts[0];
1793 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1794 // IPv4
1795 $subnet = $matches[1];
1796 }
1797 if ( $subnet !== false ) {
1798 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1799 }
1800 }
1801 }
1802 // Check for group-specific permissions
1803 // If more than one group applies, use the group with the highest limit
1804 foreach ( $this->getGroups() as $group ) {
1805 if ( isset( $limits[$group] ) ) {
1806 if ( $userLimit === false
1807 || $limits[$group][0] / $limits[$group][1] > $userLimit[0] / $userLimit[1]
1808 ) {
1809 $userLimit = $limits[$group];
1810 }
1811 }
1812 }
1813 // Set the user limit key
1814 if ( $userLimit !== false ) {
1815 list( $max, $period ) = $userLimit;
1816 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1817 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1818 }
1819
1820 $triggered = false;
1821 foreach ( $keys as $key => $limit ) {
1822 list( $max, $period ) = $limit;
1823 $summary = "(limit $max in {$period}s)";
1824 $count = $wgMemc->get( $key );
1825 // Already pinged?
1826 if ( $count ) {
1827 if ( $count >= $max ) {
1828 wfDebugLog( 'ratelimit', "User '{$this->getName()}' " .
1829 "(IP {$this->getRequest()->getIP()}) tripped $key at $count $summary" );
1830 $triggered = true;
1831 } else {
1832 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1833 }
1834 } else {
1835 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1836 if ( $incrBy > 0 ) {
1837 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1838 }
1839 }
1840 if ( $incrBy > 0 ) {
1841 $wgMemc->incr( $key, $incrBy );
1842 }
1843 }
1844
1845 return $triggered;
1846 }
1847
1848 /**
1849 * Check if user is blocked
1850 *
1851 * @param bool $bFromSlave Whether to check the slave database instead of
1852 * the master. Hacked from false due to horrible probs on site.
1853 * @return bool True if blocked, false otherwise
1854 */
1855 public function isBlocked( $bFromSlave = true ) {
1856 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1857 }
1858
1859 /**
1860 * Get the block affecting the user, or null if the user is not blocked
1861 *
1862 * @param bool $bFromSlave Whether to check the slave database instead of the master
1863 * @return Block|null
1864 */
1865 public function getBlock( $bFromSlave = true ) {
1866 $this->getBlockedStatus( $bFromSlave );
1867 return $this->mBlock instanceof Block ? $this->mBlock : null;
1868 }
1869
1870 /**
1871 * Check if user is blocked from editing a particular article
1872 *
1873 * @param Title $title Title to check
1874 * @param bool $bFromSlave Whether to check the slave database instead of the master
1875 * @return bool
1876 */
1877 public function isBlockedFrom( $title, $bFromSlave = false ) {
1878 global $wgBlockAllowsUTEdit;
1879
1880 $blocked = $this->isBlocked( $bFromSlave );
1881 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1882 // If a user's name is suppressed, they cannot make edits anywhere
1883 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName()
1884 && $title->getNamespace() == NS_USER_TALK ) {
1885 $blocked = false;
1886 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1887 }
1888
1889 Hooks::run( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1890
1891 return $blocked;
1892 }
1893
1894 /**
1895 * If user is blocked, return the name of the user who placed the block
1896 * @return string Name of blocker
1897 */
1898 public function blockedBy() {
1899 $this->getBlockedStatus();
1900 return $this->mBlockedby;
1901 }
1902
1903 /**
1904 * If user is blocked, return the specified reason for the block
1905 * @return string Blocking reason
1906 */
1907 public function blockedFor() {
1908 $this->getBlockedStatus();
1909 return $this->mBlockreason;
1910 }
1911
1912 /**
1913 * If user is blocked, return the ID for the block
1914 * @return int Block ID
1915 */
1916 public function getBlockId() {
1917 $this->getBlockedStatus();
1918 return ( $this->mBlock ? $this->mBlock->getId() : false );
1919 }
1920
1921 /**
1922 * Check if user is blocked on all wikis.
1923 * Do not use for actual edit permission checks!
1924 * This is intended for quick UI checks.
1925 *
1926 * @param string $ip IP address, uses current client if none given
1927 * @return bool True if blocked, false otherwise
1928 */
1929 public function isBlockedGlobally( $ip = '' ) {
1930 if ( $this->mBlockedGlobally !== null ) {
1931 return $this->mBlockedGlobally;
1932 }
1933 // User is already an IP?
1934 if ( IP::isIPAddress( $this->getName() ) ) {
1935 $ip = $this->getName();
1936 } elseif ( !$ip ) {
1937 $ip = $this->getRequest()->getIP();
1938 }
1939 $blocked = false;
1940 Hooks::run( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1941 $this->mBlockedGlobally = (bool)$blocked;
1942 return $this->mBlockedGlobally;
1943 }
1944
1945 /**
1946 * Check if user account is locked
1947 *
1948 * @return bool True if locked, false otherwise
1949 */
1950 public function isLocked() {
1951 if ( $this->mLocked !== null ) {
1952 return $this->mLocked;
1953 }
1954 global $wgAuth;
1955 $authUser = $wgAuth->getUserInstance( $this );
1956 $this->mLocked = (bool)$authUser->isLocked();
1957 return $this->mLocked;
1958 }
1959
1960 /**
1961 * Check if user account is hidden
1962 *
1963 * @return bool True if hidden, false otherwise
1964 */
1965 public function isHidden() {
1966 if ( $this->mHideName !== null ) {
1967 return $this->mHideName;
1968 }
1969 $this->getBlockedStatus();
1970 if ( !$this->mHideName ) {
1971 global $wgAuth;
1972 $authUser = $wgAuth->getUserInstance( $this );
1973 $this->mHideName = (bool)$authUser->isHidden();
1974 }
1975 return $this->mHideName;
1976 }
1977
1978 /**
1979 * Get the user's ID.
1980 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1981 */
1982 public function getId() {
1983 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1984 // Special case, we know the user is anonymous
1985 return 0;
1986 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1987 // Don't load if this was initialized from an ID
1988 $this->load();
1989 }
1990 return $this->mId;
1991 }
1992
1993 /**
1994 * Set the user and reload all fields according to a given ID
1995 * @param int $v User ID to reload
1996 */
1997 public function setId( $v ) {
1998 $this->mId = $v;
1999 $this->clearInstanceCache( 'id' );
2000 }
2001
2002 /**
2003 * Get the user name, or the IP of an anonymous user
2004 * @return string User's name or IP address
2005 */
2006 public function getName() {
2007 if ( $this->isItemLoaded( 'name', 'only' ) ) {
2008 // Special case optimisation
2009 return $this->mName;
2010 } else {
2011 $this->load();
2012 if ( $this->mName === false ) {
2013 // Clean up IPs
2014 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
2015 }
2016 return $this->mName;
2017 }
2018 }
2019
2020 /**
2021 * Set the user name.
2022 *
2023 * This does not reload fields from the database according to the given
2024 * name. Rather, it is used to create a temporary "nonexistent user" for
2025 * later addition to the database. It can also be used to set the IP
2026 * address for an anonymous user to something other than the current
2027 * remote IP.
2028 *
2029 * @note User::newFromName() has roughly the same function, when the named user
2030 * does not exist.
2031 * @param string $str New user name to set
2032 */
2033 public function setName( $str ) {
2034 $this->load();
2035 $this->mName = $str;
2036 }
2037
2038 /**
2039 * Get the user's name escaped by underscores.
2040 * @return string Username escaped by underscores.
2041 */
2042 public function getTitleKey() {
2043 return str_replace( ' ', '_', $this->getName() );
2044 }
2045
2046 /**
2047 * Check if the user has new messages.
2048 * @return bool True if the user has new messages
2049 */
2050 public function getNewtalk() {
2051 $this->load();
2052
2053 // Load the newtalk status if it is unloaded (mNewtalk=-1)
2054 if ( $this->mNewtalk === -1 ) {
2055 $this->mNewtalk = false; # reset talk page status
2056
2057 // Check memcached separately for anons, who have no
2058 // entire User object stored in there.
2059 if ( !$this->mId ) {
2060 global $wgDisableAnonTalk;
2061 if ( $wgDisableAnonTalk ) {
2062 // Anon newtalk disabled by configuration.
2063 $this->mNewtalk = false;
2064 } else {
2065 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
2066 }
2067 } else {
2068 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
2069 }
2070 }
2071
2072 return (bool)$this->mNewtalk;
2073 }
2074
2075 /**
2076 * Return the data needed to construct links for new talk page message
2077 * alerts. If there are new messages, this will return an associative array
2078 * with the following data:
2079 * wiki: The database name of the wiki
2080 * link: Root-relative link to the user's talk page
2081 * rev: The last talk page revision that the user has seen or null. This
2082 * is useful for building diff links.
2083 * If there are no new messages, it returns an empty array.
2084 * @note This function was designed to accomodate multiple talk pages, but
2085 * currently only returns a single link and revision.
2086 * @return array
2087 */
2088 public function getNewMessageLinks() {
2089 $talks = array();
2090 if ( !Hooks::run( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
2091 return $talks;
2092 } elseif ( !$this->getNewtalk() ) {
2093 return array();
2094 }
2095 $utp = $this->getTalkPage();
2096 $dbr = wfGetDB( DB_SLAVE );
2097 // Get the "last viewed rev" timestamp from the oldest message notification
2098 $timestamp = $dbr->selectField( 'user_newtalk',
2099 'MIN(user_last_timestamp)',
2100 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
2101 __METHOD__ );
2102 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
2103 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
2104 }
2105
2106 /**
2107 * Get the revision ID for the last talk page revision viewed by the talk
2108 * page owner.
2109 * @return int|null Revision ID or null
2110 */
2111 public function getNewMessageRevisionId() {
2112 $newMessageRevisionId = null;
2113 $newMessageLinks = $this->getNewMessageLinks();
2114 if ( $newMessageLinks ) {
2115 // Note: getNewMessageLinks() never returns more than a single link
2116 // and it is always for the same wiki, but we double-check here in
2117 // case that changes some time in the future.
2118 if ( count( $newMessageLinks ) === 1
2119 && $newMessageLinks[0]['wiki'] === wfWikiID()
2120 && $newMessageLinks[0]['rev']
2121 ) {
2122 $newMessageRevision = $newMessageLinks[0]['rev'];
2123 $newMessageRevisionId = $newMessageRevision->getId();
2124 }
2125 }
2126 return $newMessageRevisionId;
2127 }
2128
2129 /**
2130 * Internal uncached check for new messages
2131 *
2132 * @see getNewtalk()
2133 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2134 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2135 * @return bool True if the user has new messages
2136 */
2137 protected function checkNewtalk( $field, $id ) {
2138 $dbr = wfGetDB( DB_SLAVE );
2139
2140 $ok = $dbr->selectField( 'user_newtalk', $field, array( $field => $id ), __METHOD__ );
2141
2142 return $ok !== false;
2143 }
2144
2145 /**
2146 * Add or update the new messages flag
2147 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2148 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2149 * @param Revision|null $curRev New, as yet unseen revision of the user talk page. Ignored if null.
2150 * @return bool True if successful, false otherwise
2151 */
2152 protected function updateNewtalk( $field, $id, $curRev = null ) {
2153 // Get timestamp of the talk page revision prior to the current one
2154 $prevRev = $curRev ? $curRev->getPrevious() : false;
2155 $ts = $prevRev ? $prevRev->getTimestamp() : null;
2156 // Mark the user as having new messages since this revision
2157 $dbw = wfGetDB( DB_MASTER );
2158 $dbw->insert( 'user_newtalk',
2159 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
2160 __METHOD__,
2161 'IGNORE' );
2162 if ( $dbw->affectedRows() ) {
2163 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
2164 return true;
2165 } else {
2166 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
2167 return false;
2168 }
2169 }
2170
2171 /**
2172 * Clear the new messages flag for the given user
2173 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
2174 * @param string|int $id User's IP address for anonymous users, User ID otherwise
2175 * @return bool True if successful, false otherwise
2176 */
2177 protected function deleteNewtalk( $field, $id ) {
2178 $dbw = wfGetDB( DB_MASTER );
2179 $dbw->delete( 'user_newtalk',
2180 array( $field => $id ),
2181 __METHOD__ );
2182 if ( $dbw->affectedRows() ) {
2183 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
2184 return true;
2185 } else {
2186 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
2187 return false;
2188 }
2189 }
2190
2191 /**
2192 * Update the 'You have new messages!' status.
2193 * @param bool $val Whether the user has new messages
2194 * @param Revision $curRev New, as yet unseen revision of the user talk
2195 * page. Ignored if null or !$val.
2196 */
2197 public function setNewtalk( $val, $curRev = null ) {
2198 if ( wfReadOnly() ) {
2199 return;
2200 }
2201
2202 $this->load();
2203 $this->mNewtalk = $val;
2204
2205 if ( $this->isAnon() ) {
2206 $field = 'user_ip';
2207 $id = $this->getName();
2208 } else {
2209 $field = 'user_id';
2210 $id = $this->getId();
2211 }
2212 global $wgMemc;
2213
2214 if ( $val ) {
2215 $changed = $this->updateNewtalk( $field, $id, $curRev );
2216 } else {
2217 $changed = $this->deleteNewtalk( $field, $id );
2218 }
2219
2220 if ( $this->isAnon() ) {
2221 // Anons have a separate memcached space, since
2222 // user records aren't kept for them.
2223 $key = wfMemcKey( 'newtalk', 'ip', $id );
2224 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
2225 }
2226 if ( $changed ) {
2227 $this->invalidateCache();
2228 }
2229 }
2230
2231 /**
2232 * Generate a current or new-future timestamp to be stored in the
2233 * user_touched field when we update things.
2234 * @return string Timestamp in TS_MW format
2235 */
2236 private function newTouchedTimestamp() {
2237 global $wgClockSkewFudge;
2238
2239 $time = wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2240 if ( $this->mTouched && $time <= $this->mTouched ) {
2241 $time = wfTimestamp( TS_MW, wfTimestamp( TS_UNIX, $this->mTouched ) + 1 );
2242 }
2243
2244 return $time;
2245 }
2246
2247 /**
2248 * Clear user data from memcached.
2249 * Use after applying fun updates to the database; caller's
2250 * responsibility to update user_touched if appropriate.
2251 *
2252 * Called implicitly from invalidateCache() and saveSettings().
2253 */
2254 public function clearSharedCache() {
2255 global $wgMemc;
2256
2257 $this->load();
2258 if ( $this->mId ) {
2259 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2260 }
2261 }
2262
2263 /**
2264 * Immediately touch the user data cache for this account.
2265 * Updates user_touched field, and removes account data from memcached
2266 * for reload on the next hit.
2267 */
2268 public function invalidateCache() {
2269 if ( wfReadOnly() ) {
2270 return;
2271 }
2272 $this->load();
2273 if ( $this->mId ) {
2274 $this->mTouched = $this->newTouchedTimestamp();
2275
2276 $dbw = wfGetDB( DB_MASTER );
2277 $userid = $this->mId;
2278 $touched = $this->mTouched;
2279 $method = __METHOD__;
2280 $dbw->onTransactionIdle( function () use ( $dbw, $userid, $touched, $method ) {
2281 // Prevent contention slams by checking user_touched first
2282 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2283 $needsPurge = $dbw->selectField( 'user', '1',
2284 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2285 if ( $needsPurge ) {
2286 $dbw->update( 'user',
2287 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2288 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2289 $method
2290 );
2291 }
2292 } );
2293 $this->clearSharedCache();
2294 }
2295 }
2296
2297 /**
2298 * Update the "touched" timestamp for the user
2299 *
2300 * This is useful on various login/logout events when making sure that
2301 * a browser or proxy that has multiple tenants does not suffer cache
2302 * pollution where the new user sees the old users content. The value
2303 * of getTouched() is checked when determining 304 vs 200 responses.
2304 * Unlike invalidateCache(), this preserves the User object cache and
2305 * avoids database writes.
2306 *
2307 * @since 1.25
2308 */
2309 public function touch() {
2310 global $wgMemc;
2311
2312 $this->load();
2313
2314 if ( $this->mId ) {
2315 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId );
2316 $timestamp = $this->newTouchedTimestamp();
2317 $wgMemc->set( $key, $timestamp );
2318 $this->mQuickTouched = $timestamp;
2319 }
2320 }
2321
2322 /**
2323 * Validate the cache for this account.
2324 * @param string $timestamp A timestamp in TS_MW format
2325 * @return bool
2326 */
2327 public function validateCache( $timestamp ) {
2328 return ( $timestamp >= $this->getTouched() );
2329 }
2330
2331 /**
2332 * Get the user touched timestamp
2333 * @return string TS_MW Timestamp
2334 */
2335 public function getTouched() {
2336 global $wgMemc;
2337
2338 $this->load();
2339
2340 if ( $this->mId ) {
2341 if ( $this->mQuickTouched === null ) {
2342 $key = wfMemcKey( 'user-quicktouched', 'id', $this->mId );
2343 $timestamp = $wgMemc->get( $key );
2344 if ( $timestamp ) {
2345 $this->mQuickTouched = $timestamp;
2346 } else {
2347 # Set the timestamp to get HTTP 304 cache hits
2348 $this->touch();
2349 }
2350 }
2351
2352 return max( $this->mTouched, $this->mQuickTouched );
2353 }
2354
2355 return $this->mTouched;
2356 }
2357
2358 /**
2359 * @return Password
2360 * @since 1.24
2361 */
2362 public function getPassword() {
2363 $this->loadPasswords();
2364
2365 return $this->mPassword;
2366 }
2367
2368 /**
2369 * @return Password
2370 * @since 1.24
2371 */
2372 public function getTemporaryPassword() {
2373 $this->loadPasswords();
2374
2375 return $this->mNewpassword;
2376 }
2377
2378 /**
2379 * Set the password and reset the random token.
2380 * Calls through to authentication plugin if necessary;
2381 * will have no effect if the auth plugin refuses to
2382 * pass the change through or if the legal password
2383 * checks fail.
2384 *
2385 * As a special case, setting the password to null
2386 * wipes it, so the account cannot be logged in until
2387 * a new password is set, for instance via e-mail.
2388 *
2389 * @param string $str New password to set
2390 * @throws PasswordError On failure
2391 *
2392 * @return bool
2393 */
2394 public function setPassword( $str ) {
2395 global $wgAuth;
2396
2397 $this->loadPasswords();
2398
2399 if ( $str !== null ) {
2400 if ( !$wgAuth->allowPasswordChange() ) {
2401 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2402 }
2403
2404 $status = $this->checkPasswordValidity( $str );
2405 if ( !$status->isGood() ) {
2406 throw new PasswordError( $status->getMessage()->text() );
2407 }
2408 }
2409
2410 if ( !$wgAuth->setPassword( $this, $str ) ) {
2411 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2412 }
2413
2414 $this->setInternalPassword( $str );
2415
2416 return true;
2417 }
2418
2419 /**
2420 * Set the password and reset the random token unconditionally.
2421 *
2422 * @param string|null $str New password to set or null to set an invalid
2423 * password hash meaning that the user will not be able to log in
2424 * through the web interface.
2425 */
2426 public function setInternalPassword( $str ) {
2427 $this->setToken();
2428
2429 $passwordFactory = self::getPasswordFactory();
2430 $this->mPassword = $passwordFactory->newFromPlaintext( $str );
2431
2432 $this->mNewpassword = $passwordFactory->newFromCiphertext( null );
2433 $this->mNewpassTime = null;
2434 }
2435
2436 /**
2437 * Get the user's current token.
2438 * @param bool $forceCreation Force the generation of a new token if the
2439 * user doesn't have one (default=true for backwards compatibility).
2440 * @return string Token
2441 */
2442 public function getToken( $forceCreation = true ) {
2443 $this->load();
2444 if ( !$this->mToken && $forceCreation ) {
2445 $this->setToken();
2446 }
2447 return $this->mToken;
2448 }
2449
2450 /**
2451 * Set the random token (used for persistent authentication)
2452 * Called from loadDefaults() among other places.
2453 *
2454 * @param string|bool $token If specified, set the token to this value
2455 */
2456 public function setToken( $token = false ) {
2457 $this->load();
2458 if ( !$token ) {
2459 $this->mToken = MWCryptRand::generateHex( self::TOKEN_LENGTH );
2460 } else {
2461 $this->mToken = $token;
2462 }
2463 }
2464
2465 /**
2466 * Set the password for a password reminder or new account email
2467 *
2468 * @param string $str New password to set or null to set an invalid
2469 * password hash meaning that the user will not be able to use it
2470 * @param bool $throttle If true, reset the throttle timestamp to the present
2471 */
2472 public function setNewpassword( $str, $throttle = true ) {
2473 $this->loadPasswords();
2474
2475 $this->mNewpassword = self::getPasswordFactory()->newFromPlaintext( $str );
2476 if ( $str === null ) {
2477 $this->mNewpassTime = null;
2478 } elseif ( $throttle ) {
2479 $this->mNewpassTime = wfTimestampNow();
2480 }
2481 }
2482
2483 /**
2484 * Has password reminder email been sent within the last
2485 * $wgPasswordReminderResendTime hours?
2486 * @return bool
2487 */
2488 public function isPasswordReminderThrottled() {
2489 global $wgPasswordReminderResendTime;
2490 $this->load();
2491 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2492 return false;
2493 }
2494 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2495 return time() < $expiry;
2496 }
2497
2498 /**
2499 * Get the user's e-mail address
2500 * @return string User's email address
2501 */
2502 public function getEmail() {
2503 $this->load();
2504 Hooks::run( 'UserGetEmail', array( $this, &$this->mEmail ) );
2505 return $this->mEmail;
2506 }
2507
2508 /**
2509 * Get the timestamp of the user's e-mail authentication
2510 * @return string TS_MW timestamp
2511 */
2512 public function getEmailAuthenticationTimestamp() {
2513 $this->load();
2514 Hooks::run( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2515 return $this->mEmailAuthenticated;
2516 }
2517
2518 /**
2519 * Set the user's e-mail address
2520 * @param string $str New e-mail address
2521 */
2522 public function setEmail( $str ) {
2523 $this->load();
2524 if ( $str == $this->mEmail ) {
2525 return;
2526 }
2527 $this->invalidateEmail();
2528 $this->mEmail = $str;
2529 Hooks::run( 'UserSetEmail', array( $this, &$this->mEmail ) );
2530 }
2531
2532 /**
2533 * Set the user's e-mail address and a confirmation mail if needed.
2534 *
2535 * @since 1.20
2536 * @param string $str New e-mail address
2537 * @return Status
2538 */
2539 public function setEmailWithConfirmation( $str ) {
2540 global $wgEnableEmail, $wgEmailAuthentication;
2541
2542 if ( !$wgEnableEmail ) {
2543 return Status::newFatal( 'emaildisabled' );
2544 }
2545
2546 $oldaddr = $this->getEmail();
2547 if ( $str === $oldaddr ) {
2548 return Status::newGood( true );
2549 }
2550
2551 $this->setEmail( $str );
2552
2553 if ( $str !== '' && $wgEmailAuthentication ) {
2554 // Send a confirmation request to the new address if needed
2555 $type = $oldaddr != '' ? 'changed' : 'set';
2556 $result = $this->sendConfirmationMail( $type );
2557 if ( $result->isGood() ) {
2558 // Say to the caller that a confirmation mail has been sent
2559 $result->value = 'eauth';
2560 }
2561 } else {
2562 $result = Status::newGood( true );
2563 }
2564
2565 return $result;
2566 }
2567
2568 /**
2569 * Get the user's real name
2570 * @return string User's real name
2571 */
2572 public function getRealName() {
2573 if ( !$this->isItemLoaded( 'realname' ) ) {
2574 $this->load();
2575 }
2576
2577 return $this->mRealName;
2578 }
2579
2580 /**
2581 * Set the user's real name
2582 * @param string $str New real name
2583 */
2584 public function setRealName( $str ) {
2585 $this->load();
2586 $this->mRealName = $str;
2587 }
2588
2589 /**
2590 * Get the user's current setting for a given option.
2591 *
2592 * @param string $oname The option to check
2593 * @param string $defaultOverride A default value returned if the option does not exist
2594 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2595 * @return string User's current value for the option
2596 * @see getBoolOption()
2597 * @see getIntOption()
2598 */
2599 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2600 global $wgHiddenPrefs;
2601 $this->loadOptions();
2602
2603 # We want 'disabled' preferences to always behave as the default value for
2604 # users, even if they have set the option explicitly in their settings (ie they
2605 # set it, and then it was disabled removing their ability to change it). But
2606 # we don't want to erase the preferences in the database in case the preference
2607 # is re-enabled again. So don't touch $mOptions, just override the returned value
2608 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2609 return self::getDefaultOption( $oname );
2610 }
2611
2612 if ( array_key_exists( $oname, $this->mOptions ) ) {
2613 return $this->mOptions[$oname];
2614 } else {
2615 return $defaultOverride;
2616 }
2617 }
2618
2619 /**
2620 * Get all user's options
2621 *
2622 * @param int $flags Bitwise combination of:
2623 * User::GETOPTIONS_EXCLUDE_DEFAULTS Exclude user options that are set
2624 * to the default value. (Since 1.25)
2625 * @return array
2626 */
2627 public function getOptions( $flags = 0 ) {
2628 global $wgHiddenPrefs;
2629 $this->loadOptions();
2630 $options = $this->mOptions;
2631
2632 # We want 'disabled' preferences to always behave as the default value for
2633 # users, even if they have set the option explicitly in their settings (ie they
2634 # set it, and then it was disabled removing their ability to change it). But
2635 # we don't want to erase the preferences in the database in case the preference
2636 # is re-enabled again. So don't touch $mOptions, just override the returned value
2637 foreach ( $wgHiddenPrefs as $pref ) {
2638 $default = self::getDefaultOption( $pref );
2639 if ( $default !== null ) {
2640 $options[$pref] = $default;
2641 }
2642 }
2643
2644 if ( $flags & self::GETOPTIONS_EXCLUDE_DEFAULTS ) {
2645 $options = array_diff_assoc( $options, self::getDefaultOptions() );
2646 }
2647
2648 return $options;
2649 }
2650
2651 /**
2652 * Get the user's current setting for a given option, as a boolean value.
2653 *
2654 * @param string $oname The option to check
2655 * @return bool User's current value for the option
2656 * @see getOption()
2657 */
2658 public function getBoolOption( $oname ) {
2659 return (bool)$this->getOption( $oname );
2660 }
2661
2662 /**
2663 * Get the user's current setting for a given option, as an integer value.
2664 *
2665 * @param string $oname The option to check
2666 * @param int $defaultOverride A default value returned if the option does not exist
2667 * @return int User's current value for the option
2668 * @see getOption()
2669 */
2670 public function getIntOption( $oname, $defaultOverride = 0 ) {
2671 $val = $this->getOption( $oname );
2672 if ( $val == '' ) {
2673 $val = $defaultOverride;
2674 }
2675 return intval( $val );
2676 }
2677
2678 /**
2679 * Set the given option for a user.
2680 *
2681 * You need to call saveSettings() to actually write to the database.
2682 *
2683 * @param string $oname The option to set
2684 * @param mixed $val New value to set
2685 */
2686 public function setOption( $oname, $val ) {
2687 $this->loadOptions();
2688
2689 // Explicitly NULL values should refer to defaults
2690 if ( is_null( $val ) ) {
2691 $val = self::getDefaultOption( $oname );
2692 }
2693
2694 $this->mOptions[$oname] = $val;
2695 }
2696
2697 /**
2698 * Get a token stored in the preferences (like the watchlist one),
2699 * resetting it if it's empty (and saving changes).
2700 *
2701 * @param string $oname The option name to retrieve the token from
2702 * @return string|bool User's current value for the option, or false if this option is disabled.
2703 * @see resetTokenFromOption()
2704 * @see getOption()
2705 */
2706 public function getTokenFromOption( $oname ) {
2707 global $wgHiddenPrefs;
2708 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2709 return false;
2710 }
2711
2712 $token = $this->getOption( $oname );
2713 if ( !$token ) {
2714 $token = $this->resetTokenFromOption( $oname );
2715 if ( !wfReadOnly() ) {
2716 $this->saveSettings();
2717 }
2718 }
2719 return $token;
2720 }
2721
2722 /**
2723 * Reset a token stored in the preferences (like the watchlist one).
2724 * *Does not* save user's preferences (similarly to setOption()).
2725 *
2726 * @param string $oname The option name to reset the token in
2727 * @return string|bool New token value, or false if this option is disabled.
2728 * @see getTokenFromOption()
2729 * @see setOption()
2730 */
2731 public function resetTokenFromOption( $oname ) {
2732 global $wgHiddenPrefs;
2733 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2734 return false;
2735 }
2736
2737 $token = MWCryptRand::generateHex( 40 );
2738 $this->setOption( $oname, $token );
2739 return $token;
2740 }
2741
2742 /**
2743 * Return a list of the types of user options currently returned by
2744 * User::getOptionKinds().
2745 *
2746 * Currently, the option kinds are:
2747 * - 'registered' - preferences which are registered in core MediaWiki or
2748 * by extensions using the UserGetDefaultOptions hook.
2749 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2750 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2751 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2752 * be used by user scripts.
2753 * - 'special' - "preferences" that are not accessible via User::getOptions
2754 * or User::setOptions.
2755 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2756 * These are usually legacy options, removed in newer versions.
2757 *
2758 * The API (and possibly others) use this function to determine the possible
2759 * option types for validation purposes, so make sure to update this when a
2760 * new option kind is added.
2761 *
2762 * @see User::getOptionKinds
2763 * @return array Option kinds
2764 */
2765 public static function listOptionKinds() {
2766 return array(
2767 'registered',
2768 'registered-multiselect',
2769 'registered-checkmatrix',
2770 'userjs',
2771 'special',
2772 'unused'
2773 );
2774 }
2775
2776 /**
2777 * Return an associative array mapping preferences keys to the kind of a preference they're
2778 * used for. Different kinds are handled differently when setting or reading preferences.
2779 *
2780 * See User::listOptionKinds for the list of valid option types that can be provided.
2781 *
2782 * @see User::listOptionKinds
2783 * @param IContextSource $context
2784 * @param array $options Assoc. array with options keys to check as keys.
2785 * Defaults to $this->mOptions.
2786 * @return array The key => kind mapping data
2787 */
2788 public function getOptionKinds( IContextSource $context, $options = null ) {
2789 $this->loadOptions();
2790 if ( $options === null ) {
2791 $options = $this->mOptions;
2792 }
2793
2794 $prefs = Preferences::getPreferences( $this, $context );
2795 $mapping = array();
2796
2797 // Pull out the "special" options, so they don't get converted as
2798 // multiselect or checkmatrix.
2799 $specialOptions = array_fill_keys( Preferences::getSaveBlacklist(), true );
2800 foreach ( $specialOptions as $name => $value ) {
2801 unset( $prefs[$name] );
2802 }
2803
2804 // Multiselect and checkmatrix options are stored in the database with
2805 // one key per option, each having a boolean value. Extract those keys.
2806 $multiselectOptions = array();
2807 foreach ( $prefs as $name => $info ) {
2808 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2809 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2810 $opts = HTMLFormField::flattenOptions( $info['options'] );
2811 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2812
2813 foreach ( $opts as $value ) {
2814 $multiselectOptions["$prefix$value"] = true;
2815 }
2816
2817 unset( $prefs[$name] );
2818 }
2819 }
2820 $checkmatrixOptions = array();
2821 foreach ( $prefs as $name => $info ) {
2822 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2823 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2824 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2825 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2826 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2827
2828 foreach ( $columns as $column ) {
2829 foreach ( $rows as $row ) {
2830 $checkmatrixOptions["$prefix$column-$row"] = true;
2831 }
2832 }
2833
2834 unset( $prefs[$name] );
2835 }
2836 }
2837
2838 // $value is ignored
2839 foreach ( $options as $key => $value ) {
2840 if ( isset( $prefs[$key] ) ) {
2841 $mapping[$key] = 'registered';
2842 } elseif ( isset( $multiselectOptions[$key] ) ) {
2843 $mapping[$key] = 'registered-multiselect';
2844 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2845 $mapping[$key] = 'registered-checkmatrix';
2846 } elseif ( isset( $specialOptions[$key] ) ) {
2847 $mapping[$key] = 'special';
2848 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2849 $mapping[$key] = 'userjs';
2850 } else {
2851 $mapping[$key] = 'unused';
2852 }
2853 }
2854
2855 return $mapping;
2856 }
2857
2858 /**
2859 * Reset certain (or all) options to the site defaults
2860 *
2861 * The optional parameter determines which kinds of preferences will be reset.
2862 * Supported values are everything that can be reported by getOptionKinds()
2863 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2864 *
2865 * @param array|string $resetKinds Which kinds of preferences to reset. Defaults to
2866 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2867 * for backwards-compatibility.
2868 * @param IContextSource|null $context Context source used when $resetKinds
2869 * does not contain 'all', passed to getOptionKinds().
2870 * Defaults to RequestContext::getMain() when null.
2871 */
2872 public function resetOptions(
2873 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2874 IContextSource $context = null
2875 ) {
2876 $this->load();
2877 $defaultOptions = self::getDefaultOptions();
2878
2879 if ( !is_array( $resetKinds ) ) {
2880 $resetKinds = array( $resetKinds );
2881 }
2882
2883 if ( in_array( 'all', $resetKinds ) ) {
2884 $newOptions = $defaultOptions;
2885 } else {
2886 if ( $context === null ) {
2887 $context = RequestContext::getMain();
2888 }
2889
2890 $optionKinds = $this->getOptionKinds( $context );
2891 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2892 $newOptions = array();
2893
2894 // Use default values for the options that should be deleted, and
2895 // copy old values for the ones that shouldn't.
2896 foreach ( $this->mOptions as $key => $value ) {
2897 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2898 if ( array_key_exists( $key, $defaultOptions ) ) {
2899 $newOptions[$key] = $defaultOptions[$key];
2900 }
2901 } else {
2902 $newOptions[$key] = $value;
2903 }
2904 }
2905 }
2906
2907 Hooks::run( 'UserResetAllOptions', array( $this, &$newOptions, $this->mOptions, $resetKinds ) );
2908
2909 $this->mOptions = $newOptions;
2910 $this->mOptionsLoaded = true;
2911 }
2912
2913 /**
2914 * Get the user's preferred date format.
2915 * @return string User's preferred date format
2916 */
2917 public function getDatePreference() {
2918 // Important migration for old data rows
2919 if ( is_null( $this->mDatePreference ) ) {
2920 global $wgLang;
2921 $value = $this->getOption( 'date' );
2922 $map = $wgLang->getDatePreferenceMigrationMap();
2923 if ( isset( $map[$value] ) ) {
2924 $value = $map[$value];
2925 }
2926 $this->mDatePreference = $value;
2927 }
2928 return $this->mDatePreference;
2929 }
2930
2931 /**
2932 * Determine based on the wiki configuration and the user's options,
2933 * whether this user must be over HTTPS no matter what.
2934 *
2935 * @return bool
2936 */
2937 public function requiresHTTPS() {
2938 global $wgSecureLogin;
2939 if ( !$wgSecureLogin ) {
2940 return false;
2941 } else {
2942 $https = $this->getBoolOption( 'prefershttps' );
2943 Hooks::run( 'UserRequiresHTTPS', array( $this, &$https ) );
2944 if ( $https ) {
2945 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2946 }
2947 return $https;
2948 }
2949 }
2950
2951 /**
2952 * Get the user preferred stub threshold
2953 *
2954 * @return int
2955 */
2956 public function getStubThreshold() {
2957 global $wgMaxArticleSize; # Maximum article size, in Kb
2958 $threshold = $this->getIntOption( 'stubthreshold' );
2959 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2960 // If they have set an impossible value, disable the preference
2961 // so we can use the parser cache again.
2962 $threshold = 0;
2963 }
2964 return $threshold;
2965 }
2966
2967 /**
2968 * Get the permissions this user has.
2969 * @return array Array of String permission names
2970 */
2971 public function getRights() {
2972 if ( is_null( $this->mRights ) ) {
2973 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2974 Hooks::run( 'UserGetRights', array( $this, &$this->mRights ) );
2975 // Force reindexation of rights when a hook has unset one of them
2976 $this->mRights = array_values( array_unique( $this->mRights ) );
2977 }
2978 return $this->mRights;
2979 }
2980
2981 /**
2982 * Get the list of explicit group memberships this user has.
2983 * The implicit * and user groups are not included.
2984 * @return array Array of String internal group names
2985 */
2986 public function getGroups() {
2987 $this->load();
2988 $this->loadGroups();
2989 return $this->mGroups;
2990 }
2991
2992 /**
2993 * Get the list of implicit group memberships this user has.
2994 * This includes all explicit groups, plus 'user' if logged in,
2995 * '*' for all accounts, and autopromoted groups
2996 * @param bool $recache Whether to avoid the cache
2997 * @return array Array of String internal group names
2998 */
2999 public function getEffectiveGroups( $recache = false ) {
3000 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
3001 $this->mEffectiveGroups = array_unique( array_merge(
3002 $this->getGroups(), // explicit groups
3003 $this->getAutomaticGroups( $recache ) // implicit groups
3004 ) );
3005 // Hook for additional groups
3006 Hooks::run( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
3007 // Force reindexation of groups when a hook has unset one of them
3008 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
3009 }
3010 return $this->mEffectiveGroups;
3011 }
3012
3013 /**
3014 * Get the list of implicit group memberships this user has.
3015 * This includes 'user' if logged in, '*' for all accounts,
3016 * and autopromoted groups
3017 * @param bool $recache Whether to avoid the cache
3018 * @return array Array of String internal group names
3019 */
3020 public function getAutomaticGroups( $recache = false ) {
3021 if ( $recache || is_null( $this->mImplicitGroups ) ) {
3022 $this->mImplicitGroups = array( '*' );
3023 if ( $this->getId() ) {
3024 $this->mImplicitGroups[] = 'user';
3025
3026 $this->mImplicitGroups = array_unique( array_merge(
3027 $this->mImplicitGroups,
3028 Autopromote::getAutopromoteGroups( $this )
3029 ) );
3030 }
3031 if ( $recache ) {
3032 // Assure data consistency with rights/groups,
3033 // as getEffectiveGroups() depends on this function
3034 $this->mEffectiveGroups = null;
3035 }
3036 }
3037 return $this->mImplicitGroups;
3038 }
3039
3040 /**
3041 * Returns the groups the user has belonged to.
3042 *
3043 * The user may still belong to the returned groups. Compare with getGroups().
3044 *
3045 * The function will not return groups the user had belonged to before MW 1.17
3046 *
3047 * @return array Names of the groups the user has belonged to.
3048 */
3049 public function getFormerGroups() {
3050 $this->load();
3051
3052 if ( is_null( $this->mFormerGroups ) ) {
3053 $dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
3054 ? wfGetDB( DB_MASTER )
3055 : wfGetDB( DB_SLAVE );
3056 $res = $dbr->select( 'user_former_groups',
3057 array( 'ufg_group' ),
3058 array( 'ufg_user' => $this->mId ),
3059 __METHOD__ );
3060 $this->mFormerGroups = array();
3061 foreach ( $res as $row ) {
3062 $this->mFormerGroups[] = $row->ufg_group;
3063 }
3064 }
3065
3066 return $this->mFormerGroups;
3067 }
3068
3069 /**
3070 * Get the user's edit count.
3071 * @return int|null Null for anonymous users
3072 */
3073 public function getEditCount() {
3074 if ( !$this->getId() ) {
3075 return null;
3076 }
3077
3078 if ( $this->mEditCount === null ) {
3079 /* Populate the count, if it has not been populated yet */
3080 $dbr = wfGetDB( DB_SLAVE );
3081 // check if the user_editcount field has been initialized
3082 $count = $dbr->selectField(
3083 'user', 'user_editcount',
3084 array( 'user_id' => $this->mId ),
3085 __METHOD__
3086 );
3087
3088 if ( $count === null ) {
3089 // it has not been initialized. do so.
3090 $count = $this->initEditCount();
3091 }
3092 $this->mEditCount = $count;
3093 }
3094 return (int)$this->mEditCount;
3095 }
3096
3097 /**
3098 * Add the user to the given group.
3099 * This takes immediate effect.
3100 * @param string $group Name of the group to add
3101 * @return bool
3102 */
3103 public function addGroup( $group ) {
3104 $this->load();
3105
3106 if ( !Hooks::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3107 return false;
3108 }
3109
3110 $dbw = wfGetDB( DB_MASTER );
3111 if ( $this->getId() ) {
3112 $dbw->insert( 'user_groups',
3113 array(
3114 'ug_user' => $this->getID(),
3115 'ug_group' => $group,
3116 ),
3117 __METHOD__,
3118 array( 'IGNORE' ) );
3119 }
3120
3121 $this->loadGroups();
3122 $this->mGroups[] = $group;
3123 // In case loadGroups was not called before, we now have the right twice.
3124 // Get rid of the duplicate.
3125 $this->mGroups = array_unique( $this->mGroups );
3126
3127 // Refresh the groups caches, and clear the rights cache so it will be
3128 // refreshed on the next call to $this->getRights().
3129 $this->getEffectiveGroups( true );
3130 $this->mRights = null;
3131
3132 $this->invalidateCache();
3133
3134 return true;
3135 }
3136
3137 /**
3138 * Remove the user from the given group.
3139 * This takes immediate effect.
3140 * @param string $group Name of the group to remove
3141 * @return bool
3142 */
3143 public function removeGroup( $group ) {
3144 $this->load();
3145 if ( !Hooks::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3146 return false;
3147 }
3148
3149 $dbw = wfGetDB( DB_MASTER );
3150 $dbw->delete( 'user_groups',
3151 array(
3152 'ug_user' => $this->getID(),
3153 'ug_group' => $group,
3154 ), __METHOD__
3155 );
3156 // Remember that the user was in this group
3157 $dbw->insert( 'user_former_groups',
3158 array(
3159 'ufg_user' => $this->getID(),
3160 'ufg_group' => $group,
3161 ),
3162 __METHOD__,
3163 array( 'IGNORE' )
3164 );
3165
3166 $this->loadGroups();
3167 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
3168
3169 // Refresh the groups caches, and clear the rights cache so it will be
3170 // refreshed on the next call to $this->getRights().
3171 $this->getEffectiveGroups( true );
3172 $this->mRights = null;
3173
3174 $this->invalidateCache();
3175
3176 return true;
3177 }
3178
3179 /**
3180 * Get whether the user is logged in
3181 * @return bool
3182 */
3183 public function isLoggedIn() {
3184 return $this->getID() != 0;
3185 }
3186
3187 /**
3188 * Get whether the user is anonymous
3189 * @return bool
3190 */
3191 public function isAnon() {
3192 return !$this->isLoggedIn();
3193 }
3194
3195 /**
3196 * Check if user is allowed to access a feature / make an action
3197 *
3198 * @param string $permissions,... Permissions to test
3199 * @return bool True if user is allowed to perform *any* of the given actions
3200 */
3201 public function isAllowedAny( /*...*/ ) {
3202 $permissions = func_get_args();
3203 foreach ( $permissions as $permission ) {
3204 if ( $this->isAllowed( $permission ) ) {
3205 return true;
3206 }
3207 }
3208 return false;
3209 }
3210
3211 /**
3212 *
3213 * @param string $permissions,... Permissions to test
3214 * @return bool True if the user is allowed to perform *all* of the given actions
3215 */
3216 public function isAllowedAll( /*...*/ ) {
3217 $permissions = func_get_args();
3218 foreach ( $permissions as $permission ) {
3219 if ( !$this->isAllowed( $permission ) ) {
3220 return false;
3221 }
3222 }
3223 return true;
3224 }
3225
3226 /**
3227 * Internal mechanics of testing a permission
3228 * @param string $action
3229 * @return bool
3230 */
3231 public function isAllowed( $action = '' ) {
3232 if ( $action === '' ) {
3233 return true; // In the spirit of DWIM
3234 }
3235 // Patrolling may not be enabled
3236 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3237 global $wgUseRCPatrol, $wgUseNPPatrol;
3238 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3239 return false;
3240 }
3241 }
3242 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3243 // by misconfiguration: 0 == 'foo'
3244 return in_array( $action, $this->getRights(), true );
3245 }
3246
3247 /**
3248 * Check whether to enable recent changes patrol features for this user
3249 * @return bool True or false
3250 */
3251 public function useRCPatrol() {
3252 global $wgUseRCPatrol;
3253 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3254 }
3255
3256 /**
3257 * Check whether to enable new pages patrol features for this user
3258 * @return bool True or false
3259 */
3260 public function useNPPatrol() {
3261 global $wgUseRCPatrol, $wgUseNPPatrol;
3262 return (
3263 ( $wgUseRCPatrol || $wgUseNPPatrol )
3264 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3265 );
3266 }
3267
3268 /**
3269 * Get the WebRequest object to use with this object
3270 *
3271 * @return WebRequest
3272 */
3273 public function getRequest() {
3274 if ( $this->mRequest ) {
3275 return $this->mRequest;
3276 } else {
3277 global $wgRequest;
3278 return $wgRequest;
3279 }
3280 }
3281
3282 /**
3283 * Get the current skin, loading it if required
3284 * @return Skin The current skin
3285 * @todo FIXME: Need to check the old failback system [AV]
3286 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3287 */
3288 public function getSkin() {
3289 wfDeprecated( __METHOD__, '1.18' );
3290 return RequestContext::getMain()->getSkin();
3291 }
3292
3293 /**
3294 * Get a WatchedItem for this user and $title.
3295 *
3296 * @since 1.22 $checkRights parameter added
3297 * @param Title $title
3298 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3299 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3300 * @return WatchedItem
3301 */
3302 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3303 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3304
3305 if ( isset( $this->mWatchedItems[$key] ) ) {
3306 return $this->mWatchedItems[$key];
3307 }
3308
3309 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3310 $this->mWatchedItems = array();
3311 }
3312
3313 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3314 return $this->mWatchedItems[$key];
3315 }
3316
3317 /**
3318 * Check the watched status of an article.
3319 * @since 1.22 $checkRights parameter added
3320 * @param Title $title Title of the article to look at
3321 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3322 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3323 * @return bool
3324 */
3325 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3326 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3327 }
3328
3329 /**
3330 * Watch an article.
3331 * @since 1.22 $checkRights parameter added
3332 * @param Title $title Title of the article to look at
3333 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3334 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3335 */
3336 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3337 $this->getWatchedItem( $title, $checkRights )->addWatch();
3338 $this->invalidateCache();
3339 }
3340
3341 /**
3342 * Stop watching an article.
3343 * @since 1.22 $checkRights parameter added
3344 * @param Title $title Title of the article to look at
3345 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3346 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3347 */
3348 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3349 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3350 $this->invalidateCache();
3351 }
3352
3353 /**
3354 * Clear the user's notification timestamp for the given title.
3355 * If e-notif e-mails are on, they will receive notification mails on
3356 * the next change of the page if it's watched etc.
3357 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3358 * @param Title $title Title of the article to look at
3359 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3360 */
3361 public function clearNotification( &$title, $oldid = 0 ) {
3362 global $wgUseEnotif, $wgShowUpdatedMarker;
3363
3364 // Do nothing if the database is locked to writes
3365 if ( wfReadOnly() ) {
3366 return;
3367 }
3368
3369 // Do nothing if not allowed to edit the watchlist
3370 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3371 return;
3372 }
3373
3374 // If we're working on user's talk page, we should update the talk page message indicator
3375 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3376 if ( !Hooks::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3377 return;
3378 }
3379
3380 $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null;
3381
3382 if ( !$oldid || !$nextid ) {
3383 // If we're looking at the latest revision, we should definitely clear it
3384 $this->setNewtalk( false );
3385 } else {
3386 // Otherwise we should update its revision, if it's present
3387 if ( $this->getNewtalk() ) {
3388 // Naturally the other one won't clear by itself
3389 $this->setNewtalk( false );
3390 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3391 }
3392 }
3393 }
3394
3395 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3396 return;
3397 }
3398
3399 if ( $this->isAnon() ) {
3400 // Nothing else to do...
3401 return;
3402 }
3403
3404 // Only update the timestamp if the page is being watched.
3405 // The query to find out if it is watched is cached both in memcached and per-invocation,
3406 // and when it does have to be executed, it can be on a slave
3407 // If this is the user's newtalk page, we always update the timestamp
3408 $force = '';
3409 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3410 $force = 'force';
3411 }
3412
3413 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3414 }
3415
3416 /**
3417 * Resets all of the given user's page-change notification timestamps.
3418 * If e-notif e-mails are on, they will receive notification mails on
3419 * the next change of any watched page.
3420 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3421 */
3422 public function clearAllNotifications() {
3423 if ( wfReadOnly() ) {
3424 return;
3425 }
3426
3427 // Do nothing if not allowed to edit the watchlist
3428 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3429 return;
3430 }
3431
3432 global $wgUseEnotif, $wgShowUpdatedMarker;
3433 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3434 $this->setNewtalk( false );
3435 return;
3436 }
3437 $id = $this->getId();
3438 if ( $id != 0 ) {
3439 $dbw = wfGetDB( DB_MASTER );
3440 $dbw->update( 'watchlist',
3441 array( /* SET */ 'wl_notificationtimestamp' => null ),
3442 array( /* WHERE */ 'wl_user' => $id ),
3443 __METHOD__
3444 );
3445 // We also need to clear here the "you have new message" notification for the own user_talk page;
3446 // it's cleared one page view later in WikiPage::doViewUpdates().
3447 }
3448 }
3449
3450 /**
3451 * Set a cookie on the user's client. Wrapper for
3452 * WebResponse::setCookie
3453 * @param string $name Name of the cookie to set
3454 * @param string $value Value to set
3455 * @param int $exp Expiration time, as a UNIX time value;
3456 * if 0 or not specified, use the default $wgCookieExpiration
3457 * @param bool $secure
3458 * true: Force setting the secure attribute when setting the cookie
3459 * false: Force NOT setting the secure attribute when setting the cookie
3460 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3461 * @param array $params Array of options sent passed to WebResponse::setcookie()
3462 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3463 * is passed.
3464 */
3465 protected function setCookie(
3466 $name, $value, $exp = 0, $secure = null, $params = array(), $request = null
3467 ) {
3468 if ( $request === null ) {
3469 $request = $this->getRequest();
3470 }
3471 $params['secure'] = $secure;
3472 $request->response()->setcookie( $name, $value, $exp, $params );
3473 }
3474
3475 /**
3476 * Clear a cookie on the user's client
3477 * @param string $name Name of the cookie to clear
3478 * @param bool $secure
3479 * true: Force setting the secure attribute when setting the cookie
3480 * false: Force NOT setting the secure attribute when setting the cookie
3481 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3482 * @param array $params Array of options sent passed to WebResponse::setcookie()
3483 */
3484 protected function clearCookie( $name, $secure = null, $params = array() ) {
3485 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3486 }
3487
3488 /**
3489 * Set the default cookies for this session on the user's client.
3490 *
3491 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3492 * is passed.
3493 * @param bool $secure Whether to force secure/insecure cookies or use default
3494 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3495 */
3496 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3497 if ( $request === null ) {
3498 $request = $this->getRequest();
3499 }
3500
3501 $this->load();
3502 if ( 0 == $this->mId ) {
3503 return;
3504 }
3505 if ( !$this->mToken ) {
3506 // When token is empty or NULL generate a new one and then save it to the database
3507 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3508 // Simply by setting every cell in the user_token column to NULL and letting them be
3509 // regenerated as users log back into the wiki.
3510 $this->setToken();
3511 if ( !wfReadOnly() ) {
3512 $this->saveSettings();
3513 }
3514 }
3515 $session = array(
3516 'wsUserID' => $this->mId,
3517 'wsToken' => $this->mToken,
3518 'wsUserName' => $this->getName()
3519 );
3520 $cookies = array(
3521 'UserID' => $this->mId,
3522 'UserName' => $this->getName(),
3523 );
3524 if ( $rememberMe ) {
3525 $cookies['Token'] = $this->mToken;
3526 } else {
3527 $cookies['Token'] = false;
3528 }
3529
3530 Hooks::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3531
3532 foreach ( $session as $name => $value ) {
3533 $request->setSessionData( $name, $value );
3534 }
3535 foreach ( $cookies as $name => $value ) {
3536 if ( $value === false ) {
3537 $this->clearCookie( $name );
3538 } else {
3539 $this->setCookie( $name, $value, 0, $secure, array(), $request );
3540 }
3541 }
3542
3543 /**
3544 * If wpStickHTTPS was selected, also set an insecure cookie that
3545 * will cause the site to redirect the user to HTTPS, if they access
3546 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3547 * as the one set by centralauth (bug 53538). Also set it to session, or
3548 * standard time setting, based on if rememberme was set.
3549 */
3550 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3551 $this->setCookie(
3552 'forceHTTPS',
3553 'true',
3554 $rememberMe ? 0 : null,
3555 false,
3556 array( 'prefix' => '' ) // no prefix
3557 );
3558 }
3559 }
3560
3561 /**
3562 * Log this user out.
3563 */
3564 public function logout() {
3565 if ( Hooks::run( 'UserLogout', array( &$this ) ) ) {
3566 $this->doLogout();
3567 }
3568 }
3569
3570 /**
3571 * Clear the user's cookies and session, and reset the instance cache.
3572 * @see logout()
3573 */
3574 public function doLogout() {
3575 $this->clearInstanceCache( 'defaults' );
3576
3577 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3578
3579 $this->clearCookie( 'UserID' );
3580 $this->clearCookie( 'Token' );
3581 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3582
3583 // Remember when user logged out, to prevent seeing cached pages
3584 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3585 }
3586
3587 /**
3588 * Save this user's settings into the database.
3589 * @todo Only rarely do all these fields need to be set!
3590 */
3591 public function saveSettings() {
3592 global $wgAuth;
3593
3594 if ( wfReadOnly() ) {
3595 // @TODO: caller should deal with this instead!
3596 // This should really just be an exception.
3597 MWExceptionHandler::logException( new DBExpectedError(
3598 null,
3599 "Could not update user with ID '{$this->mId}'; DB is read-only."
3600 ) );
3601 return;
3602 }
3603
3604 $this->load();
3605 $this->loadPasswords();
3606 if ( 0 == $this->mId ) {
3607 return; // anon
3608 }
3609
3610 // This method is for updating existing users, so the user should
3611 // have been loaded from the master to begin with to avoid problems.
3612 if ( !( $this->queryFlagsUsed & self::READ_LATEST ) ) {
3613 wfWarn( "Attempting to save slave-loaded User object with ID '{$this->mId}'." );
3614 }
3615
3616 // Get a new user_touched that is higher than the old one.
3617 // This will be used for a CAS check as a last-resort safety
3618 // check against race conditions and slave lag.
3619 $oldTouched = $this->mTouched;
3620 $this->mTouched = $this->newTouchedTimestamp();
3621
3622 if ( !$wgAuth->allowSetLocalPassword() ) {
3623 $this->mPassword = self::getPasswordFactory()->newFromCiphertext( null );
3624 }
3625
3626 $dbw = wfGetDB( DB_MASTER );
3627 $dbw->update( 'user',
3628 array( /* SET */
3629 'user_name' => $this->mName,
3630 'user_password' => $this->mPassword->toString(),
3631 'user_newpassword' => $this->mNewpassword->toString(),
3632 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3633 'user_real_name' => $this->mRealName,
3634 'user_email' => $this->mEmail,
3635 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3636 'user_touched' => $dbw->timestamp( $this->mTouched ),
3637 'user_token' => strval( $this->mToken ),
3638 'user_email_token' => $this->mEmailToken,
3639 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3640 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3641 ), array( /* WHERE */
3642 'user_id' => $this->mId,
3643 'user_touched' => $dbw->timestamp( $oldTouched ) // CAS check
3644 ), __METHOD__
3645 );
3646
3647 if ( !$dbw->affectedRows() ) {
3648 // User was changed in the meantime or loaded with stale data
3649 MWExceptionHandler::logException( new MWException(
3650 "CAS update failed on user_touched for user ID '{$this->mId}'."
3651 ) );
3652 // Maybe the problem was a missed cache update; clear it to be safe
3653 $this->clearSharedCache();
3654
3655 return;
3656 }
3657
3658 $this->saveOptions();
3659
3660 Hooks::run( 'UserSaveSettings', array( $this ) );
3661 $this->clearSharedCache();
3662 $this->getUserPage()->invalidateCache();
3663 }
3664
3665 /**
3666 * If only this user's username is known, and it exists, return the user ID.
3667 * @return int
3668 */
3669 public function idForName() {
3670 $s = trim( $this->getName() );
3671 if ( $s === '' ) {
3672 return 0;
3673 }
3674
3675 $dbr = wfGetDB( DB_SLAVE );
3676 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3677 if ( $id === false ) {
3678 $id = 0;
3679 }
3680 return $id;
3681 }
3682
3683 /**
3684 * Add a user to the database, return the user object
3685 *
3686 * @param string $name Username to add
3687 * @param array $params Array of Strings Non-default parameters to save to
3688 * the database as user_* fields:
3689 * - password: The user's password hash. Password logins will be disabled
3690 * if this is omitted.
3691 * - newpassword: Hash for a temporary password that has been mailed to
3692 * the user.
3693 * - email: The user's email address.
3694 * - email_authenticated: The email authentication timestamp.
3695 * - real_name: The user's real name.
3696 * - options: An associative array of non-default options.
3697 * - token: Random authentication token. Do not set.
3698 * - registration: Registration timestamp. Do not set.
3699 *
3700 * @return User|null User object, or null if the username already exists.
3701 */
3702 public static function createNew( $name, $params = array() ) {
3703 $user = new User;
3704 $user->load();
3705 $user->loadPasswords();
3706 $user->setToken(); // init token
3707 if ( isset( $params['options'] ) ) {
3708 $user->mOptions = $params['options'] + (array)$user->mOptions;
3709 unset( $params['options'] );
3710 }
3711 $dbw = wfGetDB( DB_MASTER );
3712 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3713
3714 $fields = array(
3715 'user_id' => $seqVal,
3716 'user_name' => $name,
3717 'user_password' => $user->mPassword->toString(),
3718 'user_newpassword' => $user->mNewpassword->toString(),
3719 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3720 'user_email' => $user->mEmail,
3721 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3722 'user_real_name' => $user->mRealName,
3723 'user_token' => strval( $user->mToken ),
3724 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3725 'user_editcount' => 0,
3726 'user_touched' => $dbw->timestamp( $user->newTouchedTimestamp() ),
3727 );
3728 foreach ( $params as $name => $value ) {
3729 $fields["user_$name"] = $value;
3730 }
3731 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3732 if ( $dbw->affectedRows() ) {
3733 $newUser = User::newFromId( $dbw->insertId() );
3734 } else {
3735 $newUser = null;
3736 }
3737 return $newUser;
3738 }
3739
3740 /**
3741 * Add this existing user object to the database. If the user already
3742 * exists, a fatal status object is returned, and the user object is
3743 * initialised with the data from the database.
3744 *
3745 * Previously, this function generated a DB error due to a key conflict
3746 * if the user already existed. Many extension callers use this function
3747 * in code along the lines of:
3748 *
3749 * $user = User::newFromName( $name );
3750 * if ( !$user->isLoggedIn() ) {
3751 * $user->addToDatabase();
3752 * }
3753 * // do something with $user...
3754 *
3755 * However, this was vulnerable to a race condition (bug 16020). By
3756 * initialising the user object if the user exists, we aim to support this
3757 * calling sequence as far as possible.
3758 *
3759 * Note that if the user exists, this function will acquire a write lock,
3760 * so it is still advisable to make the call conditional on isLoggedIn(),
3761 * and to commit the transaction after calling.
3762 *
3763 * @throws MWException
3764 * @return Status
3765 */
3766 public function addToDatabase() {
3767 $this->load();
3768 $this->loadPasswords();
3769 if ( !$this->mToken ) {
3770 $this->setToken(); // init token
3771 }
3772
3773 $this->mTouched = $this->newTouchedTimestamp();
3774
3775 $dbw = wfGetDB( DB_MASTER );
3776 $inWrite = $dbw->writesOrCallbacksPending();
3777 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3778 $dbw->insert( 'user',
3779 array(
3780 'user_id' => $seqVal,
3781 'user_name' => $this->mName,
3782 'user_password' => $this->mPassword->toString(),
3783 'user_newpassword' => $this->mNewpassword->toString(),
3784 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3785 'user_email' => $this->mEmail,
3786 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3787 'user_real_name' => $this->mRealName,
3788 'user_token' => strval( $this->mToken ),
3789 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3790 'user_editcount' => 0,
3791 'user_touched' => $dbw->timestamp( $this->mTouched ),
3792 ), __METHOD__,
3793 array( 'IGNORE' )
3794 );
3795 if ( !$dbw->affectedRows() ) {
3796 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3797 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3798 if ( $inWrite ) {
3799 // Can't commit due to pending writes that may need atomicity.
3800 // This may cause some lock contention unlike the case below.
3801 $options = array( 'LOCK IN SHARE MODE' );
3802 $flags = self::READ_LOCKING;
3803 } else {
3804 // Often, this case happens early in views before any writes when
3805 // using CentralAuth. It's should be OK to commit and break the snapshot.
3806 $dbw->commit( __METHOD__, 'flush' );
3807 $options = array();
3808 $flags = self::READ_LATEST;
3809 }
3810 $this->mId = $dbw->selectField( 'user', 'user_id',
3811 array( 'user_name' => $this->mName ), __METHOD__, $options );
3812 $loaded = false;
3813 if ( $this->mId ) {
3814 if ( $this->loadFromDatabase( $flags ) ) {
3815 $loaded = true;
3816 }
3817 }
3818 if ( !$loaded ) {
3819 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3820 "to insert user '{$this->mName}' row, but it was not present in select!" );
3821 }
3822 return Status::newFatal( 'userexists' );
3823 }
3824 $this->mId = $dbw->insertId();
3825
3826 // Clear instance cache other than user table data, which is already accurate
3827 $this->clearInstanceCache();
3828
3829 $this->saveOptions();
3830 return Status::newGood();
3831 }
3832
3833 /**
3834 * If this user is logged-in and blocked,
3835 * block any IP address they've successfully logged in from.
3836 * @return bool A block was spread
3837 */
3838 public function spreadAnyEditBlock() {
3839 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3840 return $this->spreadBlock();
3841 }
3842 return false;
3843 }
3844
3845 /**
3846 * If this (non-anonymous) user is blocked,
3847 * block the IP address they've successfully logged in from.
3848 * @return bool A block was spread
3849 */
3850 protected function spreadBlock() {
3851 wfDebug( __METHOD__ . "()\n" );
3852 $this->load();
3853 if ( $this->mId == 0 ) {
3854 return false;
3855 }
3856
3857 $userblock = Block::newFromTarget( $this->getName() );
3858 if ( !$userblock ) {
3859 return false;
3860 }
3861
3862 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3863 }
3864
3865 /**
3866 * Get whether the user is explicitly blocked from account creation.
3867 * @return bool|Block
3868 */
3869 public function isBlockedFromCreateAccount() {
3870 $this->getBlockedStatus();
3871 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3872 return $this->mBlock;
3873 }
3874
3875 # bug 13611: if the IP address the user is trying to create an account from is
3876 # blocked with createaccount disabled, prevent new account creation there even
3877 # when the user is logged in
3878 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3879 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3880 }
3881 return $this->mBlockedFromCreateAccount instanceof Block
3882 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3883 ? $this->mBlockedFromCreateAccount
3884 : false;
3885 }
3886
3887 /**
3888 * Get whether the user is blocked from using Special:Emailuser.
3889 * @return bool
3890 */
3891 public function isBlockedFromEmailuser() {
3892 $this->getBlockedStatus();
3893 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3894 }
3895
3896 /**
3897 * Get whether the user is allowed to create an account.
3898 * @return bool
3899 */
3900 public function isAllowedToCreateAccount() {
3901 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3902 }
3903
3904 /**
3905 * Get this user's personal page title.
3906 *
3907 * @return Title User's personal page title
3908 */
3909 public function getUserPage() {
3910 return Title::makeTitle( NS_USER, $this->getName() );
3911 }
3912
3913 /**
3914 * Get this user's talk page title.
3915 *
3916 * @return Title User's talk page title
3917 */
3918 public function getTalkPage() {
3919 $title = $this->getUserPage();
3920 return $title->getTalkPage();
3921 }
3922
3923 /**
3924 * Determine whether the user is a newbie. Newbies are either
3925 * anonymous IPs, or the most recently created accounts.
3926 * @return bool
3927 */
3928 public function isNewbie() {
3929 return !$this->isAllowed( 'autoconfirmed' );
3930 }
3931
3932 /**
3933 * Check to see if the given clear-text password is one of the accepted passwords
3934 * @param string $password User password
3935 * @return bool True if the given password is correct, otherwise False
3936 */
3937 public function checkPassword( $password ) {
3938 global $wgAuth, $wgLegacyEncoding;
3939
3940 $this->loadPasswords();
3941
3942 // Some passwords will give a fatal Status, which means there is
3943 // some sort of technical or security reason for this password to
3944 // be completely invalid and should never be checked (e.g., T64685)
3945 if ( !$this->checkPasswordValidity( $password )->isOK() ) {
3946 return false;
3947 }
3948
3949 // Certain authentication plugins do NOT want to save
3950 // domain passwords in a mysql database, so we should
3951 // check this (in case $wgAuth->strict() is false).
3952 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3953 return true;
3954 } elseif ( $wgAuth->strict() ) {
3955 // Auth plugin doesn't allow local authentication
3956 return false;
3957 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3958 // Auth plugin doesn't allow local authentication for this user name
3959 return false;
3960 }
3961
3962 if ( !$this->mPassword->equals( $password ) ) {
3963 if ( $wgLegacyEncoding ) {
3964 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3965 // Check for this with iconv
3966 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3967 if ( $cp1252Password === $password || !$this->mPassword->equals( $cp1252Password ) ) {
3968 return false;
3969 }
3970 } else {
3971 return false;
3972 }
3973 }
3974
3975 $passwordFactory = self::getPasswordFactory();
3976 if ( $passwordFactory->needsUpdate( $this->mPassword ) && !wfReadOnly() ) {
3977 $this->mPassword = $passwordFactory->newFromPlaintext( $password );
3978 $this->saveSettings();
3979 }
3980
3981 return true;
3982 }
3983
3984 /**
3985 * Check if the given clear-text password matches the temporary password
3986 * sent by e-mail for password reset operations.
3987 *
3988 * @param string $plaintext
3989 *
3990 * @return bool True if matches, false otherwise
3991 */
3992 public function checkTemporaryPassword( $plaintext ) {
3993 global $wgNewPasswordExpiry;
3994
3995 $this->load();
3996 $this->loadPasswords();
3997 if ( $this->mNewpassword->equals( $plaintext ) ) {
3998 if ( is_null( $this->mNewpassTime ) ) {
3999 return true;
4000 }
4001 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
4002 return ( time() < $expiry );
4003 } else {
4004 return false;
4005 }
4006 }
4007
4008 /**
4009 * Alias for getEditToken.
4010 * @deprecated since 1.19, use getEditToken instead.
4011 *
4012 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4013 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4014 * @return string The new edit token
4015 */
4016 public function editToken( $salt = '', $request = null ) {
4017 wfDeprecated( __METHOD__, '1.19' );
4018 return $this->getEditToken( $salt, $request );
4019 }
4020
4021 /**
4022 * Internal implementation for self::getEditToken() and
4023 * self::matchEditToken().
4024 *
4025 * @param string|array $salt
4026 * @param WebRequest $request
4027 * @param string|int $timestamp
4028 * @return string
4029 */
4030 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
4031 if ( $this->isAnon() ) {
4032 return self::EDIT_TOKEN_SUFFIX;
4033 } else {
4034 $token = $request->getSessionData( 'wsEditToken' );
4035 if ( $token === null ) {
4036 $token = MWCryptRand::generateHex( 32 );
4037 $request->setSessionData( 'wsEditToken', $token );
4038 }
4039 if ( is_array( $salt ) ) {
4040 $salt = implode( '|', $salt );
4041 }
4042 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
4043 dechex( $timestamp ) .
4044 self::EDIT_TOKEN_SUFFIX;
4045 }
4046 }
4047
4048 /**
4049 * Initialize (if necessary) and return a session token value
4050 * which can be used in edit forms to show that the user's
4051 * login credentials aren't being hijacked with a foreign form
4052 * submission.
4053 *
4054 * @since 1.19
4055 *
4056 * @param string|array $salt Array of Strings Optional function-specific data for hashing
4057 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
4058 * @return string The new edit token
4059 */
4060 public function getEditToken( $salt = '', $request = null ) {
4061 return $this->getEditTokenAtTimestamp(
4062 $salt, $request ?: $this->getRequest(), wfTimestamp()
4063 );
4064 }
4065
4066 /**
4067 * Generate a looking random token for various uses.
4068 *
4069 * @return string The new random token
4070 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
4071 * wfRandomString for pseudo-randomness.
4072 */
4073 public static function generateToken() {
4074 return MWCryptRand::generateHex( 32 );
4075 }
4076
4077 /**
4078 * Get the embedded timestamp from a token.
4079 * @param string $val Input token
4080 * @return int|null
4081 */
4082 public static function getEditTokenTimestamp( $val ) {
4083 $suffixLen = strlen( self::EDIT_TOKEN_SUFFIX );
4084 if ( strlen( $val ) <= 32 + $suffixLen ) {
4085 return null;
4086 }
4087
4088 return hexdec( substr( $val, 32, -$suffixLen ) );
4089 }
4090
4091 /**
4092 * Check given value against the token value stored in the session.
4093 * A match should confirm that the form was submitted from the
4094 * user's own login session, not a form submission from a third-party
4095 * site.
4096 *
4097 * @param string $val Input value to compare
4098 * @param string $salt Optional function-specific data for hashing
4099 * @param WebRequest|null $request Object to use or null to use $wgRequest
4100 * @param int $maxage Fail tokens older than this, in seconds
4101 * @return bool Whether the token matches
4102 */
4103 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
4104 if ( $this->isAnon() ) {
4105 return $val === self::EDIT_TOKEN_SUFFIX;
4106 }
4107
4108 $timestamp = self::getEditTokenTimestamp( $val );
4109 if ( $timestamp === null ) {
4110 return false;
4111 }
4112 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
4113 // Expired token
4114 return false;
4115 }
4116
4117 $sessionToken = $this->getEditTokenAtTimestamp(
4118 $salt, $request ?: $this->getRequest(), $timestamp
4119 );
4120
4121 if ( $val != $sessionToken ) {
4122 wfDebug( "User::matchEditToken: broken session data\n" );
4123 }
4124
4125 return hash_equals( $sessionToken, $val );
4126 }
4127
4128 /**
4129 * Check given value against the token value stored in the session,
4130 * ignoring the suffix.
4131 *
4132 * @param string $val Input value to compare
4133 * @param string $salt Optional function-specific data for hashing
4134 * @param WebRequest|null $request Object to use or null to use $wgRequest
4135 * @param int $maxage Fail tokens older than this, in seconds
4136 * @return bool Whether the token matches
4137 */
4138 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
4139 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self::EDIT_TOKEN_SUFFIX;
4140 return $this->matchEditToken( $val, $salt, $request, $maxage );
4141 }
4142
4143 /**
4144 * Generate a new e-mail confirmation token and send a confirmation/invalidation
4145 * mail to the user's given address.
4146 *
4147 * @param string $type Message to send, either "created", "changed" or "set"
4148 * @return Status
4149 */
4150 public function sendConfirmationMail( $type = 'created' ) {
4151 global $wgLang;
4152 $expiration = null; // gets passed-by-ref and defined in next line.
4153 $token = $this->confirmationToken( $expiration );
4154 $url = $this->confirmationTokenUrl( $token );
4155 $invalidateURL = $this->invalidationTokenUrl( $token );
4156 $this->saveSettings();
4157
4158 if ( $type == 'created' || $type === false ) {
4159 $message = 'confirmemail_body';
4160 } elseif ( $type === true ) {
4161 $message = 'confirmemail_body_changed';
4162 } else {
4163 // Messages: confirmemail_body_changed, confirmemail_body_set
4164 $message = 'confirmemail_body_' . $type;
4165 }
4166
4167 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4168 wfMessage( $message,
4169 $this->getRequest()->getIP(),
4170 $this->getName(),
4171 $url,
4172 $wgLang->timeanddate( $expiration, false ),
4173 $invalidateURL,
4174 $wgLang->date( $expiration, false ),
4175 $wgLang->time( $expiration, false ) )->text() );
4176 }
4177
4178 /**
4179 * Send an e-mail to this user's account. Does not check for
4180 * confirmed status or validity.
4181 *
4182 * @param string $subject Message subject
4183 * @param string $body Message body
4184 * @param string $from Optional From address; if unspecified, default
4185 * $wgPasswordSender will be used.
4186 * @param string $replyto Reply-To address
4187 * @return Status
4188 */
4189 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4190 if ( is_null( $from ) ) {
4191 global $wgPasswordSender;
4192 $sender = new MailAddress( $wgPasswordSender,
4193 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4194 } else {
4195 $sender = MailAddress::newFromUser( $from );
4196 }
4197
4198 $to = MailAddress::newFromUser( $this );
4199 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
4200 }
4201
4202 /**
4203 * Generate, store, and return a new e-mail confirmation code.
4204 * A hash (unsalted, since it's used as a key) is stored.
4205 *
4206 * @note Call saveSettings() after calling this function to commit
4207 * this change to the database.
4208 *
4209 * @param string &$expiration Accepts the expiration time
4210 * @return string New token
4211 */
4212 protected function confirmationToken( &$expiration ) {
4213 global $wgUserEmailConfirmationTokenExpiry;
4214 $now = time();
4215 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4216 $expiration = wfTimestamp( TS_MW, $expires );
4217 $this->load();
4218 $token = MWCryptRand::generateHex( 32 );
4219 $hash = md5( $token );
4220 $this->mEmailToken = $hash;
4221 $this->mEmailTokenExpires = $expiration;
4222 return $token;
4223 }
4224
4225 /**
4226 * Return a URL the user can use to confirm their email address.
4227 * @param string $token Accepts the email confirmation token
4228 * @return string New token URL
4229 */
4230 protected function confirmationTokenUrl( $token ) {
4231 return $this->getTokenUrl( 'ConfirmEmail', $token );
4232 }
4233
4234 /**
4235 * Return a URL the user can use to invalidate their email address.
4236 * @param string $token Accepts the email confirmation token
4237 * @return string New token URL
4238 */
4239 protected function invalidationTokenUrl( $token ) {
4240 return $this->getTokenUrl( 'InvalidateEmail', $token );
4241 }
4242
4243 /**
4244 * Internal function to format the e-mail validation/invalidation URLs.
4245 * This uses a quickie hack to use the
4246 * hardcoded English names of the Special: pages, for ASCII safety.
4247 *
4248 * @note Since these URLs get dropped directly into emails, using the
4249 * short English names avoids insanely long URL-encoded links, which
4250 * also sometimes can get corrupted in some browsers/mailers
4251 * (bug 6957 with Gmail and Internet Explorer).
4252 *
4253 * @param string $page Special page
4254 * @param string $token Token
4255 * @return string Formatted URL
4256 */
4257 protected function getTokenUrl( $page, $token ) {
4258 // Hack to bypass localization of 'Special:'
4259 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4260 return $title->getCanonicalURL();
4261 }
4262
4263 /**
4264 * Mark the e-mail address confirmed.
4265 *
4266 * @note Call saveSettings() after calling this function to commit the change.
4267 *
4268 * @return bool
4269 */
4270 public function confirmEmail() {
4271 // Check if it's already confirmed, so we don't touch the database
4272 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4273 if ( !$this->isEmailConfirmed() ) {
4274 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4275 Hooks::run( 'ConfirmEmailComplete', array( $this ) );
4276 }
4277 return true;
4278 }
4279
4280 /**
4281 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4282 * address if it was already confirmed.
4283 *
4284 * @note Call saveSettings() after calling this function to commit the change.
4285 * @return bool Returns true
4286 */
4287 public function invalidateEmail() {
4288 $this->load();
4289 $this->mEmailToken = null;
4290 $this->mEmailTokenExpires = null;
4291 $this->setEmailAuthenticationTimestamp( null );
4292 $this->mEmail = '';
4293 Hooks::run( 'InvalidateEmailComplete', array( $this ) );
4294 return true;
4295 }
4296
4297 /**
4298 * Set the e-mail authentication timestamp.
4299 * @param string $timestamp TS_MW timestamp
4300 */
4301 public function setEmailAuthenticationTimestamp( $timestamp ) {
4302 $this->load();
4303 $this->mEmailAuthenticated = $timestamp;
4304 Hooks::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4305 }
4306
4307 /**
4308 * Is this user allowed to send e-mails within limits of current
4309 * site configuration?
4310 * @return bool
4311 */
4312 public function canSendEmail() {
4313 global $wgEnableEmail, $wgEnableUserEmail;
4314 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4315 return false;
4316 }
4317 $canSend = $this->isEmailConfirmed();
4318 Hooks::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4319 return $canSend;
4320 }
4321
4322 /**
4323 * Is this user allowed to receive e-mails within limits of current
4324 * site configuration?
4325 * @return bool
4326 */
4327 public function canReceiveEmail() {
4328 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4329 }
4330
4331 /**
4332 * Is this user's e-mail address valid-looking and confirmed within
4333 * limits of the current site configuration?
4334 *
4335 * @note If $wgEmailAuthentication is on, this may require the user to have
4336 * confirmed their address by returning a code or using a password
4337 * sent to the address from the wiki.
4338 *
4339 * @return bool
4340 */
4341 public function isEmailConfirmed() {
4342 global $wgEmailAuthentication;
4343 $this->load();
4344 $confirmed = true;
4345 if ( Hooks::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4346 if ( $this->isAnon() ) {
4347 return false;
4348 }
4349 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4350 return false;
4351 }
4352 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4353 return false;
4354 }
4355 return true;
4356 } else {
4357 return $confirmed;
4358 }
4359 }
4360
4361 /**
4362 * Check whether there is an outstanding request for e-mail confirmation.
4363 * @return bool
4364 */
4365 public function isEmailConfirmationPending() {
4366 global $wgEmailAuthentication;
4367 return $wgEmailAuthentication &&
4368 !$this->isEmailConfirmed() &&
4369 $this->mEmailToken &&
4370 $this->mEmailTokenExpires > wfTimestamp();
4371 }
4372
4373 /**
4374 * Get the timestamp of account creation.
4375 *
4376 * @return string|bool|null Timestamp of account creation, false for
4377 * non-existent/anonymous user accounts, or null if existing account
4378 * but information is not in database.
4379 */
4380 public function getRegistration() {
4381 if ( $this->isAnon() ) {
4382 return false;
4383 }
4384 $this->load();
4385 return $this->mRegistration;
4386 }
4387
4388 /**
4389 * Get the timestamp of the first edit
4390 *
4391 * @return string|bool Timestamp of first edit, or false for
4392 * non-existent/anonymous user accounts.
4393 */
4394 public function getFirstEditTimestamp() {
4395 if ( $this->getId() == 0 ) {
4396 return false; // anons
4397 }
4398 $dbr = wfGetDB( DB_SLAVE );
4399 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4400 array( 'rev_user' => $this->getId() ),
4401 __METHOD__,
4402 array( 'ORDER BY' => 'rev_timestamp ASC' )
4403 );
4404 if ( !$time ) {
4405 return false; // no edits
4406 }
4407 return wfTimestamp( TS_MW, $time );
4408 }
4409
4410 /**
4411 * Get the permissions associated with a given list of groups
4412 *
4413 * @param array $groups Array of Strings List of internal group names
4414 * @return array Array of Strings List of permission key names for given groups combined
4415 */
4416 public static function getGroupPermissions( $groups ) {
4417 global $wgGroupPermissions, $wgRevokePermissions;
4418 $rights = array();
4419 // grant every granted permission first
4420 foreach ( $groups as $group ) {
4421 if ( isset( $wgGroupPermissions[$group] ) ) {
4422 $rights = array_merge( $rights,
4423 // array_filter removes empty items
4424 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4425 }
4426 }
4427 // now revoke the revoked permissions
4428 foreach ( $groups as $group ) {
4429 if ( isset( $wgRevokePermissions[$group] ) ) {
4430 $rights = array_diff( $rights,
4431 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4432 }
4433 }
4434 return array_unique( $rights );
4435 }
4436
4437 /**
4438 * Get all the groups who have a given permission
4439 *
4440 * @param string $role Role to check
4441 * @return array Array of Strings List of internal group names with the given permission
4442 */
4443 public static function getGroupsWithPermission( $role ) {
4444 global $wgGroupPermissions;
4445 $allowedGroups = array();
4446 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4447 if ( self::groupHasPermission( $group, $role ) ) {
4448 $allowedGroups[] = $group;
4449 }
4450 }
4451 return $allowedGroups;
4452 }
4453
4454 /**
4455 * Check, if the given group has the given permission
4456 *
4457 * If you're wanting to check whether all users have a permission, use
4458 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4459 * from anyone.
4460 *
4461 * @since 1.21
4462 * @param string $group Group to check
4463 * @param string $role Role to check
4464 * @return bool
4465 */
4466 public static function groupHasPermission( $group, $role ) {
4467 global $wgGroupPermissions, $wgRevokePermissions;
4468 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4469 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4470 }
4471
4472 /**
4473 * Check if all users have the given permission
4474 *
4475 * @since 1.22
4476 * @param string $right Right to check
4477 * @return bool
4478 */
4479 public static function isEveryoneAllowed( $right ) {
4480 global $wgGroupPermissions, $wgRevokePermissions;
4481 static $cache = array();
4482
4483 // Use the cached results, except in unit tests which rely on
4484 // being able change the permission mid-request
4485 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4486 return $cache[$right];
4487 }
4488
4489 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4490 $cache[$right] = false;
4491 return false;
4492 }
4493
4494 // If it's revoked anywhere, then everyone doesn't have it
4495 foreach ( $wgRevokePermissions as $rights ) {
4496 if ( isset( $rights[$right] ) && $rights[$right] ) {
4497 $cache[$right] = false;
4498 return false;
4499 }
4500 }
4501
4502 // Allow extensions (e.g. OAuth) to say false
4503 if ( !Hooks::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4504 $cache[$right] = false;
4505 return false;
4506 }
4507
4508 $cache[$right] = true;
4509 return true;
4510 }
4511
4512 /**
4513 * Get the localized descriptive name for a group, if it exists
4514 *
4515 * @param string $group Internal group name
4516 * @return string Localized descriptive group name
4517 */
4518 public static function getGroupName( $group ) {
4519 $msg = wfMessage( "group-$group" );
4520 return $msg->isBlank() ? $group : $msg->text();
4521 }
4522
4523 /**
4524 * Get the localized descriptive name for a member of a group, if it exists
4525 *
4526 * @param string $group Internal group name
4527 * @param string $username Username for gender (since 1.19)
4528 * @return string Localized name for group member
4529 */
4530 public static function getGroupMember( $group, $username = '#' ) {
4531 $msg = wfMessage( "group-$group-member", $username );
4532 return $msg->isBlank() ? $group : $msg->text();
4533 }
4534
4535 /**
4536 * Return the set of defined explicit groups.
4537 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4538 * are not included, as they are defined automatically, not in the database.
4539 * @return array Array of internal group names
4540 */
4541 public static function getAllGroups() {
4542 global $wgGroupPermissions, $wgRevokePermissions;
4543 return array_diff(
4544 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4545 self::getImplicitGroups()
4546 );
4547 }
4548
4549 /**
4550 * Get a list of all available permissions.
4551 * @return string[] Array of permission names
4552 */
4553 public static function getAllRights() {
4554 if ( self::$mAllRights === false ) {
4555 global $wgAvailableRights;
4556 if ( count( $wgAvailableRights ) ) {
4557 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4558 } else {
4559 self::$mAllRights = self::$mCoreRights;
4560 }
4561 Hooks::run( 'UserGetAllRights', array( &self::$mAllRights ) );
4562 }
4563 return self::$mAllRights;
4564 }
4565
4566 /**
4567 * Get a list of implicit groups
4568 * @return array Array of Strings Array of internal group names
4569 */
4570 public static function getImplicitGroups() {
4571 global $wgImplicitGroups;
4572
4573 $groups = $wgImplicitGroups;
4574 # Deprecated, use $wgImplicitGroups instead
4575 Hooks::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4576
4577 return $groups;
4578 }
4579
4580 /**
4581 * Get the title of a page describing a particular group
4582 *
4583 * @param string $group Internal group name
4584 * @return Title|bool Title of the page if it exists, false otherwise
4585 */
4586 public static function getGroupPage( $group ) {
4587 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4588 if ( $msg->exists() ) {
4589 $title = Title::newFromText( $msg->text() );
4590 if ( is_object( $title ) ) {
4591 return $title;
4592 }
4593 }
4594 return false;
4595 }
4596
4597 /**
4598 * Create a link to the group in HTML, if available;
4599 * else return the group name.
4600 *
4601 * @param string $group Internal name of the group
4602 * @param string $text The text of the link
4603 * @return string HTML link to the group
4604 */
4605 public static function makeGroupLinkHTML( $group, $text = '' ) {
4606 if ( $text == '' ) {
4607 $text = self::getGroupName( $group );
4608 }
4609 $title = self::getGroupPage( $group );
4610 if ( $title ) {
4611 return Linker::link( $title, htmlspecialchars( $text ) );
4612 } else {
4613 return htmlspecialchars( $text );
4614 }
4615 }
4616
4617 /**
4618 * Create a link to the group in Wikitext, if available;
4619 * else return the group name.
4620 *
4621 * @param string $group Internal name of the group
4622 * @param string $text The text of the link
4623 * @return string Wikilink to the group
4624 */
4625 public static function makeGroupLinkWiki( $group, $text = '' ) {
4626 if ( $text == '' ) {
4627 $text = self::getGroupName( $group );
4628 }
4629 $title = self::getGroupPage( $group );
4630 if ( $title ) {
4631 $page = $title->getFullText();
4632 return "[[$page|$text]]";
4633 } else {
4634 return $text;
4635 }
4636 }
4637
4638 /**
4639 * Returns an array of the groups that a particular group can add/remove.
4640 *
4641 * @param string $group The group to check for whether it can add/remove
4642 * @return array Array( 'add' => array( addablegroups ),
4643 * 'remove' => array( removablegroups ),
4644 * 'add-self' => array( addablegroups to self),
4645 * 'remove-self' => array( removable groups from self) )
4646 */
4647 public static function changeableByGroup( $group ) {
4648 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4649
4650 $groups = array(
4651 'add' => array(),
4652 'remove' => array(),
4653 'add-self' => array(),
4654 'remove-self' => array()
4655 );
4656
4657 if ( empty( $wgAddGroups[$group] ) ) {
4658 // Don't add anything to $groups
4659 } elseif ( $wgAddGroups[$group] === true ) {
4660 // You get everything
4661 $groups['add'] = self::getAllGroups();
4662 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4663 $groups['add'] = $wgAddGroups[$group];
4664 }
4665
4666 // Same thing for remove
4667 if ( empty( $wgRemoveGroups[$group] ) ) {
4668 // Do nothing
4669 } elseif ( $wgRemoveGroups[$group] === true ) {
4670 $groups['remove'] = self::getAllGroups();
4671 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4672 $groups['remove'] = $wgRemoveGroups[$group];
4673 }
4674
4675 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4676 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4677 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4678 if ( is_int( $key ) ) {
4679 $wgGroupsAddToSelf['user'][] = $value;
4680 }
4681 }
4682 }
4683
4684 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4685 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4686 if ( is_int( $key ) ) {
4687 $wgGroupsRemoveFromSelf['user'][] = $value;
4688 }
4689 }
4690 }
4691
4692 // Now figure out what groups the user can add to him/herself
4693 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4694 // Do nothing
4695 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4696 // No idea WHY this would be used, but it's there
4697 $groups['add-self'] = User::getAllGroups();
4698 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4699 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4700 }
4701
4702 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4703 // Do nothing
4704 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4705 $groups['remove-self'] = User::getAllGroups();
4706 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4707 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4708 }
4709
4710 return $groups;
4711 }
4712
4713 /**
4714 * Returns an array of groups that this user can add and remove
4715 * @return array Array( 'add' => array( addablegroups ),
4716 * 'remove' => array( removablegroups ),
4717 * 'add-self' => array( addablegroups to self),
4718 * 'remove-self' => array( removable groups from self) )
4719 */
4720 public function changeableGroups() {
4721 if ( $this->isAllowed( 'userrights' ) ) {
4722 // This group gives the right to modify everything (reverse-
4723 // compatibility with old "userrights lets you change
4724 // everything")
4725 // Using array_merge to make the groups reindexed
4726 $all = array_merge( User::getAllGroups() );
4727 return array(
4728 'add' => $all,
4729 'remove' => $all,
4730 'add-self' => array(),
4731 'remove-self' => array()
4732 );
4733 }
4734
4735 // Okay, it's not so simple, we will have to go through the arrays
4736 $groups = array(
4737 'add' => array(),
4738 'remove' => array(),
4739 'add-self' => array(),
4740 'remove-self' => array()
4741 );
4742 $addergroups = $this->getEffectiveGroups();
4743
4744 foreach ( $addergroups as $addergroup ) {
4745 $groups = array_merge_recursive(
4746 $groups, $this->changeableByGroup( $addergroup )
4747 );
4748 $groups['add'] = array_unique( $groups['add'] );
4749 $groups['remove'] = array_unique( $groups['remove'] );
4750 $groups['add-self'] = array_unique( $groups['add-self'] );
4751 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4752 }
4753 return $groups;
4754 }
4755
4756 /**
4757 * Increment the user's edit-count field.
4758 * Will have no effect for anonymous users.
4759 */
4760 public function incEditCount() {
4761 if ( !$this->isAnon() ) {
4762 $dbw = wfGetDB( DB_MASTER );
4763 $dbw->update(
4764 'user',
4765 array( 'user_editcount=user_editcount+1' ),
4766 array( 'user_id' => $this->getId() ),
4767 __METHOD__
4768 );
4769
4770 // Lazy initialization check...
4771 if ( $dbw->affectedRows() == 0 ) {
4772 // Now here's a goddamn hack...
4773 $dbr = wfGetDB( DB_SLAVE );
4774 if ( $dbr !== $dbw ) {
4775 // If we actually have a slave server, the count is
4776 // at least one behind because the current transaction
4777 // has not been committed and replicated.
4778 $this->initEditCount( 1 );
4779 } else {
4780 // But if DB_SLAVE is selecting the master, then the
4781 // count we just read includes the revision that was
4782 // just added in the working transaction.
4783 $this->initEditCount();
4784 }
4785 }
4786 }
4787 // edit count in user cache too
4788 $this->invalidateCache();
4789 }
4790
4791 /**
4792 * Initialize user_editcount from data out of the revision table
4793 *
4794 * @param int $add Edits to add to the count from the revision table
4795 * @return int Number of edits
4796 */
4797 protected function initEditCount( $add = 0 ) {
4798 // Pull from a slave to be less cruel to servers
4799 // Accuracy isn't the point anyway here
4800 $dbr = wfGetDB( DB_SLAVE );
4801 $count = (int)$dbr->selectField(
4802 'revision',
4803 'COUNT(rev_user)',
4804 array( 'rev_user' => $this->getId() ),
4805 __METHOD__
4806 );
4807 $count = $count + $add;
4808
4809 $dbw = wfGetDB( DB_MASTER );
4810 $dbw->update(
4811 'user',
4812 array( 'user_editcount' => $count ),
4813 array( 'user_id' => $this->getId() ),
4814 __METHOD__
4815 );
4816
4817 return $count;
4818 }
4819
4820 /**
4821 * Get the description of a given right
4822 *
4823 * @param string $right Right to query
4824 * @return string Localized description of the right
4825 */
4826 public static function getRightDescription( $right ) {
4827 $key = "right-$right";
4828 $msg = wfMessage( $key );
4829 return $msg->isBlank() ? $right : $msg->text();
4830 }
4831
4832 /**
4833 * Make a new-style password hash
4834 *
4835 * @param string $password Plain-text password
4836 * @param bool|string $salt Optional salt, may be random or the user ID.
4837 * If unspecified or false, will generate one automatically
4838 * @return string Password hash
4839 * @deprecated since 1.24, use Password class
4840 */
4841 public static function crypt( $password, $salt = false ) {
4842 wfDeprecated( __METHOD__, '1.24' );
4843 $hash = self::getPasswordFactory()->newFromPlaintext( $password );
4844 return $hash->toString();
4845 }
4846
4847 /**
4848 * Compare a password hash with a plain-text password. Requires the user
4849 * ID if there's a chance that the hash is an old-style hash.
4850 *
4851 * @param string $hash Password hash
4852 * @param string $password Plain-text password to compare
4853 * @param string|bool $userId User ID for old-style password salt
4854 *
4855 * @return bool
4856 * @deprecated since 1.24, use Password class
4857 */
4858 public static function comparePasswords( $hash, $password, $userId = false ) {
4859 wfDeprecated( __METHOD__, '1.24' );
4860
4861 // Check for *really* old password hashes that don't even have a type
4862 // The old hash format was just an md5 hex hash, with no type information
4863 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4864 global $wgPasswordSalt;
4865 if ( $wgPasswordSalt ) {
4866 $password = ":B:{$userId}:{$hash}";
4867 } else {
4868 $password = ":A:{$hash}";
4869 }
4870 }
4871
4872 $hash = self::getPasswordFactory()->newFromCiphertext( $hash );
4873 return $hash->equals( $password );
4874 }
4875
4876 /**
4877 * Add a newuser log entry for this user.
4878 * Before 1.19 the return value was always true.
4879 *
4880 * @param string|bool $action Account creation type.
4881 * - String, one of the following values:
4882 * - 'create' for an anonymous user creating an account for himself.
4883 * This will force the action's performer to be the created user itself,
4884 * no matter the value of $wgUser
4885 * - 'create2' for a logged in user creating an account for someone else
4886 * - 'byemail' when the created user will receive its password by e-mail
4887 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4888 * - Boolean means whether the account was created by e-mail (deprecated):
4889 * - true will be converted to 'byemail'
4890 * - false will be converted to 'create' if this object is the same as
4891 * $wgUser and to 'create2' otherwise
4892 *
4893 * @param string $reason User supplied reason
4894 *
4895 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4896 */
4897 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4898 global $wgUser, $wgNewUserLog;
4899 if ( empty( $wgNewUserLog ) ) {
4900 return true; // disabled
4901 }
4902
4903 if ( $action === true ) {
4904 $action = 'byemail';
4905 } elseif ( $action === false ) {
4906 if ( $this->equals( $wgUser ) ) {
4907 $action = 'create';
4908 } else {
4909 $action = 'create2';
4910 }
4911 }
4912
4913 if ( $action === 'create' || $action === 'autocreate' ) {
4914 $performer = $this;
4915 } else {
4916 $performer = $wgUser;
4917 }
4918
4919 $logEntry = new ManualLogEntry( 'newusers', $action );
4920 $logEntry->setPerformer( $performer );
4921 $logEntry->setTarget( $this->getUserPage() );
4922 $logEntry->setComment( $reason );
4923 $logEntry->setParameters( array(
4924 '4::userid' => $this->getId(),
4925 ) );
4926 $logid = $logEntry->insert();
4927
4928 if ( $action !== 'autocreate' ) {
4929 $logEntry->publish( $logid );
4930 }
4931
4932 return (int)$logid;
4933 }
4934
4935 /**
4936 * Add an autocreate newuser log entry for this user
4937 * Used by things like CentralAuth and perhaps other authplugins.
4938 * Consider calling addNewUserLogEntry() directly instead.
4939 *
4940 * @return bool
4941 */
4942 public function addNewUserLogEntryAutoCreate() {
4943 $this->addNewUserLogEntry( 'autocreate' );
4944
4945 return true;
4946 }
4947
4948 /**
4949 * Load the user options either from cache, the database or an array
4950 *
4951 * @param array $data Rows for the current user out of the user_properties table
4952 */
4953 protected function loadOptions( $data = null ) {
4954 global $wgContLang;
4955
4956 $this->load();
4957
4958 if ( $this->mOptionsLoaded ) {
4959 return;
4960 }
4961
4962 $this->mOptions = self::getDefaultOptions();
4963
4964 if ( !$this->getId() ) {
4965 // For unlogged-in users, load language/variant options from request.
4966 // There's no need to do it for logged-in users: they can set preferences,
4967 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4968 // so don't override user's choice (especially when the user chooses site default).
4969 $variant = $wgContLang->getDefaultVariant();
4970 $this->mOptions['variant'] = $variant;
4971 $this->mOptions['language'] = $variant;
4972 $this->mOptionsLoaded = true;
4973 return;
4974 }
4975
4976 // Maybe load from the object
4977 if ( !is_null( $this->mOptionOverrides ) ) {
4978 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4979 foreach ( $this->mOptionOverrides as $key => $value ) {
4980 $this->mOptions[$key] = $value;
4981 }
4982 } else {
4983 if ( !is_array( $data ) ) {
4984 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4985 // Load from database
4986 $dbr = ( $this->queryFlagsUsed & self::READ_LATEST )
4987 ? wfGetDB( DB_MASTER )
4988 : wfGetDB( DB_SLAVE );
4989
4990 $res = $dbr->select(
4991 'user_properties',
4992 array( 'up_property', 'up_value' ),
4993 array( 'up_user' => $this->getId() ),
4994 __METHOD__
4995 );
4996
4997 $this->mOptionOverrides = array();
4998 $data = array();
4999 foreach ( $res as $row ) {
5000 $data[$row->up_property] = $row->up_value;
5001 }
5002 }
5003 foreach ( $data as $property => $value ) {
5004 $this->mOptionOverrides[$property] = $value;
5005 $this->mOptions[$property] = $value;
5006 }
5007 }
5008
5009 $this->mOptionsLoaded = true;
5010
5011 Hooks::run( 'UserLoadOptions', array( $this, &$this->mOptions ) );
5012 }
5013
5014 /**
5015 * Saves the non-default options for this user, as previously set e.g. via
5016 * setOption(), in the database's "user_properties" (preferences) table.
5017 * Usually used via saveSettings().
5018 */
5019 protected function saveOptions() {
5020 $this->loadOptions();
5021
5022 // Not using getOptions(), to keep hidden preferences in database
5023 $saveOptions = $this->mOptions;
5024
5025 // Allow hooks to abort, for instance to save to a global profile.
5026 // Reset options to default state before saving.
5027 if ( !Hooks::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
5028 return;
5029 }
5030
5031 $userId = $this->getId();
5032
5033 $insert_rows = array(); // all the new preference rows
5034 foreach ( $saveOptions as $key => $value ) {
5035 // Don't bother storing default values
5036 $defaultOption = self::getDefaultOption( $key );
5037 if ( ( $defaultOption === null && $value !== false && $value !== null )
5038 || $value != $defaultOption
5039 ) {
5040 $insert_rows[] = array(
5041 'up_user' => $userId,
5042 'up_property' => $key,
5043 'up_value' => $value,
5044 );
5045 }
5046 }
5047
5048 $dbw = wfGetDB( DB_MASTER );
5049
5050 $res = $dbw->select( 'user_properties',
5051 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__ );
5052
5053 // Find prior rows that need to be removed or updated. These rows will
5054 // all be deleted (the later so that INSERT IGNORE applies the new values).
5055 $keysDelete = array();
5056 foreach ( $res as $row ) {
5057 if ( !isset( $saveOptions[$row->up_property] )
5058 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
5059 ) {
5060 $keysDelete[] = $row->up_property;
5061 }
5062 }
5063
5064 if ( count( $keysDelete ) ) {
5065 // Do the DELETE by PRIMARY KEY for prior rows.
5066 // In the past a very large portion of calls to this function are for setting
5067 // 'rememberpassword' for new accounts (a preference that has since been removed).
5068 // Doing a blanket per-user DELETE for new accounts with no rows in the table
5069 // caused gap locks on [max user ID,+infinity) which caused high contention since
5070 // updates would pile up on each other as they are for higher (newer) user IDs.
5071 // It might not be necessary these days, but it shouldn't hurt either.
5072 $dbw->delete( 'user_properties',
5073 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__ );
5074 }
5075 // Insert the new preference rows
5076 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
5077 }
5078
5079 /**
5080 * Lazily instantiate and return a factory object for making passwords
5081 *
5082 * @return PasswordFactory
5083 */
5084 public static function getPasswordFactory() {
5085 if ( self::$mPasswordFactory === null ) {
5086 self::$mPasswordFactory = new PasswordFactory();
5087 self::$mPasswordFactory->init( RequestContext::getMain()->getConfig() );
5088 }
5089
5090 return self::$mPasswordFactory;
5091 }
5092
5093 /**
5094 * Provide an array of HTML5 attributes to put on an input element
5095 * intended for the user to enter a new password. This may include
5096 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
5097 *
5098 * Do *not* use this when asking the user to enter his current password!
5099 * Regardless of configuration, users may have invalid passwords for whatever
5100 * reason (e.g., they were set before requirements were tightened up).
5101 * Only use it when asking for a new password, like on account creation or
5102 * ResetPass.
5103 *
5104 * Obviously, you still need to do server-side checking.
5105 *
5106 * NOTE: A combination of bugs in various browsers means that this function
5107 * actually just returns array() unconditionally at the moment. May as
5108 * well keep it around for when the browser bugs get fixed, though.
5109 *
5110 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
5111 *
5112 * @return array Array of HTML attributes suitable for feeding to
5113 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
5114 * That will get confused by the boolean attribute syntax used.)
5115 */
5116 public static function passwordChangeInputAttribs() {
5117 global $wgMinimalPasswordLength;
5118
5119 if ( $wgMinimalPasswordLength == 0 ) {
5120 return array();
5121 }
5122
5123 # Note that the pattern requirement will always be satisfied if the
5124 # input is empty, so we need required in all cases.
5125 #
5126 # @todo FIXME: Bug 23769: This needs to not claim the password is required
5127 # if e-mail confirmation is being used. Since HTML5 input validation
5128 # is b0rked anyway in some browsers, just return nothing. When it's
5129 # re-enabled, fix this code to not output required for e-mail
5130 # registration.
5131 #$ret = array( 'required' );
5132 $ret = array();
5133
5134 # We can't actually do this right now, because Opera 9.6 will print out
5135 # the entered password visibly in its error message! When other
5136 # browsers add support for this attribute, or Opera fixes its support,
5137 # we can add support with a version check to avoid doing this on Opera
5138 # versions where it will be a problem. Reported to Opera as
5139 # DSK-262266, but they don't have a public bug tracker for us to follow.
5140 /*
5141 if ( $wgMinimalPasswordLength > 1 ) {
5142 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
5143 $ret['title'] = wfMessage( 'passwordtooshort' )
5144 ->numParams( $wgMinimalPasswordLength )->text();
5145 }
5146 */
5147
5148 return $ret;
5149 }
5150
5151 /**
5152 * Return the list of user fields that should be selected to create
5153 * a new user object.
5154 * @return array
5155 */
5156 public static function selectFields() {
5157 return array(
5158 'user_id',
5159 'user_name',
5160 'user_real_name',
5161 'user_email',
5162 'user_touched',
5163 'user_token',
5164 'user_email_authenticated',
5165 'user_email_token',
5166 'user_email_token_expires',
5167 'user_registration',
5168 'user_editcount',
5169 );
5170 }
5171
5172 /**
5173 * Factory function for fatal permission-denied errors
5174 *
5175 * @since 1.22
5176 * @param string $permission User right required
5177 * @return Status
5178 */
5179 static function newFatalPermissionDeniedStatus( $permission ) {
5180 global $wgLang;
5181
5182 $groups = array_map(
5183 array( 'User', 'makeGroupLinkWiki' ),
5184 User::getGroupsWithPermission( $permission )
5185 );
5186
5187 if ( $groups ) {
5188 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5189 } else {
5190 return Status::newFatal( 'badaccess-group0' );
5191 }
5192 }
5193
5194 /**
5195 * Checks if two user objects point to the same user.
5196 *
5197 * @since 1.25
5198 * @param User $user
5199 * @return bool
5200 */
5201 public function equals( User $user ) {
5202 return $this->getName() === $user->getName();
5203 }
5204 }