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