* Initialize user_editcount to 0 instead of NULL for newly created accounts
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 /**
3 * See user.txt
4 *
5 * @package MediaWiki
6 */
7
8 # Number of characters in user_token field
9 define( 'USER_TOKEN_LENGTH', 32 );
10
11 # Serialized record version
12 define( 'MW_USER_VERSION', 4 );
13
14 # Some punctuation to prevent editing from broken text-mangling proxies.
15 # FIXME: this is embedded unescaped into HTML attributes in various
16 # places, so we can't safely include ' or " even though we really should.
17 define( 'EDIT_TOKEN_SUFFIX', '\\' );
18
19 /**
20 * Thrown by User::setPassword() on error
21 */
22 class PasswordError extends MWException {
23 // NOP
24 }
25
26 /**
27 *
28 * @package MediaWiki
29 */
30 class User {
31
32 /**
33 * A list of default user toggles, i.e. boolean user preferences that are
34 * displayed by Special:Preferences as checkboxes. This list can be
35 * extended via the UserToggles hook or $wgContLang->getExtraUserToggles().
36 */
37 static public $mToggles = array(
38 'highlightbroken',
39 'justify',
40 'hideminor',
41 'extendwatchlist',
42 'usenewrc',
43 'numberheadings',
44 'showtoolbar',
45 'editondblclick',
46 'editsection',
47 'editsectiononrightclick',
48 'showtoc',
49 'rememberpassword',
50 'editwidth',
51 'watchcreations',
52 'watchdefault',
53 'watchdeletion',
54 'minordefault',
55 'previewontop',
56 'previewonfirst',
57 'nocache',
58 'enotifwatchlistpages',
59 'enotifusertalkpages',
60 'enotifminoredits',
61 'enotifrevealaddr',
62 'shownumberswatching',
63 'fancysig',
64 'externaleditor',
65 'externaldiff',
66 'showjumplinks',
67 'uselivepreview',
68 'forceeditsummary',
69 'watchlisthideown',
70 'watchlisthidebots',
71 'ccmeonemails',
72 );
73
74 /**
75 * List of member variables which are saved to the shared cache (memcached).
76 * Any operation which changes the corresponding database fields must
77 * call a cache-clearing function.
78 */
79 static $mCacheVars = array(
80 # user table
81 'mId',
82 'mName',
83 'mRealName',
84 'mPassword',
85 'mNewpassword',
86 'mNewpassTime',
87 'mEmail',
88 'mOptions',
89 'mTouched',
90 'mToken',
91 'mEmailAuthenticated',
92 'mEmailToken',
93 'mEmailTokenExpires',
94 'mRegistration',
95
96 # user_group table
97 'mGroups',
98 );
99
100 /**
101 * The cache variable declarations
102 */
103 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
104 $mEmail, $mOptions, $mTouched, $mToken, $mEmailAuthenticated,
105 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups;
106
107 /**
108 * Whether the cache variables have been loaded
109 */
110 var $mDataLoaded;
111
112 /**
113 * Initialisation data source if mDataLoaded==false. May be one of:
114 * defaults anonymous user initialised from class defaults
115 * name initialise from mName
116 * id initialise from mId
117 * session log in from cookies or session if possible
118 *
119 * Use the User::newFrom*() family of functions to set this.
120 */
121 var $mFrom;
122
123 /**
124 * Lazy-initialised variables, invalidated with clearInstanceCache
125 */
126 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
127 $mBlockreason, $mBlock, $mEffectiveGroups;
128
129 /**
130 * Lightweight constructor for anonymous user
131 * Use the User::newFrom* factory functions for other kinds of users
132 */
133 function User() {
134 $this->clearInstanceCache( 'defaults' );
135 }
136
137 /**
138 * Load the user table data for this object from the source given by mFrom
139 */
140 function load() {
141 if ( $this->mDataLoaded ) {
142 return;
143 }
144 wfProfileIn( __METHOD__ );
145
146 # Set it now to avoid infinite recursion in accessors
147 $this->mDataLoaded = true;
148
149 switch ( $this->mFrom ) {
150 case 'defaults':
151 $this->loadDefaults();
152 break;
153 case 'name':
154 $this->mId = self::idFromName( $this->mName );
155 if ( !$this->mId ) {
156 # Nonexistent user placeholder object
157 $this->loadDefaults( $this->mName );
158 } else {
159 $this->loadFromId();
160 }
161 break;
162 case 'id':
163 $this->loadFromId();
164 break;
165 case 'session':
166 $this->loadFromSession();
167 break;
168 default:
169 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
170 }
171 wfProfileOut( __METHOD__ );
172 }
173
174 /**
175 * Load user table data given mId
176 * @return false if the ID does not exist, true otherwise
177 * @private
178 */
179 function loadFromId() {
180 global $wgMemc;
181 if ( $this->mId == 0 ) {
182 $this->loadDefaults();
183 return false;
184 }
185
186 # Try cache
187 $key = wfMemcKey( 'user', 'id', $this->mId );
188 $data = $wgMemc->get( $key );
189
190 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
191 # Object is expired, load from DB
192 $data = false;
193 }
194
195 if ( !$data ) {
196 wfDebug( "Cache miss for user {$this->mId}\n" );
197 # Load from DB
198 if ( !$this->loadFromDatabase() ) {
199 # Can't load from ID, user is anonymous
200 return false;
201 }
202
203 # Save to cache
204 $data = array();
205 foreach ( self::$mCacheVars as $name ) {
206 $data[$name] = $this->$name;
207 }
208 $data['mVersion'] = MW_USER_VERSION;
209 $wgMemc->set( $key, $data );
210 } else {
211 wfDebug( "Got user {$this->mId} from cache\n" );
212 # Restore from cache
213 foreach ( self::$mCacheVars as $name ) {
214 $this->$name = $data[$name];
215 }
216 }
217 return true;
218 }
219
220 /**
221 * Static factory method for creation from username.
222 *
223 * This is slightly less efficient than newFromId(), so use newFromId() if
224 * you have both an ID and a name handy.
225 *
226 * @param string $name Username, validated by Title:newFromText()
227 * @param mixed $validate Validate username. Takes the same parameters as
228 * User::getCanonicalName(), except that true is accepted as an alias
229 * for 'valid', for BC.
230 *
231 * @return User object, or null if the username is invalid. If the username
232 * is not present in the database, the result will be a user object with
233 * a name, zero user ID and default settings.
234 * @static
235 */
236 static function newFromName( $name, $validate = 'valid' ) {
237 if ( $validate === true ) {
238 $validate = 'valid';
239 }
240 $name = self::getCanonicalName( $name, $validate );
241 if ( $name === false ) {
242 return null;
243 } else {
244 # Create unloaded user object
245 $u = new User;
246 $u->mName = $name;
247 $u->mFrom = 'name';
248 return $u;
249 }
250 }
251
252 static function newFromId( $id ) {
253 $u = new User;
254 $u->mId = $id;
255 $u->mFrom = 'id';
256 return $u;
257 }
258
259 /**
260 * Factory method to fetch whichever user has a given email confirmation code.
261 * This code is generated when an account is created or its e-mail address
262 * has changed.
263 *
264 * If the code is invalid or has expired, returns NULL.
265 *
266 * @param string $code
267 * @return User
268 * @static
269 */
270 static function newFromConfirmationCode( $code ) {
271 $dbr =& wfGetDB( DB_SLAVE );
272 $id = $dbr->selectField( 'user', 'user_id', array(
273 'user_email_token' => md5( $code ),
274 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
275 ) );
276 if( $id !== false ) {
277 return User::newFromId( $id );
278 } else {
279 return null;
280 }
281 }
282
283 /**
284 * Create a new user object using data from session or cookies. If the
285 * login credentials are invalid, the result is an anonymous user.
286 *
287 * @return User
288 * @static
289 */
290 static function newFromSession() {
291 $user = new User;
292 $user->mFrom = 'session';
293 return $user;
294 }
295
296 /**
297 * Get username given an id.
298 * @param integer $id Database user id
299 * @return string Nickname of a user
300 * @static
301 */
302 static function whoIs( $id ) {
303 $dbr =& wfGetDB( DB_SLAVE );
304 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), 'User::whoIs' );
305 }
306
307 /**
308 * Get real username given an id.
309 * @param integer $id Database user id
310 * @return string Realname of a user
311 * @static
312 */
313 static function whoIsReal( $id ) {
314 $dbr =& wfGetDB( DB_SLAVE );
315 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), 'User::whoIsReal' );
316 }
317
318 /**
319 * Get database id given a user name
320 * @param string $name Nickname of a user
321 * @return integer|null Database user id (null: if non existent
322 * @static
323 */
324 static function idFromName( $name ) {
325 $nt = Title::newFromText( $name );
326 if( is_null( $nt ) ) {
327 # Illegal name
328 return null;
329 }
330 $dbr =& wfGetDB( DB_SLAVE );
331 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
332
333 if ( $s === false ) {
334 return 0;
335 } else {
336 return $s->user_id;
337 }
338 }
339
340 /**
341 * Does the string match an anonymous IPv4 address?
342 *
343 * This function exists for username validation, in order to reject
344 * usernames which are similar in form to IP addresses. Strings such
345 * as 300.300.300.300 will return true because it looks like an IP
346 * address, despite not being strictly valid.
347 *
348 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
349 * address because the usemod software would "cloak" anonymous IP
350 * addresses like this, if we allowed accounts like this to be created
351 * new users could get the old edits of these anonymous users.
352 *
353 * @bug 3631
354 *
355 * @static
356 * @param string $name Nickname of a user
357 * @return bool
358 */
359 static function isIP( $name ) {
360 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name);
361 /*return preg_match("/^
362 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
363 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
364 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))\.
365 (?:[01]?\d{1,2}|2(:?[0-4]\d|5[0-5]))
366 $/x", $name);*/
367 }
368
369 /**
370 * Is the input a valid username?
371 *
372 * Checks if the input is a valid username, we don't want an empty string,
373 * an IP address, anything that containins slashes (would mess up subpages),
374 * is longer than the maximum allowed username size or doesn't begin with
375 * a capital letter.
376 *
377 * @param string $name
378 * @return bool
379 * @static
380 */
381 static function isValidUserName( $name ) {
382 global $wgContLang, $wgMaxNameChars;
383
384 if ( $name == ''
385 || User::isIP( $name )
386 || strpos( $name, '/' ) !== false
387 || strlen( $name ) > $wgMaxNameChars
388 || $name != $wgContLang->ucfirst( $name ) )
389 return false;
390
391 // Ensure that the name can't be misresolved as a different title,
392 // such as with extra namespace keys at the start.
393 $parsed = Title::newFromText( $name );
394 if( is_null( $parsed )
395 || $parsed->getNamespace()
396 || strcmp( $name, $parsed->getPrefixedText() ) )
397 return false;
398
399 // Check an additional blacklist of troublemaker characters.
400 // Should these be merged into the title char list?
401 $unicodeBlacklist = '/[' .
402 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
403 '\x{00a0}' . # non-breaking space
404 '\x{2000}-\x{200f}' . # various whitespace
405 '\x{2028}-\x{202f}' . # breaks and control chars
406 '\x{3000}' . # ideographic space
407 '\x{e000}-\x{f8ff}' . # private use
408 ']/u';
409 if( preg_match( $unicodeBlacklist, $name ) ) {
410 return false;
411 }
412
413 return true;
414 }
415
416 /**
417 * Usernames which fail to pass this function will be blocked
418 * from user login and new account registrations, but may be used
419 * internally by batch processes.
420 *
421 * If an account already exists in this form, login will be blocked
422 * by a failure to pass this function.
423 *
424 * @param string $name
425 * @return bool
426 */
427 static function isUsableName( $name ) {
428 global $wgReservedUsernames;
429 return
430 // Must be a usable username, obviously ;)
431 self::isValidUserName( $name ) &&
432
433 // Certain names may be reserved for batch processes.
434 !in_array( $name, $wgReservedUsernames );
435 }
436
437 /**
438 * Usernames which fail to pass this function will be blocked
439 * from new account registrations, but may be used internally
440 * either by batch processes or by user accounts which have
441 * already been created.
442 *
443 * Additional character blacklisting may be added here
444 * rather than in isValidUserName() to avoid disrupting
445 * existing accounts.
446 *
447 * @param string $name
448 * @return bool
449 */
450 static function isCreatableName( $name ) {
451 return
452 self::isUsableName( $name ) &&
453
454 // Registration-time character blacklisting...
455 strpos( $name, '@' ) === false;
456 }
457
458 /**
459 * Is the input a valid password?
460 *
461 * @param string $password
462 * @return bool
463 * @static
464 */
465 static function isValidPassword( $password ) {
466 global $wgMinimalPasswordLength;
467 return strlen( $password ) >= $wgMinimalPasswordLength;
468 }
469
470 /**
471 * Does the string match roughly an email address ?
472 *
473 * There used to be a regular expression here, it got removed because it
474 * rejected valid addresses. Actually just check if there is '@' somewhere
475 * in the given address.
476 *
477 * @todo Check for RFC 2822 compilance
478 * @bug 959
479 *
480 * @param string $addr email address
481 * @static
482 * @return bool
483 */
484 static function isValidEmailAddr ( $addr ) {
485 return ( trim( $addr ) != '' ) &&
486 (false !== strpos( $addr, '@' ) );
487 }
488
489 /**
490 * Given unvalidated user input, return a canonical username, or false if
491 * the username is invalid.
492 * @param string $name
493 * @param mixed $validate Type of validation to use:
494 * false No validation
495 * 'valid' Valid for batch processes
496 * 'usable' Valid for batch processes and login
497 * 'creatable' Valid for batch processes, login and account creation
498 */
499 static function getCanonicalName( $name, $validate = 'valid' ) {
500 # Force usernames to capital
501 global $wgContLang;
502 $name = $wgContLang->ucfirst( $name );
503
504 # Clean up name according to title rules
505 $t = Title::newFromText( $name );
506 if( is_null( $t ) ) {
507 return false;
508 }
509
510 # Reject various classes of invalid names
511 $name = $t->getText();
512 global $wgAuth;
513 $name = $wgAuth->getCanonicalName( $t->getText() );
514
515 switch ( $validate ) {
516 case false:
517 break;
518 case 'valid':
519 if ( !User::isValidUserName( $name ) ) {
520 $name = false;
521 }
522 break;
523 case 'usable':
524 if ( !User::isUsableName( $name ) ) {
525 $name = false;
526 }
527 break;
528 case 'creatable':
529 if ( !User::isCreatableName( $name ) ) {
530 $name = false;
531 }
532 break;
533 default:
534 throw new MWException( 'Invalid parameter value for $validate in '.__METHOD__ );
535 }
536 return $name;
537 }
538
539 /**
540 * Count the number of edits of a user
541 *
542 * @param int $uid The user ID to check
543 * @return int
544 * @static
545 */
546 static function edits( $uid ) {
547 $dbr =& wfGetDB( DB_SLAVE );
548 return $dbr->selectField(
549 'revision', 'count(*)',
550 array( 'rev_user' => $uid ),
551 __METHOD__
552 );
553 }
554
555 /**
556 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
557 * @todo: hash random numbers to improve security, like generateToken()
558 *
559 * @return string
560 * @static
561 */
562 static function randomPassword() {
563 global $wgMinimalPasswordLength;
564 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
565 $l = strlen( $pwchars ) - 1;
566
567 $pwlength = max( 7, $wgMinimalPasswordLength );
568 $digit = mt_rand(0, $pwlength - 1);
569 $np = '';
570 for ( $i = 0; $i < $pwlength; $i++ ) {
571 $np .= $i == $digit ? chr( mt_rand(48, 57) ) : $pwchars{ mt_rand(0, $l)};
572 }
573 return $np;
574 }
575
576 /**
577 * Set cached properties to default. Note: this no longer clears
578 * uncached lazy-initialised properties. The constructor does that instead.
579 *
580 * @private
581 */
582 function loadDefaults( $name = false ) {
583 wfProfileIn( __METHOD__ );
584
585 global $wgCookiePrefix;
586
587 $this->mId = 0;
588 $this->mName = $name;
589 $this->mRealName = '';
590 $this->mPassword = $this->mNewpassword = '';
591 $this->mNewpassTime = null;
592 $this->mEmail = '';
593 $this->mOptions = null; # Defer init
594
595 if ( isset( $_COOKIE[$wgCookiePrefix.'LoggedOut'] ) ) {
596 $this->mTouched = wfTimestamp( TS_MW, $_COOKIE[$wgCookiePrefix.'LoggedOut'] );
597 } else {
598 $this->mTouched = '0'; # Allow any pages to be cached
599 }
600
601 $this->setToken(); # Random
602 $this->mEmailAuthenticated = null;
603 $this->mEmailToken = '';
604 $this->mEmailTokenExpires = null;
605 $this->mRegistration = wfTimestamp( TS_MW );
606 $this->mGroups = array();
607
608 wfProfileOut( __METHOD__ );
609 }
610
611 /**
612 * Initialise php session
613 * @deprecated use wfSetupSession()
614 */
615 function SetupSession() {
616 wfSetupSession();
617 }
618
619 /**
620 * Load user data from the session or login cookie. If there are no valid
621 * credentials, initialises the user as an anon.
622 * @return true if the user is logged in, false otherwise
623 *
624 * @private
625 */
626 function loadFromSession() {
627 global $wgMemc, $wgCookiePrefix;
628
629 if ( isset( $_SESSION['wsUserID'] ) ) {
630 if ( 0 != $_SESSION['wsUserID'] ) {
631 $sId = $_SESSION['wsUserID'];
632 } else {
633 $this->loadDefaults();
634 return false;
635 }
636 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserID"] ) ) {
637 $sId = intval( $_COOKIE["{$wgCookiePrefix}UserID"] );
638 $_SESSION['wsUserID'] = $sId;
639 } else {
640 $this->loadDefaults();
641 return false;
642 }
643 if ( isset( $_SESSION['wsUserName'] ) ) {
644 $sName = $_SESSION['wsUserName'];
645 } else if ( isset( $_COOKIE["{$wgCookiePrefix}UserName"] ) ) {
646 $sName = $_COOKIE["{$wgCookiePrefix}UserName"];
647 $_SESSION['wsUserName'] = $sName;
648 } else {
649 $this->loadDefaults();
650 return false;
651 }
652
653 $passwordCorrect = FALSE;
654 $this->mId = $sId;
655 if ( !$this->loadFromId() ) {
656 # Not a valid ID, loadFromId has switched the object to anon for us
657 return false;
658 }
659
660 if ( isset( $_SESSION['wsToken'] ) ) {
661 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
662 $from = 'session';
663 } else if ( isset( $_COOKIE["{$wgCookiePrefix}Token"] ) ) {
664 $passwordCorrect = $this->mToken == $_COOKIE["{$wgCookiePrefix}Token"];
665 $from = 'cookie';
666 } else {
667 # No session or persistent login cookie
668 $this->loadDefaults();
669 return false;
670 }
671
672 if ( ( $sName == $this->mName ) && $passwordCorrect ) {
673 wfDebug( "Logged in from $from\n" );
674 return true;
675 } else {
676 # Invalid credentials
677 wfDebug( "Can't log in from $from, invalid credentials\n" );
678 $this->loadDefaults();
679 return false;
680 }
681 }
682
683 /**
684 * Load user and user_group data from the database
685 * $this->mId must be set, this is how the user is identified.
686 *
687 * @return true if the user exists, false if the user is anonymous
688 * @private
689 */
690 function loadFromDatabase() {
691 # Paranoia
692 $this->mId = intval( $this->mId );
693
694 /** Anonymous user */
695 if( !$this->mId ) {
696 $this->loadDefaults();
697 return false;
698 }
699
700 $dbr =& wfGetDB( DB_MASTER );
701 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
702
703 if ( $s !== false ) {
704 # Initialise user table data
705 $this->mName = $s->user_name;
706 $this->mRealName = $s->user_real_name;
707 $this->mPassword = $s->user_password;
708 $this->mNewpassword = $s->user_newpassword;
709 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $s->user_newpass_time );
710 $this->mEmail = $s->user_email;
711 $this->decodeOptions( $s->user_options );
712 $this->mTouched = wfTimestamp(TS_MW,$s->user_touched);
713 $this->mToken = $s->user_token;
714 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $s->user_email_authenticated );
715 $this->mEmailToken = $s->user_email_token;
716 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $s->user_email_token_expires );
717 $this->mRegistration = wfTimestampOrNull( TS_MW, $s->user_registration );
718
719 # Load group data
720 $res = $dbr->select( 'user_groups',
721 array( 'ug_group' ),
722 array( 'ug_user' => $this->mId ),
723 __METHOD__ );
724 $this->mGroups = array();
725 while( $row = $dbr->fetchObject( $res ) ) {
726 $this->mGroups[] = $row->ug_group;
727 }
728 return true;
729 } else {
730 # Invalid user_id
731 $this->mId = 0;
732 $this->loadDefaults();
733 return false;
734 }
735 }
736
737 /**
738 * Clear various cached data stored in this object.
739 * @param string $reloadFrom Reload user and user_groups table data from a
740 * given source. May be "name", "id", "defaults", "session" or false for
741 * no reload.
742 */
743 function clearInstanceCache( $reloadFrom = false ) {
744 $this->mNewtalk = -1;
745 $this->mDatePreference = null;
746 $this->mBlockedby = -1; # Unset
747 $this->mHash = false;
748 $this->mSkin = null;
749 $this->mRights = null;
750 $this->mEffectiveGroups = null;
751
752 if ( $reloadFrom ) {
753 $this->mDataLoaded = false;
754 $this->mFrom = $reloadFrom;
755 }
756 }
757
758 /**
759 * Combine the language default options with any site-specific options
760 * and add the default language variants.
761 *
762 * @return array
763 * @static
764 * @private
765 */
766 function getDefaultOptions() {
767 global $wgNamespacesToBeSearchedDefault;
768 /**
769 * Site defaults will override the global/language defaults
770 */
771 global $wgDefaultUserOptions, $wgContLang;
772 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
773
774 /**
775 * default language setting
776 */
777 $variant = $wgContLang->getPreferredVariant( false );
778 $defOpt['variant'] = $variant;
779 $defOpt['language'] = $variant;
780
781 foreach( $wgNamespacesToBeSearchedDefault as $nsnum => $val ) {
782 $defOpt['searchNs'.$nsnum] = $val;
783 }
784 return $defOpt;
785 }
786
787 /**
788 * Get a given default option value.
789 *
790 * @param string $opt
791 * @return string
792 * @static
793 * @public
794 */
795 function getDefaultOption( $opt ) {
796 $defOpts = User::getDefaultOptions();
797 if( isset( $defOpts[$opt] ) ) {
798 return $defOpts[$opt];
799 } else {
800 return '';
801 }
802 }
803
804 /**
805 * Get a list of user toggle names
806 * @return array
807 */
808 static function getToggles() {
809 global $wgContLang;
810 $extraToggles = array();
811 wfRunHooks( 'UserToggles', array( &$extraToggles ) );
812 return array_merge( self::$mToggles, $extraToggles, $wgContLang->getExtraUserToggles() );
813 }
814
815
816 /**
817 * Get blocking information
818 * @private
819 * @param bool $bFromSlave Specify whether to check slave or master. To improve performance,
820 * non-critical checks are done against slaves. Check when actually saving should be done against
821 * master.
822 */
823 function getBlockedStatus( $bFromSlave = true ) {
824 global $wgEnableSorbs, $wgProxyWhitelist;
825
826 if ( -1 != $this->mBlockedby ) {
827 wfDebug( "User::getBlockedStatus: already loaded.\n" );
828 return;
829 }
830
831 wfProfileIn( __METHOD__ );
832 wfDebug( __METHOD__.": checking...\n" );
833
834 $this->mBlockedby = 0;
835 $ip = wfGetIP();
836
837 # User/IP blocking
838 $this->mBlock = new Block();
839 $this->mBlock->fromMaster( !$bFromSlave );
840 if ( $this->mBlock->load( $ip , $this->mId ) ) {
841 wfDebug( __METHOD__.": Found block.\n" );
842 $this->mBlockedby = $this->mBlock->mBy;
843 $this->mBlockreason = $this->mBlock->mReason;
844 if ( $this->isLoggedIn() ) {
845 $this->spreadBlock();
846 }
847 } else {
848 $this->mBlock = null;
849 wfDebug( __METHOD__.": No block.\n" );
850 }
851
852 # Proxy blocking
853 if ( !$this->isAllowed('proxyunbannable') && !in_array( $ip, $wgProxyWhitelist ) ) {
854
855 # Local list
856 if ( wfIsLocallyBlockedProxy( $ip ) ) {
857 $this->mBlockedby = wfMsg( 'proxyblocker' );
858 $this->mBlockreason = wfMsg( 'proxyblockreason' );
859 }
860
861 # DNSBL
862 if ( !$this->mBlockedby && $wgEnableSorbs && !$this->getID() ) {
863 if ( $this->inSorbsBlacklist( $ip ) ) {
864 $this->mBlockedby = wfMsg( 'sorbs' );
865 $this->mBlockreason = wfMsg( 'sorbsreason' );
866 }
867 }
868 }
869
870 # Extensions
871 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
872
873 wfProfileOut( __METHOD__ );
874 }
875
876 function inSorbsBlacklist( $ip ) {
877 global $wgEnableSorbs, $wgSorbsUrl;
878
879 return $wgEnableSorbs &&
880 $this->inDnsBlacklist( $ip, $wgSorbsUrl );
881 }
882
883 function inDnsBlacklist( $ip, $base ) {
884 wfProfileIn( __METHOD__ );
885
886 $found = false;
887 $host = '';
888
889 $m = array();
890 if ( preg_match( '/^(\d{1,3})\.(\d{1,3})\.(\d{1,3})\.(\d{1,3})$/', $ip, $m ) ) {
891 # Make hostname
892 for ( $i=4; $i>=1; $i-- ) {
893 $host .= $m[$i] . '.';
894 }
895 $host .= $base;
896
897 # Send query
898 $ipList = gethostbynamel( $host );
899
900 if ( $ipList ) {
901 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
902 $found = true;
903 } else {
904 wfDebug( "Requested $host, not found in $base.\n" );
905 }
906 }
907
908 wfProfileOut( __METHOD__ );
909 return $found;
910 }
911
912 /**
913 * Primitive rate limits: enforce maximum actions per time period
914 * to put a brake on flooding.
915 *
916 * Note: when using a shared cache like memcached, IP-address
917 * last-hit counters will be shared across wikis.
918 *
919 * @return bool true if a rate limiter was tripped
920 * @public
921 */
922 function pingLimiter( $action='edit' ) {
923
924 # Call the 'PingLimiter' hook
925 $result = false;
926 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
927 return $result;
928 }
929
930 global $wgRateLimits, $wgRateLimitsExcludedGroups;
931 if( !isset( $wgRateLimits[$action] ) ) {
932 return false;
933 }
934
935 # Some groups shouldn't trigger the ping limiter, ever
936 foreach( $this->getGroups() as $group ) {
937 if( array_search( $group, $wgRateLimitsExcludedGroups ) !== false )
938 return false;
939 }
940
941 global $wgMemc, $wgRateLimitLog;
942 wfProfileIn( __METHOD__ );
943
944 $limits = $wgRateLimits[$action];
945 $keys = array();
946 $id = $this->getId();
947 $ip = wfGetIP();
948
949 if( isset( $limits['anon'] ) && $id == 0 ) {
950 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
951 }
952
953 if( isset( $limits['user'] ) && $id != 0 ) {
954 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['user'];
955 }
956 if( $this->isNewbie() ) {
957 if( isset( $limits['newbie'] ) && $id != 0 ) {
958 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
959 }
960 if( isset( $limits['ip'] ) ) {
961 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
962 }
963 $matches = array();
964 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
965 $subnet = $matches[1];
966 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
967 }
968 }
969
970 $triggered = false;
971 foreach( $keys as $key => $limit ) {
972 list( $max, $period ) = $limit;
973 $summary = "(limit $max in {$period}s)";
974 $count = $wgMemc->get( $key );
975 if( $count ) {
976 if( $count > $max ) {
977 wfDebug( __METHOD__.": tripped! $key at $count $summary\n" );
978 if( $wgRateLimitLog ) {
979 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
980 }
981 $triggered = true;
982 } else {
983 wfDebug( __METHOD__.": ok. $key at $count $summary\n" );
984 }
985 } else {
986 wfDebug( __METHOD__.": adding record for $key $summary\n" );
987 $wgMemc->add( $key, 1, intval( $period ) );
988 }
989 $wgMemc->incr( $key );
990 }
991
992 wfProfileOut( __METHOD__ );
993 return $triggered;
994 }
995
996 /**
997 * Check if user is blocked
998 * @return bool True if blocked, false otherwise
999 */
1000 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1001 wfDebug( "User::isBlocked: enter\n" );
1002 $this->getBlockedStatus( $bFromSlave );
1003 return $this->mBlockedby !== 0;
1004 }
1005
1006 /**
1007 * Check if user is blocked from editing a particular article
1008 */
1009 function isBlockedFrom( $title, $bFromSlave = false ) {
1010 global $wgBlockAllowsUTEdit;
1011 wfProfileIn( __METHOD__ );
1012 wfDebug( __METHOD__.": enter\n" );
1013
1014 if ( $wgBlockAllowsUTEdit && $title->getText() === $this->getName() &&
1015 $title->getNamespace() == NS_USER_TALK )
1016 {
1017 $blocked = false;
1018 wfDebug( __METHOD__.": self-talk page, ignoring any blocks\n" );
1019 } else {
1020 wfDebug( __METHOD__.": asking isBlocked()\n" );
1021 $blocked = $this->isBlocked( $bFromSlave );
1022 }
1023 wfProfileOut( __METHOD__ );
1024 return $blocked;
1025 }
1026
1027 /**
1028 * Get name of blocker
1029 * @return string name of blocker
1030 */
1031 function blockedBy() {
1032 $this->getBlockedStatus();
1033 return $this->mBlockedby;
1034 }
1035
1036 /**
1037 * Get blocking reason
1038 * @return string Blocking reason
1039 */
1040 function blockedFor() {
1041 $this->getBlockedStatus();
1042 return $this->mBlockreason;
1043 }
1044
1045 /**
1046 * Get the user ID. Returns 0 if the user is anonymous or nonexistent.
1047 */
1048 function getID() {
1049 $this->load();
1050 return $this->mId;
1051 }
1052
1053 /**
1054 * Set the user and reload all fields according to that ID
1055 * @deprecated use User::newFromId()
1056 */
1057 function setID( $v ) {
1058 $this->mId = $v;
1059 $this->clearInstanceCache( 'id' );
1060 }
1061
1062 /**
1063 * Get the user name, or the IP for anons
1064 */
1065 function getName() {
1066 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1067 # Special case optimisation
1068 return $this->mName;
1069 } else {
1070 $this->load();
1071 if ( $this->mName === false ) {
1072 $this->mName = wfGetIP();
1073 }
1074 return $this->mName;
1075 }
1076 }
1077
1078 /**
1079 * Set the user name.
1080 *
1081 * This does not reload fields from the database according to the given
1082 * name. Rather, it is used to create a temporary "nonexistent user" for
1083 * later addition to the database. It can also be used to set the IP
1084 * address for an anonymous user to something other than the current
1085 * remote IP.
1086 *
1087 * User::newFromName() has rougly the same function, when the named user
1088 * does not exist.
1089 */
1090 function setName( $str ) {
1091 $this->load();
1092 $this->mName = $str;
1093 }
1094
1095 /**
1096 * Return the title dbkey form of the name, for eg user pages.
1097 * @return string
1098 * @public
1099 */
1100 function getTitleKey() {
1101 return str_replace( ' ', '_', $this->getName() );
1102 }
1103
1104 function getNewtalk() {
1105 $this->load();
1106
1107 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1108 if( $this->mNewtalk === -1 ) {
1109 $this->mNewtalk = false; # reset talk page status
1110
1111 # Check memcached separately for anons, who have no
1112 # entire User object stored in there.
1113 if( !$this->mId ) {
1114 global $wgMemc;
1115 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1116 $newtalk = $wgMemc->get( $key );
1117 if( is_integer( $newtalk ) ) {
1118 $this->mNewtalk = (bool)$newtalk;
1119 } else {
1120 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName() );
1121 $wgMemc->set( $key, $this->mNewtalk, time() ); // + 1800 );
1122 }
1123 } else {
1124 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1125 }
1126 }
1127
1128 return (bool)$this->mNewtalk;
1129 }
1130
1131 /**
1132 * Return the talk page(s) this user has new messages on.
1133 */
1134 function getNewMessageLinks() {
1135 $talks = array();
1136 if (!wfRunHooks('UserRetrieveNewTalks', array(&$this, &$talks)))
1137 return $talks;
1138
1139 if (!$this->getNewtalk())
1140 return array();
1141 $up = $this->getUserPage();
1142 $utp = $up->getTalkPage();
1143 return array(array("wiki" => wfWikiID(), "link" => $utp->getLocalURL()));
1144 }
1145
1146
1147 /**
1148 * Perform a user_newtalk check on current slaves; if the memcached data
1149 * is funky we don't want newtalk state to get stuck on save, as that's
1150 * damn annoying.
1151 *
1152 * @param string $field
1153 * @param mixed $id
1154 * @return bool
1155 * @private
1156 */
1157 function checkNewtalk( $field, $id ) {
1158 $dbr =& wfGetDB( DB_SLAVE );
1159 $ok = $dbr->selectField( 'user_newtalk', $field,
1160 array( $field => $id ), __METHOD__ );
1161 return $ok !== false;
1162 }
1163
1164 /**
1165 * Add or update the
1166 * @param string $field
1167 * @param mixed $id
1168 * @private
1169 */
1170 function updateNewtalk( $field, $id ) {
1171 if( $this->checkNewtalk( $field, $id ) ) {
1172 wfDebug( __METHOD__." already set ($field, $id), ignoring\n" );
1173 return false;
1174 }
1175 $dbw =& wfGetDB( DB_MASTER );
1176 $dbw->insert( 'user_newtalk',
1177 array( $field => $id ),
1178 __METHOD__,
1179 'IGNORE' );
1180 wfDebug( __METHOD__.": set on ($field, $id)\n" );
1181 return true;
1182 }
1183
1184 /**
1185 * Clear the new messages flag for the given user
1186 * @param string $field
1187 * @param mixed $id
1188 * @private
1189 */
1190 function deleteNewtalk( $field, $id ) {
1191 if( !$this->checkNewtalk( $field, $id ) ) {
1192 wfDebug( __METHOD__.": already gone ($field, $id), ignoring\n" );
1193 return false;
1194 }
1195 $dbw =& wfGetDB( DB_MASTER );
1196 $dbw->delete( 'user_newtalk',
1197 array( $field => $id ),
1198 __METHOD__ );
1199 wfDebug( __METHOD__.": killed on ($field, $id)\n" );
1200 return true;
1201 }
1202
1203 /**
1204 * Update the 'You have new messages!' status.
1205 * @param bool $val
1206 */
1207 function setNewtalk( $val ) {
1208 if( wfReadOnly() ) {
1209 return;
1210 }
1211
1212 $this->load();
1213 $this->mNewtalk = $val;
1214
1215 if( $this->isAnon() ) {
1216 $field = 'user_ip';
1217 $id = $this->getName();
1218 } else {
1219 $field = 'user_id';
1220 $id = $this->getId();
1221 }
1222
1223 if( $val ) {
1224 $changed = $this->updateNewtalk( $field, $id );
1225 } else {
1226 $changed = $this->deleteNewtalk( $field, $id );
1227 }
1228
1229 if( $changed ) {
1230 if( $this->isAnon() ) {
1231 // Anons have a separate memcached space, since
1232 // user records aren't kept for them.
1233 global $wgMemc;
1234 $key = wfMemcKey( 'newtalk', 'ip', $val );
1235 $wgMemc->set( $key, $val ? 1 : 0 );
1236 } else {
1237 if( $val ) {
1238 // Make sure the user page is watched, so a notification
1239 // will be sent out if enabled.
1240 $this->addWatch( $this->getTalkPage() );
1241 }
1242 }
1243 $this->invalidateCache();
1244 }
1245 }
1246
1247 /**
1248 * Generate a current or new-future timestamp to be stored in the
1249 * user_touched field when we update things.
1250 */
1251 private static function newTouchedTimestamp() {
1252 global $wgClockSkewFudge;
1253 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1254 }
1255
1256 /**
1257 * Clear user data from memcached.
1258 * Use after applying fun updates to the database; caller's
1259 * responsibility to update user_touched if appropriate.
1260 *
1261 * Called implicitly from invalidateCache() and saveSettings().
1262 */
1263 private function clearSharedCache() {
1264 if( $this->mId ) {
1265 global $wgMemc;
1266 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1267 }
1268 }
1269
1270 /**
1271 * Immediately touch the user data cache for this account.
1272 * Updates user_touched field, and removes account data from memcached
1273 * for reload on the next hit.
1274 */
1275 function invalidateCache() {
1276 $this->load();
1277 if( $this->mId ) {
1278 $this->mTouched = self::newTouchedTimestamp();
1279
1280 $dbw =& wfGetDB( DB_MASTER );
1281 $dbw->update( 'user',
1282 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1283 array( 'user_id' => $this->mId ),
1284 __METHOD__ );
1285
1286 $this->clearSharedCache();
1287 }
1288 }
1289
1290 function validateCache( $timestamp ) {
1291 $this->load();
1292 return ($timestamp >= $this->mTouched);
1293 }
1294
1295 /**
1296 * Encrypt a password.
1297 * It can eventuall salt a password @see User::addSalt()
1298 * @param string $p clear Password.
1299 * @return string Encrypted password.
1300 */
1301 function encryptPassword( $p ) {
1302 $this->load();
1303 return wfEncryptPassword( $this->mId, $p );
1304 }
1305
1306 /**
1307 * Set the password and reset the random token
1308 * Calls through to authentication plugin if necessary;
1309 * will have no effect if the auth plugin refuses to
1310 * pass the change through or if the legal password
1311 * checks fail.
1312 *
1313 * As a special case, setting the password to null
1314 * wipes it, so the account cannot be logged in until
1315 * a new password is set, for instance via e-mail.
1316 *
1317 * @param string $str
1318 * @throws PasswordError on failure
1319 */
1320 function setPassword( $str ) {
1321 global $wgAuth;
1322
1323 if( $str !== null ) {
1324 if( !$wgAuth->allowPasswordChange() ) {
1325 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1326 }
1327
1328 if( !$this->isValidPassword( $str ) ) {
1329 global $wgMinimalPasswordLength;
1330 throw new PasswordError( wfMsg( 'passwordtooshort',
1331 $wgMinimalPasswordLength ) );
1332 }
1333 }
1334
1335 if( !$wgAuth->setPassword( $this, $str ) ) {
1336 throw new PasswordError( wfMsg( 'externaldberror' ) );
1337 }
1338
1339 $this->load();
1340 $this->setToken();
1341
1342 if( $str === null ) {
1343 // Save an invalid hash...
1344 $this->mPassword = '';
1345 } else {
1346 $this->mPassword = $this->encryptPassword( $str );
1347 }
1348 $this->mNewpassword = '';
1349 $this->mNewpassTime = null;
1350
1351 return true;
1352 }
1353
1354 /**
1355 * Set the random token (used for persistent authentication)
1356 * Called from loadDefaults() among other places.
1357 * @private
1358 */
1359 function setToken( $token = false ) {
1360 global $wgSecretKey, $wgProxyKey;
1361 $this->load();
1362 if ( !$token ) {
1363 if ( $wgSecretKey ) {
1364 $key = $wgSecretKey;
1365 } elseif ( $wgProxyKey ) {
1366 $key = $wgProxyKey;
1367 } else {
1368 $key = microtime();
1369 }
1370 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1371 } else {
1372 $this->mToken = $token;
1373 }
1374 }
1375
1376 function setCookiePassword( $str ) {
1377 $this->load();
1378 $this->mCookiePassword = md5( $str );
1379 }
1380
1381 /**
1382 * Set the password for a password reminder or new account email
1383 * Sets the user_newpass_time field if $throttle is true
1384 */
1385 function setNewpassword( $str, $throttle = true ) {
1386 $this->load();
1387 $this->mNewpassword = $this->encryptPassword( $str );
1388 if ( $throttle ) {
1389 $this->mNewpassTime = wfTimestampNow();
1390 }
1391 }
1392
1393 /**
1394 * Returns true if a password reminder email has already been sent within
1395 * the last $wgPasswordReminderResendTime hours
1396 */
1397 function isPasswordReminderThrottled() {
1398 global $wgPasswordReminderResendTime;
1399 $this->load();
1400 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1401 return false;
1402 }
1403 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1404 return time() < $expiry;
1405 }
1406
1407 function getEmail() {
1408 $this->load();
1409 return $this->mEmail;
1410 }
1411
1412 function getEmailAuthenticationTimestamp() {
1413 $this->load();
1414 return $this->mEmailAuthenticated;
1415 }
1416
1417 function setEmail( $str ) {
1418 $this->load();
1419 $this->mEmail = $str;
1420 }
1421
1422 function getRealName() {
1423 $this->load();
1424 return $this->mRealName;
1425 }
1426
1427 function setRealName( $str ) {
1428 $this->load();
1429 $this->mRealName = $str;
1430 }
1431
1432 /**
1433 * @param string $oname The option to check
1434 * @param string $defaultOverride A default value returned if the option does not exist
1435 * @return string
1436 */
1437 function getOption( $oname, $defaultOverride = '' ) {
1438 $this->load();
1439
1440 if ( is_null( $this->mOptions ) ) {
1441 if($defaultOverride != '') {
1442 return $defaultOverride;
1443 }
1444 $this->mOptions = User::getDefaultOptions();
1445 }
1446
1447 if ( array_key_exists( $oname, $this->mOptions ) ) {
1448 return trim( $this->mOptions[$oname] );
1449 } else {
1450 return $defaultOverride;
1451 }
1452 }
1453
1454 /**
1455 * Get the user's date preference, including some important migration for
1456 * old user rows.
1457 */
1458 function getDatePreference() {
1459 if ( is_null( $this->mDatePreference ) ) {
1460 global $wgLang;
1461 $value = $this->getOption( 'date' );
1462 $map = $wgLang->getDatePreferenceMigrationMap();
1463 if ( isset( $map[$value] ) ) {
1464 $value = $map[$value];
1465 }
1466 $this->mDatePreference = $value;
1467 }
1468 return $this->mDatePreference;
1469 }
1470
1471 /**
1472 * @param string $oname The option to check
1473 * @return bool False if the option is not selected, true if it is
1474 */
1475 function getBoolOption( $oname ) {
1476 return (bool)$this->getOption( $oname );
1477 }
1478
1479 /**
1480 * Get an option as an integer value from the source string.
1481 * @param string $oname The option to check
1482 * @param int $default Optional value to return if option is unset/blank.
1483 * @return int
1484 */
1485 function getIntOption( $oname, $default=0 ) {
1486 $val = $this->getOption( $oname );
1487 if( $val == '' ) {
1488 $val = $default;
1489 }
1490 return intval( $val );
1491 }
1492
1493 function setOption( $oname, $val ) {
1494 $this->load();
1495 if ( is_null( $this->mOptions ) ) {
1496 $this->mOptions = User::getDefaultOptions();
1497 }
1498 if ( $oname == 'skin' ) {
1499 # Clear cached skin, so the new one displays immediately in Special:Preferences
1500 unset( $this->mSkin );
1501 }
1502 // Filter out any newlines that may have passed through input validation.
1503 // Newlines are used to separate items in the options blob.
1504 $val = str_replace( "\r\n", "\n", $val );
1505 $val = str_replace( "\r", "\n", $val );
1506 $val = str_replace( "\n", " ", $val );
1507 $this->mOptions[$oname] = $val;
1508 }
1509
1510 function getRights() {
1511 if ( is_null( $this->mRights ) ) {
1512 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
1513 }
1514 return $this->mRights;
1515 }
1516
1517 /**
1518 * Get the list of explicit group memberships this user has.
1519 * The implicit * and user groups are not included.
1520 * @return array of strings
1521 */
1522 function getGroups() {
1523 $this->load();
1524 return $this->mGroups;
1525 }
1526
1527 /**
1528 * Get the list of implicit group memberships this user has.
1529 * This includes all explicit groups, plus 'user' if logged in
1530 * and '*' for all accounts.
1531 * @param boolean $recache Don't use the cache
1532 * @return array of strings
1533 */
1534 function getEffectiveGroups( $recache = false ) {
1535 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
1536 $this->load();
1537 $this->mEffectiveGroups = $this->mGroups;
1538 $this->mEffectiveGroups[] = '*';
1539 if( $this->mId ) {
1540 $this->mEffectiveGroups[] = 'user';
1541
1542 global $wgAutoConfirmAge;
1543 $accountAge = time() - wfTimestampOrNull( TS_UNIX, $this->mRegistration );
1544 if( $accountAge >= $wgAutoConfirmAge ) {
1545 $this->mEffectiveGroups[] = 'autoconfirmed';
1546 }
1547
1548 # Implicit group for users whose email addresses are confirmed
1549 global $wgEmailAuthentication;
1550 if( self::isValidEmailAddr( $this->mEmail ) ) {
1551 if( $wgEmailAuthentication ) {
1552 if( $this->mEmailAuthenticated )
1553 $this->mEffectiveGroups[] = 'emailconfirmed';
1554 } else {
1555 $this->mEffectiveGroups[] = 'emailconfirmed';
1556 }
1557 }
1558 }
1559 }
1560 return $this->mEffectiveGroups;
1561 }
1562
1563 /**
1564 * Add the user to the given group.
1565 * This takes immediate effect.
1566 * @string $group
1567 */
1568 function addGroup( $group ) {
1569 $this->load();
1570 $dbw =& wfGetDB( DB_MASTER );
1571 $dbw->insert( 'user_groups',
1572 array(
1573 'ug_user' => $this->getID(),
1574 'ug_group' => $group,
1575 ),
1576 'User::addGroup',
1577 array( 'IGNORE' ) );
1578
1579 $this->mGroups[] = $group;
1580 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1581
1582 $this->invalidateCache();
1583 }
1584
1585 /**
1586 * Remove the user from the given group.
1587 * This takes immediate effect.
1588 * @string $group
1589 */
1590 function removeGroup( $group ) {
1591 $this->load();
1592 $dbw =& wfGetDB( DB_MASTER );
1593 $dbw->delete( 'user_groups',
1594 array(
1595 'ug_user' => $this->getID(),
1596 'ug_group' => $group,
1597 ),
1598 'User::removeGroup' );
1599
1600 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
1601 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
1602
1603 $this->invalidateCache();
1604 }
1605
1606
1607 /**
1608 * A more legible check for non-anonymousness.
1609 * Returns true if the user is not an anonymous visitor.
1610 *
1611 * @return bool
1612 */
1613 function isLoggedIn() {
1614 return( $this->getID() != 0 );
1615 }
1616
1617 /**
1618 * A more legible check for anonymousness.
1619 * Returns true if the user is an anonymous visitor.
1620 *
1621 * @return bool
1622 */
1623 function isAnon() {
1624 return !$this->isLoggedIn();
1625 }
1626
1627 /**
1628 * Whether the user is a bot
1629 * @deprecated
1630 */
1631 function isBot() {
1632 return $this->isAllowed( 'bot' );
1633 }
1634
1635 /**
1636 * Check if user is allowed to access a feature / make an action
1637 * @param string $action Action to be checked
1638 * @return boolean True: action is allowed, False: action should not be allowed
1639 */
1640 function isAllowed($action='') {
1641 if ( $action === '' )
1642 // In the spirit of DWIM
1643 return true;
1644
1645 return in_array( $action, $this->getRights() );
1646 }
1647
1648 /**
1649 * Load a skin if it doesn't exist or return it
1650 * @todo FIXME : need to check the old failback system [AV]
1651 */
1652 function &getSkin() {
1653 global $wgRequest;
1654 if ( ! isset( $this->mSkin ) ) {
1655 wfProfileIn( __METHOD__ );
1656
1657 # get the user skin
1658 $userSkin = $this->getOption( 'skin' );
1659 $userSkin = $wgRequest->getVal('useskin', $userSkin);
1660
1661 $this->mSkin =& Skin::newFromKey( $userSkin );
1662 wfProfileOut( __METHOD__ );
1663 }
1664 return $this->mSkin;
1665 }
1666
1667 /**#@+
1668 * @param string $title Article title to look at
1669 */
1670
1671 /**
1672 * Check watched status of an article
1673 * @return bool True if article is watched
1674 */
1675 function isWatched( $title ) {
1676 $wl = WatchedItem::fromUserTitle( $this, $title );
1677 return $wl->isWatched();
1678 }
1679
1680 /**
1681 * Watch an article
1682 */
1683 function addWatch( $title ) {
1684 $wl = WatchedItem::fromUserTitle( $this, $title );
1685 $wl->addWatch();
1686 $this->invalidateCache();
1687 }
1688
1689 /**
1690 * Stop watching an article
1691 */
1692 function removeWatch( $title ) {
1693 $wl = WatchedItem::fromUserTitle( $this, $title );
1694 $wl->removeWatch();
1695 $this->invalidateCache();
1696 }
1697
1698 /**
1699 * Clear the user's notification timestamp for the given title.
1700 * If e-notif e-mails are on, they will receive notification mails on
1701 * the next change of the page if it's watched etc.
1702 */
1703 function clearNotification( &$title ) {
1704 global $wgUser, $wgUseEnotif;
1705
1706 if ($title->getNamespace() == NS_USER_TALK &&
1707 $title->getText() == $this->getName() ) {
1708 if (!wfRunHooks('UserClearNewTalkNotification', array(&$this)))
1709 return;
1710 $this->setNewtalk( false );
1711 }
1712
1713 if( !$wgUseEnotif ) {
1714 return;
1715 }
1716
1717 if( $this->isAnon() ) {
1718 // Nothing else to do...
1719 return;
1720 }
1721
1722 // Only update the timestamp if the page is being watched.
1723 // The query to find out if it is watched is cached both in memcached and per-invocation,
1724 // and when it does have to be executed, it can be on a slave
1725 // If this is the user's newtalk page, we always update the timestamp
1726 if ($title->getNamespace() == NS_USER_TALK &&
1727 $title->getText() == $wgUser->getName())
1728 {
1729 $watched = true;
1730 } elseif ( $this->getID() == $wgUser->getID() ) {
1731 $watched = $title->userIsWatching();
1732 } else {
1733 $watched = true;
1734 }
1735
1736 // If the page is watched by the user (or may be watched), update the timestamp on any
1737 // any matching rows
1738 if ( $watched ) {
1739 $dbw =& wfGetDB( DB_MASTER );
1740 $dbw->update( 'watchlist',
1741 array( /* SET */
1742 'wl_notificationtimestamp' => NULL
1743 ), array( /* WHERE */
1744 'wl_title' => $title->getDBkey(),
1745 'wl_namespace' => $title->getNamespace(),
1746 'wl_user' => $this->getID()
1747 ), 'User::clearLastVisited'
1748 );
1749 }
1750 }
1751
1752 /**#@-*/
1753
1754 /**
1755 * Resets all of the given user's page-change notification timestamps.
1756 * If e-notif e-mails are on, they will receive notification mails on
1757 * the next change of any watched page.
1758 *
1759 * @param int $currentUser user ID number
1760 * @public
1761 */
1762 function clearAllNotifications( $currentUser ) {
1763 global $wgUseEnotif;
1764 if ( !$wgUseEnotif ) {
1765 $this->setNewtalk( false );
1766 return;
1767 }
1768 if( $currentUser != 0 ) {
1769
1770 $dbw =& wfGetDB( DB_MASTER );
1771 $dbw->update( 'watchlist',
1772 array( /* SET */
1773 'wl_notificationtimestamp' => NULL
1774 ), array( /* WHERE */
1775 'wl_user' => $currentUser
1776 ), 'UserMailer::clearAll'
1777 );
1778
1779 # we also need to clear here the "you have new message" notification for the own user_talk page
1780 # This is cleared one page view later in Article::viewUpdates();
1781 }
1782 }
1783
1784 /**
1785 * @private
1786 * @return string Encoding options
1787 */
1788 function encodeOptions() {
1789 $this->load();
1790 if ( is_null( $this->mOptions ) ) {
1791 $this->mOptions = User::getDefaultOptions();
1792 }
1793 $a = array();
1794 foreach ( $this->mOptions as $oname => $oval ) {
1795 array_push( $a, $oname.'='.$oval );
1796 }
1797 $s = implode( "\n", $a );
1798 return $s;
1799 }
1800
1801 /**
1802 * @private
1803 */
1804 function decodeOptions( $str ) {
1805 $this->mOptions = array();
1806 $a = explode( "\n", $str );
1807 foreach ( $a as $s ) {
1808 $m = array();
1809 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
1810 $this->mOptions[$m[1]] = $m[2];
1811 }
1812 }
1813 }
1814
1815 function setCookies() {
1816 global $wgCookieExpiration, $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1817 $this->load();
1818 if ( 0 == $this->mId ) return;
1819 $exp = time() + $wgCookieExpiration;
1820
1821 $_SESSION['wsUserID'] = $this->mId;
1822 setcookie( $wgCookiePrefix.'UserID', $this->mId, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1823
1824 $_SESSION['wsUserName'] = $this->getName();
1825 setcookie( $wgCookiePrefix.'UserName', $this->getName(), $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1826
1827 $_SESSION['wsToken'] = $this->mToken;
1828 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
1829 setcookie( $wgCookiePrefix.'Token', $this->mToken, $exp, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1830 } else {
1831 setcookie( $wgCookiePrefix.'Token', '', time() - 3600 );
1832 }
1833 }
1834
1835 /**
1836 * Logout user
1837 * Clears the cookies and session, resets the instance cache
1838 */
1839 function logout() {
1840 global $wgCookiePath, $wgCookieDomain, $wgCookieSecure, $wgCookiePrefix;
1841 $this->clearInstanceCache( 'defaults' );
1842
1843 $_SESSION['wsUserID'] = 0;
1844
1845 setcookie( $wgCookiePrefix.'UserID', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1846 setcookie( $wgCookiePrefix.'Token', '', time() - 3600, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1847
1848 # Remember when user logged out, to prevent seeing cached pages
1849 setcookie( $wgCookiePrefix.'LoggedOut', wfTimestampNow(), time() + 86400, $wgCookiePath, $wgCookieDomain, $wgCookieSecure );
1850 }
1851
1852 /**
1853 * Save object settings into database
1854 * @fixme Only rarely do all these fields need to be set!
1855 */
1856 function saveSettings() {
1857 $this->load();
1858 if ( wfReadOnly() ) { return; }
1859 if ( 0 == $this->mId ) { return; }
1860
1861 $this->mTouched = self::newTouchedTimestamp();
1862
1863 $dbw =& wfGetDB( DB_MASTER );
1864 $dbw->update( 'user',
1865 array( /* SET */
1866 'user_name' => $this->mName,
1867 'user_password' => $this->mPassword,
1868 'user_newpassword' => $this->mNewpassword,
1869 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
1870 'user_real_name' => $this->mRealName,
1871 'user_email' => $this->mEmail,
1872 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1873 'user_options' => $this->encodeOptions(),
1874 'user_touched' => $dbw->timestamp($this->mTouched),
1875 'user_token' => $this->mToken
1876 ), array( /* WHERE */
1877 'user_id' => $this->mId
1878 ), __METHOD__
1879 );
1880 $this->clearSharedCache();
1881 }
1882
1883
1884 /**
1885 * Checks if a user with the given name exists, returns the ID
1886 */
1887 function idForName() {
1888 $s = trim( $this->getName() );
1889 if ( 0 == strcmp( '', $s ) ) return 0;
1890
1891 $dbr =& wfGetDB( DB_SLAVE );
1892 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
1893 if ( $id === false ) {
1894 $id = 0;
1895 }
1896 return $id;
1897 }
1898
1899 /**
1900 * Add a user to the database, return the user object
1901 *
1902 * @param string $name The user's name
1903 * @param array $params Associative array of non-default parameters to save to the database:
1904 * password The user's password. Password logins will be disabled if this is omitted.
1905 * newpassword A temporary password mailed to the user
1906 * email The user's email address
1907 * email_authenticated The email authentication timestamp
1908 * real_name The user's real name
1909 * options An associative array of non-default options
1910 * token Random authentication token. Do not set.
1911 * registration Registration timestamp. Do not set.
1912 *
1913 * @return User object, or null if the username already exists
1914 */
1915 static function createNew( $name, $params = array() ) {
1916 $user = new User;
1917 $user->load();
1918 if ( isset( $params['options'] ) ) {
1919 $user->mOptions = $params['options'] + $user->mOptions;
1920 unset( $params['options'] );
1921 }
1922 $dbw =& wfGetDB( DB_MASTER );
1923 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1924 $fields = array(
1925 'user_id' => $seqVal,
1926 'user_name' => $name,
1927 'user_password' => $user->mPassword,
1928 'user_newpassword' => $user->mNewpassword,
1929 'user_newpass_time' => $dbw->timestamp( $user->mNewpassTime ),
1930 'user_email' => $user->mEmail,
1931 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
1932 'user_real_name' => $user->mRealName,
1933 'user_options' => $user->encodeOptions(),
1934 'user_token' => $user->mToken,
1935 'user_registration' => $dbw->timestamp( $user->mRegistration ),
1936 'user_editcount' => 0,
1937 );
1938 foreach ( $params as $name => $value ) {
1939 $fields["user_$name"] = $value;
1940 }
1941 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
1942 if ( $dbw->affectedRows() ) {
1943 $newUser = User::newFromId( $dbw->insertId() );
1944 } else {
1945 $newUser = null;
1946 }
1947 return $newUser;
1948 }
1949
1950 /**
1951 * Add an existing user object to the database
1952 */
1953 function addToDatabase() {
1954 $this->load();
1955 $dbw =& wfGetDB( DB_MASTER );
1956 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
1957 $dbw->insert( 'user',
1958 array(
1959 'user_id' => $seqVal,
1960 'user_name' => $this->mName,
1961 'user_password' => $this->mPassword,
1962 'user_newpassword' => $this->mNewpassword,
1963 'user_newpass_time' => $dbw->timestamp( $this->mNewpassTime ),
1964 'user_email' => $this->mEmail,
1965 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
1966 'user_real_name' => $this->mRealName,
1967 'user_options' => $this->encodeOptions(),
1968 'user_token' => $this->mToken,
1969 'user_registration' => $dbw->timestamp( $this->mRegistration ),
1970 'user_editcount' => 0,
1971 ), __METHOD__
1972 );
1973 $this->mId = $dbw->insertId();
1974
1975 # Clear instance cache other than user table data, which is already accurate
1976 $this->clearInstanceCache();
1977 }
1978
1979 /**
1980 * If the (non-anonymous) user is blocked, this function will block any IP address
1981 * that they successfully log on from.
1982 */
1983 function spreadBlock() {
1984 wfDebug( __METHOD__."()\n" );
1985 $this->load();
1986 if ( $this->mId == 0 ) {
1987 return;
1988 }
1989
1990 $userblock = Block::newFromDB( '', $this->mId );
1991 if ( !$userblock ) {
1992 return;
1993 }
1994
1995 $userblock->doAutoblock( wfGetIp() );
1996
1997 }
1998
1999 /**
2000 * Generate a string which will be different for any combination of
2001 * user options which would produce different parser output.
2002 * This will be used as part of the hash key for the parser cache,
2003 * so users will the same options can share the same cached data
2004 * safely.
2005 *
2006 * Extensions which require it should install 'PageRenderingHash' hook,
2007 * which will give them a chance to modify this key based on their own
2008 * settings.
2009 *
2010 * @return string
2011 */
2012 function getPageRenderingHash() {
2013 global $wgContLang, $wgUseDynamicDates;
2014 if( $this->mHash ){
2015 return $this->mHash;
2016 }
2017
2018 // stubthreshold is only included below for completeness,
2019 // it will always be 0 when this function is called by parsercache.
2020
2021 $confstr = $this->getOption( 'math' );
2022 $confstr .= '!' . $this->getOption( 'stubthreshold' );
2023 if ( $wgUseDynamicDates ) {
2024 $confstr .= '!' . $this->getDatePreference();
2025 }
2026 $confstr .= '!' . ($this->getOption( 'numberheadings' ) ? '1' : '');
2027 $confstr .= '!' . $this->getOption( 'language' );
2028 $confstr .= '!' . $this->getOption( 'thumbsize' );
2029 // add in language specific options, if any
2030 $extra = $wgContLang->getExtraHashOptions();
2031 $confstr .= $extra;
2032
2033 // Give a chance for extensions to modify the hash, if they have
2034 // extra options or other effects on the parser cache.
2035 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2036
2037 $this->mHash = $confstr;
2038 return $confstr;
2039 }
2040
2041 function isBlockedFromCreateAccount() {
2042 $this->getBlockedStatus();
2043 return $this->mBlock && $this->mBlock->mCreateAccount;
2044 }
2045
2046 function isAllowedToCreateAccount() {
2047 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2048 }
2049
2050 /**
2051 * @deprecated
2052 */
2053 function setLoaded( $loaded ) {}
2054
2055 /**
2056 * Get this user's personal page title.
2057 *
2058 * @return Title
2059 * @public
2060 */
2061 function getUserPage() {
2062 return Title::makeTitle( NS_USER, $this->getName() );
2063 }
2064
2065 /**
2066 * Get this user's talk page title.
2067 *
2068 * @return Title
2069 * @public
2070 */
2071 function getTalkPage() {
2072 $title = $this->getUserPage();
2073 return $title->getTalkPage();
2074 }
2075
2076 /**
2077 * @static
2078 */
2079 function getMaxID() {
2080 static $res; // cache
2081
2082 if ( isset( $res ) )
2083 return $res;
2084 else {
2085 $dbr =& wfGetDB( DB_SLAVE );
2086 return $res = $dbr->selectField( 'user', 'max(user_id)', false, 'User::getMaxID' );
2087 }
2088 }
2089
2090 /**
2091 * Determine whether the user is a newbie. Newbies are either
2092 * anonymous IPs, or the most recently created accounts.
2093 * @return bool True if it is a newbie.
2094 */
2095 function isNewbie() {
2096 return !$this->isAllowed( 'autoconfirmed' );
2097 }
2098
2099 /**
2100 * Check to see if the given clear-text password is one of the accepted passwords
2101 * @param string $password User password.
2102 * @return bool True if the given password is correct otherwise False.
2103 */
2104 function checkPassword( $password ) {
2105 global $wgAuth;
2106 $this->load();
2107
2108 // Even though we stop people from creating passwords that
2109 // are shorter than this, doesn't mean people wont be able
2110 // to. Certain authentication plugins do NOT want to save
2111 // domain passwords in a mysql database, so we should
2112 // check this (incase $wgAuth->strict() is false).
2113 if( !$this->isValidPassword( $password ) ) {
2114 return false;
2115 }
2116
2117 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2118 return true;
2119 } elseif( $wgAuth->strict() ) {
2120 /* Auth plugin doesn't allow local authentication */
2121 return false;
2122 }
2123 $ep = $this->encryptPassword( $password );
2124 if ( 0 == strcmp( $ep, $this->mPassword ) ) {
2125 return true;
2126 } elseif ( function_exists( 'iconv' ) ) {
2127 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2128 # Check for this with iconv
2129 $cp1252hash = $this->encryptPassword( iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password ) );
2130 if ( 0 == strcmp( $cp1252hash, $this->mPassword ) ) {
2131 return true;
2132 }
2133 }
2134 return false;
2135 }
2136
2137 /**
2138 * Check if the given clear-text password matches the temporary password
2139 * sent by e-mail for password reset operations.
2140 * @return bool
2141 */
2142 function checkTemporaryPassword( $plaintext ) {
2143 $hash = $this->encryptPassword( $plaintext );
2144 return $hash === $this->mNewpassword;
2145 }
2146
2147 /**
2148 * Initialize (if necessary) and return a session token value
2149 * which can be used in edit forms to show that the user's
2150 * login credentials aren't being hijacked with a foreign form
2151 * submission.
2152 *
2153 * @param mixed $salt - Optional function-specific data for hash.
2154 * Use a string or an array of strings.
2155 * @return string
2156 * @public
2157 */
2158 function editToken( $salt = '' ) {
2159 if( !isset( $_SESSION['wsEditToken'] ) ) {
2160 $token = $this->generateToken();
2161 $_SESSION['wsEditToken'] = $token;
2162 } else {
2163 $token = $_SESSION['wsEditToken'];
2164 }
2165 if( is_array( $salt ) ) {
2166 $salt = implode( '|', $salt );
2167 }
2168 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2169 }
2170
2171 /**
2172 * Generate a hex-y looking random token for various uses.
2173 * Could be made more cryptographically sure if someone cares.
2174 * @return string
2175 */
2176 function generateToken( $salt = '' ) {
2177 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2178 return md5( $token . $salt );
2179 }
2180
2181 /**
2182 * Check given value against the token value stored in the session.
2183 * A match should confirm that the form was submitted from the
2184 * user's own login session, not a form submission from a third-party
2185 * site.
2186 *
2187 * @param string $val - the input value to compare
2188 * @param string $salt - Optional function-specific data for hash
2189 * @return bool
2190 * @public
2191 */
2192 function matchEditToken( $val, $salt = '' ) {
2193 global $wgMemc;
2194 $sessionToken = $this->editToken( $salt );
2195 if ( $val != $sessionToken ) {
2196 wfDebug( "User::matchEditToken: broken session data\n" );
2197 }
2198 return $val == $sessionToken;
2199 }
2200
2201 /**
2202 * Generate a new e-mail confirmation token and send a confirmation
2203 * mail to the user's given address.
2204 *
2205 * @return mixed True on success, a WikiError object on failure.
2206 */
2207 function sendConfirmationMail() {
2208 global $wgContLang;
2209 $expiration = null; // gets passed-by-ref and defined in next line.
2210 $url = $this->confirmationTokenUrl( $expiration );
2211 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2212 wfMsg( 'confirmemail_body',
2213 wfGetIP(),
2214 $this->getName(),
2215 $url,
2216 $wgContLang->timeanddate( $expiration, false ) ) );
2217 }
2218
2219 /**
2220 * Send an e-mail to this user's account. Does not check for
2221 * confirmed status or validity.
2222 *
2223 * @param string $subject
2224 * @param string $body
2225 * @param strong $from Optional from address; default $wgPasswordSender will be used otherwise.
2226 * @return mixed True on success, a WikiError object on failure.
2227 */
2228 function sendMail( $subject, $body, $from = null ) {
2229 if( is_null( $from ) ) {
2230 global $wgPasswordSender;
2231 $from = $wgPasswordSender;
2232 }
2233
2234 require_once( 'UserMailer.php' );
2235 $to = new MailAddress( $this );
2236 $sender = new MailAddress( $from );
2237 $error = userMailer( $to, $sender, $subject, $body );
2238
2239 if( $error == '' ) {
2240 return true;
2241 } else {
2242 return new WikiError( $error );
2243 }
2244 }
2245
2246 /**
2247 * Generate, store, and return a new e-mail confirmation code.
2248 * A hash (unsalted since it's used as a key) is stored.
2249 * @param &$expiration mixed output: accepts the expiration time
2250 * @return string
2251 * @private
2252 */
2253 function confirmationToken( &$expiration ) {
2254 $now = time();
2255 $expires = $now + 7 * 24 * 60 * 60;
2256 $expiration = wfTimestamp( TS_MW, $expires );
2257
2258 $token = $this->generateToken( $this->mId . $this->mEmail . $expires );
2259 $hash = md5( $token );
2260
2261 $dbw =& wfGetDB( DB_MASTER );
2262 $dbw->update( 'user',
2263 array( 'user_email_token' => $hash,
2264 'user_email_token_expires' => $dbw->timestamp( $expires ) ),
2265 array( 'user_id' => $this->mId ),
2266 __METHOD__ );
2267
2268 return $token;
2269 }
2270
2271 /**
2272 * Generate and store a new e-mail confirmation token, and return
2273 * the URL the user can use to confirm.
2274 * @param &$expiration mixed output: accepts the expiration time
2275 * @return string
2276 * @private
2277 */
2278 function confirmationTokenUrl( &$expiration ) {
2279 $token = $this->confirmationToken( $expiration );
2280 $title = SpecialPage::getTitleFor( 'Confirmemail', $token );
2281 return $title->getFullUrl();
2282 }
2283
2284 /**
2285 * Mark the e-mail address confirmed and save.
2286 */
2287 function confirmEmail() {
2288 $this->load();
2289 $this->mEmailAuthenticated = wfTimestampNow();
2290 $this->saveSettings();
2291 return true;
2292 }
2293
2294 /**
2295 * Is this user allowed to send e-mails within limits of current
2296 * site configuration?
2297 * @return bool
2298 */
2299 function canSendEmail() {
2300 return $this->isEmailConfirmed();
2301 }
2302
2303 /**
2304 * Is this user allowed to receive e-mails within limits of current
2305 * site configuration?
2306 * @return bool
2307 */
2308 function canReceiveEmail() {
2309 return $this->canSendEmail() && !$this->getOption( 'disablemail' );
2310 }
2311
2312 /**
2313 * Is this user's e-mail address valid-looking and confirmed within
2314 * limits of the current site configuration?
2315 *
2316 * If $wgEmailAuthentication is on, this may require the user to have
2317 * confirmed their address by returning a code or using a password
2318 * sent to the address from the wiki.
2319 *
2320 * @return bool
2321 */
2322 function isEmailConfirmed() {
2323 global $wgEmailAuthentication;
2324 $this->load();
2325 $confirmed = true;
2326 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
2327 if( $this->isAnon() )
2328 return false;
2329 if( !self::isValidEmailAddr( $this->mEmail ) )
2330 return false;
2331 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
2332 return false;
2333 return true;
2334 } else {
2335 return $confirmed;
2336 }
2337 }
2338
2339 /**
2340 * Return true if there is an outstanding request for e-mail confirmation.
2341 * @return bool
2342 */
2343 function isEmailConfirmationPending() {
2344 global $wgEmailAuthentication;
2345 return $wgEmailAuthentication &&
2346 !$this->isEmailConfirmed() &&
2347 $this->mEmailToken &&
2348 $this->mEmailTokenExpires > wfTimestamp();
2349 }
2350
2351 /**
2352 * @param array $groups list of groups
2353 * @return array list of permission key names for given groups combined
2354 * @static
2355 */
2356 static function getGroupPermissions( $groups ) {
2357 global $wgGroupPermissions;
2358 $rights = array();
2359 foreach( $groups as $group ) {
2360 if( isset( $wgGroupPermissions[$group] ) ) {
2361 $rights = array_merge( $rights,
2362 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
2363 }
2364 }
2365 return $rights;
2366 }
2367
2368 /**
2369 * @param string $group key name
2370 * @return string localized descriptive name for group, if provided
2371 * @static
2372 */
2373 static function getGroupName( $group ) {
2374 $key = "group-$group";
2375 $name = wfMsg( $key );
2376 if( $name == '' || wfEmptyMsg( $key, $name ) ) {
2377 return $group;
2378 } else {
2379 return $name;
2380 }
2381 }
2382
2383 /**
2384 * @param string $group key name
2385 * @return string localized descriptive name for member of a group, if provided
2386 * @static
2387 */
2388 static function getGroupMember( $group ) {
2389 $key = "group-$group-member";
2390 $name = wfMsg( $key );
2391 if( $name == '' || wfEmptyMsg( $key, $name ) ) {
2392 return $group;
2393 } else {
2394 return $name;
2395 }
2396 }
2397
2398 /**
2399 * Return the set of defined explicit groups.
2400 * The *, 'user', 'autoconfirmed' and 'emailconfirmed'
2401 * groups are not included, as they are defined
2402 * automatically, not in the database.
2403 * @return array
2404 * @static
2405 */
2406 static function getAllGroups() {
2407 global $wgGroupPermissions;
2408 return array_diff(
2409 array_keys( $wgGroupPermissions ),
2410 array( '*', 'user', 'autoconfirmed', 'emailconfirmed' ) );
2411 }
2412
2413 /**
2414 * Get the title of a page describing a particular group
2415 *
2416 * @param $group Name of the group
2417 * @return mixed
2418 */
2419 static function getGroupPage( $group ) {
2420 $page = wfMsgForContent( 'grouppage-' . $group );
2421 if( !wfEmptyMsg( 'grouppage-' . $group, $page ) ) {
2422 $title = Title::newFromText( $page );
2423 if( is_object( $title ) )
2424 return $title;
2425 }
2426 return false;
2427 }
2428
2429 /**
2430 * Create a link to the group in HTML, if available
2431 *
2432 * @param $group Name of the group
2433 * @param $text The text of the link
2434 * @return mixed
2435 */
2436 static function makeGroupLinkHTML( $group, $text = '' ) {
2437 if( $text == '' ) {
2438 $text = self::getGroupName( $group );
2439 }
2440 $title = self::getGroupPage( $group );
2441 if( $title ) {
2442 global $wgUser;
2443 $sk = $wgUser->getSkin();
2444 return $sk->makeLinkObj( $title, $text );
2445 } else {
2446 return $text;
2447 }
2448 }
2449
2450 /**
2451 * Create a link to the group in Wikitext, if available
2452 *
2453 * @param $group Name of the group
2454 * @param $text The text of the link (by default, the name of the group)
2455 * @return mixed
2456 */
2457 static function makeGroupLinkWiki( $group, $text = '' ) {
2458 if( $text == '' ) {
2459 $text = self::getGroupName( $group );
2460 }
2461 $title = self::getGroupPage( $group );
2462 if( $title ) {
2463 $page = $title->getPrefixedText();
2464 return "[[$page|$text]]";
2465 } else {
2466 return $text;
2467 }
2468 }
2469
2470 /**
2471 * Increment the user's edit-count field.
2472 * Will have no effect for anonymous users.
2473 */
2474 function incEditCount() {
2475 if( !$this->isAnon() ) {
2476 $dbw = wfGetDB( DB_MASTER );
2477 $dbw->update( 'user',
2478 array( 'user_editcount=user_editcount+1' ),
2479 array( 'user_id' => $this->getId() ),
2480 __METHOD__ );
2481
2482 // Lazy initialization check...
2483 if( $dbw->affectedRows() == 0 ) {
2484 // Pull from a slave to be less cruel to servers
2485 // Accuracy isn't the point anyway here
2486 $dbr = wfGetDB( DB_SLAVE );
2487 $count = $dbr->selectField( 'revision',
2488 'COUNT(rev_user)',
2489 array( 'rev_user' => $this->getId() ),
2490 __METHOD__ );
2491
2492 // Now here's a goddamn hack...
2493 if( $dbr !== $dbw ) {
2494 // If we actually have a slave server, the count is
2495 // at least one behind because the current transaction
2496 // has not been committed and replicated.
2497 $count++;
2498 } else {
2499 // But if DB_SLAVE is selecting the master, then the
2500 // count we just read includes the revision that was
2501 // just added in the working transaction.
2502 }
2503
2504 $dbw->update( 'user',
2505 array( 'user_editcount' => $count ),
2506 array( 'user_id' => $this->getId() ),
2507 __METHOD__ );
2508 }
2509 }
2510 }
2511 }
2512
2513 ?>