Followup r81446: and mergehistory too
[lhc/web/wiklou.git] / includes / User.php
1 <?php
2 /**
3 * Implements the User class for the %MediaWiki software.
4 * @file
5 */
6
7 /**
8 * Int Number of characters in user_token field.
9 * @ingroup Constants
10 */
11 define( 'USER_TOKEN_LENGTH', 32 );
12
13 /**
14 * Int Serialized record version.
15 * @ingroup Constants
16 */
17 define( 'MW_USER_VERSION', 8 );
18
19 /**
20 * String Some punctuation to prevent editing from broken text-mangling proxies.
21 * @ingroup Constants
22 */
23 define( 'EDIT_TOKEN_SUFFIX', '+\\' );
24
25 /**
26 * Thrown by User::setPassword() on error.
27 * @ingroup Exception
28 */
29 class PasswordError extends MWException {
30 // NOP
31 }
32
33 /**
34 * The User object encapsulates all of the user-specific settings (user_id,
35 * name, rights, password, email address, options, last login time). Client
36 * classes use the getXXX() functions to access these fields. These functions
37 * do all the work of determining whether the user is logged in,
38 * whether the requested option can be satisfied from cookies or
39 * whether a database query is needed. Most of the settings needed
40 * for rendering normal pages are set in the cookie to minimize use
41 * of the database.
42 */
43 class User {
44 /**
45 * Global constants made accessible as class constants so that autoloader
46 * magic can be used.
47 */
48 const USER_TOKEN_LENGTH = USER_TOKEN_LENGTH;
49 const MW_USER_VERSION = MW_USER_VERSION;
50 const EDIT_TOKEN_SUFFIX = EDIT_TOKEN_SUFFIX;
51
52 /**
53 * Array of Strings List of member variables which are saved to the
54 * shared cache (memcached). Any operation which changes the
55 * corresponding database fields must call a cache-clearing function.
56 * @showinitializer
57 */
58 static $mCacheVars = array(
59 // user table
60 'mId',
61 'mName',
62 'mRealName',
63 'mPassword',
64 'mNewpassword',
65 'mNewpassTime',
66 'mEmail',
67 'mTouched',
68 'mToken',
69 'mEmailAuthenticated',
70 'mEmailToken',
71 'mEmailTokenExpires',
72 'mRegistration',
73 'mEditCount',
74 // user_group table
75 'mGroups',
76 // user_properties table
77 'mOptionOverrides',
78 );
79
80 /**
81 * Array of Strings Core rights.
82 * Each of these should have a corresponding message of the form
83 * "right-$right".
84 * @showinitializer
85 */
86 static $mCoreRights = array(
87 'apihighlimits',
88 'autoconfirmed',
89 'autopatrol',
90 'bigdelete',
91 'block',
92 'blockemail',
93 'bot',
94 'browsearchive',
95 'createaccount',
96 'createpage',
97 'createtalk',
98 'delete',
99 'deletedhistory',
100 'deletedtext',
101 'deleterevision',
102 'disableaccount',
103 'edit',
104 'editinterface',
105 'editusercssjs', #deprecated
106 'editusercss',
107 'edituserjs',
108 'hideuser',
109 'import',
110 'importupload',
111 'ipblock-exempt',
112 'markbotedits',
113 'mergehistory',
114 'minoredit',
115 'move',
116 'movefile',
117 'move-rootuserpages',
118 'move-subpages',
119 'nominornewtalk',
120 'noratelimit',
121 'override-export-depth',
122 'patrol',
123 'protect',
124 'proxyunbannable',
125 'purge',
126 'read',
127 'reupload',
128 'reupload-shared',
129 'rollback',
130 'selenium',
131 'sendemail',
132 'siteadmin',
133 'suppressionlog',
134 'suppressredirect',
135 'suppressrevision',
136 'trackback',
137 'undelete',
138 'unwatchedpages',
139 'upload',
140 'upload_by_url',
141 'userrights',
142 'userrights-interwiki',
143 'writeapi',
144 );
145 /**
146 * String Cached results of getAllRights()
147 */
148 static $mAllRights = false;
149
150 /** @name Cache variables */
151 //@{
152 var $mId, $mName, $mRealName, $mPassword, $mNewpassword, $mNewpassTime,
153 $mEmail, $mTouched, $mToken, $mEmailAuthenticated,
154 $mEmailToken, $mEmailTokenExpires, $mRegistration, $mGroups, $mOptionOverrides;
155 //@}
156
157 /**
158 * Bool Whether the cache variables have been loaded.
159 */
160 var $mDataLoaded, $mAuthLoaded, $mOptionsLoaded;
161
162 /**
163 * String Initialization data source if mDataLoaded==false. May be one of:
164 * - 'defaults' anonymous user initialised from class defaults
165 * - 'name' initialise from mName
166 * - 'id' initialise from mId
167 * - 'session' log in from cookies or session if possible
168 *
169 * Use the User::newFrom*() family of functions to set this.
170 */
171 var $mFrom;
172
173 /**
174 * Lazy-initialized variables, invalidated with clearInstanceCache
175 */
176 var $mNewtalk, $mDatePreference, $mBlockedby, $mHash, $mSkin, $mRights,
177 $mBlockreason, $mBlock, $mEffectiveGroups, $mBlockedGlobally,
178 $mLocked, $mHideName, $mOptions;
179
180 static $idCacheByName = array();
181
182 /**
183 * Lightweight constructor for an anonymous user.
184 * Use the User::newFrom* factory functions for other kinds of users.
185 *
186 * @see newFromName()
187 * @see newFromId()
188 * @see newFromConfirmationCode()
189 * @see newFromSession()
190 * @see newFromRow()
191 */
192 function __construct() {
193 $this->clearInstanceCache( 'defaults' );
194 }
195
196 /**
197 * Load the user table data for this object from the source given by mFrom.
198 */
199 function load() {
200 if ( $this->mDataLoaded ) {
201 return;
202 }
203 wfProfileIn( __METHOD__ );
204
205 # Set it now to avoid infinite recursion in accessors
206 $this->mDataLoaded = true;
207
208 switch ( $this->mFrom ) {
209 case 'defaults':
210 $this->loadDefaults();
211 break;
212 case 'name':
213 $this->mId = self::idFromName( $this->mName );
214 if ( !$this->mId ) {
215 # Nonexistent user placeholder object
216 $this->loadDefaults( $this->mName );
217 } else {
218 $this->loadFromId();
219 }
220 break;
221 case 'id':
222 $this->loadFromId();
223 break;
224 case 'session':
225 $this->loadFromSession();
226 wfRunHooks( 'UserLoadAfterLoadFromSession', array( $this ) );
227 break;
228 default:
229 throw new MWException( "Unrecognised value for User->mFrom: \"{$this->mFrom}\"" );
230 }
231 wfProfileOut( __METHOD__ );
232 }
233
234 /**
235 * Load user table data, given mId has already been set.
236 * @return Bool false if the ID does not exist, true otherwise
237 * @private
238 */
239 function loadFromId() {
240 global $wgMemc;
241 if ( $this->mId == 0 ) {
242 $this->loadDefaults();
243 return false;
244 }
245
246 # Try cache
247 $key = wfMemcKey( 'user', 'id', $this->mId );
248 $data = $wgMemc->get( $key );
249 if ( !is_array( $data ) || $data['mVersion'] < MW_USER_VERSION ) {
250 # Object is expired, load from DB
251 $data = false;
252 }
253
254 if ( !$data ) {
255 wfDebug( "User: cache miss for user {$this->mId}\n" );
256 # Load from DB
257 if ( !$this->loadFromDatabase() ) {
258 # Can't load from ID, user is anonymous
259 return false;
260 }
261 $this->saveToCache();
262 } else {
263 wfDebug( "User: got user {$this->mId} from cache\n" );
264 # Restore from cache
265 foreach ( self::$mCacheVars as $name ) {
266 $this->$name = $data[$name];
267 }
268 }
269 return true;
270 }
271
272 /**
273 * Save user data to the shared cache
274 */
275 function saveToCache() {
276 $this->load();
277 $this->loadGroups();
278 $this->loadOptions();
279 if ( $this->isAnon() ) {
280 // Anonymous users are uncached
281 return;
282 }
283 $data = array();
284 foreach ( self::$mCacheVars as $name ) {
285 $data[$name] = $this->$name;
286 }
287 $data['mVersion'] = MW_USER_VERSION;
288 $key = wfMemcKey( 'user', 'id', $this->mId );
289 global $wgMemc;
290 $wgMemc->set( $key, $data );
291 }
292
293
294 /** @name newFrom*() static factory methods */
295 //@{
296
297 /**
298 * Static factory method for creation from username.
299 *
300 * This is slightly less efficient than newFromId(), so use newFromId() if
301 * you have both an ID and a name handy.
302 *
303 * @param $name String Username, validated by Title::newFromText()
304 * @param $validate String|Bool Validate username. Takes the same parameters as
305 * User::getCanonicalName(), except that true is accepted as an alias
306 * for 'valid', for BC.
307 *
308 * @return User object, or false if the username is invalid
309 * (e.g. if it contains illegal characters or is an IP address). If the
310 * username is not present in the database, the result will be a user object
311 * with a name, zero user ID and default settings.
312 */
313 static function newFromName( $name, $validate = 'valid' ) {
314 if ( $validate === true ) {
315 $validate = 'valid';
316 }
317 $name = self::getCanonicalName( $name, $validate );
318 if ( $name === false ) {
319 return false;
320 } else {
321 # Create unloaded user object
322 $u = new User;
323 $u->mName = $name;
324 $u->mFrom = 'name';
325 return $u;
326 }
327 }
328
329 /**
330 * Static factory method for creation from a given user ID.
331 *
332 * @param $id Int Valid user ID
333 * @return User The corresponding User object
334 */
335 static function newFromId( $id ) {
336 $u = new User;
337 $u->mId = $id;
338 $u->mFrom = 'id';
339 return $u;
340 }
341
342 /**
343 * Factory method to fetch whichever user has a given email confirmation code.
344 * This code is generated when an account is created or its e-mail address
345 * has changed.
346 *
347 * If the code is invalid or has expired, returns NULL.
348 *
349 * @param $code String Confirmation code
350 * @return User
351 */
352 static function newFromConfirmationCode( $code ) {
353 $dbr = wfGetDB( DB_SLAVE );
354 $id = $dbr->selectField( 'user', 'user_id', array(
355 'user_email_token' => md5( $code ),
356 'user_email_token_expires > ' . $dbr->addQuotes( $dbr->timestamp() ),
357 ) );
358 if( $id !== false ) {
359 return User::newFromId( $id );
360 } else {
361 return null;
362 }
363 }
364
365 /**
366 * Create a new user object using data from session or cookies. If the
367 * login credentials are invalid, the result is an anonymous user.
368 *
369 * @return User
370 */
371 static function newFromSession() {
372 $user = new User;
373 $user->mFrom = 'session';
374 return $user;
375 }
376
377 /**
378 * Create a new user object from a user row.
379 * The row should have all fields from the user table in it.
380 * @param $row Array A row from the user table
381 * @return User
382 */
383 static function newFromRow( $row ) {
384 $user = new User;
385 $user->loadFromRow( $row );
386 return $user;
387 }
388
389 //@}
390
391
392 /**
393 * Get the username corresponding to a given user ID
394 * @param $id Int User ID
395 * @return String The corresponding username
396 */
397 static function whoIs( $id ) {
398 $dbr = wfGetDB( DB_SLAVE );
399 return $dbr->selectField( 'user', 'user_name', array( 'user_id' => $id ), __METHOD__ );
400 }
401
402 /**
403 * Get the real name of a user given their user ID
404 *
405 * @param $id Int User ID
406 * @return String The corresponding user's real name
407 */
408 static function whoIsReal( $id ) {
409 $dbr = wfGetDB( DB_SLAVE );
410 return $dbr->selectField( 'user', 'user_real_name', array( 'user_id' => $id ), __METHOD__ );
411 }
412
413 /**
414 * Get database id given a user name
415 * @param $name String Username
416 * @return Int|Null The corresponding user's ID, or null if user is nonexistent
417 */
418 static function idFromName( $name ) {
419 $nt = Title::makeTitleSafe( NS_USER, $name );
420 if( is_null( $nt ) ) {
421 # Illegal name
422 return null;
423 }
424
425 if ( isset( self::$idCacheByName[$name] ) ) {
426 return self::$idCacheByName[$name];
427 }
428
429 $dbr = wfGetDB( DB_SLAVE );
430 $s = $dbr->selectRow( 'user', array( 'user_id' ), array( 'user_name' => $nt->getText() ), __METHOD__ );
431
432 if ( $s === false ) {
433 $result = null;
434 } else {
435 $result = $s->user_id;
436 }
437
438 self::$idCacheByName[$name] = $result;
439
440 if ( count( self::$idCacheByName ) > 1000 ) {
441 self::$idCacheByName = array();
442 }
443
444 return $result;
445 }
446
447 /**
448 * Reset the cache used in idFromName(). For use in tests.
449 */
450 public static function resetIdByNameCache() {
451 self::$idCacheByName = array();
452 }
453
454 /**
455 * Does the string match an anonymous IPv4 address?
456 *
457 * This function exists for username validation, in order to reject
458 * usernames which are similar in form to IP addresses. Strings such
459 * as 300.300.300.300 will return true because it looks like an IP
460 * address, despite not being strictly valid.
461 *
462 * We match \d{1,3}\.\d{1,3}\.\d{1,3}\.xxx as an anonymous IP
463 * address because the usemod software would "cloak" anonymous IP
464 * addresses like this, if we allowed accounts like this to be created
465 * new users could get the old edits of these anonymous users.
466 *
467 * @param $name String to match
468 * @return Bool
469 */
470 static function isIP( $name ) {
471 return preg_match('/^\d{1,3}\.\d{1,3}\.\d{1,3}\.(?:xxx|\d{1,3})$/',$name) || IP::isIPv6($name);
472 }
473
474 /**
475 * Is the input a valid username?
476 *
477 * Checks if the input is a valid username, we don't want an empty string,
478 * an IP address, anything that containins slashes (would mess up subpages),
479 * is longer than the maximum allowed username size or doesn't begin with
480 * a capital letter.
481 *
482 * @param $name String to match
483 * @return Bool
484 */
485 static function isValidUserName( $name ) {
486 global $wgContLang, $wgMaxNameChars;
487
488 if ( $name == ''
489 || User::isIP( $name )
490 || strpos( $name, '/' ) !== false
491 || strlen( $name ) > $wgMaxNameChars
492 || $name != $wgContLang->ucfirst( $name ) ) {
493 wfDebugLog( 'username', __METHOD__ .
494 ": '$name' invalid due to empty, IP, slash, length, or lowercase" );
495 return false;
496 }
497
498 // Ensure that the name can't be misresolved as a different title,
499 // such as with extra namespace keys at the start.
500 $parsed = Title::newFromText( $name );
501 if( is_null( $parsed )
502 || $parsed->getNamespace()
503 || strcmp( $name, $parsed->getPrefixedText() ) ) {
504 wfDebugLog( 'username', __METHOD__ .
505 ": '$name' invalid due to ambiguous prefixes" );
506 return false;
507 }
508
509 // Check an additional blacklist of troublemaker characters.
510 // Should these be merged into the title char list?
511 $unicodeBlacklist = '/[' .
512 '\x{0080}-\x{009f}' . # iso-8859-1 control chars
513 '\x{00a0}' . # non-breaking space
514 '\x{2000}-\x{200f}' . # various whitespace
515 '\x{2028}-\x{202f}' . # breaks and control chars
516 '\x{3000}' . # ideographic space
517 '\x{e000}-\x{f8ff}' . # private use
518 ']/u';
519 if( preg_match( $unicodeBlacklist, $name ) ) {
520 wfDebugLog( 'username', __METHOD__ .
521 ": '$name' invalid due to blacklisted characters" );
522 return false;
523 }
524
525 return true;
526 }
527
528 /**
529 * Usernames which fail to pass this function will be blocked
530 * from user login and new account registrations, but may be used
531 * internally by batch processes.
532 *
533 * If an account already exists in this form, login will be blocked
534 * by a failure to pass this function.
535 *
536 * @param $name String to match
537 * @return Bool
538 */
539 static function isUsableName( $name ) {
540 global $wgReservedUsernames;
541 // Must be a valid username, obviously ;)
542 if ( !self::isValidUserName( $name ) ) {
543 return false;
544 }
545
546 static $reservedUsernames = false;
547 if ( !$reservedUsernames ) {
548 $reservedUsernames = $wgReservedUsernames;
549 wfRunHooks( 'UserGetReservedNames', array( &$reservedUsernames ) );
550 }
551
552 // Certain names may be reserved for batch processes.
553 foreach ( $reservedUsernames as $reserved ) {
554 if ( substr( $reserved, 0, 4 ) == 'msg:' ) {
555 $reserved = wfMsgForContent( substr( $reserved, 4 ) );
556 }
557 if ( $reserved == $name ) {
558 return false;
559 }
560 }
561 return true;
562 }
563
564 /**
565 * Usernames which fail to pass this function will be blocked
566 * from new account registrations, but may be used internally
567 * either by batch processes or by user accounts which have
568 * already been created.
569 *
570 * Additional blacklisting may be added here rather than in
571 * isValidUserName() to avoid disrupting existing accounts.
572 *
573 * @param $name String to match
574 * @return Bool
575 */
576 static function isCreatableName( $name ) {
577 global $wgInvalidUsernameCharacters;
578
579 // Ensure that the username isn't longer than 235 bytes, so that
580 // (at least for the builtin skins) user javascript and css files
581 // will work. (bug 23080)
582 if( strlen( $name ) > 235 ) {
583 wfDebugLog( 'username', __METHOD__ .
584 ": '$name' invalid due to length" );
585 return false;
586 }
587
588 if( preg_match( '/[' . preg_quote( $wgInvalidUsernameCharacters, '/' ) . ']/', $name ) ) {
589 wfDebugLog( 'username', __METHOD__ .
590 ": '$name' invalid due to wgInvalidUsernameCharacters" );
591 return false;
592 }
593
594 return self::isUsableName( $name );
595 }
596
597 /**
598 * Is the input a valid password for this user?
599 *
600 * @param $password String Desired password
601 * @return Bool
602 */
603 function isValidPassword( $password ) {
604 //simple boolean wrapper for getPasswordValidity
605 return $this->getPasswordValidity( $password ) === true;
606 }
607
608 /**
609 * Given unvalidated password input, return error message on failure.
610 *
611 * @param $password String Desired password
612 * @return mixed: true on success, string or array of error message on failure
613 */
614 function getPasswordValidity( $password ) {
615 global $wgMinimalPasswordLength, $wgContLang;
616
617 static $blockedLogins = array(
618 'Useruser' => 'Passpass', 'Useruser1' => 'Passpass1', # r75589
619 'Apitestsysop' => 'testpass', 'Apitestuser' => 'testpass' # r75605
620 );
621
622 $result = false; //init $result to false for the internal checks
623
624 if( !wfRunHooks( 'isValidPassword', array( $password, &$result, $this ) ) )
625 return $result;
626
627 if ( $result === false ) {
628 if( strlen( $password ) < $wgMinimalPasswordLength ) {
629 return 'passwordtooshort';
630 } elseif ( $wgContLang->lc( $password ) == $wgContLang->lc( $this->mName ) ) {
631 return 'password-name-match';
632 } elseif ( isset( $blockedLogins[ $this->getName() ] ) && $password == $blockedLogins[ $this->getName() ] ) {
633 return 'password-login-forbidden';
634 } else {
635 //it seems weird returning true here, but this is because of the
636 //initialization of $result to false above. If the hook is never run or it
637 //doesn't modify $result, then we will likely get down into this if with
638 //a valid password.
639 return true;
640 }
641 } elseif( $result === true ) {
642 return true;
643 } else {
644 return $result; //the isValidPassword hook set a string $result and returned true
645 }
646 }
647
648 /**
649 * Does a string look like an e-mail address?
650 *
651 * This validates an email address using an HTML5 specification found at:
652 * http://www.whatwg.org/specs/web-apps/current-work/multipage/states-of-the-type-attribute.html#valid-e-mail-address
653 * Which as of 2011-01-24 says:
654 *
655 * A valid e-mail address is a string that matches the ABNF production
656 * 1*( atext / "." ) "@" ldh-str *( "." ldh-str ) where atext is defined
657 * in RFC 5322 section 3.2.3, and ldh-str is defined in RFC 1034 section
658 * 3.5.
659 *
660 * This function is an implementation of the specification as requested in
661 * bug 22449.
662 *
663 * Client-side forms will use the same standard validation rules via JS or
664 * HTML 5 validation; additional restrictions can be enforced server-side
665 * by extensions via the 'isValidEmailAddr' hook.
666 *
667 * Note that this validation doesn't 100% match RFC 2822, but is believed
668 * to be liberal enough for wide use. Some invalid addresses will still
669 * pass validation here.
670 *
671 * @param $addr String E-mail address
672 * @return Bool
673 */
674 public static function isValidEmailAddr( $addr ) {
675 $result = null;
676 if( !wfRunHooks( 'isValidEmailAddr', array( $addr, &$result ) ) ) {
677 return $result;
678 }
679
680 // Please note strings below are enclosed in brackets [], this make the
681 // hyphen "-" a range indicator. Hence it is double backslashed below.
682 // See bug 26948
683 $rfc5322_atext = "a-z0-9!#$%&'*+\\-\/=?^_`{|}~" ;
684 $rfc1034_ldh_str = "a-z0-9\\-" ;
685
686 $HTML5_email_regexp = "/
687 ^ # start of string
688 [$rfc5322_atext\\.]+ # user part which is liberal :p
689 @ # 'apostrophe'
690 [$rfc1034_ldh_str]+ # First domain part
691 (\\.[$rfc1034_ldh_str]+)* # Following part prefixed with a dot
692 $ # End of string
693 /ix" ; // case Insensitive, eXtended
694
695 return (bool) preg_match( $HTML5_email_regexp, $addr );
696 }
697
698 /**
699 * Given unvalidated user input, return a canonical username, or false if
700 * the username is invalid.
701 * @param $name String User input
702 * @param $validate String|Bool type of validation to use:
703 * - false No validation
704 * - 'valid' Valid for batch processes
705 * - 'usable' Valid for batch processes and login
706 * - 'creatable' Valid for batch processes, login and account creation
707 */
708 static function getCanonicalName( $name, $validate = 'valid' ) {
709 # Force usernames to capital
710 global $wgContLang;
711 $name = $wgContLang->ucfirst( $name );
712
713 # Reject names containing '#'; these will be cleaned up
714 # with title normalisation, but then it's too late to
715 # check elsewhere
716 if( strpos( $name, '#' ) !== false )
717 return false;
718
719 # Clean up name according to title rules
720 $t = ( $validate === 'valid' ) ?
721 Title::newFromText( $name ) : Title::makeTitle( NS_USER, $name );
722 # Check for invalid titles
723 if( is_null( $t ) ) {
724 return false;
725 }
726
727 # Reject various classes of invalid names
728 global $wgAuth;
729 $name = $wgAuth->getCanonicalName( $t->getText() );
730
731 switch ( $validate ) {
732 case false:
733 break;
734 case 'valid':
735 if ( !User::isValidUserName( $name ) ) {
736 $name = false;
737 }
738 break;
739 case 'usable':
740 if ( !User::isUsableName( $name ) ) {
741 $name = false;
742 }
743 break;
744 case 'creatable':
745 if ( !User::isCreatableName( $name ) ) {
746 $name = false;
747 }
748 break;
749 default:
750 throw new MWException( 'Invalid parameter value for $validate in ' . __METHOD__ );
751 }
752 return $name;
753 }
754
755 /**
756 * Count the number of edits of a user
757 * @todo It should not be static and some day should be merged as proper member function / deprecated -- domas
758 *
759 * @param $uid Int User ID to check
760 * @return Int the user's edit count
761 */
762 static function edits( $uid ) {
763 wfProfileIn( __METHOD__ );
764 $dbr = wfGetDB( DB_SLAVE );
765 // check if the user_editcount field has been initialized
766 $field = $dbr->selectField(
767 'user', 'user_editcount',
768 array( 'user_id' => $uid ),
769 __METHOD__
770 );
771
772 if( $field === null ) { // it has not been initialized. do so.
773 $dbw = wfGetDB( DB_MASTER );
774 $count = $dbr->selectField(
775 'revision', 'count(*)',
776 array( 'rev_user' => $uid ),
777 __METHOD__
778 );
779 $dbw->update(
780 'user',
781 array( 'user_editcount' => $count ),
782 array( 'user_id' => $uid ),
783 __METHOD__
784 );
785 } else {
786 $count = $field;
787 }
788 wfProfileOut( __METHOD__ );
789 return $count;
790 }
791
792 /**
793 * Return a random password. Sourced from mt_rand, so it's not particularly secure.
794 * @todo hash random numbers to improve security, like generateToken()
795 *
796 * @return String new random password
797 */
798 static function randomPassword() {
799 global $wgMinimalPasswordLength;
800 $pwchars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz';
801 $l = strlen( $pwchars ) - 1;
802
803 $pwlength = max( 7, $wgMinimalPasswordLength );
804 $digit = mt_rand( 0, $pwlength - 1 );
805 $np = '';
806 for ( $i = 0; $i < $pwlength; $i++ ) {
807 $np .= $i == $digit ? chr( mt_rand( 48, 57 ) ) : $pwchars{ mt_rand( 0, $l ) };
808 }
809 return $np;
810 }
811
812 /**
813 * Set cached properties to default.
814 *
815 * @note This no longer clears uncached lazy-initialised properties;
816 * the constructor does that instead.
817 * @private
818 */
819 function loadDefaults( $name = false ) {
820 wfProfileIn( __METHOD__ );
821
822 global $wgRequest;
823
824 $this->mId = 0;
825 $this->mName = $name;
826 $this->mRealName = '';
827 $this->mPassword = $this->mNewpassword = '';
828 $this->mNewpassTime = null;
829 $this->mEmail = '';
830 $this->mOptionOverrides = null;
831 $this->mOptionsLoaded = false;
832
833 if( $wgRequest->getCookie( 'LoggedOut' ) !== null ) {
834 $this->mTouched = wfTimestamp( TS_MW, $wgRequest->getCookie( 'LoggedOut' ) );
835 } else {
836 $this->mTouched = '0'; # Allow any pages to be cached
837 }
838
839 $this->setToken(); # Random
840 $this->mEmailAuthenticated = null;
841 $this->mEmailToken = '';
842 $this->mEmailTokenExpires = null;
843 $this->mRegistration = wfTimestamp( TS_MW );
844 $this->mGroups = array();
845
846 wfRunHooks( 'UserLoadDefaults', array( $this, $name ) );
847
848 wfProfileOut( __METHOD__ );
849 }
850
851 /**
852 * Load user data from the session or login cookie. If there are no valid
853 * credentials, initialises the user as an anonymous user.
854 * @return Bool True if the user is logged in, false otherwise.
855 */
856 private function loadFromSession() {
857 global $wgRequest, $wgExternalAuthType, $wgAutocreatePolicy;
858
859 $result = null;
860 wfRunHooks( 'UserLoadFromSession', array( $this, &$result ) );
861 if ( $result !== null ) {
862 return $result;
863 }
864
865 if ( $wgExternalAuthType && $wgAutocreatePolicy == 'view' ) {
866 $extUser = ExternalUser::newFromCookie();
867 if ( $extUser ) {
868 # TODO: Automatically create the user here (or probably a bit
869 # lower down, in fact)
870 }
871 }
872
873 if ( $wgRequest->getCookie( 'UserID' ) !== null ) {
874 $sId = intval( $wgRequest->getCookie( 'UserID' ) );
875 if( isset( $_SESSION['wsUserID'] ) && $sId != $_SESSION['wsUserID'] ) {
876 $this->loadDefaults(); // Possible collision!
877 wfDebugLog( 'loginSessions', "Session user ID ({$_SESSION['wsUserID']}) and
878 cookie user ID ($sId) don't match!" );
879 return false;
880 }
881 $_SESSION['wsUserID'] = $sId;
882 } else if ( isset( $_SESSION['wsUserID'] ) ) {
883 if ( $_SESSION['wsUserID'] != 0 ) {
884 $sId = $_SESSION['wsUserID'];
885 } else {
886 $this->loadDefaults();
887 return false;
888 }
889 } else {
890 $this->loadDefaults();
891 return false;
892 }
893
894 if ( isset( $_SESSION['wsUserName'] ) ) {
895 $sName = $_SESSION['wsUserName'];
896 } else if ( $wgRequest->getCookie('UserName') !== null ) {
897 $sName = $wgRequest->getCookie('UserName');
898 $_SESSION['wsUserName'] = $sName;
899 } else {
900 $this->loadDefaults();
901 return false;
902 }
903
904 $this->mId = $sId;
905 if ( !$this->loadFromId() ) {
906 # Not a valid ID, loadFromId has switched the object to anon for us
907 return false;
908 }
909
910 global $wgBlockDisablesLogin;
911 if( $wgBlockDisablesLogin && $this->isBlocked() ) {
912 # User blocked and we've disabled blocked user logins
913 $this->loadDefaults();
914 return false;
915 }
916
917 if ( isset( $_SESSION['wsToken'] ) ) {
918 $passwordCorrect = $_SESSION['wsToken'] == $this->mToken;
919 $from = 'session';
920 } else if ( $wgRequest->getCookie( 'Token' ) !== null ) {
921 $passwordCorrect = $this->mToken == $wgRequest->getCookie( 'Token' );
922 $from = 'cookie';
923 } else {
924 # No session or persistent login cookie
925 $this->loadDefaults();
926 return false;
927 }
928
929 if ( ( $sName == $this->mName ) && $passwordCorrect ) {
930 $_SESSION['wsToken'] = $this->mToken;
931 wfDebug( "User: logged in from $from\n" );
932 return true;
933 } else {
934 # Invalid credentials
935 wfDebug( "User: can't log in from $from, invalid credentials\n" );
936 $this->loadDefaults();
937 return false;
938 }
939 }
940
941 /**
942 * Load user and user_group data from the database.
943 * $this::mId must be set, this is how the user is identified.
944 *
945 * @return Bool True if the user exists, false if the user is anonymous
946 * @private
947 */
948 function loadFromDatabase() {
949 # Paranoia
950 $this->mId = intval( $this->mId );
951
952 /** Anonymous user */
953 if( !$this->mId ) {
954 $this->loadDefaults();
955 return false;
956 }
957
958 $dbr = wfGetDB( DB_MASTER );
959 $s = $dbr->selectRow( 'user', '*', array( 'user_id' => $this->mId ), __METHOD__ );
960
961 wfRunHooks( 'UserLoadFromDatabase', array( $this, &$s ) );
962
963 if ( $s !== false ) {
964 # Initialise user table data
965 $this->loadFromRow( $s );
966 $this->mGroups = null; // deferred
967 $this->getEditCount(); // revalidation for nulls
968 return true;
969 } else {
970 # Invalid user_id
971 $this->mId = 0;
972 $this->loadDefaults();
973 return false;
974 }
975 }
976
977 /**
978 * Initialize this object from a row from the user table.
979 *
980 * @param $row Array Row from the user table to load.
981 */
982 function loadFromRow( $row ) {
983 $this->mDataLoaded = true;
984
985 if ( isset( $row->user_id ) ) {
986 $this->mId = intval( $row->user_id );
987 }
988 $this->mName = $row->user_name;
989 $this->mRealName = $row->user_real_name;
990 $this->mPassword = $row->user_password;
991 $this->mNewpassword = $row->user_newpassword;
992 $this->mNewpassTime = wfTimestampOrNull( TS_MW, $row->user_newpass_time );
993 $this->mEmail = $row->user_email;
994 $this->decodeOptions( $row->user_options );
995 $this->mTouched = wfTimestamp(TS_MW,$row->user_touched);
996 $this->mToken = $row->user_token;
997 $this->mEmailAuthenticated = wfTimestampOrNull( TS_MW, $row->user_email_authenticated );
998 $this->mEmailToken = $row->user_email_token;
999 $this->mEmailTokenExpires = wfTimestampOrNull( TS_MW, $row->user_email_token_expires );
1000 $this->mRegistration = wfTimestampOrNull( TS_MW, $row->user_registration );
1001 $this->mEditCount = $row->user_editcount;
1002 }
1003
1004 /**
1005 * Load the groups from the database if they aren't already loaded.
1006 * @private
1007 */
1008 function loadGroups() {
1009 if ( is_null( $this->mGroups ) ) {
1010 $dbr = wfGetDB( DB_MASTER );
1011 $res = $dbr->select( 'user_groups',
1012 array( 'ug_group' ),
1013 array( 'ug_user' => $this->mId ),
1014 __METHOD__ );
1015 $this->mGroups = array();
1016 foreach ( $res as $row ) {
1017 $this->mGroups[] = $row->ug_group;
1018 }
1019 }
1020 }
1021
1022 /**
1023 * Clear various cached data stored in this object.
1024 * @param $reloadFrom String Reload user and user_groups table data from a
1025 * given source. May be "name", "id", "defaults", "session", or false for
1026 * no reload.
1027 */
1028 function clearInstanceCache( $reloadFrom = false ) {
1029 $this->mNewtalk = -1;
1030 $this->mDatePreference = null;
1031 $this->mBlockedby = -1; # Unset
1032 $this->mHash = false;
1033 $this->mSkin = null;
1034 $this->mRights = null;
1035 $this->mEffectiveGroups = null;
1036 $this->mOptions = null;
1037
1038 if ( $reloadFrom ) {
1039 $this->mDataLoaded = false;
1040 $this->mFrom = $reloadFrom;
1041 }
1042 }
1043
1044 /**
1045 * Combine the language default options with any site-specific options
1046 * and add the default language variants.
1047 *
1048 * @return Array of String options
1049 */
1050 static function getDefaultOptions() {
1051 global $wgNamespacesToBeSearchedDefault;
1052 /**
1053 * Site defaults will override the global/language defaults
1054 */
1055 global $wgDefaultUserOptions, $wgContLang, $wgDefaultSkin;
1056 $defOpt = $wgDefaultUserOptions + $wgContLang->getDefaultUserOptionOverrides();
1057
1058 /**
1059 * default language setting
1060 */
1061 $variant = $wgContLang->getDefaultVariant();
1062 $defOpt['variant'] = $variant;
1063 $defOpt['language'] = $variant;
1064 foreach( SearchEngine::searchableNamespaces() as $nsnum => $nsname ) {
1065 $defOpt['searchNs'.$nsnum] = !empty( $wgNamespacesToBeSearchedDefault[$nsnum] );
1066 }
1067 $defOpt['skin'] = $wgDefaultSkin;
1068
1069 return $defOpt;
1070 }
1071
1072 /**
1073 * Get a given default option value.
1074 *
1075 * @param $opt String Name of option to retrieve
1076 * @return String Default option value
1077 */
1078 public static function getDefaultOption( $opt ) {
1079 $defOpts = self::getDefaultOptions();
1080 if( isset( $defOpts[$opt] ) ) {
1081 return $defOpts[$opt];
1082 } else {
1083 return null;
1084 }
1085 }
1086
1087
1088 /**
1089 * Get blocking information
1090 * @private
1091 * @param $bFromSlave Bool Whether to check the slave database first. To
1092 * improve performance, non-critical checks are done
1093 * against slaves. Check when actually saving should be
1094 * done against master.
1095 */
1096 function getBlockedStatus( $bFromSlave = true ) {
1097 global $wgProxyWhitelist, $wgUser;
1098
1099 if ( -1 != $this->mBlockedby ) {
1100 return;
1101 }
1102
1103 wfProfileIn( __METHOD__ );
1104 wfDebug( __METHOD__.": checking...\n" );
1105
1106 // Initialize data...
1107 // Otherwise something ends up stomping on $this->mBlockedby when
1108 // things get lazy-loaded later, causing false positive block hits
1109 // due to -1 !== 0. Probably session-related... Nothing should be
1110 // overwriting mBlockedby, surely?
1111 $this->load();
1112
1113 $this->mBlockedby = 0;
1114 $this->mHideName = 0;
1115 $this->mAllowUsertalk = 0;
1116
1117 # Check if we are looking at an IP or a logged-in user
1118 if ( $this->isIP( $this->getName() ) ) {
1119 $ip = $this->getName();
1120 } else {
1121 # Check if we are looking at the current user
1122 # If we don't, and the user is logged in, we don't know about
1123 # his IP / autoblock status, so ignore autoblock of current user's IP
1124 if ( $this->getID() != $wgUser->getID() ) {
1125 $ip = '';
1126 } else {
1127 # Get IP of current user
1128 $ip = wfGetIP();
1129 }
1130 }
1131
1132 if ( $this->isAllowed( 'ipblock-exempt' ) ) {
1133 # Exempt from all types of IP-block
1134 $ip = '';
1135 }
1136
1137 # User/IP blocking
1138 $this->mBlock = new Block();
1139 $this->mBlock->fromMaster( !$bFromSlave );
1140 if ( $this->mBlock->load( $ip , $this->mId ) ) {
1141 wfDebug( __METHOD__ . ": Found block.\n" );
1142 $this->mBlockedby = $this->mBlock->mBy;
1143 if( $this->mBlockedby == 0 )
1144 $this->mBlockedby = $this->mBlock->mByName;
1145 $this->mBlockreason = $this->mBlock->mReason;
1146 $this->mHideName = $this->mBlock->mHideName;
1147 $this->mAllowUsertalk = $this->mBlock->mAllowUsertalk;
1148 if ( $this->isLoggedIn() && $wgUser->getID() == $this->getID() ) {
1149 $this->spreadBlock();
1150 }
1151 } else {
1152 // Bug 13611: don't remove mBlock here, to allow account creation blocks to
1153 // apply to users. Note that the existence of $this->mBlock is not used to
1154 // check for edit blocks, $this->mBlockedby is instead.
1155 }
1156
1157 # Proxy blocking
1158 if ( !$this->isAllowed( 'proxyunbannable' ) && !in_array( $ip, $wgProxyWhitelist ) ) {
1159 # Local list
1160 if ( wfIsLocallyBlockedProxy( $ip ) ) {
1161 $this->mBlockedby = wfMsg( 'proxyblocker' );
1162 $this->mBlockreason = wfMsg( 'proxyblockreason' );
1163 }
1164
1165 # DNSBL
1166 if ( !$this->mBlockedby && !$this->getID() ) {
1167 if ( $this->isDnsBlacklisted( $ip ) ) {
1168 $this->mBlockedby = wfMsg( 'sorbs' );
1169 $this->mBlockreason = wfMsg( 'sorbsreason' );
1170 }
1171 }
1172 }
1173
1174 # Extensions
1175 wfRunHooks( 'GetBlockedStatus', array( &$this ) );
1176
1177 wfProfileOut( __METHOD__ );
1178 }
1179
1180 /**
1181 * Whether the given IP is in a DNS blacklist.
1182 *
1183 * @param $ip String IP to check
1184 * @param $checkWhitelist Bool: whether to check the whitelist first
1185 * @return Bool True if blacklisted.
1186 */
1187 function isDnsBlacklisted( $ip, $checkWhitelist = false ) {
1188 global $wgEnableSorbs, $wgEnableDnsBlacklist,
1189 $wgSorbsUrl, $wgDnsBlacklistUrls, $wgProxyWhitelist;
1190
1191 if ( !$wgEnableDnsBlacklist && !$wgEnableSorbs )
1192 return false;
1193
1194 if ( $checkWhitelist && in_array( $ip, $wgProxyWhitelist ) )
1195 return false;
1196
1197 $urls = array_merge( $wgDnsBlacklistUrls, (array)$wgSorbsUrl );
1198 return $this->inDnsBlacklist( $ip, $urls );
1199 }
1200
1201 /**
1202 * Whether the given IP is in a given DNS blacklist.
1203 *
1204 * @param $ip String IP to check
1205 * @param $bases String|Array of Strings: URL of the DNS blacklist
1206 * @return Bool True if blacklisted.
1207 */
1208 function inDnsBlacklist( $ip, $bases ) {
1209 wfProfileIn( __METHOD__ );
1210
1211 $found = false;
1212 // FIXME: IPv6 ??? (http://bugs.php.net/bug.php?id=33170)
1213 if( IP::isIPv4( $ip ) ) {
1214 # Reverse IP, bug 21255
1215 $ipReversed = implode( '.', array_reverse( explode( '.', $ip ) ) );
1216
1217 foreach( (array)$bases as $base ) {
1218 # Make hostname
1219 $host = "$ipReversed.$base";
1220
1221 # Send query
1222 $ipList = gethostbynamel( $host );
1223
1224 if( $ipList ) {
1225 wfDebug( "Hostname $host is {$ipList[0]}, it's a proxy says $base!\n" );
1226 $found = true;
1227 break;
1228 } else {
1229 wfDebug( "Requested $host, not found in $base.\n" );
1230 }
1231 }
1232 }
1233
1234 wfProfileOut( __METHOD__ );
1235 return $found;
1236 }
1237
1238 /**
1239 * Is this user subject to rate limiting?
1240 *
1241 * @return Bool True if rate limited
1242 */
1243 public function isPingLimitable() {
1244 global $wgRateLimitsExcludedGroups;
1245 global $wgRateLimitsExcludedIPs;
1246 if( array_intersect( $this->getEffectiveGroups(), $wgRateLimitsExcludedGroups ) ) {
1247 // Deprecated, but kept for backwards-compatibility config
1248 return false;
1249 }
1250 if( in_array( wfGetIP(), $wgRateLimitsExcludedIPs ) ) {
1251 // No other good way currently to disable rate limits
1252 // for specific IPs. :P
1253 // But this is a crappy hack and should die.
1254 return false;
1255 }
1256 return !$this->isAllowed('noratelimit');
1257 }
1258
1259 /**
1260 * Primitive rate limits: enforce maximum actions per time period
1261 * to put a brake on flooding.
1262 *
1263 * @note When using a shared cache like memcached, IP-address
1264 * last-hit counters will be shared across wikis.
1265 *
1266 * @param $action String Action to enforce; 'edit' if unspecified
1267 * @return Bool True if a rate limiter was tripped
1268 */
1269 function pingLimiter( $action = 'edit' ) {
1270 # Call the 'PingLimiter' hook
1271 $result = false;
1272 if( !wfRunHooks( 'PingLimiter', array( &$this, $action, $result ) ) ) {
1273 return $result;
1274 }
1275
1276 global $wgRateLimits;
1277 if( !isset( $wgRateLimits[$action] ) ) {
1278 return false;
1279 }
1280
1281 # Some groups shouldn't trigger the ping limiter, ever
1282 if( !$this->isPingLimitable() )
1283 return false;
1284
1285 global $wgMemc, $wgRateLimitLog;
1286 wfProfileIn( __METHOD__ );
1287
1288 $limits = $wgRateLimits[$action];
1289 $keys = array();
1290 $id = $this->getId();
1291 $ip = wfGetIP();
1292 $userLimit = false;
1293
1294 if( isset( $limits['anon'] ) && $id == 0 ) {
1295 $keys[wfMemcKey( 'limiter', $action, 'anon' )] = $limits['anon'];
1296 }
1297
1298 if( isset( $limits['user'] ) && $id != 0 ) {
1299 $userLimit = $limits['user'];
1300 }
1301 if( $this->isNewbie() ) {
1302 if( isset( $limits['newbie'] ) && $id != 0 ) {
1303 $keys[wfMemcKey( 'limiter', $action, 'user', $id )] = $limits['newbie'];
1304 }
1305 if( isset( $limits['ip'] ) ) {
1306 $keys["mediawiki:limiter:$action:ip:$ip"] = $limits['ip'];
1307 }
1308 $matches = array();
1309 if( isset( $limits['subnet'] ) && preg_match( '/^(\d+\.\d+\.\d+)\.\d+$/', $ip, $matches ) ) {
1310 $subnet = $matches[1];
1311 $keys["mediawiki:limiter:$action:subnet:$subnet"] = $limits['subnet'];
1312 }
1313 }
1314 // Check for group-specific permissions
1315 // If more than one group applies, use the group with the highest limit
1316 foreach ( $this->getGroups() as $group ) {
1317 if ( isset( $limits[$group] ) ) {
1318 if ( $userLimit === false || $limits[$group] > $userLimit ) {
1319 $userLimit = $limits[$group];
1320 }
1321 }
1322 }
1323 // Set the user limit key
1324 if ( $userLimit !== false ) {
1325 wfDebug( __METHOD__ . ": effective user limit: $userLimit\n" );
1326 $keys[ wfMemcKey( 'limiter', $action, 'user', $id ) ] = $userLimit;
1327 }
1328
1329 $triggered = false;
1330 foreach( $keys as $key => $limit ) {
1331 list( $max, $period ) = $limit;
1332 $summary = "(limit $max in {$period}s)";
1333 $count = $wgMemc->get( $key );
1334 // Already pinged?
1335 if( $count ) {
1336 if( $count > $max ) {
1337 wfDebug( __METHOD__ . ": tripped! $key at $count $summary\n" );
1338 if( $wgRateLimitLog ) {
1339 @error_log( wfTimestamp( TS_MW ) . ' ' . wfWikiID() . ': ' . $this->getName() . " tripped $key at $count $summary\n", 3, $wgRateLimitLog );
1340 }
1341 $triggered = true;
1342 } else {
1343 wfDebug( __METHOD__ . ": ok. $key at $count $summary\n" );
1344 }
1345 } else {
1346 wfDebug( __METHOD__ . ": adding record for $key $summary\n" );
1347 $wgMemc->add( $key, 0, intval( $period ) ); // first ping
1348 }
1349 $wgMemc->incr( $key );
1350 }
1351
1352 wfProfileOut( __METHOD__ );
1353 return $triggered;
1354 }
1355
1356 /**
1357 * Check if user is blocked
1358 *
1359 * @param $bFromSlave Bool Whether to check the slave database instead of the master
1360 * @return Bool True if blocked, false otherwise
1361 */
1362 function isBlocked( $bFromSlave = true ) { // hacked from false due to horrible probs on site
1363 $this->getBlockedStatus( $bFromSlave );
1364 return $this->mBlockedby !== 0;
1365 }
1366
1367 /**
1368 * Check if user is blocked from editing a particular article
1369 *
1370 * @param $title Title to check
1371 * @param $bFromSlave Bool whether to check the slave database instead of the master
1372 * @return Bool
1373 */
1374 function isBlockedFrom( $title, $bFromSlave = false ) {
1375 global $wgBlockAllowsUTEdit;
1376 wfProfileIn( __METHOD__ );
1377
1378 $blocked = $this->isBlocked( $bFromSlave );
1379 $allowUsertalk = ( $wgBlockAllowsUTEdit ? $this->mAllowUsertalk : false );
1380 # If a user's name is suppressed, they cannot make edits anywhere
1381 if ( !$this->mHideName && $allowUsertalk && $title->getText() === $this->getName() &&
1382 $title->getNamespace() == NS_USER_TALK ) {
1383 $blocked = false;
1384 wfDebug( __METHOD__ . ": self-talk page, ignoring any blocks\n" );
1385 }
1386
1387 wfRunHooks( 'UserIsBlockedFrom', array( $this, $title, &$blocked, &$allowUsertalk ) );
1388
1389 wfProfileOut( __METHOD__ );
1390 return $blocked;
1391 }
1392
1393 /**
1394 * If user is blocked, return the name of the user who placed the block
1395 * @return String name of blocker
1396 */
1397 function blockedBy() {
1398 $this->getBlockedStatus();
1399 return $this->mBlockedby;
1400 }
1401
1402 /**
1403 * If user is blocked, return the specified reason for the block
1404 * @return String Blocking reason
1405 */
1406 function blockedFor() {
1407 $this->getBlockedStatus();
1408 return $this->mBlockreason;
1409 }
1410
1411 /**
1412 * If user is blocked, return the ID for the block
1413 * @return Int Block ID
1414 */
1415 function getBlockId() {
1416 $this->getBlockedStatus();
1417 return ( $this->mBlock ? $this->mBlock->mId : false );
1418 }
1419
1420 /**
1421 * Check if user is blocked on all wikis.
1422 * Do not use for actual edit permission checks!
1423 * This is intented for quick UI checks.
1424 *
1425 * @param $ip String IP address, uses current client if none given
1426 * @return Bool True if blocked, false otherwise
1427 */
1428 function isBlockedGlobally( $ip = '' ) {
1429 if( $this->mBlockedGlobally !== null ) {
1430 return $this->mBlockedGlobally;
1431 }
1432 // User is already an IP?
1433 if( IP::isIPAddress( $this->getName() ) ) {
1434 $ip = $this->getName();
1435 } else if( !$ip ) {
1436 $ip = wfGetIP();
1437 }
1438 $blocked = false;
1439 wfRunHooks( 'UserIsBlockedGlobally', array( &$this, $ip, &$blocked ) );
1440 $this->mBlockedGlobally = (bool)$blocked;
1441 return $this->mBlockedGlobally;
1442 }
1443
1444 /**
1445 * Check if user account is locked
1446 *
1447 * @return Bool True if locked, false otherwise
1448 */
1449 function isLocked() {
1450 if( $this->mLocked !== null ) {
1451 return $this->mLocked;
1452 }
1453 global $wgAuth;
1454 $authUser = $wgAuth->getUserInstance( $this );
1455 $this->mLocked = (bool)$authUser->isLocked();
1456 return $this->mLocked;
1457 }
1458
1459 /**
1460 * Check if user account is hidden
1461 *
1462 * @return Bool True if hidden, false otherwise
1463 */
1464 function isHidden() {
1465 if( $this->mHideName !== null ) {
1466 return $this->mHideName;
1467 }
1468 $this->getBlockedStatus();
1469 if( !$this->mHideName ) {
1470 global $wgAuth;
1471 $authUser = $wgAuth->getUserInstance( $this );
1472 $this->mHideName = (bool)$authUser->isHidden();
1473 }
1474 return $this->mHideName;
1475 }
1476
1477 /**
1478 * Get the user's ID.
1479 * @return Int The user's ID; 0 if the user is anonymous or nonexistent
1480 */
1481 function getId() {
1482 if( $this->mId === null and $this->mName !== null
1483 and User::isIP( $this->mName ) ) {
1484 // Special case, we know the user is anonymous
1485 return 0;
1486 } elseif( $this->mId === null ) {
1487 // Don't load if this was initialized from an ID
1488 $this->load();
1489 }
1490 return $this->mId;
1491 }
1492
1493 /**
1494 * Set the user and reload all fields according to a given ID
1495 * @param $v Int User ID to reload
1496 */
1497 function setId( $v ) {
1498 $this->mId = $v;
1499 $this->clearInstanceCache( 'id' );
1500 }
1501
1502 /**
1503 * Get the user name, or the IP of an anonymous user
1504 * @return String User's name or IP address
1505 */
1506 function getName() {
1507 if ( !$this->mDataLoaded && $this->mFrom == 'name' ) {
1508 # Special case optimisation
1509 return $this->mName;
1510 } else {
1511 $this->load();
1512 if ( $this->mName === false ) {
1513 # Clean up IPs
1514 $this->mName = IP::sanitizeIP( wfGetIP() );
1515 }
1516 return $this->mName;
1517 }
1518 }
1519
1520 /**
1521 * Set the user name.
1522 *
1523 * This does not reload fields from the database according to the given
1524 * name. Rather, it is used to create a temporary "nonexistent user" for
1525 * later addition to the database. It can also be used to set the IP
1526 * address for an anonymous user to something other than the current
1527 * remote IP.
1528 *
1529 * @note User::newFromName() has rougly the same function, when the named user
1530 * does not exist.
1531 * @param $str String New user name to set
1532 */
1533 function setName( $str ) {
1534 $this->load();
1535 $this->mName = $str;
1536 }
1537
1538 /**
1539 * Get the user's name escaped by underscores.
1540 * @return String Username escaped by underscores.
1541 */
1542 function getTitleKey() {
1543 return str_replace( ' ', '_', $this->getName() );
1544 }
1545
1546 /**
1547 * Check if the user has new messages.
1548 * @return Bool True if the user has new messages
1549 */
1550 function getNewtalk() {
1551 $this->load();
1552
1553 # Load the newtalk status if it is unloaded (mNewtalk=-1)
1554 if( $this->mNewtalk === -1 ) {
1555 $this->mNewtalk = false; # reset talk page status
1556
1557 # Check memcached separately for anons, who have no
1558 # entire User object stored in there.
1559 if( !$this->mId ) {
1560 global $wgMemc;
1561 $key = wfMemcKey( 'newtalk', 'ip', $this->getName() );
1562 $newtalk = $wgMemc->get( $key );
1563 if( strval( $newtalk ) !== '' ) {
1564 $this->mNewtalk = (bool)$newtalk;
1565 } else {
1566 // Since we are caching this, make sure it is up to date by getting it
1567 // from the master
1568 $this->mNewtalk = $this->checkNewtalk( 'user_ip', $this->getName(), true );
1569 $wgMemc->set( $key, (int)$this->mNewtalk, 1800 );
1570 }
1571 } else {
1572 $this->mNewtalk = $this->checkNewtalk( 'user_id', $this->mId );
1573 }
1574 }
1575
1576 return (bool)$this->mNewtalk;
1577 }
1578
1579 /**
1580 * Return the talk page(s) this user has new messages on.
1581 * @return Array of String page URLs
1582 */
1583 function getNewMessageLinks() {
1584 $talks = array();
1585 if( !wfRunHooks( 'UserRetrieveNewTalks', array( &$this, &$talks ) ) )
1586 return $talks;
1587
1588 if( !$this->getNewtalk() )
1589 return array();
1590 $up = $this->getUserPage();
1591 $utp = $up->getTalkPage();
1592 return array( array( 'wiki' => wfWikiID(), 'link' => $utp->getLocalURL() ) );
1593 }
1594
1595 /**
1596 * Internal uncached check for new messages
1597 *
1598 * @see getNewtalk()
1599 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1600 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1601 * @param $fromMaster Bool true to fetch from the master, false for a slave
1602 * @return Bool True if the user has new messages
1603 * @private
1604 */
1605 function checkNewtalk( $field, $id, $fromMaster = false ) {
1606 if ( $fromMaster ) {
1607 $db = wfGetDB( DB_MASTER );
1608 } else {
1609 $db = wfGetDB( DB_SLAVE );
1610 }
1611 $ok = $db->selectField( 'user_newtalk', $field,
1612 array( $field => $id ), __METHOD__ );
1613 return $ok !== false;
1614 }
1615
1616 /**
1617 * Add or update the new messages flag
1618 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1619 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1620 * @return Bool True if successful, false otherwise
1621 * @private
1622 */
1623 function updateNewtalk( $field, $id ) {
1624 $dbw = wfGetDB( DB_MASTER );
1625 $dbw->insert( 'user_newtalk',
1626 array( $field => $id ),
1627 __METHOD__,
1628 'IGNORE' );
1629 if ( $dbw->affectedRows() ) {
1630 wfDebug( __METHOD__ . ": set on ($field, $id)\n" );
1631 return true;
1632 } else {
1633 wfDebug( __METHOD__ . " already set ($field, $id)\n" );
1634 return false;
1635 }
1636 }
1637
1638 /**
1639 * Clear the new messages flag for the given user
1640 * @param $field String 'user_ip' for anonymous users, 'user_id' otherwise
1641 * @param $id String|Int User's IP address for anonymous users, User ID otherwise
1642 * @return Bool True if successful, false otherwise
1643 * @private
1644 */
1645 function deleteNewtalk( $field, $id ) {
1646 $dbw = wfGetDB( DB_MASTER );
1647 $dbw->delete( 'user_newtalk',
1648 array( $field => $id ),
1649 __METHOD__ );
1650 if ( $dbw->affectedRows() ) {
1651 wfDebug( __METHOD__ . ": killed on ($field, $id)\n" );
1652 return true;
1653 } else {
1654 wfDebug( __METHOD__ . ": already gone ($field, $id)\n" );
1655 return false;
1656 }
1657 }
1658
1659 /**
1660 * Update the 'You have new messages!' status.
1661 * @param $val Bool Whether the user has new messages
1662 */
1663 function setNewtalk( $val ) {
1664 if( wfReadOnly() ) {
1665 return;
1666 }
1667
1668 $this->load();
1669 $this->mNewtalk = $val;
1670
1671 if( $this->isAnon() ) {
1672 $field = 'user_ip';
1673 $id = $this->getName();
1674 } else {
1675 $field = 'user_id';
1676 $id = $this->getId();
1677 }
1678 global $wgMemc;
1679
1680 if( $val ) {
1681 $changed = $this->updateNewtalk( $field, $id );
1682 } else {
1683 $changed = $this->deleteNewtalk( $field, $id );
1684 }
1685
1686 if( $this->isAnon() ) {
1687 // Anons have a separate memcached space, since
1688 // user records aren't kept for them.
1689 $key = wfMemcKey( 'newtalk', 'ip', $id );
1690 $wgMemc->set( $key, $val ? 1 : 0, 1800 );
1691 }
1692 if ( $changed ) {
1693 $this->invalidateCache();
1694 }
1695 }
1696
1697 /**
1698 * Generate a current or new-future timestamp to be stored in the
1699 * user_touched field when we update things.
1700 * @return String Timestamp in TS_MW format
1701 */
1702 private static function newTouchedTimestamp() {
1703 global $wgClockSkewFudge;
1704 return wfTimestamp( TS_MW, time() + $wgClockSkewFudge );
1705 }
1706
1707 /**
1708 * Clear user data from memcached.
1709 * Use after applying fun updates to the database; caller's
1710 * responsibility to update user_touched if appropriate.
1711 *
1712 * Called implicitly from invalidateCache() and saveSettings().
1713 */
1714 private function clearSharedCache() {
1715 $this->load();
1716 if( $this->mId ) {
1717 global $wgMemc;
1718 $wgMemc->delete( wfMemcKey( 'user', 'id', $this->mId ) );
1719 }
1720 }
1721
1722 /**
1723 * Immediately touch the user data cache for this account.
1724 * Updates user_touched field, and removes account data from memcached
1725 * for reload on the next hit.
1726 */
1727 function invalidateCache() {
1728 if( wfReadOnly() ) {
1729 return;
1730 }
1731 $this->load();
1732 if( $this->mId ) {
1733 $this->mTouched = self::newTouchedTimestamp();
1734
1735 $dbw = wfGetDB( DB_MASTER );
1736 $dbw->update( 'user',
1737 array( 'user_touched' => $dbw->timestamp( $this->mTouched ) ),
1738 array( 'user_id' => $this->mId ),
1739 __METHOD__ );
1740
1741 $this->clearSharedCache();
1742 }
1743 }
1744
1745 /**
1746 * Validate the cache for this account.
1747 * @param $timestamp String A timestamp in TS_MW format
1748 */
1749 function validateCache( $timestamp ) {
1750 $this->load();
1751 return ( $timestamp >= $this->mTouched );
1752 }
1753
1754 /**
1755 * Get the user touched timestamp
1756 * @return String timestamp
1757 */
1758 function getTouched() {
1759 $this->load();
1760 return $this->mTouched;
1761 }
1762
1763 /**
1764 * Set the password and reset the random token.
1765 * Calls through to authentication plugin if necessary;
1766 * will have no effect if the auth plugin refuses to
1767 * pass the change through or if the legal password
1768 * checks fail.
1769 *
1770 * As a special case, setting the password to null
1771 * wipes it, so the account cannot be logged in until
1772 * a new password is set, for instance via e-mail.
1773 *
1774 * @param $str String New password to set
1775 * @throws PasswordError on failure
1776 */
1777 function setPassword( $str ) {
1778 global $wgAuth;
1779
1780 if( $str !== null ) {
1781 if( !$wgAuth->allowPasswordChange() ) {
1782 throw new PasswordError( wfMsg( 'password-change-forbidden' ) );
1783 }
1784
1785 if( !$this->isValidPassword( $str ) ) {
1786 global $wgMinimalPasswordLength;
1787 $valid = $this->getPasswordValidity( $str );
1788 if ( is_array( $valid ) ) {
1789 $message = array_shift( $valid );
1790 $params = $valid;
1791 } else {
1792 $message = $valid;
1793 $params = array( $wgMinimalPasswordLength );
1794 }
1795 throw new PasswordError( wfMsgExt( $message, array( 'parsemag' ), $params ) );
1796 }
1797 }
1798
1799 if( !$wgAuth->setPassword( $this, $str ) ) {
1800 throw new PasswordError( wfMsg( 'externaldberror' ) );
1801 }
1802
1803 $this->setInternalPassword( $str );
1804
1805 return true;
1806 }
1807
1808 /**
1809 * Set the password and reset the random token unconditionally.
1810 *
1811 * @param $str String New password to set
1812 */
1813 function setInternalPassword( $str ) {
1814 $this->load();
1815 $this->setToken();
1816
1817 if( $str === null ) {
1818 // Save an invalid hash...
1819 $this->mPassword = '';
1820 } else {
1821 $this->mPassword = self::crypt( $str );
1822 }
1823 $this->mNewpassword = '';
1824 $this->mNewpassTime = null;
1825 }
1826
1827 /**
1828 * Get the user's current token.
1829 * @return String Token
1830 */
1831 function getToken() {
1832 $this->load();
1833 return $this->mToken;
1834 }
1835
1836 /**
1837 * Set the random token (used for persistent authentication)
1838 * Called from loadDefaults() among other places.
1839 *
1840 * @param $token String If specified, set the token to this value
1841 * @private
1842 */
1843 function setToken( $token = false ) {
1844 global $wgSecretKey, $wgProxyKey;
1845 $this->load();
1846 if ( !$token ) {
1847 if ( $wgSecretKey ) {
1848 $key = $wgSecretKey;
1849 } elseif ( $wgProxyKey ) {
1850 $key = $wgProxyKey;
1851 } else {
1852 $key = microtime();
1853 }
1854 $this->mToken = md5( $key . mt_rand( 0, 0x7fffffff ) . wfWikiID() . $this->mId );
1855 } else {
1856 $this->mToken = $token;
1857 }
1858 }
1859
1860 /**
1861 * Set the cookie password
1862 *
1863 * @param $str String New cookie password
1864 * @private
1865 */
1866 function setCookiePassword( $str ) {
1867 $this->load();
1868 $this->mCookiePassword = md5( $str );
1869 }
1870
1871 /**
1872 * Set the password for a password reminder or new account email
1873 *
1874 * @param $str String New password to set
1875 * @param $throttle Bool If true, reset the throttle timestamp to the present
1876 */
1877 function setNewpassword( $str, $throttle = true ) {
1878 $this->load();
1879 $this->mNewpassword = self::crypt( $str );
1880 if ( $throttle ) {
1881 $this->mNewpassTime = wfTimestampNow();
1882 }
1883 }
1884
1885 /**
1886 * Has password reminder email been sent within the last
1887 * $wgPasswordReminderResendTime hours?
1888 * @return Bool
1889 */
1890 function isPasswordReminderThrottled() {
1891 global $wgPasswordReminderResendTime;
1892 $this->load();
1893 if ( !$this->mNewpassTime || !$wgPasswordReminderResendTime ) {
1894 return false;
1895 }
1896 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgPasswordReminderResendTime * 3600;
1897 return time() < $expiry;
1898 }
1899
1900 /**
1901 * Get the user's e-mail address
1902 * @return String User's email address
1903 */
1904 function getEmail() {
1905 $this->load();
1906 wfRunHooks( 'UserGetEmail', array( $this, &$this->mEmail ) );
1907 return $this->mEmail;
1908 }
1909
1910 /**
1911 * Get the timestamp of the user's e-mail authentication
1912 * @return String TS_MW timestamp
1913 */
1914 function getEmailAuthenticationTimestamp() {
1915 $this->load();
1916 wfRunHooks( 'UserGetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
1917 return $this->mEmailAuthenticated;
1918 }
1919
1920 /**
1921 * Set the user's e-mail address
1922 * @param $str String New e-mail address
1923 */
1924 function setEmail( $str ) {
1925 $this->load();
1926 $this->mEmail = $str;
1927 wfRunHooks( 'UserSetEmail', array( $this, &$this->mEmail ) );
1928 }
1929
1930 /**
1931 * Get the user's real name
1932 * @return String User's real name
1933 */
1934 function getRealName() {
1935 $this->load();
1936 return $this->mRealName;
1937 }
1938
1939 /**
1940 * Set the user's real name
1941 * @param $str String New real name
1942 */
1943 function setRealName( $str ) {
1944 $this->load();
1945 $this->mRealName = $str;
1946 }
1947
1948 /**
1949 * Get the user's current setting for a given option.
1950 *
1951 * @param $oname String The option to check
1952 * @param $defaultOverride String A default value returned if the option does not exist
1953 * @return String User's current value for the option
1954 * @see getBoolOption()
1955 * @see getIntOption()
1956 */
1957 function getOption( $oname, $defaultOverride = null ) {
1958 $this->loadOptions();
1959
1960 if ( is_null( $this->mOptions ) ) {
1961 if($defaultOverride != '') {
1962 return $defaultOverride;
1963 }
1964 $this->mOptions = User::getDefaultOptions();
1965 }
1966
1967 if ( array_key_exists( $oname, $this->mOptions ) ) {
1968 return $this->mOptions[$oname];
1969 } else {
1970 return $defaultOverride;
1971 }
1972 }
1973
1974 /**
1975 * Get all user's options
1976 *
1977 * @return array
1978 */
1979 public function getOptions() {
1980 $this->loadOptions();
1981 return $this->mOptions;
1982 }
1983
1984 /**
1985 * Get the user's current setting for a given option, as a boolean value.
1986 *
1987 * @param $oname String The option to check
1988 * @return Bool User's current value for the option
1989 * @see getOption()
1990 */
1991 function getBoolOption( $oname ) {
1992 return (bool)$this->getOption( $oname );
1993 }
1994
1995
1996 /**
1997 * Get the user's current setting for a given option, as a boolean value.
1998 *
1999 * @param $oname String The option to check
2000 * @param $defaultOverride Int A default value returned if the option does not exist
2001 * @return Int User's current value for the option
2002 * @see getOption()
2003 */
2004 function getIntOption( $oname, $defaultOverride=0 ) {
2005 $val = $this->getOption( $oname );
2006 if( $val == '' ) {
2007 $val = $defaultOverride;
2008 }
2009 return intval( $val );
2010 }
2011
2012 /**
2013 * Set the given option for a user.
2014 *
2015 * @param $oname String The option to set
2016 * @param $val mixed New value to set
2017 */
2018 function setOption( $oname, $val ) {
2019 $this->load();
2020 $this->loadOptions();
2021
2022 if ( $oname == 'skin' ) {
2023 # Clear cached skin, so the new one displays immediately in Special:Preferences
2024 $this->mSkin = null;
2025 }
2026
2027 // Explicitly NULL values should refer to defaults
2028 global $wgDefaultUserOptions;
2029 if( is_null( $val ) && isset( $wgDefaultUserOptions[$oname] ) ) {
2030 $val = $wgDefaultUserOptions[$oname];
2031 }
2032
2033 $this->mOptions[$oname] = $val;
2034 }
2035
2036 /**
2037 * Reset all options to the site defaults
2038 */
2039 function resetOptions() {
2040 $this->mOptions = User::getDefaultOptions();
2041 }
2042
2043 /**
2044 * Get the user's preferred date format.
2045 * @return String User's preferred date format
2046 */
2047 function getDatePreference() {
2048 // Important migration for old data rows
2049 if ( is_null( $this->mDatePreference ) ) {
2050 global $wgLang;
2051 $value = $this->getOption( 'date' );
2052 $map = $wgLang->getDatePreferenceMigrationMap();
2053 if ( isset( $map[$value] ) ) {
2054 $value = $map[$value];
2055 }
2056 $this->mDatePreference = $value;
2057 }
2058 return $this->mDatePreference;
2059 }
2060
2061 /**
2062 * Get the user preferred stub threshold
2063 */
2064 function getStubThreshold() {
2065 global $wgMaxArticleSize; # Maximum article size, in Kb
2066 $threshold = intval( $this->getOption( 'stubthreshold' ) );
2067 if ( $threshold > $wgMaxArticleSize * 1024 ) {
2068 # If they have set an impossible value, disable the preference
2069 # so we can use the parser cache again.
2070 $threshold = 0;
2071 }
2072 return $threshold;
2073 }
2074
2075 /**
2076 * Get the permissions this user has.
2077 * @return Array of String permission names
2078 */
2079 function getRights() {
2080 if ( is_null( $this->mRights ) ) {
2081 $this->mRights = self::getGroupPermissions( $this->getEffectiveGroups() );
2082 wfRunHooks( 'UserGetRights', array( $this, &$this->mRights ) );
2083 // Force reindexation of rights when a hook has unset one of them
2084 $this->mRights = array_values( $this->mRights );
2085 }
2086 return $this->mRights;
2087 }
2088
2089 /**
2090 * Get the list of explicit group memberships this user has.
2091 * The implicit * and user groups are not included.
2092 * @return Array of String internal group names
2093 */
2094 function getGroups() {
2095 $this->load();
2096 return $this->mGroups;
2097 }
2098
2099 /**
2100 * Get the list of implicit group memberships this user has.
2101 * This includes all explicit groups, plus 'user' if logged in,
2102 * '*' for all accounts, and autopromoted groups
2103 * @param $recache Bool Whether to avoid the cache
2104 * @return Array of String internal group names
2105 */
2106 function getEffectiveGroups( $recache = false ) {
2107 if ( $recache || is_null( $this->mEffectiveGroups ) ) {
2108 wfProfileIn( __METHOD__ );
2109 $this->mEffectiveGroups = $this->getGroups();
2110 $this->mEffectiveGroups[] = '*';
2111 if( $this->getId() ) {
2112 $this->mEffectiveGroups[] = 'user';
2113
2114 $this->mEffectiveGroups = array_unique( array_merge(
2115 $this->mEffectiveGroups,
2116 Autopromote::getAutopromoteGroups( $this )
2117 ) );
2118
2119 # Hook for additional groups
2120 wfRunHooks( 'UserEffectiveGroups', array( &$this, &$this->mEffectiveGroups ) );
2121 }
2122 wfProfileOut( __METHOD__ );
2123 }
2124 return $this->mEffectiveGroups;
2125 }
2126
2127 /**
2128 * Get the user's edit count.
2129 * @return Int
2130 */
2131 function getEditCount() {
2132 if( $this->getId() ) {
2133 if ( !isset( $this->mEditCount ) ) {
2134 /* Populate the count, if it has not been populated yet */
2135 $this->mEditCount = User::edits( $this->mId );
2136 }
2137 return $this->mEditCount;
2138 } else {
2139 /* nil */
2140 return null;
2141 }
2142 }
2143
2144 /**
2145 * Add the user to the given group.
2146 * This takes immediate effect.
2147 * @param $group String Name of the group to add
2148 */
2149 function addGroup( $group ) {
2150 $dbw = wfGetDB( DB_MASTER );
2151 if( $this->getId() ) {
2152 $dbw->insert( 'user_groups',
2153 array(
2154 'ug_user' => $this->getID(),
2155 'ug_group' => $group,
2156 ),
2157 __METHOD__,
2158 array( 'IGNORE' ) );
2159 }
2160
2161 $this->loadGroups();
2162 $this->mGroups[] = $group;
2163 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2164
2165 $this->invalidateCache();
2166 }
2167
2168 /**
2169 * Remove the user from the given group.
2170 * This takes immediate effect.
2171 * @param $group String Name of the group to remove
2172 */
2173 function removeGroup( $group ) {
2174 $this->load();
2175 $dbw = wfGetDB( DB_MASTER );
2176 $dbw->delete( 'user_groups',
2177 array(
2178 'ug_user' => $this->getID(),
2179 'ug_group' => $group,
2180 ), __METHOD__ );
2181
2182 $this->loadGroups();
2183 $this->mGroups = array_diff( $this->mGroups, array( $group ) );
2184 $this->mRights = User::getGroupPermissions( $this->getEffectiveGroups( true ) );
2185
2186 $this->invalidateCache();
2187 }
2188
2189 /**
2190 * Get whether the user is logged in
2191 * @return Bool
2192 */
2193 function isLoggedIn() {
2194 return $this->getID() != 0;
2195 }
2196
2197 /**
2198 * Get whether the user is anonymous
2199 * @return Bool
2200 */
2201 function isAnon() {
2202 return !$this->isLoggedIn();
2203 }
2204
2205 /**
2206 * Check if user is allowed to access a feature / make an action
2207 * @param $action String action to be checked
2208 * @return Boolean: True if action is allowed, else false
2209 */
2210 function isAllowed( $action = '' ) {
2211 if ( $action === '' ) {
2212 return true; // In the spirit of DWIM
2213 }
2214 # Patrolling may not be enabled
2215 if( $action === 'patrol' || $action === 'autopatrol' ) {
2216 global $wgUseRCPatrol, $wgUseNPPatrol;
2217 if( !$wgUseRCPatrol && !$wgUseNPPatrol )
2218 return false;
2219 }
2220 # Use strict parameter to avoid matching numeric 0 accidentally inserted
2221 # by misconfiguration: 0 == 'foo'
2222 return in_array( $action, $this->getRights(), true );
2223 }
2224
2225 /**
2226 * Check whether to enable recent changes patrol features for this user
2227 * @return Boolean: True or false
2228 */
2229 public function useRCPatrol() {
2230 global $wgUseRCPatrol;
2231 return( $wgUseRCPatrol && ( $this->isAllowed( 'patrol' ) || $this->isAllowed( 'patrolmarks' ) ) );
2232 }
2233
2234 /**
2235 * Check whether to enable new pages patrol features for this user
2236 * @return Bool True or false
2237 */
2238 public function useNPPatrol() {
2239 global $wgUseRCPatrol, $wgUseNPPatrol;
2240 return( ( $wgUseRCPatrol || $wgUseNPPatrol ) && ( $this->isAllowed( 'patrol' ) || $this->isAllowed( 'patrolmarks' ) ) );
2241 }
2242
2243 /**
2244 * Get the current skin, loading it if required, and setting a title
2245 * @param $t Title: the title to use in the skin
2246 * @return Skin The current skin
2247 * @todo: FIXME : need to check the old failback system [AV]
2248 */
2249 function getSkin( $t = null ) {
2250 if ( $t ) {
2251 $skin = $this->createSkinObject();
2252 $skin->setTitle( $t );
2253 return $skin;
2254 } else {
2255 if ( !$this->mSkin ) {
2256 $this->mSkin = $this->createSkinObject();
2257 }
2258
2259 if ( !$this->mSkin->getTitle() ) {
2260 global $wgOut;
2261 $t = $wgOut->getTitle();
2262 $this->mSkin->setTitle($t);
2263 }
2264
2265 return $this->mSkin;
2266 }
2267 }
2268
2269 // Creates a Skin object, for getSkin()
2270 private function createSkinObject() {
2271 wfProfileIn( __METHOD__ );
2272
2273 global $wgHiddenPrefs;
2274 if( !in_array( 'skin', $wgHiddenPrefs ) ) {
2275 global $wgRequest;
2276 # get the user skin
2277 $userSkin = $this->getOption( 'skin' );
2278 $userSkin = $wgRequest->getVal( 'useskin', $userSkin );
2279 } else {
2280 # if we're not allowing users to override, then use the default
2281 global $wgDefaultSkin;
2282 $userSkin = $wgDefaultSkin;
2283 }
2284
2285 $skin = Skin::newFromKey( $userSkin );
2286 wfProfileOut( __METHOD__ );
2287
2288 return $skin;
2289 }
2290
2291 /**
2292 * Check the watched status of an article.
2293 * @param $title Title of the article to look at
2294 * @return Bool
2295 */
2296 function isWatched( $title ) {
2297 $wl = WatchedItem::fromUserTitle( $this, $title );
2298 return $wl->isWatched();
2299 }
2300
2301 /**
2302 * Watch an article.
2303 * @param $title Title of the article to look at
2304 */
2305 function addWatch( $title ) {
2306 $wl = WatchedItem::fromUserTitle( $this, $title );
2307 $wl->addWatch();
2308 $this->invalidateCache();
2309 }
2310
2311 /**
2312 * Stop watching an article.
2313 * @param $title Title of the article to look at
2314 */
2315 function removeWatch( $title ) {
2316 $wl = WatchedItem::fromUserTitle( $this, $title );
2317 $wl->removeWatch();
2318 $this->invalidateCache();
2319 }
2320
2321 /**
2322 * Clear the user's notification timestamp for the given title.
2323 * If e-notif e-mails are on, they will receive notification mails on
2324 * the next change of the page if it's watched etc.
2325 * @param $title Title of the article to look at
2326 */
2327 function clearNotification( &$title ) {
2328 global $wgUser, $wgUseEnotif, $wgShowUpdatedMarker;
2329
2330 # Do nothing if the database is locked to writes
2331 if( wfReadOnly() ) {
2332 return;
2333 }
2334
2335 if( $title->getNamespace() == NS_USER_TALK &&
2336 $title->getText() == $this->getName() ) {
2337 if( !wfRunHooks( 'UserClearNewTalkNotification', array( &$this ) ) )
2338 return;
2339 $this->setNewtalk( false );
2340 }
2341
2342 if( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2343 return;
2344 }
2345
2346 if( $this->isAnon() ) {
2347 // Nothing else to do...
2348 return;
2349 }
2350
2351 // Only update the timestamp if the page is being watched.
2352 // The query to find out if it is watched is cached both in memcached and per-invocation,
2353 // and when it does have to be executed, it can be on a slave
2354 // If this is the user's newtalk page, we always update the timestamp
2355 if( $title->getNamespace() == NS_USER_TALK &&
2356 $title->getText() == $wgUser->getName() )
2357 {
2358 $watched = true;
2359 } elseif ( $this->getId() == $wgUser->getId() ) {
2360 $watched = $title->userIsWatching();
2361 } else {
2362 $watched = true;
2363 }
2364
2365 // If the page is watched by the user (or may be watched), update the timestamp on any
2366 // any matching rows
2367 if ( $watched ) {
2368 $dbw = wfGetDB( DB_MASTER );
2369 $dbw->update( 'watchlist',
2370 array( /* SET */
2371 'wl_notificationtimestamp' => null
2372 ), array( /* WHERE */
2373 'wl_title' => $title->getDBkey(),
2374 'wl_namespace' => $title->getNamespace(),
2375 'wl_user' => $this->getID()
2376 ), __METHOD__
2377 );
2378 }
2379 }
2380
2381 /**
2382 * Resets all of the given user's page-change notification timestamps.
2383 * If e-notif e-mails are on, they will receive notification mails on
2384 * the next change of any watched page.
2385 *
2386 * @param $currentUser Int User ID
2387 */
2388 function clearAllNotifications( $currentUser ) {
2389 global $wgUseEnotif, $wgShowUpdatedMarker;
2390 if ( !$wgUseEnotif && !$wgShowUpdatedMarker ) {
2391 $this->setNewtalk( false );
2392 return;
2393 }
2394 if( $currentUser != 0 ) {
2395 $dbw = wfGetDB( DB_MASTER );
2396 $dbw->update( 'watchlist',
2397 array( /* SET */
2398 'wl_notificationtimestamp' => null
2399 ), array( /* WHERE */
2400 'wl_user' => $currentUser
2401 ), __METHOD__
2402 );
2403 # We also need to clear here the "you have new message" notification for the own user_talk page
2404 # This is cleared one page view later in Article::viewUpdates();
2405 }
2406 }
2407
2408 /**
2409 * Set this user's options from an encoded string
2410 * @param $str String Encoded options to import
2411 * @private
2412 */
2413 function decodeOptions( $str ) {
2414 if( !$str )
2415 return;
2416
2417 $this->mOptionsLoaded = true;
2418 $this->mOptionOverrides = array();
2419
2420 // If an option is not set in $str, use the default value
2421 $this->mOptions = self::getDefaultOptions();
2422
2423 $a = explode( "\n", $str );
2424 foreach ( $a as $s ) {
2425 $m = array();
2426 if ( preg_match( "/^(.[^=]*)=(.*)$/", $s, $m ) ) {
2427 $this->mOptions[$m[1]] = $m[2];
2428 $this->mOptionOverrides[$m[1]] = $m[2];
2429 }
2430 }
2431 }
2432
2433 /**
2434 * Set a cookie on the user's client. Wrapper for
2435 * WebResponse::setCookie
2436 * @param $name String Name of the cookie to set
2437 * @param $value String Value to set
2438 * @param $exp Int Expiration time, as a UNIX time value;
2439 * if 0 or not specified, use the default $wgCookieExpiration
2440 */
2441 protected function setCookie( $name, $value, $exp = 0 ) {
2442 global $wgRequest;
2443 $wgRequest->response()->setcookie( $name, $value, $exp );
2444 }
2445
2446 /**
2447 * Clear a cookie on the user's client
2448 * @param $name String Name of the cookie to clear
2449 */
2450 protected function clearCookie( $name ) {
2451 $this->setCookie( $name, '', time() - 86400 );
2452 }
2453
2454 /**
2455 * Set the default cookies for this session on the user's client.
2456 */
2457 function setCookies() {
2458 $this->load();
2459 if ( 0 == $this->mId ) return;
2460 $session = array(
2461 'wsUserID' => $this->mId,
2462 'wsToken' => $this->mToken,
2463 'wsUserName' => $this->getName()
2464 );
2465 $cookies = array(
2466 'UserID' => $this->mId,
2467 'UserName' => $this->getName(),
2468 );
2469 if ( 1 == $this->getOption( 'rememberpassword' ) ) {
2470 $cookies['Token'] = $this->mToken;
2471 } else {
2472 $cookies['Token'] = false;
2473 }
2474
2475 wfRunHooks( 'UserSetCookies', array( $this, &$session, &$cookies ) );
2476 #check for null, since the hook could cause a null value
2477 if ( !is_null( $session ) && isset( $_SESSION ) ){
2478 $_SESSION = $session + $_SESSION;
2479 }
2480 foreach ( $cookies as $name => $value ) {
2481 if ( $value === false ) {
2482 $this->clearCookie( $name );
2483 } else {
2484 $this->setCookie( $name, $value );
2485 }
2486 }
2487 }
2488
2489 /**
2490 * Log this user out.
2491 */
2492 function logout() {
2493 if( wfRunHooks( 'UserLogout', array( &$this ) ) ) {
2494 $this->doLogout();
2495 }
2496 }
2497
2498 /**
2499 * Clear the user's cookies and session, and reset the instance cache.
2500 * @private
2501 * @see logout()
2502 */
2503 function doLogout() {
2504 $this->clearInstanceCache( 'defaults' );
2505
2506 $_SESSION['wsUserID'] = 0;
2507
2508 $this->clearCookie( 'UserID' );
2509 $this->clearCookie( 'Token' );
2510
2511 # Remember when user logged out, to prevent seeing cached pages
2512 $this->setCookie( 'LoggedOut', wfTimestampNow(), time() + 86400 );
2513 }
2514
2515 /**
2516 * Save this user's settings into the database.
2517 * @todo Only rarely do all these fields need to be set!
2518 */
2519 function saveSettings() {
2520 $this->load();
2521 if ( wfReadOnly() ) { return; }
2522 if ( 0 == $this->mId ) { return; }
2523
2524 $this->mTouched = self::newTouchedTimestamp();
2525
2526 $dbw = wfGetDB( DB_MASTER );
2527 $dbw->update( 'user',
2528 array( /* SET */
2529 'user_name' => $this->mName,
2530 'user_password' => $this->mPassword,
2531 'user_newpassword' => $this->mNewpassword,
2532 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2533 'user_real_name' => $this->mRealName,
2534 'user_email' => $this->mEmail,
2535 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2536 'user_options' => '',
2537 'user_touched' => $dbw->timestamp( $this->mTouched ),
2538 'user_token' => $this->mToken,
2539 'user_email_token' => $this->mEmailToken,
2540 'user_email_token_expires' => $dbw->timestampOrNull( $this->mEmailTokenExpires ),
2541 ), array( /* WHERE */
2542 'user_id' => $this->mId
2543 ), __METHOD__
2544 );
2545
2546 $this->saveOptions();
2547
2548 wfRunHooks( 'UserSaveSettings', array( $this ) );
2549 $this->clearSharedCache();
2550 $this->getUserPage()->invalidateCache();
2551 }
2552
2553 /**
2554 * If only this user's username is known, and it exists, return the user ID.
2555 * @return Int
2556 */
2557 function idForName() {
2558 $s = trim( $this->getName() );
2559 if ( $s === '' ) return 0;
2560
2561 $dbr = wfGetDB( DB_SLAVE );
2562 $id = $dbr->selectField( 'user', 'user_id', array( 'user_name' => $s ), __METHOD__ );
2563 if ( $id === false ) {
2564 $id = 0;
2565 }
2566 return $id;
2567 }
2568
2569 /**
2570 * Add a user to the database, return the user object
2571 *
2572 * @param $name String Username to add
2573 * @param $params Array of Strings Non-default parameters to save to the database:
2574 * - password The user's password. Password logins will be disabled if this is omitted.
2575 * - newpassword A temporary password mailed to the user
2576 * - email The user's email address
2577 * - email_authenticated The email authentication timestamp
2578 * - real_name The user's real name
2579 * - options An associative array of non-default options
2580 * - token Random authentication token. Do not set.
2581 * - registration Registration timestamp. Do not set.
2582 *
2583 * @return User object, or null if the username already exists
2584 */
2585 static function createNew( $name, $params = array() ) {
2586 $user = new User;
2587 $user->load();
2588 if ( isset( $params['options'] ) ) {
2589 $user->mOptions = $params['options'] + (array)$user->mOptions;
2590 unset( $params['options'] );
2591 }
2592 $dbw = wfGetDB( DB_MASTER );
2593 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2594
2595 $fields = array(
2596 'user_id' => $seqVal,
2597 'user_name' => $name,
2598 'user_password' => $user->mPassword,
2599 'user_newpassword' => $user->mNewpassword,
2600 'user_newpass_time' => $dbw->timestampOrNull( $user->mNewpassTime ),
2601 'user_email' => $user->mEmail,
2602 'user_email_authenticated' => $dbw->timestampOrNull( $user->mEmailAuthenticated ),
2603 'user_real_name' => $user->mRealName,
2604 'user_options' => '',
2605 'user_token' => $user->mToken,
2606 'user_registration' => $dbw->timestamp( $user->mRegistration ),
2607 'user_editcount' => 0,
2608 );
2609 foreach ( $params as $name => $value ) {
2610 $fields["user_$name"] = $value;
2611 }
2612 $dbw->insert( 'user', $fields, __METHOD__, array( 'IGNORE' ) );
2613 if ( $dbw->affectedRows() ) {
2614 $newUser = User::newFromId( $dbw->insertId() );
2615 } else {
2616 $newUser = null;
2617 }
2618 return $newUser;
2619 }
2620
2621 /**
2622 * Add this existing user object to the database
2623 */
2624 function addToDatabase() {
2625 $this->load();
2626 $dbw = wfGetDB( DB_MASTER );
2627 $seqVal = $dbw->nextSequenceValue( 'user_user_id_seq' );
2628 $dbw->insert( 'user',
2629 array(
2630 'user_id' => $seqVal,
2631 'user_name' => $this->mName,
2632 'user_password' => $this->mPassword,
2633 'user_newpassword' => $this->mNewpassword,
2634 'user_newpass_time' => $dbw->timestampOrNull( $this->mNewpassTime ),
2635 'user_email' => $this->mEmail,
2636 'user_email_authenticated' => $dbw->timestampOrNull( $this->mEmailAuthenticated ),
2637 'user_real_name' => $this->mRealName,
2638 'user_options' => '',
2639 'user_token' => $this->mToken,
2640 'user_registration' => $dbw->timestamp( $this->mRegistration ),
2641 'user_editcount' => 0,
2642 ), __METHOD__
2643 );
2644 $this->mId = $dbw->insertId();
2645
2646 // Clear instance cache other than user table data, which is already accurate
2647 $this->clearInstanceCache();
2648
2649 $this->saveOptions();
2650 }
2651
2652 /**
2653 * If this (non-anonymous) user is blocked, block any IP address
2654 * they've successfully logged in from.
2655 */
2656 function spreadBlock() {
2657 wfDebug( __METHOD__ . "()\n" );
2658 $this->load();
2659 if ( $this->mId == 0 ) {
2660 return;
2661 }
2662
2663 $userblock = Block::newFromDB( '', $this->mId );
2664 if ( !$userblock ) {
2665 return;
2666 }
2667
2668 $userblock->doAutoblock( wfGetIP() );
2669 }
2670
2671 /**
2672 * Generate a string which will be different for any combination of
2673 * user options which would produce different parser output.
2674 * This will be used as part of the hash key for the parser cache,
2675 * so users with the same options can share the same cached data
2676 * safely.
2677 *
2678 * Extensions which require it should install 'PageRenderingHash' hook,
2679 * which will give them a chance to modify this key based on their own
2680 * settings.
2681 *
2682 * @deprecated @since 1.17 use the ParserOptions object to get the relevant options
2683 * @return String Page rendering hash
2684 */
2685 function getPageRenderingHash() {
2686 global $wgUseDynamicDates, $wgRenderHashAppend, $wgLang, $wgContLang;
2687 if( $this->mHash ){
2688 return $this->mHash;
2689 }
2690 wfDeprecated( __METHOD__ );
2691
2692 // stubthreshold is only included below for completeness,
2693 // since it disables the parser cache, its value will always
2694 // be 0 when this function is called by parsercache.
2695
2696 $confstr = $this->getOption( 'math' );
2697 $confstr .= '!' . $this->getStubThreshold();
2698 if ( $wgUseDynamicDates ) { # This is wrong (bug 24714)
2699 $confstr .= '!' . $this->getDatePreference();
2700 }
2701 $confstr .= '!' . ( $this->getOption( 'numberheadings' ) ? '1' : '' );
2702 $confstr .= '!' . $wgLang->getCode();
2703 $confstr .= '!' . $this->getOption( 'thumbsize' );
2704 // add in language specific options, if any
2705 $extra = $wgContLang->getExtraHashOptions();
2706 $confstr .= $extra;
2707
2708 // Since the skin could be overloading link(), it should be
2709 // included here but in practice, none of our skins do that.
2710
2711 $confstr .= $wgRenderHashAppend;
2712
2713 // Give a chance for extensions to modify the hash, if they have
2714 // extra options or other effects on the parser cache.
2715 wfRunHooks( 'PageRenderingHash', array( &$confstr ) );
2716
2717 // Make it a valid memcached key fragment
2718 $confstr = str_replace( ' ', '_', $confstr );
2719 $this->mHash = $confstr;
2720 return $confstr;
2721 }
2722
2723 /**
2724 * Get whether the user is explicitly blocked from account creation.
2725 * @return Bool
2726 */
2727 function isBlockedFromCreateAccount() {
2728 $this->getBlockedStatus();
2729 return $this->mBlock && $this->mBlock->mCreateAccount;
2730 }
2731
2732 /**
2733 * Get whether the user is blocked from using Special:Emailuser.
2734 * @return Bool
2735 */
2736 function isBlockedFromEmailuser() {
2737 $this->getBlockedStatus();
2738 return $this->mBlock && $this->mBlock->mBlockEmail;
2739 }
2740
2741 /**
2742 * Get whether the user is allowed to create an account.
2743 * @return Bool
2744 */
2745 function isAllowedToCreateAccount() {
2746 return $this->isAllowed( 'createaccount' ) && !$this->isBlockedFromCreateAccount();
2747 }
2748
2749 /**
2750 * Get this user's personal page title.
2751 *
2752 * @return Title: User's personal page title
2753 */
2754 function getUserPage() {
2755 return Title::makeTitle( NS_USER, $this->getName() );
2756 }
2757
2758 /**
2759 * Get this user's talk page title.
2760 *
2761 * @return Title: User's talk page title
2762 */
2763 function getTalkPage() {
2764 $title = $this->getUserPage();
2765 return $title->getTalkPage();
2766 }
2767
2768 /**
2769 * Get the maximum valid user ID.
2770 * @return Integer: User ID
2771 * @static
2772 */
2773 function getMaxID() {
2774 static $res; // cache
2775
2776 if ( isset( $res ) ) {
2777 return $res;
2778 } else {
2779 $dbr = wfGetDB( DB_SLAVE );
2780 return $res = $dbr->selectField( 'user', 'max(user_id)', false, __METHOD__ );
2781 }
2782 }
2783
2784 /**
2785 * Determine whether the user is a newbie. Newbies are either
2786 * anonymous IPs, or the most recently created accounts.
2787 * @return Bool
2788 */
2789 function isNewbie() {
2790 return !$this->isAllowed( 'autoconfirmed' );
2791 }
2792
2793 /**
2794 * Check to see if the given clear-text password is one of the accepted passwords
2795 * @param $password String: user password.
2796 * @return Boolean: True if the given password is correct, otherwise False.
2797 */
2798 function checkPassword( $password ) {
2799 global $wgAuth;
2800 $this->load();
2801
2802 // Even though we stop people from creating passwords that
2803 // are shorter than this, doesn't mean people wont be able
2804 // to. Certain authentication plugins do NOT want to save
2805 // domain passwords in a mysql database, so we should
2806 // check this (in case $wgAuth->strict() is false).
2807 if( !$this->isValidPassword( $password ) ) {
2808 return false;
2809 }
2810
2811 if( $wgAuth->authenticate( $this->getName(), $password ) ) {
2812 return true;
2813 } elseif( $wgAuth->strict() ) {
2814 /* Auth plugin doesn't allow local authentication */
2815 return false;
2816 } elseif( $wgAuth->strictUserAuth( $this->getName() ) ) {
2817 /* Auth plugin doesn't allow local authentication for this user name */
2818 return false;
2819 }
2820 if ( self::comparePasswords( $this->mPassword, $password, $this->mId ) ) {
2821 return true;
2822 } elseif ( function_exists( 'iconv' ) ) {
2823 # Some wikis were converted from ISO 8859-1 to UTF-8, the passwords can't be converted
2824 # Check for this with iconv
2825 $cp1252Password = iconv( 'UTF-8', 'WINDOWS-1252//TRANSLIT', $password );
2826 if ( self::comparePasswords( $this->mPassword, $cp1252Password, $this->mId ) ) {
2827 return true;
2828 }
2829 }
2830 return false;
2831 }
2832
2833 /**
2834 * Check if the given clear-text password matches the temporary password
2835 * sent by e-mail for password reset operations.
2836 * @return Boolean: True if matches, false otherwise
2837 */
2838 function checkTemporaryPassword( $plaintext ) {
2839 global $wgNewPasswordExpiry;
2840 if( self::comparePasswords( $this->mNewpassword, $plaintext, $this->getId() ) ) {
2841 if ( is_null( $this->mNewpassTime ) ) {
2842 return true;
2843 }
2844 $expiry = wfTimestamp( TS_UNIX, $this->mNewpassTime ) + $wgNewPasswordExpiry;
2845 return ( time() < $expiry );
2846 } else {
2847 return false;
2848 }
2849 }
2850
2851 /**
2852 * Initialize (if necessary) and return a session token value
2853 * which can be used in edit forms to show that the user's
2854 * login credentials aren't being hijacked with a foreign form
2855 * submission.
2856 *
2857 * @param $salt String|Array of Strings Optional function-specific data for hashing
2858 * @return String The new edit token
2859 */
2860 function editToken( $salt = '' ) {
2861 if ( $this->isAnon() ) {
2862 return EDIT_TOKEN_SUFFIX;
2863 } else {
2864 if( !isset( $_SESSION['wsEditToken'] ) ) {
2865 $token = self::generateToken();
2866 $_SESSION['wsEditToken'] = $token;
2867 } else {
2868 $token = $_SESSION['wsEditToken'];
2869 }
2870 if( is_array( $salt ) ) {
2871 $salt = implode( '|', $salt );
2872 }
2873 return md5( $token . $salt ) . EDIT_TOKEN_SUFFIX;
2874 }
2875 }
2876
2877 /**
2878 * Generate a looking random token for various uses.
2879 *
2880 * @param $salt String Optional salt value
2881 * @return String The new random token
2882 */
2883 public static function generateToken( $salt = '' ) {
2884 $token = dechex( mt_rand() ) . dechex( mt_rand() );
2885 return md5( $token . $salt );
2886 }
2887
2888 /**
2889 * Check given value against the token value stored in the session.
2890 * A match should confirm that the form was submitted from the
2891 * user's own login session, not a form submission from a third-party
2892 * site.
2893 *
2894 * @param $val String Input value to compare
2895 * @param $salt String Optional function-specific data for hashing
2896 * @return Boolean: Whether the token matches
2897 */
2898 function matchEditToken( $val, $salt = '' ) {
2899 $sessionToken = $this->editToken( $salt );
2900 if ( $val != $sessionToken ) {
2901 wfDebug( "User::matchEditToken: broken session data\n" );
2902 }
2903 return $val == $sessionToken;
2904 }
2905
2906 /**
2907 * Check given value against the token value stored in the session,
2908 * ignoring the suffix.
2909 *
2910 * @param $val String Input value to compare
2911 * @param $salt String Optional function-specific data for hashing
2912 * @return Boolean: Whether the token matches
2913 */
2914 function matchEditTokenNoSuffix( $val, $salt = '' ) {
2915 $sessionToken = $this->editToken( $salt );
2916 return substr( $sessionToken, 0, 32 ) == substr( $val, 0, 32 );
2917 }
2918
2919 /**
2920 * Generate a new e-mail confirmation token and send a confirmation/invalidation
2921 * mail to the user's given address.
2922 *
2923 * @param $type String: message to send, either "created", "changed" or "set"
2924 * @return Status object
2925 */
2926 function sendConfirmationMail( $type = 'created' ) {
2927 global $wgLang;
2928 $expiration = null; // gets passed-by-ref and defined in next line.
2929 $token = $this->confirmationToken( $expiration );
2930 $url = $this->confirmationTokenUrl( $token );
2931 $invalidateURL = $this->invalidationTokenUrl( $token );
2932 $this->saveSettings();
2933
2934 if ( $type == 'created' || $type === false ) {
2935 $message = 'confirmemail_body';
2936 } elseif ( $type === true ) {
2937 $message = 'confirmemail_body_changed';
2938 } else {
2939 $message = 'confirmemail_body_' . $type;
2940 }
2941
2942 return $this->sendMail( wfMsg( 'confirmemail_subject' ),
2943 wfMsg( $message,
2944 wfGetIP(),
2945 $this->getName(),
2946 $url,
2947 $wgLang->timeanddate( $expiration, false ),
2948 $invalidateURL,
2949 $wgLang->date( $expiration, false ),
2950 $wgLang->time( $expiration, false ) ) );
2951 }
2952
2953 /**
2954 * Send an e-mail to this user's account. Does not check for
2955 * confirmed status or validity.
2956 *
2957 * @param $subject String Message subject
2958 * @param $body String Message body
2959 * @param $from String Optional From address; if unspecified, default $wgPasswordSender will be used
2960 * @param $replyto String Reply-To address
2961 * @return Status
2962 */
2963 function sendMail( $subject, $body, $from = null, $replyto = null ) {
2964 if( is_null( $from ) ) {
2965 global $wgPasswordSender, $wgPasswordSenderName;
2966 $sender = new MailAddress( $wgPasswordSender, $wgPasswordSenderName );
2967 } else {
2968 $sender = new MailAddress( $from );
2969 }
2970
2971 $to = new MailAddress( $this );
2972 return UserMailer::send( $to, $sender, $subject, $body, $replyto );
2973 }
2974
2975 /**
2976 * Generate, store, and return a new e-mail confirmation code.
2977 * A hash (unsalted, since it's used as a key) is stored.
2978 *
2979 * @note Call saveSettings() after calling this function to commit
2980 * this change to the database.
2981 *
2982 * @param[out] &$expiration \mixed Accepts the expiration time
2983 * @return String New token
2984 * @private
2985 */
2986 function confirmationToken( &$expiration ) {
2987 $now = time();
2988 $expires = $now + 7 * 24 * 60 * 60;
2989 $expiration = wfTimestamp( TS_MW, $expires );
2990 $token = self::generateToken( $this->mId . $this->mEmail . $expires );
2991 $hash = md5( $token );
2992 $this->load();
2993 $this->mEmailToken = $hash;
2994 $this->mEmailTokenExpires = $expiration;
2995 return $token;
2996 }
2997
2998 /**
2999 * Return a URL the user can use to confirm their email address.
3000 * @param $token String Accepts the email confirmation token
3001 * @return String New token URL
3002 * @private
3003 */
3004 function confirmationTokenUrl( $token ) {
3005 return $this->getTokenUrl( 'ConfirmEmail', $token );
3006 }
3007
3008 /**
3009 * Return a URL the user can use to invalidate their email address.
3010 * @param $token String Accepts the email confirmation token
3011 * @return String New token URL
3012 * @private
3013 */
3014 function invalidationTokenUrl( $token ) {
3015 return $this->getTokenUrl( 'Invalidateemail', $token );
3016 }
3017
3018 /**
3019 * Internal function to format the e-mail validation/invalidation URLs.
3020 * This uses $wgArticlePath directly as a quickie hack to use the
3021 * hardcoded English names of the Special: pages, for ASCII safety.
3022 *
3023 * @note Since these URLs get dropped directly into emails, using the
3024 * short English names avoids insanely long URL-encoded links, which
3025 * also sometimes can get corrupted in some browsers/mailers
3026 * (bug 6957 with Gmail and Internet Explorer).
3027 *
3028 * @param $page String Special page
3029 * @param $token String Token
3030 * @return String Formatted URL
3031 */
3032 protected function getTokenUrl( $page, $token ) {
3033 global $wgArticlePath;
3034 return wfExpandUrl(
3035 str_replace(
3036 '$1',
3037 "Special:$page/$token",
3038 $wgArticlePath ) );
3039 }
3040
3041 /**
3042 * Mark the e-mail address confirmed.
3043 *
3044 * @note Call saveSettings() after calling this function to commit the change.
3045 */
3046 function confirmEmail() {
3047 $this->setEmailAuthenticationTimestamp( wfTimestampNow() );
3048 wfRunHooks( 'ConfirmEmailComplete', array( $this ) );
3049 return true;
3050 }
3051
3052 /**
3053 * Invalidate the user's e-mail confirmation, and unauthenticate the e-mail
3054 * address if it was already confirmed.
3055 *
3056 * @note Call saveSettings() after calling this function to commit the change.
3057 */
3058 function invalidateEmail() {
3059 $this->load();
3060 $this->mEmailToken = null;
3061 $this->mEmailTokenExpires = null;
3062 $this->setEmailAuthenticationTimestamp( null );
3063 wfRunHooks( 'InvalidateEmailComplete', array( $this ) );
3064 return true;
3065 }
3066
3067 /**
3068 * Set the e-mail authentication timestamp.
3069 * @param $timestamp String TS_MW timestamp
3070 */
3071 function setEmailAuthenticationTimestamp( $timestamp ) {
3072 $this->load();
3073 $this->mEmailAuthenticated = $timestamp;
3074 wfRunHooks( 'UserSetEmailAuthenticationTimestamp', array( $this, &$this->mEmailAuthenticated ) );
3075 }
3076
3077 /**
3078 * Is this user allowed to send e-mails within limits of current
3079 * site configuration?
3080 * @return Bool
3081 */
3082 function canSendEmail() {
3083 global $wgEnableEmail, $wgEnableUserEmail;
3084 if( !$wgEnableEmail || !$wgEnableUserEmail || !$this->isAllowed( 'sendemail' ) ) {
3085 return false;
3086 }
3087 $canSend = $this->isEmailConfirmed();
3088 wfRunHooks( 'UserCanSendEmail', array( &$this, &$canSend ) );
3089 return $canSend;
3090 }
3091
3092 /**
3093 * Is this user allowed to receive e-mails within limits of current
3094 * site configuration?
3095 * @return Bool
3096 */
3097 function canReceiveEmail() {
3098 return $this->isEmailConfirmed() && !$this->getOption( 'disablemail' );
3099 }
3100
3101 /**
3102 * Is this user's e-mail address valid-looking and confirmed within
3103 * limits of the current site configuration?
3104 *
3105 * @note If $wgEmailAuthentication is on, this may require the user to have
3106 * confirmed their address by returning a code or using a password
3107 * sent to the address from the wiki.
3108 *
3109 * @return Bool
3110 */
3111 function isEmailConfirmed() {
3112 global $wgEmailAuthentication;
3113 $this->load();
3114 $confirmed = true;
3115 if( wfRunHooks( 'EmailConfirmed', array( &$this, &$confirmed ) ) ) {
3116 if( $this->isAnon() )
3117 return false;
3118 if( !self::isValidEmailAddr( $this->mEmail ) )
3119 return false;
3120 if( $wgEmailAuthentication && !$this->getEmailAuthenticationTimestamp() )
3121 return false;
3122 return true;
3123 } else {
3124 return $confirmed;
3125 }
3126 }
3127
3128 /**
3129 * Check whether there is an outstanding request for e-mail confirmation.
3130 * @return Bool
3131 */
3132 function isEmailConfirmationPending() {
3133 global $wgEmailAuthentication;
3134 return $wgEmailAuthentication &&
3135 !$this->isEmailConfirmed() &&
3136 $this->mEmailToken &&
3137 $this->mEmailTokenExpires > wfTimestamp();
3138 }
3139
3140 /**
3141 * Get the timestamp of account creation.
3142 *
3143 * @return String|Bool Timestamp of account creation, or false for
3144 * non-existent/anonymous user accounts.
3145 */
3146 public function getRegistration() {
3147 return $this->getId() > 0
3148 ? $this->mRegistration
3149 : false;
3150 }
3151
3152 /**
3153 * Get the timestamp of the first edit
3154 *
3155 * @return String|Bool Timestamp of first edit, or false for
3156 * non-existent/anonymous user accounts.
3157 */
3158 public function getFirstEditTimestamp() {
3159 if( $this->getId() == 0 ) {
3160 return false; // anons
3161 }
3162 $dbr = wfGetDB( DB_SLAVE );
3163 $time = $dbr->selectField( 'revision', 'rev_timestamp',
3164 array( 'rev_user' => $this->getId() ),
3165 __METHOD__,
3166 array( 'ORDER BY' => 'rev_timestamp ASC' )
3167 );
3168 if( !$time ) {
3169 return false; // no edits
3170 }
3171 return wfTimestamp( TS_MW, $time );
3172 }
3173
3174 /**
3175 * Get the permissions associated with a given list of groups
3176 *
3177 * @param $groups Array of Strings List of internal group names
3178 * @return Array of Strings List of permission key names for given groups combined
3179 */
3180 static function getGroupPermissions( $groups ) {
3181 global $wgGroupPermissions, $wgRevokePermissions;
3182 $rights = array();
3183 // grant every granted permission first
3184 foreach( $groups as $group ) {
3185 if( isset( $wgGroupPermissions[$group] ) ) {
3186 $rights = array_merge( $rights,
3187 // array_filter removes empty items
3188 array_keys( array_filter( $wgGroupPermissions[$group] ) ) );
3189 }
3190 }
3191 // now revoke the revoked permissions
3192 foreach( $groups as $group ) {
3193 if( isset( $wgRevokePermissions[$group] ) ) {
3194 $rights = array_diff( $rights,
3195 array_keys( array_filter( $wgRevokePermissions[$group] ) ) );
3196 }
3197 }
3198 return array_unique( $rights );
3199 }
3200
3201 /**
3202 * Get all the groups who have a given permission
3203 *
3204 * @param $role String Role to check
3205 * @return Array of Strings List of internal group names with the given permission
3206 */
3207 static function getGroupsWithPermission( $role ) {
3208 global $wgGroupPermissions;
3209 $allowedGroups = array();
3210 foreach ( $wgGroupPermissions as $group => $rights ) {
3211 if ( isset( $rights[$role] ) && $rights[$role] ) {
3212 $allowedGroups[] = $group;
3213 }
3214 }
3215 return $allowedGroups;
3216 }
3217
3218 /**
3219 * Get the localized descriptive name for a group, if it exists
3220 *
3221 * @param $group String Internal group name
3222 * @return String Localized descriptive group name
3223 */
3224 static function getGroupName( $group ) {
3225 $msg = wfMessage( "group-$group" );
3226 return $msg->isBlank() ? $group : $msg->text();
3227 }
3228
3229 /**
3230 * Get the localized descriptive name for a member of a group, if it exists
3231 *
3232 * @param $group String Internal group name
3233 * @return String Localized name for group member
3234 */
3235 static function getGroupMember( $group ) {
3236 $msg = wfMessage( "group-$group-member" );
3237 return $msg->isBlank() ? $group : $msg->text();
3238 }
3239
3240 /**
3241 * Return the set of defined explicit groups.
3242 * The implicit groups (by default *, 'user' and 'autoconfirmed')
3243 * are not included, as they are defined automatically, not in the database.
3244 * @return Array of internal group names
3245 */
3246 static function getAllGroups() {
3247 global $wgGroupPermissions, $wgRevokePermissions;
3248 return array_diff(
3249 array_merge( array_keys( $wgGroupPermissions ), array_keys( $wgRevokePermissions ) ),
3250 self::getImplicitGroups()
3251 );
3252 }
3253
3254 /**
3255 * Get a list of all available permissions.
3256 * @return Array of permission names
3257 */
3258 static function getAllRights() {
3259 if ( self::$mAllRights === false ) {
3260 global $wgAvailableRights;
3261 if ( count( $wgAvailableRights ) ) {
3262 self::$mAllRights = array_unique( array_merge( self::$mCoreRights, $wgAvailableRights ) );
3263 } else {
3264 self::$mAllRights = self::$mCoreRights;
3265 }
3266 wfRunHooks( 'UserGetAllRights', array( &self::$mAllRights ) );
3267 }
3268 return self::$mAllRights;
3269 }
3270
3271 /**
3272 * Get a list of implicit groups
3273 * @return Array of Strings Array of internal group names
3274 */
3275 public static function getImplicitGroups() {
3276 global $wgImplicitGroups;
3277 $groups = $wgImplicitGroups;
3278 wfRunHooks( 'UserGetImplicitGroups', array( &$groups ) ); #deprecated, use $wgImplictGroups instead
3279 return $groups;
3280 }
3281
3282 /**
3283 * Get the title of a page describing a particular group
3284 *
3285 * @param $group String Internal group name
3286 * @return Title|Bool Title of the page if it exists, false otherwise
3287 */
3288 static function getGroupPage( $group ) {
3289 $msg = wfMessage( 'grouppage-' . $group )->inContentLanguage();
3290 if( $msg->exists() ) {
3291 $title = Title::newFromText( $msg->text() );
3292 if( is_object( $title ) )
3293 return $title;
3294 }
3295 return false;
3296 }
3297
3298 /**
3299 * Create a link to the group in HTML, if available;
3300 * else return the group name.
3301 *
3302 * @param $group String Internal name of the group
3303 * @param $text String The text of the link
3304 * @return String HTML link to the group
3305 */
3306 static function makeGroupLinkHTML( $group, $text = '' ) {
3307 if( $text == '' ) {
3308 $text = self::getGroupName( $group );
3309 }
3310 $title = self::getGroupPage( $group );
3311 if( $title ) {
3312 global $wgUser;
3313 $sk = $wgUser->getSkin();
3314 return $sk->link( $title, htmlspecialchars( $text ) );
3315 } else {
3316 return $text;
3317 }
3318 }
3319
3320 /**
3321 * Create a link to the group in Wikitext, if available;
3322 * else return the group name.
3323 *
3324 * @param $group String Internal name of the group
3325 * @param $text String The text of the link
3326 * @return String Wikilink to the group
3327 */
3328 static function makeGroupLinkWiki( $group, $text = '' ) {
3329 if( $text == '' ) {
3330 $text = self::getGroupName( $group );
3331 }
3332 $title = self::getGroupPage( $group );
3333 if( $title ) {
3334 $page = $title->getPrefixedText();
3335 return "[[$page|$text]]";
3336 } else {
3337 return $text;
3338 }
3339 }
3340
3341 /**
3342 * Returns an array of the groups that a particular group can add/remove.
3343 *
3344 * @param $group String: the group to check for whether it can add/remove
3345 * @return Array array( 'add' => array( addablegroups ),
3346 * 'remove' => array( removablegroups ),
3347 * 'add-self' => array( addablegroups to self),
3348 * 'remove-self' => array( removable groups from self) )
3349 */
3350 static function changeableByGroup( $group ) {
3351 global $wgAddGroups, $wgRemoveGroups, $wgGroupsAddToSelf, $wgGroupsRemoveFromSelf;
3352
3353 $groups = array( 'add' => array(), 'remove' => array(), 'add-self' => array(), 'remove-self' => array() );
3354 if( empty( $wgAddGroups[$group] ) ) {
3355 // Don't add anything to $groups
3356 } elseif( $wgAddGroups[$group] === true ) {
3357 // You get everything
3358 $groups['add'] = self::getAllGroups();
3359 } elseif( is_array( $wgAddGroups[$group] ) ) {
3360 $groups['add'] = $wgAddGroups[$group];
3361 }
3362
3363 // Same thing for remove
3364 if( empty( $wgRemoveGroups[$group] ) ) {
3365 } elseif( $wgRemoveGroups[$group] === true ) {
3366 $groups['remove'] = self::getAllGroups();
3367 } elseif( is_array( $wgRemoveGroups[$group] ) ) {
3368 $groups['remove'] = $wgRemoveGroups[$group];
3369 }
3370
3371 // Re-map numeric keys of AddToSelf/RemoveFromSelf to the 'user' key for backwards compatibility
3372 if( empty( $wgGroupsAddToSelf['user']) || $wgGroupsAddToSelf['user'] !== true ) {
3373 foreach( $wgGroupsAddToSelf as $key => $value ) {
3374 if( is_int( $key ) ) {
3375 $wgGroupsAddToSelf['user'][] = $value;
3376 }
3377 }
3378 }
3379
3380 if( empty( $wgGroupsRemoveFromSelf['user']) || $wgGroupsRemoveFromSelf['user'] !== true ) {
3381 foreach( $wgGroupsRemoveFromSelf as $key => $value ) {
3382 if( is_int( $key ) ) {
3383 $wgGroupsRemoveFromSelf['user'][] = $value;
3384 }
3385 }
3386 }
3387
3388 // Now figure out what groups the user can add to him/herself
3389 if( empty( $wgGroupsAddToSelf[$group] ) ) {
3390 } elseif( $wgGroupsAddToSelf[$group] === true ) {
3391 // No idea WHY this would be used, but it's there
3392 $groups['add-self'] = User::getAllGroups();
3393 } elseif( is_array( $wgGroupsAddToSelf[$group] ) ) {
3394 $groups['add-self'] = $wgGroupsAddToSelf[$group];
3395 }
3396
3397 if( empty( $wgGroupsRemoveFromSelf[$group] ) ) {
3398 } elseif( $wgGroupsRemoveFromSelf[$group] === true ) {
3399 $groups['remove-self'] = User::getAllGroups();
3400 } elseif( is_array( $wgGroupsRemoveFromSelf[$group] ) ) {
3401 $groups['remove-self'] = $wgGroupsRemoveFromSelf[$group];
3402 }
3403
3404 return $groups;
3405 }
3406
3407 /**
3408 * Returns an array of groups that this user can add and remove
3409 * @return Array array( 'add' => array( addablegroups ),
3410 * 'remove' => array( removablegroups ),
3411 * 'add-self' => array( addablegroups to self),
3412 * 'remove-self' => array( removable groups from self) )
3413 */
3414 function changeableGroups() {
3415 if( $this->isAllowed( 'userrights' ) ) {
3416 // This group gives the right to modify everything (reverse-
3417 // compatibility with old "userrights lets you change
3418 // everything")
3419 // Using array_merge to make the groups reindexed
3420 $all = array_merge( User::getAllGroups() );
3421 return array(
3422 'add' => $all,
3423 'remove' => $all,
3424 'add-self' => array(),
3425 'remove-self' => array()
3426 );
3427 }
3428
3429 // Okay, it's not so simple, we will have to go through the arrays
3430 $groups = array(
3431 'add' => array(),
3432 'remove' => array(),
3433 'add-self' => array(),
3434 'remove-self' => array()
3435 );
3436 $addergroups = $this->getEffectiveGroups();
3437
3438 foreach( $addergroups as $addergroup ) {
3439 $groups = array_merge_recursive(
3440 $groups, $this->changeableByGroup( $addergroup )
3441 );
3442 $groups['add'] = array_unique( $groups['add'] );
3443 $groups['remove'] = array_unique( $groups['remove'] );
3444 $groups['add-self'] = array_unique( $groups['add-self'] );
3445 $groups['remove-self'] = array_unique( $groups['remove-self'] );
3446 }
3447 return $groups;
3448 }
3449
3450 /**
3451 * Increment the user's edit-count field.
3452 * Will have no effect for anonymous users.
3453 */
3454 function incEditCount() {
3455 if( !$this->isAnon() ) {
3456 $dbw = wfGetDB( DB_MASTER );
3457 $dbw->update( 'user',
3458 array( 'user_editcount=user_editcount+1' ),
3459 array( 'user_id' => $this->getId() ),
3460 __METHOD__ );
3461
3462 // Lazy initialization check...
3463 if( $dbw->affectedRows() == 0 ) {
3464 // Pull from a slave to be less cruel to servers
3465 // Accuracy isn't the point anyway here
3466 $dbr = wfGetDB( DB_SLAVE );
3467 $count = $dbr->selectField( 'revision',
3468 'COUNT(rev_user)',
3469 array( 'rev_user' => $this->getId() ),
3470 __METHOD__ );
3471
3472 // Now here's a goddamn hack...
3473 if( $dbr !== $dbw ) {
3474 // If we actually have a slave server, the count is
3475 // at least one behind because the current transaction
3476 // has not been committed and replicated.
3477 $count++;
3478 } else {
3479 // But if DB_SLAVE is selecting the master, then the
3480 // count we just read includes the revision that was
3481 // just added in the working transaction.
3482 }
3483
3484 $dbw->update( 'user',
3485 array( 'user_editcount' => $count ),
3486 array( 'user_id' => $this->getId() ),
3487 __METHOD__ );
3488 }
3489 }
3490 // edit count in user cache too
3491 $this->invalidateCache();
3492 }
3493
3494 /**
3495 * Get the description of a given right
3496 *
3497 * @param $right String Right to query
3498 * @return String Localized description of the right
3499 */
3500 static function getRightDescription( $right ) {
3501 $key = "right-$right";
3502 $name = wfMsg( $key );
3503 return $name == '' || wfEmptyMsg( $key, $name )
3504 ? $right
3505 : $name;
3506 }
3507
3508 /**
3509 * Make an old-style password hash
3510 *
3511 * @param $password String Plain-text password
3512 * @param $userId String User ID
3513 * @return String Password hash
3514 */
3515 static function oldCrypt( $password, $userId ) {
3516 global $wgPasswordSalt;
3517 if ( $wgPasswordSalt ) {
3518 return md5( $userId . '-' . md5( $password ) );
3519 } else {
3520 return md5( $password );
3521 }
3522 }
3523
3524 /**
3525 * Make a new-style password hash
3526 *
3527 * @param $password String Plain-text password
3528 * @param $salt String Optional salt, may be random or the user ID.
3529 * If unspecified or false, will generate one automatically
3530 * @return String Password hash
3531 */
3532 static function crypt( $password, $salt = false ) {
3533 global $wgPasswordSalt;
3534
3535 $hash = '';
3536 if( !wfRunHooks( 'UserCryptPassword', array( &$password, &$salt, &$wgPasswordSalt, &$hash ) ) ) {
3537 return $hash;
3538 }
3539
3540 if( $wgPasswordSalt ) {
3541 if ( $salt === false ) {
3542 $salt = substr( wfGenerateToken(), 0, 8 );
3543 }
3544 return ':B:' . $salt . ':' . md5( $salt . '-' . md5( $password ) );
3545 } else {
3546 return ':A:' . md5( $password );
3547 }
3548 }
3549
3550 /**
3551 * Compare a password hash with a plain-text password. Requires the user
3552 * ID if there's a chance that the hash is an old-style hash.
3553 *
3554 * @param $hash String Password hash
3555 * @param $password String Plain-text password to compare
3556 * @param $userId String User ID for old-style password salt
3557 * @return Boolean:
3558 */
3559 static function comparePasswords( $hash, $password, $userId = false ) {
3560 $type = substr( $hash, 0, 3 );
3561
3562 $result = false;
3563 if( !wfRunHooks( 'UserComparePasswords', array( &$hash, &$password, &$userId, &$result ) ) ) {
3564 return $result;
3565 }
3566
3567 if ( $type == ':A:' ) {
3568 # Unsalted
3569 return md5( $password ) === substr( $hash, 3 );
3570 } elseif ( $type == ':B:' ) {
3571 # Salted
3572 list( $salt, $realHash ) = explode( ':', substr( $hash, 3 ), 2 );
3573 return md5( $salt.'-'.md5( $password ) ) == $realHash;
3574 } else {
3575 # Old-style
3576 return self::oldCrypt( $password, $userId ) === $hash;
3577 }
3578 }
3579
3580 /**
3581 * Add a newuser log entry for this user
3582 *
3583 * @param $byEmail Boolean: account made by email?
3584 * @param $reason String: user supplied reason
3585 */
3586 public function addNewUserLogEntry( $byEmail = false, $reason = '' ) {
3587 global $wgUser, $wgContLang, $wgNewUserLog;
3588 if( empty( $wgNewUserLog ) ) {
3589 return true; // disabled
3590 }
3591
3592 if( $this->getName() == $wgUser->getName() ) {
3593 $action = 'create';
3594 } else {
3595 $action = 'create2';
3596 if ( $byEmail ) {
3597 if ( $reason === '' ) {
3598 $reason = wfMsgForContent( 'newuserlog-byemail' );
3599 } else {
3600 $reason = $wgContLang->commaList( array(
3601 $reason, wfMsgForContent( 'newuserlog-byemail' ) ) );
3602 }
3603 }
3604 }
3605 $log = new LogPage( 'newusers' );
3606 $log->addEntry(
3607 $action,
3608 $this->getUserPage(),
3609 $reason,
3610 array( $this->getId() )
3611 );
3612 return true;
3613 }
3614
3615 /**
3616 * Add an autocreate newuser log entry for this user
3617 * Used by things like CentralAuth and perhaps other authplugins.
3618 */
3619 public function addNewUserLogEntryAutoCreate() {
3620 global $wgNewUserLog, $wgLogAutocreatedAccounts;
3621 if( !$wgNewUserLog || !$wgLogAutocreatedAccounts ) {
3622 return true; // disabled
3623 }
3624 $log = new LogPage( 'newusers', false );
3625 $log->addEntry( 'autocreate', $this->getUserPage(), '', array( $this->getId() ) );
3626 return true;
3627 }
3628
3629 protected function loadOptions() {
3630 $this->load();
3631 if ( $this->mOptionsLoaded || !$this->getId() )
3632 return;
3633
3634 $this->mOptions = self::getDefaultOptions();
3635
3636 // Maybe load from the object
3637 if ( !is_null( $this->mOptionOverrides ) ) {
3638 wfDebug( "User: loading options for user " . $this->getId() . " from override cache.\n" );
3639 foreach( $this->mOptionOverrides as $key => $value ) {
3640 $this->mOptions[$key] = $value;
3641 }
3642 } else {
3643 wfDebug( "User: loading options for user " . $this->getId() . " from database.\n" );
3644 // Load from database
3645 $dbr = wfGetDB( DB_SLAVE );
3646
3647 $res = $dbr->select(
3648 'user_properties',
3649 '*',
3650 array( 'up_user' => $this->getId() ),
3651 __METHOD__
3652 );
3653
3654 foreach ( $res as $row ) {
3655 $this->mOptionOverrides[$row->up_property] = $row->up_value;
3656 $this->mOptions[$row->up_property] = $row->up_value;
3657 }
3658 }
3659
3660 $this->mOptionsLoaded = true;
3661
3662 wfRunHooks( 'UserLoadOptions', array( $this, &$this->mOptions ) );
3663 }
3664
3665 protected function saveOptions() {
3666 global $wgAllowPrefChange;
3667
3668 $extuser = ExternalUser::newFromUser( $this );
3669
3670 $this->loadOptions();
3671 $dbw = wfGetDB( DB_MASTER );
3672
3673 $insert_rows = array();
3674
3675 $saveOptions = $this->mOptions;
3676
3677 // Allow hooks to abort, for instance to save to a global profile.
3678 // Reset options to default state before saving.
3679 if( !wfRunHooks( 'UserSaveOptions', array( $this, &$saveOptions ) ) )
3680 return;
3681
3682 foreach( $saveOptions as $key => $value ) {
3683 # Don't bother storing default values
3684 if ( ( is_null( self::getDefaultOption( $key ) ) &&
3685 !( $value === false || is_null($value) ) ) ||
3686 $value != self::getDefaultOption( $key ) ) {
3687 $insert_rows[] = array(
3688 'up_user' => $this->getId(),
3689 'up_property' => $key,
3690 'up_value' => $value,
3691 );
3692 }
3693 if ( $extuser && isset( $wgAllowPrefChange[$key] ) ) {
3694 switch ( $wgAllowPrefChange[$key] ) {
3695 case 'local':
3696 case 'message':
3697 break;
3698 case 'semiglobal':
3699 case 'global':
3700 $extuser->setPref( $key, $value );
3701 }
3702 }
3703 }
3704
3705 $dbw->begin();
3706 $dbw->delete( 'user_properties', array( 'up_user' => $this->getId() ), __METHOD__ );
3707 $dbw->insert( 'user_properties', $insert_rows, __METHOD__ );
3708 $dbw->commit();
3709 }
3710
3711 /**
3712 * Provide an array of HTML5 attributes to put on an input element
3713 * intended for the user to enter a new password. This may include
3714 * required, title, and/or pattern, depending on $wgMinimalPasswordLength.
3715 *
3716 * Do *not* use this when asking the user to enter his current password!
3717 * Regardless of configuration, users may have invalid passwords for whatever
3718 * reason (e.g., they were set before requirements were tightened up).
3719 * Only use it when asking for a new password, like on account creation or
3720 * ResetPass.
3721 *
3722 * Obviously, you still need to do server-side checking.
3723 *
3724 * NOTE: A combination of bugs in various browsers means that this function
3725 * actually just returns array() unconditionally at the moment. May as
3726 * well keep it around for when the browser bugs get fixed, though.
3727 *
3728 * FIXME : This does not belong here; put it in Html or Linker or somewhere
3729 *
3730 * @return array Array of HTML attributes suitable for feeding to
3731 * Html::element(), directly or indirectly. (Don't feed to Xml::*()!
3732 * That will potentially output invalid XHTML 1.0 Transitional, and will
3733 * get confused by the boolean attribute syntax used.)
3734 */
3735 public static function passwordChangeInputAttribs() {
3736 global $wgMinimalPasswordLength;
3737
3738 if ( $wgMinimalPasswordLength == 0 ) {
3739 return array();
3740 }
3741
3742 # Note that the pattern requirement will always be satisfied if the
3743 # input is empty, so we need required in all cases.
3744 #
3745 # FIXME (bug 23769): This needs to not claim the password is required
3746 # if e-mail confirmation is being used. Since HTML5 input validation
3747 # is b0rked anyway in some browsers, just return nothing. When it's
3748 # re-enabled, fix this code to not output required for e-mail
3749 # registration.
3750 #$ret = array( 'required' );
3751 $ret = array();
3752
3753 # We can't actually do this right now, because Opera 9.6 will print out
3754 # the entered password visibly in its error message! When other
3755 # browsers add support for this attribute, or Opera fixes its support,
3756 # we can add support with a version check to avoid doing this on Opera
3757 # versions where it will be a problem. Reported to Opera as
3758 # DSK-262266, but they don't have a public bug tracker for us to follow.
3759 /*
3760 if ( $wgMinimalPasswordLength > 1 ) {
3761 $ret['pattern'] = '.{' . intval( $wgMinimalPasswordLength ) . ',}';
3762 $ret['title'] = wfMsgExt( 'passwordtooshort', 'parsemag',
3763 $wgMinimalPasswordLength );
3764 }
3765 */
3766
3767 return $ret;
3768 }
3769
3770 /**
3771 * Format the user message using a hook, a template, or, failing these, a static format.
3772 * @param $subject String the subject of the message
3773 * @param $text String the content of the message
3774 * @param $signature String the signature, if provided.
3775 */
3776 static protected function formatUserMessage( $subject, $text, $signature ) {
3777 if ( wfRunHooks( 'FormatUserMessage',
3778 array( $subject, &$text, $signature ) ) ) {
3779
3780 $signature = empty($signature) ? "~~~~~" : "{$signature} ~~~~~";
3781
3782 $template = Title::newFromText( wfMsgForContent( 'usermessage-template' ) );
3783 if ( !$template
3784 || $template->getNamespace() !== NS_TEMPLATE
3785 || !$template->exists() ) {
3786 $text = "\n== $subject ==\n\n$text\n\n-- $signature";
3787 } else {
3788 $text = '{{'. $template->getText()
3789 . " | subject=$subject | body=$text | signature=$signature }}";
3790 }
3791 }
3792
3793 return $text;
3794 }
3795
3796 /**
3797 * Leave a user a message
3798 * @param $subject String the subject of the message
3799 * @param $text String the message to leave
3800 * @param $signature String Text to leave in the signature
3801 * @param $summary String the summary for this change, defaults to
3802 * "Leave system message."
3803 * @param $editor User The user leaving the message, defaults to
3804 * "{{MediaWiki:usermessage-editor}}"
3805 * @param $flags Int default edit flags
3806 *
3807 * @return boolean true if it was successful
3808 */
3809 public function leaveUserMessage( $subject, $text, $signature = "",
3810 $summary = null, $editor = null, $flags = 0 ) {
3811 if ( !isset( $summary ) ) {
3812 $summary = wfMsgForContent( 'usermessage-summary' );
3813 }
3814
3815 if ( !isset( $editor ) ) {
3816 $editor = User::newFromName( wfMsgForContent( 'usermessage-editor' ) );
3817 if ( !$editor->isLoggedIn() ) {
3818 $editor->addToDatabase();
3819 }
3820 }
3821
3822 $article = new Article( $this->getTalkPage() );
3823 wfRunHooks( 'SetupUserMessageArticle',
3824 array( $this, &$article, $subject, $text, $signature, $summary, $editor ) );
3825
3826
3827 $text = self::formatUserMessage( $subject, $text, $signature );
3828 $flags = $article->checkFlags( $flags );
3829
3830 if ( $flags & EDIT_UPDATE ) {
3831 $text = $article->getContent() . $text;
3832 }
3833
3834 $dbw = wfGetDB( DB_MASTER );
3835 $dbw->begin();
3836
3837 try {
3838 $status = $article->doEdit( $text, $summary, $flags, false, $editor );
3839 } catch ( DBQueryError $e ) {
3840 $status = Status::newFatal("DB Error");
3841 }
3842
3843 if ( $status->isGood() ) {
3844 // Set newtalk with the right user ID
3845 $this->setNewtalk( true );
3846 wfRunHooks( 'AfterUserMessage',
3847 array( $this, $article, $subject, $text, $signature, $summary, $editor ) );
3848 $dbw->commit();
3849 } else {
3850 // The article was concurrently created
3851 wfDebug( __METHOD__ . ": Error ".$status->getWikiText() );
3852 $dbw->rollback();
3853 }
3854
3855 return $status->isGood();
3856 }
3857 }