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