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