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