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