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