Merge "libxml_disable_entity_loader() just in case..."
[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, $wgAuth;
1166
1167 $toPromote = array();
1168 if ( $this->getId() ) {
1169 $toPromote = Autopromote::getAutopromoteOnceGroups( $this, $event );
1170 if ( count( $toPromote ) ) {
1171 $oldGroups = $this->getGroups(); // previous groups
1172
1173 foreach ( $toPromote as $group ) {
1174 $this->addGroup( $group );
1175 }
1176 // update groups in external authentication database
1177 $wgAuth->updateExternalDBGroups( $this, $toPromote );
1178
1179 $newGroups = array_merge( $oldGroups, $toPromote ); // all groups
1180
1181 $logEntry = new ManualLogEntry( 'rights', 'autopromote' );
1182 $logEntry->setPerformer( $this );
1183 $logEntry->setTarget( $this->getUserPage() );
1184 $logEntry->setParameters( array(
1185 '4::oldgroups' => $oldGroups,
1186 '5::newgroups' => $newGroups,
1187 ) );
1188 $logid = $logEntry->insert();
1189 if ( $wgAutopromoteOnceLogInRC ) {
1190 $logEntry->publish( $logid );
1191 }
1192 }
1193 }
1194 return $toPromote;
1195 }
1196
1197 /**
1198 * Clear various cached data stored in this object. The cache of the user table
1199 * data (i.e. self::$mCacheVars) is not cleared unless $reloadFrom is given.
1200 *
1201 * @param bool|string $reloadFrom Reload user and user_groups table data from a
1202 * given source. May be "name", "id", "defaults", "session", or false for
1203 * no reload.
1204 */
1205 public function clearInstanceCache( $reloadFrom = false ) {
1206 $this->mNewtalk = -1;
1207 $this->mDatePreference = null;
1208 $this->mBlockedby = -1; # Unset
1209 $this->mHash = false;
1210 $this->mRights = null;
1211 $this->mEffectiveGroups = null;
1212 $this->mImplicitGroups = null;
1213 $this->mGroups = null;
1214 $this->mOptions = null;
1215 $this->mOptionsLoaded = false;
1216 $this->mEditCount = null;
1217
1218 if ( $reloadFrom ) {
1219 $this->mLoadedItems = array();
1220 $this->mFrom = $reloadFrom;
1221 }
1222 }
1223
1224 /**
1225 * Combine the language default options with any site-specific options
1226 * and add the default language variants.
1227 *
1228 * @return Array of String options
1229 */
1230 public static function getDefaultOptions() {
1231 global $wgNamespacesToBeSearchedDefault, $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1232
1233 static $defOpt = null;
1234 if ( !defined( 'MW_PHPUNIT_TEST' ) && $defOpt !== null ) {
1235 // Disabling this for the unit tests, as they rely on being able to change $wgContLang
1236 // mid-request and see that change reflected in the return value of this function.
1237 // Which is insane and would never happen during normal MW operation
1238 return $defOpt;
1239 }
1240
1241 $defOpt = $wgDefaultUserOptions;
1242 // Default language setting
1243 $defOpt['language'] = $wgContLang->getCode();
1244 foreach ( LanguageConverter::$languagesWithVariants as $langCode ) {
1245 $defOpt[$langCode == $wgContLang->getCode() ? 'variant' : "variant-$langCode"] = $langCode;
1246 }
1247 foreach ( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1248 $defOpt['searchNs' . $nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1249 }
1250 $defOpt['skin'] = $wgDefaultSkin;
1251
1252 wfRunHooks( 'UserGetDefaultOptions', array( &$defOpt ) );
1253
1254 return $defOpt;
1255 }
1256
1257 /**
1258 * Get a given default option value.
1259 *
1260 * @param string $opt Name of option to retrieve
1261 * @return string Default option value
1262 */
1263 public static function getDefaultOption( $opt ) {
1264 $defOpts = self::getDefaultOptions();
1265 if ( isset( $defOpts[$opt] ) ) {
1266 return $defOpts[$opt];
1267 } else {
1268 return null;
1269 }
1270 }
1271
1272 /**
1273 * Get blocking information
1274 * @param bool $bFromSlave Whether to check the slave database first. To
1275 * improve performance, non-critical checks are done
1276 * against slaves. Check when actually saving should be
1277 * done against master.
1278 */
1279 private function getBlockedStatus( $bFromSlave = true ) {
1280 global $wgProxyWhitelist, $wgUser, $wgApplyIpBlocksToXff;
1281
1282 if ( -1 != $this->mBlockedby ) {
1283 return;
1284 }
1285
1286 wfProfileIn( __METHOD__ );
1287 wfDebug( __METHOD__ . ": checking...\n" );
1288
1289 // Initialize data...
1290 // Otherwise something ends up stomping on $this->mBlockedby when
1291 // things get lazy-loaded later, causing false positive block hits
1292 // due to -1 !== 0. Probably session-related... Nothing should be
1293 // overwriting mBlockedby, surely?
1294 $this->load();
1295
1296 # We only need to worry about passing the IP address to the Block generator if the
1297 # user is not immune to autoblocks/hardblocks, and they are the current user so we
1298 # know which IP address they're actually coming from
1299 if ( !$this->isAllowed( 'ipblock-exempt' ) && $this->getID() == $wgUser->getID() ) {
1300 $ip = $this->getRequest()->getIP();
1301 } else {
1302 $ip = null;
1303 }
1304
1305 // User/IP blocking
1306 $block = Block::newFromTarget( $this, $ip, !$bFromSlave );
1307
1308 // Proxy blocking
1309 if ( !$block instanceof Block && $ip !== null && !$this->isAllowed( 'proxyunbannable' )
1310 && !in_array( $ip, $wgProxyWhitelist ) )
1311 {
1312 // Local list
1313 if ( self::isLocallyBlockedProxy( $ip ) ) {
1314 $block = new Block;
1315 $block->setBlocker( wfMessage( 'proxyblocker' )->text() );
1316 $block->mReason = wfMessage( 'proxyblockreason' )->text();
1317 $block->setTarget( $ip );
1318 } elseif ( $this->isAnon() && $this->isDnsBlacklisted( $ip ) ) {
1319 $block = new Block;
1320 $block->setBlocker( wfMessage( 'sorbs' )->text() );
1321 $block->mReason = wfMessage( 'sorbsreason' )->text();
1322 $block->setTarget( $ip );
1323 }
1324 }
1325
1326 // (bug 23343) Apply IP blocks to the contents of XFF headers, if enabled
1327 if ( !$block instanceof Block
1328 && $wgApplyIpBlocksToXff
1329 && $ip !== null
1330 && !$this->isAllowed( 'proxyunbannable' )
1331 && !in_array( $ip, $wgProxyWhitelist )
1332 ) {
1333 $xff = $this->getRequest()->getHeader( 'X-Forwarded-For' );
1334 $xff = array_map( 'trim', explode( ',', $xff ) );
1335 $xff = array_diff( $xff, array( $ip ) );
1336 $xffblocks = Block::getBlocksForIPList( $xff, $this->isAnon(), !$bFromSlave );
1337 $block = Block::chooseBlock( $xffblocks, $xff );
1338 if ( $block instanceof Block ) {
1339 # Mangle the reason to alert the user that the block
1340 # originated from matching the X-Forwarded-For header.
1341 $block->mReason = wfMessage( 'xffblockreason', $block->mReason )->text();
1342 }
1343 }
1344
1345 if ( $block instanceof Block ) {
1346 wfDebug( __METHOD__ . ": Found block.\n" );
1347 $this->mBlock = $block;
1348 $this->mBlockedby = $block->getByName();
1349 $this->mBlockreason = $block->mReason;
1350 $this->mHideName = $block->mHideName;
1351 $this->mAllowUsertalk = !$block->prevents( 'editownusertalk' );
1352 } else {
1353 $this->mBlockedby = '';
1354 $this->mHideName = 0;
1355 $this->mAllowUsertalk = false;
1356 }
1357
1358 // Extensions
1359 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1360
1361 wfProfileOut( __METHOD__ );
1362 }
1363
1364 /**
1365 * Whether the given IP is in a DNS blacklist.
1366 *
1367 * @param string $ip IP to check
1368 * @param bool $checkWhitelist whether to check the whitelist first
1369 * @return bool True if blacklisted.
1370 */
1371 public function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1372 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1373 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1374
1375 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs ) {
1376 return false;
1377 }
1378
1379 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) ) {
1380 return false;
1381 }
1382
1383 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1384 return $this->inDnsBlacklist( $ip, $urls );
1385 }
1386
1387 /**
1388 * Whether the given IP is in a given DNS blacklist.
1389 *
1390 * @param string $ip IP to check
1391 * @param string|array $bases of Strings: URL of the DNS blacklist
1392 * @return bool True if blacklisted.
1393 */
1394 public function inDnsBlacklist( $ip, $bases ) {
1395 wfProfileIn( __METHOD__ );
1396
1397 $found = false;
1398 // @todo FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1399 if ( IP::isIPv4( $ip ) ) {
1400 // Reverse IP, bug 21255
1401 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1402
1403 foreach ( (array)$bases as $base ) {
1404 // Make hostname
1405 // If we have an access key, use that too (ProjectHoneypot, etc.)
1406 if ( is_array( $base ) ) {
1407 if ( count( $base ) >= 2 ) {
1408 // Access key is 1, base URL is 0
1409 $host = "{$base[1]}.$ipReversed.{$base[0]}";
1410 } else {
1411 $host = "$ipReversed.{$base[0]}";
1412 }
1413 } else {
1414 $host = "$ipReversed.$base";
1415 }
1416
1417 // Send query
1418 $ipList = gethostbynamel( $host );
1419
1420 if ( $ipList ) {
1421 wfDebugLog( 'dnsblacklist', "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1422 $found = true;
1423 break;
1424 } else {
1425 wfDebugLog( 'dnsblacklist', "Requested $host, not found in $base.\n" );
1426 }
1427 }
1428 }
1429
1430 wfProfileOut( __METHOD__ );
1431 return $found;
1432 }
1433
1434 /**
1435 * Check if an IP address is in the local proxy list
1436 *
1437 * @param $ip string
1438 *
1439 * @return bool
1440 */
1441 public static function isLocallyBlockedProxy( $ip ) {
1442 global $wgProxyList;
1443
1444 if ( !$wgProxyList ) {
1445 return false;
1446 }
1447 wfProfileIn( __METHOD__ );
1448
1449 if ( !is_array( $wgProxyList ) ) {
1450 // Load from the specified file
1451 $wgProxyList = array_map( 'trim', file( $wgProxyList ) );
1452 }
1453
1454 if ( !is_array( $wgProxyList ) ) {
1455 $ret = false;
1456 } elseif ( array_search( $ip, $wgProxyList ) !== false ) {
1457 $ret = true;
1458 } elseif ( array_key_exists( $ip, $wgProxyList ) ) {
1459 // Old-style flipped proxy list
1460 $ret = true;
1461 } else {
1462 $ret = false;
1463 }
1464 wfProfileOut( __METHOD__ );
1465 return $ret;
1466 }
1467
1468 /**
1469 * Is this user subject to rate limiting?
1470 *
1471 * @return bool True if rate limited
1472 */
1473 public function isPingLimitable() {
1474 global $wgRateLimitsExcludedIPs;
1475 if ( in_array( $this->getRequest()->getIP(), $wgRateLimitsExcludedIPs ) ) {
1476 // No other good way currently to disable rate limits
1477 // for specific IPs. :P
1478 // But this is a crappy hack and should die.
1479 return false;
1480 }
1481 return !$this->isAllowed( 'noratelimit' );
1482 }
1483
1484 /**
1485 * Primitive rate limits: enforce maximum actions per time period
1486 * to put a brake on flooding.
1487 *
1488 * @note When using a shared cache like memcached, IP-address
1489 * last-hit counters will be shared across wikis.
1490 *
1491 * @param string $action Action to enforce; 'edit' if unspecified
1492 * @return bool True if a rate limiter was tripped
1493 */
1494 public function pingLimiter( $action = 'edit' ) {
1495 // Call the 'PingLimiter' hook
1496 $result = false;
1497 if ( !wfRunHooks( 'PingLimiter', array( &$this, $action, &$result ) ) ) {
1498 return $result;
1499 }
1500
1501 global $wgRateLimits;
1502 if ( !isset( $wgRateLimits[$action] ) ) {
1503 return false;
1504 }
1505
1506 // Some groups shouldn't trigger the ping limiter, ever
1507 if ( !$this->isPingLimitable() ) {
1508 return false;
1509 }
1510
1511 global $wgMemc, $wgRateLimitLog;
1512 wfProfileIn( __METHOD__ );
1513
1514 $limits = $wgRateLimits[$action];
1515 $keys = array();
1516 $id = $this->getId();
1517 $userLimit = false;
1518
1519 if ( isset( $limits['anon'] ) && $id == 0 ) {
1520 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1521 }
1522
1523 if ( isset( $limits['user'] ) && $id != 0 ) {
1524 $userLimit = $limits['user'];
1525 }
1526 if ( $this->isNewbie() ) {
1527 if ( isset( $limits['newbie'] ) && $id != 0 ) {
1528 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1529 }
1530 if ( isset( $limits['ip'] ) ) {
1531 $ip = $this->getRequest()->getIP();
1532 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1533 }
1534 if ( isset( $limits['subnet'] ) ) {
1535 $ip = $this->getRequest()->getIP();
1536 $matches = array();
1537 $subnet = false;
1538 if ( IP::isIPv6( $ip ) ) {
1539 $parts = IP::parseRange( "$ip/64" );
1540 $subnet = $parts[0];
1541 } elseif ( preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1542 // IPv4
1543 $subnet = $matches[1];
1544 }
1545 if ( $subnet !== false ) {
1546 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1547 }
1548 }
1549 }
1550 // Check for group-specific permissions
1551 // If more than one group applies, use the group with the highest limit
1552 foreach ( $this->getGroups() as $group ) {
1553 if ( isset( $limits[$group] ) ) {
1554 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1555 $userLimit = $limits[$group];
1556 }
1557 }
1558 }
1559 // Set the user limit key
1560 if ( $userLimit !== false ) {
1561 list( $max, $period ) = $userLimit;
1562 wfDebug( __METHOD__ . ": effective user limit: $max in {$period}s\n" );
1563 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $userLimit;
1564 }
1565
1566 $triggered = false;
1567 foreach ( $keys as $key => $limit ) {
1568 list( $max, $period ) = $limit;
1569 $summary = "(limit $max in {$period}s)";
1570 $count = $wgMemc->get( $key );
1571 // Already pinged?
1572 if ( $count ) {
1573 if ( $count >= $max ) {
1574 wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" );
1575 if ( $wgRateLimitLog ) {
1576 wfSuppressWarnings();
1577 file_put_contents( $wgRateLimitLog, wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", FILE_APPEND );
1578 wfRestoreWarnings();
1579 }
1580 $triggered = true;
1581 } else {
1582 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1583 }
1584 } else {
1585 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1586 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1587 }
1588 $wgMemc->incr( $key );
1589 }
1590
1591 wfProfileOut( __METHOD__ );
1592 return $triggered;
1593 }
1594
1595 /**
1596 * Check if user is blocked
1597 *
1598 * @param bool $bFromSlave Whether to check the slave database instead of the master
1599 * @return bool True if blocked, false otherwise
1600 */
1601 public function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1602 return $this->getBlock( $bFromSlave ) instanceof Block && $this->getBlock()->prevents( 'edit' );
1603 }
1604
1605 /**
1606 * Get the block affecting the user, or null if the user is not blocked
1607 *
1608 * @param bool $bFromSlave Whether to check the slave database instead of the master
1609 * @return Block|null
1610 */
1611 public function getBlock( $bFromSlave = true ) {
1612 $this->getBlockedStatus( $bFromSlave );
1613 return $this->mBlock instanceof Block ? $this->mBlock : null;
1614 }
1615
1616 /**
1617 * Check if user is blocked from editing a particular article
1618 *
1619 * @param Title $title Title to check
1620 * @param bool $bFromSlave whether to check the slave database instead of the master
1621 * @return bool
1622 */
1623 function isBlockedFrom( $title, $bFromSlave = false ) {
1624 global $wgBlockAllowsUTEdit;
1625 wfProfileIn( __METHOD__ );
1626
1627 $blocked = $this->isBlocked( $bFromSlave );
1628 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1629 // If a user's name is suppressed, they cannot make edits anywhere
1630 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
1631 $title->getNamespace() == NS_USER_TALK ) {
1632 $blocked = false;
1633 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1634 }
1635
1636 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1637
1638 wfProfileOut( __METHOD__ );
1639 return $blocked;
1640 }
1641
1642 /**
1643 * If user is blocked, return the name of the user who placed the block
1644 * @return string Name of blocker
1645 */
1646 public function blockedBy() {
1647 $this->getBlockedStatus();
1648 return $this->mBlockedby;
1649 }
1650
1651 /**
1652 * If user is blocked, return the specified reason for the block
1653 * @return string Blocking reason
1654 */
1655 public function blockedFor() {
1656 $this->getBlockedStatus();
1657 return $this->mBlockreason;
1658 }
1659
1660 /**
1661 * If user is blocked, return the ID for the block
1662 * @return int Block ID
1663 */
1664 public function getBlockId() {
1665 $this->getBlockedStatus();
1666 return ( $this->mBlock ? $this->mBlock->getId() : false );
1667 }
1668
1669 /**
1670 * Check if user is blocked on all wikis.
1671 * Do not use for actual edit permission checks!
1672 * This is intended for quick UI checks.
1673 *
1674 * @param string $ip IP address, uses current client if none given
1675 * @return bool True if blocked, false otherwise
1676 */
1677 public function isBlockedGlobally( $ip = '' ) {
1678 if ( $this->mBlockedGlobally !== null ) {
1679 return $this->mBlockedGlobally;
1680 }
1681 // User is already an IP?
1682 if ( IP::isIPAddress( $this->getName() ) ) {
1683 $ip = $this->getName();
1684 } elseif ( !$ip ) {
1685 $ip = $this->getRequest()->getIP();
1686 }
1687 $blocked = false;
1688 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1689 $this->mBlockedGlobally = (bool)$blocked;
1690 return $this->mBlockedGlobally;
1691 }
1692
1693 /**
1694 * Check if user account is locked
1695 *
1696 * @return bool True if locked, false otherwise
1697 */
1698 public function isLocked() {
1699 if ( $this->mLocked !== null ) {
1700 return $this->mLocked;
1701 }
1702 global $wgAuth;
1703 StubObject::unstub( $wgAuth );
1704 $authUser = $wgAuth->getUserInstance( $this );
1705 $this->mLocked = (bool)$authUser->isLocked();
1706 return $this->mLocked;
1707 }
1708
1709 /**
1710 * Check if user account is hidden
1711 *
1712 * @return bool True if hidden, false otherwise
1713 */
1714 public function isHidden() {
1715 if ( $this->mHideName !== null ) {
1716 return $this->mHideName;
1717 }
1718 $this->getBlockedStatus();
1719 if ( !$this->mHideName ) {
1720 global $wgAuth;
1721 StubObject::unstub( $wgAuth );
1722 $authUser = $wgAuth->getUserInstance( $this );
1723 $this->mHideName = (bool)$authUser->isHidden();
1724 }
1725 return $this->mHideName;
1726 }
1727
1728 /**
1729 * Get the user's ID.
1730 * @return int The user's ID; 0 if the user is anonymous or nonexistent
1731 */
1732 public function getId() {
1733 if ( $this->mId === null && $this->mName !== null && User::isIP( $this->mName ) ) {
1734 // Special case, we know the user is anonymous
1735 return 0;
1736 } elseif ( !$this->isItemLoaded( 'id' ) ) {
1737 // Don't load if this was initialized from an ID
1738 $this->load();
1739 }
1740 return $this->mId;
1741 }
1742
1743 /**
1744 * Set the user and reload all fields according to a given ID
1745 * @param int $v User ID to reload
1746 */
1747 public function setId( $v ) {
1748 $this->mId = $v;
1749 $this->clearInstanceCache( 'id' );
1750 }
1751
1752 /**
1753 * Get the user name, or the IP of an anonymous user
1754 * @return string User's name or IP address
1755 */
1756 public function getName() {
1757 if ( $this->isItemLoaded( 'name', 'only' ) ) {
1758 // Special case optimisation
1759 return $this->mName;
1760 } else {
1761 $this->load();
1762 if ( $this->mName === false ) {
1763 // Clean up IPs
1764 $this->mName = IP::sanitizeIP( $this->getRequest()->getIP() );
1765 }
1766 return $this->mName;
1767 }
1768 }
1769
1770 /**
1771 * Set the user name.
1772 *
1773 * This does not reload fields from the database according to the given
1774 * name. Rather, it is used to create a temporary "nonexistent user" for
1775 * later addition to the database. It can also be used to set the IP
1776 * address for an anonymous user to something other than the current
1777 * remote IP.
1778 *
1779 * @note User::newFromName() has roughly the same function, when the named user
1780 * does not exist.
1781 * @param string $str New user name to set
1782 */
1783 public function setName( $str ) {
1784 $this->load();
1785 $this->mName = $str;
1786 }
1787
1788 /**
1789 * Get the user's name escaped by underscores.
1790 * @return string Username escaped by underscores.
1791 */
1792 public function getTitleKey() {
1793 return str_replace( ' ', '_', $this->getName() );
1794 }
1795
1796 /**
1797 * Check if the user has new messages.
1798 * @return bool True if the user has new messages
1799 */
1800 public function getNewtalk() {
1801 $this->load();
1802
1803 // Load the newtalk status if it is unloaded (mNewtalk=-1)
1804 if ( $this->mNewtalk === -1 ) {
1805 $this->mNewtalk = false; # reset talk page status
1806
1807 // Check memcached separately for anons, who have no
1808 // entire User object stored in there.
1809 if ( !$this->mId ) {
1810 global $wgDisableAnonTalk;
1811 if ( $wgDisableAnonTalk ) {
1812 // Anon newtalk disabled by configuration.
1813 $this->mNewtalk = false;
1814 } else {
1815 global $wgMemc;
1816 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1817 $newtalk = $wgMemc->get( $key );
1818 if ( strval( $newtalk ) !== '' ) {
1819 $this->mNewtalk = (bool)$newtalk;
1820 } else {
1821 // Since we are caching this, make sure it is up to date by getting it
1822 // from the master
1823 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1824 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1825 }
1826 }
1827 } else {
1828 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1829 }
1830 }
1831
1832 return (bool)$this->mNewtalk;
1833 }
1834
1835 /**
1836 * Return the data needed to construct links for new talk page message
1837 * alerts. If there are new messages, this will return an associative array
1838 * with the following data:
1839 * wiki: The database name of the wiki
1840 * link: Root-relative link to the user's talk page
1841 * rev: The last talk page revision that the user has seen or null. This
1842 * is useful for building diff links.
1843 * If there are no new messages, it returns an empty array.
1844 * @note This function was designed to accomodate multiple talk pages, but
1845 * currently only returns a single link and revision.
1846 * @return Array
1847 */
1848 public function getNewMessageLinks() {
1849 $talks = array();
1850 if ( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) ) {
1851 return $talks;
1852 } elseif ( !$this->getNewtalk() ) {
1853 return array();
1854 }
1855 $utp = $this->getTalkPage();
1856 $dbr = wfGetDB( DB_SLAVE );
1857 // Get the "last viewed rev" timestamp from the oldest message notification
1858 $timestamp = $dbr->selectField( 'user_newtalk',
1859 'MIN(user_last_timestamp)',
1860 $this->isAnon() ? array( 'user_ip' => $this->getName() ) : array( 'user_id' => $this->getID() ),
1861 __METHOD__ );
1862 $rev = $timestamp ? Revision::loadFromTimestamp( $dbr, $utp, $timestamp ) : null;
1863 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL(), 'rev' => $rev ) );
1864 }
1865
1866 /**
1867 * Get the revision ID for the last talk page revision viewed by the talk
1868 * page owner.
1869 * @return int|null Revision ID or null
1870 */
1871 public function getNewMessageRevisionId() {
1872 $newMessageRevisionId = null;
1873 $newMessageLinks = $this->getNewMessageLinks();
1874 if ( $newMessageLinks ) {
1875 // Note: getNewMessageLinks() never returns more than a single link
1876 // and it is always for the same wiki, but we double-check here in
1877 // case that changes some time in the future.
1878 if ( count( $newMessageLinks ) === 1
1879 && $newMessageLinks[0]['wiki'] === wfWikiID()
1880 && $newMessageLinks[0]['rev']
1881 ) {
1882 $newMessageRevision = $newMessageLinks[0]['rev'];
1883 $newMessageRevisionId = $newMessageRevision->getId();
1884 }
1885 }
1886 return $newMessageRevisionId;
1887 }
1888
1889 /**
1890 * Internal uncached check for new messages
1891 *
1892 * @see getNewtalk()
1893 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1894 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1895 * @param bool $fromMaster true to fetch from the master, false for a slave
1896 * @return bool True if the user has new messages
1897 */
1898 protected function checkNewtalk( $field, $id, $fromMaster = false ) {
1899 if ( $fromMaster ) {
1900 $db = wfGetDB( DB_MASTER );
1901 } else {
1902 $db = wfGetDB( DB_SLAVE );
1903 }
1904 $ok = $db->selectField( 'user_newtalk', $field,
1905 array( $field => $id ), __METHOD__ );
1906 return $ok !== false;
1907 }
1908
1909 /**
1910 * Add or update the new messages flag
1911 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1912 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1913 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null.
1914 * @return bool True if successful, false otherwise
1915 */
1916 protected function updateNewtalk( $field, $id, $curRev = null ) {
1917 // Get timestamp of the talk page revision prior to the current one
1918 $prevRev = $curRev ? $curRev->getPrevious() : false;
1919 $ts = $prevRev ? $prevRev->getTimestamp() : null;
1920 // Mark the user as having new messages since this revision
1921 $dbw = wfGetDB( DB_MASTER );
1922 $dbw->insert( 'user_newtalk',
1923 array( $field => $id, 'user_last_timestamp' => $dbw->timestampOrNull( $ts ) ),
1924 __METHOD__,
1925 'IGNORE' );
1926 if ( $dbw->affectedRows() ) {
1927 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
1928 return true;
1929 } else {
1930 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
1931 return false;
1932 }
1933 }
1934
1935 /**
1936 * Clear the new messages flag for the given user
1937 * @param string $field 'user_ip' for anonymous users, 'user_id' otherwise
1938 * @param string|int $id User's IP address for anonymous users, User ID otherwise
1939 * @return bool True if successful, false otherwise
1940 */
1941 protected function deleteNewtalk( $field, $id ) {
1942 $dbw = wfGetDB( DB_MASTER );
1943 $dbw->delete( 'user_newtalk',
1944 array( $field => $id ),
1945 __METHOD__ );
1946 if ( $dbw->affectedRows() ) {
1947 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
1948 return true;
1949 } else {
1950 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
1951 return false;
1952 }
1953 }
1954
1955 /**
1956 * Update the 'You have new messages!' status.
1957 * @param bool $val Whether the user has new messages
1958 * @param $curRev Revision new, as yet unseen revision of the user talk page. Ignored if null or !$val.
1959 */
1960 public function setNewtalk( $val, $curRev = null ) {
1961 if ( wfReadOnly() ) {
1962 return;
1963 }
1964
1965 $this->load();
1966 $this->mNewtalk = $val;
1967
1968 if ( $this->isAnon() ) {
1969 $field = 'user_ip';
1970 $id = $this->getName();
1971 } else {
1972 $field = 'user_id';
1973 $id = $this->getId();
1974 }
1975 global $wgMemc;
1976
1977 if ( $val ) {
1978 $changed = $this->updateNewtalk( $field, $id, $curRev );
1979 } else {
1980 $changed = $this->deleteNewtalk( $field, $id );
1981 }
1982
1983 if ( $this->isAnon() ) {
1984 // Anons have a separate memcached space, since
1985 // user records aren't kept for them.
1986 $key = wfMemcKey( 'newtalk', 'ip', $id );
1987 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1988 }
1989 if ( $changed ) {
1990 $this->invalidateCache();
1991 }
1992 }
1993
1994 /**
1995 * Generate a current or new-future timestamp to be stored in the
1996 * user_touched field when we update things.
1997 * @return string Timestamp in TS_MW format
1998 */
1999 private static function newTouchedTimestamp() {
2000 global $wgClockSkewFudge;
2001 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
2002 }
2003
2004 /**
2005 * Clear user data from memcached.
2006 * Use after applying fun updates to the database; caller's
2007 * responsibility to update user_touched if appropriate.
2008 *
2009 * Called implicitly from invalidateCache() and saveSettings().
2010 */
2011 private function clearSharedCache() {
2012 $this->load();
2013 if ( $this->mId ) {
2014 global $wgMemc;
2015 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
2016 }
2017 }
2018
2019 /**
2020 * Immediately touch the user data cache for this account.
2021 * Updates user_touched field, and removes account data from memcached
2022 * for reload on the next hit.
2023 */
2024 public function invalidateCache() {
2025 if ( wfReadOnly() ) {
2026 return;
2027 }
2028 $this->load();
2029 if ( $this->mId ) {
2030 $this->mTouched = self::newTouchedTimestamp();
2031
2032 $dbw = wfGetDB( DB_MASTER );
2033 $userid = $this->mId;
2034 $touched = $this->mTouched;
2035 $method = __METHOD__;
2036 $dbw->onTransactionIdle( function() use ( $dbw, $userid, $touched, $method ) {
2037 // Prevent contention slams by checking user_touched first
2038 $encTouched = $dbw->addQuotes( $dbw->timestamp( $touched ) );
2039 $needsPurge = $dbw->selectField( 'user', '1',
2040 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ) );
2041 if ( $needsPurge ) {
2042 $dbw->update( 'user',
2043 array( 'user_touched' => $dbw->timestamp( $touched ) ),
2044 array( 'user_id' => $userid, 'user_touched < ' . $encTouched ),
2045 $method
2046 );
2047 }
2048 } );
2049 $this->clearSharedCache();
2050 }
2051 }
2052
2053 /**
2054 * Validate the cache for this account.
2055 * @param string $timestamp A timestamp in TS_MW format
2056 * @return bool
2057 */
2058 public function validateCache( $timestamp ) {
2059 $this->load();
2060 return ( $timestamp >= $this->mTouched );
2061 }
2062
2063 /**
2064 * Get the user touched timestamp
2065 * @return string timestamp
2066 */
2067 public function getTouched() {
2068 $this->load();
2069 return $this->mTouched;
2070 }
2071
2072 /**
2073 * Set the password and reset the random token.
2074 * Calls through to authentication plugin if necessary;
2075 * will have no effect if the auth plugin refuses to
2076 * pass the change through or if the legal password
2077 * checks fail.
2078 *
2079 * As a special case, setting the password to null
2080 * wipes it, so the account cannot be logged in until
2081 * a new password is set, for instance via e-mail.
2082 *
2083 * @param string $str New password to set
2084 * @throws PasswordError on failure
2085 *
2086 * @return bool
2087 */
2088 public function setPassword( $str ) {
2089 global $wgAuth;
2090
2091 if ( $str !== null ) {
2092 if ( !$wgAuth->allowPasswordChange() ) {
2093 throw new PasswordError( wfMessage( 'password-change-forbidden' )->text() );
2094 }
2095
2096 if ( !$this->isValidPassword( $str ) ) {
2097 global $wgMinimalPasswordLength;
2098 $valid = $this->getPasswordValidity( $str );
2099 if ( is_array( $valid ) ) {
2100 $message = array_shift( $valid );
2101 $params = $valid;
2102 } else {
2103 $message = $valid;
2104 $params = array( $wgMinimalPasswordLength );
2105 }
2106 throw new PasswordError( wfMessage( $message, $params )->text() );
2107 }
2108 }
2109
2110 if ( !$wgAuth->setPassword( $this, $str ) ) {
2111 throw new PasswordError( wfMessage( 'externaldberror' )->text() );
2112 }
2113
2114 $this->setInternalPassword( $str );
2115
2116 return true;
2117 }
2118
2119 /**
2120 * Set the password and reset the random token unconditionally.
2121 *
2122 * @param string|null $str New password to set or null to set an invalid
2123 * password hash meaning that the user will not be able to log in
2124 * through the web interface.
2125 */
2126 public function setInternalPassword( $str ) {
2127 $this->load();
2128 $this->setToken();
2129
2130 if ( $str === null ) {
2131 // Save an invalid hash...
2132 $this->mPassword = '';
2133 } else {
2134 $this->mPassword = self::crypt( $str );
2135 }
2136 $this->mNewpassword = '';
2137 $this->mNewpassTime = null;
2138 }
2139
2140 /**
2141 * Get the user's current token.
2142 * @param bool $forceCreation Force the generation of a new token if the user doesn't have one (default=true for backwards compatibility)
2143 * @return string Token
2144 */
2145 public function getToken( $forceCreation = true ) {
2146 $this->load();
2147 if ( !$this->mToken && $forceCreation ) {
2148 $this->setToken();
2149 }
2150 return $this->mToken;
2151 }
2152
2153 /**
2154 * Set the random token (used for persistent authentication)
2155 * Called from loadDefaults() among other places.
2156 *
2157 * @param string|bool $token If specified, set the token to this value
2158 */
2159 public function setToken( $token = false ) {
2160 $this->load();
2161 if ( !$token ) {
2162 $this->mToken = MWCryptRand::generateHex( USER_TOKEN_LENGTH );
2163 } else {
2164 $this->mToken = $token;
2165 }
2166 }
2167
2168 /**
2169 * Set the password for a password reminder or new account email
2170 *
2171 * @param string $str New password to set
2172 * @param bool $throttle If true, reset the throttle timestamp to the present
2173 */
2174 public function setNewpassword( $str, $throttle = true ) {
2175 $this->load();
2176 $this->mNewpassword = self::crypt( $str );
2177 if ( $throttle ) {
2178 $this->mNewpassTime = wfTimestampNow();
2179 }
2180 }
2181
2182 /**
2183 * Has password reminder email been sent within the last
2184 * $wgPasswordReminderResendTime hours?
2185 * @return bool
2186 */
2187 public function isPasswordReminderThrottled() {
2188 global $wgPasswordReminderResendTime;
2189 $this->load();
2190 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
2191 return false;
2192 }
2193 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
2194 return time() < $expiry;
2195 }
2196
2197 /**
2198 * Get the user's e-mail address
2199 * @return string User's email address
2200 */
2201 public function getEmail() {
2202 $this->load();
2203 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
2204 return $this->mEmail;
2205 }
2206
2207 /**
2208 * Get the timestamp of the user's e-mail authentication
2209 * @return string TS_MW timestamp
2210 */
2211 public function getEmailAuthenticationTimestamp() {
2212 $this->load();
2213 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2214 return $this->mEmailAuthenticated;
2215 }
2216
2217 /**
2218 * Set the user's e-mail address
2219 * @param string $str New e-mail address
2220 */
2221 public function setEmail( $str ) {
2222 $this->load();
2223 if ( $str == $this->mEmail ) {
2224 return;
2225 }
2226 $this->mEmail = $str;
2227 $this->invalidateEmail();
2228 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
2229 }
2230
2231 /**
2232 * Set the user's e-mail address and a confirmation mail if needed.
2233 *
2234 * @since 1.20
2235 * @param string $str New e-mail address
2236 * @return Status
2237 */
2238 public function setEmailWithConfirmation( $str ) {
2239 global $wgEnableEmail, $wgEmailAuthentication;
2240
2241 if ( !$wgEnableEmail ) {
2242 return Status::newFatal( 'emaildisabled' );
2243 }
2244
2245 $oldaddr = $this->getEmail();
2246 if ( $str === $oldaddr ) {
2247 return Status::newGood( true );
2248 }
2249
2250 $this->setEmail( $str );
2251
2252 if ( $str !== '' && $wgEmailAuthentication ) {
2253 // Send a confirmation request to the new address if needed
2254 $type = $oldaddr != '' ? 'changed' : 'set';
2255 $result = $this->sendConfirmationMail( $type );
2256 if ( $result->isGood() ) {
2257 // Say the the caller that a confirmation mail has been sent
2258 $result->value = 'eauth';
2259 }
2260 } else {
2261 $result = Status::newGood( true );
2262 }
2263
2264 return $result;
2265 }
2266
2267 /**
2268 * Get the user's real name
2269 * @return string User's real name
2270 */
2271 public function getRealName() {
2272 if ( !$this->isItemLoaded( 'realname' ) ) {
2273 $this->load();
2274 }
2275
2276 return $this->mRealName;
2277 }
2278
2279 /**
2280 * Set the user's real name
2281 * @param string $str New real name
2282 */
2283 public function setRealName( $str ) {
2284 $this->load();
2285 $this->mRealName = $str;
2286 }
2287
2288 /**
2289 * Get the user's current setting for a given option.
2290 *
2291 * @param string $oname The option to check
2292 * @param string $defaultOverride A default value returned if the option does not exist
2293 * @param bool $ignoreHidden Whether to ignore the effects of $wgHiddenPrefs
2294 * @return string User's current value for the option
2295 * @see getBoolOption()
2296 * @see getIntOption()
2297 */
2298 public function getOption( $oname, $defaultOverride = null, $ignoreHidden = false ) {
2299 global $wgHiddenPrefs;
2300 $this->loadOptions();
2301
2302 # We want 'disabled' preferences to always behave as the default value for
2303 # users, even if they have set the option explicitly in their settings (ie they
2304 # set it, and then it was disabled removing their ability to change it). But
2305 # we don't want to erase the preferences in the database in case the preference
2306 # is re-enabled again. So don't touch $mOptions, just override the returned value
2307 if ( !$ignoreHidden && in_array( $oname, $wgHiddenPrefs ) ) {
2308 return self::getDefaultOption( $oname );
2309 }
2310
2311 if ( array_key_exists( $oname, $this->mOptions ) ) {
2312 return $this->mOptions[$oname];
2313 } else {
2314 return $defaultOverride;
2315 }
2316 }
2317
2318 /**
2319 * Get all user's options
2320 *
2321 * @return array
2322 */
2323 public function getOptions() {
2324 global $wgHiddenPrefs;
2325 $this->loadOptions();
2326 $options = $this->mOptions;
2327
2328 # We want 'disabled' preferences to always behave as the default value for
2329 # users, even if they have set the option explicitly in their settings (ie they
2330 # set it, and then it was disabled removing their ability to change it). But
2331 # we don't want to erase the preferences in the database in case the preference
2332 # is re-enabled again. So don't touch $mOptions, just override the returned value
2333 foreach ( $wgHiddenPrefs as $pref ) {
2334 $default = self::getDefaultOption( $pref );
2335 if ( $default !== null ) {
2336 $options[$pref] = $default;
2337 }
2338 }
2339
2340 return $options;
2341 }
2342
2343 /**
2344 * Get the user's current setting for a given option, as a boolean value.
2345 *
2346 * @param string $oname The option to check
2347 * @return bool User's current value for the option
2348 * @see getOption()
2349 */
2350 public function getBoolOption( $oname ) {
2351 return (bool)$this->getOption( $oname );
2352 }
2353
2354 /**
2355 * Get the user's current setting for a given option, as an integer value.
2356 *
2357 * @param string $oname The option to check
2358 * @param int $defaultOverride A default value returned if the option does not exist
2359 * @return int User's current value for the option
2360 * @see getOption()
2361 */
2362 public function getIntOption( $oname, $defaultOverride = 0 ) {
2363 $val = $this->getOption( $oname );
2364 if ( $val == '' ) {
2365 $val = $defaultOverride;
2366 }
2367 return intval( $val );
2368 }
2369
2370 /**
2371 * Set the given option for a user.
2372 *
2373 * @param string $oname The option to set
2374 * @param mixed $val New value to set
2375 */
2376 public function setOption( $oname, $val ) {
2377 $this->loadOptions();
2378
2379 // Explicitly NULL values should refer to defaults
2380 if ( is_null( $val ) ) {
2381 $val = self::getDefaultOption( $oname );
2382 }
2383
2384 $this->mOptions[$oname] = $val;
2385 }
2386
2387 /**
2388 * Get a token stored in the preferences (like the watchlist one),
2389 * resetting it if it's empty (and saving changes).
2390 *
2391 * @param string $oname The option name to retrieve the token from
2392 * @return string|bool User's current value for the option, or false if this option is disabled.
2393 * @see resetTokenFromOption()
2394 * @see getOption()
2395 */
2396 public function getTokenFromOption( $oname ) {
2397 global $wgHiddenPrefs;
2398 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2399 return false;
2400 }
2401
2402 $token = $this->getOption( $oname );
2403 if ( !$token ) {
2404 $token = $this->resetTokenFromOption( $oname );
2405 $this->saveSettings();
2406 }
2407 return $token;
2408 }
2409
2410 /**
2411 * Reset a token stored in the preferences (like the watchlist one).
2412 * *Does not* save user's preferences (similarly to setOption()).
2413 *
2414 * @param string $oname The option name to reset the token in
2415 * @return string|bool New token value, or false if this option is disabled.
2416 * @see getTokenFromOption()
2417 * @see setOption()
2418 */
2419 public function resetTokenFromOption( $oname ) {
2420 global $wgHiddenPrefs;
2421 if ( in_array( $oname, $wgHiddenPrefs ) ) {
2422 return false;
2423 }
2424
2425 $token = MWCryptRand::generateHex( 40 );
2426 $this->setOption( $oname, $token );
2427 return $token;
2428 }
2429
2430 /**
2431 * Return a list of the types of user options currently returned by
2432 * User::getOptionKinds().
2433 *
2434 * Currently, the option kinds are:
2435 * - 'registered' - preferences which are registered in core MediaWiki or
2436 * by extensions using the UserGetDefaultOptions hook.
2437 * - 'registered-multiselect' - as above, using the 'multiselect' type.
2438 * - 'registered-checkmatrix' - as above, using the 'checkmatrix' type.
2439 * - 'userjs' - preferences with names starting with 'userjs-', intended to
2440 * be used by user scripts.
2441 * - 'unused' - preferences about which MediaWiki doesn't know anything.
2442 * These are usually legacy options, removed in newer versions.
2443 *
2444 * The API (and possibly others) use this function to determine the possible
2445 * option types for validation purposes, so make sure to update this when a
2446 * new option kind is added.
2447 *
2448 * @see User::getOptionKinds
2449 * @return array Option kinds
2450 */
2451 public static function listOptionKinds() {
2452 return array(
2453 'registered',
2454 'registered-multiselect',
2455 'registered-checkmatrix',
2456 'userjs',
2457 'unused'
2458 );
2459 }
2460
2461 /**
2462 * Return an associative array mapping preferences keys to the kind of a preference they're
2463 * used for. Different kinds are handled differently when setting or reading preferences.
2464 *
2465 * See User::listOptionKinds for the list of valid option types that can be provided.
2466 *
2467 * @see User::listOptionKinds
2468 * @param $context IContextSource
2469 * @param array $options assoc. array with options keys to check as keys. Defaults to $this->mOptions.
2470 * @return array the key => kind mapping data
2471 */
2472 public function getOptionKinds( IContextSource $context, $options = null ) {
2473 $this->loadOptions();
2474 if ( $options === null ) {
2475 $options = $this->mOptions;
2476 }
2477
2478 $prefs = Preferences::getPreferences( $this, $context );
2479 $mapping = array();
2480
2481 // Multiselect and checkmatrix options are stored in the database with
2482 // one key per option, each having a boolean value. Extract those keys.
2483 $multiselectOptions = array();
2484 foreach ( $prefs as $name => $info ) {
2485 if ( ( isset( $info['type'] ) && $info['type'] == 'multiselect' ) ||
2486 ( isset( $info['class'] ) && $info['class'] == 'HTMLMultiSelectField' ) ) {
2487 $opts = HTMLFormField::flattenOptions( $info['options'] );
2488 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2489
2490 foreach ( $opts as $value ) {
2491 $multiselectOptions["$prefix$value"] = true;
2492 }
2493
2494 unset( $prefs[$name] );
2495 }
2496 }
2497 $checkmatrixOptions = array();
2498 foreach ( $prefs as $name => $info ) {
2499 if ( ( isset( $info['type'] ) && $info['type'] == 'checkmatrix' ) ||
2500 ( isset( $info['class'] ) && $info['class'] == 'HTMLCheckMatrix' ) ) {
2501 $columns = HTMLFormField::flattenOptions( $info['columns'] );
2502 $rows = HTMLFormField::flattenOptions( $info['rows'] );
2503 $prefix = isset( $info['prefix'] ) ? $info['prefix'] : $name;
2504
2505 foreach ( $columns as $column ) {
2506 foreach ( $rows as $row ) {
2507 $checkmatrixOptions["$prefix-$column-$row"] = true;
2508 }
2509 }
2510
2511 unset( $prefs[$name] );
2512 }
2513 }
2514
2515 // $value is ignored
2516 foreach ( $options as $key => $value ) {
2517 if ( isset( $prefs[$key] ) ) {
2518 $mapping[$key] = 'registered';
2519 } elseif ( isset( $multiselectOptions[$key] ) ) {
2520 $mapping[$key] = 'registered-multiselect';
2521 } elseif ( isset( $checkmatrixOptions[$key] ) ) {
2522 $mapping[$key] = 'registered-checkmatrix';
2523 } elseif ( substr( $key, 0, 7 ) === 'userjs-' ) {
2524 $mapping[$key] = 'userjs';
2525 } else {
2526 $mapping[$key] = 'unused';
2527 }
2528 }
2529
2530 return $mapping;
2531 }
2532
2533 /**
2534 * Reset certain (or all) options to the site defaults
2535 *
2536 * The optional parameter determines which kinds of preferences will be reset.
2537 * Supported values are everything that can be reported by getOptionKinds()
2538 * and 'all', which forces a reset of *all* preferences and overrides everything else.
2539 *
2540 * @param array|string $resetKinds which kinds of preferences to reset. Defaults to
2541 * array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' )
2542 * for backwards-compatibility.
2543 * @param $context IContextSource|null context source used when $resetKinds
2544 * does not contain 'all', passed to getOptionKinds().
2545 * Defaults to RequestContext::getMain() when null.
2546 */
2547 public function resetOptions(
2548 $resetKinds = array( 'registered', 'registered-multiselect', 'registered-checkmatrix', 'unused' ),
2549 IContextSource $context = null
2550 ) {
2551 $this->load();
2552 $defaultOptions = self::getDefaultOptions();
2553
2554 if ( !is_array( $resetKinds ) ) {
2555 $resetKinds = array( $resetKinds );
2556 }
2557
2558 if ( in_array( 'all', $resetKinds ) ) {
2559 $newOptions = $defaultOptions;
2560 } else {
2561 if ( $context === null ) {
2562 $context = RequestContext::getMain();
2563 }
2564
2565 $optionKinds = $this->getOptionKinds( $context );
2566 $resetKinds = array_intersect( $resetKinds, self::listOptionKinds() );
2567 $newOptions = array();
2568
2569 // Use default values for the options that should be deleted, and
2570 // copy old values for the ones that shouldn't.
2571 foreach ( $this->mOptions as $key => $value ) {
2572 if ( in_array( $optionKinds[$key], $resetKinds ) ) {
2573 if ( array_key_exists( $key, $defaultOptions ) ) {
2574 $newOptions[$key] = $defaultOptions[$key];
2575 }
2576 } else {
2577 $newOptions[$key] = $value;
2578 }
2579 }
2580 }
2581
2582 $this->mOptions = $newOptions;
2583 $this->mOptionsLoaded = true;
2584 }
2585
2586 /**
2587 * Get the user's preferred date format.
2588 * @return string User's preferred date format
2589 */
2590 public function getDatePreference() {
2591 // Important migration for old data rows
2592 if ( is_null( $this->mDatePreference ) ) {
2593 global $wgLang;
2594 $value = $this->getOption( 'date' );
2595 $map = $wgLang->getDatePreferenceMigrationMap();
2596 if ( isset( $map[$value] ) ) {
2597 $value = $map[$value];
2598 }
2599 $this->mDatePreference = $value;
2600 }
2601 return $this->mDatePreference;
2602 }
2603
2604 /**
2605 * Determine based on the wiki configuration and the user's options,
2606 * whether this user must be over HTTPS no matter what.
2607 *
2608 * @return bool
2609 */
2610 public function requiresHTTPS() {
2611 global $wgSecureLogin;
2612 if ( !$wgSecureLogin ) {
2613 return false;
2614 } else {
2615 $https = $this->getBoolOption( 'prefershttps' );
2616 wfRunHooks( 'UserRequiresHTTPS', array( $this, &$https ) );
2617 if ( $https ) {
2618 $https = wfCanIPUseHTTPS( $this->getRequest()->getIP() );
2619 }
2620 return $https;
2621 }
2622 }
2623
2624 /**
2625 * Get the user preferred stub threshold
2626 *
2627 * @return int
2628 */
2629 public function getStubThreshold() {
2630 global $wgMaxArticleSize; # Maximum article size, in Kb
2631 $threshold = $this->getIntOption( 'stubthreshold' );
2632 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2633 // If they have set an impossible value, disable the preference
2634 // so we can use the parser cache again.
2635 $threshold = 0;
2636 }
2637 return $threshold;
2638 }
2639
2640 /**
2641 * Get the permissions this user has.
2642 * @return Array of String permission names
2643 */
2644 public function getRights() {
2645 if ( is_null( $this->mRights ) ) {
2646 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2647 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2648 // Force reindexation of rights when a hook has unset one of them
2649 $this->mRights = array_values( array_unique( $this->mRights ) );
2650 }
2651 return $this->mRights;
2652 }
2653
2654 /**
2655 * Get the list of explicit group memberships this user has.
2656 * The implicit * and user groups are not included.
2657 * @return Array of String internal group names
2658 */
2659 public function getGroups() {
2660 $this->load();
2661 $this->loadGroups();
2662 return $this->mGroups;
2663 }
2664
2665 /**
2666 * Get the list of implicit group memberships this user has.
2667 * This includes all explicit groups, plus 'user' if logged in,
2668 * '*' for all accounts, and autopromoted groups
2669 * @param bool $recache Whether to avoid the cache
2670 * @return Array of String internal group names
2671 */
2672 public function getEffectiveGroups( $recache = false ) {
2673 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2674 wfProfileIn( __METHOD__ );
2675 $this->mEffectiveGroups = array_unique( array_merge(
2676 $this->getGroups(), // explicit groups
2677 $this->getAutomaticGroups( $recache ) // implicit groups
2678 ) );
2679 // Hook for additional groups
2680 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2681 // Force reindexation of groups when a hook has unset one of them
2682 $this->mEffectiveGroups = array_values( array_unique( $this->mEffectiveGroups ) );
2683 wfProfileOut( __METHOD__ );
2684 }
2685 return $this->mEffectiveGroups;
2686 }
2687
2688 /**
2689 * Get the list of implicit group memberships this user has.
2690 * This includes 'user' if logged in, '*' for all accounts,
2691 * and autopromoted groups
2692 * @param bool $recache Whether to avoid the cache
2693 * @return Array of String internal group names
2694 */
2695 public function getAutomaticGroups( $recache = false ) {
2696 if ( $recache || is_null( $this->mImplicitGroups ) ) {
2697 wfProfileIn( __METHOD__ );
2698 $this->mImplicitGroups = array( '*' );
2699 if ( $this->getId() ) {
2700 $this->mImplicitGroups[] = 'user';
2701
2702 $this->mImplicitGroups = array_unique( array_merge(
2703 $this->mImplicitGroups,
2704 Autopromote::getAutopromoteGroups( $this )
2705 ) );
2706 }
2707 if ( $recache ) {
2708 // Assure data consistency with rights/groups,
2709 // as getEffectiveGroups() depends on this function
2710 $this->mEffectiveGroups = null;
2711 }
2712 wfProfileOut( __METHOD__ );
2713 }
2714 return $this->mImplicitGroups;
2715 }
2716
2717 /**
2718 * Returns the groups the user has belonged to.
2719 *
2720 * The user may still belong to the returned groups. Compare with getGroups().
2721 *
2722 * The function will not return groups the user had belonged to before MW 1.17
2723 *
2724 * @return array Names of the groups the user has belonged to.
2725 */
2726 public function getFormerGroups() {
2727 if ( is_null( $this->mFormerGroups ) ) {
2728 $dbr = wfGetDB( DB_MASTER );
2729 $res = $dbr->select( 'user_former_groups',
2730 array( 'ufg_group' ),
2731 array( 'ufg_user' => $this->mId ),
2732 __METHOD__ );
2733 $this->mFormerGroups = array();
2734 foreach ( $res as $row ) {
2735 $this->mFormerGroups[] = $row->ufg_group;
2736 }
2737 }
2738 return $this->mFormerGroups;
2739 }
2740
2741 /**
2742 * Get the user's edit count.
2743 * @return int, null for anonymous users
2744 */
2745 public function getEditCount() {
2746 if ( !$this->getId() ) {
2747 return null;
2748 }
2749
2750 if ( !isset( $this->mEditCount ) ) {
2751 /* Populate the count, if it has not been populated yet */
2752 wfProfileIn( __METHOD__ );
2753 $dbr = wfGetDB( DB_SLAVE );
2754 // check if the user_editcount field has been initialized
2755 $count = $dbr->selectField(
2756 'user', 'user_editcount',
2757 array( 'user_id' => $this->mId ),
2758 __METHOD__
2759 );
2760
2761 if ( $count === null ) {
2762 // it has not been initialized. do so.
2763 $count = $this->initEditCount();
2764 }
2765 $this->mEditCount = $count;
2766 wfProfileOut( __METHOD__ );
2767 }
2768 return (int)$this->mEditCount;
2769 }
2770
2771 /**
2772 * Add the user to the given group.
2773 * This takes immediate effect.
2774 * @param string $group Name of the group to add
2775 */
2776 public function addGroup( $group ) {
2777 if ( wfRunHooks( 'UserAddGroup', array( $this, &$group ) ) ) {
2778 $dbw = wfGetDB( DB_MASTER );
2779 if ( $this->getId() ) {
2780 $dbw->insert( 'user_groups',
2781 array(
2782 'ug_user' => $this->getID(),
2783 'ug_group' => $group,
2784 ),
2785 __METHOD__,
2786 array( 'IGNORE' ) );
2787 }
2788 }
2789 $this->loadGroups();
2790 $this->mGroups[] = $group;
2791 // In case loadGroups was not called before, we now have the right twice.
2792 // Get rid of the duplicate.
2793 $this->mGroups = array_unique( $this->mGroups );
2794
2795 // Refresh the groups caches, and clear the rights cache so it will be
2796 // refreshed on the next call to $this->getRights().
2797 $this->getEffectiveGroups( true );
2798 $this->mRights = null;
2799
2800 $this->invalidateCache();
2801 }
2802
2803 /**
2804 * Remove the user from the given group.
2805 * This takes immediate effect.
2806 * @param string $group Name of the group to remove
2807 */
2808 public function removeGroup( $group ) {
2809 $this->load();
2810 if ( wfRunHooks( 'UserRemoveGroup', array( $this, &$group ) ) ) {
2811 $dbw = wfGetDB( DB_MASTER );
2812 $dbw->delete( 'user_groups',
2813 array(
2814 'ug_user' => $this->getID(),
2815 'ug_group' => $group,
2816 ), __METHOD__ );
2817 // Remember that the user was in this group
2818 $dbw->insert( 'user_former_groups',
2819 array(
2820 'ufg_user' => $this->getID(),
2821 'ufg_group' => $group,
2822 ),
2823 __METHOD__,
2824 array( 'IGNORE' ) );
2825 }
2826 $this->loadGroups();
2827 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2828
2829 // Refresh the groups caches, and clear the rights cache so it will be
2830 // refreshed on the next call to $this->getRights().
2831 $this->getEffectiveGroups( true );
2832 $this->mRights = null;
2833
2834 $this->invalidateCache();
2835 }
2836
2837 /**
2838 * Get whether the user is logged in
2839 * @return bool
2840 */
2841 public function isLoggedIn() {
2842 return $this->getID() != 0;
2843 }
2844
2845 /**
2846 * Get whether the user is anonymous
2847 * @return bool
2848 */
2849 public function isAnon() {
2850 return !$this->isLoggedIn();
2851 }
2852
2853 /**
2854 * Check if user is allowed to access a feature / make an action
2855 *
2856 * @internal param \String $varargs permissions to test
2857 * @return boolean: True if user is allowed to perform *any* of the given actions
2858 *
2859 * @return bool
2860 */
2861 public function isAllowedAny( /*...*/ ) {
2862 $permissions = func_get_args();
2863 foreach ( $permissions as $permission ) {
2864 if ( $this->isAllowed( $permission ) ) {
2865 return true;
2866 }
2867 }
2868 return false;
2869 }
2870
2871 /**
2872 *
2873 * @internal param $varargs string
2874 * @return bool True if the user is allowed to perform *all* of the given actions
2875 */
2876 public function isAllowedAll( /*...*/ ) {
2877 $permissions = func_get_args();
2878 foreach ( $permissions as $permission ) {
2879 if ( !$this->isAllowed( $permission ) ) {
2880 return false;
2881 }
2882 }
2883 return true;
2884 }
2885
2886 /**
2887 * Internal mechanics of testing a permission
2888 * @param string $action
2889 * @return bool
2890 */
2891 public function isAllowed( $action = '' ) {
2892 if ( $action === '' ) {
2893 return true; // In the spirit of DWIM
2894 }
2895 // Patrolling may not be enabled
2896 if ( $action === 'patrol' || $action === 'autopatrol' ) {
2897 global $wgUseRCPatrol, $wgUseNPPatrol;
2898 if ( !$wgUseRCPatrol && !$wgUseNPPatrol ) {
2899 return false;
2900 }
2901 }
2902 // Use strict parameter to avoid matching numeric 0 accidentally inserted
2903 // by misconfiguration: 0 == 'foo'
2904 return in_array( $action, $this->getRights(), true );
2905 }
2906
2907 /**
2908 * Check whether to enable recent changes patrol features for this user
2909 * @return boolean: True or false
2910 */
2911 public function useRCPatrol() {
2912 global $wgUseRCPatrol;
2913 return $wgUseRCPatrol && $this->isAllowedAny( 'patrol', 'patrolmarks' );
2914 }
2915
2916 /**
2917 * Check whether to enable new pages patrol features for this user
2918 * @return bool True or false
2919 */
2920 public function useNPPatrol() {
2921 global $wgUseRCPatrol, $wgUseNPPatrol;
2922 return (
2923 ( $wgUseRCPatrol || $wgUseNPPatrol )
2924 && ( $this->isAllowedAny( 'patrol', 'patrolmarks' ) )
2925 );
2926 }
2927
2928 /**
2929 * Get the WebRequest object to use with this object
2930 *
2931 * @return WebRequest
2932 */
2933 public function getRequest() {
2934 if ( $this->mRequest ) {
2935 return $this->mRequest;
2936 } else {
2937 global $wgRequest;
2938 return $wgRequest;
2939 }
2940 }
2941
2942 /**
2943 * Get the current skin, loading it if required
2944 * @return Skin The current skin
2945 * @todo FIXME: Need to check the old failback system [AV]
2946 * @deprecated since 1.18 Use ->getSkin() in the most relevant outputting context you have
2947 */
2948 public function getSkin() {
2949 wfDeprecated( __METHOD__, '1.18' );
2950 return RequestContext::getMain()->getSkin();
2951 }
2952
2953 /**
2954 * Get a WatchedItem for this user and $title.
2955 *
2956 * @since 1.22 $checkRights parameter added
2957 * @param $title Title
2958 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
2959 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
2960 * @return WatchedItem
2961 */
2962 public function getWatchedItem( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
2963 $key = $checkRights . ':' . $title->getNamespace() . ':' . $title->getDBkey();
2964
2965 if ( isset( $this->mWatchedItems[$key] ) ) {
2966 return $this->mWatchedItems[$key];
2967 }
2968
2969 if ( count( $this->mWatchedItems ) >= self::MAX_WATCHED_ITEMS_CACHE ) {
2970 $this->mWatchedItems = array();
2971 }
2972
2973 $this->mWatchedItems[$key] = WatchedItem::fromUserTitle( $this, $title, $checkRights );
2974 return $this->mWatchedItems[$key];
2975 }
2976
2977 /**
2978 * Check the watched status of an article.
2979 * @since 1.22 $checkRights parameter added
2980 * @param $title Title of the article to look at
2981 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
2982 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
2983 * @return bool
2984 */
2985 public function isWatched( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
2986 return $this->getWatchedItem( $title, $checkRights )->isWatched();
2987 }
2988
2989 /**
2990 * Watch an article.
2991 * @since 1.22 $checkRights parameter added
2992 * @param $title Title of the article to look at
2993 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
2994 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
2995 */
2996 public function addWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
2997 $this->getWatchedItem( $title, $checkRights )->addWatch();
2998 $this->invalidateCache();
2999 }
3000
3001 /**
3002 * Stop watching an article.
3003 * @since 1.22 $checkRights parameter added
3004 * @param $title Title of the article to look at
3005 * @param $checkRights int Whether to check 'viewmywatchlist'/'editmywatchlist' rights.
3006 * Pass WatchedItem::CHECK_USER_RIGHTS or WatchedItem::IGNORE_USER_RIGHTS.
3007 */
3008 public function removeWatch( $title, $checkRights = WatchedItem::CHECK_USER_RIGHTS ) {
3009 $this->getWatchedItem( $title, $checkRights )->removeWatch();
3010 $this->invalidateCache();
3011 }
3012
3013 /**
3014 * Clear the user's notification timestamp for the given title.
3015 * If e-notif e-mails are on, they will receive notification mails on
3016 * the next change of the page if it's watched etc.
3017 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3018 * @param $title Title of the article to look at
3019 */
3020 public function clearNotification( &$title ) {
3021 global $wgUseEnotif, $wgShowUpdatedMarker;
3022
3023 // Do nothing if the database is locked to writes
3024 if ( wfReadOnly() ) {
3025 return;
3026 }
3027
3028 // Do nothing if not allowed to edit the watchlist
3029 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3030 return;
3031 }
3032
3033 if ( $title->getNamespace() == NS_USER_TALK &&
3034 $title->getText() == $this->getName() ) {
3035 if ( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) ) {
3036 return;
3037 }
3038 $this->setNewtalk( false );
3039 }
3040
3041 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3042 return;
3043 }
3044
3045 if ( $this->isAnon() ) {
3046 // Nothing else to do...
3047 return;
3048 }
3049
3050 // Only update the timestamp if the page is being watched.
3051 // The query to find out if it is watched is cached both in memcached and per-invocation,
3052 // and when it does have to be executed, it can be on a slave
3053 // If this is the user's newtalk page, we always update the timestamp
3054 $force = '';
3055 if ( $title->getNamespace() == NS_USER_TALK &&
3056 $title->getText() == $this->getName() )
3057 {
3058 $force = 'force';
3059 }
3060
3061 $this->getWatchedItem( $title )->resetNotificationTimestamp( $force );
3062 }
3063
3064 /**
3065 * Resets all of the given user's page-change notification timestamps.
3066 * If e-notif e-mails are on, they will receive notification mails on
3067 * the next change of any watched page.
3068 * @note If the user doesn't have 'editmywatchlist', this will do nothing.
3069 */
3070 public function clearAllNotifications() {
3071 if ( wfReadOnly() ) {
3072 return;
3073 }
3074
3075 // Do nothing if not allowed to edit the watchlist
3076 if ( !$this->isAllowed( 'editmywatchlist' ) ) {
3077 return;
3078 }
3079
3080 global $wgUseEnotif, $wgShowUpdatedMarker;
3081 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
3082 $this->setNewtalk( false );
3083 return;
3084 }
3085 $id = $this->getId();
3086 if ( $id != 0 ) {
3087 $dbw = wfGetDB( DB_MASTER );
3088 $dbw->update( 'watchlist',
3089 array( /* SET */
3090 'wl_notificationtimestamp' => null
3091 ), array( /* WHERE */
3092 'wl_user' => $id
3093 ), __METHOD__
3094 );
3095 # We also need to clear here the "you have new message" notification for the own user_talk page
3096 # This is cleared one page view later in Article::viewUpdates();
3097 }
3098 }
3099
3100 /**
3101 * Set this user's options from an encoded string
3102 * @param string $str Encoded options to import
3103 *
3104 * @deprecated in 1.19 due to removal of user_options from the user table
3105 */
3106 private function decodeOptions( $str ) {
3107 wfDeprecated( __METHOD__, '1.19' );
3108 if ( !$str ) {
3109 return;
3110 }
3111
3112 $this->mOptionsLoaded = true;
3113 $this->mOptionOverrides = array();
3114
3115 // If an option is not set in $str, use the default value
3116 $this->mOptions = self::getDefaultOptions();
3117
3118 $a = explode( "\n", $str );
3119 foreach ( $a as $s ) {
3120 $m = array();
3121 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
3122 $this->mOptions[$m[1]] = $m[2];
3123 $this->mOptionOverrides[$m[1]] = $m[2];
3124 }
3125 }
3126 }
3127
3128 /**
3129 * Set a cookie on the user's client. Wrapper for
3130 * WebResponse::setCookie
3131 * @param string $name Name of the cookie to set
3132 * @param string $value Value to set
3133 * @param int $exp Expiration time, as a UNIX time value;
3134 * if 0 or not specified, use the default $wgCookieExpiration
3135 * @param bool $secure
3136 * true: Force setting the secure attribute when setting the cookie
3137 * false: Force NOT setting the secure attribute when setting the cookie
3138 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3139 * @param array $params Array of options sent passed to WebResponse::setcookie()
3140 */
3141 protected function setCookie( $name, $value, $exp = 0, $secure = null, $params = array() ) {
3142 $params['secure'] = $secure;
3143 $this->getRequest()->response()->setcookie( $name, $value, $exp, $params );
3144 }
3145
3146 /**
3147 * Clear a cookie on the user's client
3148 * @param string $name Name of the cookie to clear
3149 * @param bool $secure
3150 * true: Force setting the secure attribute when setting the cookie
3151 * false: Force NOT setting the secure attribute when setting the cookie
3152 * null (default): Use the default ($wgCookieSecure) to set the secure attribute
3153 * @param array $params Array of options sent passed to WebResponse::setcookie()
3154 */
3155 protected function clearCookie( $name, $secure = null, $params = array() ) {
3156 $this->setCookie( $name, '', time() - 86400, $secure, $params );
3157 }
3158
3159 /**
3160 * Set the default cookies for this session on the user's client.
3161 *
3162 * @param $request WebRequest object to use; $wgRequest will be used if null
3163 * is passed.
3164 * @param bool $secure Whether to force secure/insecure cookies or use default
3165 */
3166 public function setCookies( $request = null, $secure = null ) {
3167 if ( $request === null ) {
3168 $request = $this->getRequest();
3169 }
3170
3171 $this->load();
3172 if ( 0 == $this->mId ) {
3173 return;
3174 }
3175 if ( !$this->mToken ) {
3176 // When token is empty or NULL generate a new one and then save it to the database
3177 // This allows a wiki to re-secure itself after a leak of it's user table or $wgSecretKey
3178 // Simply by setting every cell in the user_token column to NULL and letting them be
3179 // regenerated as users log back into the wiki.
3180 $this->setToken();
3181 $this->saveSettings();
3182 }
3183 $session = array(
3184 'wsUserID' => $this->mId,
3185 'wsToken' => $this->mToken,
3186 'wsUserName' => $this->getName()
3187 );
3188 $cookies = array(
3189 'UserID' => $this->mId,
3190 'UserName' => $this->getName(),
3191 );
3192 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
3193 $cookies['Token'] = $this->mToken;
3194 } else {
3195 $cookies['Token'] = false;
3196 }
3197
3198 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
3199
3200 foreach ( $session as $name => $value ) {
3201 $request->setSessionData( $name, $value );
3202 }
3203 foreach ( $cookies as $name => $value ) {
3204 if ( $value === false ) {
3205 $this->clearCookie( $name );
3206 } else {
3207 $this->setCookie( $name, $value, 0, $secure );
3208 }
3209 }
3210
3211 /**
3212 * If wpStickHTTPS was selected, also set an insecure cookie that
3213 * will cause the site to redirect the user to HTTPS, if they access
3214 * it over HTTP. Bug 29898. Use an un-prefixed cookie, so it's the same
3215 * as the one set by centralauth (bug 53538). Also set it to session, or
3216 * standard time setting, based on if rememberme was set.
3217 */
3218 if ( $request->getCheck( 'wpStickHTTPS' ) || $this->requiresHTTPS() ) {
3219 $time = null;
3220 if ( ( 1 == $this->getOption( 'rememberpassword' ) ) ) {
3221 $time = 0; // set to $wgCookieExpiration
3222 }
3223 $this->setCookie(
3224 'forceHTTPS',
3225 'true',
3226 $time,
3227 false,
3228 array( 'prefix' => '' ) // no prefix
3229 );
3230 }
3231 }
3232
3233 /**
3234 * Log this user out.
3235 */
3236 public function logout() {
3237 if ( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
3238 $this->doLogout();
3239 }
3240 }
3241
3242 /**
3243 * Clear the user's cookies and session, and reset the instance cache.
3244 * @see logout()
3245 */
3246 public function doLogout() {
3247 $this->clearInstanceCache( 'defaults' );
3248
3249 $this->getRequest()->setSessionData( 'wsUserID', 0 );
3250
3251 $this->clearCookie( 'UserID' );
3252 $this->clearCookie( 'Token' );
3253 $this->clearCookie( 'forceHTTPS', false, array( 'prefix' => '' ) );
3254
3255 // Remember when user logged out, to prevent seeing cached pages
3256 $this->setCookie( 'LoggedOut', time(), time() + 86400 );
3257 }
3258
3259 /**
3260 * Save this user's settings into the database.
3261 * @todo Only rarely do all these fields need to be set!
3262 */
3263 public function saveSettings() {
3264 global $wgAuth;
3265
3266 $this->load();
3267 if ( wfReadOnly() ) {
3268 return;
3269 }
3270 if ( 0 == $this->mId ) {
3271 return;
3272 }
3273
3274 $this->mTouched = self::newTouchedTimestamp();
3275 if ( !$wgAuth->allowSetLocalPassword() ) {
3276 $this->mPassword = '';
3277 }
3278
3279 $dbw = wfGetDB( DB_MASTER );
3280 $dbw->update( 'user',
3281 array( /* SET */
3282 'user_name' => $this->mName,
3283 'user_password' => $this->mPassword,
3284 'user_newpassword' => $this->mNewpassword,
3285 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3286 'user_real_name' => $this->mRealName,
3287 'user_email' => $this->mEmail,
3288 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3289 'user_touched' => $dbw->timestamp( $this->mTouched ),
3290 'user_token' => strval( $this->mToken ),
3291 'user_email_token' => $this->mEmailToken,
3292 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
3293 ), array( /* WHERE */
3294 'user_id' => $this->mId
3295 ), __METHOD__
3296 );
3297
3298 $this->saveOptions();
3299
3300 wfRunHooks( 'UserSaveSettings', array( $this ) );
3301 $this->clearSharedCache();
3302 $this->getUserPage()->invalidateCache();
3303 }
3304
3305 /**
3306 * If only this user's username is known, and it exists, return the user ID.
3307 * @return int
3308 */
3309 public function idForName() {
3310 $s = trim( $this->getName() );
3311 if ( $s === '' ) {
3312 return 0;
3313 }
3314
3315 $dbr = wfGetDB( DB_SLAVE );
3316 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
3317 if ( $id === false ) {
3318 $id = 0;
3319 }
3320 return $id;
3321 }
3322
3323 /**
3324 * Add a user to the database, return the user object
3325 *
3326 * @param string $name Username to add
3327 * @param array $params of Strings Non-default parameters to save to the database as user_* fields:
3328 * - password The user's password hash. Password logins will be disabled if this is omitted.
3329 * - newpassword Hash for a temporary password that has been mailed to the user
3330 * - email The user's email address
3331 * - email_authenticated The email authentication timestamp
3332 * - real_name The user's real name
3333 * - options An associative array of non-default options
3334 * - token Random authentication token. Do not set.
3335 * - registration Registration timestamp. Do not set.
3336 *
3337 * @return User object, or null if the username already exists
3338 */
3339 public static function createNew( $name, $params = array() ) {
3340 $user = new User;
3341 $user->load();
3342 $user->setToken(); // init token
3343 if ( isset( $params['options'] ) ) {
3344 $user->mOptions = $params['options'] + (array)$user->mOptions;
3345 unset( $params['options'] );
3346 }
3347 $dbw = wfGetDB( DB_MASTER );
3348 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3349
3350 $fields = array(
3351 'user_id' => $seqVal,
3352 'user_name' => $name,
3353 'user_password' => $user->mPassword,
3354 'user_newpassword' => $user->mNewpassword,
3355 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
3356 'user_email' => $user->mEmail,
3357 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
3358 'user_real_name' => $user->mRealName,
3359 'user_token' => strval( $user->mToken ),
3360 'user_registration' => $dbw->timestamp( $user->mRegistration ),
3361 'user_editcount' => 0,
3362 'user_touched' => $dbw->timestamp( self::newTouchedTimestamp() ),
3363 );
3364 foreach ( $params as $name => $value ) {
3365 $fields["user_$name"] = $value;
3366 }
3367 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
3368 if ( $dbw->affectedRows() ) {
3369 $newUser = User::newFromId( $dbw->insertId() );
3370 } else {
3371 $newUser = null;
3372 }
3373 return $newUser;
3374 }
3375
3376 /**
3377 * Add this existing user object to the database. If the user already
3378 * exists, a fatal status object is returned, and the user object is
3379 * initialised with the data from the database.
3380 *
3381 * Previously, this function generated a DB error due to a key conflict
3382 * if the user already existed. Many extension callers use this function
3383 * in code along the lines of:
3384 *
3385 * $user = User::newFromName( $name );
3386 * if ( !$user->isLoggedIn() ) {
3387 * $user->addToDatabase();
3388 * }
3389 * // do something with $user...
3390 *
3391 * However, this was vulnerable to a race condition (bug 16020). By
3392 * initialising the user object if the user exists, we aim to support this
3393 * calling sequence as far as possible.
3394 *
3395 * Note that if the user exists, this function will acquire a write lock,
3396 * so it is still advisable to make the call conditional on isLoggedIn(),
3397 * and to commit the transaction after calling.
3398 *
3399 * @throws MWException
3400 * @return Status
3401 */
3402 public function addToDatabase() {
3403 $this->load();
3404 if ( !$this->mToken ) {
3405 $this->setToken(); // init token
3406 }
3407
3408 $this->mTouched = self::newTouchedTimestamp();
3409
3410 $dbw = wfGetDB( DB_MASTER );
3411 $inWrite = $dbw->writesOrCallbacksPending();
3412 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
3413 $dbw->insert( 'user',
3414 array(
3415 'user_id' => $seqVal,
3416 'user_name' => $this->mName,
3417 'user_password' => $this->mPassword,
3418 'user_newpassword' => $this->mNewpassword,
3419 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
3420 'user_email' => $this->mEmail,
3421 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
3422 'user_real_name' => $this->mRealName,
3423 'user_token' => strval( $this->mToken ),
3424 'user_registration' => $dbw->timestamp( $this->mRegistration ),
3425 'user_editcount' => 0,
3426 'user_touched' => $dbw->timestamp( $this->mTouched ),
3427 ), __METHOD__,
3428 array( 'IGNORE' )
3429 );
3430 if ( !$dbw->affectedRows() ) {
3431 if ( !$inWrite ) {
3432 // XXX: Get out of REPEATABLE-READ so the SELECT below works.
3433 // Often this case happens early in views before any writes.
3434 // This shows up at least with CentralAuth.
3435 $dbw->commit( __METHOD__, 'flush' );
3436 }
3437 $this->mId = $dbw->selectField( 'user', 'user_id',
3438 array( 'user_name' => $this->mName ), __METHOD__ );
3439 $loaded = false;
3440 if ( $this->mId ) {
3441 if ( $this->loadFromDatabase() ) {
3442 $loaded = true;
3443 }
3444 }
3445 if ( !$loaded ) {
3446 throw new MWException( __METHOD__ . ": hit a key conflict attempting " .
3447 "to insert user '{$this->mName}' row, but it was not present in select!" );
3448 }
3449 return Status::newFatal( 'userexists' );
3450 }
3451 $this->mId = $dbw->insertId();
3452
3453 // Clear instance cache other than user table data, which is already accurate
3454 $this->clearInstanceCache();
3455
3456 $this->saveOptions();
3457 return Status::newGood();
3458 }
3459
3460 /**
3461 * If this user is logged-in and blocked,
3462 * block any IP address they've successfully logged in from.
3463 * @return bool A block was spread
3464 */
3465 public function spreadAnyEditBlock() {
3466 if ( $this->isLoggedIn() && $this->isBlocked() ) {
3467 return $this->spreadBlock();
3468 }
3469 return false;
3470 }
3471
3472 /**
3473 * If this (non-anonymous) user is blocked,
3474 * block the IP address they've successfully logged in from.
3475 * @return bool A block was spread
3476 */
3477 protected function spreadBlock() {
3478 wfDebug( __METHOD__ . "()\n" );
3479 $this->load();
3480 if ( $this->mId == 0 ) {
3481 return false;
3482 }
3483
3484 $userblock = Block::newFromTarget( $this->getName() );
3485 if ( !$userblock ) {
3486 return false;
3487 }
3488
3489 return (bool)$userblock->doAutoblock( $this->getRequest()->getIP() );
3490 }
3491
3492 /**
3493 * Generate a string which will be different for any combination of
3494 * user options which would produce different parser output.
3495 * This will be used as part of the hash key for the parser cache,
3496 * so users with the same options can share the same cached data
3497 * safely.
3498 *
3499 * Extensions which require it should install 'PageRenderingHash' hook,
3500 * which will give them a chance to modify this key based on their own
3501 * settings.
3502 *
3503 * @deprecated since 1.17 use the ParserOptions object to get the relevant options
3504 * @return string Page rendering hash
3505 */
3506 public function getPageRenderingHash() {
3507 wfDeprecated( __METHOD__, '1.17' );
3508
3509 global $wgRenderHashAppend, $wgLang, $wgContLang;
3510 if ( $this->mHash ) {
3511 return $this->mHash;
3512 }
3513
3514 // stubthreshold is only included below for completeness,
3515 // since it disables the parser cache, its value will always
3516 // be 0 when this function is called by parsercache.
3517
3518 $confstr = $this->getOption( 'math' );
3519 $confstr .= '!' . $this->getStubThreshold();
3520 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ? '1' : '' );
3521 $confstr .= '!' . $wgLang->getCode();
3522 $confstr .= '!' . $this->getOption( 'thumbsize' );
3523 // add in language specific options, if any
3524 $extra = $wgContLang->getExtraHashOptions();
3525 $confstr .= $extra;
3526
3527 // Since the skin could be overloading link(), it should be
3528 // included here but in practice, none of our skins do that.
3529
3530 $confstr .= $wgRenderHashAppend;
3531
3532 // Give a chance for extensions to modify the hash, if they have
3533 // extra options or other effects on the parser cache.
3534 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
3535
3536 // Make it a valid memcached key fragment
3537 $confstr = str_replace( ' ', '_', $confstr );
3538 $this->mHash = $confstr;
3539 return $confstr;
3540 }
3541
3542 /**
3543 * Get whether the user is explicitly blocked from account creation.
3544 * @return bool|Block
3545 */
3546 public function isBlockedFromCreateAccount() {
3547 $this->getBlockedStatus();
3548 if ( $this->mBlock && $this->mBlock->prevents( 'createaccount' ) ) {
3549 return $this->mBlock;
3550 }
3551
3552 # bug 13611: if the IP address the user is trying to create an account from is
3553 # blocked with createaccount disabled, prevent new account creation there even
3554 # when the user is logged in
3555 if ( $this->mBlockedFromCreateAccount === false && !$this->isAllowed( 'ipblock-exempt' ) ) {
3556 $this->mBlockedFromCreateAccount = Block::newFromTarget( null, $this->getRequest()->getIP() );
3557 }
3558 return $this->mBlockedFromCreateAccount instanceof Block && $this->mBlockedFromCreateAccount->prevents( 'createaccount' )
3559 ? $this->mBlockedFromCreateAccount
3560 : false;
3561 }
3562
3563 /**
3564 * Get whether the user is blocked from using Special:Emailuser.
3565 * @return bool
3566 */
3567 public function isBlockedFromEmailuser() {
3568 $this->getBlockedStatus();
3569 return $this->mBlock && $this->mBlock->prevents( 'sendemail' );
3570 }
3571
3572 /**
3573 * Get whether the user is allowed to create an account.
3574 * @return bool
3575 */
3576 function isAllowedToCreateAccount() {
3577 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
3578 }
3579
3580 /**
3581 * Get this user's personal page title.
3582 *
3583 * @return Title: User's personal page title
3584 */
3585 public function getUserPage() {
3586 return Title::makeTitle( NS_USER, $this->getName() );
3587 }
3588
3589 /**
3590 * Get this user's talk page title.
3591 *
3592 * @return Title: User's talk page title
3593 */
3594 public function getTalkPage() {
3595 $title = $this->getUserPage();
3596 return $title->getTalkPage();
3597 }
3598
3599 /**
3600 * Determine whether the user is a newbie. Newbies are either
3601 * anonymous IPs, or the most recently created accounts.
3602 * @return bool
3603 */
3604 public function isNewbie() {
3605 return !$this->isAllowed( 'autoconfirmed' );
3606 }
3607
3608 /**
3609 * Check to see if the given clear-text password is one of the accepted passwords
3610 * @param string $password user password.
3611 * @return boolean: True if the given password is correct, otherwise False.
3612 */
3613 public function checkPassword( $password ) {
3614 global $wgAuth, $wgLegacyEncoding;
3615 $this->load();
3616
3617 // Even though we stop people from creating passwords that
3618 // are shorter than this, doesn't mean people wont be able
3619 // to. Certain authentication plugins do NOT want to save
3620 // domain passwords in a mysql database, so we should
3621 // check this (in case $wgAuth->strict() is false).
3622 if ( !$this->isValidPassword( $password ) ) {
3623 return false;
3624 }
3625
3626 if ( $wgAuth->authenticate( $this->getName(), $password ) ) {
3627 return true;
3628 } elseif ( $wgAuth->strict() ) {
3629 // Auth plugin doesn't allow local authentication
3630 return false;
3631 } elseif ( $wgAuth->strictUserAuth( $this->getName() ) ) {
3632 // Auth plugin doesn't allow local authentication for this user name
3633 return false;
3634 }
3635 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
3636 return true;
3637 } elseif ( $wgLegacyEncoding ) {
3638 // Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
3639 // Check for this with iconv
3640 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
3641 if ( $cp1252Password != $password &&
3642 self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) )
3643 {
3644 return true;
3645 }
3646 }
3647 return false;
3648 }
3649
3650 /**
3651 * Check if the given clear-text password matches the temporary password
3652 * sent by e-mail for password reset operations.
3653 *
3654 * @param $plaintext string
3655 *
3656 * @return boolean: True if matches, false otherwise
3657 */
3658 public function checkTemporaryPassword( $plaintext ) {
3659 global $wgNewPasswordExpiry;
3660
3661 $this->load();
3662 if ( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
3663 if ( is_null( $this->mNewpassTime ) ) {
3664 return true;
3665 }
3666 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
3667 return ( time() < $expiry );
3668 } else {
3669 return false;
3670 }
3671 }
3672
3673 /**
3674 * Alias for getEditToken.
3675 * @deprecated since 1.19, use getEditToken instead.
3676 *
3677 * @param string|array $salt of Strings Optional function-specific data for hashing
3678 * @param $request WebRequest object to use or null to use $wgRequest
3679 * @return string The new edit token
3680 */
3681 public function editToken( $salt = '', $request = null ) {
3682 wfDeprecated( __METHOD__, '1.19' );
3683 return $this->getEditToken( $salt, $request );
3684 }
3685
3686 /**
3687 * Initialize (if necessary) and return a session token value
3688 * which can be used in edit forms to show that the user's
3689 * login credentials aren't being hijacked with a foreign form
3690 * submission.
3691 *
3692 * @since 1.19
3693 *
3694 * @param string|array $salt of Strings Optional function-specific data for hashing
3695 * @param $request WebRequest object to use or null to use $wgRequest
3696 * @return string The new edit token
3697 */
3698 public function getEditToken( $salt = '', $request = null ) {
3699 if ( $request == null ) {
3700 $request = $this->getRequest();
3701 }
3702
3703 if ( $this->isAnon() ) {
3704 return EDIT_TOKEN_SUFFIX;
3705 } else {
3706 $token = $request->getSessionData( 'wsEditToken' );
3707 if ( $token === null ) {
3708 $token = MWCryptRand::generateHex( 32 );
3709 $request->setSessionData( 'wsEditToken', $token );
3710 }
3711 if ( is_array( $salt ) ) {
3712 $salt = implode( '|', $salt );
3713 }
3714 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
3715 }
3716 }
3717
3718 /**
3719 * Generate a looking random token for various uses.
3720 *
3721 * @return string The new random token
3722 * @deprecated since 1.20: Use MWCryptRand for secure purposes or wfRandomString for pseudo-randomness
3723 */
3724 public static function generateToken() {
3725 return MWCryptRand::generateHex( 32 );
3726 }
3727
3728 /**
3729 * Check given value against the token value stored in the session.
3730 * A match should confirm that the form was submitted from the
3731 * user's own login session, not a form submission from a third-party
3732 * site.
3733 *
3734 * @param string $val Input value to compare
3735 * @param string $salt Optional function-specific data for hashing
3736 * @param WebRequest $request Object to use or null to use $wgRequest
3737 * @return boolean: Whether the token matches
3738 */
3739 public function matchEditToken( $val, $salt = '', $request = null ) {
3740 $sessionToken = $this->getEditToken( $salt, $request );
3741 if ( $val != $sessionToken ) {
3742 wfDebug( "User::matchEditToken: broken session data\n" );
3743 }
3744 return $val == $sessionToken;
3745 }
3746
3747 /**
3748 * Check given value against the token value stored in the session,
3749 * ignoring the suffix.
3750 *
3751 * @param string $val Input value to compare
3752 * @param string $salt Optional function-specific data for hashing
3753 * @param WebRequest $request object to use or null to use $wgRequest
3754 * @return boolean: Whether the token matches
3755 */
3756 public function matchEditTokenNoSuffix( $val, $salt = '', $request = null ) {
3757 $sessionToken = $this->getEditToken( $salt, $request );
3758 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
3759 }
3760
3761 /**
3762 * Generate a new e-mail confirmation token and send a confirmation/invalidation
3763 * mail to the user's given address.
3764 *
3765 * @param string $type message to send, either "created", "changed" or "set"
3766 * @return Status object
3767 */
3768 public function sendConfirmationMail( $type = 'created' ) {
3769 global $wgLang;
3770 $expiration = null; // gets passed-by-ref and defined in next line.
3771 $token = $this->confirmationToken( $expiration );
3772 $url = $this->confirmationTokenUrl( $token );
3773 $invalidateURL = $this->invalidationTokenUrl( $token );
3774 $this->saveSettings();
3775
3776 if ( $type == 'created' || $type === false ) {
3777 $message = 'confirmemail_body';
3778 } elseif ( $type === true ) {
3779 $message = 'confirmemail_body_changed';
3780 } else {
3781 // Messages: confirmemail_body_changed, confirmemail_body_set
3782 $message = 'confirmemail_body_' . $type;
3783 }
3784
3785 return $this->sendMail( wfMessage( 'confirmemail_subject' )->text(),
3786 wfMessage( $message,
3787 $this->getRequest()->getIP(),
3788 $this->getName(),
3789 $url,
3790 $wgLang->timeanddate( $expiration, false ),
3791 $invalidateURL,
3792 $wgLang->date( $expiration, false ),
3793 $wgLang->time( $expiration, false ) )->text() );
3794 }
3795
3796 /**
3797 * Send an e-mail to this user's account. Does not check for
3798 * confirmed status or validity.
3799 *
3800 * @param string $subject Message subject
3801 * @param string $body Message body
3802 * @param string $from Optional From address; if unspecified, default $wgPasswordSender will be used
3803 * @param string $replyto Reply-To address
3804 * @return Status
3805 */
3806 public function sendMail( $subject, $body, $from = null, $replyto = null ) {
3807 if ( is_null( $from ) ) {
3808 global $wgPasswordSender, $wgPasswordSenderName;
3809 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
3810 } else {
3811 $sender = new MailAddress( $from );
3812 }
3813
3814 $to = new MailAddress( $this );
3815 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
3816 }
3817
3818 /**
3819 * Generate, store, and return a new e-mail confirmation code.
3820 * A hash (unsalted, since it's used as a key) is stored.
3821 *
3822 * @note Call saveSettings() after calling this function to commit
3823 * this change to the database.
3824 *
3825 * @param &$expiration \mixed Accepts the expiration time
3826 * @return string New token
3827 */
3828 protected function confirmationToken( &$expiration ) {
3829 global $wgUserEmailConfirmationTokenExpiry;
3830 $now = time();
3831 $expires = $now + $wgUserEmailConfirmationTokenExpiry;
3832 $expiration = wfTimestamp( TS_MW, $expires );
3833 $this->load();
3834 $token = MWCryptRand::generateHex( 32 );
3835 $hash = md5( $token );
3836 $this->mEmailToken = $hash;
3837 $this->mEmailTokenExpires = $expiration;
3838 return $token;
3839 }
3840
3841 /**
3842 * Return a URL the user can use to confirm their email address.
3843 * @param string $token Accepts the email confirmation token
3844 * @return string New token URL
3845 */
3846 protected function confirmationTokenUrl( $token ) {
3847 return $this->getTokenUrl( 'ConfirmEmail', $token );
3848 }
3849
3850 /**
3851 * Return a URL the user can use to invalidate their email address.
3852 * @param string $token Accepts the email confirmation token
3853 * @return string New token URL
3854 */
3855 protected function invalidationTokenUrl( $token ) {
3856 return $this->getTokenUrl( 'InvalidateEmail', $token );
3857 }
3858
3859 /**
3860 * Internal function to format the e-mail validation/invalidation URLs.
3861 * This uses a quickie hack to use the
3862 * hardcoded English names of the Special: pages, for ASCII safety.
3863 *
3864 * @note Since these URLs get dropped directly into emails, using the
3865 * short English names avoids insanely long URL-encoded links, which
3866 * also sometimes can get corrupted in some browsers/mailers
3867 * (bug 6957 with Gmail and Internet Explorer).
3868 *
3869 * @param string $page Special page
3870 * @param string $token Token
3871 * @return string Formatted URL
3872 */
3873 protected function getTokenUrl( $page, $token ) {
3874 // Hack to bypass localization of 'Special:'
3875 $title = Title::makeTitle( NS_MAIN, "Special:$page/$token" );
3876 return $title->getCanonicalURL();
3877 }
3878
3879 /**
3880 * Mark the e-mail address confirmed.
3881 *
3882 * @note Call saveSettings() after calling this function to commit the change.
3883 *
3884 * @return bool
3885 */
3886 public function confirmEmail() {
3887 // Check if it's already confirmed, so we don't touch the database
3888 // and fire the ConfirmEmailComplete hook on redundant confirmations.
3889 if ( !$this->isEmailConfirmed() ) {
3890 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3891 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3892 }
3893 return true;
3894 }
3895
3896 /**
3897 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3898 * address if it was already confirmed.
3899 *
3900 * @note Call saveSettings() after calling this function to commit the change.
3901 * @return bool Returns true
3902 */
3903 function invalidateEmail() {
3904 $this->load();
3905 $this->mEmailToken = null;
3906 $this->mEmailTokenExpires = null;
3907 $this->setEmailAuthenticationTimestamp( null );
3908 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3909 return true;
3910 }
3911
3912 /**
3913 * Set the e-mail authentication timestamp.
3914 * @param string $timestamp TS_MW timestamp
3915 */
3916 function setEmailAuthenticationTimestamp( $timestamp ) {
3917 $this->load();
3918 $this->mEmailAuthenticated = $timestamp;
3919 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
3920 }
3921
3922 /**
3923 * Is this user allowed to send e-mails within limits of current
3924 * site configuration?
3925 * @return bool
3926 */
3927 public function canSendEmail() {
3928 global $wgEnableEmail, $wgEnableUserEmail;
3929 if ( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
3930 return false;
3931 }
3932 $canSend = $this->isEmailConfirmed();
3933 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3934 return $canSend;
3935 }
3936
3937 /**
3938 * Is this user allowed to receive e-mails within limits of current
3939 * site configuration?
3940 * @return bool
3941 */
3942 public function canReceiveEmail() {
3943 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3944 }
3945
3946 /**
3947 * Is this user's e-mail address valid-looking and confirmed within
3948 * limits of the current site configuration?
3949 *
3950 * @note If $wgEmailAuthentication is on, this may require the user to have
3951 * confirmed their address by returning a code or using a password
3952 * sent to the address from the wiki.
3953 *
3954 * @return bool
3955 */
3956 public function isEmailConfirmed() {
3957 global $wgEmailAuthentication;
3958 $this->load();
3959 $confirmed = true;
3960 if ( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3961 if ( $this->isAnon() ) {
3962 return false;
3963 }
3964 if ( !Sanitizer::validateEmail( $this->mEmail ) ) {
3965 return false;
3966 }
3967 if ( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() ) {
3968 return false;
3969 }
3970 return true;
3971 } else {
3972 return $confirmed;
3973 }
3974 }
3975
3976 /**
3977 * Check whether there is an outstanding request for e-mail confirmation.
3978 * @return bool
3979 */
3980 public function isEmailConfirmationPending() {
3981 global $wgEmailAuthentication;
3982 return $wgEmailAuthentication &&
3983 !$this->isEmailConfirmed() &&
3984 $this->mEmailToken &&
3985 $this->mEmailTokenExpires > wfTimestamp();
3986 }
3987
3988 /**
3989 * Get the timestamp of account creation.
3990 *
3991 * @return string|bool|null Timestamp of account creation, false for
3992 * non-existent/anonymous user accounts, or null if existing account
3993 * but information is not in database.
3994 */
3995 public function getRegistration() {
3996 if ( $this->isAnon() ) {
3997 return false;
3998 }
3999 $this->load();
4000 return $this->mRegistration;
4001 }
4002
4003 /**
4004 * Get the timestamp of the first edit
4005 *
4006 * @return string|bool Timestamp of first edit, or false for
4007 * non-existent/anonymous user accounts.
4008 */
4009 public function getFirstEditTimestamp() {
4010 if ( $this->getId() == 0 ) {
4011 return false; // anons
4012 }
4013 $dbr = wfGetDB( DB_SLAVE );
4014 $time = $dbr->selectField( 'revision', 'rev_timestamp',
4015 array( 'rev_user' => $this->getId() ),
4016 __METHOD__,
4017 array( 'ORDER BY' => 'rev_timestamp ASC' )
4018 );
4019 if ( !$time ) {
4020 return false; // no edits
4021 }
4022 return wfTimestamp( TS_MW, $time );
4023 }
4024
4025 /**
4026 * Get the permissions associated with a given list of groups
4027 *
4028 * @param array $groups of Strings List of internal group names
4029 * @return Array of Strings List of permission key names for given groups combined
4030 */
4031 public static function getGroupPermissions( $groups ) {
4032 global $wgGroupPermissions, $wgRevokePermissions;
4033 $rights = array();
4034 // grant every granted permission first
4035 foreach ( $groups as $group ) {
4036 if ( isset( $wgGroupPermissions[$group] ) ) {
4037 $rights = array_merge( $rights,
4038 // array_filter removes empty items
4039 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
4040 }
4041 }
4042 // now revoke the revoked permissions
4043 foreach ( $groups as $group ) {
4044 if ( isset( $wgRevokePermissions[$group] ) ) {
4045 $rights = array_diff( $rights,
4046 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
4047 }
4048 }
4049 return array_unique( $rights );
4050 }
4051
4052 /**
4053 * Get all the groups who have a given permission
4054 *
4055 * @param string $role Role to check
4056 * @return Array of Strings List of internal group names with the given permission
4057 */
4058 public static function getGroupsWithPermission( $role ) {
4059 global $wgGroupPermissions;
4060 $allowedGroups = array();
4061 foreach ( array_keys( $wgGroupPermissions ) as $group ) {
4062 if ( self::groupHasPermission( $group, $role ) ) {
4063 $allowedGroups[] = $group;
4064 }
4065 }
4066 return $allowedGroups;
4067 }
4068
4069 /**
4070 * Check, if the given group has the given permission
4071 *
4072 * If you're wanting to check whether all users have a permission, use
4073 * User::isEveryoneAllowed() instead. That properly checks if it's revoked
4074 * from anyone.
4075 *
4076 * @since 1.21
4077 * @param string $group Group to check
4078 * @param string $role Role to check
4079 * @return bool
4080 */
4081 public static function groupHasPermission( $group, $role ) {
4082 global $wgGroupPermissions, $wgRevokePermissions;
4083 return isset( $wgGroupPermissions[$group][$role] ) && $wgGroupPermissions[$group][$role]
4084 && !( isset( $wgRevokePermissions[$group][$role] ) && $wgRevokePermissions[$group][$role] );
4085 }
4086
4087 /**
4088 * Check if all users have the given permission
4089 *
4090 * @since 1.22
4091 * @param string $right Right to check
4092 * @return bool
4093 */
4094 public static function isEveryoneAllowed( $right ) {
4095 global $wgGroupPermissions, $wgRevokePermissions;
4096 static $cache = array();
4097
4098 // Use the cached results, except in unit tests which rely on
4099 // being able change the permission mid-request
4100 if ( isset( $cache[$right] ) && !defined( 'MW_PHPUNIT_TEST' ) ) {
4101 return $cache[$right];
4102 }
4103
4104 if ( !isset( $wgGroupPermissions['*'][$right] ) || !$wgGroupPermissions['*'][$right] ) {
4105 $cache[$right] = false;
4106 return false;
4107 }
4108
4109 // If it's revoked anywhere, then everyone doesn't have it
4110 foreach ( $wgRevokePermissions as $rights ) {
4111 if ( isset( $rights[$right] ) && $rights[$right] ) {
4112 $cache[$right] = false;
4113 return false;
4114 }
4115 }
4116
4117 // Allow extensions (e.g. OAuth) to say false
4118 if ( !wfRunHooks( 'UserIsEveryoneAllowed', array( $right ) ) ) {
4119 $cache[$right] = false;
4120 return false;
4121 }
4122
4123 $cache[$right] = true;
4124 return true;
4125 }
4126
4127 /**
4128 * Get the localized descriptive name for a group, if it exists
4129 *
4130 * @param string $group Internal group name
4131 * @return string Localized descriptive group name
4132 */
4133 public static function getGroupName( $group ) {
4134 $msg = wfMessage( "group-$group" );
4135 return $msg->isBlank() ? $group : $msg->text();
4136 }
4137
4138 /**
4139 * Get the localized descriptive name for a member of a group, if it exists
4140 *
4141 * @param string $group Internal group name
4142 * @param string $username Username for gender (since 1.19)
4143 * @return string Localized name for group member
4144 */
4145 public static function getGroupMember( $group, $username = '#' ) {
4146 $msg = wfMessage( "group-$group-member", $username );
4147 return $msg->isBlank() ? $group : $msg->text();
4148 }
4149
4150 /**
4151 * Return the set of defined explicit groups.
4152 * The implicit groups (by default *, 'user' and 'autoconfirmed')
4153 * are not included, as they are defined automatically, not in the database.
4154 * @return Array of internal group names
4155 */
4156 public static function getAllGroups() {
4157 global $wgGroupPermissions, $wgRevokePermissions;
4158 return array_diff(
4159 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
4160 self::getImplicitGroups()
4161 );
4162 }
4163
4164 /**
4165 * Get a list of all available permissions.
4166 * @return Array of permission names
4167 */
4168 public static function getAllRights() {
4169 if ( self::$mAllRights === false ) {
4170 global $wgAvailableRights;
4171 if ( count( $wgAvailableRights ) ) {
4172 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
4173 } else {
4174 self::$mAllRights = self::$mCoreRights;
4175 }
4176 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
4177 }
4178 return self::$mAllRights;
4179 }
4180
4181 /**
4182 * Get a list of implicit groups
4183 * @return Array of Strings Array of internal group names
4184 */
4185 public static function getImplicitGroups() {
4186 global $wgImplicitGroups;
4187 $groups = $wgImplicitGroups;
4188 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
4189 return $groups;
4190 }
4191
4192 /**
4193 * Get the title of a page describing a particular group
4194 *
4195 * @param string $group Internal group name
4196 * @return Title|bool Title of the page if it exists, false otherwise
4197 */
4198 public static function getGroupPage( $group ) {
4199 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
4200 if ( $msg->exists() ) {
4201 $title = Title::newFromText( $msg->text() );
4202 if ( is_object( $title ) ) {
4203 return $title;
4204 }
4205 }
4206 return false;
4207 }
4208
4209 /**
4210 * Create a link to the group in HTML, if available;
4211 * else return the group name.
4212 *
4213 * @param string $group Internal name of the group
4214 * @param string $text The text of the link
4215 * @return string HTML link to the group
4216 */
4217 public static function makeGroupLinkHTML( $group, $text = '' ) {
4218 if ( $text == '' ) {
4219 $text = self::getGroupName( $group );
4220 }
4221 $title = self::getGroupPage( $group );
4222 if ( $title ) {
4223 return Linker::link( $title, htmlspecialchars( $text ) );
4224 } else {
4225 return $text;
4226 }
4227 }
4228
4229 /**
4230 * Create a link to the group in Wikitext, if available;
4231 * else return the group name.
4232 *
4233 * @param string $group Internal name of the group
4234 * @param string $text The text of the link
4235 * @return string Wikilink to the group
4236 */
4237 public static function makeGroupLinkWiki( $group, $text = '' ) {
4238 if ( $text == '' ) {
4239 $text = self::getGroupName( $group );
4240 }
4241 $title = self::getGroupPage( $group );
4242 if ( $title ) {
4243 $page = $title->getPrefixedText();
4244 return "[[$page|$text]]";
4245 } else {
4246 return $text;
4247 }
4248 }
4249
4250 /**
4251 * Returns an array of the groups that a particular group can add/remove.
4252 *
4253 * @param string $group the group to check for whether it can add/remove
4254 * @return Array array( 'add' => array( addablegroups ),
4255 * 'remove' => array( removablegroups ),
4256 * 'add-self' => array( addablegroups to self),
4257 * 'remove-self' => array( removable groups from self) )
4258 */
4259 public static function changeableByGroup( $group ) {
4260 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
4261
4262 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
4263 if ( empty( $wgAddGroups[$group] ) ) {
4264 // Don't add anything to $groups
4265 } elseif ( $wgAddGroups[$group] === true ) {
4266 // You get everything
4267 $groups['add'] = self::getAllGroups();
4268 } elseif ( is_array( $wgAddGroups[$group] ) ) {
4269 $groups['add'] = $wgAddGroups[$group];
4270 }
4271
4272 // Same thing for remove
4273 if ( empty( $wgRemoveGroups[$group] ) ) {
4274 } elseif ( $wgRemoveGroups[$group] === true ) {
4275 $groups['remove'] = self::getAllGroups();
4276 } elseif ( is_array( $wgRemoveGroups[$group] ) ) {
4277 $groups['remove'] = $wgRemoveGroups[$group];
4278 }
4279
4280 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
4281 if ( empty( $wgGroupsAddToSelf['user'] ) || $wgGroupsAddToSelf['user'] !== true ) {
4282 foreach ( $wgGroupsAddToSelf as $key => $value ) {
4283 if ( is_int( $key ) ) {
4284 $wgGroupsAddToSelf['user'][] = $value;
4285 }
4286 }
4287 }
4288
4289 if ( empty( $wgGroupsRemoveFromSelf['user'] ) || $wgGroupsRemoveFromSelf['user'] !== true ) {
4290 foreach ( $wgGroupsRemoveFromSelf as $key => $value ) {
4291 if ( is_int( $key ) ) {
4292 $wgGroupsRemoveFromSelf['user'][] = $value;
4293 }
4294 }
4295 }
4296
4297 // Now figure out what groups the user can add to him/herself
4298 if ( empty( $wgGroupsAddToSelf[$group] ) ) {
4299 } elseif ( $wgGroupsAddToSelf[$group] === true ) {
4300 // No idea WHY this would be used, but it's there
4301 $groups['add-self'] = User::getAllGroups();
4302 } elseif ( is_array( $wgGroupsAddToSelf[$group] ) ) {
4303 $groups['add-self'] = $wgGroupsAddToSelf[$group];
4304 }
4305
4306 if ( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
4307 } elseif ( $wgGroupsRemoveFromSelf[$group] === true ) {
4308 $groups['remove-self'] = User::getAllGroups();
4309 } elseif ( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
4310 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
4311 }
4312
4313 return $groups;
4314 }
4315
4316 /**
4317 * Returns an array of groups that this user can add and remove
4318 * @return Array array( 'add' => array( addablegroups ),
4319 * 'remove' => array( removablegroups ),
4320 * 'add-self' => array( addablegroups to self),
4321 * 'remove-self' => array( removable groups from self) )
4322 */
4323 public function changeableGroups() {
4324 if ( $this->isAllowed( 'userrights' ) ) {
4325 // This group gives the right to modify everything (reverse-
4326 // compatibility with old "userrights lets you change
4327 // everything")
4328 // Using array_merge to make the groups reindexed
4329 $all = array_merge( User::getAllGroups() );
4330 return array(
4331 'add' => $all,
4332 'remove' => $all,
4333 'add-self' => array(),
4334 'remove-self' => array()
4335 );
4336 }
4337
4338 // Okay, it's not so simple, we will have to go through the arrays
4339 $groups = array(
4340 'add' => array(),
4341 'remove' => array(),
4342 'add-self' => array(),
4343 'remove-self' => array()
4344 );
4345 $addergroups = $this->getEffectiveGroups();
4346
4347 foreach ( $addergroups as $addergroup ) {
4348 $groups = array_merge_recursive(
4349 $groups, $this->changeableByGroup( $addergroup )
4350 );
4351 $groups['add'] = array_unique( $groups['add'] );
4352 $groups['remove'] = array_unique( $groups['remove'] );
4353 $groups['add-self'] = array_unique( $groups['add-self'] );
4354 $groups['remove-self'] = array_unique( $groups['remove-self'] );
4355 }
4356 return $groups;
4357 }
4358
4359 /**
4360 * Increment the user's edit-count field.
4361 * Will have no effect for anonymous users.
4362 */
4363 public function incEditCount() {
4364 if ( !$this->isAnon() ) {
4365 $dbw = wfGetDB( DB_MASTER );
4366 $dbw->update(
4367 'user',
4368 array( 'user_editcount=user_editcount+1' ),
4369 array( 'user_id' => $this->getId() ),
4370 __METHOD__
4371 );
4372
4373 // Lazy initialization check...
4374 if ( $dbw->affectedRows() == 0 ) {
4375 // Now here's a goddamn hack...
4376 $dbr = wfGetDB( DB_SLAVE );
4377 if ( $dbr !== $dbw ) {
4378 // If we actually have a slave server, the count is
4379 // at least one behind because the current transaction
4380 // has not been committed and replicated.
4381 $this->initEditCount( 1 );
4382 } else {
4383 // But if DB_SLAVE is selecting the master, then the
4384 // count we just read includes the revision that was
4385 // just added in the working transaction.
4386 $this->initEditCount();
4387 }
4388 }
4389 }
4390 // edit count in user cache too
4391 $this->invalidateCache();
4392 }
4393
4394 /**
4395 * Initialize user_editcount from data out of the revision table
4396 *
4397 * @param $add Integer Edits to add to the count from the revision table
4398 * @return integer Number of edits
4399 */
4400 protected function initEditCount( $add = 0 ) {
4401 // Pull from a slave to be less cruel to servers
4402 // Accuracy isn't the point anyway here
4403 $dbr = wfGetDB( DB_SLAVE );
4404 $count = (int)$dbr->selectField(
4405 'revision',
4406 'COUNT(rev_user)',
4407 array( 'rev_user' => $this->getId() ),
4408 __METHOD__
4409 );
4410 $count = $count + $add;
4411
4412 $dbw = wfGetDB( DB_MASTER );
4413 $dbw->update(
4414 'user',
4415 array( 'user_editcount' => $count ),
4416 array( 'user_id' => $this->getId() ),
4417 __METHOD__
4418 );
4419
4420 return $count;
4421 }
4422
4423 /**
4424 * Get the description of a given right
4425 *
4426 * @param string $right Right to query
4427 * @return string Localized description of the right
4428 */
4429 public static function getRightDescription( $right ) {
4430 $key = "right-$right";
4431 $msg = wfMessage( $key );
4432 return $msg->isBlank() ? $right : $msg->text();
4433 }
4434
4435 /**
4436 * Make an old-style password hash
4437 *
4438 * @param string $password Plain-text password
4439 * @param string $userId User ID
4440 * @return string Password hash
4441 */
4442 public static function oldCrypt( $password, $userId ) {
4443 global $wgPasswordSalt;
4444 if ( $wgPasswordSalt ) {
4445 return md5( $userId . '-' . md5( $password ) );
4446 } else {
4447 return md5( $password );
4448 }
4449 }
4450
4451 /**
4452 * Make a new-style password hash
4453 *
4454 * @param string $password Plain-text password
4455 * @param bool|string $salt Optional salt, may be random or the user ID.
4456 * If unspecified or false, will generate one automatically
4457 * @return string Password hash
4458 */
4459 public static function crypt( $password, $salt = false ) {
4460 global $wgPasswordSalt;
4461
4462 $hash = '';
4463 if ( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
4464 return $hash;
4465 }
4466
4467 if ( $wgPasswordSalt ) {
4468 if ( $salt === false ) {
4469 $salt = MWCryptRand::generateHex( 8 );
4470 }
4471 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
4472 } else {
4473 return ':A:' . md5( $password );
4474 }
4475 }
4476
4477 /**
4478 * Compare a password hash with a plain-text password. Requires the user
4479 * ID if there's a chance that the hash is an old-style hash.
4480 *
4481 * @param string $hash Password hash
4482 * @param string $password Plain-text password to compare
4483 * @param string|bool $userId User ID for old-style password salt
4484 *
4485 * @return boolean
4486 */
4487 public static function comparePasswords( $hash, $password, $userId = false ) {
4488 $type = substr( $hash, 0, 3 );
4489
4490 $result = false;
4491 if ( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
4492 return $result;
4493 }
4494
4495 if ( $type == ':A:' ) {
4496 // Unsalted
4497 return md5( $password ) === substr( $hash, 3 );
4498 } elseif ( $type == ':B:' ) {
4499 // Salted
4500 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
4501 return md5( $salt . '-' . md5( $password ) ) === $realHash;
4502 } else {
4503 // Old-style
4504 return self::oldCrypt( $password, $userId ) === $hash;
4505 }
4506 }
4507
4508 /**
4509 * Add a newuser log entry for this user.
4510 * Before 1.19 the return value was always true.
4511 *
4512 * @param string|bool $action account creation type.
4513 * - String, one of the following values:
4514 * - 'create' for an anonymous user creating an account for himself.
4515 * This will force the action's performer to be the created user itself,
4516 * no matter the value of $wgUser
4517 * - 'create2' for a logged in user creating an account for someone else
4518 * - 'byemail' when the created user will receive its password by e-mail
4519 * - 'autocreate' when the user is automatically created (such as by CentralAuth).
4520 * - Boolean means whether the account was created by e-mail (deprecated):
4521 * - true will be converted to 'byemail'
4522 * - false will be converted to 'create' if this object is the same as
4523 * $wgUser and to 'create2' otherwise
4524 *
4525 * @param string $reason user supplied reason
4526 *
4527 * @return int|bool True if not $wgNewUserLog; otherwise ID of log item or 0 on failure
4528 */
4529 public function addNewUserLogEntry( $action = false, $reason = '' ) {
4530 global $wgUser, $wgNewUserLog;
4531 if ( empty( $wgNewUserLog ) ) {
4532 return true; // disabled
4533 }
4534
4535 if ( $action === true ) {
4536 $action = 'byemail';
4537 } elseif ( $action === false ) {
4538 if ( $this->getName() == $wgUser->getName() ) {
4539 $action = 'create';
4540 } else {
4541 $action = 'create2';
4542 }
4543 }
4544
4545 if ( $action === 'create' || $action === 'autocreate' ) {
4546 $performer = $this;
4547 } else {
4548 $performer = $wgUser;
4549 }
4550
4551 $logEntry = new ManualLogEntry( 'newusers', $action );
4552 $logEntry->setPerformer( $performer );
4553 $logEntry->setTarget( $this->getUserPage() );
4554 $logEntry->setComment( $reason );
4555 $logEntry->setParameters( array(
4556 '4::userid' => $this->getId(),
4557 ) );
4558 $logid = $logEntry->insert();
4559
4560 if ( $action !== 'autocreate' ) {
4561 $logEntry->publish( $logid );
4562 }
4563
4564 return (int)$logid;
4565 }
4566
4567 /**
4568 * Add an autocreate newuser log entry for this user
4569 * Used by things like CentralAuth and perhaps other authplugins.
4570 * Consider calling addNewUserLogEntry() directly instead.
4571 *
4572 * @return bool
4573 */
4574 public function addNewUserLogEntryAutoCreate() {
4575 $this->addNewUserLogEntry( 'autocreate' );
4576
4577 return true;
4578 }
4579
4580 /**
4581 * Load the user options either from cache, the database or an array
4582 *
4583 * @param array $data Rows for the current user out of the user_properties table
4584 */
4585 protected function loadOptions( $data = null ) {
4586 global $wgContLang;
4587
4588 $this->load();
4589
4590 if ( $this->mOptionsLoaded ) {
4591 return;
4592 }
4593
4594 $this->mOptions = self::getDefaultOptions();
4595
4596 if ( !$this->getId() ) {
4597 // For unlogged-in users, load language/variant options from request.
4598 // There's no need to do it for logged-in users: they can set preferences,
4599 // and handling of page content is done by $pageLang->getPreferredVariant() and such,
4600 // so don't override user's choice (especially when the user chooses site default).
4601 $variant = $wgContLang->getDefaultVariant();
4602 $this->mOptions['variant'] = $variant;
4603 $this->mOptions['language'] = $variant;
4604 $this->mOptionsLoaded = true;
4605 return;
4606 }
4607
4608 // Maybe load from the object
4609 if ( !is_null( $this->mOptionOverrides ) ) {
4610 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
4611 foreach ( $this->mOptionOverrides as $key => $value ) {
4612 $this->mOptions[$key] = $value;
4613 }
4614 } else {
4615 if ( !is_array( $data ) ) {
4616 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
4617 // Load from database
4618 $dbr = wfGetDB( DB_SLAVE );
4619
4620 $res = $dbr->select(
4621 'user_properties',
4622 array( 'up_property', 'up_value' ),
4623 array( 'up_user' => $this->getId() ),
4624 __METHOD__
4625 );
4626
4627 $this->mOptionOverrides = array();
4628 $data = array();
4629 foreach ( $res as $row ) {
4630 $data[$row->up_property] = $row->up_value;
4631 }
4632 }
4633 foreach ( $data as $property => $value ) {
4634 $this->mOptionOverrides[$property] = $value;
4635 $this->mOptions[$property] = $value;
4636 }
4637 }
4638
4639 $this->mOptionsLoaded = true;
4640
4641 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
4642 }
4643
4644 /**
4645 * @todo document
4646 */
4647 protected function saveOptions() {
4648 $this->loadOptions();
4649
4650 // Not using getOptions(), to keep hidden preferences in database
4651 $saveOptions = $this->mOptions;
4652
4653 // Allow hooks to abort, for instance to save to a global profile.
4654 // Reset options to default state before saving.
4655 if ( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) ) {
4656 return;
4657 }
4658
4659 $userId = $this->getId();
4660 $insert_rows = array();
4661 foreach ( $saveOptions as $key => $value ) {
4662 // Don't bother storing default values
4663 $defaultOption = self::getDefaultOption( $key );
4664 if ( ( is_null( $defaultOption ) &&
4665 !( $value === false || is_null( $value ) ) ) ||
4666 $value != $defaultOption ) {
4667 $insert_rows[] = array(
4668 'up_user' => $userId,
4669 'up_property' => $key,
4670 'up_value' => $value,
4671 );
4672 }
4673 }
4674
4675 $dbw = wfGetDB( DB_MASTER );
4676 $hasRows = $dbw->selectField( 'user_properties', '1',
4677 array( 'up_user' => $userId ), __METHOD__ );
4678
4679 if ( $hasRows ) {
4680 // Only do this delete if there is something there. A very large portion of
4681 // calls to this function are for setting 'rememberpassword' for new accounts.
4682 // Doing this delete for new accounts with no rows in the table rougly causes
4683 // gap locks on [max user ID,+infinity) which causes high contention since many
4684 // updates will pile up on each other since they are for higher (newer) user IDs.
4685 $dbw->delete( 'user_properties', array( 'up_user' => $userId ), __METHOD__ );
4686 }
4687 $dbw->insert( 'user_properties', $insert_rows, __METHOD__, array( 'IGNORE' ) );
4688 }
4689
4690 /**
4691 * Provide an array of HTML5 attributes to put on an input element
4692 * intended for the user to enter a new password. This may include
4693 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
4694 *
4695 * Do *not* use this when asking the user to enter his current password!
4696 * Regardless of configuration, users may have invalid passwords for whatever
4697 * reason (e.g., they were set before requirements were tightened up).
4698 * Only use it when asking for a new password, like on account creation or
4699 * ResetPass.
4700 *
4701 * Obviously, you still need to do server-side checking.
4702 *
4703 * NOTE: A combination of bugs in various browsers means that this function
4704 * actually just returns array() unconditionally at the moment. May as
4705 * well keep it around for when the browser bugs get fixed, though.
4706 *
4707 * @todo FIXME: This does not belong here; put it in Html or Linker or somewhere
4708 *
4709 * @return array Array of HTML attributes suitable for feeding to
4710 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
4711 * That will get confused by the boolean attribute syntax used.)
4712 */
4713 public static function passwordChangeInputAttribs() {
4714 global $wgMinimalPasswordLength;
4715
4716 if ( $wgMinimalPasswordLength == 0 ) {
4717 return array();
4718 }
4719
4720 # Note that the pattern requirement will always be satisfied if the
4721 # input is empty, so we need required in all cases.
4722 #
4723 # @todo FIXME: Bug 23769: This needs to not claim the password is required
4724 # if e-mail confirmation is being used. Since HTML5 input validation
4725 # is b0rked anyway in some browsers, just return nothing. When it's
4726 # re-enabled, fix this code to not output required for e-mail
4727 # registration.
4728 #$ret = array( 'required' );
4729 $ret = array();
4730
4731 # We can't actually do this right now, because Opera 9.6 will print out
4732 # the entered password visibly in its error message! When other
4733 # browsers add support for this attribute, or Opera fixes its support,
4734 # we can add support with a version check to avoid doing this on Opera
4735 # versions where it will be a problem. Reported to Opera as
4736 # DSK-262266, but they don't have a public bug tracker for us to follow.
4737 /*
4738 if ( $wgMinimalPasswordLength > 1 ) {
4739 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
4740 $ret['title'] = wfMessage( 'passwordtooshort' )
4741 ->numParams( $wgMinimalPasswordLength )->text();
4742 }
4743 */
4744
4745 return $ret;
4746 }
4747
4748 /**
4749 * Return the list of user fields that should be selected to create
4750 * a new user object.
4751 * @return array
4752 */
4753 public static function selectFields() {
4754 return array(
4755 'user_id',
4756 'user_name',
4757 'user_real_name',
4758 'user_password',
4759 'user_newpassword',
4760 'user_newpass_time',
4761 'user_email',
4762 'user_touched',
4763 'user_token',
4764 'user_email_authenticated',
4765 'user_email_token',
4766 'user_email_token_expires',
4767 'user_registration',
4768 'user_editcount',
4769 );
4770 }
4771
4772 /**
4773 * Factory function for fatal permission-denied errors
4774 *
4775 * @since 1.22
4776 * @param string $permission User right required
4777 * @return Status
4778 */
4779 static function newFatalPermissionDeniedStatus( $permission ) {
4780 global $wgLang;
4781
4782 $groups = array_map(
4783 array( 'User', 'makeGroupLinkWiki' ),
4784 User::getGroupsWithPermission( $permission )
4785 );
4786
4787 if ( $groups ) {
4788 return Status::newFatal( 'badaccess-groups', $wgLang->commaList( $groups ), count( $groups ) );
4789 } else {
4790 return Status::newFatal( 'badaccess-group0' );
4791 }
4792 }
4793 }