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