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