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