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