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