Typo in previous commit.
[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 function getToken() {
1583 $this->load();
1584 return $this->mToken;
1585 }
1586
1587 /**
1588 * Set the random token (used for persistent authentication)
1589 * Called from loadDefaults() among other places.
1590 * @private
1591 */
1592 function setToken( $token = false ) {
1593 global $wgSecretKey, $wgProxyKey;
1594 $this->load();
1595 if ( !$token ) {
1596 if ( $wgSecretKey ) {
1597 $key = $wgSecretKey;
1598 } elseif ( $wgProxyKey ) {
1599 $key = $wgProxyKey;
1600 } else {
1601 $key = microtime();
1602 }
1603 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1604 } else {
1605 $this->mToken = $token;
1606 }
1607 }
1608
1609 function setCookiePassword( $str ) {
1610 $this->load();
1611 $this->mCookiePassword = md5( $str );
1612 }
1613
1614 /**
1615 * Set the password for a password reminder or new account email
1616 * Sets the user_newpass_time field if $throttle is true
1617 */
1618 function setNewpassword( $str, $throttle = true ) {
1619 $this->load();
1620 $this->mNewpassword = $this->encryptPassword( $str );
1621 if ( $throttle ) {
1622 $this->mNewpassTime = wfTimestampNow();
1623 }
1624 }
1625
1626 /**
1627 * Returns true if a password reminder email has already been sent within
1628 * the last $wgPasswordReminderResendTime hours
1629 */
1630 function isPasswordReminderThrottled() {
1631 global $wgPasswordReminderResendTime;
1632 $this->load();
1633 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1634 return false;
1635 }
1636 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1637 return time() < $expiry;
1638 }
1639
1640 function getEmail() {
1641 $this->load();
1642 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1643 return $this->mEmail;
1644 }
1645
1646 function getEmailAuthenticationTimestamp() {
1647 $this->load();
1648 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1649 return $this->mEmailAuthenticated;
1650 }
1651
1652 function setEmail( $str ) {
1653 $this->load();
1654 $this->mEmail = $str;
1655 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1656 }
1657
1658 function getRealName() {
1659 $this->load();
1660 return $this->mRealName;
1661 }
1662
1663 function setRealName( $str ) {
1664 $this->load();
1665 $this->mRealName = $str;
1666 }
1667
1668 /**
1669 * @param string $oname The option to check
1670 * @param string $defaultOverride A default value returned if the option does not exist
1671 * @return string
1672 */
1673 function getOption( $oname, $defaultOverride = '' ) {
1674 $this->load();
1675
1676 if ( is_null( $this->mOptions ) ) {
1677 if($defaultOverride != '') {
1678 return $defaultOverride;
1679 }
1680 $this->mOptions = User::getDefaultOptions();
1681 }
1682
1683 if ( array_key_exists( $oname, $this->mOptions ) ) {
1684 return trim( $this->mOptions[$oname] );
1685 } else {
1686 return $defaultOverride;
1687 }
1688 }
1689
1690 /**
1691 * Get the user's date preference, including some important migration for
1692 * old user rows.
1693 */
1694 function getDatePreference() {
1695 if ( is_null( $this->mDatePreference ) ) {
1696 global $wgLang;
1697 $value = $this->getOption( 'date' );
1698 $map = $wgLang->getDatePreferenceMigrationMap();
1699 if ( isset( $map[$value] ) ) {
1700 $value = $map[$value];
1701 }
1702 $this->mDatePreference = $value;
1703 }
1704 return $this->mDatePreference;
1705 }
1706
1707 /**
1708 * @param string $oname The option to check
1709 * @return bool False if the option is not selected, true if it is
1710 */
1711 function getBoolOption( $oname ) {
1712 return (bool)$this->getOption( $oname );
1713 }
1714
1715 /**
1716 * Get an option as an integer value from the source string.
1717 * @param string $oname The option to check
1718 * @param int $default Optional value to return if option is unset/blank.
1719 * @return int
1720 */
1721 function getIntOption( $oname, $default=0 ) {
1722 $val = $this->getOption( $oname );
1723 if( $val == '' ) {
1724 $val = $default;
1725 }
1726 return intval( $val );
1727 }
1728
1729 function setOption( $oname, $val ) {
1730 $this->load();
1731 if ( is_null( $this->mOptions ) ) {
1732 $this->mOptions = User::getDefaultOptions();
1733 }
1734 if ( $oname == 'skin' ) {
1735 # Clear cached skin, so the new one displays immediately in Special:Preferences
1736 unset( $this->mSkin );
1737 }
1738 // Filter out any newlines that may have passed through input validation.
1739 // Newlines are used to separate items in the options blob.
1740 if( $val ) {
1741 $val = str_replace( "\r\n", "\n", $val );
1742 $val = str_replace( "\r", "\n", $val );
1743 $val = str_replace( "\n", " ", $val );
1744 }
1745 // Explicitly NULL values should refer to defaults
1746 global $wgDefaultUserOptions;
1747 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1748 $val = $wgDefaultUserOptions[$oname];
1749 }
1750 $this->mOptions[$oname] = $val;
1751 }
1752
1753 function getRights() {
1754 if ( is_null( $this->mRights ) ) {
1755 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
1756 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
1757 // Force reindexation of rights when a hook has unset one of them
1758 $this->mRights = array_values( $this->mRights );
1759 }
1760 return $this->mRights;
1761 }
1762
1763 /**
1764 * Get the list of explicit group memberships this user has.
1765 * The implicit * and user groups are not included.
1766 * @return array of strings
1767 */
1768 function getGroups() {
1769 $this->load();
1770 return $this->mGroups;
1771 }
1772
1773 /**
1774 * Get the list of implicit group memberships this user has.
1775 * This includes all explicit groups, plus 'user' if logged in,
1776 * '*' for all accounts and autopromoted groups
1777 * @param boolean $recache Don't use the cache
1778 * @return array of strings
1779 */
1780 function getEffectiveGroups( $recache = false ) {
1781 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
1782 $this->mEffectiveGroups = $this->getGroups();
1783 $this->mEffectiveGroups[] = '*';
1784 if( $this->getId() ) {
1785 $this->mEffectiveGroups[] = 'user';
1786
1787 $this->mEffectiveGroups = array_unique( array_merge(
1788 $this->mEffectiveGroups,
1789 Autopromote::getAutopromoteGroups( $this )
1790 ) );
1791
1792 # Hook for additional groups
1793 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
1794 }
1795 }
1796 return $this->mEffectiveGroups;
1797 }
1798
1799 /* Return the edit count for the user. This is where User::edits should have been */
1800 function getEditCount() {
1801 if ($this->mId) {
1802 if ( !isset( $this->mEditCount ) ) {
1803 /* Populate the count, if it has not been populated yet */
1804 $this->mEditCount = User::edits($this->mId);
1805 }
1806 return $this->mEditCount;
1807 } else {
1808 /* nil */
1809 return null;
1810 }
1811 }
1812
1813 /**
1814 * Add the user to the given group.
1815 * This takes immediate effect.
1816 * @param string $group
1817 */
1818 function addGroup( $group ) {
1819 $dbw = wfGetDB( DB_MASTER );
1820 if( $this->getId() ) {
1821 $dbw->insert( 'user_groups',
1822 array(
1823 'ug_user' => $this->getID(),
1824 'ug_group' => $group,
1825 ),
1826 'User::addGroup',
1827 array( 'IGNORE' ) );
1828 }
1829
1830 $this->loadGroups();
1831 $this->mGroups[] = $group;
1832 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1833
1834 $this->invalidateCache();
1835 }
1836
1837 /**
1838 * Remove the user from the given group.
1839 * This takes immediate effect.
1840 * @param string $group
1841 */
1842 function removeGroup( $group ) {
1843 $this->load();
1844 $dbw = wfGetDB( DB_MASTER );
1845 $dbw->delete( 'user_groups',
1846 array(
1847 'ug_user' => $this->getID(),
1848 'ug_group' => $group,
1849 ),
1850 'User::removeGroup' );
1851
1852 $this->loadGroups();
1853 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
1854 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1855
1856 $this->invalidateCache();
1857 }
1858
1859
1860 /**
1861 * A more legible check for non-anonymousness.
1862 * Returns true if the user is not an anonymous visitor.
1863 *
1864 * @return bool
1865 */
1866 function isLoggedIn() {
1867 return $this->getID() != 0;
1868 }
1869
1870 /**
1871 * A more legible check for anonymousness.
1872 * Returns true if the user is an anonymous visitor.
1873 *
1874 * @return bool
1875 */
1876 function isAnon() {
1877 return !$this->isLoggedIn();
1878 }
1879
1880 /**
1881 * Whether the user is a bot
1882 * @deprecated
1883 */
1884 function isBot() {
1885 wfDeprecated( __METHOD__ );
1886 return $this->isAllowed( 'bot' );
1887 }
1888
1889 /**
1890 * Check if user is allowed to access a feature / make an action
1891 * @param string $action Action to be checked
1892 * @return boolean True: action is allowed, False: action should not be allowed
1893 */
1894 function isAllowed($action='') {
1895 if ( $action === '' )
1896 // In the spirit of DWIM
1897 return true;
1898
1899 return in_array( $action, $this->getRights() );
1900 }
1901
1902 /**
1903 * Check whether to enable recent changes patrol features for this user
1904 * @return bool
1905 */
1906 public function useRCPatrol() {
1907 global $wgUseRCPatrol;
1908 return( $wgUseRCPatrol && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
1909 }
1910
1911 /**
1912 * Check whether to enable recent changes patrol features for this user
1913 * @return bool
1914 */
1915 public function useNPPatrol() {
1916 global $wgUseRCPatrol, $wgUseNPPatrol;
1917 return( ($wgUseRCPatrol || $wgUseNPPatrol) && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
1918 }
1919
1920 /**
1921 * Load a skin if it doesn't exist or return it
1922 * @todo FIXME : need to check the old failback system [AV]
1923 */
1924 function &getSkin() {
1925 global $wgRequest;
1926 if ( ! isset( $this->mSkin ) ) {
1927 wfProfileIn( __METHOD__ );
1928
1929 # get the user skin
1930 $userSkin = $this->getOption( 'skin' );
1931 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1932
1933 $this->mSkin =& Skin::newFromKey( $userSkin );
1934 wfProfileOut( __METHOD__ );
1935 }
1936 return $this->mSkin;
1937 }
1938
1939 /**#@+
1940 * @param string $title Article title to look at
1941 */
1942
1943 /**
1944 * Check watched status of an article
1945 * @return bool True if article is watched
1946 */
1947 function isWatched( $title ) {
1948 $wl = WatchedItem::fromUserTitle( $this, $title );
1949 return $wl->isWatched();
1950 }
1951
1952 /**
1953 * Watch an article
1954 */
1955 function addWatch( $title ) {
1956 $wl = WatchedItem::fromUserTitle( $this, $title );
1957 $wl->addWatch();
1958 $this->invalidateCache();
1959 }
1960
1961 /**
1962 * Stop watching an article
1963 */
1964 function removeWatch( $title ) {
1965 $wl = WatchedItem::fromUserTitle( $this, $title );
1966 $wl->removeWatch();
1967 $this->invalidateCache();
1968 }
1969
1970 /**
1971 * Clear the user's notification timestamp for the given title.
1972 * If e-notif e-mails are on, they will receive notification mails on
1973 * the next change of the page if it's watched etc.
1974 */
1975 function clearNotification( &$title ) {
1976 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
1977
1978 # Do nothing if the database is locked to writes
1979 if( wfReadOnly() ) {
1980 return;
1981 }
1982
1983 if ($title->getNamespace() == NS_USER_TALK &&
1984 $title->getText() == $this->getName() ) {
1985 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1986 return;
1987 $this->setNewtalk( false );
1988 }
1989
1990 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
1991 return;
1992 }
1993
1994 if( $this->isAnon() ) {
1995 // Nothing else to do...
1996 return;
1997 }
1998
1999 // Only update the timestamp if the page is being watched.
2000 // The query to find out if it is watched is cached both in memcached and per-invocation,
2001 // and when it does have to be executed, it can be on a slave
2002 // If this is the user's newtalk page, we always update the timestamp
2003 if ($title->getNamespace() == NS_USER_TALK &&
2004 $title->getText() == $wgUser->getName())
2005 {
2006 $watched = true;
2007 } elseif ( $this->getId() == $wgUser->getId() ) {
2008 $watched = $title->userIsWatching();
2009 } else {
2010 $watched = true;
2011 }
2012
2013 // If the page is watched by the user (or may be watched), update the timestamp on any
2014 // any matching rows
2015 if ( $watched ) {
2016 $dbw = wfGetDB( DB_MASTER );
2017 $dbw->update( 'watchlist',
2018 array( /* SET */
2019 'wl_notificationtimestamp' => NULL
2020 ), array( /* WHERE */
2021 'wl_title' => $title->getDBkey(),
2022 'wl_namespace' => $title->getNamespace(),
2023 'wl_user' => $this->getID()
2024 ), 'User::clearLastVisited'
2025 );
2026 }
2027 }
2028
2029 /**#@-*/
2030
2031 /**
2032 * Resets all of the given user's page-change notification timestamps.
2033 * If e-notif e-mails are on, they will receive notification mails on
2034 * the next change of any watched page.
2035 *
2036 * @param int $currentUser user ID number
2037 * @public
2038 */
2039 function clearAllNotifications( $currentUser ) {
2040 global $wgUseEnotif, $wgShowUpdatedMarker;
2041 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2042 $this->setNewtalk( false );
2043 return;
2044 }
2045 if( $currentUser != 0 ) {
2046 $dbw = wfGetDB( DB_MASTER );
2047 $dbw->update( 'watchlist',
2048 array( /* SET */
2049 'wl_notificationtimestamp' => NULL
2050 ), array( /* WHERE */
2051 'wl_user' => $currentUser
2052 ), __METHOD__
2053 );
2054 # We also need to clear here the "you have new message" notification for the own user_talk page
2055 # This is cleared one page view later in Article::viewUpdates();
2056 }
2057 }
2058
2059 /**
2060 * @private
2061 * @return string Encoding options
2062 */
2063 function encodeOptions() {
2064 $this->load();
2065 if ( is_null( $this->mOptions ) ) {
2066 $this->mOptions = User::getDefaultOptions();
2067 }
2068 $a = array();
2069 foreach ( $this->mOptions as $oname => $oval ) {
2070 array_push( $a, $oname.'='.$oval );
2071 }
2072 $s = implode( "\n", $a );
2073 return $s;
2074 }
2075
2076 /**
2077 * @private
2078 */
2079 function decodeOptions( $str ) {
2080 $this->mOptions = array();
2081 $a = explode( "\n", $str );
2082 foreach ( $a as $s ) {
2083 $m = array();
2084 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2085 $this->mOptions[$m[1]] = $m[2];
2086 }
2087 }
2088 }
2089
2090 protected function setCookie( $name, $value, $exp=0 ) {
2091 global $wgCookiePrefix,$wgCookieDomain,$wgCookieSecure,$wgCookieExpiration, $wgCookieHttpOnly;
2092 if( $exp == 0 ) {
2093 $exp = time() + $wgCookieExpiration;
2094 }
2095 $httpOnlySafe = wfHttpOnlySafe();
2096 wfDebugLog( 'cookie',
2097 'setcookie: "' . implode( '", "',
2098 array(
2099 $wgCookiePrefix . $name,
2100 $value,
2101 $exp,
2102 '/',
2103 $wgCookieDomain,
2104 $wgCookieSecure,
2105 $httpOnlySafe && $wgCookieHttpOnly ) ) . '"' );
2106 if( $httpOnlySafe && isset( $wgCookieHttpOnly ) ) {
2107 setcookie( $wgCookiePrefix . $name,
2108 $value,
2109 $exp,
2110 '/',
2111 $wgCookieDomain,
2112 $wgCookieSecure,
2113 $wgCookieHttpOnly );
2114 } else {
2115 // setcookie() fails on PHP 5.1 if you give it future-compat paramters.
2116 // stab stab!
2117 setcookie( $wgCookiePrefix . $name,
2118 $value,
2119 $exp,
2120 '/',
2121 $wgCookieDomain,
2122 $wgCookieSecure );
2123 }
2124 }
2125
2126 protected function clearCookie( $name ) {
2127 $this->setCookie( $name, '', time() - 86400 );
2128 }
2129
2130 function setCookies() {
2131 $this->load();
2132 if ( 0 == $this->mId ) return;
2133 $session = array(
2134 'wsUserID' => $this->mId,
2135 'wsToken' => $this->mToken,
2136 'wsUserName' => $this->getName()
2137 );
2138 $cookies = array(
2139 'UserID' => $this->mId,
2140 'UserName' => $this->getName(),
2141 );
2142 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2143 $cookies['Token'] = $this->mToken;
2144 } else {
2145 $cookies['Token'] = false;
2146 }
2147
2148 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2149 $_SESSION = $session + $_SESSION;
2150 foreach ( $cookies as $name => $value ) {
2151 if ( $value === false ) {
2152 $this->clearCookie( $name );
2153 } else {
2154 $this->setCookie( $name, $value );
2155 }
2156 }
2157 }
2158
2159 /**
2160 * Logout user.
2161 */
2162 function logout() {
2163 global $wgUser;
2164 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2165 $this->doLogout();
2166 }
2167 }
2168
2169 /**
2170 * Really logout user
2171 * Clears the cookies and session, resets the instance cache
2172 */
2173 function doLogout() {
2174 $this->clearInstanceCache( 'defaults' );
2175
2176 $_SESSION['wsUserID'] = 0;
2177
2178 $this->clearCookie( 'UserID' );
2179 $this->clearCookie( 'Token' );
2180
2181 # Remember when user logged out, to prevent seeing cached pages
2182 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2183 }
2184
2185 /**
2186 * Save object settings into database
2187 * @todo Only rarely do all these fields need to be set!
2188 */
2189 function saveSettings() {
2190 $this->load();
2191 if ( wfReadOnly() ) { return; }
2192 if ( 0 == $this->mId ) { return; }
2193
2194 $this->mTouched = self::newTouchedTimestamp();
2195
2196 $dbw = wfGetDB( DB_MASTER );
2197 $dbw->update( 'user',
2198 array( /* SET */
2199 'user_name' => $this->mName,
2200 'user_password' => $this->mPassword,
2201 'user_newpassword' => $this->mNewpassword,
2202 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2203 'user_real_name' => $this->mRealName,
2204 'user_email' => $this->mEmail,
2205 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2206 'user_options' => $this->encodeOptions(),
2207 'user_touched' => $dbw->timestamp($this->mTouched),
2208 'user_token' => $this->mToken,
2209 'user_email_token' => $this->mEmailToken,
2210 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2211 ), array( /* WHERE */
2212 'user_id' => $this->mId
2213 ), __METHOD__
2214 );
2215 wfRunHooks( 'UserSaveSettings', array( $this ) );
2216 $this->clearSharedCache();
2217 }
2218
2219 /**
2220 * Checks if a user with the given name exists, returns the ID.
2221 */
2222 function idForName() {
2223 $s = trim( $this->getName() );
2224 if ( $s === '' ) return 0;
2225
2226 $dbr = wfGetDB( DB_SLAVE );
2227 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2228 if ( $id === false ) {
2229 $id = 0;
2230 }
2231 return $id;
2232 }
2233
2234 /**
2235 * Add a user to the database, return the user object
2236 *
2237 * @param string $name The user's name
2238 * @param array $params Associative array of non-default parameters to save to the database:
2239 * password The user's password. Password logins will be disabled if this is omitted.
2240 * newpassword A temporary password mailed to the user
2241 * email The user's email address
2242 * email_authenticated The email authentication timestamp
2243 * real_name The user's real name
2244 * options An associative array of non-default options
2245 * token Random authentication token. Do not set.
2246 * registration Registration timestamp. Do not set.
2247 *
2248 * @return User object, or null if the username already exists
2249 */
2250 static function createNew( $name, $params = array() ) {
2251 $user = new User;
2252 $user->load();
2253 if ( isset( $params['options'] ) ) {
2254 $user->mOptions = $params['options'] + $user->mOptions;
2255 unset( $params['options'] );
2256 }
2257 $dbw = wfGetDB( DB_MASTER );
2258 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2259 $fields = array(
2260 'user_id' => $seqVal,
2261 'user_name' => $name,
2262 'user_password' => $user->mPassword,
2263 'user_newpassword' => $user->mNewpassword,
2264 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ),
2265 'user_email' => $user->mEmail,
2266 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2267 'user_real_name' => $user->mRealName,
2268 'user_options' => $user->encodeOptions(),
2269 'user_token' => $user->mToken,
2270 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2271 'user_editcount' => 0,
2272 );
2273 foreach ( $params as $name => $value ) {
2274 $fields["user_$name"] = $value;
2275 }
2276 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2277 if ( $dbw->affectedRows() ) {
2278 $newUser = User::newFromId( $dbw->insertId() );
2279 } else {
2280 $newUser = null;
2281 }
2282 return $newUser;
2283 }
2284
2285 /**
2286 * Add an existing user object to the database
2287 */
2288 function addToDatabase() {
2289 $this->load();
2290 $dbw = wfGetDB( DB_MASTER );
2291 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2292 $dbw->insert( 'user',
2293 array(
2294 'user_id' => $seqVal,
2295 'user_name' => $this->mName,
2296 'user_password' => $this->mPassword,
2297 'user_newpassword' => $this->mNewpassword,
2298 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ),
2299 'user_email' => $this->mEmail,
2300 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2301 'user_real_name' => $this->mRealName,
2302 'user_options' => $this->encodeOptions(),
2303 'user_token' => $this->mToken,
2304 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2305 'user_editcount' => 0,
2306 ), __METHOD__
2307 );
2308 $this->mId = $dbw->insertId();
2309
2310 # Clear instance cache other than user table data, which is already accurate
2311 $this->clearInstanceCache();
2312 }
2313
2314 /**
2315 * If the (non-anonymous) user is blocked, this function will block any IP address
2316 * that they successfully log on from.
2317 */
2318 function spreadBlock() {
2319 wfDebug( __METHOD__."()\n" );
2320 $this->load();
2321 if ( $this->mId == 0 ) {
2322 return;
2323 }
2324
2325 $userblock = Block::newFromDB( '', $this->mId );
2326 if ( !$userblock ) {
2327 return;
2328 }
2329
2330 $userblock->doAutoblock( wfGetIp() );
2331
2332 }
2333
2334 /**
2335 * Generate a string which will be different for any combination of
2336 * user options which would produce different parser output.
2337 * This will be used as part of the hash key for the parser cache,
2338 * so users will the same options can share the same cached data
2339 * safely.
2340 *
2341 * Extensions which require it should install 'PageRenderingHash' hook,
2342 * which will give them a chance to modify this key based on their own
2343 * settings.
2344 *
2345 * @return string
2346 */
2347 function getPageRenderingHash() {
2348 global $wgContLang, $wgUseDynamicDates, $wgLang;
2349 if( $this->mHash ){
2350 return $this->mHash;
2351 }
2352
2353 // stubthreshold is only included below for completeness,
2354 // it will always be 0 when this function is called by parsercache.
2355
2356 $confstr = $this->getOption( 'math' );
2357 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2358 if ( $wgUseDynamicDates ) {
2359 $confstr .= '!' . $this->getDatePreference();
2360 }
2361 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
2362 $confstr .= '!' . $wgLang->getCode();
2363 $confstr .= '!' . $this->getOption( 'thumbsize' );
2364 // add in language specific options, if any
2365 $extra = $wgContLang->getExtraHashOptions();
2366 $confstr .= $extra;
2367
2368 // Give a chance for extensions to modify the hash, if they have
2369 // extra options or other effects on the parser cache.
2370 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2371
2372 // Make it a valid memcached key fragment
2373 $confstr = str_replace( ' ', '_', $confstr );
2374 $this->mHash = $confstr;
2375 return $confstr;
2376 }
2377
2378 function isBlockedFromCreateAccount() {
2379 $this->getBlockedStatus();
2380 return $this->mBlock && $this->mBlock->mCreateAccount;
2381 }
2382
2383 /**
2384 * Determine if the user is blocked from using Special:Emailuser.
2385 *
2386 * @public
2387 * @return boolean
2388 */
2389 function isBlockedFromEmailuser() {
2390 $this->getBlockedStatus();
2391 return $this->mBlock && $this->mBlock->mBlockEmail;
2392 }
2393
2394 function isAllowedToCreateAccount() {
2395 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2396 }
2397
2398 /**
2399 * @deprecated
2400 */
2401 function setLoaded( $loaded ) {
2402 wfDeprecated( __METHOD__ );
2403 }
2404
2405 /**
2406 * Get this user's personal page title.
2407 *
2408 * @return Title
2409 * @public
2410 */
2411 function getUserPage() {
2412 return Title::makeTitle( NS_USER, $this->getName() );
2413 }
2414
2415 /**
2416 * Get this user's talk page title.
2417 *
2418 * @return Title
2419 * @public
2420 */
2421 function getTalkPage() {
2422 $title = $this->getUserPage();
2423 return $title->getTalkPage();
2424 }
2425
2426 /**
2427 * @static
2428 */
2429 function getMaxID() {
2430 static $res; // cache
2431
2432 if ( isset( $res ) )
2433 return $res;
2434 else {
2435 $dbr = wfGetDB( DB_SLAVE );
2436 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2437 }
2438 }
2439
2440 /**
2441 * Determine whether the user is a newbie. Newbies are either
2442 * anonymous IPs, or the most recently created accounts.
2443 * @return bool True if it is a newbie.
2444 */
2445 function isNewbie() {
2446 return !$this->isAllowed( 'autoconfirmed' );
2447 }
2448
2449 /**
2450 * Is the user active? We check to see if they've made at least
2451 * X number of edits in the last Y days.
2452 *
2453 * @return bool true if the user is active, false if not
2454 */
2455 public function isActiveUser() {
2456 global $wgActiveUserEditcount, $wgActiveUserDays;
2457 $dbr = wfGetDB( DB_SLAVE );
2458
2459 // Stolen without shame from RC
2460 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2461 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime % 86400 );
2462 $oldTime = $dbr->timestamp ( $cutoff_unixtime );
2463
2464 $res = $dbr->select( 'revision', '1',
2465 array( 'rev_user_text' => $this->getName(), "rev_timestamp $oldTime "),
2466 __METHOD__,
2467 array('LIMIT' => $wgActiveUserEditcount ) );
2468
2469 return $dbr->numRows($res) == $wgActiveUserEditcount ? true : false;
2470 }
2471
2472 /**
2473 * Check to see if the given clear-text password is one of the accepted passwords
2474 * @param string $password User password.
2475 * @return bool True if the given password is correct otherwise False.
2476 */
2477 function checkPassword( $password ) {
2478 global $wgAuth;
2479 $this->load();
2480
2481 // Even though we stop people from creating passwords that
2482 // are shorter than this, doesn't mean people wont be able
2483 // to. Certain authentication plugins do NOT want to save
2484 // domain passwords in a mysql database, so we should
2485 // check this (incase $wgAuth->strict() is false).
2486 if( !$this->isValidPassword( $password ) ) {
2487 return false;
2488 }
2489
2490 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2491 return true;
2492 } elseif( $wgAuth->strict() ) {
2493 /* Auth plugin doesn't allow local authentication */
2494 return false;
2495 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2496 /* Auth plugin doesn't allow local authentication for this user name */
2497 return false;
2498 }
2499 $ep = $this->encryptPassword( $password );
2500 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
2501 return true;
2502 } elseif ( function_exists( 'iconv' ) ) {
2503 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2504 # Check for this with iconv
2505 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2506 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
2507 return true;
2508 }
2509 }
2510 return false;
2511 }
2512
2513 /**
2514 * Check if the given clear-text password matches the temporary password
2515 * sent by e-mail for password reset operations.
2516 * @return bool
2517 */
2518 function checkTemporaryPassword( $plaintext ) {
2519 $hash = $this->encryptPassword( $plaintext );
2520 return $hash === $this->mNewpassword;
2521 }
2522
2523 /**
2524 * Initialize (if necessary) and return a session token value
2525 * which can be used in edit forms to show that the user's
2526 * login credentials aren't being hijacked with a foreign form
2527 * submission.
2528 *
2529 * @param mixed $salt - Optional function-specific data for hash.
2530 * Use a string or an array of strings.
2531 * @return string
2532 * @public
2533 */
2534 function editToken( $salt = '' ) {
2535 if ( $this->isAnon() ) {
2536 return EDIT_TOKEN_SUFFIX;
2537 } else {
2538 if( !isset( $_SESSION['wsEditToken'] ) ) {
2539 $token = $this->generateToken();
2540 $_SESSION['wsEditToken'] = $token;
2541 } else {
2542 $token = $_SESSION['wsEditToken'];
2543 }
2544 if( is_array( $salt ) ) {
2545 $salt = implode( '|', $salt );
2546 }
2547 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2548 }
2549 }
2550
2551 /**
2552 * Generate a hex-y looking random token for various uses.
2553 * Could be made more cryptographically sure if someone cares.
2554 * @return string
2555 */
2556 function generateToken( $salt = '' ) {
2557 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2558 return md5( $token . $salt );
2559 }
2560
2561 /**
2562 * Check given value against the token value stored in the session.
2563 * A match should confirm that the form was submitted from the
2564 * user's own login session, not a form submission from a third-party
2565 * site.
2566 *
2567 * @param string $val - the input value to compare
2568 * @param string $salt - Optional function-specific data for hash
2569 * @return bool
2570 * @public
2571 */
2572 function matchEditToken( $val, $salt = '' ) {
2573 $sessionToken = $this->editToken( $salt );
2574 if ( $val != $sessionToken ) {
2575 wfDebug( "User::matchEditToken: broken session data\n" );
2576 }
2577 return $val == $sessionToken;
2578 }
2579
2580 /**
2581 * Check whether the edit token is fine except for the suffix
2582 */
2583 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2584 $sessionToken = $this->editToken( $salt );
2585 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2586 }
2587
2588 /**
2589 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2590 * mail to the user's given address.
2591 *
2592 * Calls saveSettings() internally; as it has side effects, not committing changes
2593 * would be pretty silly.
2594 *
2595 * @return mixed True on success, a WikiError object on failure.
2596 */
2597 function sendConfirmationMail() {
2598 global $wgLang;
2599 $expiration = null; // gets passed-by-ref and defined in next line.
2600 $token = $this->confirmationToken( $expiration );
2601 $url = $this->confirmationTokenUrl( $token );
2602 $invalidateURL = $this->invalidationTokenUrl( $token );
2603 $this->saveSettings();
2604
2605 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2606 wfMsg( 'confirmemail_body',
2607 wfGetIP(),
2608 $this->getName(),
2609 $url,
2610 $wgLang->timeanddate( $expiration, false ),
2611 $invalidateURL ) );
2612 }
2613
2614 /**
2615 * Send an e-mail to this user's account. Does not check for
2616 * confirmed status or validity.
2617 *
2618 * @param string $subject
2619 * @param string $body
2620 * @param string $from Optional from address; default $wgPasswordSender will be used otherwise.
2621 * @return mixed True on success, a WikiError object on failure.
2622 */
2623 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2624 if( is_null( $from ) ) {
2625 global $wgPasswordSender;
2626 $from = $wgPasswordSender;
2627 }
2628
2629 $to = new MailAddress( $this );
2630 $sender = new MailAddress( $from );
2631 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2632 }
2633
2634 /**
2635 * Generate, store, and return a new e-mail confirmation code.
2636 * A hash (unsalted since it's used as a key) is stored.
2637 *
2638 * Call saveSettings() after calling this function to commit
2639 * this change to the database.
2640 *
2641 * @param &$expiration mixed output: accepts the expiration time
2642 * @return string
2643 * @private
2644 */
2645 function confirmationToken( &$expiration ) {
2646 $now = time();
2647 $expires = $now + 7 * 24 * 60 * 60;
2648 $expiration = wfTimestamp( TS_MW, $expires );
2649 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
2650 $hash = md5( $token );
2651 $this->load();
2652 $this->mEmailToken = $hash;
2653 $this->mEmailTokenExpires = $expiration;
2654 return $token;
2655 }
2656
2657 /**
2658 * Return a URL the user can use to confirm their email address.
2659 * @param $token: accepts the email confirmation token
2660 * @return string
2661 * @private
2662 */
2663 function confirmationTokenUrl( $token ) {
2664 return $this->getTokenUrl( 'ConfirmEmail', $token );
2665 }
2666 /**
2667 * Return a URL the user can use to invalidate their email address.
2668 * @param $token: accepts the email confirmation token
2669 * @return string
2670 * @private
2671 */
2672 function invalidationTokenUrl( $token ) {
2673 return $this->getTokenUrl( 'Invalidateemail', $token );
2674 }
2675
2676 /**
2677 * Internal function to format the e-mail validation/invalidation URLs.
2678 * This uses $wgArticlePath directly as a quickie hack to use the
2679 * hardcoded English names of the Special: pages, for ASCII safety.
2680 *
2681 * Since these URLs get dropped directly into emails, using the
2682 * short English names avoids insanely long URL-encoded links, which
2683 * also sometimes can get corrupted in some browsers/mailers
2684 * (bug 6957 with Gmail and Internet Explorer).
2685 */
2686 protected function getTokenUrl( $page, $token ) {
2687 global $wgArticlePath;
2688 return wfExpandUrl(
2689 str_replace(
2690 '$1',
2691 "Special:$page/$token",
2692 $wgArticlePath ) );
2693 }
2694
2695 /**
2696 * Mark the e-mail address confirmed.
2697 *
2698 * Call saveSettings() after calling this function to commit the change.
2699 */
2700 function confirmEmail() {
2701 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2702 return true;
2703 }
2704
2705 /**
2706 * Invalidate the user's email confirmation, unauthenticate the email
2707 * if it was already confirmed.
2708 *
2709 * Call saveSettings() after calling this function to commit the change.
2710 */
2711 function invalidateEmail() {
2712 $this->load();
2713 $this->mEmailToken = null;
2714 $this->mEmailTokenExpires = null;
2715 $this->setEmailAuthenticationTimestamp( null );
2716 return true;
2717 }
2718
2719 function setEmailAuthenticationTimestamp( $timestamp ) {
2720 $this->load();
2721 $this->mEmailAuthenticated = $timestamp;
2722 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2723 }
2724
2725 /**
2726 * Is this user allowed to send e-mails within limits of current
2727 * site configuration?
2728 * @return bool
2729 */
2730 function canSendEmail() {
2731 $canSend = $this->isEmailConfirmed();
2732 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2733 return $canSend;
2734 }
2735
2736 /**
2737 * Is this user allowed to receive e-mails within limits of current
2738 * site configuration?
2739 * @return bool
2740 */
2741 function canReceiveEmail() {
2742 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2743 }
2744
2745 /**
2746 * Is this user's e-mail address valid-looking and confirmed within
2747 * limits of the current site configuration?
2748 *
2749 * If $wgEmailAuthentication is on, this may require the user to have
2750 * confirmed their address by returning a code or using a password
2751 * sent to the address from the wiki.
2752 *
2753 * @return bool
2754 */
2755 function isEmailConfirmed() {
2756 global $wgEmailAuthentication;
2757 $this->load();
2758 $confirmed = true;
2759 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2760 if( $this->isAnon() )
2761 return false;
2762 if( !self::isValidEmailAddr( $this->mEmail ) )
2763 return false;
2764 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2765 return false;
2766 return true;
2767 } else {
2768 return $confirmed;
2769 }
2770 }
2771
2772 /**
2773 * Return true if there is an outstanding request for e-mail confirmation.
2774 * @return bool
2775 */
2776 function isEmailConfirmationPending() {
2777 global $wgEmailAuthentication;
2778 return $wgEmailAuthentication &&
2779 !$this->isEmailConfirmed() &&
2780 $this->mEmailToken &&
2781 $this->mEmailTokenExpires > wfTimestamp();
2782 }
2783
2784 /**
2785 * Get the timestamp of account creation, or false for
2786 * non-existent/anonymous user accounts
2787 *
2788 * @return mixed
2789 */
2790 public function getRegistration() {
2791 return $this->mId > 0
2792 ? $this->mRegistration
2793 : false;
2794 }
2795
2796 /**
2797 * @param array $groups list of groups
2798 * @return array list of permission key names for given groups combined
2799 */
2800 static function getGroupPermissions( $groups ) {
2801 global $wgGroupPermissions;
2802 $rights = array();
2803 foreach( $groups as $group ) {
2804 if( isset( $wgGroupPermissions[$group] ) ) {
2805 $rights = array_merge( $rights,
2806 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2807 }
2808 }
2809 return $rights;
2810 }
2811
2812 /**
2813 * @param string $group key name
2814 * @return string localized descriptive name for group, if provided
2815 */
2816 static function getGroupName( $group ) {
2817 global $wgMessageCache;
2818 $wgMessageCache->loadAllMessages();
2819 $key = "group-$group";
2820 $name = wfMsg( $key );
2821 return $name == '' || wfEmptyMsg( $key, $name )
2822 ? $group
2823 : $name;
2824 }
2825
2826 /**
2827 * @param string $group key name
2828 * @return string localized descriptive name for member of a group, if provided
2829 */
2830 static function getGroupMember( $group ) {
2831 global $wgMessageCache;
2832 $wgMessageCache->loadAllMessages();
2833 $key = "group-$group-member";
2834 $name = wfMsg( $key );
2835 return $name == '' || wfEmptyMsg( $key, $name )
2836 ? $group
2837 : $name;
2838 }
2839
2840 /**
2841 * Return the set of defined explicit groups.
2842 * The implicit groups (by default *, 'user' and 'autoconfirmed')
2843 * are not included, as they are defined automatically,
2844 * not in the database.
2845 * @return array
2846 */
2847 static function getAllGroups() {
2848 global $wgGroupPermissions;
2849 return array_diff(
2850 array_keys( $wgGroupPermissions ),
2851 self::getImplicitGroups()
2852 );
2853 }
2854
2855 /**
2856 * Get a list of all available permissions
2857 */
2858 static function getAllRights() {
2859 if ( self::$mAllRights === false ) {
2860 global $wgAvailableRights;
2861 if ( count( $wgAvailableRights ) ) {
2862 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
2863 } else {
2864 self::$mAllRights = self::$mCoreRights;
2865 }
2866 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
2867 }
2868 return self::$mAllRights;
2869 }
2870
2871 /**
2872 * Get a list of implicit groups
2873 *
2874 * @return array
2875 */
2876 public static function getImplicitGroups() {
2877 global $wgImplicitGroups;
2878 $groups = $wgImplicitGroups;
2879 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
2880 return $groups;
2881 }
2882
2883 /**
2884 * Get the title of a page describing a particular group
2885 *
2886 * @param $group Name of the group
2887 * @return mixed
2888 */
2889 static function getGroupPage( $group ) {
2890 global $wgMessageCache;
2891 $wgMessageCache->loadAllMessages();
2892 $page = wfMsgForContent( 'grouppage-' . $group );
2893 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2894 $title = Title::newFromText( $page );
2895 if( is_object( $title ) )
2896 return $title;
2897 }
2898 return false;
2899 }
2900
2901 /**
2902 * Create a link to the group in HTML, if available
2903 *
2904 * @param $group Name of the group
2905 * @param $text The text of the link
2906 * @return mixed
2907 */
2908 static function makeGroupLinkHTML( $group, $text = '' ) {
2909 if( $text == '' ) {
2910 $text = self::getGroupName( $group );
2911 }
2912 $title = self::getGroupPage( $group );
2913 if( $title ) {
2914 global $wgUser;
2915 $sk = $wgUser->getSkin();
2916 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
2917 } else {
2918 return $text;
2919 }
2920 }
2921
2922 /**
2923 * Create a link to the group in Wikitext, if available
2924 *
2925 * @param $group Name of the group
2926 * @param $text The text of the link (by default, the name of the group)
2927 * @return mixed
2928 */
2929 static function makeGroupLinkWiki( $group, $text = '' ) {
2930 if( $text == '' ) {
2931 $text = self::getGroupName( $group );
2932 }
2933 $title = self::getGroupPage( $group );
2934 if( $title ) {
2935 $page = $title->getPrefixedText();
2936 return "[[$page|$text]]";
2937 } else {
2938 return $text;
2939 }
2940 }
2941
2942 /**
2943 * Increment the user's edit-count field.
2944 * Will have no effect for anonymous users.
2945 */
2946 function incEditCount() {
2947 if( !$this->isAnon() ) {
2948 $dbw = wfGetDB( DB_MASTER );
2949 $dbw->update( 'user',
2950 array( 'user_editcount=user_editcount+1' ),
2951 array( 'user_id' => $this->getId() ),
2952 __METHOD__ );
2953
2954 // Lazy initialization check...
2955 if( $dbw->affectedRows() == 0 ) {
2956 // Pull from a slave to be less cruel to servers
2957 // Accuracy isn't the point anyway here
2958 $dbr = wfGetDB( DB_SLAVE );
2959 $count = $dbr->selectField( 'revision',
2960 'COUNT(rev_user)',
2961 array( 'rev_user' => $this->getId() ),
2962 __METHOD__ );
2963
2964 // Now here's a goddamn hack...
2965 if( $dbr !== $dbw ) {
2966 // If we actually have a slave server, the count is
2967 // at least one behind because the current transaction
2968 // has not been committed and replicated.
2969 $count++;
2970 } else {
2971 // But if DB_SLAVE is selecting the master, then the
2972 // count we just read includes the revision that was
2973 // just added in the working transaction.
2974 }
2975
2976 $dbw->update( 'user',
2977 array( 'user_editcount' => $count ),
2978 array( 'user_id' => $this->getId() ),
2979 __METHOD__ );
2980 }
2981 }
2982 // edit count in user cache too
2983 $this->invalidateCache();
2984 }
2985
2986 static function getRightDescription( $right ) {
2987 global $wgMessageCache;
2988 $wgMessageCache->loadAllMessages();
2989 $key = "right-$right";
2990 $name = wfMsg( $key );
2991 return $name == '' || wfEmptyMsg( $key, $name )
2992 ? $right
2993 : $name;
2994 }
2995 }