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