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