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