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