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