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