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