0c6b15f3b03e2edd8e26768f6be44c7d1249e34f
[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 */
3012 public function addGroup( $group ) {
3013 if ( Hooks::run( 'UserAddGroup', array( $this, &$group ) ) ) {
3014 $dbw = wfGetDB( DB_MASTER );
3015 if ( $this->getId() ) {
3016 $dbw->insert( 'user_groups',
3017 array(
3018 'ug_user' => $this->getID(),
3019 'ug_group' => $group,
3020 ),
3021 __METHOD__,
3022 array( 'IGNORE' ) );
3023 }
3024 }
3025 $this->loadGroups();
3026 $this->mGroups[] = $group;
3027 // In case loadGroups was not called before, we now have the right twice.
3028 // Get rid of the duplicate.
3029 $this->mGroups = array_unique( $this->mGroups );
3030
3031 // Refresh the groups caches, and clear the rights cache so it will be
3032 // refreshed on the next call to $this->getRights().
3033 $this->getEffectiveGroups( true );
3034 $this->mRights = null;
3035
3036 $this->invalidateCache();
3037 }
3038
3039 /**
3040 * Remove the user from the given group.
3041 * This takes immediate effect.
3042 * @param string $group Name of the group to remove
3043 */
3044 public function removeGroup( $group ) {
3045 $this->load();
3046 if ( Hooks::run( 'UserRemoveGroup', array( $this, &$group ) ) ) {
3047 $dbw = wfGetDB( DB_MASTER );
3048 $dbw->delete( 'user_groups',
3049 array(
3050 'ug_user' => $this->getID(),
3051 'ug_group' => $group,
3052 ), __METHOD__ );
3053 // Remember that the user was in this group
3054 $dbw->insert( 'user_former_groups',
3055 array(
3056 'ufg_user' => $this->getID(),
3057 'ufg_group' => $group,
3058 ),
3059 __METHOD__,
3060 array( 'IGNORE' ) );
3061 }
3062 $this->loadGroups();
3063 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
3064
3065 // Refresh the groups caches, and clear the rights cache so it will be
3066 // refreshed on the next call to $this->getRights().
3067 $this->getEffectiveGroups( true );
3068 $this->mRights = null;
3069
3070 $this->invalidateCache();
3071 }
3072
3073 /**
3074 * Get whether the user is logged in
3075 * @return bool
3076 */
3077 public function isLoggedIn() {
3078 return $this->getID() != 0;
3079 }
3080
3081 /**
3082 * Get whether the user is anonymous
3083 * @return bool
3084 */
3085 public function isAnon() {
3086 return !$this->isLoggedIn();
3087 }
3088
3089 /**
3090 * Check if user is allowed to access a feature / make an action
3091 *
3092 * @param string $permissions,... Permissions to test
3093 * @return bool True if user is allowed to perform *any* of the given actions
3094 */
3095 public function isAllowedAny( /*...*/ ) {
3096 $permissions = func_get_args();
3097 foreach ( $permissions as $permission ) {
3098 if ( $this->isAllowed( $permission ) ) {
3099 return true;
3100 }
3101 }
3102 return false;
3103 }
3104
3105 /**
3106 *
3107 * @param string $permissions,... Permissions to test
3108 * @return bool True if the user is allowed to perform *all* of the given actions
3109 */
3110 public function isAllowedAll( /*...*/ ) {
3111 $permissions = func_get_args();
3112 foreach ( $permissions as $permission ) {
3113 if ( !$this->isAllowed( $permission ) ) {
3114 return false;
3115 }
3116 }
3117 return true;
3118 }
3119
3120 /**
3121 * Internal mechanics of testing a permission
3122 * @param string $action
3123 * @return bool
3124 */
3125 public function isAllowed( $action = '' ) {
3126 if ( $action === '' ) {
3127 return true; // In the spirit of DWIM
3128 }
3129 // Patrolling may not be enabled
3130 if ( $action === 'patrol' || $action === 'autopatrol' ) {
3131 global $wgUseRCPatrol, $wgUseNPPatrol;
3132 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
3133 return false;
3134 }
3135 }
3136 // Use strict parameter to avoid matching numeric 0 accidentally inserted
3137 // by misconfiguration: 0 == 'foo'
3138 return in_array( $action, $this->getRights(), true );
3139 }
3140
3141 /**
3142 * Check whether to enable recent changes patrol features for this user
3143 * @return bool True or false
3144 */
3145 public function useRCPatrol() {
3146 global $wgUseRCPatrol;
3147 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
3148 }
3149
3150 /**
3151 * Check whether to enable new pages patrol features for this user
3152 * @return bool True or false
3153 */
3154 public function useNPPatrol() {
3155 global $wgUseRCPatrol, $wgUseNPPatrol;
3156 return (
3157 ( $wgUseRCPatrol || $wgUseNPPatrol )
3158 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
3159 );
3160 }
3161
3162 /**
3163 * Get the WebRequest object to use with this object
3164 *
3165 * @return WebRequest
3166 */
3167 public function getRequest() {
3168 if ( $this->mRequest ) {
3169 return $this->mRequest;
3170 } else {
3171 global $wgRequest;
3172 return $wgRequest;
3173 }
3174 }
3175
3176 /**
3177 * Get the current skin, loading it if required
3178 * @return Skin The current skin
3179 * @todo FIXME: Need to check the old failback system [AV]
3180 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
3181 */
3182 public function getSkin() {
3183 wfDeprecated( __METHOD__, '1.18' );
3184 return RequestContext::getMain()->getSkin();
3185 }
3186
3187 /**
3188 * Get a WatchedItem for this user and $title.
3189 *
3190 * @since 1.22 $checkRights parameter added
3191 * @param Title $title
3192 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3193 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3194 * @return WatchedItem
3195 */
3196 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3197 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
3198
3199 if ( isset( $this->mWatchedItems[$key] ) ) {
3200 return $this->mWatchedItems[$key];
3201 }
3202
3203 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
3204 $this->mWatchedItems = array();
3205 }
3206
3207 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
3208 return $this->mWatchedItems[$key];
3209 }
3210
3211 /**
3212 * Check the watched status of an article.
3213 * @since 1.22 $checkRights parameter added
3214 * @param Title $title Title of the article to look at
3215 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3216 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3217 * @return bool
3218 */
3219 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3220 return $this->getWatchedItem( $title, $checkRights )->isWatched();
3221 }
3222
3223 /**
3224 * Watch an article.
3225 * @since 1.22 $checkRights parameter added
3226 * @param Title $title Title of the article to look at
3227 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3228 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3229 */
3230 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3231 $this->getWatchedItem( $title, $checkRights )->addWatch();
3232 $this->invalidateCache();
3233 }
3234
3235 /**
3236 * Stop watching an article.
3237 * @since 1.22 $checkRights parameter added
3238 * @param Title $title Title of the article to look at
3239 * @param int $checkRights Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3240 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3241 */
3242 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3243 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3244 $this->invalidateCache();
3245 }
3246
3247 /**
3248 * Clear the user's notification timestamp for the given title.
3249 * If e-notif e-mails are on, they will receive notification mails on
3250 * the next change of the page if it's watched etc.
3251 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3252 * @param Title $title Title of the article to look at
3253 * @param int $oldid The revision id being viewed. If not given or 0, latest revision is assumed.
3254 */
3255 public function clearNotification( &$title, $oldid = 0 ) {
3256 global $wgUseEnotif, $wgShowUpdatedMarker;
3257
3258 // Do nothing if the database is locked to writes
3259 if ( wfReadOnly() ) {
3260 return;
3261 }
3262
3263 // Do nothing if not allowed to edit the watchlist
3264 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3265 return;
3266 }
3267
3268 // If we're working on user's talk page, we should update the talk page message indicator
3269 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3270 if ( !Hooks::run( 'UserClearNewTalkNotification', array( &$this, $oldid ) ) ) {
3271 return;
3272 }
3273
3274 $nextid = $oldid ? $title->getNextRevisionID( $oldid ) : null;
3275
3276 if ( !$oldid || !$nextid ) {
3277 // If we're looking at the latest revision, we should definitely clear it
3278 $this->setNewtalk( false );
3279 } else {
3280 // Otherwise we should update its revision, if it's present
3281 if ( $this->getNewtalk() ) {
3282 // Naturally the other one won't clear by itself
3283 $this->setNewtalk( false );
3284 $this->setNewtalk( true, Revision::newFromId( $nextid ) );
3285 }
3286 }
3287 }
3288
3289 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3290 return;
3291 }
3292
3293 if ( $this->isAnon() ) {
3294 // Nothing else to do...
3295 return;
3296 }
3297
3298 // Only update the timestamp if the page is being watched.
3299 // The query to find out if it is watched is cached both in memcached and per-invocation,
3300 // and when it does have to be executed, it can be on a slave
3301 // If this is the user's newtalk page, we always update the timestamp
3302 $force = '';
3303 if ( $title->getNamespace() == NS_USER_TALK && $title->getText() == $this->getName() ) {
3304 $force = 'force';
3305 }
3306
3307 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force, $oldid );
3308 }
3309
3310 /**
3311 * Resets all of the given user's page-change notification timestamps.
3312 * If e-notif e-mails are on, they will receive notification mails on
3313 * the next change of any watched page.
3314 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3315 */
3316 public function clearAllNotifications() {
3317 if ( wfReadOnly() ) {
3318 return;
3319 }
3320
3321 // Do nothing if not allowed to edit the watchlist
3322 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3323 return;
3324 }
3325
3326 global $wgUseEnotif, $wgShowUpdatedMarker;
3327 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3328 $this->setNewtalk( false );
3329 return;
3330 }
3331 $id = $this->getId();
3332 if ( $id != 0 ) {
3333 $dbw = wfGetDB( DB_MASTER );
3334 $dbw->update( 'watchlist',
3335 array( /* SET */ 'wl_notificationtimestamp' => null ),
3336 array( /* WHERE */ 'wl_user' => $id ),
3337 __METHOD__
3338 );
3339 // We also need to clear here the "you have new message" notification for the own user_talk page;
3340 // it's cleared one page view later in WikiPage::doViewUpdates().
3341 }
3342 }
3343
3344 /**
3345 * Set a cookie on the user's client. Wrapper for
3346 * WebResponse::setCookie
3347 * @param string $name Name of the cookie to set
3348 * @param string $value Value to set
3349 * @param int $exp Expiration time, as a UNIX time value;
3350 * if 0 or not specified, use the default $wgCookieExpiration
3351 * @param bool $secure
3352 * true: Force setting the secure attribute when setting the cookie
3353 * false: Force NOT setting the secure attribute when setting the cookie
3354 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3355 * @param array $params Array of options sent passed to WebResponse::setcookie()
3356 */
3357 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3358 $params['secure'] = $secure;
3359 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3360 }
3361
3362 /**
3363 * Clear a cookie on the user's client
3364 * @param string $name Name of the cookie to clear
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 clearCookie( $name, $secure = null, $params = array() ) {
3372 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3373 }
3374
3375 /**
3376 * Set the default cookies for this session on the user's client.
3377 *
3378 * @param WebRequest|null $request WebRequest object to use; $wgRequest will be used if null
3379 * is passed.
3380 * @param bool $secure Whether to force secure/insecure cookies or use default
3381 * @param bool $rememberMe Whether to add a Token cookie for elongated sessions
3382 */
3383 public function setCookies( $request = null, $secure = null, $rememberMe = false ) {
3384 if ( $request === null ) {
3385 $request = $this->getRequest();
3386 }
3387
3388 $this->load();
3389 if ( 0 == $this->mId ) {
3390 return;
3391 }
3392 if ( !$this->mToken ) {
3393 // When token is empty or NULL generate a new one and then save it to the database
3394 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3395 // Simply by setting every cell in the user_token column to NULL and letting them be
3396 // regenerated as users log back into the wiki.
3397 $this->setToken();
3398 $this->saveSettings();
3399 }
3400 $session = array(
3401 'wsUserID' => $this->mId,
3402 'wsToken' => $this->mToken,
3403 'wsUserName' => $this->getName()
3404 );
3405 $cookies = array(
3406 'UserID' => $this->mId,
3407 'UserName' => $this->getName(),
3408 );
3409 if ( $rememberMe ) {
3410 $cookies['Token'] = $this->mToken;
3411 } else {
3412 $cookies['Token'] = false;
3413 }
3414
3415 Hooks::run( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3416
3417 foreach ( $session as $name => $value ) {
3418 $request->setSessionData( $name, $value );
3419 }
3420 foreach ( $cookies as $name => $value ) {
3421 if ( $value === false ) {
3422 $this->clearCookie( $name );
3423 } else {
3424 $this->setCookie( $name, $value, 0, $secure );
3425 }
3426 }
3427
3428 /**
3429 * If wpStickHTTPS was selected, also set an insecure cookie that
3430 * will cause the site to redirect the user to HTTPS, if they access
3431 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3432 * as the one set by centralauth (bug 53538). Also set it to session, or
3433 * standard time setting, based on if rememberme was set.
3434 */
3435 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3436 $this->setCookie(
3437 'forceHTTPS',
3438 'true',
3439 $rememberMe ? 0 : null,
3440 false,
3441 array( 'prefix' => '' ) // no prefix
3442 );
3443 }
3444 }
3445
3446 /**
3447 * Log this user out.
3448 */
3449 public function logout() {
3450 if ( Hooks::run( 'UserLogout', array( &$this ) ) ) {
3451 $this->doLogout();
3452 }
3453 }
3454
3455 /**
3456 * Clear the user's cookies and session, and reset the instance cache.
3457 * @see logout()
3458 */
3459 public function doLogout() {
3460 $this->clearInstanceCache( 'defaults' );
3461
3462 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3463
3464 $this->clearCookie( 'UserID' );
3465 $this->clearCookie( 'Token' );
3466 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3467
3468 // Remember when user logged out, to prevent seeing cached pages
3469 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3470 }
3471
3472 /**
3473 * Save this user's settings into the database.
3474 * @todo Only rarely do all these fields need to be set!
3475 */
3476 public function saveSettings() {
3477 global $wgAuth;
3478
3479 $this->load();
3480 $this->loadPasswords();
3481 if ( wfReadOnly() ) {
3482 return;
3483 }
3484 if ( 0 == $this->mId ) {
3485 return;
3486 }
3487
3488 $this->mTouched = self::newTouchedTimestamp();
3489 if ( !$wgAuth->allowSetLocalPassword() ) {
3490 $this->mPassword = self::getPasswordFactory()->newFromCiphertext( null );
3491 }
3492
3493 $dbw = wfGetDB( DB_MASTER );
3494 $dbw->update( 'user',
3495 array( /* SET */
3496 'user_name' => $this->mName,
3497 'user_password' => $this->mPassword->toString(),
3498 'user_newpassword' => $this->mNewpassword->toString(),
3499 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3500 'user_real_name' => $this->mRealName,
3501 'user_email' => $this->mEmail,
3502 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3503 'user_touched' => $dbw->timestamp( $this->mTouched ),
3504 'user_token' => strval( $this->mToken ),
3505 'user_email_token' => $this->mEmailToken,
3506 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3507 'user_password_expires' => $dbw->timestampOrNull( $this->mPasswordExpires ),
3508 ), array( /* WHERE */
3509 'user_id' => $this->mId
3510 ), __METHOD__
3511 );
3512
3513 $this->saveOptions();
3514
3515 Hooks::run( 'UserSaveSettings', array( $this ) );
3516 $this->clearSharedCache();
3517 $this->getUserPage()->invalidateCache();
3518 }
3519
3520 /**
3521 * If only this user's username is known, and it exists, return the user ID.
3522 * @return int
3523 */
3524 public function idForName() {
3525 $s = trim( $this->getName() );
3526 if ( $s === '' ) {
3527 return 0;
3528 }
3529
3530 $dbr = wfGetDB( DB_SLAVE );
3531 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3532 if ( $id === false ) {
3533 $id = 0;
3534 }
3535 return $id;
3536 }
3537
3538 /**
3539 * Add a user to the database, return the user object
3540 *
3541 * @param string $name Username to add
3542 * @param array $params Array of Strings Non-default parameters to save to
3543 * the database as user_* fields:
3544 * - password: The user's password hash. Password logins will be disabled
3545 * if this is omitted.
3546 * - newpassword: Hash for a temporary password that has been mailed to
3547 * the user.
3548 * - email: The user's email address.
3549 * - email_authenticated: The email authentication timestamp.
3550 * - real_name: The user's real name.
3551 * - options: An associative array of non-default options.
3552 * - token: Random authentication token. Do not set.
3553 * - registration: Registration timestamp. Do not set.
3554 *
3555 * @return User|null User object, or null if the username already exists.
3556 */
3557 public static function createNew( $name, $params = array() ) {
3558 $user = new User;
3559 $user->load();
3560 $user->loadPasswords();
3561 $user->setToken(); // init token
3562 if ( isset( $params['options'] ) ) {
3563 $user->mOptions = $params['options'] + (array)$user->mOptions;
3564 unset( $params['options'] );
3565 }
3566 $dbw = wfGetDB( DB_MASTER );
3567 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3568
3569 $fields = array(
3570 'user_id' => $seqVal,
3571 'user_name' => $name,
3572 'user_password' => $user->mPassword->toString(),
3573 'user_newpassword' => $user->mNewpassword->toString(),
3574 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3575 'user_email' => $user->mEmail,
3576 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3577 'user_real_name' => $user->mRealName,
3578 'user_token' => strval( $user->mToken ),
3579 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3580 'user_editcount' => 0,
3581 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3582 );
3583 foreach ( $params as $name => $value ) {
3584 $fields["user_$name"] = $value;
3585 }
3586 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3587 if ( $dbw->affectedRows() ) {
3588 $newUser = User::newFromId( $dbw->insertId() );
3589 } else {
3590 $newUser = null;
3591 }
3592 return $newUser;
3593 }
3594
3595 /**
3596 * Add this existing user object to the database. If the user already
3597 * exists, a fatal status object is returned, and the user object is
3598 * initialised with the data from the database.
3599 *
3600 * Previously, this function generated a DB error due to a key conflict
3601 * if the user already existed. Many extension callers use this function
3602 * in code along the lines of:
3603 *
3604 * $user = User::newFromName( $name );
3605 * if ( !$user->isLoggedIn() ) {
3606 * $user->addToDatabase();
3607 * }
3608 * // do something with $user...
3609 *
3610 * However, this was vulnerable to a race condition (bug 16020). By
3611 * initialising the user object if the user exists, we aim to support this
3612 * calling sequence as far as possible.
3613 *
3614 * Note that if the user exists, this function will acquire a write lock,
3615 * so it is still advisable to make the call conditional on isLoggedIn(),
3616 * and to commit the transaction after calling.
3617 *
3618 * @throws MWException
3619 * @return Status
3620 */
3621 public function addToDatabase() {
3622 $this->load();
3623 $this->loadPasswords();
3624 if ( !$this->mToken ) {
3625 $this->setToken(); // init token
3626 }
3627
3628 $this->mTouched = self::newTouchedTimestamp();
3629
3630 $dbw = wfGetDB( DB_MASTER );
3631 $inWrite = $dbw->writesOrCallbacksPending();
3632 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3633 $dbw->insert( 'user',
3634 array(
3635 'user_id' => $seqVal,
3636 'user_name' => $this->mName,
3637 'user_password' => $this->mPassword->toString(),
3638 'user_newpassword' => $this->mNewpassword->toString(),
3639 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3640 'user_email' => $this->mEmail,
3641 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3642 'user_real_name' => $this->mRealName,
3643 'user_token' => strval( $this->mToken ),
3644 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3645 'user_editcount' => 0,
3646 'user_touched' => $dbw->timestamp( $this->mTouched ),
3647 ), __METHOD__,
3648 array( 'IGNORE' )
3649 );
3650 if ( !$dbw->affectedRows() ) {
3651 // The queries below cannot happen in the same REPEATABLE-READ snapshot.
3652 // Handle this by COMMIT, if possible, or by LOCK IN SHARE MODE otherwise.
3653 if ( $inWrite ) {
3654 // Can't commit due to pending writes that may need atomicity.
3655 // This may cause some lock contention unlike the case below.
3656 $options = array( 'LOCK IN SHARE MODE' );
3657 $flags = self::READ_LOCKING;
3658 } else {
3659 // Often, this case happens early in views before any writes when
3660 // using CentralAuth. It's should be OK to commit and break the snapshot.
3661 $dbw->commit( __METHOD__, 'flush' );
3662 $options = array();
3663 $flags = 0;
3664 }
3665 $this->mId = $dbw->selectField( 'user', 'user_id',
3666 array( 'user_name' => $this->mName ), __METHOD__, $options );
3667 $loaded = false;
3668 if ( $this->mId ) {
3669 if ( $this->loadFromDatabase( $flags ) ) {
3670 $loaded = true;
3671 }
3672 }
3673 if ( !$loaded ) {
3674 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3675 "to insert user '{$this->mName}' row, but it was not present in select!" );
3676 }
3677 return Status::newFatal( 'userexists' );
3678 }
3679 $this->mId = $dbw->insertId();
3680
3681 // Clear instance cache other than user table data, which is already accurate
3682 $this->clearInstanceCache();
3683
3684 $this->saveOptions();
3685 return Status::newGood();
3686 }
3687
3688 /**
3689 * If this user is logged-in and blocked,
3690 * block any IP address they've successfully logged in from.
3691 * @return bool A block was spread
3692 */
3693 public function spreadAnyEditBlock() {
3694 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3695 return $this->spreadBlock();
3696 }
3697 return false;
3698 }
3699
3700 /**
3701 * If this (non-anonymous) user is blocked,
3702 * block the IP address they've successfully logged in from.
3703 * @return bool A block was spread
3704 */
3705 protected function spreadBlock() {
3706 wfDebug( __METHOD__ . "()\n" );
3707 $this->load();
3708 if ( $this->mId == 0 ) {
3709 return false;
3710 }
3711
3712 $userblock = Block::newFromTarget( $this->getName() );
3713 if ( !$userblock ) {
3714 return false;
3715 }
3716
3717 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3718 }
3719
3720 /**
3721 * Get whether the user is explicitly blocked from account creation.
3722 * @return bool|Block
3723 */
3724 public function isBlockedFromCreateAccount() {
3725 $this->getBlockedStatus();
3726 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3727 return $this->mBlock;
3728 }
3729
3730 # bug 13611: if the IP address the user is trying to create an account from is
3731 # blocked with createaccount disabled, prevent new account creation there even
3732 # when the user is logged in
3733 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3734 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3735 }
3736 return $this->mBlockedFromCreateAccount instanceof Block
3737 && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3738 ? $this->mBlockedFromCreateAccount
3739 : false;
3740 }
3741
3742 /**
3743 * Get whether the user is blocked from using Special:Emailuser.
3744 * @return bool
3745 */
3746 public function isBlockedFromEmailuser() {
3747 $this->getBlockedStatus();
3748 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3749 }
3750
3751 /**
3752 * Get whether the user is allowed to create an account.
3753 * @return bool
3754 */
3755 public function isAllowedToCreateAccount() {
3756 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3757 }
3758
3759 /**
3760 * Get this user's personal page title.
3761 *
3762 * @return Title User's personal page title
3763 */
3764 public function getUserPage() {
3765 return Title::makeTitle( NS_USER, $this->getName() );
3766 }
3767
3768 /**
3769 * Get this user's talk page title.
3770 *
3771 * @return Title User's talk page title
3772 */
3773 public function getTalkPage() {
3774 $title = $this->getUserPage();
3775 return $title->getTalkPage();
3776 }
3777
3778 /**
3779 * Determine whether the user is a newbie. Newbies are either
3780 * anonymous IPs, or the most recently created accounts.
3781 * @return bool
3782 */
3783 public function isNewbie() {
3784 return !$this->isAllowed( 'autoconfirmed' );
3785 }
3786
3787 /**
3788 * Check to see if the given clear-text password is one of the accepted passwords
3789 * @param string $password User password
3790 * @return bool True if the given password is correct, otherwise False
3791 */
3792 public function checkPassword( $password ) {
3793 global $wgAuth, $wgLegacyEncoding;
3794
3795
3796 $this->loadPasswords();
3797
3798 // Certain authentication plugins do NOT want to save
3799 // domain passwords in a mysql database, so we should
3800 // check this (in case $wgAuth->strict() is false).
3801 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3802 return true;
3803 } elseif ( $wgAuth->strict() ) {
3804 // Auth plugin doesn't allow local authentication
3805 return false;
3806 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3807 // Auth plugin doesn't allow local authentication for this user name
3808 return false;
3809 }
3810
3811 if ( !$this->mPassword->equals( $password ) ) {
3812 if ( $wgLegacyEncoding ) {
3813 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3814 // Check for this with iconv
3815 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3816 if ( $cp1252Password === $password || !$this->mPassword->equals( $cp1252Password ) ) {
3817 return false;
3818 }
3819 } else {
3820 return false;
3821 }
3822 }
3823
3824 $passwordFactory = self::getPasswordFactory();
3825 if ( $passwordFactory->needsUpdate( $this->mPassword ) ) {
3826 $this->mPassword = $passwordFactory->newFromPlaintext( $password );
3827 $this->saveSettings();
3828 }
3829
3830 return true;
3831 }
3832
3833 /**
3834 * Check if the given clear-text password matches the temporary password
3835 * sent by e-mail for password reset operations.
3836 *
3837 * @param string $plaintext
3838 *
3839 * @return bool True if matches, false otherwise
3840 */
3841 public function checkTemporaryPassword( $plaintext ) {
3842 global $wgNewPasswordExpiry;
3843
3844 $this->load();
3845 $this->loadPasswords();
3846 if ( $this->mNewpassword->equals( $plaintext ) ) {
3847 if ( is_null( $this->mNewpassTime ) ) {
3848 return true;
3849 }
3850 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3851 return ( time() < $expiry );
3852 } else {
3853 return false;
3854 }
3855 }
3856
3857 /**
3858 * Alias for getEditToken.
3859 * @deprecated since 1.19, use getEditToken instead.
3860 *
3861 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3862 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3863 * @return string The new edit token
3864 */
3865 public function editToken( $salt = '', $request = null ) {
3866 wfDeprecated( __METHOD__, '1.19' );
3867 return $this->getEditToken( $salt, $request );
3868 }
3869
3870 /**
3871 * Internal implementation for self::getEditToken() and
3872 * self::matchEditToken().
3873 *
3874 * @param string|array $salt
3875 * @param WebRequest $request
3876 * @param string|int $timestamp
3877 * @return string
3878 */
3879 private function getEditTokenAtTimestamp( $salt, $request, $timestamp ) {
3880 if ( $this->isAnon() ) {
3881 return self::EDIT_TOKEN_SUFFIX;
3882 } else {
3883 $token = $request->getSessionData( 'wsEditToken' );
3884 if ( $token === null ) {
3885 $token = MWCryptRand::generateHex( 32 );
3886 $request->setSessionData( 'wsEditToken', $token );
3887 }
3888 if ( is_array( $salt ) ) {
3889 $salt = implode( '|', $salt );
3890 }
3891 return hash_hmac( 'md5', $timestamp . $salt, $token, false ) .
3892 dechex( $timestamp ) .
3893 self::EDIT_TOKEN_SUFFIX;
3894 }
3895 }
3896
3897 /**
3898 * Initialize (if necessary) and return a session token value
3899 * which can be used in edit forms to show that the user's
3900 * login credentials aren't being hijacked with a foreign form
3901 * submission.
3902 *
3903 * @since 1.19
3904 *
3905 * @param string|array $salt Array of Strings Optional function-specific data for hashing
3906 * @param WebRequest|null $request WebRequest object to use or null to use $wgRequest
3907 * @return string The new edit token
3908 */
3909 public function getEditToken( $salt = '', $request = null ) {
3910 return $this->getEditTokenAtTimestamp(
3911 $salt, $request ?: $this->getRequest(), wfTimestamp()
3912 );
3913 }
3914
3915 /**
3916 * Generate a looking random token for various uses.
3917 *
3918 * @return string The new random token
3919 * @deprecated since 1.20: Use MWCryptRand for secure purposes or
3920 * wfRandomString for pseudo-randomness.
3921 */
3922 public static function generateToken() {
3923 return MWCryptRand::generateHex( 32 );
3924 }
3925
3926 /**
3927 * Check given value against the token value stored in the session.
3928 * A match should confirm that the form was submitted from the
3929 * user's own login session, not a form submission from a third-party
3930 * site.
3931 *
3932 * @param string $val Input value to compare
3933 * @param string $salt Optional function-specific data for hashing
3934 * @param WebRequest|null $request Object to use or null to use $wgRequest
3935 * @param int $maxage Fail tokens older than this, in seconds
3936 * @return bool Whether the token matches
3937 */
3938 public function matchEditToken( $val, $salt = '', $request = null, $maxage = null ) {
3939 if ( $this->isAnon() ) {
3940 return $val === self::EDIT_TOKEN_SUFFIX;
3941 }
3942
3943 $suffixLen = strlen( self::EDIT_TOKEN_SUFFIX );
3944 if ( strlen( $val ) <= 32 + $suffixLen ) {
3945 return false;
3946 }
3947
3948 $timestamp = hexdec( substr( $val, 32, -$suffixLen ) );
3949 if ( $maxage !== null && $timestamp < wfTimestamp() - $maxage ) {
3950 // Expired token
3951 return false;
3952 }
3953
3954 $sessionToken = $this->getEditTokenAtTimestamp(
3955 $salt, $request ?: $this->getRequest(), $timestamp
3956 );
3957
3958 if ( $val != $sessionToken ) {
3959 wfDebug( "User::matchEditToken: broken session data\n" );
3960 }
3961
3962 return hash_equals( $sessionToken, $val );
3963 }
3964
3965 /**
3966 * Check given value against the token value stored in the session,
3967 * ignoring the suffix.
3968 *
3969 * @param string $val Input value to compare
3970 * @param string $salt Optional function-specific data for hashing
3971 * @param WebRequest|null $request Object to use or null to use $wgRequest
3972 * @param int $maxage Fail tokens older than this, in seconds
3973 * @return bool Whether the token matches
3974 */
3975 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null, $maxage = null ) {
3976 $val = substr( $val, 0, strspn( $val, '0123456789abcdef' ) ) . self::EDIT_TOKEN_SUFFIX;
3977 return $this->matchEditToken( $val, $salt, $request, $maxage );
3978 }
3979
3980 /**
3981 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3982 * mail to the user's given address.
3983 *
3984 * @param string $type Message to send, either "created", "changed" or "set"
3985 * @return Status
3986 */
3987 public function sendConfirmationMail( $type = 'created' ) {
3988 global $wgLang;
3989 $expiration = null; // gets passed-by-ref and defined in next line.
3990 $token = $this->confirmationToken( $expiration );
3991 $url = $this->confirmationTokenUrl( $token );
3992 $invalidateURL = $this->invalidationTokenUrl( $token );
3993 $this->saveSettings();
3994
3995 if ( $type == 'created' || $type === false ) {
3996 $message = 'confirmemail_body';
3997 } elseif ( $type === true ) {
3998 $message = 'confirmemail_body_changed';
3999 } else {
4000 // Messages: confirmemail_body_changed, confirmemail_body_set
4001 $message = 'confirmemail_body_' . $type;
4002 }
4003
4004 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
4005 wfMessage( $message,
4006 $this->getRequest()->getIP(),
4007 $this->getName(),
4008 $url,
4009 $wgLang->timeanddate( $expiration, false ),
4010 $invalidateURL,
4011 $wgLang->date( $expiration, false ),
4012 $wgLang->time( $expiration, false ) )->text() );
4013 }
4014
4015 /**
4016 * Send an e-mail to this user's account. Does not check for
4017 * confirmed status or validity.
4018 *
4019 * @param string $subject Message subject
4020 * @param string $body Message body
4021 * @param string $from Optional From address; if unspecified, default
4022 * $wgPasswordSender will be used.
4023 * @param string $replyto Reply-To address
4024 * @return Status
4025 */
4026 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
4027 if ( is_null( $from ) ) {
4028 global $wgPasswordSender;
4029 $sender = new MailAddress( $wgPasswordSender,
4030 wfMessage( 'emailsender' )->inContentLanguage()->text() );
4031 } else {
4032 $sender = MailAddress::newFromUser( $from );
4033 }
4034
4035 $to = MailAddress::newFromUser( $this );
4036 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
4037 }
4038
4039 /**
4040 * Generate, store, and return a new e-mail confirmation code.
4041 * A hash (unsalted, since it's used as a key) is stored.
4042 *
4043 * @note Call saveSettings() after calling this function to commit
4044 * this change to the database.
4045 *
4046 * @param string &$expiration Accepts the expiration time
4047 * @return string New token
4048 */
4049 protected function confirmationToken( &$expiration ) {
4050 global $wgUserEmailConfirmationTokenExpiry;
4051 $now = time();
4052 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
4053 $expiration = wfTimestamp( TS_MW, $expires );
4054 $this->load();
4055 $token = MWCryptRand::generateHex( 32 );
4056 $hash = md5( $token );
4057 $this->mEmailToken = $hash;
4058 $this->mEmailTokenExpires = $expiration;
4059 return $token;
4060 }
4061
4062 /**
4063 * Return a URL the user can use to confirm their email address.
4064 * @param string $token Accepts the email confirmation token
4065 * @return string New token URL
4066 */
4067 protected function confirmationTokenUrl( $token ) {
4068 return $this->getTokenUrl( 'ConfirmEmail', $token );
4069 }
4070
4071 /**
4072 * Return a URL the user can use to invalidate their email address.
4073 * @param string $token Accepts the email confirmation token
4074 * @return string New token URL
4075 */
4076 protected function invalidationTokenUrl( $token ) {
4077 return $this->getTokenUrl( 'InvalidateEmail', $token );
4078 }
4079
4080 /**
4081 * Internal function to format the e-mail validation/invalidation URLs.
4082 * This uses a quickie hack to use the
4083 * hardcoded English names of the Special: pages, for ASCII safety.
4084 *
4085 * @note Since these URLs get dropped directly into emails, using the
4086 * short English names avoids insanely long URL-encoded links, which
4087 * also sometimes can get corrupted in some browsers/mailers
4088 * (bug 6957 with Gmail and Internet Explorer).
4089 *
4090 * @param string $page Special page
4091 * @param string $token Token
4092 * @return string Formatted URL
4093 */
4094 protected function getTokenUrl( $page, $token ) {
4095 // Hack to bypass localization of 'Special:'
4096 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
4097 return $title->getCanonicalURL();
4098 }
4099
4100 /**
4101 * Mark the e-mail address confirmed.
4102 *
4103 * @note Call saveSettings() after calling this function to commit the change.
4104 *
4105 * @return bool
4106 */
4107 public function confirmEmail() {
4108 // Check if it's already confirmed, so we don't touch the database
4109 // and fire the ConfirmEmailComplete hook on redundant confirmations.
4110 if ( !$this->isEmailConfirmed() ) {
4111 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
4112 Hooks::run( 'ConfirmEmailComplete', array( $this ) );
4113 }
4114 return true;
4115 }
4116
4117 /**
4118 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
4119 * address if it was already confirmed.
4120 *
4121 * @note Call saveSettings() after calling this function to commit the change.
4122 * @return bool Returns true
4123 */
4124 public function invalidateEmail() {
4125 $this->load();
4126 $this->mEmailToken = null;
4127 $this->mEmailTokenExpires = null;
4128 $this->setEmailAuthenticationTimestamp( null );
4129 $this->mEmail = '';
4130 Hooks::run( 'InvalidateEmailComplete', array( $this ) );
4131 return true;
4132 }
4133
4134 /**
4135 * Set the e-mail authentication timestamp.
4136 * @param string $timestamp TS_MW timestamp
4137 */
4138 public function setEmailAuthenticationTimestamp( $timestamp ) {
4139 $this->load();
4140 $this->mEmailAuthenticated = $timestamp;
4141 Hooks::run( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
4142 }
4143
4144 /**
4145 * Is this user allowed to send e-mails within limits of current
4146 * site configuration?
4147 * @return bool
4148 */
4149 public function canSendEmail() {
4150 global $wgEnableEmail, $wgEnableUserEmail;
4151 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
4152 return false;
4153 }
4154 $canSend = $this->isEmailConfirmed();
4155 Hooks::run( 'UserCanSendEmail', array( &$this, &$canSend ) );
4156 return $canSend;
4157 }
4158
4159 /**
4160 * Is this user allowed to receive e-mails within limits of current
4161 * site configuration?
4162 * @return bool
4163 */
4164 public function canReceiveEmail() {
4165 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
4166 }
4167
4168 /**
4169 * Is this user's e-mail address valid-looking and confirmed within
4170 * limits of the current site configuration?
4171 *
4172 * @note If $wgEmailAuthentication is on, this may require the user to have
4173 * confirmed their address by returning a code or using a password
4174 * sent to the address from the wiki.
4175 *
4176 * @return bool
4177 */
4178 public function isEmailConfirmed() {
4179 global $wgEmailAuthentication;
4180 $this->load();
4181 $confirmed = true;
4182 if ( Hooks::run( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
4183 if ( $this->isAnon() ) {
4184 return false;
4185 }
4186 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
4187 return false;
4188 }
4189 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
4190 return false;
4191 }
4192 return true;
4193 } else {
4194 return $confirmed;
4195 }
4196 }
4197
4198 /**
4199 * Check whether there is an outstanding request for e-mail confirmation.
4200 * @return bool
4201 */
4202 public function isEmailConfirmationPending() {
4203 global $wgEmailAuthentication;
4204 return $wgEmailAuthentication &&
4205 !$this->isEmailConfirmed() &&
4206 $this->mEmailToken &&
4207 $this->mEmailTokenExpires > wfTimestamp();
4208 }
4209
4210 /**
4211 * Get the timestamp of account creation.
4212 *
4213 * @return string|bool|null Timestamp of account creation, false for
4214 * non-existent/anonymous user accounts, or null if existing account
4215 * but information is not in database.
4216 */
4217 public function getRegistration() {
4218 if ( $this->isAnon() ) {
4219 return false;
4220 }
4221 $this->load();
4222 return $this->mRegistration;
4223 }
4224
4225 /**
4226 * Get the timestamp of the first edit
4227 *
4228 * @return string|bool Timestamp of first edit, or false for
4229 * non-existent/anonymous user accounts.
4230 */
4231 public function getFirstEditTimestamp() {
4232 if ( $this->getId() == 0 ) {
4233 return false; // anons
4234 }
4235 $dbr = wfGetDB( DB_SLAVE );
4236 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4237 array( 'rev_user' => $this->getId() ),
4238 __METHOD__,
4239 array( 'ORDER BY' => 'rev_timestamp ASC' )
4240 );
4241 if ( !$time ) {
4242 return false; // no edits
4243 }
4244 return wfTimestamp( TS_MW, $time );
4245 }
4246
4247 /**
4248 * Get the permissions associated with a given list of groups
4249 *
4250 * @param array $groups Array of Strings List of internal group names
4251 * @return array Array of Strings List of permission key names for given groups combined
4252 */
4253 public static function getGroupPermissions( $groups ) {
4254 global $wgGroupPermissions, $wgRevokePermissions;
4255 $rights = array();
4256 // grant every granted permission first
4257 foreach ( $groups as $group ) {
4258 if ( isset( $wgGroupPermissions[$group] ) ) {
4259 $rights = array_merge( $rights,
4260 // array_filter removes empty items
4261 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4262 }
4263 }
4264 // now revoke the revoked permissions
4265 foreach ( $groups as $group ) {
4266 if ( isset( $wgRevokePermissions[$group] ) ) {
4267 $rights = array_diff( $rights,
4268 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4269 }
4270 }
4271 return array_unique( $rights );
4272 }
4273
4274 /**
4275 * Get all the groups who have a given permission
4276 *
4277 * @param string $role Role to check
4278 * @return array Array of Strings List of internal group names with the given permission
4279 */
4280 public static function getGroupsWithPermission( $role ) {
4281 global $wgGroupPermissions;
4282 $allowedGroups = array();
4283 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4284 if ( self::groupHasPermission( $group, $role ) ) {
4285 $allowedGroups[] = $group;
4286 }
4287 }
4288 return $allowedGroups;
4289 }
4290
4291 /**
4292 * Check, if the given group has the given permission
4293 *
4294 * If you're wanting to check whether all users have a permission, use
4295 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4296 * from anyone.
4297 *
4298 * @since 1.21
4299 * @param string $group Group to check
4300 * @param string $role Role to check
4301 * @return bool
4302 */
4303 public static function groupHasPermission( $group, $role ) {
4304 global $wgGroupPermissions, $wgRevokePermissions;
4305 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4306 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4307 }
4308
4309 /**
4310 * Check if all users have the given permission
4311 *
4312 * @since 1.22
4313 * @param string $right Right to check
4314 * @return bool
4315 */
4316 public static function isEveryoneAllowed( $right ) {
4317 global $wgGroupPermissions, $wgRevokePermissions;
4318 static $cache = array();
4319
4320 // Use the cached results, except in unit tests which rely on
4321 // being able change the permission mid-request
4322 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4323 return $cache[$right];
4324 }
4325
4326 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4327 $cache[$right] = false;
4328 return false;
4329 }
4330
4331 // If it's revoked anywhere, then everyone doesn't have it
4332 foreach ( $wgRevokePermissions as $rights ) {
4333 if ( isset( $rights[$right] ) && $rights[$right] ) {
4334 $cache[$right] = false;
4335 return false;
4336 }
4337 }
4338
4339 // Allow extensions (e.g. OAuth) to say false
4340 if ( !Hooks::run( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4341 $cache[$right] = false;
4342 return false;
4343 }
4344
4345 $cache[$right] = true;
4346 return true;
4347 }
4348
4349 /**
4350 * Get the localized descriptive name for a group, if it exists
4351 *
4352 * @param string $group Internal group name
4353 * @return string Localized descriptive group name
4354 */
4355 public static function getGroupName( $group ) {
4356 $msg = wfMessage( "group-$group" );
4357 return $msg->isBlank() ? $group : $msg->text();
4358 }
4359
4360 /**
4361 * Get the localized descriptive name for a member of a group, if it exists
4362 *
4363 * @param string $group Internal group name
4364 * @param string $username Username for gender (since 1.19)
4365 * @return string Localized name for group member
4366 */
4367 public static function getGroupMember( $group, $username = '#' ) {
4368 $msg = wfMessage( "group-$group-member", $username );
4369 return $msg->isBlank() ? $group : $msg->text();
4370 }
4371
4372 /**
4373 * Return the set of defined explicit groups.
4374 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4375 * are not included, as they are defined automatically, not in the database.
4376 * @return array Array of internal group names
4377 */
4378 public static function getAllGroups() {
4379 global $wgGroupPermissions, $wgRevokePermissions;
4380 return array_diff(
4381 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4382 self::getImplicitGroups()
4383 );
4384 }
4385
4386 /**
4387 * Get a list of all available permissions.
4388 * @return array Array of permission names
4389 */
4390 public static function getAllRights() {
4391 if ( self::$mAllRights === false ) {
4392 global $wgAvailableRights;
4393 if ( count( $wgAvailableRights ) ) {
4394 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4395 } else {
4396 self::$mAllRights = self::$mCoreRights;
4397 }
4398 Hooks::run( 'UserGetAllRights', array( &self::$mAllRights ) );
4399 }
4400 return self::$mAllRights;
4401 }
4402
4403 /**
4404 * Get a list of implicit groups
4405 * @return array Array of Strings Array of internal group names
4406 */
4407 public static function getImplicitGroups() {
4408 global $wgImplicitGroups;
4409
4410 $groups = $wgImplicitGroups;
4411 # Deprecated, use $wgImplicitGroups instead
4412 Hooks::run( 'UserGetImplicitGroups', array( &$groups ), '1.25' );
4413
4414 return $groups;
4415 }
4416
4417 /**
4418 * Get the title of a page describing a particular group
4419 *
4420 * @param string $group Internal group name
4421 * @return Title|bool Title of the page if it exists, false otherwise
4422 */
4423 public static function getGroupPage( $group ) {
4424 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4425 if ( $msg->exists() ) {
4426 $title = Title::newFromText( $msg->text() );
4427 if ( is_object( $title ) ) {
4428 return $title;
4429 }
4430 }
4431 return false;
4432 }
4433
4434 /**
4435 * Create a link to the group in HTML, if available;
4436 * else return the group name.
4437 *
4438 * @param string $group Internal name of the group
4439 * @param string $text The text of the link
4440 * @return string HTML link to the group
4441 */
4442 public static function makeGroupLinkHTML( $group, $text = '' ) {
4443 if ( $text == '' ) {
4444 $text = self::getGroupName( $group );
4445 }
4446 $title = self::getGroupPage( $group );
4447 if ( $title ) {
4448 return Linker::link( $title, htmlspecialchars( $text ) );
4449 } else {
4450 return htmlspecialchars( $text );
4451 }
4452 }
4453
4454 /**
4455 * Create a link to the group in Wikitext, if available;
4456 * else return the group name.
4457 *
4458 * @param string $group Internal name of the group
4459 * @param string $text The text of the link
4460 * @return string Wikilink to the group
4461 */
4462 public static function makeGroupLinkWiki( $group, $text = '' ) {
4463 if ( $text == '' ) {
4464 $text = self::getGroupName( $group );
4465 }
4466 $title = self::getGroupPage( $group );
4467 if ( $title ) {
4468 $page = $title->getFullText();
4469 return "[[$page|$text]]";
4470 } else {
4471 return $text;
4472 }
4473 }
4474
4475 /**
4476 * Returns an array of the groups that a particular group can add/remove.
4477 *
4478 * @param string $group The group to check for whether it can add/remove
4479 * @return array Array( 'add' => array( addablegroups ),
4480 * 'remove' => array( removablegroups ),
4481 * 'add-self' => array( addablegroups to self),
4482 * 'remove-self' => array( removable groups from self) )
4483 */
4484 public static function changeableByGroup( $group ) {
4485 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4486
4487 $groups = array(
4488 'add' => array(),
4489 'remove' => array(),
4490 'add-self' => array(),
4491 'remove-self' => array()
4492 );
4493
4494 if ( empty( $wgAddGroups[$group] ) ) {
4495 // Don't add anything to $groups
4496 } elseif ( $wgAddGroups[$group] === true ) {
4497 // You get everything
4498 $groups['add'] = self::getAllGroups();
4499 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4500 $groups['add'] = $wgAddGroups[$group];
4501 }
4502
4503 // Same thing for remove
4504 if ( empty( $wgRemoveGroups[$group] ) ) {
4505 // Do nothing
4506 } elseif ( $wgRemoveGroups[$group] === true ) {
4507 $groups['remove'] = self::getAllGroups();
4508 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4509 $groups['remove'] = $wgRemoveGroups[$group];
4510 }
4511
4512 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4513 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4514 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4515 if ( is_int( $key ) ) {
4516 $wgGroupsAddToSelf['user'][] = $value;
4517 }
4518 }
4519 }
4520
4521 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4522 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4523 if ( is_int( $key ) ) {
4524 $wgGroupsRemoveFromSelf['user'][] = $value;
4525 }
4526 }
4527 }
4528
4529 // Now figure out what groups the user can add to him/herself
4530 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4531 // Do nothing
4532 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4533 // No idea WHY this would be used, but it's there
4534 $groups['add-self'] = User::getAllGroups();
4535 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4536 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4537 }
4538
4539 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4540 // Do nothing
4541 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4542 $groups['remove-self'] = User::getAllGroups();
4543 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4544 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4545 }
4546
4547 return $groups;
4548 }
4549
4550 /**
4551 * Returns an array of groups that this user can add and remove
4552 * @return array Array( 'add' => array( addablegroups ),
4553 * 'remove' => array( removablegroups ),
4554 * 'add-self' => array( addablegroups to self),
4555 * 'remove-self' => array( removable groups from self) )
4556 */
4557 public function changeableGroups() {
4558 if ( $this->isAllowed( 'userrights' ) ) {
4559 // This group gives the right to modify everything (reverse-
4560 // compatibility with old "userrights lets you change
4561 // everything")
4562 // Using array_merge to make the groups reindexed
4563 $all = array_merge( User::getAllGroups() );
4564 return array(
4565 'add' => $all,
4566 'remove' => $all,
4567 'add-self' => array(),
4568 'remove-self' => array()
4569 );
4570 }
4571
4572 // Okay, it's not so simple, we will have to go through the arrays
4573 $groups = array(
4574 'add' => array(),
4575 'remove' => array(),
4576 'add-self' => array(),
4577 'remove-self' => array()
4578 );
4579 $addergroups = $this->getEffectiveGroups();
4580
4581 foreach ( $addergroups as $addergroup ) {
4582 $groups = array_merge_recursive(
4583 $groups, $this->changeableByGroup( $addergroup )
4584 );
4585 $groups['add'] = array_unique( $groups['add'] );
4586 $groups['remove'] = array_unique( $groups['remove'] );
4587 $groups['add-self'] = array_unique( $groups['add-self'] );
4588 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4589 }
4590 return $groups;
4591 }
4592
4593 /**
4594 * Increment the user's edit-count field.
4595 * Will have no effect for anonymous users.
4596 */
4597 public function incEditCount() {
4598 if ( !$this->isAnon() ) {
4599 $dbw = wfGetDB( DB_MASTER );
4600 $dbw->update(
4601 'user',
4602 array( 'user_editcount=user_editcount+1' ),
4603 array( 'user_id' => $this->getId() ),
4604 __METHOD__
4605 );
4606
4607 // Lazy initialization check...
4608 if ( $dbw->affectedRows() == 0 ) {
4609 // Now here's a goddamn hack...
4610 $dbr = wfGetDB( DB_SLAVE );
4611 if ( $dbr !== $dbw ) {
4612 // If we actually have a slave server, the count is
4613 // at least one behind because the current transaction
4614 // has not been committed and replicated.
4615 $this->initEditCount( 1 );
4616 } else {
4617 // But if DB_SLAVE is selecting the master, then the
4618 // count we just read includes the revision that was
4619 // just added in the working transaction.
4620 $this->initEditCount();
4621 }
4622 }
4623 }
4624 // edit count in user cache too
4625 $this->invalidateCache();
4626 }
4627
4628 /**
4629 * Initialize user_editcount from data out of the revision table
4630 *
4631 * @param int $add Edits to add to the count from the revision table
4632 * @return int Number of edits
4633 */
4634 protected function initEditCount( $add = 0 ) {
4635 // Pull from a slave to be less cruel to servers
4636 // Accuracy isn't the point anyway here
4637 $dbr = wfGetDB( DB_SLAVE );
4638 $count = (int)$dbr->selectField(
4639 'revision',
4640 'COUNT(rev_user)',
4641 array( 'rev_user' => $this->getId() ),
4642 __METHOD__
4643 );
4644 $count = $count + $add;
4645
4646 $dbw = wfGetDB( DB_MASTER );
4647 $dbw->update(
4648 'user',
4649 array( 'user_editcount' => $count ),
4650 array( 'user_id' => $this->getId() ),
4651 __METHOD__
4652 );
4653
4654 return $count;
4655 }
4656
4657 /**
4658 * Get the description of a given right
4659 *
4660 * @param string $right Right to query
4661 * @return string Localized description of the right
4662 */
4663 public static function getRightDescription( $right ) {
4664 $key = "right-$right";
4665 $msg = wfMessage( $key );
4666 return $msg->isBlank() ? $right : $msg->text();
4667 }
4668
4669 /**
4670 * Make a new-style password hash
4671 *
4672 * @param string $password Plain-text password
4673 * @param bool|string $salt Optional salt, may be random or the user ID.
4674 * If unspecified or false, will generate one automatically
4675 * @return string Password hash
4676 * @deprecated since 1.24, use Password class
4677 */
4678 public static function crypt( $password, $salt = false ) {
4679 wfDeprecated( __METHOD__, '1.24' );
4680 $hash = self::getPasswordFactory()->newFromPlaintext( $password );
4681 return $hash->toString();
4682 }
4683
4684 /**
4685 * Compare a password hash with a plain-text password. Requires the user
4686 * ID if there's a chance that the hash is an old-style hash.
4687 *
4688 * @param string $hash Password hash
4689 * @param string $password Plain-text password to compare
4690 * @param string|bool $userId User ID for old-style password salt
4691 *
4692 * @return bool
4693 * @deprecated since 1.24, use Password class
4694 */
4695 public static function comparePasswords( $hash, $password, $userId = false ) {
4696 wfDeprecated( __METHOD__, '1.24' );
4697
4698 // Check for *really* old password hashes that don't even have a type
4699 // The old hash format was just an md5 hex hash, with no type information
4700 if ( preg_match( '/^[0-9a-f]{32}$/', $hash ) ) {
4701 global $wgPasswordSalt;
4702 if ( $wgPasswordSalt ) {
4703 $password = ":B:{$userId}:{$hash}";
4704 } else {
4705 $password = ":A:{$hash}";
4706 }
4707 }
4708
4709 $hash = self::getPasswordFactory()->newFromCiphertext( $hash );
4710 return $hash->equals( $password );
4711 }
4712
4713 /**
4714 * Add a newuser log entry for this user.
4715 * Before 1.19 the return value was always true.
4716 *
4717 * @param string|bool $action Account creation type.
4718 * - String, one of the following values:
4719 * - 'create' for an anonymous user creating an account for himself.
4720 * This will force the action's performer to be the created user itself,
4721 * no matter the value of $wgUser
4722 * - 'create2' for a logged in user creating an account for someone else
4723 * - 'byemail' when the created user will receive its password by e-mail
4724 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4725 * - Boolean means whether the account was created by e-mail (deprecated):
4726 * - true will be converted to 'byemail'
4727 * - false will be converted to 'create' if this object is the same as
4728 * $wgUser and to 'create2' otherwise
4729 *
4730 * @param string $reason User supplied reason
4731 *
4732 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4733 */
4734 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4735 global $wgUser, $wgNewUserLog;
4736 if ( empty( $wgNewUserLog ) ) {
4737 return true; // disabled
4738 }
4739
4740 if ( $action === true ) {
4741 $action = 'byemail';
4742 } elseif ( $action === false ) {
4743 if ( $this->getName() == $wgUser->getName() ) {
4744 $action = 'create';
4745 } else {
4746 $action = 'create2';
4747 }
4748 }
4749
4750 if ( $action === 'create' || $action === 'autocreate' ) {
4751 $performer = $this;
4752 } else {
4753 $performer = $wgUser;
4754 }
4755
4756 $logEntry = new ManualLogEntry( 'newusers', $action );
4757 $logEntry->setPerformer( $performer );
4758 $logEntry->setTarget( $this->getUserPage() );
4759 $logEntry->setComment( $reason );
4760 $logEntry->setParameters( array(
4761 '4::userid' => $this->getId(),
4762 ) );
4763 $logid = $logEntry->insert();
4764
4765 if ( $action !== 'autocreate' ) {
4766 $logEntry->publish( $logid );
4767 }
4768
4769 return (int)$logid;
4770 }
4771
4772 /**
4773 * Add an autocreate newuser log entry for this user
4774 * Used by things like CentralAuth and perhaps other authplugins.
4775 * Consider calling addNewUserLogEntry() directly instead.
4776 *
4777 * @return bool
4778 */
4779 public function addNewUserLogEntryAutoCreate() {
4780 $this->addNewUserLogEntry( 'autocreate' );
4781
4782 return true;
4783 }
4784
4785 /**
4786 * Load the user options either from cache, the database or an array
4787 *
4788 * @param array $data Rows for the current user out of the user_properties table
4789 */
4790 protected function loadOptions( $data = null ) {
4791 global $wgContLang;
4792
4793 $this->load();
4794
4795 if ( $this->mOptionsLoaded ) {
4796 return;
4797 }
4798
4799 $this->mOptions = self::getDefaultOptions();
4800
4801 if ( !$this->getId() ) {
4802 // For unlogged-in users, load language/variant options from request.
4803 // There's no need to do it for logged-in users: they can set preferences,
4804 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4805 // so don't override user's choice (especially when the user chooses site default).
4806 $variant = $wgContLang->getDefaultVariant();
4807 $this->mOptions['variant'] = $variant;
4808 $this->mOptions['language'] = $variant;
4809 $this->mOptionsLoaded = true;
4810 return;
4811 }
4812
4813 // Maybe load from the object
4814 if ( !is_null( $this->mOptionOverrides ) ) {
4815 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4816 foreach ( $this->mOptionOverrides as $key => $value ) {
4817 $this->mOptions[$key] = $value;
4818 }
4819 } else {
4820 if ( !is_array( $data ) ) {
4821 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4822 // Load from database
4823 $dbr = wfGetDB( DB_SLAVE );
4824
4825 $res = $dbr->select(
4826 'user_properties',
4827 array( 'up_property', 'up_value' ),
4828 array( 'up_user' => $this->getId() ),
4829 __METHOD__
4830 );
4831
4832 $this->mOptionOverrides = array();
4833 $data = array();
4834 foreach ( $res as $row ) {
4835 $data[$row->up_property] = $row->up_value;
4836 }
4837 }
4838 foreach ( $data as $property => $value ) {
4839 $this->mOptionOverrides[$property] = $value;
4840 $this->mOptions[$property] = $value;
4841 }
4842 }
4843
4844 $this->mOptionsLoaded = true;
4845
4846 Hooks::run( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4847 }
4848
4849 /**
4850 * Saves the non-default options for this user, as previously set e.g. via
4851 * setOption(), in the database's "user_properties" (preferences) table.
4852 * Usually used via saveSettings().
4853 */
4854 protected function saveOptions() {
4855 $this->loadOptions();
4856
4857 // Not using getOptions(), to keep hidden preferences in database
4858 $saveOptions = $this->mOptions;
4859
4860 // Allow hooks to abort, for instance to save to a global profile.
4861 // Reset options to default state before saving.
4862 if ( !Hooks::run( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4863 return;
4864 }
4865
4866 $userId = $this->getId();
4867
4868 $insert_rows = array(); // all the new preference rows
4869 foreach ( $saveOptions as $key => $value ) {
4870 // Don't bother storing default values
4871 $defaultOption = self::getDefaultOption( $key );
4872 if ( ( $defaultOption === null && $value !== false && $value !== null )
4873 || $value != $defaultOption
4874 ) {
4875 $insert_rows[] = array(
4876 'up_user' => $userId,
4877 'up_property' => $key,
4878 'up_value' => $value,
4879 );
4880 }
4881 }
4882
4883 $dbw = wfGetDB( DB_MASTER );
4884
4885 $res = $dbw->select( 'user_properties',
4886 array( 'up_property', 'up_value' ), array( 'up_user' => $userId ), __METHOD__ );
4887
4888 // Find prior rows that need to be removed or updated. These rows will
4889 // all be deleted (the later so that INSERT IGNORE applies the new values).
4890 $keysDelete = array();
4891 foreach ( $res as $row ) {
4892 if ( !isset( $saveOptions[$row->up_property] )
4893 || strcmp( $saveOptions[$row->up_property], $row->up_value ) != 0
4894 ) {
4895 $keysDelete[] = $row->up_property;
4896 }
4897 }
4898
4899 if ( count( $keysDelete ) ) {
4900 // Do the DELETE by PRIMARY KEY for prior rows.
4901 // In the past a very large portion of calls to this function are for setting
4902 // 'rememberpassword' for new accounts (a preference that has since been removed).
4903 // Doing a blanket per-user DELETE for new accounts with no rows in the table
4904 // caused gap locks on [max user ID,+infinity) which caused high contention since
4905 // updates would pile up on each other as they are for higher (newer) user IDs.
4906 // It might not be necessary these days, but it shouldn't hurt either.
4907 $dbw->delete( 'user_properties',
4908 array( 'up_user' => $userId, 'up_property' => $keysDelete ), __METHOD__ );
4909 }
4910 // Insert the new preference rows
4911 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4912 }
4913
4914 /**
4915 * Lazily instantiate and return a factory object for making passwords
4916 *
4917 * @return PasswordFactory
4918 */
4919 public static function getPasswordFactory() {
4920 if ( self::$mPasswordFactory === null ) {
4921 self::$mPasswordFactory = new PasswordFactory();
4922 self::$mPasswordFactory->init( RequestContext::getMain()->getConfig() );
4923 }
4924
4925 return self::$mPasswordFactory;
4926 }
4927
4928 /**
4929 * Provide an array of HTML5 attributes to put on an input element
4930 * intended for the user to enter a new password. This may include
4931 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4932 *
4933 * Do *not* use this when asking the user to enter his current password!
4934 * Regardless of configuration, users may have invalid passwords for whatever
4935 * reason (e.g., they were set before requirements were tightened up).
4936 * Only use it when asking for a new password, like on account creation or
4937 * ResetPass.
4938 *
4939 * Obviously, you still need to do server-side checking.
4940 *
4941 * NOTE: A combination of bugs in various browsers means that this function
4942 * actually just returns array() unconditionally at the moment. May as
4943 * well keep it around for when the browser bugs get fixed, though.
4944 *
4945 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4946 *
4947 * @return array Array of HTML attributes suitable for feeding to
4948 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4949 * That will get confused by the boolean attribute syntax used.)
4950 */
4951 public static function passwordChangeInputAttribs() {
4952 global $wgMinimalPasswordLength;
4953
4954 if ( $wgMinimalPasswordLength == 0 ) {
4955 return array();
4956 }
4957
4958 # Note that the pattern requirement will always be satisfied if the
4959 # input is empty, so we need required in all cases.
4960 #
4961 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4962 # if e-mail confirmation is being used. Since HTML5 input validation
4963 # is b0rked anyway in some browsers, just return nothing. When it's
4964 # re-enabled, fix this code to not output required for e-mail
4965 # registration.
4966 #$ret = array( 'required' );
4967 $ret = array();
4968
4969 # We can't actually do this right now, because Opera 9.6 will print out
4970 # the entered password visibly in its error message! When other
4971 # browsers add support for this attribute, or Opera fixes its support,
4972 # we can add support with a version check to avoid doing this on Opera
4973 # versions where it will be a problem. Reported to Opera as
4974 # DSK-262266, but they don't have a public bug tracker for us to follow.
4975 /*
4976 if ( $wgMinimalPasswordLength > 1 ) {
4977 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4978 $ret['title'] = wfMessage( 'passwordtooshort' )
4979 ->numParams( $wgMinimalPasswordLength )->text();
4980 }
4981 */
4982
4983 return $ret;
4984 }
4985
4986 /**
4987 * Return the list of user fields that should be selected to create
4988 * a new user object.
4989 * @return array
4990 */
4991 public static function selectFields() {
4992 return array(
4993 'user_id',
4994 'user_name',
4995 'user_real_name',
4996 'user_email',
4997 'user_touched',
4998 'user_token',
4999 'user_email_authenticated',
5000 'user_email_token',
5001 'user_email_token_expires',
5002 'user_registration',
5003 'user_editcount',
5004 );
5005 }
5006
5007 /**
5008 * Factory function for fatal permission-denied errors
5009 *
5010 * @since 1.22
5011 * @param string $permission User right required
5012 * @return Status
5013 */
5014 static function newFatalPermissionDeniedStatus( $permission ) {
5015 global $wgLang;
5016
5017 $groups = array_map(
5018 array( 'User', 'makeGroupLinkWiki' ),
5019 User::getGroupsWithPermission( $permission )
5020 );
5021
5022 if ( $groups ) {
5023 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
5024 } else {
5025 return Status::newFatal( 'badaccess-group0' );
5026 }
5027 }
5028 }