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