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