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