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