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