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