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