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