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