* Fix CentralAuth logout, was mostly broken.
[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 global $wgRateLimitsExcludedGroups;
1105 return array_intersect($this->getEffectiveGroups(), $wgRateLimitsExcludedGroups) == array();
1106 }
1107
1108 /**
1109 * Primitive rate limits: enforce maximum actions per time period
1110 * to put a brake on flooding.
1111 *
1112 * Note: when using a shared cache like memcached, IP-address
1113 * last-hit counters will be shared across wikis.
1114 *
1115 * @return bool true if a rate limiter was tripped
1116 * @public
1117 */
1118 function pingLimiter( $action='edit' ) {
1119
1120 # Call the 'PingLimiter' hook
1121 $result = false;
1122 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1123 return $result;
1124 }
1125
1126 global $wgRateLimits;
1127 if( !isset( $wgRateLimits[$action] ) ) {
1128 return false;
1129 }
1130
1131 # Some groups shouldn't trigger the ping limiter, ever
1132 if( !$this->isPingLimitable() )
1133 return false;
1134
1135 global $wgMemc, $wgRateLimitLog;
1136 wfProfileIn( __METHOD__ );
1137
1138 $limits = $wgRateLimits[$action];
1139 $keys = array();
1140 $id = $this->getId();
1141 $ip = wfGetIP();
1142 $userLimit = false;
1143
1144 if( isset( $limits['anon'] ) && $id == 0 ) {
1145 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1146 }
1147
1148 if( isset( $limits['user'] ) && $id != 0 ) {
1149 $userLimit = $limits['user'];
1150 }
1151 if( $this->isNewbie() ) {
1152 if( isset( $limits['newbie'] ) && $id != 0 ) {
1153 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1154 }
1155 if( isset( $limits['ip'] ) ) {
1156 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1157 }
1158 $matches = array();
1159 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1160 $subnet = $matches[1];
1161 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1162 }
1163 }
1164 // Check for group-specific permissions
1165 // If more than one group applies, use the group with the highest limit
1166 foreach ( $this->getGroups() as $group ) {
1167 if ( isset( $limits[$group] ) ) {
1168 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1169 $userLimit = $limits[$group];
1170 }
1171 }
1172 }
1173 // Set the user limit key
1174 if ( $userLimit !== false ) {
1175 wfDebug( __METHOD__.": effective user limit: $userLimit\n" );
1176 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1177 }
1178
1179 $triggered = false;
1180 foreach( $keys as $key => $limit ) {
1181 list( $max, $period ) = $limit;
1182 $summary = "(limit $max in {$period}s)";
1183 $count = $wgMemc->get( $key );
1184 if( $count ) {
1185 if( $count > $max ) {
1186 wfDebug( __METHOD__.": tripped! $key at $count $summary\n" );
1187 if( $wgRateLimitLog ) {
1188 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1189 }
1190 $triggered = true;
1191 } else {
1192 wfDebug( __METHOD__.": ok. $key at $count $summary\n" );
1193 }
1194 } else {
1195 wfDebug( __METHOD__.": adding record for $key $summary\n" );
1196 $wgMemc->add( $key, 1, intval( $period ) );
1197 }
1198 $wgMemc->incr( $key );
1199 }
1200
1201 wfProfileOut( __METHOD__ );
1202 return $triggered;
1203 }
1204
1205 /**
1206 * Check if user is blocked
1207 * @return bool True if blocked, false otherwise
1208 */
1209 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1210 wfDebug( "User::isBlocked: enter\n" );
1211 $this->getBlockedStatus( $bFromSlave );
1212 return $this->mBlockedby !== 0;
1213 }
1214
1215 /**
1216 * Check if user is blocked from editing a particular article
1217 */
1218 function isBlockedFrom( $title, $bFromSlave = false ) {
1219 global $wgBlockAllowsUTEdit;
1220 wfProfileIn( __METHOD__ );
1221 wfDebug( __METHOD__.": enter\n" );
1222
1223 wfDebug( __METHOD__.": asking isBlocked()\n" );
1224 $blocked = $this->isBlocked( $bFromSlave );
1225 # If a user's name is suppressed, they cannot make edits anywhere
1226 if ( !$this->mHideName && $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1227 $title->getNamespace() == NS_USER_TALK ) {
1228 $blocked = false;
1229 wfDebug( __METHOD__.": self-talk page, ignoring any blocks\n" );
1230 }
1231 wfProfileOut( __METHOD__ );
1232 return $blocked;
1233 }
1234
1235 /**
1236 * Get name of blocker
1237 * @return string name of blocker
1238 */
1239 function blockedBy() {
1240 $this->getBlockedStatus();
1241 return $this->mBlockedby;
1242 }
1243
1244 /**
1245 * Get blocking reason
1246 * @return string Blocking reason
1247 */
1248 function blockedFor() {
1249 $this->getBlockedStatus();
1250 return $this->mBlockreason;
1251 }
1252
1253 /**
1254 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1255 */
1256 function getId() {
1257 if( $this->mId === null and $this->mName !== null
1258 and User::isIP( $this->mName ) ) {
1259 // Special case, we know the user is anonymous
1260 return 0;
1261 } elseif( $this->mId === null ) {
1262 // Don't load if this was initialized from an ID
1263 $this->load();
1264 }
1265 return $this->mId;
1266 }
1267
1268 /**
1269 * Set the user and reload all fields according to that ID
1270 */
1271 function setId( $v ) {
1272 $this->mId = $v;
1273 $this->clearInstanceCache( 'id' );
1274 }
1275
1276 /**
1277 * Get the user name, or the IP for anons
1278 */
1279 function getName() {
1280 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1281 # Special case optimisation
1282 return $this->mName;
1283 } else {
1284 $this->load();
1285 if ( $this->mName === false ) {
1286 # Clean up IPs
1287 $this->mName = IP::sanitizeIP( wfGetIP() );
1288 }
1289 return $this->mName;
1290 }
1291 }
1292
1293 /**
1294 * Set the user name.
1295 *
1296 * This does not reload fields from the database according to the given
1297 * name. Rather, it is used to create a temporary "nonexistent user" for
1298 * later addition to the database. It can also be used to set the IP
1299 * address for an anonymous user to something other than the current
1300 * remote IP.
1301 *
1302 * User::newFromName() has rougly the same function, when the named user
1303 * does not exist.
1304 */
1305 function setName( $str ) {
1306 $this->load();
1307 $this->mName = $str;
1308 }
1309
1310 /**
1311 * Return the title dbkey form of the name, for eg user pages.
1312 * @return string
1313 * @public
1314 */
1315 function getTitleKey() {
1316 return str_replace( ' ', '_', $this->getName() );
1317 }
1318
1319 function getNewtalk() {
1320 $this->load();
1321
1322 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1323 if( $this->mNewtalk === -1 ) {
1324 $this->mNewtalk = false; # reset talk page status
1325
1326 # Check memcached separately for anons, who have no
1327 # entire User object stored in there.
1328 if( !$this->mId ) {
1329 global $wgMemc;
1330 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1331 $newtalk = $wgMemc->get( $key );
1332 if( strval( $newtalk ) !== '' ) {
1333 $this->mNewtalk = (bool)$newtalk;
1334 } else {
1335 // Since we are caching this, make sure it is up to date by getting it
1336 // from the master
1337 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1338 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1339 }
1340 } else {
1341 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1342 }
1343 }
1344
1345 return (bool)$this->mNewtalk;
1346 }
1347
1348 /**
1349 * Return the talk page(s) this user has new messages on.
1350 */
1351 function getNewMessageLinks() {
1352 $talks = array();
1353 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1354 return $talks;
1355
1356 if (!$this->getNewtalk())
1357 return array();
1358 $up = $this->getUserPage();
1359 $utp = $up->getTalkPage();
1360 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1361 }
1362
1363
1364 /**
1365 * Perform a user_newtalk check, uncached.
1366 * Use getNewtalk for a cached check.
1367 *
1368 * @param string $field
1369 * @param mixed $id
1370 * @param bool $fromMaster True to fetch from the master, false for a slave
1371 * @return bool
1372 * @private
1373 */
1374 function checkNewtalk( $field, $id, $fromMaster = false ) {
1375 if ( $fromMaster ) {
1376 $db = wfGetDB( DB_MASTER );
1377 } else {
1378 $db = wfGetDB( DB_SLAVE );
1379 }
1380 $ok = $db->selectField( 'user_newtalk', $field,
1381 array( $field => $id ), __METHOD__ );
1382 return $ok !== false;
1383 }
1384
1385 /**
1386 * Add or update the
1387 * @param string $field
1388 * @param mixed $id
1389 * @private
1390 */
1391 function updateNewtalk( $field, $id ) {
1392 $dbw = wfGetDB( DB_MASTER );
1393 $dbw->insert( 'user_newtalk',
1394 array( $field => $id ),
1395 __METHOD__,
1396 'IGNORE' );
1397 if ( $dbw->affectedRows() ) {
1398 wfDebug( __METHOD__.": set on ($field, $id)\n" );
1399 return true;
1400 } else {
1401 wfDebug( __METHOD__." already set ($field, $id)\n" );
1402 return false;
1403 }
1404 }
1405
1406 /**
1407 * Clear the new messages flag for the given user
1408 * @param string $field
1409 * @param mixed $id
1410 * @private
1411 */
1412 function deleteNewtalk( $field, $id ) {
1413 $dbw = wfGetDB( DB_MASTER );
1414 $dbw->delete( 'user_newtalk',
1415 array( $field => $id ),
1416 __METHOD__ );
1417 if ( $dbw->affectedRows() ) {
1418 wfDebug( __METHOD__.": killed on ($field, $id)\n" );
1419 return true;
1420 } else {
1421 wfDebug( __METHOD__.": already gone ($field, $id)\n" );
1422 return false;
1423 }
1424 }
1425
1426 /**
1427 * Update the 'You have new messages!' status.
1428 * @param bool $val
1429 */
1430 function setNewtalk( $val ) {
1431 if( wfReadOnly() ) {
1432 return;
1433 }
1434
1435 $this->load();
1436 $this->mNewtalk = $val;
1437
1438 if( $this->isAnon() ) {
1439 $field = 'user_ip';
1440 $id = $this->getName();
1441 } else {
1442 $field = 'user_id';
1443 $id = $this->getId();
1444 }
1445 global $wgMemc;
1446
1447 if( $val ) {
1448 $changed = $this->updateNewtalk( $field, $id );
1449 } else {
1450 $changed = $this->deleteNewtalk( $field, $id );
1451 }
1452
1453 if( $this->isAnon() ) {
1454 // Anons have a separate memcached space, since
1455 // user records aren't kept for them.
1456 $key = wfMemcKey( 'newtalk', 'ip', $id );
1457 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1458 }
1459 if ( $changed ) {
1460 $this->invalidateCache();
1461 }
1462 }
1463
1464 /**
1465 * Generate a current or new-future timestamp to be stored in the
1466 * user_touched field when we update things.
1467 */
1468 private static function newTouchedTimestamp() {
1469 global $wgClockSkewFudge;
1470 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1471 }
1472
1473 /**
1474 * Clear user data from memcached.
1475 * Use after applying fun updates to the database; caller's
1476 * responsibility to update user_touched if appropriate.
1477 *
1478 * Called implicitly from invalidateCache() and saveSettings().
1479 */
1480 private function clearSharedCache() {
1481 if( $this->mId ) {
1482 global $wgMemc;
1483 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1484 }
1485 }
1486
1487 /**
1488 * Immediately touch the user data cache for this account.
1489 * Updates user_touched field, and removes account data from memcached
1490 * for reload on the next hit.
1491 */
1492 function invalidateCache() {
1493 $this->load();
1494 if( $this->mId ) {
1495 $this->mTouched = self::newTouchedTimestamp();
1496
1497 $dbw = wfGetDB( DB_MASTER );
1498 $dbw->update( 'user',
1499 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1500 array( 'user_id' => $this->mId ),
1501 __METHOD__ );
1502
1503 $this->clearSharedCache();
1504 }
1505 }
1506
1507 function validateCache( $timestamp ) {
1508 $this->load();
1509 return ($timestamp >= $this->mTouched);
1510 }
1511
1512 /**
1513 * Encrypt a password.
1514 * It can eventually salt a password.
1515 * @see User::addSalt()
1516 * @param string $p clear Password.
1517 * @return string Encrypted password.
1518 */
1519 function encryptPassword( $p ) {
1520 $this->load();
1521 return wfEncryptPassword( $this->mId, $p );
1522 }
1523
1524 /**
1525 * Set the password and reset the random token
1526 * Calls through to authentication plugin if necessary;
1527 * will have no effect if the auth plugin refuses to
1528 * pass the change through or if the legal password
1529 * checks fail.
1530 *
1531 * As a special case, setting the password to null
1532 * wipes it, so the account cannot be logged in until
1533 * a new password is set, for instance via e-mail.
1534 *
1535 * @param string $str
1536 * @throws PasswordError on failure
1537 */
1538 function setPassword( $str ) {
1539 global $wgAuth;
1540
1541 if( $str !== null ) {
1542 if( !$wgAuth->allowPasswordChange() ) {
1543 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1544 }
1545
1546 if( !$this->isValidPassword( $str ) ) {
1547 global $wgMinimalPasswordLength;
1548 throw new PasswordError( wfMsg( 'passwordtooshort',
1549 $wgMinimalPasswordLength ) );
1550 }
1551 }
1552
1553 if( !$wgAuth->setPassword( $this, $str ) ) {
1554 throw new PasswordError( wfMsg( 'externaldberror' ) );
1555 }
1556
1557 $this->setInternalPassword( $str );
1558
1559 return true;
1560 }
1561
1562 /**
1563 * Set the password and reset the random token no matter
1564 * what.
1565 *
1566 * @param string $str
1567 */
1568 function setInternalPassword( $str ) {
1569 $this->load();
1570 $this->setToken();
1571
1572 if( $str === null ) {
1573 // Save an invalid hash...
1574 $this->mPassword = '';
1575 } else {
1576 $this->mPassword = $this->encryptPassword( $str );
1577 }
1578 $this->mNewpassword = '';
1579 $this->mNewpassTime = null;
1580 }
1581 /**
1582 * Set the random token (used for persistent authentication)
1583 * Called from loadDefaults() among other places.
1584 * @private
1585 */
1586 function setToken( $token = false ) {
1587 global $wgSecretKey, $wgProxyKey;
1588 $this->load();
1589 if ( !$token ) {
1590 if ( $wgSecretKey ) {
1591 $key = $wgSecretKey;
1592 } elseif ( $wgProxyKey ) {
1593 $key = $wgProxyKey;
1594 } else {
1595 $key = microtime();
1596 }
1597 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1598 } else {
1599 $this->mToken = $token;
1600 }
1601 }
1602
1603 function setCookiePassword( $str ) {
1604 $this->load();
1605 $this->mCookiePassword = md5( $str );
1606 }
1607
1608 /**
1609 * Set the password for a password reminder or new account email
1610 * Sets the user_newpass_time field if $throttle is true
1611 */
1612 function setNewpassword( $str, $throttle = true ) {
1613 $this->load();
1614 $this->mNewpassword = $this->encryptPassword( $str );
1615 if ( $throttle ) {
1616 $this->mNewpassTime = wfTimestampNow();
1617 }
1618 }
1619
1620 /**
1621 * Returns true if a password reminder email has already been sent within
1622 * the last $wgPasswordReminderResendTime hours
1623 */
1624 function isPasswordReminderThrottled() {
1625 global $wgPasswordReminderResendTime;
1626 $this->load();
1627 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1628 return false;
1629 }
1630 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1631 return time() < $expiry;
1632 }
1633
1634 function getEmail() {
1635 $this->load();
1636 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1637 return $this->mEmail;
1638 }
1639
1640 function getEmailAuthenticationTimestamp() {
1641 $this->load();
1642 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1643 return $this->mEmailAuthenticated;
1644 }
1645
1646 function setEmail( $str ) {
1647 $this->load();
1648 $this->mEmail = $str;
1649 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1650 }
1651
1652 function getRealName() {
1653 $this->load();
1654 return $this->mRealName;
1655 }
1656
1657 function setRealName( $str ) {
1658 $this->load();
1659 $this->mRealName = $str;
1660 }
1661
1662 /**
1663 * @param string $oname The option to check
1664 * @param string $defaultOverride A default value returned if the option does not exist
1665 * @return string
1666 */
1667 function getOption( $oname, $defaultOverride = '' ) {
1668 $this->load();
1669
1670 if ( is_null( $this->mOptions ) ) {
1671 if($defaultOverride != '') {
1672 return $defaultOverride;
1673 }
1674 $this->mOptions = User::getDefaultOptions();
1675 }
1676
1677 if ( array_key_exists( $oname, $this->mOptions ) ) {
1678 return trim( $this->mOptions[$oname] );
1679 } else {
1680 return $defaultOverride;
1681 }
1682 }
1683
1684 /**
1685 * Get the user's date preference, including some important migration for
1686 * old user rows.
1687 */
1688 function getDatePreference() {
1689 if ( is_null( $this->mDatePreference ) ) {
1690 global $wgLang;
1691 $value = $this->getOption( 'date' );
1692 $map = $wgLang->getDatePreferenceMigrationMap();
1693 if ( isset( $map[$value] ) ) {
1694 $value = $map[$value];
1695 }
1696 $this->mDatePreference = $value;
1697 }
1698 return $this->mDatePreference;
1699 }
1700
1701 /**
1702 * @param string $oname The option to check
1703 * @return bool False if the option is not selected, true if it is
1704 */
1705 function getBoolOption( $oname ) {
1706 return (bool)$this->getOption( $oname );
1707 }
1708
1709 /**
1710 * Get an option as an integer value from the source string.
1711 * @param string $oname The option to check
1712 * @param int $default Optional value to return if option is unset/blank.
1713 * @return int
1714 */
1715 function getIntOption( $oname, $default=0 ) {
1716 $val = $this->getOption( $oname );
1717 if( $val == '' ) {
1718 $val = $default;
1719 }
1720 return intval( $val );
1721 }
1722
1723 function setOption( $oname, $val ) {
1724 $this->load();
1725 if ( is_null( $this->mOptions ) ) {
1726 $this->mOptions = User::getDefaultOptions();
1727 }
1728 if ( $oname == 'skin' ) {
1729 # Clear cached skin, so the new one displays immediately in Special:Preferences
1730 unset( $this->mSkin );
1731 }
1732 // Filter out any newlines that may have passed through input validation.
1733 // Newlines are used to separate items in the options blob.
1734 if( $val ) {
1735 $val = str_replace( "\r\n", "\n", $val );
1736 $val = str_replace( "\r", "\n", $val );
1737 $val = str_replace( "\n", " ", $val );
1738 }
1739 // Explicitly NULL values should refer to defaults
1740 global $wgDefaultUserOptions;
1741 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1742 $val = $wgDefaultUserOptions[$oname];
1743 }
1744 $this->mOptions[$oname] = $val;
1745 }
1746
1747 function getRights() {
1748 if ( is_null( $this->mRights ) ) {
1749 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
1750 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
1751 // Force reindexation of rights when a hook has unset one of them
1752 $this->mRights = array_values( $this->mRights );
1753 }
1754 return $this->mRights;
1755 }
1756
1757 /**
1758 * Get the list of explicit group memberships this user has.
1759 * The implicit * and user groups are not included.
1760 * @return array of strings
1761 */
1762 function getGroups() {
1763 $this->load();
1764 return $this->mGroups;
1765 }
1766
1767 /**
1768 * Get the list of implicit group memberships this user has.
1769 * This includes all explicit groups, plus 'user' if logged in,
1770 * '*' for all accounts and autopromoted groups
1771 * @param boolean $recache Don't use the cache
1772 * @return array of strings
1773 */
1774 function getEffectiveGroups( $recache = false ) {
1775 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
1776 $this->mEffectiveGroups = $this->getGroups();
1777 $this->mEffectiveGroups[] = '*';
1778 if( $this->getId() ) {
1779 $this->mEffectiveGroups[] = 'user';
1780
1781 $this->mEffectiveGroups = array_unique( array_merge(
1782 $this->mEffectiveGroups,
1783 Autopromote::getAutopromoteGroups( $this )
1784 ) );
1785
1786 # Hook for additional groups
1787 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
1788 }
1789 }
1790 return $this->mEffectiveGroups;
1791 }
1792
1793 /* Return the edit count for the user. This is where User::edits should have been */
1794 function getEditCount() {
1795 if ($this->mId) {
1796 if ( !isset( $this->mEditCount ) ) {
1797 /* Populate the count, if it has not been populated yet */
1798 $this->mEditCount = User::edits($this->mId);
1799 }
1800 return $this->mEditCount;
1801 } else {
1802 /* nil */
1803 return null;
1804 }
1805 }
1806
1807 /**
1808 * Add the user to the given group.
1809 * This takes immediate effect.
1810 * @param string $group
1811 */
1812 function addGroup( $group ) {
1813 $dbw = wfGetDB( DB_MASTER );
1814 if( $this->getId() ) {
1815 $dbw->insert( 'user_groups',
1816 array(
1817 'ug_user' => $this->getID(),
1818 'ug_group' => $group,
1819 ),
1820 'User::addGroup',
1821 array( 'IGNORE' ) );
1822 }
1823
1824 $this->loadGroups();
1825 $this->mGroups[] = $group;
1826 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1827
1828 $this->invalidateCache();
1829 }
1830
1831 /**
1832 * Remove the user from the given group.
1833 * This takes immediate effect.
1834 * @param string $group
1835 */
1836 function removeGroup( $group ) {
1837 $this->load();
1838 $dbw = wfGetDB( DB_MASTER );
1839 $dbw->delete( 'user_groups',
1840 array(
1841 'ug_user' => $this->getID(),
1842 'ug_group' => $group,
1843 ),
1844 'User::removeGroup' );
1845
1846 $this->loadGroups();
1847 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
1848 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1849
1850 $this->invalidateCache();
1851 }
1852
1853
1854 /**
1855 * A more legible check for non-anonymousness.
1856 * Returns true if the user is not an anonymous visitor.
1857 *
1858 * @return bool
1859 */
1860 function isLoggedIn() {
1861 return $this->getID() != 0;
1862 }
1863
1864 /**
1865 * A more legible check for anonymousness.
1866 * Returns true if the user is an anonymous visitor.
1867 *
1868 * @return bool
1869 */
1870 function isAnon() {
1871 return !$this->isLoggedIn();
1872 }
1873
1874 /**
1875 * Whether the user is a bot
1876 * @deprecated
1877 */
1878 function isBot() {
1879 wfDeprecated( __METHOD__ );
1880 return $this->isAllowed( 'bot' );
1881 }
1882
1883 /**
1884 * Check if user is allowed to access a feature / make an action
1885 * @param string $action Action to be checked
1886 * @return boolean True: action is allowed, False: action should not be allowed
1887 */
1888 function isAllowed($action='') {
1889 if ( $action === '' )
1890 // In the spirit of DWIM
1891 return true;
1892
1893 return in_array( $action, $this->getRights() );
1894 }
1895
1896 /**
1897 * Check whether to enable recent changes patrol features for this user
1898 * @return bool
1899 */
1900 public function useRCPatrol() {
1901 global $wgUseRCPatrol;
1902 return( $wgUseRCPatrol && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
1903 }
1904
1905 /**
1906 * Check whether to enable recent changes patrol features for this user
1907 * @return bool
1908 */
1909 public function useNPPatrol() {
1910 global $wgUseRCPatrol, $wgUseNPPatrol;
1911 return( ($wgUseRCPatrol || $wgUseNPPatrol) && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
1912 }
1913
1914 /**
1915 * Load a skin if it doesn't exist or return it
1916 * @todo FIXME : need to check the old failback system [AV]
1917 */
1918 function &getSkin() {
1919 global $wgRequest;
1920 if ( ! isset( $this->mSkin ) ) {
1921 wfProfileIn( __METHOD__ );
1922
1923 # get the user skin
1924 $userSkin = $this->getOption( 'skin' );
1925 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1926
1927 $this->mSkin =& Skin::newFromKey( $userSkin );
1928 wfProfileOut( __METHOD__ );
1929 }
1930 return $this->mSkin;
1931 }
1932
1933 /**#@+
1934 * @param string $title Article title to look at
1935 */
1936
1937 /**
1938 * Check watched status of an article
1939 * @return bool True if article is watched
1940 */
1941 function isWatched( $title ) {
1942 $wl = WatchedItem::fromUserTitle( $this, $title );
1943 return $wl->isWatched();
1944 }
1945
1946 /**
1947 * Watch an article
1948 */
1949 function addWatch( $title ) {
1950 $wl = WatchedItem::fromUserTitle( $this, $title );
1951 $wl->addWatch();
1952 $this->invalidateCache();
1953 }
1954
1955 /**
1956 * Stop watching an article
1957 */
1958 function removeWatch( $title ) {
1959 $wl = WatchedItem::fromUserTitle( $this, $title );
1960 $wl->removeWatch();
1961 $this->invalidateCache();
1962 }
1963
1964 /**
1965 * Clear the user's notification timestamp for the given title.
1966 * If e-notif e-mails are on, they will receive notification mails on
1967 * the next change of the page if it's watched etc.
1968 */
1969 function clearNotification( &$title ) {
1970 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
1971
1972 # Do nothing if the database is locked to writes
1973 if( wfReadOnly() ) {
1974 return;
1975 }
1976
1977 if ($title->getNamespace() == NS_USER_TALK &&
1978 $title->getText() == $this->getName() ) {
1979 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1980 return;
1981 $this->setNewtalk( false );
1982 }
1983
1984 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
1985 return;
1986 }
1987
1988 if( $this->isAnon() ) {
1989 // Nothing else to do...
1990 return;
1991 }
1992
1993 // Only update the timestamp if the page is being watched.
1994 // The query to find out if it is watched is cached both in memcached and per-invocation,
1995 // and when it does have to be executed, it can be on a slave
1996 // If this is the user's newtalk page, we always update the timestamp
1997 if ($title->getNamespace() == NS_USER_TALK &&
1998 $title->getText() == $wgUser->getName())
1999 {
2000 $watched = true;
2001 } elseif ( $this->getId() == $wgUser->getId() ) {
2002 $watched = $title->userIsWatching();
2003 } else {
2004 $watched = true;
2005 }
2006
2007 // If the page is watched by the user (or may be watched), update the timestamp on any
2008 // any matching rows
2009 if ( $watched ) {
2010 $dbw = wfGetDB( DB_MASTER );
2011 $dbw->update( 'watchlist',
2012 array( /* SET */
2013 'wl_notificationtimestamp' => NULL
2014 ), array( /* WHERE */
2015 'wl_title' => $title->getDBkey(),
2016 'wl_namespace' => $title->getNamespace(),
2017 'wl_user' => $this->getID()
2018 ), 'User::clearLastVisited'
2019 );
2020 }
2021 }
2022
2023 /**#@-*/
2024
2025 /**
2026 * Resets all of the given user's page-change notification timestamps.
2027 * If e-notif e-mails are on, they will receive notification mails on
2028 * the next change of any watched page.
2029 *
2030 * @param int $currentUser user ID number
2031 * @public
2032 */
2033 function clearAllNotifications( $currentUser ) {
2034 global $wgUseEnotif, $wgShowUpdatedMarker;
2035 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2036 $this->setNewtalk( false );
2037 return;
2038 }
2039 if( $currentUser != 0 ) {
2040 $dbw = wfGetDB( DB_MASTER );
2041 $dbw->update( 'watchlist',
2042 array( /* SET */
2043 'wl_notificationtimestamp' => NULL
2044 ), array( /* WHERE */
2045 'wl_user' => $currentUser
2046 ), __METHOD__
2047 );
2048 # We also need to clear here the "you have new message" notification for the own user_talk page
2049 # This is cleared one page view later in Article::viewUpdates();
2050 }
2051 }
2052
2053 /**
2054 * @private
2055 * @return string Encoding options
2056 */
2057 function encodeOptions() {
2058 $this->load();
2059 if ( is_null( $this->mOptions ) ) {
2060 $this->mOptions = User::getDefaultOptions();
2061 }
2062 $a = array();
2063 foreach ( $this->mOptions as $oname => $oval ) {
2064 array_push( $a, $oname.'='.$oval );
2065 }
2066 $s = implode( "\n", $a );
2067 return $s;
2068 }
2069
2070 /**
2071 * @private
2072 */
2073 function decodeOptions( $str ) {
2074 $this->mOptions = array();
2075 $a = explode( "\n", $str );
2076 foreach ( $a as $s ) {
2077 $m = array();
2078 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2079 $this->mOptions[$m[1]] = $m[2];
2080 }
2081 }
2082 }
2083
2084 protected function setCookie( $name, $value, $exp=0 ) {
2085 global $wgCookiePrefix,$wgCookieDomain,$wgCookieSecure,$wgCookieExpiration, $wgCookieHttpOnly;
2086 if( $exp == 0 ) {
2087 $exp = time() + $wgCookieExpiration;
2088 }
2089 $httpOnlySafe = wfHttpOnlySafe();
2090 wfDebugLog( 'cookie',
2091 'setcookie: "' . implode( '", "',
2092 array(
2093 $wgCookiePrefix . $name,
2094 $value,
2095 $exp,
2096 '/',
2097 $wgCookieDomain,
2098 $wgCookieSecure,
2099 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2100 if( $httpOnlySafe && isset( $wgCookieHttpOnly ) ) {
2101 setcookie( $wgCookiePrefix . $name,
2102 $value,
2103 $exp,
2104 '/',
2105 $wgCookieDomain,
2106 $wgCookieSecure,
2107 $wgCookieHttpOnly );
2108 } else {
2109 // setcookie() fails on PHP 5.1 if you give it future-compat paramters.
2110 // stab stab!
2111 setcookie( $wgCookiePrefix . $name,
2112 $value,
2113 $exp,
2114 '/',
2115 $wgCookieDomain,
2116 $wgCookieSecure );
2117 }
2118 }
2119
2120 protected function clearCookie( $name ) {
2121 $this->setCookie( $name, '', time() - 86400 );
2122 }
2123
2124 function setCookies() {
2125 $this->load();
2126 if ( 0 == $this->mId ) return;
2127 $session = array(
2128 'wsUserID' => $this->mId,
2129 'wsToken' => $this->mToken,
2130 'wsUserName' => $this->getName()
2131 );
2132 $cookies = array(
2133 'UserID' => $this->mId,
2134 'UserName' => $this->getName(),
2135 );
2136 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2137 $cookies['Token'] = $this->mToken;
2138 } else {
2139 $cookies['Token'] = false;
2140 }
2141
2142 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2143 $_SESSION = $session + $_SESSION;
2144 foreach ( $cookies as $name => $value ) {
2145 if ( $value === false ) {
2146 $this->clearCookie( $name );
2147 } else {
2148 $this->setCookie( $name, $value );
2149 }
2150 }
2151 }
2152
2153 /**
2154 * Logout user.
2155 */
2156 function logout() {
2157 global $wgUser;
2158 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2159 $this->doLogout();
2160 }
2161 }
2162
2163 /**
2164 * Really logout user
2165 * Clears the cookies and session, resets the instance cache
2166 */
2167 function doLogout() {
2168 $this->clearInstanceCache( 'defaults' );
2169
2170 $_SESSION['wsUserID'] = 0;
2171
2172 $this->clearCookie( 'UserID' );
2173 $this->clearCookie( 'Token' );
2174
2175 # Remember when user logged out, to prevent seeing cached pages
2176 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2177 }
2178
2179 /**
2180 * Save object settings into database
2181 * @todo Only rarely do all these fields need to be set!
2182 */
2183 function saveSettings() {
2184 $this->load();
2185 if ( wfReadOnly() ) { return; }
2186 if ( 0 == $this->mId ) { return; }
2187
2188 $this->mTouched = self::newTouchedTimestamp();
2189
2190 $dbw = wfGetDB( DB_MASTER );
2191 $dbw->update( 'user',
2192 array( /* SET */
2193 'user_name' => $this->mName,
2194 'user_password' => $this->mPassword,
2195 'user_newpassword' => $this->mNewpassword,
2196 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2197 'user_real_name' => $this->mRealName,
2198 'user_email' => $this->mEmail,
2199 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2200 'user_options' => $this->encodeOptions(),
2201 'user_touched' => $dbw->timestamp($this->mTouched),
2202 'user_token' => $this->mToken,
2203 'user_email_token' => $this->mEmailToken,
2204 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2205 ), array( /* WHERE */
2206 'user_id' => $this->mId
2207 ), __METHOD__
2208 );
2209 wfRunHooks( 'UserSaveSettings', array( $this ) );
2210 $this->clearSharedCache();
2211 }
2212
2213 /**
2214 * Checks if a user with the given name exists, returns the ID.
2215 */
2216 function idForName() {
2217 $s = trim( $this->getName() );
2218 if ( $s === '' ) return 0;
2219
2220 $dbr = wfGetDB( DB_SLAVE );
2221 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2222 if ( $id === false ) {
2223 $id = 0;
2224 }
2225 return $id;
2226 }
2227
2228 /**
2229 * Add a user to the database, return the user object
2230 *
2231 * @param string $name The user's name
2232 * @param array $params Associative array of non-default parameters to save to the database:
2233 * password The user's password. Password logins will be disabled if this is omitted.
2234 * newpassword A temporary password mailed to the user
2235 * email The user's email address
2236 * email_authenticated The email authentication timestamp
2237 * real_name The user's real name
2238 * options An associative array of non-default options
2239 * token Random authentication token. Do not set.
2240 * registration Registration timestamp. Do not set.
2241 *
2242 * @return User object, or null if the username already exists
2243 */
2244 static function createNew( $name, $params = array() ) {
2245 $user = new User;
2246 $user->load();
2247 if ( isset( $params['options'] ) ) {
2248 $user->mOptions = $params['options'] + $user->mOptions;
2249 unset( $params['options'] );
2250 }
2251 $dbw = wfGetDB( DB_MASTER );
2252 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2253 $fields = array(
2254 'user_id' => $seqVal,
2255 'user_name' => $name,
2256 'user_password' => $user->mPassword,
2257 'user_newpassword' => $user->mNewpassword,
2258 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ),
2259 'user_email' => $user->mEmail,
2260 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2261 'user_real_name' => $user->mRealName,
2262 'user_options' => $user->encodeOptions(),
2263 'user_token' => $user->mToken,
2264 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2265 'user_editcount' => 0,
2266 );
2267 foreach ( $params as $name => $value ) {
2268 $fields["user_$name"] = $value;
2269 }
2270 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2271 if ( $dbw->affectedRows() ) {
2272 $newUser = User::newFromId( $dbw->insertId() );
2273 } else {
2274 $newUser = null;
2275 }
2276 return $newUser;
2277 }
2278
2279 /**
2280 * Add an existing user object to the database
2281 */
2282 function addToDatabase() {
2283 $this->load();
2284 $dbw = wfGetDB( DB_MASTER );
2285 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2286 $dbw->insert( 'user',
2287 array(
2288 'user_id' => $seqVal,
2289 'user_name' => $this->mName,
2290 'user_password' => $this->mPassword,
2291 'user_newpassword' => $this->mNewpassword,
2292 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ),
2293 'user_email' => $this->mEmail,
2294 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2295 'user_real_name' => $this->mRealName,
2296 'user_options' => $this->encodeOptions(),
2297 'user_token' => $this->mToken,
2298 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2299 'user_editcount' => 0,
2300 ), __METHOD__
2301 );
2302 $this->mId = $dbw->insertId();
2303
2304 # Clear instance cache other than user table data, which is already accurate
2305 $this->clearInstanceCache();
2306 }
2307
2308 /**
2309 * If the (non-anonymous) user is blocked, this function will block any IP address
2310 * that they successfully log on from.
2311 */
2312 function spreadBlock() {
2313 wfDebug( __METHOD__."()\n" );
2314 $this->load();
2315 if ( $this->mId == 0 ) {
2316 return;
2317 }
2318
2319 $userblock = Block::newFromDB( '', $this->mId );
2320 if ( !$userblock ) {
2321 return;
2322 }
2323
2324 $userblock->doAutoblock( wfGetIp() );
2325
2326 }
2327
2328 /**
2329 * Generate a string which will be different for any combination of
2330 * user options which would produce different parser output.
2331 * This will be used as part of the hash key for the parser cache,
2332 * so users will the same options can share the same cached data
2333 * safely.
2334 *
2335 * Extensions which require it should install 'PageRenderingHash' hook,
2336 * which will give them a chance to modify this key based on their own
2337 * settings.
2338 *
2339 * @return string
2340 */
2341 function getPageRenderingHash() {
2342 global $wgContLang, $wgUseDynamicDates, $wgLang;
2343 if( $this->mHash ){
2344 return $this->mHash;
2345 }
2346
2347 // stubthreshold is only included below for completeness,
2348 // it will always be 0 when this function is called by parsercache.
2349
2350 $confstr = $this->getOption( 'math' );
2351 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2352 if ( $wgUseDynamicDates ) {
2353 $confstr .= '!' . $this->getDatePreference();
2354 }
2355 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
2356 $confstr .= '!' . $wgLang->getCode();
2357 $confstr .= '!' . $this->getOption( 'thumbsize' );
2358 // add in language specific options, if any
2359 $extra = $wgContLang->getExtraHashOptions();
2360 $confstr .= $extra;
2361
2362 // Give a chance for extensions to modify the hash, if they have
2363 // extra options or other effects on the parser cache.
2364 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2365
2366 // Make it a valid memcached key fragment
2367 $confstr = str_replace( ' ', '_', $confstr );
2368 $this->mHash = $confstr;
2369 return $confstr;
2370 }
2371
2372 function isBlockedFromCreateAccount() {
2373 $this->getBlockedStatus();
2374 return $this->mBlock && $this->mBlock->mCreateAccount;
2375 }
2376
2377 /**
2378 * Determine if the user is blocked from using Special:Emailuser.
2379 *
2380 * @public
2381 * @return boolean
2382 */
2383 function isBlockedFromEmailuser() {
2384 $this->getBlockedStatus();
2385 return $this->mBlock && $this->mBlock->mBlockEmail;
2386 }
2387
2388 function isAllowedToCreateAccount() {
2389 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2390 }
2391
2392 /**
2393 * @deprecated
2394 */
2395 function setLoaded( $loaded ) {
2396 wfDeprecated( __METHOD__ );
2397 }
2398
2399 /**
2400 * Get this user's personal page title.
2401 *
2402 * @return Title
2403 * @public
2404 */
2405 function getUserPage() {
2406 return Title::makeTitle( NS_USER, $this->getName() );
2407 }
2408
2409 /**
2410 * Get this user's talk page title.
2411 *
2412 * @return Title
2413 * @public
2414 */
2415 function getTalkPage() {
2416 $title = $this->getUserPage();
2417 return $title->getTalkPage();
2418 }
2419
2420 /**
2421 * @static
2422 */
2423 function getMaxID() {
2424 static $res; // cache
2425
2426 if ( isset( $res ) )
2427 return $res;
2428 else {
2429 $dbr = wfGetDB( DB_SLAVE );
2430 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2431 }
2432 }
2433
2434 /**
2435 * Determine whether the user is a newbie. Newbies are either
2436 * anonymous IPs, or the most recently created accounts.
2437 * @return bool True if it is a newbie.
2438 */
2439 function isNewbie() {
2440 return !$this->isAllowed( 'autoconfirmed' );
2441 }
2442
2443 /**
2444 * Check to see if the given clear-text password is one of the accepted passwords
2445 * @param string $password User password.
2446 * @return bool True if the given password is correct otherwise False.
2447 */
2448 function checkPassword( $password ) {
2449 global $wgAuth;
2450 $this->load();
2451
2452 // Even though we stop people from creating passwords that
2453 // are shorter than this, doesn't mean people wont be able
2454 // to. Certain authentication plugins do NOT want to save
2455 // domain passwords in a mysql database, so we should
2456 // check this (incase $wgAuth->strict() is false).
2457 if( !$this->isValidPassword( $password ) ) {
2458 return false;
2459 }
2460
2461 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2462 return true;
2463 } elseif( $wgAuth->strict() ) {
2464 /* Auth plugin doesn't allow local authentication */
2465 return false;
2466 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2467 /* Auth plugin doesn't allow local authentication for this user name */
2468 return false;
2469 }
2470 $ep = $this->encryptPassword( $password );
2471 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
2472 return true;
2473 } elseif ( function_exists( 'iconv' ) ) {
2474 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2475 # Check for this with iconv
2476 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2477 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
2478 return true;
2479 }
2480 }
2481 return false;
2482 }
2483
2484 /**
2485 * Check if the given clear-text password matches the temporary password
2486 * sent by e-mail for password reset operations.
2487 * @return bool
2488 */
2489 function checkTemporaryPassword( $plaintext ) {
2490 $hash = $this->encryptPassword( $plaintext );
2491 return $hash === $this->mNewpassword;
2492 }
2493
2494 /**
2495 * Initialize (if necessary) and return a session token value
2496 * which can be used in edit forms to show that the user's
2497 * login credentials aren't being hijacked with a foreign form
2498 * submission.
2499 *
2500 * @param mixed $salt - Optional function-specific data for hash.
2501 * Use a string or an array of strings.
2502 * @return string
2503 * @public
2504 */
2505 function editToken( $salt = '' ) {
2506 if ( $this->isAnon() ) {
2507 return EDIT_TOKEN_SUFFIX;
2508 } else {
2509 if( !isset( $_SESSION['wsEditToken'] ) ) {
2510 $token = $this->generateToken();
2511 $_SESSION['wsEditToken'] = $token;
2512 } else {
2513 $token = $_SESSION['wsEditToken'];
2514 }
2515 if( is_array( $salt ) ) {
2516 $salt = implode( '|', $salt );
2517 }
2518 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2519 }
2520 }
2521
2522 /**
2523 * Generate a hex-y looking random token for various uses.
2524 * Could be made more cryptographically sure if someone cares.
2525 * @return string
2526 */
2527 function generateToken( $salt = '' ) {
2528 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2529 return md5( $token . $salt );
2530 }
2531
2532 /**
2533 * Check given value against the token value stored in the session.
2534 * A match should confirm that the form was submitted from the
2535 * user's own login session, not a form submission from a third-party
2536 * site.
2537 *
2538 * @param string $val - the input value to compare
2539 * @param string $salt - Optional function-specific data for hash
2540 * @return bool
2541 * @public
2542 */
2543 function matchEditToken( $val, $salt = '' ) {
2544 $sessionToken = $this->editToken( $salt );
2545 if ( $val != $sessionToken ) {
2546 wfDebug( "User::matchEditToken: broken session data\n" );
2547 }
2548 return $val == $sessionToken;
2549 }
2550
2551 /**
2552 * Check whether the edit token is fine except for the suffix
2553 */
2554 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2555 $sessionToken = $this->editToken( $salt );
2556 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2557 }
2558
2559 /**
2560 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2561 * mail to the user's given address.
2562 *
2563 * Calls saveSettings() internally; as it has side effects, not committing changes
2564 * would be pretty silly.
2565 *
2566 * @return mixed True on success, a WikiError object on failure.
2567 */
2568 function sendConfirmationMail() {
2569 global $wgLang;
2570 $expiration = null; // gets passed-by-ref and defined in next line.
2571 $token = $this->confirmationToken( $expiration );
2572 $url = $this->confirmationTokenUrl( $token );
2573 $invalidateURL = $this->invalidationTokenUrl( $token );
2574 $this->saveSettings();
2575
2576 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2577 wfMsg( 'confirmemail_body',
2578 wfGetIP(),
2579 $this->getName(),
2580 $url,
2581 $wgLang->timeanddate( $expiration, false ),
2582 $invalidateURL ) );
2583 }
2584
2585 /**
2586 * Send an e-mail to this user's account. Does not check for
2587 * confirmed status or validity.
2588 *
2589 * @param string $subject
2590 * @param string $body
2591 * @param string $from Optional from address; default $wgPasswordSender will be used otherwise.
2592 * @return mixed True on success, a WikiError object on failure.
2593 */
2594 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2595 if( is_null( $from ) ) {
2596 global $wgPasswordSender;
2597 $from = $wgPasswordSender;
2598 }
2599
2600 $to = new MailAddress( $this );
2601 $sender = new MailAddress( $from );
2602 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2603 }
2604
2605 /**
2606 * Generate, store, and return a new e-mail confirmation code.
2607 * A hash (unsalted since it's used as a key) is stored.
2608 *
2609 * Call saveSettings() after calling this function to commit
2610 * this change to the database.
2611 *
2612 * @param &$expiration mixed output: accepts the expiration time
2613 * @return string
2614 * @private
2615 */
2616 function confirmationToken( &$expiration ) {
2617 $now = time();
2618 $expires = $now + 7 * 24 * 60 * 60;
2619 $expiration = wfTimestamp( TS_MW, $expires );
2620 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
2621 $hash = md5( $token );
2622 $this->load();
2623 $this->mEmailToken = $hash;
2624 $this->mEmailTokenExpires = $expiration;
2625 return $token;
2626 }
2627
2628 /**
2629 * Return a URL the user can use to confirm their email address.
2630 * @param $token: accepts the email confirmation token
2631 * @return string
2632 * @private
2633 */
2634 function confirmationTokenUrl( $token ) {
2635 return $this->getTokenUrl( 'ConfirmEmail', $token );
2636 }
2637 /**
2638 * Return a URL the user can use to invalidate their email address.
2639 * @param $token: accepts the email confirmation token
2640 * @return string
2641 * @private
2642 */
2643 function invalidationTokenUrl( $token ) {
2644 return $this->getTokenUrl( 'Invalidateemail', $token );
2645 }
2646
2647 /**
2648 * Internal function to format the e-mail validation/invalidation URLs.
2649 * This uses $wgArticlePath directly as a quickie hack to use the
2650 * hardcoded English names of the Special: pages, for ASCII safety.
2651 *
2652 * Since these URLs get dropped directly into emails, using the
2653 * short English names avoids insanely long URL-encoded links, which
2654 * also sometimes can get corrupted in some browsers/mailers
2655 * (bug 6957 with Gmail and Internet Explorer).
2656 */
2657 protected function getTokenUrl( $page, $token ) {
2658 global $wgArticlePath;
2659 return wfExpandUrl(
2660 str_replace(
2661 '$1',
2662 "Special:$page/$token",
2663 $wgArticlePath ) );
2664 }
2665
2666 /**
2667 * Mark the e-mail address confirmed.
2668 *
2669 * Call saveSettings() after calling this function to commit the change.
2670 */
2671 function confirmEmail() {
2672 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2673 return true;
2674 }
2675
2676 /**
2677 * Invalidate the user's email confirmation, unauthenticate the email
2678 * if it was already confirmed.
2679 *
2680 * Call saveSettings() after calling this function to commit the change.
2681 */
2682 function invalidateEmail() {
2683 $this->load();
2684 $this->mEmailToken = null;
2685 $this->mEmailTokenExpires = null;
2686 $this->setEmailAuthenticationTimestamp( null );
2687 return true;
2688 }
2689
2690 function setEmailAuthenticationTimestamp( $timestamp ) {
2691 $this->load();
2692 $this->mEmailAuthenticated = $timestamp;
2693 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2694 }
2695
2696 /**
2697 * Is this user allowed to send e-mails within limits of current
2698 * site configuration?
2699 * @return bool
2700 */
2701 function canSendEmail() {
2702 $canSend = $this->isEmailConfirmed();
2703 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2704 return $canSend;
2705 }
2706
2707 /**
2708 * Is this user allowed to receive e-mails within limits of current
2709 * site configuration?
2710 * @return bool
2711 */
2712 function canReceiveEmail() {
2713 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2714 }
2715
2716 /**
2717 * Is this user's e-mail address valid-looking and confirmed within
2718 * limits of the current site configuration?
2719 *
2720 * If $wgEmailAuthentication is on, this may require the user to have
2721 * confirmed their address by returning a code or using a password
2722 * sent to the address from the wiki.
2723 *
2724 * @return bool
2725 */
2726 function isEmailConfirmed() {
2727 global $wgEmailAuthentication;
2728 $this->load();
2729 $confirmed = true;
2730 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2731 if( $this->isAnon() )
2732 return false;
2733 if( !self::isValidEmailAddr( $this->mEmail ) )
2734 return false;
2735 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2736 return false;
2737 return true;
2738 } else {
2739 return $confirmed;
2740 }
2741 }
2742
2743 /**
2744 * Return true if there is an outstanding request for e-mail confirmation.
2745 * @return bool
2746 */
2747 function isEmailConfirmationPending() {
2748 global $wgEmailAuthentication;
2749 return $wgEmailAuthentication &&
2750 !$this->isEmailConfirmed() &&
2751 $this->mEmailToken &&
2752 $this->mEmailTokenExpires > wfTimestamp();
2753 }
2754
2755 /**
2756 * Get the timestamp of account creation, or false for
2757 * non-existent/anonymous user accounts
2758 *
2759 * @return mixed
2760 */
2761 public function getRegistration() {
2762 return $this->mId > 0
2763 ? $this->mRegistration
2764 : false;
2765 }
2766
2767 /**
2768 * @param array $groups list of groups
2769 * @return array list of permission key names for given groups combined
2770 */
2771 static function getGroupPermissions( $groups ) {
2772 global $wgGroupPermissions;
2773 $rights = array();
2774 foreach( $groups as $group ) {
2775 if( isset( $wgGroupPermissions[$group] ) ) {
2776 $rights = array_merge( $rights,
2777 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2778 }
2779 }
2780 return $rights;
2781 }
2782
2783 /**
2784 * @param string $group key name
2785 * @return string localized descriptive name for group, if provided
2786 */
2787 static function getGroupName( $group ) {
2788 global $wgMessageCache;
2789 $wgMessageCache->loadAllMessages();
2790 $key = "group-$group";
2791 $name = wfMsg( $key );
2792 return $name == '' || wfEmptyMsg( $key, $name )
2793 ? $group
2794 : $name;
2795 }
2796
2797 /**
2798 * @param string $group key name
2799 * @return string localized descriptive name for member of a group, if provided
2800 */
2801 static function getGroupMember( $group ) {
2802 global $wgMessageCache;
2803 $wgMessageCache->loadAllMessages();
2804 $key = "group-$group-member";
2805 $name = wfMsg( $key );
2806 return $name == '' || wfEmptyMsg( $key, $name )
2807 ? $group
2808 : $name;
2809 }
2810
2811 /**
2812 * Return the set of defined explicit groups.
2813 * The implicit groups (by default *, 'user' and 'autoconfirmed')
2814 * are not included, as they are defined automatically,
2815 * not in the database.
2816 * @return array
2817 */
2818 static function getAllGroups() {
2819 global $wgGroupPermissions;
2820 return array_diff(
2821 array_keys( $wgGroupPermissions ),
2822 self::getImplicitGroups()
2823 );
2824 }
2825
2826 /**
2827 * Get a list of all available permissions
2828 */
2829 static function getAllRights() {
2830 if ( self::$mAllRights === false ) {
2831 global $wgAvailableRights;
2832 if ( count( $wgAvailableRights ) ) {
2833 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
2834 } else {
2835 self::$mAllRights = self::$mCoreRights;
2836 }
2837 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
2838 }
2839 return self::$mAllRights;
2840 }
2841
2842 /**
2843 * Get a list of implicit groups
2844 *
2845 * @return array
2846 */
2847 public static function getImplicitGroups() {
2848 global $wgImplicitGroups;
2849 $groups = $wgImplicitGroups;
2850 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
2851 return $groups;
2852 }
2853
2854 /**
2855 * Get the title of a page describing a particular group
2856 *
2857 * @param $group Name of the group
2858 * @return mixed
2859 */
2860 static function getGroupPage( $group ) {
2861 global $wgMessageCache;
2862 $wgMessageCache->loadAllMessages();
2863 $page = wfMsgForContent( 'grouppage-' . $group );
2864 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2865 $title = Title::newFromText( $page );
2866 if( is_object( $title ) )
2867 return $title;
2868 }
2869 return false;
2870 }
2871
2872 /**
2873 * Create a link to the group in HTML, if available
2874 *
2875 * @param $group Name of the group
2876 * @param $text The text of the link
2877 * @return mixed
2878 */
2879 static function makeGroupLinkHTML( $group, $text = '' ) {
2880 if( $text == '' ) {
2881 $text = self::getGroupName( $group );
2882 }
2883 $title = self::getGroupPage( $group );
2884 if( $title ) {
2885 global $wgUser;
2886 $sk = $wgUser->getSkin();
2887 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2888 } else {
2889 return $text;
2890 }
2891 }
2892
2893 /**
2894 * Create a link to the group in Wikitext, if available
2895 *
2896 * @param $group Name of the group
2897 * @param $text The text of the link (by default, the name of the group)
2898 * @return mixed
2899 */
2900 static function makeGroupLinkWiki( $group, $text = '' ) {
2901 if( $text == '' ) {
2902 $text = self::getGroupName( $group );
2903 }
2904 $title = self::getGroupPage( $group );
2905 if( $title ) {
2906 $page = $title->getPrefixedText();
2907 return "[[$page|$text]]";
2908 } else {
2909 return $text;
2910 }
2911 }
2912
2913 /**
2914 * Increment the user's edit-count field.
2915 * Will have no effect for anonymous users.
2916 */
2917 function incEditCount() {
2918 if( !$this->isAnon() ) {
2919 $dbw = wfGetDB( DB_MASTER );
2920 $dbw->update( 'user',
2921 array( 'user_editcount=user_editcount+1' ),
2922 array( 'user_id' => $this->getId() ),
2923 __METHOD__ );
2924
2925 // Lazy initialization check...
2926 if( $dbw->affectedRows() == 0 ) {
2927 // Pull from a slave to be less cruel to servers
2928 // Accuracy isn't the point anyway here
2929 $dbr = wfGetDB( DB_SLAVE );
2930 $count = $dbr->selectField( 'revision',
2931 'COUNT(rev_user)',
2932 array( 'rev_user' => $this->getId() ),
2933 __METHOD__ );
2934
2935 // Now here's a goddamn hack...
2936 if( $dbr !== $dbw ) {
2937 // If we actually have a slave server, the count is
2938 // at least one behind because the current transaction
2939 // has not been committed and replicated.
2940 $count++;
2941 } else {
2942 // But if DB_SLAVE is selecting the master, then the
2943 // count we just read includes the revision that was
2944 // just added in the working transaction.
2945 }
2946
2947 $dbw->update( 'user',
2948 array( 'user_editcount' => $count ),
2949 array( 'user_id' => $this->getId() ),
2950 __METHOD__ );
2951 }
2952 }
2953 // edit count in user cache too
2954 $this->invalidateCache();
2955 }
2956
2957 static function getRightDescription( $right ) {
2958 global $wgMessageCache;
2959 $wgMessageCache->loadAllMessages();
2960 $key = "right-$right";
2961 $name = wfMsg( $key );
2962 return $name == '' || wfEmptyMsg( $key, $name )
2963 ? $right
2964 : $name;
2965 }
2966 }