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