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