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