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