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