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