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