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