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