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