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