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