Moving some optimization code into User::isAllowed instead of higher up in Title...
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 /**
3 * See user.txt
4 *
5 */
6
7 # Number of characters in user_token field
8 define( 'USER_TOKEN_LENGTH', 32 );
9
10 # Serialized record version
11 define( 'MW_USER_VERSION', 5 );
12
13 # Some punctuation to prevent editing from broken text-mangling proxies.
14 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
15
16 /**
17 * Thrown by User::setPassword() on error
18 * @addtogroup Exception
19 */
20 class PasswordError extends MWException {
21 // NOP
22 }
23
24 /**
25 * The User object encapsulates all of the user-specific settings (user_id,
26 * name, rights, password, email address, options, last login time). Client
27 * classes use the getXXX() functions to access these fields. These functions
28 * do all the work of determining whether the user is logged in,
29 * whether the requested option can be satisfied from cookies or
30 * whether a database query is needed. Most of the settings needed
31 * for rendering normal pages are set in the cookie to minimize use
32 * of the database.
33 */
34 class User {
35
36 /**
37 * A list of default user toggles, i.e. boolean user preferences that are
38 * displayed by Special:Preferences as checkboxes. This list can be
39 * extended via the UserToggles hook or $wgContLang->getExtraUserToggles().
40 */
41 static public $mToggles = array(
42 'highlightbroken',
43 'justify',
44 'hideminor',
45 'extendwatchlist',
46 'usenewrc',
47 'numberheadings',
48 'showtoolbar',
49 'editondblclick',
50 'editsection',
51 'editsectiononrightclick',
52 'showtoc',
53 'rememberpassword',
54 'editwidth',
55 'watchcreations',
56 'watchdefault',
57 'watchmoves',
58 'watchdeletion',
59 'minordefault',
60 'previewontop',
61 'previewonfirst',
62 'nocache',
63 'enotifwatchlistpages',
64 'enotifusertalkpages',
65 'enotifminoredits',
66 'enotifrevealaddr',
67 'shownumberswatching',
68 'fancysig',
69 'externaleditor',
70 'externaldiff',
71 'showjumplinks',
72 'uselivepreview',
73 'forceeditsummary',
74 'watchlisthideown',
75 'watchlisthidebots',
76 'watchlisthideminor',
77 'ccmeonemails',
78 'diffonly',
79 'showhiddencats',
80 );
81
82 /**
83 * List of member variables which are saved to the shared cache (memcached).
84 * Any operation which changes the corresponding database fields must
85 * call a cache-clearing function.
86 */
87 static $mCacheVars = array(
88 # user table
89 'mId',
90 'mName',
91 'mRealName',
92 'mPassword',
93 'mNewpassword',
94 'mNewpassTime',
95 'mEmail',
96 'mOptions',
97 'mTouched',
98 'mToken',
99 'mEmailAuthenticated',
100 'mEmailToken',
101 'mEmailTokenExpires',
102 'mRegistration',
103 'mEditCount',
104 # user_group table
105 'mGroups',
106 );
107
108 /**
109 * The cache variable declarations
110 */
111 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
112 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
113 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
114
115 /**
116 * Whether the cache variables have been loaded
117 */
118 var $mDataLoaded;
119
120 /**
121 * Initialisation data source if mDataLoaded==false. May be one of:
122 * defaults anonymous user initialised from class defaults
123 * name initialise from mName
124 * id initialise from mId
125 * session log in from cookies or session if possible
126 *
127 * Use the User::newFrom*() family of functions to set this.
128 */
129 var $mFrom;
130
131 /**
132 * Lazy-initialised variables, invalidated with clearInstanceCache
133 */
134 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
135 $mBlockreason, $mBlock, $mEffectiveGroups;
136
137 /**
138 * Lightweight constructor for anonymous user
139 * Use the User::newFrom* factory functions for other kinds of users
140 */
141 function User() {
142 $this->clearInstanceCache( 'defaults' );
143 }
144
145 /**
146 * Load the user table data for this object from the source given by mFrom
147 */
148 function load() {
149 if ( $this->mDataLoaded ) {
150 return;
151 }
152 wfProfileIn( __METHOD__ );
153
154 # Set it now to avoid infinite recursion in accessors
155 $this->mDataLoaded = true;
156
157 switch ( $this->mFrom ) {
158 case 'defaults':
159 $this->loadDefaults();
160 break;
161 case 'name':
162 $this->mId = self::idFromName( $this->mName );
163 if ( !$this->mId ) {
164 # Nonexistent user placeholder object
165 $this->loadDefaults( $this->mName );
166 } else {
167 $this->loadFromId();
168 }
169 break;
170 case 'id':
171 $this->loadFromId();
172 break;
173 case 'session':
174 $this->loadFromSession();
175 break;
176 default:
177 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
178 }
179 wfProfileOut( __METHOD__ );
180 }
181
182 /**
183 * Load user table data given mId
184 * @return false if the ID does not exist, true otherwise
185 * @private
186 */
187 function loadFromId() {
188 global $wgMemc;
189 if ( $this->mId == 0 ) {
190 $this->loadDefaults();
191 return false;
192 }
193
194 # Try cache
195 $key = wfMemcKey( 'user', 'id', $this->mId );
196 $data = $wgMemc->get( $key );
197 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
198 # Object is expired, load from DB
199 $data = false;
200 }
201
202 if ( !$data ) {
203 wfDebug( "Cache miss for user {$this->mId}\n" );
204 # Load from DB
205 if ( !$this->loadFromDatabase() ) {
206 # Can't load from ID, user is anonymous
207 return false;
208 }
209
210 $this->saveToCache();
211 } else {
212 wfDebug( "Got user {$this->mId} from cache\n" );
213 # Restore from cache
214 foreach ( self::$mCacheVars as $name ) {
215 $this->$name = $data[$name];
216 }
217 }
218 return true;
219 }
220
221 /**
222 * Save user data to the shared cache
223 */
224 function saveToCache() {
225 $this->load();
226 if ( $this->isAnon() ) {
227 // Anonymous users are uncached
228 return;
229 }
230 $data = array();
231 foreach ( self::$mCacheVars as $name ) {
232 $data[$name] = $this->$name;
233 }
234 $data['mVersion'] = MW_USER_VERSION;
235 $key = wfMemcKey( 'user', 'id', $this->mId );
236 global $wgMemc;
237 $wgMemc->set( $key, $data );
238 }
239
240 /**
241 * Static factory method for creation from username.
242 *
243 * This is slightly less efficient than newFromId(), so use newFromId() if
244 * you have both an ID and a name handy.
245 *
246 * @param string $name Username, validated by Title:newFromText()
247 * @param mixed $validate Validate username. Takes the same parameters as
248 * User::getCanonicalName(), except that true is accepted as an alias
249 * for 'valid', for BC.
250 *
251 * @return User object, or null if the username is invalid. If the username
252 * is not present in the database, the result will be a user object with
253 * a name, zero user ID and default settings.
254 * @static
255 */
256 static function newFromName( $name, $validate = 'valid' ) {
257 if ( $validate === true ) {
258 $validate = 'valid';
259 }
260 $name = self::getCanonicalName( $name, $validate );
261 if ( $name === false ) {
262 return null;
263 } else {
264 # Create unloaded user object
265 $u = new User;
266 $u->mName = $name;
267 $u->mFrom = 'name';
268 return $u;
269 }
270 }
271
272 static function newFromId( $id ) {
273 $u = new User;
274 $u->mId = $id;
275 $u->mFrom = 'id';
276 return $u;
277 }
278
279 /**
280 * Factory method to fetch whichever user has a given email confirmation code.
281 * This code is generated when an account is created or its e-mail address
282 * has changed.
283 *
284 * If the code is invalid or has expired, returns NULL.
285 *
286 * @param string $code
287 * @return User
288 * @static
289 */
290 static function newFromConfirmationCode( $code ) {
291 $dbr = wfGetDB( DB_SLAVE );
292 $id = $dbr->selectField( 'user', 'user_id', array(
293 'user_email_token' => md5( $code ),
294 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
295 ) );
296 if( $id !== false ) {
297 return User::newFromId( $id );
298 } else {
299 return null;
300 }
301 }
302
303 /**
304 * Create a new user object using data from session or cookies. If the
305 * login credentials are invalid, the result is an anonymous user.
306 *
307 * @return User
308 * @static
309 */
310 static function newFromSession() {
311 $user = new User;
312 $user->mFrom = 'session';
313 return $user;
314 }
315
316 /**
317 * Get username given an id.
318 * @param integer $id Database user id
319 * @return string Nickname of a user
320 * @static
321 */
322 static function whoIs( $id ) {
323 $dbr = wfGetDB( DB_SLAVE );
324 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
325 }
326
327 /**
328 * Get the real name of a user given their identifier
329 *
330 * @param int $id Database user id
331 * @return string Real name of a user
332 */
333 static function whoIsReal( $id ) {
334 $dbr = wfGetDB( DB_SLAVE );
335 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ );
336 }
337
338 /**
339 * Get database id given a user name
340 * @param string $name Nickname of a user
341 * @return integer|null Database user id (null: if non existent
342 * @static
343 */
344 static function idFromName( $name ) {
345 $nt = Title::newFromText( $name );
346 if( is_null( $nt ) ) {
347 # Illegal name
348 return null;
349 }
350 $dbr = wfGetDB( DB_SLAVE );
351 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
352
353 if ( $s === false ) {
354 return 0;
355 } else {
356 return $s->user_id;
357 }
358 }
359
360 /**
361 * Does the string match an anonymous IPv4 address?
362 *
363 * This function exists for username validation, in order to reject
364 * usernames which are similar in form to IP addresses. Strings such
365 * as 300.300.300.300 will return true because it looks like an IP
366 * address, despite not being strictly valid.
367 *
368 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
369 * address because the usemod software would "cloak" anonymous IP
370 * addresses like this, if we allowed accounts like this to be created
371 * new users could get the old edits of these anonymous users.
372 *
373 * @static
374 * @param string $name Nickname of a user
375 * @return bool
376 */
377 static function isIP( $name ) {
378 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || User::isIPv6($name);
379 /*return preg_match("/^
380 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
381 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
382 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
383 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
384 $/x", $name);*/
385 }
386
387 /**
388 * Check if $name is an IPv6 IP.
389 */
390 static function isIPv6($name) {
391 /*
392 * if it has any non-valid characters, it can't be a valid IPv6
393 * address.
394 */
395 if (preg_match("/[^:a-fA-F0-9]/", $name))
396 return false;
397
398 $parts = explode(":", $name);
399 if (count($parts) < 3)
400 return false;
401 foreach ($parts as $part) {
402 if (!preg_match("/^[0-9a-fA-F]{0,4}$/", $part))
403 return false;
404 }
405 return true;
406 }
407
408 /**
409 * Is the input a valid username?
410 *
411 * Checks if the input is a valid username, we don't want an empty string,
412 * an IP address, anything that containins slashes (would mess up subpages),
413 * is longer than the maximum allowed username size or doesn't begin with
414 * a capital letter.
415 *
416 * @param string $name
417 * @return bool
418 * @static
419 */
420 static function isValidUserName( $name ) {
421 global $wgContLang, $wgMaxNameChars;
422
423 if ( $name == ''
424 || User::isIP( $name )
425 || strpos( $name, '/' ) !== false
426 || strlen( $name ) > $wgMaxNameChars
427 || $name != $wgContLang->ucfirst( $name ) ) {
428 wfDebugLog( 'username', __METHOD__ .
429 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
430 return false;
431 }
432
433 // Ensure that the name can't be misresolved as a different title,
434 // such as with extra namespace keys at the start.
435 $parsed = Title::newFromText( $name );
436 if( is_null( $parsed )
437 || $parsed->getNamespace()
438 || strcmp( $name, $parsed->getPrefixedText() ) ) {
439 wfDebugLog( 'username', __METHOD__ .
440 ": '$name' invalid due to ambiguous prefixes" );
441 return false;
442 }
443
444 // Check an additional blacklist of troublemaker characters.
445 // Should these be merged into the title char list?
446 $unicodeBlacklist = '/[' .
447 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
448 '\x{00a0}' . # non-breaking space
449 '\x{2000}-\x{200f}' . # various whitespace
450 '\x{2028}-\x{202f}' . # breaks and control chars
451 '\x{3000}' . # ideographic space
452 '\x{e000}-\x{f8ff}' . # private use
453 ']/u';
454 if( preg_match( $unicodeBlacklist, $name ) ) {
455 wfDebugLog( 'username', __METHOD__ .
456 ": '$name' invalid due to blacklisted characters" );
457 return false;
458 }
459
460 return true;
461 }
462
463 /**
464 * Usernames which fail to pass this function will be blocked
465 * from user login and new account registrations, but may be used
466 * internally by batch processes.
467 *
468 * If an account already exists in this form, login will be blocked
469 * by a failure to pass this function.
470 *
471 * @param string $name
472 * @return bool
473 */
474 static function isUsableName( $name ) {
475 global $wgReservedUsernames;
476 return
477 // Must be a valid username, obviously ;)
478 self::isValidUserName( $name ) &&
479
480 // Certain names may be reserved for batch processes.
481 !in_array( $name, $wgReservedUsernames );
482 }
483
484 /**
485 * Usernames which fail to pass this function will be blocked
486 * from new account registrations, but may be used internally
487 * either by batch processes or by user accounts which have
488 * already been created.
489 *
490 * Additional character blacklisting may be added here
491 * rather than in isValidUserName() to avoid disrupting
492 * existing accounts.
493 *
494 * @param string $name
495 * @return bool
496 */
497 static function isCreatableName( $name ) {
498 return
499 self::isUsableName( $name ) &&
500
501 // Registration-time character blacklisting...
502 strpos( $name, '@' ) === false;
503 }
504
505 /**
506 * Is the input a valid password for this user?
507 *
508 * @param string $password Desired password
509 * @return bool
510 */
511 function isValidPassword( $password ) {
512 global $wgMinimalPasswordLength, $wgContLang;
513
514 $result = null;
515 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
516 return $result;
517 if( $result === false )
518 return false;
519
520 // Password needs to be long enough, and can't be the same as the username
521 return strlen( $password ) >= $wgMinimalPasswordLength
522 && $wgContLang->lc( $password ) !== $wgContLang->lc( $this->mName );
523 }
524
525 /**
526 * Does a string look like an email address?
527 *
528 * There used to be a regular expression here, it got removed because it
529 * rejected valid addresses. Actually just check if there is '@' somewhere
530 * in the given address.
531 *
532 * @todo Check for RFC 2822 compilance (bug 959)
533 *
534 * @param string $addr email address
535 * @return bool
536 */
537 public static function isValidEmailAddr( $addr ) {
538 $result = null;
539 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
540 return $result;
541 }
542
543 return strpos( $addr, '@' ) !== false;
544 }
545
546 /**
547 * Given unvalidated user input, return a canonical username, or false if
548 * the username is invalid.
549 * @param string $name
550 * @param mixed $validate Type of validation to use:
551 * false No validation
552 * 'valid' Valid for batch processes
553 * 'usable' Valid for batch processes and login
554 * 'creatable' Valid for batch processes, login and account creation
555 */
556 static function getCanonicalName( $name, $validate = 'valid' ) {
557 # Force usernames to capital
558 global $wgContLang;
559 $name = $wgContLang->ucfirst( $name );
560
561 # Reject names containing '#'; these will be cleaned up
562 # with title normalisation, but then it's too late to
563 # check elsewhere
564 if( strpos( $name, '#' ) !== false )
565 return false;
566
567 # Clean up name according to title rules
568 $t = Title::newFromText( $name );
569 if( is_null( $t ) ) {
570 return false;
571 }
572
573 # Reject various classes of invalid names
574 $name = $t->getText();
575 global $wgAuth;
576 $name = $wgAuth->getCanonicalName( $t->getText() );
577
578 switch ( $validate ) {
579 case false:
580 break;
581 case 'valid':
582 if ( !User::isValidUserName( $name ) ) {
583 $name = false;
584 }
585 break;
586 case 'usable':
587 if ( !User::isUsableName( $name ) ) {
588 $name = false;
589 }
590 break;
591 case 'creatable':
592 if ( !User::isCreatableName( $name ) ) {
593 $name = false;
594 }
595 break;
596 default:
597 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__ );
598 }
599 return $name;
600 }
601
602 /**
603 * Count the number of edits of a user
604 *
605 * It should not be static and some day should be merged as proper member function / deprecated -- domas
606 *
607 * @param int $uid The user ID to check
608 * @return int
609 * @static
610 */
611 static function edits( $uid ) {
612 wfProfileIn( __METHOD__ );
613 $dbr = wfGetDB( DB_SLAVE );
614 // check if the user_editcount field has been initialized
615 $field = $dbr->selectField(
616 'user', 'user_editcount',
617 array( 'user_id' => $uid ),
618 __METHOD__
619 );
620
621 if( $field === null ) { // it has not been initialized. do so.
622 $dbw = wfGetDB( DB_MASTER );
623 $count = $dbr->selectField(
624 'revision', 'count(*)',
625 array( 'rev_user' => $uid ),
626 __METHOD__
627 );
628 $dbw->update(
629 'user',
630 array( 'user_editcount' => $count ),
631 array( 'user_id' => $uid ),
632 __METHOD__
633 );
634 } else {
635 $count = $field;
636 }
637 wfProfileOut( __METHOD__ );
638 return $count;
639 }
640
641 /**
642 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
643 * @todo hash random numbers to improve security, like generateToken()
644 *
645 * @return string
646 * @static
647 */
648 static function randomPassword() {
649 global $wgMinimalPasswordLength;
650 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
651 $l = strlen( $pwchars ) - 1;
652
653 $pwlength = max( 7, $wgMinimalPasswordLength );
654 $digit = mt_rand(0, $pwlength - 1);
655 $np = '';
656 for ( $i = 0; $i < $pwlength; $i++ ) {
657 $np .= $i == $digit ? chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
658 }
659 return $np;
660 }
661
662 /**
663 * Set cached properties to default. Note: this no longer clears
664 * uncached lazy-initialised properties. The constructor does that instead.
665 *
666 * @private
667 */
668 function loadDefaults( $name = false ) {
669 wfProfileIn( __METHOD__ );
670
671 global $wgCookiePrefix;
672
673 $this->mId = 0;
674 $this->mName = $name;
675 $this->mRealName = '';
676 $this->mPassword = $this->mNewpassword = '';
677 $this->mNewpassTime = null;
678 $this->mEmail = '';
679 $this->mOptions = null; # Defer init
680
681 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
682 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
683 } else {
684 $this->mTouched = '0'; # Allow any pages to be cached
685 }
686
687 $this->setToken(); # Random
688 $this->mEmailAuthenticated = null;
689 $this->mEmailToken = '';
690 $this->mEmailTokenExpires = null;
691 $this->mRegistration = wfTimestamp( TS_MW );
692 $this->mGroups = array();
693
694 wfProfileOut( __METHOD__ );
695 }
696
697 /**
698 * Initialise php session
699 * @deprecated use wfSetupSession()
700 */
701 function SetupSession() {
702 wfDeprecated( __METHOD__ );
703 wfSetupSession();
704 }
705
706 /**
707 * Load user data from the session or login cookie. If there are no valid
708 * credentials, initialises the user as an anon.
709 * @return true if the user is logged in, false otherwise
710 */
711 private function loadFromSession() {
712 global $wgMemc, $wgCookiePrefix;
713
714 if ( isset( $_SESSION['wsUserID'] ) ) {
715 if ( 0 != $_SESSION['wsUserID'] ) {
716 $sId = $_SESSION['wsUserID'];
717 } else {
718 $this->loadDefaults();
719 return false;
720 }
721 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
722 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
723 $_SESSION['wsUserID'] = $sId;
724 } else {
725 $this->loadDefaults();
726 return false;
727 }
728 if ( isset( $_SESSION['wsUserName'] ) ) {
729 $sName = $_SESSION['wsUserName'];
730 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
731 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
732 $_SESSION['wsUserName'] = $sName;
733 } else {
734 $this->loadDefaults();
735 return false;
736 }
737
738 $passwordCorrect = FALSE;
739 $this->mId = $sId;
740 if ( !$this->loadFromId() ) {
741 # Not a valid ID, loadFromId has switched the object to anon for us
742 return false;
743 }
744
745 if ( isset( $_SESSION['wsToken'] ) ) {
746 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
747 $from = 'session';
748 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
749 $passwordCorrect = $this->mToken == $_COOKIE["{$wgCookiePrefix}Token"];
750 $from = 'cookie';
751 } else {
752 # No session or persistent login cookie
753 $this->loadDefaults();
754 return false;
755 }
756
757 if ( ( $sName == $this->mName ) && $passwordCorrect ) {
758 $_SESSION['wsToken'] = $this->mToken;
759 wfDebug( "Logged in from $from\n" );
760 return true;
761 } else {
762 # Invalid credentials
763 wfDebug( "Can't log in from $from, invalid credentials\n" );
764 $this->loadDefaults();
765 return false;
766 }
767 }
768
769 /**
770 * Load user and user_group data from the database
771 * $this->mId must be set, this is how the user is identified.
772 *
773 * @return true if the user exists, false if the user is anonymous
774 * @private
775 */
776 function loadFromDatabase() {
777 # Paranoia
778 $this->mId = intval( $this->mId );
779
780 /** Anonymous user */
781 if( !$this->mId ) {
782 $this->loadDefaults();
783 return false;
784 }
785
786 $dbr = wfGetDB( DB_MASTER );
787 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
788
789 if ( $s !== false ) {
790 # Initialise user table data
791 $this->mName = $s->user_name;
792 $this->mRealName = $s->user_real_name;
793 $this->mPassword = $s->user_password;
794 $this->mNewpassword = $s->user_newpassword;
795 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $s->user_newpass_time );
796 $this->mEmail = $s->user_email;
797 $this->decodeOptions( $s->user_options );
798 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
799 $this->mToken = $s->user_token;
800 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $s->user_email_authenticated );
801 $this->mEmailToken = $s->user_email_token;
802 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $s->user_email_token_expires );
803 $this->mRegistration = wfTimestampOrNull( TS_MW, $s->user_registration );
804 $this->mEditCount = $s->user_editcount;
805 $this->getEditCount(); // revalidation for nulls
806
807 # Load group data
808 $res = $dbr->select( 'user_groups',
809 array( 'ug_group' ),
810 array( 'ug_user' => $this->mId ),
811 __METHOD__ );
812 $this->mGroups = array();
813 while( $row = $dbr->fetchObject( $res ) ) {
814 $this->mGroups[] = $row->ug_group;
815 }
816 return true;
817 } else {
818 # Invalid user_id
819 $this->mId = 0;
820 $this->loadDefaults();
821 return false;
822 }
823 }
824
825 /**
826 * Clear various cached data stored in this object.
827 * @param string $reloadFrom Reload user and user_groups table data from a
828 * given source. May be "name", "id", "defaults", "session" or false for
829 * no reload.
830 */
831 function clearInstanceCache( $reloadFrom = false ) {
832 $this->mNewtalk = -1;
833 $this->mDatePreference = null;
834 $this->mBlockedby = -1; # Unset
835 $this->mHash = false;
836 $this->mSkin = null;
837 $this->mRights = null;
838 $this->mEffectiveGroups = null;
839
840 if ( $reloadFrom ) {
841 $this->mDataLoaded = false;
842 $this->mFrom = $reloadFrom;
843 }
844 }
845
846 /**
847 * Combine the language default options with any site-specific options
848 * and add the default language variants.
849 * Not really private cause it's called by Language class
850 * @return array
851 * @static
852 * @private
853 */
854 static function getDefaultOptions() {
855 global $wgNamespacesToBeSearchedDefault;
856 /**
857 * Site defaults will override the global/language defaults
858 */
859 global $wgDefaultUserOptions, $wgContLang;
860 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
861
862 /**
863 * default language setting
864 */
865 $variant = $wgContLang->getPreferredVariant( false );
866 $defOpt['variant'] = $variant;
867 $defOpt['language'] = $variant;
868
869 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
870 $defOpt['searchNs'.$nsnum] = $val;
871 }
872 return $defOpt;
873 }
874
875 /**
876 * Get a given default option value.
877 *
878 * @param string $opt
879 * @return string
880 * @static
881 * @public
882 */
883 function getDefaultOption( $opt ) {
884 $defOpts = User::getDefaultOptions();
885 if( isset( $defOpts[$opt] ) ) {
886 return $defOpts[$opt];
887 } else {
888 return '';
889 }
890 }
891
892 /**
893 * Get a list of user toggle names
894 * @return array
895 */
896 static function getToggles() {
897 global $wgContLang;
898 $extraToggles = array();
899 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
900 return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
901 }
902
903
904 /**
905 * Get blocking information
906 * @private
907 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
908 * non-critical checks are done against slaves. Check when actually saving should be done against
909 * master.
910 */
911 function getBlockedStatus( $bFromSlave = true ) {
912 global $wgEnableSorbs, $wgProxyWhitelist;
913
914 if ( -1 != $this->mBlockedby ) {
915 wfDebug( "User::getBlockedStatus: already loaded.\n" );
916 return;
917 }
918
919 wfProfileIn( __METHOD__ );
920 wfDebug( __METHOD__.": checking...\n" );
921
922 $this->mBlockedby = 0;
923 $this->mHideName = 0;
924 $ip = wfGetIP();
925
926 if ($this->isAllowed( 'ipblock-exempt' ) ) {
927 # Exempt from all types of IP-block
928 $ip = '';
929 }
930
931 # User/IP blocking
932 $this->mBlock = new Block();
933 $this->mBlock->fromMaster( !$bFromSlave );
934 if ( $this->mBlock->load( $ip , $this->mId ) ) {
935 wfDebug( __METHOD__.": Found block.\n" );
936 $this->mBlockedby = $this->mBlock->mBy;
937 $this->mBlockreason = $this->mBlock->mReason;
938 $this->mHideName = $this->mBlock->mHideName;
939 if ( $this->isLoggedIn() ) {
940 $this->spreadBlock();
941 }
942 } else {
943 $this->mBlock = null;
944 wfDebug( __METHOD__.": No block.\n" );
945 }
946
947 # Proxy blocking
948 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
949
950 # Local list
951 if ( wfIsLocallyBlockedProxy( $ip ) ) {
952 $this->mBlockedby = wfMsg( 'proxyblocker' );
953 $this->mBlockreason = wfMsg( 'proxyblockreason' );
954 }
955
956 # DNSBL
957 if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
958 if ( $this->inSorbsBlacklist( $ip ) ) {
959 $this->mBlockedby = wfMsg( 'sorbs' );
960 $this->mBlockreason = wfMsg( 'sorbsreason' );
961 }
962 }
963 }
964
965 # Extensions
966 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
967
968 wfProfileOut( __METHOD__ );
969 }
970
971 function inSorbsBlacklist( $ip ) {
972 global $wgEnableSorbs, $wgSorbsUrl;
973
974 return $wgEnableSorbs &&
975 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
976 }
977
978 function inDnsBlacklist( $ip, $base ) {
979 wfProfileIn( __METHOD__ );
980
981 $found = false;
982 $host = '';
983
984 $m = array();
985 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
986 # Make hostname
987 for ( $i=4; $i>=1; $i-- ) {
988 $host .= $m[$i] . '.';
989 }
990 $host .= $base;
991
992 # Send query
993 $ipList = gethostbynamel( $host );
994
995 if ( $ipList ) {
996 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
997 $found = true;
998 } else {
999 wfDebug( "Requested $host, not found in $base.\n" );
1000 }
1001 }
1002
1003 wfProfileOut( __METHOD__ );
1004 return $found;
1005 }
1006
1007 /**
1008 * Is this user subject to rate limiting?
1009 *
1010 * @return bool
1011 */
1012 public function isPingLimitable() {
1013 global $wgRateLimitsExcludedGroups;
1014 return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) == array();
1015 }
1016
1017 /**
1018 * Primitive rate limits: enforce maximum actions per time period
1019 * to put a brake on flooding.
1020 *
1021 * Note: when using a shared cache like memcached, IP-address
1022 * last-hit counters will be shared across wikis.
1023 *
1024 * @return bool true if a rate limiter was tripped
1025 * @public
1026 */
1027 function pingLimiter( $action='edit' ) {
1028
1029 # Call the 'PingLimiter' hook
1030 $result = false;
1031 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1032 return $result;
1033 }
1034
1035 global $wgRateLimits;
1036 if( !isset( $wgRateLimits[$action] ) ) {
1037 return false;
1038 }
1039
1040 # Some groups shouldn't trigger the ping limiter, ever
1041 if( !$this->isPingLimitable() )
1042 return false;
1043
1044 global $wgMemc, $wgRateLimitLog;
1045 wfProfileIn( __METHOD__ );
1046
1047 $limits = $wgRateLimits[$action];
1048 $keys = array();
1049 $id = $this->getId();
1050 $ip = wfGetIP();
1051
1052 if( isset( $limits['anon'] ) && $id == 0 ) {
1053 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1054 }
1055
1056 if( isset( $limits['user'] ) && $id != 0 ) {
1057 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
1058 }
1059 if( $this->isNewbie() ) {
1060 if( isset( $limits['newbie'] ) && $id != 0 ) {
1061 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1062 }
1063 if( isset( $limits['ip'] ) ) {
1064 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1065 }
1066 $matches = array();
1067 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1068 $subnet = $matches[1];
1069 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1070 }
1071 }
1072
1073 $triggered = false;
1074 foreach( $keys as $key => $limit ) {
1075 list( $max, $period ) = $limit;
1076 $summary = "(limit $max in {$period}s)";
1077 $count = $wgMemc->get( $key );
1078 if( $count ) {
1079 if( $count > $max ) {
1080 wfDebug( __METHOD__.": tripped! $key at $count $summary\n" );
1081 if( $wgRateLimitLog ) {
1082 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1083 }
1084 $triggered = true;
1085 } else {
1086 wfDebug( __METHOD__.": ok. $key at $count $summary\n" );
1087 }
1088 } else {
1089 wfDebug( __METHOD__.": adding record for $key $summary\n" );
1090 $wgMemc->add( $key, 1, intval( $period ) );
1091 }
1092 $wgMemc->incr( $key );
1093 }
1094
1095 wfProfileOut( __METHOD__ );
1096 return $triggered;
1097 }
1098
1099 /**
1100 * Check if user is blocked
1101 * @return bool True if blocked, false otherwise
1102 */
1103 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1104 wfDebug( "User::isBlocked: enter\n" );
1105 $this->getBlockedStatus( $bFromSlave );
1106 return $this->mBlockedby !== 0;
1107 }
1108
1109 /**
1110 * Check if user is blocked from editing a particular article
1111 */
1112 function isBlockedFrom( $title, $bFromSlave = false ) {
1113 global $wgBlockAllowsUTEdit;
1114 wfProfileIn( __METHOD__ );
1115 wfDebug( __METHOD__.": enter\n" );
1116
1117 wfDebug( __METHOD__.": asking isBlocked()\n" );
1118 $blocked = $this->isBlocked( $bFromSlave );
1119 # If a user's name is suppressed, they cannot make edits anywhere
1120 if ( !$this->mHideName && $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1121 $title->getNamespace() == NS_USER_TALK ) {
1122 $blocked = false;
1123 wfDebug( __METHOD__.": self-talk page, ignoring any blocks\n" );
1124 }
1125 wfProfileOut( __METHOD__ );
1126 return $blocked;
1127 }
1128
1129 /**
1130 * Get name of blocker
1131 * @return string name of blocker
1132 */
1133 function blockedBy() {
1134 $this->getBlockedStatus();
1135 return $this->mBlockedby;
1136 }
1137
1138 /**
1139 * Get blocking reason
1140 * @return string Blocking reason
1141 */
1142 function blockedFor() {
1143 $this->getBlockedStatus();
1144 return $this->mBlockreason;
1145 }
1146
1147 /**
1148 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1149 */
1150 function getID() {
1151 if( $this->mId === null and $this->mName !== null
1152 and User::isIP( $this->mName ) ) {
1153 // Special case, we know the user is anonymous
1154 return 0;
1155 } elseif( $this->mId === null ) {
1156 // Don't load if this was initialized from an ID
1157 $this->load();
1158 }
1159 return $this->mId;
1160 }
1161
1162 /**
1163 * Set the user and reload all fields according to that ID
1164 * @deprecated use User::newFromId()
1165 */
1166 function setID( $v ) {
1167 wfDeprecated( __METHOD__ );
1168 $this->mId = $v;
1169 $this->clearInstanceCache( 'id' );
1170 }
1171
1172 /**
1173 * Get the user name, or the IP for anons
1174 */
1175 function getName() {
1176 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1177 # Special case optimisation
1178 return $this->mName;
1179 } else {
1180 $this->load();
1181 if ( $this->mName === false ) {
1182 # Clean up IPs
1183 $this->mName = IP::sanitizeIP( wfGetIP() );
1184 }
1185 return $this->mName;
1186 }
1187 }
1188
1189 /**
1190 * Set the user name.
1191 *
1192 * This does not reload fields from the database according to the given
1193 * name. Rather, it is used to create a temporary "nonexistent user" for
1194 * later addition to the database. It can also be used to set the IP
1195 * address for an anonymous user to something other than the current
1196 * remote IP.
1197 *
1198 * User::newFromName() has rougly the same function, when the named user
1199 * does not exist.
1200 */
1201 function setName( $str ) {
1202 $this->load();
1203 $this->mName = $str;
1204 }
1205
1206 /**
1207 * Return the title dbkey form of the name, for eg user pages.
1208 * @return string
1209 * @public
1210 */
1211 function getTitleKey() {
1212 return str_replace( ' ', '_', $this->getName() );
1213 }
1214
1215 function getNewtalk() {
1216 $this->load();
1217
1218 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1219 if( $this->mNewtalk === -1 ) {
1220 $this->mNewtalk = false; # reset talk page status
1221
1222 # Check memcached separately for anons, who have no
1223 # entire User object stored in there.
1224 if( !$this->mId ) {
1225 global $wgMemc;
1226 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1227 $newtalk = $wgMemc->get( $key );
1228 if( strval( $newtalk ) !== '' ) {
1229 $this->mNewtalk = (bool)$newtalk;
1230 } else {
1231 // Since we are caching this, make sure it is up to date by getting it
1232 // from the master
1233 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1234 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1235 }
1236 } else {
1237 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1238 }
1239 }
1240
1241 return (bool)$this->mNewtalk;
1242 }
1243
1244 /**
1245 * Return the talk page(s) this user has new messages on.
1246 */
1247 function getNewMessageLinks() {
1248 $talks = array();
1249 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1250 return $talks;
1251
1252 if (!$this->getNewtalk())
1253 return array();
1254 $up = $this->getUserPage();
1255 $utp = $up->getTalkPage();
1256 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1257 }
1258
1259
1260 /**
1261 * Perform a user_newtalk check, uncached.
1262 * Use getNewtalk for a cached check.
1263 *
1264 * @param string $field
1265 * @param mixed $id
1266 * @param bool $fromMaster True to fetch from the master, false for a slave
1267 * @return bool
1268 * @private
1269 */
1270 function checkNewtalk( $field, $id, $fromMaster = false ) {
1271 if ( $fromMaster ) {
1272 $db = wfGetDB( DB_MASTER );
1273 } else {
1274 $db = wfGetDB( DB_SLAVE );
1275 }
1276 $ok = $db->selectField( 'user_newtalk', $field,
1277 array( $field => $id ), __METHOD__ );
1278 return $ok !== false;
1279 }
1280
1281 /**
1282 * Add or update the
1283 * @param string $field
1284 * @param mixed $id
1285 * @private
1286 */
1287 function updateNewtalk( $field, $id ) {
1288 $dbw = wfGetDB( DB_MASTER );
1289 $dbw->insert( 'user_newtalk',
1290 array( $field => $id ),
1291 __METHOD__,
1292 'IGNORE' );
1293 if ( $dbw->affectedRows() ) {
1294 wfDebug( __METHOD__.": set on ($field, $id)\n" );
1295 return true;
1296 } else {
1297 wfDebug( __METHOD__." already set ($field, $id)\n" );
1298 return false;
1299 }
1300 }
1301
1302 /**
1303 * Clear the new messages flag for the given user
1304 * @param string $field
1305 * @param mixed $id
1306 * @private
1307 */
1308 function deleteNewtalk( $field, $id ) {
1309 $dbw = wfGetDB( DB_MASTER );
1310 $dbw->delete( 'user_newtalk',
1311 array( $field => $id ),
1312 __METHOD__ );
1313 if ( $dbw->affectedRows() ) {
1314 wfDebug( __METHOD__.": killed on ($field, $id)\n" );
1315 return true;
1316 } else {
1317 wfDebug( __METHOD__.": already gone ($field, $id)\n" );
1318 return false;
1319 }
1320 }
1321
1322 /**
1323 * Update the 'You have new messages!' status.
1324 * @param bool $val
1325 */
1326 function setNewtalk( $val ) {
1327 if( wfReadOnly() ) {
1328 return;
1329 }
1330
1331 $this->load();
1332 $this->mNewtalk = $val;
1333
1334 if( $this->isAnon() ) {
1335 $field = 'user_ip';
1336 $id = $this->getName();
1337 } else {
1338 $field = 'user_id';
1339 $id = $this->getId();
1340 }
1341 global $wgMemc;
1342
1343 if( $val ) {
1344 $changed = $this->updateNewtalk( $field, $id );
1345 } else {
1346 $changed = $this->deleteNewtalk( $field, $id );
1347 }
1348
1349 if( $this->isAnon() ) {
1350 // Anons have a separate memcached space, since
1351 // user records aren't kept for them.
1352 $key = wfMemcKey( 'newtalk', 'ip', $id );
1353 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1354 }
1355 if ( $changed ) {
1356 $this->invalidateCache();
1357 }
1358 }
1359
1360 /**
1361 * Generate a current or new-future timestamp to be stored in the
1362 * user_touched field when we update things.
1363 */
1364 private static function newTouchedTimestamp() {
1365 global $wgClockSkewFudge;
1366 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1367 }
1368
1369 /**
1370 * Clear user data from memcached.
1371 * Use after applying fun updates to the database; caller's
1372 * responsibility to update user_touched if appropriate.
1373 *
1374 * Called implicitly from invalidateCache() and saveSettings().
1375 */
1376 private function clearSharedCache() {
1377 if( $this->mId ) {
1378 global $wgMemc;
1379 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1380 }
1381 }
1382
1383 /**
1384 * Immediately touch the user data cache for this account.
1385 * Updates user_touched field, and removes account data from memcached
1386 * for reload on the next hit.
1387 */
1388 function invalidateCache() {
1389 $this->load();
1390 if( $this->mId ) {
1391 $this->mTouched = self::newTouchedTimestamp();
1392
1393 $dbw = wfGetDB( DB_MASTER );
1394 $dbw->update( 'user',
1395 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1396 array( 'user_id' => $this->mId ),
1397 __METHOD__ );
1398
1399 $this->clearSharedCache();
1400 }
1401 }
1402
1403 function validateCache( $timestamp ) {
1404 $this->load();
1405 return ($timestamp >= $this->mTouched);
1406 }
1407
1408 /**
1409 * Encrypt a password.
1410 * It can eventually salt a password.
1411 * @see User::addSalt()
1412 * @param string $p clear Password.
1413 * @return string Encrypted password.
1414 */
1415 function encryptPassword( $p ) {
1416 $this->load();
1417 return wfEncryptPassword( $this->mId, $p );
1418 }
1419
1420 /**
1421 * Set the password and reset the random token
1422 * Calls through to authentication plugin if necessary;
1423 * will have no effect if the auth plugin refuses to
1424 * pass the change through or if the legal password
1425 * checks fail.
1426 *
1427 * As a special case, setting the password to null
1428 * wipes it, so the account cannot be logged in until
1429 * a new password is set, for instance via e-mail.
1430 *
1431 * @param string $str
1432 * @throws PasswordError on failure
1433 */
1434 function setPassword( $str ) {
1435 global $wgAuth;
1436
1437 if( $str !== null ) {
1438 if( !$wgAuth->allowPasswordChange() ) {
1439 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1440 }
1441
1442 if( !$this->isValidPassword( $str ) ) {
1443 global $wgMinimalPasswordLength;
1444 throw new PasswordError( wfMsg( 'passwordtooshort',
1445 $wgMinimalPasswordLength ) );
1446 }
1447 }
1448
1449 if( !$wgAuth->setPassword( $this, $str ) ) {
1450 throw new PasswordError( wfMsg( 'externaldberror' ) );
1451 }
1452
1453 $this->setInternalPassword( $str );
1454
1455 return true;
1456 }
1457
1458 /**
1459 * Set the password and reset the random token no matter
1460 * what.
1461 *
1462 * @param string $str
1463 */
1464 function setInternalPassword( $str ) {
1465 $this->load();
1466 $this->setToken();
1467
1468 if( $str === null ) {
1469 // Save an invalid hash...
1470 $this->mPassword = '';
1471 } else {
1472 $this->mPassword = $this->encryptPassword( $str );
1473 }
1474 $this->mNewpassword = '';
1475 $this->mNewpassTime = null;
1476 }
1477 /**
1478 * Set the random token (used for persistent authentication)
1479 * Called from loadDefaults() among other places.
1480 * @private
1481 */
1482 function setToken( $token = false ) {
1483 global $wgSecretKey, $wgProxyKey;
1484 $this->load();
1485 if ( !$token ) {
1486 if ( $wgSecretKey ) {
1487 $key = $wgSecretKey;
1488 } elseif ( $wgProxyKey ) {
1489 $key = $wgProxyKey;
1490 } else {
1491 $key = microtime();
1492 }
1493 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1494 } else {
1495 $this->mToken = $token;
1496 }
1497 }
1498
1499 function setCookiePassword( $str ) {
1500 $this->load();
1501 $this->mCookiePassword = md5( $str );
1502 }
1503
1504 /**
1505 * Set the password for a password reminder or new account email
1506 * Sets the user_newpass_time field if $throttle is true
1507 */
1508 function setNewpassword( $str, $throttle = true ) {
1509 $this->load();
1510 $this->mNewpassword = $this->encryptPassword( $str );
1511 if ( $throttle ) {
1512 $this->mNewpassTime = wfTimestampNow();
1513 }
1514 }
1515
1516 /**
1517 * Returns true if a password reminder email has already been sent within
1518 * the last $wgPasswordReminderResendTime hours
1519 */
1520 function isPasswordReminderThrottled() {
1521 global $wgPasswordReminderResendTime;
1522 $this->load();
1523 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1524 return false;
1525 }
1526 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1527 return time() < $expiry;
1528 }
1529
1530 function getEmail() {
1531 $this->load();
1532 return $this->mEmail;
1533 }
1534
1535 function getEmailAuthenticationTimestamp() {
1536 $this->load();
1537 return $this->mEmailAuthenticated;
1538 }
1539
1540 function setEmail( $str ) {
1541 $this->load();
1542 $this->mEmail = $str;
1543 }
1544
1545 function getRealName() {
1546 $this->load();
1547 return $this->mRealName;
1548 }
1549
1550 function setRealName( $str ) {
1551 $this->load();
1552 $this->mRealName = $str;
1553 }
1554
1555 /**
1556 * @param string $oname The option to check
1557 * @param string $defaultOverride A default value returned if the option does not exist
1558 * @return string
1559 */
1560 function getOption( $oname, $defaultOverride = '' ) {
1561 $this->load();
1562
1563 if ( is_null( $this->mOptions ) ) {
1564 if($defaultOverride != '') {
1565 return $defaultOverride;
1566 }
1567 $this->mOptions = User::getDefaultOptions();
1568 }
1569
1570 if ( array_key_exists( $oname, $this->mOptions ) ) {
1571 return trim( $this->mOptions[$oname] );
1572 } else {
1573 return $defaultOverride;
1574 }
1575 }
1576
1577 /**
1578 * Get the user's date preference, including some important migration for
1579 * old user rows.
1580 */
1581 function getDatePreference() {
1582 if ( is_null( $this->mDatePreference ) ) {
1583 global $wgLang;
1584 $value = $this->getOption( 'date' );
1585 $map = $wgLang->getDatePreferenceMigrationMap();
1586 if ( isset( $map[$value] ) ) {
1587 $value = $map[$value];
1588 }
1589 $this->mDatePreference = $value;
1590 }
1591 return $this->mDatePreference;
1592 }
1593
1594 /**
1595 * @param string $oname The option to check
1596 * @return bool False if the option is not selected, true if it is
1597 */
1598 function getBoolOption( $oname ) {
1599 return (bool)$this->getOption( $oname );
1600 }
1601
1602 /**
1603 * Get an option as an integer value from the source string.
1604 * @param string $oname The option to check
1605 * @param int $default Optional value to return if option is unset/blank.
1606 * @return int
1607 */
1608 function getIntOption( $oname, $default=0 ) {
1609 $val = $this->getOption( $oname );
1610 if( $val == '' ) {
1611 $val = $default;
1612 }
1613 return intval( $val );
1614 }
1615
1616 function setOption( $oname, $val ) {
1617 $this->load();
1618 if ( is_null( $this->mOptions ) ) {
1619 $this->mOptions = User::getDefaultOptions();
1620 }
1621 if ( $oname == 'skin' ) {
1622 # Clear cached skin, so the new one displays immediately in Special:Preferences
1623 unset( $this->mSkin );
1624 }
1625 // Filter out any newlines that may have passed through input validation.
1626 // Newlines are used to separate items in the options blob.
1627 $val = str_replace( "\r\n", "\n", $val );
1628 $val = str_replace( "\r", "\n", $val );
1629 $val = str_replace( "\n", " ", $val );
1630 $this->mOptions[$oname] = $val;
1631 }
1632
1633 function getRights() {
1634 if ( is_null( $this->mRights ) ) {
1635 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
1636 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
1637 }
1638 return $this->mRights;
1639 }
1640
1641 /**
1642 * Get the list of explicit group memberships this user has.
1643 * The implicit * and user groups are not included.
1644 * @return array of strings
1645 */
1646 function getGroups() {
1647 $this->load();
1648 return $this->mGroups;
1649 }
1650
1651 /**
1652 * Get the list of implicit group memberships this user has.
1653 * This includes all explicit groups, plus 'user' if logged in,
1654 * '*' for all accounts and autopromoted groups
1655 * @param boolean $recache Don't use the cache
1656 * @return array of strings
1657 */
1658 function getEffectiveGroups( $recache = false ) {
1659 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
1660 $this->load();
1661 $this->mEffectiveGroups = $this->mGroups;
1662 $this->mEffectiveGroups[] = '*';
1663 if( $this->mId ) {
1664 $this->mEffectiveGroups[] = 'user';
1665
1666 $this->mEffectiveGroups = array_unique( array_merge(
1667 $this->mEffectiveGroups,
1668 Autopromote::getAutopromoteGroups( $this )
1669 ) );
1670
1671 # Hook for additional groups
1672 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
1673 }
1674 }
1675 return $this->mEffectiveGroups;
1676 }
1677
1678 /* Return the edit count for the user. This is where User::edits should have been */
1679 function getEditCount() {
1680 if ($this->mId) {
1681 if ( !isset( $this->mEditCount ) ) {
1682 /* Populate the count, if it has not been populated yet */
1683 $this->mEditCount = User::edits($this->mId);
1684 }
1685 return $this->mEditCount;
1686 } else {
1687 /* nil */
1688 return null;
1689 }
1690 }
1691
1692 /**
1693 * Add the user to the given group.
1694 * This takes immediate effect.
1695 * @param string $group
1696 */
1697 function addGroup( $group ) {
1698 $this->load();
1699 $dbw = wfGetDB( DB_MASTER );
1700 if( $this->getId() ) {
1701 $dbw->insert( 'user_groups',
1702 array(
1703 'ug_user' => $this->getID(),
1704 'ug_group' => $group,
1705 ),
1706 'User::addGroup',
1707 array( 'IGNORE' ) );
1708 }
1709
1710 $this->mGroups[] = $group;
1711 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1712
1713 $this->invalidateCache();
1714 }
1715
1716 /**
1717 * Remove the user from the given group.
1718 * This takes immediate effect.
1719 * @param string $group
1720 */
1721 function removeGroup( $group ) {
1722 $this->load();
1723 $dbw = wfGetDB( DB_MASTER );
1724 $dbw->delete( 'user_groups',
1725 array(
1726 'ug_user' => $this->getID(),
1727 'ug_group' => $group,
1728 ),
1729 'User::removeGroup' );
1730
1731 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
1732 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1733
1734 $this->invalidateCache();
1735 }
1736
1737
1738 /**
1739 * A more legible check for non-anonymousness.
1740 * Returns true if the user is not an anonymous visitor.
1741 *
1742 * @return bool
1743 */
1744 function isLoggedIn() {
1745 return $this->getID() != 0;
1746 }
1747
1748 /**
1749 * A more legible check for anonymousness.
1750 * Returns true if the user is an anonymous visitor.
1751 *
1752 * @return bool
1753 */
1754 function isAnon() {
1755 return !$this->isLoggedIn();
1756 }
1757
1758 /**
1759 * Whether the user is a bot
1760 * @deprecated
1761 */
1762 function isBot() {
1763 wfDeprecated( __METHOD__ );
1764 return $this->isAllowed( 'bot' );
1765 }
1766
1767 /**
1768 * Check if user is allowed to access a feature / make an action
1769 * @param string $action Action to be checked
1770 * @return boolean True: action is allowed, False: action should not be allowed
1771 */
1772 function isAllowed($action='') {
1773 global $wgGroupPermissions;
1774 if( $action === '' ) {
1775 // In the spirit of DWIM
1776 return true;
1777 }
1778 if( !empty( $wgGroupPermissions['*'][$action] ) ) {
1779 # Permissions are additive, so there's no need to unstub the User
1780 # object in this case.
1781 return true;
1782 }
1783
1784 return in_array( $action, $this->getRights() );
1785 }
1786
1787 /**
1788 * Load a skin if it doesn't exist or return it
1789 * @todo FIXME : need to check the old failback system [AV]
1790 */
1791 function &getSkin() {
1792 global $wgRequest;
1793 if ( ! isset( $this->mSkin ) ) {
1794 wfProfileIn( __METHOD__ );
1795
1796 # get the user skin
1797 $userSkin = $this->getOption( 'skin' );
1798 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1799
1800 $this->mSkin =& Skin::newFromKey( $userSkin );
1801 wfProfileOut( __METHOD__ );
1802 }
1803 return $this->mSkin;
1804 }
1805
1806 /**#@+
1807 * @param string $title Article title to look at
1808 */
1809
1810 /**
1811 * Check watched status of an article
1812 * @return bool True if article is watched
1813 */
1814 function isWatched( $title ) {
1815 $wl = WatchedItem::fromUserTitle( $this, $title );
1816 return $wl->isWatched();
1817 }
1818
1819 /**
1820 * Watch an article
1821 */
1822 function addWatch( $title ) {
1823 $wl = WatchedItem::fromUserTitle( $this, $title );
1824 $wl->addWatch();
1825 $this->invalidateCache();
1826 }
1827
1828 /**
1829 * Stop watching an article
1830 */
1831 function removeWatch( $title ) {
1832 $wl = WatchedItem::fromUserTitle( $this, $title );
1833 $wl->removeWatch();
1834 $this->invalidateCache();
1835 }
1836
1837 /**
1838 * Clear the user's notification timestamp for the given title.
1839 * If e-notif e-mails are on, they will receive notification mails on
1840 * the next change of the page if it's watched etc.
1841 */
1842 function clearNotification( &$title ) {
1843 global $wgUser, $wgUseEnotif;
1844
1845 # Do nothing if the database is locked to writes
1846 if( wfReadOnly() ) {
1847 return;
1848 }
1849
1850 if ($title->getNamespace() == NS_USER_TALK &&
1851 $title->getText() == $this->getName() ) {
1852 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1853 return;
1854 $this->setNewtalk( false );
1855 }
1856
1857 if( !$wgUseEnotif ) {
1858 return;
1859 }
1860
1861 if( $this->isAnon() ) {
1862 // Nothing else to do...
1863 return;
1864 }
1865
1866 // Only update the timestamp if the page is being watched.
1867 // The query to find out if it is watched is cached both in memcached and per-invocation,
1868 // and when it does have to be executed, it can be on a slave
1869 // If this is the user's newtalk page, we always update the timestamp
1870 if ($title->getNamespace() == NS_USER_TALK &&
1871 $title->getText() == $wgUser->getName())
1872 {
1873 $watched = true;
1874 } elseif ( $this->getID() == $wgUser->getID() ) {
1875 $watched = $title->userIsWatching();
1876 } else {
1877 $watched = true;
1878 }
1879
1880 // If the page is watched by the user (or may be watched), update the timestamp on any
1881 // any matching rows
1882 if ( $watched ) {
1883 $dbw = wfGetDB( DB_MASTER );
1884 $dbw->update( 'watchlist',
1885 array( /* SET */
1886 'wl_notificationtimestamp' => NULL
1887 ), array( /* WHERE */
1888 'wl_title' => $title->getDBkey(),
1889 'wl_namespace' => $title->getNamespace(),
1890 'wl_user' => $this->getID()
1891 ), 'User::clearLastVisited'
1892 );
1893 }
1894 }
1895
1896 /**#@-*/
1897
1898 /**
1899 * Resets all of the given user's page-change notification timestamps.
1900 * If e-notif e-mails are on, they will receive notification mails on
1901 * the next change of any watched page.
1902 *
1903 * @param int $currentUser user ID number
1904 * @public
1905 */
1906 function clearAllNotifications( $currentUser ) {
1907 global $wgUseEnotif;
1908 if ( !$wgUseEnotif ) {
1909 $this->setNewtalk( false );
1910 return;
1911 }
1912 if( $currentUser != 0 ) {
1913
1914 $dbw = wfGetDB( DB_MASTER );
1915 $dbw->update( 'watchlist',
1916 array( /* SET */
1917 'wl_notificationtimestamp' => NULL
1918 ), array( /* WHERE */
1919 'wl_user' => $currentUser
1920 ), __METHOD__
1921 );
1922
1923 # we also need to clear here the "you have new message" notification for the own user_talk page
1924 # This is cleared one page view later in Article::viewUpdates();
1925 }
1926 }
1927
1928 /**
1929 * @private
1930 * @return string Encoding options
1931 */
1932 function encodeOptions() {
1933 $this->load();
1934 if ( is_null( $this->mOptions ) ) {
1935 $this->mOptions = User::getDefaultOptions();
1936 }
1937 $a = array();
1938 foreach ( $this->mOptions as $oname => $oval ) {
1939 array_push( $a, $oname.'='.$oval );
1940 }
1941 $s = implode( "\n", $a );
1942 return $s;
1943 }
1944
1945 /**
1946 * @private
1947 */
1948 function decodeOptions( $str ) {
1949 $this->mOptions = array();
1950 $a = explode( "\n", $str );
1951 foreach ( $a as $s ) {
1952 $m = array();
1953 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1954 $this->mOptions[$m[1]] = $m[2];
1955 }
1956 }
1957 }
1958
1959 function setCookies() {
1960 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1961 $this->load();
1962 if ( 0 == $this->mId ) return;
1963 $exp = time() + $wgCookieExpiration;
1964
1965 $_SESSION['wsUserID'] = $this->mId;
1966 setcookie( $wgCookiePrefix.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1967
1968 $_SESSION['wsUserName'] = $this->getName();
1969 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1970
1971 $_SESSION['wsToken'] = $this->mToken;
1972 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1973 setcookie( $wgCookiePrefix.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1974 } else {
1975 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1976 }
1977 }
1978
1979 /**
1980 * Logout user.
1981 */
1982 function logout() {
1983 global $wgUser;
1984 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
1985 $this->doLogout();
1986 wfRunHooks( 'UserLogoutComplete', array(&$wgUser) );
1987 }
1988 }
1989
1990 /**
1991 * Really logout user
1992 * Clears the cookies and session, resets the instance cache
1993 */
1994 function doLogout() {
1995 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1996 $this->clearInstanceCache( 'defaults' );
1997
1998 $_SESSION['wsUserID'] = 0;
1999
2000 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2001 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2002
2003 # Remember when user logged out, to prevent seeing cached pages
2004 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
2005 }
2006
2007 /**
2008 * Save object settings into database
2009 * @todo Only rarely do all these fields need to be set!
2010 */
2011 function saveSettings() {
2012 $this->load();
2013 if ( wfReadOnly() ) { return; }
2014 if ( 0 == $this->mId ) { return; }
2015
2016 $this->mTouched = self::newTouchedTimestamp();
2017
2018 $dbw = wfGetDB( DB_MASTER );
2019 $dbw->update( 'user',
2020 array( /* SET */
2021 'user_name' => $this->mName,
2022 'user_password' => $this->mPassword,
2023 'user_newpassword' => $this->mNewpassword,
2024 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2025 'user_real_name' => $this->mRealName,
2026 'user_email' => $this->mEmail,
2027 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2028 'user_options' => $this->encodeOptions(),
2029 'user_touched' => $dbw->timestamp($this->mTouched),
2030 'user_token' => $this->mToken
2031 ), array( /* WHERE */
2032 'user_id' => $this->mId
2033 ), __METHOD__
2034 );
2035 $this->clearSharedCache();
2036 }
2037
2038
2039 /**
2040 * Checks if a user with the given name exists, returns the ID.
2041 */
2042 function idForName() {
2043 $s = trim( $this->getName() );
2044 if ( $s === '' ) return 0;
2045
2046 $dbr = wfGetDB( DB_SLAVE );
2047 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2048 if ( $id === false ) {
2049 $id = 0;
2050 }
2051 return $id;
2052 }
2053
2054 /**
2055 * Add a user to the database, return the user object
2056 *
2057 * @param string $name The user's name
2058 * @param array $params Associative array of non-default parameters to save to the database:
2059 * password The user's password. Password logins will be disabled if this is omitted.
2060 * newpassword A temporary password mailed to the user
2061 * email The user's email address
2062 * email_authenticated The email authentication timestamp
2063 * real_name The user's real name
2064 * options An associative array of non-default options
2065 * token Random authentication token. Do not set.
2066 * registration Registration timestamp. Do not set.
2067 *
2068 * @return User object, or null if the username already exists
2069 */
2070 static function createNew( $name, $params = array() ) {
2071 $user = new User;
2072 $user->load();
2073 if ( isset( $params['options'] ) ) {
2074 $user->mOptions = $params['options'] + $user->mOptions;
2075 unset( $params['options'] );
2076 }
2077 $dbw = wfGetDB( DB_MASTER );
2078 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2079 $fields = array(
2080 'user_id' => $seqVal,
2081 'user_name' => $name,
2082 'user_password' => $user->mPassword,
2083 'user_newpassword' => $user->mNewpassword,
2084 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ),
2085 'user_email' => $user->mEmail,
2086 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2087 'user_real_name' => $user->mRealName,
2088 'user_options' => $user->encodeOptions(),
2089 'user_token' => $user->mToken,
2090 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2091 'user_editcount' => 0,
2092 );
2093 foreach ( $params as $name => $value ) {
2094 $fields["user_$name"] = $value;
2095 }
2096 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2097 if ( $dbw->affectedRows() ) {
2098 $newUser = User::newFromId( $dbw->insertId() );
2099 } else {
2100 $newUser = null;
2101 }
2102 return $newUser;
2103 }
2104
2105 /**
2106 * Add an existing user object to the database
2107 */
2108 function addToDatabase() {
2109 $this->load();
2110 $dbw = wfGetDB( DB_MASTER );
2111 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2112 $dbw->insert( 'user',
2113 array(
2114 'user_id' => $seqVal,
2115 'user_name' => $this->mName,
2116 'user_password' => $this->mPassword,
2117 'user_newpassword' => $this->mNewpassword,
2118 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ),
2119 'user_email' => $this->mEmail,
2120 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2121 'user_real_name' => $this->mRealName,
2122 'user_options' => $this->encodeOptions(),
2123 'user_token' => $this->mToken,
2124 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2125 'user_editcount' => 0,
2126 ), __METHOD__
2127 );
2128 $this->mId = $dbw->insertId();
2129
2130 # Clear instance cache other than user table data, which is already accurate
2131 $this->clearInstanceCache();
2132 }
2133
2134 /**
2135 * If the (non-anonymous) user is blocked, this function will block any IP address
2136 * that they successfully log on from.
2137 */
2138 function spreadBlock() {
2139 wfDebug( __METHOD__."()\n" );
2140 $this->load();
2141 if ( $this->mId == 0 ) {
2142 return;
2143 }
2144
2145 $userblock = Block::newFromDB( '', $this->mId );
2146 if ( !$userblock ) {
2147 return;
2148 }
2149
2150 $userblock->doAutoblock( wfGetIp() );
2151
2152 }
2153
2154 /**
2155 * Generate a string which will be different for any combination of
2156 * user options which would produce different parser output.
2157 * This will be used as part of the hash key for the parser cache,
2158 * so users will the same options can share the same cached data
2159 * safely.
2160 *
2161 * Extensions which require it should install 'PageRenderingHash' hook,
2162 * which will give them a chance to modify this key based on their own
2163 * settings.
2164 *
2165 * @return string
2166 */
2167 function getPageRenderingHash() {
2168 global $wgContLang, $wgUseDynamicDates, $wgLang;
2169 if( $this->mHash ){
2170 return $this->mHash;
2171 }
2172
2173 // stubthreshold is only included below for completeness,
2174 // it will always be 0 when this function is called by parsercache.
2175
2176 $confstr = $this->getOption( 'math' );
2177 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2178 if ( $wgUseDynamicDates ) {
2179 $confstr .= '!' . $this->getDatePreference();
2180 }
2181 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
2182 $confstr .= '!' . $wgLang->getCode();
2183 $confstr .= '!' . $this->getOption( 'thumbsize' );
2184 // add in language specific options, if any
2185 $extra = $wgContLang->getExtraHashOptions();
2186 $confstr .= $extra;
2187
2188 // Give a chance for extensions to modify the hash, if they have
2189 // extra options or other effects on the parser cache.
2190 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2191
2192 // Make it a valid memcached key fragment
2193 $confstr = str_replace( ' ', '_', $confstr );
2194 $this->mHash = $confstr;
2195 return $confstr;
2196 }
2197
2198 function isBlockedFromCreateAccount() {
2199 $this->getBlockedStatus();
2200 return $this->mBlock && $this->mBlock->mCreateAccount;
2201 }
2202
2203 /**
2204 * Determine if the user is blocked from using Special:Emailuser.
2205 *
2206 * @public
2207 * @return boolean
2208 */
2209 function isBlockedFromEmailuser() {
2210 $this->getBlockedStatus();
2211 return $this->mBlock && $this->mBlock->mBlockEmail;
2212 }
2213
2214 function isAllowedToCreateAccount() {
2215 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2216 }
2217
2218 /**
2219 * @deprecated
2220 */
2221 function setLoaded( $loaded ) {
2222 wfDeprecated( __METHOD__ );
2223 }
2224
2225 /**
2226 * Get this user's personal page title.
2227 *
2228 * @return Title
2229 * @public
2230 */
2231 function getUserPage() {
2232 return Title::makeTitle( NS_USER, $this->getName() );
2233 }
2234
2235 /**
2236 * Get this user's talk page title.
2237 *
2238 * @return Title
2239 * @public
2240 */
2241 function getTalkPage() {
2242 $title = $this->getUserPage();
2243 return $title->getTalkPage();
2244 }
2245
2246 /**
2247 * @static
2248 */
2249 function getMaxID() {
2250 static $res; // cache
2251
2252 if ( isset( $res ) )
2253 return $res;
2254 else {
2255 $dbr = wfGetDB( DB_SLAVE );
2256 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2257 }
2258 }
2259
2260 /**
2261 * Determine whether the user is a newbie. Newbies are either
2262 * anonymous IPs, or the most recently created accounts.
2263 * @return bool True if it is a newbie.
2264 */
2265 function isNewbie() {
2266 return !$this->isAllowed( 'autoconfirmed' );
2267 }
2268
2269 /**
2270 * Check to see if the given clear-text password is one of the accepted passwords
2271 * @param string $password User password.
2272 * @return bool True if the given password is correct otherwise False.
2273 */
2274 function checkPassword( $password ) {
2275 global $wgAuth;
2276 $this->load();
2277
2278 // Even though we stop people from creating passwords that
2279 // are shorter than this, doesn't mean people wont be able
2280 // to. Certain authentication plugins do NOT want to save
2281 // domain passwords in a mysql database, so we should
2282 // check this (incase $wgAuth->strict() is false).
2283 if( !$this->isValidPassword( $password ) ) {
2284 return false;
2285 }
2286
2287 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2288 return true;
2289 } elseif( $wgAuth->strict() ) {
2290 /* Auth plugin doesn't allow local authentication */
2291 return false;
2292 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2293 /* Auth plugin doesn't allow local authentication for this user name */
2294 return false;
2295 }
2296 $ep = $this->encryptPassword( $password );
2297 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
2298 return true;
2299 } elseif ( function_exists( 'iconv' ) ) {
2300 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2301 # Check for this with iconv
2302 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2303 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
2304 return true;
2305 }
2306 }
2307 return false;
2308 }
2309
2310 /**
2311 * Check if the given clear-text password matches the temporary password
2312 * sent by e-mail for password reset operations.
2313 * @return bool
2314 */
2315 function checkTemporaryPassword( $plaintext ) {
2316 $hash = $this->encryptPassword( $plaintext );
2317 return $hash === $this->mNewpassword;
2318 }
2319
2320 /**
2321 * Initialize (if necessary) and return a session token value
2322 * which can be used in edit forms to show that the user's
2323 * login credentials aren't being hijacked with a foreign form
2324 * submission.
2325 *
2326 * @param mixed $salt - Optional function-specific data for hash.
2327 * Use a string or an array of strings.
2328 * @return string
2329 * @public
2330 */
2331 function editToken( $salt = '' ) {
2332 if ( $this->isAnon() ) {
2333 return EDIT_TOKEN_SUFFIX;
2334 } else {
2335 if( !isset( $_SESSION['wsEditToken'] ) ) {
2336 $token = $this->generateToken();
2337 $_SESSION['wsEditToken'] = $token;
2338 } else {
2339 $token = $_SESSION['wsEditToken'];
2340 }
2341 if( is_array( $salt ) ) {
2342 $salt = implode( '|', $salt );
2343 }
2344 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2345 }
2346 }
2347
2348 /**
2349 * Generate a hex-y looking random token for various uses.
2350 * Could be made more cryptographically sure if someone cares.
2351 * @return string
2352 */
2353 function generateToken( $salt = '' ) {
2354 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2355 return md5( $token . $salt );
2356 }
2357
2358 /**
2359 * Check given value against the token value stored in the session.
2360 * A match should confirm that the form was submitted from the
2361 * user's own login session, not a form submission from a third-party
2362 * site.
2363 *
2364 * @param string $val - the input value to compare
2365 * @param string $salt - Optional function-specific data for hash
2366 * @return bool
2367 * @public
2368 */
2369 function matchEditToken( $val, $salt = '' ) {
2370 $sessionToken = $this->editToken( $salt );
2371 if ( $val != $sessionToken ) {
2372 wfDebug( "User::matchEditToken: broken session data\n" );
2373 }
2374 return $val == $sessionToken;
2375 }
2376
2377 /**
2378 * Check whether the edit token is fine except for the suffix
2379 */
2380 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2381 $sessionToken = $this->editToken( $salt );
2382 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2383 }
2384
2385 /**
2386 * Generate a new e-mail confirmation token and send a confirmation
2387 * mail to the user's given address.
2388 *
2389 * @return mixed True on success, a WikiError object on failure.
2390 */
2391 function sendConfirmationMail() {
2392 global $wgContLang;
2393 $expiration = null; // gets passed-by-ref and defined in next line.
2394 $url = $this->confirmationTokenUrl( $expiration );
2395 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2396 wfMsg( 'confirmemail_body',
2397 wfGetIP(),
2398 $this->getName(),
2399 $url,
2400 $wgContLang->timeanddate( $expiration, false ) ) );
2401 }
2402
2403 /**
2404 * Send an e-mail to this user's account. Does not check for
2405 * confirmed status or validity.
2406 *
2407 * @param string $subject
2408 * @param string $body
2409 * @param string $from Optional from address; default $wgPasswordSender will be used otherwise.
2410 * @return mixed True on success, a WikiError object on failure.
2411 */
2412 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2413 if( is_null( $from ) ) {
2414 global $wgPasswordSender;
2415 $from = $wgPasswordSender;
2416 }
2417
2418 $to = new MailAddress( $this );
2419 $sender = new MailAddress( $from );
2420 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2421 }
2422
2423 /**
2424 * Generate, store, and return a new e-mail confirmation code.
2425 * A hash (unsalted since it's used as a key) is stored.
2426 * @param &$expiration mixed output: accepts the expiration time
2427 * @return string
2428 * @private
2429 */
2430 function confirmationToken( &$expiration ) {
2431 $now = time();
2432 $expires = $now + 7 * 24 * 60 * 60;
2433 $expiration = wfTimestamp( TS_MW, $expires );
2434
2435 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
2436 $hash = md5( $token );
2437
2438 $dbw = wfGetDB( DB_MASTER );
2439 $dbw->update( 'user',
2440 array( 'user_email_token' => $hash,
2441 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2442 array( 'user_id' => $this->mId ),
2443 __METHOD__ );
2444
2445 return $token;
2446 }
2447
2448 /**
2449 * Generate and store a new e-mail confirmation token, and return
2450 * the URL the user can use to confirm.
2451 * @param &$expiration mixed output: accepts the expiration time
2452 * @return string
2453 * @private
2454 */
2455 function confirmationTokenUrl( &$expiration ) {
2456 $token = $this->confirmationToken( $expiration );
2457 $title = SpecialPage::getTitleFor( 'Confirmemail', $token );
2458 return $title->getFullUrl();
2459 }
2460
2461 /**
2462 * Mark the e-mail address confirmed and save.
2463 */
2464 function confirmEmail() {
2465 $this->load();
2466 $this->mEmailAuthenticated = wfTimestampNow();
2467 $this->saveSettings();
2468 return true;
2469 }
2470
2471 /**
2472 * Is this user allowed to send e-mails within limits of current
2473 * site configuration?
2474 * @return bool
2475 */
2476 function canSendEmail() {
2477 $canSend = $this->isEmailConfirmed();
2478 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2479 return $canSend;
2480 }
2481
2482 /**
2483 * Is this user allowed to receive e-mails within limits of current
2484 * site configuration?
2485 * @return bool
2486 */
2487 function canReceiveEmail() {
2488 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2489 }
2490
2491 /**
2492 * Is this user's e-mail address valid-looking and confirmed within
2493 * limits of the current site configuration?
2494 *
2495 * If $wgEmailAuthentication is on, this may require the user to have
2496 * confirmed their address by returning a code or using a password
2497 * sent to the address from the wiki.
2498 *
2499 * @return bool
2500 */
2501 function isEmailConfirmed() {
2502 global $wgEmailAuthentication;
2503 $this->load();
2504 $confirmed = true;
2505 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2506 if( $this->isAnon() )
2507 return false;
2508 if( !self::isValidEmailAddr( $this->mEmail ) )
2509 return false;
2510 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2511 return false;
2512 return true;
2513 } else {
2514 return $confirmed;
2515 }
2516 }
2517
2518 /**
2519 * Return true if there is an outstanding request for e-mail confirmation.
2520 * @return bool
2521 */
2522 function isEmailConfirmationPending() {
2523 global $wgEmailAuthentication;
2524 return $wgEmailAuthentication &&
2525 !$this->isEmailConfirmed() &&
2526 $this->mEmailToken &&
2527 $this->mEmailTokenExpires > wfTimestamp();
2528 }
2529
2530 /**
2531 * Get the timestamp of account creation, or false for
2532 * non-existent/anonymous user accounts
2533 *
2534 * @return mixed
2535 */
2536 public function getRegistration() {
2537 return $this->mId > 0
2538 ? $this->mRegistration
2539 : false;
2540 }
2541
2542 /**
2543 * @param array $groups list of groups
2544 * @return array list of permission key names for given groups combined
2545 * @static
2546 */
2547 static function getGroupPermissions( $groups ) {
2548 global $wgGroupPermissions;
2549 $rights = array();
2550 foreach( $groups as $group ) {
2551 if( isset( $wgGroupPermissions[$group] ) ) {
2552 $rights = array_merge( $rights,
2553 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2554 }
2555 }
2556 return $rights;
2557 }
2558
2559 /**
2560 * @param string $group key name
2561 * @return string localized descriptive name for group, if provided
2562 * @static
2563 */
2564 static function getGroupName( $group ) {
2565 global $wgMessageCache;
2566 $wgMessageCache->loadAllMessages();
2567 $key = "group-$group";
2568 $name = wfMsg( $key );
2569 return $name == '' || wfEmptyMsg( $key, $name )
2570 ? $group
2571 : $name;
2572 }
2573
2574 /**
2575 * @param string $group key name
2576 * @return string localized descriptive name for member of a group, if provided
2577 * @static
2578 */
2579 static function getGroupMember( $group ) {
2580 global $wgMessageCache;
2581 $wgMessageCache->loadAllMessages();
2582 $key = "group-$group-member";
2583 $name = wfMsg( $key );
2584 return $name == '' || wfEmptyMsg( $key, $name )
2585 ? $group
2586 : $name;
2587 }
2588
2589 /**
2590 * Return the set of defined explicit groups.
2591 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2592 * groups are not included, as they are defined
2593 * automatically, not in the database.
2594 * @return array
2595 * @static
2596 */
2597 static function getAllGroups() {
2598 global $wgGroupPermissions;
2599 return array_diff(
2600 array_keys( $wgGroupPermissions ),
2601 self::getImplicitGroups()
2602 );
2603 }
2604
2605 /**
2606 * Get a list of implicit groups
2607 *
2608 * @return array
2609 */
2610 public static function getImplicitGroups() {
2611 global $wgImplicitGroups;
2612 $groups = $wgImplicitGroups;
2613 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
2614 return $groups;
2615 }
2616
2617 /**
2618 * Get the title of a page describing a particular group
2619 *
2620 * @param $group Name of the group
2621 * @return mixed
2622 */
2623 static function getGroupPage( $group ) {
2624 global $wgMessageCache;
2625 $wgMessageCache->loadAllMessages();
2626 $page = wfMsgForContent( 'grouppage-' . $group );
2627 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2628 $title = Title::newFromText( $page );
2629 if( is_object( $title ) )
2630 return $title;
2631 }
2632 return false;
2633 }
2634
2635 /**
2636 * Create a link to the group in HTML, if available
2637 *
2638 * @param $group Name of the group
2639 * @param $text The text of the link
2640 * @return mixed
2641 */
2642 static function makeGroupLinkHTML( $group, $text = '' ) {
2643 if( $text == '' ) {
2644 $text = self::getGroupName( $group );
2645 }
2646 $title = self::getGroupPage( $group );
2647 if( $title ) {
2648 global $wgUser;
2649 $sk = $wgUser->getSkin();
2650 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2651 } else {
2652 return $text;
2653 }
2654 }
2655
2656 /**
2657 * Create a link to the group in Wikitext, if available
2658 *
2659 * @param $group Name of the group
2660 * @param $text The text of the link (by default, the name of the group)
2661 * @return mixed
2662 */
2663 static function makeGroupLinkWiki( $group, $text = '' ) {
2664 if( $text == '' ) {
2665 $text = self::getGroupName( $group );
2666 }
2667 $title = self::getGroupPage( $group );
2668 if( $title ) {
2669 $page = $title->getPrefixedText();
2670 return "[[$page|$text]]";
2671 } else {
2672 return $text;
2673 }
2674 }
2675
2676 /**
2677 * Increment the user's edit-count field.
2678 * Will have no effect for anonymous users.
2679 */
2680 function incEditCount() {
2681 if( !$this->isAnon() ) {
2682 $dbw = wfGetDB( DB_MASTER );
2683 $dbw->update( 'user',
2684 array( 'user_editcount=user_editcount+1' ),
2685 array( 'user_id' => $this->getId() ),
2686 __METHOD__ );
2687
2688 // Lazy initialization check...
2689 if( $dbw->affectedRows() == 0 ) {
2690 // Pull from a slave to be less cruel to servers
2691 // Accuracy isn't the point anyway here
2692 $dbr = wfGetDB( DB_SLAVE );
2693 $count = $dbr->selectField( 'revision',
2694 'COUNT(rev_user)',
2695 array( 'rev_user' => $this->getId() ),
2696 __METHOD__ );
2697
2698 // Now here's a goddamn hack...
2699 if( $dbr !== $dbw ) {
2700 // If we actually have a slave server, the count is
2701 // at least one behind because the current transaction
2702 // has not been committed and replicated.
2703 $count++;
2704 } else {
2705 // But if DB_SLAVE is selecting the master, then the
2706 // count we just read includes the revision that was
2707 // just added in the working transaction.
2708 }
2709
2710 $dbw->update( 'user',
2711 array( 'user_editcount' => $count ),
2712 array( 'user_id' => $this->getId() ),
2713 __METHOD__ );
2714 }
2715 }
2716 // edit count in user cache too
2717 $this->invalidateCache();
2718 }
2719 }
2720
2721
2722