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