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