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