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