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