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