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