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