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