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