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