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