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