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