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