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