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