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