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