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