Add new hook 'UserLoadFromDatabase' that is called while loading a user from the...
[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 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
890
891 if ( $s !== false ) {
892 # Initialise user table data
893 $this->loadFromRow( $s );
894 $this->mGroups = null; // deferred
895 $this->getEditCount(); // revalidation for nulls
896 return true;
897 } else {
898 # Invalid user_id
899 $this->mId = 0;
900 $this->loadDefaults();
901 return false;
902 }
903 }
904
905 /**
906 * Initialize this object from a row from the user table.
907 *
908 * @param $row \type{\arrayof{\mixed}} Row from the user table to load.
909 */
910 function loadFromRow( $row ) {
911 $this->mDataLoaded = true;
912
913 if ( isset( $row->user_id ) ) {
914 $this->mId = $row->user_id;
915 }
916 $this->mName = $row->user_name;
917 $this->mRealName = $row->user_real_name;
918 $this->mPassword = $row->user_password;
919 $this->mNewpassword = $row->user_newpassword;
920 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
921 $this->mEmail = $row->user_email;
922 $this->decodeOptions( $row->user_options );
923 $this->mTouched = wfTimestamp(TS_MW,$row->user_touched);
924 $this->mToken = $row->user_token;
925 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
926 $this->mEmailToken = $row->user_email_token;
927 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
928 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
929 $this->mEditCount = $row->user_editcount;
930 }
931
932 /**
933 * Load the groups from the database if they aren't already loaded.
934 * @private
935 */
936 function loadGroups() {
937 if ( is_null( $this->mGroups ) ) {
938 $dbr = wfGetDB( DB_MASTER );
939 $res = $dbr->select( 'user_groups',
940 array( 'ug_group' ),
941 array( 'ug_user' => $this->mId ),
942 __METHOD__ );
943 $this->mGroups = array();
944 while( $row = $dbr->fetchObject( $res ) ) {
945 $this->mGroups[] = $row->ug_group;
946 }
947 }
948 }
949
950 /**
951 * Clear various cached data stored in this object.
952 * @param $reloadFrom \string Reload user and user_groups table data from a
953 * given source. May be "name", "id", "defaults", "session", or false for
954 * no reload.
955 */
956 function clearInstanceCache( $reloadFrom = false ) {
957 $this->mNewtalk = -1;
958 $this->mDatePreference = null;
959 $this->mBlockedby = -1; # Unset
960 $this->mHash = false;
961 $this->mSkin = null;
962 $this->mRights = null;
963 $this->mEffectiveGroups = null;
964
965 if ( $reloadFrom ) {
966 $this->mDataLoaded = false;
967 $this->mFrom = $reloadFrom;
968 }
969 }
970
971 /**
972 * Combine the language default options with any site-specific options
973 * and add the default language variants.
974 *
975 * @return \type{\arrayof{\string}} Array of options
976 */
977 static function getDefaultOptions() {
978 global $wgNamespacesToBeSearchedDefault;
979 /**
980 * Site defaults will override the global/language defaults
981 */
982 global $wgDefaultUserOptions, $wgContLang;
983 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
984
985 /**
986 * default language setting
987 */
988 $variant = $wgContLang->getPreferredVariant( false );
989 $defOpt['variant'] = $variant;
990 $defOpt['language'] = $variant;
991
992 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
993 $defOpt['searchNs'.$nsnum] = $val;
994 }
995 return $defOpt;
996 }
997
998 /**
999 * Get a given default option value.
1000 *
1001 * @param $opt \string Name of option to retrieve
1002 * @return \string Default option value
1003 */
1004 public static function getDefaultOption( $opt ) {
1005 $defOpts = self::getDefaultOptions();
1006 if( isset( $defOpts[$opt] ) ) {
1007 return $defOpts[$opt];
1008 } else {
1009 return '';
1010 }
1011 }
1012
1013 /**
1014 * Get a list of user toggle names
1015 * @return \type{\arrayof{\string}} Array of user toggle names
1016 */
1017 static function getToggles() {
1018 global $wgContLang, $wgUseRCPatrol;
1019 $extraToggles = array();
1020 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
1021 if( $wgUseRCPatrol ) {
1022 $extraToggles[] = 'hidepatrolled';
1023 $extraToggles[] = 'watchlisthidepatrolled';
1024 }
1025 return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
1026 }
1027
1028
1029 /**
1030 * Get blocking information
1031 * @private
1032 * @param $bFromSlave \bool Whether to check the slave database first. To
1033 * improve performance, non-critical checks are done
1034 * against slaves. Check when actually saving should be
1035 * done against master.
1036 */
1037 function getBlockedStatus( $bFromSlave = true ) {
1038 global $wgEnableSorbs, $wgProxyWhitelist;
1039
1040 if ( -1 != $this->mBlockedby ) {
1041 wfDebug( "User::getBlockedStatus: already loaded.\n" );
1042 return;
1043 }
1044
1045 wfProfileIn( __METHOD__ );
1046 wfDebug( __METHOD__.": checking...\n" );
1047
1048 // Initialize data...
1049 // Otherwise something ends up stomping on $this->mBlockedby when
1050 // things get lazy-loaded later, causing false positive block hits
1051 // due to -1 !== 0. Probably session-related... Nothing should be
1052 // overwriting mBlockedby, surely?
1053 $this->load();
1054
1055 $this->mBlockedby = 0;
1056 $this->mHideName = 0;
1057 $this->mAllowUsertalk = 0;
1058 $ip = wfGetIP();
1059
1060 if ($this->isAllowed( 'ipblock-exempt' ) ) {
1061 # Exempt from all types of IP-block
1062 $ip = '';
1063 }
1064
1065 # User/IP blocking
1066 $this->mBlock = new Block();
1067 $this->mBlock->fromMaster( !$bFromSlave );
1068 if ( $this->mBlock->load( $ip , $this->mId ) ) {
1069 wfDebug( __METHOD__.": Found block.\n" );
1070 $this->mBlockedby = $this->mBlock->mBy;
1071 $this->mBlockreason = $this->mBlock->mReason;
1072 $this->mHideName = $this->mBlock->mHideName;
1073 $this->mAllowUsertalk = $this->mBlock->mAllowUsertalk;
1074 if ( $this->isLoggedIn() ) {
1075 $this->spreadBlock();
1076 }
1077 } else {
1078 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1079 // apply to users. Note that the existence of $this->mBlock is not used to
1080 // check for edit blocks, $this->mBlockedby is instead.
1081 }
1082
1083 # Proxy blocking
1084 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
1085 # Local list
1086 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1087 $this->mBlockedby = wfMsg( 'proxyblocker' );
1088 $this->mBlockreason = wfMsg( 'proxyblockreason' );
1089 }
1090
1091 # DNSBL
1092 if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
1093 if ( $this->inSorbsBlacklist( $ip ) ) {
1094 $this->mBlockedby = wfMsg( 'sorbs' );
1095 $this->mBlockreason = wfMsg( 'sorbsreason' );
1096 }
1097 }
1098 }
1099
1100 # Extensions
1101 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1102
1103 wfProfileOut( __METHOD__ );
1104 }
1105
1106 /**
1107 * Whether the given IP is in the SORBS blacklist.
1108 *
1109 * @param $ip \string IP to check
1110 * @return \bool True if blacklisted.
1111 */
1112 function inSorbsBlacklist( $ip ) {
1113 global $wgEnableSorbs, $wgSorbsUrl;
1114
1115 return $wgEnableSorbs &&
1116 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
1117 }
1118
1119 /**
1120 * Whether the given IP is in a given DNS blacklist.
1121 *
1122 * @param $ip \string IP to check
1123 * @param $base \string URL of the DNS blacklist
1124 * @return \bool True if blacklisted.
1125 */
1126 function inDnsBlacklist( $ip, $base ) {
1127 wfProfileIn( __METHOD__ );
1128
1129 $found = false;
1130 $host = '';
1131 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1132 if( IP::isIPv4($ip) ) {
1133 # Make hostname
1134 $host = "$ip.$base";
1135
1136 # Send query
1137 $ipList = gethostbynamel( $host );
1138
1139 if( $ipList ) {
1140 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1141 $found = true;
1142 } else {
1143 wfDebug( "Requested $host, not found in $base.\n" );
1144 }
1145 }
1146
1147 wfProfileOut( __METHOD__ );
1148 return $found;
1149 }
1150
1151 /**
1152 * Is this user subject to rate limiting?
1153 *
1154 * @return \bool True if rate limited
1155 */
1156 public function isPingLimitable() {
1157 global $wgRateLimitsExcludedGroups;
1158 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1159 // Deprecated, but kept for backwards-compatibility config
1160 return false;
1161 }
1162 return !$this->isAllowed('noratelimit');
1163 }
1164
1165 /**
1166 * Primitive rate limits: enforce maximum actions per time period
1167 * to put a brake on flooding.
1168 *
1169 * @note When using a shared cache like memcached, IP-address
1170 * last-hit counters will be shared across wikis.
1171 *
1172 * @param $action \string Action to enforce; 'edit' if unspecified
1173 * @return \bool True if a rate limiter was tripped
1174 */
1175 function pingLimiter( $action='edit' ) {
1176
1177 # Call the 'PingLimiter' hook
1178 $result = false;
1179 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1180 return $result;
1181 }
1182
1183 global $wgRateLimits;
1184 if( !isset( $wgRateLimits[$action] ) ) {
1185 return false;
1186 }
1187
1188 # Some groups shouldn't trigger the ping limiter, ever
1189 if( !$this->isPingLimitable() )
1190 return false;
1191
1192 global $wgMemc, $wgRateLimitLog;
1193 wfProfileIn( __METHOD__ );
1194
1195 $limits = $wgRateLimits[$action];
1196 $keys = array();
1197 $id = $this->getId();
1198 $ip = wfGetIP();
1199 $userLimit = false;
1200
1201 if( isset( $limits['anon'] ) && $id == 0 ) {
1202 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1203 }
1204
1205 if( isset( $limits['user'] ) && $id != 0 ) {
1206 $userLimit = $limits['user'];
1207 }
1208 if( $this->isNewbie() ) {
1209 if( isset( $limits['newbie'] ) && $id != 0 ) {
1210 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1211 }
1212 if( isset( $limits['ip'] ) ) {
1213 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1214 }
1215 $matches = array();
1216 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1217 $subnet = $matches[1];
1218 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1219 }
1220 }
1221 // Check for group-specific permissions
1222 // If more than one group applies, use the group with the highest limit
1223 foreach ( $this->getGroups() as $group ) {
1224 if ( isset( $limits[$group] ) ) {
1225 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1226 $userLimit = $limits[$group];
1227 }
1228 }
1229 }
1230 // Set the user limit key
1231 if ( $userLimit !== false ) {
1232 wfDebug( __METHOD__.": effective user limit: $userLimit\n" );
1233 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1234 }
1235
1236 $triggered = false;
1237 foreach( $keys as $key => $limit ) {
1238 list( $max, $period ) = $limit;
1239 $summary = "(limit $max in {$period}s)";
1240 $count = $wgMemc->get( $key );
1241 if( $count ) {
1242 if( $count > $max ) {
1243 wfDebug( __METHOD__.": tripped! $key at $count $summary\n" );
1244 if( $wgRateLimitLog ) {
1245 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1246 }
1247 $triggered = true;
1248 } else {
1249 wfDebug( __METHOD__.": ok. $key at $count $summary\n" );
1250 }
1251 } else {
1252 wfDebug( __METHOD__.": adding record for $key $summary\n" );
1253 $wgMemc->add( $key, 1, intval( $period ) );
1254 }
1255 $wgMemc->incr( $key );
1256 }
1257
1258 wfProfileOut( __METHOD__ );
1259 return $triggered;
1260 }
1261
1262 /**
1263 * Check if user is blocked
1264 *
1265 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1266 * @return \bool True if blocked, false otherwise
1267 */
1268 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1269 wfDebug( "User::isBlocked: enter\n" );
1270 $this->getBlockedStatus( $bFromSlave );
1271 return $this->mBlockedby !== 0;
1272 }
1273
1274 /**
1275 * Check if user is blocked from editing a particular article
1276 *
1277 * @param $title \string Title to check
1278 * @param $bFromSlave \bool Whether to check the slave database instead of the master
1279 * @return \bool True if blocked, false otherwise
1280 */
1281 function isBlockedFrom( $title, $bFromSlave = false ) {
1282 global $wgBlockAllowsUTEdit;
1283 wfProfileIn( __METHOD__ );
1284 wfDebug( __METHOD__.": enter\n" );
1285
1286 wfDebug( __METHOD__.": asking isBlocked()\n" );
1287 $blocked = $this->isBlocked( $bFromSlave );
1288 $allowUsertalk = ($wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false);
1289 # If a user's name is suppressed, they cannot make edits anywhere
1290 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
1291 $title->getNamespace() == NS_USER_TALK ) {
1292 $blocked = false;
1293 wfDebug( __METHOD__.": self-talk page, ignoring any blocks\n" );
1294 }
1295 wfProfileOut( __METHOD__ );
1296 return $blocked;
1297 }
1298
1299 /**
1300 * If user is blocked, return the name of the user who placed the block
1301 * @return \string name of blocker
1302 */
1303 function blockedBy() {
1304 $this->getBlockedStatus();
1305 return $this->mBlockedby;
1306 }
1307
1308 /**
1309 * If user is blocked, return the specified reason for the block
1310 * @return \string Blocking reason
1311 */
1312 function blockedFor() {
1313 $this->getBlockedStatus();
1314 return $this->mBlockreason;
1315 }
1316
1317 /**
1318 * Check if user is blocked on all wikis.
1319 * Do not use for actual edit permission checks!
1320 * This is intented for quick UI checks.
1321 *
1322 * @param $ip \type{\string} IP address, uses current client if none given
1323 * @return \type{\bool} True if blocked, false otherwise
1324 */
1325 function isBlockedGlobally( $ip = '' ) {
1326 if( $this->mBlockedGlobally !== null ) {
1327 return $this->mBlockedGlobally;
1328 }
1329 // User is already an IP?
1330 if( IP::isIPAddress( $this->getName() ) ) {
1331 $ip = $this->getName();
1332 } else if( !$ip ) {
1333 $ip = wfGetIP();
1334 }
1335 $blocked = false;
1336 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1337 $this->mBlockedGlobally = (bool)$blocked;
1338 return $this->mBlockedGlobally;
1339 }
1340
1341 /**
1342 * Check if user account is locked
1343 *
1344 * @return \type{\bool} True if locked, false otherwise
1345 */
1346 function isLocked() {
1347 if( $this->mLocked !== null ) {
1348 return $this->mLocked;
1349 }
1350 global $wgAuth;
1351 $authUser = $wgAuth->getUserInstance( $this );
1352 $this->mLocked = (bool)$authUser->isLocked();
1353 return $this->mLocked;
1354 }
1355
1356 /**
1357 * Check if user account is hidden
1358 *
1359 * @return \type{\bool} True if hidden, false otherwise
1360 */
1361 function isHidden() {
1362 if( $this->mHideName !== null ) {
1363 return $this->mHideName;
1364 }
1365 $this->getBlockedStatus();
1366 if( !$this->mHideName ) {
1367 global $wgAuth;
1368 $authUser = $wgAuth->getUserInstance( $this );
1369 $this->mHideName = (bool)$authUser->isHidden();
1370 }
1371 return $this->mHideName;
1372 }
1373
1374 /**
1375 * Get the user's ID.
1376 * @return \int The user's ID; 0 if the user is anonymous or nonexistent
1377 */
1378 function getId() {
1379 if( $this->mId === null and $this->mName !== null
1380 and User::isIP( $this->mName ) ) {
1381 // Special case, we know the user is anonymous
1382 return 0;
1383 } elseif( $this->mId === null ) {
1384 // Don't load if this was initialized from an ID
1385 $this->load();
1386 }
1387 return $this->mId;
1388 }
1389
1390 /**
1391 * Set the user and reload all fields according to a given ID
1392 * @param $v \int User ID to reload
1393 */
1394 function setId( $v ) {
1395 $this->mId = $v;
1396 $this->clearInstanceCache( 'id' );
1397 }
1398
1399 /**
1400 * Get the user name, or the IP of an anonymous user
1401 * @return \string User's name or IP address
1402 */
1403 function getName() {
1404 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1405 # Special case optimisation
1406 return $this->mName;
1407 } else {
1408 $this->load();
1409 if ( $this->mName === false ) {
1410 # Clean up IPs
1411 $this->mName = IP::sanitizeIP( wfGetIP() );
1412 }
1413 return $this->mName;
1414 }
1415 }
1416
1417 /**
1418 * Set the user name.
1419 *
1420 * This does not reload fields from the database according to the given
1421 * name. Rather, it is used to create a temporary "nonexistent user" for
1422 * later addition to the database. It can also be used to set the IP
1423 * address for an anonymous user to something other than the current
1424 * remote IP.
1425 *
1426 * @note User::newFromName() has rougly the same function, when the named user
1427 * does not exist.
1428 * @param $str \string New user name to set
1429 */
1430 function setName( $str ) {
1431 $this->load();
1432 $this->mName = $str;
1433 }
1434
1435 /**
1436 * Get the user's name escaped by underscores.
1437 * @return \string Username escaped by underscores.
1438 */
1439 function getTitleKey() {
1440 return str_replace( ' ', '_', $this->getName() );
1441 }
1442
1443 /**
1444 * Check if the user has new messages.
1445 * @return \bool True if the user has new messages
1446 */
1447 function getNewtalk() {
1448 $this->load();
1449
1450 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1451 if( $this->mNewtalk === -1 ) {
1452 $this->mNewtalk = false; # reset talk page status
1453
1454 # Check memcached separately for anons, who have no
1455 # entire User object stored in there.
1456 if( !$this->mId ) {
1457 global $wgMemc;
1458 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1459 $newtalk = $wgMemc->get( $key );
1460 if( strval( $newtalk ) !== '' ) {
1461 $this->mNewtalk = (bool)$newtalk;
1462 } else {
1463 // Since we are caching this, make sure it is up to date by getting it
1464 // from the master
1465 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1466 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1467 }
1468 } else {
1469 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1470 }
1471 }
1472
1473 return (bool)$this->mNewtalk;
1474 }
1475
1476 /**
1477 * Return the talk page(s) this user has new messages on.
1478 * @return \type{\arrayof{\string}} Array of page URLs
1479 */
1480 function getNewMessageLinks() {
1481 $talks = array();
1482 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1483 return $talks;
1484
1485 if (!$this->getNewtalk())
1486 return array();
1487 $up = $this->getUserPage();
1488 $utp = $up->getTalkPage();
1489 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1490 }
1491
1492
1493 /**
1494 * Internal uncached check for new messages
1495 *
1496 * @see getNewtalk()
1497 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1498 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1499 * @param $fromMaster \bool true to fetch from the master, false for a slave
1500 * @return \bool True if the user has new messages
1501 * @private
1502 */
1503 function checkNewtalk( $field, $id, $fromMaster = false ) {
1504 if ( $fromMaster ) {
1505 $db = wfGetDB( DB_MASTER );
1506 } else {
1507 $db = wfGetDB( DB_SLAVE );
1508 }
1509 $ok = $db->selectField( 'user_newtalk', $field,
1510 array( $field => $id ), __METHOD__ );
1511 return $ok !== false;
1512 }
1513
1514 /**
1515 * Add or update the new messages flag
1516 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1517 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1518 * @return \bool True if successful, false otherwise
1519 * @private
1520 */
1521 function updateNewtalk( $field, $id ) {
1522 $dbw = wfGetDB( DB_MASTER );
1523 $dbw->insert( 'user_newtalk',
1524 array( $field => $id ),
1525 __METHOD__,
1526 'IGNORE' );
1527 if ( $dbw->affectedRows() ) {
1528 wfDebug( __METHOD__.": set on ($field, $id)\n" );
1529 return true;
1530 } else {
1531 wfDebug( __METHOD__." already set ($field, $id)\n" );
1532 return false;
1533 }
1534 }
1535
1536 /**
1537 * Clear the new messages flag for the given user
1538 * @param $field \string 'user_ip' for anonymous users, 'user_id' otherwise
1539 * @param $id \types{\string,\int} User's IP address for anonymous users, User ID otherwise
1540 * @return \bool True if successful, false otherwise
1541 * @private
1542 */
1543 function deleteNewtalk( $field, $id ) {
1544 $dbw = wfGetDB( DB_MASTER );
1545 $dbw->delete( 'user_newtalk',
1546 array( $field => $id ),
1547 __METHOD__ );
1548 if ( $dbw->affectedRows() ) {
1549 wfDebug( __METHOD__.": killed on ($field, $id)\n" );
1550 return true;
1551 } else {
1552 wfDebug( __METHOD__.": already gone ($field, $id)\n" );
1553 return false;
1554 }
1555 }
1556
1557 /**
1558 * Update the 'You have new messages!' status.
1559 * @param $val \bool Whether the user has new messages
1560 */
1561 function setNewtalk( $val ) {
1562 if( wfReadOnly() ) {
1563 return;
1564 }
1565
1566 $this->load();
1567 $this->mNewtalk = $val;
1568
1569 if( $this->isAnon() ) {
1570 $field = 'user_ip';
1571 $id = $this->getName();
1572 } else {
1573 $field = 'user_id';
1574 $id = $this->getId();
1575 }
1576 global $wgMemc;
1577
1578 if( $val ) {
1579 $changed = $this->updateNewtalk( $field, $id );
1580 } else {
1581 $changed = $this->deleteNewtalk( $field, $id );
1582 }
1583
1584 if( $this->isAnon() ) {
1585 // Anons have a separate memcached space, since
1586 // user records aren't kept for them.
1587 $key = wfMemcKey( 'newtalk', 'ip', $id );
1588 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1589 }
1590 if ( $changed ) {
1591 $this->invalidateCache();
1592 }
1593 }
1594
1595 /**
1596 * Generate a current or new-future timestamp to be stored in the
1597 * user_touched field when we update things.
1598 * @return \string Timestamp in TS_MW format
1599 */
1600 private static function newTouchedTimestamp() {
1601 global $wgClockSkewFudge;
1602 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1603 }
1604
1605 /**
1606 * Clear user data from memcached.
1607 * Use after applying fun updates to the database; caller's
1608 * responsibility to update user_touched if appropriate.
1609 *
1610 * Called implicitly from invalidateCache() and saveSettings().
1611 */
1612 private function clearSharedCache() {
1613 $this->load();
1614 if( $this->mId ) {
1615 global $wgMemc;
1616 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1617 }
1618 }
1619
1620 /**
1621 * Immediately touch the user data cache for this account.
1622 * Updates user_touched field, and removes account data from memcached
1623 * for reload on the next hit.
1624 */
1625 function invalidateCache() {
1626 $this->load();
1627 if( $this->mId ) {
1628 $this->mTouched = self::newTouchedTimestamp();
1629
1630 $dbw = wfGetDB( DB_MASTER );
1631 $dbw->update( 'user',
1632 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1633 array( 'user_id' => $this->mId ),
1634 __METHOD__ );
1635
1636 $this->clearSharedCache();
1637 }
1638 }
1639
1640 /**
1641 * Validate the cache for this account.
1642 * @param $timestamp \string A timestamp in TS_MW format
1643 */
1644 function validateCache( $timestamp ) {
1645 $this->load();
1646 return ($timestamp >= $this->mTouched);
1647 }
1648
1649 /**
1650 * Get the user touched timestamp
1651 */
1652 function getTouched() {
1653 $this->load();
1654 return $this->mTouched;
1655 }
1656
1657 /**
1658 * Set the password and reset the random token.
1659 * Calls through to authentication plugin if necessary;
1660 * will have no effect if the auth plugin refuses to
1661 * pass the change through or if the legal password
1662 * checks fail.
1663 *
1664 * As a special case, setting the password to null
1665 * wipes it, so the account cannot be logged in until
1666 * a new password is set, for instance via e-mail.
1667 *
1668 * @param $str \string New password to set
1669 * @throws PasswordError on failure
1670 */
1671 function setPassword( $str ) {
1672 global $wgAuth;
1673
1674 if( $str !== null ) {
1675 if( !$wgAuth->allowPasswordChange() ) {
1676 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1677 }
1678
1679 if( !$this->isValidPassword( $str ) ) {
1680 global $wgMinimalPasswordLength;
1681 throw new PasswordError( wfMsgExt( 'passwordtooshort', array( 'parsemag' ),
1682 $wgMinimalPasswordLength ) );
1683 }
1684 }
1685
1686 if( !$wgAuth->setPassword( $this, $str ) ) {
1687 throw new PasswordError( wfMsg( 'externaldberror' ) );
1688 }
1689
1690 $this->setInternalPassword( $str );
1691
1692 return true;
1693 }
1694
1695 /**
1696 * Set the password and reset the random token unconditionally.
1697 *
1698 * @param $str \string New password to set
1699 */
1700 function setInternalPassword( $str ) {
1701 $this->load();
1702 $this->setToken();
1703
1704 if( $str === null ) {
1705 // Save an invalid hash...
1706 $this->mPassword = '';
1707 } else {
1708 $this->mPassword = self::crypt( $str );
1709 }
1710 $this->mNewpassword = '';
1711 $this->mNewpassTime = null;
1712 }
1713
1714 /**
1715 * Get the user's current token.
1716 * @return \string Token
1717 */
1718 function getToken() {
1719 $this->load();
1720 return $this->mToken;
1721 }
1722
1723 /**
1724 * Set the random token (used for persistent authentication)
1725 * Called from loadDefaults() among other places.
1726 *
1727 * @param $token \string If specified, set the token to this value
1728 * @private
1729 */
1730 function setToken( $token = false ) {
1731 global $wgSecretKey, $wgProxyKey;
1732 $this->load();
1733 if ( !$token ) {
1734 if ( $wgSecretKey ) {
1735 $key = $wgSecretKey;
1736 } elseif ( $wgProxyKey ) {
1737 $key = $wgProxyKey;
1738 } else {
1739 $key = microtime();
1740 }
1741 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1742 } else {
1743 $this->mToken = $token;
1744 }
1745 }
1746
1747 /**
1748 * Set the cookie password
1749 *
1750 * @param $str \string New cookie password
1751 * @private
1752 */
1753 function setCookiePassword( $str ) {
1754 $this->load();
1755 $this->mCookiePassword = md5( $str );
1756 }
1757
1758 /**
1759 * Set the password for a password reminder or new account email
1760 *
1761 * @param $str \string New password to set
1762 * @param $throttle \bool If true, reset the throttle timestamp to the present
1763 */
1764 function setNewpassword( $str, $throttle = true ) {
1765 $this->load();
1766 $this->mNewpassword = self::crypt( $str );
1767 if ( $throttle ) {
1768 $this->mNewpassTime = wfTimestampNow();
1769 }
1770 }
1771
1772 /**
1773 * Has password reminder email been sent within the last
1774 * $wgPasswordReminderResendTime hours?
1775 * @return \bool True or false
1776 */
1777 function isPasswordReminderThrottled() {
1778 global $wgPasswordReminderResendTime;
1779 $this->load();
1780 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1781 return false;
1782 }
1783 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1784 return time() < $expiry;
1785 }
1786
1787 /**
1788 * Get the user's e-mail address
1789 * @return \string User's email address
1790 */
1791 function getEmail() {
1792 $this->load();
1793 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1794 return $this->mEmail;
1795 }
1796
1797 /**
1798 * Get the timestamp of the user's e-mail authentication
1799 * @return \string TS_MW timestamp
1800 */
1801 function getEmailAuthenticationTimestamp() {
1802 $this->load();
1803 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1804 return $this->mEmailAuthenticated;
1805 }
1806
1807 /**
1808 * Set the user's e-mail address
1809 * @param $str \string New e-mail address
1810 */
1811 function setEmail( $str ) {
1812 $this->load();
1813 $this->mEmail = $str;
1814 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1815 }
1816
1817 /**
1818 * Get the user's real name
1819 * @return \string User's real name
1820 */
1821 function getRealName() {
1822 $this->load();
1823 return $this->mRealName;
1824 }
1825
1826 /**
1827 * Set the user's real name
1828 * @param $str \string New real name
1829 */
1830 function setRealName( $str ) {
1831 $this->load();
1832 $this->mRealName = $str;
1833 }
1834
1835 /**
1836 * Get the user's current setting for a given option.
1837 *
1838 * @param $oname \string The option to check
1839 * @param $defaultOverride \string A default value returned if the option does not exist
1840 * @return \string User's current value for the option
1841 * @see getBoolOption()
1842 * @see getIntOption()
1843 */
1844 function getOption( $oname, $defaultOverride = '' ) {
1845 $this->load();
1846
1847 if ( is_null( $this->mOptions ) ) {
1848 if($defaultOverride != '') {
1849 return $defaultOverride;
1850 }
1851 $this->mOptions = User::getDefaultOptions();
1852 }
1853
1854 if ( array_key_exists( $oname, $this->mOptions ) ) {
1855 return trim( $this->mOptions[$oname] );
1856 } else {
1857 return $defaultOverride;
1858 }
1859 }
1860
1861 /**
1862 * Get the user's current setting for a given option, as a boolean value.
1863 *
1864 * @param $oname \string The option to check
1865 * @return \bool User's current value for the option
1866 * @see getOption()
1867 */
1868 function getBoolOption( $oname ) {
1869 return (bool)$this->getOption( $oname );
1870 }
1871
1872
1873 /**
1874 * Get the user's current setting for a given option, as a boolean value.
1875 *
1876 * @param $oname \string The option to check
1877 * @param $defaultOverride \int A default value returned if the option does not exist
1878 * @return \int User's current value for the option
1879 * @see getOption()
1880 */
1881 function getIntOption( $oname, $defaultOverride=0 ) {
1882 $val = $this->getOption( $oname );
1883 if( $val == '' ) {
1884 $val = $defaultOverride;
1885 }
1886 return intval( $val );
1887 }
1888
1889 /**
1890 * Set the given option for a user.
1891 *
1892 * @param $oname \string The option to set
1893 * @param $val \mixed New value to set
1894 */
1895 function setOption( $oname, $val ) {
1896 $this->load();
1897 if ( is_null( $this->mOptions ) ) {
1898 $this->mOptions = User::getDefaultOptions();
1899 }
1900 if ( $oname == 'skin' ) {
1901 # Clear cached skin, so the new one displays immediately in Special:Preferences
1902 unset( $this->mSkin );
1903 }
1904 // Filter out any newlines that may have passed through input validation.
1905 // Newlines are used to separate items in the options blob.
1906 if( $val ) {
1907 $val = str_replace( "\r\n", "\n", $val );
1908 $val = str_replace( "\r", "\n", $val );
1909 $val = str_replace( "\n", " ", $val );
1910 }
1911 // Explicitly NULL values should refer to defaults
1912 global $wgDefaultUserOptions;
1913 if( is_null($val) && isset($wgDefaultUserOptions[$oname]) ) {
1914 $val = $wgDefaultUserOptions[$oname];
1915 }
1916 $this->mOptions[$oname] = $val;
1917 }
1918
1919 /**
1920 * Reset all options to the site defaults
1921 */
1922 function restoreOptions() {
1923 $this->mOptions = User::getDefaultOptions();
1924 }
1925
1926 /**
1927 * Get the user's preferred date format.
1928 * @return \string User's preferred date format
1929 */
1930 function getDatePreference() {
1931 // Important migration for old data rows
1932 if ( is_null( $this->mDatePreference ) ) {
1933 global $wgLang;
1934 $value = $this->getOption( 'date' );
1935 $map = $wgLang->getDatePreferenceMigrationMap();
1936 if ( isset( $map[$value] ) ) {
1937 $value = $map[$value];
1938 }
1939 $this->mDatePreference = $value;
1940 }
1941 return $this->mDatePreference;
1942 }
1943
1944 /**
1945 * Get the permissions this user has.
1946 * @return \type{\arrayof{\string}} Array of permission names
1947 */
1948 function getRights() {
1949 if ( is_null( $this->mRights ) ) {
1950 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
1951 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
1952 // Force reindexation of rights when a hook has unset one of them
1953 $this->mRights = array_values( $this->mRights );
1954 }
1955 return $this->mRights;
1956 }
1957
1958 /**
1959 * Get the list of explicit group memberships this user has.
1960 * The implicit * and user groups are not included.
1961 * @return \type{\arrayof{\string}} Array of internal group names
1962 */
1963 function getGroups() {
1964 $this->load();
1965 return $this->mGroups;
1966 }
1967
1968 /**
1969 * Get the list of implicit group memberships this user has.
1970 * This includes all explicit groups, plus 'user' if logged in,
1971 * '*' for all accounts and autopromoted groups
1972 * @param $recache \bool Whether to avoid the cache
1973 * @return \type{\arrayof{\string}} Array of internal group names
1974 */
1975 function getEffectiveGroups( $recache = false ) {
1976 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
1977 $this->mEffectiveGroups = $this->getGroups();
1978 $this->mEffectiveGroups[] = '*';
1979 if( $this->getId() ) {
1980 $this->mEffectiveGroups[] = 'user';
1981
1982 $this->mEffectiveGroups = array_unique( array_merge(
1983 $this->mEffectiveGroups,
1984 Autopromote::getAutopromoteGroups( $this )
1985 ) );
1986
1987 # Hook for additional groups
1988 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
1989 }
1990 }
1991 return $this->mEffectiveGroups;
1992 }
1993
1994 /**
1995 * Get the user's edit count.
1996 * @return \int User'e edit count
1997 */
1998 function getEditCount() {
1999 if ($this->mId) {
2000 if ( !isset( $this->mEditCount ) ) {
2001 /* Populate the count, if it has not been populated yet */
2002 $this->mEditCount = User::edits($this->mId);
2003 }
2004 return $this->mEditCount;
2005 } else {
2006 /* nil */
2007 return null;
2008 }
2009 }
2010
2011 /**
2012 * Add the user to the given group.
2013 * This takes immediate effect.
2014 * @param $group \string Name of the group to add
2015 */
2016 function addGroup( $group ) {
2017 $dbw = wfGetDB( DB_MASTER );
2018 if( $this->getId() ) {
2019 $dbw->insert( 'user_groups',
2020 array(
2021 'ug_user' => $this->getID(),
2022 'ug_group' => $group,
2023 ),
2024 'User::addGroup',
2025 array( 'IGNORE' ) );
2026 }
2027
2028 $this->loadGroups();
2029 $this->mGroups[] = $group;
2030 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2031
2032 $this->invalidateCache();
2033 }
2034
2035 /**
2036 * Remove the user from the given group.
2037 * This takes immediate effect.
2038 * @param $group \string Name of the group to remove
2039 */
2040 function removeGroup( $group ) {
2041 $this->load();
2042 $dbw = wfGetDB( DB_MASTER );
2043 $dbw->delete( 'user_groups',
2044 array(
2045 'ug_user' => $this->getID(),
2046 'ug_group' => $group,
2047 ),
2048 'User::removeGroup' );
2049
2050 $this->loadGroups();
2051 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2052 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2053
2054 $this->invalidateCache();
2055 }
2056
2057
2058 /**
2059 * Get whether the user is logged in
2060 * @return \bool True or false
2061 */
2062 function isLoggedIn() {
2063 return $this->getID() != 0;
2064 }
2065
2066 /**
2067 * Get whether the user is anonymous
2068 * @return \bool True or false
2069 */
2070 function isAnon() {
2071 return !$this->isLoggedIn();
2072 }
2073
2074 /**
2075 * Get whether the user is a bot
2076 * @return \bool True or false
2077 * @deprecated
2078 */
2079 function isBot() {
2080 wfDeprecated( __METHOD__ );
2081 return $this->isAllowed( 'bot' );
2082 }
2083
2084 /**
2085 * Check if user is allowed to access a feature / make an action
2086 * @param $action \string action to be checked
2087 * @return \bool True if action is allowed, else false
2088 */
2089 function isAllowed($action='') {
2090 if ( $action === '' )
2091 // In the spirit of DWIM
2092 return true;
2093
2094 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2095 # by misconfiguration: 0 == 'foo'
2096 return in_array( $action, $this->getRights(), true );
2097 }
2098
2099 /**
2100 * Check whether to enable recent changes patrol features for this user
2101 * @return \bool True or false
2102 */
2103 public function useRCPatrol() {
2104 global $wgUseRCPatrol;
2105 return( $wgUseRCPatrol && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
2106 }
2107
2108 /**
2109 * Check whether to enable new pages patrol features for this user
2110 * @return \bool True or false
2111 */
2112 public function useNPPatrol() {
2113 global $wgUseRCPatrol, $wgUseNPPatrol;
2114 return( ($wgUseRCPatrol || $wgUseNPPatrol) && ($this->isAllowed('patrol') || $this->isAllowed('patrolmarks')) );
2115 }
2116
2117 /**
2118 * Get the current skin, loading it if required
2119 * @return \type{Skin} Current skin
2120 * @todo FIXME : need to check the old failback system [AV]
2121 */
2122 function &getSkin() {
2123 global $wgRequest, $wgAllowUserSkin, $wgDefaultSkin;
2124 if ( ! isset( $this->mSkin ) ) {
2125 wfProfileIn( __METHOD__ );
2126
2127 if( $wgAllowUserSkin ) {
2128 # get the user skin
2129 $userSkin = $this->getOption( 'skin' );
2130 $userSkin = $wgRequest->getVal('useskin', $userSkin);
2131 } else {
2132 # if we're not allowing users to override, then use the default
2133 $userSkin = $wgDefaultSkin;
2134 }
2135
2136 $this->mSkin =& Skin::newFromKey( $userSkin );
2137 wfProfileOut( __METHOD__ );
2138 }
2139 return $this->mSkin;
2140 }
2141
2142 /**
2143 * Check the watched status of an article.
2144 * @param $title \type{Title} Title of the article to look at
2145 * @return \bool True if article is watched
2146 */
2147 function isWatched( $title ) {
2148 $wl = WatchedItem::fromUserTitle( $this, $title );
2149 return $wl->isWatched();
2150 }
2151
2152 /**
2153 * Watch an article.
2154 * @param $title \type{Title} Title of the article to look at
2155 */
2156 function addWatch( $title ) {
2157 $wl = WatchedItem::fromUserTitle( $this, $title );
2158 $wl->addWatch();
2159 $this->invalidateCache();
2160 }
2161
2162 /**
2163 * Stop watching an article.
2164 * @param $title \type{Title} Title of the article to look at
2165 */
2166 function removeWatch( $title ) {
2167 $wl = WatchedItem::fromUserTitle( $this, $title );
2168 $wl->removeWatch();
2169 $this->invalidateCache();
2170 }
2171
2172 /**
2173 * Clear the user's notification timestamp for the given title.
2174 * If e-notif e-mails are on, they will receive notification mails on
2175 * the next change of the page if it's watched etc.
2176 * @param $title \type{Title} Title of the article to look at
2177 */
2178 function clearNotification( &$title ) {
2179 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2180
2181 # Do nothing if the database is locked to writes
2182 if( wfReadOnly() ) {
2183 return;
2184 }
2185
2186 if ($title->getNamespace() == NS_USER_TALK &&
2187 $title->getText() == $this->getName() ) {
2188 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
2189 return;
2190 $this->setNewtalk( false );
2191 }
2192
2193 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2194 return;
2195 }
2196
2197 if( $this->isAnon() ) {
2198 // Nothing else to do...
2199 return;
2200 }
2201
2202 // Only update the timestamp if the page is being watched.
2203 // The query to find out if it is watched is cached both in memcached and per-invocation,
2204 // and when it does have to be executed, it can be on a slave
2205 // If this is the user's newtalk page, we always update the timestamp
2206 if ($title->getNamespace() == NS_USER_TALK &&
2207 $title->getText() == $wgUser->getName())
2208 {
2209 $watched = true;
2210 } elseif ( $this->getId() == $wgUser->getId() ) {
2211 $watched = $title->userIsWatching();
2212 } else {
2213 $watched = true;
2214 }
2215
2216 // If the page is watched by the user (or may be watched), update the timestamp on any
2217 // any matching rows
2218 if ( $watched ) {
2219 $dbw = wfGetDB( DB_MASTER );
2220 $dbw->update( 'watchlist',
2221 array( /* SET */
2222 'wl_notificationtimestamp' => NULL
2223 ), array( /* WHERE */
2224 'wl_title' => $title->getDBkey(),
2225 'wl_namespace' => $title->getNamespace(),
2226 'wl_user' => $this->getID()
2227 ), __METHOD__
2228 );
2229 }
2230 }
2231
2232 /**
2233 * Resets all of the given user's page-change notification timestamps.
2234 * If e-notif e-mails are on, they will receive notification mails on
2235 * the next change of any watched page.
2236 *
2237 * @param $currentUser \int User ID
2238 */
2239 function clearAllNotifications( $currentUser ) {
2240 global $wgUseEnotif, $wgShowUpdatedMarker;
2241 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2242 $this->setNewtalk( false );
2243 return;
2244 }
2245 if( $currentUser != 0 ) {
2246 $dbw = wfGetDB( DB_MASTER );
2247 $dbw->update( 'watchlist',
2248 array( /* SET */
2249 'wl_notificationtimestamp' => NULL
2250 ), array( /* WHERE */
2251 'wl_user' => $currentUser
2252 ), __METHOD__
2253 );
2254 # We also need to clear here the "you have new message" notification for the own user_talk page
2255 # This is cleared one page view later in Article::viewUpdates();
2256 }
2257 }
2258
2259 /**
2260 * Encode this user's options as a string
2261 * @return \string Encoded options
2262 * @private
2263 */
2264 function encodeOptions() {
2265 $this->load();
2266 if ( is_null( $this->mOptions ) ) {
2267 $this->mOptions = User::getDefaultOptions();
2268 }
2269 $a = array();
2270 foreach ( $this->mOptions as $oname => $oval ) {
2271 array_push( $a, $oname.'='.$oval );
2272 }
2273 $s = implode( "\n", $a );
2274 return $s;
2275 }
2276
2277 /**
2278 * Set this user's options from an encoded string
2279 * @param $str \string Encoded options to import
2280 * @private
2281 */
2282 function decodeOptions( $str ) {
2283 $this->mOptions = array();
2284 $a = explode( "\n", $str );
2285 foreach ( $a as $s ) {
2286 $m = array();
2287 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2288 $this->mOptions[$m[1]] = $m[2];
2289 }
2290 }
2291 }
2292
2293 /**
2294 * Set a cookie on the user's client. Wrapper for
2295 * WebResponse::setCookie
2296 * @param $name \string Name of the cookie to set
2297 * @param $value \string Value to set
2298 * @param $exp \int Expiration time, as a UNIX time value;
2299 * if 0 or not specified, use the default $wgCookieExpiration
2300 */
2301 protected function setCookie( $name, $value, $exp=0 ) {
2302 global $wgRequest;
2303 $wgRequest->response()->setcookie( $name, $value, $exp );
2304 }
2305
2306 /**
2307 * Clear a cookie on the user's client
2308 * @param $name \string Name of the cookie to clear
2309 */
2310 protected function clearCookie( $name ) {
2311 $this->setCookie( $name, '', time() - 86400 );
2312 }
2313
2314 /**
2315 * Set the default cookies for this session on the user's client.
2316 */
2317 function setCookies() {
2318 $this->load();
2319 if ( 0 == $this->mId ) return;
2320 $session = array(
2321 'wsUserID' => $this->mId,
2322 'wsToken' => $this->mToken,
2323 'wsUserName' => $this->getName()
2324 );
2325 $cookies = array(
2326 'UserID' => $this->mId,
2327 'UserName' => $this->getName(),
2328 );
2329 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2330 $cookies['Token'] = $this->mToken;
2331 } else {
2332 $cookies['Token'] = false;
2333 }
2334
2335 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2336 #check for null, since the hook could cause a null value
2337 if ( !is_null( $session ) && isset( $_SESSION ) ){
2338 $_SESSION = $session + $_SESSION;
2339 }
2340 foreach ( $cookies as $name => $value ) {
2341 if ( $value === false ) {
2342 $this->clearCookie( $name );
2343 } else {
2344 $this->setCookie( $name, $value );
2345 }
2346 }
2347 }
2348
2349 /**
2350 * Log this user out.
2351 */
2352 function logout() {
2353 global $wgUser;
2354 if( wfRunHooks( 'UserLogout', array(&$this) ) ) {
2355 $this->doLogout();
2356 }
2357 }
2358
2359 /**
2360 * Clear the user's cookies and session, and reset the instance cache.
2361 * @private
2362 * @see logout()
2363 */
2364 function doLogout() {
2365 $this->clearInstanceCache( 'defaults' );
2366
2367 $_SESSION['wsUserID'] = 0;
2368
2369 $this->clearCookie( 'UserID' );
2370 $this->clearCookie( 'Token' );
2371
2372 # Remember when user logged out, to prevent seeing cached pages
2373 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2374 }
2375
2376 /**
2377 * Save this user's settings into the database.
2378 * @todo Only rarely do all these fields need to be set!
2379 */
2380 function saveSettings() {
2381 $this->load();
2382 if ( wfReadOnly() ) { return; }
2383 if ( 0 == $this->mId ) { return; }
2384
2385 $this->mTouched = self::newTouchedTimestamp();
2386
2387 $dbw = wfGetDB( DB_MASTER );
2388 $dbw->update( 'user',
2389 array( /* SET */
2390 'user_name' => $this->mName,
2391 'user_password' => $this->mPassword,
2392 'user_newpassword' => $this->mNewpassword,
2393 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2394 'user_real_name' => $this->mRealName,
2395 'user_email' => $this->mEmail,
2396 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2397 'user_options' => $this->encodeOptions(),
2398 'user_touched' => $dbw->timestamp($this->mTouched),
2399 'user_token' => $this->mToken,
2400 'user_email_token' => $this->mEmailToken,
2401 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2402 ), array( /* WHERE */
2403 'user_id' => $this->mId
2404 ), __METHOD__
2405 );
2406 wfRunHooks( 'UserSaveSettings', array( $this ) );
2407 $this->clearSharedCache();
2408 $this->getUserPage()->invalidateCache();
2409 }
2410
2411 /**
2412 * If only this user's username is known, and it exists, return the user ID.
2413 */
2414 function idForName() {
2415 $s = trim( $this->getName() );
2416 if ( $s === '' ) return 0;
2417
2418 $dbr = wfGetDB( DB_SLAVE );
2419 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2420 if ( $id === false ) {
2421 $id = 0;
2422 }
2423 return $id;
2424 }
2425
2426 /**
2427 * Add a user to the database, return the user object
2428 *
2429 * @param $name \string Username to add
2430 * @param $params \type{\arrayof{\string}} Non-default parameters to save to the database:
2431 * - password The user's password. Password logins will be disabled if this is omitted.
2432 * - newpassword A temporary password mailed to the user
2433 * - email The user's email address
2434 * - email_authenticated The email authentication timestamp
2435 * - real_name The user's real name
2436 * - options An associative array of non-default options
2437 * - token Random authentication token. Do not set.
2438 * - registration Registration timestamp. Do not set.
2439 *
2440 * @return \type{User} A new User object, or null if the username already exists
2441 */
2442 static function createNew( $name, $params = array() ) {
2443 $user = new User;
2444 $user->load();
2445 if ( isset( $params['options'] ) ) {
2446 $user->mOptions = $params['options'] + $user->mOptions;
2447 unset( $params['options'] );
2448 }
2449 $dbw = wfGetDB( DB_MASTER );
2450 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2451 $fields = array(
2452 'user_id' => $seqVal,
2453 'user_name' => $name,
2454 'user_password' => $user->mPassword,
2455 'user_newpassword' => $user->mNewpassword,
2456 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ),
2457 'user_email' => $user->mEmail,
2458 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2459 'user_real_name' => $user->mRealName,
2460 'user_options' => $user->encodeOptions(),
2461 'user_token' => $user->mToken,
2462 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2463 'user_editcount' => 0,
2464 );
2465 foreach ( $params as $name => $value ) {
2466 $fields["user_$name"] = $value;
2467 }
2468 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2469 if ( $dbw->affectedRows() ) {
2470 $newUser = User::newFromId( $dbw->insertId() );
2471 } else {
2472 $newUser = null;
2473 }
2474 return $newUser;
2475 }
2476
2477 /**
2478 * Add this existing user object to the database
2479 */
2480 function addToDatabase() {
2481 $this->load();
2482 $dbw = wfGetDB( DB_MASTER );
2483 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2484 $dbw->insert( 'user',
2485 array(
2486 'user_id' => $seqVal,
2487 'user_name' => $this->mName,
2488 'user_password' => $this->mPassword,
2489 'user_newpassword' => $this->mNewpassword,
2490 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ),
2491 'user_email' => $this->mEmail,
2492 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2493 'user_real_name' => $this->mRealName,
2494 'user_options' => $this->encodeOptions(),
2495 'user_token' => $this->mToken,
2496 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2497 'user_editcount' => 0,
2498 ), __METHOD__
2499 );
2500 $this->mId = $dbw->insertId();
2501
2502 // Clear instance cache other than user table data, which is already accurate
2503 $this->clearInstanceCache();
2504 }
2505
2506 /**
2507 * If this (non-anonymous) user is blocked, block any IP address
2508 * they've successfully logged in from.
2509 */
2510 function spreadBlock() {
2511 wfDebug( __METHOD__."()\n" );
2512 $this->load();
2513 if ( $this->mId == 0 ) {
2514 return;
2515 }
2516
2517 $userblock = Block::newFromDB( '', $this->mId );
2518 if ( !$userblock ) {
2519 return;
2520 }
2521
2522 $userblock->doAutoblock( wfGetIp() );
2523
2524 }
2525
2526 /**
2527 * Generate a string which will be different for any combination of
2528 * user options which would produce different parser output.
2529 * This will be used as part of the hash key for the parser cache,
2530 * so users will the same options can share the same cached data
2531 * safely.
2532 *
2533 * Extensions which require it should install 'PageRenderingHash' hook,
2534 * which will give them a chance to modify this key based on their own
2535 * settings.
2536 *
2537 * @return \string Page rendering hash
2538 */
2539 function getPageRenderingHash() {
2540 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2541 if( $this->mHash ){
2542 return $this->mHash;
2543 }
2544
2545 // stubthreshold is only included below for completeness,
2546 // it will always be 0 when this function is called by parsercache.
2547
2548 $confstr = $this->getOption( 'math' );
2549 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2550 if ( $wgUseDynamicDates ) {
2551 $confstr .= '!' . $this->getDatePreference();
2552 }
2553 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
2554 $confstr .= '!' . $wgLang->getCode();
2555 $confstr .= '!' . $this->getOption( 'thumbsize' );
2556 // add in language specific options, if any
2557 $extra = $wgContLang->getExtraHashOptions();
2558 $confstr .= $extra;
2559
2560 $confstr .= $wgRenderHashAppend;
2561
2562 // Give a chance for extensions to modify the hash, if they have
2563 // extra options or other effects on the parser cache.
2564 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2565
2566 // Make it a valid memcached key fragment
2567 $confstr = str_replace( ' ', '_', $confstr );
2568 $this->mHash = $confstr;
2569 return $confstr;
2570 }
2571
2572 /**
2573 * Get whether the user is explicitly blocked from account creation.
2574 * @return \bool True if blocked
2575 */
2576 function isBlockedFromCreateAccount() {
2577 $this->getBlockedStatus();
2578 return $this->mBlock && $this->mBlock->mCreateAccount;
2579 }
2580
2581 /**
2582 * Get whether the user is blocked from using Special:Emailuser.
2583 * @return \bool True if blocked
2584 */
2585 function isBlockedFromEmailuser() {
2586 $this->getBlockedStatus();
2587 return $this->mBlock && $this->mBlock->mBlockEmail;
2588 }
2589
2590 /**
2591 * Get whether the user is allowed to create an account.
2592 * @return \bool True if allowed
2593 */
2594 function isAllowedToCreateAccount() {
2595 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2596 }
2597
2598 /**
2599 * @deprecated
2600 */
2601 function setLoaded( $loaded ) {
2602 wfDeprecated( __METHOD__ );
2603 }
2604
2605 /**
2606 * Get this user's personal page title.
2607 *
2608 * @return \type{Title} User's personal page title
2609 */
2610 function getUserPage() {
2611 return Title::makeTitle( NS_USER, $this->getName() );
2612 }
2613
2614 /**
2615 * Get this user's talk page title.
2616 *
2617 * @return \type{Title} User's talk page title
2618 */
2619 function getTalkPage() {
2620 $title = $this->getUserPage();
2621 return $title->getTalkPage();
2622 }
2623
2624 /**
2625 * Get the maximum valid user ID.
2626 * @return \int User ID
2627 * @static
2628 */
2629 function getMaxID() {
2630 static $res; // cache
2631
2632 if ( isset( $res ) )
2633 return $res;
2634 else {
2635 $dbr = wfGetDB( DB_SLAVE );
2636 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2637 }
2638 }
2639
2640 /**
2641 * Determine whether the user is a newbie. Newbies are either
2642 * anonymous IPs, or the most recently created accounts.
2643 * @return \bool True if the user is a newbie
2644 */
2645 function isNewbie() {
2646 return !$this->isAllowed( 'autoconfirmed' );
2647 }
2648
2649 /**
2650 * Is the user active? We check to see if they've made at least
2651 * X number of edits in the last Y days.
2652 *
2653 * @return \bool True if the user is active, false if not.
2654 */
2655 public function isActiveEditor() {
2656 global $wgActiveUserEditCount, $wgActiveUserDays;
2657 $dbr = wfGetDB( DB_SLAVE );
2658
2659 // Stolen without shame from RC
2660 $cutoff_unixtime = time() - ( $wgActiveUserDays * 86400 );
2661 $cutoff_unixtime = $cutoff_unixtime - ( $cutoff_unixtime % 86400 );
2662 $oldTime = $dbr->addQuotes( $dbr->timestamp( $cutoff_unixtime ) );
2663
2664 $res = $dbr->select( 'revision', '1',
2665 array( 'rev_user_text' => $this->getName(), "rev_timestamp > $oldTime"),
2666 __METHOD__,
2667 array('LIMIT' => $wgActiveUserEditCount ) );
2668
2669 $count = $dbr->numRows($res);
2670 $dbr->freeResult($res);
2671
2672 return $count == $wgActiveUserEditCount;
2673 }
2674
2675 /**
2676 * Check to see if the given clear-text password is one of the accepted passwords
2677 * @param $password \string user password.
2678 * @return \bool True if the given password is correct, otherwise False.
2679 */
2680 function checkPassword( $password ) {
2681 global $wgAuth;
2682 $this->load();
2683
2684 // Even though we stop people from creating passwords that
2685 // are shorter than this, doesn't mean people wont be able
2686 // to. Certain authentication plugins do NOT want to save
2687 // domain passwords in a mysql database, so we should
2688 // check this (incase $wgAuth->strict() is false).
2689 if( !$this->isValidPassword( $password ) ) {
2690 return false;
2691 }
2692
2693 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2694 return true;
2695 } elseif( $wgAuth->strict() ) {
2696 /* Auth plugin doesn't allow local authentication */
2697 return false;
2698 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2699 /* Auth plugin doesn't allow local authentication for this user name */
2700 return false;
2701 }
2702 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
2703 return true;
2704 } elseif ( function_exists( 'iconv' ) ) {
2705 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2706 # Check for this with iconv
2707 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2708 if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) {
2709 return true;
2710 }
2711 }
2712 return false;
2713 }
2714
2715 /**
2716 * Check if the given clear-text password matches the temporary password
2717 * sent by e-mail for password reset operations.
2718 * @return \bool True if matches, false otherwise
2719 */
2720 function checkTemporaryPassword( $plaintext ) {
2721 global $wgNewPasswordExpiry;
2722 if( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
2723 $this->load();
2724 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
2725 return ( time() < $expiry );
2726 } else {
2727 return false;
2728 }
2729 }
2730
2731 /**
2732 * Initialize (if necessary) and return a session token value
2733 * which can be used in edit forms to show that the user's
2734 * login credentials aren't being hijacked with a foreign form
2735 * submission.
2736 *
2737 * @param $salt \types{\string,\arrayof{\string}} Optional function-specific data for hashing
2738 * @return \string The new edit token
2739 */
2740 function editToken( $salt = '' ) {
2741 if ( $this->isAnon() ) {
2742 return EDIT_TOKEN_SUFFIX;
2743 } else {
2744 if( !isset( $_SESSION['wsEditToken'] ) ) {
2745 $token = $this->generateToken();
2746 $_SESSION['wsEditToken'] = $token;
2747 } else {
2748 $token = $_SESSION['wsEditToken'];
2749 }
2750 if( is_array( $salt ) ) {
2751 $salt = implode( '|', $salt );
2752 }
2753 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2754 }
2755 }
2756
2757 /**
2758 * Generate a looking random token for various uses.
2759 *
2760 * @param $salt \string Optional salt value
2761 * @return \string The new random token
2762 */
2763 function generateToken( $salt = '' ) {
2764 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2765 return md5( $token . $salt );
2766 }
2767
2768 /**
2769 * Check given value against the token value stored in the session.
2770 * A match should confirm that the form was submitted from the
2771 * user's own login session, not a form submission from a third-party
2772 * site.
2773 *
2774 * @param $val \string Input value to compare
2775 * @param $salt \string Optional function-specific data for hashing
2776 * @return \bool Whether the token matches
2777 */
2778 function matchEditToken( $val, $salt = '' ) {
2779 $sessionToken = $this->editToken( $salt );
2780 if ( $val != $sessionToken ) {
2781 wfDebug( "User::matchEditToken: broken session data\n" );
2782 }
2783 return $val == $sessionToken;
2784 }
2785
2786 /**
2787 * Check given value against the token value stored in the session,
2788 * ignoring the suffix.
2789 *
2790 * @param $val \string Input value to compare
2791 * @param $salt \string Optional function-specific data for hashing
2792 * @return \bool Whether the token matches
2793 */
2794 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2795 $sessionToken = $this->editToken( $salt );
2796 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2797 }
2798
2799 /**
2800 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2801 * mail to the user's given address.
2802 *
2803 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure.
2804 */
2805 function sendConfirmationMail() {
2806 global $wgLang;
2807 $expiration = null; // gets passed-by-ref and defined in next line.
2808 $token = $this->confirmationToken( $expiration );
2809 $url = $this->confirmationTokenUrl( $token );
2810 $invalidateURL = $this->invalidationTokenUrl( $token );
2811 $this->saveSettings();
2812
2813 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2814 wfMsg( 'confirmemail_body',
2815 wfGetIP(),
2816 $this->getName(),
2817 $url,
2818 $wgLang->timeanddate( $expiration, false ),
2819 $invalidateURL ) );
2820 }
2821
2822 /**
2823 * Send an e-mail to this user's account. Does not check for
2824 * confirmed status or validity.
2825 *
2826 * @param $subject \string Message subject
2827 * @param $body \string Message body
2828 * @param $from \string Optional From address; if unspecified, default $wgPasswordSender will be used
2829 * @param $replyto \string Reply-To address
2830 * @return \types{\bool,\type{WikiError}} True on success, a WikiError object on failure
2831 */
2832 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2833 if( is_null( $from ) ) {
2834 global $wgPasswordSender;
2835 $from = $wgPasswordSender;
2836 }
2837
2838 $to = new MailAddress( $this );
2839 $sender = new MailAddress( $from );
2840 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2841 }
2842
2843 /**
2844 * Generate, store, and return a new e-mail confirmation code.
2845 * A hash (unsalted, since it's used as a key) is stored.
2846 *
2847 * @note Call saveSettings() after calling this function to commit
2848 * this change to the database.
2849 *
2850 * @param[out] &$expiration \mixed Accepts the expiration time
2851 * @return \string New token
2852 * @private
2853 */
2854 function confirmationToken( &$expiration ) {
2855 $now = time();
2856 $expires = $now + 7 * 24 * 60 * 60;
2857 $expiration = wfTimestamp( TS_MW, $expires );
2858 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
2859 $hash = md5( $token );
2860 $this->load();
2861 $this->mEmailToken = $hash;
2862 $this->mEmailTokenExpires = $expiration;
2863 return $token;
2864 }
2865
2866 /**
2867 * Return a URL the user can use to confirm their email address.
2868 * @param $token \string Accepts the email confirmation token
2869 * @return \string New token URL
2870 * @private
2871 */
2872 function confirmationTokenUrl( $token ) {
2873 return $this->getTokenUrl( 'ConfirmEmail', $token );
2874 }
2875 /**
2876 * Return a URL the user can use to invalidate their email address.
2877 * @param $token \string Accepts the email confirmation token
2878 * @return \string New token URL
2879 * @private
2880 */
2881 function invalidationTokenUrl( $token ) {
2882 return $this->getTokenUrl( 'Invalidateemail', $token );
2883 }
2884
2885 /**
2886 * Internal function to format the e-mail validation/invalidation URLs.
2887 * This uses $wgArticlePath directly as a quickie hack to use the
2888 * hardcoded English names of the Special: pages, for ASCII safety.
2889 *
2890 * @note Since these URLs get dropped directly into emails, using the
2891 * short English names avoids insanely long URL-encoded links, which
2892 * also sometimes can get corrupted in some browsers/mailers
2893 * (bug 6957 with Gmail and Internet Explorer).
2894 *
2895 * @param $page \string Special page
2896 * @param $token \string Token
2897 * @return \string Formatted URL
2898 */
2899 protected function getTokenUrl( $page, $token ) {
2900 global $wgArticlePath;
2901 return wfExpandUrl(
2902 str_replace(
2903 '$1',
2904 "Special:$page/$token",
2905 $wgArticlePath ) );
2906 }
2907
2908 /**
2909 * Mark the e-mail address confirmed.
2910 *
2911 * @note Call saveSettings() after calling this function to commit the change.
2912 */
2913 function confirmEmail() {
2914 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
2915 return true;
2916 }
2917
2918 /**
2919 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
2920 * address if it was already confirmed.
2921 *
2922 * @note Call saveSettings() after calling this function to commit the change.
2923 */
2924 function invalidateEmail() {
2925 $this->load();
2926 $this->mEmailToken = null;
2927 $this->mEmailTokenExpires = null;
2928 $this->setEmailAuthenticationTimestamp( null );
2929 return true;
2930 }
2931
2932 /**
2933 * Set the e-mail authentication timestamp.
2934 * @param $timestamp \string TS_MW timestamp
2935 */
2936 function setEmailAuthenticationTimestamp( $timestamp ) {
2937 $this->load();
2938 $this->mEmailAuthenticated = $timestamp;
2939 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
2940 }
2941
2942 /**
2943 * Is this user allowed to send e-mails within limits of current
2944 * site configuration?
2945 * @return \bool True if allowed
2946 */
2947 function canSendEmail() {
2948 global $wgEnableEmail, $wgEnableUserEmail;
2949 if( !$wgEnableEmail || !$wgEnableUserEmail ) {
2950 return false;
2951 }
2952 $canSend = $this->isEmailConfirmed();
2953 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
2954 return $canSend;
2955 }
2956
2957 /**
2958 * Is this user allowed to receive e-mails within limits of current
2959 * site configuration?
2960 * @return \bool True if allowed
2961 */
2962 function canReceiveEmail() {
2963 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
2964 }
2965
2966 /**
2967 * Is this user's e-mail address valid-looking and confirmed within
2968 * limits of the current site configuration?
2969 *
2970 * @note If $wgEmailAuthentication is on, this may require the user to have
2971 * confirmed their address by returning a code or using a password
2972 * sent to the address from the wiki.
2973 *
2974 * @return \bool True if confirmed
2975 */
2976 function isEmailConfirmed() {
2977 global $wgEmailAuthentication;
2978 $this->load();
2979 $confirmed = true;
2980 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2981 if( $this->isAnon() )
2982 return false;
2983 if( !self::isValidEmailAddr( $this->mEmail ) )
2984 return false;
2985 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2986 return false;
2987 return true;
2988 } else {
2989 return $confirmed;
2990 }
2991 }
2992
2993 /**
2994 * Check whether there is an outstanding request for e-mail confirmation.
2995 * @return \bool True if pending
2996 */
2997 function isEmailConfirmationPending() {
2998 global $wgEmailAuthentication;
2999 return $wgEmailAuthentication &&
3000 !$this->isEmailConfirmed() &&
3001 $this->mEmailToken &&
3002 $this->mEmailTokenExpires > wfTimestamp();
3003 }
3004
3005 /**
3006 * Get the timestamp of account creation.
3007 *
3008 * @return \types{\string,\bool} string Timestamp of account creation, or false for
3009 * non-existent/anonymous user accounts.
3010 */
3011 public function getRegistration() {
3012 return $this->getId() > 0
3013 ? $this->mRegistration
3014 : false;
3015 }
3016
3017 /**
3018 * Get the timestamp of the first edit
3019 *
3020 * @return \types{\string,\bool} string Timestamp of first edit, or false for
3021 * non-existent/anonymous user accounts.
3022 */
3023 public function getFirstEditTimestamp() {
3024 if( $this->getId() == 0 ) return false; // anons
3025 $dbr = wfGetDB( DB_SLAVE );
3026 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3027 array( 'rev_user' => $this->getId() ),
3028 __METHOD__,
3029 array( 'ORDER BY' => 'rev_timestamp ASC' )
3030 );
3031 if( !$time ) return false; // no edits
3032 return wfTimestamp( TS_MW, $time );
3033 }
3034
3035 /**
3036 * Get the permissions associated with a given list of groups
3037 *
3038 * @param $groups \type{\arrayof{\string}} List of internal group names
3039 * @return \type{\arrayof{\string}} List of permission key names for given groups combined
3040 */
3041 static function getGroupPermissions( $groups ) {
3042 global $wgGroupPermissions;
3043 $rights = array();
3044 foreach( $groups as $group ) {
3045 if( isset( $wgGroupPermissions[$group] ) ) {
3046 $rights = array_merge( $rights,
3047 // array_filter removes empty items
3048 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3049 }
3050 }
3051 return array_unique($rights);
3052 }
3053
3054 /**
3055 * Get all the groups who have a given permission
3056 *
3057 * @param $role \string Role to check
3058 * @return \type{\arrayof{\string}} List of internal group names with the given permission
3059 */
3060 static function getGroupsWithPermission( $role ) {
3061 global $wgGroupPermissions;
3062 $allowedGroups = array();
3063 foreach ( $wgGroupPermissions as $group => $rights ) {
3064 if ( isset( $rights[$role] ) && $rights[$role] ) {
3065 $allowedGroups[] = $group;
3066 }
3067 }
3068 return $allowedGroups;
3069 }
3070
3071 /**
3072 * Get the localized descriptive name for a group, if it exists
3073 *
3074 * @param $group \string Internal group name
3075 * @return \string Localized descriptive group name
3076 */
3077 static function getGroupName( $group ) {
3078 global $wgMessageCache;
3079 $wgMessageCache->loadAllMessages();
3080 $key = "group-$group";
3081 $name = wfMsg( $key );
3082 return $name == '' || wfEmptyMsg( $key, $name )
3083 ? $group
3084 : $name;
3085 }
3086
3087 /**
3088 * Get the localized descriptive name for a member of a group, if it exists
3089 *
3090 * @param $group \string Internal group name
3091 * @return \string Localized name for group member
3092 */
3093 static function getGroupMember( $group ) {
3094 global $wgMessageCache;
3095 $wgMessageCache->loadAllMessages();
3096 $key = "group-$group-member";
3097 $name = wfMsg( $key );
3098 return $name == '' || wfEmptyMsg( $key, $name )
3099 ? $group
3100 : $name;
3101 }
3102
3103 /**
3104 * Return the set of defined explicit groups.
3105 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3106 * are not included, as they are defined automatically, not in the database.
3107 * @return \type{\arrayof{\string}} Array of internal group names
3108 */
3109 static function getAllGroups() {
3110 global $wgGroupPermissions;
3111 return array_diff(
3112 array_keys( $wgGroupPermissions ),
3113 self::getImplicitGroups()
3114 );
3115 }
3116
3117 /**
3118 * Get a list of all available permissions.
3119 * @return \type{\arrayof{\string}} Array of permission names
3120 */
3121 static function getAllRights() {
3122 if ( self::$mAllRights === false ) {
3123 global $wgAvailableRights;
3124 if ( count( $wgAvailableRights ) ) {
3125 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
3126 } else {
3127 self::$mAllRights = self::$mCoreRights;
3128 }
3129 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
3130 }
3131 return self::$mAllRights;
3132 }
3133
3134 /**
3135 * Get a list of implicit groups
3136 * @return \type{\arrayof{\string}} Array of internal group names
3137 */
3138 public static function getImplicitGroups() {
3139 global $wgImplicitGroups;
3140 $groups = $wgImplicitGroups;
3141 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3142 return $groups;
3143 }
3144
3145 /**
3146 * Get the title of a page describing a particular group
3147 *
3148 * @param $group \string Internal group name
3149 * @return \types{\type{Title},\bool} Title of the page if it exists, false otherwise
3150 */
3151 static function getGroupPage( $group ) {
3152 global $wgMessageCache;
3153 $wgMessageCache->loadAllMessages();
3154 $page = wfMsgForContent( 'grouppage-' . $group );
3155 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
3156 $title = Title::newFromText( $page );
3157 if( is_object( $title ) )
3158 return $title;
3159 }
3160 return false;
3161 }
3162
3163 /**
3164 * Create a link to the group in HTML, if available;
3165 * else return the group name.
3166 *
3167 * @param $group \string Internal name of the group
3168 * @param $text \string The text of the link
3169 * @return \string HTML link to the group
3170 */
3171 static function makeGroupLinkHTML( $group, $text = '' ) {
3172 if( $text == '' ) {
3173 $text = self::getGroupName( $group );
3174 }
3175 $title = self::getGroupPage( $group );
3176 if( $title ) {
3177 global $wgUser;
3178 $sk = $wgUser->getSkin();
3179 return $sk->makeLinkObj( $title, htmlspecialchars( $text ) );
3180 } else {
3181 return $text;
3182 }
3183 }
3184
3185 /**
3186 * Create a link to the group in Wikitext, if available;
3187 * else return the group name.
3188 *
3189 * @param $group \string Internal name of the group
3190 * @param $text \string The text of the link
3191 * @return \string Wikilink to the group
3192 */
3193 static function makeGroupLinkWiki( $group, $text = '' ) {
3194 if( $text == '' ) {
3195 $text = self::getGroupName( $group );
3196 }
3197 $title = self::getGroupPage( $group );
3198 if( $title ) {
3199 $page = $title->getPrefixedText();
3200 return "[[$page|$text]]";
3201 } else {
3202 return $text;
3203 }
3204 }
3205
3206 /**
3207 * Increment the user's edit-count field.
3208 * Will have no effect for anonymous users.
3209 */
3210 function incEditCount() {
3211 if( !$this->isAnon() ) {
3212 $dbw = wfGetDB( DB_MASTER );
3213 $dbw->update( 'user',
3214 array( 'user_editcount=user_editcount+1' ),
3215 array( 'user_id' => $this->getId() ),
3216 __METHOD__ );
3217
3218 // Lazy initialization check...
3219 if( $dbw->affectedRows() == 0 ) {
3220 // Pull from a slave to be less cruel to servers
3221 // Accuracy isn't the point anyway here
3222 $dbr = wfGetDB( DB_SLAVE );
3223 $count = $dbr->selectField( 'revision',
3224 'COUNT(rev_user)',
3225 array( 'rev_user' => $this->getId() ),
3226 __METHOD__ );
3227
3228 // Now here's a goddamn hack...
3229 if( $dbr !== $dbw ) {
3230 // If we actually have a slave server, the count is
3231 // at least one behind because the current transaction
3232 // has not been committed and replicated.
3233 $count++;
3234 } else {
3235 // But if DB_SLAVE is selecting the master, then the
3236 // count we just read includes the revision that was
3237 // just added in the working transaction.
3238 }
3239
3240 $dbw->update( 'user',
3241 array( 'user_editcount' => $count ),
3242 array( 'user_id' => $this->getId() ),
3243 __METHOD__ );
3244 }
3245 }
3246 // edit count in user cache too
3247 $this->invalidateCache();
3248 }
3249
3250 /**
3251 * Get the description of a given right
3252 *
3253 * @param $right \string Right to query
3254 * @return \string Localized description of the right
3255 */
3256 static function getRightDescription( $right ) {
3257 global $wgMessageCache;
3258 $wgMessageCache->loadAllMessages();
3259 $key = "right-$right";
3260 $name = wfMsg( $key );
3261 return $name == '' || wfEmptyMsg( $key, $name )
3262 ? $right
3263 : $name;
3264 }
3265
3266 /**
3267 * Make an old-style password hash
3268 *
3269 * @param $password \string Plain-text password
3270 * @param $userId \string User ID
3271 * @return \string Password hash
3272 */
3273 static function oldCrypt( $password, $userId ) {
3274 global $wgPasswordSalt;
3275 if ( $wgPasswordSalt ) {
3276 return md5( $userId . '-' . md5( $password ) );
3277 } else {
3278 return md5( $password );
3279 }
3280 }
3281
3282 /**
3283 * Make a new-style password hash
3284 *
3285 * @param $password \string Plain-text password
3286 * @param $salt \string Optional salt, may be random or the user ID.
3287 * If unspecified or false, will generate one automatically
3288 * @return \string Password hash
3289 */
3290 static function crypt( $password, $salt = false ) {
3291 global $wgPasswordSalt;
3292
3293 $hash = '';
3294 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3295 return $hash;
3296 }
3297
3298 if( $wgPasswordSalt ) {
3299 if ( $salt === false ) {
3300 $salt = substr( wfGenerateToken(), 0, 8 );
3301 }
3302 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3303 } else {
3304 return ':A:' . md5( $password );
3305 }
3306 }
3307
3308 /**
3309 * Compare a password hash with a plain-text password. Requires the user
3310 * ID if there's a chance that the hash is an old-style hash.
3311 *
3312 * @param $hash \string Password hash
3313 * @param $password \string Plain-text password to compare
3314 * @param $userId \string User ID for old-style password salt
3315 * @return \bool
3316 */
3317 static function comparePasswords( $hash, $password, $userId = false ) {
3318 $m = false;
3319 $type = substr( $hash, 0, 3 );
3320
3321 $result = false;
3322 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3323 return $result;
3324 }
3325
3326 if ( $type == ':A:' ) {
3327 # Unsalted
3328 return md5( $password ) === substr( $hash, 3 );
3329 } elseif ( $type == ':B:' ) {
3330 # Salted
3331 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3332 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3333 } else {
3334 # Old-style
3335 return self::oldCrypt( $password, $userId ) === $hash;
3336 }
3337 }
3338
3339 /**
3340 * Add a newuser log entry for this user
3341 * @param $byEmail Boolean: account made by email?
3342 */
3343 public function addNewUserLogEntry( $byEmail = false ) {
3344 global $wgUser, $wgContLang, $wgNewUserLog;
3345 if( empty($wgNewUserLog) ) {
3346 return true; // disabled
3347 }
3348 $talk = $wgContLang->getFormattedNsText( NS_TALK );
3349 if( $this->getName() == $wgUser->getName() ) {
3350 $action = 'create';
3351 $message = '';
3352 } else {
3353 $action = 'create2';
3354 $message = $byEmail ? wfMsgForContent( 'newuserlog-byemail' ) : '';
3355 }
3356 $log = new LogPage( 'newusers' );
3357 $log->addEntry( $action, $this->getUserPage(), $message, array( $this->getId() ) );
3358 return true;
3359 }
3360
3361 /**
3362 * Add an autocreate newuser log entry for this user
3363 * Used by things like CentralAuth and perhaps other authplugins.
3364 */
3365 public function addNewUserLogEntryAutoCreate() {
3366 global $wgNewUserLog;
3367 if( empty($wgNewUserLog) ) {
3368 return true; // disabled
3369 }
3370 $log = new LogPage( 'newusers', false );
3371 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3372 return true;
3373 }
3374
3375 }