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