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