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