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