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