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